repo_name
stringlengths
6
112
path
stringlengths
4
204
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
714
810k
license
stringclasses
15 values
Akshay0724/scikit-learn
examples/preprocessing/plot_scaling_importance.py
45
5269
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Importance of Feature Scaling ========================================================= Feature scaling though standardization (or Z-score normalization) can be an important preprocessing step for many machine learning algorithms. Standardization involves rescaling the features such that they have the properties of a standard normal distribution with a mean of zero and a standard deviation of one. While many algorithms (such as SVM, K-nearest neighbors, and logistic regression) require features to be normalized, intuitively we can think of Principle Component Analysis (PCA) as being a prime example of when normalization is important. In PCA we are interested in the components that maximize the variance. If one component (e.g. human height) varies less than another (e.g. weight) because of their respective scales (meters vs. kilos), PCA might determine that the direction of maximal variance more closely corresponds with the 'weight' axis, if those features are not scaled. As a change in height of one meter can be considered much more important than the change in weight of one kilogram, this is clearly incorrect. To illustrate this, PCA is performed comparing the use of data with :class:`StandardScaler <sklearn.preprocessing.StandardScaler>` applied, to unscaled data. The results are visualized and a clear difference noted. The 1st principal component in the unscaled set can be seen. It can be seen that feature #13 dominates the direction, being a whole two orders of magnitude above the other features. This is contrasted when observing the principal component for the scaled version of the data. In the scaled version, the orders of magnitude are roughly the same across all the features. The dataset used is the Wine Dataset available at UCI. This dataset has continuous features that are heterogeneous in scale due to differing properties that they measure (i.e alcohol content, and malic acid). The transformed data is then used to train a naive Bayes classifier, and a clear difference in prediction accuracies is observed wherein the dataset which is scaled before PCA vastly outperforms the unscaled version. """ from __future__ import print_function from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.naive_bayes import GaussianNB from sklearn import metrics import matplotlib.pyplot as plt from sklearn.datasets import load_wine from sklearn.pipeline import make_pipeline print(__doc__) # Code source: Tyler Lanigan <[email protected]> # Sebastian Raschka <[email protected]> # License: BSD 3 clause RANDOM_STATE = 42 FIG_SIZE = (10, 7) features, target = load_wine(return_X_y=True) # Make a train/test split using 30% test size X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.30, random_state=RANDOM_STATE) # Fit to data and predict using pipelined GNB and PCA. unscaled_clf = make_pipeline(PCA(n_components=2), GaussianNB()) unscaled_clf.fit(X_train, y_train) pred_test = unscaled_clf.predict(X_test) # Fit to data and predict using pipelined scaling, GNB and PCA. std_clf = make_pipeline(StandardScaler(), PCA(n_components=2), GaussianNB()) std_clf.fit(X_train, y_train) pred_test_std = std_clf.predict(X_test) # Show prediction accuracies in scaled and unscaled data. print('\nPrediction accuracy for the normal test dataset with PCA') print('{:.2%}\n'.format(metrics.accuracy_score(y_test, pred_test))) print('\nPrediction accuracy for the standardized test dataset with PCA') print('{:.2%}\n'.format(metrics.accuracy_score(y_test, pred_test_std))) # Extract PCA from pipeline pca = unscaled_clf.named_steps['pca'] pca_std = std_clf.named_steps['pca'] # Show first principal componenets print('\nPC 1 without scaling:\n', pca.components_[0]) print('\nPC 1 with scaling:\n', pca_std.components_[0]) # Scale and use PCA on X_train data for visualization. scaler = std_clf.named_steps['standardscaler'] X_train_std = pca_std.transform(scaler.transform(X_train)) # visualize standardized vs. untouched dataset with PCA performed fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=FIG_SIZE) for l, c, m in zip(range(0, 3), ('blue', 'red', 'green'), ('^', 's', 'o')): ax1.scatter(X_train[y_train == l, 0], X_train[y_train == l, 1], color=c, label='class %s' % l, alpha=0.5, marker=m ) for l, c, m in zip(range(0, 3), ('blue', 'red', 'green'), ('^', 's', 'o')): ax2.scatter(X_train_std[y_train == l, 0], X_train_std[y_train == l, 1], color=c, label='class %s' % l, alpha=0.5, marker=m ) ax1.set_title('Training dataset after PCA') ax2.set_title('Standardized training dataset after PCA') for ax in (ax1, ax2): ax.set_xlabel('1st principal component') ax.set_ylabel('2nd principal component') ax.legend(loc='upper right') ax.grid() plt.tight_layout() plt.show()
bsd-3-clause
rs2/pandas
pandas/core/arrays/timedeltas.py
1
35326
from datetime import timedelta from typing import List, Union import numpy as np from pandas._libs import lib, tslibs from pandas._libs.tslibs import ( NaT, NaTType, Period, Tick, Timedelta, Timestamp, iNaT, to_offset, ) from pandas._libs.tslibs.conversion import precision_from_unit from pandas._libs.tslibs.fields import get_timedelta_field from pandas._libs.tslibs.timedeltas import array_to_timedelta64, parse_timedelta_unit from pandas.compat.numpy import function as nv from pandas.core.dtypes.common import ( DT64NS_DTYPE, TD64NS_DTYPE, is_dtype_equal, is_float_dtype, is_integer_dtype, is_object_dtype, is_scalar, is_string_dtype, is_timedelta64_dtype, is_timedelta64_ns_dtype, pandas_dtype, ) from pandas.core.dtypes.dtypes import DatetimeTZDtype from pandas.core.dtypes.generic import ABCSeries, ABCTimedeltaIndex from pandas.core.dtypes.missing import isna from pandas.core import nanops from pandas.core.algorithms import checked_add_with_arr from pandas.core.arrays import IntegerArray, datetimelike as dtl from pandas.core.arrays._ranges import generate_regular_range import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.ops.common import unpack_zerodim_and_defer def _field_accessor(name, alias, docstring=None): def f(self): values = self.asi8 result = get_timedelta_field(values, alias) if self._hasnans: result = self._maybe_mask_results( result, fill_value=None, convert="float64" ) return result f.__name__ = name f.__doc__ = f"\n{docstring}\n" return property(f) class TimedeltaArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps): """ Pandas ExtensionArray for timedelta data. .. versionadded:: 0.24.0 .. warning:: TimedeltaArray is currently experimental, and its API may change without warning. In particular, :attr:`TimedeltaArray.dtype` is expected to change to be an instance of an ``ExtensionDtype`` subclass. Parameters ---------- values : array-like The timedelta data. dtype : numpy.dtype Currently, only ``numpy.dtype("timedelta64[ns]")`` is accepted. freq : Offset, optional copy : bool, default False Whether to copy the underlying array of data. Attributes ---------- None Methods ------- None """ _typ = "timedeltaarray" _scalar_type = Timedelta _recognized_scalars = (timedelta, np.timedelta64, Tick) _is_recognized_dtype = is_timedelta64_dtype __array_priority__ = 1000 # define my properties & methods for delegation _other_ops: List[str] = [] _bool_ops: List[str] = [] _object_ops = ["freq"] _field_ops = ["days", "seconds", "microseconds", "nanoseconds"] _datetimelike_ops = _field_ops + _object_ops + _bool_ops _datetimelike_methods = [ "to_pytimedelta", "total_seconds", "round", "floor", "ceil", ] # Note: ndim must be defined to ensure NaT.__richcmp(TimedeltaArray) # operates pointwise. def _box_func(self, x) -> Union[Timedelta, NaTType]: return Timedelta(x, unit="ns") @property def dtype(self): """ The dtype for the TimedeltaArray. .. warning:: A future version of pandas will change dtype to be an instance of a :class:`pandas.api.extensions.ExtensionDtype` subclass, not a ``numpy.dtype``. Returns ------- numpy.dtype """ return TD64NS_DTYPE # ---------------------------------------------------------------- # Constructors def __init__(self, values, dtype=TD64NS_DTYPE, freq=lib.no_default, copy=False): values = extract_array(values) inferred_freq = getattr(values, "_freq", None) explicit_none = freq is None freq = freq if freq is not lib.no_default else None if isinstance(values, type(self)): if explicit_none: # dont inherit from values pass elif freq is None: freq = values.freq elif freq and values.freq: freq = to_offset(freq) freq, _ = dtl.validate_inferred_freq(freq, values.freq, False) values = values._data if not isinstance(values, np.ndarray): msg = ( f"Unexpected type '{type(values).__name__}'. 'values' must be a " "TimedeltaArray ndarray, or Series or Index containing one of those." ) raise ValueError(msg) if values.ndim not in [1, 2]: raise ValueError("Only 1-dimensional input arrays are supported.") if values.dtype == "i8": # for compat with datetime/timedelta/period shared methods, # we can sometimes get here with int64 values. These represent # nanosecond UTC (or tz-naive) unix timestamps values = values.view(TD64NS_DTYPE) _validate_td64_dtype(values.dtype) dtype = _validate_td64_dtype(dtype) if freq == "infer": msg = ( "Frequency inference not allowed in TimedeltaArray.__init__. " "Use 'pd.array()' instead." ) raise ValueError(msg) if copy: values = values.copy() if freq: freq = to_offset(freq) self._data = values self._dtype = dtype self._freq = freq if inferred_freq is None and freq is not None: type(self)._validate_frequency(self, freq) @classmethod def _simple_new(cls, values, freq=None, dtype=TD64NS_DTYPE): assert dtype == TD64NS_DTYPE, dtype assert isinstance(values, np.ndarray), type(values) if values.dtype != TD64NS_DTYPE: assert values.dtype == "i8" values = values.view(TD64NS_DTYPE) result = object.__new__(cls) result._data = values result._freq = to_offset(freq) result._dtype = TD64NS_DTYPE return result @classmethod def _from_sequence( cls, data, dtype=TD64NS_DTYPE, copy=False, freq=lib.no_default, unit=None ): if dtype: _validate_td64_dtype(dtype) explicit_none = freq is None freq = freq if freq is not lib.no_default else None freq, freq_infer = dtl.maybe_infer_freq(freq) data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=unit) freq, freq_infer = dtl.validate_inferred_freq(freq, inferred_freq, freq_infer) if explicit_none: freq = None result = cls._simple_new(data, freq=freq) if inferred_freq is None and freq is not None: # this condition precludes `freq_infer` cls._validate_frequency(result, freq) elif freq_infer: # Set _freq directly to bypass duplicative _validate_frequency # check. result._freq = to_offset(result.inferred_freq) return result @classmethod def _generate_range(cls, start, end, periods, freq, closed=None): periods = dtl.validate_periods(periods) if freq is None and any(x is None for x in [periods, start, end]): raise ValueError("Must provide freq argument if no data is supplied") if com.count_not_none(start, end, periods, freq) != 3: raise ValueError( "Of the four parameters: start, end, periods, " "and freq, exactly three must be specified" ) if start is not None: start = Timedelta(start) if end is not None: end = Timedelta(end) left_closed, right_closed = dtl.validate_endpoints(closed) if freq is not None: index = generate_regular_range(start, end, periods, freq) else: index = np.linspace(start.value, end.value, periods).astype("i8") if not left_closed: index = index[1:] if not right_closed: index = index[:-1] return cls._simple_new(index, freq=freq) # ---------------------------------------------------------------- # DatetimeLike Interface @classmethod def _rebox_native(cls, value: int) -> np.timedelta64: return np.int64(value).view("m8[ns]") def _unbox_scalar(self, value, setitem: bool = False): if not isinstance(value, self._scalar_type) and value is not NaT: raise ValueError("'value' should be a Timedelta.") self._check_compatible_with(value, setitem=setitem) return value.value def _scalar_from_string(self, value): return Timedelta(value) def _check_compatible_with(self, other, setitem: bool = False): # we don't have anything to validate. pass def _maybe_clear_freq(self): self._freq = None # ---------------------------------------------------------------- # Array-Like / EA-Interface Methods def astype(self, dtype, copy=True): # We handle # --> timedelta64[ns] # --> timedelta64 # DatetimeLikeArrayMixin super call handles other cases dtype = pandas_dtype(dtype) if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype): # by pandas convention, converting to non-nano timedelta64 # returns an int64-dtyped array with ints representing multiples # of the desired timedelta unit. This is essentially division if self._hasnans: # avoid double-copying result = self._data.astype(dtype, copy=False) values = self._maybe_mask_results( result, fill_value=None, convert="float64" ) return values result = self._data.astype(dtype, copy=copy) return result.astype("i8") elif is_timedelta64_ns_dtype(dtype): if copy: return self.copy() return self return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy=copy) # ---------------------------------------------------------------- # Reductions def sum( self, axis=None, dtype=None, out=None, keepdims: bool = False, initial=None, skipna: bool = True, min_count: int = 0, ): nv.validate_sum( (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial) ) if not len(self): return NaT if not skipna and self._hasnans: return NaT result = nanops.nansum( self._data, axis=axis, skipna=skipna, min_count=min_count ) return Timedelta(result) def std( self, axis=None, dtype=None, out=None, ddof: int = 1, keepdims: bool = False, skipna: bool = True, ): nv.validate_stat_ddof_func( (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="std" ) if not len(self): return NaT if not skipna and self._hasnans: return NaT result = nanops.nanstd(self._data, axis=axis, skipna=skipna, ddof=ddof) return Timedelta(result) def median( self, axis=None, out=None, overwrite_input: bool = False, keepdims: bool = False, skipna: bool = True, ): nv.validate_median( (), dict(out=out, overwrite_input=overwrite_input, keepdims=keepdims) ) return nanops.nanmedian(self._data, axis=axis, skipna=skipna) # ---------------------------------------------------------------- # Rendering Methods def _formatter(self, boxed=False): from pandas.io.formats.format import get_format_timedelta64 return get_format_timedelta64(self, box=True) def _format_native_types(self, na_rep="NaT", date_format=None, **kwargs): from pandas.io.formats.format import get_format_timedelta64 formatter = get_format_timedelta64(self._data, na_rep) return np.array([formatter(x) for x in self._data.ravel()]).reshape(self.shape) # ---------------------------------------------------------------- # Arithmetic Methods def _add_offset(self, other): assert not isinstance(other, Tick) raise TypeError( f"cannot add the type {type(other).__name__} to a {type(self).__name__}" ) def _add_period(self, other: Period): """ Add a Period object. """ # We will wrap in a PeriodArray and defer to the reversed operation from .period import PeriodArray i8vals = np.broadcast_to(other.ordinal, self.shape) oth = PeriodArray(i8vals, freq=other.freq) return oth + self def _add_datetime_arraylike(self, other): """ Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray. """ if isinstance(other, np.ndarray): # At this point we have already checked that dtype is datetime64 from pandas.core.arrays import DatetimeArray other = DatetimeArray(other) # defer to implementation in DatetimeArray return other + self def _add_datetimelike_scalar(self, other): # adding a timedeltaindex to a datetimelike from pandas.core.arrays import DatetimeArray assert other is not NaT other = Timestamp(other) if other is NaT: # In this case we specifically interpret NaT as a datetime, not # the timedelta interpretation we would get by returning self + NaT result = self.asi8.view("m8[ms]") + NaT.to_datetime64() return DatetimeArray(result) i8 = self.asi8 result = checked_add_with_arr(i8, other.value, arr_mask=self._isnan) result = self._maybe_mask_results(result) dtype = DatetimeTZDtype(tz=other.tz) if other.tz else DT64NS_DTYPE return DatetimeArray(result, dtype=dtype, freq=self.freq) def _addsub_object_array(self, other, op): # Add or subtract Array-like of objects try: # TimedeltaIndex can only operate with a subset of DateOffset # subclasses. Incompatible classes will raise AttributeError, # which we re-raise as TypeError return super()._addsub_object_array(other, op) except AttributeError as err: raise TypeError( f"Cannot add/subtract non-tick DateOffset to {type(self).__name__}" ) from err @unpack_zerodim_and_defer("__mul__") def __mul__(self, other): if is_scalar(other): # numpy will accept float and int, raise TypeError for others result = self._data * other freq = None if self.freq is not None and not isna(other): freq = self.freq * other return type(self)(result, freq=freq) if not hasattr(other, "dtype"): # list, tuple other = np.array(other) if len(other) != len(self) and not is_timedelta64_dtype(other.dtype): # Exclude timedelta64 here so we correctly raise TypeError # for that instead of ValueError raise ValueError("Cannot multiply with unequal lengths") if is_object_dtype(other.dtype): # this multiplication will succeed only if all elements of other # are int or float scalars, so we will end up with # timedelta64[ns]-dtyped result result = [self[n] * other[n] for n in range(len(self))] result = np.array(result) return type(self)(result) # numpy will accept float or int dtype, raise TypeError for others result = self._data * other return type(self)(result) __rmul__ = __mul__ @unpack_zerodim_and_defer("__truediv__") def __truediv__(self, other): # timedelta / X is well-defined for timedelta-like or numeric X if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) if other is NaT: # specifically timedelta64-NaT result = np.empty(self.shape, dtype=np.float64) result.fill(np.nan) return result # otherwise, dispatch to Timedelta implementation return self._data / other elif lib.is_scalar(other): # assume it is numeric result = self._data / other freq = None if self.freq is not None: # Tick division is not implemented, so operate on Timedelta freq = self.freq.delta / other return type(self)(result, freq=freq) if not hasattr(other, "dtype"): # e.g. list, tuple other = np.array(other) if len(other) != len(self): raise ValueError("Cannot divide vectors with unequal lengths") elif is_timedelta64_dtype(other.dtype): # let numpy handle it return self._data / other elif is_object_dtype(other.dtype): # We operate on raveled arrays to avoid problems in inference # on NaT srav = self.ravel() orav = other.ravel() result = [srav[n] / orav[n] for n in range(len(srav))] result = np.array(result).reshape(self.shape) # We need to do dtype inference in order to keep DataFrame ops # behavior consistent with Series behavior inferred = lib.infer_dtype(result) if inferred == "timedelta": flat = result.ravel() result = type(self)._from_sequence(flat).reshape(result.shape) elif inferred == "floating": result = result.astype(float) return result else: result = self._data / other return type(self)(result) @unpack_zerodim_and_defer("__rtruediv__") def __rtruediv__(self, other): # X / timedelta is defined only for timedelta-like X if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) if other is NaT: # specifically timedelta64-NaT result = np.empty(self.shape, dtype=np.float64) result.fill(np.nan) return result # otherwise, dispatch to Timedelta implementation return other / self._data elif lib.is_scalar(other): raise TypeError( f"Cannot divide {type(other).__name__} by {type(self).__name__}" ) if not hasattr(other, "dtype"): # e.g. list, tuple other = np.array(other) if len(other) != len(self): raise ValueError("Cannot divide vectors with unequal lengths") elif is_timedelta64_dtype(other.dtype): # let numpy handle it return other / self._data elif is_object_dtype(other.dtype): # Note: unlike in __truediv__, we do not _need_ to do type # inference on the result. It does not raise, a numeric array # is returned. GH#23829 result = [other[n] / self[n] for n in range(len(self))] return np.array(result) else: raise TypeError( f"Cannot divide {other.dtype} data by {type(self).__name__}" ) @unpack_zerodim_and_defer("__floordiv__") def __floordiv__(self, other): if is_scalar(other): if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) if other is NaT: # treat this specifically as timedelta-NaT result = np.empty(self.shape, dtype=np.float64) result.fill(np.nan) return result # dispatch to Timedelta implementation result = other.__rfloordiv__(self._data) return result # at this point we should only have numeric scalars; anything # else will raise result = self.asi8 // other result[self._isnan] = iNaT freq = None if self.freq is not None: # Note: freq gets division, not floor-division freq = self.freq / other if freq.nanos == 0 and self.freq.nanos != 0: # e.g. if self.freq is Nano(1) then dividing by 2 # rounds down to zero freq = None return type(self)(result.view("m8[ns]"), freq=freq) if not hasattr(other, "dtype"): # list, tuple other = np.array(other) if len(other) != len(self): raise ValueError("Cannot divide with unequal lengths") elif is_timedelta64_dtype(other.dtype): other = type(self)(other) # numpy timedelta64 does not natively support floordiv, so operate # on the i8 values result = self.asi8 // other.asi8 mask = self._isnan | other._isnan if mask.any(): result = result.astype(np.float64) result[mask] = np.nan return result elif is_object_dtype(other.dtype): result = [self[n] // other[n] for n in range(len(self))] result = np.array(result) if lib.infer_dtype(result, skipna=False) == "timedelta": result, _ = sequence_to_td64ns(result) return type(self)(result) return result elif is_integer_dtype(other.dtype) or is_float_dtype(other.dtype): result = self._data // other return type(self)(result) else: dtype = getattr(other, "dtype", type(other).__name__) raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}") @unpack_zerodim_and_defer("__rfloordiv__") def __rfloordiv__(self, other): if is_scalar(other): if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) if other is NaT: # treat this specifically as timedelta-NaT result = np.empty(self.shape, dtype=np.float64) result.fill(np.nan) return result # dispatch to Timedelta implementation result = other.__floordiv__(self._data) return result raise TypeError( f"Cannot divide {type(other).__name__} by {type(self).__name__}" ) if not hasattr(other, "dtype"): # list, tuple other = np.array(other) if len(other) != len(self): raise ValueError("Cannot divide with unequal lengths") elif is_timedelta64_dtype(other.dtype): other = type(self)(other) # numpy timedelta64 does not natively support floordiv, so operate # on the i8 values result = other.asi8 // self.asi8 mask = self._isnan | other._isnan if mask.any(): result = result.astype(np.float64) result[mask] = np.nan return result elif is_object_dtype(other.dtype): result = [other[n] // self[n] for n in range(len(self))] result = np.array(result) return result else: dtype = getattr(other, "dtype", type(other).__name__) raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}") @unpack_zerodim_and_defer("__mod__") def __mod__(self, other): # Note: This is a naive implementation, can likely be optimized if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) return self - (self // other) * other @unpack_zerodim_and_defer("__rmod__") def __rmod__(self, other): # Note: This is a naive implementation, can likely be optimized if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) return other - (other // self) * self @unpack_zerodim_and_defer("__divmod__") def __divmod__(self, other): # Note: This is a naive implementation, can likely be optimized if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) res1 = self // other res2 = self - res1 * other return res1, res2 @unpack_zerodim_and_defer("__rdivmod__") def __rdivmod__(self, other): # Note: This is a naive implementation, can likely be optimized if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) res1 = other // self res2 = other - res1 * self return res1, res2 def __neg__(self): if self.freq is not None: return type(self)(-self._data, freq=-self.freq) return type(self)(-self._data) def __pos__(self): return type(self)(self._data, freq=self.freq) def __abs__(self): # Note: freq is not preserved return type(self)(np.abs(self._data)) # ---------------------------------------------------------------- # Conversion Methods - Vectorized analogues of Timedelta methods def total_seconds(self): """ Return total duration of each element expressed in seconds. This method is available directly on TimedeltaArray, TimedeltaIndex and on Series containing timedelta values under the ``.dt`` namespace. Returns ------- seconds : [ndarray, Float64Index, Series] When the calling object is a TimedeltaArray, the return type is ndarray. When the calling object is a TimedeltaIndex, the return type is a Float64Index. When the calling object is a Series, the return type is Series of type `float64` whose index is the same as the original. See Also -------- datetime.timedelta.total_seconds : Standard library version of this method. TimedeltaIndex.components : Return a DataFrame with components of each Timedelta. Examples -------- **Series** >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d')) >>> s 0 0 days 1 1 days 2 2 days 3 3 days 4 4 days dtype: timedelta64[ns] >>> s.dt.total_seconds() 0 0.0 1 86400.0 2 172800.0 3 259200.0 4 345600.0 dtype: float64 **TimedeltaIndex** >>> idx = pd.to_timedelta(np.arange(5), unit='d') >>> idx TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq=None) >>> idx.total_seconds() Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0], dtype='float64') """ return self._maybe_mask_results(1e-9 * self.asi8, fill_value=None) def to_pytimedelta(self) -> np.ndarray: """ Return Timedelta Array/Index as object ndarray of datetime.timedelta objects. Returns ------- datetimes : ndarray """ return tslibs.ints_to_pytimedelta(self.asi8) days = _field_accessor("days", "days", "Number of days for each element.") seconds = _field_accessor( "seconds", "seconds", "Number of seconds (>= 0 and less than 1 day) for each element.", ) microseconds = _field_accessor( "microseconds", "microseconds", "Number of microseconds (>= 0 and less than 1 second) for each element.", ) nanoseconds = _field_accessor( "nanoseconds", "nanoseconds", "Number of nanoseconds (>= 0 and less than 1 microsecond) for each element.", ) @property def components(self): """ Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas. Returns ------- a DataFrame """ from pandas import DataFrame columns = [ "days", "hours", "minutes", "seconds", "milliseconds", "microseconds", "nanoseconds", ] hasnans = self._hasnans if hasnans: def f(x): if isna(x): return [np.nan] * len(columns) return x.components else: def f(x): return x.components result = DataFrame([f(x) for x in self], columns=columns) if not hasnans: result = result.astype("int64") return result # --------------------------------------------------------------------- # Constructor Helpers def sequence_to_td64ns(data, copy=False, unit=None, errors="raise"): """ Parameters ---------- data : list-like copy : bool, default False unit : str, optional The timedelta unit to treat integers as multiples of. For numeric data this defaults to ``'ns'``. Must be un-specified if the data contains a str and ``errors=="raise"``. errors : {"raise", "coerce", "ignore"}, default "raise" How to handle elements that cannot be converted to timedelta64[ns]. See ``pandas.to_timedelta`` for details. Returns ------- converted : numpy.ndarray The sequence converted to a numpy array with dtype ``timedelta64[ns]``. inferred_freq : Tick or None The inferred frequency of the sequence. Raises ------ ValueError : Data cannot be converted to timedelta64[ns]. Notes ----- Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause errors to be ignored; they are caught and subsequently ignored at a higher level. """ inferred_freq = None if unit is not None: unit = parse_timedelta_unit(unit) # Unwrap whatever we have into a np.ndarray if not hasattr(data, "dtype"): # e.g. list, tuple if np.ndim(data) == 0: # i.e. generator data = list(data) data = np.array(data, copy=False) elif isinstance(data, ABCSeries): data = data._values elif isinstance(data, (ABCTimedeltaIndex, TimedeltaArray)): inferred_freq = data.freq data = data._data elif isinstance(data, IntegerArray): data = data.to_numpy("int64", na_value=tslibs.iNaT) # Convert whatever we have into timedelta64[ns] dtype if is_object_dtype(data.dtype) or is_string_dtype(data.dtype): # no need to make a copy, need to convert if string-dtyped data = objects_to_td64ns(data, unit=unit, errors=errors) copy = False elif is_integer_dtype(data.dtype): # treat as multiples of the given unit data, copy_made = ints_to_td64ns(data, unit=unit) copy = copy and not copy_made elif is_float_dtype(data.dtype): # cast the unit, multiply base/frac separately # to avoid precision issues from float -> int mask = np.isnan(data) m, p = precision_from_unit(unit or "ns") base = data.astype(np.int64) frac = data - base if p: frac = np.round(frac, p) data = (base * m + (frac * m).astype(np.int64)).view("timedelta64[ns]") data[mask] = iNaT copy = False elif is_timedelta64_dtype(data.dtype): if data.dtype != TD64NS_DTYPE: # non-nano unit # TODO: watch out for overflows data = data.astype(TD64NS_DTYPE) copy = False else: # This includes datetime64-dtype, see GH#23539, GH#29794 raise TypeError(f"dtype {data.dtype} cannot be converted to timedelta64[ns]") data = np.array(data, copy=copy) assert data.dtype == "m8[ns]", data return data, inferred_freq def ints_to_td64ns(data, unit="ns"): """ Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating the integers as multiples of the given timedelta unit. Parameters ---------- data : numpy.ndarray with integer-dtype unit : str, default "ns" The timedelta unit to treat integers as multiples of. Returns ------- numpy.ndarray : timedelta64[ns] array converted from data bool : whether a copy was made """ copy_made = False unit = unit if unit is not None else "ns" if data.dtype != np.int64: # converting to int64 makes a copy, so we can avoid # re-copying later data = data.astype(np.int64) copy_made = True if unit != "ns": dtype_str = f"timedelta64[{unit}]" data = data.view(dtype_str) # TODO: watch out for overflows when converting from lower-resolution data = data.astype("timedelta64[ns]") # the astype conversion makes a copy, so we can avoid re-copying later copy_made = True else: data = data.view("timedelta64[ns]") return data, copy_made def objects_to_td64ns(data, unit=None, errors="raise"): """ Convert a object-dtyped or string-dtyped array into an timedelta64[ns]-dtyped array. Parameters ---------- data : ndarray or Index unit : str, default "ns" The timedelta unit to treat integers as multiples of. Must not be specified if the data contains a str. errors : {"raise", "coerce", "ignore"}, default "raise" How to handle elements that cannot be converted to timedelta64[ns]. See ``pandas.to_timedelta`` for details. Returns ------- numpy.ndarray : timedelta64[ns] array converted from data Raises ------ ValueError : Data cannot be converted to timedelta64[ns]. Notes ----- Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause errors to be ignored; they are caught and subsequently ignored at a higher level. """ # coerce Index to np.ndarray, converting string-dtype if necessary values = np.array(data, dtype=np.object_, copy=False) result = array_to_timedelta64(values, unit=unit, errors=errors) return result.view("timedelta64[ns]") def _validate_td64_dtype(dtype): dtype = pandas_dtype(dtype) if is_dtype_equal(dtype, np.dtype("timedelta64")): # no precision disallowed GH#24806 msg = ( "Passing in 'timedelta' dtype with no precision is not allowed. " "Please pass in 'timedelta64[ns]' instead." ) raise ValueError(msg) if not is_dtype_equal(dtype, TD64NS_DTYPE): raise ValueError(f"dtype {dtype} cannot be converted to timedelta64[ns]") return dtype
bsd-3-clause
numenta-ci/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
fbagirov/scikit-learn
sklearn/metrics/cluster/unsupervised.py
230
8281
""" Unsupervised evaluation metrics. """ # Authors: Robert Layton <[email protected]> # # License: BSD 3 clause import numpy as np from ...utils import check_random_state from ..pairwise import pairwise_distances def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. To clarify, ``b`` is the distance between a sample and the nearest cluster that the sample is not a part of. Note that Silhouette Coefficent is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the mean Silhouette Coefficient over all samples. To obtain the values for each sample, use :func:`silhouette_samples`. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Negative values generally indicate that a sample has been assigned to the wrong cluster, as a different cluster is more similar. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] Predicted labels for each sample. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`metrics.pairwise.pairwise_distances <sklearn.metrics.pairwise.pairwise_distances>`. If X is the distance array itself, use ``metric="precomputed"``. sample_size : int or None The size of the sample to use when computing the Silhouette Coefficient on a random subset of the data. If ``sample_size is None``, no sampling is used. random_state : integer or numpy.RandomState, optional The generator used to randomly select a subset of samples if ``sample_size is not None``. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : float Mean Silhouette Coefficient for all samples. References ---------- .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <http://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ n_labels = len(np.unique(labels)) n_samples = X.shape[0] if not 1 < n_labels < n_samples: raise ValueError("Number of labels is %d. Valid values are 2 " "to n_samples - 1 (inclusive)" % n_labels) if sample_size is not None: random_state = check_random_state(random_state) indices = random_state.permutation(X.shape[0])[:sample_size] if metric == "precomputed": X, labels = X[indices].T[indices].T, labels[indices] else: X, labels = X[indices], labels[indices] return np.mean(silhouette_samples(X, labels, metric=metric, **kwds)) def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each other, and well separated, where samples in different clusters are not very similar to each other. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. Note that Silhouette Coefficent is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the Silhouette Coefficient for each sample. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] label values for each sample metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is the distance array itself, use "precomputed" as the metric. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a ``scipy.spatial.distance`` metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : array, shape = [n_samples] Silhouette Coefficient for each samples. References ---------- .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <http://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ distances = pairwise_distances(X, metric=metric, **kwds) n = labels.shape[0] A = np.array([_intra_cluster_distance(distances[i], labels, i) for i in range(n)]) B = np.array([_nearest_cluster_distance(distances[i], labels, i) for i in range(n)]) sil_samples = (B - A) / np.maximum(A, B) return sil_samples def _intra_cluster_distance(distances_row, labels, i): """Calculate the mean intra-cluster distance for sample i. Parameters ---------- distances_row : array, shape = [n_samples] Pairwise distance matrix between sample i and each sample. labels : array, shape = [n_samples] label values for each sample i : int Sample index being calculated. It is excluded from calculation and used to determine the current label Returns ------- a : float Mean intra-cluster distance for sample i """ mask = labels == labels[i] mask[i] = False if not np.any(mask): # cluster of size 1 return 0 a = np.mean(distances_row[mask]) return a def _nearest_cluster_distance(distances_row, labels, i): """Calculate the mean nearest-cluster distance for sample i. Parameters ---------- distances_row : array, shape = [n_samples] Pairwise distance matrix between sample i and each sample. labels : array, shape = [n_samples] label values for each sample i : int Sample index being calculated. It is used to determine the current label. Returns ------- b : float Mean nearest-cluster distance for sample i """ label = labels[i] b = np.min([np.mean(distances_row[labels == cur_label]) for cur_label in set(labels) if not cur_label == label]) return b
bsd-3-clause
jshiv/turntable
test/lib/python2.7/site-packages/scipy/signal/windows.py
7
48626
"""The suite of window functions.""" from __future__ import division, print_function, absolute_import import warnings import numpy as np from scipy import special, linalg from scipy.fftpack import fft from scipy.lib.six import string_types __all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall', 'blackmanharris', 'flattop', 'bartlett', 'hanning', 'barthann', 'hamming', 'kaiser', 'gaussian', 'general_gaussian', 'chebwin', 'slepian', 'cosine', 'hann', 'get_window'] def boxcar(M, sym=True): """Return a boxcar or rectangular window. Included for completeness, this is equivalent to no window at all. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional Whether the window is symmetric. (Has no effect for boxcar.) Returns ------- w : ndarray The window, with the maximum value normalized to 1. Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.boxcar(51) >>> plt.plot(window) >>> plt.title("Boxcar window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the boxcar window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ return np.ones(M, float) def triang(M, sym=True): """Return a triangular window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.triang(51) >>> plt.plot(window) >>> plt.title("Triangular window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the triangular window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(1, (M + 1) // 2 + 1) if M % 2 == 0: w = (2 * n - 1.0) / M w = np.r_[w, w[::-1]] else: w = 2 * n / (M + 1.0) w = np.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w def parzen(M, sym=True): """Return a Parzen window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.parzen(51) >>> plt.plot(window) >>> plt.title("Parzen window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Parzen window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(-(M - 1) / 2.0, (M - 1) / 2.0 + 0.5, 1.0) na = np.extract(n < -(M - 1) / 4.0, n) nb = np.extract(abs(n) <= (M - 1) / 4.0, n) wa = 2 * (1 - np.abs(na) / (M / 2.0)) ** 3.0 wb = (1 - 6 * (np.abs(nb) / (M / 2.0)) ** 2.0 + 6 * (np.abs(nb) / (M / 2.0)) ** 3.0) w = np.r_[wa, wb, wa[::-1]] if not sym and not odd: w = w[:-1] return w def bohman(M, sym=True): """Return a Bohman window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.bohman(51) >>> plt.plot(window) >>> plt.title("Bohman window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Bohman window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 fac = np.abs(np.linspace(-1, 1, M)[1:-1]) w = (1 - fac) * np.cos(np.pi * fac) + 1.0 / np.pi * np.sin(np.pi * fac) w = np.r_[0, w, 0] if not sym and not odd: w = w[:-1] return w def blackman(M, sym=True): r""" Return a Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- The Blackman window is defined as .. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M) Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a "near optimal" tapering function, almost as good (by some measures) as the Kaiser window. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.blackman(51) >>> plt.plot(window) >>> plt.title("Blackman window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Blackman window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ # Docstring adapted from NumPy's blackman function if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) w = (0.42 - 0.5 * np.cos(2.0 * np.pi * n / (M - 1)) + 0.08 * np.cos(4.0 * np.pi * n / (M - 1))) if not sym and not odd: w = w[:-1] return w def nuttall(M, sym=True): """Return a minimum 4-term Blackman-Harris window according to Nuttall. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.nuttall(51) >>> plt.plot(window) >>> plt.title("Nuttall window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Nuttall window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 a = [0.3635819, 0.4891775, 0.1365995, 0.0106411] n = np.arange(0, M) fac = n * 2 * np.pi / (M - 1.0) w = (a[0] - a[1] * np.cos(fac) + a[2] * np.cos(2 * fac) - a[3] * np.cos(3 * fac)) if not sym and not odd: w = w[:-1] return w def blackmanharris(M, sym=True): """Return a minimum 4-term Blackman-Harris window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.blackmanharris(51) >>> plt.plot(window) >>> plt.title("Blackman-Harris window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Blackman-Harris window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 a = [0.35875, 0.48829, 0.14128, 0.01168] n = np.arange(0, M) fac = n * 2 * np.pi / (M - 1.0) w = (a[0] - a[1] * np.cos(fac) + a[2] * np.cos(2 * fac) - a[3] * np.cos(3 * fac)) if not sym and not odd: w = w[:-1] return w def flattop(M, sym=True): """Return a flat top window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.flattop(51) >>> plt.plot(window) >>> plt.title("Flat top window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the flat top window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 a = [0.2156, 0.4160, 0.2781, 0.0836, 0.0069] n = np.arange(0, M) fac = n * 2 * np.pi / (M - 1.0) w = (a[0] - a[1] * np.cos(fac) + a[2] * np.cos(2 * fac) - a[3] * np.cos(3 * fac) + a[4] * np.cos(4 * fac)) if not sym and not odd: w = w[:-1] return w def bartlett(M, sym=True): r""" Return a Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The triangular window, with the first and last samples equal to zero and the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- The Bartlett window is defined as .. math:: w(n) = \frac{2}{M-1} \left( \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right| \right) Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means"removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The Fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich. References ---------- .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", Biometrika 37, 1-16, 1950. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal Processing", Prentice-Hall, 1999, pp. 468-471. .. [4] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 429. Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.bartlett(51) >>> plt.plot(window) >>> plt.title("Bartlett window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Bartlett window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ # Docstring adapted from NumPy's bartlett function if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) w = np.where(np.less_equal(n, (M - 1) / 2.0), 2.0 * n / (M - 1), 2.0 - 2.0 * n / (M - 1)) if not sym and not odd: w = w[:-1] return w def hann(M, sym=True): r""" Return a Hann window. The Hann window is a taper formed by using a raised cosine or sine-squared with ends that touch zero. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- The Hann window is defined as .. math:: w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1 The window was named for Julius van Hann, an Austrian meteorologist. It is also known as the Cosine Bell. It is sometimes erroneously referred to as the "Hanning" window, from the use of "hann" as a verb in the original paper and confusion with the very similar Hamming window. Most references to the Hann window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 106-108. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.hann(51) >>> plt.plot(window) >>> plt.title("Hann window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Hann window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ # Docstring adapted from NumPy's hanning function if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) w = 0.5 - 0.5 * np.cos(2.0 * np.pi * n / (M - 1)) if not sym and not odd: w = w[:-1] return w hanning = hann def barthann(M, sym=True): """Return a modified Bartlett-Hann window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.barthann(51) >>> plt.plot(window) >>> plt.title("Bartlett-Hann window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Bartlett-Hann window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) fac = np.abs(n / (M - 1.0) - 0.5) w = 0.62 - 0.48 * fac + 0.38 * np.cos(2 * np.pi * fac) if not sym and not odd: w = w[:-1] return w def hamming(M, sym=True): r"""Return a Hamming window. The Hamming window is a taper formed by using a raised cosine with non-zero endpoints, optimized to minimize the nearest side lobe. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- The Hamming window is defined as .. math:: w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1 The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman and Tukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Most references to the Hamming window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.hamming(51) >>> plt.plot(window) >>> plt.title("Hamming window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Hamming window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ # Docstring adapted from NumPy's hamming function if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) w = 0.54 - 0.46 * np.cos(2.0 * np.pi * n / (M - 1)) if not sym and not odd: w = w[:-1] return w def kaiser(M, beta, sym=True): r"""Return a Kaiser window. The Kaiser window is a taper formed by using a Bessel function. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. beta : float Shape parameter, determines trade-off between main-lobe width and side lobe level. As beta gets large, the window narrows. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- The Kaiser window is defined as .. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}} \right)/I_0(\beta) with .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2}, where :math:`I_0` is the modified zeroth-order Bessel function. The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based on Bessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence, or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative to total energy. The Kaiser can approximate many other windows by varying the beta parameter. ==== ======================= beta Window shape ==== ======================= 0 Rectangular 5 Similar to a Hamming 6 Similar to a Hann 8.6 Similar to a Blackman ==== ======================= A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned. Most references to the Kaiser window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966). .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 177-178. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.kaiser(51, beta=14) >>> plt.plot(window) >>> plt.title(r"Kaiser window ($\beta$=14)") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ # Docstring adapted from NumPy's kaiser function if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) alpha = (M - 1) / 2.0 w = (special.i0(beta * np.sqrt(1 - ((n - alpha) / alpha) ** 2.0)) / special.i0(beta)) if not sym and not odd: w = w[:-1] return w def gaussian(M, std, sym=True): r"""Return a Gaussian window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. std : float The standard deviation, sigma. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- The Gaussian window is defined as .. math:: w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 } Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.gaussian(51, std=7) >>> plt.plot(window) >>> plt.title(r"Gaussian window ($\sigma$=7)") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) - (M - 1.0) / 2.0 sig2 = 2 * std * std w = np.exp(-n ** 2 / sig2) if not sym and not odd: w = w[:-1] return w def general_gaussian(M, p, sig, sym=True): r"""Return a window with a generalized Gaussian shape. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. p : float Shape parameter. p = 1 is identical to `gaussian`, p = 0.5 is the same shape as the Laplace distribution. sig : float The standard deviation, sigma. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- The generalized Gaussian window is defined as .. math:: w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} } the half-power point is at .. math:: (2 \log(2))^{1/(2 p)} \sigma Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.general_gaussian(51, p=1.5, sig=7) >>> plt.plot(window) >>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title(r"Freq. resp. of the gen. Gaussian window (p=1.5, $\sigma$=7)") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 n = np.arange(0, M) - (M - 1.0) / 2.0 w = np.exp(-0.5 * np.abs(n / sig) ** (2 * p)) if not sym and not odd: w = w[:-1] return w # `chebwin` contributed by Kumar Appaiah. def chebwin(M, at, sym=True): r"""Return a Dolph-Chebyshev window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. at : float Attenuation (in dB). sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value always normalized to 1 Notes ----- This window optimizes for the narrowest main lobe width for a given order `M` and sidelobe equiripple attenuation `at`, using Chebyshev polynomials. It was originally developed by Dolph to optimize the directionality of radio antenna arrays. Unlike most windows, the Dolph-Chebyshev is defined in terms of its frequency response: .. math:: W(k) = \frac {\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}} {\cosh[M \cosh^{-1}(\beta)]} where .. math:: \beta = \cosh \left [\frac{1}{M} \cosh^{-1}(10^\frac{A}{20}) \right ] and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`). The time domain window is then generated using the IFFT, so power-of-two `M` are the fastest to generate, and prime number `M` are the slowest. The equiripple condition in the frequency domain creates impulses in the time domain, which appear at the ends of the window. References ---------- .. [1] C. Dolph, "A current distribution for broadside arrays which optimizes the relationship between beam width and side-lobe level", Proceedings of the IEEE, Vol. 34, Issue 6 .. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter", American Meteorological Society (April 1997) http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf .. [3] F. J. Harris, "On the use of windows for harmonic analysis with the discrete Fourier transforms", Proceedings of the IEEE, Vol. 66, No. 1, January 1978 Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.chebwin(51, at=100) >>> plt.plot(window) >>> plt.title("Dolph-Chebyshev window (100 dB)") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if np.abs(at) < 45: warnings.warn("This window is not suitable for spectral analysis " "for attenuation values lower than about 45dB because " "the equivalent noise bandwidth of a Chebyshev window " "does not grow monotonically with increasing sidelobe " "attenuation when the attenuation is smaller than " "about 45 dB.") if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 # compute the parameter beta order = M - 1.0 beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.))) k = np.r_[0:M] * 1.0 x = beta * np.cos(np.pi * k / M) # Find the window's DFT coefficients # Use analytic definition of Chebyshev polynomial instead of expansion # from scipy.special. Using the expansion in scipy.special leads to errors. p = np.zeros(x.shape) p[x > 1] = np.cosh(order * np.arccosh(x[x > 1])) p[x < -1] = (1 - 2 * (order % 2)) * np.cosh(order * np.arccosh(-x[x < -1])) p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1])) # Appropriate IDFT and filling up # depending on even/odd M if M % 2: w = np.real(fft(p)) n = (M + 1) // 2 w = w[:n] w = np.concatenate((w[n - 1:0:-1], w)) else: p = p * np.exp(1.j * np.pi / M * np.r_[0:M]) w = np.real(fft(p)) n = M // 2 + 1 w = np.concatenate((w[n - 1:0:-1], w[1:n])) w = w / max(w) if not sym and not odd: w = w[:-1] return w def slepian(M, width, sym=True): """Return a digital Slepian (DPSS) window. Used to maximize the energy concentration in the main lobe. Also called the digital prolate spheroidal sequence (DPSS). Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. width : float Bandwidth sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value always normalized to 1 Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.slepian(51, width=0.3) >>> plt.plot(window) >>> plt.title("Slepian (DPSS) window (BW=0.3)") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Slepian window (BW=0.3)") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ if (M * width > 27.38): raise ValueError("Cannot reliably obtain Slepian sequences for" " M*width > 27.38.") if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 twoF = width / 2.0 alpha = (M - 1) / 2.0 m = np.arange(0, M) - alpha n = m[:, np.newaxis] k = m[np.newaxis, :] AF = twoF * special.sinc(twoF * (n - k)) [lam, vec] = linalg.eig(AF) ind = np.argmax(abs(lam), axis=-1) w = np.abs(vec[:, ind]) w = w / max(w) if not sym and not odd: w = w[:-1] return w def cosine(M, sym=True): """Return a window with a simple cosine shape. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- .. versionadded:: 0.13.0 Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.cosine(51) >>> plt.plot(window) >>> plt.title("Cosine window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the cosine window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.show() """ if M < 1: return np.array([]) if M == 1: return np.ones(1, 'd') odd = M % 2 if not sym and not odd: M = M + 1 w = np.sin(np.pi / M * (np.arange(0, M) + .5)) if not sym and not odd: w = w[:-1] return w def get_window(window, Nx, fftbins=True): """ Return a window. Parameters ---------- window : string, float, or tuple The type of window to create. See below for more details. Nx : int The number of samples in the window. fftbins : bool, optional If True, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Returns ------- get_window : ndarray Returns a window of length `Nx` and type `window` Notes ----- Window types: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation) If the window requires no parameters, then `window` can be a string. If the window requires parameters, then `window` must be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If `window` is a floating point number, it is interpreted as the beta parameter of the kaiser window. Each of the window types listed above is also the name of a function that can be called directly to create a window of that type. Examples -------- >>> from scipy import signal >>> signal.get_window('triang', 7) array([ 0.25, 0.5 , 0.75, 1. , 0.75, 0.5 , 0.25]) >>> signal.get_window(('kaiser', 4.0), 9) array([ 0.08848053, 0.32578323, 0.63343178, 0.89640418, 1. , 0.89640418, 0.63343178, 0.32578323, 0.08848053]) >>> signal.get_window(4.0, 9) array([ 0.08848053, 0.32578323, 0.63343178, 0.89640418, 1. , 0.89640418, 0.63343178, 0.32578323, 0.08848053]) """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, tuple): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, string_types): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs', 'slepian', 'optimal', 'slep', 'dss', 'chebwin', 'cheb']: raise ValueError("The '" + window + "' window needs one or " "more parameters -- pass a tuple.") else: winstr = window else: raise ValueError("%s as window type is not supported." % str(type(window))) if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hann elif winstr in ['blackmanharris', 'blackharr', 'bkh']: winfunc = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfunc = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfunc = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfunc = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfunc = barthann elif winstr in ['flattop', 'flat', 'flt']: winfunc = flattop elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones', 'rect', 'rectangular']: winfunc = boxcar elif winstr in ['slepian', 'slep', 'optimal', 'dpss', 'dss']: winfunc = slepian elif winstr in ['cosine', 'halfcosine']: winfunc = cosine elif winstr in ['chebwin', 'cheb']: winfunc = chebwin else: raise ValueError("Unknown window type.") params = (Nx,) + args + (sym,) else: winfunc = kaiser params = (Nx, beta, sym) return winfunc(*params)
mit
mikebenfield/scipy
scipy/cluster/hierarchy.py
5
98379
""" ======================================================== Hierarchical clustering (:mod:`scipy.cluster.hierarchy`) ======================================================== .. currentmodule:: scipy.cluster.hierarchy These functions cut hierarchical clusterings into flat clusterings or find the roots of the forest formed by a cut by providing the flat cluster ids of each observation. .. autosummary:: :toctree: generated/ fcluster fclusterdata leaders These are routines for agglomerative clustering. .. autosummary:: :toctree: generated/ linkage single complete average weighted centroid median ward These routines compute statistics on hierarchies. .. autosummary:: :toctree: generated/ cophenet from_mlab_linkage inconsistent maxinconsts maxdists maxRstat to_mlab_linkage Routines for visualizing flat clusters. .. autosummary:: :toctree: generated/ dendrogram These are data structures and routines for representing hierarchies as tree objects. .. autosummary:: :toctree: generated/ ClusterNode leaves_list to_tree cut_tree These are predicates for checking the validity of linkage and inconsistency matrices as well as for checking isomorphism of two flat cluster assignments. .. autosummary:: :toctree: generated/ is_valid_im is_valid_linkage is_isomorphic is_monotonic correspond num_obs_linkage Utility routines for plotting: .. autosummary:: :toctree: generated/ set_link_color_palette References ---------- .. [1] "Statistics toolbox." API Reference Documentation. The MathWorks. http://www.mathworks.com/access/helpdesk/help/toolbox/stats/. Accessed October 1, 2007. .. [2] "Hierarchical clustering." API Reference Documentation. The Wolfram Research, Inc. http://reference.wolfram.com/mathematica/HierarchicalClustering/tutorial/ HierarchicalClustering.html. Accessed October 1, 2007. .. [3] Gower, JC and Ross, GJS. "Minimum Spanning Trees and Single Linkage Cluster Analysis." Applied Statistics. 18(1): pp. 54--64. 1969. .. [4] Ward Jr, JH. "Hierarchical grouping to optimize an objective function." Journal of the American Statistical Association. 58(301): pp. 236--44. 1963. .. [5] Johnson, SC. "Hierarchical clustering schemes." Psychometrika. 32(2): pp. 241--54. 1966. .. [6] Sneath, PH and Sokal, RR. "Numerical taxonomy." Nature. 193: pp. 855--60. 1962. .. [7] Batagelj, V. "Comparing resemblance measures." Journal of Classification. 12: pp. 73--90. 1995. .. [8] Sokal, RR and Michener, CD. "A statistical method for evaluating systematic relationships." Scientific Bulletins. 38(22): pp. 1409--38. 1958. .. [9] Edelbrock, C. "Mixture model tests of hierarchical clustering algorithms: the problem of classifying everybody." Multivariate Behavioral Research. 14: pp. 367--84. 1979. .. [10] Jain, A., and Dubes, R., "Algorithms for Clustering Data." Prentice-Hall. Englewood Cliffs, NJ. 1988. .. [11] Fisher, RA "The use of multiple measurements in taxonomic problems." Annals of Eugenics, 7(2): 179-188. 1936 * MATLAB and MathWorks are registered trademarks of The MathWorks, Inc. * Mathematica is a registered trademark of The Wolfram Research, Inc. """ from __future__ import division, print_function, absolute_import # Copyright (C) Damian Eads, 2007-2008. New BSD License. # hierarchy.py (derived from cluster.py, http://scipy-cluster.googlecode.com) # # Author: Damian Eads # Date: September 22, 2007 # # Copyright (c) 2007, 2008, Damian Eads # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # - Redistributions of source code must retain the above # copyright notice, this list of conditions and the # following disclaimer. # - 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. # - Neither the name of the author nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # 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 # OWNER 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 warnings import bisect from collections import deque import numpy as np from . import _hierarchy import scipy.spatial.distance as distance from scipy._lib.six import string_types from scipy._lib.six import xrange _LINKAGE_METHODS = {'single': 0, 'complete': 1, 'average': 2, 'centroid': 3, 'median': 4, 'ward': 5, 'weighted': 6} _EUCLIDEAN_METHODS = ('centroid', 'median', 'ward') __all__ = ['ClusterNode', 'average', 'centroid', 'complete', 'cophenet', 'correspond', 'cut_tree', 'dendrogram', 'fcluster', 'fclusterdata', 'from_mlab_linkage', 'inconsistent', 'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage', 'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists', 'maxinconsts', 'median', 'num_obs_linkage', 'set_link_color_palette', 'single', 'to_mlab_linkage', 'to_tree', 'ward', 'weighted', 'distance'] class ClusterWarning(UserWarning): pass def _warning(s): warnings.warn('scipy.cluster: %s' % s, ClusterWarning, stacklevel=3) def _copy_array_if_base_present(a): """ Copies the array if its base points to a parent array. """ if a.base is not None: return a.copy() elif np.issubsctype(a, np.float32): return np.array(a, dtype=np.double) else: return a def _copy_arrays_if_base_present(T): """ Accepts a tuple of arrays T. Copies the array T[i] if its base array points to an actual array. Otherwise, the reference is just copied. This is useful if the arrays are being passed to a C function that does not do proper striding. """ l = [_copy_array_if_base_present(a) for a in T] return l def _randdm(pnts): """ Generates a random distance matrix stored in condensed form. A pnts * (pnts - 1) / 2 sized vector is returned. """ if pnts >= 2: D = np.random.rand(pnts * (pnts - 1) / 2) else: raise ValueError("The number of points in the distance matrix " "must be at least 2.") return D def single(y): """ Performs single/min/nearest linkage on the condensed distance matrix ``y`` Parameters ---------- y : ndarray The upper triangular of the distance matrix. The result of ``pdist`` is returned in this form. Returns ------- Z : ndarray The linkage matrix. See Also -------- linkage: for advanced creation of hierarchical clusterings. scipy.spatial.distance.pdist : pairwise distance metrics """ return linkage(y, method='single', metric='euclidean') def complete(y): """ Performs complete/max/farthest point linkage on a condensed distance matrix Parameters ---------- y : ndarray The upper triangular of the distance matrix. The result of ``pdist`` is returned in this form. Returns ------- Z : ndarray A linkage matrix containing the hierarchical clustering. See the `linkage` function documentation for more information on its structure. See Also -------- linkage: for advanced creation of hierarchical clusterings. scipy.spatial.distance.pdist : pairwise distance metrics """ return linkage(y, method='complete', metric='euclidean') def average(y): """ Performs average/UPGMA linkage on a condensed distance matrix Parameters ---------- y : ndarray The upper triangular of the distance matrix. The result of ``pdist`` is returned in this form. Returns ------- Z : ndarray A linkage matrix containing the hierarchical clustering. See the `linkage` function documentation for more information on its structure. See Also -------- linkage: for advanced creation of hierarchical clusterings. scipy.spatial.distance.pdist : pairwise distance metrics """ return linkage(y, method='average', metric='euclidean') def weighted(y): """ Performs weighted/WPGMA linkage on the condensed distance matrix. See ``linkage`` for more information on the return structure and algorithm. Parameters ---------- y : ndarray The upper triangular of the distance matrix. The result of ``pdist`` is returned in this form. Returns ------- Z : ndarray A linkage matrix containing the hierarchical clustering. See the ``linkage`` function documentation for more information on its structure. See Also -------- linkage : for advanced creation of hierarchical clusterings. scipy.spatial.distance.pdist : pairwise distance metrics """ return linkage(y, method='weighted', metric='euclidean') def centroid(y): """ Performs centroid/UPGMC linkage. See ``linkage`` for more information on the input matrix, return structure, and algorithm. The following are common calling conventions: 1. ``Z = centroid(y)`` Performs centroid/UPGMC linkage on the condensed distance matrix ``y``. See ``linkage`` for more information on the return structure and algorithm. 2. ``Z = centroid(X)`` Performs centroid/UPGMC linkage on the observation matrix ``X`` using Euclidean distance as the distance metric. See `linkage` for more information on the return structure and algorithm. Parameters ---------- y : ndarray A condensed distance matrix. A condensed distance matrix is a flat array containing the upper triangular of the distance matrix. This is the form that ``pdist`` returns. Alternatively, a collection of m observation vectors in n dimensions may be passed as a m by n array. Returns ------- Z : ndarray A linkage matrix containing the hierarchical clustering. See the `linkage` function documentation for more information on its structure. See Also -------- linkage: for advanced creation of hierarchical clusterings. """ return linkage(y, method='centroid', metric='euclidean') def median(y): """ Performs median/WPGMC linkage. See ``linkage`` for more information on the return structure and algorithm. The following are common calling conventions: 1. ``Z = median(y)`` Performs median/WPGMC linkage on the condensed distance matrix ``y``. See ``linkage`` for more information on the return structure and algorithm. 2. ``Z = median(X)`` Performs median/WPGMC linkage on the observation matrix ``X`` using Euclidean distance as the distance metric. See `linkage` for more information on the return structure and algorithm. Parameters ---------- y : ndarray A condensed distance matrix. A condensed distance matrix is a flat array containing the upper triangular of the distance matrix. This is the form that ``pdist`` returns. Alternatively, a collection of m observation vectors in n dimensions may be passed as a m by n array. Returns ------- Z : ndarray The hierarchical clustering encoded as a linkage matrix. See Also -------- linkage: for advanced creation of hierarchical clusterings. scipy.spatial.distance.pdist : pairwise distance metrics """ return linkage(y, method='median', metric='euclidean') def ward(y): """ Performs Ward's linkage on a condensed distance matrix. See linkage for more information on the return structure and algorithm. The following are common calling conventions: 1. ``Z = ward(y)`` Performs Ward's linkage on the condensed distance matrix ``Z``. See linkage for more information on the return structure and algorithm. 2. ``Z = ward(X)`` Performs Ward's linkage on the observation matrix ``X`` using Euclidean distance as the distance metric. See linkage for more information on the return structure and algorithm. Parameters ---------- y : ndarray A condensed distance matrix. A condensed distance matrix is a flat array containing the upper triangular of the distance matrix. This is the form that ``pdist`` returns. Alternatively, a collection of m observation vectors in n dimensions may be passed as a m by n array. Returns ------- Z : ndarray The hierarchical clustering encoded as a linkage matrix. See Also -------- linkage: for advanced creation of hierarchical clusterings. scipy.spatial.distance.pdist : pairwise distance metrics """ return linkage(y, method='ward', metric='euclidean') def linkage(y, method='single', metric='euclidean'): """ Performs hierarchical/agglomerative clustering. The input y may be either a 1d compressed distance matrix or a 2d array of observation vectors. If y is a 1d compressed distance matrix, then y must be a :math:`{n \\choose 2}` sized vector where n is the number of original observations paired in the distance matrix. The behavior of this function is very similar to the MATLAB linkage function. A :math:`(n-1)` by 4 matrix ``Z`` is returned. At the :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A cluster with an index less than :math:`n` corresponds to one of the :math:`n` original observations. The distance between clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The fourth value ``Z[i, 3]`` represents the number of original observations in the newly formed cluster. The following linkage methods are used to compute the distance :math:`d(s, t)` between two clusters :math:`s` and :math:`t`. The algorithm begins with a forest of clusters that have yet to be used in the hierarchy being formed. When two clusters :math:`s` and :math:`t` from this forest are combined into a single cluster :math:`u`, :math:`s` and :math:`t` are removed from the forest, and :math:`u` is added to the forest. When only one cluster remains in the forest, the algorithm stops, and this cluster becomes the root. A distance matrix is maintained at each iteration. The ``d[i,j]`` entry corresponds to the distance between cluster :math:`i` and :math:`j` in the original forest. At each iteration, the algorithm must update the distance matrix to reflect the distance of the newly formed cluster u with the remaining clusters in the forest. Suppose there are :math:`|u|` original observations :math:`u[0], \\ldots, u[|u|-1]` in cluster :math:`u` and :math:`|v|` original objects :math:`v[0], \\ldots, v[|v|-1]` in cluster :math:`v`. Recall :math:`s` and :math:`t` are combined to form cluster :math:`u`. Let :math:`v` be any remaining cluster in the forest that is not :math:`u`. The following are methods for calculating the distance between the newly formed cluster :math:`u` and each :math:`v`. * method='single' assigns .. math:: d(u,v) = \\min(dist(u[i],v[j])) for all points :math:`i` in cluster :math:`u` and :math:`j` in cluster :math:`v`. This is also known as the Nearest Point Algorithm. * method='complete' assigns .. math:: d(u, v) = \\max(dist(u[i],v[j])) for all points :math:`i` in cluster u and :math:`j` in cluster :math:`v`. This is also known by the Farthest Point Algorithm or Voor Hees Algorithm. * method='average' assigns .. math:: d(u,v) = \\sum_{ij} \\frac{d(u[i], v[j])} {(|u|*|v|)} for all points :math:`i` and :math:`j` where :math:`|u|` and :math:`|v|` are the cardinalities of clusters :math:`u` and :math:`v`, respectively. This is also called the UPGMA algorithm. * method='weighted' assigns .. math:: d(u,v) = (dist(s,v) + dist(t,v))/2 where cluster u was formed with cluster s and t and v is a remaining cluster in the forest. (also called WPGMA) * method='centroid' assigns .. math:: dist(s,t) = ||c_s-c_t||_2 where :math:`c_s` and :math:`c_t` are the centroids of clusters :math:`s` and :math:`t`, respectively. When two clusters :math:`s` and :math:`t` are combined into a new cluster :math:`u`, the new centroid is computed over all the original objects in clusters :math:`s` and :math:`t`. The distance then becomes the Euclidean distance between the centroid of :math:`u` and the centroid of a remaining cluster :math:`v` in the forest. This is also known as the UPGMC algorithm. * method='median' assigns :math:`d(s,t)` like the ``centroid`` method. When two clusters :math:`s` and :math:`t` are combined into a new cluster :math:`u`, the average of centroids s and t give the new centroid :math:`u`. This is also known as the WPGMC algorithm. * method='ward' uses the Ward variance minimization algorithm. The new entry :math:`d(u,v)` is computed as follows, .. math:: d(u,v) = \\sqrt{\\frac{|v|+|s|} {T}d(v,s)^2 + \\frac{|v|+|t|} {T}d(v,t)^2 - \\frac{|v|} {T}d(s,t)^2} where :math:`u` is the newly joined cluster consisting of clusters :math:`s` and :math:`t`, :math:`v` is an unused cluster in the forest, :math:`T=|v|+|s|+|t|`, and :math:`|*|` is the cardinality of its argument. This is also known as the incremental algorithm. Warning: When the minimum distance pair in the forest is chosen, there may be two or more pairs with the same minimum distance. This implementation may chose a different minimum than the MATLAB version. Parameters ---------- y : ndarray A condensed distance matrix. A condensed distance matrix is a flat array containing the upper triangular of the distance matrix. This is the form that ``pdist`` returns. Alternatively, a collection of :math:`m` observation vectors in n dimensions may be passed as an :math:`m` by :math:`n` array. All elements of `y` must be finite, i.e. no NaNs or infs. method : str, optional The linkage algorithm to use. See the ``Linkage Methods`` section below for full descriptions. metric : str or function, optional The distance metric to use in the case that y is a collection of observation vectors; ignored otherwise. See the ``pdist`` function for a list of valid distance metrics. A custom distance function can also be used. Returns ------- Z : ndarray The hierarchical clustering encoded as a linkage matrix. Notes ----- 1. For method 'single' an optimized algorithm based on minimum spanning tree is implemented. It has time complexity :math:`O(n^2)`. For methods 'complete', 'average', 'weighted' and 'ward' an algorithm called nearest-neighbors chain is implemented. It also has time complexity :math:`O(n^2)`. For other methods a naive algorithm is implemented with :math:`O(n^3)` time complexity. All algorithms use :math:`O(n^2)` memory. Refer to [1]_ for details about the algorithms. 2. Methods 'centroid', 'median' and 'ward' are correctly defined only if Euclidean pairwise metric is used. If `y` is passed as precomputed pairwise distances, then it is a user responsibility to assure that these distances are in fact Euclidean, otherwise the produced result will be incorrect. See Also -------- scipy.spatial.distance.pdist : pairwise distance metrics References ---------- .. [1] Daniel Mullner, "Modern hierarchical, agglomerative clustering algorithms", :arXiv:`1109.2378v1`. """ if method not in _LINKAGE_METHODS: raise ValueError("Invalid method: {0}".format(method)) y = _convert_to_double(np.asarray(y, order='c')) if y.ndim == 1: distance.is_valid_y(y, throw=True, name='y') [y] = _copy_arrays_if_base_present([y]) elif y.ndim == 2: if method in _EUCLIDEAN_METHODS and metric != 'euclidean': raise ValueError("Method '{0}' requires the distance metric " "to be Euclidean".format(method)) if y.shape[0] == y.shape[1] and np.allclose(np.diag(y), 0): if np.all(y >= 0) and np.allclose(y, y.T): _warning('The symmetric non-negative hollow observation ' 'matrix looks suspiciously like an uncondensed ' 'distance matrix') y = distance.pdist(y, metric) else: raise ValueError("`y` must be 1 or 2 dimensional.") if not np.all(np.isfinite(y)): raise ValueError("`y` must contain only finite values.") n = int(distance.num_obs_y(y)) method_code = _LINKAGE_METHODS[method] if method == 'single': return _hierarchy.mst_single_linkage(y, n) elif method in ['complete', 'average', 'weighted', 'ward']: return _hierarchy.nn_chain(y, n, method_code) else: return _hierarchy.linkage(y, n, method_code) class ClusterNode: """ A tree node class for representing a cluster. Leaf nodes correspond to original observations, while non-leaf nodes correspond to non-singleton clusters. The `to_tree` function converts a matrix returned by the linkage function into an easy-to-use tree representation. All parameter names are also attributes. Parameters ---------- id : int The node id. left : ClusterNode instance, optional The left child tree node. right : ClusterNode instance, optional The right child tree node. dist : float, optional Distance for this cluster in the linkage matrix. count : int, optional The number of samples in this cluster. See Also -------- to_tree : for converting a linkage matrix ``Z`` into a tree object. """ def __init__(self, id, left=None, right=None, dist=0, count=1): if id < 0: raise ValueError('The id must be non-negative.') if dist < 0: raise ValueError('The distance must be non-negative.') if (left is None and right is not None) or \ (left is not None and right is None): raise ValueError('Only full or proper binary trees are permitted.' ' This node has one child.') if count < 1: raise ValueError('A cluster must contain at least one original ' 'observation.') self.id = id self.left = left self.right = right self.dist = dist if self.left is None: self.count = count else: self.count = left.count + right.count def __lt__(self, node): if not isinstance(node, ClusterNode): raise ValueError("Can't compare ClusterNode " "to type {}".format(type(node))) return self.dist < node.dist def __gt__(self, node): if not isinstance(node, ClusterNode): raise ValueError("Can't compare ClusterNode " "to type {}".format(type(node))) return self.dist > node.dist def __eq__(self, node): if not isinstance(node, ClusterNode): raise ValueError("Can't compare ClusterNode " "to type {}".format(type(node))) return self.dist == node.dist def get_id(self): """ The identifier of the target node. For ``0 <= i < n``, `i` corresponds to original observation i. For ``n <= i < 2n-1``, `i` corresponds to non-singleton cluster formed at iteration ``i-n``. Returns ------- id : int The identifier of the target node. """ return self.id def get_count(self): """ The number of leaf nodes (original observations) belonging to the cluster node nd. If the target node is a leaf, 1 is returned. Returns ------- get_count : int The number of leaf nodes below the target node. """ return self.count def get_left(self): """ Return a reference to the left child tree object. Returns ------- left : ClusterNode The left child of the target node. If the node is a leaf, None is returned. """ return self.left def get_right(self): """ Returns a reference to the right child tree object. Returns ------- right : ClusterNode The left child of the target node. If the node is a leaf, None is returned. """ return self.right def is_leaf(self): """ Returns True if the target node is a leaf. Returns ------- leafness : bool True if the target node is a leaf node. """ return self.left is None def pre_order(self, func=(lambda x: x.id)): """ Performs pre-order traversal without recursive function calls. When a leaf node is first encountered, ``func`` is called with the leaf node as its argument, and its result is appended to the list. For example, the statement:: ids = root.pre_order(lambda x: x.id) returns a list of the node ids corresponding to the leaf nodes of the tree as they appear from left to right. Parameters ---------- func : function Applied to each leaf ClusterNode object in the pre-order traversal. Given the ``i``-th leaf node in the pre-order traversal ``n[i]``, the result of ``func(n[i])`` is stored in ``L[i]``. If not provided, the index of the original observation to which the node corresponds is used. Returns ------- L : list The pre-order traversal. """ # Do a preorder traversal, caching the result. To avoid having to do # recursion, we'll store the previous index we've visited in a vector. n = self.count curNode = [None] * (2 * n) lvisited = set() rvisited = set() curNode[0] = self k = 0 preorder = [] while k >= 0: nd = curNode[k] ndid = nd.id if nd.is_leaf(): preorder.append(func(nd)) k = k - 1 else: if ndid not in lvisited: curNode[k + 1] = nd.left lvisited.add(ndid) k = k + 1 elif ndid not in rvisited: curNode[k + 1] = nd.right rvisited.add(ndid) k = k + 1 # If we've visited the left and right of this non-leaf # node already, go up in the tree. else: k = k - 1 return preorder _cnode_bare = ClusterNode(0) _cnode_type = type(ClusterNode) def _order_cluster_tree(Z): """ Returns clustering nodes in bottom-up order by distance. Parameters ---------- Z : scipy.cluster.linkage array The linkage matrix. Returns ------- nodes : list A list of ClusterNode objects. """ q = deque() tree = to_tree(Z) q.append(tree) nodes = [] while q: node = q.popleft() if not node.is_leaf(): bisect.insort_left(nodes, node) q.append(node.get_right()) q.append(node.get_left()) return nodes def cut_tree(Z, n_clusters=None, height=None): """ Given a linkage matrix Z, return the cut tree. Parameters ---------- Z : scipy.cluster.linkage array The linkage matrix. n_clusters : array_like, optional Number of clusters in the tree at the cut point. height : array_like, optional The height at which to cut the tree. Only possible for ultrametric trees. Returns ------- cutree : array An array indicating group membership at each agglomeration step. I.e., for a full cut tree, in the first column each data point is in its own cluster. At the next step, two nodes are merged. Finally all singleton and non-singleton clusters are in one group. If `n_clusters` or `height` is given, the columns correspond to the columns of `n_clusters` or `height`. Examples -------- >>> from scipy import cluster >>> np.random.seed(23) >>> X = np.random.randn(50, 4) >>> Z = cluster.hierarchy.ward(X) >>> cutree = cluster.hierarchy.cut_tree(Z, n_clusters=[5, 10]) >>> cutree[:10] array([[0, 0], [1, 1], [2, 2], [3, 3], [3, 4], [2, 2], [0, 0], [1, 5], [3, 6], [4, 7]]) """ nobs = num_obs_linkage(Z) nodes = _order_cluster_tree(Z) if height is not None and n_clusters is not None: raise ValueError("At least one of either height or n_clusters " "must be None") elif height is None and n_clusters is None: # return the full cut tree cols_idx = np.arange(nobs) elif height is not None: heights = np.array([x.dist for x in nodes]) cols_idx = np.searchsorted(heights, height) else: cols_idx = nobs - np.searchsorted(np.arange(nobs), n_clusters) try: n_cols = len(cols_idx) except TypeError: # scalar n_cols = 1 cols_idx = np.array([cols_idx]) groups = np.zeros((n_cols, nobs), dtype=int) last_group = np.arange(nobs) if 0 in cols_idx: groups[0] = last_group for i, node in enumerate(nodes): idx = node.pre_order() this_group = last_group.copy() this_group[idx] = last_group[idx].min() this_group[this_group > last_group[idx].max()] -= 1 if i + 1 in cols_idx: groups[np.where(i + 1 == cols_idx)[0]] = this_group last_group = this_group return groups.T def to_tree(Z, rd=False): """ Converts a linkage matrix into an easy-to-use tree object. The reference to the root `ClusterNode` object is returned (by default). Each `ClusterNode` object has a ``left``, ``right``, ``dist``, ``id``, and ``count`` attribute. The left and right attributes point to ClusterNode objects that were combined to generate the cluster. If both are None then the `ClusterNode` object is a leaf node, its count must be 1, and its distance is meaningless but set to 0. *Note: This function is provided for the convenience of the library user. ClusterNodes are not used as input to any of the functions in this library.* Parameters ---------- Z : ndarray The linkage matrix in proper form (see the `linkage` function documentation). rd : bool, optional When False (default), a reference to the root `ClusterNode` object is returned. Otherwise, a tuple ``(r, d)`` is returned. ``r`` is a reference to the root node while ``d`` is a list of `ClusterNode` objects - one per original entry in the linkage matrix plus entries for all clustering steps. If a cluster id is less than the number of samples ``n`` in the data that the linkage matrix describes, then it corresponds to a singleton cluster (leaf node). See `linkage` for more information on the assignment of cluster ids to clusters. Returns ------- tree : ClusterNode or tuple (ClusterNode, list of ClusterNode) If ``rd`` is False, a `ClusterNode`. If ``rd`` is True, a list of length ``2*n - 1``, with ``n`` the number of samples. See the description of `rd` above for more details. See Also -------- linkage, is_valid_linkage, ClusterNode Examples -------- >>> from scipy.cluster import hierarchy >>> x = np.random.rand(10).reshape(5, 2) >>> Z = hierarchy.linkage(x) >>> hierarchy.to_tree(Z) <scipy.cluster.hierarchy.ClusterNode object at ... >>> rootnode, nodelist = hierarchy.to_tree(Z, rd=True) >>> rootnode <scipy.cluster.hierarchy.ClusterNode object at ... >>> len(nodelist) 9 """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') # Number of original objects is equal to the number of rows minus 1. n = Z.shape[0] + 1 # Create a list full of None's to store the node objects d = [None] * (n * 2 - 1) # Create the nodes corresponding to the n original objects. for i in xrange(0, n): d[i] = ClusterNode(i) nd = None for i in xrange(0, n - 1): fi = int(Z[i, 0]) fj = int(Z[i, 1]) if fi > i + n: raise ValueError(('Corrupt matrix Z. Index to derivative cluster ' 'is used before it is formed. See row %d, ' 'column 0') % fi) if fj > i + n: raise ValueError(('Corrupt matrix Z. Index to derivative cluster ' 'is used before it is formed. See row %d, ' 'column 1') % fj) nd = ClusterNode(i + n, d[fi], d[fj], Z[i, 2]) # ^ id ^ left ^ right ^ dist if Z[i, 3] != nd.count: raise ValueError(('Corrupt matrix Z. The count Z[%d,3] is ' 'incorrect.') % i) d[n + i] = nd if rd: return (nd, d) else: return nd def _convert_to_bool(X): if X.dtype != bool: X = X.astype(bool) if not X.flags.contiguous: X = X.copy() return X def _convert_to_double(X): if X.dtype != np.double: X = X.astype(np.double) if not X.flags.contiguous: X = X.copy() return X def cophenet(Z, Y=None): """ Calculates the cophenetic distances between each observation in the hierarchical clustering defined by the linkage ``Z``. Suppose ``p`` and ``q`` are original observations in disjoint clusters ``s`` and ``t``, respectively and ``s`` and ``t`` are joined by a direct parent cluster ``u``. The cophenetic distance between observations ``i`` and ``j`` is simply the distance between clusters ``s`` and ``t``. Parameters ---------- Z : ndarray The hierarchical clustering encoded as an array (see `linkage` function). Y : ndarray (optional) Calculates the cophenetic correlation coefficient ``c`` of a hierarchical clustering defined by the linkage matrix `Z` of a set of :math:`n` observations in :math:`m` dimensions. `Y` is the condensed distance matrix from which `Z` was generated. Returns ------- c : ndarray The cophentic correlation distance (if ``Y`` is passed). d : ndarray The cophenetic distance matrix in condensed form. The :math:`ij` th entry is the cophenetic distance between original observations :math:`i` and :math:`j`. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') Zs = Z.shape n = Zs[0] + 1 zz = np.zeros((n * (n-1)) // 2, dtype=np.double) # Since the C code does not support striding using strides. # The dimensions are used instead. Z = _convert_to_double(Z) _hierarchy.cophenetic_distances(Z, zz, int(n)) if Y is None: return zz Y = np.asarray(Y, order='c') distance.is_valid_y(Y, throw=True, name='Y') z = zz.mean() y = Y.mean() Yy = Y - y Zz = zz - z numerator = (Yy * Zz) denomA = Yy**2 denomB = Zz**2 c = numerator.sum() / np.sqrt((denomA.sum() * denomB.sum())) return (c, zz) def inconsistent(Z, d=2): r""" Calculates inconsistency statistics on a linkage matrix. Parameters ---------- Z : ndarray The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical clustering). See `linkage` documentation for more information on its form. d : int, optional The number of links up to `d` levels below each non-singleton cluster. Returns ------- R : ndarray A :math:`(n-1)` by 5 matrix where the ``i``'th row contains the link statistics for the non-singleton cluster ``i``. The link statistics are computed over the link heights for links :math:`d` levels below the cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard deviation of the link heights, respectively; ``R[i,2]`` is the number of links included in the calculation; and ``R[i,3]`` is the inconsistency coefficient, .. math:: \frac{\mathtt{Z[i,2]} - \mathtt{R[i,0]}} {R[i,1]} Notes ----- This function behaves similarly to the MATLAB(TM) ``inconsistent`` function. """ Z = np.asarray(Z, order='c') Zs = Z.shape is_valid_linkage(Z, throw=True, name='Z') if (not d == np.floor(d)) or d < 0: raise ValueError('The second argument d must be a nonnegative ' 'integer value.') # Since the C code does not support striding using strides. # The dimensions are used instead. [Z] = _copy_arrays_if_base_present([Z]) n = Zs[0] + 1 R = np.zeros((n - 1, 4), dtype=np.double) _hierarchy.inconsistent(Z, R, int(n), int(d)) return R def from_mlab_linkage(Z): """ Converts a linkage matrix generated by MATLAB(TM) to a new linkage matrix compatible with this module. The conversion does two things: * the indices are converted from ``1..N`` to ``0..(N-1)`` form, and * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the number of original observations (leaves) in the non-singleton cluster ``i``. This function is useful when loading in linkages from legacy data files generated by MATLAB. Parameters ---------- Z : ndarray A linkage matrix generated by MATLAB(TM). Returns ------- ZS : ndarray A linkage matrix compatible with ``scipy.cluster.hierarchy``. """ Z = np.asarray(Z, dtype=np.double, order='c') Zs = Z.shape # If it's empty, return it. if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0): return Z.copy() if len(Zs) != 2: raise ValueError("The linkage array must be rectangular.") # If it contains no rows, return it. if Zs[0] == 0: return Z.copy() Zpart = Z.copy() if Zpart[:, 0:2].min() != 1.0 and Zpart[:, 0:2].max() != 2 * Zs[0]: raise ValueError('The format of the indices is not 1..N') Zpart[:, 0:2] -= 1.0 CS = np.zeros((Zs[0],), dtype=np.double) _hierarchy.calculate_cluster_sizes(Zpart, CS, int(Zs[0]) + 1) return np.hstack([Zpart, CS.reshape(Zs[0], 1)]) def to_mlab_linkage(Z): """ Converts a linkage matrix to a MATLAB(TM) compatible one. Converts a linkage matrix ``Z`` generated by the linkage function of this module to a MATLAB(TM) compatible one. The return linkage matrix has the last column removed and the cluster indices are converted to ``1..N`` indexing. Parameters ---------- Z : ndarray A linkage matrix generated by ``scipy.cluster.hierarchy``. Returns ------- to_mlab_linkage : ndarray A linkage matrix compatible with MATLAB(TM)'s hierarchical clustering functions. The return linkage matrix has the last column removed and the cluster indices are converted to ``1..N`` indexing. """ Z = np.asarray(Z, order='c', dtype=np.double) Zs = Z.shape if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0): return Z.copy() is_valid_linkage(Z, throw=True, name='Z') ZP = Z[:, 0:3].copy() ZP[:, 0:2] += 1.0 return ZP def is_monotonic(Z): """ Returns True if the linkage passed is monotonic. The linkage is monotonic if for every cluster :math:`s` and :math:`t` joined, the distance between them is no less than the distance between any previously joined clusters. Parameters ---------- Z : ndarray The linkage matrix to check for monotonicity. Returns ------- b : bool A boolean indicating whether the linkage is monotonic. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') # We expect the i'th value to be greater than its successor. return (Z[1:, 2] >= Z[:-1, 2]).all() def is_valid_im(R, warning=False, throw=False, name=None): """Returns True if the inconsistency matrix passed is valid. It must be a :math:`n` by 4 array of doubles. The standard deviations ``R[:,1]`` must be nonnegative. The link counts ``R[:,2]`` must be positive and no greater than :math:`n-1`. Parameters ---------- R : ndarray The inconsistency matrix to check for validity. warning : bool, optional When True, issues a Python warning if the linkage matrix passed is invalid. throw : bool, optional When True, throws a Python exception if the linkage matrix passed is invalid. name : str, optional This string refers to the variable name of the invalid linkage matrix. Returns ------- b : bool True if the inconsistency matrix is valid. """ R = np.asarray(R, order='c') valid = True name_str = "%r " % name if name else '' try: if type(R) != np.ndarray: raise TypeError('Variable %spassed as inconsistency matrix is not ' 'a numpy array.' % name_str) if R.dtype != np.double: raise TypeError('Inconsistency matrix %smust contain doubles ' '(double).' % name_str) if len(R.shape) != 2: raise ValueError('Inconsistency matrix %smust have shape=2 (i.e. ' 'be two-dimensional).' % name_str) if R.shape[1] != 4: raise ValueError('Inconsistency matrix %smust have 4 columns.' % name_str) if R.shape[0] < 1: raise ValueError('Inconsistency matrix %smust have at least one ' 'row.' % name_str) if (R[:, 0] < 0).any(): raise ValueError('Inconsistency matrix %scontains negative link ' 'height means.' % name_str) if (R[:, 1] < 0).any(): raise ValueError('Inconsistency matrix %scontains negative link ' 'height standard deviations.' % name_str) if (R[:, 2] < 0).any(): raise ValueError('Inconsistency matrix %scontains negative link ' 'counts.' % name_str) except Exception as e: if throw: raise if warning: _warning(str(e)) valid = False return valid def is_valid_linkage(Z, warning=False, throw=False, name=None): """ Checks the validity of a linkage matrix. A linkage matrix is valid if it is a two dimensional array (type double) with :math:`n` rows and 4 columns. The first two columns must contain indices between 0 and :math:`2n-1`. For a given row ``i``, the following two expressions have to hold: .. math:: 0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1 0 \\leq Z[i,1] \\leq i+n-1 I.e. a cluster cannot join another cluster unless the cluster being joined has been generated. Parameters ---------- Z : array_like Linkage matrix. warning : bool, optional When True, issues a Python warning if the linkage matrix passed is invalid. throw : bool, optional When True, throws a Python exception if the linkage matrix passed is invalid. name : str, optional This string refers to the variable name of the invalid linkage matrix. Returns ------- b : bool True if the inconsistency matrix is valid. """ Z = np.asarray(Z, order='c') valid = True name_str = "%r " % name if name else '' try: if type(Z) != np.ndarray: raise TypeError('Passed linkage argument %sis not a valid array.' % name_str) if Z.dtype != np.double: raise TypeError('Linkage matrix %smust contain doubles.' % name_str) if len(Z.shape) != 2: raise ValueError('Linkage matrix %smust have shape=2 (i.e. be ' 'two-dimensional).' % name_str) if Z.shape[1] != 4: raise ValueError('Linkage matrix %smust have 4 columns.' % name_str) if Z.shape[0] == 0: raise ValueError('Linkage must be computed on at least two ' 'observations.') n = Z.shape[0] if n > 1: if ((Z[:, 0] < 0).any() or (Z[:, 1] < 0).any()): raise ValueError('Linkage %scontains negative indices.' % name_str) if (Z[:, 2] < 0).any(): raise ValueError('Linkage %scontains negative distances.' % name_str) if (Z[:, 3] < 0).any(): raise ValueError('Linkage %scontains negative counts.' % name_str) if _check_hierarchy_uses_cluster_before_formed(Z): raise ValueError('Linkage %suses non-singleton cluster before ' 'it is formed.' % name_str) if _check_hierarchy_uses_cluster_more_than_once(Z): raise ValueError('Linkage %suses the same cluster more than once.' % name_str) except Exception as e: if throw: raise if warning: _warning(str(e)) valid = False return valid def _check_hierarchy_uses_cluster_before_formed(Z): n = Z.shape[0] + 1 for i in xrange(0, n - 1): if Z[i, 0] >= n + i or Z[i, 1] >= n + i: return True return False def _check_hierarchy_uses_cluster_more_than_once(Z): n = Z.shape[0] + 1 chosen = set([]) for i in xrange(0, n - 1): if (Z[i, 0] in chosen) or (Z[i, 1] in chosen) or Z[i, 0] == Z[i, 1]: return True chosen.add(Z[i, 0]) chosen.add(Z[i, 1]) return False def _check_hierarchy_not_all_clusters_used(Z): n = Z.shape[0] + 1 chosen = set([]) for i in xrange(0, n - 1): chosen.add(int(Z[i, 0])) chosen.add(int(Z[i, 1])) must_chosen = set(range(0, 2 * n - 2)) return len(must_chosen.difference(chosen)) > 0 def num_obs_linkage(Z): """ Returns the number of original observations of the linkage matrix passed. Parameters ---------- Z : ndarray The linkage matrix on which to perform the operation. Returns ------- n : int The number of original observations in the linkage. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') return (Z.shape[0] + 1) def correspond(Z, Y): """ Checks for correspondence between linkage and condensed distance matrices They must have the same number of original observations for the check to succeed. This function is useful as a sanity check in algorithms that make extensive use of linkage and distance matrices that must correspond to the same set of original observations. Parameters ---------- Z : array_like The linkage matrix to check for correspondence. Y : array_like The condensed distance matrix to check for correspondence. Returns ------- b : bool A boolean indicating whether the linkage matrix and distance matrix could possibly correspond to one another. """ is_valid_linkage(Z, throw=True) distance.is_valid_y(Y, throw=True) Z = np.asarray(Z, order='c') Y = np.asarray(Y, order='c') return distance.num_obs_y(Y) == num_obs_linkage(Z) def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None): """ Forms flat clusters from the hierarchical clustering defined by the given linkage matrix. Parameters ---------- Z : ndarray The hierarchical clustering encoded with the matrix returned by the `linkage` function. t : float The threshold to apply when forming flat clusters. criterion : str, optional The criterion to use in forming flat clusters. This can be any of the following values: ``inconsistent`` : If a cluster node and all its descendants have an inconsistent value less than or equal to `t` then all its leaf descendants belong to the same flat cluster. When no non-singleton cluster meets this criterion, every node is assigned to its own cluster. (Default) ``distance`` : Forms flat clusters so that the original observations in each flat cluster have no greater a cophenetic distance than `t`. ``maxclust`` : Finds a minimum threshold ``r`` so that the cophenetic distance between any two original observations in the same flat cluster is no more than ``r`` and no more than `t` flat clusters are formed. ``monocrit`` : Forms a flat cluster from a cluster node c with index i when ``monocrit[j] <= t``. For example, to threshold on the maximum mean distance as computed in the inconsistency matrix R with a threshold of 0.8 do:: MR = maxRstat(Z, R, 3) cluster(Z, t=0.8, criterion='monocrit', monocrit=MR) ``maxclust_monocrit`` : Forms a flat cluster from a non-singleton cluster node ``c`` when ``monocrit[i] <= r`` for all cluster indices ``i`` below and including ``c``. ``r`` is minimized such that no more than ``t`` flat clusters are formed. monocrit must be monotonic. For example, to minimize the threshold t on maximum inconsistency values so that no more than 3 flat clusters are formed, do:: MI = maxinconsts(Z, R) cluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI) depth : int, optional The maximum depth to perform the inconsistency calculation. It has no meaning for the other criteria. Default is 2. R : ndarray, optional The inconsistency matrix to use for the 'inconsistent' criterion. This matrix is computed if not provided. monocrit : ndarray, optional An array of length n-1. `monocrit[i]` is the statistics upon which non-singleton i is thresholded. The monocrit vector must be monotonic, i.e. given a node c with index i, for all node indices j corresponding to nodes below c, ``monocrit[i] >= monocrit[j]``. Returns ------- fcluster : ndarray An array of length ``n``. ``T[i]`` is the flat cluster number to which original observation ``i`` belongs. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') n = Z.shape[0] + 1 T = np.zeros((n,), dtype='i') # Since the C code does not support striding using strides. # The dimensions are used instead. [Z] = _copy_arrays_if_base_present([Z]) if criterion == 'inconsistent': if R is None: R = inconsistent(Z, depth) else: R = np.asarray(R, order='c') is_valid_im(R, throw=True, name='R') # Since the C code does not support striding using strides. # The dimensions are used instead. [R] = _copy_arrays_if_base_present([R]) _hierarchy.cluster_in(Z, R, T, float(t), int(n)) elif criterion == 'distance': _hierarchy.cluster_dist(Z, T, float(t), int(n)) elif criterion == 'maxclust': _hierarchy.cluster_maxclust_dist(Z, T, int(n), int(t)) elif criterion == 'monocrit': [monocrit] = _copy_arrays_if_base_present([monocrit]) _hierarchy.cluster_monocrit(Z, monocrit, T, float(t), int(n)) elif criterion == 'maxclust_monocrit': [monocrit] = _copy_arrays_if_base_present([monocrit]) _hierarchy.cluster_maxclust_monocrit(Z, monocrit, T, int(n), int(t)) else: raise ValueError('Invalid cluster formation criterion: %s' % str(criterion)) return T def fclusterdata(X, t, criterion='inconsistent', metric='euclidean', depth=2, method='single', R=None): """ Cluster observation data using a given metric. Clusters the original observations in the n-by-m data matrix X (n observations in m dimensions), using the euclidean distance metric to calculate distances between original observations, performs hierarchical clustering using the single linkage algorithm, and forms flat clusters using the inconsistency method with `t` as the cut-off threshold. A one-dimensional array ``T`` of length ``n`` is returned. ``T[i]`` is the index of the flat cluster to which the original observation ``i`` belongs. Parameters ---------- X : (N, M) ndarray N by M data matrix with N observations in M dimensions. t : float The threshold to apply when forming flat clusters. criterion : str, optional Specifies the criterion for forming flat clusters. Valid values are 'inconsistent' (default), 'distance', or 'maxclust' cluster formation algorithms. See `fcluster` for descriptions. metric : str, optional The distance metric for calculating pairwise distances. See ``distance.pdist`` for descriptions and linkage to verify compatibility with the linkage method. depth : int, optional The maximum depth for the inconsistency calculation. See `inconsistent` for more information. method : str, optional The linkage method to use (single, complete, average, weighted, median centroid, ward). See `linkage` for more information. Default is "single". R : ndarray, optional The inconsistency matrix. It will be computed if necessary if it is not passed. Returns ------- fclusterdata : ndarray A vector of length n. T[i] is the flat cluster number to which original observation i belongs. See Also -------- scipy.spatial.distance.pdist : pairwise distance metrics Notes ----- This function is similar to the MATLAB function ``clusterdata``. """ X = np.asarray(X, order='c', dtype=np.double) if type(X) != np.ndarray or len(X.shape) != 2: raise TypeError('The observation matrix X must be an n by m numpy ' 'array.') Y = distance.pdist(X, metric=metric) Z = linkage(Y, method=method) if R is None: R = inconsistent(Z, d=depth) else: R = np.asarray(R, order='c') T = fcluster(Z, criterion=criterion, depth=depth, R=R, t=t) return T def leaves_list(Z): """ Returns a list of leaf node ids The return corresponds to the observation vector index as it appears in the tree from left to right. Z is a linkage matrix. Parameters ---------- Z : ndarray The hierarchical clustering encoded as a matrix. `Z` is a linkage matrix. See `linkage` for more information. Returns ------- leaves_list : ndarray The list of leaf node ids. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') n = Z.shape[0] + 1 ML = np.zeros((n,), dtype='i') [Z] = _copy_arrays_if_base_present([Z]) _hierarchy.prelist(Z, ML, int(n)) return ML # Maps number of leaves to text size. # # p <= 20, size="12" # 20 < p <= 30, size="10" # 30 < p <= 50, size="8" # 50 < p <= np.inf, size="6" _dtextsizes = {20: 12, 30: 10, 50: 8, 85: 6, np.inf: 5} _drotation = {20: 0, 40: 45, np.inf: 90} _dtextsortedkeys = list(_dtextsizes.keys()) _dtextsortedkeys.sort() _drotationsortedkeys = list(_drotation.keys()) _drotationsortedkeys.sort() def _remove_dups(L): """ Removes duplicates AND preserves the original order of the elements. The set class is not guaranteed to do this. """ seen_before = set([]) L2 = [] for i in L: if i not in seen_before: seen_before.add(i) L2.append(i) return L2 def _get_tick_text_size(p): for k in _dtextsortedkeys: if p <= k: return _dtextsizes[k] def _get_tick_rotation(p): for k in _drotationsortedkeys: if p <= k: return _drotation[k] def _plot_dendrogram(icoords, dcoords, ivl, p, n, mh, orientation, no_labels, color_list, leaf_font_size=None, leaf_rotation=None, contraction_marks=None, ax=None, above_threshold_color='b'): # Import matplotlib here so that it's not imported unless dendrograms # are plotted. Raise an informative error if importing fails. try: # if an axis is provided, don't use pylab at all if ax is None: import matplotlib.pylab import matplotlib.patches import matplotlib.collections except ImportError: raise ImportError("You must install the matplotlib library to plot " "the dendrogram. Use no_plot=True to calculate the " "dendrogram without plotting.") if ax is None: ax = matplotlib.pylab.gca() # if we're using pylab, we want to trigger a draw at the end trigger_redraw = True else: trigger_redraw = False # Independent variable plot width ivw = len(ivl) * 10 # Dependent variable plot height dvw = mh + mh * 0.05 iv_ticks = np.arange(5, len(ivl) * 10 + 5, 10) if orientation in ('top', 'bottom'): if orientation == 'top': ax.set_ylim([0, dvw]) ax.set_xlim([0, ivw]) else: ax.set_ylim([dvw, 0]) ax.set_xlim([0, ivw]) xlines = icoords ylines = dcoords if no_labels: ax.set_xticks([]) ax.set_xticklabels([]) else: ax.set_xticks(iv_ticks) if orientation == 'top': ax.xaxis.set_ticks_position('bottom') else: ax.xaxis.set_ticks_position('top') # Make the tick marks invisible because they cover up the links for line in ax.get_xticklines(): line.set_visible(False) leaf_rot = float(_get_tick_rotation(len(ivl))) if ( leaf_rotation is None) else leaf_rotation leaf_font = float(_get_tick_text_size(len(ivl))) if ( leaf_font_size is None) else leaf_font_size ax.set_xticklabels(ivl, rotation=leaf_rot, size=leaf_font) elif orientation in ('left', 'right'): if orientation == 'left': ax.set_xlim([dvw, 0]) ax.set_ylim([0, ivw]) else: ax.set_xlim([0, dvw]) ax.set_ylim([0, ivw]) xlines = dcoords ylines = icoords if no_labels: ax.set_yticks([]) ax.set_yticklabels([]) else: ax.set_yticks(iv_ticks) if orientation == 'left': ax.yaxis.set_ticks_position('right') else: ax.yaxis.set_ticks_position('left') # Make the tick marks invisible because they cover up the links for line in ax.get_yticklines(): line.set_visible(False) leaf_font = float(_get_tick_text_size(len(ivl))) if ( leaf_font_size is None) else leaf_font_size if leaf_rotation is not None: ax.set_yticklabels(ivl, rotation=leaf_rotation, size=leaf_font) else: ax.set_yticklabels(ivl, size=leaf_font) # Let's use collections instead. This way there is a separate legend item # for each tree grouping, rather than stupidly one for each line segment. colors_used = _remove_dups(color_list) color_to_lines = {} for color in colors_used: color_to_lines[color] = [] for (xline, yline, color) in zip(xlines, ylines, color_list): color_to_lines[color].append(list(zip(xline, yline))) colors_to_collections = {} # Construct the collections. for color in colors_used: coll = matplotlib.collections.LineCollection(color_to_lines[color], colors=(color,)) colors_to_collections[color] = coll # Add all the groupings below the color threshold. for color in colors_used: if color != above_threshold_color: ax.add_collection(colors_to_collections[color]) # If there's a grouping of links above the color threshold, it goes last. if above_threshold_color in colors_to_collections: ax.add_collection(colors_to_collections[above_threshold_color]) if contraction_marks is not None: Ellipse = matplotlib.patches.Ellipse for (x, y) in contraction_marks: if orientation in ('left', 'right'): e = Ellipse((y, x), width=dvw / 100, height=1.0) else: e = Ellipse((x, y), width=1.0, height=dvw / 100) ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(0.5) e.set_facecolor('k') if trigger_redraw: matplotlib.pylab.draw_if_interactive() _link_line_colors = ['g', 'r', 'c', 'm', 'y', 'k'] def set_link_color_palette(palette): """ Set list of matplotlib color codes for use by dendrogram. Note that this palette is global (i.e. setting it once changes the colors for all subsequent calls to `dendrogram`) and that it affects only the the colors below ``color_threshold``. Note that `dendrogram` also accepts a custom coloring function through its ``link_color_func`` keyword, which is more flexible and non-global. Parameters ---------- palette : list of str or None A list of matplotlib color codes. The order of the color codes is the order in which the colors are cycled through when color thresholding in the dendrogram. If ``None``, resets the palette to its default (which is ``['g', 'r', 'c', 'm', 'y', 'k']``). Returns ------- None See Also -------- dendrogram Notes ----- Ability to reset the palette with ``None`` added in Scipy 0.17.0. Examples -------- >>> from scipy.cluster import hierarchy >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268., 400., ... 754., 564., 138., 219., 869., 669.]) >>> Z = hierarchy.linkage(ytdist, 'single') >>> dn = hierarchy.dendrogram(Z, no_plot=True) >>> dn['color_list'] ['g', 'b', 'b', 'b', 'b'] >>> hierarchy.set_link_color_palette(['c', 'm', 'y', 'k']) >>> dn = hierarchy.dendrogram(Z, no_plot=True) >>> dn['color_list'] ['c', 'b', 'b', 'b', 'b'] >>> dn = hierarchy.dendrogram(Z, no_plot=True, color_threshold=267, ... above_threshold_color='k') >>> dn['color_list'] ['c', 'm', 'm', 'k', 'k'] Now reset the color palette to its default: >>> hierarchy.set_link_color_palette(None) """ if palette is None: # reset to its default palette = ['g', 'r', 'c', 'm', 'y', 'k'] elif type(palette) not in (list, tuple): raise TypeError("palette must be a list or tuple") _ptypes = [isinstance(p, string_types) for p in palette] if False in _ptypes: raise TypeError("all palette list elements must be color strings") for i in list(_link_line_colors): _link_line_colors.remove(i) _link_line_colors.extend(list(palette)) def dendrogram(Z, p=30, truncate_mode=None, color_threshold=None, get_leaves=True, orientation='top', labels=None, count_sort=False, distance_sort=False, show_leaf_counts=True, no_plot=False, no_labels=False, leaf_font_size=None, leaf_rotation=None, leaf_label_func=None, show_contracted=False, link_color_func=None, ax=None, above_threshold_color='b'): """ Plots the hierarchical clustering as a dendrogram. The dendrogram illustrates how each cluster is composed by drawing a U-shaped link between a non-singleton cluster and its children. The height of the top of the U-link is the distance between its children clusters. It is also the cophenetic distance between original observations in the two children clusters. It is expected that the distances in Z[:,2] be monotonic, otherwise crossings appear in the dendrogram. Parameters ---------- Z : ndarray The linkage matrix encoding the hierarchical clustering to render as a dendrogram. See the ``linkage`` function for more information on the format of ``Z``. p : int, optional The ``p`` parameter for ``truncate_mode``. truncate_mode : str, optional The dendrogram can be hard to read when the original observation matrix from which the linkage is derived is large. Truncation is used to condense the dendrogram. There are several modes: ``None/'none'`` No truncation is performed (Default). ``'lastp'`` The last ``p`` non-singleton formed in the linkage are the only non-leaf nodes in the linkage; they correspond to rows ``Z[n-p-2:end]`` in ``Z``. All other non-singleton clusters are contracted into leaf nodes. ``'mlab'`` This corresponds to MATLAB(TM) behavior. (not implemented yet) ``'level'/'mtica'`` No more than ``p`` levels of the dendrogram tree are displayed. This corresponds to Mathematica(TM) behavior. color_threshold : double, optional For brevity, let :math:`t` be the ``color_threshold``. Colors all the descendent links below a cluster node :math:`k` the same color if :math:`k` is the first node below the cut threshold :math:`t`. All links connecting nodes with distances greater than or equal to the threshold are colored blue. If :math:`t` is less than or equal to zero, all nodes are colored blue. If ``color_threshold`` is None or 'default', corresponding with MATLAB(TM) behavior, the threshold is set to ``0.7*max(Z[:,2])``. get_leaves : bool, optional Includes a list ``R['leaves']=H`` in the result dictionary. For each :math:`i`, ``H[i] == j``, cluster node ``j`` appears in position ``i`` in the left-to-right traversal of the leaves, where :math:`j < 2n-1` and :math:`i < n`. orientation : str, optional The direction to plot the dendrogram, which can be any of the following strings: ``'top'`` Plots the root at the top, and plot descendent links going downwards. (default). ``'bottom'`` Plots the root at the bottom, and plot descendent links going upwards. ``'left'`` Plots the root at the left, and plot descendent links going right. ``'right'`` Plots the root at the right, and plot descendent links going left. labels : ndarray, optional By default ``labels`` is None so the index of the original observation is used to label the leaf nodes. Otherwise, this is an :math:`n` -sized list (or tuple). The ``labels[i]`` value is the text to put under the :math:`i` th leaf node only if it corresponds to an original observation and not a non-singleton cluster. count_sort : str or bool, optional For each node n, the order (visually, from left-to-right) n's two descendent links are plotted is determined by this parameter, which can be any of the following values: ``False`` Nothing is done. ``'ascending'`` or ``True`` The child with the minimum number of original objects in its cluster is plotted first. ``'descendent'`` The child with the maximum number of original objects in its cluster is plotted first. Note ``distance_sort`` and ``count_sort`` cannot both be True. distance_sort : str or bool, optional For each node n, the order (visually, from left-to-right) n's two descendent links are plotted is determined by this parameter, which can be any of the following values: ``False`` Nothing is done. ``'ascending'`` or ``True`` The child with the minimum distance between its direct descendents is plotted first. ``'descending'`` The child with the maximum distance between its direct descendents is plotted first. Note ``distance_sort`` and ``count_sort`` cannot both be True. show_leaf_counts : bool, optional When True, leaf nodes representing :math:`k>1` original observation are labeled with the number of observations they contain in parentheses. no_plot : bool, optional When True, the final rendering is not performed. This is useful if only the data structures computed for the rendering are needed or if matplotlib is not available. no_labels : bool, optional When True, no labels appear next to the leaf nodes in the rendering of the dendrogram. leaf_rotation : double, optional Specifies the angle (in degrees) to rotate the leaf labels. When unspecified, the rotation is based on the number of nodes in the dendrogram (default is 0). leaf_font_size : int, optional Specifies the font size (in points) of the leaf labels. When unspecified, the size based on the number of nodes in the dendrogram. leaf_label_func : lambda or function, optional When leaf_label_func is a callable function, for each leaf with cluster index :math:`k < 2n-1`. The function is expected to return a string with the label for the leaf. Indices :math:`k < n` correspond to original observations while indices :math:`k \\geq n` correspond to non-singleton clusters. For example, to label singletons with their node id and non-singletons with their id, count, and inconsistency coefficient, simply do:: # First define the leaf label function. def llf(id): if id < n: return str(id) else: return '[%d %d %1.2f]' % (id, count, R[n-id,3]) # The text for the leaf nodes is going to be big so force # a rotation of 90 degrees. dendrogram(Z, leaf_label_func=llf, leaf_rotation=90) show_contracted : bool, optional When True the heights of non-singleton nodes contracted into a leaf node are plotted as crosses along the link connecting that leaf node. This really is only useful when truncation is used (see ``truncate_mode`` parameter). link_color_func : callable, optional If given, `link_color_function` is called with each non-singleton id corresponding to each U-shaped link it will paint. The function is expected to return the color to paint the link, encoded as a matplotlib color string code. For example:: dendrogram(Z, link_color_func=lambda k: colors[k]) colors the direct links below each untruncated non-singleton node ``k`` using ``colors[k]``. ax : matplotlib Axes instance, optional If None and `no_plot` is not True, the dendrogram will be plotted on the current axes. Otherwise if `no_plot` is not True the dendrogram will be plotted on the given ``Axes`` instance. This can be useful if the dendrogram is part of a more complex figure. above_threshold_color : str, optional This matplotlib color string sets the color of the links above the color_threshold. The default is 'b'. Returns ------- R : dict A dictionary of data structures computed to render the dendrogram. Its has the following keys: ``'color_list'`` A list of color names. The k'th element represents the color of the k'th link. ``'icoord'`` and ``'dcoord'`` Each of them is a list of lists. Let ``icoord = [I1, I2, ..., Ip]`` where ``Ik = [xk1, xk2, xk3, xk4]`` and ``dcoord = [D1, D2, ..., Dp]`` where ``Dk = [yk1, yk2, yk3, yk4]``, then the k'th link painted is ``(xk1, yk1)`` - ``(xk2, yk2)`` - ``(xk3, yk3)`` - ``(xk4, yk4)``. ``'ivl'`` A list of labels corresponding to the leaf nodes. ``'leaves'`` For each i, ``H[i] == j``, cluster node ``j`` appears in position ``i`` in the left-to-right traversal of the leaves, where :math:`j < 2n-1` and :math:`i < n`. If ``j`` is less than ``n``, the ``i``-th leaf node corresponds to an original observation. Otherwise, it corresponds to a non-singleton cluster. See Also -------- linkage, set_link_color_palette Examples -------- >>> from scipy.cluster import hierarchy >>> import matplotlib.pyplot as plt A very basic example: >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268., ... 400., 754., 564., 138., 219., 869., 669.]) >>> Z = hierarchy.linkage(ytdist, 'single') >>> plt.figure() >>> dn = hierarchy.dendrogram(Z) Now plot in given axes, improve the color scheme and use both vertical and horizontal orientations: >>> hierarchy.set_link_color_palette(['m', 'c', 'y', 'k']) >>> fig, axes = plt.subplots(1, 2, figsize=(8, 3)) >>> dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y', ... orientation='top') >>> dn2 = hierarchy.dendrogram(Z, ax=axes[1], above_threshold_color='#bcbddc', ... orientation='right') >>> hierarchy.set_link_color_palette(None) # reset to default after use >>> plt.show() """ # This feature was thought about but never implemented (still useful?): # # ... = dendrogram(..., leaves_order=None) # # Plots the leaves in the order specified by a vector of # original observation indices. If the vector contains duplicates # or results in a crossing, an exception will be thrown. Passing # None orders leaf nodes based on the order they appear in the # pre-order traversal. Z = np.asarray(Z, order='c') if orientation not in ["top", "left", "bottom", "right"]: raise ValueError("orientation must be one of 'top', 'left', " "'bottom', or 'right'") is_valid_linkage(Z, throw=True, name='Z') Zs = Z.shape n = Zs[0] + 1 if type(p) in (int, float): p = int(p) else: raise TypeError('The second argument must be a number') if truncate_mode not in ('lastp', 'mlab', 'mtica', 'level', 'none', None): raise ValueError('Invalid truncation mode.') if truncate_mode == 'lastp' or truncate_mode == 'mlab': if p > n or p == 0: p = n if truncate_mode == 'mtica' or truncate_mode == 'level': if p <= 0: p = np.inf if get_leaves: lvs = [] else: lvs = None icoord_list = [] dcoord_list = [] color_list = [] current_color = [0] currently_below_threshold = [False] ivl = [] # list of leaves if color_threshold is None or (isinstance(color_threshold, string_types) and color_threshold == 'default'): color_threshold = max(Z[:, 2]) * 0.7 R = {'icoord': icoord_list, 'dcoord': dcoord_list, 'ivl': ivl, 'leaves': lvs, 'color_list': color_list} # Empty list will be filled in _dendrogram_calculate_info contraction_marks = [] if show_contracted else None _dendrogram_calculate_info( Z=Z, p=p, truncate_mode=truncate_mode, color_threshold=color_threshold, get_leaves=get_leaves, orientation=orientation, labels=labels, count_sort=count_sort, distance_sort=distance_sort, show_leaf_counts=show_leaf_counts, i=2*n - 2, iv=0.0, ivl=ivl, n=n, icoord_list=icoord_list, dcoord_list=dcoord_list, lvs=lvs, current_color=current_color, color_list=color_list, currently_below_threshold=currently_below_threshold, leaf_label_func=leaf_label_func, contraction_marks=contraction_marks, link_color_func=link_color_func, above_threshold_color=above_threshold_color) if not no_plot: mh = max(Z[:, 2]) _plot_dendrogram(icoord_list, dcoord_list, ivl, p, n, mh, orientation, no_labels, color_list, leaf_font_size=leaf_font_size, leaf_rotation=leaf_rotation, contraction_marks=contraction_marks, ax=ax, above_threshold_color=above_threshold_color) return R def _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, i, labels): # If the leaf id structure is not None and is a list then the caller # to dendrogram has indicated that cluster id's corresponding to the # leaf nodes should be recorded. if lvs is not None: lvs.append(int(i)) # If leaf node labels are to be displayed... if ivl is not None: # If a leaf_label_func has been provided, the label comes from the # string returned from the leaf_label_func, which is a function # passed to dendrogram. if leaf_label_func: ivl.append(leaf_label_func(int(i))) else: # Otherwise, if the dendrogram caller has passed a labels list # for the leaf nodes, use it. if labels is not None: ivl.append(labels[int(i - n)]) else: # Otherwise, use the id as the label for the leaf.x ivl.append(str(int(i))) def _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, i, labels, show_leaf_counts): # If the leaf id structure is not None and is a list then the caller # to dendrogram has indicated that cluster id's corresponding to the # leaf nodes should be recorded. if lvs is not None: lvs.append(int(i)) if ivl is not None: if leaf_label_func: ivl.append(leaf_label_func(int(i))) else: if show_leaf_counts: ivl.append("(" + str(int(Z[i - n, 3])) + ")") else: ivl.append("") def _append_contraction_marks(Z, iv, i, n, contraction_marks): _append_contraction_marks_sub(Z, iv, int(Z[i - n, 0]), n, contraction_marks) _append_contraction_marks_sub(Z, iv, int(Z[i - n, 1]), n, contraction_marks) def _append_contraction_marks_sub(Z, iv, i, n, contraction_marks): if i >= n: contraction_marks.append((iv, Z[i - n, 2])) _append_contraction_marks_sub(Z, iv, int(Z[i - n, 0]), n, contraction_marks) _append_contraction_marks_sub(Z, iv, int(Z[i - n, 1]), n, contraction_marks) def _dendrogram_calculate_info(Z, p, truncate_mode, color_threshold=np.inf, get_leaves=True, orientation='top', labels=None, count_sort=False, distance_sort=False, show_leaf_counts=False, i=-1, iv=0.0, ivl=[], n=0, icoord_list=[], dcoord_list=[], lvs=None, mhr=False, current_color=[], color_list=[], currently_below_threshold=[], leaf_label_func=None, level=0, contraction_marks=None, link_color_func=None, above_threshold_color='b'): """ Calculates the endpoints of the links as well as the labels for the the dendrogram rooted at the node with index i. iv is the independent variable value to plot the left-most leaf node below the root node i (if orientation='top', this would be the left-most x value where the plotting of this root node i and its descendents should begin). ivl is a list to store the labels of the leaf nodes. The leaf_label_func is called whenever ivl != None, labels == None, and leaf_label_func != None. When ivl != None and labels != None, the labels list is used only for labeling the leaf nodes. When ivl == None, no labels are generated for leaf nodes. When get_leaves==True, a list of leaves is built as they are visited in the dendrogram. Returns a tuple with l being the independent variable coordinate that corresponds to the midpoint of cluster to the left of cluster i if i is non-singleton, otherwise the independent coordinate of the leaf node if i is a leaf node. Returns ------- A tuple (left, w, h, md), where: * left is the independent variable coordinate of the center of the the U of the subtree * w is the amount of space used for the subtree (in independent variable units) * h is the height of the subtree in dependent variable units * md is the ``max(Z[*,2]``) for all nodes ``*`` below and including the target node. """ if n == 0: raise ValueError("Invalid singleton cluster count n.") if i == -1: raise ValueError("Invalid root cluster index i.") if truncate_mode == 'lastp': # If the node is a leaf node but corresponds to a non-single cluster, # its label is either the empty string or the number of original # observations belonging to cluster i. if 2 * n - p > i >= n: d = Z[i - n, 2] _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, i, labels, show_leaf_counts) if contraction_marks is not None: _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks) return (iv + 5.0, 10.0, 0.0, d) elif i < n: _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, i, labels) return (iv + 5.0, 10.0, 0.0, 0.0) elif truncate_mode in ('mtica', 'level'): if i > n and level > p: d = Z[i - n, 2] _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, i, labels, show_leaf_counts) if contraction_marks is not None: _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks) return (iv + 5.0, 10.0, 0.0, d) elif i < n: _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, i, labels) return (iv + 5.0, 10.0, 0.0, 0.0) elif truncate_mode in ('mlab',): pass # Otherwise, only truncate if we have a leaf node. # # If the truncate_mode is mlab, the linkage has been modified # with the truncated tree. # # Only place leaves if they correspond to original observations. if i < n: _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, i, labels) return (iv + 5.0, 10.0, 0.0, 0.0) # !!! Otherwise, we don't have a leaf node, so work on plotting a # non-leaf node. # Actual indices of a and b aa = int(Z[i - n, 0]) ab = int(Z[i - n, 1]) if aa > n: # The number of singletons below cluster a na = Z[aa - n, 3] # The distance between a's two direct children. da = Z[aa - n, 2] else: na = 1 da = 0.0 if ab > n: nb = Z[ab - n, 3] db = Z[ab - n, 2] else: nb = 1 db = 0.0 if count_sort == 'ascending' or count_sort == True: # If a has a count greater than b, it and its descendents should # be drawn to the right. Otherwise, to the left. if na > nb: # The cluster index to draw to the left (ua) will be ab # and the one to draw to the right (ub) will be aa ua = ab ub = aa else: ua = aa ub = ab elif count_sort == 'descending': # If a has a count less than or equal to b, it and its # descendents should be drawn to the left. Otherwise, to # the right. if na > nb: ua = aa ub = ab else: ua = ab ub = aa elif distance_sort == 'ascending' or distance_sort == True: # If a has a distance greater than b, it and its descendents should # be drawn to the right. Otherwise, to the left. if da > db: ua = ab ub = aa else: ua = aa ub = ab elif distance_sort == 'descending': # If a has a distance less than or equal to b, it and its # descendents should be drawn to the left. Otherwise, to # the right. if da > db: ua = aa ub = ab else: ua = ab ub = aa else: ua = aa ub = ab # Updated iv variable and the amount of space used. (uiva, uwa, uah, uamd) = \ _dendrogram_calculate_info( Z=Z, p=p, truncate_mode=truncate_mode, color_threshold=color_threshold, get_leaves=get_leaves, orientation=orientation, labels=labels, count_sort=count_sort, distance_sort=distance_sort, show_leaf_counts=show_leaf_counts, i=ua, iv=iv, ivl=ivl, n=n, icoord_list=icoord_list, dcoord_list=dcoord_list, lvs=lvs, current_color=current_color, color_list=color_list, currently_below_threshold=currently_below_threshold, leaf_label_func=leaf_label_func, level=level + 1, contraction_marks=contraction_marks, link_color_func=link_color_func, above_threshold_color=above_threshold_color) h = Z[i - n, 2] if h >= color_threshold or color_threshold <= 0: c = above_threshold_color if currently_below_threshold[0]: current_color[0] = (current_color[0] + 1) % len(_link_line_colors) currently_below_threshold[0] = False else: currently_below_threshold[0] = True c = _link_line_colors[current_color[0]] (uivb, uwb, ubh, ubmd) = \ _dendrogram_calculate_info( Z=Z, p=p, truncate_mode=truncate_mode, color_threshold=color_threshold, get_leaves=get_leaves, orientation=orientation, labels=labels, count_sort=count_sort, distance_sort=distance_sort, show_leaf_counts=show_leaf_counts, i=ub, iv=iv + uwa, ivl=ivl, n=n, icoord_list=icoord_list, dcoord_list=dcoord_list, lvs=lvs, current_color=current_color, color_list=color_list, currently_below_threshold=currently_below_threshold, leaf_label_func=leaf_label_func, level=level + 1, contraction_marks=contraction_marks, link_color_func=link_color_func, above_threshold_color=above_threshold_color) max_dist = max(uamd, ubmd, h) icoord_list.append([uiva, uiva, uivb, uivb]) dcoord_list.append([uah, h, h, ubh]) if link_color_func is not None: v = link_color_func(int(i)) if not isinstance(v, string_types): raise TypeError("link_color_func must return a matplotlib " "color string!") color_list.append(v) else: color_list.append(c) return (((uiva + uivb) / 2), uwa + uwb, h, max_dist) def is_isomorphic(T1, T2): """ Determines if two different cluster assignments are equivalent. Parameters ---------- T1 : array_like An assignment of singleton cluster ids to flat cluster ids. T2 : array_like An assignment of singleton cluster ids to flat cluster ids. Returns ------- b : bool Whether the flat cluster assignments `T1` and `T2` are equivalent. """ T1 = np.asarray(T1, order='c') T2 = np.asarray(T2, order='c') if type(T1) != np.ndarray: raise TypeError('T1 must be a numpy array.') if type(T2) != np.ndarray: raise TypeError('T2 must be a numpy array.') T1S = T1.shape T2S = T2.shape if len(T1S) != 1: raise ValueError('T1 must be one-dimensional.') if len(T2S) != 1: raise ValueError('T2 must be one-dimensional.') if T1S[0] != T2S[0]: raise ValueError('T1 and T2 must have the same number of elements.') n = T1S[0] d = {} for i in xrange(0, n): if T1[i] in d: if d[T1[i]] != T2[i]: return False else: d[T1[i]] = T2[i] return True def maxdists(Z): """ Returns the maximum distance between any non-singleton cluster. Parameters ---------- Z : ndarray The hierarchical clustering encoded as a matrix. See ``linkage`` for more information. Returns ------- maxdists : ndarray A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents the maximum distance between any cluster (including singletons) below and including the node with index i. More specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the set of all node indices below and including node i. """ Z = np.asarray(Z, order='c', dtype=np.double) is_valid_linkage(Z, throw=True, name='Z') n = Z.shape[0] + 1 MD = np.zeros((n - 1,)) [Z] = _copy_arrays_if_base_present([Z]) _hierarchy.get_max_dist_for_each_cluster(Z, MD, int(n)) return MD def maxinconsts(Z, R): """ Returns the maximum inconsistency coefficient for each non-singleton cluster and its descendents. Parameters ---------- Z : ndarray The hierarchical clustering encoded as a matrix. See `linkage` for more information. R : ndarray The inconsistency matrix. Returns ------- MI : ndarray A monotonic ``(n-1)``-sized numpy array of doubles. """ Z = np.asarray(Z, order='c') R = np.asarray(R, order='c') is_valid_linkage(Z, throw=True, name='Z') is_valid_im(R, throw=True, name='R') n = Z.shape[0] + 1 if Z.shape[0] != R.shape[0]: raise ValueError("The inconsistency matrix and linkage matrix each " "have a different number of rows.") MI = np.zeros((n - 1,)) [Z, R] = _copy_arrays_if_base_present([Z, R]) _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, int(n), 3) return MI def maxRstat(Z, R, i): """ Returns the maximum statistic for each non-singleton cluster and its descendents. Parameters ---------- Z : array_like The hierarchical clustering encoded as a matrix. See `linkage` for more information. R : array_like The inconsistency matrix. i : int The column of `R` to use as the statistic. Returns ------- MR : ndarray Calculates the maximum statistic for the i'th column of the inconsistency matrix `R` for each non-singleton cluster node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]`` where ``Q(j)`` the set of all node ids corresponding to nodes below and including ``j``. """ Z = np.asarray(Z, order='c') R = np.asarray(R, order='c') is_valid_linkage(Z, throw=True, name='Z') is_valid_im(R, throw=True, name='R') if type(i) is not int: raise TypeError('The third argument must be an integer.') if i < 0 or i > 3: raise ValueError('i must be an integer between 0 and 3 inclusive.') if Z.shape[0] != R.shape[0]: raise ValueError("The inconsistency matrix and linkage matrix each " "have a different number of rows.") n = Z.shape[0] + 1 MR = np.zeros((n - 1,)) [Z, R] = _copy_arrays_if_base_present([Z, R]) _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MR, int(n), i) return MR def leaders(Z, T): """ Returns the root nodes in a hierarchical clustering. Returns the root nodes in a hierarchical clustering corresponding to a cut defined by a flat cluster assignment vector ``T``. See the ``fcluster`` function for more information on the format of ``T``. For each flat cluster :math:`j` of the :math:`k` flat clusters represented in the n-sized flat cluster assignment vector ``T``, this function finds the lowest cluster node :math:`i` in the linkage tree Z such that: * leaf descendents belong only to flat cluster j (i.e. ``T[p]==j`` for all :math:`p` in :math:`S(i)` where :math:`S(i)` is the set of leaf ids of leaf nodes descendent with cluster node :math:`i`) * there does not exist a leaf that is not descendent with :math:`i` that also belongs to cluster :math:`j` (i.e. ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`). If this condition is violated, ``T`` is not a valid cluster assignment vector, and an exception will be thrown. Parameters ---------- Z : ndarray The hierarchical clustering encoded as a matrix. See `linkage` for more information. T : ndarray The flat cluster assignment vector. Returns ------- L : ndarray The leader linkage node id's stored as a k-element 1-D array where ``k`` is the number of flat clusters found in ``T``. ``L[j]=i`` is the linkage cluster node id that is the leader of flat cluster with id M[j]. If ``i < n``, ``i`` corresponds to an original observation, otherwise it corresponds to a non-singleton cluster. For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with id 8's leader is linkage node 2. M : ndarray The leader linkage node id's stored as a k-element 1-D array where ``k`` is the number of flat clusters found in ``T``. This allows the set of flat cluster ids to be any arbitrary set of ``k`` integers. """ Z = np.asarray(Z, order='c') T = np.asarray(T, order='c') if type(T) != np.ndarray or T.dtype != 'i': raise TypeError('T must be a one-dimensional numpy array of integers.') is_valid_linkage(Z, throw=True, name='Z') if len(T) != Z.shape[0] + 1: raise ValueError('Mismatch: len(T)!=Z.shape[0] + 1.') Cl = np.unique(T) kk = len(Cl) L = np.zeros((kk,), dtype='i') M = np.zeros((kk,), dtype='i') n = Z.shape[0] + 1 [Z, T] = _copy_arrays_if_base_present([Z, T]) s = _hierarchy.leaders(Z, T, L, M, int(kk), int(n)) if s >= 0: raise ValueError(('T is not a valid assignment vector. Error found ' 'when examining linkage node %d (< 2n-1).') % s) return (L, M)
bsd-3-clause
nschaetti/nsNLP
features/BagOfCharactersTensor.py
1
13672
# -*- coding: utf-8 -*- # # File : core/downloader/PySpeechesConfig.py # Description : . # Date : 20th of February 2017 # # This file is part of pySpeeches. pySpeeches 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, version 2. # # 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. # # Copyright Nils Schaetti, University of Neuchâtel <[email protected]> # Import packages import torch import matplotlib.pyplot as plt # Bag of characters tensor class BagOfCharactersTensor(object): """ Bag of characters tensor """ # Constructor def __init__(self, alphabet, uppercase=False, n_gram=1, multi=10, tokenizer=None, start_grams=False, end_grams=False): """ Constructor :param n_gram: """ # Variables self._alphabet = alphabet self._uppercase = uppercase self._n_gram = n_gram self._n_chars = len(alphabet) + 1 self.chars = list() self.char_count = dict() self._multi = multi self._start_grams = start_grams self._end_grams = end_grams self._tokenizer = tokenizer # Char to index self._char2index = dict() for index, c in enumerate(alphabet): self._char2index[c] = index # end for # end __init__ ######################################### # Override ######################################### # Call def __call__(self, text, normalize=True): """ Call :return: """ # Size factor size_factor = 1 # Start grams if self._start_grams: size_factor += 1 # end if # End grams if self._end_grams: size_factor += 1 # end if # Tensor gram_tensor = None if self._n_gram == 1: gram_tensor = torch.zeros(1, self._n_chars * size_factor) elif self._n_gram == 2: gram_tensor = torch.zeros(1, self._n_chars * size_factor, self._n_chars + 1) elif self._n_gram == 3: gram_tensor = torch.zeros(1, self._n_chars * size_factor, self._n_chars + 1, self._n_chars + 1) # end if # Compute 1 gram gram_tensor = self._compute_1gram(gram_tensor, text, normalize) # Compute 2 gram if self._n_gram >= 2: gram_tensor = self._compute_2gram(gram_tensor, text, normalize) # end if # Compute 3 gram if self._n_gram == 3: gram_tensor = self._compute_3gram(gram_tensor, text, normalize) # end if # Start characters if self._start_grams: gram_tensor = self._compute_position_1gram(gram_tensor, text, 'start', self._n_chars, normalize) # end if # Start 2-grams if self._start_grams and self._n_gram >= 2: self._compute_position_2gram(gram_tensor, text, 'start', self._n_chars, normalize) # end if # End characters if self._end_grams: self._compute_position_1gram\ ( gram_tensor, text, 'end', self._n_chars if not self._start_grams else self._n_chars * 2, normalize ) # end if # End grams if self._end_grams and self._n_gram >= 2: self._compute_position_2gram\ ( gram_tensor, text, 'end', self._n_chars if not self._start_grams else self._n_chars * 2, normalize ) # end if return gram_tensor # end __call__ ######################################### # Private ######################################### # Compute 1-gram values def _compute_1gram(self, tensor, text, normalize=True): """ Compute 1-gram values :param tensor: :param text: :return: """ # Total total = 0.0 # For each grams for i in range(len(text)): # Gram gram = text[i] # Index char_index = self._get_char_index(gram) # Not found if char_index == -1: char_index = self._n_chars - 1 # end if # Set if self._n_gram == 1: tensor[0, char_index] += 1.0 elif self._n_gram == 2: tensor[0, char_index, 0] += 1.0 elif self._n_gram == 3: tensor[0, char_index, 0, 0] += 1.0 # end if total += 1.0 # end for # Normalize if normalize: if self._n_gram == 1: tensor /= total elif self._n_gram == 2: tensor[0, :self._n_chars, 0] /= total tensor[0, :self._n_chars, 0] /= tensor[0, :, 0].max() tensor[0, :self._n_chars, 0] *= self._multi elif self._n_gram == 3: tensor[0, :self._n_chars, 0, 0] /= total tensor[0, :self._n_chars, 0, 0] /= tensor[0, :, 0, 0].max() tensor[0, :self._n_chars, 0, 0] *= self._multi # end if # end if return tensor # end _compute_1gram # Compute 2-gram values def _compute_2gram(self, tensor, text, normalize=True): """ Compute 2-gram values :param tensor: :param text: :param normalize: :return: """ # Total total = 0.0 # For each grams for i in range(len(text)-1): # Gram gram = text[i:i+2] # Index char_index1 = self._get_char_index(gram[0]) char_index2 = self._get_char_index(gram[1]) # Not found if char_index1 == -1: char_index1 = self._n_chars - 1 # end if # Add char_index2 = char_index2 + 1 if char_index2 != -1 else -1 # Set if self._n_gram == 2: tensor[0, char_index1, char_index2] += 1.0 elif self._n_gram == 3: tensor[0, 0, char_index1, char_index2, 0] += 1.0 # end if total += 1.0 # end for # Normalize if normalize: if self._n_gram == 2: tensor[0, :self._n_chars, 1:] /= total tensor[0, :self._n_chars, 1:] /= tensor[0, :, 1:].max() tensor[0, :self._n_chars, 1:] *= self._multi elif self._n_gram == 3: tensor[0, :self._n_chars, 1:, 0] /= total tensor[0, :self._n_chars, 1:, 0] /= tensor[0, :, 1:, 0] tensor[0, :self._n_chars, 1:, 0] *= self._multi # end if # end if return tensor # end _compute_2gram # Compute 3-gram values def _compute_3gram(self, tensor, text, normalize=True): """ Compute 3-gram values :param tensor: :param text: :param normalize: :return: """ # Total total = 0.0 # For each grams for i in range(len(text)-2): # Gram gram = text[i:i + 3] # Index char_index1 = self._get_char_index(gram[0]) char_index2 = self._get_char_index(gram[1]) char_index3 = self._get_char_index(gram[2]) # Not found if char_index1 == -1: char_index1 = self._n_chars - 1 # end if # Add char_index2 = char_index2 + 1 if char_index2 != -1 else -1 char_index3 = char_index3 + 1 if char_index3 != -1 else -1 # Set tensor[0, char_index1, char_index2, char_index3] += 1.0 total += 1.0 # end for # Normalize if normalize: tensor[0, :self._n_chars, 1:, 1:] /= total tensor[0, :self._n_chars, 1:, 1:] /= tensor[0, :self._n_chars, 1:, 1:].max() tensor[0, :self._n_chars, 1:, 1:] *= self._multi # end if return tensor # end _compute_3gram # Compute position grams def _compute_position_1gram(self, tensor, text, gram_type, start_pos, normalize=True): """ Compute position 1grams :param tensor: :param text: :param gram_type: :param start_pos: :param normalize: :return: """ # Total total = 0.0 # Check tokenizer if self._tokenizer is None: raise Exception(u"I need a tokenizer!") # end if # Gram position gram_pos1 = 0 if gram_type == 'end': gram_pos1 = -1 # end if # For each token for token in self._tokenizer(text): # Length if len(token) > 0: # Index char_index1 = self._get_char_index(token[gram_pos1]) # Not found if char_index1 == -1: char_index1 = self._n_chars - 1 # end if # Set if self._n_gram == 1: tensor[0, start_pos + char_index1] += 1.0 elif self._n_gram == 2: tensor[0, start_pos + char_index1, 0] += 1.0 else: tensor[0, start_pos + char_index1, 0, 0] += 1.0 # end if # Total total += 1.0 # end if # end for # Normalize if normalize: if self._n_gram == 1: tensor[0, start_pos:start_pos + self._n_chars] /= total if self._n_gram == 2: tensor[0, start_pos:start_pos + self._n_chars, 0] /= total max = tensor[0, start_pos:start_pos + self._n_chars, 0].max() tensor[0, start_pos:start_pos + self._n_chars, 0] /= max tensor[0, start_pos:start_pos + self._n_chars, 0] *= self._multi elif self._n_gram == 3: tensor[0, start_pos:start_pos + self._n_chars, 0, 0] /= total max = tensor[0, start_pos:start_pos + self._n_chars, 0, 0].max() tensor[0, start_pos:start_pos + self._n_chars, 0, 0] /= max tensor[0, start_pos:start_pos + self._n_chars, 0, 0] *= self._multi # end if # end if return tensor # end _compute_position_1gram # Compute position grams def _compute_position_2gram(self, tensor, text, gram_type, start_pos, normalize=True): """ Compute position grams :param tensor: :param text: :param start_pos: :param normalize: :return: """ # Total total = 0.0 # Check tokenizer if self._tokenizer is None: raise Exception(u"I need a tokenizer!") # end if # Gram positin gram_pos1 = 0 gram_pos2 = 1 if gram_type == 'end': gram_pos1 = -2 gram_pos2 = -1 # end if # For each token for token in self._tokenizer(text): # Length if len(token) > 1: # Index char_index1 = self._get_char_index(token[gram_pos1]) char_index2 = self._get_char_index(token[gram_pos2]) # Not found if char_index1 == -1: char_index1 = self._n_chars - 1 # end if # Add char_index2 = char_index2 + 1 if char_index2 != -1 else -1 # Set if self._n_gram == 2: tensor[0, start_pos + char_index1, char_index2] += 1.0 else: tensor[0, start_pos + char_index1, char_index2, 0] += 1.0 # end if # Total total += 1.0 # end if # end for # Normalize if normalize: if self._n_gram == 2: tensor[0, start_pos:start_pos+self._n_chars, 1:] /= total max = tensor[0, start_pos:start_pos+self._n_chars, 1:].max() tensor[0, start_pos:start_pos + self._n_chars, 1:] /= max tensor[0, start_pos:start_pos + self._n_chars, 1:] *= self._multi elif self._n_gram == 3: tensor[0, start_pos:start_pos+self._n_chars, 1:, 0] /= total max = tensor[0, start_pos:start_pos+self._n_chars, 1:, 0].max() tensor[0, start_pos:start_pos + self._n_chars, 1:, 0] /= max tensor[0, start_pos:start_pos + self._n_chars, 1:, 0] *= self._multi # end if # end if return tensor # end _compute_position_gram # Get char index def _get_char_index(self, c): """ Get char index :param c: :return: """ try: return self._char2index[c] except KeyError: return -1 # end try # end _get_char_index # end BagOfCharactersTensor
gpl-3.0
chenyyx/scikit-learn-doc-zh
examples/zh/linear_model/plot_iris_logistic.py
119
1679
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Logistic Regression 3-class Classifier ========================================================= Show below is a logistic-regression classifiers decision boundaries on the `iris <https://en.wikipedia.org/wiki/Iris_flower_data_set>`_ dataset. The datapoints are colored according to their labels. """ print(__doc__) # Code source: Gaël Varoquaux # Modified for documentation by Jaques Grobler # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, datasets # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. Y = iris.target h = .02 # step size in the mesh logreg = linear_model.LogisticRegression(C=1e5) # we create an instance of Neighbours Classifier and fit the data. logreg.fit(X, Y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure(1, figsize=(4, 3)) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show()
gpl-3.0
jjx02230808/project0223
examples/applications/plot_species_distribution_modeling.py
254
7434
""" ============================= Species distribution modeling ============================= Modeling species' geographic distributions is an important problem in conservation biology. In this example we model the geographic distribution of two south american mammals given past observations and 14 environmental variables. Since we have only positive examples (there are no unsuccessful observations), we cast this problem as a density estimation problem and use the `OneClassSVM` provided by the package `sklearn.svm` as our modeling tool. The dataset is provided by Phillips et. al. (2006). If available, the example uses `basemap <http://matplotlib.sourceforge.net/basemap/doc/html/>`_ to plot the coast lines and national boundaries of South America. 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. """ # Authors: Peter Prettenhofer <[email protected]> # Jake Vanderplas <[email protected]> # # License: BSD 3 clause from __future__ import print_function from time import time import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.base import Bunch from sklearn.datasets import fetch_species_distributions from sklearn.datasets.species_distributions import construct_grids from sklearn import svm, metrics # if basemap is available, we'll use it. # otherwise, we'll improvise later... try: from mpl_toolkits.basemap import Basemap basemap = True except ImportError: basemap = False print(__doc__) def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid): """Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name. """ bunch = Bunch(name=' '.join(species_name.split("_")[:2])) species_name = species_name.encode('ascii') points = dict(test=test, train=train) for label, pts in points.items(): # choose points associated with the desired species pts = pts[pts['species'] == species_name] bunch['pts_%s' % label] = pts # determine coverage values for each of the training & testing points ix = np.searchsorted(xgrid, pts['dd long']) iy = np.searchsorted(ygrid, pts['dd lat']) bunch['cov_%s' % label] = coverages[:, -iy, ix].T return bunch def plot_species_distribution(species=("bradypus_variegatus_0", "microryzomys_minutus_0")): """ Plot the species distribution. """ if len(species) > 2: print("Note: when more than two species are provided," " only the first two will be used") t0 = time() # Load the compressed data data = fetch_species_distributions() # Set up the data grid xgrid, ygrid = construct_grids(data) # The grid in x,y coordinates X, Y = np.meshgrid(xgrid, ygrid[::-1]) # create a bunch for each species BV_bunch = create_species_bunch(species[0], data.train, data.test, data.coverages, xgrid, ygrid) MM_bunch = create_species_bunch(species[1], data.train, data.test, data.coverages, xgrid, ygrid) # background points (grid coordinates) for evaluation np.random.seed(13) background_points = np.c_[np.random.randint(low=0, high=data.Ny, size=10000), np.random.randint(low=0, high=data.Nx, size=10000)].T # We'll make use of the fact that coverages[6] has measurements at all # land points. This will help us decide between land and water. land_reference = data.coverages[6] # Fit, predict, and plot for each species. for i, species in enumerate([BV_bunch, MM_bunch]): print("_" * 80) print("Modeling distribution of species '%s'" % species.name) # Standardize features mean = species.cov_train.mean(axis=0) std = species.cov_train.std(axis=0) train_cover_std = (species.cov_train - mean) / std # Fit OneClassSVM print(" - fit OneClassSVM ... ", end='') clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.5) clf.fit(train_cover_std) print("done.") # Plot map of South America plt.subplot(1, 2, i + 1) if basemap: print(" - plot coastlines using basemap") m = Basemap(projection='cyl', llcrnrlat=Y.min(), urcrnrlat=Y.max(), llcrnrlon=X.min(), urcrnrlon=X.max(), resolution='c') m.drawcoastlines() m.drawcountries() else: print(" - plot coastlines from coverage") plt.contour(X, Y, land_reference, levels=[-9999], colors="k", linestyles="solid") plt.xticks([]) plt.yticks([]) print(" - predict species distribution") # Predict species distribution using the training data Z = np.ones((data.Ny, data.Nx), dtype=np.float64) # We'll predict only for the land points. idx = np.where(land_reference > -9999) coverages_land = data.coverages[:, idx[0], idx[1]].T pred = clf.decision_function((coverages_land - mean) / std)[:, 0] Z *= pred.min() Z[idx[0], idx[1]] = pred levels = np.linspace(Z.min(), Z.max(), 25) Z[land_reference == -9999] = -9999 # plot contours of the prediction plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds) plt.colorbar(format='%.2f') # scatter training/testing points plt.scatter(species.pts_train['dd long'], species.pts_train['dd lat'], s=2 ** 2, c='black', marker='^', label='train') plt.scatter(species.pts_test['dd long'], species.pts_test['dd lat'], s=2 ** 2, c='black', marker='x', label='test') plt.legend() plt.title(species.name) plt.axis('equal') # Compute AUC with regards to background points pred_background = Z[background_points[0], background_points[1]] pred_test = clf.decision_function((species.cov_test - mean) / std)[:, 0] scores = np.r_[pred_test, pred_background] y = np.r_[np.ones(pred_test.shape), np.zeros(pred_background.shape)] fpr, tpr, thresholds = metrics.roc_curve(y, scores) roc_auc = metrics.auc(fpr, tpr) plt.text(-35, -70, "AUC: %.3f" % roc_auc, ha="right") print("\n Area under the ROC curve : %f" % roc_auc) print("\ntime elapsed: %.2fs" % (time() - t0)) plot_species_distribution() plt.show()
bsd-3-clause
Eric89GXL/mne-python
mne/io/tests/test_what.py
10
1766
# Authors: Eric Larson <[email protected]> # License: BSD import glob import os.path as op import numpy as np import pytest from mne import what, create_info from mne.datasets import testing from mne.io import RawArray from mne.preprocessing import ICA from mne.utils import run_tests_if_main, requires_sklearn data_path = testing.data_path(download=False) @pytest.mark.slowtest @requires_sklearn @testing.requires_testing_data def test_what(tmpdir, verbose_debug): """Test mne.what.""" # ICA ica = ICA(max_iter=1) raw = RawArray(np.random.RandomState(0).randn(3, 10), create_info(3, 1000., 'eeg')) with pytest.warns(None): # convergence sometimes ica.fit(raw) fname = op.join(str(tmpdir), 'x-ica.fif') ica.save(fname) assert what(fname) == 'ica' # test files fnames = glob.glob( op.join(data_path, 'MEG', 'sample', '*.fif')) fnames += glob.glob( op.join(data_path, 'subjects', 'sample', 'bem', '*.fif')) fnames = sorted(fnames) want_dict = dict(eve='events', ave='evoked', cov='cov', inv='inverse', fwd='forward', trans='transform', proj='proj', raw='raw', meg='raw', sol='bem solution', bem='bem surfaces', src='src', dense='bem surfaces', sparse='bem surfaces', head='bem surfaces', fiducials='fiducials') for fname in fnames: kind = op.splitext(fname)[0].split('-')[-1] if len(kind) > 5: kind = kind.split('_')[-1] this = what(fname) assert this == want_dict[kind] fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave_xfit.dip') assert what(fname) == 'unknown' run_tests_if_main()
bsd-3-clause
BBN-Q/QGL
QGL/drivers/APS3Pattern.py
1
67288
''' Module for writing hdf5 APS2 files from sequences and patterns Copyright 2014 Raytheon BBN Technologies 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 os import logging from warnings import warn from copy import copy from itertools import zip_longest import pickle import struct import sys import numpy as np from QGL import Compiler, ControlFlow, BlockLabel, PatternUtils from QGL import PulseSequencer from QGL.PatternUtils import hash_pulse, flatten from QGL import TdmInstructions # Python 2/3 compatibility: use 'int' that subclasses 'long' from builtins import int logger = logging.getLogger(__name__) #Some constants SAMPLING_RATE = 2.5e9 ADDRESS_UNIT = 8 #everything is done in units of 4 timesteps MIN_ENTRY_LENGTH = 8 MAX_WAVEFORM_PTS = 2**28 #maximum size of waveform memory WAVEFORM_CACHE_SIZE = 2**17 MAX_WAVEFORM_VALUE = 2**15 - 1 #maximum waveform value i.e. 14bit DAC MAX_NUM_INSTRUCTIONS = 2**26 MAX_REPEAT_COUNT = 2**16 - 1 MAX_TRIGGER_COUNT = 2**32 - 1 MODULATION_CLOCK = 312.5e6 # instruction encodings WFM = 0x0 MARKER = 0x1 WAIT = 0x2 LOAD = 0x3 REPEAT = 0x4 CMP = 0x5 GOTO = 0x6 CALL = 0x7 RET = 0x8 SYNC = 0x9 MODULATION = 0xA LOADCMP = 0xB PREFETCH = 0xC NOP = 0XF # # APS3 prototype CUSTOM = 0xD INVALIDATE = 0xE # Invalidate and WriteAddr use the same opcode WRITEADDR = 0xE # WFM/MARKER op codes PLAY = 0x0 WAIT_TRIG = 0x1 WAIT_SYNC = 0x2 WFM_PREFETCH = 0x3 WFM_OP_OFFSET = 46 TA_PAIR_BIT = 45 # CMP op encodings EQUAL = 0x0 NOTEQUAL = 0x1 GREATERTHAN = 0x2 LESSTHAN = 0x3 CMPTABLE = {'==': EQUAL, '!=': NOTEQUAL, '>': GREATERTHAN, '<': LESSTHAN} # custom OP_CODES TDM_MAJORITY_VOTE = 0 TDM_MAJORITY_VOTE_SET_MASK = 1 TDM_TSM_SET_ROUNDS = 2 TDM_TSM = 3 APS_CUSTOM_DECODE = ["APS_RAND", "APS_CLIFFORD_RAND","APS_CLIFFORD_SET_SEED" ,"APS_CLIFFORD_SET_OFFSET" , "APS_CLIFFORD_SET_SPACING"] TDM_CUSTOM_DECODE = ["TDM_MAJORITY_VOTE", "TDM_MAJORITY_VOTE_SET_MASK", "TDM_TSM_SET_ROUNDS", "TDM_TSM"] # Whether we use PHASE_OFFSET modulation commands or bake it into waveform # Default to false as we usually don't have many variants USE_PHASE_OFFSET_INSTRUCTION = False # Whether to save the waveform offsets for partial compilation SAVE_WF_OFFSETS = False # Do we want a pulse file per instrument or per channel SEQFILE_PER_CHANNEL = False def get_empty_channel_set(): return {'ch1': {}, 'm1': {}} def get_seq_file_extension(): return '.aps3' def is_compatible_file(filename): with open(filename, 'rb') as FID: byte = FID.read(4) if byte == b'APS3': return True return False def create_wf_vector(wfLib, seqs): ''' Helper function to create the wf vector and offsets into it. ''' max_pts_needed = 0 for wf in wfLib.values(): if len(wf) == 1: max_pts_needed += ADDRESS_UNIT else: max_pts_needed += len(wf) #If we have more than fits in cache we'll need to align and prefetch need_prefetch = max_pts_needed > WAVEFORM_CACHE_SIZE idx = 0 if not need_prefetch: offsets = [{}] cache_lines = [] #if we can fit them all in just pack wfVec = np.zeros(max_pts_needed, dtype=np.int16) for key, wf in wfLib.items(): #Clip the wf wf[wf > 1] = 1.0 wf[wf < -1] = -1.0 #TA pairs need to be repeated ADDRESS_UNIT times if wf.size == 1: wf = wf.repeat(ADDRESS_UNIT) #Ensure the wf is an integer number of ADDRESS_UNIT's trim = wf.size % ADDRESS_UNIT if trim: wf = wf[:-trim] wfVec[idx:idx + wf.size] = np.int16(MAX_WAVEFORM_VALUE * wf) offsets[-1][key] = idx idx += wf.size #Trim the waveform wfVec.resize(idx) else: #otherwise fill in one cache line at a time CACHE_LINE_LENGTH = int(np.round(WAVEFORM_CACHE_SIZE / 2)) - 1 wfVec = np.zeros(CACHE_LINE_LENGTH, dtype=np.int16) offsets = [{}] cache_lines = [] for seq in seqs: #go through sequence and see what we need to add pts_to_add = 0 for entry in seq: if isinstance(entry, Compiler.Waveform): sig = wf_sig(entry) if sig not in offsets[-1]: pts_to_add += entry.length #If what we need to add spills over then add a line and start again if (idx % CACHE_LINE_LENGTH) + pts_to_add > CACHE_LINE_LENGTH: idx = int(CACHE_LINE_LENGTH * ( (idx + CACHE_LINE_LENGTH) // CACHE_LINE_LENGTH)) wfVec = np.append(wfVec, np.zeros(int(CACHE_LINE_LENGTH), dtype=np.int16)) offsets.append({}) for entry in seq: if isinstance(entry, Compiler.Waveform): sig = wf_sig(entry) if sig not in offsets[-1]: wf = wfLib[sig] wf[wf > 1] = 1.0 wf[wf < -1] = -1.0 #TA pairs need to be repeated ADDRESS_UNIT times if wf.size == 1: wf = wf.repeat(ADDRESS_UNIT) #Ensure the wf is an integer number of ADDRESS_UNIT's trim = wf.size % ADDRESS_UNIT if trim: wf = wf[:-trim] wfVec[idx:idx + wf.size] = np.int16( MAX_WAVEFORM_VALUE * wf) offsets[-1][sig] = idx idx += wf.size cache_lines.append(int(idx // CACHE_LINE_LENGTH)) return wfVec, offsets, cache_lines class Instruction(object): def __init__(self, header, payload, label=None, target=None, decode_as_tdm = False): self.header = header self.payload = int(payload) self.label = label self.target = target self.decode_as_tdm = decode_as_tdm @classmethod def unflatten(cls, instr, decode_as_tdm = False): return cls(header=(int(instr) >> 56) & 0xff, payload=int(instr) & 0xffffffffffffff, decode_as_tdm = decode_as_tdm) def __repr__(self): return self.__str__() def __str__(self): opCodes = ["WFM", "MARKER", "WAIT", "LOAD", "REPEAT", "CMP", "GOTO", "CALL", "RET", "SYNC", "MODULATION", "LOADCMP", "PREFETCH", "CUSTOM", "WRITEADDR", "NOP"] # list of opCodes where the reprenstation will change excludeList = ["WRITEADDR", "LOADCMP"] out = "{0} ".format(self.label) if self.label else "" instrOpCode = (self.header >> 4) & 0xf opCodeStr = opCodes[instrOpCode] if opCodeStr not in excludeList: out += opCodeStr if (instrOpCode == MARKER) or (instrOpCode == WFM) or ( instrOpCode == MODULATION): if (instrOpCode == MARKER) or (instrOpCode == WFM): out += "; engine={}, ".format((self.header >> 2) & 0x3) else: out += "; " if self.header & 0x1: out += "write=1 | " else: out += "write=0 | " if self.target: out += " {}".format(self.target) if instrOpCode == WFM: wfOpCode = (self.payload >> 46) & 0x3 wfOpCodes = ["PLAY", "TRIG", "SYNC", "PREFETCH"] out += wfOpCodes[wfOpCode] out += "; TA_bit={}".format((self.payload >> 45) & 0x1) out += ", count={}".format((self.payload >> 24) & 2**21 - 1) out += ", addr={}".format(self.payload & 2**24 - 1) # # APS3/TDM modifier to use VRAM output # if self.payload & (1 << 48): # out += ", use_vram" elif instrOpCode == MARKER: mrkOpCode = (self.payload >> 46) & 0x3 mrkOpCodes = ["PLAY", "TRIG", "SYNC"] out += mrkOpCodes[mrkOpCode] out += "; state={}".format((self.payload >> 32) & 0x1) out += ", count={}".format(self.payload & 2**32 - 1) elif instrOpCode == MODULATION: modulatorOpCode = (self.payload >> 45) & 0x7 modulatorOpCodes = ["MODULATE", "RESET_PHASE", "TRIG", "SET_FREQ", "SYNC", "SET_PHASE", "", "UPDATE_FRAME"] out += modulatorOpCodes[modulatorOpCode] out += "; nco_select=0x{:x}".format((self.payload >> 40) & 0xf) if modulatorOpCode == 0x0: out += ", count={:d}".format(self.payload & 0xffffffff) elif modulatorOpCode == 0x3: out += ", increment=0x{:08x}".format(self.payload & 0xffffffff) elif modulatorOpCode == 0x5: out += ", phase=0x{:08x}".format(self.payload & 0xffffffff) elif modulatorOpCode == 0x7: out += ", frame_change=0x{:08x}".format(self.payload & 0xffffffff) elif instrOpCode == CMP: cmpCodes = ["EQUAL", "NOTEQUAL", "GREATERTHAN", "LESSTHAN"] cmpCode = (self.payload >> 8) & 0x3 out += " | " + cmpCodes[cmpCode] out += ", value={}".format(self.payload & 0xff) elif any( [instrOpCode == op for op in [GOTO, CALL, RET, REPEAT, PREFETCH]]): out += " | target_addr={}".format(self.payload & 2**26 - 1) elif instrOpCode == LOAD: out += " | count={}".format(self.payload) elif instrOpCode == CUSTOM: store_addr = self.payload & 0xFFFF load_addr = (self.payload >> 16) & 0xFFFF instruction = (self.payload >> 32) & 0xFF instructionAPS = TDM_CUSTOM_DECODE[instruction] out += " | instruction={0} ({1}), load_addr=0x{2:0x}, store_addr=0x{3:0x}".format(instruction, instructionAPS, load_addr, store_addr) elif instrOpCode == WRITEADDR: addr = self.payload & 0xFFFF value = (self.payload >> 16) & 0xFFFFFFFF invalidate = not (self.header & 0x1) mapTrigger = (self.header >> 2) & 0x1 writeCrossbar = (self.header >> 1) & 0x1 instrStr = "WRITEADDR " valueType = "value" if invalidate: instrStr = "INVALIDATE" valueType = "valid_mask" if mapTrigger: instrStr = "STOREMEAS" valueType = "mapping" if writeCrossbar: instrStr = "WRITECB" valuetype = "mapping" addr = (self.payload >> 16) & 0xFFFF value = (self.payload >> 32) & 0xFFFF out += "{0} | addr=0x{1:0x}, {2}=0x{3:0x}".format(instrStr, addr, valueType, value) elif instrOpCode == LOADCMP: addr = self.payload & 0xFFFF mask = (self.payload >> 16) & 0xFFFF7 use_ram = (self.payload >> 48) & 0x1 if self.decode_as_tdm and not use_ram: out += "WAITMEAS" else: src = "EXT" if use_ram: src = "RAM" out += "LOADCMP | source={0}, addr=0x{1:0x}, read_mask=0x{2:0x}".format(src, addr, mask) return out def __eq__(self, other): return self.header == other.header and self.payload == other.payload and self.label == other.label def __ne__(self, other): return not self == other def __hash__(self): return hash((self.header, self.payload, self.label)) @property def address(self): return self.payload & 0xffffffff # bottom 32-bits of payload @address.setter def address(self, value): self.payload |= value & 0xffffffff @property def writeFlag(self): return self.header & 0x1 @writeFlag.setter def writeFlag(self, value): self.header |= value & 0x1 @property def opcode(self): return self.header >> 4 def flatten(self): return int((self.header << 56) | (self.payload & 0xffffffffffffff)) def Waveform(addr, count, isTA, write=False, label=None): header = (WFM << 4) | (0x3 << 2) | (write & 0x1) #broadcast to both engines count = int(count) count = ((count // ADDRESS_UNIT) - 1) & 0x000fffff # 20 bit count addr = (addr // ADDRESS_UNIT) & 0x00ffffff # 24 bit addr payload = (PLAY << WFM_OP_OFFSET) | ((int(isTA) & 0x1) << TA_PAIR_BIT) | (count << 24) | addr return Instruction(header, payload, label) def WaveformPrefetch(addr): header = (WFM << 4) | (0x3 << 2) | (0x1) payload = (WFM_PREFETCH << WFM_OP_OFFSET) | addr return Instruction(header, payload, None) def Marker(sel, state, count, write=False, label=None): header = (MARKER << 4) | ((sel & 0x3) << 2) | (write & 0x1) count = int(count) four_count = ((count // ADDRESS_UNIT) - 1) & 0xffffffff # 32 bit count count_rem = 0#count % ADDRESS_UNIT if state == 0: transitionWords = {0: 0b0000, 1: 0b1000, 2: 0b1100, 3: 0b1110} transition = transitionWords[count_rem] else: transitionWords = {0: 0b1111, 1: 0b0111, 2: 0b0011, 3: 0b0001} transition = transitionWords[count_rem] payload = (PLAY << WFM_OP_OFFSET) | (transition << 33) | ( (state & 0x1) << 32) | four_count return Instruction(header, payload, label) def Command(cmd, payload, write=False, label=None): header = (cmd << 4) if isinstance(payload, int): instr = Instruction(header, payload, label) else: instr = Instruction(header, 0, label, target=payload) instr.writeFlag = write return instr def Sync(label=None): return Command(SYNC, WAIT_SYNC << WFM_OP_OFFSET, write=True, label=label) def Wait(label=None): return Command(WAIT, WAIT_TRIG << WFM_OP_OFFSET, write=True, label=label) def LoadCmp(label=None): return Command(LOADCMP, 0, label=label) def Cmp(op, value, label=None): return Command(CMP, (op << 8) | (value & 0xff), label=label) def Goto(addr, label=None): return Command(GOTO, addr, label=label) def Call(addr, label=None): return Command(CALL, addr, label=label) def Return(label=None): return Command(RET, 0, label=label) def Load(count, label=None): return Command(LOAD, count, label=label) def Repeat(addr, label=None): return Command(REPEAT, addr, label=label) def Prefetch(addr, label=None): return Command(PREFETCH, addr) def NoOp(): return Instruction.unflatten(0xffffffffffffffff) # QGL instructions def Invalidate(addr, mask, label=None): header = WRITEADDR << 4 payload = (mask << 16) | addr return Instruction(header, payload, label=label) def WriteAddr(addr, value, label=None): header = (WRITEADDR << 4) | 1 payload = (value << 16) | addr return Instruction(header, payload, label=label) def StoreMeas(addr, mapping, label=None): header = (WRITEADDR << 4) | 5 payload = (mapping << 16) | addr return Instruction(header, payload, label=label) def CrossBar(addr, value, label=None): header = (WRITEADDR << 4) | 3 payload = (value << 32) | (addr << 16) return Instruction(header, payload, label=label) def Custom(in_addr, out_addr, custom_op, label=None): header = CUSTOM << 4 payload = (custom_op << 32) | (in_addr << 16) | out_addr return Instruction(header, payload, label=label) def MajorityVote(in_addr, out_addr, label=None): return Custom(in_addr, out_addr, 0, label=label) def MajorityVoteMask(in_addr, out_addr, label=None): return Custom(in_addr, out_addr, 1, label=label) def DecodeSetRounds(in_addr, out_addr, label=None): return Custom(in_addr, out_addr, 2, label=label) def Decode(in_addr, out_addr, label=None): return Custom(in_addr, out_addr, 3, label=label) def LoadCmpVram(addr, mask, label=None): header = LOADCMP << 4 payload = (1 << 48) | (mask << 16) | addr return Instruction(header, payload, label=label) def preprocess(seqs, shapeLib): seqs = PatternUtils.convert_lengths_to_samples( seqs, SAMPLING_RATE, ADDRESS_UNIT, Compiler.Waveform) wfLib = build_waveforms(seqs, shapeLib) inject_modulation_cmds(seqs) return seqs, wfLib def wf_sig(wf): ''' Compute a signature of a Compiler.Waveform that identifies the relevant properties for two Waveforms to be considered "equal" in the waveform library. For example, we ignore length of TA waveforms. ''' if wf.isZero or wf.isTimeAmp: # 2nd condition necessary until we support RT SSB if USE_PHASE_OFFSET_INSTRUCTION: return (wf.amp) else: return (wf.amp, round(wf.phase * 2**13)) else: #TODO: why do we need the length? if USE_PHASE_OFFSET_INSTRUCTION: return (wf.key, wf.amp, wf.length) else: return (wf.key, round(wf.phase * 2**13), wf.amp, wf.length) class ModulationCommand(object): """docstring for ModulationCommand""" def __init__(self, instruction, nco_select, frequency=0, phase=0, length=0): super(ModulationCommand, self).__init__() self.instruction = instruction self.nco_select = nco_select self.frequency = frequency self.phase = phase self.length = length def __str__(self): out = "Modulation({}, nco_select=0x{:x}".format(self.instruction, self.nco_select) if self.instruction == "MODULATE": out += ", length={})".format(self.length) elif self.instruction == "SET_FREQ": out += ", frequency={})".format(self.frequency) elif self.instruction == "SET_PHASE" or self.instruction == "UPDATE_FRAME": out += ", phase={})".format(self.phase) else: out += ")" return out def _repr_pretty_(self, p, cycle): p.text(str(self)) def __repr__(self): return str(self) def to_instruction(self, write_flag=True, label=None): #Modulator op codes MODULATOR_OP_OFFSET = 44 NCO_SELECT_OP_OFFSET = 40 op_code_map = {"MODULATE": 0x0, "RESET_PHASE": 0x2, "SET_FREQ": 0x6, "SET_PHASE": 0xa, "UPDATE_FRAME": 0xe} payload = (op_code_map[self.instruction] << MODULATOR_OP_OFFSET) | ( self.nco_select << NCO_SELECT_OP_OFFSET) if self.instruction == "MODULATE": #zero-indexed quad count payload |= np.uint32(self.length / ADDRESS_UNIT - 1) elif self.instruction == "SET_FREQ": # frequencies can span -4 to 4 or 0 to 8 in unsigned payload |= np.uint32( (self.frequency / MODULATION_CLOCK if self.frequency > 0 else self.frequency / MODULATION_CLOCK + 8) * 2**27) elif (self.instruction == "SET_PHASE") | ( self.instruction == "UPDATE_FRAME"): #phases can span -0.5 to 0.5 or 0 to 1 in unsigned payload |= np.uint32(np.mod(self.phase / (2 * np.pi), 1) * 2**27) instr = Instruction(MODULATION << 4, payload, label) instr.writeFlag = write_flag return instr def inject_modulation_cmds(seqs): """ Inject modulation commands from phase, frequency and frameChange of waveforms in an IQ waveform sequence. Assume up to 2 NCOs for now. """ cur_freq = 0 cur_phase = 0 for ct,seq in enumerate(seqs): #check whether we have modulation commands freqs = np.unique([entry.frequency for entry in filter(lambda s: isinstance(s,Compiler.Waveform), seq)]) if len(freqs) > 2: raise Exception("Max 2 frequencies on the same channel allowed.") no_freq_cmds = np.all(np.less(np.abs(freqs), 1e-8)) phases = [entry.phase for entry in filter(lambda s: isinstance(s,Compiler.Waveform), seq)] no_phase_cmds = np.all(np.less(np.abs(phases), 1e-8)) frame_changes = [entry.frameChange for entry in filter(lambda s: isinstance(s,Compiler.Waveform), seq)] no_frame_cmds = np.all(np.less(np.abs(frame_changes), 1e-8)) no_modulation_cmds = no_freq_cmds and no_phase_cmds and no_frame_cmds if no_modulation_cmds: continue mod_seq = [] pending_frame_update = False for entry in seq: #copies to avoid same object having different timestamps later #copy through BlockLabel if isinstance(entry, BlockLabel.BlockLabel): mod_seq.append(copy(entry)) #mostly copy through control-flow elif isinstance(entry, ControlFlow.ControlInstruction) or isinstance(entry, TdmInstructions.LoadCmpVramInstruction) or isinstance(entry, TdmInstructions.WriteAddrInstruction): #heuristic to insert phase reset before trigger if we have modulation commands if isinstance(entry, ControlFlow.Wait): if not ( no_modulation_cmds and (cur_freq == 0) and (cur_phase == 0)): mod_seq.append(ModulationCommand("RESET_PHASE", 0x3)) for nco_ind, freq in enumerate(freqs): mod_seq.append( ModulationCommand("SET_FREQ", nco_ind + 1, frequency = freq) ) elif isinstance(entry, ControlFlow.Return): cur_freq = 0 #makes sure that the frequency is set in the first sequence after the definition of subroutines mod_seq.append(copy(entry)) elif isinstance(entry, Compiler.Waveform): if not no_modulation_cmds: #select nco nco_select = (list(freqs)).index(entry.frequency) + 1 cur_freq = entry.frequency if USE_PHASE_OFFSET_INSTRUCTION and (entry.length > 0) and (cur_phase != entry.phase): mod_seq.append( ModulationCommand("SET_PHASE", nco_select, phase=entry.phase) ) cur_phase = entry.phase #now apply modulation for count command and waveform command, if non-zero length if entry.length > 0: mod_seq.append(entry) # if we have a modulate waveform modulate pattern and there is no pending frame update we can append length to previous modulation command if (len(mod_seq) > 1) and (isinstance(mod_seq[-1], Compiler.Waveform)) and (isinstance(mod_seq[-2], ModulationCommand)) and (mod_seq[-2].instruction == "MODULATE") \ and mod_seq[-1].frequency == freqs[mod_seq[-2].nco_select - 1] and not pending_frame_update: mod_seq[-2].length += entry.length else: mod_seq.append( ModulationCommand("MODULATE", nco_select, length = entry.length)) pending_frame_update = False #now apply non-zero frame changes after so it is applied at end if entry.frameChange != 0: pending_frame_update = True #zero length frame changes (Z pulses) need to be combined with the previous frame change or injected where possible if entry.length == 0: #if the last is a frame change then we can add to the frame change if isinstance(mod_seq[-1], ModulationCommand) and mod_seq[-1].instruction == "UPDATE_FRAME": mod_seq[-1].phase += entry.frameChange #if last entry was pulse without frame change we add frame change elif (isinstance(mod_seq[-1], Compiler.Waveform)) or (mod_seq[-1].instruction == "MODULATE"): mod_seq.append( ModulationCommand("UPDATE_FRAME", nco_select, phase=entry.frameChange) ) #if this is the first entry with a wait for trigger then we can inject a frame change #before the wait for trigger but after the RESET_PHASE elif isinstance(mod_seq[-1], ControlFlow.Wait): mod_seq.insert(-1, ModulationCommand("UPDATE_FRAME", nco_select, phase=entry.frameChange) ) elif isinstance(mod_seq[-2], ControlFlow.Wait) and isinstance(mod_seq[-1], ModulationCommand) and mod_seq[-1].instruction == "SET_FREQ": mod_seq.insert(-2, ModulationCommand("UPDATE_FRAME", nco_select, phase=entry.frameChange) ) #otherwise drop and error if frame has been defined else: raise Exception("Unable to implement zero time Z pulse") else: mod_seq.append( ModulationCommand("UPDATE_FRAME", nco_select, phase=entry.frameChange) ) seqs[ct] = mod_seq def build_waveforms(seqs, shapeLib): # apply amplitude (and optionally phase) and add the resulting waveforms to the library wfLib = {} for wf in flatten(seqs): if isinstance(wf, Compiler.Waveform) and wf_sig(wf) not in wfLib: shape = wf.amp * shapeLib[wf.key] if not USE_PHASE_OFFSET_INSTRUCTION: shape *= np.exp(1j * wf.phase) wfLib[wf_sig(wf)] = shape return wfLib def timestamp_entries(seq): t = 0 for ct in range(len(seq)): seq[ct].startTime = t t += seq[ct].length def synchronize_clocks(seqs): # Control-flow instructions (CFIs) must occur at the same time on all channels. # Therefore, we need to "reset the clock" by synchronizing the accumulated # time at each CFI to the largest value on any channel syncInstructions = [list(filter( lambda s: isinstance(s, ControlFlow.ControlInstruction), seq)) for seq in seqs if seq] # Add length to control-flow instructions to make accumulated time match at end of CFI. # Keep running tally of how much each channel has been shifted so far. localShift = [0 for _ in syncInstructions] for ct in range(len(syncInstructions[0])): step = [seq[ct] for seq in syncInstructions] endTime = max((s.startTime + shift for s, shift in zip(step, localShift))) for ct, s in enumerate(step): s.length = endTime - (s.startTime + localShift[ct]) # localShift[ct] += endTime - (s.startTime + localShift[ct]) # the += and the last term cancel, therefore: localShift[ct] = endTime - s.startTime # re-timestamp to propagate changes across the sequences for seq in seqs: timestamp_entries(seq) # then transfer the control flow "lengths" back into start times for seq in syncInstructions: for instr in seq: instr.startTime += instr.length instr.length = 0 def create_seq_instructions(seqs, offsets, label = None): ''' Helper function to create instruction vector from an IR sequence and an offset dictionary keyed on the wf keys. Seqs is a list of lists containing waveform and marker data, e.g. [wfSeq & modulationSeq, m1Seq, m2Seq, m3Seq, m4Seq] We take the strategy of greedily grabbing the next instruction that occurs in time, accross all waveform and marker channels. ''' # timestamp all entries before filtering (where we lose time information on control flow) for seq in seqs: timestamp_entries(seq) synchronize_clocks(seqs) # create (seq, startTime) pairs over all sequences timeTuples = [] for ct, seq in enumerate(seqs): timeTuples += [(entry.startTime, ct) for entry in seq] timeTuples.sort() # keep track of where we are in each sequence indexes = np.zeros(len(seqs), dtype=np.int64) # always start with SYNC (stealing label from beginning of sequence) # unless it is a subroutine (using last entry as return as tell) instructions = [] for ct, seq in enumerate(seqs): if len(seq): first_non_empty = ct break if not isinstance(seqs[first_non_empty][-1], ControlFlow.Return): if isinstance(seqs[first_non_empty][0], BlockLabel.BlockLabel): if not label: label = seqs[first_non_empty][0] timeTuples.pop(0) indexes[first_non_empty] += 1 instructions.append(Sync(label=label)) label = None while len(timeTuples) > 0: #pop off all entries that have the same time entries = [] start_time = 0 while True: start_time, seq_idx = timeTuples.pop(0) entries.append((seqs[seq_idx][indexes[seq_idx]], seq_idx)) indexes[seq_idx] += 1 next_start_time = timeTuples[0][0] if len(timeTuples) > 0 else -1 if start_time != next_start_time: break write_flags = [True] * len(entries) for ct, (entry, seq_idx) in enumerate(entries): #use first non empty sequence for control flow if seq_idx == first_non_empty and ( isinstance(entry, ControlFlow.ControlInstruction) or isinstance(entry, BlockLabel.BlockLabel) or isinstance(entry, TdmInstructions.CustomInstruction) or isinstance(entry, TdmInstructions.WriteAddrInstruction) or isinstance(entry, TdmInstructions.LoadCmpVramInstruction)): if isinstance(entry, BlockLabel.BlockLabel): # carry label forward to next entry label = entry continue # control flow instructions elif isinstance(entry, ControlFlow.Wait): instructions.append(Wait(label=label)) elif isinstance(entry, ControlFlow.LoadCmp): instructions.append(LoadCmp(label=label)) elif isinstance(entry, ControlFlow.Sync): instructions.append(Sync(label=label)) elif isinstance(entry, ControlFlow.Return): instructions.append(Return(label=label)) # target argument commands elif isinstance(entry, ControlFlow.Goto): instructions.append(Goto(entry.target, label=label)) elif isinstance(entry, ControlFlow.Call): instructions.append(Call(entry.target, label=label)) elif isinstance(entry, ControlFlow.Repeat): instructions.append(Repeat(entry.target, label=label)) # value argument commands elif isinstance(entry, ControlFlow.LoadRepeat): instructions.append(Load(entry.value - 1, label=label)) elif isinstance(entry, ControlFlow.ComparisonInstruction): # TODO modify Cmp operator to load from specified address instructions.append(Cmp(CMPTABLE[entry.operator], entry.value, label=label)) elif isinstance(entry, TdmInstructions.LoadCmpVramInstruction) and entry.tdm == False: instructions.append(LoadCmpVram(entry.addr, entry.mask, label=label)) # some TDM instructions are ignored by the APS elif isinstance(entry, TdmInstructions.CustomInstruction): pass elif isinstance(entry, TdmInstructions.WriteAddrInstruction): if entry.instruction == 'INVALIDATE' and entry.tdm == False: instructions.append(Invalidate(entry.addr, entry.value, label=label)) continue if seq_idx == 0: #analog - waveforms or modulation if isinstance(entry, Compiler.Waveform): if entry.length < MIN_ENTRY_LENGTH: warn("Dropping Waveform entry of length %s!" % entry.length) continue instructions.append(Waveform( offsets[wf_sig(entry)], entry.length, entry.isTimeAmp or entry.isZero, write=write_flags[ct], label=label)) elif isinstance(entry, ModulationCommand): instructions.append(entry.to_instruction( write_flag=write_flags[ct], label=label)) else: # a marker engine if isinstance(entry, Compiler.Waveform): if entry.length < MIN_ENTRY_LENGTH: warn("Dropping entry!") continue markerSel = seq_idx - 1 state = not entry.isZero instructions.append(Marker(markerSel, state, entry.length , write=write_flags[ct], label=label)) #clear label if len(timeTuples)>0: label = None return instructions, label def create_instr_data(seqs, offsets, cache_lines): ''' Constructs the complete instruction data vector, and does basic checks for validity. Subroutines will be placed at least 8 cache lines away from sequences and aligned to cache line ''' logger = logging.getLogger(__name__) logger.debug('') seq_instrs = [] need_prefetch = len(cache_lines) > 0 num_cache_lines = len(set(cache_lines)) cache_line_changes = np.concatenate( ([0], np.where(np.diff(cache_lines))[0] + 1)) label = None for ct, seq in enumerate(zip_longest(*seqs, fillvalue=[])): new_instrs, label = create_seq_instructions(list(seq), offsets[cache_lines[ct]] if need_prefetch else offsets[0], label = label) seq_instrs.append(new_instrs) #if we need wf prefetching and have moved waveform cache lines then inject prefetch for the next line if need_prefetch and (ct in cache_line_changes): next_cache_line = cache_lines[cache_line_changes[(np.where( ct == cache_line_changes)[0][0] + 1) % len( cache_line_changes)]] seq_instrs[-1].insert(0, WaveformPrefetch(int( next_cache_line * WAVEFORM_CACHE_SIZE / 2))) #steal label if necessary if not seq_instrs[-1][0].label: seq_instrs[-1][0].label = seq_instrs[-1][1].label seq_instrs[-1][1].label = None #concatenate instructions instructions = [] subroutines_start = -1 for ct, seq in enumerate(seq_instrs): #Use last instruction being return as mark of start of subroutines try: if (seq[-1].header >> 4) == RET: subroutines_start = ct break except: pass instructions += seq #if we have any subroutines then group in cache lines if subroutines_start >= 0: subroutine_instrs = [] subroutine_cache_line = {} CACHE_LINE_LENGTH = 128 offset = 0 for sub in seq_instrs[subroutines_start:]: #TODO for now we don't properly handle prefetching mulitple cache lines if len(sub) > CACHE_LINE_LENGTH: warnings.warn( "Subroutines longer than {} instructions may not be prefetched correctly") #Don't unecessarily split across a cache line if (len(sub) + offset > CACHE_LINE_LENGTH) and ( len(sub) < CACHE_LINE_LENGTH): pad_instrs = 128 - ((offset + 128) % 128) subroutine_instrs += [NoOp()] * pad_instrs offset = 0 if offset == 0: line_label = sub[0].label subroutine_cache_line[sub[0].label] = line_label subroutine_instrs += sub offset += len(sub) % CACHE_LINE_LENGTH logger.debug("Placed {} subroutines into {} cache lines".format( len(seq_instrs[subroutines_start:]), len(subroutine_instrs) // CACHE_LINE_LENGTH)) #inject prefetch commands before waits wait_idx = [idx for idx, instr in enumerate(instructions) if (instr.header >> 4) == WAIT] + [len(instructions)] instructions_with_prefetch = instructions[:wait_idx[0]] last_prefetch = None for start, stop in zip(wait_idx[:-1], wait_idx[1:]): call_targets = [instr.target for instr in instructions[start:stop] if (instr.header >> 4) == CALL] needed_lines = set() for target in call_targets: needed_lines.add(subroutine_cache_line[target]) if len(needed_lines) > 8: raise RuntimeError( "Unable to prefetch more than 8 cache lines") for needed_line in needed_lines: if needed_line != last_prefetch: instructions_with_prefetch.append(Prefetch(needed_line)) last_prefetch = needed_line instructions_with_prefetch += instructions[start:stop] instructions = instructions_with_prefetch #pad out instruction vector to ensure circular cache never loads a subroutine pad_instrs = 7 * 128 + (128 - ((len(instructions) + 128) % 128)) instructions += [NoOp()] * pad_instrs instructions += subroutine_instrs #turn symbols into integers addresses resolve_symbols(instructions) assert len(instructions) < MAX_NUM_INSTRUCTIONS, \ 'Oops! too many instructions: {0}'.format(len(instructions)) return np.fromiter((instr.flatten() for instr in instructions), np.uint64, len(instructions)) def resolve_symbols(seq): symbols = {} # create symbol look-up table for ct, entry in enumerate(seq): if entry.label and entry.label not in symbols: symbols[entry.label] = ct # then update for (ct, entry) in enumerate(seq): if entry.target: # find next available label. The TDM may miss some labels if branches only contain waveforms (which are ignored) for k in range(len(seq)-ct): temp = seq[ct+k] if temp.target in symbols: break entry.address = symbols[temp.target] def compress_marker(markerLL): ''' Compresses adjacent entries of the same state into single entries ''' for seq in markerLL: idx = 0 while idx + 1 < len(seq): if (isinstance(seq[idx], Compiler.Waveform) and isinstance(seq[idx + 1], Compiler.Waveform) and seq[idx].isZero == seq[idx + 1].isZero): seq[idx].length += seq[idx + 1].length del seq[idx + 1] else: idx += 1 def write_sequence_file(awgData, fileName): ''' Main function to pack channel sequences into an APS2 h5 file. ''' # Convert QGL IR into a representation that is closer to the hardware. awgData['ch1']['linkList'], wfLib = preprocess( awgData['ch1']['linkList'], awgData['ch1']['wfLib']) # compress marker data for field in ['m1']: if 'linkList' in awgData[field].keys(): PatternUtils.convert_lengths_to_samples(awgData[field]['linkList'], SAMPLING_RATE, 1, Compiler.Waveform) compress_marker(awgData[field]['linkList']) else: awgData[field]['linkList'] = [] #Create the waveform vectors wfInfo = [] wfInfo.append(create_wf_vector({key: wf.real for key, wf in wfLib.items()}, awgData[ 'ch1']['linkList'])) wfInfo.append(create_wf_vector({key: wf.imag for key, wf in wfLib.items()}, awgData[ 'ch1']['linkList'])) if SAVE_WF_OFFSETS: #create a set of all waveform signatures in offset dictionaries #we could have multiple offsets for the same pulse becuase it could #be repeated in multiple cache lines wf_sigs = set() for offset_dict in wfInfo[0][1]: wf_sigs |= set(offset_dict.keys()) #create dictionary linking entry labels (that's what we'll have later) with offsets offsets = {} for seq in awgData['ch1']['linkList']: for entry in seq: if len(wf_sigs) == 0: break if isinstance(entry, Compiler.Waveform): sig = wf_sig(entry) if sig in wf_sigs: #store offsets and wavefor lib length #time ampltidue entries are clamped to ADDRESS_UNIT wf_length = ADDRESS_UNIT if entry.isTimeAmp else entry.length offsets[entry.label] = ([_[sig] for _ in wfInfo[0][1]], wf_length) wf_sigs.discard(sig) #break out of outer loop too if len(wf_sigs) == 0: break #now pickle the label=>offsets with open(os.path.splitext(fileName)[0] + ".offsets", "wb") as FID: pickle.dump(offsets, FID) # build instruction vector seq_data = [awgData[s]['linkList'] for s in ['ch1', 'm1']] instructions = create_instr_data(seq_data, wfInfo[0][1], wfInfo[0][2]) #Open the binary file if os.path.isfile(fileName): os.remove(fileName) with open(fileName, 'wb') as FID: FID.write(b'APS3') # target hardware FID.write(np.float32(4.0).tobytes()) # Version FID.write(np.float32(4.0).tobytes()) # minimum firmware version FID.write(np.uint16(2).tobytes()) # number of channels # FID.write(np.uint16([1, 2]).tobytes()) # channelDataFor FID.write(np.uint64(instructions.size).tobytes()) # instructions length FID.write(instructions.tobytes()) # instructions in uint64 form #Create the groups and datasets for chanct in range(2): #Write the waveformLib to file if wfInfo[chanct][0].size == 0: #If there are no waveforms, ensure that there is some element #so that the waveform group gets written to file. #TODO: Fix this in libaps2 data = np.array([0], dtype=np.int16) else: data = wfInfo[chanct][0] FID.write(np.uint64(data.size).tobytes()) # waveform data length for channel FID.write(data.tobytes()) def read_sequence_file(fileName): """ Reads a HDF5 sequence file and returns a dictionary of lists. Dictionary keys are channel strings such as ch1, m1 Lists are or tuples of time-amplitude pairs (time, output) """ chanStrs = ['ch1', 'ch2', 'm1', 'mod_phase'] seqs = {ch: [] for ch in chanStrs} def start_new_seq(): for ct, ch in enumerate(chanStrs): if (ct < 2) or (ct == 6): #analog or modulation channel seqs[ch].append([]) else: #marker channel seqs[ch].append([]) with open(fileName, 'rb') as FID: target_hw = FID.read(4).decode('utf-8') file_version = struct.unpack('<f', FID.read(4))[0] min_fw = struct.unpack('<f', FID.read(4))[0] num_chans = struct.unpack('<H', FID.read(2))[0] inst_len = struct.unpack('<Q', FID.read(8))[0] instructions = np.frombuffer(FID.read(8*inst_len), dtype=np.uint64) wf_lib = {} for i in range(num_chans): wf_len = struct.unpack('<Q', FID.read(8))[0] wf_dat = np.frombuffer(FID.read(2*wf_len), dtype=np.int16) wf_lib[f'ch{i+1}'] = ( 1.0 / MAX_WAVEFORM_VALUE) * wf_dat.flatten() NUM_NCO = 2 freq = np.zeros(NUM_NCO) #radians per timestep phase = np.zeros(NUM_NCO) frame = np.zeros(NUM_NCO) next_freq = np.zeros(NUM_NCO) next_phase = np.zeros(NUM_NCO) next_frame = np.zeros(NUM_NCO) accumulated_phase = np.zeros(NUM_NCO) reset_flag = [False]*NUM_NCO for data in instructions: instr = Instruction.unflatten(data) modulator_opcode = instr.payload >> 44 #update phases at these boundaries if (instr.opcode == WAIT) | (instr.opcode == SYNC) | ( (instr.opcode) == MODULATION and (modulator_opcode == 0x0)): for ct in range(NUM_NCO): if reset_flag[ct]: #would expect this to be zero but this is first non-zero point accumulated_phase[ct] = next_freq[ct] * ADDRESS_UNIT reset_flag[ct] = False freq[:] = next_freq[:] phase[:] = next_phase[:] frame[:] = next_frame[:] #Assume new sequence at every WAIT if instr.opcode == WAIT: start_new_seq() elif instr.opcode == WFM and (( (instr.payload >> WFM_OP_OFFSET) & 0x3) == PLAY): addr = (instr.payload & 0x00ffffff) * ADDRESS_UNIT count = (instr.payload >> 24) & 0xfffff count = (count + 1) * ADDRESS_UNIT isTA = (instr.payload >> 45) & 0x1 chan_select_bits = ((instr.header >> 2) & 0x1, (instr.header >> 3) & 0x1) #On older firmware we broadcast by default whereas on newer we respect the engine select for chan, select_bit in zip(('ch1', 'ch2'), chan_select_bits): if (file_version < 4) or select_bit: if isTA: seqs[chan][-1].append((count, wf_lib[chan][addr])) else: for sample in wf_lib[chan][addr:addr + count]: seqs[chan][-1].append((1, sample)) elif instr.opcode == MARKER: chan = 'm' + str(((instr.header >> 2) & 0x3) + 1) count = instr.payload & 0xffffffff count = (count + 1) * ADDRESS_UNIT state = (instr.payload >> 32) & 0x1 seqs[chan][-1].append((count, state)) elif instr.opcode == MODULATION: # modulator_op_code_map = {"MODULATE":0x0, "RESET_PHASE":0x2, "SET_FREQ":0x6, "SET_PHASE":0xa, "UPDATE_FRAME":0xe} nco_select_bits = (instr.payload >> 40) & 0xf if modulator_opcode == 0x0: #modulate count = ((instr.payload & 0xffffffff) + 1) * ADDRESS_UNIT nco_select = {0b0001: 0, 0b0010: 1, 0b0100: 2, 0b1000: 3}[nco_select_bits] seqs['mod_phase'][-1] = np.append( seqs['mod_phase'][-1], freq[nco_select] * np.arange(count) + accumulated_phase[nco_select] + phase[nco_select] + frame[nco_select]) accumulated_phase += count * freq else: phase_rad = 2 * np.pi * (instr.payload & 0xffffffff) / 2**27 for ct in range(NUM_NCO): if (nco_select_bits >> ct) & 0x1: if modulator_opcode == 0x2: #reset next_phase[ct] = 0 next_frame[ct] = 0 reset_flag[ct] = True elif modulator_opcode == 0x6: #set frequency next_freq[ct] = phase_rad / ADDRESS_UNIT elif modulator_opcode == 0xa: #set phase next_phase[ct] = phase_rad elif modulator_opcode == 0xe: #update frame next_frame[ct] += phase_rad #Apply modulation if we have any for ct, ( ch1, ch2, mod_phase ) in enumerate(zip(seqs['ch1'], seqs['ch2'], seqs['mod_phase'])): if len(mod_phase): #only really works if ch1, ch2 are broadcast together mod_ch1 = [] mod_ch2 = [] cum_time = 0 for ((time_ch1, amp_ch1), (time_ch2, amp_ch2)) in zip(ch1, ch2): if (amp_ch1 != 0) or (amp_ch2 != 0): assert time_ch1 == time_ch2 if time_ch1 == 1: #single timestep modulated = np.exp(1j * mod_phase[cum_time]) * ( amp_ch1 + 1j * amp_ch2) mod_ch1.append((1, modulated.real)) mod_ch2.append((1, modulated.imag)) else: #expand TA modulated = np.exp( 1j * mod_phase[cum_time:cum_time + time_ch1]) * ( amp_ch1 + 1j * amp_ch2) for val in modulated: mod_ch1.append((1, val.real)) mod_ch2.append((1, val.imag)) else: mod_ch1.append((time_ch1, amp_ch1)) mod_ch2.append((time_ch2, amp_ch2)) cum_time += time_ch1 seqs['ch1'][ct] = mod_ch1 seqs['ch2'][ct] = mod_ch2 del seqs['mod_phase'] return seqs def update_wf_library(filename, pulses, offsets): """ Update a H5 waveform library in place give an iterable of (pulseName, pulse) tuples and offsets into the waveform library. """ assert USE_PHASE_OFFSET_INSTRUCTION == False #load the h5 file with h5py.File(filename) as FID: for label, pulse in pulses.items(): #create a new waveform if pulse.isTimeAmp: shape = np.repeat(pulse.amp * np.exp(1j * pulse.phase), 4) else: shape = pulse.amp * np.exp(1j * pulse.phase) * pulse.shape try: length = offsets[label][1] except KeyError: print("\t{} not found in offsets so skipping".format(pulse)) continue for offset in offsets[label][0]: print("\tUpdating {} at offset {}".format(pulse, offset)) FID['/chan_1/waveforms'][offset:offset + length] = np.int16( MAX_WAVEFORM_VALUE * shape.real) FID['/chan_2/waveforms'][offset:offset + length] = np.int16( MAX_WAVEFORM_VALUE * shape.imag) def tdm_instructions(seqs): """ Generate the TDM instructions for the given sequence. This assumes that there is one instruction sequence, not a list of them (as is generally the case elsewhere). FIXME """ instructions = list() label2addr = dict() # the backpatch table for labels label = seqs[0][0] for seq in seqs: seq = list(flatten(copy(seq))) #add sync at the beginning of the sequence. FIXME: for now, ignore subroutines. Assume that the first entry is a label instructions.append(Sync(label=label)) label = None for s in seq: if isinstance(s, BlockLabel.BlockLabel): #label2addr[s.label] = len(instructions) #FIXME this convert a label (A, B, ...) to the instruction number, i.e. the address (typically) # carry label forward to next entry label = s continue if isinstance(s, ControlFlow.Wait): instructions.append(Wait(label=label)) elif isinstance(s, ControlFlow.LoadCmp): instructions.append(LoadCmp(label=label)) elif isinstance(s, TdmInstructions.WriteAddrInstruction) and s.tdm == True: if s.instruction == 'INVALIDATE': print('o INVALIDATE(channel=%s, addr=0x%x, mask=0x%x)' % (str(s.channel), s.addr, s.value)) instructions.append(Invalidate(s.addr, s.value, label=label)) elif s.instruction == 'WRITEADDR': print('o WRITEADDR(channel=%s, addr=0x%x, value=0x%x)' % (str(s.channel), s.addr, s.value)) instructions.append(WriteAddr(s.addr, s.value, label=label)) elif s.instruction == 'STOREMEAS': print('STOREMEAS(channel=%s, addr=0x%x, mapping=0x%x)' % (str(s.channel), s.addr, s.value)) instructions.append(StoreMeas(s.addr, s.value, label=label)) else: # TODO: add CrossBar (no need for explicit QGL call for TDM) print('UNSUPPORTED WriteAddr: %s(channel=%s, addr=0x%x, val=0x%x)' % (s.instruction, str(s.channel), s.addr, s.value)) continue elif isinstance(s, TdmInstructions.CustomInstruction): if s.instruction == 'MAJORITY': print('MAJORITY(in_addr=%x, out_addr=%x)' % (s.in_addr, s.out_addr)) instructions.append( MajorityVote(s.in_addr, s.out_addr, label=label)) elif s.instruction == 'MAJORITYMASK': print('MAJORITYMASK(in_addr=%x, out_addr=%x)' % (s.in_addr, s.out_addr)) instructions.append( MajorityVoteMask(s.in_addr, s.out_addr, label=label)) elif s.instruction == 'TSM': print('DECODE(in_addr=%x, out_addr=%x)' % (s.in_addr, s.out_addr)) instructions.append( Decode(s.in_addr, s.out_addr, label=label)) elif s.instruction == 'TSM_SET_ROUNDS': print('DECODESETROUNDS(in_addr=%x, out_addr=%x)' % (s.in_addr, s.out_addr)) instructions.append( DecodeSetRounds(s.in_addr, s.out_addr, label=label)) else: #TODO: add decoder print('UNSUPPORTED CUSTOM: %s(in_addr=0x%x, out_addr=0x%x)' % (s.instruction, s.in_addr, s.out_addr)) elif isinstance(s, ControlFlow.Goto): instructions.append(Goto(s.target, label=label)) elif isinstance(s, ControlFlow.Repeat): instructions.append(Repeat(s.target, label=label)) elif isinstance(s, ControlFlow.LoadRepeat): instructions.append(Load(s.value - 1, label=label)) elif isinstance(s, TdmInstructions.LoadCmpVramInstruction): if s.instruction == 'LOADCMPVRAM' and s.tdm == True: instructions.append( LoadCmpVram(s.addr, s.mask, label=label)) elif isinstance(s, PulseSequencer.Pulse): if s.label == 'MEAS' and s.maddr != (-1, 0): instructions.append(CrossBar(2**s.maddr[1], 0x1, label=label)) instructions.append(LoadCmp(label=label)) instructions.append(StoreMeas(s.maddr[0], 1 << 16, label=label)) elif isinstance(s, PulseSequencer.PulseBlock): sim_meas = [] for k in s.pulses: if s.pulses[k].label == 'MEAS' and s.pulses[k].maddr != (-1, 0): sim_meas.append(s.pulses[k]) if sim_meas: maddr = [m.maddr[0] for m in sim_meas] if len(set(maddr))>1: raise Exception('Storing simultaneous measurements on different addresses not supported.') for n,m in enumerate(sim_meas): instructions.append(CrossBar(2**m.maddr[1], 2**n)) instructions.append(LoadCmp(label=label)) instructions.append(StoreMeas(maddr[0], 1 << 16)) elif isinstance(s, list): # FIXME: # If this happens, we are confused. print('FIXME: TDM GOT LIST: %s' % str(s)) elif isinstance(s, ControlFlow.ComparisonInstruction): instructions.append( Cmp(CMPTABLE[s.operator], s.value, label=label)) else: pass # use this for debugging purposes #print('OOPS: unhandled [%s]' % str(type(s))) resolve_symbols(instructions) return np.fromiter((instr.flatten() for instr in instructions), np.uint64, len(instructions)) def write_tdm_seq(seq, tdm_fileName): #Open the HDF5 file if os.path.isfile(tdm_fileName): os.remove(tdm_fileName) with h5py.File(tdm_fileName, 'w') as FID: FID['/'].attrs['Version'] = 5.0 FID['/'].attrs['target hardware'] = 'APS3' FID['/'].attrs['minimum firmware version'] = 5.0 FID['/'].attrs['channelDataFor'] = np.uint16([1, 2]) #Create the groups and datasets for chanct in range(2): chanStr = '/chan_{0}'.format(chanct + 1) chanGroup = FID.create_group(chanStr) FID.create_dataset(chanStr + '/waveforms', data=np.uint16([])) #Write the instructions to channel 1 if np.mod(chanct, 2) == 0: FID.create_dataset(chanStr + '/instructions', data=seq) # Utility Functions for displaying programs def raw_instructions(fileName): with open(fileName, 'rb') as FID: target_hw = FID.read(4).decode('utf-8') file_version = struct.unpack('<f', FID.read(4))[0] min_fw = struct.unpack('<f', FID.read(4))[0] num_chans = struct.unpack('<H', FID.read(2))[0] inst_len = struct.unpack('<Q', FID.read(8))[0] instructions = np.frombuffer(FID.read(8*inst_len), dtype=np.uint64) return instructions def decompile_instructions(instructions, tdm = False): return [Instruction.unflatten(x, decode_as_tdm = tdm) for x in instructions] def read_instructions(filename): raw_instrs = raw_instructions(filename) return decompile_instructions(raw_instrs) def read_waveforms(filename): with open(filename, 'rb') as FID: target_hw = FID.read(4).decode('utf-8') file_version = struct.unpack('<f', FID.read(4))[0] min_fw = struct.unpack('<f', FID.read(4))[0] num_chans = struct.unpack('<H', FID.read(2))[0] inst_len = struct.unpack('<Q', FID.read(8))[0] instructions = np.frombuffer(FID.read(8*inst_len), dtype=np.uint64) wf_dat = [] for i in range(num_chans): wf_len = struct.unpack('<Q', FID.read(8))[0] dat = ( 1.0 / MAX_WAVEFORM_VALUE) * np.frombuffer(FID.read(2*wf_len), dtype=np.int16).flatten() wf_dat.append(dat) return wf_dat def replace_instructions(filename, instructions, channel = 1): channelStr = get_channel_instructions_string(channel) with h5py.File(filename, 'r+') as fid: del fid[channelStr] fid.create_dataset(channelStr, data=instructions) def display_decompiled_file(filename, tdm = False): raw = raw_instructions(filename) display_decompiled_instructions(raw, tdm) def display_decompiled_instructions(raw, tdm = False, display_op_codes = True): cmds = decompile_instructions(raw, tdm) opcodeStr = '' for i,a in enumerate(zip(raw,cmds)): x,y = a if display_op_codes: opcodeStr = "0x{:016x} - ".format(x) print("{:5}: {}{}".format(i, opcodeStr,y)) def display_raw_instructions(raw): for x in raw: print("0x{:016x}".format(x)) def display_raw_file(filename): raw = raw_instructions(filename) display_raw_instructions(raw) if __name__ == '__main__': if len(sys.argv) == 2: from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QAbstractItemView, QPushButton from PyQt5.QtGui import QIcon, QColor, QFont from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg from matplotlib.figure import Figure table_font = QFont("Arial", weight=QFont.Bold) colors = {"WFM": QColor(0,200,0), "GOTO": QColor(0,100,100), "MARKER": QColor(150,150,200)} class MatplotlibWidget(QWidget): def __init__(self, I, Q, parent=None): super(MatplotlibWidget, self).__init__(parent) self.title = 'Waveform' self.left = 100 self.top = 100 self.width = 800 self.height = 600 self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.figure = Figure() self.canvas = FigureCanvasQTAgg(self.figure) self.axis = self.figure.add_subplot(111) self.axis.plot(I) self.axis.plot(Q) self.layout = QVBoxLayout(self) self.layout.addWidget(self.canvas) self.setLayout(self.layout) self.canvas.draw() self.show() class App(QWidget): COLUMN_COUNT = 7 def __init__(self, instructions, waveforms): super().__init__() self.title = 'APS3 Disassembled Instructions' self.left = 100 self.top = 100 self.width = 1000 self.height = 1200 self.instructions = instructions self.waveforms = waveforms print(self.waveforms) self.initUI() self.plotters = [] def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.createTable() self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout) # Show widget self.show() def createTable(self): # Create table self.tableWidget = QTableWidget() self.tableWidget.setRowCount(len(self.instructions)) self.tableWidget.setColumnCount(7) for k, instr in enumerate(self.instructions): fields = str(instr).replace(',','').replace(';', '').split(" ") if "|" in fields: fields.remove("|") if fields[0] in colors: color = colors[fields[0]] else: color = None for l, f in enumerate(fields): text = fields[l] if text == "GOTO": btn = QPushButton(self.tableWidget) btn.setText('GOTO') target_row = int(fields[1].split("=")[1]) def scroll_to_goto_target(row=target_row, tab=self.tableWidget): tab.scrollToItem(tab.item(row, 0)) btn.clicked.connect(scroll_to_goto_target) self.tableWidget.setCellWidget(k, l, btn) if text == "WFM" and int(fields[4].split("=")[1])==0: # Not a TA pair btn = QPushButton(self.tableWidget) btn.setText('WFM') addr = int(fields[6].split("=")[1]) count = int(fields[5].split("=")[1]) def open_plotter(addr=None, I=self.waveforms[0][addr:addr+count], Q=self.waveforms[1][addr:addr+count]): w = MatplotlibWidget(I,Q) self.plotters.append(w) btn.clicked.connect(open_plotter) self.tableWidget.setCellWidget(k, l, btn) else: item = QTableWidgetItem(text) item.setFont(table_font) if color: item.setBackground(color) self.tableWidget.setItem(k, l, item) if l < self.COLUMN_COUNT-1: for j in range(l+1, self.COLUMN_COUNT): item = QTableWidgetItem("") if color: item.setBackground(color) self.tableWidget.setItem(k, j, item) self.tableWidget.move(0,0) self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) app = QApplication(sys.argv[:1]) ex = App(read_instructions(sys.argv[1]), read_waveforms(sys.argv[1])) sys.exit(app.exec_())
apache-2.0
frank-tancf/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
Leminen/project_template_deeplearning
src/models/logreg_example.py
1
7774
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 10 16:43:52 2017 @author: leminen """ import os import tensorflow as tf import matplotlib.pyplot as plt import datetime import argparse import shlex import src.utils as utils import src.data.util_data as util_data def hparams_parser_train(hparams_string): parser = argparse.ArgumentParser() parser.add_argument('--epoch_max', type=int, default='100', help='Max number of epochs to run') parser.add_argument('--batch_size', type=int, default='64', help='Number of samples in each batch') ## add more model parameters to enable configuration from terminal return parser.parse_args(shlex.split(hparams_string)) def hparams_parser_evaluate(hparams_string): parser = argparse.ArgumentParser() parser.add_argument('--epoch_no', type=int, default=None, help='Epoch no to reload') ## add more model parameters to enable configuration from terminal return parser.parse_args(shlex.split(hparams_string)) class logreg_example(object): def __init__(self, dataset, id): self.model = 'logreg_example' if id != None: self.model = self.model + '_' + id self.dir_base = 'models/' + self.model self.dir_logs = self.dir_base + '/logs' self.dir_checkpoints = self.dir_base + '/checkpoints' self.dir_results = self.dir_base + '/results' utils.checkfolder(self.dir_checkpoints) utils.checkfolder(self.dir_logs) utils.checkfolder(self.dir_results) # Specify valid dataset for model if dataset == 'MNIST': self.dateset_filenames = ['data/processed/MNIST/train.tfrecord'] self.lbl_dim = 10 else: raise ValueError('Selected Dataset is not supported by model: logreg_example') def _create_inference(self, inputs): """ Define the inference model for the network Args: Returns: """ X = tf.reshape(inputs,[-1,784]) w = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name='weights') b = tf.Variable(tf.zeros([1, 10]), name="bias") outputs = tf.matmul(X, w) + b return outputs def _create_losses(self, outputs, labels): """ Define loss function[s] for the network Args: Returns: """ entropy = tf.nn.softmax_cross_entropy_with_logits(logits=outputs, labels=labels, name='loss') loss = tf.reduce_mean(entropy) # computes the mean over all the examples in the batch return loss def _create_optimizer(self, loss): """ Create optimizer for the network Args: Returns: """ optimizer = tf.train.AdamOptimizer(learning_rate = 0.01) optimizer_op = optimizer.minimize(loss) return optimizer_op def _create_summaries(self, loss): """ Create summaries for the network Args: Returns: """ ### Add summaries with tf.name_scope("summaries"): tf.summary.scalar('model_loss', loss) # placeholder summary summary_op = tf.summary.merge_all() return summary_op def train(self, hparams_string): """ Run training of the network Args: Returns: """ args_train = hparams_parser_train(hparams_string) batch_size = args_train.batch_size epoch_max = args_train.epoch_max utils.save_model_configuration(args_train, self.dir_base) # Use dataset for loading in datasamples from .tfrecord (https://www.tensorflow.org/programmers_guide/datasets#consuming_tfrecord_data) # The iterator will get a new batch from the dataset each time a sess.run() is executed on the graph. dataset = tf.data.TFRecordDataset(self.dateset_filenames) dataset = dataset.map(util_data.decode_image) # decoding the tfrecord dataset = dataset.map(self._preProcessData) # potential local preprocessing of data dataset = dataset.shuffle(buffer_size = 10000, seed = None) dataset = dataset.batch(batch_size = batch_size) iterator = dataset.make_initializable_iterator() inputs = iterator.get_next() # depends on self._preProcessData [in_image, in_label] = inputs # show network architecture utils.show_all_variables() # define model, loss, optimizer and summaries. outputs = self._create_inference(in_image) loss = self._create_losses(outputs, in_label) optimizer_op = self._create_optimizer(loss) summary_op = self._create_summaries(loss) with tf.Session() as sess: # Initialize all model Variables. sess.run(tf.global_variables_initializer()) # Create Saver object for loading and storing checkpoints saver = tf.train.Saver() # Create Writer object for storing graph and summaries for TensorBoard writer = tf.summary.FileWriter(self.dir_logs, sess.graph) # Reload Tensor values from latest checkpoint ckpt = tf.train.get_checkpoint_state(self.dir_checkpoints) epoch_start = 0 if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) ckpt_name = os.path.basename(ckpt.model_checkpoint_path) epoch_start = int(ckpt_name.split('-')[-1]) interationCnt = 0 # Do training loops for epoch_n in range(epoch_start, epoch_max): # Initiate or Re-initiate iterator sess.run(iterator.initializer) # Test model output before any training if epoch_n == 0: summary = sess.run(summary_op) writer.add_summary(summary, global_step=-1) utils.show_message('Running training epoch no: {0}'.format(epoch_n)) while True: try: _, summary = sess.run([optimizer_op, summary_op]) writer.add_summary(summary, global_step=interationCnt) counter =+ 1 except tf.errors.OutOfRangeError: # Do some evaluation after each Epoch break if epoch_n % 1 == 0: saver.save(sess,os.path.join(self.dir_checkpoints, self.model + '.model'), global_step=epoch_n) def evaluate(self, hparams_string): """ Run prediction of the network Args: Returns: """ args_evaluate = hparams_parser_evaluate(hparams_string) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) def _preProcessData(self, image_proto, lbl_proto, class_proto, height_proto, width_proto, channels_proto, origin_proto): """ Local preprocessing of data from dataset also used to select which elements to parse onto the model Args: all outputs of util_data.decode_image Returns: """ image = image_proto label = tf.one_hot(lbl_proto, self.lbl_dim) return image, label
mit
skudriashev/incubator-airflow
airflow/hooks/presto_hook.py
15
3549
# -*- coding: utf-8 -*- # # 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. from builtins import str from pyhive import presto from pyhive.exc import DatabaseError from airflow.hooks.dbapi_hook import DbApiHook class PrestoException(Exception): pass class PrestoHook(DbApiHook): """ Interact with Presto through PyHive! >>> ph = PrestoHook() >>> sql = "SELECT count(1) AS num FROM airflow.static_babynames" >>> ph.get_records(sql) [[340698]] """ conn_name_attr = 'presto_conn_id' default_conn_name = 'presto_default' def get_conn(self): """Returns a connection object""" db = self.get_connection(self.presto_conn_id) return presto.connect( host=db.host, port=db.port, username=db.login, catalog=db.extra_dejson.get('catalog', 'hive'), schema=db.schema) @staticmethod def _strip_sql(sql): return sql.strip().rstrip(';') def _get_pretty_exception_message(self, e): """ Parses some DatabaseError to provide a better error message """ if (hasattr(e, 'message') and 'errorName' in e.message and 'message' in e.message): return ('{name}: {message}'.format( name=e.message['errorName'], message=e.message['message'])) else: return str(e) def get_records(self, hql, parameters=None): """ Get a set of records from Presto """ try: return super(PrestoHook, self).get_records( self._strip_sql(hql), parameters) except DatabaseError as e: raise PrestoException(self._parse_exception_message(e)) def get_first(self, hql, parameters=None): """ Returns only the first row, regardless of how many rows the query returns. """ try: return super(PrestoHook, self).get_first( self._strip_sql(hql), parameters) except DatabaseError as e: raise PrestoException(self._parse_exception_message(e)) def get_pandas_df(self, hql, parameters=None): """ Get a pandas dataframe from a sql query. """ import pandas cursor = self.get_cursor() try: cursor.execute(self._strip_sql(hql), parameters) data = cursor.fetchall() except DatabaseError as e: raise PrestoException(self._parse_exception_message(e)) column_descriptions = cursor.description if data: df = pandas.DataFrame(data) df.columns = [c[0] for c in column_descriptions] else: df = pandas.DataFrame() return df def run(self, hql, parameters=None): """ Execute the statement against Presto. Can be used to create views. """ return super(PrestoHook, self).run(self._strip_sql(hql), parameters) def insert_rows(self): raise NotImplementedError()
apache-2.0
rsutormin/narrative
src/notebook/ipython_profiles/profile_narrative_local/ipython_notebook_config.py
4
19256
import os import inspect import biokbase.narrative.monkeypatch as monkeypatch # Configuration file for ipython-notebook. c = get_config() #------------------------------------------------------------------------------ # NotebookApp configuration #------------------------------------------------------------------------------ # NotebookApp will inherit config from: BaseIPythonApplication, Application # The IPython profile to use. # c.NotebookApp.profile = u'default' # The url for MathJax.js. # c.NotebookApp.mathjax_url = '' # The IP address the notebook server will listen on. # c.NotebookApp.ip = '127.0.0.1' # The base URL for the notebook server # c.NotebookApp.base_project_url = '/' # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.NotebookApp.verbose_crash = False # The number of additional ports to try if the specified port is not available. # c.NotebookApp.port_retries = 50 # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.NotebookApp.copy_config_files = False # The base URL for the kernel server # c.NotebookApp.base_kernel_url = '/' # The port the notebook server will listen on. # c.NotebookApp.port = 8888 # Whether to overwrite existing config files when copying # c.NotebookApp.overwrite = False # Whether to prevent editing/execution of notebooks. # c.NotebookApp.read_only = False # Whether to enable MathJax for typesetting math/TeX # # MathJax is the javascript library IPython uses to render math/LaTeX. It is # very large, so you may want to disable it if you have a slow internet # connection, or for offline use of the notebook. # # When disabled, equations etc. will appear as their untransformed TeX source. # c.NotebookApp.enable_mathjax = True # Whether to open in a browser after starting. The specific browser used is # platform dependent and determined by the python standard library `webbrowser` # module, unless it is overridden using the --browser (NotebookApp.browser) # configuration option. # c.NotebookApp.open_browser = True # The full path to an SSL/TLS certificate file. # c.NotebookApp.certfile = u'' # The hostname for the websocket server. # c.NotebookApp.websocket_host = '' # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This options can also be specified through the environment # variable IPYTHONDIR. # c.NotebookApp.ipython_dir = u'/Users/sychan/.ipython' # Set the log level by value or name. # c.NotebookApp.log_level = 20 # Hashed password to use for web authentication. # # To generate, type in a python/IPython shell: # # from IPython.lib import passwd; passwd() # # The string should be of the form type:salt:hashed-password. # c.NotebookApp.password = u'' # The Logging format template # c.NotebookApp.log_format = '[%(name)s] %(message)s' # The full path to a private key file for usage with SSL/TLS. # c.NotebookApp.keyfile = u'' # Supply overrides for the tornado.web.Application that the IPython notebook # uses. # c.NotebookApp.webapp_settings = {} # Supply overrides for the tornado.web.Application that the IPython notebook # uses. #c.NotebookApp.webapp_settings = { 'template_path': '/Users/wjriehl/Projects/kbase/narrative/src/ipythondir/profile_narrative/kbase_templates', # 'static_path': '/Users/wjriehl/Projects/kbase/narrative/src/ipythondir/profile_narrative/kbase_templates/static' } try: myfile = __file__ except NameError: myfile = os.path.abspath(inspect.getsourcefile(lambda _: None)) myfile = os.path.dirname( myfile) c.NotebookApp.webapp_settings = { 'template_path': os.path.join(myfile,"kbase_templates"), 'static_path': os.path.join(myfile,"kbase_templates","static"), 'debug' : True } c.NotebookApp.kbase_auth = True # Specify what command to use to invoke a web browser when opening the notebook. # If not specified, the default browser will be determined by the `webbrowser` # standard library module, which allows setting of the BROWSER environment # variable to override it. # c.NotebookApp.browser = u'' #------------------------------------------------------------------------------ # IPKernelApp configuration #------------------------------------------------------------------------------ # IPython: an enhanced interactive Python shell. # IPKernelApp will inherit config from: KernelApp, BaseIPythonApplication, # Application, InteractiveShellApp # The importstring for the DisplayHook factory # c.IPKernelApp.displayhook_class = 'IPython.zmq.displayhook.ZMQDisplayHook' # Set the IP or interface on which the kernel will listen. # c.IPKernelApp.ip = '127.0.0.1' # # c.IPKernelApp.parent_appname = u'' # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.IPKernelApp.verbose_crash = False # Run the module as a script. # c.IPKernelApp.module_to_run = '' # set the shell (ROUTER) port [default: random] # c.IPKernelApp.shell_port = 0 # Whether to overwrite existing config files when copying # c.IPKernelApp.overwrite = False # Execute the given command string. # c.IPKernelApp.code_to_run = '' # set the stdin (DEALER) port [default: random] # c.IPKernelApp.stdin_port = 0 # Set the log level by value or name. # c.IPKernelApp.log_level = 30 # lines of code to run at IPython startup. c.IPKernelApp.exec_lines = [ 'import biokbase.narrative.magics'] # The importstring for the OutStream factory # c.IPKernelApp.outstream_class = 'IPython.zmq.iostream.OutStream' # Whether to create profile dir if it doesn't exist # c.IPKernelApp.auto_create = False # set the heartbeat port [default: random] # c.IPKernelApp.hb_port = 0 # redirect stdout to the null device # c.IPKernelApp.no_stdout = False # dotted module name of an IPython extension to load. # c.IPKernelApp.extra_extension = '' # A file to be run # c.IPKernelApp.file_to_run = '' # The IPython profile to use. # c.IPKernelApp.profile = u'default' # Pre-load matplotlib and numpy for interactive use, selecting a particular # matplotlib backend and loop integration. # c.IPKernelApp.pylab = None # kill this process if its parent dies. On Windows, the argument specifies the # HANDLE of the parent process, otherwise it is simply boolean. # c.IPKernelApp.parent = 0 # JSON file in which to store connection info [default: kernel-<pid>.json] # # This file will contain the IP, ports, and authentication key needed to connect # clients to this kernel. By default, this file will be created in the security- # dir of the current profile, but can be specified by absolute path. # c.IPKernelApp.connection_file = '' # If true, an 'import *' is done from numpy and pylab, when using pylab # c.IPKernelApp.pylab_import_all = True # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This options can also be specified through the environment # variable IPYTHONDIR. # c.IPKernelApp.ipython_dir = u'/Users/sychan/.ipython' # ONLY USED ON WINDOWS Interrupt this process when the parent is signalled. # c.IPKernelApp.interrupt = 0 # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.IPKernelApp.copy_config_files = False # List of files to run at IPython startup. # c.IPKernelApp.exec_files = [] # Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet', # 'osx'). # c.IPKernelApp.gui = None # A list of dotted module names of IPython extensions to load. #c.IPKernelApp.extensions = [] # redirect stderr to the null device # c.IPKernelApp.no_stderr = False # The Logging format template # c.IPKernelApp.log_format = '[%(name)s] %(message)s' # set the iopub (PUB) port [default: random] # c.IPKernelApp.iopub_port = 0 #------------------------------------------------------------------------------ # ZMQInteractiveShell configuration #------------------------------------------------------------------------------ # A subclass of InteractiveShell for ZMQ. # ZMQInteractiveShell will inherit config from: InteractiveShell # Use colors for displaying information about objects. Because this information # is passed through a pager (like 'less'), and some pagers get confused with # color codes, this capability can be turned off. # c.ZMQInteractiveShell.color_info = True # # c.ZMQInteractiveShell.history_length = 10000 # Don't call post-execute functions that have failed in the past. # c.ZMQInteractiveShell.disable_failing_post_execute = False # Show rewritten input, e.g. for autocall. # c.ZMQInteractiveShell.show_rewritten_input = True # Set the color scheme (NoColor, Linux, or LightBG). # c.ZMQInteractiveShell.colors = 'LightBG' # # c.ZMQInteractiveShell.separate_in = '\n' # Deprecated, use PromptManager.in2_template # c.ZMQInteractiveShell.prompt_in2 = ' .\\D.: ' # # c.ZMQInteractiveShell.separate_out = '' # Deprecated, use PromptManager.in_template # c.ZMQInteractiveShell.prompt_in1 = 'In [\\#]: ' # Enable deep (recursive) reloading by default. IPython can use the deep_reload # module which reloads changes in modules recursively (it replaces the reload() # function, so you don't need to change anything to use it). deep_reload() # forces a full reload of modules whose code may have changed, which the default # reload() function does not. When deep_reload is off, IPython will use the # normal reload(), but deep_reload will still be available as dreload(). # c.ZMQInteractiveShell.deep_reload = False # Make IPython automatically call any callable object even if you didn't type # explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. # The value can be '0' to disable the feature, '1' for 'smart' autocall, where # it is not applied if there are no more arguments on the line, and '2' for # 'full' autocall, where all callable objects are automatically called (even if # no arguments are present). # c.ZMQInteractiveShell.autocall = 0 # # c.ZMQInteractiveShell.separate_out2 = '' # Deprecated, use PromptManager.justify # c.ZMQInteractiveShell.prompts_pad_left = True # # c.ZMQInteractiveShell.readline_parse_and_bind = ['tab: complete', '"\\C-l": clear-screen', 'set show-all-if-ambiguous on', '"\\C-o": tab-insert', '"\\C-r": reverse-search-history', '"\\C-s": forward-search-history', '"\\C-p": history-search-backward', '"\\C-n": history-search-forward', '"\\e[A": history-search-backward', '"\\e[B": history-search-forward', '"\\C-k": kill-line', '"\\C-u": unix-line-discard'] # Enable magic commands to be called without the leading %. # c.ZMQInteractiveShell.automagic = True # # c.ZMQInteractiveShell.debug = False # # c.ZMQInteractiveShell.object_info_string_level = 0 # # c.ZMQInteractiveShell.ipython_dir = '' # # c.ZMQInteractiveShell.readline_remove_delims = '-/~' # Start logging to the default log file. # c.ZMQInteractiveShell.logstart = False # The name of the logfile to use. # c.ZMQInteractiveShell.logfile = '' # # c.ZMQInteractiveShell.wildcards_case_sensitive = True # Save multi-line entries as one entry in readline history # c.ZMQInteractiveShell.multiline_history = True # Start logging to the given file in append mode. # c.ZMQInteractiveShell.logappend = '' # # c.ZMQInteractiveShell.xmode = 'Context' # # c.ZMQInteractiveShell.quiet = False # Deprecated, use PromptManager.out_template # c.ZMQInteractiveShell.prompt_out = 'Out[\\#]: ' # Set the size of the output cache. The default is 1000, you can change it # permanently in your config file. Setting it to 0 completely disables the # caching system, and the minimum value accepted is 20 (if you provide a value # less than 20, it is reset to 0 and a warning is issued). This limit is # defined because otherwise you'll spend more time re-flushing a too small cache # than working # c.ZMQInteractiveShell.cache_size = 1000 # 'all', 'last', 'last_expr' or 'none', specifying which nodes should be run # interactively (displaying output from expressions). # c.ZMQInteractiveShell.ast_node_interactivity = 'last_expr' # Automatically call the pdb debugger after every exception. # c.ZMQInteractiveShell.pdb = False #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = u'' #------------------------------------------------------------------------------ # Session configuration #------------------------------------------------------------------------------ # Object for handling serialization and sending of messages. # # The Session object handles building messages and sending them with ZMQ sockets # or ZMQStream objects. Objects can communicate with each other over the # network via Session objects, and only need to work with the dict-based IPython # message spec. The Session will handle serialization/deserialization, security, # and metadata. # # Sessions support configurable serialiization via packer/unpacker traits, and # signing with HMAC digests via the key/keyfile traits. # # Parameters ---------- # # debug : bool # whether to trigger extra debugging statements # packer/unpacker : str : 'json', 'pickle' or import_string # importstrings for methods to serialize message parts. If just # 'json' or 'pickle', predefined JSON and pickle packers will be used. # Otherwise, the entire importstring must be used. # # The functions must accept at least valid JSON input, and output *bytes*. # # For example, to use msgpack: # packer = 'msgpack.packb', unpacker='msgpack.unpackb' # pack/unpack : callables # You can also set the pack/unpack callables for serialization directly. # session : bytes # the ID of this Session object. The default is to generate a new UUID. # username : unicode # username added to message headers. The default is to ask the OS. # key : bytes # The key used to initialize an HMAC signature. If unset, messages # will not be signed or checked. # keyfile : filepath # The file containing a key. If this is set, `key` will be initialized # to the contents of the file. # Username for the Session. Default is your system username. # c.Session.username = 'sychan' # The name of the packer for serializing messages. Should be one of 'json', # 'pickle', or an import name for a custom callable serializer. # c.Session.packer = 'json' # The UUID identifying this session. # c.Session.session = u'' # execution key, for extra authentication. # c.Session.key = '' # Debug output in the Session # c.Session.debug = False # The name of the unpacker for unserializing messages. Only used with custom # functions for `packer`. # c.Session.unpacker = 'json' # path to file containing execution key. # c.Session.keyfile = '' #------------------------------------------------------------------------------ # InlineBackend configuration #------------------------------------------------------------------------------ # An object to store configuration of the inline backend. # The image format for figures with the inline backend. # c.InlineBackend.figure_format = 'png' # Close all figures at the end of each cell. # # When True, ensures that each cell starts with no active figures, but it also # means that one must keep track of references in order to edit or redraw # figures in subsequent cells. This mode is ideal for the notebook, where # residual plots from other cells might be surprising. # # When False, one must call figure() to create new figures. This means that # gcf() and getfigs() can reference figures created in other cells, and the # active figure can continue to be edited with pylab/pyplot methods that # reference the current active figure. This mode facilitates iterative editing # of figures, and behaves most consistently with other matplotlib backends, but # figure barriers between cells must be explicit. # c.InlineBackend.close_figures = True # Subset of matplotlib rcParams that should be different for the inline backend. # c.InlineBackend.rc = {'font.size': 10, 'savefig.dpi': 72, 'figure.figsize': (6.0, 4.0), 'figure.subplot.bottom': 0.125} #------------------------------------------------------------------------------ # MappingKernelManager configuration #------------------------------------------------------------------------------ # A KernelManager that handles notebok mapping and HTTP error handling # MappingKernelManager will inherit config from: MultiKernelManager # The max raw message size accepted from the browser over a WebSocket # connection. # c.MappingKernelManager.max_msg_size = 65536 # Kernel heartbeat interval in seconds. # c.MappingKernelManager.time_to_dead = 3.0 # The kernel manager class. This is configurable to allow subclassing of the # KernelManager for customized behavior. # c.MappingKernelManager.kernel_manager_class = 'IPython.zmq.blockingkernelmanager.BlockingKernelManager' # Delay (in seconds) before sending first heartbeat. # c.MappingKernelManager.first_beat = 5.0 #------------------------------------------------------------------------------ # NotebookManager configuration #------------------------------------------------------------------------------ # Automatically create a Python script when saving the notebook. # # For easier use of import, %run and %load across notebooks, a <notebook- # name>.py script will be created next to any <notebook-name>.ipynb on each # save. This can also be set with the short `--script` flag. # c.NotebookManager.save_script = False # The directory to use for notebooks. # c.NotebookManager.notebook_dir = u'/Users/sychan/src/kbase/dev_container/modules/narrative/src' #---------------------- # Tweaks for running notebook #---------------------- c.IPKernelApp.pylab = 'inline' # Do the monkeypatching after we have declared our configs. The monkeypatching code should be # checking for config directives that control what to patch. For example if # NotebookApp.kbase_auth = True then the monkeypatch code should patch all the notebook app # handlers to enforce and pass along kbase auth tokens monkeypatch.do_patching(c)
mit
shahankhatch/scikit-learn
examples/ensemble/plot_voting_decision_regions.py
230
2386
""" ================================================== Plot the decision boundaries of a VotingClassifier ================================================== Plot the decision boundaries of a `VotingClassifier` for two features of the Iris dataset. 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 (`DecisionTreeClassifier`, `KNeighborsClassifier`, and `SVC`) and used to initialize a soft-voting `VotingClassifier` with weights `[2, 1, 2]`, which means that the predicted probabilities of the `DecisionTreeClassifier` and `SVC` count 5 times as much as the weights of the `KNeighborsClassifier` classifier when the averaged probability is calculated. """ print(__doc__) from itertools import product import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.ensemble import VotingClassifier # Loading some example data iris = datasets.load_iris() X = iris.data[:, [0, 2]] y = iris.target # Training classifiers clf1 = DecisionTreeClassifier(max_depth=4) clf2 = KNeighborsClassifier(n_neighbors=7) clf3 = SVC(kernel='rbf', probability=True) eclf = VotingClassifier(estimators=[('dt', clf1), ('knn', clf2), ('svc', clf3)], voting='soft', weights=[2, 1, 2]) clf1.fit(X, y) clf2.fit(X, y) clf3.fit(X, y) eclf.fit(X, y) # Plotting decision regions x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8)) for idx, clf, tt in zip(product([0, 1], [0, 1]), [clf1, clf2, clf3, eclf], ['Decision Tree (depth=4)', 'KNN (k=7)', 'Kernel SVM', 'Soft Voting']): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4) axarr[idx[0], idx[1]].scatter(X[:, 0], X[:, 1], c=y, alpha=0.8) axarr[idx[0], idx[1]].set_title(tt) plt.show()
bsd-3-clause
Sentient07/scikit-learn
sklearn/linear_model/tests/test_sag.py
45
28228
# Authors: Danny Sullivan <[email protected]> # Tom Dupre la Tour <[email protected]> # # License: BSD 3 clause import math import numpy as np import scipy.sparse as sp from sklearn.linear_model.sag import get_auto_step_size from sklearn.linear_model.sag_fast import _multinomial_grad_loss_all_samples from sklearn.linear_model import LogisticRegression, Ridge from sklearn.linear_model.base import make_dataset from sklearn.linear_model.logistic import _multinomial_loss_grad from sklearn.utils.extmath import logsumexp from sklearn.utils.extmath import row_norms from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import ignore_warnings from sklearn.utils import compute_class_weight from sklearn.utils import check_random_state from sklearn.preprocessing import LabelEncoder, LabelBinarizer from sklearn.datasets import make_blobs, load_iris from sklearn.base import clone iris = load_iris() # this is used for sag classification def log_dloss(p, y): z = p * y # approximately equal and saves the computation of the log if z > 18.0: return math.exp(-z) * -y if z < -18.0: return -y return -y / (math.exp(z) + 1.0) def log_loss(p, y): return np.mean(np.log(1. + np.exp(-y * p))) # this is used for sag regression def squared_dloss(p, y): return p - y def squared_loss(p, y): return np.mean(0.5 * (p - y) * (p - y)) # function for measuring the log loss def get_pobj(w, alpha, myX, myy, loss): w = w.ravel() pred = np.dot(myX, w) p = loss(pred, myy) p += alpha * w.dot(w) / 2. return p def sag(X, y, step_size, alpha, n_iter=1, dloss=None, sparse=False, sample_weight=None, fit_intercept=True): n_samples, n_features = X.shape[0], X.shape[1] weights = np.zeros(X.shape[1]) sum_gradient = np.zeros(X.shape[1]) gradient_memory = np.zeros((n_samples, n_features)) intercept = 0.0 intercept_sum_gradient = 0.0 intercept_gradient_memory = np.zeros(n_samples) rng = np.random.RandomState(77) decay = 1.0 seen = set() # sparse data has a fixed decay of .01 if sparse: decay = .01 for epoch in range(n_iter): for k in range(n_samples): idx = int(rng.rand(1) * n_samples) # idx = k entry = X[idx] seen.add(idx) p = np.dot(entry, weights) + intercept gradient = dloss(p, y[idx]) if sample_weight is not None: gradient *= sample_weight[idx] update = entry * gradient + alpha * weights sum_gradient += update - gradient_memory[idx] gradient_memory[idx] = update if fit_intercept: intercept_sum_gradient += (gradient - intercept_gradient_memory[idx]) intercept_gradient_memory[idx] = gradient intercept -= (step_size * intercept_sum_gradient / len(seen) * decay) weights -= step_size * sum_gradient / len(seen) return weights, intercept def sag_sparse(X, y, step_size, alpha, n_iter=1, dloss=None, sample_weight=None, sparse=False, fit_intercept=True): if step_size * alpha == 1.: raise ZeroDivisionError("Sparse sag does not handle the case " "step_size * alpha == 1") n_samples, n_features = X.shape[0], X.shape[1] weights = np.zeros(n_features) sum_gradient = np.zeros(n_features) last_updated = np.zeros(n_features, dtype=np.int) gradient_memory = np.zeros(n_samples) rng = np.random.RandomState(77) intercept = 0.0 intercept_sum_gradient = 0.0 wscale = 1.0 decay = 1.0 seen = set() c_sum = np.zeros(n_iter * n_samples) # sparse data has a fixed decay of .01 if sparse: decay = .01 counter = 0 for epoch in range(n_iter): for k in range(n_samples): # idx = k idx = int(rng.rand(1) * n_samples) entry = X[idx] seen.add(idx) if counter >= 1: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= ((c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j]) last_updated[j] = counter p = (wscale * np.dot(entry, weights)) + intercept gradient = dloss(p, y[idx]) if sample_weight is not None: gradient *= sample_weight[idx] update = entry * gradient sum_gradient += update - (gradient_memory[idx] * entry) if fit_intercept: intercept_sum_gradient += gradient - gradient_memory[idx] intercept -= (step_size * intercept_sum_gradient / len(seen) * decay) gradient_memory[idx] = gradient wscale *= (1.0 - alpha * step_size) if counter == 0: c_sum[0] = step_size / (wscale * len(seen)) else: c_sum[counter] = (c_sum[counter - 1] + step_size / (wscale * len(seen))) if counter >= 1 and wscale < 1e-9: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter] * sum_gradient[j] else: weights[j] -= ((c_sum[counter] - c_sum[last_updated[j] - 1]) * sum_gradient[j]) last_updated[j] = counter + 1 c_sum[counter] = 0 weights *= wscale wscale = 1.0 counter += 1 for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= ((c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j]) weights *= wscale return weights, intercept def get_step_size(X, alpha, fit_intercept, classification=True): if classification: return (4.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + 4.0 * alpha)) else: return 1.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + alpha) @ignore_warnings def test_classifier_matching(): n_samples = 20 X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1) y[y == 0] = -1 alpha = 1.1 n_iter = 80 fit_intercept = True step_size = get_step_size(X, alpha, fit_intercept) clf = LogisticRegression(solver="sag", fit_intercept=fit_intercept, tol=1e-11, C=1. / alpha / n_samples, max_iter=n_iter, random_state=10) clf.fit(X, y) weights, intercept = sag_sparse(X, y, step_size, alpha, n_iter=n_iter, dloss=log_dloss, fit_intercept=fit_intercept) weights2, intercept2 = sag(X, y, step_size, alpha, n_iter=n_iter, dloss=log_dloss, fit_intercept=fit_intercept) weights = np.atleast_2d(weights) intercept = np.atleast_1d(intercept) weights2 = np.atleast_2d(weights2) intercept2 = np.atleast_1d(intercept2) assert_array_almost_equal(weights, clf.coef_, decimal=10) assert_array_almost_equal(intercept, clf.intercept_, decimal=10) assert_array_almost_equal(weights2, clf.coef_, decimal=10) assert_array_almost_equal(intercept2, clf.intercept_, decimal=10) @ignore_warnings def test_regressor_matching(): n_samples = 10 n_features = 5 rng = np.random.RandomState(10) X = rng.normal(size=(n_samples, n_features)) true_w = rng.normal(size=n_features) y = X.dot(true_w) alpha = 1. n_iter = 100 fit_intercept = True step_size = get_step_size(X, alpha, fit_intercept, classification=False) clf = Ridge(fit_intercept=fit_intercept, tol=.00000000001, solver='sag', alpha=alpha * n_samples, max_iter=n_iter) clf.fit(X, y) weights1, intercept1 = sag_sparse(X, y, step_size, alpha, n_iter=n_iter, dloss=squared_dloss, fit_intercept=fit_intercept) weights2, intercept2 = sag(X, y, step_size, alpha, n_iter=n_iter, dloss=squared_dloss, fit_intercept=fit_intercept) assert_array_almost_equal(weights1, clf.coef_, decimal=10) assert_array_almost_equal(intercept1, clf.intercept_, decimal=10) assert_array_almost_equal(weights2, clf.coef_, decimal=10) assert_array_almost_equal(intercept2, clf.intercept_, decimal=10) @ignore_warnings def test_sag_pobj_matches_logistic_regression(): """tests if the sag pobj matches log reg""" n_samples = 100 alpha = 1.0 max_iter = 20 X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1) clf1 = LogisticRegression(solver='sag', fit_intercept=False, tol=.0000001, C=1. / alpha / n_samples, max_iter=max_iter, random_state=10) clf2 = clone(clf1) clf3 = LogisticRegression(fit_intercept=False, tol=.0000001, C=1. / alpha / n_samples, max_iter=max_iter, random_state=10) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) clf3.fit(X, y) pobj1 = get_pobj(clf1.coef_, alpha, X, y, log_loss) pobj2 = get_pobj(clf2.coef_, alpha, X, y, log_loss) pobj3 = get_pobj(clf3.coef_, alpha, X, y, log_loss) assert_array_almost_equal(pobj1, pobj2, decimal=4) assert_array_almost_equal(pobj2, pobj3, decimal=4) assert_array_almost_equal(pobj3, pobj1, decimal=4) @ignore_warnings def test_sag_pobj_matches_ridge_regression(): """tests if the sag pobj matches ridge reg""" n_samples = 100 n_features = 10 alpha = 1.0 n_iter = 100 fit_intercept = False rng = np.random.RandomState(10) X = rng.normal(size=(n_samples, n_features)) true_w = rng.normal(size=n_features) y = X.dot(true_w) clf1 = Ridge(fit_intercept=fit_intercept, tol=.00000000001, solver='sag', alpha=alpha, max_iter=n_iter, random_state=42) clf2 = clone(clf1) clf3 = Ridge(fit_intercept=fit_intercept, tol=.00001, solver='lsqr', alpha=alpha, max_iter=n_iter, random_state=42) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) clf3.fit(X, y) pobj1 = get_pobj(clf1.coef_, alpha, X, y, squared_loss) pobj2 = get_pobj(clf2.coef_, alpha, X, y, squared_loss) pobj3 = get_pobj(clf3.coef_, alpha, X, y, squared_loss) assert_array_almost_equal(pobj1, pobj2, decimal=4) assert_array_almost_equal(pobj1, pobj3, decimal=4) assert_array_almost_equal(pobj3, pobj2, decimal=4) @ignore_warnings def test_sag_regressor_computed_correctly(): """tests if the sag regressor is computed correctly""" alpha = .1 n_features = 10 n_samples = 40 max_iter = 50 tol = .000001 fit_intercept = True rng = np.random.RandomState(0) X = rng.normal(size=(n_samples, n_features)) w = rng.normal(size=n_features) y = np.dot(X, w) + 2. step_size = get_step_size(X, alpha, fit_intercept, classification=False) clf1 = Ridge(fit_intercept=fit_intercept, tol=tol, solver='sag', alpha=alpha * n_samples, max_iter=max_iter) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) spweights1, spintercept1 = sag_sparse(X, y, step_size, alpha, n_iter=max_iter, dloss=squared_dloss, fit_intercept=fit_intercept) spweights2, spintercept2 = sag_sparse(X, y, step_size, alpha, n_iter=max_iter, dloss=squared_dloss, sparse=True, fit_intercept=fit_intercept) assert_array_almost_equal(clf1.coef_.ravel(), spweights1.ravel(), decimal=3) assert_almost_equal(clf1.intercept_, spintercept1, decimal=1) # TODO: uncomment when sparse Ridge with intercept will be fixed (#4710) #assert_array_almost_equal(clf2.coef_.ravel(), # spweights2.ravel(), # decimal=3) #assert_almost_equal(clf2.intercept_, spintercept2, decimal=1)''' @ignore_warnings def test_get_auto_step_size(): X = np.array([[1, 2, 3], [2, 3, 4], [2, 3, 2]], dtype=np.float64) alpha = 1.2 fit_intercept = False # sum the squares of the second sample because that's the largest max_squared_sum = 4 + 9 + 16 max_squared_sum_ = row_norms(X, squared=True).max() assert_almost_equal(max_squared_sum, max_squared_sum_, decimal=4) for fit_intercept in (True, False): step_size_sqr = 1.0 / (max_squared_sum + alpha + int(fit_intercept)) step_size_log = 4.0 / (max_squared_sum + 4.0 * alpha + int(fit_intercept)) step_size_sqr_ = get_auto_step_size(max_squared_sum_, alpha, "squared", fit_intercept) step_size_log_ = get_auto_step_size(max_squared_sum_, alpha, "log", fit_intercept) assert_almost_equal(step_size_sqr, step_size_sqr_, decimal=4) assert_almost_equal(step_size_log, step_size_log_, decimal=4) msg = 'Unknown loss function for SAG solver, got wrong instead of' assert_raise_message(ValueError, msg, get_auto_step_size, max_squared_sum_, alpha, "wrong", fit_intercept) @ignore_warnings def test_sag_regressor(): """tests if the sag regressor performs well""" xmin, xmax = -5, 5 n_samples = 20 tol = .001 max_iter = 20 alpha = 0.1 rng = np.random.RandomState(0) X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1) # simple linear function without noise y = 0.5 * X.ravel() clf1 = Ridge(tol=tol, solver='sag', max_iter=max_iter, alpha=alpha * n_samples) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) score1 = clf1.score(X, y) score2 = clf2.score(X, y) assert_greater(score1, 0.99) assert_greater(score2, 0.99) # simple linear function with noise y = 0.5 * X.ravel() + rng.randn(n_samples, 1).ravel() clf1 = Ridge(tol=tol, solver='sag', max_iter=max_iter, alpha=alpha * n_samples) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) score1 = clf1.score(X, y) score2 = clf2.score(X, y) score2 = clf2.score(X, y) assert_greater(score1, 0.5) assert_greater(score2, 0.5) @ignore_warnings def test_sag_classifier_computed_correctly(): """tests if the binary classifier is computed correctly""" alpha = .1 n_samples = 50 n_iter = 50 tol = .00001 fit_intercept = True X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1) step_size = get_step_size(X, alpha, fit_intercept, classification=True) classes = np.unique(y) y_tmp = np.ones(n_samples) y_tmp[y != classes[1]] = -1 y = y_tmp clf1 = LogisticRegression(solver='sag', C=1. / alpha / n_samples, max_iter=n_iter, tol=tol, random_state=77, fit_intercept=fit_intercept) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) spweights, spintercept = sag_sparse(X, y, step_size, alpha, n_iter=n_iter, dloss=log_dloss, fit_intercept=fit_intercept) spweights2, spintercept2 = sag_sparse(X, y, step_size, alpha, n_iter=n_iter, dloss=log_dloss, sparse=True, fit_intercept=fit_intercept) assert_array_almost_equal(clf1.coef_.ravel(), spweights.ravel(), decimal=2) assert_almost_equal(clf1.intercept_, spintercept, decimal=1) assert_array_almost_equal(clf2.coef_.ravel(), spweights2.ravel(), decimal=2) assert_almost_equal(clf2.intercept_, spintercept2, decimal=1) @ignore_warnings def test_sag_multiclass_computed_correctly(): """tests if the multiclass classifier is computed correctly""" alpha = .1 n_samples = 20 tol = .00001 max_iter = 40 fit_intercept = True X, y = make_blobs(n_samples=n_samples, centers=3, random_state=0, cluster_std=0.1) step_size = get_step_size(X, alpha, fit_intercept, classification=True) classes = np.unique(y) clf1 = LogisticRegression(solver='sag', C=1. / alpha / n_samples, max_iter=max_iter, tol=tol, random_state=77, fit_intercept=fit_intercept) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) coef1 = [] intercept1 = [] coef2 = [] intercept2 = [] for cl in classes: y_encoded = np.ones(n_samples) y_encoded[y != cl] = -1 spweights1, spintercept1 = sag_sparse(X, y_encoded, step_size, alpha, dloss=log_dloss, n_iter=max_iter, fit_intercept=fit_intercept) spweights2, spintercept2 = sag_sparse(X, y_encoded, step_size, alpha, dloss=log_dloss, n_iter=max_iter, sparse=True, fit_intercept=fit_intercept) coef1.append(spweights1) intercept1.append(spintercept1) coef2.append(spweights2) intercept2.append(spintercept2) coef1 = np.vstack(coef1) intercept1 = np.array(intercept1) coef2 = np.vstack(coef2) intercept2 = np.array(intercept2) for i, cl in enumerate(classes): assert_array_almost_equal(clf1.coef_[i].ravel(), coef1[i].ravel(), decimal=2) assert_almost_equal(clf1.intercept_[i], intercept1[i], decimal=1) assert_array_almost_equal(clf2.coef_[i].ravel(), coef2[i].ravel(), decimal=2) assert_almost_equal(clf2.intercept_[i], intercept2[i], decimal=1) @ignore_warnings def test_classifier_results(): """tests if classifier results match target""" alpha = .1 n_features = 20 n_samples = 10 tol = .01 max_iter = 200 rng = np.random.RandomState(0) X = rng.normal(size=(n_samples, n_features)) w = rng.normal(size=n_features) y = np.dot(X, w) y = np.sign(y) clf1 = LogisticRegression(solver='sag', C=1. / alpha / n_samples, max_iter=max_iter, tol=tol, random_state=77) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) pred1 = clf1.predict(X) pred2 = clf2.predict(X) assert_almost_equal(pred1, y, decimal=12) assert_almost_equal(pred2, y, decimal=12) @ignore_warnings def test_binary_classifier_class_weight(): """tests binary classifier with classweights for each class""" alpha = .1 n_samples = 50 n_iter = 20 tol = .00001 fit_intercept = True X, y = make_blobs(n_samples=n_samples, centers=2, random_state=10, cluster_std=0.1) step_size = get_step_size(X, alpha, fit_intercept, classification=True) classes = np.unique(y) y_tmp = np.ones(n_samples) y_tmp[y != classes[1]] = -1 y = y_tmp class_weight = {1: .45, -1: .55} clf1 = LogisticRegression(solver='sag', C=1. / alpha / n_samples, max_iter=n_iter, tol=tol, random_state=77, fit_intercept=fit_intercept, class_weight=class_weight) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) le = LabelEncoder() class_weight_ = compute_class_weight(class_weight, np.unique(y), y) sample_weight = class_weight_[le.fit_transform(y)] spweights, spintercept = sag_sparse(X, y, step_size, alpha, n_iter=n_iter, dloss=log_dloss, sample_weight=sample_weight, fit_intercept=fit_intercept) spweights2, spintercept2 = sag_sparse(X, y, step_size, alpha, n_iter=n_iter, dloss=log_dloss, sparse=True, sample_weight=sample_weight, fit_intercept=fit_intercept) assert_array_almost_equal(clf1.coef_.ravel(), spweights.ravel(), decimal=2) assert_almost_equal(clf1.intercept_, spintercept, decimal=1) assert_array_almost_equal(clf2.coef_.ravel(), spweights2.ravel(), decimal=2) assert_almost_equal(clf2.intercept_, spintercept2, decimal=1) @ignore_warnings def test_multiclass_classifier_class_weight(): """tests multiclass with classweights for each class""" alpha = .1 n_samples = 20 tol = .00001 max_iter = 50 class_weight = {0: .45, 1: .55, 2: .75} fit_intercept = True X, y = make_blobs(n_samples=n_samples, centers=3, random_state=0, cluster_std=0.1) step_size = get_step_size(X, alpha, fit_intercept, classification=True) classes = np.unique(y) clf1 = LogisticRegression(solver='sag', C=1. / alpha / n_samples, max_iter=max_iter, tol=tol, random_state=77, fit_intercept=fit_intercept, class_weight=class_weight) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) le = LabelEncoder() class_weight_ = compute_class_weight(class_weight, np.unique(y), y) sample_weight = class_weight_[le.fit_transform(y)] coef1 = [] intercept1 = [] coef2 = [] intercept2 = [] for cl in classes: y_encoded = np.ones(n_samples) y_encoded[y != cl] = -1 spweights1, spintercept1 = sag_sparse(X, y_encoded, step_size, alpha, n_iter=max_iter, dloss=log_dloss, sample_weight=sample_weight) spweights2, spintercept2 = sag_sparse(X, y_encoded, step_size, alpha, n_iter=max_iter, dloss=log_dloss, sample_weight=sample_weight, sparse=True) coef1.append(spweights1) intercept1.append(spintercept1) coef2.append(spweights2) intercept2.append(spintercept2) coef1 = np.vstack(coef1) intercept1 = np.array(intercept1) coef2 = np.vstack(coef2) intercept2 = np.array(intercept2) for i, cl in enumerate(classes): assert_array_almost_equal(clf1.coef_[i].ravel(), coef1[i].ravel(), decimal=2) assert_almost_equal(clf1.intercept_[i], intercept1[i], decimal=1) assert_array_almost_equal(clf2.coef_[i].ravel(), coef2[i].ravel(), decimal=2) assert_almost_equal(clf2.intercept_[i], intercept2[i], decimal=1) def test_classifier_single_class(): """tests if ValueError is thrown with only one class""" X = [[1, 2], [3, 4]] y = [1, 1] assert_raise_message(ValueError, "This solver needs samples of at least 2 classes " "in the data", LogisticRegression(solver='sag').fit, X, y) def test_step_size_alpha_error(): X = [[0, 0], [0, 0]] y = [1, -1] fit_intercept = False alpha = 1. msg = ("Current sag implementation does not handle the case" " step_size * alpha_scaled == 1") clf1 = LogisticRegression(solver='sag', C=1. / alpha, fit_intercept=fit_intercept) assert_raise_message(ZeroDivisionError, msg, clf1.fit, X, y) clf2 = Ridge(fit_intercept=fit_intercept, solver='sag', alpha=alpha) assert_raise_message(ZeroDivisionError, msg, clf2.fit, X, y) def test_multinomial_loss(): # test if the multinomial loss and gradient computations are consistent X, y = iris.data, iris.target.astype(np.float64) n_samples, n_features = X.shape n_classes = len(np.unique(y)) rng = check_random_state(42) weights = rng.randn(n_features, n_classes) intercept = rng.randn(n_classes) sample_weights = rng.randn(n_samples) np.abs(sample_weights, sample_weights) # compute loss and gradient like in multinomial SAG dataset, _ = make_dataset(X, y, sample_weights, random_state=42) loss_1, grad_1 = _multinomial_grad_loss_all_samples(dataset, weights, intercept, n_samples, n_features, n_classes) # compute loss and gradient like in multinomial LogisticRegression lbin = LabelBinarizer() Y_bin = lbin.fit_transform(y) weights_intercept = np.vstack((weights, intercept)).T.ravel() loss_2, grad_2, _ = _multinomial_loss_grad(weights_intercept, X, Y_bin, 0.0, sample_weights) grad_2 = grad_2.reshape(n_classes, -1) grad_2 = grad_2[:, :-1].T # comparison assert_array_almost_equal(grad_1, grad_2) assert_almost_equal(loss_1, loss_2) def test_multinomial_loss_ground_truth(): # n_samples, n_features, n_classes = 4, 2, 3 n_classes = 3 X = np.array([[1.1, 2.2], [2.2, -4.4], [3.3, -2.2], [1.1, 1.1]]) y = np.array([0, 1, 2, 0]) lbin = LabelBinarizer() Y_bin = lbin.fit_transform(y) weights = np.array([[0.1, 0.2, 0.3], [1.1, 1.2, -1.3]]) intercept = np.array([1., 0, -.2]) sample_weights = np.array([0.8, 1, 1, 0.8]) prediction = np.dot(X, weights) + intercept logsumexp_prediction = logsumexp(prediction, axis=1) p = prediction - logsumexp_prediction[:, np.newaxis] loss_1 = -(sample_weights[:, np.newaxis] * p * Y_bin).sum() diff = sample_weights[:, np.newaxis] * (np.exp(p) - Y_bin) grad_1 = np.dot(X.T, diff) weights_intercept = np.vstack((weights, intercept)).T.ravel() loss_2, grad_2, _ = _multinomial_loss_grad(weights_intercept, X, Y_bin, 0.0, sample_weights) grad_2 = grad_2.reshape(n_classes, -1) grad_2 = grad_2[:, :-1].T assert_almost_equal(loss_1, loss_2) assert_array_almost_equal(grad_1, grad_2) # ground truth loss_gt = 11.680360354325961 grad_gt = np.array([[-0.557487, -1.619151, +2.176638], [-0.903942, +5.258745, -4.354803]]) assert_almost_equal(loss_1, loss_gt) assert_array_almost_equal(grad_1, grad_gt)
bsd-3-clause
dimatura/pydisp
pydisp/pydisp.py
1
5469
# -*- coding: utf-8 -*- import cStringIO as StringIO import base64 import json import uuid import os from PIL import Image import matplotlib as mpl import matplotlib.cm as cm import numpy as np import requests __all__ = ['image', 'dyplot', 'send', 'text', 'pylab', 'pane', 'b64_encode', 'is_valid_image_mime_type', 'CONFIG', ] VALID_IMAGE_MIME_TYPES = {'png','gif','bmp','webp','jpeg'} class CONFIG(object): PORT = 8000 HOSTNAME = 'localhost' @staticmethod def load_config(): # TODO what is the right way (TM) fname = os.path.join(os.environ['HOME'], '.display', 'config.json') if os.path.exists(fname): with open(fname, 'r') as f: cfg = json.load(f) CONFIG.PORT = int(cfg['port']) CONFIG.HOSTNAME = cfg['hostname'] @staticmethod def display_url(): return "http://{:s}:{:d}/events".format(CONFIG.HOSTNAME, CONFIG.PORT) CONFIG.load_config() def send(**command): """ send command to server """ command = json.dumps(command) headers = {'Content-Type': 'application/text'} req = requests.post(CONFIG.display_url(), headers=headers, data=command.encode('ascii')) resp = req.content return resp is not None def uid(): """ return a unique id for a pane """ return 'pane_{}'.format(uuid.uuid4()) def pane(panetype, win, title, content): """ create a pane (formerly window) """ if win is None: win = uid() send(command='pane', type=panetype, id=win, title=title, content=content) return win def is_valid_image_mime_type(mt): return mt in VALID_IMAGE_MIME_TYPES def scalar_preprocess(img, **kwargs): """ vmin, vmax, clip, cmap """ vmin = kwargs.get('vmin') vmax = kwargs.get('vmax') clip = kwargs.get('clip') cmap = kwargs.get('cmap', 'jet') # TODO customization normalizer = mpl.colors.Normalize(vmin, vmax, clip) nimg = normalizer(img) cmap = cm.get_cmap(cmap) cimg = cmap(nimg)[:, :, :3] # ignore alpha simg = (255*cimg).astype(np.uint8) return simg def rgb_preprocess(img): if np.issubdtype(img.dtype, np.float): # assuming 0., 1. range return (img*255).clip(0, 255).astype(np.uint8) if not img.dtype == np.uint8: raise ValueError('only uint8 or float for 3-channel images') return img def img_encode(img, encoding): # ret, data = cv2.imencode('.'+encoding, img) if encoding=='jpg': encoding = 'jpeg' buf = StringIO.StringIO() Image.fromarray(img).save(buf, format=encoding) data = buf.getvalue() buf.close() return data def b64_encode(data, encoding): b64data = ('data:image/{};base64,{}' .format(encoding, base64.b64encode(data).decode('ascii'))) return b64data def pylab(fig, **kwargs): """ Display a matplotlib figure. """ # save figure to buffer output = StringIO.StringIO() fig.savefig(output, format='png') data = output.getvalue() output.close() encoded = b64_encode(data, 'png') pydisp.pane('image', win=kwargs.get('win'), title=kwargs.get('title'), content={ 'src': encoded, 'width': kwargs.get('width'), }) return win def image(img, **kwargs): """ Display image encoded as an array. image(img, [win, title, labels, width, kwargs]) to_bgr: swap blue and red channels (default False) encoding: 'jpg' (default) or 'png' kwargs is argument for scalar preprocessing """ to_bgr = kwargs.get('to_bgr', False) if img.ndim not in (2, 3): raise ValueError('image should be 2 (gray) or 3 (rgb) dimensional') assert img.ndim == 2 or img.ndim == 3 if img.ndim == 3: img = rgb_preprocess(img) else: img = scalar_preprocess(img, **kwargs) if to_bgr: img = img[...,[2, 1, 0]] encoding = kwargs.get('encoding', 'jpg') data = img_encode(img, encoding) encoded = b64_encode(data, encoding) return pane('image', kwargs.get('win'), kwargs.get('title'), content={ 'src': encoded, 'labels': kwargs.get('labels'), 'width': kwargs.get('width'), }) def text(txt, **kwargs): win = kwargs.get('win') or uid() title = kwargs.get('title') or 'text' return pane('text', win, title, content=txt) def dyplot(data, **kwargs): """ Plot data as line chart with dygraph Params: data: either a 2-d numpy array or a list of lists. win: pane id labels: list of series names, first series is always the X-axis see http://dygraphs.com/options.html for other supported options """ win = kwargs.get('win') or uid() dataset = {} if type(data).__module__ == np.__name__: dataset = data.tolist() else: dataset = data # clone kwargs into options options = dict(kwargs) options['file'] = dataset if options.get('labels'): options['xlabel'] = options['labels'][0] # Don't pass our options to dygraphs. options.pop('win', None) return pane('plot', kwargs.get('win'), kwargs.get('title'), content=options)
mit
mtustin-handy/airflow
airflow/hooks/presto_hook.py
37
2626
from builtins import str from pyhive import presto from pyhive.exc import DatabaseError from airflow.hooks.dbapi_hook import DbApiHook import logging logging.getLogger("pyhive").setLevel(logging.INFO) class PrestoException(Exception): pass class PrestoHook(DbApiHook): """ Interact with Presto through PyHive! >>> ph = PrestoHook() >>> sql = "SELECT count(1) AS num FROM airflow.static_babynames" >>> ph.get_records(sql) [[340698]] """ conn_name_attr = 'presto_conn_id' default_conn_name = 'presto_default' def get_conn(self): """Returns a connection object""" db = self.get_connection(self.presto_conn_id) return presto.connect( host=db.host, port=db.port, username=db.login, catalog=db.extra_dejson.get('catalog', 'hive'), schema=db.schema) @staticmethod def _strip_sql(sql): return sql.strip().rstrip(';') def get_records(self, hql, parameters=None): """ Get a set of records from Presto """ try: return super(PrestoHook, self).get_records( self._strip_sql(hql), parameters) except DatabaseError as e: obj = eval(str(e)) raise PrestoException(obj['message']) def get_first(self, hql, parameters=None): """ Returns only the first row, regardless of how many rows the query returns. """ try: return super(PrestoHook, self).get_first( self._strip_sql(hql), parameters) except DatabaseError as e: obj = eval(str(e)) raise PrestoException(obj['message']) def get_pandas_df(self, hql, parameters=None): """ Get a pandas dataframe from a sql query. """ import pandas cursor = self.get_cursor() cursor.execute(self._strip_sql(hql), parameters) try: data = cursor.fetchall() except DatabaseError as e: obj = eval(str(e)) raise PrestoException(obj['message']) column_descriptions = cursor.description if data: df = pandas.DataFrame(data) df.columns = [c[0] for c in column_descriptions] else: df = pandas.DataFrame() return df def run(self, hql, parameters=None): """ Execute the statement against Presto. Can be used to create views. """ return super(PrestoHook, self).run(self._strip_sql(hql), parameters) def insert_rows(self): raise NotImplemented()
apache-2.0
juanyaw/PTVS
Python/Product/Analyzer/BuiltinScraperTests.py
18
18954
# ############################################################################ # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # [email protected]. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ########################################################################### import re import unittest from pprint import pformat from BuiltinScraper import parse_doc_str, BUILTIN, __builtins__, get_overloads_from_doc_string, TOKENS_REGEX try: unicode except NameError: from BuiltinScraper import unicode import sys class Test_BuiltinScraperTests(unittest.TestCase): def check_doc_str(self, doc, module_name, func_name, expected, mod=None, extra_args=[], obj_class=None): r = parse_doc_str(doc, module_name, mod, func_name, extra_args, obj_class) # Quick pass if everything matches if r == expected: return msg = 'Expected:\n%s\nActual\n%s' % (pformat(expected), pformat(r)) self.assertEqual(len(r), len(expected), msg) def check_dict(e, a, indent): if e == a: return missing_keys = set(e.keys()) - set(a.keys()) extra_keys = set(a.keys()) - set(e.keys()) mismatched_keys = [k for k in set(a.keys()) & set(e.keys()) if a[k] != e[k]] if missing_keys: print('%sDid not received following keys: %s' % (indent, ', '.join(missing_keys))) if extra_keys: print('%sDid not expect following keys: %s' % (indent, ', '.join(extra_keys))) for k in mismatched_keys: if isinstance(e[k], dict) and isinstance(a[k], dict): check_dict(e[k], a[k], indent + ' ') elif (isinstance(e[k], tuple) and isinstance(a[k], tuple) or isinstance(e[k], list) and isinstance(a[k], list)): check_seq(e[k], a[k], indent + ' ') else: print('%sExpected "%s": "%s"' % (indent, k, e[k])) print('%sActual "%s": "%s"' % (indent, k, a[k])) print('') def check_seq(e, a, indent): if e == a: return for i, (e2, a2) in enumerate(zip(e, a)): if isinstance(e2, dict) and isinstance(a2, dict): check_dict(e2, a2, indent + ' ') elif (isinstance(e2, tuple) and isinstance(a2, tuple) or isinstance(e2, list) and isinstance(a2, list)): check_seq(e2, a2, indent + ' ') elif e1 != a1: print('%sExpected "%s"' % (indent, e2)) print('%sActual "%s"' % (indent, a2)) print('') for e1, a1 in zip(expected, r): check_dict(e1, a1, '') self.fail(msg) def test_regex(self): self.assertSequenceEqual( [i.strip() for i in re.split(TOKENS_REGEX, 'f(\'\', \'a\', \'a\\\'b\', "", "a", "a\\\"b")') if i.strip()], ['f', '(', "''", ',', "'a'", ',', "'a\\'b'", ',', '""', ',', '"a"', ',', '"a\\"b"', ')'] ) self.assertSequenceEqual( [i.strip() for i in re.split(TOKENS_REGEX, 'f(1, 1., -1, -1.)') if i.strip()], ['f', '(', '1', ',', '1.', ',', '-1', ',', '-1.', ')'] ) self.assertSequenceEqual( [i.strip() for i in re.split(TOKENS_REGEX, 'f(a, *a, **a, ...)') if i.strip()], ['f', '(', 'a', ',', '*', 'a', ',', '**', 'a', ',', '...', ')'] ) self.assertSequenceEqual( [i.strip() for i in re.split(TOKENS_REGEX, 'f(a:123, a=123) --> => ->') if i.strip()], ['f', '(', 'a', ':', '123', ',', 'a', '=', '123', ')', '-->', '=>', '->'] ) def test_numpy_1(self): self.check_doc_str( """arange([start,] stop[, step,], dtype=None) Returns ------- out : ndarray""", 'numpy', 'arange', [{ 'doc': 'Returns\n -------\n out : ndarray', 'ret_type': [('', 'ndarray')], 'args': ( {'name': 'start', 'default_value':'None'}, {'name': 'stop'}, {'name': 'step', 'default_value': 'None'}, {'name': 'dtype', 'default_value':'None'}, ) }] ) def test_numpy_2(self): self.check_doc_str( """arange([start,] stop[, step,], dtype=None) Return - out : ndarray""", 'numpy', 'arange', [{ 'doc': 'Return - out : ndarray', 'ret_type': [('', 'ndarray')], 'args': ( {'name': 'start', 'default_value':'None'}, {'name': 'stop'}, {'name': 'step', 'default_value': 'None'}, {'name': 'dtype', 'default_value':'None'}, ) }] ) def test_reduce(self): self.check_doc_str( 'reduce(function, sequence[, initial]) -> value', BUILTIN, 'reduce', mod=__builtins__, expected = [{ 'args': ( {'name': 'function'}, {'name': 'sequence'}, {'default_value': 'None', 'name': 'initial'} ), 'doc': '', 'ret_type': [('', 'value')] }] ) def test_pygame_draw_arc(self): self.check_doc_str( 'pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect', 'draw', 'arc', [{ 'args': ( {'name': 'Surface'}, {'name': 'color'}, {'name': 'Rect'}, {'name': 'start_angle'}, {'name': 'stop_angle'}, {'default_value': '1', 'name': 'width'} ), 'doc': '', 'ret_type': [('', 'Rect')] }] ) def test_isdigit(self): self.check_doc_str( '''B.isdigit() -> bool Return True if all characters in B are digits and there is at least one character in B, False otherwise.''', 'bytes', 'isdigit', [{ 'args': (), 'doc': 'Return True if all characters in B are digits\nand there is at least one character in B, False otherwise.', 'ret_type': [(BUILTIN, 'bool')] }] ) def test_init(self): self.check_doc_str( 'x.__init__(...) initializes x; see help(type(x)) for signature', 'str', '__init__', [{'args': ({'arg_format': '*', 'name': 'args'},), 'doc': 'initializes x; see help(type(x)) for signature'}] ) def test_find(self): self.check_doc_str( 'S.find(sub [,start [,end]]) -> int', 'str', 'find', [{ 'args': ( {'name': 'sub'}, {'default_value': 'None', 'name': 'start'}, {'default_value': 'None', 'name': 'end'} ), 'doc': '', 'ret_type': [(BUILTIN, 'int')] }] ) def test_format(self): self.check_doc_str( 'S.format(*args, **kwargs) -> unicode', 'str', 'format', [{ 'args': ( {'arg_format': '*', 'name': 'args'}, {'arg_format': '**', 'name': 'kwargs'} ), 'doc': '', 'ret_type': [(BUILTIN, unicode.__name__)] }] ) def test_ascii(self): self.check_doc_str( "'ascii(object) -> string\n\nReturn the same as repr(). In Python 3.x, the repr() result will\\ncontain printable characters unescaped, while the ascii() result\\nwill have such characters backslash-escaped.'", 'future_builtins', 'ascii', [{ 'args': ({'name': 'object'},), 'doc': "Return the same as repr(). In Python 3.x, the repr() result will\\ncontain printable characters unescaped, while the ascii() result\\nwill have such characters backslash-escaped.'", 'ret_type': [(BUILTIN, 'str')] }] ) def test_preannotation(self): self.check_doc_str( 'f(INT class_code) => SpaceID', 'fob', 'f', [{ 'args': ({'name': 'class_code', 'type': [(BUILTIN, 'int')]},), 'doc': '', 'ret_type': [('', 'SpaceID')] }]) def test_compress(self): self.check_doc_str( 'compress(data, selectors) --> iterator over selected data\n\nReturn data elements', 'itertools', 'compress', [{ 'args': ({'name': 'data'}, {'name': 'selectors'}), 'doc': 'Return data elements', 'ret_type': [('', 'iterator')] }] ) def test_isinstance(self): self.check_doc_str( 'isinstance(object, class-or-type-or-tuple) -> bool\n\nReturn whether an object is an ' 'instance of a class or of a subclass thereof.\nWith a type as second argument, ' 'return whether that is the object\'s type.\nThe form using a tuple, isinstance(x, (A, B, ...)),' ' is a shortcut for\nisinstance(x, A) or isinstance(x, B) or ... (etc.).', BUILTIN, 'isinstance', [{ 'args': ({'name': 'object'}, {'name': 'class-or-type-or-tuple'}), 'doc': "Return whether an object is an instance of a class or of a subclass thereof.\n" "With a type as second argument, return whether that is the object's type.\n" "The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n" "isinstance(x, A) or isinstance(x, B) or ... (etc.).", 'ret_type': [(BUILTIN, 'bool')] }] ) def test_tuple_parameters(self): self.check_doc_str( 'pygame.Rect(left, top, width, height): return Rect\n' 'pygame.Rect((left, top), (width, height)): return Rect\n' 'pygame.Rect(object): return Rect\n' 'pygame object for storing rectangular coordinates', 'pygame', 'Rect', [{ 'args': ({'name': 'left'}, {'name': 'top'}, {'name': 'width'}, {'name': 'height'}), 'doc': 'pygame object for storing rectangular coordinates', 'ret_type': [('', 'Rect')] }, { 'args': ({'name': 'left, top'}, {'name': 'width, height'}), 'doc': 'pygame object for storing rectangular coordinates', 'ret_type': [('', 'Rect')] }, { 'args': ({'name': 'object'},), 'doc': 'pygame object for storing rectangular coordinates', 'ret_type': [('', 'Rect')] }] ) def test_read(self): self.check_doc_str( 'read([size]) -> read at most size bytes, returned as a string.\n\n' 'If the size argument is negative or omitted, read until EOF is reached.\n' 'Notice that when in non-blocking mode, less data than what was requested\n' 'may be returned, even if no size parameter was given.', BUILTIN, 'read', mod=__builtins__, expected=[{ 'args': ({'default_value': 'None', 'name': 'size'},), 'doc': 'read at most size bytes, returned as a string.\n\nIf the size argument is negative or omitted, read until EOF is reached.\nNotice that when in non-blocking mode, less data than what was requested\nmay be returned, even if no size parameter was given.', 'ret_type': [('', '')] }] ) r = get_overloads_from_doc_string( 'read([size]) -> read at most size bytes, returned as a string.\n\n' 'If the size argument is negative or omitted, read until EOF is reached.\n' 'Notice that when in non-blocking mode, less data than what was requested\n' 'may be returned, even if no size parameter was given.', __builtins__, None, 'read' ) self.assertEqual( r, [{ 'args': ({'default_value': 'None', 'name': 'size'},), 'doc': 'read at most size bytes, returned as a string.\n\nIf the size argument is negative or omitted, read until EOF is reached.\nNotice that when in non-blocking mode, less data than what was requested\nmay be returned, even if no size parameter was given.', 'ret_type': [('', '')] }], repr(r) ) def test_new(self): self.check_doc_str( 'T.__new__(S, ...) -> a new object with type S, a subtype of T', 'struct', '__new__', [{ 'ret_type': [('', '')], 'doc': 'a new object with type S, a subtype of T', 'args': ({'name': 'S'}, {'arg_format': '*', 'name': 'args'}) }] ) def test_C_prototype(self): self.check_doc_str( 'GetDriverByName(char const * name) -> Driver', '', 'GetDriverByName', [{ 'ret_type': [('', 'Driver')], 'doc': '', 'args': ({'name': 'name', 'type': [(BUILTIN, 'str')]},), }] ) def test_chmod(self): self.check_doc_str( 'chmod(path, mode, *, dir_fd=None, follow_symlinks=True)', 'nt', 'chmod', [{ 'doc': '', 'args': ( {'name': 'path'}, {'name': 'mode'}, {'name': 'args', 'arg_format': '*'}, {'name': 'dir_fd', 'default_value': 'None'}, {'name': 'follow_symlinks', 'default_value': 'True'} ) }] ) def test_open(self): if sys.version_info[0] >= 3: expect_ret_type = ('_io', '_IOBase') else: expect_ret_type = (BUILTIN, 'file') self.check_doc_str( 'open(file, mode=\'r\', buffering=-1, encoding=None,\n' + ' errors=None, newline=None, closefd=True, opener=None)' + ' -> file object\n\nOpen file', BUILTIN, 'open', [{ 'doc': 'Open file', 'ret_type': [expect_ret_type], 'args': ( {'name': 'file'}, {'name': 'mode', 'default_value': "'r'"}, {'name': 'buffering', 'default_value': '-1'}, {'name': 'encoding', 'default_value': 'None'}, {'name': 'errors', 'default_value': 'None'}, {'name': 'newline', 'default_value': 'None'}, {'name': 'closefd', 'default_value': 'True'}, {'name': 'opener', 'default_value': 'None'}, ) }] ) def test_optional_with_default(self): self.check_doc_str( 'max(iterable[, key=func]) -> value', BUILTIN, 'max', [{ 'doc': '', 'ret_type': [('', 'value')], 'args': ( {'name': 'iterable'}, {'name': 'key', 'default_value': 'func'} ) }] ) def test_pyplot_figure(self): pyplot_doc = """ Creates a new figure. Parameters ---------- num : integer or string, optional, default: none If not provided, a new figure will be created, and a the figure number will be increamted. The figure objects holds this number in a `number` attribute. If num is provided, and a figure with this id already exists, make it active, and returns a reference to it. If this figure does not exists, create it and returns it. If num is a string, the window title will be set to this figure's `num`. figsize : tuple of integers, optional, default : None width, height in inches. If not provided, defaults to rc figure.figsize. dpi : integer, optional, default ; None resolution of the figure. If not provided, defaults to rc figure.dpi. facecolor : the background color; If not provided, defaults to rc figure.facecolor edgecolor : the border color. If not provided, defaults to rc figure.edgecolor Returns ------- figure : Figure The Figure instance returned will also be passed to new_figure_manager in the backends, which allows to hook custom Figure classes into the pylab interface. Additional kwargs will be passed to the figure init function. Note ---- If you are creating many figures, make sure you explicitly call "close" on the figures you are not using, because this will enable pylab to properly clean up the memory. rcParams defines the default values, which can be modified in the matplotlibrc file """ self.check_doc_str( pyplot_doc, 'matplotlib.pyplot', 'figure', [{ 'doc': pyplot_doc, 'ret_type': [('', 'Figure')], 'args': ( {'name': 'args', 'arg_format': '*'}, {'name': 'kwargs', 'arg_format': '**'} ) }] ) if __name__ == '__main__': unittest.main()
apache-2.0
davidrobles/mlnd-capstone-code
capstone/datasets/ucic4.py
1
1524
from __future__ import division, unicode_literals import pandas as pd from capstone.game.games import Connect4 as C4 def load_dataframe(): ''' Returns a Pandas Dataframe of the UCI Connect 4 dataset https://archive.ics.uci.edu/ml/machine-learning-databases/connect-4/connect-4.names ''' def column_name(i): if i == 42: return 'outcome' row = chr(ord('a') + (i // C4.ROWS)) col = (i % C4.ROWS) + 1 return '{row}{col}'.format(row=row, col=col) column_names = [column_name(i) for i in range(43)] return pd.read_csv('datasets/uci_c4.csv', header=None, names=column_names) def series_to_game(series): '''Converts a Pandas Series to a Connect 4 game''' cell_map = {'x': 'X', 'o': 'O', 'b': '-'} board = [[' '] * C4.COLS for row in range(C4.ROWS)] cells = series.iloc[:-1] outcome = series.iloc[-1] for ix, cell in enumerate(cells): row = C4.ROWS - (ix % C4.ROWS) - 1 col = ix // C4.ROWS board[row][col] = cell_map[cell] return C4(board), outcome _df = load_dataframe() def get_random_game(outcome=None): if outcome: sample_df = _df.loc[_df['outcome'] == outcome].sample() else: sample_df = _df.sample() row = sample_df.iloc[0] game, _ = series_to_game(row) return game def get_random_win_game(): return get_random_game('win') def get_random_loss_game(): return get_random_game('loss') def get_random_draw_game(): return get_random_game('draw')
mit
XueqingLin/tensorflow
tensorflow/examples/skflow/mnist.py
8
3167
# 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. """This showcases how simple it is to build image classification networks. It follows description from this TensorFlow tutorial: https://www.tensorflow.org/versions/master/tutorials/mnist/pros/index.html#deep-mnist-for-experts """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from sklearn import metrics import tensorflow as tf from tensorflow.contrib import learn ### Download and load MNIST data. mnist = learn.datasets.load_dataset('mnist') ### Linear classifier. feature_columns = learn.infer_real_valued_columns_from_input(mnist.train.images) classifier = learn.LinearClassifier( feature_columns=feature_columns, n_classes=10) classifier.fit(mnist.train.images, mnist.train.labels, batch_size=100, steps=1000) score = metrics.accuracy_score( mnist.test.labels, classifier.predict(mnist.test.images)) print('Accuracy: {0:f}'.format(score)) ### Convolutional network def max_pool_2x2(tensor_in): return tf.nn.max_pool( tensor_in, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def conv_model(X, y): # pylint: disable=invalid-name,missing-docstring # reshape X to 4d tensor with 2nd and 3rd dimensions being image width and # height final dimension being the number of color channels. X = tf.reshape(X, [-1, 28, 28, 1]) # first conv layer will compute 32 features for each 5x5 patch with tf.variable_scope('conv_layer1'): h_conv1 = learn.ops.conv2d(X, n_filters=32, filter_shape=[5, 5], bias=True, activation=tf.nn.relu) h_pool1 = max_pool_2x2(h_conv1) # second conv layer will compute 64 features for each 5x5 patch. with tf.variable_scope('conv_layer2'): h_conv2 = learn.ops.conv2d(h_pool1, n_filters=64, filter_shape=[5, 5], bias=True, activation=tf.nn.relu) h_pool2 = max_pool_2x2(h_conv2) # reshape tensor into a batch of vectors h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) # densely connected layer with 1024 neurons. h_fc1 = learn.ops.dnn( h_pool2_flat, [1024], activation=tf.nn.relu, dropout=0.5) return learn.models.logistic_regression(h_fc1, y) # Training and predicting. classifier = learn.TensorFlowEstimator( model_fn=conv_model, n_classes=10, batch_size=100, steps=20000, learning_rate=0.001) classifier.fit(mnist.train.images, mnist.train.labels) score = metrics.accuracy_score( mnist.test.labels, classifier.predict(mnist.test.images)) print('Accuracy: {0:f}'.format(score))
apache-2.0
MrNuggelz/sklearn-glvq
setup.py
1
1432
from __future__ import print_function import sys from setuptools import setup with open('requirements.txt') as f: INSTALL_REQUIRES = [l.strip() for l in f.readlines() if l] try: import numpy except ImportError: print('numpy is required during installation') sys.exit(1) try: import scipy except ImportError: print('scipy is required during installation') sys.exit(1) CLASSIFIERS = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Operating System :: POSIX', 'Operating System :: MacOS', 'Operating System :: Unix', 'Operating System :: Microsoft :: Windows', ] version = '1.1.0' setup(name='sklearn-lvq', version=version, description='sklearn compatible Generalized Learning Vector ' 'Quantization and Robust Soft Learning Vector Quantization implementation', author='Joris Jensen', url='https://github.com/MrNuggelz/sklearn-lvq', download_url='https://github.com/MrNuggelz/sklearn-lvq/releases/tag/{}'.format(version), tests_require=['nose'], platforms=['any'], license='BSD-3-Clause', packages=['sklearn_lvq'], install_requires=INSTALL_REQUIRES, author_email='[email protected]', classifiers=CLASSIFIERS, )
bsd-3-clause
musically-ut/numpy
numpy/core/tests/test_multiarray.py
5
220057
from __future__ import division, absolute_import, print_function import collections import tempfile import sys import os import shutil import warnings import operator import io import itertools if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins from decimal import Decimal import numpy as np from nose import SkipTest from numpy.core import * from numpy.compat import asbytes, getexception, strchar, sixu from test_print import in_foreign_locale from numpy.core.multiarray_tests import ( test_neighborhood_iterator, test_neighborhood_iterator_oob, test_pydatamem_seteventhook_start, test_pydatamem_seteventhook_end, test_inplace_increment, get_buffer_info, test_as_c_array ) from numpy.testing import ( TestCase, run_module_suite, assert_, assert_raises, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_allclose, assert_array_less, runstring, dec ) # Need to test an object that does not fully implement math interface from datetime import timedelta if sys.version_info[:2] > (3, 2): # In Python 3.3 the representation of empty shape, strides and suboffsets # is an empty tuple instead of None. # http://docs.python.org/dev/whatsnew/3.3.html#api-changes EMPTY = () else: EMPTY = None class TestFlags(TestCase): def setUp(self): self.a = arange(10) def test_writeable(self): mydict = locals() self.a.flags.writeable = False self.assertRaises(ValueError, runstring, 'self.a[0] = 3', mydict) self.assertRaises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict) self.a.flags.writeable = True self.a[0] = 5 self.a[0] = 0 def test_otherflags(self): assert_equal(self.a.flags.carray, True) assert_equal(self.a.flags.farray, False) assert_equal(self.a.flags.behaved, True) assert_equal(self.a.flags.fnc, False) assert_equal(self.a.flags.forc, True) assert_equal(self.a.flags.owndata, True) assert_equal(self.a.flags.writeable, True) assert_equal(self.a.flags.aligned, True) assert_equal(self.a.flags.updateifcopy, False) def test_string_align(self): a = np.zeros(4, dtype=np.dtype('|S4')) assert_(a.flags.aligned) # not power of two are accessed bytewise and thus considered aligned a = np.zeros(5, dtype=np.dtype('|S4')) assert_(a.flags.aligned) def test_void_align(self): a = np.zeros(4, dtype=np.dtype([("a", "i4"), ("b", "i4")])) assert_(a.flags.aligned) class TestHash(TestCase): # see #3793 def test_int(self): for st, ut, s in [(np.int8, np.uint8, 8), (np.int16, np.uint16, 16), (np.int32, np.uint32, 32), (np.int64, np.uint64, 64)]: for i in range(1, s): assert_equal(hash(st(-2**i)), hash(-2**i), err_msg="%r: -2**%d" % (st, i)) assert_equal(hash(st(2**(i - 1))), hash(2**(i - 1)), err_msg="%r: 2**%d" % (st, i - 1)) assert_equal(hash(st(2**i - 1)), hash(2**i - 1), err_msg="%r: 2**%d - 1" % (st, i)) i = max(i - 1, 1) assert_equal(hash(ut(2**(i - 1))), hash(2**(i - 1)), err_msg="%r: 2**%d" % (ut, i - 1)) assert_equal(hash(ut(2**i - 1)), hash(2**i - 1), err_msg="%r: 2**%d - 1" % (ut, i)) class TestAttributes(TestCase): def setUp(self): self.one = arange(10) self.two = arange(20).reshape(4, 5) self.three = arange(60, dtype=float64).reshape(2, 5, 6) def test_attributes(self): assert_equal(self.one.shape, (10,)) assert_equal(self.two.shape, (4, 5)) assert_equal(self.three.shape, (2, 5, 6)) self.three.shape = (10, 3, 2) assert_equal(self.three.shape, (10, 3, 2)) self.three.shape = (2, 5, 6) assert_equal(self.one.strides, (self.one.itemsize,)) num = self.two.itemsize assert_equal(self.two.strides, (5*num, num)) num = self.three.itemsize assert_equal(self.three.strides, (30*num, 6*num, num)) assert_equal(self.one.ndim, 1) assert_equal(self.two.ndim, 2) assert_equal(self.three.ndim, 3) num = self.two.itemsize assert_equal(self.two.size, 20) assert_equal(self.two.nbytes, 20*num) assert_equal(self.two.itemsize, self.two.dtype.itemsize) assert_equal(self.two.base, arange(20)) def test_dtypeattr(self): assert_equal(self.one.dtype, dtype(int_)) assert_equal(self.three.dtype, dtype(float_)) assert_equal(self.one.dtype.char, 'l') assert_equal(self.three.dtype.char, 'd') self.assertTrue(self.three.dtype.str[0] in '<>') assert_equal(self.one.dtype.str[1], 'i') assert_equal(self.three.dtype.str[1], 'f') def test_int_subclassing(self): # Regression test for https://github.com/numpy/numpy/pull/3526 numpy_int = np.int_(0) if sys.version_info[0] >= 3: # On Py3k int_ should not inherit from int, because it's not fixed-width anymore assert_equal(isinstance(numpy_int, int), False) else: # Otherwise, it should inherit from int... assert_equal(isinstance(numpy_int, int), True) # ... and fast-path checks on C-API level should also work from numpy.core.multiarray_tests import test_int_subclass assert_equal(test_int_subclass(numpy_int), True) def test_stridesattr(self): x = self.one def make_array(size, offset, strides): return ndarray(size, buffer=x, dtype=int, offset=offset*x.itemsize, strides=strides*x.itemsize) assert_equal(make_array(4, 4, -1), array([4, 3, 2, 1])) self.assertRaises(ValueError, make_array, 4, 4, -2) self.assertRaises(ValueError, make_array, 4, 2, -1) self.assertRaises(ValueError, make_array, 8, 3, 1) assert_equal(make_array(8, 3, 0), np.array([3]*8)) # Check behavior reported in gh-2503: self.assertRaises(ValueError, make_array, (2, 3), 5, array([-2, -3])) make_array(0, 0, 10) def test_set_stridesattr(self): x = self.one def make_array(size, offset, strides): try: r = ndarray([size], dtype=int, buffer=x, offset=offset*x.itemsize) except: raise RuntimeError(getexception()) r.strides = strides=strides*x.itemsize return r assert_equal(make_array(4, 4, -1), array([4, 3, 2, 1])) assert_equal(make_array(7, 3, 1), array([3, 4, 5, 6, 7, 8, 9])) self.assertRaises(ValueError, make_array, 4, 4, -2) self.assertRaises(ValueError, make_array, 4, 2, -1) self.assertRaises(RuntimeError, make_array, 8, 3, 1) # Check that the true extent of the array is used. # Test relies on as_strided base not exposing a buffer. x = np.lib.stride_tricks.as_strided(arange(1), (10, 10), (0, 0)) def set_strides(arr, strides): arr.strides = strides self.assertRaises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize)) # Test for offset calculations: x = np.lib.stride_tricks.as_strided(np.arange(10, dtype=np.int8)[-1], shape=(10,), strides=(-1,)) self.assertRaises(ValueError, set_strides, x[::-1], -1) a = x[::-1] a.strides = 1 a[::2].strides = 2 def test_fill(self): for t in "?bhilqpBHILQPfdgFDGO": x = empty((3, 2, 1), t) y = empty((3, 2, 1), t) x.fill(1) y[...] = 1 assert_equal(x, y) def test_fill_max_uint64(self): x = empty((3, 2, 1), dtype=uint64) y = empty((3, 2, 1), dtype=uint64) value = 2**64 - 1 y[...] = value x.fill(value) assert_array_equal(x, y) def test_fill_struct_array(self): # Filling from a scalar x = array([(0, 0.0), (1, 1.0)], dtype='i4,f8') x.fill(x[0]) assert_equal(x['f1'][1], x['f1'][0]) # Filling from a tuple that can be converted # to a scalar x = np.zeros(2, dtype=[('a', 'f8'), ('b', 'i4')]) x.fill((3.5, -2)) assert_array_equal(x['a'], [3.5, 3.5]) assert_array_equal(x['b'], [-2, -2]) class TestArrayConstruction(TestCase): def test_array(self): d = np.ones(6) r = np.array([d, d]) assert_equal(r, np.ones((2, 6))) d = np.ones(6) tgt = np.ones((2, 6)) r = np.array([d, d]) assert_equal(r, tgt) tgt[1] = 2 r = np.array([d, d + 1]) assert_equal(r, tgt) d = np.ones(6) r = np.array([[d, d]]) assert_equal(r, np.ones((1, 2, 6))) d = np.ones(6) r = np.array([[d, d], [d, d]]) assert_equal(r, np.ones((2, 2, 6))) d = np.ones((6, 6)) r = np.array([d, d]) assert_equal(r, np.ones((2, 6, 6))) d = np.ones((6, )) r = np.array([[d, d + 1], d + 2]) assert_equal(len(r), 2) assert_equal(r[0], [d, d + 1]) assert_equal(r[1], d + 2) tgt = np.ones((2, 3), dtype=np.bool) tgt[0, 2] = False tgt[1, 0:2] = False r = np.array([[True, True, False], [False, False, True]]) assert_equal(r, tgt) r = np.array([[True, False], [True, False], [False, True]]) assert_equal(r, tgt.T) def test_array_empty(self): assert_raises(TypeError, np.array) def test_array_copy_false(self): d = np.array([1, 2, 3]) e = np.array(d, copy=False) d[1] = 3 assert_array_equal(e, [1, 3, 3]) e = np.array(d, copy=False, order='F') d[1] = 4 assert_array_equal(e, [1, 4, 3]) e[2] = 7 assert_array_equal(d, [1, 4, 7]) def test_array_copy_true(self): d = np.array([[1,2,3], [1, 2, 3]]) e = np.array(d, copy=True) d[0, 1] = 3 e[0, 2] = -7 assert_array_equal(e, [[1, 2, -7], [1, 2, 3]]) assert_array_equal(d, [[1, 3, 3], [1, 2, 3]]) e = np.array(d, copy=True, order='F') d[0, 1] = 5 e[0, 2] = 7 assert_array_equal(e, [[1, 3, 7], [1, 2, 3]]) assert_array_equal(d, [[1, 5, 3], [1,2,3]]) def test_array_cont(self): d = np.ones(10)[::2] assert_(np.ascontiguousarray(d).flags.c_contiguous) assert_(np.ascontiguousarray(d).flags.f_contiguous) assert_(np.asfortranarray(d).flags.c_contiguous) assert_(np.asfortranarray(d).flags.f_contiguous) d = np.ones((10, 10))[::2,::2] assert_(np.ascontiguousarray(d).flags.c_contiguous) assert_(np.asfortranarray(d).flags.f_contiguous) class TestAssignment(TestCase): def test_assignment_broadcasting(self): a = np.arange(6).reshape(2, 3) # Broadcasting the input to the output a[...] = np.arange(3) assert_equal(a, [[0, 1, 2], [0, 1, 2]]) a[...] = np.arange(2).reshape(2, 1) assert_equal(a, [[0, 0, 0], [1, 1, 1]]) # For compatibility with <= 1.5, a limited version of broadcasting # the output to the input. # # This behavior is inconsistent with NumPy broadcasting # in general, because it only uses one of the two broadcasting # rules (adding a new "1" dimension to the left of the shape), # applied to the output instead of an input. In NumPy 2.0, this kind # of broadcasting assignment will likely be disallowed. a[...] = np.arange(6)[::-1].reshape(1, 2, 3) assert_equal(a, [[5, 4, 3], [2, 1, 0]]) # The other type of broadcasting would require a reduction operation. def assign(a, b): a[...] = b assert_raises(ValueError, assign, a, np.arange(12).reshape(2, 2, 3)) def test_assignment_errors(self): # Address issue #2276 class C: pass a = np.zeros(1) def assign(v): a[0] = v assert_raises((AttributeError, TypeError), assign, C()) assert_raises(ValueError, assign, [1]) class TestDtypedescr(TestCase): def test_construction(self): d1 = dtype('i4') assert_equal(d1, dtype(int32)) d2 = dtype('f8') assert_equal(d2, dtype(float64)) def test_byteorders(self): self.assertNotEqual(dtype('<i4'), dtype('>i4')) self.assertNotEqual(dtype([('a', '<i4')]), dtype([('a', '>i4')])) class TestZeroRank(TestCase): def setUp(self): self.d = array(0), array('x', object) def test_ellipsis_subscript(self): a, b = self.d self.assertEqual(a[...], 0) self.assertEqual(b[...], 'x') self.assertTrue(a[...].base is a) # `a[...] is a` in numpy <1.9. self.assertTrue(b[...].base is b) # `b[...] is b` in numpy <1.9. def test_empty_subscript(self): a, b = self.d self.assertEqual(a[()], 0) self.assertEqual(b[()], 'x') self.assertTrue(type(a[()]) is a.dtype.type) self.assertTrue(type(b[()]) is str) def test_invalid_subscript(self): a, b = self.d self.assertRaises(IndexError, lambda x: x[0], a) self.assertRaises(IndexError, lambda x: x[0], b) self.assertRaises(IndexError, lambda x: x[array([], int)], a) self.assertRaises(IndexError, lambda x: x[array([], int)], b) def test_ellipsis_subscript_assignment(self): a, b = self.d a[...] = 42 self.assertEqual(a, 42) b[...] = '' self.assertEqual(b.item(), '') def test_empty_subscript_assignment(self): a, b = self.d a[()] = 42 self.assertEqual(a, 42) b[()] = '' self.assertEqual(b.item(), '') def test_invalid_subscript_assignment(self): a, b = self.d def assign(x, i, v): x[i] = v self.assertRaises(IndexError, assign, a, 0, 42) self.assertRaises(IndexError, assign, b, 0, '') self.assertRaises(ValueError, assign, a, (), '') def test_newaxis(self): a, b = self.d self.assertEqual(a[newaxis].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ..., newaxis].shape, (1, 1)) self.assertEqual(a[..., newaxis, newaxis].shape, (1, 1)) self.assertEqual(a[newaxis, newaxis, ...].shape, (1, 1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): a, b = self.d def subscript(x, i): x[i] self.assertRaises(IndexError, subscript, a, (newaxis, 0)) self.assertRaises(IndexError, subscript, a, (newaxis,)*50) def test_constructor(self): x = ndarray(()) x[()] = 5 self.assertEqual(x[()], 5) y = ndarray((), buffer=x) y[()] = 6 self.assertEqual(x[()], 6) def test_output(self): x = array(2) self.assertRaises(ValueError, add, x, [1], x) class TestScalarIndexing(TestCase): def setUp(self): self.d = array([0, 1])[0] def test_ellipsis_subscript(self): a = self.d self.assertEqual(a[...], 0) self.assertEqual(a[...].shape, ()) def test_empty_subscript(self): a = self.d self.assertEqual(a[()], 0) self.assertEqual(a[()].shape, ()) def test_invalid_subscript(self): a = self.d self.assertRaises(IndexError, lambda x: x[0], a) self.assertRaises(IndexError, lambda x: x[array([], int)], a) def test_invalid_subscript_assignment(self): a = self.d def assign(x, i, v): x[i] = v self.assertRaises(TypeError, assign, a, 0, 42) def test_newaxis(self): a = self.d self.assertEqual(a[newaxis].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ..., newaxis].shape, (1, 1)) self.assertEqual(a[..., newaxis, newaxis].shape, (1, 1)) self.assertEqual(a[newaxis, newaxis, ...].shape, (1, 1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): a = self.d def subscript(x, i): x[i] self.assertRaises(IndexError, subscript, a, (newaxis, 0)) self.assertRaises(IndexError, subscript, a, (newaxis,)*50) def test_overlapping_assignment(self): # With positive strides a = np.arange(4) a[:-1] = a[1:] assert_equal(a, [1, 2, 3, 3]) a = np.arange(4) a[1:] = a[:-1] assert_equal(a, [0, 0, 1, 2]) # With positive and negative strides a = np.arange(4) a[:] = a[::-1] assert_equal(a, [3, 2, 1, 0]) a = np.arange(6).reshape(2, 3) a[::-1,:] = a[:, ::-1] assert_equal(a, [[5, 4, 3], [2, 1, 0]]) a = np.arange(6).reshape(2, 3) a[::-1, ::-1] = a[:, ::-1] assert_equal(a, [[3, 4, 5], [0, 1, 2]]) # With just one element overlapping a = np.arange(5) a[:3] = a[2:] assert_equal(a, [2, 3, 4, 3, 4]) a = np.arange(5) a[2:] = a[:3] assert_equal(a, [0, 1, 0, 1, 2]) a = np.arange(5) a[2::-1] = a[2:] assert_equal(a, [4, 3, 2, 3, 4]) a = np.arange(5) a[2:] = a[2::-1] assert_equal(a, [0, 1, 2, 1, 0]) a = np.arange(5) a[2::-1] = a[:1:-1] assert_equal(a, [2, 3, 4, 3, 4]) a = np.arange(5) a[:1:-1] = a[2::-1] assert_equal(a, [0, 1, 0, 1, 2]) class TestCreation(TestCase): def test_from_attribute(self): class x(object): def __array__(self, dtype=None): pass self.assertRaises(ValueError, array, x()) def test_from_string(self) : types = np.typecodes['AllInteger'] + np.typecodes['Float'] nstr = ['123', '123'] result = array([123, 123], dtype=int) for type in types : msg = 'String conversion for %s' % type assert_equal(array(nstr, dtype=type), result, err_msg=msg) def test_void(self): arr = np.array([], dtype='V') assert_equal(arr.dtype.kind, 'V') def test_zeros(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] for dt in types: d = np.zeros((13,), dtype=dt) assert_equal(np.count_nonzero(d), 0) # true for ieee floats assert_equal(d.sum(), 0) assert_(not d.any()) d = np.zeros(2, dtype='(2,4)i4') assert_equal(np.count_nonzero(d), 0) assert_equal(d.sum(), 0) assert_(not d.any()) d = np.zeros(2, dtype='4i4') assert_equal(np.count_nonzero(d), 0) assert_equal(d.sum(), 0) assert_(not d.any()) d = np.zeros(2, dtype='(2,4)i4, (2,4)i4') assert_equal(np.count_nonzero(d), 0) @dec.slow def test_zeros_big(self): # test big array as they might be allocated different by the sytem types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] for dt in types: d = np.zeros((30 * 1024**2,), dtype=dt) assert_(not d.any()) def test_zeros_obj(self): # test initialization from PyLong(0) d = np.zeros((13,), dtype=object) assert_array_equal(d, [0] * 13) assert_equal(np.count_nonzero(d), 0) def test_zeros_obj_obj(self): d = zeros(10, dtype=[('k', object, 2)]) assert_array_equal(d['k'], 0) def test_zeros_like_like_zeros(self): # test zeros_like returns the same as zeros for c in np.typecodes['All']: if c == 'V': continue d = zeros((3,3), dtype=c) assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) # explicitly check some special cases d = zeros((3,3), dtype='S5') assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) d = zeros((3,3), dtype='U5') assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) d = zeros((3,3), dtype='<i4') assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) d = zeros((3,3), dtype='>i4') assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) d = zeros((3,3), dtype='<M8[s]') assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) d = zeros((3,3), dtype='>M8[s]') assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) d = zeros((3,3), dtype='f4,f4') assert_array_equal(zeros_like(d), d) assert_equal(zeros_like(d).dtype, d.dtype) def test_empty_unicode(self): # don't throw decode errors on garbage memory for i in range(5, 100, 5): d = np.empty(i, dtype='U') str(d) def test_sequence_non_homogenous(self): assert_equal(np.array([4, 2**80]).dtype, np.object) assert_equal(np.array([4, 2**80, 4]).dtype, np.object) assert_equal(np.array([2**80, 4]).dtype, np.object) assert_equal(np.array([2**80] * 3).dtype, np.object) assert_equal(np.array([[1, 1],[1j, 1j]]).dtype, np.complex) assert_equal(np.array([[1j, 1j],[1, 1]]).dtype, np.complex) assert_equal(np.array([[1, 1, 1],[1, 1j, 1.], [1, 1, 1]]).dtype, np.complex) @dec.skipif(sys.version_info[0] >= 3) def test_sequence_long(self): assert_equal(np.array([long(4), long(4)]).dtype, np.long) assert_equal(np.array([long(4), 2**80]).dtype, np.object) assert_equal(np.array([long(4), 2**80, long(4)]).dtype, np.object) assert_equal(np.array([2**80, long(4)]).dtype, np.object) def test_non_sequence_sequence(self): """Should not segfault. Class Fail breaks the sequence protocol for new style classes, i.e., those derived from object. Class Map is a mapping type indicated by raising a ValueError. At some point we may raise a warning instead of an error in the Fail case. """ class Fail(object): def __len__(self): return 1 def __getitem__(self, index): raise ValueError() class Map(object): def __len__(self): return 1 def __getitem__(self, index): raise KeyError() a = np.array([Map()]) assert_(a.shape == (1,)) assert_(a.dtype == np.dtype(object)) assert_raises(ValueError, np.array, [Fail()]) def test_no_len_object_type(self): # gh-5100, want object array from iterable object without len() class Point2: def __init__(self): pass def __getitem__(self, ind): if ind in [0, 1]: return ind else: raise IndexError() d = np.array([Point2(), Point2(), Point2()]) assert_equal(d.dtype, np.dtype(object)) class TestStructured(TestCase): def test_subarray_field_access(self): a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))]) a['a'] = np.arange(60).reshape(3, 5, 2, 2) # Since the subarray is always in C-order, a transpose # does not swap the subarray: assert_array_equal(a.T['a'], a['a'].transpose(1, 0, 2, 3)) # In Fortran order, the subarray gets appended # like in all other cases, not prepended as a special case b = a.copy(order='F') assert_equal(a['a'].shape, b['a'].shape) assert_equal(a.T['a'].shape, a.T.copy()['a'].shape) def test_subarray_comparison(self): # Check that comparisons between record arrays with # multi-dimensional field types work properly a = np.rec.fromrecords( [([1, 2, 3], 'a', [[1, 2], [3, 4]]), ([3, 3, 3], 'b', [[0, 0], [0, 0]])], dtype=[('a', ('f4', 3)), ('b', np.object), ('c', ('i4', (2, 2)))]) b = a.copy() assert_equal(a==b, [True, True]) assert_equal(a!=b, [False, False]) b[1].b = 'c' assert_equal(a==b, [True, False]) assert_equal(a!=b, [False, True]) for i in range(3): b[0].a = a[0].a b[0].a[i] = 5 assert_equal(a==b, [False, False]) assert_equal(a!=b, [True, True]) for i in range(2): for j in range(2): b = a.copy() b[0].c[i, j] = 10 assert_equal(a==b, [False, True]) assert_equal(a!=b, [True, False]) # Check that broadcasting with a subarray works a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8')]) b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8')]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8', (1,))]) b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8', (1,))]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))]) b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that broadcasting Fortran-style arrays with a subarray work a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))], order='F') b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that incompatible sub-array shapes don't result to broadcasting x = np.zeros((1,), dtype=[('a', ('f4', (1, 2))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) # This comparison invokes deprecated behaviour, and will probably # start raising an error eventually. What we really care about in this # test is just that it doesn't return True. with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) assert_equal(x == y, False) x = np.zeros((1,), dtype=[('a', ('f4', (2, 1))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) # This comparison invokes deprecated behaviour, and will probably # start raising an error eventually. What we really care about in this # test is just that it doesn't return True. with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) assert_equal(x == y, False) # Check that structured arrays that are different only in # byte-order work a = np.array([(5, 42), (10, 1)], dtype=[('a', '>i8'), ('b', '<f8')]) b = np.array([(5, 43), (10, 1)], dtype=[('a', '<i8'), ('b', '>f8')]) assert_equal(a == b, [False, True]) def test_casting(self): # Check that casting a structured array to change its byte order # works a = np.array([(1,)], dtype=[('a', '<i4')]) assert_(np.can_cast(a.dtype, [('a', '>i4')], casting='unsafe')) b = a.astype([('a', '>i4')]) assert_equal(b, a.byteswap().newbyteorder()) assert_equal(a['a'][0], b['a'][0]) # Check that equality comparison works on structured arrays if # they are 'equiv'-castable a = np.array([(5, 42), (10, 1)], dtype=[('a', '>i4'), ('b', '<f8')]) b = np.array([(42, 5), (1, 10)], dtype=[('b', '>f8'), ('a', '<i4')]) assert_(np.can_cast(a.dtype, b.dtype, casting='equiv')) assert_equal(a == b, [True, True]) # Check that 'equiv' casting can reorder fields and change byte # order assert_(np.can_cast(a.dtype, b.dtype, casting='equiv')) c = a.astype(b.dtype, casting='equiv') assert_equal(a == c, [True, True]) # Check that 'safe' casting can change byte order and up-cast # fields t = [('a', '<i8'), ('b', '>f8')] assert_(np.can_cast(a.dtype, t, casting='safe')) c = a.astype(t, casting='safe') assert_equal((c == np.array([(5, 42), (10, 1)], dtype=t)), [True, True]) # Check that 'same_kind' casting can change byte order and # change field widths within a "kind" t = [('a', '<i4'), ('b', '>f4')] assert_(np.can_cast(a.dtype, t, casting='same_kind')) c = a.astype(t, casting='same_kind') assert_equal((c == np.array([(5, 42), (10, 1)], dtype=t)), [True, True]) # Check that casting fails if the casting rule should fail on # any of the fields t = [('a', '>i8'), ('b', '<f4')] assert_(not np.can_cast(a.dtype, t, casting='safe')) assert_raises(TypeError, a.astype, t, casting='safe') t = [('a', '>i2'), ('b', '<f8')] assert_(not np.can_cast(a.dtype, t, casting='equiv')) assert_raises(TypeError, a.astype, t, casting='equiv') t = [('a', '>i8'), ('b', '<i2')] assert_(not np.can_cast(a.dtype, t, casting='same_kind')) assert_raises(TypeError, a.astype, t, casting='same_kind') assert_(not np.can_cast(a.dtype, b.dtype, casting='no')) assert_raises(TypeError, a.astype, b.dtype, casting='no') # Check that non-'unsafe' casting can't change the set of field names for casting in ['no', 'safe', 'equiv', 'same_kind']: t = [('a', '>i4')] assert_(not np.can_cast(a.dtype, t, casting=casting)) t = [('a', '>i4'), ('b', '<f8'), ('c', 'i4')] assert_(not np.can_cast(a.dtype, t, casting=casting)) def test_objview(self): # https://github.com/numpy/numpy/issues/3286 a = np.array([], dtype=[('a', 'f'), ('b', 'f'), ('c', 'O')]) a[['a', 'b']] # TypeError? # https://github.com/numpy/numpy/issues/3253 dat2 = np.zeros(3, [('A', 'i'), ('B', '|O')]) new2 = dat2[['B', 'A']] # TypeError? def test_setfield(self): # https://github.com/numpy/numpy/issues/3126 struct_dt = np.dtype([('elem', 'i4', 5),]) dt = np.dtype([('field', 'i4', 10),('struct', struct_dt)]) x = np.zeros(1, dt) x[0]['field'] = np.ones(10, dtype='i4') x[0]['struct'] = np.ones(1, dtype=struct_dt) assert_equal(x[0]['field'], np.ones(10, dtype='i4')) def test_setfield_object(self): # make sure object field assignment with ndarray value # on void scalar mimics setitem behavior b = np.zeros(1, dtype=[('x', 'O')]) # next line should work identically to b['x'][0] = np.arange(3) b[0]['x'] = np.arange(3) assert_equal(b[0]['x'], np.arange(3)) #check that broadcasting check still works c = np.zeros(1, dtype=[('x', 'O', 5)]) def testassign(): c[0]['x'] = np.arange(3) assert_raises(ValueError, testassign) class TestBool(TestCase): def test_test_interning(self): a0 = bool_(0) b0 = bool_(False) self.assertTrue(a0 is b0) a1 = bool_(1) b1 = bool_(True) self.assertTrue(a1 is b1) self.assertTrue(array([True])[0] is a1) self.assertTrue(array(True)[()] is a1) def test_sum(self): d = np.ones(101, dtype=np.bool); assert_equal(d.sum(), d.size) assert_equal(d[::2].sum(), d[::2].size) assert_equal(d[::-2].sum(), d[::-2].size) d = np.frombuffer(b'\xff\xff' * 100, dtype=bool) assert_equal(d.sum(), d.size) assert_equal(d[::2].sum(), d[::2].size) assert_equal(d[::-2].sum(), d[::-2].size) def check_count_nonzero(self, power, length): powers = [2 ** i for i in range(length)] for i in range(2**power): l = [(i & x) != 0 for x in powers] a = np.array(l, dtype=np.bool) c = builtins.sum(l) self.assertEqual(np.count_nonzero(a), c) av = a.view(np.uint8) av *= 3 self.assertEqual(np.count_nonzero(a), c) av *= 4 self.assertEqual(np.count_nonzero(a), c) av[av != 0] = 0xFF self.assertEqual(np.count_nonzero(a), c) def test_count_nonzero(self): # check all 12 bit combinations in a length 17 array # covers most cases of the 16 byte unrolled code self.check_count_nonzero(12, 17) @dec.slow def test_count_nonzero_all(self): # check all combinations in a length 17 array # covers all cases of the 16 byte unrolled code self.check_count_nonzero(17, 17) def test_count_nonzero_unaligned(self): # prevent mistakes as e.g. gh-4060 for o in range(7): a = np.zeros((18,), dtype=np.bool)[o+1:] a[:o] = True self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist())) a = np.ones((18,), dtype=np.bool)[o+1:] a[:o] = False self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist())) class TestMethods(TestCase): def test_round(self): def check_round(arr, expected, *round_args): assert_equal(arr.round(*round_args), expected) # With output array out = np.zeros_like(arr) res = arr.round(*round_args, out=out) assert_equal(out, expected) assert_equal(out, res) check_round(array([1.2, 1.5]), [1, 2]) check_round(array(1.5), 2) check_round(array([12.2, 15.5]), [10, 20], -1) check_round(array([12.15, 15.51]), [12.2, 15.5], 1) # Complex rounding check_round(array([4.5 + 1.5j]), [4 + 2j]) check_round(array([12.5 + 15.5j]), [10 + 20j], -1) def test_transpose(self): a = array([[1, 2], [3, 4]]) assert_equal(a.transpose(), [[1, 3], [2, 4]]) self.assertRaises(ValueError, lambda: a.transpose(0)) self.assertRaises(ValueError, lambda: a.transpose(0, 0)) self.assertRaises(ValueError, lambda: a.transpose(0, 1, 2)) def test_sort(self): # test ordering for floats and complex containing nans. It is only # necessary to check the lessthan comparison, so sorts that # only follow the insertion sort path are sufficient. We only # test doubles and complex doubles as the logic is the same. # check doubles msg = "Test real sort order with nans" a = np.array([np.nan, 1, 0]) b = sort(a) assert_equal(b, a[::-1], msg) # check complex msg = "Test complex sort order with nans" a = np.zeros(9, dtype=np.complex128) a.real += [np.nan, np.nan, np.nan, 1, 0, 1, 1, 0, 0] a.imag += [np.nan, 1, 0, np.nan, np.nan, 1, 0, 1, 0] b = sort(a) assert_equal(b, a[::-1], msg) # all c scalar sorts use the same code with different types # so it suffices to run a quick check with one type. The number # of sorted items must be greater than ~50 to check the actual # algorithm because quick and merge sort fall over to insertion # sort for small arrays. a = np.arange(101) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "scalar sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test complex sorts. These use the same code as the scalars # but the compare function differs. ai = a*1j + 1 bi = b*1j + 1 for kind in ['q', 'm', 'h'] : msg = "complex sort, real part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) c = bi.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) ai = a + 1j bi = b + 1j for kind in ['q', 'm', 'h'] : msg = "complex sort, imag part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) c = bi.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) # test sorting of complex arrays requiring byte-swapping, gh-5441 for endianess in '<>': for dt in np.typecodes['Complex']: dtype = '{0}{1}'.format(endianess, dt) arr = np.array([1+3.j, 2+2.j, 3+1.j], dtype=dt) c = arr.copy() c.sort() msg = 'byte-swapped complex sort, dtype={0}'.format(dt) assert_equal(c, arr, msg) # test string sorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)]) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "string sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test unicode sorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "unicode sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test object array sorts. a = np.empty((101,), dtype=np.object) a[:] = list(range(101)) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test record array sorts. dt = np.dtype([('f', float), ('i', int)]) a = array([(i, i) for i in range(101)], dtype = dt) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test datetime64 sorts. a = np.arange(0, 101, dtype='datetime64[D]') b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "datetime64 sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test timedelta64 sorts. a = np.arange(0, 101, dtype='timedelta64[D]') b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "timedelta64 sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # check axis handling. This should be the same for all type # specific sorts, so we only check it for one type and one kind a = np.array([[3, 2], [1, 0]]) b = np.array([[1, 0], [3, 2]]) c = np.array([[2, 3], [0, 1]]) d = a.copy() d.sort(axis=0) assert_equal(d, b, "test sort with axis=0") d = a.copy() d.sort(axis=1) assert_equal(d, c, "test sort with axis=1") d = a.copy() d.sort() assert_equal(d, c, "test sort with default axis") # check axis handling for multidimensional empty arrays a = np.array([]) a.shape = (3, 2, 1, 0) for axis in range(-a.ndim, a.ndim): msg = 'test empty array sort with axis={0}'.format(axis) assert_equal(np.sort(a, axis=axis), a, msg) msg = 'test empty array sort with axis=None' assert_equal(np.sort(a, axis=None), a.ravel(), msg) def test_copy(self): def assert_fortran(arr): assert_(arr.flags.fortran) assert_(arr.flags.f_contiguous) assert_(not arr.flags.c_contiguous) def assert_c(arr): assert_(not arr.flags.fortran) assert_(not arr.flags.f_contiguous) assert_(arr.flags.c_contiguous) a = np.empty((2, 2), order='F') # Test copying a Fortran array assert_c(a.copy()) assert_c(a.copy('C')) assert_fortran(a.copy('F')) assert_fortran(a.copy('A')) # Now test starting with a C array. a = np.empty((2, 2), order='C') assert_c(a.copy()) assert_c(a.copy('C')) assert_fortran(a.copy('F')) assert_c(a.copy('A')) def test_sort_order(self): # Test sorting an array with fields x1=np.array([21, 32, 14]) x2=np.array(['my', 'first', 'name']) x3=np.array([3.1, 4.5, 6.2]) r=np.rec.fromarrays([x1, x2, x3], names='id,word,number') r.sort(order=['id']) assert_equal(r.id, array([14, 21, 32])) assert_equal(r.word, array(['name', 'my', 'first'])) assert_equal(r.number, array([6.2, 3.1, 4.5])) r.sort(order=['word']) assert_equal(r.id, array([32, 21, 14])) assert_equal(r.word, array(['first', 'my', 'name'])) assert_equal(r.number, array([4.5, 3.1, 6.2])) r.sort(order=['number']) assert_equal(r.id, array([21, 32, 14])) assert_equal(r.word, array(['my', 'first', 'name'])) assert_equal(r.number, array([3.1, 4.5, 6.2])) if sys.byteorder == 'little': strtype = '>i2' else: strtype = '<i2' mydtype = [('name', strchar + '5'), ('col2', strtype)] r = np.array([('a', 1), ('b', 255), ('c', 3), ('d', 258)], dtype= mydtype) r.sort(order='col2') assert_equal(r['col2'], [1, 3, 255, 258]) assert_equal(r, np.array([('a', 1), ('c', 3), ('b', 255), ('d', 258)], dtype=mydtype)) def test_argsort(self): # all c scalar argsorts use the same code with different types # so it suffices to run a quick check with one type. The number # of sorted items must be greater than ~50 to check the actual # algorithm because quick and merge sort fall over to insertion # sort for small arrays. a = np.arange(101) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "scalar argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), a, msg) assert_equal(b.copy().argsort(kind=kind), b, msg) # test complex argsorts. These use the same code as the scalars # but the compare fuction differs. ai = a*1j + 1 bi = b*1j + 1 for kind in ['q', 'm', 'h'] : msg = "complex argsort, kind=%s" % kind assert_equal(ai.copy().argsort(kind=kind), a, msg) assert_equal(bi.copy().argsort(kind=kind), b, msg) ai = a + 1j bi = b + 1j for kind in ['q', 'm', 'h'] : msg = "complex argsort, kind=%s" % kind assert_equal(ai.copy().argsort(kind=kind), a, msg) assert_equal(bi.copy().argsort(kind=kind), b, msg) # test argsort of complex arrays requiring byte-swapping, gh-5441 for endianess in '<>': for dt in np.typecodes['Complex']: dtype = '{0}{1}'.format(endianess, dt) arr = np.array([1+3.j, 2+2.j, 3+1.j], dtype=dt) msg = 'byte-swapped complex argsort, dtype={0}'.format(dt) assert_equal(arr.argsort(), np.arange(len(arr), dtype=np.intp), msg) # test string argsorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)]) b = a[::-1].copy() r = np.arange(101) rr = r[::-1] for kind in ['q', 'm', 'h'] : msg = "string argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), r, msg) assert_equal(b.copy().argsort(kind=kind), rr, msg) # test unicode argsorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode) b = a[::-1] r = np.arange(101) rr = r[::-1] for kind in ['q', 'm', 'h'] : msg = "unicode argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), r, msg) assert_equal(b.copy().argsort(kind=kind), rr, msg) # test object array argsorts. a = np.empty((101,), dtype=np.object) a[:] = list(range(101)) b = a[::-1] r = np.arange(101) rr = r[::-1] for kind in ['q', 'm', 'h'] : msg = "object argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), r, msg) assert_equal(b.copy().argsort(kind=kind), rr, msg) # test structured array argsorts. dt = np.dtype([('f', float), ('i', int)]) a = array([(i, i) for i in range(101)], dtype = dt) b = a[::-1] r = np.arange(101) rr = r[::-1] for kind in ['q', 'm', 'h'] : msg = "structured array argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), r, msg) assert_equal(b.copy().argsort(kind=kind), rr, msg) # test datetime64 argsorts. a = np.arange(0, 101, dtype='datetime64[D]') b = a[::-1] r = np.arange(101) rr = r[::-1] for kind in ['q', 'h', 'm'] : msg = "datetime64 argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), r, msg) assert_equal(b.copy().argsort(kind=kind), rr, msg) # test timedelta64 argsorts. a = np.arange(0, 101, dtype='timedelta64[D]') b = a[::-1] r = np.arange(101) rr = r[::-1] for kind in ['q', 'h', 'm'] : msg = "timedelta64 argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), r, msg) assert_equal(b.copy().argsort(kind=kind), rr, msg) # check axis handling. This should be the same for all type # specific argsorts, so we only check it for one type and one kind a = np.array([[3, 2], [1, 0]]) b = np.array([[1, 1], [0, 0]]) c = np.array([[1, 0], [1, 0]]) assert_equal(a.copy().argsort(axis=0), b) assert_equal(a.copy().argsort(axis=1), c) assert_equal(a.copy().argsort(), c) # using None is known fail at this point #assert_equal(a.copy().argsort(axis=None, c) # check axis handling for multidimensional empty arrays a = np.array([]) a.shape = (3, 2, 1, 0) for axis in range(-a.ndim, a.ndim): msg = 'test empty array argsort with axis={0}'.format(axis) assert_equal(np.argsort(a, axis=axis), np.zeros_like(a, dtype=np.intp), msg) msg = 'test empty array argsort with axis=None' assert_equal(np.argsort(a, axis=None), np.zeros_like(a.ravel(), dtype=np.intp), msg) # check that stable argsorts are stable r = np.arange(100) # scalars a = np.zeros(100) assert_equal(a.argsort(kind='m'), r) # complex a = np.zeros(100, dtype=np.complex) assert_equal(a.argsort(kind='m'), r) # string a = np.array(['aaaaaaaaa' for i in range(100)]) assert_equal(a.argsort(kind='m'), r) # unicode a = np.array(['aaaaaaaaa' for i in range(100)], dtype=np.unicode) assert_equal(a.argsort(kind='m'), r) def test_sort_unicode_kind(self): d = np.arange(10) k = b'\xc3\xa4'.decode("UTF8") assert_raises(ValueError, d.sort, kind=k) assert_raises(ValueError, d.argsort, kind=k) def test_searchsorted(self): # test for floats and complex containing nans. The logic is the # same for all float types so only test double types for now. # The search sorted routines use the compare functions for the # array type, so this checks if that is consistent with the sort # order. # check double a = np.array([0, 1, np.nan]) msg = "Test real searchsorted with nans, side='l'" b = a.searchsorted(a, side='l') assert_equal(b, np.arange(3), msg) msg = "Test real searchsorted with nans, side='r'" b = a.searchsorted(a, side='r') assert_equal(b, np.arange(1, 4), msg) # check double complex a = np.zeros(9, dtype=np.complex128) a.real += [0, 0, 1, 1, 0, 1, np.nan, np.nan, np.nan] a.imag += [0, 1, 0, 1, np.nan, np.nan, 0, 1, np.nan] msg = "Test complex searchsorted with nans, side='l'" b = a.searchsorted(a, side='l') assert_equal(b, np.arange(9), msg) msg = "Test complex searchsorted with nans, side='r'" b = a.searchsorted(a, side='r') assert_equal(b, np.arange(1, 10), msg) msg = "Test searchsorted with little endian, side='l'" a = np.array([0, 128], dtype='<i4') b = a.searchsorted(np.array(128, dtype='<i4')) assert_equal(b, 1, msg) msg = "Test searchsorted with big endian, side='l'" a = np.array([0, 128], dtype='>i4') b = a.searchsorted(np.array(128, dtype='>i4')) assert_equal(b, 1, msg) # Check 0 elements a = np.ones(0) b = a.searchsorted([0, 1, 2], 'l') assert_equal(b, [0, 0, 0]) b = a.searchsorted([0, 1, 2], 'r') assert_equal(b, [0, 0, 0]) a = np.ones(1) # Check 1 element b = a.searchsorted([0, 1, 2], 'l') assert_equal(b, [0, 0, 1]) b = a.searchsorted([0, 1, 2], 'r') assert_equal(b, [0, 1, 1]) # Check all elements equal a = np.ones(2) b = a.searchsorted([0, 1, 2], 'l') assert_equal(b, [0, 0, 2]) b = a.searchsorted([0, 1, 2], 'r') assert_equal(b, [0, 2, 2]) # Test searching unaligned array a = np.arange(10) aligned = np.empty(a.itemsize * a.size + 1, 'uint8') unaligned = aligned[1:].view(a.dtype) unaligned[:] = a # Test searching unaligned array b = unaligned.searchsorted(a, 'l') assert_equal(b, a) b = unaligned.searchsorted(a, 'r') assert_equal(b, a + 1) # Test searching for unaligned keys b = a.searchsorted(unaligned, 'l') assert_equal(b, a) b = a.searchsorted(unaligned, 'r') assert_equal(b, a + 1) # Test smart resetting of binsearch indices a = np.arange(5) b = a.searchsorted([6, 5, 4], 'l') assert_equal(b, [5, 5, 4]) b = a.searchsorted([6, 5, 4], 'r') assert_equal(b, [5, 5, 5]) # Test all type specific binary search functions types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'], np.typecodes['Datetime'], '?O')) for dt in types: if dt == 'M': dt = 'M8[D]' if dt == '?': a = np.arange(2, dtype=dt) out = np.arange(2) else: a = np.arange(0, 5, dtype=dt) out = np.arange(5) b = a.searchsorted(a, 'l') assert_equal(b, out) b = a.searchsorted(a, 'r') assert_equal(b, out + 1) def test_searchsorted_unicode(self): # Test searchsorted on unicode strings. # 1.6.1 contained a string length miscalculation in # arraytypes.c.src:UNICODE_compare() which manifested as # incorrect/inconsistent results from searchsorted. a = np.array(['P:\\20x_dapi_cy3\\20x_dapi_cy3_20100185_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100186_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100187_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100189_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100190_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100191_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100192_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100193_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100194_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100195_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100196_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100197_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100198_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100199_1'], dtype=np.unicode) ind = np.arange(len(a)) assert_equal([a.searchsorted(v, 'left') for v in a], ind) assert_equal([a.searchsorted(v, 'right') for v in a], ind + 1) assert_equal([a.searchsorted(a[i], 'left') for i in ind], ind) assert_equal([a.searchsorted(a[i], 'right') for i in ind], ind + 1) def test_searchsorted_with_sorter(self): a = np.array([5, 2, 1, 3, 4]) s = np.argsort(a) assert_raises(TypeError, np.searchsorted, a, 0, sorter=(1, (2, 3))) assert_raises(TypeError, np.searchsorted, a, 0, sorter=[1.1]) assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4]) assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4, 5, 6]) # bounds check assert_raises(ValueError, np.searchsorted, a, 4, sorter=[0, 1, 2, 3, 5]) assert_raises(ValueError, np.searchsorted, a, 0, sorter=[-1, 0, 1, 2, 3]) assert_raises(ValueError, np.searchsorted, a, 0, sorter=[4, 0, -1, 2, 3]) a = np.random.rand(300) s = a.argsort() b = np.sort(a) k = np.linspace(0, 1, 20) assert_equal(b.searchsorted(k), a.searchsorted(k, sorter=s)) a = np.array([0, 1, 2, 3, 5]*20) s = a.argsort() k = [0, 1, 2, 3, 5] expected = [0, 20, 40, 60, 80] assert_equal(a.searchsorted(k, side='l', sorter=s), expected) expected = [20, 40, 60, 80, 100] assert_equal(a.searchsorted(k, side='r', sorter=s), expected) # Test searching unaligned array keys = np.arange(10) a = keys.copy() np.random.shuffle(s) s = a.argsort() aligned = np.empty(a.itemsize * a.size + 1, 'uint8') unaligned = aligned[1:].view(a.dtype) # Test searching unaligned array unaligned[:] = a b = unaligned.searchsorted(keys, 'l', s) assert_equal(b, keys) b = unaligned.searchsorted(keys, 'r', s) assert_equal(b, keys + 1) # Test searching for unaligned keys unaligned[:] = keys b = a.searchsorted(unaligned, 'l', s) assert_equal(b, keys) b = a.searchsorted(unaligned, 'r', s) assert_equal(b, keys + 1) # Test all type specific indirect binary search functions types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'], np.typecodes['Datetime'], '?O')) for dt in types: if dt == 'M': dt = 'M8[D]' if dt == '?': a = np.array([1, 0], dtype=dt) # We want the sorter array to be of a type that is different # from np.intp in all platforms, to check for #4698 s = np.array([1, 0], dtype=np.int16) out = np.array([1, 0]) else: a = np.array([3, 4, 1, 2, 0], dtype=dt) # We want the sorter array to be of a type that is different # from np.intp in all platforms, to check for #4698 s = np.array([4, 2, 3, 0, 1], dtype=np.int16) out = np.array([3, 4, 1, 2, 0], dtype=np.intp) b = a.searchsorted(a, 'l', s) assert_equal(b, out) b = a.searchsorted(a, 'r', s) assert_equal(b, out + 1) # Test non-contiguous sorter array a = np.array([3, 4, 1, 2, 0]) srt = np.empty((10,), dtype=np.intp) srt[1::2] = -1 srt[::2] = [4, 2, 3, 0, 1] s = srt[::2] out = np.array([3, 4, 1, 2, 0], dtype=np.intp) b = a.searchsorted(a, 'l', s) assert_equal(b, out) b = a.searchsorted(a, 'r', s) assert_equal(b, out + 1) def test_argpartition_out_of_range(self): # Test out of range values in kth raise an error, gh-5469 d = np.arange(10) assert_raises(ValueError, d.argpartition, 10) assert_raises(ValueError, d.argpartition, -11) # Test also for generic type argpartition, which uses sorting # and used to not bound check kth d_obj = np.arange(10, dtype=object) assert_raises(ValueError, d_obj.argpartition, 10) assert_raises(ValueError, d_obj.argpartition, -11) def test_partition_out_of_range(self): # Test out of range values in kth raise an error, gh-5469 d = np.arange(10) assert_raises(ValueError, d.partition, 10) assert_raises(ValueError, d.partition, -11) # Test also for generic type partition, which uses sorting # and used to not bound check kth d_obj = np.arange(10, dtype=object) assert_raises(ValueError, d_obj.partition, 10) assert_raises(ValueError, d_obj.partition, -11) def test_partition_empty_array(self): # check axis handling for multidimensional empty arrays a = np.array([]) a.shape = (3, 2, 1, 0) for axis in range(-a.ndim, a.ndim): msg = 'test empty array partition with axis={0}'.format(axis) assert_equal(np.partition(a, 0, axis=axis), a, msg) msg = 'test empty array partition with axis=None' assert_equal(np.partition(a, 0, axis=None), a.ravel(), msg) def test_argpartition_empty_array(self): # check axis handling for multidimensional empty arrays a = np.array([]) a.shape = (3, 2, 1, 0) for axis in range(-a.ndim, a.ndim): msg = 'test empty array argpartition with axis={0}'.format(axis) assert_equal(np.partition(a, 0, axis=axis), np.zeros_like(a, dtype=np.intp), msg) msg = 'test empty array argpartition with axis=None' assert_equal(np.partition(a, 0, axis=None), np.zeros_like(a.ravel(), dtype=np.intp), msg) def test_partition(self): d = np.arange(10) assert_raises(TypeError, np.partition, d, 2, kind=1) assert_raises(ValueError, np.partition, d, 2, kind="nonsense") assert_raises(ValueError, np.argpartition, d, 2, kind="nonsense") assert_raises(ValueError, d.partition, 2, axis=0, kind="nonsense") assert_raises(ValueError, d.argpartition, 2, axis=0, kind="nonsense") for k in ("introselect",): d = np.array([]) assert_array_equal(np.partition(d, 0, kind=k), d) assert_array_equal(np.argpartition(d, 0, kind=k), d) d = np.ones((1)) assert_array_equal(np.partition(d, 0, kind=k)[0], d) assert_array_equal(d[np.argpartition(d, 0, kind=k)], np.partition(d, 0, kind=k)) # kth not modified kth = np.array([30, 15, 5]) okth = kth.copy() np.partition(np.arange(40), kth) assert_array_equal(kth, okth) for r in ([2, 1], [1, 2], [1, 1]): d = np.array(r) tgt = np.sort(d) assert_array_equal(np.partition(d, 0, kind=k)[0], tgt[0]) assert_array_equal(np.partition(d, 1, kind=k)[1], tgt[1]) assert_array_equal(d[np.argpartition(d, 0, kind=k)], np.partition(d, 0, kind=k)) assert_array_equal(d[np.argpartition(d, 1, kind=k)], np.partition(d, 1, kind=k)) for i in range(d.size): d[i:].partition(0, kind=k) assert_array_equal(d, tgt) for r in ([3, 2, 1], [1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 1, 1], [1, 2, 2], [2, 2, 1], [1, 2, 1]): d = np.array(r) tgt = np.sort(d) assert_array_equal(np.partition(d, 0, kind=k)[0], tgt[0]) assert_array_equal(np.partition(d, 1, kind=k)[1], tgt[1]) assert_array_equal(np.partition(d, 2, kind=k)[2], tgt[2]) assert_array_equal(d[np.argpartition(d, 0, kind=k)], np.partition(d, 0, kind=k)) assert_array_equal(d[np.argpartition(d, 1, kind=k)], np.partition(d, 1, kind=k)) assert_array_equal(d[np.argpartition(d, 2, kind=k)], np.partition(d, 2, kind=k)) for i in range(d.size): d[i:].partition(0, kind=k) assert_array_equal(d, tgt) d = np.ones((50)) assert_array_equal(np.partition(d, 0, kind=k), d) assert_array_equal(d[np.argpartition(d, 0, kind=k)], np.partition(d, 0, kind=k)) # sorted d = np.arange((49)) self.assertEqual(np.partition(d, 5, kind=k)[5], 5) self.assertEqual(np.partition(d, 15, kind=k)[15], 15) assert_array_equal(d[np.argpartition(d, 5, kind=k)], np.partition(d, 5, kind=k)) assert_array_equal(d[np.argpartition(d, 15, kind=k)], np.partition(d, 15, kind=k)) # rsorted d = np.arange((47))[::-1] self.assertEqual(np.partition(d, 6, kind=k)[6], 6) self.assertEqual(np.partition(d, 16, kind=k)[16], 16) assert_array_equal(d[np.argpartition(d, 6, kind=k)], np.partition(d, 6, kind=k)) assert_array_equal(d[np.argpartition(d, 16, kind=k)], np.partition(d, 16, kind=k)) assert_array_equal(np.partition(d, -6, kind=k), np.partition(d, 41, kind=k)) assert_array_equal(np.partition(d, -16, kind=k), np.partition(d, 31, kind=k)) assert_array_equal(d[np.argpartition(d, -6, kind=k)], np.partition(d, 41, kind=k)) # median of 3 killer, O(n^2) on pure median 3 pivot quickselect # exercises the median of median of 5 code used to keep O(n) d = np.arange(1000000) x = np.roll(d, d.size // 2) mid = x.size // 2 + 1 assert_equal(np.partition(x, mid)[mid], mid) d = np.arange(1000001) x = np.roll(d, d.size // 2 + 1) mid = x.size // 2 + 1 assert_equal(np.partition(x, mid)[mid], mid) # max d = np.ones(10); d[1] = 4; assert_equal(np.partition(d, (2, -1))[-1], 4) assert_equal(np.partition(d, (2, -1))[2], 1) assert_equal(d[np.argpartition(d, (2, -1))][-1], 4) assert_equal(d[np.argpartition(d, (2, -1))][2], 1) d[1] = np.nan assert_(np.isnan(d[np.argpartition(d, (2, -1))][-1])) assert_(np.isnan(np.partition(d, (2, -1))[-1])) # equal elements d = np.arange((47)) % 7 tgt = np.sort(np.arange((47)) % 7) np.random.shuffle(d) for i in range(d.size): self.assertEqual(np.partition(d, i, kind=k)[i], tgt[i]) assert_array_equal(d[np.argpartition(d, 6, kind=k)], np.partition(d, 6, kind=k)) assert_array_equal(d[np.argpartition(d, 16, kind=k)], np.partition(d, 16, kind=k)) for i in range(d.size): d[i:].partition(0, kind=k) assert_array_equal(d, tgt) d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9]) kth = [0, 3, 19, 20] assert_equal(np.partition(d, kth, kind=k)[kth], (0, 3, 7, 7)) assert_equal(d[np.argpartition(d, kth, kind=k)][kth], (0, 3, 7, 7)) d = np.array([2, 1]) d.partition(0, kind=k) assert_raises(ValueError, d.partition, 2) assert_raises(ValueError, d.partition, 3, axis=1) assert_raises(ValueError, np.partition, d, 2) assert_raises(ValueError, np.partition, d, 2, axis=1) assert_raises(ValueError, d.argpartition, 2) assert_raises(ValueError, d.argpartition, 3, axis=1) assert_raises(ValueError, np.argpartition, d, 2) assert_raises(ValueError, np.argpartition, d, 2, axis=1) d = np.arange(10).reshape((2, 5)) d.partition(1, axis=0, kind=k) d.partition(4, axis=1, kind=k) np.partition(d, 1, axis=0, kind=k) np.partition(d, 4, axis=1, kind=k) np.partition(d, 1, axis=None, kind=k) np.partition(d, 9, axis=None, kind=k) d.argpartition(1, axis=0, kind=k) d.argpartition(4, axis=1, kind=k) np.argpartition(d, 1, axis=0, kind=k) np.argpartition(d, 4, axis=1, kind=k) np.argpartition(d, 1, axis=None, kind=k) np.argpartition(d, 9, axis=None, kind=k) assert_raises(ValueError, d.partition, 2, axis=0) assert_raises(ValueError, d.partition, 11, axis=1) assert_raises(TypeError, d.partition, 2, axis=None) assert_raises(ValueError, np.partition, d, 9, axis=1) assert_raises(ValueError, np.partition, d, 11, axis=None) assert_raises(ValueError, d.argpartition, 2, axis=0) assert_raises(ValueError, d.argpartition, 11, axis=1) assert_raises(ValueError, np.argpartition, d, 9, axis=1) assert_raises(ValueError, np.argpartition, d, 11, axis=None) td = [(dt, s) for dt in [np.int32, np.float32, np.complex64] for s in (9, 16)] for dt, s in td: aae = assert_array_equal at = self.assertTrue d = np.arange(s, dtype=dt) np.random.shuffle(d) d1 = np.tile(np.arange(s, dtype=dt), (4, 1)) map(np.random.shuffle, d1) d0 = np.transpose(d1) for i in range(d.size): p = np.partition(d, i, kind=k) self.assertEqual(p[i], i) # all before are smaller assert_array_less(p[:i], p[i]) # all after are larger assert_array_less(p[i], p[i + 1:]) aae(p, d[np.argpartition(d, i, kind=k)]) p = np.partition(d1, i, axis=1, kind=k) aae(p[:, i], np.array([i] * d1.shape[0], dtype=dt)) # array_less does not seem to work right at((p[:, :i].T <= p[:, i]).all(), msg="%d: %r <= %r" % (i, p[:, i], p[:, :i].T)) at((p[:, i + 1:].T > p[:, i]).all(), msg="%d: %r < %r" % (i, p[:, i], p[:, i + 1:].T)) aae(p, d1[np.arange(d1.shape[0])[:, None], np.argpartition(d1, i, axis=1, kind=k)]) p = np.partition(d0, i, axis=0, kind=k) aae(p[i,:], np.array([i] * d1.shape[0], dtype=dt)) # array_less does not seem to work right at((p[:i,:] <= p[i,:]).all(), msg="%d: %r <= %r" % (i, p[i,:], p[:i,:])) at((p[i + 1:,:] > p[i,:]).all(), msg="%d: %r < %r" % (i, p[i,:], p[:, i + 1:])) aae(p, d0[np.argpartition(d0, i, axis=0, kind=k), np.arange(d0.shape[1])[None,:]]) # check inplace dc = d.copy() dc.partition(i, kind=k) assert_equal(dc, np.partition(d, i, kind=k)) dc = d0.copy() dc.partition(i, axis=0, kind=k) assert_equal(dc, np.partition(d0, i, axis=0, kind=k)) dc = d1.copy() dc.partition(i, axis=1, kind=k) assert_equal(dc, np.partition(d1, i, axis=1, kind=k)) def assert_partitioned(self, d, kth): prev = 0 for k in np.sort(kth): assert_array_less(d[prev:k], d[k], err_msg='kth %d' % k) assert_((d[k:] >= d[k]).all(), msg="kth %d, %r not greater equal %d" % (k, d[k:], d[k])) prev = k + 1 def test_partition_iterative(self): d = np.arange(17) kth = (0, 1, 2, 429, 231) assert_raises(ValueError, d.partition, kth) assert_raises(ValueError, d.argpartition, kth) d = np.arange(10).reshape((2, 5)) assert_raises(ValueError, d.partition, kth, axis=0) assert_raises(ValueError, d.partition, kth, axis=1) assert_raises(ValueError, np.partition, d, kth, axis=1) assert_raises(ValueError, np.partition, d, kth, axis=None) d = np.array([3, 4, 2, 1]) p = np.partition(d, (0, 3)) self.assert_partitioned(p, (0, 3)) self.assert_partitioned(d[np.argpartition(d, (0, 3))], (0, 3)) assert_array_equal(p, np.partition(d, (-3, -1))) assert_array_equal(p, d[np.argpartition(d, (-3, -1))]) d = np.arange(17) np.random.shuffle(d) d.partition(range(d.size)) assert_array_equal(np.arange(17), d) np.random.shuffle(d) assert_array_equal(np.arange(17), d[d.argpartition(range(d.size))]) # test unsorted kth d = np.arange(17) np.random.shuffle(d) keys = np.array([1, 3, 8, -2]) np.random.shuffle(d) p = np.partition(d, keys) self.assert_partitioned(p, keys) p = d[np.argpartition(d, keys)] self.assert_partitioned(p, keys) np.random.shuffle(keys) assert_array_equal(np.partition(d, keys), p) assert_array_equal(d[np.argpartition(d, keys)], p) # equal kth d = np.arange(20)[::-1] self.assert_partitioned(np.partition(d, [5]*4), [5]) self.assert_partitioned(np.partition(d, [5]*4 + [6, 13]), [5]*4 + [6, 13]) self.assert_partitioned(d[np.argpartition(d, [5]*4)], [5]) self.assert_partitioned(d[np.argpartition(d, [5]*4 + [6, 13])], [5]*4 + [6, 13]) d = np.arange(12) np.random.shuffle(d) d1 = np.tile(np.arange(12), (4, 1)) map(np.random.shuffle, d1) d0 = np.transpose(d1) kth = (1, 6, 7, -1) p = np.partition(d1, kth, axis=1) pa = d1[np.arange(d1.shape[0])[:, None], d1.argpartition(kth, axis=1)] assert_array_equal(p, pa) for i in range(d1.shape[0]): self.assert_partitioned(p[i,:], kth) p = np.partition(d0, kth, axis=0) pa = d0[np.argpartition(d0, kth, axis=0), np.arange(d0.shape[1])[None,:]] assert_array_equal(p, pa) for i in range(d0.shape[1]): self.assert_partitioned(p[:, i], kth) def test_partition_cdtype(self): d = array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), ('Lancelot', 1.9, 38)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) tgt = np.sort(d, order=['age', 'height']) assert_array_equal(np.partition(d, range(d.size), order=['age', 'height']), tgt) assert_array_equal(d[np.argpartition(d, range(d.size), order=['age', 'height'])], tgt) for k in range(d.size): assert_equal(np.partition(d, k, order=['age', 'height'])[k], tgt[k]) assert_equal(d[np.argpartition(d, k, order=['age', 'height'])][k], tgt[k]) d = array(['Galahad', 'Arthur', 'zebra', 'Lancelot']) tgt = np.sort(d) assert_array_equal(np.partition(d, range(d.size)), tgt) for k in range(d.size): assert_equal(np.partition(d, k)[k], tgt[k]) assert_equal(d[np.argpartition(d, k)][k], tgt[k]) def test_partition_unicode_kind(self): d = np.arange(10) k = b'\xc3\xa4'.decode("UTF8") assert_raises(ValueError, d.partition, 2, kind=k) assert_raises(ValueError, d.argpartition, 2, kind=k) def test_partition_fuzz(self): # a few rounds of random data testing for j in range(10, 30): for i in range(1, j - 2): d = np.arange(j) np.random.shuffle(d) d = d % np.random.randint(2, 30) idx = np.random.randint(d.size) kth = [0, idx, i, i + 1] tgt = np.sort(d)[kth] assert_array_equal(np.partition(d, kth)[kth], tgt, err_msg="data: %r\n kth: %r" % (d, kth)) def test_argpartition_gh5524(self): # A test for functionality of argpartition on lists. d = [6,7,3,2,9,0] p = np.argpartition(d,1) self.assert_partitioned(np.array(d)[p],[1]) def test_flatten(self): x0 = np.array([[1, 2, 3], [4, 5, 6]], np.int32) x1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], np.int32) y0 = np.array([1, 2, 3, 4, 5, 6], np.int32) y0f = np.array([1, 4, 2, 5, 3, 6], np.int32) y1 = np.array([1, 2, 3, 4, 5, 6, 7, 8], np.int32) y1f = np.array([1, 5, 3, 7, 2, 6, 4, 8], np.int32) assert_equal(x0.flatten(), y0) assert_equal(x0.flatten('F'), y0f) assert_equal(x0.flatten('F'), x0.T.flatten()) assert_equal(x1.flatten(), y1) assert_equal(x1.flatten('F'), y1f) assert_equal(x1.flatten('F'), x1.T.flatten()) def test_dot(self): a = np.array([[1, 0], [0, 1]]) b = np.array([[0, 1], [1, 0]]) c = np.array([[9, 1], [1, -9]]) assert_equal(np.dot(a, b), a.dot(b)) assert_equal(np.dot(np.dot(a, b), c), a.dot(b).dot(c)) # test passing in an output array c = np.zeros_like(a) a.dot(b, c) assert_equal(c, np.dot(a, b)) # test keyword args c = np.zeros_like(a) a.dot(b=b, out=c) assert_equal(c, np.dot(a, b)) def test_dot_override(self): class A(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return "A" class B(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return NotImplemented a = A() b = B() c = np.array([[1]]) assert_equal(np.dot(a, b), "A") assert_equal(c.dot(a), "A") assert_raises(TypeError, np.dot, b, c) assert_raises(TypeError, c.dot, b) def test_diagonal(self): a = np.arange(12).reshape((3, 4)) assert_equal(a.diagonal(), [0, 5, 10]) assert_equal(a.diagonal(0), [0, 5, 10]) assert_equal(a.diagonal(1), [1, 6, 11]) assert_equal(a.diagonal(-1), [4, 9]) b = np.arange(8).reshape((2, 2, 2)) assert_equal(b.diagonal(), [[0, 6], [1, 7]]) assert_equal(b.diagonal(0), [[0, 6], [1, 7]]) assert_equal(b.diagonal(1), [[2], [3]]) assert_equal(b.diagonal(-1), [[4], [5]]) assert_raises(ValueError, b.diagonal, axis1=0, axis2=0) assert_equal(b.diagonal(0, 1, 2), [[0, 3], [4, 7]]) assert_equal(b.diagonal(0, 0, 1), [[0, 6], [1, 7]]) assert_equal(b.diagonal(offset=1, axis1=0, axis2=2), [[1], [3]]) # Order of axis argument doesn't matter: assert_equal(b.diagonal(0, 2, 1), [[0, 3], [4, 7]]) def test_diagonal_view_notwriteable(self): # this test is only for 1.9, the diagonal view will be # writeable in 1.10. a = np.eye(3).diagonal() assert_(not a.flags.writeable) assert_(not a.flags.owndata) a = np.diagonal(np.eye(3)) assert_(not a.flags.writeable) assert_(not a.flags.owndata) a = np.diag(np.eye(3)) assert_(not a.flags.writeable) assert_(not a.flags.owndata) def test_diagonal_memleak(self): # Regression test for a bug that crept in at one point a = np.zeros((100, 100)) assert_(sys.getrefcount(a) < 50) for i in range(100): a.diagonal() assert_(sys.getrefcount(a) < 50) def test_put(self): icodes = np.typecodes['AllInteger'] fcodes = np.typecodes['AllFloat'] for dt in icodes + fcodes + 'O': tgt = np.array([0, 1, 0, 3, 0, 5], dtype=dt) # test 1-d a = np.zeros(6, dtype=dt) a.put([1, 3, 5], [1, 3, 5]) assert_equal(a, tgt) # test 2-d a = np.zeros((2, 3), dtype=dt) a.put([1, 3, 5], [1, 3, 5]) assert_equal(a, tgt.reshape(2, 3)) for dt in '?': tgt = np.array([False, True, False, True, False, True], dtype=dt) # test 1-d a = np.zeros(6, dtype=dt) a.put([1, 3, 5], [True]*3) assert_equal(a, tgt) # test 2-d a = np.zeros((2, 3), dtype=dt) a.put([1, 3, 5], [True]*3) assert_equal(a, tgt.reshape(2, 3)) # check must be writeable a = np.zeros(6) a.flags.writeable = False assert_raises(ValueError, a.put, [1, 3, 5], [1, 3, 5]) def test_ravel(self): a = np.array([[0, 1], [2, 3]]) assert_equal(a.ravel(), [0, 1, 2, 3]) assert_(not a.ravel().flags.owndata) assert_equal(a.ravel('F'), [0, 2, 1, 3]) assert_equal(a.ravel(order='C'), [0, 1, 2, 3]) assert_equal(a.ravel(order='F'), [0, 2, 1, 3]) assert_equal(a.ravel(order='A'), [0, 1, 2, 3]) assert_(not a.ravel(order='A').flags.owndata) assert_equal(a.ravel(order='K'), [0, 1, 2, 3]) assert_(not a.ravel(order='K').flags.owndata) assert_equal(a.ravel(), a.reshape(-1)) a = np.array([[0, 1], [2, 3]], order='F') assert_equal(a.ravel(), [0, 1, 2, 3]) assert_equal(a.ravel(order='A'), [0, 2, 1, 3]) assert_equal(a.ravel(order='K'), [0, 2, 1, 3]) assert_(not a.ravel(order='A').flags.owndata) assert_(not a.ravel(order='K').flags.owndata) assert_equal(a.ravel(), a.reshape(-1)) assert_equal(a.ravel(order='A'), a.reshape(-1, order='A')) a = np.array([[0, 1], [2, 3]])[::-1, :] assert_equal(a.ravel(), [2, 3, 0, 1]) assert_equal(a.ravel(order='C'), [2, 3, 0, 1]) assert_equal(a.ravel(order='F'), [2, 0, 3, 1]) assert_equal(a.ravel(order='A'), [2, 3, 0, 1]) # 'K' doesn't reverse the axes of negative strides assert_equal(a.ravel(order='K'), [2, 3, 0, 1]) assert_(a.ravel(order='K').flags.owndata) # Not contiguous and 1-sized axis with non matching stride a = np.arange(2**3 * 2)[::2] a = a.reshape(2, 1, 2, 2).swapaxes(-1, -2) strides = list(a.strides) strides[1] = 123 a.strides = strides assert_(np.may_share_memory(a.ravel(order='K'), a)) assert_equal(a.ravel('K'), np.arange(0, 15, 2)) # General case of possible ravel that is not contiguous but # works and includes a 1-sized axis with non matching stride a = a.swapaxes(-1, -2) # swap back to C-order assert_(np.may_share_memory(a.ravel(order='C'), a)) assert_(np.may_share_memory(a.ravel(order='K'), a)) a = a.T # swap all to Fortran order assert_(np.may_share_memory(a.ravel(order='F'), a)) assert_(np.may_share_memory(a.ravel(order='K'), a)) # Test negative strides: a = np.arange(4)[::-1].reshape(2, 2) assert_(np.may_share_memory(a.ravel(order='C'), a)) assert_(np.may_share_memory(a.ravel(order='K'), a)) assert_equal(a.ravel('C'), [3, 2, 1, 0]) assert_equal(a.ravel('K'), [3, 2, 1, 0]) # Test keeporder with weirdly strided 1-sized dims (1-d first stride) a = np.arange(8)[::2].reshape(1, 2, 2, 1) # neither C, nor F order strides = list(a.strides) strides[0] = -12 strides[-1] = 0 a.strides = strides assert_(np.may_share_memory(a.ravel(order='K'), a)) assert_equal(a.ravel('K'), a.ravel('C')) # 1-element tidy strides test (NPY_RELAXED_STRIDES_CHECKING): a = np.array([[1]]) a.strides = (123, 432) # If the stride is not 8, NPY_RELAXED_STRIDES_CHECKING is messing # them up on purpose: if np.ones(1).strides == (8,): assert_(np.may_share_memory(a.ravel('K'), a)) assert_equal(a.ravel('K').strides, (a.dtype.itemsize,)) for order in ('C', 'F', 'A', 'K'): # 0-d corner case: a = np.array(0) assert_equal(a.ravel(order), [0]) assert_(np.may_share_memory(a.ravel(order), a)) #Test that certain non-inplace ravels work right (mostly) for 'K': b = np.arange(2**4 * 2)[::2].reshape(2, 2, 2, 2) a = b[..., ::2] assert_equal(a.ravel('K'), [0, 4, 8, 12, 16, 20, 24, 28]) assert_equal(a.ravel('C'), [0, 4, 8, 12, 16, 20, 24, 28]) assert_equal(a.ravel('A'), [0, 4, 8, 12, 16, 20, 24, 28]) assert_equal(a.ravel('F'), [0, 16, 8, 24, 4, 20, 12, 28]) a = b[::2, ...] assert_equal(a.ravel('K'), [0, 2, 4, 6, 8, 10, 12, 14]) assert_equal(a.ravel('C'), [0, 2, 4, 6, 8, 10, 12, 14]) assert_equal(a.ravel('A'), [0, 2, 4, 6, 8, 10, 12, 14]) assert_equal(a.ravel('F'), [0, 8, 4, 12, 2, 10, 6, 14]) def test_swapaxes(self): a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy() idx = np.indices(a.shape) assert_(a.flags['OWNDATA']) b = a.copy() # check exceptions assert_raises(ValueError, a.swapaxes, -5, 0) assert_raises(ValueError, a.swapaxes, 4, 0) assert_raises(ValueError, a.swapaxes, 0, -5) assert_raises(ValueError, a.swapaxes, 0, 4) for i in range(-4, 4): for j in range(-4, 4): for k, src in enumerate((a, b)): c = src.swapaxes(i, j) # check shape shape = list(src.shape) shape[i] = src.shape[j] shape[j] = src.shape[i] assert_equal(c.shape, shape, str((i, j, k))) # check array contents i0, i1, i2, i3 = [dim-1 for dim in c.shape] j0, j1, j2, j3 = [dim-1 for dim in src.shape] assert_equal(src[idx[j0], idx[j1], idx[j2], idx[j3]], c[idx[i0], idx[i1], idx[i2], idx[i3]], str((i, j, k))) # check a view is always returned, gh-5260 assert_(not c.flags['OWNDATA'], str((i, j, k))) # check on non-contiguous input array if k == 1: b = c def test_conjugate(self): a = np.array([1-1j, 1+1j, 23+23.0j]) ac = a.conj() assert_equal(a.real, ac.real) assert_equal(a.imag, -ac.imag) assert_equal(ac, a.conjugate()) assert_equal(ac, np.conjugate(a)) a = np.array([1-1j, 1+1j, 23+23.0j], 'F') ac = a.conj() assert_equal(a.real, ac.real) assert_equal(a.imag, -ac.imag) assert_equal(ac, a.conjugate()) assert_equal(ac, np.conjugate(a)) a = np.array([1, 2, 3]) ac = a.conj() assert_equal(a, ac) assert_equal(ac, a.conjugate()) assert_equal(ac, np.conjugate(a)) a = np.array([1.0, 2.0, 3.0]) ac = a.conj() assert_equal(a, ac) assert_equal(ac, a.conjugate()) assert_equal(ac, np.conjugate(a)) a = np.array([1-1j, 1+1j, 1, 2.0], object) ac = a.conj() assert_equal(ac, [k.conjugate() for k in a]) assert_equal(ac, a.conjugate()) assert_equal(ac, np.conjugate(a)) a = np.array([1-1j, 1, 2.0, 'f'], object) assert_raises(AttributeError, lambda: a.conj()) assert_raises(AttributeError, lambda: a.conjugate()) class TestBinop(object): def test_inplace(self): # test refcount 1 inplace conversion assert_array_almost_equal(np.array([0.5]) * np.array([1.0, 2.0]), [0.5, 1.0]) d = np.array([0.5, 0.5])[::2] assert_array_almost_equal(d * (d * np.array([1.0, 2.0])), [0.25, 0.5]) a = np.array([0.5]) b = np.array([0.5]) c = a + b c = a - b c = a * b c = a / b assert_equal(a, b) assert_almost_equal(c, 1.) c = a + b * 2. / b * a - a / b assert_equal(a, b) assert_equal(c, 0.5) # true divide a = np.array([5]) b = np.array([3]) c = (a * a) / b assert_almost_equal(c, 25 / 3) assert_equal(a, 5) assert_equal(b, 3) def test_extension_incref_elide(self): # test extension (e.g. cython) calling PyNumber_* slots without # increasing the reference counts # # def incref_elide(a): # d = input.copy() # refcount 1 # return d, d + d # PyNumber_Add without increasing refcount from numpy.core.multiarray_tests import incref_elide d = np.ones(5) orig, res = incref_elide(d) # the return original should not be changed to an inplace operation assert_array_equal(orig, d) assert_array_equal(res, d + d) def test_extension_incref_elide_stack(self): # scanning if the refcount == 1 object is on the python stack to check # that we are called directly from python is flawed as object may still # be above the stack pointer and we have no access to the top of it # # def incref_elide_l(d): # return l[4] + l[4] # PyNumber_Add without increasing refcount from numpy.core.multiarray_tests import incref_elide_l # padding with 1 makes sure the object on the stack is not overwriten l = [1, 1, 1, 1, np.ones(5)] res = incref_elide_l(l) # the return original should not be changed to an inplace operation assert_array_equal(l[4], np.ones(5)) assert_array_equal(res, l[4] + l[4]) def test_ufunc_override_rop_precedence(self): # Check that __rmul__ and other right-hand operations have # precedence over __numpy_ufunc__ ops = { '__add__': ('__radd__', np.add, True), '__sub__': ('__rsub__', np.subtract, True), '__mul__': ('__rmul__', np.multiply, True), '__truediv__': ('__rtruediv__', np.true_divide, True), '__floordiv__': ('__rfloordiv__', np.floor_divide, True), '__mod__': ('__rmod__', np.remainder, True), '__divmod__': ('__rdivmod__', None, False), '__pow__': ('__rpow__', np.power, True), '__lshift__': ('__rlshift__', np.left_shift, True), '__rshift__': ('__rrshift__', np.right_shift, True), '__and__': ('__rand__', np.bitwise_and, True), '__xor__': ('__rxor__', np.bitwise_xor, True), '__or__': ('__ror__', np.bitwise_or, True), '__ge__': ('__le__', np.less_equal, False), '__gt__': ('__lt__', np.less, False), '__le__': ('__ge__', np.greater_equal, False), '__lt__': ('__gt__', np.greater, False), '__eq__': ('__eq__', np.equal, False), '__ne__': ('__ne__', np.not_equal, False), } class OtherNdarraySubclass(ndarray): pass class OtherNdarraySubclassWithOverride(ndarray): def __numpy_ufunc__(self, *a, **kw): raise AssertionError(("__numpy_ufunc__ %r %r shouldn't have " "been called!") % (a, kw)) def check(op_name, ndsubclass): rop_name, np_op, has_iop = ops[op_name] if has_iop: iop_name = '__i' + op_name[2:] iop = getattr(operator, iop_name) if op_name == "__divmod__": op = divmod else: op = getattr(operator, op_name) # Dummy class def __init__(self, *a, **kw): pass def __numpy_ufunc__(self, *a, **kw): raise AssertionError(("__numpy_ufunc__ %r %r shouldn't have " "been called!") % (a, kw)) def __op__(self, *other): return "op" def __rop__(self, *other): return "rop" if ndsubclass: bases = (ndarray,) else: bases = (object,) dct = {'__init__': __init__, '__numpy_ufunc__': __numpy_ufunc__, op_name: __op__} if op_name != rop_name: dct[rop_name] = __rop__ cls = type("Rop" + rop_name, bases, dct) # Check behavior against both bare ndarray objects and a # ndarray subclasses with and without their own override obj = cls((1,), buffer=np.ones(1,)) arr_objs = [np.array([1]), np.array([2]).view(OtherNdarraySubclass), np.array([3]).view(OtherNdarraySubclassWithOverride), ] for arr in arr_objs: err_msg = "%r %r" % (op_name, arr,) # Check that ndarray op gives up if it sees a non-subclass if not isinstance(obj, arr.__class__): assert_equal(getattr(arr, op_name)(obj), NotImplemented, err_msg=err_msg) # Check that the Python binops have priority assert_equal(op(obj, arr), "op", err_msg=err_msg) if op_name == rop_name: assert_equal(op(arr, obj), "op", err_msg=err_msg) else: assert_equal(op(arr, obj), "rop", err_msg=err_msg) # Check that Python binops have priority also for in-place ops if has_iop: assert_equal(getattr(arr, iop_name)(obj), NotImplemented, err_msg=err_msg) if op_name != "__pow__": # inplace pow requires the other object to be # integer-like? assert_equal(iop(arr, obj), "rop", err_msg=err_msg) # Check that ufunc call __numpy_ufunc__ normally if np_op is not None: assert_raises(AssertionError, np_op, arr, obj, err_msg=err_msg) assert_raises(AssertionError, np_op, obj, arr, err_msg=err_msg) # Check all binary operations for op_name in sorted(ops.keys()): yield check, op_name, True yield check, op_name, False def test_ufunc_override_rop_simple(self): # Check parts of the binary op overriding behavior in an # explicit test case that is easier to understand. class SomeClass(object): def __numpy_ufunc__(self, *a, **kw): return "ufunc" def __mul__(self, other): return 123 def __rmul__(self, other): return 321 def __rsub__(self, other): return "no subs for me" def __gt__(self, other): return "yep" def __lt__(self, other): return "nope" class SomeClass2(SomeClass, ndarray): def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw): if ufunc is np.multiply or ufunc is np.bitwise_and: return "ufunc" else: inputs = list(inputs) inputs[i] = np.asarray(self) func = getattr(ufunc, method) r = func(*inputs, **kw) if 'out' in kw: return r else: x = self.__class__(r.shape, dtype=r.dtype) x[...] = r return x class SomeClass3(SomeClass2): def __rsub__(self, other): return "sub for me" arr = np.array([0]) obj = SomeClass() obj2 = SomeClass2((1,), dtype=np.int_) obj2[0] = 9 obj3 = SomeClass3((1,), dtype=np.int_) obj3[0] = 4 # obj is first, so should get to define outcome. assert_equal(obj * arr, 123) # obj is second, but has __numpy_ufunc__ and defines __rmul__. assert_equal(arr * obj, 321) # obj is second, but has __numpy_ufunc__ and defines __rsub__. assert_equal(arr - obj, "no subs for me") # obj is second, but has __numpy_ufunc__ and defines __lt__. assert_equal(arr > obj, "nope") # obj is second, but has __numpy_ufunc__ and defines __gt__. assert_equal(arr < obj, "yep") # Called as a ufunc, obj.__numpy_ufunc__ is used. assert_equal(np.multiply(arr, obj), "ufunc") # obj is second, but has __numpy_ufunc__ and defines __rmul__. arr *= obj assert_equal(arr, 321) # obj2 is an ndarray subclass, so CPython takes care of the same rules. assert_equal(obj2 * arr, 123) assert_equal(arr * obj2, 321) assert_equal(arr - obj2, "no subs for me") assert_equal(arr > obj2, "nope") assert_equal(arr < obj2, "yep") # Called as a ufunc, obj2.__numpy_ufunc__ is called. assert_equal(np.multiply(arr, obj2), "ufunc") # Also when the method is not overridden. assert_equal(arr & obj2, "ufunc") arr *= obj2 assert_equal(arr, 321) obj2 += 33 assert_equal(obj2[0], 42) assert_equal(obj2.sum(), 42) assert_(isinstance(obj2, SomeClass2)) # Obj3 is subclass that defines __rsub__. CPython calls it. assert_equal(arr - obj3, "sub for me") assert_equal(obj2 - obj3, "sub for me") # obj3 is a subclass that defines __rmul__. CPython calls it. assert_equal(arr * obj3, 321) # But not here, since obj3.__rmul__ is obj2.__rmul__. assert_equal(obj2 * obj3, 123) # And of course, here obj3.__mul__ should be called. assert_equal(obj3 * obj2, 123) # obj3 defines __numpy_ufunc__ but obj3.__radd__ is obj2.__radd__. # (and both are just ndarray.__radd__); see #4815. res = obj2 + obj3 assert_equal(res, 46) assert_(isinstance(res, SomeClass2)) # Since obj3 is a subclass, it should have precedence, like CPython # would give, even though obj2 has __numpy_ufunc__ and __radd__. # See gh-4815 and gh-5747. res = obj3 + obj2 assert_equal(res, 46) assert_(isinstance(res, SomeClass3)) def test_ufunc_override_normalize_signature(self): # gh-5674 class SomeClass(object): def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw): return kw a = SomeClass() kw = np.add(a, [1]) assert_('sig' not in kw and 'signature' not in kw) kw = np.add(a, [1], sig='ii->i') assert_('sig' not in kw and 'signature' in kw) assert_equal(kw['signature'], 'ii->i') kw = np.add(a, [1], signature='ii->i') assert_('sig' not in kw and 'signature' in kw) assert_equal(kw['signature'], 'ii->i') class TestCAPI(TestCase): def test_IsPythonScalar(self): from numpy.core.multiarray_tests import IsPythonScalar assert_(IsPythonScalar(b'foobar')) assert_(IsPythonScalar(1)) assert_(IsPythonScalar(2**80)) assert_(IsPythonScalar(2.)) assert_(IsPythonScalar("a")) class TestSubscripting(TestCase): def test_test_zero_rank(self): x = array([1, 2, 3]) self.assertTrue(isinstance(x[0], np.int_)) if sys.version_info[0] < 3: self.assertTrue(isinstance(x[0], int)) self.assertTrue(type(x[0, ...]) is ndarray) class TestPickling(TestCase): def test_roundtrip(self): import pickle carray = array([[2, 9], [7, 0], [3, 8]]) DATA = [ carray, transpose(carray), array([('xxx', 1, 2.0)], dtype=[('a', (str, 3)), ('b', int), ('c', float)]) ] for a in DATA: assert_equal(a, pickle.loads(a.dumps()), err_msg="%r" % a) def _loads(self, obj): if sys.version_info[0] >= 3: return loads(obj, encoding='latin1') else: return loads(obj) # version 0 pickles, using protocol=2 to pickle # version 0 doesn't have a version field def test_version0_int8(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.' a = array([1, 2, 3, 4], dtype=int8) p = self._loads(asbytes(s)) assert_equal(a, p) def test_version0_float32(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.' a = array([1.0, 2.0, 3.0, 4.0], dtype=float32) p = self._loads(asbytes(s)) assert_equal(a, p) def test_version0_object(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.' a = np.array([{'a':1}, {'b':2}]) p = self._loads(asbytes(s)) assert_equal(a, p) # version 1 pickles, using protocol=2 to pickle def test_version1_int8(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.' a = array([1, 2, 3, 4], dtype=int8) p = self._loads(asbytes(s)) assert_equal(a, p) def test_version1_float32(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(K\x01U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.' a = array([1.0, 2.0, 3.0, 4.0], dtype=float32) p = self._loads(asbytes(s)) assert_equal(a, p) def test_version1_object(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.' a = array([{'a':1}, {'b':2}]) p = self._loads(asbytes(s)) assert_equal(a, p) def test_subarray_int_shape(self): s = "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'V6'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'a'\np12\ng3\ntp13\n(dp14\ng12\n(g7\n(S'V4'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'|'\np18\n(g7\n(S'i1'\np19\nI0\nI1\ntp20\nRp21\n(I3\nS'|'\np22\nNNNI-1\nI-1\nI0\ntp23\nb(I2\nI2\ntp24\ntp25\nNNI4\nI1\nI0\ntp26\nbI0\ntp27\nsg3\n(g7\n(S'V2'\np28\nI0\nI1\ntp29\nRp30\n(I3\nS'|'\np31\n(g21\nI2\ntp32\nNNI2\nI1\nI0\ntp33\nbI4\ntp34\nsI6\nI1\nI0\ntp35\nbI00\nS'\\x01\\x01\\x01\\x01\\x01\\x02'\np36\ntp37\nb." a = np.array([(1, (1, 2))], dtype=[('a', 'i1', (2, 2)), ('b', 'i1', 2)]) p = self._loads(asbytes(s)) assert_equal(a, p) class TestFancyIndexing(TestCase): def test_list(self): x = ones((1, 1)) x[:, [0]] = 2.0 assert_array_equal(x, array([[2.0]])) x = ones((1, 1, 1)) x[:,:, [0]] = 2.0 assert_array_equal(x, array([[[2.0]]])) def test_tuple(self): x = ones((1, 1)) x[:, (0,)] = 2.0 assert_array_equal(x, array([[2.0]])) x = ones((1, 1, 1)) x[:,:, (0,)] = 2.0 assert_array_equal(x, array([[[2.0]]])) def test_mask(self): x = array([1, 2, 3, 4]) m = array([0, 1, 0, 0], bool) assert_array_equal(x[m], array([2])) def test_mask2(self): x = array([[1, 2, 3, 4], [5, 6, 7, 8]]) m = array([0, 1], bool) m2 = array([[0, 1, 0, 0], [1, 0, 0, 0]], bool) m3 = array([[0, 1, 0, 0], [0, 0, 0, 0]], bool) assert_array_equal(x[m], array([[5, 6, 7, 8]])) assert_array_equal(x[m2], array([2, 5])) assert_array_equal(x[m3], array([2])) def test_assign_mask(self): x = array([1, 2, 3, 4]) m = array([0, 1, 0, 0], bool) x[m] = 5 assert_array_equal(x, array([1, 5, 3, 4])) def test_assign_mask2(self): xorig = array([[1, 2, 3, 4], [5, 6, 7, 8]]) m = array([0, 1], bool) m2 = array([[0, 1, 0, 0], [1, 0, 0, 0]], bool) m3 = array([[0, 1, 0, 0], [0, 0, 0, 0]], bool) x = xorig.copy() x[m] = 10 assert_array_equal(x, array([[1, 2, 3, 4], [10, 10, 10, 10]])) x = xorig.copy() x[m2] = 10 assert_array_equal(x, array([[1, 10, 3, 4], [10, 6, 7, 8]])) x = xorig.copy() x[m3] = 10 assert_array_equal(x, array([[1, 10, 3, 4], [5, 6, 7, 8]])) class TestStringCompare(TestCase): def test_string(self): g1 = array(["This", "is", "example"]) g2 = array(["This", "was", "example"]) assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) def test_mixed(self): g1 = array(["spam", "spa", "spammer", "and eggs"]) g2 = "spam" assert_array_equal(g1 == g2, [x == g2 for x in g1]) assert_array_equal(g1 != g2, [x != g2 for x in g1]) assert_array_equal(g1 < g2, [x < g2 for x in g1]) assert_array_equal(g1 > g2, [x > g2 for x in g1]) assert_array_equal(g1 <= g2, [x <= g2 for x in g1]) assert_array_equal(g1 >= g2, [x >= g2 for x in g1]) def test_unicode(self): g1 = array([sixu("This"), sixu("is"), sixu("example")]) g2 = array([sixu("This"), sixu("was"), sixu("example")]) assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) class TestArgmax(TestCase): nan_arr = [ ([0, 1, 2, 3, np.nan], 4), ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), ([0, 1, 2, 3, complex(0, np.nan)], 4), ([0, 1, 2, 3, complex(np.nan, 0)], 4), ([0, 1, 2, complex(np.nan, 0), 3], 3), ([0, 1, 2, complex(0, np.nan), 3], 3), ([complex(0, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0), ([complex(0, 0), complex(0, 2), complex(0, 1)], 1), ([complex(1, 0), complex(0, 2), complex(0, 1)], 0), ([complex(1, 0), complex(0, 2), complex(1, 1)], 2), ([np.datetime64('1923-04-14T12:43:12'), np.datetime64('1994-06-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('1995-11-25T16:02:16'), np.datetime64('2005-01-04T03:14:12'), np.datetime64('2041-12-03T14:05:03')], 5), ([np.datetime64('1935-09-14T04:40:11'), np.datetime64('1949-10-12T12:32:11'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('2015-11-20T12:20:59'), np.datetime64('1932-09-23T10:10:13'), np.datetime64('2014-10-10T03:50:30')], 3), # Assorted tests with NaTs ([np.datetime64('NaT'), np.datetime64('NaT'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('NaT'), np.datetime64('2015-09-23T10:10:13'), np.datetime64('1932-10-10T03:50:30')], 4), ([np.datetime64('2059-03-14T12:43:12'), np.datetime64('1996-09-21T14:43:15'), np.datetime64('NaT'), np.datetime64('2022-12-25T16:02:16'), np.datetime64('1963-10-04T03:14:12'), np.datetime64('2013-05-08T18:15:23')], 0), ([np.timedelta64(2, 's'), np.timedelta64(1, 's'), np.timedelta64('NaT', 's'), np.timedelta64(3, 's')], 3), ([np.timedelta64('NaT', 's')] * 3, 0), ([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35), timedelta(days=-1, seconds=23)], 0), ([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5), timedelta(days=5, seconds=14)], 1), ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 2), ([False, False, False, False, True], 4), ([False, False, False, True, False], 3), ([True, False, False, False, False], 0), ([True, False, True, False, False], 0), # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 3), #(['zz', 'a', 'aa', 'a'], 0), #(['aa', 'z', 'zz', 'a'], 2), ] def test_all(self): a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): amax = a.max(i) aargmax = a.argmax(i) axes = list(range(a.ndim)) axes.remove(i) assert_(all(amax == aargmax.choose(*a.transpose(i,*axes)))) def test_combinations(self): for arr, pos in self.nan_arr: assert_equal(np.argmax(arr), pos, err_msg="%r"%arr) assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r"%arr) def test_output_shape(self): # see also gh-616 a = np.ones((10, 5)) # Check some simple shape mismatches out = np.ones(11, dtype=np.int_) assert_raises(ValueError, a.argmax, -1, out) out = np.ones((2, 5), dtype=np.int_) assert_raises(ValueError, a.argmax, -1, out) # these could be relaxed possibly (used to allow even the previous) out = np.ones((1, 10), dtype=np.int_) assert_raises(ValueError, a.argmax, -1, np.ones((1, 10))) out = np.ones(10, dtype=np.int_) a.argmax(-1, out=out) assert_equal(out, a.argmax(-1)) def test_argmax_unicode(self): d = np.zeros(6031, dtype='<U9') d[5942] = "as" assert_equal(d.argmax(), 5942) def test_np_vs_ndarray(self): # make sure both ndarray.argmax and numpy.argmax support out/axis args a = np.random.normal(size=(2,3)) #check positional args out1 = zeros(2, dtype=int) out2 = zeros(2, dtype=int) assert_equal(a.argmax(1, out1), np.argmax(a, 1, out2)) assert_equal(out1, out2) #check keyword args out1 = zeros(3, dtype=int) out2 = zeros(3, dtype=int) assert_equal(a.argmax(out=out1, axis=0), np.argmax(a, out=out2, axis=0)) assert_equal(out1, out2) class TestArgmin(TestCase): nan_arr = [ ([0, 1, 2, 3, np.nan], 4), ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), ([0, 1, 2, 3, complex(0, np.nan)], 4), ([0, 1, 2, 3, complex(np.nan, 0)], 4), ([0, 1, 2, complex(np.nan, 0), 3], 3), ([0, 1, 2, complex(0, np.nan), 3], 3), ([complex(0, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0), ([complex(0, 0), complex(0, 2), complex(0, 1)], 0), ([complex(1, 0), complex(0, 2), complex(0, 1)], 2), ([complex(1, 0), complex(0, 2), complex(1, 1)], 1), ([np.datetime64('1923-04-14T12:43:12'), np.datetime64('1994-06-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('1995-11-25T16:02:16'), np.datetime64('2005-01-04T03:14:12'), np.datetime64('2041-12-03T14:05:03')], 0), ([np.datetime64('1935-09-14T04:40:11'), np.datetime64('1949-10-12T12:32:11'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('2014-11-20T12:20:59'), np.datetime64('2015-09-23T10:10:13'), np.datetime64('1932-10-10T03:50:30')], 5), # Assorted tests with NaTs ([np.datetime64('NaT'), np.datetime64('NaT'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('NaT'), np.datetime64('2015-09-23T10:10:13'), np.datetime64('1932-10-10T03:50:30')], 5), ([np.datetime64('2059-03-14T12:43:12'), np.datetime64('1996-09-21T14:43:15'), np.datetime64('NaT'), np.datetime64('2022-12-25T16:02:16'), np.datetime64('1963-10-04T03:14:12'), np.datetime64('2013-05-08T18:15:23')], 4), ([np.timedelta64(2, 's'), np.timedelta64(1, 's'), np.timedelta64('NaT', 's'), np.timedelta64(3, 's')], 1), ([np.timedelta64('NaT', 's')] * 3, 0), ([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35), timedelta(days=-1, seconds=23)], 2), ([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5), timedelta(days=5, seconds=14)], 0), ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 1), ([True, True, True, True, False], 4), ([True, True, True, False, True], 3), ([False, True, True, True, True], 0), ([False, True, False, True, True], 0), # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 0), #(['zz', 'a', 'aa', 'a'], 1), #(['aa', 'z', 'zz', 'a'], 3), ] def test_all(self): a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): amin = a.min(i) aargmin = a.argmin(i) axes = list(range(a.ndim)) axes.remove(i) assert_(all(amin == aargmin.choose(*a.transpose(i,*axes)))) def test_combinations(self): for arr, pos in self.nan_arr: assert_equal(np.argmin(arr), pos, err_msg="%r"%arr) assert_equal(arr[np.argmin(arr)], np.min(arr), err_msg="%r"%arr) def test_minimum_signed_integers(self): a = np.array([1, -2**7, -2**7 + 1], dtype=np.int8) assert_equal(np.argmin(a), 1) a = np.array([1, -2**15, -2**15 + 1], dtype=np.int16) assert_equal(np.argmin(a), 1) a = np.array([1, -2**31, -2**31 + 1], dtype=np.int32) assert_equal(np.argmin(a), 1) a = np.array([1, -2**63, -2**63 + 1], dtype=np.int64) assert_equal(np.argmin(a), 1) def test_output_shape(self): # see also gh-616 a = np.ones((10, 5)) # Check some simple shape mismatches out = np.ones(11, dtype=np.int_) assert_raises(ValueError, a.argmin, -1, out) out = np.ones((2, 5), dtype=np.int_) assert_raises(ValueError, a.argmin, -1, out) # these could be relaxed possibly (used to allow even the previous) out = np.ones((1, 10), dtype=np.int_) assert_raises(ValueError, a.argmin, -1, np.ones((1, 10))) out = np.ones(10, dtype=np.int_) a.argmin(-1, out=out) assert_equal(out, a.argmin(-1)) def test_argmin_unicode(self): d = np.ones(6031, dtype='<U9') d[6001] = "0" assert_equal(d.argmin(), 6001) def test_np_vs_ndarray(self): # make sure both ndarray.argmin and numpy.argmin support out/axis args a = np.random.normal(size=(2,3)) #check positional args out1 = zeros(2, dtype=int) out2 = ones(2, dtype=int) assert_equal(a.argmin(1, out1), np.argmin(a, 1, out2)) assert_equal(out1, out2) #check keyword args out1 = zeros(3, dtype=int) out2 = ones(3, dtype=int) assert_equal(a.argmin(out=out1, axis=0), np.argmin(a, out=out2, axis=0)) assert_equal(out1, out2) class TestMinMax(TestCase): def test_scalar(self): assert_raises(ValueError, np.amax, 1, 1) assert_raises(ValueError, np.amin, 1, 1) assert_equal(np.amax(1, axis=0), 1) assert_equal(np.amin(1, axis=0), 1) assert_equal(np.amax(1, axis=None), 1) assert_equal(np.amin(1, axis=None), 1) def test_axis(self): assert_raises(ValueError, np.amax, [1, 2, 3], 1000) assert_equal(np.amax([[1, 2, 3]], axis=1), 3) def test_datetime(self): # NaTs are ignored for dtype in ('m8[s]', 'm8[Y]'): a = np.arange(10).astype(dtype) a[3] = 'NaT' assert_equal(np.amin(a), a[0]) assert_equal(np.amax(a), a[9]) a[0] = 'NaT' assert_equal(np.amin(a), a[1]) assert_equal(np.amax(a), a[9]) a.fill('NaT') assert_equal(np.amin(a), a[0]) assert_equal(np.amax(a), a[0]) class TestNewaxis(TestCase): def test_basic(self): sk = array([0, -0.1, 0.1]) res = 250*sk[:, newaxis] assert_almost_equal(res.ravel(), 250*sk) class TestClip(TestCase): def _check_range(self, x, cmin, cmax): assert_(np.all(x >= cmin)) assert_(np.all(x <= cmax)) def _clip_type(self,type_group,array_max, clip_min,clip_max,inplace=False, expected_min=None,expected_max=None): if expected_min is None: expected_min = clip_min if expected_max is None: expected_max = clip_max for T in np.sctypes[type_group]: if sys.byteorder == 'little': byte_orders = ['=', '>'] else: byte_orders = ['<', '='] for byteorder in byte_orders: dtype = np.dtype(T).newbyteorder(byteorder) x = (np.random.random(1000) * array_max).astype(dtype) if inplace: x.clip(clip_min, clip_max, x) else: x = x.clip(clip_min, clip_max) byteorder = '=' if x.dtype.byteorder == '|': byteorder = '|' assert_equal(x.dtype.byteorder, byteorder) self._check_range(x, expected_min, expected_max) return x def test_basic(self): for inplace in [False, True]: self._clip_type('float', 1024, -12.8, 100.2, inplace=inplace) self._clip_type('float', 1024, 0, 0, inplace=inplace) self._clip_type('int', 1024, -120, 100.5, inplace=inplace) self._clip_type('int', 1024, 0, 0, inplace=inplace) x = self._clip_type('uint', 1024, -120, 100, expected_min=0, inplace=inplace) x = self._clip_type('uint', 1024, 0, 0, inplace=inplace) def test_record_array(self): rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')]) y = rec['x'].clip(-0.3, 0.5) self._check_range(y, -0.3, 0.5) def test_max_or_min(self): val = np.array([0, 1, 2, 3, 4, 5, 6, 7]) x = val.clip(3) assert_(np.all(x >= 3)) x = val.clip(min=3) assert_(np.all(x >= 3)) x = val.clip(max=4) assert_(np.all(x <= 4)) class TestPutmask(object): def tst_basic(self, x, T, mask, val): np.putmask(x, mask, val) assert_(np.all(x[mask] == T(val))) assert_(x.dtype == T) def test_ip_types(self): unchecked_types = [str, unicode, np.void, object] x = np.random.random(1000)*100 mask = x < 40 for val in [-100, 0, 15]: for types in np.sctypes.values(): for T in types: if T not in unchecked_types: yield self.tst_basic, x.copy().astype(T), T, mask, val def test_mask_size(self): assert_raises(ValueError, np.putmask, np.array([1, 2, 3]), [True], 5) def tst_byteorder(self, dtype): x = np.array([1, 2, 3], dtype) np.putmask(x, [True, False, True], -1) assert_array_equal(x, [-1, 2, -1]) def test_ip_byteorder(self): for dtype in ('>i4', '<i4'): yield self.tst_byteorder, dtype def test_record_array(self): # Note mixed byteorder. rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '<f8'), ('y', '>f8'), ('z', '<f8')]) np.putmask(rec['x'], [True, False], 10) assert_array_equal(rec['x'], [10, 5]) assert_array_equal(rec['y'], [2, 4]) assert_array_equal(rec['z'], [3, 3]) np.putmask(rec['y'], [True, False], 11) assert_array_equal(rec['x'], [10, 5]) assert_array_equal(rec['y'], [11, 4]) assert_array_equal(rec['z'], [3, 3]) def test_masked_array(self): ## x = np.array([1,2,3]) ## z = np.ma.array(x,mask=[True,False,False]) ## np.putmask(z,[True,True,True],3) pass class TestTake(object): def tst_basic(self, x): ind = list(range(x.shape[0])) assert_array_equal(x.take(ind, axis=0), x) def test_ip_types(self): unchecked_types = [str, unicode, np.void, object] x = np.random.random(24)*100 x.shape = 2, 3, 4 for types in np.sctypes.values(): for T in types: if T not in unchecked_types: yield self.tst_basic, x.copy().astype(T) def test_raise(self): x = np.random.random(24)*100 x.shape = 2, 3, 4 assert_raises(IndexError, x.take, [0, 1, 2], axis=0) assert_raises(IndexError, x.take, [-3], axis=0) assert_array_equal(x.take([-1], axis=0)[0], x[1]) def test_clip(self): x = np.random.random(24)*100 x.shape = 2, 3, 4 assert_array_equal(x.take([-1], axis=0, mode='clip')[0], x[0]) assert_array_equal(x.take([2], axis=0, mode='clip')[0], x[1]) def test_wrap(self): x = np.random.random(24)*100 x.shape = 2, 3, 4 assert_array_equal(x.take([-1], axis=0, mode='wrap')[0], x[1]) assert_array_equal(x.take([2], axis=0, mode='wrap')[0], x[0]) assert_array_equal(x.take([3], axis=0, mode='wrap')[0], x[1]) def tst_byteorder(self, dtype): x = np.array([1, 2, 3], dtype) assert_array_equal(x.take([0, 2, 1]), [1, 3, 2]) def test_ip_byteorder(self): for dtype in ('>i4', '<i4'): yield self.tst_byteorder, dtype def test_record_array(self): # Note mixed byteorder. rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '<f8'), ('y', '>f8'), ('z', '<f8')]) rec1 = rec.take([1]) assert_(rec1['x'] == 5.0 and rec1['y'] == 4.0) class TestLexsort(TestCase): def test_basic(self): a = [1, 2, 1, 3, 1, 5] b = [0, 4, 5, 6, 2, 3] idx = np.lexsort((b, a)) expected_idx = np.array([0, 4, 2, 1, 3, 5]) assert_array_equal(idx, expected_idx) x = np.vstack((b, a)) idx = np.lexsort(x) assert_array_equal(idx, expected_idx) assert_array_equal(x[1][idx], np.sort(x[1])) def test_datetime(self): a = np.array([0,0,0], dtype='datetime64[D]') b = np.array([2,1,0], dtype='datetime64[D]') idx = np.lexsort((b, a)) expected_idx = np.array([2, 1, 0]) assert_array_equal(idx, expected_idx) a = np.array([0,0,0], dtype='timedelta64[D]') b = np.array([2,1,0], dtype='timedelta64[D]') idx = np.lexsort((b, a)) expected_idx = np.array([2, 1, 0]) assert_array_equal(idx, expected_idx) class TestIO(object): """Test tofile, fromfile, tobytes, and fromstring""" def setUp(self): shape = (2, 4, 3) rand = np.random.random self.x = rand(shape) + rand(shape).astype(np.complex)*1j self.x[0,:, 1] = [nan, inf, -inf, nan] self.dtype = self.x.dtype self.tempdir = tempfile.mkdtemp() self.filename = tempfile.mktemp(dir=self.tempdir) def tearDown(self): shutil.rmtree(self.tempdir) def test_bool_fromstring(self): v = np.array([True, False, True, False], dtype=np.bool_) y = np.fromstring('1 0 -2.3 0.0', sep=' ', dtype=np.bool_) assert_array_equal(v, y) def test_uint64_fromstring(self): d = np.fromstring("9923372036854775807 104783749223640", dtype=np.uint64, sep=' '); e = np.array([9923372036854775807, 104783749223640], dtype=np.uint64) assert_array_equal(d, e) def test_int64_fromstring(self): d = np.fromstring("-25041670086757 104783749223640", dtype=np.int64, sep=' '); e = np.array([-25041670086757, 104783749223640], dtype=np.int64) assert_array_equal(d, e) def test_empty_files_binary(self): f = open(self.filename, 'w') f.close() y = fromfile(self.filename) assert_(y.size == 0, "Array not empty") def test_empty_files_text(self): f = open(self.filename, 'w') f.close() y = fromfile(self.filename, sep=" ") assert_(y.size == 0, "Array not empty") def test_roundtrip_file(self): f = open(self.filename, 'wb') self.x.tofile(f) f.close() # NB. doesn't work with flush+seek, due to use of C stdio f = open(self.filename, 'rb') y = np.fromfile(f, dtype=self.dtype) f.close() assert_array_equal(y, self.x.flat) def test_roundtrip_filename(self): self.x.tofile(self.filename) y = np.fromfile(self.filename, dtype=self.dtype) assert_array_equal(y, self.x.flat) def test_roundtrip_binary_str(self): s = self.x.tobytes() y = np.fromstring(s, dtype=self.dtype) assert_array_equal(y, self.x.flat) s = self.x.tobytes('F') y = np.fromstring(s, dtype=self.dtype) assert_array_equal(y, self.x.flatten('F')) def test_roundtrip_str(self): x = self.x.real.ravel() s = "@".join(map(str, x)) y = np.fromstring(s, sep="@") # NB. str imbues less precision nan_mask = ~np.isfinite(x) assert_array_equal(x[nan_mask], y[nan_mask]) assert_array_almost_equal(x[~nan_mask], y[~nan_mask], decimal=5) def test_roundtrip_repr(self): x = self.x.real.ravel() s = "@".join(map(repr, x)) y = np.fromstring(s, sep="@") assert_array_equal(x, y) def test_file_position_after_fromfile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, io.DEFAULT_BUFFER_SIZE, io.DEFAULT_BUFFER_SIZE*8] for size in sizes: f = open(self.filename, 'wb') f.seek(size-1) f.write(b'\0') f.close() for mode in ['rb', 'r+b']: err_msg = "%d %s" % (size, mode) f = open(self.filename, mode) f.read(2) np.fromfile(f, dtype=np.float64, count=1) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) def test_file_position_after_tofile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, io.DEFAULT_BUFFER_SIZE, io.DEFAULT_BUFFER_SIZE*8] for size in sizes: err_msg = "%d" % (size,) f = open(self.filename, 'wb') f.seek(size-1) f.write(b'\0') f.seek(10) f.write(b'12') np.array([0], dtype=np.float64).tofile(f) pos = f.tell() f.close() assert_equal(pos, 10 + 2 + 8, err_msg=err_msg) f = open(self.filename, 'r+b') f.read(2) f.seek(0, 1) # seek between read&write required by ANSI C np.array([0], dtype=np.float64).tofile(f) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) def _check_from(self, s, value, **kw): y = np.fromstring(asbytes(s), **kw) assert_array_equal(y, value) f = open(self.filename, 'wb') f.write(asbytes(s)) f.close() y = np.fromfile(self.filename, **kw) assert_array_equal(y, value) def test_nan(self): self._check_from("nan +nan -nan NaN nan(foo) +NaN(BAR) -NAN(q_u_u_x_)", [nan, nan, nan, nan, nan, nan, nan], sep=' ') def test_inf(self): self._check_from("inf +inf -inf infinity -Infinity iNfInItY -inF", [inf, inf, -inf, inf, -inf, inf, -inf], sep=' ') def test_numbers(self): self._check_from("1.234 -1.234 .3 .3e55 -123133.1231e+133", [1.234, -1.234, .3, .3e55, -123133.1231e+133], sep=' ') def test_binary(self): self._check_from('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', array([1, 2, 3, 4]), dtype='<f4') @dec.slow # takes > 1 minute on mechanical hard drive def test_big_binary(self): """Test workarounds for 32-bit limited fwrite, fseek, and ftell calls in windows. These normally would hang doing something like this. See http://projects.scipy.org/numpy/ticket/1660""" if sys.platform != 'win32': return try: # before workarounds, only up to 2**32-1 worked fourgbplus = 2**32 + 2**16 testbytes = np.arange(8, dtype=np.int8) n = len(testbytes) flike = tempfile.NamedTemporaryFile() f = flike.file np.tile(testbytes, fourgbplus // testbytes.nbytes).tofile(f) flike.seek(0) a = np.fromfile(f, dtype=np.int8) flike.close() assert_(len(a) == fourgbplus) # check only start and end for speed: assert_((a[:n] == testbytes).all()) assert_((a[-n:] == testbytes).all()) except (MemoryError, ValueError): pass def test_string(self): self._check_from('1,2,3,4', [1., 2., 3., 4.], sep=',') def test_counted_string(self): self._check_from('1,2,3,4', [1., 2., 3., 4.], count=4, sep=',') self._check_from('1,2,3,4', [1., 2., 3.], count=3, sep=',') self._check_from('1,2,3,4', [1., 2., 3., 4.], count=-1, sep=',') def test_string_with_ws(self): self._check_from('1 2 3 4 ', [1, 2, 3, 4], dtype=int, sep=' ') def test_counted_string_with_ws(self): self._check_from('1 2 3 4 ', [1, 2, 3], count=3, dtype=int, sep=' ') def test_ascii(self): self._check_from('1 , 2 , 3 , 4', [1., 2., 3., 4.], sep=',') self._check_from('1,2,3,4', [1., 2., 3., 4.], dtype=float, sep=',') def test_malformed(self): self._check_from('1.234 1,234', [1.234, 1.], sep=' ') def test_long_sep(self): self._check_from('1_x_3_x_4_x_5', [1, 3, 4, 5], sep='_x_') def test_dtype(self): v = np.array([1, 2, 3, 4], dtype=np.int_) self._check_from('1,2,3,4', v, sep=',', dtype=np.int_) def test_dtype_bool(self): # can't use _check_from because fromstring can't handle True/False v = np.array([True, False, True, False], dtype=np.bool_) s = '1,0,-2.3,0' f = open(self.filename, 'wb') f.write(asbytes(s)) f.close() y = np.fromfile(self.filename, sep=',', dtype=np.bool_) assert_(y.dtype == '?') assert_array_equal(y, v) def test_tofile_sep(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.0,3.51,4.0') def test_tofile_format(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',', format='%.2f') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.00,3.51,4.00') def test_locale(self): in_foreign_locale(self.test_numbers)() in_foreign_locale(self.test_nan)() in_foreign_locale(self.test_inf)() in_foreign_locale(self.test_counted_string)() in_foreign_locale(self.test_ascii)() in_foreign_locale(self.test_malformed)() in_foreign_locale(self.test_tofile_sep)() in_foreign_locale(self.test_tofile_format)() class TestFromBuffer(object): def tst_basic(self, buffer, expected, kwargs): assert_array_equal(np.frombuffer(buffer,**kwargs), expected) def test_ip_basic(self): for byteorder in ['<', '>']: for dtype in [float, int, np.complex]: dt = np.dtype(dtype).newbyteorder(byteorder) x = (np.random.random((4, 7))*5).astype(dt) buf = x.tobytes() yield self.tst_basic, buf, x.flat, {'dtype':dt} def test_empty(self): yield self.tst_basic, asbytes(''), np.array([]), {} class TestFlat(TestCase): def setUp(self): a0 = arange(20.0) a = a0.reshape(4, 5) a0.shape = (4, 5) a.flags.writeable = False self.a = a self.b = a[::2, ::2] self.a0 = a0 self.b0 = a0[::2, ::2] def test_contiguous(self): testpassed = False try: self.a.flat[12] = 100.0 except ValueError: testpassed = True assert testpassed assert self.a.flat[12] == 12.0 def test_discontiguous(self): testpassed = False try: self.b.flat[4] = 100.0 except ValueError: testpassed = True assert testpassed assert self.b.flat[4] == 12.0 def test___array__(self): c = self.a.flat.__array__() d = self.b.flat.__array__() e = self.a0.flat.__array__() f = self.b0.flat.__array__() assert c.flags.writeable is False assert d.flags.writeable is False assert e.flags.writeable is True assert f.flags.writeable is True assert c.flags.updateifcopy is False assert d.flags.updateifcopy is False assert e.flags.updateifcopy is False assert f.flags.updateifcopy is True assert f.base is self.b0 class TestResize(TestCase): def test_basic(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) x.resize((5, 5)) assert_array_equal(x.flat[:9], np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).flat) assert_array_equal(x[9:].flat, 0) def test_check_reference(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) y = x self.assertRaises(ValueError, x.resize, (5, 1)) def test_int_shape(self): x = np.eye(3) x.resize(3) assert_array_equal(x, np.eye(3)[0,:]) def test_none_shape(self): x = np.eye(3) x.resize(None) assert_array_equal(x, np.eye(3)) x.resize() assert_array_equal(x, np.eye(3)) def test_invalid_arguements(self): self.assertRaises(TypeError, np.eye(3).resize, 'hi') self.assertRaises(ValueError, np.eye(3).resize, -1) self.assertRaises(TypeError, np.eye(3).resize, order=1) self.assertRaises(TypeError, np.eye(3).resize, refcheck='hi') def test_freeform_shape(self): x = np.eye(3) x.resize(3, 2, 1) assert_(x.shape == (3, 2, 1)) def test_zeros_appended(self): x = np.eye(3) x.resize(2, 3, 3) assert_array_equal(x[0], np.eye(3)) assert_array_equal(x[1], np.zeros((3, 3))) def test_obj_obj(self): # check memory is initialized on resize, gh-4857 a = ones(10, dtype=[('k', object, 2)]) a.resize(15,) assert_equal(a.shape, (15,)) assert_array_equal(a['k'][-5:], 0) assert_array_equal(a['k'][:-5], 1) class TestRecord(TestCase): def test_field_rename(self): dt = np.dtype([('f', float), ('i', int)]) dt.names = ['p', 'q'] assert_equal(dt.names, ['p', 'q']) if sys.version_info[0] >= 3: def test_bytes_fields(self): # Bytes are not allowed in field names and not recognized in titles # on Py3 assert_raises(TypeError, np.dtype, [(asbytes('a'), int)]) assert_raises(TypeError, np.dtype, [(('b', asbytes('a')), int)]) dt = np.dtype([((asbytes('a'), 'b'), int)]) assert_raises(ValueError, dt.__getitem__, asbytes('a')) x = np.array([(1,), (2,), (3,)], dtype=dt) assert_raises(IndexError, x.__getitem__, asbytes('a')) y = x[0] assert_raises(IndexError, y.__getitem__, asbytes('a')) else: def test_unicode_field_titles(self): # Unicode field titles are added to field dict on Py2 title = unicode('b') dt = np.dtype([((title, 'a'), int)]) dt[title] dt['a'] x = np.array([(1,), (2,), (3,)], dtype=dt) x[title] x['a'] y = x[0] y[title] y['a'] def test_unicode_field_names(self): # Unicode field names are not allowed on Py2 title = unicode('b') assert_raises(TypeError, np.dtype, [(title, int)]) assert_raises(TypeError, np.dtype, [(('a', title), int)]) def test_field_names(self): # Test unicode and 8-bit / byte strings can be used a = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) is_py3 = sys.version_info[0] >= 3 if is_py3: funcs = (str,) # byte string indexing fails gracefully assert_raises(IndexError, a.__setitem__, asbytes('f1'), 1) assert_raises(IndexError, a.__getitem__, asbytes('f1')) assert_raises(IndexError, a['f1'].__setitem__, asbytes('sf1'), 1) assert_raises(IndexError, a['f1'].__getitem__, asbytes('sf1')) else: funcs = (str, unicode) for func in funcs: b = a.copy() fn1 = func('f1') b[fn1] = 1 assert_equal(b[fn1], 1) fnn = func('not at all') assert_raises(ValueError, b.__setitem__, fnn, 1) assert_raises(ValueError, b.__getitem__, fnn) b[0][fn1] = 2 assert_equal(b[fn1], 2) # Subfield assert_raises(IndexError, b[0].__setitem__, fnn, 1) assert_raises(IndexError, b[0].__getitem__, fnn) # Subfield fn3 = func('f3') sfn1 = func('sf1') b[fn3][sfn1] = 1 assert_equal(b[fn3][sfn1], 1) assert_raises(ValueError, b[fn3].__setitem__, fnn, 1) assert_raises(ValueError, b[fn3].__getitem__, fnn) # multiple Subfields fn2 = func('f2') b[fn2] = 3 assert_equal(b[['f1', 'f2']][0].tolist(), (2, 3)) assert_equal(b[['f2', 'f1']][0].tolist(), (3, 2)) assert_equal(b[['f1', 'f3']][0].tolist(), (2, (1,))) # view of subfield view/copy assert_equal(b[['f1', 'f2']][0].view(('i4', 2)).tolist(), (2, 3)) assert_equal(b[['f2', 'f1']][0].view(('i4', 2)).tolist(), (3, 2)) view_dtype=[('f1', 'i4'), ('f3', [('', 'i4')])] assert_equal(b[['f1', 'f3']][0].view(view_dtype).tolist(), (2, (1,))) # non-ascii unicode field indexing is well behaved if not is_py3: raise SkipTest('non ascii unicode field indexing skipped; ' 'raises segfault on python 2.x') else: assert_raises(ValueError, a.__setitem__, sixu('\u03e0'), 1) assert_raises(ValueError, a.__getitem__, sixu('\u03e0')) def test_field_names_deprecation(self): def collect_warnings(f, *args, **kwargs): with warnings.catch_warnings(record=True) as log: warnings.simplefilter("always") f(*args, **kwargs) return [w.category for w in log] a = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) a['f1'][0] = 1 a['f2'][0] = 2 a['f3'][0] = (3,) b = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) b['f1'][0] = 1 b['f2'][0] = 2 b['f3'][0] = (3,) # All the different functions raise a warning, but not an error, and # 'a' is not modified: assert_equal(collect_warnings(a[['f1', 'f2']].__setitem__, 0, (10, 20)), [FutureWarning]) assert_equal(a, b) # Views also warn subset = a[['f1', 'f2']] subset_view = subset.view() assert_equal(collect_warnings(subset_view['f1'].__setitem__, 0, 10), [FutureWarning]) # But the write goes through: assert_equal(subset['f1'][0], 10) # Only one warning per multiple field indexing, though (even if there # are multiple views involved): assert_equal(collect_warnings(subset['f1'].__setitem__, 0, 10), []) def test_record_hash(self): a = np.array([(1, 2), (1, 2)], dtype='i1,i2') a.flags.writeable = False b = np.array([(1, 2), (3, 4)], dtype=[('num1', 'i1'), ('num2', 'i2')]) b.flags.writeable = False c = np.array([(1, 2), (3, 4)], dtype='i1,i2') c.flags.writeable = False self.assertTrue(hash(a[0]) == hash(a[1])) self.assertTrue(hash(a[0]) == hash(b[0])) self.assertTrue(hash(a[0]) != hash(b[1])) self.assertTrue(hash(c[0]) == hash(a[0]) and c[0] == a[0]) def test_record_no_hash(self): a = np.array([(1, 2), (1, 2)], dtype='i1,i2') self.assertRaises(TypeError, hash, a[0]) def test_empty_structure_creation(self): # make sure these do not raise errors (gh-5631) array([()], dtype={'names': [], 'formats': [], 'offsets': [], 'itemsize': 12}) array([(), (), (), (), ()], dtype={'names': [], 'formats': [], 'offsets': [], 'itemsize': 12}) class TestView(TestCase): def test_basic(self): x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype=[('r', np.int8), ('g', np.int8), ('b', np.int8), ('a', np.int8)]) # We must be specific about the endianness here: y = x.view(dtype='<i4') # ... and again without the keyword. z = x.view('<i4') assert_array_equal(y, z) assert_array_equal(y, [67305985, 134678021]) def _mean(a, **args): return a.mean(**args) def _var(a, **args): return a.var(**args) def _std(a, **args): return a.std(**args) class TestStats(TestCase): funcs = [_mean, _var, _std] def setUp(self): np.random.seed(range(3)) self.rmat = np.random.random((4, 5)) self.cmat = self.rmat + 1j * self.rmat self.omat = np.array([Decimal(repr(r)) for r in self.rmat.flat]) self.omat = self.omat.reshape(4, 5) def test_keepdims(self): mat = np.eye(3) for f in self.funcs: for axis in [0, 1]: res = f(mat, axis=axis, keepdims=True) assert_(res.ndim == mat.ndim) assert_(res.shape[axis] == 1) for axis in [None]: res = f(mat, axis=axis, keepdims=True) assert_(res.shape == (1, 1)) def test_out(self): mat = np.eye(3) for f in self.funcs: out = np.zeros(3) tgt = f(mat, axis=1) res = f(mat, axis=1, out=out) assert_almost_equal(res, out) assert_almost_equal(res, tgt) out = np.empty(2) assert_raises(ValueError, f, mat, axis=1, out=out) out = np.empty((2, 2)) assert_raises(ValueError, f, mat, axis=1, out=out) def test_dtype_from_input(self): icodes = np.typecodes['AllInteger'] fcodes = np.typecodes['AllFloat'] # object type for f in self.funcs: mat = np.array([[Decimal(1)]*3]*3) tgt = mat.dtype.type res = f(mat, axis=1).dtype.type assert_(res is tgt) # scalar case res = type(f(mat, axis=None)) assert_(res is Decimal) # integer types for f in self.funcs: for c in icodes: mat = np.eye(3, dtype=c) tgt = np.float64 res = f(mat, axis=1).dtype.type assert_(res is tgt) # scalar case res = f(mat, axis=None).dtype.type assert_(res is tgt) # mean for float types for f in [_mean]: for c in fcodes: mat = np.eye(3, dtype=c) tgt = mat.dtype.type res = f(mat, axis=1).dtype.type assert_(res is tgt) # scalar case res = f(mat, axis=None).dtype.type assert_(res is tgt) # var, std for float types for f in [_var, _std]: for c in fcodes: mat = np.eye(3, dtype=c) # deal with complex types tgt = mat.real.dtype.type res = f(mat, axis=1).dtype.type assert_(res is tgt) # scalar case res = f(mat, axis=None).dtype.type assert_(res is tgt) def test_dtype_from_dtype(self): icodes = np.typecodes['AllInteger'] fcodes = np.typecodes['AllFloat'] mat = np.eye(3) # stats for integer types # fixme: # this needs definition as there are lots places along the line # where type casting may take place. #for f in self.funcs: #for c in icodes: #tgt = np.dtype(c).type #res = f(mat, axis=1, dtype=c).dtype.type #assert_(res is tgt) ## scalar case #res = f(mat, axis=None, dtype=c).dtype.type #assert_(res is tgt) # stats for float types for f in self.funcs: for c in fcodes: tgt = np.dtype(c).type res = f(mat, axis=1, dtype=c).dtype.type assert_(res is tgt) # scalar case res = f(mat, axis=None, dtype=c).dtype.type assert_(res is tgt) def test_ddof(self): for f in [_var]: for ddof in range(3): dim = self.rmat.shape[1] tgt = f(self.rmat, axis=1) * dim res = f(self.rmat, axis=1, ddof=ddof) * (dim - ddof) for f in [_std]: for ddof in range(3): dim = self.rmat.shape[1] tgt = f(self.rmat, axis=1) * np.sqrt(dim) res = f(self.rmat, axis=1, ddof=ddof) * np.sqrt(dim - ddof) assert_almost_equal(res, tgt) assert_almost_equal(res, tgt) def test_ddof_too_big(self): dim = self.rmat.shape[1] for f in [_var, _std]: for ddof in range(dim, dim + 2): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') res = f(self.rmat, axis=1, ddof=ddof) assert_(not (res < 0).any()) assert_(len(w) > 0) assert_(issubclass(w[0].category, RuntimeWarning)) def test_empty(self): A = np.zeros((0, 3)) for f in self.funcs: for axis in [0, None]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_(np.isnan(f(A, axis=axis)).all()) assert_(len(w) > 0) assert_(issubclass(w[0].category, RuntimeWarning)) for axis in [1]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_equal(f(A, axis=axis), np.zeros([])) def test_mean_values(self): for mat in [self.rmat, self.cmat, self.omat]: for axis in [0, 1]: tgt = mat.sum(axis=axis) res = _mean(mat, axis=axis) * mat.shape[axis] assert_almost_equal(res, tgt) for axis in [None]: tgt = mat.sum(axis=axis) res = _mean(mat, axis=axis) * np.prod(mat.shape) assert_almost_equal(res, tgt) def test_var_values(self): for mat in [self.rmat, self.cmat, self.omat]: for axis in [0, 1, None]: msqr = _mean(mat * mat.conj(), axis=axis) mean = _mean(mat, axis=axis) tgt = msqr - mean * mean.conjugate() res = _var(mat, axis=axis) assert_almost_equal(res, tgt) def test_std_values(self): for mat in [self.rmat, self.cmat, self.omat]: for axis in [0, 1, None]: tgt = np.sqrt(_var(mat, axis=axis)) res = _std(mat, axis=axis) assert_almost_equal(res, tgt) def test_subclass(self): class TestArray(np.ndarray): def __new__(cls, data, info): result = np.array(data) result = result.view(cls) result.info = info return result def __array_finalize__(self, obj): self.info = getattr(obj, "info", '') dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba') res = dat.mean(1) assert_(res.info == dat.info) res = dat.std(1) assert_(res.info == dat.info) res = dat.var(1) assert_(res.info == dat.info) class TestVdot(TestCase): def test_basic(self): dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger'] dt_complex = np.typecodes['Complex'] # test real a = np.eye(3) for dt in dt_numeric + 'O': b = a.astype(dt) res = np.vdot(b, b) assert_(np.isscalar(res)) assert_equal(np.vdot(b, b), 3) # test complex a = np.eye(3) * 1j for dt in dt_complex + 'O': b = a.astype(dt) res = np.vdot(b, b) assert_(np.isscalar(res)) assert_equal(np.vdot(b, b), 3) # test boolean b = np.eye(3, dtype=np.bool) res = np.vdot(b, b) assert_(np.isscalar(res)) assert_equal(np.vdot(b, b), True) def test_vdot_array_order(self): a = array([[1, 2], [3, 4]], order='C') b = array([[1, 2], [3, 4]], order='F') res = np.vdot(a, a) # integer arrays are exact assert_equal(np.vdot(a, b), res) assert_equal(np.vdot(b, a), res) assert_equal(np.vdot(b, b), res) class TestDot(TestCase): def test_dot_2args(self): from numpy.core.multiarray import dot a = np.array([[1, 2], [3, 4]], dtype=float) b = np.array([[1, 0], [1, 1]], dtype=float) c = np.array([[3, 2], [7, 4]], dtype=float) d = dot(a, b) assert_allclose(c, d) def test_dot_3args(self): from numpy.core.multiarray import dot np.random.seed(22) f = np.random.random_sample((1024, 16)) v = np.random.random_sample((16, 32)) r = np.empty((1024, 32)) for i in range(12): dot(f, v, r) assert_equal(sys.getrefcount(r), 2) r2 = dot(f, v, out=None) assert_array_equal(r2, r) assert_(r is dot(f, v, out=r)) v = v[:, 0].copy() # v.shape == (16,) r = r[:, 0].copy() # r.shape == (1024,) r2 = dot(f, v) assert_(r is dot(f, v, r)) assert_array_equal(r2, r) def test_dot_3args_errors(self): from numpy.core.multiarray import dot np.random.seed(22) f = np.random.random_sample((1024, 16)) v = np.random.random_sample((16, 32)) r = np.empty((1024, 31)) assert_raises(ValueError, dot, f, v, r) r = np.empty((1024,)) assert_raises(ValueError, dot, f, v, r) r = np.empty((32,)) assert_raises(ValueError, dot, f, v, r) r = np.empty((32, 1024)) assert_raises(ValueError, dot, f, v, r) assert_raises(ValueError, dot, f, v, r.T) r = np.empty((1024, 64)) assert_raises(ValueError, dot, f, v, r[:, ::2]) assert_raises(ValueError, dot, f, v, r[:, :32]) r = np.empty((1024, 32), dtype=np.float32) assert_raises(ValueError, dot, f, v, r) r = np.empty((1024, 32), dtype=int) assert_raises(ValueError, dot, f, v, r) def test_dot_array_order(self): a = array([[1, 2], [3, 4]], order='C') b = array([[1, 2], [3, 4]], order='F') res = np.dot(a, a) # integer arrays are exact assert_equal(np.dot(a, b), res) assert_equal(np.dot(b, a), res) assert_equal(np.dot(b, b), res) def test_dot_scalar_and_matrix_of_objects(self): # Ticket #2469 arr = np.matrix([1, 2], dtype=object) desired = np.matrix([[3, 6]], dtype=object) assert_equal(np.dot(arr, 3), desired) assert_equal(np.dot(3, arr), desired) def test_dot_override(self): class A(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return "A" class B(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return NotImplemented a = A() b = B() c = np.array([[1]]) assert_equal(np.dot(a, b), "A") assert_equal(c.dot(a), "A") assert_raises(TypeError, np.dot, b, c) assert_raises(TypeError, c.dot, b) def test_accelerate_framework_sgemv_fix(self): if sys.platform != 'darwin': return def aligned_array(shape, align, dtype, order='C'): d = dtype() N = np.prod(shape) tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8) address = tmp.__array_interface__["data"][0] for offset in range(align): if (address + offset) % align == 0: break tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype) return tmp.reshape(shape, order=order) def as_aligned(arr, align, dtype, order='C'): aligned = aligned_array(arr.shape, align, dtype, order) aligned[:] = arr[:] return aligned def assert_dot_close(A, X, desired): assert_allclose(np.dot(A, X), desired, rtol=1e-5, atol=1e-7) m = aligned_array(100, 15, np.float32) s = aligned_array((100, 100), 15, np.float32) np.dot(s, m) # this will always segfault if the bug is present testdata = itertools.product((15,32), (10000,), (200,89), ('C','F')) for align, m, n, a_order in testdata: # Calculation in double precision A_d = np.random.rand(m, n) X_d = np.random.rand(n) desired = np.dot(A_d, X_d) # Calculation with aligned single precision A_f = as_aligned(A_d, align, np.float32, order=a_order) X_f = as_aligned(X_d, align, np.float32) assert_dot_close(A_f, X_f, desired) # Strided A rows A_d_2 = A_d[::2] desired = np.dot(A_d_2, X_d) A_f_2 = A_f[::2] assert_dot_close(A_f_2, X_f, desired) # Strided A columns, strided X vector A_d_22 = A_d_2[:, ::2] X_d_2 = X_d[::2] desired = np.dot(A_d_22, X_d_2) A_f_22 = A_f_2[:, ::2] X_f_2 = X_f[::2] assert_dot_close(A_f_22, X_f_2, desired) # Check the strides are as expected if a_order == 'F': assert_equal(A_f_22.strides, (8, 8 * m)) else: assert_equal(A_f_22.strides, (8 * n, 8)) assert_equal(X_f_2.strides, (8,)) # Strides in A rows + cols only X_f_2c = as_aligned(X_f_2, align, np.float32) assert_dot_close(A_f_22, X_f_2c, desired) # Strides just in A cols A_d_12 = A_d[:, ::2] desired = np.dot(A_d_12, X_d_2) A_f_12 = A_f[:, ::2] assert_dot_close(A_f_12, X_f_2c, desired) # Strides in A cols and X assert_dot_close(A_f_12, X_f_2, desired) class MatmulCommon(): """Common tests for '@' operator and numpy.matmul. Do not derive from TestCase to avoid nose running it. """ # Should work with these types. Will want to add # "O" at some point types = "?bhilqBHILQefdgFDG" def test_exceptions(self): dims = [ ((1,), (2,)), # mismatched vector vector ((2, 1,), (2,)), # mismatched matrix vector ((2,), (1, 2)), # mismatched vector matrix ((1, 2), (3, 1)), # mismatched matrix matrix ((1,), ()), # vector scalar ((), (1)), # scalar vector ((1, 1), ()), # matrix scalar ((), (1, 1)), # scalar matrix ((2, 2, 1), (3, 1, 2)), # cannot broadcast ] for dt, (dm1, dm2) in itertools.product(self.types, dims): a = np.ones(dm1, dtype=dt) b = np.ones(dm2, dtype=dt) assert_raises(ValueError, self.matmul, a, b) def test_shapes(self): dims = [ ((1, 1), (2, 1, 1)), # broadcast first argument ((2, 1, 1), (1, 1)), # broadcast second argument ((2, 1, 1), (2, 1, 1)), # matrix stack sizes match ] for dt, (dm1, dm2) in itertools.product(self.types, dims): a = np.ones(dm1, dtype=dt) b = np.ones(dm2, dtype=dt) res = self.matmul(a, b) assert_(res.shape == (2, 1, 1)) # vector vector returns scalars. for dt in self.types: a = np.ones((2,), dtype=dt) b = np.ones((2,), dtype=dt) c = self.matmul(a, b) assert_(np.array(c).shape == ()) def test_result_types(self): mat = np.ones((1,1)) vec = np.ones((1,)) for dt in self.types: m = mat.astype(dt) v = vec.astype(dt) for arg in [(m, v), (v, m), (m, m)]: res = matmul(*arg) assert_(res.dtype == dt) # vector vector returns scalars res = matmul(v, v) assert_(type(res) is dtype(dt).type) def test_vector_vector_values(self): vec = np.array([1, 2]) tgt = 5 for dt in self.types[1:]: v1 = vec.astype(dt) res = matmul(v1, v1) assert_equal(res, tgt) # boolean type vec = np.array([True, True], dtype='?') res = matmul(vec, vec) assert_equal(res, True) def test_vector_matrix_values(self): vec = np.array([1, 2]) mat1 = np.array([[1, 2], [3, 4]]) mat2 = np.stack([mat1]*2, axis=0) tgt1 = np.array([7, 10]) tgt2 = np.stack([tgt1]*2, axis=0) for dt in self.types[1:]: v = vec.astype(dt) m1 = mat1.astype(dt) m2 = mat2.astype(dt) res = matmul(v, m1) assert_equal(res, tgt1) res = matmul(v, m2) assert_equal(res, tgt2) # boolean type vec = np.array([True, False]) mat1 = np.array([[True, False], [False, True]]) mat2 = np.stack([mat1]*2, axis=0) tgt1 = np.array([True, False]) tgt2 = np.stack([tgt1]*2, axis=0) res = matmul(vec, mat1) assert_equal(res, tgt1) res = matmul(vec, mat2) assert_equal(res, tgt2) def test_matrix_vector_values(self): vec = np.array([1, 2]) mat1 = np.array([[1, 2], [3, 4]]) mat2 = np.stack([mat1]*2, axis=0) tgt1 = np.array([5, 11]) tgt2 = np.stack([tgt1]*2, axis=0) for dt in self.types[1:]: v = vec.astype(dt) m1 = mat1.astype(dt) m2 = mat2.astype(dt) res = matmul(m1, v) assert_equal(res, tgt1) res = matmul(m2, v) assert_equal(res, tgt2) # boolean type vec = np.array([True, False]) mat1 = np.array([[True, False], [False, True]]) mat2 = np.stack([mat1]*2, axis=0) tgt1 = np.array([True, False]) tgt2 = np.stack([tgt1]*2, axis=0) res = matmul(vec, mat1) assert_equal(res, tgt1) res = matmul(vec, mat2) assert_equal(res, tgt2) def test_matrix_matrix_values(self): mat1 = np.array([[1, 2], [3, 4]]) mat2 = np.array([[1, 0], [1, 1]]) mat12 = np.stack([mat1, mat2], axis=0) mat21 = np.stack([mat2, mat1], axis=0) tgt11 = np.array([[7, 10], [15, 22]]) tgt12 = np.array([[3, 2], [7, 4]]) tgt21 = np.array([[1, 2], [4, 6]]) tgt22 = np.array([[1, 0], [2, 1]]) tgt12_21 = np.stack([tgt12, tgt21], axis=0) tgt11_12 = np.stack((tgt11, tgt12), axis=0) tgt11_21 = np.stack((tgt11, tgt21), axis=0) for dt in self.types[1:]: m1 = mat1.astype(dt) m2 = mat2.astype(dt) m12 = mat12.astype(dt) m21 = mat21.astype(dt) # matrix @ matrix res = matmul(m1, m2) assert_equal(res, tgt12) res = matmul(m2, m1) assert_equal(res, tgt21) # stacked @ matrix res = self.matmul(m12, m1) assert_equal(res, tgt11_21) # matrix @ stacked res = self.matmul(m1, m12) assert_equal(res, tgt11_12) # stacked @ stacked res = self.matmul(m12, m21) assert_equal(res, tgt12_21) # boolean type m1 = np.array([[1, 1], [0, 0]], dtype=np.bool_) m2 = np.array([[1, 0], [1, 1]], dtype=np.bool_) m12 = np.stack([m1, m2], axis=0) m21 = np.stack([m2, m1], axis=0) tgt11 = m1 tgt12 = m1 tgt21 = np.array([[1, 1], [1, 1]], dtype=np.bool_) tgt22 = m2 tgt12_21 = np.stack([tgt12, tgt21], axis=0) tgt11_12 = np.stack((tgt11, tgt12), axis=0) tgt11_21 = np.stack((tgt11, tgt21), axis=0) # matrix @ matrix res = matmul(m1, m2) assert_equal(res, tgt12) res = matmul(m2, m1) assert_equal(res, tgt21) # stacked @ matrix res = self.matmul(m12, m1) assert_equal(res, tgt11_21) # matrix @ stacked res = self.matmul(m1, m12) assert_equal(res, tgt11_12) # stacked @ stacked res = self.matmul(m12, m21) assert_equal(res, tgt12_21) def test_numpy_ufunc_override(self): class A(np.ndarray): def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return "A" class B(np.ndarray): def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return NotImplemented a = A([1, 2]) b = B([1, 2]) c = ones(2) assert_equal(self.matmul(a, b), "A") assert_equal(self.matmul(b, a), "A") assert_raises(TypeError, self.matmul, b, c) class TestMatmul(MatmulCommon, TestCase): matmul = np.matmul def test_out_arg(self): a = np.ones((2, 2), dtype=np.float) b = np.ones((2, 2), dtype=np.float) tgt = np.full((2,2), 2, dtype=np.float) # test as positional argument msg = "out positional argument" out = np.zeros((2, 2), dtype=np.float) self.matmul(a, b, out) assert_array_equal(out, tgt, err_msg=msg) # test as keyword argument msg = "out keyword argument" out = np.zeros((2, 2), dtype=np.float) self.matmul(a, b, out=out) assert_array_equal(out, tgt, err_msg=msg) # test out with not allowed type cast (safe casting) # einsum and cblas raise different error types, so # use Exception. msg = "out argument with illegal cast" out = np.zeros((2, 2), dtype=np.int32) assert_raises(Exception, self.matmul, a, b, out=out) # skip following tests for now, cblas does not allow non-contiguous # outputs and consistency with dot would require same type, # dimensions, subtype, and c_contiguous. # test out with allowed type cast # msg = "out argument with allowed cast" # out = np.zeros((2, 2), dtype=np.complex128) # self.matmul(a, b, out=out) # assert_array_equal(out, tgt, err_msg=msg) # test out non-contiguous # msg = "out argument with non-contiguous layout" # c = np.zeros((2, 2, 2), dtype=np.float) # self.matmul(a, b, out=c[..., 0]) # assert_array_equal(c, tgt, err_msg=msg) if sys.version_info[:2] >= (3, 5): class TestMatmulOperator(MatmulCommon, TestCase): from operator import matmul def test_array_priority_override(self): class A(object): __array_priority__ = 1000 def __matmul__(self, other): return "A" def __rmatmul__(self, other): return "A" a = A() b = ones(2) assert_equal(self.matmul(a, b), "A") assert_equal(self.matmul(b, a), "A") def test_matmul_inplace(): # It would be nice to support in-place matmul eventually, but for now # we don't have a working implementation, so better just to error out # and nudge people to writing "a = a @ b". a = np.eye(3) b = np.eye(3) assert_raises(TypeError, a.__imatmul__, b) import operator assert_raises(TypeError, operator.imatmul, a, b) # we avoid writing the token `exec` so as not to crash python 2's # parser exec_ = getattr(builtins, "exec") assert_raises(TypeError, exec_, "a @= b", globals(), locals()) class TestInner(TestCase): def test_inner_scalar_and_matrix_of_objects(self): # Ticket #4482 arr = np.matrix([1, 2], dtype=object) desired = np.matrix([[3, 6]], dtype=object) assert_equal(np.inner(arr, 3), desired) assert_equal(np.inner(3, arr), desired) def test_vecself(self): # Ticket 844. # Inner product of a vector with itself segfaults or give # meaningless result a = zeros(shape = (1, 80), dtype = float64) p = inner(a, a) assert_almost_equal(p, 0, decimal=14) class TestSummarization(TestCase): def test_1d(self): A = np.arange(1001) strA = '[ 0 1 2 ..., 998 999 1000]' assert_(str(A) == strA) reprA = 'array([ 0, 1, 2, ..., 998, 999, 1000])' assert_(repr(A) == reprA) def test_2d(self): A = np.arange(1002).reshape(2, 501) strA = '[[ 0 1 2 ..., 498 499 500]\n' \ ' [ 501 502 503 ..., 999 1000 1001]]' assert_(str(A) == strA) reprA = 'array([[ 0, 1, 2, ..., 498, 499, 500],\n' \ ' [ 501, 502, 503, ..., 999, 1000, 1001]])' assert_(repr(A) == reprA) class TestChoose(TestCase): def setUp(self): self.x = 2*ones((3,), dtype=int) self.y = 3*ones((3,), dtype=int) self.x2 = 2*ones((2, 3), dtype=int) self.y2 = 3*ones((2, 3), dtype=int) self.ind = [0, 0, 1] def test_basic(self): A = np.choose(self.ind, (self.x, self.y)) assert_equal(A, [2, 2, 3]) def test_broadcast1(self): A = np.choose(self.ind, (self.x2, self.y2)) assert_equal(A, [[2, 2, 3], [2, 2, 3]]) def test_broadcast2(self): A = np.choose(self.ind, (self.x, self.y2)) assert_equal(A, [[2, 2, 3], [2, 2, 3]]) # TODO: test for multidimensional NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4} class TestNeighborhoodIter(TestCase): # Simple, 2d tests def _test_simple2d(self, dt): # Test zero and one padding for simple data type x = np.array([[0, 1], [2, 3]], dtype=dt) r = [np.array([[0, 0, 0], [0, 0, 1]], dtype=dt), np.array([[0, 0, 0], [0, 1, 0]], dtype=dt), np.array([[0, 0, 1], [0, 2, 3]], dtype=dt), np.array([[0, 1, 0], [2, 3, 0]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['zero']) assert_array_equal(l, r) r = [np.array([[1, 1, 1], [1, 0, 1]], dtype=dt), np.array([[1, 1, 1], [0, 1, 1]], dtype=dt), np.array([[1, 0, 1], [1, 2, 3]], dtype=dt), np.array([[0, 1, 1], [2, 3, 1]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['one']) assert_array_equal(l, r) r = [np.array([[4, 4, 4], [4, 0, 1]], dtype=dt), np.array([[4, 4, 4], [0, 1, 4]], dtype=dt), np.array([[4, 0, 1], [4, 2, 3]], dtype=dt), np.array([[0, 1, 4], [2, 3, 4]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], 4, NEIGH_MODE['constant']) assert_array_equal(l, r) def test_simple2d(self): self._test_simple2d(np.float) def test_simple2d_object(self): self._test_simple2d(Decimal) def _test_mirror2d(self, dt): x = np.array([[0, 1], [2, 3]], dtype=dt) r = [np.array([[0, 0, 1], [0, 0, 1]], dtype=dt), np.array([[0, 1, 1], [0, 1, 1]], dtype=dt), np.array([[0, 0, 1], [2, 2, 3]], dtype=dt), np.array([[0, 1, 1], [2, 3, 3]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['mirror']) assert_array_equal(l, r) def test_mirror2d(self): self._test_mirror2d(np.float) def test_mirror2d_object(self): self._test_mirror2d(Decimal) # Simple, 1d tests def _test_simple(self, dt): # Test padding with constant values x = np.linspace(1, 5, 5).astype(dt) r = [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 0]] l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['zero']) assert_array_equal(l, r) r = [[1, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 1]] l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['one']) assert_array_equal(l, r) r = [[x[4], 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, x[4]]] l = test_neighborhood_iterator(x, [-1, 1], x[4], NEIGH_MODE['constant']) assert_array_equal(l, r) def test_simple_float(self): self._test_simple(np.float) def test_simple_object(self): self._test_simple(Decimal) # Test mirror modes def _test_mirror(self, dt): x = np.linspace(1, 5, 5).astype(dt) r = np.array([[2, 1, 1, 2, 3], [1, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 5], [3, 4, 5, 5, 4]], dtype=dt) l = test_neighborhood_iterator(x, [-2, 2], x[1], NEIGH_MODE['mirror']) self.assertTrue([i.dtype == dt for i in l]) assert_array_equal(l, r) def test_mirror(self): self._test_mirror(np.float) def test_mirror_object(self): self._test_mirror(Decimal) # Circular mode def _test_circular(self, dt): x = np.linspace(1, 5, 5).astype(dt) r = np.array([[4, 5, 1, 2, 3], [5, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 1], [3, 4, 5, 1, 2]], dtype=dt) l = test_neighborhood_iterator(x, [-2, 2], x[0], NEIGH_MODE['circular']) assert_array_equal(l, r) def test_circular(self): self._test_circular(np.float) def test_circular_object(self): self._test_circular(Decimal) # Test stacking neighborhood iterators class TestStackedNeighborhoodIter(TestCase): # Simple, 1d test: stacking 2 constant-padded neigh iterators def test_simple_const(self): dt = np.float64 # Test zero and one padding for simple data type x = np.array([1, 2, 3], dtype=dt) r = [np.array([0], dtype=dt), np.array([0], dtype=dt), np.array([1], dtype=dt), np.array([2], dtype=dt), np.array([3], dtype=dt), np.array([0], dtype=dt), np.array([0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-2, 4], NEIGH_MODE['zero'], [0, 0], NEIGH_MODE['zero']) assert_array_equal(l, r) r = [np.array([1, 0, 1], dtype=dt), np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt), np.array([3, 0, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-1, 1], NEIGH_MODE['one']) assert_array_equal(l, r) # 2nd simple, 1d test: stacking 2 neigh iterators, mixing const padding and # mirror padding def test_simple_mirror(self): dt = np.float64 # Stacking zero on top of mirror x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 1, 1], dtype=dt), np.array([1, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 3], dtype=dt), np.array([3, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['mirror'], [-1, 1], NEIGH_MODE['zero']) assert_array_equal(l, r) # Stacking mirror on top of zero x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 0, 0], dtype=dt), np.array([0, 0, 1], dtype=dt), np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 0], NEIGH_MODE['mirror']) assert_array_equal(l, r) # Stacking mirror on top of zero: 2nd x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt), np.array([3, 0, 0], dtype=dt), np.array([0, 0, 3], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [0, 2], NEIGH_MODE['mirror']) assert_array_equal(l, r) # Stacking mirror on top of zero: 3rd x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 0, 0, 1, 2], dtype=dt), np.array([0, 0, 1, 2, 3], dtype=dt), np.array([0, 1, 2, 3, 0], dtype=dt), np.array([1, 2, 3, 0, 0], dtype=dt), np.array([2, 3, 0, 0, 3], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 2], NEIGH_MODE['mirror']) assert_array_equal(l, r) # 3rd simple, 1d test: stacking 2 neigh iterators, mixing const padding and # circular padding def test_simple_circular(self): dt = np.float64 # Stacking zero on top of mirror x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 3, 1], dtype=dt), np.array([3, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 1], dtype=dt), np.array([3, 1, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['circular'], [-1, 1], NEIGH_MODE['zero']) assert_array_equal(l, r) # Stacking mirror on top of zero x = np.array([1, 2, 3], dtype=dt) r = [np.array([3, 0, 0], dtype=dt), np.array([0, 0, 1], dtype=dt), np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 0], NEIGH_MODE['circular']) assert_array_equal(l, r) # Stacking mirror on top of zero: 2nd x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt), np.array([3, 0, 0], dtype=dt), np.array([0, 0, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [0, 2], NEIGH_MODE['circular']) assert_array_equal(l, r) # Stacking mirror on top of zero: 3rd x = np.array([1, 2, 3], dtype=dt) r = [np.array([3, 0, 0, 1, 2], dtype=dt), np.array([0, 0, 1, 2, 3], dtype=dt), np.array([0, 1, 2, 3, 0], dtype=dt), np.array([1, 2, 3, 0, 0], dtype=dt), np.array([2, 3, 0, 0, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 2], NEIGH_MODE['circular']) assert_array_equal(l, r) # 4th simple, 1d test: stacking 2 neigh iterators, but with lower iterator # being strictly within the array def test_simple_strict_within(self): dt = np.float64 # Stacking zero on top of zero, first neighborhood strictly inside the # array x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 2, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'], [-1, 2], NEIGH_MODE['zero']) assert_array_equal(l, r) # Stacking mirror on top of zero, first neighborhood strictly inside the # array x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 2, 3, 3], dtype=dt)] l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'], [-1, 2], NEIGH_MODE['mirror']) assert_array_equal(l, r) # Stacking mirror on top of zero, first neighborhood strictly inside the # array x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 2, 3, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'], [-1, 2], NEIGH_MODE['circular']) assert_array_equal(l, r) class TestWarnings(object): def test_complex_warning(self): x = np.array([1, 2]) y = np.array([1-2j, 1+2j]) with warnings.catch_warnings(): warnings.simplefilter("error", np.ComplexWarning) assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y) assert_equal(x, [1, 2]) class TestMinScalarType(object): def test_usigned_shortshort(self): dt = np.min_scalar_type(2**8-1) wanted = np.dtype('uint8') assert_equal(wanted, dt) def test_usigned_short(self): dt = np.min_scalar_type(2**16-1) wanted = np.dtype('uint16') assert_equal(wanted, dt) def test_usigned_int(self): dt = np.min_scalar_type(2**32-1) wanted = np.dtype('uint32') assert_equal(wanted, dt) def test_usigned_longlong(self): dt = np.min_scalar_type(2**63-1) wanted = np.dtype('uint64') assert_equal(wanted, dt) def test_object(self): dt = np.min_scalar_type(2**64) wanted = np.dtype('O') assert_equal(wanted, dt) if sys.version_info[:2] == (2, 6): from numpy.core.multiarray import memorysimpleview as memoryview from numpy.core._internal import _dtype_from_pep3118 class TestPEP3118Dtype(object): def _check(self, spec, wanted): dt = np.dtype(wanted) if isinstance(wanted, list) and isinstance(wanted[-1], tuple): if wanted[-1][0] == '': names = list(dt.names) names[-1] = '' dt.names = tuple(names) assert_equal(_dtype_from_pep3118(spec), dt, err_msg="spec %r != dtype %r" % (spec, wanted)) def test_native_padding(self): align = np.dtype('i').alignment for j in range(8): if j == 0: s = 'bi' else: s = 'b%dxi' % j self._check('@'+s, {'f0': ('i1', 0), 'f1': ('i', align*(1 + j//align))}) self._check('='+s, {'f0': ('i1', 0), 'f1': ('i', 1+j)}) def test_native_padding_2(self): # Native padding should work also for structs and sub-arrays self._check('x3T{xi}', {'f0': (({'f0': ('i', 4)}, (3,)), 4)}) self._check('^x3T{xi}', {'f0': (({'f0': ('i', 1)}, (3,)), 1)}) def test_trailing_padding(self): # Trailing padding should be included, *and*, the item size # should match the alignment if in aligned mode align = np.dtype('i').alignment def VV(n): return 'V%d' % (align*(1 + (n-1)//align)) self._check('ix', [('f0', 'i'), ('', VV(1))]) self._check('ixx', [('f0', 'i'), ('', VV(2))]) self._check('ixxx', [('f0', 'i'), ('', VV(3))]) self._check('ixxxx', [('f0', 'i'), ('', VV(4))]) self._check('i7x', [('f0', 'i'), ('', VV(7))]) self._check('^ix', [('f0', 'i'), ('', 'V1')]) self._check('^ixx', [('f0', 'i'), ('', 'V2')]) self._check('^ixxx', [('f0', 'i'), ('', 'V3')]) self._check('^ixxxx', [('f0', 'i'), ('', 'V4')]) self._check('^i7x', [('f0', 'i'), ('', 'V7')]) def test_native_padding_3(self): dt = np.dtype( [('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')], align=True) self._check("T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxxi:c:}", dt) dt = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'), ('e', 'b'), ('sub', np.dtype('b,i', align=True))]) self._check("T{b:a:=i:b:b:c:b:d:b:e:T{b:f0:xxxi:f1:}:sub:}", dt) def test_padding_with_array_inside_struct(self): dt = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')], align=True) self._check("T{b:a:xxxi:b:3b:c:xi:d:}", dt) def test_byteorder_inside_struct(self): # The byte order after @T{=i} should be '=', not '@'. # Check this by noting the absence of native alignment. self._check('@T{^i}xi', {'f0': ({'f0': ('i', 0)}, 0), 'f1': ('i', 5)}) def test_intra_padding(self): # Natively aligned sub-arrays may require some internal padding align = np.dtype('i').alignment def VV(n): return 'V%d' % (align*(1 + (n-1)//align)) self._check('(3)T{ix}', ({'f0': ('i', 0), '': (VV(1), 4)}, (3,))) class TestNewBufferProtocol(object): def _check_roundtrip(self, obj): obj = np.asarray(obj) x = memoryview(obj) y = np.asarray(x) y2 = np.array(x) assert_(not y.flags.owndata) assert_(y2.flags.owndata) assert_equal(y.dtype, obj.dtype) assert_equal(y.shape, obj.shape) assert_array_equal(obj, y) assert_equal(y2.dtype, obj.dtype) assert_equal(y2.shape, obj.shape) assert_array_equal(obj, y2) def test_roundtrip(self): x = np.array([1, 2, 3, 4, 5], dtype='i4') self._check_roundtrip(x) x = np.array([[1, 2], [3, 4]], dtype=np.float64) self._check_roundtrip(x) x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:] self._check_roundtrip(x) dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'), ('i', np.single), ('j', np.double), ('k', np.longdouble), ('ix', np.csingle), ('jx', np.cdouble), ('kx', np.clongdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?'), ('p', np.half), ] x = np.array( [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, asbytes('aaaa'), 'bbbb', asbytes('xxx'), True, 1.0)], dtype=dt) self._check_roundtrip(x) x = np.array(([[1, 2], [3, 4]],), dtype=[('a', (int, (2, 2)))]) self._check_roundtrip(x) x = np.array([1, 2, 3], dtype='>i2') self._check_roundtrip(x) x = np.array([1, 2, 3], dtype='<i2') self._check_roundtrip(x) x = np.array([1, 2, 3], dtype='>i4') self._check_roundtrip(x) x = np.array([1, 2, 3], dtype='<i4') self._check_roundtrip(x) # check long long can be represented as non-native x = np.array([1, 2, 3], dtype='>q') self._check_roundtrip(x) # Native-only data types can be passed through the buffer interface # only in native byte order if sys.byteorder == 'little': x = np.array([1, 2, 3], dtype='>g') assert_raises(ValueError, self._check_roundtrip, x) x = np.array([1, 2, 3], dtype='<g') self._check_roundtrip(x) else: x = np.array([1, 2, 3], dtype='>g') self._check_roundtrip(x) x = np.array([1, 2, 3], dtype='<g') assert_raises(ValueError, self._check_roundtrip, x) def test_roundtrip_half(self): half_list = [ 1.0, -2.0, 6.5504 * 10**4, # (max half precision) 2**-14, # ~= 6.10352 * 10**-5 (minimum positive normal) 2**-24, # ~= 5.96046 * 10**-8 (minimum strictly positive subnormal) 0.0, -0.0, float('+inf'), float('-inf'), 0.333251953125, # ~= 1/3 ] x = np.array(half_list, dtype='>e') self._check_roundtrip(x) x = np.array(half_list, dtype='<e') self._check_roundtrip(x) def test_roundtrip_single_types(self): for typ in np.typeDict.values(): dtype = np.dtype(typ) if dtype.char in 'Mm': # datetimes cannot be used in buffers continue if dtype.char == 'V': # skip void continue x = np.zeros(4, dtype=dtype) self._check_roundtrip(x) if dtype.char not in 'qQgG': dt = dtype.newbyteorder('<') x = np.zeros(4, dtype=dt) self._check_roundtrip(x) dt = dtype.newbyteorder('>') x = np.zeros(4, dtype=dt) self._check_roundtrip(x) def test_roundtrip_scalar(self): # Issue #4015. self._check_roundtrip(0) def test_export_simple_1d(self): x = np.array([1, 2, 3, 4, 5], dtype='i') y = memoryview(x) assert_equal(y.format, 'i') assert_equal(y.shape, (5,)) assert_equal(y.ndim, 1) assert_equal(y.strides, (4,)) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 4) def test_export_simple_nd(self): x = np.array([[1, 2], [3, 4]], dtype=np.float64) y = memoryview(x) assert_equal(y.format, 'd') assert_equal(y.shape, (2, 2)) assert_equal(y.ndim, 2) assert_equal(y.strides, (16, 8)) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 8) def test_export_discontiguous(self): x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:] y = memoryview(x) assert_equal(y.format, 'f') assert_equal(y.shape, (3, 3)) assert_equal(y.ndim, 2) assert_equal(y.strides, (36, 4)) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 4) def test_export_record(self): dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'), ('i', np.single), ('j', np.double), ('k', np.longdouble), ('ix', np.csingle), ('jx', np.cdouble), ('kx', np.clongdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?'), ('p', np.half), ] x = np.array( [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, asbytes('aaaa'), 'bbbb', asbytes(' '), True, 1.0)], dtype=dt) y = memoryview(x) assert_equal(y.shape, (1,)) assert_equal(y.ndim, 1) assert_equal(y.suboffsets, EMPTY) sz = sum([dtype(b).itemsize for a, b in dt]) if dtype('l').itemsize == 4: assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:q:dx:B:e:@H:f:=I:g:L:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') else: assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:q:dx:B:e:@H:f:=I:g:Q:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides if not (np.ones(1).strides[0] == np.iinfo(np.intp).max): assert_equal(y.strides, (sz,)) assert_equal(y.itemsize, sz) def test_export_subarray(self): x = np.array(([[1, 2], [3, 4]],), dtype=[('a', ('i', (2, 2)))]) y = memoryview(x) assert_equal(y.format, 'T{(2,2)i:a:}') assert_equal(y.shape, EMPTY) assert_equal(y.ndim, 0) assert_equal(y.strides, EMPTY) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 16) def test_export_endian(self): x = np.array([1, 2, 3], dtype='>i') y = memoryview(x) if sys.byteorder == 'little': assert_equal(y.format, '>i') else: assert_equal(y.format, 'i') x = np.array([1, 2, 3], dtype='<i') y = memoryview(x) if sys.byteorder == 'little': assert_equal(y.format, 'i') else: assert_equal(y.format, '<i') def test_export_flags(self): # Check SIMPLE flag, see also gh-3613 (exception should be BufferError) assert_raises(ValueError, get_buffer_info, np.arange(5)[::2], ('SIMPLE',)) def test_padding(self): for j in range(8): x = np.array([(1,), (2,)], dtype={'f0': (int, j)}) self._check_roundtrip(x) def test_reference_leak(self): count_1 = sys.getrefcount(np.core._internal) a = np.zeros(4) b = memoryview(a) c = np.asarray(b) count_2 = sys.getrefcount(np.core._internal) assert_equal(count_1, count_2) def test_padded_struct_array(self): dt1 = np.dtype( [('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')], align=True) x1 = np.arange(dt1.itemsize, dtype=np.int8).view(dt1) self._check_roundtrip(x1) dt2 = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')], align=True) x2 = np.arange(dt2.itemsize, dtype=np.int8).view(dt2) self._check_roundtrip(x2) dt3 = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'), ('e', 'b'), ('sub', np.dtype('b,i', align=True))]) x3 = np.arange(dt3.itemsize, dtype=np.int8).view(dt3) self._check_roundtrip(x3) def test_relaxed_strides(self): # Test that relaxed strides are converted to non-relaxed c = np.ones((1, 10, 10), dtype='i8') # Check for NPY_RELAXED_STRIDES_CHECKING: if np.ones((10, 1), order="C").flags.f_contiguous: c.strides = (-1, 80, 8) assert memoryview(c).strides == (800, 80, 8) # Writing C-contiguous data to a BytesIO buffer should work fd = io.BytesIO() fd.write(c.data) fortran = c.T assert memoryview(fortran).strides == (8, 80, 800) arr = np.ones((1, 10)) if arr.flags.f_contiguous: shape, strides = get_buffer_info(arr, ['F_CONTIGUOUS']) assert_(strides[0] == 8) arr = np.ones((10, 1), order='F') shape, strides = get_buffer_info(arr, ['C_CONTIGUOUS']) assert_(strides[-1] == 8) class TestArrayAttributeDeletion(object): def test_multiarray_writable_attributes_deletion(self): """ticket #2046, should not seqfault, raise AttributeError""" a = np.ones(2) attr = ['shape', 'strides', 'data', 'dtype', 'real', 'imag', 'flat'] for s in attr: assert_raises(AttributeError, delattr, a, s) def test_multiarray_not_writable_attributes_deletion(self): a = np.ones(2) attr = ["ndim", "flags", "itemsize", "size", "nbytes", "base", "ctypes", "T", "__array_interface__", "__array_struct__", "__array_priority__", "__array_finalize__"] for s in attr: assert_raises(AttributeError, delattr, a, s) def test_multiarray_flags_writable_attribute_deletion(self): a = np.ones(2).flags attr = ['updateifcopy', 'aligned', 'writeable'] for s in attr: assert_raises(AttributeError, delattr, a, s) def test_multiarray_flags_not_writable_attribute_deletion(self): a = np.ones(2).flags attr = ["contiguous", "c_contiguous", "f_contiguous", "fortran", "owndata", "fnc", "forc", "behaved", "carray", "farray", "num"] for s in attr: assert_raises(AttributeError, delattr, a, s) def test_array_interface(): # Test scalar coercion within the array interface class Foo(object): def __init__(self, value): self.value = value self.iface = {'typestr' : '=f8'} def __float__(self): return float(self.value) @property def __array_interface__(self): return self.iface f = Foo(0.5) assert_equal(np.array(f), 0.5) assert_equal(np.array([f]), [0.5]) assert_equal(np.array([f, f]), [0.5, 0.5]) assert_equal(np.array(f).dtype, np.dtype('=f8')) # Test various shape definitions f.iface['shape'] = () assert_equal(np.array(f), 0.5) f.iface['shape'] = None assert_raises(TypeError, np.array, f) f.iface['shape'] = (1, 1) assert_equal(np.array(f), [[0.5]]) f.iface['shape'] = (2,) assert_raises(ValueError, np.array, f) # test scalar with no shape class ArrayLike(object): array = np.array(1) __array_interface__ = array.__array_interface__ assert_equal(np.array(ArrayLike()), 1) def test_flat_element_deletion(): it = np.ones(3).flat try: del it[1] del it[1:2] except TypeError: pass except: raise AssertionError def test_scalar_element_deletion(): a = np.zeros(2, dtype=[('x', 'int'), ('y', 'int')]) assert_raises(ValueError, a[0].__delitem__, 'x') class TestMemEventHook(TestCase): def test_mem_seteventhook(self): # The actual tests are within the C code in # multiarray/multiarray_tests.c.src test_pydatamem_seteventhook_start() # force an allocation and free of a numpy array # needs to be larger then limit of small memory cacher in ctors.c a = np.zeros(1000) del a test_pydatamem_seteventhook_end() class TestMapIter(TestCase): def test_mapiter(self): # The actual tests are within the C code in # multiarray/multiarray_tests.c.src a = arange(12).reshape((3, 4)).astype(float) index = ([1, 1, 2, 0], [0, 0, 2, 3]) vals = [50, 50, 30, 16] test_inplace_increment(a, index, vals) assert_equal(a, [[ 0., 1., 2., 19.,], [ 104., 5., 6., 7.,], [ 8., 9., 40., 11.,]]) b = arange(6).astype(float) index = (array([1, 2, 0]),) vals = [50, 4, 100.1] test_inplace_increment(b, index, vals) assert_equal(b, [ 100.1, 51., 6., 3., 4., 5. ]) class TestAsCArray(TestCase): def test_1darray(self): array = np.arange(24, dtype=np.double) from_c = test_as_c_array(array, 3) assert_equal(array[3], from_c) def test_2darray(self): array = np.arange(24, dtype=np.double).reshape(3, 8) from_c = test_as_c_array(array, 2, 4) assert_equal(array[2, 4], from_c) def test_3darray(self): array = np.arange(24, dtype=np.double).reshape(2, 3, 4) from_c = test_as_c_array(array, 1, 2, 3) assert_equal(array[1, 2, 3], from_c) class PriorityNdarray(): __array_priority__ = 1000 def __init__(self, array): self.array = array def __lt__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array < array) def __gt__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array > array) def __le__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array <= array) def __ge__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array >= array) def __eq__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array == array) def __ne__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array != array) class TestArrayPriority(TestCase): def test_lt(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l < r res2 = l < rp res3 = lp < r res4 = lp < rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_gt(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l > r res2 = l > rp res3 = lp > r res4 = lp > rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_le(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l <= r res2 = l <= rp res3 = lp <= r res4 = lp <= rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_ge(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l >= r res2 = l >= rp res3 = lp >= r res4 = lp >= rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_eq(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l == r res2 = l == rp res3 = lp == r res4 = lp == rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_ne(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l != r res2 = l != rp res3 = lp != r res4 = lp != rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) class TestConversion(TestCase): def test_array_scalar_relational_operation(self): #All integer for dt1 in np.typecodes['AllInteger']: assert_(1 > np.array(0, dtype=dt1), "type %s failed" % (dt1,)) assert_(not 1 < np.array(0, dtype=dt1), "type %s failed" % (dt1,)) for dt2 in np.typecodes['AllInteger']: assert_(np.array(1, dtype=dt1) > np.array(0, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1) < np.array(0, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) #Unsigned integers for dt1 in 'BHILQP': assert_(-1 < np.array(1, dtype=dt1), "type %s failed" % (dt1,)) assert_(not -1 > np.array(1, dtype=dt1), "type %s failed" % (dt1,)) assert_(-1 != np.array(1, dtype=dt1), "type %s failed" % (dt1,)) #unsigned vs signed for dt2 in 'bhilqp': assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) assert_(np.array(1, dtype=dt1) != np.array(-1, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) #Signed integers and floats for dt1 in 'bhlqp' + np.typecodes['Float']: assert_(1 > np.array(-1, dtype=dt1), "type %s failed" % (dt1,)) assert_(not 1 < np.array(-1, dtype=dt1), "type %s failed" % (dt1,)) assert_(-1 == np.array(-1, dtype=dt1), "type %s failed" % (dt1,)) for dt2 in 'bhlqp' + np.typecodes['Float']: assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) assert_(np.array(-1, dtype=dt1) == np.array(-1, dtype=dt2), "type %s and %s failed" % (dt1, dt2)) class TestWhere(TestCase): def test_basic(self): dts = [np.bool, np.int16, np.int32, np.int64, np.double, np.complex128, np.longdouble, np.clongdouble] for dt in dts: c = np.ones(53, dtype=np.bool) assert_equal(np.where( c, dt(0), dt(1)), dt(0)) assert_equal(np.where(~c, dt(0), dt(1)), dt(1)) assert_equal(np.where(True, dt(0), dt(1)), dt(0)) assert_equal(np.where(False, dt(0), dt(1)), dt(1)) d = np.ones_like(c).astype(dt) e = np.zeros_like(d) r = d.astype(dt) c[7] = False r[7] = e[7] assert_equal(np.where(c, e, e), e) assert_equal(np.where(c, d, e), r) assert_equal(np.where(c, d, e[0]), r) assert_equal(np.where(c, d[0], e), r) assert_equal(np.where(c[::2], d[::2], e[::2]), r[::2]) assert_equal(np.where(c[1::2], d[1::2], e[1::2]), r[1::2]) assert_equal(np.where(c[::3], d[::3], e[::3]), r[::3]) assert_equal(np.where(c[1::3], d[1::3], e[1::3]), r[1::3]) assert_equal(np.where(c[::-2], d[::-2], e[::-2]), r[::-2]) assert_equal(np.where(c[::-3], d[::-3], e[::-3]), r[::-3]) assert_equal(np.where(c[1::-3], d[1::-3], e[1::-3]), r[1::-3]) def test_exotic(self): # object assert_array_equal(np.where(True, None, None), np.array(None)) # zero sized m = np.array([], dtype=bool).reshape(0, 3) b = np.array([], dtype=np.float64).reshape(0, 3) assert_array_equal(np.where(m, 0, b), np.array([]).reshape(0, 3)) # object cast d = np.array([-1.34, -0.16, -0.54, -0.31, -0.08, -0.95, 0.000, 0.313, 0.547, -0.18, 0.876, 0.236, 1.969, 0.310, 0.699, 1.013, 1.267, 0.229, -1.39, 0.487]) nan = float('NaN') e = np.array(['5z', '0l', nan, 'Wz', nan, nan, 'Xq', 'cs', nan, nan, 'QN', nan, nan, 'Fd', nan, nan, 'kp', nan, '36', 'i1'], dtype=object); m = np.array([0,0,1,0,1,1,0,0,1,1,0,1,1,0,1,1,0,1,0,0], dtype=bool) r = e[:] r[np.where(m)] = d[np.where(m)] assert_array_equal(np.where(m, d, e), r) r = e[:] r[np.where(~m)] = d[np.where(~m)] assert_array_equal(np.where(m, e, d), r) assert_array_equal(np.where(m, e, e), e) # minimal dtype result with NaN scalar (e.g required by pandas) d = np.array([1., 2.], dtype=np.float32) e = float('NaN') assert_equal(np.where(True, d, e).dtype, np.float32) e = float('Infinity') assert_equal(np.where(True, d, e).dtype, np.float32) e = float('-Infinity') assert_equal(np.where(True, d, e).dtype, np.float32) # also check upcast e = float(1e150) assert_equal(np.where(True, d, e).dtype, np.float64) def test_ndim(self): c = [True, False] a = np.zeros((2, 25)) b = np.ones((2, 25)) r = np.where(np.array(c)[:,np.newaxis], a, b) assert_array_equal(r[0], a[0]) assert_array_equal(r[1], b[0]) a = a.T b = b.T r = np.where(c, a, b) assert_array_equal(r[:,0], a[:,0]) assert_array_equal(r[:,1], b[:,0]) def test_dtype_mix(self): c = np.array([False, True, False, False, False, False, True, False, False, False, True, False]) a = np.uint32(1) b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.], dtype=np.float64) r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.], dtype=np.float64) assert_equal(np.where(c, a, b), r) a = a.astype(np.float32) b = b.astype(np.int64) assert_equal(np.where(c, a, b), r) # non bool mask c = c.astype(np.int) c[c != 0] = 34242324 assert_equal(np.where(c, a, b), r) # invert tmpmask = c != 0 c[c == 0] = 41247212 c[tmpmask] = 0 assert_equal(np.where(c, b, a), r) def test_foreign(self): c = np.array([False, True, False, False, False, False, True, False, False, False, True, False]) r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.], dtype=np.float64) a = np.ones(1, dtype='>i4') b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.], dtype=np.float64) assert_equal(np.where(c, a, b), r) b = b.astype('>f8') assert_equal(np.where(c, a, b), r) a = a.astype('<i4') assert_equal(np.where(c, a, b), r) c = c.astype('>i4') assert_equal(np.where(c, a, b), r) def test_error(self): c = [True, True] a = np.ones((4, 5)) b = np.ones((5, 5)) assert_raises(ValueError, np.where, c, a, a) assert_raises(ValueError, np.where, c[0], a, b) def test_string(self): # gh-4778 check strings are properly filled with nulls a = np.array("abc") b = np.array("x" * 753) assert_equal(np.where(True, a, b), "abc") assert_equal(np.where(False, b, a), "abc") # check native datatype sized strings a = np.array("abcd") b = np.array("x" * 8) assert_equal(np.where(True, a, b), "abcd") assert_equal(np.where(False, b, a), "abcd") class TestSizeOf(TestCase): def test_empty_array(self): x = np.array([]) assert_(sys.getsizeof(x) > 0) def check_array(self, dtype): elem_size = dtype(0).itemsize for length in [10, 50, 100, 500]: x = np.arange(length, dtype=dtype) assert_(sys.getsizeof(x) > length * elem_size) def test_array_int32(self): self.check_array(np.int32) def test_array_int64(self): self.check_array(np.int64) def test_array_float32(self): self.check_array(np.float32) def test_array_float64(self): self.check_array(np.float64) def test_view(self): d = np.ones(100) assert_(sys.getsizeof(d[...]) < sys.getsizeof(d)) def test_reshape(self): d = np.ones(100) assert_(sys.getsizeof(d) < sys.getsizeof(d.reshape(100, 1, 1).copy())) def test_resize(self): d = np.ones(100) old = sys.getsizeof(d) d.resize(50) assert_(old > sys.getsizeof(d)) d.resize(150) assert_(old < sys.getsizeof(d)) def test_error(self): d = np.ones(100) assert_raises(TypeError, d.__sizeof__, "a") class TestHashing(TestCase): def test_collections_hashable(self): x = np.array([]) self.assertFalse(isinstance(x, collections.Hashable)) from numpy.core._internal import _view_is_safe class TestObjViewSafetyFuncs(TestCase): def test_view_safety(self): psize = dtype('p').itemsize # creates dtype but with extra character code - for missing 'p' fields def mtype(s): n, offset, fields = 0, 0, [] for c in s.split(','): #subarrays won't work if c != '-': fields.append(('f{0}'.format(n), c, offset)) n += 1 offset += dtype(c).itemsize if c != '-' else psize names, formats, offsets = zip(*fields) return dtype({'names': names, 'formats': formats, 'offsets': offsets, 'itemsize': offset}) # test nonequal itemsizes with objects: # these should succeed: _view_is_safe(dtype('O,p,O,p'), dtype('O,p,O,p,O,p')) _view_is_safe(dtype('O,O'), dtype('O,O,O')) # these should fail: assert_raises(TypeError, _view_is_safe, dtype('O,O,p'), dtype('O,O')) assert_raises(TypeError, _view_is_safe, dtype('O,O,p'), dtype('O,p')) assert_raises(TypeError, _view_is_safe, dtype('O,O,p'), dtype('p,O')) # test nonequal itemsizes with missing fields: # these should succeed: _view_is_safe(mtype('-,p,-,p'), mtype('-,p,-,p,-,p')) _view_is_safe(dtype('p,p'), dtype('p,p,p')) # these should fail: assert_raises(TypeError, _view_is_safe, mtype('p,p,-'), mtype('p,p')) assert_raises(TypeError, _view_is_safe, mtype('p,p,-'), mtype('p,-')) assert_raises(TypeError, _view_is_safe, mtype('p,p,-'), mtype('-,p')) # scans through positions at which we can view a type def scanView(d1, otype): goodpos = [] for shift in range(d1.itemsize - dtype(otype).itemsize+1): d2 = dtype({'names': ['f0'], 'formats': [otype], 'offsets': [shift], 'itemsize': d1.itemsize}) try: _view_is_safe(d1, d2) except TypeError: pass else: goodpos.append(shift) return goodpos # test partial overlap with object field assert_equal(scanView(dtype('p,O,p,p,O,O'), 'p'), [0] + list(range(2*psize, 3*psize+1))) assert_equal(scanView(dtype('p,O,p,p,O,O'), 'O'), [psize, 4*psize, 5*psize]) # test partial overlap with missing field assert_equal(scanView(mtype('p,-,p,p,-,-'), 'p'), [0] + list(range(2*psize, 3*psize+1))) # test nested structures with objects: nestedO = dtype([('f0', 'p'), ('f1', 'p,O,p')]) assert_equal(scanView(nestedO, 'p'), list(range(psize+1)) + [3*psize]) assert_equal(scanView(nestedO, 'O'), [2*psize]) # test nested structures with missing fields: nestedM = dtype([('f0', 'p'), ('f1', mtype('p,-,p'))]) assert_equal(scanView(nestedM, 'p'), list(range(psize+1)) + [3*psize]) # test subarrays with objects subarrayO = dtype('p,(2,3)O,p') assert_equal(scanView(subarrayO, 'p'), [0, 7*psize]) assert_equal(scanView(subarrayO, 'O'), list(range(psize, 6*psize+1, psize))) #test dtype with overlapping fields overlapped = dtype({'names': ['f0', 'f1', 'f2', 'f3'], 'formats': ['p', 'p', 'p', 'p'], 'offsets': [0, 1, 3*psize-1, 3*psize], 'itemsize': 4*psize}) assert_equal(scanView(overlapped, 'p'), [0, 1, 3*psize-1, 3*psize]) class TestArrayPriority(TestCase): # This will go away when __array_priority__ is settled, meanwhile # it serves to check unintended changes. op = operator binary_ops = [ op.pow, op.add, op.sub, op.mul, op.floordiv, op.truediv, op.mod, op.and_, op.or_, op.xor, op.lshift, op.rshift, op.mod, op.gt, op.ge, op.lt, op.le, op.ne, op.eq ] if sys.version_info[0] < 3: binary_ops.append(op.div) class Foo(np.ndarray): __array_priority__ = 100. def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) class Bar(np.ndarray): __array_priority__ = 101. def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) class Other(object): __array_priority__ = 1000. def _all(self, other): return self.__class__() __add__ = __radd__ = _all __sub__ = __rsub__ = _all __mul__ = __rmul__ = _all __pow__ = __rpow__ = _all __div__ = __rdiv__ = _all __mod__ = __rmod__ = _all __truediv__ = __rtruediv__ = _all __floordiv__ = __rfloordiv__ = _all __and__ = __rand__ = _all __xor__ = __rxor__ = _all __or__ = __ror__ = _all __lshift__ = __rlshift__ = _all __rshift__ = __rrshift__ = _all __eq__ = _all __ne__ = _all __gt__ = _all __ge__ = _all __lt__ = _all __le__ = _all def test_ndarray_subclass(self): a = np.array([1, 2]) b = self.Bar([1, 2]) for f in self.binary_ops: msg = repr(f) assert_(isinstance(f(a, b), self.Bar), msg) assert_(isinstance(f(b, a), self.Bar), msg) def test_ndarray_other(self): a = np.array([1, 2]) b = self.Other() for f in self.binary_ops: msg = repr(f) assert_(isinstance(f(a, b), self.Other), msg) assert_(isinstance(f(b, a), self.Other), msg) def test_subclass_subclass(self): a = self.Foo([1, 2]) b = self.Bar([1, 2]) for f in self.binary_ops: msg = repr(f) assert_(isinstance(f(a, b), self.Bar), msg) assert_(isinstance(f(b, a), self.Bar), msg) def test_subclass_other(self): a = self.Foo([1, 2]) b = self.Other() for f in self.binary_ops: msg = repr(f) assert_(isinstance(f(a, b), self.Other), msg) assert_(isinstance(f(b, a), self.Other), msg) class TestBytestringArrayNonzero(TestCase): def test_empty_bstring_array_is_falsey(self): self.assertFalse(np.array([''], dtype=np.str)) def test_whitespace_bstring_array_is_falsey(self): a = np.array(['spam'], dtype=np.str) a[0] = ' \0\0' self.assertFalse(a) def test_all_null_bstring_array_is_falsey(self): a = np.array(['spam'], dtype=np.str) a[0] = '\0\0\0\0' self.assertFalse(a) def test_null_inside_bstring_array_is_truthy(self): a = np.array(['spam'], dtype=np.str) a[0] = ' \0 \0' self.assertTrue(a) class TestUnicodeArrayNonzero(TestCase): def test_empty_ustring_array_is_falsey(self): self.assertFalse(np.array([''], dtype=np.unicode)) def test_whitespace_ustring_array_is_falsey(self): a = np.array(['eggs'], dtype=np.unicode) a[0] = ' \0\0' self.assertFalse(a) def test_all_null_ustring_array_is_falsey(self): a = np.array(['eggs'], dtype=np.unicode) a[0] = '\0\0\0\0' self.assertFalse(a) def test_null_inside_ustring_array_is_truthy(self): a = np.array(['eggs'], dtype=np.unicode) a[0] = ' \0 \0' self.assertTrue(a) if __name__ == "__main__": run_module_suite()
bsd-3-clause
qianfengzh/ML-source-code
algorithms/decisionTrees/treePlotter.py
1
1851
#-*-coding=utf-8-*- #----------------------- # Named: Decision Trees Plotter # Created: 2016-07-10 # @Author: Qianfeng #----------------------- import matplotlib.pyplot as plt decisionNode = dict(boxstyle='sawtooth', fc='0.8') leafNode = dict(boxstyle='round4', fc='0.8') arrow_args = dict(arrowstyle='<-') def plotNode(nodeTxt, centerPt, parentPt, nodeType): createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', \ xytext=centerPt, textcoords='axes fraction', va='center', ha='center', \ bbox=nodeType, arrowprops=arrow_args) def createPlot(): fig = plt.figure(1, facecolor='white') fig.clf() createPlot.ax1 = plt.subplot(111, frameon=False) plotNode(U'决策节点', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode(U'叶节点', (0.8, 0.1), (0.3, 0.8), leafNode) plt.show() #------------------------------------------------------------------- # 构造注解树 # 双递归,探测树深度 def getNumLeafs(myTree): """ 递归获取叶节点总数 """ numLeafs = 0 firstStr = myTree.keys()[0] secondDict = myTree[firstStr] for key in secondDict.keys(): if type(secondDict[key]).__name__ == 'dict': numLeafs += getNumLeafs(secondDict[key]) else: numLeafs += 1 return numLeafs def getTreeDepth(myTree): """ 递归获取树深度 """ maxDepth = 0 firstStr = myTree.keys()[0] secondDict = myTree[firstStr] for key in secondDict.keys(): if type(secondDict[key]).__name__ == 'dict': thisDepth = 1+ getTreeDepth(secondDict[key]) else: thisDepth = 1 if thisDepth > maxDepth: maxDepth = thisDepth return maxDepth def retrieveTree(i): listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},\ {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}} ] return listOfTrees[i]
gpl-2.0
aewhatley/scikit-learn
examples/cluster/plot_segmentation_toy.py
258
3336
""" =========================================== Spectral clustering for image segmentation =========================================== In this example, an image with connected circles is generated and spectral clustering is used to separate the circles. In these settings, the :ref:`spectral_clustering` approach solves the problem know as 'normalized graph cuts': the image is seen as a graph of connected voxels, and the spectral clustering algorithm amounts to choosing graph cuts defining regions while minimizing the ratio of the gradient along the cut, and the volume of the region. As the algorithm tries to balance the volume (ie balance the region sizes), if we take circles with different sizes, the segmentation fails. In addition, as there is no useful information in the intensity of the image, or its gradient, we choose to perform the spectral clustering on a graph that is only weakly informed by the gradient. This is close to performing a Voronoi partition of the graph. In addition, we use the mask of the objects to restrict the graph to the outline of the objects. In this example, we are interested in separating the objects one from the other, and not from the background. """ print(__doc__) # Authors: Emmanuelle Gouillart <[email protected]> # Gael Varoquaux <[email protected]> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering ############################################################################### l = 100 x, y = np.indices((l, l)) center1 = (28, 24) center2 = (40, 50) center3 = (67, 58) center4 = (24, 70) radius1, radius2, radius3, radius4 = 16, 14, 15, 14 circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1 ** 2 circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2 ** 2 circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3 ** 2 circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4 ** 2 ############################################################################### # 4 circles img = circle1 + circle2 + circle3 + circle4 mask = img.astype(bool) img = img.astype(float) img += 1 + 0.2 * np.random.randn(*img.shape) # Convert the image into a graph with the value of the gradient on the # edges. graph = image.img_to_graph(img, mask=mask) # Take a decreasing function of the gradient: we take it weakly # dependent from the gradient the segmentation is close to a voronoi graph.data = np.exp(-graph.data / graph.data.std()) # Force the solver to be arpack, since amg is numerically # unstable on this example labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack') label_im = -np.ones(mask.shape) label_im[mask] = labels plt.matshow(img) plt.matshow(label_im) ############################################################################### # 2 circles img = circle1 + circle2 mask = img.astype(bool) img = img.astype(float) img += 1 + 0.2 * np.random.randn(*img.shape) graph = image.img_to_graph(img, mask=mask) graph.data = np.exp(-graph.data / graph.data.std()) labels = spectral_clustering(graph, n_clusters=2, eigen_solver='arpack') label_im = -np.ones(mask.shape) label_im[mask] = labels plt.matshow(img) plt.matshow(label_im) plt.show()
bsd-3-clause
jangorecki/h2o-3
h2o-py/h2o/model/metrics_base.py
1
26162
# -*- encoding: utf-8 -*- """ Regression model. :copyright: (c) 2016 H2O.ai :license: Apache License Version 2.0 (see LICENSE for details) """ from __future__ import absolute_import, division, print_function, unicode_literals import imp from h2o.model.confusion_matrix import ConfusionMatrix from h2o.utils.backward_compatibility import backwards_compatible from h2o.utils.compatibility import * # NOQA from h2o.utils.typechecks import assert_is_type, assert_satisfies, numeric class MetricsBase(backwards_compatible()): """ A parent class to house common metrics available for the various Metrics types. The methods here are available across different model categories, and so appear here. """ def __init__(self, metric_json, on=None, algo=""): super(MetricsBase, self).__init__() # Yep, it's messed up... if isinstance(metric_json, MetricsBase): metric_json = metric_json._metric_json self._metric_json = metric_json # train and valid and xval are not mutually exclusive -- could have a test. train and # valid only make sense at model build time. self._on_train = False self._on_valid = False self._on_xval = False self._algo = algo if on == "training_metrics": self._on_train = True elif on == "validation_metrics": self._on_valid = True elif on == "cross_validation_metrics": self._on_xval = True elif on is None: pass else: raise ValueError("on expected to be train,valid,or xval. Got: " + str(on)) @classmethod def make(cls, kvs): """Factory method to instantiate a MetricsBase object from the list of key-value pairs.""" return cls(metric_json=dict(kvs)) def __repr__(self): # FIXME !!! __repr__ should never print anything, but return a string self.show() return "" # TODO: convert to actual fields list def __getitem__(self, key): return self._metric_json.get(key) @staticmethod def _has(dictionary, key): return key in dictionary and dictionary[key] is not None def show(self): """ Display a short summary of the metrics. :return: None """ metric_type = self._metric_json['__meta']['schema_type'] types_w_glm = ['ModelMetricsRegressionGLM', 'ModelMetricsBinomialGLM'] types_w_clustering = ['ModelMetricsClustering'] types_w_mult = ['ModelMetricsMultinomial'] types_w_bin = ['ModelMetricsBinomial', 'ModelMetricsBinomialGLM'] types_w_r2 = ['ModelMetricsRegressionGLM'] types_w_mean_residual_deviance = ['ModelMetricsRegressionGLM', 'ModelMetricsRegression'] types_w_mean_absolute_error = ['ModelMetricsRegressionGLM', 'ModelMetricsRegression'] types_w_logloss = types_w_bin + types_w_mult types_w_dim = ["ModelMetricsGLRM"] print() print(metric_type + ": " + self._algo) reported_on = "** Reported on {} data. **" if self._on_train: print(reported_on.format("train")) elif self._on_valid: print(reported_on.format("validation")) elif self._on_xval: print(reported_on.format("cross-validation")) else: print(reported_on.format("test")) print() print("MSE: " + str(self.mse())) print("RMSE: " + str(self.rmse())) if metric_type in types_w_mean_absolute_error: print("MAE: " + str(self.mae())) print("RMSLE: " + str(self.rmsle())) if metric_type in types_w_r2: print("R^2: " + str(self.r2())) if metric_type in types_w_mean_residual_deviance: print("Mean Residual Deviance: " + str(self.mean_residual_deviance())) if metric_type in types_w_logloss: print("LogLoss: " + str(self.logloss())) if metric_type == 'ModelMetricsBinomial': # second element for first threshold is the actual mean per class error print("Mean Per-Class Error: %s" % self.mean_per_class_error()[0][1]) if metric_type == 'ModelMetricsMultinomial': print("Mean Per-Class Error: " + str(self.mean_per_class_error())) if metric_type in types_w_glm: print("Null degrees of freedom: " + str(self.null_degrees_of_freedom())) print("Residual degrees of freedom: " + str(self.residual_degrees_of_freedom())) print("Null deviance: " + str(self.null_deviance())) print("Residual deviance: " + str(self.residual_deviance())) print("AIC: " + str(self.aic())) if metric_type in types_w_bin: print("AUC: " + str(self.auc())) print("Gini: " + str(self.gini())) self.confusion_matrix().show() self._metric_json["max_criteria_and_metric_scores"].show() if self.gains_lift(): print(self.gains_lift()) if metric_type in types_w_mult: self.confusion_matrix().show() self.hit_ratio_table().show() if metric_type in types_w_clustering: print("Total Within Cluster Sum of Square Error: " + str(self.tot_withinss())) print("Total Sum of Square Error to Grand Mean: " + str(self.totss())) print("Between Cluster Sum of Square Error: " + str(self.betweenss())) self._metric_json['centroid_stats'].show() if metric_type in types_w_dim: print("Sum of Squared Error (Numeric): " + str(self.num_err())) print("Misclassification Error (Categorical): " + str(self.cat_err())) def r2(self): """The R^2 coefficient.""" return self._metric_json["r2"] def logloss(self): """Log loss.""" return self._metric_json["logloss"] def nobs(self): """ :return: Retrieve the number of observations. """ return self._metric_json["nobs"] def mean_residual_deviance(self): """ :return: Retrieve the mean residual deviance for this set of metrics. """ return self._metric_json["mean_residual_deviance"] def auc(self): """ :return: Retrieve the AUC for this set of metrics. """ return self._metric_json['AUC'] def aic(self): """ :return: Retrieve the AIC for this set of metrics. """ return self._metric_json['AIC'] def gini(self): """Gini coefficient.""" return self._metric_json['Gini'] def mse(self): """ :return: Retrieve the MSE for this set of metrics """ return self._metric_json['MSE'] def rmse(self): """ :return: Retrieve the RMSE for this set of metrics """ return self._metric_json['RMSE'] def mae(self): """ :return: Retrieve the MAE for this set of metrics """ return self._metric_json['mae'] def rmsle(self): """ :return: Retrieve the RMSLE for this set of metrics """ return self._metric_json['rmsle'] def residual_deviance(self): """ :return: the residual deviance if the model has residual deviance, or None if no residual deviance. """ if MetricsBase._has(self._metric_json, "residual_deviance"): return self._metric_json["residual_deviance"] return None def residual_degrees_of_freedom(self): """ :return: the residual dof if the model has residual deviance, or None if no residual dof. """ if MetricsBase._has(self._metric_json, "residual_degrees_of_freedom"): return self._metric_json["residual_degrees_of_freedom"] return None def null_deviance(self): """ :return: the null deviance if the model has residual deviance, or None if no null deviance. """ if MetricsBase._has(self._metric_json, "null_deviance"): return self._metric_json["null_deviance"] return None def null_degrees_of_freedom(self): """ :return: the null dof if the model has residual deviance, or None if no null dof. """ if MetricsBase._has(self._metric_json, "null_degrees_of_freedom"): return self._metric_json["null_degrees_of_freedom"] return None def mean_per_class_error(self): """ Retrieve the mean per class error. """ return self._metric_json['mean_per_class_error'] # Deprecated functions; left here for backward compatibility _bcim = { "giniCoef": lambda self, *args, **kwargs: self.gini(*args, **kwargs) } class H2ORegressionModelMetrics(MetricsBase): """ This class provides an API for inspecting the metrics returned by a regression model. It is possible to retrieve the R^2 (1 - MSE/variance) and MSE """ def __init__(self, metric_json, on=None, algo=""): super(H2ORegressionModelMetrics, self).__init__(metric_json, on, algo) class H2OClusteringModelMetrics(MetricsBase): def __init__(self, metric_json, on=None, algo=""): super(H2OClusteringModelMetrics, self).__init__(metric_json, on, algo) def tot_withinss(self): """ :return: the Total Within Cluster Sum-of-Square Error, or None if not present. """ if MetricsBase._has(self._metric_json, "tot_withinss"): return self._metric_json["tot_withinss"] return None def totss(self): """ :return: the Total Sum-of-Square Error to Grand Mean, or None if not present. """ if MetricsBase._has(self._metric_json, "totss"): return self._metric_json["totss"] return None def betweenss(self): """ :return: the Between Cluster Sum-of-Square Error, or None if not present. """ if MetricsBase._has(self._metric_json, "betweenss"): return self._metric_json["betweenss"] return None class H2OMultinomialModelMetrics(MetricsBase): def __init__(self, metric_json, on=None, algo=""): super(H2OMultinomialModelMetrics, self).__init__(metric_json, on, algo) def confusion_matrix(self): """ Returns a confusion matrix based of H2O's default prediction threshold for a dataset """ return self._metric_json['cm']['table'] def hit_ratio_table(self): """ Retrieve the Hit Ratios """ return self._metric_json['hit_ratio_table'] class H2OBinomialModelMetrics(MetricsBase): """ This class is essentially an API for the AUC object. This class contains methods for inspecting the AUC for different criteria. To input the different criteria, use the static variable `criteria` """ def __init__(self, metric_json, on=None, algo=""): """ Create a new Binomial Metrics object (essentially a wrapper around some json) :param metric_json: A blob of json holding all of the needed information :param on_train: Metrics built on training data (default is False) :param on_valid: Metrics built on validation data (default is False) :param on_xval: Metrics built on cross validation data (default is False) :param algo: The algorithm the metrics are based off of (e.g. deeplearning, gbm, etc.) :return: A new H2OBinomialModelMetrics object. """ super(H2OBinomialModelMetrics, self).__init__(metric_json, on, algo) def F1(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The F1 for the given set of thresholds. """ return self.metric("f1", thresholds=thresholds) def F2(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The F2 for this set of metrics and thresholds """ return self.metric("f2", thresholds=thresholds) def F0point5(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The F0point5 for this set of metrics and thresholds. """ return self.metric("f0point5", thresholds=thresholds) def accuracy(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The accuracy for this set of metrics and thresholds """ return self.metric("accuracy", thresholds=thresholds) def error(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The error for this set of metrics and thresholds. """ return 1 - self.metric("accuracy", thresholds=thresholds) def precision(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The precision for this set of metrics and thresholds. """ return self.metric("precision", thresholds=thresholds) def tpr(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The True Postive Rate """ return self.metric("tpr", thresholds=thresholds) def tnr(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The True Negative Rate """ return self.metric("tnr", thresholds=thresholds) def fnr(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The False Negative Rate """ return self.metric("fnr", thresholds=thresholds) def fpr(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The False Positive Rate """ return self.metric("fpr", thresholds=thresholds) def recall(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: Recall for this set of metrics and thresholds """ return self.metric("tpr", thresholds=thresholds) def sensitivity(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: Sensitivity or True Positive Rate for this set of metrics and thresholds """ return self.metric("tpr", thresholds=thresholds) def fallout(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The fallout or False Positive Rate for this set of metrics and thresholds """ return self.metric("fpr", thresholds=thresholds) def missrate(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: THe missrate or False Negative Rate. """ return self.metric("fnr", thresholds=thresholds) def specificity(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The specificity or True Negative Rate. """ return self.metric("tnr", thresholds=thresholds) def mcc(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The absolute MCC (a value between 0 and 1, 0 being totally dissimilar, 1 being identical) """ return self.metric("absolute_mcc", thresholds=thresholds) def max_per_class_error(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: Return 1 - min_per_class_accuracy """ return 1 - self.metric("min_per_class_accuracy", thresholds=thresholds) def mean_per_class_error(self, thresholds=None): """ :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: Return mean_per_class_error """ return [[x[0], 1 - x[1]] for x in self.metric("mean_per_class_accuracy", thresholds=thresholds)] def metric(self, metric, thresholds=None): """ :param metric: The desired metric :param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds in this set of metrics will be used. :return: The set of metrics for the list of thresholds """ assert_is_type(thresholds, None, [numeric]) if not thresholds: thresholds = [self.find_threshold_by_max_metric(metric)] thresh2d = self._metric_json['thresholds_and_metric_scores'] metrics = [] for t in thresholds: idx = self.find_idx_by_threshold(t) metrics.append([t, thresh2d[metric][idx]]) return metrics def plot(self, type="roc", server=False): """ Produce the desired metric plot :param type: the type of metric plot (currently, only ROC supported) :param show: if False, the plot is not shown. matplotlib show method is blocking. :return: None """ # TODO: add more types (i.e. cutoffs) assert_is_type(type, "roc") # check for matplotlib. exit if absent. try: imp.find_module('matplotlib') import matplotlib if server: matplotlib.use('Agg', warn=False) import matplotlib.pyplot as plt except ImportError: print("matplotlib is required for this function!") return if type == "roc": plt.xlabel('False Positive Rate (FPR)') plt.ylabel('True Positive Rate (TPR)') plt.title('ROC Curve') plt.text(0.5, 0.5, r'AUC={0:.4f}'.format(self._metric_json["AUC"])) plt.plot(self.fprs, self.tprs, 'b--') plt.axis([0, 1, 0, 1]) if not server: plt.show() @property def fprs(self): """ Return all false positive rates for all threshold values. :return: a list of false positive rates. """ return self._metric_json["thresholds_and_metric_scores"]["fpr"] @property def tprs(self): """ Return all true positive rates for all threshold values. :return: a list of true positive rates. """ return self._metric_json["thresholds_and_metric_scores"]["tpr"] def confusion_matrix(self, metrics=None, thresholds=None): """ Get the confusion matrix for the specified metric :param metrics: A string (or list of strings) in {"min_per_class_accuracy", "absolute_mcc", "tnr", "fnr", "fpr", "tpr", "precision", "accuracy", "f0point5", "f2", "f1","mean_per_class_accuracy"} :param thresholds: A value (or list of values) between 0 and 1 :return: a list of ConfusionMatrix objects (if there are more than one to return), or a single ConfusionMatrix (if there is only one) """ # make lists out of metrics and thresholds arguments if metrics is None and thresholds is None: metrics = ["f1"] if isinstance(metrics, list): metrics_list = metrics elif metrics is None: metrics_list = [] else: metrics_list = [metrics] if isinstance(thresholds, list): thresholds_list = thresholds elif thresholds is None: thresholds_list = [] else: thresholds_list = [thresholds] # error check the metrics_list and thresholds_list assert_is_type(thresholds_list, [numeric]) assert_satisfies(thresholds_list, all(0 <= t <= 1 for t in thresholds_list)) if not all(m.lower() in ["min_per_class_accuracy", "absolute_mcc", "precision", "recall", "specificity", "accuracy", "f0point5", "f2", "f1", "mean_per_class_accuracy"] for m in metrics_list): raise ValueError( "The only allowable metrics are min_per_class_accuracy, absolute_mcc, precision, accuracy, f0point5, " "f2, f1, mean_per_class_accuracy") # make one big list that combines the thresholds and metric-thresholds metrics_thresholds = [self.find_threshold_by_max_metric(m) for m in metrics_list] for mt in metrics_thresholds: thresholds_list.append(mt) thresh2d = self._metric_json['thresholds_and_metric_scores'] actual_thresholds = [float(e[0]) for i, e in enumerate(thresh2d.cell_values)] cms = [] for t in thresholds_list: idx = self.find_idx_by_threshold(t) row = thresh2d.cell_values[idx] tns = row[11] fns = row[12] fps = row[13] tps = row[14] p = tps + fns n = tns + fps c0 = n - fps c1 = p - tps if t in metrics_thresholds: m = metrics_list[metrics_thresholds.index(t)] table_header = "Confusion Matrix (Act/Pred) for max " + m + " @ threshold = " + str( actual_thresholds[idx]) else: table_header = "Confusion Matrix (Act/Pred) @ threshold = " + str(actual_thresholds[idx]) cms.append(ConfusionMatrix(cm=[[c0, fps], [c1, tps]], domains=self._metric_json['domain'], table_header=table_header)) if len(cms) == 1: return cms[0] else: return cms def find_threshold_by_max_metric(self, metric): """ :param metric: A string in {"min_per_class_accuracy", "absolute_mcc", "precision", "recall", "specificity", "accuracy", "f0point5", "f2", "f1", "mean_per_class_accuracy"} :return: the threshold at which the given metric is maximum. """ crit2d = self._metric_json['max_criteria_and_metric_scores'] for e in crit2d.cell_values: if e[0] == "max " + metric.lower(): return e[1] raise ValueError("No metric " + str(metric.lower())) def find_idx_by_threshold(self, threshold): """ Retrieve the index in this metric's threshold list at which the given threshold is located. :param threshold: Find the index of this input threshold. :return: Return the index or throw a ValueError if no such index can be found. """ assert_is_type(threshold, numeric) thresh2d = self._metric_json['thresholds_and_metric_scores'] for i, e in enumerate(thresh2d.cell_values): t = float(e[0]) if abs(t - threshold) < 0.00000001 * max(t, threshold): return i if threshold >= 0 and threshold <= 1: thresholds = [float(e[0]) for i, e in enumerate(thresh2d.cell_values)] threshold_diffs = [abs(t - threshold) for t in thresholds] closest_idx = threshold_diffs.index(min(threshold_diffs)) closest_threshold = thresholds[closest_idx] print("Could not find exact threshold {0}; using closest threshold found {1}." \ .format(threshold, closest_threshold)) return closest_idx raise ValueError("Threshold must be between 0 and 1, but got {0} ".format(threshold)) def gains_lift(self): """ Retrieve the Gains/Lift table """ if 'gains_lift_table' in self._metric_json: return self._metric_json['gains_lift_table'] return None class H2OAutoEncoderModelMetrics(MetricsBase): def __init__(self, metric_json, on=None, algo=""): super(H2OAutoEncoderModelMetrics, self).__init__(metric_json, on, algo) class H2ODimReductionModelMetrics(MetricsBase): def __init__(self, metric_json, on=None, algo=""): super(H2ODimReductionModelMetrics, self).__init__(metric_json, on, algo) def num_err(self): """ :return: the Sum of Squared Error over non-missing numeric entries, or None if not present. """ if MetricsBase._has(self._metric_json, "numerr"): return self._metric_json["numerr"] return None def cat_err(self): """ :return: the Number of Misclassified categories over non-missing categorical entries, or None if not present. """ if MetricsBase._has(self._metric_json, "caterr"): return self._metric_json["caterr"] return None
apache-2.0
sounay/flaminggo-test
onadata/libs/utils/export_tools.py
3
40050
import csv from datetime import datetime, date import json import os import re import six from urlparse import urlparse from zipfile import ZipFile from bson import json_util from django.conf import settings from django.core.files.base import File from django.core.files.temp import NamedTemporaryFile from django.core.files.storage import get_storage_class from django.contrib.auth.models import User from django.shortcuts import render_to_response from openpyxl.date_time import SharedDate from openpyxl.workbook import Workbook from pyxform.question import Question from pyxform.section import Section, RepeatingSection from savReaderWriter import SavWriter from json2xlsclient.client import Client from onadata.apps.logger.models import Attachment, Instance, XForm from onadata.apps.main.models.meta_data import MetaData from onadata.apps.viewer.models.export import Export from onadata.apps.viewer.models.parsed_instance import\ _is_invalid_for_mongo, _encode_for_mongo, dict_for_mongo,\ _decode_from_mongo from onadata.libs.utils.viewer_tools import create_attachments_zipfile,\ image_urls from onadata.libs.utils.common_tags import ( ID, XFORM_ID_STRING, STATUS, ATTACHMENTS, GEOLOCATION, BAMBOO_DATASET_ID, DELETEDAT, USERFORM_ID, INDEX, PARENT_INDEX, PARENT_TABLE_NAME, SUBMISSION_TIME, UUID, TAGS, NOTES, VERSION) from onadata.libs.exceptions import J2XException # this is Mongo Collection where we will store the parsed submissions xform_instances = settings.MONGO_DB.instances QUESTION_TYPES_TO_EXCLUDE = [ u'note', ] # the bind type of select multiples that we use to compare MULTIPLE_SELECT_BIND_TYPE = u"select" GEOPOINT_BIND_TYPE = u"geopoint" def encode_if_str(row, key, encode_dates=False): val = row.get(key) if isinstance(val, six.string_types): return val.encode('utf-8') if encode_dates and isinstance(val, datetime): return val.strftime('%Y-%m-%dT%H:%M:%S%z').encode('utf-8') if encode_dates and isinstance(val, date): return val.strftime('%Y-%m-%d').encode('utf-8') return val def question_types_to_exclude(_type): return _type in QUESTION_TYPES_TO_EXCLUDE class DictOrganizer(object): def set_dict_iterator(self, dict_iterator): self._dict_iterator = dict_iterator # Every section will get its own table # I need to think of an easy way to flatten out a dictionary # parent name, index, table name, data def _build_obs_from_dict(self, d, obs, table_name, parent_table_name, parent_index): if table_name not in obs: obs[table_name] = [] this_index = len(obs[table_name]) obs[table_name].append({ u"_parent_table_name": parent_table_name, u"_parent_index": parent_index, }) for k, v in d.items(): if type(v) != dict and type(v) != list: assert k not in obs[table_name][-1] obs[table_name][-1][k] = v obs[table_name][-1][u"_index"] = this_index for k, v in d.items(): if type(v) == dict: kwargs = { "d": v, "obs": obs, "table_name": k, "parent_table_name": table_name, "parent_index": this_index } self._build_obs_from_dict(**kwargs) if type(v) == list: for i, item in enumerate(v): kwargs = { "d": item, "obs": obs, "table_name": k, "parent_table_name": table_name, "parent_index": this_index, } self._build_obs_from_dict(**kwargs) return obs def get_observation_from_dict(self, d): result = {} assert len(d.keys()) == 1 root_name = d.keys()[0] kwargs = { "d": d[root_name], "obs": result, "table_name": root_name, "parent_table_name": u"", "parent_index": -1, } self._build_obs_from_dict(**kwargs) return result def dict_to_joined_export(data, index, indices, name): """ Converts a dict into one or more tabular datasets """ output = {} # TODO: test for _geolocation and attachment lists if isinstance(data, dict): for key, val in data.iteritems(): if isinstance(val, list) and key not in [NOTES, TAGS]: output[key] = [] for child in val: if key not in indices: indices[key] = 0 indices[key] += 1 child_index = indices[key] new_output = dict_to_joined_export( child, child_index, indices, key) d = {INDEX: child_index, PARENT_INDEX: index, PARENT_TABLE_NAME: name} # iterate over keys within new_output and append to # main output for out_key, out_val in new_output.iteritems(): if isinstance(out_val, list): if out_key not in output: output[out_key] = [] output[out_key].extend(out_val) else: d.update(out_val) output[key].append(d) else: if name not in output: output[name] = {} if key in [TAGS]: output[name][key] = ",".join(val) elif key in [NOTES]: output[name][key] = "\r\n".join( [v['note'] for v in val]) else: output[name][key] = val return output class ExportBuilder(object): IGNORED_COLUMNS = [XFORM_ID_STRING, STATUS, ATTACHMENTS, GEOLOCATION, BAMBOO_DATASET_ID, DELETEDAT] # fields we export but are not within the form's structure EXTRA_FIELDS = [ID, UUID, SUBMISSION_TIME, INDEX, PARENT_TABLE_NAME, PARENT_INDEX, TAGS, NOTES, VERSION] SPLIT_SELECT_MULTIPLES = True BINARY_SELECT_MULTIPLES = False # column group delimiters GROUP_DELIMITER_SLASH = '/' GROUP_DELIMITER_DOT = '.' GROUP_DELIMITER = GROUP_DELIMITER_SLASH GROUP_DELIMITERS = [GROUP_DELIMITER_SLASH, GROUP_DELIMITER_DOT] TYPES_TO_CONVERT = ['int', 'decimal', 'date'] # , 'dateTime'] CONVERT_FUNCS = { 'int': lambda x: int(x), 'decimal': lambda x: float(x), 'date': lambda x: ExportBuilder.string_to_date_with_xls_validation(x), 'dateTime': lambda x: datetime.strptime(x[:19], '%Y-%m-%dT%H:%M:%S') } XLS_SHEET_NAME_MAX_CHARS = 31 @classmethod def string_to_date_with_xls_validation(cls, date_str): date_obj = datetime.strptime(date_str, '%Y-%m-%d').date() try: SharedDate().datetime_to_julian(date_obj) except ValueError: return date_str else: return date_obj @classmethod def format_field_title(cls, abbreviated_xpath, field_delimiter): if field_delimiter != '/': return field_delimiter.join(abbreviated_xpath.split('/')) return abbreviated_xpath def set_survey(self, survey): # TODO resolve circular import from onadata.apps.viewer.models.data_dictionary import\ DataDictionary def build_sections( current_section, survey_element, sections, select_multiples, gps_fields, encoded_fields, field_delimiter='/'): for child in survey_element.children: current_section_name = current_section['name'] # if a section, recurs if isinstance(child, Section): # if its repeating, build a new section if isinstance(child, RepeatingSection): # section_name in recursive call changes section = { 'name': child.get_abbreviated_xpath(), 'elements': []} self.sections.append(section) build_sections( section, child, sections, select_multiples, gps_fields, encoded_fields, field_delimiter) else: # its a group, recurs using the same section build_sections( current_section, child, sections, select_multiples, gps_fields, encoded_fields, field_delimiter) elif isinstance(child, Question) and child.bind.get(u"type")\ not in QUESTION_TYPES_TO_EXCLUDE: # add to survey_sections if isinstance(child, Question): child_xpath = child.get_abbreviated_xpath() current_section['elements'].append({ 'title': ExportBuilder.format_field_title( child.get_abbreviated_xpath(), field_delimiter), 'xpath': child_xpath, 'type': child.bind.get(u"type") }) if _is_invalid_for_mongo(child_xpath): if current_section_name not in encoded_fields: encoded_fields[current_section_name] = {} encoded_fields[current_section_name].update( {child_xpath: _encode_for_mongo(child_xpath)}) # if its a select multiple, make columns out of its choices if child.bind.get(u"type") == MULTIPLE_SELECT_BIND_TYPE\ and self.SPLIT_SELECT_MULTIPLES: for c in child.children: _xpath = c.get_abbreviated_xpath() _title = ExportBuilder.format_field_title( _xpath, field_delimiter) choice = { 'title': _title, 'xpath': _xpath, 'type': 'string' } if choice not in current_section['elements']: current_section['elements'].append(choice) _append_xpaths_to_section( current_section_name, select_multiples, child.get_abbreviated_xpath(), [c.get_abbreviated_xpath() for c in child.children]) # split gps fields within this section if child.bind.get(u"type") == GEOPOINT_BIND_TYPE: # add columns for geopoint components xpaths = DataDictionary.get_additional_geopoint_xpaths( child.get_abbreviated_xpath()) current_section['elements'].extend( [ { 'title': ExportBuilder.format_field_title( xpath, field_delimiter), 'xpath': xpath, 'type': 'decimal' } for xpath in xpaths ]) _append_xpaths_to_section( current_section_name, gps_fields, child.get_abbreviated_xpath(), xpaths) def _append_xpaths_to_section(current_section_name, field_list, xpath, xpaths): if current_section_name not in field_list: field_list[current_section_name] = {} field_list[ current_section_name][xpath] = xpaths self.survey = survey self.select_multiples = {} self.gps_fields = {} self.encoded_fields = {} main_section = {'name': survey.name, 'elements': []} self.sections = [main_section] build_sections( main_section, self.survey, self.sections, self.select_multiples, self.gps_fields, self.encoded_fields, self.GROUP_DELIMITER) def section_by_name(self, name): matches = filter(lambda s: s['name'] == name, self.sections) assert(len(matches) == 1) return matches[0] @classmethod def split_select_multiples(cls, row, select_multiples): # for each select_multiple, get the associated data and split it for xpath, choices in select_multiples.iteritems(): # get the data matching this xpath data = row.get(xpath) selections = [] if data: selections = [ u'{0}/{1}'.format( xpath, selection) for selection in data.split()] if not cls.BINARY_SELECT_MULTIPLES: row.update(dict( [(choice, choice in selections if selections else None) for choice in choices])) else: YES = 1 NO = 0 row.update(dict( [(choice, YES if choice in selections else NO) for choice in choices])) return row @classmethod def split_gps_components(cls, row, gps_fields): # for each gps_field, get associated data and split it for xpath, gps_components in gps_fields.iteritems(): data = row.get(xpath) if data: gps_parts = data.split() if len(gps_parts) > 0: row.update(zip(gps_components, gps_parts)) return row @classmethod def decode_mongo_encoded_fields(cls, row, encoded_fields): for xpath, encoded_xpath in encoded_fields.iteritems(): if row.get(encoded_xpath): val = row.pop(encoded_xpath) row.update({xpath: val}) return row @classmethod def decode_mongo_encoded_section_names(cls, data): return dict([(_decode_from_mongo(k), v) for k, v in data.iteritems()]) @classmethod def convert_type(cls, value, data_type): """ Convert data to its native type e.g. string '1' to int 1 @param value: the string value to convert @param data_type: the native data type to convert to @return: the converted value """ func = ExportBuilder.CONVERT_FUNCS.get(data_type, lambda x: x) try: return func(value) except ValueError: return value def pre_process_row(self, row, section): """ Split select multiples, gps and decode . and $ """ section_name = section['name'] # first decode fields so that subsequent lookups # have decoded field names if section_name in self.encoded_fields: row = ExportBuilder.decode_mongo_encoded_fields( row, self.encoded_fields[section_name]) if self.SPLIT_SELECT_MULTIPLES and\ section_name in self.select_multiples: row = ExportBuilder.split_select_multiples( row, self.select_multiples[section_name]) if section_name in self.gps_fields: row = ExportBuilder.split_gps_components( row, self.gps_fields[section_name]) # convert to native types for elm in section['elements']: # only convert if its in our list and its not empty, just to # optimize value = row.get(elm['xpath']) if elm['type'] in ExportBuilder.TYPES_TO_CONVERT\ and value is not None and value != '': row[elm['xpath']] = ExportBuilder.convert_type( value, elm['type']) return row def to_zipped_csv(self, path, data, *args): def write_row(row, csv_writer, fields): csv_writer.writerow( [encode_if_str(row, field) for field in fields]) csv_defs = {} for section in self.sections: csv_file = NamedTemporaryFile(suffix=".csv") csv_writer = csv.writer(csv_file) csv_defs[section['name']] = { 'csv_file': csv_file, 'csv_writer': csv_writer} # write headers for section in self.sections: fields = [element['title'] for element in section['elements']]\ + self.EXTRA_FIELDS csv_defs[section['name']]['csv_writer'].writerow( [f.encode('utf-8') for f in fields]) index = 1 indices = {} survey_name = self.survey.name for d in data: # decode mongo section names joined_export = dict_to_joined_export(d, index, indices, survey_name) output = ExportBuilder.decode_mongo_encoded_section_names( joined_export) # attach meta fields (index, parent_index, parent_table) # output has keys for every section if survey_name not in output: output[survey_name] = {} output[survey_name][INDEX] = index output[survey_name][PARENT_INDEX] = -1 for section in self.sections: # get data for this section and write to csv section_name = section['name'] csv_def = csv_defs[section_name] fields = [ element['xpath'] for element in section['elements']] + self.EXTRA_FIELDS csv_writer = csv_def['csv_writer'] # section name might not exist within the output, e.g. data was # not provided for said repeat - write test to check this row = output.get(section_name, None) if type(row) == dict: write_row( self.pre_process_row(row, section), csv_writer, fields) elif type(row) == list: for child_row in row: write_row( self.pre_process_row(child_row, section), csv_writer, fields) index += 1 # write zipfile with ZipFile(path, 'w') as zip_file: for section_name, csv_def in csv_defs.iteritems(): csv_file = csv_def['csv_file'] csv_file.seek(0) zip_file.write( csv_file.name, "_".join(section_name.split("/")) + ".csv") # close files when we are done for section_name, csv_def in csv_defs.iteritems(): csv_def['csv_file'].close() @classmethod def get_valid_sheet_name(cls, desired_name, existing_names): # a sheet name has to be <= 31 characters and not a duplicate of an # existing sheet # truncate sheet_name to XLSDataFrameBuilder.SHEET_NAME_MAX_CHARS new_sheet_name = \ desired_name[:cls.XLS_SHEET_NAME_MAX_CHARS] # make sure its unique within the list i = 1 generated_name = new_sheet_name while generated_name in existing_names: digit_length = len(str(i)) allowed_name_len = cls.XLS_SHEET_NAME_MAX_CHARS - \ digit_length # make name the required len if len(generated_name) > allowed_name_len: generated_name = generated_name[:allowed_name_len] generated_name = "{0}{1}".format(generated_name, i) i += 1 return generated_name def to_xls_export(self, path, data, *args): def write_row(data, work_sheet, fields, work_sheet_titles): # update parent_table with the generated sheet's title data[PARENT_TABLE_NAME] = work_sheet_titles.get( data.get(PARENT_TABLE_NAME)) work_sheet.append([data.get(f) for f in fields]) wb = Workbook(optimized_write=True) work_sheets = {} # map of section_names to generated_names work_sheet_titles = {} for section in self.sections: section_name = section['name'] work_sheet_title = ExportBuilder.get_valid_sheet_name( "_".join(section_name.split("/")), work_sheet_titles.values()) work_sheet_titles[section_name] = work_sheet_title work_sheets[section_name] = wb.create_sheet( title=work_sheet_title) # write the headers for section in self.sections: section_name = section['name'] headers = [ element['title'] for element in section['elements']] + self.EXTRA_FIELDS # get the worksheet ws = work_sheets[section_name] ws.append(headers) index = 1 indices = {} survey_name = self.survey.name for d in data: joined_export = dict_to_joined_export(d, index, indices, survey_name) output = ExportBuilder.decode_mongo_encoded_section_names( joined_export) # attach meta fields (index, parent_index, parent_table) # output has keys for every section if survey_name not in output: output[survey_name] = {} output[survey_name][INDEX] = index output[survey_name][PARENT_INDEX] = -1 for section in self.sections: # get data for this section and write to xls section_name = section['name'] fields = [ element['xpath'] for element in section['elements']] + self.EXTRA_FIELDS ws = work_sheets[section_name] # section might not exist within the output, e.g. data was # not provided for said repeat - write test to check this row = output.get(section_name, None) if type(row) == dict: write_row( self.pre_process_row(row, section), ws, fields, work_sheet_titles) elif type(row) == list: for child_row in row: write_row( self.pre_process_row(child_row, section), ws, fields, work_sheet_titles) index += 1 wb.save(filename=path) def to_flat_csv_export( self, path, data, username, id_string, filter_query): # TODO resolve circular import from onadata.apps.viewer.pandas_mongo_bridge import\ CSVDataFrameBuilder csv_builder = CSVDataFrameBuilder( username, id_string, filter_query, self.GROUP_DELIMITER, self.SPLIT_SELECT_MULTIPLES, self.BINARY_SELECT_MULTIPLES) csv_builder.export_to(path) def to_zipped_sav(self, path, data, *args): def write_row(row, csv_writer, fields): sav_writer.writerow( [encode_if_str(row, field, True) for field in fields]) sav_defs = {} # write headers for section in self.sections: fields = [element['title'] for element in section['elements']]\ + self.EXTRA_FIELDS c = 0 var_labels = {} var_names = [] tmp_k = {} for field in fields: c += 1 var_name = 'var%d' % c var_labels[var_name] = field var_names.append(var_name) tmp_k[field] = var_name var_types = dict( [(tmp_k[element['title']], 0 if element['type'] in ['decimal', 'int'] else 255) for element in section['elements']] + [(tmp_k[item], 0 if item in ['_id', '_index', '_parent_index'] else 255) for item in self.EXTRA_FIELDS] ) sav_file = NamedTemporaryFile(suffix=".sav") sav_writer = SavWriter(sav_file.name, varNames=var_names, varTypes=var_types, varLabels=var_labels, ioUtf8=True) sav_defs[section['name']] = { 'sav_file': sav_file, 'sav_writer': sav_writer} index = 1 indices = {} survey_name = self.survey.name for d in data: # decode mongo section names joined_export = dict_to_joined_export(d, index, indices, survey_name) output = ExportBuilder.decode_mongo_encoded_section_names( joined_export) # attach meta fields (index, parent_index, parent_table) # output has keys for every section if survey_name not in output: output[survey_name] = {} output[survey_name][INDEX] = index output[survey_name][PARENT_INDEX] = -1 for section in self.sections: # get data for this section and write to csv section_name = section['name'] sav_def = sav_defs[section_name] fields = [ element['xpath'] for element in section['elements']] + self.EXTRA_FIELDS sav_writer = sav_def['sav_writer'] row = output.get(section_name, None) if type(row) == dict: write_row( self.pre_process_row(row, section), sav_writer, fields) elif type(row) == list: for child_row in row: write_row( self.pre_process_row(child_row, section), sav_writer, fields) index += 1 for section_name, sav_def in sav_defs.iteritems(): sav_def['sav_writer'].closeSavFile( sav_def['sav_writer'].fh, mode='wb') # write zipfile with ZipFile(path, 'w') as zip_file: for section_name, sav_def in sav_defs.iteritems(): sav_file = sav_def['sav_file'] sav_file.seek(0) zip_file.write( sav_file.name, "_".join(section_name.split("/")) + ".sav") # close files when we are done for section_name, sav_def in sav_defs.iteritems(): sav_def['sav_file'].close() def dict_to_flat_export(d, parent_index=0): pass def generate_export(export_type, extension, username, id_string, export_id=None, filter_query=None, group_delimiter='/', split_select_multiples=True, binary_select_multiples=False): """ Create appropriate export object given the export type """ # TODO resolve circular import from onadata.apps.viewer.models.export import Export export_type_func_map = { Export.XLS_EXPORT: 'to_xls_export', Export.CSV_EXPORT: 'to_flat_csv_export', Export.CSV_ZIP_EXPORT: 'to_zipped_csv', Export.SAV_ZIP_EXPORT: 'to_zipped_sav', } xform = XForm.objects.get( user__username__iexact=username, id_string__iexact=id_string) # query mongo for the cursor records = query_mongo(username, id_string, filter_query) export_builder = ExportBuilder() export_builder.GROUP_DELIMITER = group_delimiter export_builder.SPLIT_SELECT_MULTIPLES = split_select_multiples export_builder.BINARY_SELECT_MULTIPLES = binary_select_multiples export_builder.set_survey(xform.data_dictionary().survey) temp_file = NamedTemporaryFile(suffix=("." + extension)) # get the export function by export type func = getattr(export_builder, export_type_func_map[export_type]) func.__call__( temp_file.name, records, username, id_string, filter_query) # generate filename basename = "%s_%s" % ( id_string, datetime.now().strftime("%Y_%m_%d_%H_%M_%S")) filename = basename + "." + extension # check filename is unique while not Export.is_filename_unique(xform, filename): filename = increment_index_in_filename(filename) file_path = os.path.join( username, 'exports', id_string, export_type, filename) # TODO: if s3 storage, make private - how will we protect local storage?? storage = get_storage_class()() # seek to the beginning as required by storage classes temp_file.seek(0) export_filename = storage.save( file_path, File(temp_file, file_path)) temp_file.close() dir_name, basename = os.path.split(export_filename) # get or create export object if export_id: export = Export.objects.get(id=export_id) else: export = Export(xform=xform, export_type=export_type) export.filedir = dir_name export.filename = basename export.internal_status = Export.SUCCESSFUL # dont persist exports that have a filter if filter_query is None: export.save() return export def query_mongo(username, id_string, query=None, hide_deleted=True): query = json.loads(query, object_hook=json_util.object_hook)\ if query else {} query = dict_for_mongo(query) query[USERFORM_ID] = u'{0}_{1}'.format(username, id_string) if hide_deleted: # display only active elements # join existing query with deleted_at_query on an $and query = {"$and": [query, {"_deleted_at": None}]} return xform_instances.find(query) def should_create_new_export(xform, export_type): # TODO resolve circular import from onadata.apps.viewer.models.export import Export if Export.objects.filter( xform=xform, export_type=export_type).count() == 0\ or Export.exports_outdated(xform, export_type=export_type): return True return False def newset_export_for(xform, export_type): """ Make sure you check that an export exists before calling this, it will a DoesNotExist exception otherwise """ # TODO resolve circular import from onadata.apps.viewer.models.export import Export return Export.objects.filter(xform=xform, export_type=export_type)\ .latest('created_on') def increment_index_in_filename(filename): """ filename should be in the form file.ext or file-2.ext - we check for the dash and index and increment appropriately """ # check for an index i.e. dash then number then dot extension regex = re.compile(r"(.+?)\-(\d+)(\..+)") match = regex.match(filename) if match: basename = match.groups()[0] index = int(match.groups()[1]) + 1 ext = match.groups()[2] else: index = 1 # split filename from ext basename, ext = os.path.splitext(filename) new_filename = "%s-%d%s" % (basename, index, ext) return new_filename def generate_attachments_zip_export( export_type, extension, username, id_string, export_id=None, filter_query=None): # TODO resolve circular import from onadata.apps.viewer.models.export import Export xform = XForm.objects.get(user__username=username, id_string=id_string) attachments = Attachment.objects.filter(instance__xform=xform) basename = "%s_%s" % (id_string, datetime.now().strftime("%Y_%m_%d_%H_%M_%S")) filename = basename + "." + extension file_path = os.path.join( username, 'exports', id_string, export_type, filename) storage = get_storage_class()() zip_file = None try: zip_file = create_attachments_zipfile(attachments) try: temp_file = open(zip_file.name) export_filename = storage.save( file_path, File(temp_file, file_path)) finally: temp_file.close() finally: zip_file and zip_file.close() dir_name, basename = os.path.split(export_filename) # get or create export object if(export_id): export = Export.objects.get(id=export_id) else: export = Export.objects.create(xform=xform, export_type=export_type) export.filedir = dir_name export.filename = basename export.internal_status = Export.SUCCESSFUL export.save() return export def generate_kml_export( export_type, extension, username, id_string, export_id=None, filter_query=None): # TODO resolve circular import from onadata.apps.viewer.models.export import Export user = User.objects.get(username=username) xform = XForm.objects.get(user__username=username, id_string=id_string) response = render_to_response( 'survey.kml', {'data': kml_export_data(id_string, user)}) basename = "%s_%s" % (id_string, datetime.now().strftime("%Y_%m_%d_%H_%M_%S")) filename = basename + "." + extension file_path = os.path.join( username, 'exports', id_string, export_type, filename) storage = get_storage_class()() temp_file = NamedTemporaryFile(suffix=extension) temp_file.write(response.content) temp_file.seek(0) export_filename = storage.save( file_path, File(temp_file, file_path)) temp_file.close() dir_name, basename = os.path.split(export_filename) # get or create export object if(export_id): export = Export.objects.get(id=export_id) else: export = Export.objects.create(xform=xform, export_type=export_type) export.filedir = dir_name export.filename = basename export.internal_status = Export.SUCCESSFUL export.save() return export def kml_export_data(id_string, user): # TODO resolve circular import from onadata.apps.viewer.models.data_dictionary import DataDictionary dd = DataDictionary.objects.get(id_string=id_string, user=user) instances = Instance.objects.filter( xform__user=user, xform__id_string=id_string, geom__isnull=False ).order_by('id') data_for_template = [] labels = {} def cached_get_labels(xpath): if xpath in labels.keys(): return labels[xpath] labels[xpath] = dd.get_label(xpath) return labels[xpath] for instance in instances: # read the survey instances data_for_display = instance.get_dict() xpaths = data_for_display.keys() xpaths.sort(cmp=instance.xform.data_dictionary().get_xpath_cmp()) label_value_pairs = [ (cached_get_labels(xpath), data_for_display[xpath]) for xpath in xpaths if not xpath.startswith(u"_")] table_rows = ['<tr><td>%s</td><td>%s</td></tr>' % (k, v) for k, v in label_value_pairs] img_urls = image_urls(instance) img_url = img_urls[0] if img_urls else "" point = instance.point if point: data_for_template.append({ 'name': id_string, 'id': instance.id, 'lat': point.y, 'lng': point.x, 'image_urls': img_urls, 'table': '<table border="1"><a href="#"><img width="210" ' 'class="thumbnail" src="%s" alt=""></a>%s' '</table>' % (img_url, ''.join(table_rows))}) return data_for_template def _get_records(instances): return [clean_keys_of_slashes(instance.get_dict()) for instance in instances] def clean_keys_of_slashes(record): """ Replaces the slashes found in a dataset keys with underscores :param record: list containing a couple of dictionaries :return: record with keys without slashes """ for key in record: value = record[key] if '/' in key: # replace with _ record[key.replace('/', '_')]\ = record.pop(key) # Check if the value is a list containing nested dict and apply same if value: if isinstance(value, list) and isinstance(value[0], dict): for v in value: clean_keys_of_slashes(v) return record def _get_server_from_metadata(xform, meta, token): report_templates = MetaData.external_export(xform) if meta: try: int(meta) except ValueError: raise Exception(u"Invalid metadata pk {0}".format(meta)) # Get the external server from the metadata result = report_templates.get(pk=meta) server = result.external_export_url name = result.external_export_name elif token: server = token name = None else: # Take the latest value in the metadata if not report_templates: raise Exception( u"Could not find the template token: Please upload template.") server = report_templates[0].external_export_url name = report_templates[0].external_export_name return server, name def generate_external_export( export_type, username, id_string, export_id=None, token=None, filter_query=None, meta=None): xform = XForm.objects.get( user__username__iexact=username, id_string__iexact=id_string) user = User.objects.get(username=username) server, name = _get_server_from_metadata(xform, meta, token) # dissect the url parsed_url = urlparse(server) token = parsed_url.path[5:] ser = parsed_url.scheme + '://' + parsed_url.netloc records = _get_records(Instance.objects.filter( xform__user=user, xform__id_string=id_string)) status_code = 0 if records and server: try: client = Client(ser) response = client.xls.create(token, json.dumps(records)) if hasattr(client.xls.conn, 'last_response'): status_code = client.xls.conn.last_response.status_code except Exception as e: raise J2XException( u"J2X client could not generate report. Server -> {0}," u" Error-> {1}".format(server, e) ) else: if not server: raise J2XException(u"External server not set") elif not records: raise J2XException( u"No record to export. Form -> {0}".format(id_string) ) # get or create export object if export_id: export = Export.objects.get(id=export_id) else: export = Export.objects.create(xform=xform, export_type=export_type) export.export_url = response if status_code == 201: export.internal_status = Export.SUCCESSFUL export.filename = name + '-' + response[5:] if name else response[5:] export.export_url = ser + response else: export.internal_status = Export.FAILED export.save() return export def upload_template_for_external_export(server, file_obj): try: client = Client(server) response = client.template.create(template_file=file_obj) if hasattr(client.template.conn, 'last_response'): status_code = client.template.conn.last_response.status_code except Exception as e: response = str(e) status_code = 500 return str(status_code) + '|' + response
bsd-2-clause
all-umass/superman
superman/preprocess/steps.py
1
5980
from __future__ import absolute_import, division, print_function import numpy as np import scipy.signal import scipy.sparse from sklearn.preprocessing import normalize from sklearn.decomposition import PCA from .utils import libs_norm3, cumulative_norm __all__ = [ 'BandNormalize', 'BezierSquash', 'CosineSquash', 'CumulativeNormalize', 'HingeSquash', 'L1Normalize', 'L2Normalize', 'LibsNormalize', 'LogSquash', 'MaxNormalize', 'MinZeroNormalize', 'Offset', 'PolynomialSquash', 'PrincipalComponents', 'SavitzkyGolayDerivative', 'SavitzkyGolaySmooth', 'SqrtSquash', 'TanhSquash' ] class Preprocessor(object): arg_type = float def apply(self, spectra, wavelengths): ''' S, w = apply(S, w)''' raise NotImplementedError('Subclasses must implement apply_vector.') @classmethod def from_string(cls, s): if not s: return cls() args = map(cls.arg_type, s.split(':')) return cls(*args) class PrincipalComponents(Preprocessor): name = 'pca' def __init__(self, num_pcs): # Hack: may be float in (0,1] or positive int. We'll assume 1-D in the case # of 1.0, as that's more common. if num_pcs >= 1: assert num_pcs - int(num_pcs) == 0 num_pcs = int(num_pcs) self.model = PCA(n_components=num_pcs) def apply(self, spectra, wavelengths): pcs = self.model.fit_transform(spectra) return pcs, wavelengths class PolynomialSquash(Preprocessor): '''Generalized polynomial squashing function. Derived from a normal cubic polynomial with f(0) = 0 and f(1) = 1. We also enforce d/dx => 0 and d2/d2x <= 0, for a concave shape. This constrains -0.5 < a < 1, and -2a-1 < b < min(-3a, 0). ''' name = 'poly' def __init__(self, a, b): assert -0.5 < a < 1 assert -2*a - 1 < b < min(-3*a, 0) c = 1 - a - b self.poly = np.poly1d([a, b, c, 0]) def apply(self, spectra, wavelengths): x = spectra / np.max(spectra, axis=1, keepdims=True) p = self.poly(x) return normalize(p, norm='l2', copy=False), wavelengths class BezierSquash(Preprocessor): '''Bezier squashing function. Derived from a bezier curve with control points at [(0,0), (a,b), (1,1)] Constraints are 0 < a < 1, 0 < b < 1, b > a (upper left of y = x line). ''' name = 'bezier' def __init__(self, a, b): assert 0 < a < 1 assert 0 < b < 1 assert b > a twoa = 2*a twob = 2*b if twoa == 1: a += 1e-5 twoa = 2*a self.args = (a, b, twoa, twob) def apply(self, spectra, wavelengths): x = spectra / np.max(spectra, axis=1, keepdims=True) a, b, twoa, twob = self.args tmp = np.sqrt(a*a-twoa*x+x) foo = x * (1 - twob) top = -twoa*(tmp+foo+b) + twob*tmp + foo + twoa*a p = top / (1-twoa)**2 return normalize(p, norm='l2', copy=False), wavelengths class HingeSquash(Preprocessor): name = 'squash:hinge' def __init__(self, h): self.hinge = h def apply(self, spectra, wavelengths): return np.minimum(spectra, self.hinge), wavelengths class CosineSquash(Preprocessor): name = 'squash:cos' def apply(self, spectra, wavelengths): np.maximum(spectra, 1e-10, out=spectra) # Hack: fix NaN issues s = (1 - np.cos(np.pi * spectra)) / 2.0 return s, wavelengths def _generic_squash(numpy_func_name): fn = getattr(np, numpy_func_name) class _GenericSquash(Preprocessor): name = 'squash:' + numpy_func_name def apply(self, spectra, wavelengths): return fn(spectra), wavelengths _GenericSquash.__name__ = numpy_func_name.title() + 'Squash' return _GenericSquash TanhSquash = _generic_squash('tanh') SqrtSquash = _generic_squash('sqrt') LogSquash = _generic_squash('log') class LibsNormalize(Preprocessor): name = 'normalize:norm3' def apply(self, spectra, wavelengths): s = libs_norm3(spectra, wavelengths=wavelengths, copy=False) return s, wavelengths class CumulativeNormalize(Preprocessor): name = 'normalize:cum' def apply(self, spectra, wavelengths): return cumulative_norm(spectra), wavelengths class MinZeroNormalize(Preprocessor): name = 'normalize:min' def apply(self, spectra, wavelengths): spectra -= spectra.min(axis=1)[:, None] return spectra, wavelengths class BandNormalize(Preprocessor): name = 'normalize:band' def __init__(self, loc): self.loc = loc def apply(self, spectra, wavelengths): idx = np.searchsorted(wavelengths, self.loc) a = max(0, idx - 2) b = min(len(wavelengths), idx + 3) x = spectra[:, a:b].max(axis=1) spectra /= x[:,None] return spectra, wavelengths def _generic_norm(norm): assert norm in ('max', 'l1', 'l2') class _GenericNorm(Preprocessor): name = 'normalize:' + norm def apply(self, spectra, wavelengths): return normalize(spectra, norm=norm, copy=False), wavelengths _GenericNorm.__name__ = norm.title() + 'Normalize' return _GenericNorm MaxNormalize = _generic_norm('max') L1Normalize = _generic_norm('l1') L2Normalize = _generic_norm('l2') class SavitzkyGolayDerivative(Preprocessor): name = 'deriv' arg_type = int def __init__(self, window, order): self.window = window self.order = order def apply(self, spectra, wavelengths): assert not scipy.sparse.issparse(spectra) d = scipy.signal.savgol_filter(spectra, self.window, self.order, deriv=1) return d, wavelengths class SavitzkyGolaySmooth(SavitzkyGolayDerivative): name = 'smooth' def apply(self, spectra, wavelengths): assert not scipy.sparse.issparse(spectra) d = scipy.signal.savgol_filter(spectra, self.window, self.order, deriv=0) return d, wavelengths class Offset(Preprocessor): name = 'offset' def __init__(self, x, y=0): self.intensity_offset = y self.wavelength_offset = x def apply(self, spectra, wavelengths): if self.intensity_offset != 0: spectra += self.intensity_offset if self.wavelength_offset != 0: wavelengths += self.wavelength_offset return spectra, wavelengths
mit
alpatania/MapperTools
inside_mapper.py
1
8292
# MapperTools -- a Python library that computes a mapper graph # @author: Alice Patania <[email protected]> # # MapperTools/inside_mapper.py # function called in the 2d mapper from collections import defaultdict import pandas as pd import numpy as np from .clusters import compute_bic, cluster_affinity, cluster_kmeans, cluster_DBSCAN, cluster_HDBSCAN, cluster_spectral, cluster_agglomerative def inside_mapper_pb(idx, data_dict, level_idx, node_info, method, level, b, verb=False): ''' Computes the partions and node_info dictionary entries for the new nodes in the graph. Parameters ---------- idx : set Set of indices in data_dict data_dict: pandas.DataFame level_idx: dict dictionary containing the nodes constructed at each level node_info: dict dictionary containing the attributes of the nodes in the graph method : str Clustering method to be used. Can be {"kmeans","affinity","HDBSCAN"}. Refer to sklearn documentation for more information on the differences between the methods. level : tuple level indices of the bins, int() b : tuple extreme values of the bins Returns ------- node_info, level_idx[level] udated versions of the dictionaries in input ''' num_points = len(idx) if num_points<5: if verb: print "\x1b[31m less 5 points \x1b[0m" if verb: print ("\tEstimated number of clusters: %d' "% num_points) now=data_dict.ix[idx] X=now.as_matrix() node_colors = np.array(range(len(idx))) num_colors = len(set(node_colors)) num_graph_nodes = len(node_info) level_idx[level] = [] if level[0]>level[1]: for k in set(node_colors): curr_color = k + num_graph_nodes level_idx[level].append(curr_color) #node_info[curr_color]['level'] = level; #node_info[curr_color]['fnval'] = b; node_info[curr_color]['set'] = set(now.index[node_colors == k]); #node_info[curr_color]['data'] = X[node_colors == k,:]; else: for k in set(node_colors): curr_color = k + num_graph_nodes level_idx[level].append(curr_color) #node_info[curr_color]['level'] = level; #node_info[curr_color]['fnval'] = b; node_info[curr_color]['set'] = set(now.index[node_colors == k]); #node_info[curr_color]['data'] = X[node_colors == k,:]; return node_info,level_idx[level] #----------------- dam=0.8 #print idx #print data_dict.index now=data_dict.ix[idx] X=now.as_matrix() if method== "kmeans": labels, n_clusters_=cluster_kmeans(now,range(1,5)) elif method== "affinity": labels, n_clusters_=cluster_affinity(X) elif method == "HDBSCAN": labels, n_clusters_=cluster_HDBSCAN(X) else: raise ValueError('The chosen clustering method is not valid') if n_clusters_==0: if verb: print "\x1b[31m no cluster \x1b[0m" return 0 #-------------------- if verb: print ("\tEstimated number of clusters: %d' "% n_clusters_) node_colors = labels num_colors = len(set(node_colors)) num_graph_nodes = len(node_info) #-------------------- level_idx[level] = [] if level[0]>level[1]: for k in set(node_colors): curr_color = k + num_graph_nodes level_idx[level].append(curr_color) #node_info[curr_color]['level'] = level; #node_info[curr_color]['fnval'] = b; node_info[curr_color]['set'] = set(now.index[node_colors == k]); #node_info[curr_color]['data'] = X[node_colors == k,:]; else: for k in set(node_colors): curr_color = k + num_graph_nodes level_idx[level].append(curr_color) #node_info[curr_color]['level'] = level; #node_info[curr_color]['fnval'] = b; node_info[curr_color]['set'] = set(now.index[node_colors == k]); #node_info[curr_color]['data'] = X[node_colors == k,:]; return node_info,level_idx[level] def creat_adja(node_info, level, adja, level_idx, direction="both"): ''' Computes the edges of the graph connecting the new created nodes with the existing ones Parameters ---------- node_info : defaultdict(dict) dictionary containing the attributes of the nodes in the graph (output from inside_mapper or inside_mapper_pb) level : tuple level indices of the bins, int() adja : defaultdict(dict) the keys are tuples (i,j) where i,j is and existing edge in the graph. the values are the wights of the edges computed as the numer of elements in common between clusters i and j. level_idx: dict dictionary containing the nodes constructed at each level direction : str Can be: {"both","left","down"}. "both" : runs creat_adja with `direction`="left". Runs again creat_adja with adja updated and `direction`="down". "left" : computes the edges considering the overlap between bin (i,j) and (i,j-1). "down" : computes the edges considering the overlap between bin (i,j) and (i-1,j). Returns ------- adja : defaultdict(dict) updated versions of the dictionary in input ''' if adja == 0: return 0 if direction == "both": result = creat_adja(node_info, level, adja.copy(), level_idx, "left") matrix = creat_adja(node_info, level, result.copy(), level_idx, "down") if matrix == 0: return 0 else: return matrix elif direction == "left": prev_lvl_idx = level_idx[(level[0],level[1] - 1)] this_lvl_idx = level_idx[level] elif direction == "down": prev_lvl_idx = level_idx[(level[0] - 1, level[1])] this_lvl_idx = level_idx[level] for i1 in prev_lvl_idx: for i2 in this_lvl_idx: a = int(i1) b = int(i2) if len(node_info[a]['set'] & node_info[b]['set']) > 0: adja[(a, b)] = len(node_info[a]['set'] & node_info[b]['set']) adja[(b, a)] = len(node_info[a]['set'] & node_info[b]['set']) return adja.copy() def creat_adja_notefficient(node_info, adja, level_idx): ''' Computes the edges of the graph connecting the new created nodes with the existing ones Parameters ---------- node_info : defaultdict(dict) dictionary containing the attributes of the nodes in the graph (output from inside_mapper or inside_mapper_pb) adja : defaultdict(dict) the keys are tuples (i,j) where i,j is and existing edge in the graph. the values are the wights of the edges computed as the numer of elements in common between clusters i and j. level_idx: dict dictionary containing the nodes constructed at each level direction : str Can be: {"both","left","down"}. "both" : runs creat_adja with `direction`="left". Runs again creat_adja with adja updated and `direction`="down". "left" : computes the edges considering the overlap between bin (i,j) and (i,j-1). "down" : computes the edges considering the overlap between bin (i,j) and (i-1,j). Returns ------- adja : defaultdict(dict) updated versions of the dictionary in input ''' if adja == 0: return 0 for i,j in level_idx.keys(): for i_compare in [i-1,i,i+1]: if i_compare<0: continue for j_compare in [j-1,j,j+1]: if j_compare<0: continue this_lvl_node = level_idx[(i,j)] compare_lvl_node = level_idx[(i_compare,j_compare)] for i1 in compare_lvl_node: for i2 in this_lvl_node: a = int(i1) b = int(i2) if len(node_info[a]['set'] & node_info[b]['set']) > 0: adja[(a, b)] = len(node_info[a]['set'] & node_info[b]['set']) adja[(b, a)] = len(node_info[a]['set'] & node_info[b]['set']) return adja.copy()
gpl-3.0
Bismarrck/tensorflow
tensorflow/contrib/learn/python/learn/estimators/estimator_input_test.py
46
13101
# 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. # ============================================================================== """Tests for Estimator input.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import tempfile import numpy as np from tensorflow.python.training import training_util from tensorflow.contrib.layers.python.layers import optimizers from tensorflow.contrib.learn.python.learn import metric_spec from tensorflow.contrib.learn.python.learn import models from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.contrib.learn.python.learn.estimators import _sklearn from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test from tensorflow.python.training import input as input_lib from tensorflow.python.training import queue_runner_impl _BOSTON_INPUT_DIM = 13 _IRIS_INPUT_DIM = 4 def boston_input_fn(num_epochs=None): boston = base.load_boston() features = input_lib.limit_epochs( array_ops.reshape( constant_op.constant(boston.data), [-1, _BOSTON_INPUT_DIM]), num_epochs=num_epochs) labels = array_ops.reshape(constant_op.constant(boston.target), [-1, 1]) return features, labels def boston_input_fn_with_queue(num_epochs=None): features, labels = boston_input_fn(num_epochs=num_epochs) # Create a minimal queue runner. fake_queue = data_flow_ops.FIFOQueue(30, dtypes.int32) queue_runner = queue_runner_impl.QueueRunner(fake_queue, [constant_op.constant(0)]) queue_runner_impl.add_queue_runner(queue_runner) return features, labels def iris_input_fn(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = array_ops.reshape(constant_op.constant(iris.target), [-1]) return features, labels def iris_input_fn_labels_dict(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = { 'labels': array_ops.reshape(constant_op.constant(iris.target), [-1]) } return features, labels def boston_eval_fn(): boston = base.load_boston() n_examples = len(boston.target) features = array_ops.reshape( constant_op.constant(boston.data), [n_examples, _BOSTON_INPUT_DIM]) labels = array_ops.reshape( constant_op.constant(boston.target), [n_examples, 1]) return array_ops.concat([features, features], 0), array_ops.concat([labels, labels], 0) def extract(data, key): if isinstance(data, dict): assert key in data return data[key] else: return data def linear_model_params_fn(features, labels, mode, params): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=params['learning_rate']) return prediction, loss, train_op def linear_model_fn(features, labels, mode): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) if isinstance(features, dict): (_, features), = features.items() prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return prediction, loss, train_op def linear_model_fn_with_model_fn_ops(features, labels, mode): """Same as linear_model_fn, but returns `ModelFnOps`.""" assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return model_fn.ModelFnOps( mode=mode, predictions=prediction, loss=loss, train_op=train_op) def logistic_model_no_mode_fn(features, labels): features = extract(features, 'input') labels = extract(labels, 'labels') labels = array_ops.one_hot(labels, 3, 1, 0) prediction, loss = (models.logistic_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, training_util.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return { 'class': math_ops.argmax(prediction, 1), 'prob': prediction }, loss, train_op VOCAB_FILE_CONTENT = 'emerson\nlake\npalmer\n' EXTRA_FILE_CONTENT = 'kermit\npiggy\nralph\n' class EstimatorInputTest(test.TestCase): def testContinueTrainingDictionaryInput(self): boston = base.load_boston() output_dir = tempfile.mkdtemp() est = estimator.Estimator(model_fn=linear_model_fn, model_dir=output_dir) boston_input = {'input': boston.data} float64_target = {'labels': boston.target.astype(np.float64)} est.fit(x=boston_input, y=float64_target, steps=50) scores = est.evaluate( x=boston_input, y=float64_target, metrics={ 'MSE': metric_ops.streaming_mean_squared_error }) del est # Create another estimator object with the same output dir. est2 = estimator.Estimator(model_fn=linear_model_fn, model_dir=output_dir) # Check we can evaluate and predict. scores2 = est2.evaluate( x=boston_input, y=float64_target, metrics={ 'MSE': metric_ops.streaming_mean_squared_error }) self.assertAllClose(scores2['MSE'], scores['MSE']) predictions = np.array(list(est2.predict(x=boston_input))) other_score = _sklearn.mean_squared_error(predictions, float64_target['labels']) self.assertAllClose(other_score, scores['MSE']) def testBostonAll(self): boston = base.load_boston() est = estimator.SKCompat(estimator.Estimator(model_fn=linear_model_fn)) float64_labels = boston.target.astype(np.float64) est.fit(x=boston.data, y=float64_labels, steps=100) scores = est.score( x=boston.data, y=float64_labels, metrics={ 'MSE': metric_ops.streaming_mean_squared_error }) predictions = np.array(list(est.predict(x=boston.data))) other_score = _sklearn.mean_squared_error(predictions, boston.target) self.assertAllClose(scores['MSE'], other_score) self.assertTrue('global_step' in scores) self.assertEqual(100, scores['global_step']) def testBostonAllDictionaryInput(self): boston = base.load_boston() est = estimator.Estimator(model_fn=linear_model_fn) boston_input = {'input': boston.data} float64_target = {'labels': boston.target.astype(np.float64)} est.fit(x=boston_input, y=float64_target, steps=100) scores = est.evaluate( x=boston_input, y=float64_target, metrics={ 'MSE': metric_ops.streaming_mean_squared_error }) predictions = np.array(list(est.predict(x=boston_input))) other_score = _sklearn.mean_squared_error(predictions, boston.target) self.assertAllClose(other_score, scores['MSE']) self.assertTrue('global_step' in scores) self.assertEqual(scores['global_step'], 100) def testIrisAll(self): iris = base.load_iris() est = estimator.SKCompat( estimator.Estimator(model_fn=logistic_model_no_mode_fn)) est.fit(iris.data, iris.target, steps=100) scores = est.score( x=iris.data, y=iris.target, metrics={ ('accuracy', 'class'): metric_ops.streaming_accuracy }) predictions = est.predict(x=iris.data) predictions_class = est.predict(x=iris.data, outputs=['class'])['class'] self.assertEqual(predictions['prob'].shape[0], iris.target.shape[0]) self.assertAllClose(predictions['class'], predictions_class) self.assertAllClose(predictions['class'], np.argmax(predictions['prob'], axis=1)) other_score = _sklearn.accuracy_score(iris.target, predictions['class']) self.assertAllClose(scores['accuracy'], other_score) self.assertTrue('global_step' in scores) self.assertEqual(100, scores['global_step']) def testIrisAllDictionaryInput(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) iris_data = {'input': iris.data} iris_target = {'labels': iris.target} est.fit(iris_data, iris_target, steps=100) scores = est.evaluate( x=iris_data, y=iris_target, metrics={ ('accuracy', 'class'): metric_ops.streaming_accuracy }) predictions = list(est.predict(x=iris_data)) predictions_class = list(est.predict(x=iris_data, outputs=['class'])) self.assertEqual(len(predictions), iris.target.shape[0]) classes_batch = np.array([p['class'] for p in predictions]) self.assertAllClose(classes_batch, np.array([p['class'] for p in predictions_class])) self.assertAllClose(classes_batch, np.argmax( np.array([p['prob'] for p in predictions]), axis=1)) other_score = _sklearn.accuracy_score(iris.target, classes_batch) self.assertAllClose(other_score, scores['accuracy']) self.assertTrue('global_step' in scores) self.assertEqual(scores['global_step'], 100) def testIrisInputFn(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) est.fit(input_fn=iris_input_fn, steps=100) _ = est.evaluate(input_fn=iris_input_fn, steps=1) predictions = list(est.predict(x=iris.data)) self.assertEqual(len(predictions), iris.target.shape[0]) def testIrisInputFnLabelsDict(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) est.fit(input_fn=iris_input_fn_labels_dict, steps=100) _ = est.evaluate( input_fn=iris_input_fn_labels_dict, steps=1, metrics={ 'accuracy': metric_spec.MetricSpec( metric_fn=metric_ops.streaming_accuracy, prediction_key='class', label_key='labels') }) predictions = list(est.predict(x=iris.data)) self.assertEqual(len(predictions), iris.target.shape[0]) def testTrainInputFn(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1) _ = est.evaluate(input_fn=boston_eval_fn, steps=1) def testPredictInputFn(self): est = estimator.Estimator(model_fn=linear_model_fn) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) input_fn = functools.partial(boston_input_fn, num_epochs=1) output = list(est.predict(input_fn=input_fn)) self.assertEqual(len(output), boston.target.shape[0]) def testPredictInputFnWithQueue(self): est = estimator.Estimator(model_fn=linear_model_fn) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) input_fn = functools.partial(boston_input_fn_with_queue, num_epochs=2) output = list(est.predict(input_fn=input_fn)) self.assertEqual(len(output), boston.target.shape[0] * 2) def testPredictConstInputFn(self): est = estimator.Estimator(model_fn=linear_model_fn) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) def input_fn(): features = array_ops.reshape( constant_op.constant(boston.data), [-1, _BOSTON_INPUT_DIM]) labels = array_ops.reshape(constant_op.constant(boston.target), [-1, 1]) return features, labels output = list(est.predict(input_fn=input_fn)) self.assertEqual(len(output), boston.target.shape[0]) if __name__ == '__main__': test.main()
apache-2.0
rstoneback/pysat
demo/cnofs_vefi_dc_b_orbit_plots.py
2
3127
""" Demonstrates iterating over an instrument data set by orbit and plotting the results. """ import os import pysat import matplotlib.pyplot as plt # set the directory to save plots to results_dir = '' # select vefi dc magnetometer data, use longitude to determine where # there are changes in the orbit (local time info not in file) orbit_info = {'index': 'longitude', 'kind': 'longitude'} vefi = pysat.Instrument(platform='cnofs', name='vefi', tag='dc_b', clean_level=None, orbit_info=orbit_info) # set limits on dates analysis will cover, inclusive start = pysat.datetime(2010, 5, 9) stop = pysat.datetime(2010, 5, 12) # if there is no vefi dc magnetometer data on your system, then run command # below where start and stop are pandas datetimes (from above) # pysat will automatically register the addition of this data at the end of # download vefi.download(start, stop) # leave bounds unassigned to cover the whole dataset (comment out lines below) vefi.bounds = (start, stop) for orbit_count, vefi in enumerate(vefi.orbits): # for each loop pysat puts a copy of the next available orbit into # vefi.data # changing .data at this level does not alter other orbits # reloading the same orbit will erase any changes made # satellite data can have time gaps, which leads to plots # with erroneous lines connecting measurements on both sides of the gap # command below fills in any data gaps using a 1-second cadence with NaNs # see pandas documentation for more info vefi.data = vefi.data.resample('1S', fill_method='ffill', limit=1, label='left') f, ax = plt.subplots(7, sharex=True, figsize=(8.5, 11)) ax[0].plot(vefi['longitude'], vefi['B_flag']) ax[0].set_title(vefi.data.index[0].ctime() + ' - '+vefi.data.index[-1].ctime()) ax[0].set_ylabel('Interp. Flag') ax[0].set_ylim((0, 2)) ax[1].plot(vefi['longitude'], vefi['B_north']) ax[1].set_title(vefi.meta['B_north'].long_name) ax[1].set_ylabel(vefi.meta['B_north'].units) ax[2].plot(vefi['longitude'], vefi['B_up']) ax[2].set_title(vefi.meta['B_up'].long_name) ax[2].set_ylabel(vefi.meta['B_up'].units) ax[3].plot(vefi['longitude'], vefi['B_west']) ax[3].set_title(vefi.meta['B_west'].long_name) ax[3].set_ylabel(vefi.meta['B_west'].units) ax[4].plot(vefi['longitude'], vefi['dB_mer']) ax[4].set_title(vefi.meta['dB_mer'].long_name) ax[4].set_ylabel(vefi.meta['dB_mer'].units) ax[5].plot(vefi['longitude'], vefi['dB_par']) ax[5].set_title(vefi.meta['dB_par'].long_name) ax[5].set_ylabel(vefi.meta['dB_par'].units) ax[6].plot(vefi['longitude'], vefi['dB_zon']) ax[6].set_title(vefi.meta['dB_zon'].long_name) ax[6].set_ylabel(vefi.meta['dB_zon'].units) ax[6].set_xlabel(vefi.meta['longitude'].long_name) ax[6].set_xticks([0, 60, 120, 180, 240, 300, 360]) ax[6].set_xlim((0, 360)) f.tight_layout() plt.savefig(os.path.join(results_dir, 'orbit_{num:05}.png').format(num=orbit_count)) plt.close()
bsd-3-clause
mdbartos/RIPS
network_model.py
1
11127
import numpy as np import pandas as pd import geopandas as gpd class network_model(): def __init__(self, lines, subs, util, gen, bbox=None, loads=None, pop_dens=None): self.lines = gpd.read_file(lines) self.subs = gpd.read_file(subs) self.util = gpd.read_file(util) self.gen = gpd.read_file(gen) if loads is None: if pop_dens is not None: loads = self.partition_loads(self.construct_voronoi(), pop_dens) if edges is None: edges = self.line_to_sub() if node_gen is None: node_gen = self.gen_to_sub() self.net = pd.concat([loads.groupby('SUB_ID').sum()['summer_loa'], gen.groupby('SUB_ID').sum()['S_CAP_MW'].fillna(0)], axis=1, join='outer')[['summer_loa', 'S_CAP_MW']].fillna(0) self.net = self.net['S_CAP_MW'] - self.net['summer_loa'] if bbox is not None: self.nodes, self.edges, self.loads = self.set_bbox(*bbox) # Set up graph self.G = nx.Graph() for i in self.loads.index: self.G.add_node(i, load=self.loads[i]) for i in self.edges.index: row = self.edges.loc[i] self.G.add_edge(*tuple(row[['SUB_1', 'SUB_2']].astype(int).values), tot_kv=row['TOT_CAP_KV'], num_lines=int(row['NUM_LINES']), length=row['LENGTH']) def construct_voronoi(self): from scipy import spatial from geopandas import tools from shapely import geometry util = self.util sub = self.sub # Fix utility service areas with invalid geometry invalid_util = util[~util['geometry'].apply(lambda x: x.is_valid)] util.loc[invalid_util.index, 'geometry'] = util.loc[invalid_util.index, 'geometry'].apply(lambda x: x.buffer(0)) # Spatially join substations with utility service territories sub_util = tools.sjoin(sub, util, op='within', how='left') # Construct voronoi polygons for each substation sub_xy = np.vstack(sub['geometry'].apply(lambda u: np.concatenate(u.xy)).values) vor = spatial.Voronoi(sub_xy) reg, vert = self.voronoi_finite_polygons_2d(vor,1) # Convert voronoi diagram to polygons and insert into GeoDataFrame v_poly = gpd.GeoSeries(pd.Series(reg).apply(lambda x: geometry.Polygon(vert[x]))) v_gdf = gpd.GeoDataFrame(pd.concat([sub.drop('geometry', axis=1), v_poly], axis=1)).rename(columns={0:'geometry'}) v_gdf.crs = sub.crs # Spatially join utility service areas with voronoi polygons j = tools.sjoin(util, v_gdf, op='intersects') j['right_geom'] = j['UNIQUE_ID_right'].map(v_gdf.set_index('UNIQUE_ID')['geometry']) j = j.dropna(subset=['geometry', 'right_geom']).set_index('UNIQUE_ID_left') # Clip voronoi polygons to utility service area j_inter = j.apply(lambda x: x['geometry'].intersection(x['right_geom']), axis=1) # Create output GeoDataFrame with relevant fields outdf = gpd.GeoDataFrame(pd.concat([j[['UNIQUE_ID_right', 'SUMMERPEAK', 'WINTERPEAK']].reset_index(), j_inter.reset_index()[0]], axis=1), crs=sub.crs).rename(columns={0:'geometry', 'UNIQUE_ID_left':'UTIL_ID', 'UNIQUE_ID_right':'SUB_ID'}) return outdf def partition_loads(self, vor, pop_dens): # voronoi_stats.shp import rasterstats import rasterio #### FOR ICLUS, BEST PROJECTION IS EPSG 5070: NAD83/CONUS ALBERS # vor = '/home/akagi/voronoi_intersect.shp' # pop_dens = '/home/akagi/Desktop/rastercopy.tif' # gdf = gpd.GeoDataFrame.from_file(vor) # rast = rasterio.open(pop_dens) if isinstance(vor, str): gdf = gpd.read_file(vor) if isinstance(pop_dens, str): pop_dens = rasterio.open(pop_dens) zones = gdf['geometry'].to_crs(pop_dens.crs) rstats = pd.DataFrame.from_dict(rasterstats.zonal_stats(zones, pop_dens, stats=['sum', 'mean'])) util_stats = pd.concat([rstats, gdf], join='inner', axis=1) tot_util = util_stats.groupby('UTIL_ID').sum()['sum'] util_stats['util_tot'] = util_stats['UTIL_ID'].map(tot_util) util_stats['load_frac'] = util_stats['sum']/util_stats['util_tot'] util_stats['summer_load'] = util_stats['SUMMERPEAK']*util_stats['load_frac'] util_stats['winter_load'] = util_stats['WINTERPEAK']*util_stats['load_frac'] return util_stats def gen_to_sub(self): from shapely import geometry from scipy import spatial sub = self.sub gen = self.gen # Find nearest neighbors tree = spatial.cKDTree(np.vstack(sub.geometry.apply(lambda x: x.coords[0]).values)) node_query = tree.query(np.vstack(gen.geometry.apply(lambda x: x.coords[0]).values)) crosswalk = pd.DataFrame(np.column_stack([gen[['UNIQUE_ID', 'S_CAP_MW']].values, s.iloc[node_query[1]]['UNIQUE_ID'].values.astype(int)]), columns=['GEN_ID', 'S_CAP_MW', 'SUB_ID']) crosswalk = crosswalk[['GEN_ID', 'SUB_ID', 'S_CAP_MW']] return crosswalk #gen_to_sub_static.csv def line_to_sub(self): from shapely import geometry from scipy import spatial t = self.lines s = self.subs # Extract start and end nodes in networkK start = t.geometry[t.geometry.type=='LineString'].apply(lambda x: np.array([x.xy[0][0], x.xy[1][0]])).append(t.geometry[t.geometry.type=='MultiLineString'].apply(lambda x: np.hstack([i.xy for i in x])[:,0])).sort_index() end = t.geometry[t.geometry.type=='LineString'].apply(lambda x: np.array([x.xy[0][-1], x.xy[1][-1]])).append(t.geometry[t.geometry.type=='MultiLineString'].apply(lambda x: np.hstack([i.xy for i in x])[:,-1])).sort_index() # Find nearest neighbors tree = spatial.cKDTree(np.vstack(s.geometry.apply(lambda x: x.coords[0]).values)) start_node_query = tree.query(np.vstack(start.values)) end_node_query = tree.query(np.vstack(end.values)) # Create crosswalk table crosswalk = pd.DataFrame(np.column_stack([t[['UNIQUE_ID', 'TOT_CAP_KV', 'NUM_LINES', 'Shape_Leng']].values, s.iloc[start_node_query[1]][['UNIQUE_ID', 'NAME']].values, start_node_query[0], s.iloc[end_node_query[1]][['UNIQUE_ID', 'NAME']].values, end_node_query[0]]), columns=['TRANS_ID', 'TOT_CAP_KV', 'NUM_LINES', 'LENGTH', 'SUB_1', 'NAME_1', 'ERR_1', 'SUB_2', 'NAME_2', 'ERR_2']) crosswalk = crosswalk[['TRANS_ID', 'SUB_1', 'SUB_2', 'NAME_1', 'NAME_2', 'ERR_1', 'ERR_2', 'TOT_CAP_KV', 'NUM_LINES', 'LENGTH']] return crosswalk #edges.csv def set_bbox(self, xmin, ymin, xmax, ymax): t = self.lines s = self.subs edges = self.edges net = self.net bbox = tuple(xmin, ymin, xmax, ymax) bbox_poly = shapely.geometry.MultiPoint(np.vstack(np.dstack(np.meshgrid(*np.hsplit(bbox, 2)))).tolist()).convex_hull bbox_lines = t[t.intersects(bbox_poly)]['UNIQUE_ID'].astype(int).values bbox_edges = edges[edges['TRANS_ID'].isin(bbox_lines)] bbox_edges = bbox_edges[bbox_edges['SUB_1'] != bbox_edges['SUB_2']] bbox_nodes = np.unique(bbox_edges[['SUB_1', 'SUB_2']].values.astype(int).ravel()) # Outer lines edgesubs = pd.merge(t[t.intersects(bbox_poly.boundary)], edges, left_on='UNIQUE_ID', right_on='TRANS_ID')[['SUB_1_y', 'SUB_2_y']].values.ravel().astype(int) # Nodes just outside of bbox (entering) outer_nodes = np.unique(edgesubs[~np.in1d(edgesubs, s[s.within(bbox_poly)]['UNIQUE_ID'].values.astype(int))]) weights = s.loc[s['UNIQUE_ID'].astype(int).isin(edgesubs[~np.in1d(edgesubs, s[s.within(bbox_poly)]['UNIQUE_ID'].values.astype(int))])].set_index('UNIQUE_ID')['MAX_VOLT'].sort_index() transfers = -net[bbox_nodes].sum()*(weights/weights.sum()) bbox_loads = net[bbox_nodes] + transfers.reindex(bbox_nodes).fillna(0) return bbox_nodes, bbox_edges, bbox_loads def voronoi_finite_polygons_2d(vor, radius=None): """ Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end. """ if vor.points.shape[1] != 2: raise ValueError("Requires 2D input") new_regions = [] new_vertices = vor.vertices.tolist() center = vor.points.mean(axis=0) if radius is None: radius = vor.points.ptp().max()*2 # Construct a map containing all ridges for a given point all_ridges = {} for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices): all_ridges.setdefault(p1, []).append((p2, v1, v2)) all_ridges.setdefault(p2, []).append((p1, v1, v2)) # Reconstruct infinite regions for p1, region in enumerate(vor.point_region): vertices = vor.regions[region] if all([v >= 0 for v in vertices]): # finite region new_regions.append(vertices) continue # reconstruct a non-finite region ridges = all_ridges[p1] new_region = [v for v in vertices if v >= 0] for p2, v1, v2 in ridges: if v2 < 0: v1, v2 = v2, v1 if v1 >= 0: # finite ridge: already in the region continue # Compute the missing endpoint of an infinite ridge t = vor.points[p2] - vor.points[p1] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[[p1, p2]].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[v2] + direction * radius new_region.append(len(new_vertices)) new_vertices.append(far_point.tolist()) # sort region counterclockwise vs = np.asarray([new_vertices[v] for v in new_region]) c = vs.mean(axis=0) angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0]) new_region = np.array(new_region)[np.argsort(angles)] # finish new_regions.append(new_region.tolist()) return new_regions, np.asarray(new_vertices)
mit
supriyantomaftuh/innstereo
innstereo/rotation_dialog.py
1
22040
#!/usr/bin/python3 """ This module stores the RotationDialog class which controls the rotation dialog. The module contains only the RotationDialog class. It controls the behaviour of the data-rotation dialog. """ from gi.repository import Gtk from matplotlib.figure import Figure from matplotlib.gridspec import GridSpec from matplotlib.backends.backend_gtk3cairo import (FigureCanvasGTK3Cairo as FigureCanvas) import numpy as np import mplstereonet import os class RotationDialog(object): """ This class controls the appearance and signals of the data-rotation dialog. This class pulls the rotation dialog from the Glade file, intilizes the widgets and has methods for the signals defined in Glade. """ def __init__(self, main_window, settings, data, add_layer_dataset, add_feature, redraw_main): """ Initializes the RotationDialog class. Requires the main_window object, the settings object (PlotSettings class) and the data rows to initialize. All the necessary widgets are loaded from the Glade file. A matplotlib figure is set up and added to the scrolledwindow. Two axes are set up that show the original and rotated data. """ self.builder = Gtk.Builder() script_dir = os.path.dirname(__file__) rel_path = "gui_layout.glade" abs_path = os.path.join(script_dir, rel_path) self.builder.add_objects_from_file(abs_path, ("dialog_rotation", "adjustment_rotation_dipdir", "adjustment_rotation_dip", "adjustment_rotation_angle")) self.dialog = self.builder.get_object("dialog_rotation") self.dialog.set_transient_for(main_window) self.settings = settings self.data = data self.trans = self.settings.get_transform() self.add_layer_dataset = add_layer_dataset self.add_feature = add_feature self.redraw_main = redraw_main self.adjustment_rotation_dipdir = self.builder.get_object("adjustment_rotation_dipdir") self.adjustment_rotation_dip = self.builder.get_object("adjustment_rotation_dip") self.adjustment_rotation_angle = self.builder.get_object("adjustment_rotation_angle") self.spinbutton_rotation_dipdir = self.builder.get_object("spinbutton_rotation_dipdir") self.spinbutton_rotation_dip = self.builder.get_object("spinbutton_rotation_dip") self.spinbutton_rotation_angle = self.builder.get_object("spinbutton_rotation_angle") self.scrolledwindow_rotate = self.builder.get_object("scrolledwindow_rotate") self.fig = Figure(dpi=self.settings.get_pixel_density()) self.canvas = FigureCanvas(self.fig) self.scrolledwindow_rotate.add_with_viewport(self.canvas) gridspec = GridSpec(1, 2) original_sp = gridspec.new_subplotspec((0, 0), rowspan=1, colspan=1) rotated_sp = gridspec.new_subplotspec((0, 1), rowspan=1, colspan=1) self.original_ax = self.fig.add_subplot(original_sp, projection=self.settings.get_projection()) self.rotated_ax = self.fig.add_subplot(rotated_sp, projection=self.settings.get_projection()) self.canvas.draw() self.redraw_plot() self.dialog.show_all() self.builder.connect_signals(self) def run(self): """ Runs the dialog. Called from the MainWindow class. Initializes and shows the dialog. """ self.dialog.run() def on_dialog_rotation_destroy(self, widget): """ Hides the dialog on destroy. When the dialog is destroyed it is hidden. """ self.dialog.hide() def on_button_cancel_rotation_clicked(self, button): """ Exits the rotation dialog and makes no changes to the project. When the user clicks on Cancel the dialog is hidden, and no changes are made to the project structure. """ self.dialog.hide() def on_button_apply_rotate_clicked(self, button): """ Adds the rotated layers to the project. When the user clicks on "apply the rotation", the rotated data is added to the project as new datasets. """ raxis_dipdir = self.spinbutton_rotation_dipdir.get_value() raxis_dip = self.spinbutton_rotation_dip.get_value() raxis = [raxis_dipdir, raxis_dip] raxis_angle = self.spinbutton_rotation_angle.get_value() for lyr_obj in self.data: lyr_type = lyr_obj.get_layer_type() lyr_store = lyr_obj.get_data_treestore() if lyr_type == "plane": dipdir_org, dips_org, dipdir_lst, dips_lst, strat, dipdir_az = \ self.parse_plane(lyr_store, raxis, raxis_angle) store, new_lyr_obj = self.add_layer_dataset("plane") for dipdir, dip, strt in zip(dipdir_az, dips_lst, strat): self.add_feature("plane", store, dipdir, dip, strt) elif lyr_type == "line": ldipdir_org, ldips_org, ldipdir_lst, ldips_lst, sense = \ self.parse_line(lyr_store, raxis, raxis_angle) store, new_lyr_obj = self.add_layer_dataset("line") for dipdir, dip, sns in zip(ldipdir_lst, ldips_lst, sense): self.add_feature("line", store, dipdir, dip, sns) elif lyr_type == "smallcircle": ldipdir_org, ldips_org, ldipdir_lst, ldips_lst, angle = \ self.parse_line(lyr_store, raxis, raxis_angle) store, new_lyr_obj = self.add_layer_dataset("smallcircle") for dipdir, dip, ang in zip(ldipdir_lst, ldips_lst, angle): self.add_feature("smallcircle", store, dipdir, dip, ang) elif lyr_type == "faultplane": rtrn = self.parse_faultplane(lyr_store, raxis, raxis_angle) dipdir_org, dips_org, dipdir_lst, dips_lst, ldipdir_org, \ ldips_org, ldipdir_lst, ldips_lst, sense, dipdir_az = rtrn[0], \ rtrn[1], rtrn[2], rtrn[3], rtrn[4], rtrn[5], rtrn[6], rtrn[7], \ rtrn[8], rtrn[9] store, new_lyr_obj = self.add_layer_dataset("faultplane") for dipdir, dip, ldipdir, ldip, sns in zip(dipdir_az, dips_lst, ldipdir_lst, ldips_lst, sense): self.add_feature("faultplane", store, dipdir, dip, ldipdir, ldip, sns) new_lyr_obj.set_properties(lyr_obj.get_properties()) self.dialog.hide() self.redraw_main() def on_spinbutton_rotation_dipdir_value_changed(self, spinbutton): """ Redraws the plot. When the value of the spinbutton is changed, the redraw_plot method is called, which rotates the data according to the new setting. """ self.redraw_plot() def on_spinbutton_rotation_dip_value_changed(self, spinbutton): """ Redraws the plot. When the value of the spinbutton is changed, the redraw_plot method is called, which rotates the data according to the new setting. """ self.redraw_plot() def on_spinbutton_rotation_angle_value_changed(self, spinbutton): """ Redraws the plot. When the value of the spinbutton is changed, the redraw_plot method is called, which rotates the data according to the new setting. """ self.redraw_plot() def convert_lonlat_to_dipdir(self, lon, lat): """ Converts lat-lon data to dip-direction and dip. Expects a longitude and a latitude value. The measurment is forward transformed into stereonet-space. Then the azimut (dip-direction) and diping angle are calculated. Returns two values: dip-direction and dip. """ #The longitude and latitude have to be forward-transformed to get #the corect azimuth angle xy = np.array([[lon, lat]]) xy_trans = self.trans.transform(xy) x = float(xy_trans[0,0:1]) y = float(xy_trans[0,1:2]) alpha = np.arctan2(x, y) alpha_deg = np.degrees(alpha) if alpha_deg < 0: alpha_deg += 360 #Longitude and Latitude don't need to be converted for rotation. #The correct dip is the array[1] value once the vector has been #rotated in north-south position. array = mplstereonet.stereonet_math._rotate(np.degrees(lon), np.degrees(lat), alpha_deg * (-1)) gamma = float(array[1]) gamma_deg = 90 - np.degrees(gamma) #If the longitude is larger or small than pi/2 the measurment lies #on the upper hemisphere and needs to be corrected. if lon > (np.pi / 2) or lon < (-np.pi / 2): alpha_deg = alpha_deg + 180 return alpha_deg, gamma_deg def rotate_data(self, raxis, raxis_angle, dipdir, dip): """ Rotates a measurment around a rotation axis a set number of degrees. Expects a rotation-axis, a rotation-angle, a dip-direction and a dip angle. The measurement is converted to latlot and then passed to the mplstereonet rotate function. """ lonlat = mplstereonet.line(dip, dipdir) #Rotation around x-axis until rotation-axis azimuth is east-west rot1 = (90 - raxis[0]) lon1 = np.degrees(lonlat[0]) lat1 = np.degrees(lonlat[1]) lon_rot1, lat_rot1 = mplstereonet.stereonet_math._rotate(lon1, lat1, theta=rot1, axis="x") #Rotation around z-axis until rotation-axis dip is east-west rot2 = -(90 - raxis[1]) lon2 = np.degrees(lon_rot1) lat2 = np.degrees(lat_rot1) lon_rot2, lat_rot2 = mplstereonet.stereonet_math._rotate(lon2, lat2, theta=rot2, axis="z") #Rotate around the x-axis for the specified rotation: rot3 = raxis_angle lon3 = np.degrees(lon_rot2) lat3 = np.degrees(lat_rot2) lon_rot3, lat_rot3 = mplstereonet.stereonet_math._rotate(lon3, lat3, theta=rot3, axis="x") #Undo the z-axis rotation rot4 = -rot2 lon4 = np.degrees(lon_rot3) lat4 = np.degrees(lat_rot3) lon_rot4, lat_rot4 = mplstereonet.stereonet_math._rotate(lon4, lat4, theta=rot4, axis="z") #Undo the x-axis rotation rot5 = -rot1 lon5 = np.degrees(lon_rot4) lat5 = np.degrees(lat_rot4) lon_rot5, lat_rot5 = mplstereonet.stereonet_math._rotate(lon5, lat5, theta=rot5, axis="x") dipdir5, dip5 = self.convert_lonlat_to_dipdir(lon_rot5, lat_rot5) return dipdir5, dip5 def parse_plane(self, lyr_store, raxis, raxis_angle): """ Parses and rotates data of a plane layer. Expects a TreeStore of a layer, the rotation axis and the angle of rotation. The method returns each column unrotated and rotated. """ dipdir_org = [] dips_org = [] dipdir_lst = [] dips_lst = [] dipdir_az = [] strat = [] for row in lyr_store: dipdir_org.append(row[0] - 90) dips_org.append(row[1]) #Planes and faultplanes are rotated using their poles dipdir, dip = self.rotate_data(raxis, raxis_angle, row[0] + 180, 90 - row[1]) dipdir_lst.append(dipdir + 90) dipdir_az.append(dipdir + 180) dips_lst.append(90 - dip) strat.append(row[2]) return dipdir_org, dips_org, dipdir_lst, dips_lst, strat, dipdir_az def parse_line(self, lyr_store, raxis, raxis_angle): """ Parses and rotates data of a linear or smallcircle layer. Expects a TreeStore of a layer, the rotation axis and the angle of rotation. The method returns each column unrotated and rotated. """ ldipdir_org = [] ldips_org = [] ldipdir_lst = [] ldips_lst = [] third_col = [] for row in lyr_store: ldipdir_org.append(row[0]) ldips_org.append(row[1]) ldipdir, ldip = self.rotate_data(raxis, raxis_angle, row[0], row[1]) ldipdir_lst.append(ldipdir) ldips_lst.append(ldip) third_col.append(row[2]) return ldipdir_org, ldips_org, ldipdir_lst, ldips_lst, third_col def parse_faultplane(self, lyr_store, raxis, raxis_angle): """ Parses and rotates data of a faultplane layer. Expects a TreeStore of a faultplane layer, the rotation axis and the angle of rotation. The method returns each column unrotated and rotated. """ dipdir_org = [] dips_org = [] dipdir_lst = [] dips_lst = [] ldipdir_org = [] ldips_org = [] ldipdir_lst = [] ldips_lst = [] dipdir_az = [] sense = [] for row in lyr_store: dipdir_org.append(row[0] - 90) dips_org.append(row[1]) #Planes and faultplanes are rotated using their poles dipdir, dip = self.rotate_data(raxis, raxis_angle, row[0] + 180, 90 - row[1]) dipdir_lst.append(dipdir + 90) dipdir_az.append(dipdir + 270) dips_lst.append(90 - dip) ldipdir_org.append(row[2]) ldips_org.append(row[3]) ldipdir, ldip = self.rotate_data(raxis, raxis_angle, row[2], row[3]) ldipdir_lst.append(ldipdir) ldips_lst.append(ldip) sense.append(row[4]) return (dipdir_org, dips_org, dipdir_lst, dips_lst, ldipdir_org, ldips_org, ldipdir_lst, ldips_lst, sense, dipdir_az) def redraw_plot(self): """ Redraws the plot using the current settings of the dialog's spinbuttons. This method clears the two axes and adds the annotations. The current values of the rotation axis and rotation angle spinbuttons are retrieved. The data is parsed, and the features are then drawn. In addition the rotation-axis is drawn. """ self.original_ax.cla() self.rotated_ax.cla() self.original_ax.grid(False) self.rotated_ax.grid(False) self.original_ax.set_azimuth_ticks([0], labels=["N"]) self.rotated_ax.set_azimuth_ticks([0], labels=["N"]) bar = 0.05 self.original_ax.annotate("", xy = (-bar, 0), xytext = (bar, 0), xycoords = "data", arrowprops = dict(arrowstyle = "-", connectionstyle = "arc3")) self.original_ax.annotate("", xy = (0, -bar), xytext = (0, bar), xycoords = "data", arrowprops = dict(arrowstyle = "-", connectionstyle = "arc3")) self.rotated_ax.annotate("", xy = (-bar, 0), xytext = (bar, 0), xycoords = "data", arrowprops = dict(arrowstyle = "-", connectionstyle = "arc3")) self.rotated_ax.annotate("", xy = (0, -bar), xytext = (0, bar), xycoords = "data", arrowprops = dict(arrowstyle = "-", connectionstyle = "arc3")) raxis_dipdir = self.spinbutton_rotation_dipdir.get_value() raxis_dip = self.spinbutton_rotation_dip.get_value() raxis = [raxis_dipdir, raxis_dip] raxis_angle = self.spinbutton_rotation_angle.get_value() for lyr_obj in self.data: lyr_type = lyr_obj.get_layer_type() lyr_store = lyr_obj.get_data_treestore() if lyr_type == "plane": dipdir_org, dips_org, dipdir_lst, dips_lst, strat, dipdir_az = \ self.parse_plane(lyr_store, raxis, raxis_angle) self.original_ax.plane(dipdir_org, dips_org, color=lyr_obj.get_line_color(), linewidth=lyr_obj.get_line_width(), linestyle=lyr_obj.get_line_style(), dash_capstyle=lyr_obj.get_capstyle(), alpha=lyr_obj.get_line_alpha(), clip_on=False) self.rotated_ax.plane(dipdir_lst, dips_lst, color=lyr_obj.get_line_color(), linewidth=lyr_obj.get_line_width(), linestyle=lyr_obj.get_line_style(), dash_capstyle=lyr_obj.get_capstyle(), alpha=lyr_obj.get_line_alpha(), clip_on=False) elif lyr_type == "line": ldipdir_org, ldips_org, ldipdir_lst, ldips_lst, sense = \ self.parse_line(lyr_store, raxis, raxis_angle) self.original_ax.line(ldips_org, ldipdir_org, marker=lyr_obj.get_marker_style(), markersize=lyr_obj.get_marker_size(), color=lyr_obj.get_marker_fill(), markeredgewidth=lyr_obj.get_marker_edge_width(), markeredgecolor=lyr_obj.get_marker_edge_color(), alpha=lyr_obj.get_marker_alpha(), clip_on=False) self.rotated_ax.line(ldips_lst, ldipdir_lst, marker=lyr_obj.get_marker_style(), markersize=lyr_obj.get_marker_size(), color=lyr_obj.get_marker_fill(), markeredgewidth=lyr_obj.get_marker_edge_width(), markeredgecolor=lyr_obj.get_marker_edge_color(), alpha=lyr_obj.get_marker_alpha(), clip_on=False) elif lyr_type == "smallcircle": ldipdir_org, ldips_org, ldipdir_lst, ldips_lst, angle = \ self.parse_line(lyr_store, raxis, raxis_angle) self.original_ax.cone(ldips_org, ldipdir_org, angle, facecolor="None", color=lyr_obj.get_line_color(), linewidth=lyr_obj.get_line_width(), label=lyr_obj.get_label(), linestyle=lyr_obj.get_line_style()) self.rotated_ax.cone(ldips_lst, ldipdir_lst, angle, facecolor="None", color=lyr_obj.get_line_color(), linewidth=lyr_obj.get_line_width(), label=lyr_obj.get_label(), linestyle=lyr_obj.get_line_style()) elif lyr_type == "faultplane": rtrn = self.parse_faultplane(lyr_store, raxis, raxis_angle) dipdir_org, dips_org, dipdir_lst, dips_lst, ldipdir_org, \ ldips_org, ldipdir_lst, ldips_lst, sense = rtrn[0], rtrn[1], \ rtrn[2], rtrn[3], rtrn[4], rtrn[5], rtrn[6], rtrn[7], rtrn[8] self.original_ax.plane(dipdir_org, dips_org, color=lyr_obj.get_line_color(), linewidth=lyr_obj.get_line_width(), linestyle=lyr_obj.get_line_style(), dash_capstyle=lyr_obj.get_capstyle(), alpha=lyr_obj.get_line_alpha(), clip_on=False) self.rotated_ax.plane(dipdir_lst, dips_lst, color=lyr_obj.get_line_color(), linewidth=lyr_obj.get_line_width(), linestyle=lyr_obj.get_line_style(), dash_capstyle=lyr_obj.get_capstyle(), alpha=lyr_obj.get_line_alpha(), clip_on=False) self.original_ax.line(ldips_org, ldipdir_org, marker=lyr_obj.get_marker_style(), markersize=lyr_obj.get_marker_size(), color=lyr_obj.get_marker_fill(), markeredgewidth=lyr_obj.get_marker_edge_width(), markeredgecolor=lyr_obj.get_marker_edge_color(), alpha=lyr_obj.get_marker_alpha(), clip_on=False) self.rotated_ax.line(ldips_lst, ldipdir_lst, marker=lyr_obj.get_marker_style(), markersize=lyr_obj.get_marker_size(), color=lyr_obj.get_marker_fill(), markeredgewidth=lyr_obj.get_marker_edge_width(), markeredgecolor=lyr_obj.get_marker_edge_color(), alpha=lyr_obj.get_marker_alpha(), clip_on=False) #Plot rotation axis self.original_ax.line(raxis_dip, raxis_dipdir, marker="o", markersize=10, color="#ff0000", markeredgewidth=1, markeredgecolor="#000000", alpha=1, clip_on=False) self.canvas.draw()
gpl-2.0
MG-RAST/kmerspectrumanalyzer
pfge_analysis/PFGE_analysis.py
2
12407
#!/usr/bin/env python2.7 import os import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import spline # from http://www.lfd.uci.edu/~gohlke/ try: import tifffile except ImportError: print ''' The Tifffile module by Christoph Gohlke is required for gel image analysis. Download from http://www.lfd.uci.edu/~gohlke/, save in src/ (same folder as this script) and try again (but save the rendered contents of the html file tifffile.py.html as tifffile.py). Warnings about additional modules can be ignored after Tifffile installation. ''' import sys sys.exit() def getLanes(imagefile,lanes,top,bottom): '''Load pixel data summed by pixel rows down length of specified region corresponding to a gel lane''' tif = tifffile.TiffFile(imagefile) image = tif.asarray() lanes1d = [] for l in lanes: lanes1d += [np.sum(image[top:bottom,l[0]:l[1]],axis=1)] return(lanes1d) def getPerLaneLadder(ladder1x,ladder1peaks,ladder2x,ladder2peaks,samplelanes,sampleoffsets): '''Linearly interpolate between corresponding bands in ladders on either side of samples for "per lane ladders"''' ldiff = ladder2x - ladder1x # take min peaks counting from small to big nladderpeaks = min(len(ladder1peaks),len(ladder2peaks)) ladder1peaks = ladder1peaks[-nladderpeaks:] ladder2peaks = ladder2peaks[-nladderpeaks:] ladderbylanes = [] for n1,l in enumerate(samplelanes): thesepeaks = [] soffset = sampleoffsets[n1] - ladder1x for p in range(nladderpeaks): peakdiff = ladder1peaks[p]-ladder2peaks[p] thesepeaks += [ladder1peaks[p]-peakdiff*(soffset/float(ldiff))] ladderbylanes += [np.array(thesepeaks)] return(ladderbylanes) def Quantify(ladderbylanes,laddersizes,allpeaks,samplenames,doplot,outfolder=None,prefix=None,desired_range=False,gelimagefile=None): '''Interpolate ladder sizes versus migration distance with second order splines and quantify samples''' sizes = {} for n,ladder_peak_dists in enumerate(ladderbylanes): sizes[samplenames[n]] = [] # interpolate and smooth between ladder peaks (which may not be linear or log-linear etc) interpolated_lsizes = np.linspace(laddersizes.min(),laddersizes.max(),1000) smoothed_lpeaks_dists = spline(laddersizes[::-1],ladder_peak_dists[::-1],interpolated_lsizes[::-1],order=2)[::-1] if doplot: fig = plt.figure(figsize=(12, 9)) axes = fig.add_subplot(111) axes.plot(interpolated_lsizes,smoothed_lpeaks_dists,'-r',lw=0.7) axes.plot(laddersizes,ladder_peak_dists,'og') axes.set_xlabel('Fragment size (bp)') axes.set_ylabel('Band migration (pixels)') if desired_range: drange = 'Desired range: %s bp, s'%desired_range else: drange = 'S' #axes.set_title('Band fragment sizes by interpolation of ladder migration distances\n%sample lane %s, %s' % (drange,n+1,samplenames[n])) plt.title('Band fragment sizes by interpolation of ladder migration distances\n%sample lane %s, %s, %s' % (drange,n+1,samplenames[n],gelimagefile)) for b,band in enumerate(ladder_peak_dists): axes.annotate('%s bp' % laddersizes[b], xy=(laddersizes[b],band), xytext=(laddersizes[b]+5000,band), arrowprops=None) # find where sample peaks intersect ladder spline and get corresponding DNA fragment size xmin,xmax = axes.get_xlim() ymin,ymax = axes.get_ylim() for peak in allpeaks[n+1]: s = [i for i,a in enumerate(smoothed_lpeaks_dists[1:]) if a < peak and smoothed_lpeaks_dists[i-1] >= peak][0] sizes[samplenames[n]] += [int(round(interpolated_lsizes[s]))] if doplot: axes.axvline(x=interpolated_lsizes[s],ymax=(peak-ymin)/(ymax-ymin),color = 'purple',lw=1) axes.axhline(y=peak,xmax=(interpolated_lsizes[s]-xmin)/(xmax-xmin),color = 'purple',lw=1) if doplot: axes.annotate('%s' % '\n'.join(['Quantification:']+[str(s)+' bp' for s in sorted(sizes[samplenames[n]])]), xy=((xmax-xmin)*0.6+xmin,(ymax-ymin)*0.8+ymin), xytext=((xmax-xmin)*0.6+xmin,(ymax-ymin)*0.8+ymin), arrowprops=None) plt.savefig(outfolder+os.sep+prefix+'quantification_sample_lane_%s_%s%ssvg' % (n+1,samplenames[n],os.extsep), format='svg') return(sizes) def AnalyseGel(gelimagefile,samplenames,lane_x_ranges,top,bottom,allpeaks,laddersizes,outfolder,prefix,doplot,desired_range): # get lane data from image file lanes1d = getLanes(gelimagefile,lane_x_ranges,top,bottom) if not os.path.exists(outfolder): os.mkdir(outfolder) if doplot: fig = plt.figure(figsize=(12, 9)) # plot ladder peak intensities axes = fig.add_subplot(111) axes.plot(lanes1d[0]) axes.set_xlabel('Distance along lane (pixels)') axes.set_ylabel('Pixel row intensity') plt.title('Lane intensities summed across pixel rows versus distance along ladder lane 1\n%s' % gelimagefile) [axes.axvline(x=a,color = 'red') for a in allpeaks[0]] plt.savefig(outfolder+os.sep+prefix+os.extsep.join(['ladder1','svg']), format='svg') axes.clear() axes.plot(lanes1d[-1]) axes.set_xlabel('Distance along lane (pixels)') axes.set_ylabel('Pixel row intensity') plt.title('Lane intensities summed across pixel rows versus distance along ladder lane 2\n%s' % gelimagefile) [axes.axvline(x=a,color = 'red') for a in allpeaks[-1]] plt.savefig(outfolder+os.sep+prefix+os.extsep.join(['ladder2','svg']), format='svg') # plot samples for n,lane in enumerate(lanes1d[1:-1]): plt.cla() axes.plot(lane) axes.set_xlabel('Distance along lane (pixels)') axes.set_ylabel('Pixel row intensity') plt.title('Lane intensities summed across pixel rows versus distance along\nsample lane %s, %s, %s' % (n+1,samplenames[n],gelimagefile)) [axes.axvline(x=a,color = 'red') for a in allpeaks[n+1]] plt.savefig(outfolder+os.sep+prefix+'intensities_sample_lane_%s_%s.svg' % ((n+1),samplenames[n]), format='svg') # linear regress between ladder bands to create per lane ladders ladder1x = sum(lane_x_ranges[0])/2 ladder2x = sum(lane_x_ranges[-1])/2 ladder1peaks = allpeaks[0] ladder2peaks = allpeaks[-1] samplepeaks = [np.array(a) for a in allpeaks[1:-1]] sampleoffsets = [sum(n)/2 for n in lane_x_ranges[1:-1]] ladderbylanes = getPerLaneLadder(ladder1x,ladder1peaks,ladder2x,ladder2peaks,samplepeaks,sampleoffsets) # interpolate with a smoothed spline sizes = Quantify(ladderbylanes,laddersizes,allpeaks,samplenames,doplot,outfolder,prefix,desired_range,gelimagefile) # print sizes for sample,thesesizes in sizes.items(): print 'Sample %s: %s' % (sample,', '.join([str(s) for s in sorted(thesesizes)])) return(sizes) # low range ladder # https://www.neb.com/products/n0350-low-range-pfg-marker lowrangeladder = [23100,9420,6550,4360,2320,2030] # includes lambda ladder # lambda ladder: # http://www.neb.com/nebecomm/products/productn0340.asp lambdaladder = [1018500,970000,921500,873000,824500,776000,727500, 679000, 630500, 582000, 533500, 485000, 436500, 388000, 339500, 291000, 242500, 194000, 145500, 97000, 48500] # H. wingei chromosomes ladder: # http://www.bio-rad.com/prd/en/US/adirect/biorad?cmd=catProductDetail&vertical=LSR&country=US&lang=en&productID=170-3667 Hwingeiladder = [3130000,2700000,2350000,1810000,1660000,1370000,1050000] doplot = True samples = ['E_1_37','A_3_34','C_4_22','D_4_27','B_4_28','K12'] outfolder = os.sep.join([os.pardir,'image','analysis']) sizes = {} def main(): ## Small fragment ICeuI PFGE gel desired_range = '< 145,500' gelimagefile = os.sep.join([os.pardir,'image','gels',os.extsep.join(['ICeuI_small','tif'])]) laddersizes = np.array(lambdaladder[-4:]+lowrangeladder[:1]) ## samples in left lanes samplenames = samples[:3] # x pixel ranges of lanes lane_x_ranges = ((176,274),(334,434),(494,584),(642,726),(798,904)) # upper and lower pixels (top,bottom) = (10,1128) # band peak intensity distance down gel image -top allpeaks = [np.array([ 25, 237, 549, 856, 1030]), np.array([286, 415, 930]), np.array([280, 428, 912]), np.array([399, 512, 909]), np.array([ 33, 243, 554, 862, 1032])] prefix = 'ICeuI_small_123_' print('\nAnalysing %s, plotting to %s%s%s*.svg\n' % (gelimagefile,outfolder,os.sep,prefix)) sizes[prefix] = AnalyseGel(gelimagefile,samplenames,lane_x_ranges,top,bottom,allpeaks,laddersizes,outfolder,prefix,doplot,desired_range) ## samples in right lanes samplenames = samples[3:] # x pixel ranges of lanes lane_x_ranges = ((798,904),(962,1082),(1114,1224),(1264,1368),(1422,1530)) # band peak intensity distance down gel image -top allpeaks = [np.array([ 33, 243, 554, 862, 1032]), np.array([ 76, 408, 914]), np.array([304, 575, 913]), np.array([331, 588, 927]), np.array([ 36, 255, 568, 879, 1053])] prefix = 'ICeuI_small_456_' print('\nAnalysing %s, plotting to %s%s%s*.svg\n' % (gelimagefile,outfolder,os.sep,prefix)) sizes[prefix] = AnalyseGel(gelimagefile,samplenames,lane_x_ranges,top,bottom,allpeaks,laddersizes,outfolder,prefix,doplot,desired_range) ## Mid fragment ICeuI PFGE gel desired_range = '> 145,500 & < 1,000,000' gelimagefile = os.sep.join([os.pardir,'image','gels',os.extsep.join(['ICeuI_medium','tif'])]) laddersizes = np.array(lambdaladder[-18:-9]) samplenames = samples # x pixel ranges of lanes lane_x_ranges = ((23,63),(96,148),(173,230),(255,305),(333,389),(415,466),(493,546),(584,622)) # upper and lower pixels (top,bottom) = (0,260) # band peak intensity distance down gel image -top allpeaks = [np.array([ 8, 31, 55, 79, 106, 135, 167, 202, 240]), np.array([ 38, 90, 193]), np.array([105, 107, 210]), np.array([ 79, 108, 207]), np.array([ 32, 92, 202]), np.array([ 88, 131, 202]), np.array([ 99, 121, 212]), np.array([ 17, 39, 62, 87, 113, 143, 175, 209, 247])] prefix = 'ICeuI_medium_123456_' print('\nAnalysing %s, plotting to %s%s%s*.svg\n' % (gelimagefile,outfolder,os.sep,prefix)) sizes[prefix] = AnalyseGel(gelimagefile,samplenames,lane_x_ranges,top,bottom,allpeaks,laddersizes,outfolder,prefix,doplot,desired_range) ## Large fragment ICeuI PFGE gel desired_range = '> 2,000,000' gelimagefile = os.sep.join([os.pardir,'image','gels',os.extsep.join(['ICeuI_large','tif'])]) laddersizes = np.array(Hwingeiladder[:3]) # upper and lower pixels (top,bottom) = (130,482) ## sample in left lane samplenames = samples[:1] lane_x_ranges = ((162,204),(316,386),(472,514)) # band peak intensity distance down gel image -top allpeaks = [np.array([ 84, 165, 263]), np.array([119]), np.array([ 87, 158, 254])] prefix = 'ICeuI_large_1_' print('\nAnalysing %s, plotting to %s%s%s*.svg\n' % (gelimagefile,outfolder,os.sep,prefix)) sizes[prefix] = AnalyseGel(gelimagefile,samplenames,lane_x_ranges,top,bottom,allpeaks,laddersizes,outfolder,prefix,doplot,desired_range) ## samples in middle lane samplenames = samples[1:3] lane_x_ranges = ((472,514),(598,660),(728,802),(878,922)) # band peak intensity distance down gel image -top allpeaks = [np.array([ 87, 158, 248]), np.array([163]), np.array([116]), np.array([ 90, 163, 251])] prefix = 'ICeuI_large_23_' print('\nAnalysing %s, plotting to %s%s%s*.svg\n' % (gelimagefile,outfolder,os.sep,prefix)) sizes[prefix] = AnalyseGel(gelimagefile,samplenames,lane_x_ranges,top,bottom,allpeaks,laddersizes,outfolder,prefix,doplot,desired_range) ## samples in right lanes samplenames = samples[3:] lane_x_ranges = ((878,922),(1020,1076),(1160,1220),(1292,1362),(1436,1508)) # band peak intensity distance down gel image -top allpeaks = [np.array([ 90, 163, 251]), np.array([107]), np.array([130]), np.array([145]), np.array([83, 166, 256])] prefix = 'ICeuI_large_456_' print('\nAnalysing %s, plotting to %s%s%s*.svg\n' % (gelimagefile,outfolder,os.sep,prefix)) sizes[prefix] = AnalyseGel(gelimagefile,samplenames,lane_x_ranges,top,bottom,allpeaks,laddersizes,outfolder,prefix,doplot,desired_range) allsizes = {} for sz in sizes.values(): for sm in samples: if sm in sz: if sm in allsizes: allsizes[sm] += sz[sm] else: allsizes[sm] = sz[sm] print('\n') for sm,szs in sorted(allsizes.items()): print('%s: %s' % (sm,sum(szs))) print('\nSee ../image/analysis/ for analysis plots\n') if __name__ == '__main__': main()
bsd-2-clause
simudream/dask
dask/array/tests/test_percentiles.py
8
1486
import pytest pytest.importorskip('numpy') from dask.utils import skip import dask.array as da from dask.array.percentile import _percentile import dask import numpy as np def eq(a, b): if isinstance(a, da.Array): a = a.compute(get=dask.get) if isinstance(b, da.Array): b = b.compute(get=dask.get) c = a == b if isinstance(c, np.ndarray): c = c.all() return c def test_percentile(): d = da.ones((16,), chunks=(4,)) assert eq(da.percentile(d, [0, 50, 100]), [1, 1, 1]) x = np.array([0, 0, 5, 5, 5, 5, 20, 20]) d = da.from_array(x, chunks=(3,)) assert eq(da.percentile(d, [0, 50, 100]), [0, 5, 20]) x = np.array(['a', 'a', 'd', 'd', 'd', 'e']) d = da.from_array(x, chunks=(3,)) assert eq(da.percentile(d, [0, 50, 100]), ['a', 'd', 'e']) @skip def test_percentile_with_categoricals(): try: import pandas as pd except ImportError: return x0 = pd.Categorical(['Alice', 'Bob', 'Charlie', 'Dennis', 'Alice', 'Alice']) x1 = pd.Categorical(['Alice', 'Bob', 'Charlie', 'Dennis', 'Alice', 'Alice']) dsk = {('x', 0): x0, ('x', 1): x1} x = da.Array(dsk, 'x', chunks=((6, 6),)) p = da.percentile(x, [50]) assert (p.compute().categories == x0.categories).all() assert (p.compute().codes == [0]).all() def test_percentiles_with_empty_arrays(): x = da.ones(10, chunks=((5, 0, 5),)) assert da.percentile(x, [10, 50, 90]).compute().tolist() == [1, 1, 1]
bsd-3-clause
JamesSample/nirams_ii
Code/niramsii/nirams.py
1
18049
#------------------------------------------------------------------------------- # Name: nirams.py # Purpose: The main script for NIRAMS II. # # Author: James Sample # # Created: 18/01/2012 # Copyright: (c) James Sample and JHI, 2012 # Licence: <your licence> #------------------------------------------------------------------------------- """ This is the main or parent script for NIRAMS II. """ def run_model(param_xls, run_type): """ Run the NIRAMS II model wtht he specified parameters and options. Args: param_xls: Path to complete Excel template for model setup. run_type: The name of the worksheet to read data from in 'param_xls'. Either 'single_run' for a single model run with the specified parameter set or 'param_combos' for multiple model runs. """ import time, input_output as io st_time = time.time() # Check run_type is valid assert run_type in ('single_run', 'param_combos'), ( "The run_type must be either 'single_run' or 'param_combos'.\n" "Please check and try again.") # Read user input from specified sheet user_dict = io.read_user_input(param_xls, run_type) # Determine which version of NIRAMS to run if run_type == 'single_run': print 'Running NIRAMS II for a single parameter set...' # Run single model single_niramsii_run(user_dict) else: # run_type = 'param_combos' import multiprocessing as mp, pandas as pd, os, shutil import input_output as io print 'Running NIRAMS II for multiple parameter sets...' # Create temp folder for intermediate output temp_path = os.path.split(user_dict['Output HDF5 path'])[0] temp_fold = os.path.join(temp_path, 'temp') os.makedirs(temp_fold) # Calculate parameter combinations based on user input param_combos = calculate_combinations(user_dict) # Write param combos to CSV df = pd.DataFrame(data=param_combos) df.index = df['Run ID'] del df['Run ID'] # Re-order columns col_order = ['Number of processors', 'Input HDF5 path', 'Parameter CSV', 'Output HDF5 path', 'Write GeoTiffs', 'Output GeoTiff folder', 'Start year', 'End year', 'xmin', 'xmax', 'ymin', 'ymax', 'Default PET to AET grid', 'Use IACS', 'T_snow', 'T_melt', 'Degree-day factor', 'Organic N factor', 'Mineralisation parameter', 'Denitrification parameter', 'N leaching parameter'] df[col_order].to_csv(user_dict['Parameter CSV'][0], index_label='Run ID') # Add the temp folder to each param_dict for idx, param_dict in enumerate(param_combos): param_dict['Output HDF5 folder'] = temp_fold # Setup multiprocessing pool pool = mp.Pool(user_dict['Number of processors'][0]) # Distribute runs to processors pool.map(single_niramsii_run, param_combos) pool.close() # Merge outputs from each run to single HDF5 io.merge_hdf5(temp_fold, user_dict['Output HDF5 path'][0]) # Remove temp folder shutil.rmtree(temp_fold) end_time = time.time() print 'Finished. Processing time: %.2f minutes.' % ((end_time-st_time)/60) def single_niramsii_run(params_dict): """ Run the NIRAMS II model with the specified parameters. Args: params_dict: Dict containing all model parameters and user-specified options. Returns: None. Model outptus are written to the specified HDF5 file (and GeoTiffs if specified). """ import input_output as io, snow as sn, drainage as dr import nitrate as ni, calendar, numpy.ma as ma, os # Paths to static nodes in the input HDF5 file nodes_dict = {'land_props' : r'/one_km_grids/old_land_properties/', 'soil_props' : r'/one_km_grids/soil_properties/', 'met_data' : r'/five_km_grids/meteorological_data/', 'iacs_pet' : r'/one_km_grids/iacs_pet_facts/', 'or' : r'/one_km_grids/organic_n/', 'in' : r'/one_km_grids/inorganic_n/', 'up' : r'/one_km_grids/n_uptake/', 'n_dep' : r'/one_km_grids/n_deposition/', 'time_series': r'/time_series/'} # Create output HDF5 file io.create_output_h5(params_dict) # Dicts storing number of days in each month (one for leap years; one for # non-leap years) days_in_month_dict = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31} days_in_month_lpyr_dict = {1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31} # Extract the grid indices for the bounding box into a dict indices_dict = io.get_grid_indices( params_dict['xmin'], params_dict['xmax'], params_dict['ymin'], params_dict['ymax']) # Extract the static grids from the HDF5 file fc, sat, calibl, calibv = io.read_static_grids( params_dict['Input HDF5 path'], nodes_dict['soil_props'], ['fc', 'sat', 'calibl', 'calibv'], indices_dict) # Extract the PET to AET correction factor grid from the HDF5 file default_pet_fact = io.read_static_grids( params_dict['Input HDF5 path'], nodes_dict['land_props'], [params_dict['Default PET to AET grid'],], indices_dict)[0] # Set an initial water level halfway between field and saturation capacity wat_lev = (fc + sat)/2 # Set an initial snow pack of zero rows = (params_dict['ymax']-params_dict['ymin'])/1000 cols = (params_dict['xmax']-params_dict['xmin'])/1000 snow_pk = ma.zeros((rows,cols)) # Set the initial amount of available N using a simple annual balance for # 2001 # Get the annual N grids for 2001 in a dict n_bud_dict = io.read_annual_n_grids(params_dict['Input HDF5 path'], nodes_dict, 2001, indices_dict) avail_n = ni.initial_n_budget(n_bud_dict, params_dict['Organic N factor']) # Begin looping over time series data for year in range(params_dict['Start year'], params_dict['End year']+1): # Choose PET to AET conversion grids based on user input if (params_dict['Use IACS'] == True) and (year in range(2001, 2011)): # Get the iacs_pet_fact grid for this year pet_fact = io.read_static_grids(params_dict['Input HDF5 path'], nodes_dict['iacs_pet'], ['pet_fact_%s' % year,], indices_dict)[0] else: # Use the default pet_fact grid pet_fact = default_pet_fact # Read the annual N grids annual_n_dict = io.read_annual_n_grids(params_dict['Input HDF5 path'], nodes_dict, year, indices_dict) # Calculate daily n_dep rate for this year if calendar.isleap(year) == True: daily_n_dep = annual_n_dict['n_dep'] / 366. else: daily_n_dep = annual_n_dict['n_dep'] / 365. # Keep track of annual totals an_n_leach = ma.zeros((rows,cols)) an_ssf = ma.zeros((rows,cols)) an_gwf = ma.zeros((rows,cols)) an_of = ma.zeros((rows,cols)) # Loop over months for month in range(1,13): # Allow for leap years if calendar.isleap(year) == True: days_in_month = days_in_month_lpyr_dict[month] else: days_in_month = days_in_month_dict[month] # Loop over days for day in range(1, days_in_month+1): # Get today's met data from the HDF5 file pptn, t_min, t_max, pet = io.read_met_data( params_dict['Input HDF5 path'], nodes_dict['met_data'], indices_dict, year, month, day, days_in_month) # Convert PET to AET using pet_fact aet = pet_fact*pet # Where the ground is already covered in snow, set AET to zero aet[snow_pk>0] = 0 # Reduce the AET if the soil is dry i.e. if wat_lev < 0.7*fc aet = dr.reduce_aet_if_dry(aet, wat_lev, fc) # Split today's pptn into rain and snow components rain, snow = sn.estimate_snow_and_rain(pptn, t_min, t_max, params_dict['T_snow']) # Calculate today's snow melt melt = sn.estimate_snow_melt(snow_pk, t_min, t_max, params_dict['T_melt'], params_dict['Degree-day factor']) # Estimate temp and moisture factors t_fact = ni.est_temp_factor(t_min, t_max) moist_fact = ni.est_moisture_fact(wat_lev, fc) # Calculate today's mineralisation n_mineral = ni.est_mineralisation( params_dict['Mineralisation parameter'], t_fact, moist_fact) # Calculate today's denitrification n_denit = ni.est_denitrification( params_dict['Denitrification parameter'], wat_lev, t_fact, moist_fact, avail_n) # Estimate amount of N added today ts_row = io.read_ts_table(params_dict['Input HDF5 path'], nodes_dict['time_series'], day, month) n_added = ni.estimate_n_added(annual_n_dict, daily_n_dep, params_dict['Organic N factor'], n_mineral, n_denit, ts_row) # Calculate today's drainage grids dr_list = dr.estimate_drainage(fc, sat, calibl, calibv, wat_lev, snow_pk, rain, snow, melt, aet) snow_pk, wat_lev, surf_ro, lat_dr, vert_dr, tot_dr = dr_list # Calculate today's N leaching n_leach_list = ni.calculate_n_leaching( avail_n, n_added, dr_list, fc, params_dict['N leaching parameter']) leached_n, avail_n = n_leach_list # Increment annual totals an_n_leach += leached_n an_gwf += vert_dr an_ssf += lat_dr an_of += surf_ro # Calculate yearly drainage an_drain = an_ssf+an_gwf+an_of an_ss_drain = an_ssf+an_gwf # Get path to output HDF5 hdf5_fold = params_dict['Output HDF5 folder'] run_id = params_dict['Run ID'] out_hdf5 = os.path.join(hdf5_fold, 'run_%03d.h5' % run_id) # Write to output file # Total drainage io.write_array_to_h5(out_hdf5, '/run_%03d' % run_id, 'total_drainage_%s' % year, an_drain, units='mm', xmin=params_dict['xmin'], xmax=params_dict['xmax'], ymin=params_dict['ymin'], ymax=params_dict['ymax']) # Sub-surface drainage io.write_array_to_h5(out_hdf5, '/run_%03d' % run_id, 'sub-surface_drainage_%s' % year, an_ss_drain, units='mm', xmin=params_dict['xmin'], xmax=params_dict['xmax'], ymin=params_dict['ymin'], ymax=params_dict['ymax']) # N leached io.write_array_to_h5(out_hdf5, '/run_%03d' % run_id, 'n_leached_%s' % year, an_n_leach, units='mm', xmin=params_dict['xmin'], xmax=params_dict['xmax'], ymin=params_dict['ymin'], ymax=params_dict['ymax']) # Write to GTiff if params_dict['Write GeoTiffs'] == True: # Total drainage tot_dr_path = os.path.join(params_dict['Output GeoTiff folder'], 'run_%03d_total_drainage_%s.tif' % (run_id, year)) io.ma_to_gtiff(params_dict['xmin'], params_dict['ymax'], 1000, tot_dr_path, an_drain) # Sub-surface drainage ss_dr_path = os.path.join(params_dict['Output GeoTiff folder'], 'run_%03d_sub-surface_drainage_%s.tif' % (run_id, year)) io.ma_to_gtiff(params_dict['xmin'], params_dict['ymax'], 1000, ss_dr_path, an_ss_drain) # N leached n_leach_path = os.path.join(params_dict['Output GeoTiff folder'], 'run_%03d_n_leached_%s.tif' % (run_id, year)) io.ma_to_gtiff(params_dict['xmin'], params_dict['ymax'], 1000, n_leach_path, an_n_leach) def calculate_combinations(user_dict): """ Read user inut from 'param_combos' sheet in input Excel file and calculate all combnations of the parameters entered. Args: user_dict: Dict of user-defined input from the 'param_combos' sheet in the input Excel template. Returns: List of dicts, where each dict is a valid input for single_niramsii_run() """ import itertools as it # List of params for which multiple parameter values can be entered phys_params = ['T_snow', 'T_melt', 'Degree-day factor', 'Organic N factor', 'Mineralisation parameter', 'Denitrification parameter', 'N leaching parameter'] # To work with itertools, all dict elements must be in lists. Also need to # Parse any comma separated lists entered for physical params for key in user_dict.keys(): if key in phys_params: if isinstance(user_dict[key], (float, int)): # User has just entered a single value user_dict[key] = [user_dict[key],] else: # User has entered a comma-separated list user_dict[key] = [float(i) for i in user_dict[key].split(',')] else: # Just add the param directly to a list user_dict[key] = [user_dict[key],] # Generate combinations. See # http://stackoverflow.com/questions/3873654/combinations-from-dictionary-with-list-values-using-python # for details param_dicts = sorted(user_dict) param_combos = [dict(zip(param_dicts, prod)) for prod in it.product(*(user_dict[param_dict] for param_dict in param_dicts))] # Check n_runs < 1000 (because my file naming is padded to 3 digits, so # more than 999 runs won't work. Could be easily extended if necessary) assert len(param_combos) < 1000, ('The maximum numbers of runs for this ' 'code is 999.') # Assign unique run IDs from 1 to n for n param combos for idx, param_dict in enumerate(param_combos): param_dict['Run ID'] = idx + 1 return param_combos
mit
Anderson-Lab/anderson-lab.github.io
csc_466_2021_spring/MLCode/Ch16/Kalman_full.py
3
5085
# Code from Chapter 16 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by Stephen Marsland (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no warranty of any kind. # Stephen Marsland, 2008, 2014 import numpy as np import pylab as pl def Kalman_update(A,H,Q,R,y,x,Sig,B=None,u=None): if B is None: xpred = np.dot(A,x) else: xpred = np.dot(A,x) + np.dot(B,u) SigPred = np.dot(A,np.dot(Sig,A.T)) + Q e = y - np.dot(H,xpred) Sinv = np.linalg.inv(np.dot(H,np.dot(SigPred,H.T)) + R) K = np.dot(SigPred,np.dot(H.T,Sinv)) xnew = xpred + np.dot(K,e) SigNew = np.dot((np.eye(np.shape(A)[0]) - np.dot(K,H)),SigPred) return xnew.T,SigNew def Kalman_smoother_update(A,Q,B,u,xs_t,Sigs_t,xfilt,Sigfilt,Sigfilt_t): if B is None: xpred = np.dot(A,xfilt) else: xpred = np.dot(A,xfilt) + np.dot(B,u) SigPred = np.dot(A,np.dot(Sigfilt,A.T)) + Q J = np.dot(Sigfilt,np.dot(A.T,np.linalg.inv(SigPred))) xs = xfilt + np.dot(J,(xs_t - xpred)) Sigs = Sigfilt + np.dot(J,np.dot((Sigs_t - SigPred),J.T)) return xs.T, Sigs def Kalman_filter(y,A,H,Q,R,x0,Sig0,B=None,u=None): obs_size,T = np.shape(y) state_size = np.shape(A)[0] x = np.zeros((state_size,T)) Sig = np.zeros((state_size,state_size,T)) [x[:,0],Sig[:,:,0]] = Kalman_update(A,H,Q,R,y[:,0].reshape(len(y),1),x0,Sig0,B,u) for t in range(1,T): prevx = x[:,t-1].reshape(state_size,1) prevSig = Sig[:,:,t-1] [x[:,t],Sig[:,:,t]] = Kalman_update(A,H,Q,R,y[:,t].reshape(len(y),1),prevx,prevSig,B,u) return x,Sig def Kalman_smoother(y,A,H,Q,R,x0,Sig0,B=None,u=None): obs_size,T = np.shape(y) state_size = np.shape(A)[0] xs = np.zeros((state_size,T)) Sigs = np.zeros((state_size,state_size,T)) [xfilt,Sigfilt] = Kalman_filter(y,A,H,Q,R,x0,Sig0,B,u) xs[:,T-1] = xfilt[:,T-1] Sigs[:,:,T-1] = Sigfilt[:,:,T-1] for t in range(T-2,-1,-1): [xs[:,t],Sigs[:,:,t]] = Kalman_smoother_update(A,Q,B,u,xs[:,t+1].reshape(len(xs),1),Sigs[:,:,t+1],xfilt[:,t].reshape(len(xfilt),1),Sigfilt[:,:,t],Sigfilt[:,:,t+1]) return xs,Sigs def lds_sample(A,H,Q,R,state0,T): # x(t+1) = Ax(t) + state_noise(t), state_noise ~ N(O,Q), x(0) = state0 # y(t) = Hx(t) + obs_noise(t), obs_noise~N(O,R) state_noise_samples = np.random.multivariate_normal(np.zeros((len(Q))),Q,T).T obs_noise_samples = np.random.multivariate_normal(np.zeros((len(R))),R,T).T x = np.zeros((np.shape(H)[1],T)) y = np.zeros((np.shape(H)[0],T)) x[:,0] = state0.T y[:,0] = np.dot(H,x[:,0]) + obs_noise_samples[:,0] for t in range(1,T): x[:,t] = np.dot(A,x[:,t-1]) + state_noise_samples[:,t] y[:,t] = np.dot(H,x[:,t-1]) + obs_noise_samples[:,t] return [x,y] def Kalman_demo(): state_size = 4 observation_size = 2 A = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],dtype=float) H = np.array([[1,0,0,0],[0,1,0,0]],dtype=float) Q = 0.1*np.eye((state_size)) R = np.eye(observation_size,dtype=float) x0 = np.array([[10],[10],[1],[0]],dtype=float) Sig0 = 10. * np.eye(state_size) np.random.seed(3) T = 15 [x,y] = lds_sample(A,H,Q,R,x0,T) [xfilt,Sigfilt] = Kalman_filter(y,A,H,Q,R,x0,Sig0) [xsmooth,Sigsmooth] = Kalman_smoother(y,A,H,Q,R,x0,Sig0) dfilt = x[[0,1],:] - xfilt[[0,1],:] mse_filt = np.sqrt(np.sum(dfilt**2)) dsmooth = x[[0,1],:] - xsmooth[[0,1],:] mse_smooth = np.sqrt(np.sum(dsmooth**2)) plot_track(x,y,xfilt,Sigfilt) plot_track(x,y,xsmooth,Sigsmooth) def plot_track(x,y,Kx,Sig): fig = pl.figure() ax = fig.add_subplot(111, aspect='equal') pl.plot(x[0,:],x[1,:],'ks-') pl.plot(y[0,:],y[1,:],'k*') pl.plot(Kx[0,:],Kx[1,:],'kx:') pl.legend(('True','Observed','Filtered')) obs_size,T = np.shape(y) from matplotlib.patches import Ellipse # Axes of ellipse are eigenvectors of covariance matrix, lengths are square roots of eigenvalues ellsize = np.zeros((obs_size,T)) ellangle = np.zeros((T)) for t in range(T): [evals,evecs] = np.linalg.eig(Sig[:2,:2,t]) ellsize[:,t] = np.sqrt(evals) ellangle[t] = np.angle(evecs[0,0]+0.j*evecs[0,1]) ells = [Ellipse(xy=[Kx[0,t],Kx[1,t]] ,width=ellsize[0,t],height=ellsize[1,t], angle=ellangle[t]) for t in range(T)] for e in ells: ax.add_artist(e) e.set_alpha(0.1) e.set_facecolor([0.7,0.7,0.7]) pl.xlabel('x') pl.ylabel('y') def Kalman_demo1d(): x0 = np.array([-0.37727]) Sig0 = 0.1*np.ones((1)) T = 50 y = np.random.normal(x0,Sig0,(1,T)) A = np.eye(1) H = np.eye(1) Q = np.eye(1)*1e-5 R = np.eye(1)*0.01 xfilt = np.zeros((1,T),dtype=float) Sigfilt = np.zeros((1,T),dtype=float) [xfilt,Sigfilt] = Kalman_filter(y,A,H,Q,R,x0,Sig0) xfilt = np.squeeze(xfilt) Sigfilt = np.squeeze(Sigfilt) pl.figure() time = np.arange(T) pl.plot(time,y[0,:],'ko',ms=6) pl.plot(time,xfilt,'k-',lw=3) pl.plot(time,xfilt+20*Sigfilt,'k--',lw=2) pl.plot(time,xfilt-20*Sigfilt,'k--',lw=2) pl.legend(['Noisy Datapoints','Kalman estimate','20*Covariance']) pl.xlabel('Time')
mit
deo1/deo1
KaggleKkboxChurn/preprocessor_classifier_config_dict.py
2
2606
import numpy as np classifier_config_dict = { # Preprocesssors 'sklearn.preprocessing.Binarizer': { 'threshold': np.arange(0.0, 1.01, 0.05) }, 'sklearn.decomposition.FastICA': { 'tol': np.arange(0.0, 1.01, 0.05) }, 'sklearn.cluster.FeatureAgglomeration': { 'linkage': ['ward', 'complete', 'average'], 'affinity': ['euclidean', 'l1', 'l2', 'manhattan', 'cosine', 'precomputed'] }, 'sklearn.preprocessing.MaxAbsScaler': { }, 'sklearn.preprocessing.MinMaxScaler': { }, 'sklearn.preprocessing.Normalizer': { 'norm': ['l1', 'l2', 'max'] }, 'sklearn.kernel_approximation.Nystroem': { 'kernel': ['rbf', 'cosine', 'chi2', 'laplacian', 'polynomial', 'poly', 'linear', 'additive_chi2', 'sigmoid'], 'gamma': np.arange(0.0, 1.01, 0.05), 'n_components': range(1, 11) }, 'sklearn.decomposition.PCA': { 'svd_solver': ['randomized'], 'iterated_power': range(1, 11) }, 'sklearn.preprocessing.PolynomialFeatures': { 'degree': [2], 'include_bias': [False], 'interaction_only': [False] }, 'sklearn.kernel_approximation.RBFSampler': { 'gamma': np.arange(0.0, 1.01, 0.05) }, 'sklearn.preprocessing.RobustScaler': { }, 'sklearn.preprocessing.StandardScaler': { }, 'tpot.builtins.ZeroCount': { }, # Selectors 'sklearn.feature_selection.SelectFwe': { 'alpha': np.arange(0, 0.05, 0.001), 'score_func': { 'sklearn.feature_selection.f_classif': None } }, 'sklearn.feature_selection.SelectPercentile': { 'percentile': range(1, 100), 'score_func': { 'sklearn.feature_selection.f_classif': None } }, 'sklearn.feature_selection.VarianceThreshold': { 'threshold': np.arange(0.05, 1.01, 0.05) }, 'sklearn.feature_selection.RFE': { 'step': np.arange(0.05, 1.01, 0.05), 'estimator': { 'sklearn.ensemble.ExtraTreesClassifier': { 'n_estimators': [100], 'criterion': ['gini', 'entropy'], 'max_features': np.arange(0.05, 1.01, 0.05) } } }, 'sklearn.feature_selection.SelectFromModel': { 'threshold': np.arange(0, 1.01, 0.05), 'estimator': { 'sklearn.ensemble.ExtraTreesClassifier': { 'n_estimators': [100], 'criterion': ['gini', 'entropy'], 'max_features': np.arange(0.05, 1.01, 0.05) } } } }
mit
fyffyt/scikit-learn
sklearn/datasets/twenty_newsgroups.py
126
13591
"""Caching loader for the 20 newsgroups text classification dataset The description of the dataset is available on the official website at: http://people.csail.mit.edu/jrennie/20Newsgroups/ Quoting the introduction: The 20 Newsgroups data set is a collection of approximately 20,000 newsgroup documents, partitioned (nearly) evenly across 20 different newsgroups. To the best of my knowledge, it was originally collected by Ken Lang, probably for his Newsweeder: Learning to filter netnews paper, though he does not explicitly mention this collection. The 20 newsgroups collection has become a popular data set for experiments in text applications of machine learning techniques, such as text classification and text clustering. This dataset loader will download the recommended "by date" variant of the dataset and which features a point in time split between the train and test sets. The compressed dataset size is around 14 Mb compressed. Once uncompressed the train set is 52 MB and the test set is 34 MB. The data is downloaded, extracted and cached in the '~/scikit_learn_data' folder. The `fetch_20newsgroups` function will not vectorize the data into numpy arrays but the dataset lists the filenames of the posts and their categories as target labels. The `fetch_20newsgroups_vectorized` function will in addition do a simple tf-idf vectorization step. """ # Copyright (c) 2011 Olivier Grisel <[email protected]> # License: BSD 3 clause import os import logging import tarfile import pickle import shutil import re import codecs import numpy as np import scipy.sparse as sp from .base import get_data_home from .base import Bunch from .base import load_files from ..utils import check_random_state from ..feature_extraction.text import CountVectorizer from ..preprocessing import normalize from ..externals import joblib, six if six.PY3: from urllib.request import urlopen else: from urllib2 import urlopen logger = logging.getLogger(__name__) URL = ("http://people.csail.mit.edu/jrennie/" "20Newsgroups/20news-bydate.tar.gz") ARCHIVE_NAME = "20news-bydate.tar.gz" CACHE_NAME = "20news-bydate.pkz" TRAIN_FOLDER = "20news-bydate-train" TEST_FOLDER = "20news-bydate-test" def download_20newsgroups(target_dir, cache_path): """Download the 20 newsgroups data and stored it as a zipped pickle.""" archive_path = os.path.join(target_dir, ARCHIVE_NAME) train_path = os.path.join(target_dir, TRAIN_FOLDER) test_path = os.path.join(target_dir, TEST_FOLDER) if not os.path.exists(target_dir): os.makedirs(target_dir) if os.path.exists(archive_path): # Download is not complete as the .tar.gz file is removed after # download. logger.warning("Download was incomplete, downloading again.") os.remove(archive_path) logger.warning("Downloading dataset from %s (14 MB)", URL) opener = urlopen(URL) with open(archive_path, 'wb') as f: f.write(opener.read()) logger.info("Decompressing %s", archive_path) tarfile.open(archive_path, "r:gz").extractall(path=target_dir) os.remove(archive_path) # Store a zipped pickle cache = dict(train=load_files(train_path, encoding='latin1'), test=load_files(test_path, encoding='latin1')) compressed_content = codecs.encode(pickle.dumps(cache), 'zlib_codec') with open(cache_path, 'wb') as f: f.write(compressed_content) shutil.rmtree(target_dir) return cache def strip_newsgroup_header(text): """ Given text in "news" format, strip the headers, by removing everything before the first blank line. """ _before, _blankline, after = text.partition('\n\n') return after _QUOTE_RE = re.compile(r'(writes in|writes:|wrote:|says:|said:' r'|^In article|^Quoted from|^\||^>)') def strip_newsgroup_quoting(text): """ Given text in "news" format, strip lines beginning with the quote characters > or |, plus lines that often introduce a quoted section (for example, because they contain the string 'writes:'.) """ good_lines = [line for line in text.split('\n') if not _QUOTE_RE.search(line)] return '\n'.join(good_lines) def strip_newsgroup_footer(text): """ Given text in "news" format, attempt to remove a signature block. As a rough heuristic, we assume that signatures are set apart by either a blank line or a line made of hyphens, and that it is the last such line in the file (disregarding blank lines at the end). """ lines = text.strip().split('\n') for line_num in range(len(lines) - 1, -1, -1): line = lines[line_num] if line.strip().strip('-') == '': break if line_num > 0: return '\n'.join(lines[:line_num]) else: return text def fetch_20newsgroups(data_home=None, subset='train', categories=None, shuffle=True, random_state=42, remove=(), download_if_missing=True): """Load the filenames and data from the 20 newsgroups dataset. Read more in the :ref:`User Guide <20newsgroups>`. Parameters ---------- subset: 'train' or 'test', 'all', optional Select the dataset to load: 'train' for the training set, 'test' for the test set, 'all' for both, with shuffled ordering. data_home: optional, default: None Specify a download and cache folder for the datasets. If None, all scikit-learn data is stored in '~/scikit_learn_data' subfolders. categories: None or collection of string or unicode If None (default), load all the categories. If not None, list of category names to load (other categories ignored). shuffle: bool, optional Whether or not to shuffle the data: might be important for models that make the assumption that the samples are independent and identically distributed (i.i.d.), such as stochastic gradient descent. random_state: numpy random number generator or seed integer Used to shuffle the dataset. download_if_missing: optional, True by default If False, raise an IOError if the data is not locally available instead of trying to download the data from the source site. remove: tuple May contain any subset of ('headers', 'footers', 'quotes'). Each of these are kinds of text that will be detected and removed from the newsgroup posts, preventing classifiers from overfitting on metadata. 'headers' removes newsgroup headers, 'footers' removes blocks at the ends of posts that look like signatures, and 'quotes' removes lines that appear to be quoting another post. 'headers' follows an exact standard; the other filters are not always correct. """ data_home = get_data_home(data_home=data_home) cache_path = os.path.join(data_home, CACHE_NAME) twenty_home = os.path.join(data_home, "20news_home") cache = None if os.path.exists(cache_path): try: with open(cache_path, 'rb') as f: compressed_content = f.read() uncompressed_content = codecs.decode( compressed_content, 'zlib_codec') cache = pickle.loads(uncompressed_content) except Exception as e: print(80 * '_') print('Cache loading failed') print(80 * '_') print(e) if cache is None: if download_if_missing: cache = download_20newsgroups(target_dir=twenty_home, cache_path=cache_path) else: raise IOError('20Newsgroups dataset not found') if subset in ('train', 'test'): data = cache[subset] elif subset == 'all': data_lst = list() target = list() filenames = list() for subset in ('train', 'test'): data = cache[subset] data_lst.extend(data.data) target.extend(data.target) filenames.extend(data.filenames) data.data = data_lst data.target = np.array(target) data.filenames = np.array(filenames) else: raise ValueError( "subset can only be 'train', 'test' or 'all', got '%s'" % subset) data.description = 'the 20 newsgroups by date dataset' if 'headers' in remove: data.data = [strip_newsgroup_header(text) for text in data.data] if 'footers' in remove: data.data = [strip_newsgroup_footer(text) for text in data.data] if 'quotes' in remove: data.data = [strip_newsgroup_quoting(text) for text in data.data] if categories is not None: labels = [(data.target_names.index(cat), cat) for cat in categories] # Sort the categories to have the ordering of the labels labels.sort() labels, categories = zip(*labels) mask = np.in1d(data.target, labels) data.filenames = data.filenames[mask] data.target = data.target[mask] # searchsorted to have continuous labels data.target = np.searchsorted(labels, data.target) data.target_names = list(categories) # Use an object array to shuffle: avoids memory copy data_lst = np.array(data.data, dtype=object) data_lst = data_lst[mask] data.data = data_lst.tolist() if shuffle: random_state = check_random_state(random_state) indices = np.arange(data.target.shape[0]) random_state.shuffle(indices) data.filenames = data.filenames[indices] data.target = data.target[indices] # Use an object array to shuffle: avoids memory copy data_lst = np.array(data.data, dtype=object) data_lst = data_lst[indices] data.data = data_lst.tolist() return data def fetch_20newsgroups_vectorized(subset="train", remove=(), data_home=None): """Load the 20 newsgroups dataset and transform it into tf-idf vectors. This is a convenience function; the tf-idf transformation is done using the default settings for `sklearn.feature_extraction.text.Vectorizer`. For more advanced usage (stopword filtering, n-gram extraction, etc.), combine fetch_20newsgroups with a custom `Vectorizer` or `CountVectorizer`. Read more in the :ref:`User Guide <20newsgroups>`. Parameters ---------- subset: 'train' or 'test', 'all', optional Select the dataset to load: 'train' for the training set, 'test' for the test set, 'all' for both, with shuffled ordering. data_home: optional, default: None Specify an download and cache folder for the datasets. If None, all scikit-learn data is stored in '~/scikit_learn_data' subfolders. remove: tuple May contain any subset of ('headers', 'footers', 'quotes'). Each of these are kinds of text that will be detected and removed from the newsgroup posts, preventing classifiers from overfitting on metadata. 'headers' removes newsgroup headers, 'footers' removes blocks at the ends of posts that look like signatures, and 'quotes' removes lines that appear to be quoting another post. Returns ------- bunch : Bunch object bunch.data: sparse matrix, shape [n_samples, n_features] bunch.target: array, shape [n_samples] bunch.target_names: list, length [n_classes] """ data_home = get_data_home(data_home=data_home) filebase = '20newsgroup_vectorized' if remove: filebase += 'remove-' + ('-'.join(remove)) target_file = os.path.join(data_home, filebase + ".pk") # we shuffle but use a fixed seed for the memoization data_train = fetch_20newsgroups(data_home=data_home, subset='train', categories=None, shuffle=True, random_state=12, remove=remove) data_test = fetch_20newsgroups(data_home=data_home, subset='test', categories=None, shuffle=True, random_state=12, remove=remove) if os.path.exists(target_file): X_train, X_test = joblib.load(target_file) else: vectorizer = CountVectorizer(dtype=np.int16) X_train = vectorizer.fit_transform(data_train.data).tocsr() X_test = vectorizer.transform(data_test.data).tocsr() joblib.dump((X_train, X_test), target_file, compress=9) # the data is stored as int16 for compactness # but normalize needs floats X_train = X_train.astype(np.float64) X_test = X_test.astype(np.float64) normalize(X_train, copy=False) normalize(X_test, copy=False) target_names = data_train.target_names if subset == "train": data = X_train target = data_train.target elif subset == "test": data = X_test target = data_test.target elif subset == "all": data = sp.vstack((X_train, X_test)).tocsr() target = np.concatenate((data_train.target, data_test.target)) else: raise ValueError("%r is not a valid subset: should be one of " "['train', 'test', 'all']" % subset) return Bunch(data=data, target=target, target_names=target_names)
bsd-3-clause
ryfeus/lambda-packs
Skimage_numpy/source/scipy/ndimage/filters.py
24
42327
# Copyright (C) 2003-2005 Peter J. Verveer # # 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. # # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. from __future__ import division, print_function, absolute_import import math import numpy from . import _ni_support from . import _nd_image from scipy.misc import doccer from scipy._lib._version import NumpyVersion __all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace', 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude', 'gaussian_gradient_magnitude', 'correlate', 'convolve', 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', 'maximum_filter1d', 'minimum_filter', 'maximum_filter', 'rank_filter', 'median_filter', 'percentile_filter', 'generic_filter1d', 'generic_filter'] _input_doc = \ """input : array_like Input array to filter.""" _axis_doc = \ """axis : int, optional The axis of `input` along which to calculate. Default is -1.""" _output_doc = \ """output : array, optional The `output` parameter passes an array in which to store the filter output.""" _size_foot_doc = \ """size : scalar or tuple, optional See footprint, below footprint : array, optional Either `size` or `footprint` must be defined. `size` gives the shape that is taken from the input array, at every element position, to define the input to the filter function. `footprint` is a boolean array that specifies (implicitly) a shape, but also which of the elements within this shape will get passed to the filter function. Thus ``size=(n,m)`` is equivalent to ``footprint=np.ones((n,m))``. We adjust `size` to the number of dimensions of the input array, so that, if the input array is shape (10,10,10), and `size` is 2, then the actual size used is (2,2,2). """ _mode_doc = \ """mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional The `mode` parameter determines how the array borders are handled, where `cval` is the value when mode is equal to 'constant'. Default is 'reflect'""" _cval_doc = \ """cval : scalar, optional Value to fill past edges of input if `mode` is 'constant'. Default is 0.0""" _origin_doc = \ """origin : scalar, optional The `origin` parameter controls the placement of the filter. Default 0.0.""" _extra_arguments_doc = \ """extra_arguments : sequence, optional Sequence of extra positional arguments to pass to passed function""" _extra_keywords_doc = \ """extra_keywords : dict, optional dict of extra keyword arguments to pass to passed function""" docdict = { 'input': _input_doc, 'axis': _axis_doc, 'output': _output_doc, 'size_foot': _size_foot_doc, 'mode': _mode_doc, 'cval': _cval_doc, 'origin': _origin_doc, 'extra_arguments': _extra_arguments_doc, 'extra_keywords': _extra_keywords_doc, } docfiller = doccer.filldoc(docdict) @docfiller def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional correlation along the given axis. The lines of the array along the given axis are correlated with the given weights. Parameters ---------- %(input)s weights : array One-dimensional sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) weights = numpy.asarray(weights, dtype=numpy.float64) if weights.ndim != 1 or weights.shape[0] < 1: raise RuntimeError('no filter weights given') if not weights.flags.contiguous: weights = weights.copy() axis = _ni_support._check_axis(axis, input.ndim) if (len(weights) // 2 + origin < 0) or (len(weights) // 2 + origin > len(weights)): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate1d(input, weights, axis, output, mode, cval, origin) return return_value @docfiller def convolve1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional convolution along the given axis. The lines of the array along the given axis are convolved with the given weights. Parameters ---------- %(input)s weights : ndarray One-dimensional sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- convolve1d : ndarray Convolved array with same shape as input """ weights = weights[::-1] origin = -origin if not len(weights) & 1: origin -= 1 return correlate1d(input, weights, axis, output, mode, cval, origin) @docfiller def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """One-dimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar standard deviation for Gaussian kernel %(axis)s order : {0, 1, 2, 3}, optional An order of 0 corresponds to convolution with a Gaussian kernel. An order of 1, 2, or 3 corresponds to convolution with the first, second or third derivatives of a Gaussian. Higher order derivatives are not implemented %(output)s %(mode)s %(cval)s truncate : float, optional Truncate the filter at this many standard deviations. Default is 4.0. Returns ------- gaussian_filter1d : ndarray """ if order not in range(4): raise ValueError('Order outside 0..3 not implemented') sd = float(sigma) # make the radius of the filter equal to truncate standard deviations lw = int(truncate * sd + 0.5) weights = [0.0] * (2 * lw + 1) weights[lw] = 1.0 sum = 1.0 sd = sd * sd # calculate the kernel: for ii in range(1, lw + 1): tmp = math.exp(-0.5 * float(ii * ii) / sd) weights[lw + ii] = tmp weights[lw - ii] = tmp sum += 2.0 * tmp for ii in range(2 * lw + 1): weights[ii] /= sum # implement first, second and third order derivatives: if order == 1: # first derivative weights[lw] = 0.0 for ii in range(1, lw + 1): x = float(ii) tmp = -x / sd * weights[lw + ii] weights[lw + ii] = -tmp weights[lw - ii] = tmp elif order == 2: # second derivative weights[lw] *= -1.0 / sd for ii in range(1, lw + 1): x = float(ii) tmp = (x * x / sd - 1.0) * weights[lw + ii] / sd weights[lw + ii] = tmp weights[lw - ii] = tmp elif order == 3: # third derivative weights[lw] = 0.0 sd2 = sd * sd for ii in range(1, lw + 1): x = float(ii) tmp = (3.0 - x * x / sd) * x * weights[lw + ii] / sd2 weights[lw + ii] = -tmp weights[lw - ii] = tmp return correlate1d(input, weights, axis, output, mode, cval, 0) @docfiller def gaussian_filter(input, sigma, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """Multidimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar or sequence of scalars Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. order : {0, 1, 2, 3} or sequence from same set, optional The order of the filter along each axis is given as a sequence of integers, or as a single number. An order of 0 corresponds to convolution with a Gaussian kernel. An order of 1, 2, or 3 corresponds to convolution with the first, second or third derivatives of a Gaussian. Higher order derivatives are not implemented %(output)s %(mode)s %(cval)s truncate : float Truncate the filter at this many standard deviations. Default is 4.0. Returns ------- gaussian_filter : ndarray Returned array of same shape as `input`. Notes ----- The multidimensional filter is implemented as a sequence of one-dimensional convolution filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. Examples -------- >>> from scipy.ndimage import gaussian_filter >>> a = np.arange(50, step=2).reshape((5,5)) >>> a array([[ 0, 2, 4, 6, 8], [10, 12, 14, 16, 18], [20, 22, 24, 26, 28], [30, 32, 34, 36, 38], [40, 42, 44, 46, 48]]) >>> gaussian_filter(a, sigma=1) array([[ 4, 6, 8, 9, 11], [10, 12, 14, 15, 17], [20, 22, 24, 25, 27], [29, 31, 33, 34, 36], [35, 37, 39, 40, 42]]) """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) orders = _ni_support._normalize_sequence(order, input.ndim) if not set(orders).issubset(set(range(4))): raise ValueError('Order outside 0..4 not implemented') sigmas = _ni_support._normalize_sequence(sigma, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sigmas[ii], orders[ii]) for ii in range(len(axes)) if sigmas[ii] > 1e-15] if len(axes) > 0: for axis, sigma, order in axes: gaussian_filter1d(input, sigma, axis, order, output, mode, cval, truncate) input = output else: output[...] = input[...] return return_value @docfiller def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Prewitt filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> ascent = misc.ascent() >>> result = ndimage.prewitt(ascent) >>> plt.gray() # show the filtered result in grayscale >>> plt.imshow(result) """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) output, return_value = _ni_support._get_output(output, input) correlate1d(input, [-1, 0, 1], axis, output, mode, cval, 0) axes = [ii for ii in range(input.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 1, 1], ii, output, mode, cval, 0,) return return_value @docfiller def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Sobel filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> ascent = misc.ascent() >>> result = ndimage.sobel(ascent) >>> plt.gray() # show the filtered result in grayscale >>> plt.imshow(result) """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) output, return_value = _ni_support._get_output(output, input) correlate1d(input, [-1, 0, 1], axis, output, mode, cval, 0) axes = [ii for ii in range(input.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 2, 1], ii, output, mode, cval, 0) return return_value @docfiller def generic_laplace(input, derivative2, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords = None): """N-dimensional Laplace filter using a provided second derivative function Parameters ---------- %(input)s derivative2 : callable Callable with the following signature:: derivative2(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = list(range(input.ndim)) if len(axes) > 0: derivative2(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) for ii in range(1, len(axes)): tmp = derivative2(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) output += tmp else: output[...] = input[...] return return_value @docfiller def laplace(input, output=None, mode="reflect", cval=0.0): """N-dimensional Laplace filter based on approximate second derivatives. Parameters ---------- %(input)s %(output)s %(mode)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> ascent = misc.ascent() >>> result = ndimage.laplace(ascent) >>> plt.gray() # show the filtered result in grayscale >>> plt.imshow(result) """ def derivative2(input, axis, output, mode, cval): return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0) return generic_laplace(input, derivative2, output, mode, cval) @docfiller def gaussian_laplace(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multidimensional Laplace filter using gaussian second derivatives. Parameters ---------- %(input)s sigma : scalar or sequence of scalars The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. %(output)s %(mode)s %(cval)s Extra keyword arguments will be passed to gaussian_filter(). Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>> ascent = misc.ascent() >>> fig = plt.figure() >>> plt.gray() # show the filtered result in grayscale >>> ax1 = fig.add_subplot(121) # left side >>> ax2 = fig.add_subplot(122) # right side >>> result = ndimage.gaussian_laplace(ascent, sigma=1) >>> ax1.imshow(result) >>> result = ndimage.gaussian_laplace(ascent, sigma=3) >>> ax2.imshow(result) >>> plt.show() """ input = numpy.asarray(input) def derivative2(input, axis, output, mode, cval, sigma, **kwargs): order = [0] * input.ndim order[axis] = 2 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) return generic_laplace(input, derivative2, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs) @docfiller def generic_gradient_magnitude(input, derivative, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords = None): """Gradient magnitude using a provided gradient function. Parameters ---------- %(input)s derivative : callable Callable with the following signature:: derivative(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. `derivative` can assume that `input` and `output` are ndarrays. Note that the output from `derivative` is modified inplace; be careful to copy important inputs before returning them. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = list(range(input.ndim)) if len(axes) > 0: derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(output, output, output) for ii in range(1, len(axes)): tmp = derivative(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(tmp, tmp, tmp) output += tmp # This allows the sqrt to work with a different default casting numpy.sqrt(output, output, casting='unsafe') else: output[...] = input[...] return return_value @docfiller def gaussian_gradient_magnitude(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multidimensional gradient magnitude using Gaussian derivatives. Parameters ---------- %(input)s sigma : scalar or sequence of scalars The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.. %(output)s %(mode)s %(cval)s Extra keyword arguments will be passed to gaussian_filter(). """ input = numpy.asarray(input) def derivative(input, axis, output, mode, cval, sigma, **kwargs): order = [0] * input.ndim order[axis] = 1 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) return generic_gradient_magnitude(input, derivative, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs) def _correlate_or_convolve(input, weights, output, mode, cval, origin, convolution): input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) weights = numpy.asarray(weights, dtype=numpy.float64) wshape = [ii for ii in weights.shape if ii > 0] if len(wshape) != input.ndim: raise RuntimeError('filter weights array has incorrect shape.') if convolution: weights = weights[tuple([slice(None, None, -1)] * weights.ndim)] for ii in range(len(origins)): origins[ii] = -origins[ii] if not weights.shape[ii] & 1: origins[ii] -= 1 for origin, lenw in zip(origins, wshape): if (lenw // 2 + origin < 0) or (lenw // 2 + origin > lenw): raise ValueError('invalid origin') if not weights.flags.contiguous: weights = weights.copy() output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate(input, weights, output, mode, cval, origins) return return_value @docfiller def correlate(input, weights, output=None, mode='reflect', cval=0.0, origin=0): """ Multi-dimensional correlation. The array is correlated with the given kernel. Parameters ---------- input : array-like input array to filter weights : ndarray array of weights, same number of dimensions as input output : array, optional The ``output`` parameter passes an array in which to store the filter output. mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional The ``mode`` parameter determines how the array borders are handled, where ``cval`` is the value when mode is equal to 'constant'. Default is 'reflect' cval : scalar, optional Value to fill past edges of input if ``mode`` is 'constant'. Default is 0.0 origin : scalar, optional The ``origin`` parameter controls the placement of the filter. Default 0 See Also -------- convolve : Convolve an image with a kernel. """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, False) @docfiller def convolve(input, weights, output=None, mode='reflect', cval=0.0, origin=0): """ Multidimensional convolution. The array is convolved with the given kernel. Parameters ---------- input : array_like Input array to filter. weights : array_like Array of weights, same number of dimensions as input output : ndarray, optional The `output` parameter passes an array in which to store the filter output. mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional the `mode` parameter determines how the array borders are handled. For 'constant' mode, values beyond borders are set to be `cval`. Default is 'reflect'. cval : scalar, optional Value to fill past edges of input if `mode` is 'constant'. Default is 0.0 origin : array_like, optional The `origin` parameter controls the placement of the filter, relative to the centre of the current element of the input. Default of 0 is equivalent to ``(0,)*input.ndim``. Returns ------- result : ndarray The result of convolution of `input` with `weights`. See Also -------- correlate : Correlate an image with a kernel. Notes ----- Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where W is the `weights` kernel, j is the n-D spatial index over :math:`W`, I is the `input` and k is the coordinate of the center of W, specified by `origin` in the input parameters. Examples -------- Perhaps the simplest case to understand is ``mode='constant', cval=0.0``, because in this case borders (i.e. where the `weights` kernel, centered on any one value, extends beyond an edge of `input`. >>> a = np.array([[1, 2, 0, 0], ... [5, 3, 0, 4], ... [0, 0, 0, 7], ... [9, 3, 0, 0]]) >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]]) >>> from scipy import ndimage >>> ndimage.convolve(a, k, mode='constant', cval=0.0) array([[11, 10, 7, 4], [10, 3, 11, 11], [15, 12, 14, 7], [12, 3, 7, 0]]) Setting ``cval=1.0`` is equivalent to padding the outer edge of `input` with 1.0's (and then extracting only the original region of the result). >>> ndimage.convolve(a, k, mode='constant', cval=1.0) array([[13, 11, 8, 7], [11, 3, 11, 14], [16, 12, 14, 10], [15, 6, 10, 5]]) With ``mode='reflect'`` (the default), outer values are reflected at the edge of `input` to fill in missing values. >>> b = np.array([[2, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]]) >>> ndimage.convolve(b, k, mode='reflect') array([[5, 0, 0], [3, 0, 0], [1, 0, 0]]) This includes diagonally at the corners. >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]]) >>> ndimage.convolve(b, k) array([[4, 2, 0], [3, 2, 0], [1, 1, 0]]) With ``mode='nearest'``, the single nearest value in to an edge in `input` is repeated as many times as needed to match the overlapping `weights`. >>> c = np.array([[2, 0, 1], ... [1, 0, 0], ... [0, 0, 0]]) >>> k = np.array([[0, 1, 0], ... [0, 1, 0], ... [0, 1, 0], ... [0, 1, 0], ... [0, 1, 0]]) >>> ndimage.convolve(c, k, mode='nearest') array([[7, 0, 3], [5, 0, 2], [3, 0, 1]]) """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, True) @docfiller def uniform_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional uniform filter along the given axis. The lines of the array along the given axis are filtered with a uniform filter of given size. Parameters ---------- %(input)s size : int length of uniform filter %(axis)s %(output)s %(mode)s %(cval)s %(origin)s """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, origin) return return_value @docfiller def uniform_filter(input, size=3, output=None, mode="reflect", cval=0.0, origin=0): """Multi-dimensional uniform filter. Parameters ---------- %(input)s size : int or sequence of ints, optional The sizes of the uniform filter are given for each axis as a sequence, or as a single number, in which case the size is equal for all axes. %(output)s %(mode)s %(cval)s %(origin)s Notes ----- The multi-dimensional filter is implemented as a sequence of one-dimensional uniform filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) sizes = _ni_support._normalize_sequence(size, input.ndim) origins = _ni_support._normalize_sequence(origin, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes)) if sizes[ii] > 1] if len(axes) > 0: for axis, size, origin in axes: uniform_filter1d(input, int(size), axis, output, mode, cval, origin) input = output else: output[...] = input[...] return return_value @docfiller def minimum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional minimum filter along the given axis. The lines of the array along the given axis are filtered with a minimum filter of given size. Parameters ---------- %(input)s size : int length along which to calculate 1D minimum %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Notes ----- This function implements the MINLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 1) return return_value @docfiller def maximum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional maximum filter along the given axis. The lines of the array along the given axis are filtered with a maximum filter of given size. Parameters ---------- %(input)s size : int Length along which to calculate the 1-D maximum. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- maximum1d : ndarray, None Maximum-filtered array with same shape as input. None if `output` is not None Notes ----- This function implements the MAXLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0) return return_value def _min_or_max_filter(input, size, footprint, structure, output, mode, cval, origin, minimum): if structure is None: if footprint is None: if size is None: raise RuntimeError("no footprint provided") separable = True else: footprint = numpy.asarray(footprint) footprint = footprint.astype(bool) if numpy.alltrue(numpy.ravel(footprint), axis=0): size = footprint.shape footprint = None separable = True else: separable = False else: structure = numpy.asarray(structure, dtype=numpy.float64) separable = False if footprint is None: footprint = numpy.ones(structure.shape, bool) else: footprint = numpy.asarray(footprint) footprint = footprint.astype(bool) input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) origins = _ni_support._normalize_sequence(origin, input.ndim) if separable: sizes = _ni_support._normalize_sequence(size, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes)) if sizes[ii] > 1] if minimum: filter_ = minimum_filter1d else: filter_ = maximum_filter1d if len(axes) > 0: for axis, size, origin in axes: filter_(input, int(size), axis, output, mode, cval, origin) input = output else: output[...] = input[...] else: fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() if structure is not None: if len(structure.shape) != input.ndim: raise RuntimeError('structure array has incorrect shape') if not structure.flags.contiguous: structure = structure.copy() mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter(input, footprint, structure, output, mode, cval, origins, minimum) return return_value @docfiller def minimum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional minimum filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 1) @docfiller def maximum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional maximum filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 0) @docfiller def _rank_filter(input, rank, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, operation='rank'): input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) if footprint is None: if size is None: raise RuntimeError("no footprint or filter size provided") sizes = _ni_support._normalize_sequence(size, input.ndim) footprint = numpy.ones(sizes, dtype=bool) else: footprint = numpy.asarray(footprint, dtype=bool) fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('filter footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() filter_size = numpy.where(footprint, 1, 0).sum() if operation == 'median': rank = filter_size // 2 elif operation == 'percentile': percentile = rank if percentile < 0.0: percentile += 100.0 if percentile < 0 or percentile > 100: raise RuntimeError('invalid percentile') if percentile == 100.0: rank = filter_size - 1 else: rank = int(float(filter_size) * percentile / 100.0) if rank < 0: rank += filter_size if rank < 0 or rank >= filter_size: raise RuntimeError('rank not within filter footprint size') if rank == 0: return minimum_filter(input, None, footprint, output, mode, cval, origins) elif rank == filter_size - 1: return maximum_filter(input, None, footprint, output, mode, cval, origins) else: output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins) return return_value @docfiller def rank_filter(input, rank, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional rank filter. Parameters ---------- %(input)s rank : int The rank parameter may be less then zero, i.e., rank = -1 indicates the largest element. %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _rank_filter(input, rank, size, footprint, output, mode, cval, origin, 'rank') @docfiller def median_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """ Calculates a multidimensional median filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- median_filter : ndarray Return of same shape as `input`. """ return _rank_filter(input, 0, size, footprint, output, mode, cval, origin, 'median') @docfiller def percentile_filter(input, percentile, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional percentile filter. Parameters ---------- %(input)s percentile : scalar The percentile parameter may be less then zero, i.e., percentile = -20 equals percentile = 80 %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _rank_filter(input, percentile, size, footprint, output, mode, cval, origin, 'percentile') @docfiller def generic_filter1d(input, function, filter_size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0, extra_arguments=(), extra_keywords = None): """Calculate a one-dimensional filter along the given axis. `generic_filter1d` iterates over the lines of the array, calling the given function at each line. The arguments of the line are the input line, and the output line. The input and output lines are 1D double arrays. The input line is extended appropriately according to the filter size and origin. The output line must be modified in-place with the result. Parameters ---------- %(input)s function : callable Function to apply along given axis. filter_size : scalar Length of the filter. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s %(extra_arguments)s %(extra_keywords)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) if filter_size < 1: raise RuntimeError('invalid filter size') axis = _ni_support._check_axis(axis, input.ndim) if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >= filter_size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.generic_filter1d(input, function, filter_size, axis, output, mode, cval, origin, extra_arguments, extra_keywords) return return_value @docfiller def generic_filter(input, function, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, extra_arguments=(), extra_keywords = None): """Calculates a multi-dimensional filter using the given function. At each element the provided function is called. The input values within the filter footprint at that element are passed to the function as a 1D array of double values. Parameters ---------- %(input)s function : callable Function to apply at each element. %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s %(extra_arguments)s %(extra_keywords)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) if footprint is None: if size is None: raise RuntimeError("no footprint or filter size provided") sizes = _ni_support._normalize_sequence(size, input.ndim) footprint = numpy.ones(sizes, dtype=bool) else: footprint = numpy.asarray(footprint) footprint = footprint.astype(bool) fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('filter footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.generic_filter(input, function, footprint, output, mode, cval, origins, extra_arguments, extra_keywords) return return_value
mit
Lyleo/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/projections/polar.py
69
20981
import math import numpy as npy import matplotlib rcParams = matplotlib.rcParams from matplotlib.artist import kwdocd from matplotlib.axes import Axes from matplotlib import cbook from matplotlib.patches import Circle from matplotlib.path import Path from matplotlib.ticker import Formatter, Locator from matplotlib.transforms import Affine2D, Affine2DBase, Bbox, \ BboxTransformTo, IdentityTransform, Transform, TransformWrapper class PolarAxes(Axes): """ A polar graph projection, where the input dimensions are *theta*, *r*. Theta starts pointing east and goes anti-clockwise. """ name = 'polar' class PolarTransform(Transform): """ The base polar transform. This handles projection *theta* and *r* into Cartesian coordinate space *x* and *y*, but does not perform the ultimate affine transformation into the correct position. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, resolution): """ Create a new polar transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved polar space. """ Transform.__init__(self) self._resolution = resolution def transform(self, tr): xy = npy.zeros(tr.shape, npy.float_) t = tr[:, 0:1] r = tr[:, 1:2] x = xy[:, 0:1] y = xy[:, 1:2] x[:] = r * npy.cos(t) y[:] = r * npy.sin(t) return xy transform.__doc__ = Transform.transform.__doc__ transform_non_affine = transform transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def transform_path(self, path): vertices = path.vertices t = vertices[:, 0:1] t[t != (npy.pi * 2.0)] %= (npy.pi * 2.0) if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]: return Path(self.transform(vertices), path.codes) ipath = path.interpolated(self._resolution) return Path(self.transform(ipath.vertices), ipath.codes) transform_path.__doc__ = Transform.transform_path.__doc__ transform_path_non_affine = transform_path transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__ def inverted(self): return PolarAxes.InvertedPolarTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ class PolarAffine(Affine2DBase): """ The affine part of the polar projection. Scales the output so that maximum radius rests on the edge of the axes circle. """ def __init__(self, scale_transform, limits): u""" *limits* is the view limit of the data. The only part of its bounds that is used is ymax (for the radius maximum). The theta range is always fixed to (0, 2\u03c0). """ Affine2DBase.__init__(self) self._scale_transform = scale_transform self._limits = limits self.set_children(scale_transform, limits) self._mtx = None def get_matrix(self): if self._invalid: limits_scaled = self._limits.transformed(self._scale_transform) ymax = limits_scaled.ymax affine = Affine2D() \ .scale(0.5 / ymax) \ .translate(0.5, 0.5) self._mtx = affine.get_matrix() self._inverted = None self._invalid = 0 return self._mtx get_matrix.__doc__ = Affine2DBase.get_matrix.__doc__ class InvertedPolarTransform(Transform): """ The inverse of the polar transform, mapping Cartesian coordinate space *x* and *y* back to *theta* and *r*. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, resolution): Transform.__init__(self) self._resolution = resolution def transform(self, xy): x = xy[:, 0:1] y = xy[:, 1:] r = npy.sqrt(x*x + y*y) theta = npy.arccos(x / r) theta = npy.where(y < 0, 2 * npy.pi - theta, theta) return npy.concatenate((theta, r), 1) transform.__doc__ = Transform.transform.__doc__ def inverted(self): return PolarAxes.PolarTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ class ThetaFormatter(Formatter): u""" Used to format the *theta* tick labels. Converts the native unit of radians into degrees and adds a degree symbol (\u00b0). """ def __call__(self, x, pos=None): # \u00b0 : degree symbol if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: return r"$%0.0f^\circ$" % ((x / npy.pi) * 180.0) else: # we use unicode, rather than mathtext with \circ, so # that it will work correctly with any arbitrary font # (assuming it has a degree sign), whereas $5\circ$ # will only work correctly with one of the supported # math fonts (Computer Modern and STIX) return u"%0.0f\u00b0" % ((x / npy.pi) * 180.0) class RadialLocator(Locator): """ Used to locate radius ticks. Ensures that all ticks are strictly positive. For all other tasks, it delegates to the base :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base): self.base = base def __call__(self): ticks = self.base() return [x for x in ticks if x > 0] def autoscale(self): return self.base.autoscale() def pan(self, numsteps): return self.base.pan(numsteps) def zoom(self, direction): return self.base.zoom(direction) def refresh(self): return self.base.refresh() RESOLUTION = 75 def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. """ self._rpad = 0.05 self.resolution = kwargs.pop('resolution', self.RESOLUTION) Axes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() __init__.__doc__ = Axes.__init__.__doc__ def cla(self): Axes.cla(self) self.title.set_y(1.05) self.xaxis.set_major_formatter(self.ThetaFormatter()) angles = npy.arange(0.0, 360.0, 45.0) self.set_thetagrids(angles) self.yaxis.set_major_locator(self.RadialLocator(self.yaxis.get_major_locator())) self.grid(rcParams['polaraxes.grid']) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) data self.transProjection = self.PolarTransform(self.resolution) # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = self.transScale + self.transProjection + \ (self.transProjectionAffine + self.transAxes) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 1.0 at # the edge of the axis circle. self._xaxis_transform = ( self.transProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes) # The theta labels are moved from radius == 0.0 to radius == 1.1 self._theta_label1_position = Affine2D().translate(0.0, 1.1) self._xaxis_text1_transform = ( self._theta_label1_position + self._xaxis_transform) self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1) self._xaxis_text2_transform = ( self._theta_label2_position + self._xaxis_transform) # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to # 2pi. self._yaxis_transform = ( Affine2D().scale(npy.pi * 2.0, 1.0) + self.transData) # The r-axis labels are put at an angle and padded in the r-direction self._r_label1_position = Affine2D().translate(22.5, self._rpad) self._yaxis_text1_transform = ( self._r_label1_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform ) self._r_label2_position = Affine2D().translate(22.5, self._rpad) self._yaxis_text2_transform = ( self._r_label2_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform ) def get_xaxis_transform(self): return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return self._xaxis_text1_transform, 'center', 'center' def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'center', 'center' def get_yaxis_transform(self): return self._yaxis_transform def get_yaxis_text1_transform(self, pad): return self._yaxis_text1_transform, 'center', 'center' def get_yaxis_text2_transform(self, pad): return self._yaxis_text2_transform, 'center', 'center' def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def set_rmax(self, rmax): self.viewLim.y1 = rmax angle = self._r_label1_position.to_values()[4] self._r_label1_position.clear().translate( angle, rmax * self._rpad) self._r_label2_position.clear().translate( angle, -rmax * self._rpad) def get_rmax(self): return self.viewLim.ymax def set_yscale(self, *args, **kwargs): Axes.set_yscale(self, *args, **kwargs) self.yaxis.set_major_locator( self.RadialLocator(self.yaxis.get_major_locator())) set_rscale = Axes.set_yscale set_rticks = Axes.set_yticks def set_thetagrids(self, angles, labels=None, frac=None, **kwargs): """ Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not None, is a ``len(angles)`` list of strings of the labels to use at each angle. If *labels* is None, the labels will be ``fmt %% angle`` *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). Eg. 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ angles = npy.asarray(angles, npy.float_) self.set_xticks(angles * (npy.pi / 180.0)) if labels is not None: self.set_xticklabels(labels) if frac is not None: self._theta_label1_position.clear().translate(0.0, frac) self._theta_label2_position.clear().translate(0.0, 1.0 / frac) for t in self.xaxis.get_ticklabels(): t.update(kwargs) return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels() set_thetagrids.__doc__ = cbook.dedent(set_thetagrids.__doc__) % kwdocd def set_rgrids(self, radii, labels=None, angle=None, rpad=None, **kwargs): """ Set the radial locations and labels of the *r* grids. The labels will appear at radial distances *radii* at the given *angle* in degrees. *labels*, if not None, is a ``len(radii)`` list of strings of the labels to use at each radius. If *labels* is None, the built-in formatter will be used. *rpad* is a fraction of the max of *radii* which will pad each of the radial labels in the radial direction. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ radii = npy.asarray(radii) rmin = radii.min() if rmin <= 0: raise ValueError('radial grids must be strictly positive') self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) if angle is None: angle = self._r_label1_position.to_values()[4] if rpad is not None: self._rpad = rpad rmax = self.get_rmax() self._r_label1_position.clear().translate(angle, self._rpad * rmax) self._r_label2_position.clear().translate(angle, -self._rpad * rmax) for t in self.yaxis.get_ticklabels(): t.update(kwargs) return self.yaxis.get_ticklines(), self.yaxis.get_ticklabels() set_rgrids.__doc__ = cbook.dedent(set_rgrids.__doc__) % kwdocd def set_xscale(self, scale, *args, **kwargs): if scale != 'linear': raise NotImplementedError("You can not set the xscale on a polar plot.") def set_xlim(self, *args, **kargs): # The xlim is fixed, no matter what you do self.viewLim.intervalx = (0.0, npy.pi * 2.0) def format_coord(self, theta, r): """ Return a format string formatting the coordinate using Unicode characters. """ theta /= math.pi # \u03b8: lower-case theta # \u03c0: lower-case pi # \u00b0: degree symbol return u'\u03b8=%0.3f\u03c0 (%0.3f\u00b0), r=%0.3f' % (theta, theta * 180.0, r) def get_data_ratio(self): ''' Return the aspect ratio of the data itself. For a polar plot, this should always be 1.0 ''' return 1.0 ### Interactive panning def can_zoom(self): """ Return True if this axes support the zoom box """ return False def start_pan(self, x, y, button): angle = self._r_label1_position.to_values()[4] / 180.0 * npy.pi mode = '' if button == 1: epsilon = npy.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if t >= angle - epsilon and t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = cbook.Bunch( rmax = self.get_rmax(), trans = self.transData.frozen(), trans_inverse = self.transData.inverted().frozen(), r_label_angle = self._r_label1_position.to_values()[4], x = x, y = y, mode = mode ) def end_pan(self): del self._pan_start def drag_pan(self, button, key, x, y): p = self._pan_start if p.mode == 'drag_r_labels': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) # Deal with theta dt0 = t - startt dt1 = startt - t if abs(dt1) < abs(dt0): dt = abs(dt1) * sign(dt0) * -1.0 else: dt = dt0 * -1.0 dt = (dt / npy.pi) * 180.0 rpad = self._r_label1_position.to_values()[5] self._r_label1_position.clear().translate( p.r_label_angle - dt, rpad) self._r_label2_position.clear().translate( p.r_label_angle - dt, -rpad) elif p.mode == 'zoom': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) dr = r - startr # Deal with r scale = r / startr self.set_rmax(p.rmax / scale) # These are a couple of aborted attempts to project a polar plot using # cubic bezier curves. # def transform_path(self, path): # twopi = 2.0 * npy.pi # halfpi = 0.5 * npy.pi # vertices = path.vertices # t0 = vertices[0:-1, 0] # t1 = vertices[1: , 0] # td = npy.where(t1 > t0, t1 - t0, twopi - (t0 - t1)) # maxtd = td.max() # interpolate = npy.ceil(maxtd / halfpi) # if interpolate > 1.0: # vertices = self.interpolate(vertices, interpolate) # vertices = self.transform(vertices) # result = npy.zeros((len(vertices) * 3 - 2, 2), npy.float_) # codes = mpath.Path.CURVE4 * npy.ones((len(vertices) * 3 - 2, ), mpath.Path.code_type) # result[0] = vertices[0] # codes[0] = mpath.Path.MOVETO # kappa = 4.0 * ((npy.sqrt(2.0) - 1.0) / 3.0) # kappa = 0.5 # p0 = vertices[0:-1] # p1 = vertices[1: ] # x0 = p0[:, 0:1] # y0 = p0[:, 1: ] # b0 = ((y0 - x0) - y0) / ((x0 + y0) - x0) # a0 = y0 - b0*x0 # x1 = p1[:, 0:1] # y1 = p1[:, 1: ] # b1 = ((y1 - x1) - y1) / ((x1 + y1) - x1) # a1 = y1 - b1*x1 # x = -(a0-a1) / (b0-b1) # y = a0 + b0*x # xk = (x - x0) * kappa + x0 # yk = (y - y0) * kappa + y0 # result[1::3, 0:1] = xk # result[1::3, 1: ] = yk # xk = (x - x1) * kappa + x1 # yk = (y - y1) * kappa + y1 # result[2::3, 0:1] = xk # result[2::3, 1: ] = yk # result[3::3] = p1 # print vertices[-2:] # print result[-2:] # return mpath.Path(result, codes) # twopi = 2.0 * npy.pi # halfpi = 0.5 * npy.pi # vertices = path.vertices # t0 = vertices[0:-1, 0] # t1 = vertices[1: , 0] # td = npy.where(t1 > t0, t1 - t0, twopi - (t0 - t1)) # maxtd = td.max() # interpolate = npy.ceil(maxtd / halfpi) # print "interpolate", interpolate # if interpolate > 1.0: # vertices = self.interpolate(vertices, interpolate) # result = npy.zeros((len(vertices) * 3 - 2, 2), npy.float_) # codes = mpath.Path.CURVE4 * npy.ones((len(vertices) * 3 - 2, ), mpath.Path.code_type) # result[0] = vertices[0] # codes[0] = mpath.Path.MOVETO # kappa = 4.0 * ((npy.sqrt(2.0) - 1.0) / 3.0) # tkappa = npy.arctan(kappa) # hyp_kappa = npy.sqrt(kappa*kappa + 1.0) # t0 = vertices[0:-1, 0] # t1 = vertices[1: , 0] # r0 = vertices[0:-1, 1] # r1 = vertices[1: , 1] # td = npy.where(t1 > t0, t1 - t0, twopi - (t0 - t1)) # td_scaled = td / (npy.pi * 0.5) # rd = r1 - r0 # r0kappa = r0 * kappa * td_scaled # r1kappa = r1 * kappa * td_scaled # ravg_kappa = ((r1 + r0) / 2.0) * kappa * td_scaled # result[1::3, 0] = t0 + (tkappa * td_scaled) # result[1::3, 1] = r0*hyp_kappa # # result[1::3, 1] = r0 / npy.cos(tkappa * td_scaled) # npy.sqrt(r0*r0 + ravg_kappa*ravg_kappa) # result[2::3, 0] = t1 - (tkappa * td_scaled) # result[2::3, 1] = r1*hyp_kappa # # result[2::3, 1] = r1 / npy.cos(tkappa * td_scaled) # npy.sqrt(r1*r1 + ravg_kappa*ravg_kappa) # result[3::3, 0] = t1 # result[3::3, 1] = r1 # print vertices[:6], result[:6], t0[:6], t1[:6], td[:6], td_scaled[:6], tkappa # result = self.transform(result) # return mpath.Path(result, codes) # transform_path_non_affine = transform_path
gpl-3.0
edwardsmith999/pyDataView
postproclib/field.py
1
25726
#! /usr/bin/env python import numpy as np import sys from .pplexceptions import OutsideRecRange class Field(): """ Abstract base class to be inherited by MDField, CFDField and CPLField. Authors: Ed Smith 2019 & David Trevelyan (2010-2014) Abstract base class template that generally specifies how data should be processed and returned in postprocessing routines. Field should be inherited by MDField (which will then, in turn, be inherited by MD_mField for mass, etc.). Fields are, essentially, data reformatters. They must be instantiated with a RawData object, which is used to do the actual reading, and the methods in Field re-package that data in an easily plottable format. TOP-LEVEL EXAMPLE v = MD_vField(fdir) y, v3 = v.profile(axis=1) plt.plot(v3[:,0], y) This will instantiate a velocity field (see MDFields for details of the complex inheritance and containment), read and store the data from multiple files to construct a velocity profile, and finally will plot the x-component of velocity against the y-axis. In line with RawData readers, axes correspond to: [ spatial ax1, spatial ax2, spatial ax3, record, component ] [ 0 , 1 , 2 , 3 , 4 (&-1) ] """ def __init__(self, RawDataObj): self.Raw = RawDataObj self.fdir = self.Raw.fdir self.grid = self.Raw.grid self.maxrec = self.Raw.maxrec def read(self,startrec,endrec,**kwargs): """ TO BE OVERRIDDEN IN COMPLICATED FIELDS. Method that returns grid data that is read by Raw. """ if (endrec > self.maxrec): print(('Record ' + str(endrec) + ' is greater than the maximum ' 'available (' + str(self.maxrec) + ').')) raise OutsideRecRange grid_data = self.Raw.read(startrec,endrec,**kwargs) return grid_data def read_halo(self,startrec,endrec,**kwargs): """ Method to read halo if Raw data reader supports it. """ try: return self.Raw.read_halo(startrec,endrec,**kwargs) except AttributeError: raise def averaged_data(self,startrec,endrec,avgaxes=(),**kwargs): """ TO BE OVERRIDDEN IN ALL COMPLICATED FIELDS. Average the data in the user-specified way. """ # Read 4D time series from startrec to endrec grid_data = self.read(startrec,endrec,**kwargs) # Average over axes if (avgaxes != ()): grid_data = np.mean(grid_data,axis=avgaxes) #return avg_data return grid_data def contour(self,axes,startrec=0,endrec=None,**kwargs): """ NOT TO BE OVERRIDDEN UNLESS ABSOLUTELY NECESSARY Wrapper for averaged_data, returns easily plottable data """ avgaxes = [0,1,2,3] avgaxes.remove(axes[0]) avgaxes.remove(axes[1]) avgaxes = tuple(avgaxes) if (endrec==None): endrec = self.maxrec data = self.averaged_data(startrec,endrec,avgaxes=avgaxes,**kwargs) # Need version 1.7.1 of numpy or higher X, Y = np.meshgrid(self.grid[axes[0]],self.grid[axes[1]],indexing='ij') return X, Y, data def profile(self,axis,startrec=0,endrec=None,**kwargs): """ NOT TO BE OVERRIDDEN UNLESS ABSOLUTELY NECESSARY Wrapper for averaged_data, returns easily plottable data """ avgaxes = [0,1,2,3] avgaxes.remove(axis) avgaxes = tuple(avgaxes) if (endrec==None): endrec = self.maxrec data = self.averaged_data(startrec,endrec,avgaxes=avgaxes,**kwargs) return self.grid[axis], data def quiver(self,axes,components=None,startrec=0,endrec=None,**kwargs): """ NOT TO BE OVERRIDDEN UNLESS ABSOLUTELY NECESSARY Wrapper for averaged_data, returns easily plottable data """ if (components==None): components = axes X, Y, data = self.contour(axes,startrec=startrec,endrec=endrec,**kwargs) #avgaxes = [0,1,2,3] #avgaxes.remove(axes[0]) #avgaxes.remove(axes[1]) #avgaxes = tuple(avgaxes) #if (endrec==None): # endrec = self.maxrec #data = self.averaged_data(startrec,endrec,avgaxes=avgaxes,**kwargs) # Need version 1.7.1 of numpy or higher #X, Y = np.meshgrid(self.grid[axes[0]],self.grid[axes[1]],indexing='ij') return X, Y, data[:,:,components] class AxisManager(): def __init__(self): self.nreduced = 0 self.axisactive = [True]*5 def reduce_axes(self,axes): for axis in axes: self.nreduced += 1 self.axisactive[axis] = False def current_axis_number(self,axis_request): if (not self.axisactive[axis_request]): return None n = 0 for otheraxis in range(axis_request): if (not self.axisactive[otheraxis]): n += 1 return int(axis_request - n) def current_axes_numbers(self,axes_request): newaxes = [] for axis in list(axes_request): newaxes.append(self.current_axis_number(axis)) return tuple(newaxes) def managed_mean(self, axismanager, data, avgaxes): newaxes = axismanager.current_axes_numbers(avgaxes) if (None in newaxes): sys.exit("Can't average over an axis that has been reduced") avgdata = np.mean(data, axis=newaxes) axismanager.reduce_axes(avgaxes) return avgdata def managed_fft(self,axismanager, data, fftaxes): newaxes = axismanager.current_axes_numbers(fftaxes) if (None in newaxes): sys.exit("Can't fft over an axis that has been reduced") fftdata = np.fft.fftn(data,axes=newaxes) return fftdata def managed_energyfield(self,axismanager, data, fftaxes): def add_negatives(a): b = a for i in range(1,len(b)/2): b[i] += a[-i] return b newfftaxes = axismanager.current_axes_numbers(fftaxes) # Count N N = 1 for axis in newfftaxes: N = N * data.shape[axis] # Initial energy in every wavenumber (pos and neg) E = np.abs(data)**2.0 #Add negative contributions to positive wavenumbers nd = len(E.shape) slicer = [slice(None)]*nd for axis in newfftaxes: E = np.apply_along_axis(add_negatives,axis,E) # Discard negative parts after adding to positive k = E.shape[axis] mid = int(np.ceil(float(k)/2.0)) cutout = np.s_[0:mid+1:1] slicer[axis] = cutout E = E[slicer] # Refresh slice for new axis calculation slicer[axis] = slice(None) return E/N def managed_window(self,axismanager, data, windowaxis): def window_axis_function(a, window): a = a * window return a newaxis = axismanager.current_axis_number(windowaxis) N = data.shape[newaxis] window = np.hanning(N) # Save "window summed and squared" (see Numerical Recipes) wss = np.sum(window**2.0)/float(N) # Apply window windoweddata = np.apply_along_axis(window_axis_function, newaxis, data, window) return windoweddata, wss def trim_binlimits(self, binlimits, bins): """ Trims a given field of bins based on binlimits """ # Defaults lower = [0]*3 upper = [i for i in bins.shape] for axis in range(3): if (binlimits[axis] == None): continue else: lower[axis] = binlimits[axis][0] upper[axis] = binlimits[axis][1] return bins[lower[0]:upper[0], lower[1]:upper[1], lower[2]:upper[2], :, :] def power_spectrum(self,data=None,startrec=None,endrec=None, preavgaxes=(), fftaxes=(),postavgaxes=(), windowaxis=None, verify_Parseval=True, savefile=None,**kwargs): """ Calculates power spectrum """ # ---------------------------------------------------------------- # Checks if (not isinstance(preavgaxes,tuple)): try: preavgaxes = tuple([preavgaxes]) except: print('Failed to make preavgaxes and fftaxes a tuple') if (not isinstance(fftaxes,tuple)): try: fftaxes = tuple([fftaxes]) except: print('Failed to make preavgaxes and fftaxes a tuple') if (not isinstance(postavgaxes,tuple)): try: postavgaxes = tuple([postavgaxes]) except: print('Failed to make preavgaxes and fftaxes a tuple') if (4 in postavgaxes or 4 in fftaxes or 4 in preavgaxes): message = "WARNING: you're asking me to average or fft over " message += "each component of the field. I don't know how to " message += "deal with this right now. Aborting." sys.exit(message) if (windowaxis): if (windowaxis in preavgaxes or windowaxis in postavgaxes): message = "Warning: you're asking me to window over an axis " message += "that you're eventually going to average over. " message += "Aborting." sys.exit(message) if (windowaxis not in fftaxes): message = "Warning: you're asking me to window over an axis " message += "that won't be Fourier transformed. This makes no " message += "sense. Aborting." # ---------------------------------------------------------------- # Do the process if (startrec==None): startrec = 0 if (endrec==None): endrec = self.maxrec axisman = self.AxisManager() if data == None: data = self.read(startrec, endrec,**kwargs) data = self.managed_mean(axisman, data, preavgaxes) if (windowaxis): data, wss = self.managed_window(axisman, data, windowaxis) if (verify_Parseval): Esumreal = np.sum(np.abs(data)**2.0) fftdata = self.managed_fft(axisman, data, fftaxes) energy = self.managed_energyfield(axisman, fftdata, fftaxes) if (verify_Parseval): Esumfft = np.sum(energy) ratio = abs(Esumreal - Esumfft)/Esumreal perc = (1. - ratio)*100. print(('Parseval thm (discounting window): ' + "%9.6f"%perc + '%')) if (windowaxis): energy = energy / wss energy = self.managed_mean(axisman, energy, postavgaxes) if (savefile): with open(savefile,'w') as f: f.write(energy) return energy def grad(self, data, dx=None, dy=None, dz=None, preavgaxes=()): """ Return the gradient of a vector field """ # ---------------------------------------------------------------- # Checks if (not isinstance(preavgaxes,tuple)): try: preavgaxes = tuple([preavgaxes]) except: print('Failed to make preavgaxes in grad') #if (dxyz is None): # dxyz=[self.Raw.dx,self.Raw.dy,self.Raw.dz] data = np.mean(data,axis=preavgaxes,keepdims=True) if (dx is None): dx=self.Raw.dx if (dy is None): dy=self.Raw.dy if (dz is None): dz=self.Raw.dz dxyz = (dx, dy, dz) ndims = data.shape[4] nonsingleton = [i!=1 for i in data.shape[0:3]] dxyz = [elem for i,elem in enumerate(dxyz) if nonsingleton[i]] gradv = np.zeros(list(data.shape[:-1]) + [3*ndims]) for rec in range(gradv.shape[-2]): for ixyz in range(ndims): grad_temp = np.gradient(np.squeeze(data[:,:,:,rec,ixyz]), dx, dy, dz) for jxyz in range(np.sum(nonsingleton)): c = 3*ixyz + jxyz gradv[:,:,:,rec,c] = grad_temp[jxyz] return gradv def write_dx_file(self, startrec, endrec, writedir=None, component=0, norm=False, origin=None, **kwargs): """ Write MD field to dx file format which is primarily useful for importing into VMD, see http://www.ks.uiuc.edu/Research/vmd/plugins/molfile/dxplugin.html and format website http://www.opendx.org/index2.php NOTE -- VMD dx format assumes data points are located at the cell vertices while Field class and it's children contain cell centred data """ #Get field data datamin = []; datamax = [] for rec in range(startrec,endrec): data = self.read(startrec=rec,endrec=rec,**kwargs) if norm: if ((np.max(data[:,:,:,:,component])) > 1e-14): data = (data-np.min(data[:,:,:,:,component]) /( np.max(data[:,:,:,:,component]) -np.min(data[:,:,:,:,component]))) #Return minimum and maximum values datamin.append(np.min(data[:,:,:,:,component])) datamax.append(np.max(data[:,:,:,:,component])) Nx, Ny, Nz = data.shape[0], data.shape[1], data.shape[2] dx,dy,dz = [(self.grid[i][1] - self.grid[i][0]) for i in range(3)] Lx = float(Nx) * dx; Ly = float(Ny) * dy; Lz = float(Nz) * dz originx = np.min(self.grid[0]) originy = np.min(self.grid[1]) originz = np.min(self.grid[2]) if origin != None: assert len(origin) == 3 originx = origin[0] #-Ly/2 originy = origin[1] #-Ly/2.0 originz = origin[2] #-Lz/2.0 data = self.cellcentre2vertex(data[:,:,:,0,component]) Nx_v, Ny_v, Nz_v = data.shape[0], data.shape[1], data.shape[2] #Get file name if (writedir == None): writedir = self.fdir + '/vmd/vol_data/' dxFileName = writedir + 'DATA' + str(rec) + '.dx' #Write data with open(dxFileName,'w+') as f: # - - Write Header - - #dx_ = dx*1.25; dy_ = dy*1.25; dz_ = dz*1.25 f.write("object 1 class gridpositions counts%8.0f%8.0f%8.0f\n" % (Nx_v,Ny_v,Nz_v)) f.write("origin%16g%16g%16g\n" % (originx,originy,originz)) f.write("delta %16g 0 0\n" % dx) f.write("delta 0 %16g 0\n" % dy) f.write("delta 0 0 %16g\n" % dz) f.write("object 2 class gridconnections counts%8.0f%8.0f%8.0f\n" % (Nx_v,Ny_v,Nz_v)) f.write("object 3 class array type double rank 0 items%8.0f follows\n" % (Nx_v*Ny_v*Nz_v)) # - - Write Data - - col=1 for i in range(Nx_v): for j in range(Ny_v): for k in range(Nz_v): f.write("%16E" % data[i,j,k]) col=col+1 if (col>3): f.write(' \n') col=1 # - - Write Footer - - if (col != 1): f.write(' \n') f.write('object "'+str(self).split('.')[1].split(' ')[0]+'" class field \n') return np.mean(datamin), np.mean(datamax) # Write ascii type field def write_asciifield(self,startrec,endrec, writedir=None,maptocosine=True, flipdir=[False,True,False],**kwargs): #Get file name if (writedir == None): writedir = self.fdir Nx, Ny, Nz = data.shape[0], data.shape[1], data.shape[2] Nxyz = [Nx,Ny,Nz] for n,flip in enumerate(flipdir): if flip: mindir[n] = Nxyz[n] maxdir[n] = 0 else: mindir[n] = 0 maxdir[n] = Nxyz[n] data = self.read(startrec=startrec,endrec=endrec,**kwargs) outfiles =[] for rec in range(startrec,endrec): FileName = writedir + 'u' + str(rec) + '.asc' outfiles.append(FileName) with open(FileName,'w+') as f: for nx in range(mindir[0],maxdir[0]): for ny in range(mindir[1],maxdir[1]): for nz in range(mindir[2],maxdir[2]): for ixyz in data.shape[4]: if maptocosine: f.write(str( self.map_data_lineartocosine( data[nx,ny,nz,rec,ixyz], self.Raw.Ny, self.Raw.a, self.Raw.b)) +"\n") else: f.write(str( data[nx,ny,nz,rec,ixyz]) +"\n") return outfiles # Write ascii type field def map_3Ddata_cosinetolinear(self,data,flipdir=[False,True,False],**kwargs): Nx, Ny, Nz = data.shape[0], data.shape[1], data.shape[2] Nxyz = [Nx,Ny,Nz] mindir = [0,0,0]; maxdir = [Nx,Ny,Nz] for n,flip in enumerate(flipdir): if flip: mindir[n] = Nxyz[n] maxdir[n] = 0 else: mindir[n] = 0 maxdir[n] = Nxyz[n] lindata = np.empty(data.shape) for nx in range(mindir[0],maxdir[0]): for nz in range(mindir[2],maxdir[2]): for rec in range(data.shape[3]): for ixyz in range(data.shape[4]): print((nx,nz,rec,ixyz)) lindata[nx,:,nz,rec,ixyz] = self.map_data_cosinetolinear( data[nx,:,nz,rec,ixyz], self.Raw.Ny, self.Raw.a, self.Raw.b) return lindata def map_data_lineartocosine(self, values_on_linear_grid, Ny, a, b, plot=False): """ Map data on a linear grid to a cosine grid """ import scipy.interpolate as interp ycells = np.linspace(0, Ny, Ny) ylin = np.linspace(a, b, Ny) ycos = 0.5*(b+a) - 0.5*(b-a)*np.cos((ycells*np.pi)/(Ny-1)) values_on_cosine_grid = interp.griddata(ylin, values_on_linear_grid, ycos, method='cubic', fill_value=values_on_linear_grid[-1]) if plot: import matplotlib.pyplot as plt plt.plot(ylin,values_on_linear_grid,'o-',alpha=0.4,label='lineartocosine Before') plt.plot(ycos,values_on_cosine_grid,'x-',label='lineartocosine After') plt.legend() plt.show() return values_on_cosine_grid def map_data_cosinetolinear(self,values_on_cosine_grid,Ny,a,b): """ Map data on a cosine grid to a linear grid """ import scipy.interpolate as interp ycells = np.linspace(0, Ny, Ny) ylin = np.linspace(a, b, Ny) ycos = 0.5*(b+a) - 0.5*(b-a)*np.cos((ycells*np.pi)/(Ny-1)) #print(ycos.shape,values_on_cosine_grid.shape) #plt.plot(ycos,values_on_cosine_grid,'x-',label='cosinetolinear Before') values_on_linear_grid = interp.griddata(ycos, values_on_cosine_grid, ylin, method='cubic', fill_value=values_on_cosine_grid[-1]) #from scipy.ndimage import map_coordinates #values_on_linear_grid = interp2.map_coordinates(values_on_cosine_grid,ycos,output=ylin) #plt.plot(ylin,values_on_linear_grid,'o-',alpha=0.4,label='cosinetolinear After') #plt.legend() #plt.show() return values_on_linear_grid def field_interpolator(self, celldata): from scipy.interpolate import RegularGridInterpolator #Need to turn off bounds errors and fill values to allow extrapolation fn = RegularGridInterpolator((self.grid[0], self.grid[1], self.grid[2]), celldata, bounds_error=False, fill_value=None) return fn def interp_3Darrays(self, fn, x, y, z): """ We need array data as a list of lists """ #We need array data as a list of lists pts = [] for i, xp in enumerate(x): for j, yp in enumerate(y): for k, zp in enumerate(z): pts.append([xp, yp, zp]) #Interpolate and reshape data = fn(pts) interpdata = data.reshape(x.size, y.size, z.size) return interpdata def cellcentre2vertex(self, celldata, method="zoom"): """ Routine to return grid data on an array one larger than the existing cell centred data - currently uses zoom for simplicity """ if method is "zoom": import scipy.ndimage Nx, Ny, Nz = celldata.shape[0], celldata.shape[1], celldata.shape[2] vertexdata = scipy.ndimage.zoom(celldata,((Nx+1)/float(Nx), (Ny+1)/float(Ny), (Nz+1)/float(Nz))) elif method is "interp": #Define values xg = self.grid[0] yg = self.grid[1] zg = self.grid[2] dx = xg[1]-xg[0] dy = yg[1]-yg[0] dz = zg[1]-zg[0] #Get interpolator fn = self.field_interpolator(celldata) #Get grid of courner nodes Nx, Ny, Nz = celldata.shape[0], celldata.shape[1], celldata.shape[2] assert Nx == self.grid[0].size assert Ny == self.grid[1].size assert Nz == self.grid[2].size x = np.linspace(self.grid[0][0]-0.5*dx, self.grid[0][-1]+0.5*dx, Nx+1) y = np.linspace(self.grid[1][0]-0.5*dy, self.grid[1][-1]+0.5*dy, Ny+1) z = np.linspace(self.grid[2][0]-0.5*dz, self.grid[2][-1]+0.5*dz, Nz+1) vertexdata = self.interp_3Darrays(fn, x, y, z) else: raise exception("Unknown method") return vertexdata def cellcentre2surface(self, celldata, method="interp"): if method is "interp": surfacedata = np.zeros((celldata.shape[0], celldata.shape[1], celldata.shape[2],6)) #Get grid of centre abd surface values Nx, Ny, Nz = celldata.shape[0], celldata.shape[1], celldata.shape[2] assert Nx == self.grid[0].size assert Ny == self.grid[1].size assert Nz == self.grid[2].size xg = self.grid[0] yg = self.grid[1] zg = self.grid[2] dx = xg[1]-xg[0] dy = yg[1]-yg[0] dz = zg[1]-zg[0] xs = np.linspace(self.grid[0][0]-0.5*dx, self.grid[0][-1]+0.5*dx, Nx+1) ys = np.linspace(self.grid[1][0]-0.5*dy, self.grid[1][-1]+0.5*dy, Ny+1) zs = np.linspace(self.grid[2][0]-0.5*dz, self.grid[2][-1]+0.5*dz, Nz+1) #Get interpolator fn = self.field_interpolator(celldata) # x surfaces xs, y, z data = self.interp_3Darrays(fn, xs, yg, zg) surfacedata[:,:,:,0] = data[:-1,:,:] #Bottom surfacedata[:,:,:,3] = data[1:,:,:] #Top # y surfaces x, ys, z data = self.interp_3Darrays(fn, xg, ys, zg) surfacedata[:,:,:,1] = data[:,:-1,:] #Bottom surfacedata[:,:,:,4] = data[:,1:,:] #Top # z surfaces x, y, zs data = self.interp_3Darrays(fn, xg, yg, zs) surfacedata[:,:,:,2] = data[:,:,:-1] #Bottom surfacedata[:,:,:,5] = data[:,:,1:] #Top else: raise exception("Unknown method") return surfacedata # Innards # for i in range(1,Nx): # for j in range(1,Ny): # for k in range(1,Nz): # vertexdata[i,j,k] = np.mean(celldata[i-1:i+2,j-1:j+2,k-1:k+2])
gpl-3.0
mbonvini/GreenCardLottery
gree_card_lottery.py
1
9231
""" Author: Marco Bonvini Date: September 27 2015 This script scrapes the pages of the Department of State website to gather statistics and information about the Diversity Visa (DV) lottery, aka green card lottery. The Department of State publishes every month a visa bulletin at http://travel.state.gov/content/visas/en/law-and-policy/bulletin.html this script generates URLs of the bulletins that have been released over the last years and look for information. In particular, the script looks for information regarding the DV lottery that are typically located in section B of the page, B. DIVERSITY IMMIGRANT (DV) CATEGORY FOR THE MONTH OF ... This section contains a table that states which DV lottery numbers will be able to move forward with their application for the green card. The scripts collectes all the data from the tables and generate Pandas DataFrames that can be used to anamyze the data and compute some statistics. LICENSE ++++++++ This code is released under MIT licenseThe MIT License (MIT) Copyright (c) 2015 Marco Bonvini 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 urllib2 import re import unicodedata from datetime import datetime from bs4 import BeautifulSoup, Tag import pandas as pd import numpy as np import json # Months and year ranges. Because the bulletins refer to fiscal year (FY), the first month is October. years = range(2003,2016) months = ['october','november','december','january','february','march','april','may','june','july','august','september'] # Initialize empty pandas DataFrames that will contain the final data for every continent df_europe = pd.DataFrame(np.NAN*np.zeros((len(months),len(years))), index = months, columns = years) df_africa = pd.DataFrame(np.NAN*np.zeros((len(months),len(years))), index = months, columns = years) df_asia = pd.DataFrame(np.NAN*np.zeros((len(months),len(years))), index = months, columns = years) df_oceania = pd.DataFrame(np.NAN*np.zeros((len(months),len(years))), index = months, columns = years) df_north_america = pd.DataFrame(np.NAN*np.zeros((len(months),len(years))), index = months, columns = years) df_south_america = pd.DataFrame(np.NAN*np.zeros((len(months),len(years))), index = months, columns = years) # When the table contains the string "Current", "current", "c" or "C" instead of the number, # replace it with a np.NaN in the DataFrames current_number = np.NaN # The pattern of the URL where one can fond the information about the DV lottery pattern = "http://travel.state.gov/content/visas/english/law-and-policy/bulletin/{0}/visa-bulletin{3}-{1}-{2}.html" # Iterate over all the years and months, generate the URLs and look for the # data regarding the DV lottery. For each year of each month multiple URLS are built. # This is necessary because the URLs haven't been managed in a consistent way over the years, # for example sometimes the month starts with a lowercase letter but in other cases it does not. for fy in years: for m in months: # Initialize list of URLs to check page_urls = [] # The months of Oct, Nov and Dec needs to be treated differently # because, for example, Oct 2014 belongs to FY 2015. if m in ['october','november','december']: page_urls.append(pattern.format(fy,m,fy-1,"-for")) page_urls.append(pattern.format(fy,m,fy-1,"")) page_urls.append(pattern.format(fy,m.title(),fy-1,"")) page_urls.append(pattern.format(fy,m.title(),fy-1,"-for")) else: page_urls.append(pattern.format(fy,m,fy,"-for")) page_urls.append(pattern.format(fy,m,fy,"")) page_urls.append(pattern.format(fy,m.title(),fy,"")) page_urls.append(pattern.format(fy,m.title(),fy,"-for")) # Test the URLs, verify if they're legitimate, and get the # content of the HTML page page_ok = False i = 0 while not page_ok and i<len(page_urls): print "Reading page: {0}".format(page_urls[i]) try: response = urllib2.urlopen(page_urls[i]) html_text = response.read() if "404 - Page Not Found" not in html_text: page_ok = True except urllib2.HTTPError, e: print "Failed reading the URL: {0}".format(page_urls[i]) print str(e) i += 1 # If there was a successful read, parse the HTML page and populate the # columns/rows of the pandas DataFrames if page_ok: soup = BeautifulSoup(html_text) soup.encode('utf-8') for tag in soup.find_all('script'): tag.replaceWith('') text = unicode(soup.get_text('|', strip=True)) text = text.encode('ascii',errors='ignore') text = re.sub(',','',text) text = re.sub('\\r','',text) text = re.sub('\\n','',text) text = re.sub(':','',text) text = re.sub('-','',text) text = re.sub('\s+','',text) text = text.lower() g_europe = re.search('(europe[|]*[\s*eu[r]*\s*]*[|]*(\d+|current|c))', text) if g_europe: df_europe[fy][m] = g_europe.groups()[1] if g_europe.groups()[1] not in ['c','current'] else current_number else: print "Missing Europe..." g_africa = re.search('(africa[|]*[\s]*[af]*[\s]*[|]*(\d+|current|c))', text) if g_africa: df_africa[fy][m] = g_africa.groups()[1] if g_africa.groups()[1] not in ['c','current'] else current_number else: print "Missing Africa..." g_oceania = re.search('(oceania[|]*[\s]*[oc]*[\s]*[|]*(\d+|current|c))', text) if g_oceania: df_oceania[fy][m] = g_oceania.groups()[1] if g_oceania.groups()[1] not in ['c','current'] else current_number else: print "Missing Oceania..." g_asia = re.search('(asia[|]*[\s]*[as]*[\s]*[|]*(\d+|current|c))', text) if g_asia: df_asia[fy][m] = g_asia.groups()[1] if g_asia.groups()[1] not in ['c','current'] else current_number else: print "Missing Asia..." g_north_america = re.search('(northamerica[|]*\(bahamas\)[|]*[\s]*[na]*[\s]*[|]*(\d+|current|c))', text) if g_north_america: df_north_america[fy][m] = g_north_america.groups()[1] if g_north_america.groups()[1] not in ['c','current'] else current_number else: print "Missing North America..." g_south_america = re.search('(southamerica[|]*and[|]*the[|]*caribbean[|]*[\s]*[sa]*[\s]*[|]*(\d+|current|c))', text) if g_south_america: df_south_america[fy][m] = g_south_america.groups()[1] if g_south_america.groups()[1] not in ['c','current'] else current_number else: print "Missing South America..." def convert_month_to_date(d): """ This function converts a string representing a month like ``october`` and converts it into a format like ``2015-10-01``. """ if d in ["october", "november", "december"]: return datetime.strptime(d+"-2014", "%B-%Y").strftime("%Y-%m-%d") else: return datetime.strptime(d+"-2015", "%B-%Y").strftime("%Y-%m-%d") # Export all the data in the data frames to JSON data_frames = [df_europe, df_africa, df_asia, df_oceania, df_north_america, df_south_america] data_names = ["europe", "africa", "asia", "oceania", "north_america", "south_america"] mean_df = pd.DataFrame() std_df = pd.DataFrame() min_df = pd.DataFrame() max_df = pd.DataFrame() for name, df in zip(data_names, data_frames): # Generate statistics for every DataFrame mean_df[name] = df.mean(axis = 1) std_df[name] = df.std(axis = 1) min_df[name] = df.min(axis = 1) max_df[name] = df.max(axis = 1) data = [] for mo in months: data_point = {"date": convert_month_to_date(mo)} for c in data_names: data_point["avg_"+c] = mean_df[c][mo] data_point["u_"+c] = mean_df[c][mo] + std_df[c][mo] data_point["l_"+c] = mean_df[c][mo] - std_df[c][mo] data_point["min_"+c] = min_df[c][mo] data_point["max_"+c] = max_df[c][mo] data.append(data_point) # Save the data in a JSON file with open("dv_lottery.json", "w") as fp: json.dump(data, fp, indent = 2)
mit
rohanp/scikit-learn
sklearn/tests/test_learning_curve.py
59
10869
# Author: Alexander Fabisch <[email protected]> # # License: BSD 3 clause import sys from sklearn.externals.six.moves import cStringIO as StringIO import numpy as np import warnings from sklearn.base import BaseEstimator from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_warns from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.datasets import make_classification with warnings.catch_warnings(): warnings.simplefilter('ignore') from sklearn.learning_curve import learning_curve, validation_curve from sklearn.cross_validation import KFold from sklearn.linear_model import PassiveAggressiveClassifier 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 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=30, 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)
bsd-3-clause
justincely/lightcurve_pipeline
setup.py
1
1816
from setuptools import setup from setuptools import find_packages # Command line scripts scripts = ['reset_hstlc_filesystem = lightcurve_pipeline.scripts.reset_hstlc_filesystem:main', 'reset_hstlc_database = lightcurve_pipeline.scripts.reset_hstlc_database:main', 'download_hstlc = lightcurve_pipeline.scripts.download_hstlc:main', 'ingest_hstlc = lightcurve_pipeline.scripts.ingest_hstlc:main', 'build_stats_table = lightcurve_pipeline.scripts.build_stats_table:main', 'make_hstlc_plots = lightcurve_pipeline.scripts.make_hstlc_plots:main'] entry_points = {} entry_points['console_scripts'] = scripts setup( name = 'lightcurve-pipeline', description = 'Create lightcurves from HST/COS and HST/STIS data', url = 'https://github.com/justincely/lightcurve_pipeline.git', author = 'Matthew Bourque', author_email = '[email protected]', keywords = ['astronomy'], classifiers = ['Programming Language :: Python', 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Physics', 'Topic :: Software Development :: Libraries :: Python Modules'], packages = find_packages(), install_requires = ['lightcurve>=0.6.0', 'numpy', 'scipy', 'astropy', 'sqlalchemy', 'pymysql', 'pyyaml', 'matplotlib', 'bokeh', 'pandas'], scripts = ['scripts/hstlc_pipeline'], entry_points = entry_points, version = 1.0 )
bsd-3-clause
ningchi/scikit-learn
sklearn/neighbors/tests/test_kd_tree.py
13
7914
import numpy as np from numpy.testing import assert_array_almost_equal from sklearn.neighbors.kd_tree import (KDTree, NeighborsHeap, simultaneous_sort, kernel_norm, nodeheap_sort, DTYPE, ITYPE) from sklearn.neighbors.dist_metrics import DistanceMetric from sklearn.utils.testing import SkipTest, assert_allclose V = np.random.random((3, 3)) V = np.dot(V, V.T) DIMENSION = 3 METRICS = {'euclidean': {}, 'manhattan': {}, 'chebyshev': {}, 'minkowski': dict(p=3)} def brute_force_neighbors(X, Y, k, metric, **kwargs): D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) ind = np.argsort(D, axis=1)[:, :k] dist = D[np.arange(Y.shape[0])[:, None], ind] return dist, ind def test_kd_tree_query(): np.random.seed(0) X = np.random.random((40, DIMENSION)) Y = np.random.random((10, DIMENSION)) def check_neighbors(dualtree, breadth_first, k, metric, kwargs): kdt = KDTree(X, leaf_size=1, metric=metric, **kwargs) dist1, ind1 = kdt.query(Y, k, dualtree=dualtree, breadth_first=breadth_first) dist2, ind2 = brute_force_neighbors(X, Y, k, metric, **kwargs) # don't check indices here: if there are any duplicate distances, # the indices may not match. Distances should not have this problem. assert_array_almost_equal(dist1, dist2) for (metric, kwargs) in METRICS.items(): for k in (1, 3, 5): for dualtree in (True, False): for breadth_first in (True, False): yield (check_neighbors, dualtree, breadth_first, k, metric, kwargs) def test_kd_tree_query_radius(n_samples=100, n_features=10): np.random.seed(0) X = 2 * np.random.random(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail kdt = KDTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind = kdt.query_radius(query_pt, r + eps)[0] i = np.where(rad <= r + eps)[0] ind.sort() i.sort() assert_array_almost_equal(i, ind) def test_kd_tree_query_radius_distance(n_samples=100, n_features=10): np.random.seed(0) X = 2 * np.random.random(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail kdt = KDTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind, dist = kdt.query_radius(query_pt, r + eps, return_distance=True) ind = ind[0] dist = dist[0] d = np.sqrt(((query_pt - X[ind]) ** 2).sum(1)) assert_array_almost_equal(d, dist) def compute_kernel_slow(Y, X, kernel, h): d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1)) norm = kernel_norm(h, X.shape[1], kernel) if kernel == 'gaussian': return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1) elif kernel == 'tophat': return norm * (d < h).sum(-1) elif kernel == 'epanechnikov': return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1) elif kernel == 'exponential': return norm * (np.exp(-d / h)).sum(-1) elif kernel == 'linear': return norm * ((1 - d / h) * (d < h)).sum(-1) elif kernel == 'cosine': return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1) else: raise ValueError('kernel not recognized') def test_kd_tree_kde(n_samples=100, n_features=3): np.random.seed(0) X = np.random.random((n_samples, n_features)) Y = np.random.random((n_samples, n_features)) kdt = KDTree(X, leaf_size=10) for kernel in ['gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', 'cosine']: for h in [0.01, 0.1, 1]: dens_true = compute_kernel_slow(Y, X, kernel, h) def check_results(kernel, h, atol, rtol, breadth_first): dens = kdt.kernel_density(Y, h, atol=atol, rtol=rtol, kernel=kernel, breadth_first=breadth_first) assert_allclose(dens, dens_true, atol=atol, rtol=max(rtol, 1e-7)) for rtol in [0, 1E-5]: for atol in [1E-6, 1E-2]: for breadth_first in (True, False): yield (check_results, kernel, h, atol, rtol, breadth_first) def test_gaussian_kde(n_samples=1000): # Compare gaussian KDE results to scipy.stats.gaussian_kde from scipy.stats import gaussian_kde np.random.seed(0) x_in = np.random.normal(0, 1, n_samples) x_out = np.linspace(-5, 5, 30) for h in [0.01, 0.1, 1]: kdt = KDTree(x_in[:, None]) try: gkde = gaussian_kde(x_in, bw_method=h / np.std(x_in)) except TypeError: raise SkipTest("Old scipy, does not accept explicit bandwidth.") dens_kdt = kdt.kernel_density(x_out[:, None], h) / n_samples dens_gkde = gkde.evaluate(x_out) assert_array_almost_equal(dens_kdt, dens_gkde, decimal=3) def test_kd_tree_two_point(n_samples=100, n_features=3): np.random.seed(0) X = np.random.random((n_samples, n_features)) Y = np.random.random((n_samples, n_features)) r = np.linspace(0, 1, 10) kdt = KDTree(X, leaf_size=10) D = DistanceMetric.get_metric("euclidean").pairwise(Y, X) counts_true = [(D <= ri).sum() for ri in r] def check_two_point(r, dualtree): counts = kdt.two_point_correlation(Y, r=r, dualtree=dualtree) assert_array_almost_equal(counts, counts_true) for dualtree in (True, False): yield check_two_point, r, dualtree def test_kd_tree_pickle(): import pickle np.random.seed(0) X = np.random.random((10, 3)) kdt1 = KDTree(X, leaf_size=1) ind1, dist1 = kdt1.query(X) def check_pickle_protocol(protocol): s = pickle.dumps(kdt1, protocol=protocol) kdt2 = pickle.loads(s) ind2, dist2 = kdt2.query(X) assert_array_almost_equal(ind1, ind2) assert_array_almost_equal(dist1, dist2) for protocol in (0, 1, 2): yield check_pickle_protocol, protocol def test_neighbors_heap(n_pts=5, n_nbrs=10): heap = NeighborsHeap(n_pts, n_nbrs) for row in range(n_pts): d_in = np.random.random(2 * n_nbrs).astype(DTYPE) i_in = np.arange(2 * n_nbrs, dtype=ITYPE) for d, i in zip(d_in, i_in): heap.push(row, d, i) ind = np.argsort(d_in) d_in = d_in[ind] i_in = i_in[ind] d_heap, i_heap = heap.get_arrays(sort=True) assert_array_almost_equal(d_in[:n_nbrs], d_heap[row]) assert_array_almost_equal(i_in[:n_nbrs], i_heap[row]) def test_node_heap(n_nodes=50): vals = np.random.random(n_nodes).astype(DTYPE) i1 = np.argsort(vals) vals2, i2 = nodeheap_sort(vals) assert_array_almost_equal(i1, i2) assert_array_almost_equal(vals[i1], vals2) def test_simultaneous_sort(n_rows=10, n_pts=201): dist = np.random.random((n_rows, n_pts)).astype(DTYPE) ind = (np.arange(n_pts) + np.zeros((n_rows, 1))).astype(ITYPE) dist2 = dist.copy() ind2 = ind.copy() # simultaneous sort rows using function simultaneous_sort(dist, ind) # simultaneous sort rows using numpy i = np.argsort(dist2, axis=1) row_ind = np.arange(n_rows)[:, None] dist2 = dist2[row_ind, i] ind2 = ind2[row_ind, i] assert_array_almost_equal(dist, dist2) assert_array_almost_equal(ind, ind2) if __name__ == '__main__': import nose nose.runmodule()
bsd-3-clause
LevinJ/ud730-Deep-Learning
A1_notmnistdataset/p5_findduplication.py
1
4322
import pickle import math import matplotlib.pyplot as plt import matplotlib.image as mpimg from A1_notmnistdataset import p2_checkimage class DataExploration: def __init__(self): with open('../A1_notmnistdataset/notMNIST_3.pickle', 'rb') as f: self.dataset = pickle.load(f) self.train_dataset = self.dataset['train_dataset'] self.train_labels = self.dataset['train_labels'] self.valid_dataset = self.dataset['valid_dataset'] self.valid_labels = self.dataset['valid_labels'] self.test_dataset = self.dataset['test_dataset'] self.test_labels = self.dataset['test_labels'] self.train_filepaths = self.dataset['train_filepaths'] self.test_filepaths = self.dataset['test_filepaths'] self.valid_filepaths = self.dataset['valid_filepaths'] # print('Training:', self.train_dataset.shape, self.train_labels.shape) # print('Validation:', self.valid_dataset.shape, self.valid_labels.shape) # print('Testing:', self.test_dataset.shape, self.test_labels.shape) return def checkDupwithin(self, images, groupname, image_paths=None): temp_dict = {} dup_dict={} images.flags.writeable = False count = 0 for idx, item in enumerate(images): if item.data in temp_dict: count = count + 1 # print("duplicate {}:{}".format(count, idx)) existingId = temp_dict[item.data] if not (existingId in dup_dict): dup_dict[existingId] = [] dup_dict[existingId].append(idx) continue temp_dict[item.data] = idx print("{} has {} duplicate items, {} total items".format(groupname, count, images.shape[0])) # print(dup_dict) images[dup_dict[25]] # di = dup_dict[128] # di = dup_dict[1018] # self.dispImages(image_paths[di], images[di]) return def checkDupBetween(self,datasetA, datasetB,lablesB, A,B, Apaths = None, Bpaths=None): temp_dict = {} dup_dict={} datasetA.flags.writeable = False datasetB.flags.writeable = False count = 0 #build up base table for datasetA in temp_dict for idx, item in enumerate(datasetA): if item.data in temp_dict: continue temp_dict[item.data] = idx for idx,img in enumerate(datasetB): if img.data in temp_dict: count = count + 1 existingId = temp_dict[img.data] if not (existingId in dup_dict): dup_dict[existingId] = [] dup_dict[existingId].append(idx) print("{} {} duplicate {}, total count {}, total count {}".format(A, B, count, datasetA.shape[0], datasetB.shape[0])) # print(Apaths[16812]) # print(Bpaths[dup_dict[16812]]) return def getDiffLableCount(self, dup_table, labelsB): count = 0 for key, value in dup_table.iteritems(): truelabels = [labelsB[item] for item in value] allthesame = all(truelabels[0] == item for item in truelabels) if not allthesame: count = count + 1 print(truelabels) return count def dispImages(self, filepaths, images): ci = p2_checkimage.CheckImage() ci.dispImages_filepath(filepaths, 1) ci.dispImages(images, 2) return def run(self): self.checkDupwithin(self.train_dataset,'train_dataset', self.train_filepaths) self.checkDupwithin(self.test_dataset,'test_dataset') self.checkDupwithin(self.valid_dataset,'validation_dataset') self.checkDupBetween(self.train_dataset, self.test_dataset,self.test_labels,'train_dataset','test_dataset', self.train_filepaths, self.test_filepaths) self.checkDupBetween(self.train_dataset, self.valid_dataset,self.test_labels,'train_dataset','validation_dataset') self.checkDupBetween(self.valid_dataset, self.test_dataset,self.test_labels,'validation_dataset','test_dataset') plt.show() return if __name__ == "__main__": obj= DataExploration() obj.run()
gpl-2.0
rajat1994/scikit-learn
sklearn/gaussian_process/gaussian_process.py
83
34544
# -*- coding: utf-8 -*- # Author: Vincent Dubourg <[email protected]> # (mostly translation, see implementation details) # Licence: BSD 3 clause from __future__ import print_function import numpy as np from scipy import linalg, optimize from ..base import BaseEstimator, RegressorMixin from ..metrics.pairwise import manhattan_distances from ..utils import check_random_state, check_array, check_X_y from ..utils.validation import check_is_fitted from . import regression_models as regression from . import correlation_models as correlation MACHINE_EPSILON = np.finfo(np.double).eps def l1_cross_distances(X): """ Computes the nonzero componentwise L1 cross-distances between the vectors in X. Parameters ---------- X: array_like An array with shape (n_samples, n_features) Returns ------- D: array with shape (n_samples * (n_samples - 1) / 2, n_features) The array of componentwise L1 cross-distances. ij: arrays with shape (n_samples * (n_samples - 1) / 2, 2) The indices i and j of the vectors in X associated to the cross- distances in D: D[k] = np.abs(X[ij[k, 0]] - Y[ij[k, 1]]). """ X = check_array(X) n_samples, n_features = X.shape n_nonzero_cross_dist = n_samples * (n_samples - 1) // 2 ij = np.zeros((n_nonzero_cross_dist, 2), dtype=np.int) D = np.zeros((n_nonzero_cross_dist, n_features)) ll_1 = 0 for k in range(n_samples - 1): ll_0 = ll_1 ll_1 = ll_0 + n_samples - k - 1 ij[ll_0:ll_1, 0] = k ij[ll_0:ll_1, 1] = np.arange(k + 1, n_samples) D[ll_0:ll_1] = np.abs(X[k] - X[(k + 1):n_samples]) return D, ij class GaussianProcess(BaseEstimator, RegressorMixin): """The Gaussian Process model class. Read more in the :ref:`User Guide <gaussian_process>`. Parameters ---------- regr : string or callable, optional A regression function returning an array of outputs of the linear regression functional basis. The number of observations n_samples should be greater than the size p of this basis. Default assumes a simple constant regression trend. Available built-in regression models are:: 'constant', 'linear', 'quadratic' corr : string or callable, optional A stationary autocorrelation function returning the autocorrelation between two points x and x'. Default assumes a squared-exponential autocorrelation model. Built-in correlation models are:: 'absolute_exponential', 'squared_exponential', 'generalized_exponential', 'cubic', 'linear' beta0 : double array_like, optional The regression weight vector to perform Ordinary Kriging (OK). Default assumes Universal Kriging (UK) so that the vector beta of regression weights is estimated using the maximum likelihood principle. storage_mode : string, optional A string specifying whether the Cholesky decomposition of the correlation matrix should be stored in the class (storage_mode = 'full') or not (storage_mode = 'light'). Default assumes storage_mode = 'full', so that the Cholesky decomposition of the correlation matrix is stored. This might be a useful parameter when one is not interested in the MSE and only plan to estimate the BLUP, for which the correlation matrix is not required. verbose : boolean, optional A boolean specifying the verbose level. Default is verbose = False. theta0 : double array_like, optional An array with shape (n_features, ) or (1, ). The parameters in the autocorrelation model. If thetaL and thetaU are also specified, theta0 is considered as the starting point for the maximum likelihood estimation of the best set of parameters. Default assumes isotropic autocorrelation model with theta0 = 1e-1. thetaL : double array_like, optional An array with shape matching theta0's. Lower bound on the autocorrelation parameters for maximum likelihood estimation. Default is None, so that it skips maximum likelihood estimation and it uses theta0. thetaU : double array_like, optional An array with shape matching theta0's. Upper bound on the autocorrelation parameters for maximum likelihood estimation. Default is None, so that it skips maximum likelihood estimation and it uses theta0. normalize : boolean, optional Input X and observations y are centered and reduced wrt means and standard deviations estimated from the n_samples observations provided. Default is normalize = True so that data is normalized to ease maximum likelihood estimation. nugget : double or ndarray, optional Introduce a nugget effect to allow smooth predictions from noisy data. If nugget is an ndarray, it must be the same length as the number of data points used for the fit. The nugget is added to the diagonal of the assumed training covariance; in this way it acts as a Tikhonov regularization in the problem. In the special case of the squared exponential correlation function, the nugget mathematically represents the variance of the input values. Default assumes a nugget close to machine precision for the sake of robustness (nugget = 10. * MACHINE_EPSILON). optimizer : string, optional A string specifying the optimization algorithm to be used. Default uses 'fmin_cobyla' algorithm from scipy.optimize. Available optimizers are:: 'fmin_cobyla', 'Welch' 'Welch' optimizer is dued to Welch et al., see reference [WBSWM1992]_. It consists in iterating over several one-dimensional optimizations instead of running one single multi-dimensional optimization. random_start : int, optional The number of times the Maximum Likelihood Estimation should be performed from a random starting point. The first MLE always uses the specified starting point (theta0), the next starting points are picked at random according to an exponential distribution (log-uniform on [thetaL, thetaU]). Default does not use random starting point (random_start = 1). random_state: integer or numpy.RandomState, optional The generator used to shuffle the sequence of coordinates of theta in the Welch optimizer. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- theta_ : array Specified theta OR the best set of autocorrelation parameters (the \ sought maximizer of the reduced likelihood function). reduced_likelihood_function_value_ : array The optimal reduced likelihood function value. Examples -------- >>> import numpy as np >>> from sklearn.gaussian_process import GaussianProcess >>> X = np.array([[1., 3., 5., 6., 7., 8.]]).T >>> y = (X * np.sin(X)).ravel() >>> gp = GaussianProcess(theta0=0.1, thetaL=.001, thetaU=1.) >>> gp.fit(X, y) # doctest: +ELLIPSIS GaussianProcess(beta0=None... ... Notes ----- The presentation implementation is based on a translation of the DACE Matlab toolbox, see reference [NLNS2002]_. References ---------- .. [NLNS2002] `H.B. Nielsen, S.N. Lophaven, H. B. Nielsen and J. Sondergaard. DACE - A MATLAB Kriging Toolbox.` (2002) http://www2.imm.dtu.dk/~hbn/dace/dace.pdf .. [WBSWM1992] `W.J. Welch, R.J. Buck, J. Sacks, H.P. Wynn, T.J. Mitchell, and M.D. Morris (1992). Screening, predicting, and computer experiments. Technometrics, 34(1) 15--25.` http://www.jstor.org/pss/1269548 """ _regression_types = { 'constant': regression.constant, 'linear': regression.linear, 'quadratic': regression.quadratic} _correlation_types = { 'absolute_exponential': correlation.absolute_exponential, 'squared_exponential': correlation.squared_exponential, 'generalized_exponential': correlation.generalized_exponential, 'cubic': correlation.cubic, 'linear': correlation.linear} _optimizer_types = [ 'fmin_cobyla', 'Welch'] def __init__(self, regr='constant', corr='squared_exponential', beta0=None, storage_mode='full', verbose=False, theta0=1e-1, thetaL=None, thetaU=None, optimizer='fmin_cobyla', random_start=1, normalize=True, nugget=10. * MACHINE_EPSILON, random_state=None): self.regr = regr self.corr = corr self.beta0 = beta0 self.storage_mode = storage_mode self.verbose = verbose self.theta0 = theta0 self.thetaL = thetaL self.thetaU = thetaU self.normalize = normalize self.nugget = nugget self.optimizer = optimizer self.random_start = random_start self.random_state = random_state def fit(self, X, y): """ The Gaussian Process model fitting method. Parameters ---------- X : double array_like An array with shape (n_samples, n_features) with the input at which observations were made. y : double array_like An array with shape (n_samples, ) or shape (n_samples, n_targets) with the observations of the output to be predicted. Returns ------- gp : self A fitted Gaussian Process model object awaiting data to perform predictions. """ # Run input checks self._check_params() self.random_state = check_random_state(self.random_state) # Force data to 2D numpy.array X, y = check_X_y(X, y, multi_output=True, y_numeric=True) self.y_ndim_ = y.ndim if y.ndim == 1: y = y[:, np.newaxis] # Check shapes of DOE & observations n_samples, n_features = X.shape _, n_targets = y.shape # Run input checks self._check_params(n_samples) # Normalize data or don't if self.normalize: X_mean = np.mean(X, axis=0) X_std = np.std(X, axis=0) y_mean = np.mean(y, axis=0) y_std = np.std(y, axis=0) X_std[X_std == 0.] = 1. y_std[y_std == 0.] = 1. # center and scale X if necessary X = (X - X_mean) / X_std y = (y - y_mean) / y_std else: X_mean = np.zeros(1) X_std = np.ones(1) y_mean = np.zeros(1) y_std = np.ones(1) # Calculate matrix of distances D between samples D, ij = l1_cross_distances(X) if (np.min(np.sum(D, axis=1)) == 0. and self.corr != correlation.pure_nugget): raise Exception("Multiple input features cannot have the same" " target value.") # Regression matrix and parameters F = self.regr(X) n_samples_F = F.shape[0] if F.ndim > 1: p = F.shape[1] else: p = 1 if n_samples_F != n_samples: raise Exception("Number of rows in F and X do not match. Most " "likely something is going wrong with the " "regression model.") if p > n_samples_F: raise Exception(("Ordinary least squares problem is undetermined " "n_samples=%d must be greater than the " "regression model size p=%d.") % (n_samples, p)) if self.beta0 is not None: if self.beta0.shape[0] != p: raise Exception("Shapes of beta0 and F do not match.") # Set attributes self.X = X self.y = y self.D = D self.ij = ij self.F = F self.X_mean, self.X_std = X_mean, X_std self.y_mean, self.y_std = y_mean, y_std # Determine Gaussian Process model parameters if self.thetaL is not None and self.thetaU is not None: # Maximum Likelihood Estimation of the parameters if self.verbose: print("Performing Maximum Likelihood Estimation of the " "autocorrelation parameters...") self.theta_, self.reduced_likelihood_function_value_, par = \ self._arg_max_reduced_likelihood_function() if np.isinf(self.reduced_likelihood_function_value_): raise Exception("Bad parameter region. " "Try increasing upper bound") else: # Given parameters if self.verbose: print("Given autocorrelation parameters. " "Computing Gaussian Process model parameters...") self.theta_ = self.theta0 self.reduced_likelihood_function_value_, par = \ self.reduced_likelihood_function() if np.isinf(self.reduced_likelihood_function_value_): raise Exception("Bad point. Try increasing theta0.") self.beta = par['beta'] self.gamma = par['gamma'] self.sigma2 = par['sigma2'] self.C = par['C'] self.Ft = par['Ft'] self.G = par['G'] if self.storage_mode == 'light': # Delete heavy data (it will be computed again if required) # (it is required only when MSE is wanted in self.predict) if self.verbose: print("Light storage mode specified. " "Flushing autocorrelation matrix...") self.D = None self.ij = None self.F = None self.C = None self.Ft = None self.G = None return self def predict(self, X, eval_MSE=False, batch_size=None): """ This function evaluates the Gaussian Process model at x. Parameters ---------- X : array_like An array with shape (n_eval, n_features) giving the point(s) at which the prediction(s) should be made. eval_MSE : boolean, optional A boolean specifying whether the Mean Squared Error should be evaluated or not. Default assumes evalMSE = False and evaluates only the BLUP (mean prediction). batch_size : integer, optional An integer giving the maximum number of points that can be evaluated simultaneously (depending on the available memory). Default is None so that all given points are evaluated at the same time. Returns ------- y : array_like, shape (n_samples, ) or (n_samples, n_targets) An array with shape (n_eval, ) if the Gaussian Process was trained on an array of shape (n_samples, ) or an array with shape (n_eval, n_targets) if the Gaussian Process was trained on an array of shape (n_samples, n_targets) with the Best Linear Unbiased Prediction at x. MSE : array_like, optional (if eval_MSE == True) An array with shape (n_eval, ) or (n_eval, n_targets) as with y, with the Mean Squared Error at x. """ check_is_fitted(self, "X") # Check input shapes X = check_array(X) n_eval, _ = X.shape n_samples, n_features = self.X.shape n_samples_y, n_targets = self.y.shape # Run input checks self._check_params(n_samples) if X.shape[1] != n_features: raise ValueError(("The number of features in X (X.shape[1] = %d) " "should match the number of features used " "for fit() " "which is %d.") % (X.shape[1], n_features)) if batch_size is None: # No memory management # (evaluates all given points in a single batch run) # Normalize input X = (X - self.X_mean) / self.X_std # Initialize output y = np.zeros(n_eval) if eval_MSE: MSE = np.zeros(n_eval) # Get pairwise componentwise L1-distances to the input training set dx = manhattan_distances(X, Y=self.X, sum_over_features=False) # Get regression function and correlation f = self.regr(X) r = self.corr(self.theta_, dx).reshape(n_eval, n_samples) # Scaled predictor y_ = np.dot(f, self.beta) + np.dot(r, self.gamma) # Predictor y = (self.y_mean + self.y_std * y_).reshape(n_eval, n_targets) if self.y_ndim_ == 1: y = y.ravel() # Mean Squared Error if eval_MSE: C = self.C if C is None: # Light storage mode (need to recompute C, F, Ft and G) if self.verbose: print("This GaussianProcess used 'light' storage mode " "at instantiation. Need to recompute " "autocorrelation matrix...") reduced_likelihood_function_value, par = \ self.reduced_likelihood_function() self.C = par['C'] self.Ft = par['Ft'] self.G = par['G'] rt = linalg.solve_triangular(self.C, r.T, lower=True) if self.beta0 is None: # Universal Kriging u = linalg.solve_triangular(self.G.T, np.dot(self.Ft.T, rt) - f.T, lower=True) else: # Ordinary Kriging u = np.zeros((n_targets, n_eval)) MSE = np.dot(self.sigma2.reshape(n_targets, 1), (1. - (rt ** 2.).sum(axis=0) + (u ** 2.).sum(axis=0))[np.newaxis, :]) MSE = np.sqrt((MSE ** 2.).sum(axis=0) / n_targets) # Mean Squared Error might be slightly negative depending on # machine precision: force to zero! MSE[MSE < 0.] = 0. if self.y_ndim_ == 1: MSE = MSE.ravel() return y, MSE else: return y else: # Memory management if type(batch_size) is not int or batch_size <= 0: raise Exception("batch_size must be a positive integer") if eval_MSE: y, MSE = np.zeros(n_eval), np.zeros(n_eval) for k in range(max(1, n_eval / batch_size)): batch_from = k * batch_size batch_to = min([(k + 1) * batch_size + 1, n_eval + 1]) y[batch_from:batch_to], MSE[batch_from:batch_to] = \ self.predict(X[batch_from:batch_to], eval_MSE=eval_MSE, batch_size=None) return y, MSE else: y = np.zeros(n_eval) for k in range(max(1, n_eval / batch_size)): batch_from = k * batch_size batch_to = min([(k + 1) * batch_size + 1, n_eval + 1]) y[batch_from:batch_to] = \ self.predict(X[batch_from:batch_to], eval_MSE=eval_MSE, batch_size=None) return y def reduced_likelihood_function(self, theta=None): """ This function determines the BLUP parameters and evaluates the reduced likelihood function for the given autocorrelation parameters theta. Maximizing this function wrt the autocorrelation parameters theta is equivalent to maximizing the likelihood of the assumed joint Gaussian distribution of the observations y evaluated onto the design of experiments X. Parameters ---------- theta : array_like, optional An array containing the autocorrelation parameters at which the Gaussian Process model parameters should be determined. Default uses the built-in autocorrelation parameters (ie ``theta = self.theta_``). Returns ------- reduced_likelihood_function_value : double The value of the reduced likelihood function associated to the given autocorrelation parameters theta. par : dict A dictionary containing the requested Gaussian Process model parameters: sigma2 Gaussian Process variance. beta Generalized least-squares regression weights for Universal Kriging or given beta0 for Ordinary Kriging. gamma Gaussian Process weights. C Cholesky decomposition of the correlation matrix [R]. Ft Solution of the linear equation system : [R] x Ft = F G QR decomposition of the matrix Ft. """ check_is_fitted(self, "X") if theta is None: # Use built-in autocorrelation parameters theta = self.theta_ # Initialize output reduced_likelihood_function_value = - np.inf par = {} # Retrieve data n_samples = self.X.shape[0] D = self.D ij = self.ij F = self.F if D is None: # Light storage mode (need to recompute D, ij and F) D, ij = l1_cross_distances(self.X) if (np.min(np.sum(D, axis=1)) == 0. and self.corr != correlation.pure_nugget): raise Exception("Multiple X are not allowed") F = self.regr(self.X) # Set up R r = self.corr(theta, D) R = np.eye(n_samples) * (1. + self.nugget) R[ij[:, 0], ij[:, 1]] = r R[ij[:, 1], ij[:, 0]] = r # Cholesky decomposition of R try: C = linalg.cholesky(R, lower=True) except linalg.LinAlgError: return reduced_likelihood_function_value, par # Get generalized least squares solution Ft = linalg.solve_triangular(C, F, lower=True) try: Q, G = linalg.qr(Ft, econ=True) except: #/usr/lib/python2.6/dist-packages/scipy/linalg/decomp.py:1177: # DeprecationWarning: qr econ argument will be removed after scipy # 0.7. The economy transform will then be available through the # mode='economic' argument. Q, G = linalg.qr(Ft, mode='economic') pass sv = linalg.svd(G, compute_uv=False) rcondG = sv[-1] / sv[0] if rcondG < 1e-10: # Check F sv = linalg.svd(F, compute_uv=False) condF = sv[0] / sv[-1] if condF > 1e15: raise Exception("F is too ill conditioned. Poor combination " "of regression model and observations.") else: # Ft is too ill conditioned, get out (try different theta) return reduced_likelihood_function_value, par Yt = linalg.solve_triangular(C, self.y, lower=True) if self.beta0 is None: # Universal Kriging beta = linalg.solve_triangular(G, np.dot(Q.T, Yt)) else: # Ordinary Kriging beta = np.array(self.beta0) rho = Yt - np.dot(Ft, beta) sigma2 = (rho ** 2.).sum(axis=0) / n_samples # The determinant of R is equal to the squared product of the diagonal # elements of its Cholesky decomposition C detR = (np.diag(C) ** (2. / n_samples)).prod() # Compute/Organize output reduced_likelihood_function_value = - sigma2.sum() * detR par['sigma2'] = sigma2 * self.y_std ** 2. par['beta'] = beta par['gamma'] = linalg.solve_triangular(C.T, rho) par['C'] = C par['Ft'] = Ft par['G'] = G return reduced_likelihood_function_value, par def _arg_max_reduced_likelihood_function(self): """ This function estimates the autocorrelation parameters theta as the maximizer of the reduced likelihood function. (Minimization of the opposite reduced likelihood function is used for convenience) Parameters ---------- self : All parameters are stored in the Gaussian Process model object. Returns ------- optimal_theta : array_like The best set of autocorrelation parameters (the sought maximizer of the reduced likelihood function). optimal_reduced_likelihood_function_value : double The optimal reduced likelihood function value. optimal_par : dict The BLUP parameters associated to thetaOpt. """ # Initialize output best_optimal_theta = [] best_optimal_rlf_value = [] best_optimal_par = [] if self.verbose: print("The chosen optimizer is: " + str(self.optimizer)) if self.random_start > 1: print(str(self.random_start) + " random starts are required.") percent_completed = 0. # Force optimizer to fmin_cobyla if the model is meant to be isotropic if self.optimizer == 'Welch' and self.theta0.size == 1: self.optimizer = 'fmin_cobyla' if self.optimizer == 'fmin_cobyla': def minus_reduced_likelihood_function(log10t): return - self.reduced_likelihood_function( theta=10. ** log10t)[0] constraints = [] for i in range(self.theta0.size): constraints.append(lambda log10t, i=i: log10t[i] - np.log10(self.thetaL[0, i])) constraints.append(lambda log10t, i=i: np.log10(self.thetaU[0, i]) - log10t[i]) for k in range(self.random_start): if k == 0: # Use specified starting point as first guess theta0 = self.theta0 else: # Generate a random starting point log10-uniformly # distributed between bounds log10theta0 = (np.log10(self.thetaL) + self.random_state.rand(*self.theta0.shape) * np.log10(self.thetaU / self.thetaL)) theta0 = 10. ** log10theta0 # Run Cobyla try: log10_optimal_theta = \ optimize.fmin_cobyla(minus_reduced_likelihood_function, np.log10(theta0).ravel(), constraints, iprint=0) except ValueError as ve: print("Optimization failed. Try increasing the ``nugget``") raise ve optimal_theta = 10. ** log10_optimal_theta optimal_rlf_value, optimal_par = \ self.reduced_likelihood_function(theta=optimal_theta) # Compare the new optimizer to the best previous one if k > 0: if optimal_rlf_value > best_optimal_rlf_value: best_optimal_rlf_value = optimal_rlf_value best_optimal_par = optimal_par best_optimal_theta = optimal_theta else: best_optimal_rlf_value = optimal_rlf_value best_optimal_par = optimal_par best_optimal_theta = optimal_theta if self.verbose and self.random_start > 1: if (20 * k) / self.random_start > percent_completed: percent_completed = (20 * k) / self.random_start print("%s completed" % (5 * percent_completed)) optimal_rlf_value = best_optimal_rlf_value optimal_par = best_optimal_par optimal_theta = best_optimal_theta elif self.optimizer == 'Welch': # Backup of the given atrributes theta0, thetaL, thetaU = self.theta0, self.thetaL, self.thetaU corr = self.corr verbose = self.verbose # This will iterate over fmin_cobyla optimizer self.optimizer = 'fmin_cobyla' self.verbose = False # Initialize under isotropy assumption if verbose: print("Initialize under isotropy assumption...") self.theta0 = check_array(self.theta0.min()) self.thetaL = check_array(self.thetaL.min()) self.thetaU = check_array(self.thetaU.max()) theta_iso, optimal_rlf_value_iso, par_iso = \ self._arg_max_reduced_likelihood_function() optimal_theta = theta_iso + np.zeros(theta0.shape) # Iterate over all dimensions of theta allowing for anisotropy if verbose: print("Now improving allowing for anisotropy...") for i in self.random_state.permutation(theta0.size): if verbose: print("Proceeding along dimension %d..." % (i + 1)) self.theta0 = check_array(theta_iso) self.thetaL = check_array(thetaL[0, i]) self.thetaU = check_array(thetaU[0, i]) def corr_cut(t, d): return corr(check_array(np.hstack([optimal_theta[0][0:i], t[0], optimal_theta[0][(i + 1)::]])), d) self.corr = corr_cut optimal_theta[0, i], optimal_rlf_value, optimal_par = \ self._arg_max_reduced_likelihood_function() # Restore the given atrributes self.theta0, self.thetaL, self.thetaU = theta0, thetaL, thetaU self.corr = corr self.optimizer = 'Welch' self.verbose = verbose else: raise NotImplementedError("This optimizer ('%s') is not " "implemented yet. Please contribute!" % self.optimizer) return optimal_theta, optimal_rlf_value, optimal_par def _check_params(self, n_samples=None): # Check regression model if not callable(self.regr): if self.regr in self._regression_types: self.regr = self._regression_types[self.regr] else: raise ValueError("regr should be one of %s or callable, " "%s was given." % (self._regression_types.keys(), self.regr)) # Check regression weights if given (Ordinary Kriging) if self.beta0 is not None: self.beta0 = check_array(self.beta0) if self.beta0.shape[1] != 1: # Force to column vector self.beta0 = self.beta0.T # Check correlation model if not callable(self.corr): if self.corr in self._correlation_types: self.corr = self._correlation_types[self.corr] else: raise ValueError("corr should be one of %s or callable, " "%s was given." % (self._correlation_types.keys(), self.corr)) # Check storage mode if self.storage_mode != 'full' and self.storage_mode != 'light': raise ValueError("Storage mode should either be 'full' or " "'light', %s was given." % self.storage_mode) # Check correlation parameters self.theta0 = check_array(self.theta0) lth = self.theta0.size if self.thetaL is not None and self.thetaU is not None: self.thetaL = check_array(self.thetaL) self.thetaU = check_array(self.thetaU) if self.thetaL.size != lth or self.thetaU.size != lth: raise ValueError("theta0, thetaL and thetaU must have the " "same length.") if np.any(self.thetaL <= 0) or np.any(self.thetaU < self.thetaL): raise ValueError("The bounds must satisfy O < thetaL <= " "thetaU.") elif self.thetaL is None and self.thetaU is None: if np.any(self.theta0 <= 0): raise ValueError("theta0 must be strictly positive.") elif self.thetaL is None or self.thetaU is None: raise ValueError("thetaL and thetaU should either be both or " "neither specified.") # Force verbose type to bool self.verbose = bool(self.verbose) # Force normalize type to bool self.normalize = bool(self.normalize) # Check nugget value self.nugget = np.asarray(self.nugget) if np.any(self.nugget) < 0.: raise ValueError("nugget must be positive or zero.") if (n_samples is not None and self.nugget.shape not in [(), (n_samples,)]): raise ValueError("nugget must be either a scalar " "or array of length n_samples.") # Check optimizer if self.optimizer not in self._optimizer_types: raise ValueError("optimizer should be one of %s" % self._optimizer_types) # Force random_start type to int self.random_start = int(self.random_start)
bsd-3-clause
conorkcorbin/tractometry
call_stats.py
1
1798
from stats import bundleModel import nibabel as nib import pandas as pd import argparse import numpy as np from dipy.tracking.streamline import set_number_of_points parser = argparse.ArgumentParser() parser.add_argument('-templateBundle', '--templateBundle', required = True) parser.add_argument('-bundleName', '--bundleName', required = True) parser.add_argument('-metricName', '--metricName', required = True) parser.add_argument('-subjectInfo', '--subjectInfo', required = True) parser.add_argument('-metrics', '--metrics', required = True) parser.add_argument('-alpha', '--alpha', type=float, required = True) parser.add_argument('-out', '--out', required = True) parser.add_argument('-outPvals', '--outPvals', required = True) args = parser.parse_args() tracks, hdr = nib.trackvis.read(args.templateBundle) streamlines = [trk[0] for trk in tracks] streamlines = set_number_of_points(streamlines,50) subjectInfo = pd.read_csv(args.subjectInfo) metrics = pd.read_csv(args.metrics) ### START EDITING HERE # EDIT TO INCLUDE SUBJECT INFO YOU WANT TO REGRESS (JUST ADD THE COLUMN NAMES LIKE SHOWN BELOW) subjectInfo = subjectInfo[['Group','Age','Sex','IntracranialVolume']] # CONVERT ANY CATEGORICAL VARIABLES TO DUMMMY VARIABLES LIKE SO subjectInfo['Group'] = [1 if g == 'PD' else 0 for g in subjectInfo['Group'].values] subjectInfo['Sex'] = [1 if g == 'M' else 0 for g in subjectInfo['Sex'].values] covariate2project = 'Group' # This is the variable whose p values you want on the tracks ### STOP EDITTING HERE bm = bundleModel(subjectInfo, metrics, streamlines, hdr, args.bundleName, args.metricName, args.alpha) bm.regress() bm.correct() tracks = bm.project2Tracks(covariate2project) nib.trackvis.write(args.out,tracks,hdr) np.savez(args.outPvals,bm.pvalues)
mit
phoebe-project/phoebe2
phoebe/dependencies/autofig/call.py
1
114666
import numpy as np import astropy.units as u import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import LineCollection, PolyCollection from mpl_toolkits.mplot3d.art3d import Line3DCollection, Poly3DCollection from . import common from . import callbacks def _map_none(value): if isinstance(value, str): if value.lower() == 'none': return 'None' else: return value else: # NOTE: including None - we want this to fallback on the cycler return value def _to_linebreak_list(thing, N=1): if isinstance(thing, list): return thing else: return [thing]*N class CallGroup(common.Group): def __init__(self, items): super(CallGroup, self).__init__(Call, [], items) @property def callbacks(self): """ Returns --------- * (list) a list of <autofig.call.Call.callbacks> for each child <autofig.call.Call> """ return self._get_attrs('callbacks') def connect_callback(self, callback): for call in self._items: call.connect_callback(callback) @property def i(self): """ Returns --------- * (list) a list of <autofig.call.Call.i> for each child <autofig.call.Call> """ return CallDimensionGroup(self._get_attrs('i')) @property def x(self): """ Returns --------- * (list) a list of <autofig.call.Call.x> for each child <autofig.call.Call> """ return CallDimensionGroup(self._get_attrs('x')) @property def y(self): """ Returns --------- * (list) a list of <autofig.call.Call.y> for each child <autofig.call.Call> """ return CallDimensionGroup(self._get_attrs('y')) @property def z(self): """ Returns --------- * (list) a list of <autofig.call.Call.z> for each child <autofig.call.Call> """ return CallDimensionGroup(self._get_attrs('z')) @property def consider_for_limits(self): """ Returns --------- * (list) a list of <autofig.call.Call.consider_for_limits> for each child <autofig.call.Call> """ return self._get_attrs('consider_for_limits') @consider_for_limits.setter def consider_for_limits(self, consider_for_limits): return self._set_attrs('consider_for_limits', consider_for_limits) def draw(self, *args, **kwargs): """ Calls <autofig.call.Plot.draw> or <autofig.call.Mesh.draw> for each <autofig.call.Call> in the <autofig.call.CallGroup>. See also: * <autofig.draw> * <autofig.figure.Figure.draw> * <autofig.axes.Axes.draw> * <autofig.call.Plot.draw> * <autofig.call.Mesh.draw> Arguments ------------ * `*args`: all arguments are passed on to each <autofig.call.Call>. * `**kwargs`: all keyword arguments are passed on to each <autofig.call.Call>. Returns ----------- * (list): list of all created matplotlib artists """ # CallGroup.draw return_artists = [] for call in self._items: artists = call.draw(*args, **kwargs) return_artists += artists return return_artists class PlotGroup(CallGroup): @property def s(self): """ Returns --------- * (list) a list of <autofig.call.Plot.s> for each child <autofig.call.Plot> """ return CallDimensionSGroup(self._get_attrs('s')) @property def c(self): """ Returns --------- * (list) a list of <autofig.call.Plot.c> for each child <autofig.call.Plot> """ return CallDimensionCGroup(self._get_attrs('c')) @property def size_scale(self): """ Returns --------- * (list) a list of <autofig.call.Plot.size_scale> for each child <autofig.call.Plot> """ return self._get_attrs('size_scale') @size_scale.setter def size_scale(self, size_scale): return self._set_attrs('size_scale', size_scale) class MeshGroup(CallGroup): @property def fc(self): """ Returns --------- * (list) a list of <autofig.call.Mesh.fc> for each child <autofig.call.Mesh> """ return CallDimensionCGroup(self._get_attrs('fc')) @property def ec(self): """ Returns --------- * (list) a list of <autofig.call.Mesh.ec> for each child <autofig.call.Mesh> """ return CallDimensionCGroup(self._get_attrs('ec')) def make_callgroup(items): if np.all([isinstance(item, Plot) for item in items]): return PlotGroup(items) elif np.all([isinstance(item, Mesh) for item in items]): return MeshGroup(items) else: return CallGroup(items) class Call(object): def __init__(self, x=None, y=None, z=None, i=None, xerror=None, xunit=None, xlabel=None, xnormals=None, yerror=None, yunit=None, ylabel=None, ynormals=None, zerror=None, zunit=None, zlabel=None, znormals=None, iunit=None, itol=0.0, axorder=None, axpos=None, title=None, label=None, consider_for_limits=True, uncover=False, trail=False, **kwargs): """ Create a <autofig.call.Call> object which defines a single call to matplotlib. Arguments ------------- * `x` (list/array, optional, default=None): array of values for the x-axes. Access via <autofig.call.Call.x>. * `y` (list/array, optional, default=None): array of values for the y-axes. Access via <autofig.call.Call.y>. * `z` (list/array, optional, default=None): array of values for the z-axes. Access via <autofig.call.Call.z> * `i` (list/array or string, optional, default=None): array of values for the independent-variable. If a string, can be one of: 'x', 'y', 'z' to reference an existing array. Access via <autofig.call.Call.i>. * `xerror` (float or list/array, optional, default=None): errors for `x`. See <autofig.call.Call.x> and <autofig.call.CallDimensionX.error>. * `xunit` (string or astropy unit, optional, default=None): units for `x`. See <autofig.call.Call.x> and <autofig.call.CallDimensionX.unit>. * `xlabel` (strong, optional, default=None): label for `x`. See <autofig.call.Call.x> and <autofig.call.CallDimensionX.label>. * `xnormals` (list/array, optional, default=None): normals for `x`. Currently ignored. * `yerror` (float or list/array, optional, default=None): errors for `y`. See <autofig.call.Call.y> and <autofig.call.CallDimensionY.error>. * `yunit` (string or astropy unit, optional, default=None): units for `y`. See <autofig.call.Call.y> and <autofig.call.CallDimensionY.unit>. * `ylabel` (strong, optional, default=None): label for `y`. See <autofig.call.Call.y> and <autofig.call.CallDimensionY.label>. * `ynormals` (list/array, optional, default=None): normals for `y`. Currently ignored. * `zerror` (float or list/array, optional, default=None): errors for `z`. See <autofig.call.Call.z> and <autofig.call.CallDimensionZ.error>. * `zunit` (string or astropy unit, optional, default=None): units for `z`. See <autofig.call.Call.z> and <autofig.call.CallDimensionZ.unit>. * `zlabel` (strong, optional, default=None): label for `x`. See <autofig.call.Call.z> and <autofig.call.CallDimensionZ.label>. * `znormals` (list/array, optional, default=None): normals for `z`. Currently only used for <autofig.call.Mesh>. * `iunit` (string or astropy unit, optional, default=None): units for `i`. See <autofig.call.Call.i> and <autofig.call.CallDimensionI.unit>. * `itol` (float, optional, default=0.0): see <autofig.call.DimensionI.tol>. * `axorder` (int, optional, default=None): see <autofig.call.Call.axorder>. * `axpos` (tuple, optional, default=None): see <autofig.call.Call.axpos>. * `title` (string, optional, default=None): see <autofig.call.Call.title>. * `label` (string, optional, default=None): see <autofig.call.Call.label>. * `consider_for_limits` (bool, optional, default=True): see <autofig.call.Call.consider_for_limits>. * `uncover` (bool, optional, default=False): see <autofig.call.Call.uncover>. * `trail` (bool or Float, optional, default=False): see <autofig.call.Call.trail>. * `**kwargs`: additional keyword arguments are stored and passed on when attaching to a parent axes. See <autofig.axes.Axes.add_call>. Returns --------- * the instantiated <autofig.call.Call> object. """ self._class = 'Call' # just to avoid circular import in order to use isinstance self._axes = None self._backend_objects = [] self._callbacks = [] self._x = CallDimensionX(self, x, xerror, xunit, xlabel, xnormals) self._y = CallDimensionY(self, y, yerror, yunit, ylabel, ynormals) self._z = CallDimensionZ(self, z, zerror, zunit, zlabel, znormals) # defined last so all other dimensions are in place in case indep # is a reference and needs to access units, etc self._i = CallDimensionI(self, i, iunit, itol) self.consider_for_limits = consider_for_limits self.uncover = uncover self.trail = trail self.axorder = axorder self.axpos = axpos self.title = title self.label = label self.kwargs = kwargs # TODO: add style def _get_backend_object(): return self._backend_artists @property def callbacks(self): return self._callbacks def connect_callback(self, callback): if not isinstance(callback, str): callback = callback.__name__ if callback not in self.callbacks: self._callbacks.append(callback) @property def axes(self): """ Returns -------- * (<autofig.axes.Axes> or None): the parent axes, if applicable. """ # no setter as this can only be set internally when attaching to an axes return self._axes @property def figure(self): """ Returns -------- * (<autofig.figure.Figure> or None): the parent figure, if applicable. """ # no setter as this can only be set internally when attaching to an axes if self.axes is None: return None return self.axes.figure @property def i(self): """ Returns ---------- * <autofig.call.CallDimensionI> """ return self._i @property def indep(self): """ Shortcut to <autofig.call.Call.i> Returns ---------- * <autofig.call.CallDimensionI> """ return self.i @property def x(self): """ Returns ---------- * <autofig.call.CallDimensionX> """ return self._x @property def y(self): """ Returns ---------- * <autofig.call.CallDimensionY> """ return self._y @property def z(self): """ Returns ---------- * <autofig.call.CallDimensionZ> """ return self._z @property def consider_for_limits(self): """ Returns ----------- * (bool): whether the data in this <autofig.call.Call> should be considered when determining axes limits. """ return self._consider_for_limits @consider_for_limits.setter def consider_for_limits(self, consider): if not isinstance(consider, bool): raise TypeError("consider_for_limits must be of type bool") self._consider_for_limits = consider @property def uncover(self): """ Returns --------- * (bool): whether uncover is enabled """ return self._uncover @uncover.setter def uncover(self, uncover): if not isinstance(uncover, bool): raise TypeError("uncover must be of type bool") self._uncover = uncover @property def trail(self): """ Returns --------- * (bool or Float): whether trail is enabled. If a float, then a value between 0 and 1 indicating the length of the trail. """ return self._trail @trail.setter def trail(self, trail): if not (isinstance(trail, bool) or isinstance(trail, float)): if isinstance(trail, int): trail = float(trail) else: raise TypeError("trail must be of type bool or float") if trail < 0 or trail > 1: raise ValueError("trail must be between 0 and 1") self._trail = trail @property def axorder(self): """ See tutorial: * [Subplot/Axes Positioning](../../tutorials/subplot_positioning.md) Returns -------- * (int or None) """ return self._axorder @axorder.setter def axorder(self, axorder): if axorder is None: self._axorder = None return if not isinstance(axorder, int): raise TypeError("axorder must be of type int") self._axorder = axorder @property def axpos(self): """ See tutorial: * [Subplot/Axes Positioning](../../tutorials/subplot_positioning.md) Returns -------- * (tuple or None) """ return self._axpos @axpos.setter def axpos(self, axpos): if axpos is None: self._axpos = axpos return if isinstance(axpos, list) or isinstance(axpos, np.ndarray): axpos = tuple(axpos) if isinstance(axpos, tuple) and (len(axpos) == 3 or len(axpos) == 6) and np.all(isinstance(ap, int) for ap in axpos): self._axpos = axpos elif isinstance(axpos, int) and axpos >= 100 and axpos < 1000: self._axpos = (int(axpos/100), int(axpos/10 % 10), int(axpos % 10)) elif isinstance(axpos, int) and axpos >= 110011 and axpos < 999999: self._axpos = tuple([int(ap) for ap in str(axpos)]) else: raise ValueError("axpos must be of type int or tuple between 100 and 999 (subplot syntax: ncols, nrows, ind) or 110011 and 999999 (gridspec syntax: ncols, nrows, indx, indy, widthx, widthy)") @property def title(self): """ Returns ----------- * (str): title used for axes title """ return self._title @title.setter def title(self, title): if title is None: self._title = title return if not isinstance(title, str): raise TypeError("title must be of type str") self._title = title @property def label(self): """ Returns ----------- * (str): label used for legends """ return self._label @label.setter def label(self, label): if label is None: self._label = label return if not isinstance(label, str): raise TypeError("label must be of type str") self._label = label class Plot(Call): def __init__(self, x=None, y=None, z=None, c=None, s=None, i=None, xerror=None, xunit=None, xlabel=None, yerror=None, yunit=None, ylabel=None, zerror=None, zunit=None, zlabel=None, cunit=None, clabel=None, cmap=None, sunit=None, slabel=None, smap=None, smode=None, iunit=None, itol=0.0, axorder=None, axpos=None, title=None, label=None, marker=None, linestyle=None, linebreak=None, highlight=True, uncover=False, trail=False, consider_for_limits=True, **kwargs): """ Create a <autofig.call.Plot> object which defines a single call to matplotlib. See also: * <autofig.call.Mesh> Note that the following keyword arguments are not allowed and will raise an error suggesting the appropriate autofig argument: * `markersize` or `ms`: use `size` or `s` * `linewidth` or `lw`: use `size` or `s` Arguments ------------- * `x` (list/array, optional, default=None): array of values for the x-axes. Access via <autofig.call.Plot.x>. * `y` (list/array, optional, default=None): array of values for the y-axes. Access via <autofig.call.Plot.y>. * `z` (list/array, optional, default=None): array of values for the z-axes. Access via <autofig.call.Plot.z> * `c` or `color` (list/array, optional, default=None): array of values for the color-direction. Access via <autofig.call.Plot.c>. Note: `color` takes precedence over `c` if both are provided. * `s` or `size` (list/array, optional, default=None): array of values for the size-direction. Access via <autofig.call.Plot.s>. Note: `size` takes precedence over `s` if both are provided. * `i` (list/array or string, optional, default=None): array of values for the independent-variable. If a string, can be one of: 'x', 'y', 'z', 'c', 's' to reference an existing array. Access via <autofig.call.Plot.i>. * `xerror` (float or list/array, optional, default=None): errors for `x`. See <autofig.call.Plot.x> and <autofig.call.CallDimensionX.error>. * `xunit` (string or astropy unit, optional, default=None): units for `x`. See <autofig.call.Plot.x> and <autofig.call.CallDimensionX.unit>. * `xlabel` (strong, optional, default=None): label for `x`. See <autofig.call.Plot.x> and <autofig.call.CallDimensionX.label>. * `yerror` (float or list/array, optional, default=None): errors for `y`. See <autofig.call.Plot.y> and <autofig.call.CallDimensionY.error>. * `yunit` (string or astropy unit, optional, default=None): units for `y`. See <autofig.call.Plot.y> and <autofig.call.CallDimensionY.unit>. * `ylabel` (strong, optional, default=None): label for `y`. See <autofig.call.Plot.y> and <autofig.call.CallDimensionY.label>. * `zerror` (float or list/array, optional, default=None): errors for `z`. See <autofig.call.Plot.z> and <autofig.call.CallDimensionZ.error>. * `zunit` (string or astropy unit, optional, default=None): units for `z`. See <autofig.call.Plot.z> and <autofig.call.CallDimensionZ.unit>. * `zlabel` (strong, optional, default=None): label for `x`. See <autofig.call.Plot.z> and <autofig.call.CallDimensionZ.label>. * `cerror` (float or list/array, optional, default=None): errors for `c`. See <autofig.call.Plot.c> and <autofig.call.CallDimensionC.error>. * `cunit` (string or astropy unit, optional, default=None): units for `c`. See <autofig.call.Plot.c> and <autofig.call.CallDimensionC.unit>. * `clabel` (strong, optional, default=None): label for `c`. See <autofig.call.Plot.c> and <autofig.call.CallDimensionC.label>. * `serror` (float or list/array, optional, default=None): errors for `s`. See <autofig.call.Plot.s> and <autofig.call.CallDimensionS.error>. * `sunit` (string or astropy unit, optional, default=None): units for `s`. See <autofig.call.Plot.s> and <autofig.call.CallDimensionS.unit>. * `slabel` (strong, optional, default=None): label for `s`. See <autofig.call.Plot.s> and <autofig.call.CallDimensionS.label>. * `iunit` (string or astropy unit, optional, default=None): units for `i`. See <autofig.call.Plot.i> and <autofig.call.CallDimensionI.unit>. * `itol` (float, optional, default=0.0): see <autofig.call.DimensionI.tol>. * `axorder` (int, optional, default=None): see <autofig.call.Plot.axorder>. * `axpos` (tuple, optional, default=None): see <autofig.call.Plot.axpos>. * `title` (string, optional, default=None): see <autofig.call.Plot.title>. * `label` (string, optional, default=None): see <autofig.call.Plot.label>. * `marker` or `m` (string, optional, default=None): see <autofig.call.Plot.marker>. Note: `marker` takes precedence over `m` if both are provided. * `linestyle` or `ls` (string, optional, default=None): see <autofig.call.Plot.linestyle>. Note: `linestyle` takes precedence over `ls` if both are provided. * `linebreak` (string, optional, default=None): see <autofig.call.Plot.linebreak>. * `highlight` (bool, optional, default=False): see <autofig.call.Plot.highlight>. * `highlight_marker` (string, optional, default=None) * `highlight_linestyle` or `highlight_ls` (string, optional, default=None): Note: `highlight_linestyle` takes precedence over `highlight_ls` if both are provided. * `highlight_size` or `highlight_s` (float, optional, default=None): Note: `highlight_size` takes precedence over `highlight_s` if both are provided. * `highlight_color` or `highlight_c` (string, optional, default=None): Note: `highlight_color` takes precedence over `highlight_c` if both are provided. * `consider_for_limits` (bool, optional, default=True): see <autofig.call.Call.consider_for_limits>. * `uncover` (bool, optional, default=False): see <autofig.call.Call.uncover>. * `trail` (bool or Float, optional, default=False): see <autofig.call.Call.trail>. * `**kwargs`: additional keyword arguments are stored and passed on when attaching to a parent axes. See <autofig.axes.Axes.add_call>. Returns --------- * the instantiated <autofig.call.Plot> object. """ if 'markersize' in kwargs.keys(): raise ValueError("use 'size' or 's' instead of 'markersize'") if 'ms' in kwargs.keys(): raise ValueError("use 'size' or 's' instead of 'ms'") if 'linewidth' in kwargs.keys(): raise ValueError("use 'size' or 's' instead of 'linewidth'") if 'lw' in kwargs.keys(): raise ValueError("use 'size' or 's' instead of 'lw'") size = kwargs.pop('size', None) s = size if size is not None else s smap = kwargs.pop('sizemap', smap) self._s = CallDimensionS(self, s, None, sunit, slabel, smap=smap, mode=smode) color = kwargs.pop('color', None) c = color if color is not None else c cmap = kwargs.pop('colormap', cmap) self._c = CallDimensionC(self, c, None, cunit, clabel, cmap=cmap) self._axes = None # super will do this again, but we need it for setting marker, etc self._axes_c = None self._axes_s = None self.highlight = highlight highlight_marker = kwargs.pop('highlight_marker', None) self.highlight_marker = highlight_marker highlight_s = kwargs.pop('highlight_s', None) highlight_size = kwargs.pop('highlight_size', highlight_s) self.highlight_size = highlight_size highlight_c = kwargs.pop('highlight_c', None) highlight_color = kwargs.pop('highlight_color', highlight_c) self.highlight_color = highlight_color highlight_ls = kwargs.pop('highlight_ls', None) highlight_linestyle = kwargs.pop('highlight_linestyle', highlight_ls) self.highlight_linestyle = highlight_linestyle m = kwargs.pop('m', None) self.marker = marker if marker is not None else m ls = kwargs.pop('ls', None) self.linestyle = linestyle if linestyle is not None else ls self.linebreak = linebreak super(Plot, self).__init__(i=i, iunit=iunit, itol=itol, x=x, xerror=xerror, xunit=xunit, xlabel=xlabel, y=y, yerror=yerror, yunit=yunit, ylabel=ylabel, z=z, zerror=zerror, zunit=zunit, zlabel=zlabel, consider_for_limits=consider_for_limits, uncover=uncover, trail=trail, axorder=axorder, axpos=axpos, title=title, label=label, **kwargs ) self.connect_callback(callbacks.update_sizes) def __repr__(self): dirs = [] for direction in ['i', 'x', 'y', 'z', 's', 'c']: if getattr(self, direction).value is not None: dirs.append(direction) return "<Call:Plot | dims: {}>".format(", ".join(dirs)) @classmethod def from_dict(cls, dict): return cls(**dict) def to_dict(self): return {'classname': self.__class__.__name__, 'x': self.x.to_dict(), 'y': self.y.to_dict(), 'z': self.z.to_dict(), 'c': self.c.to_dict(), 's': self.s.to_dict(), 'i': self.i.to_dict(), 'axorder': self._axorder, 'axpos': self._axpos, 'title': self._title, 'label': self._label, 'marker': self._marker, 'linestyle': self._linestyle, 'linebreak': self._linebreak, 'highlight': self._highlight, 'highlight_linestyle': self._highlight_linestyle, 'highlight_size': self._highlight_size, 'highlight_color': self._highlight_color, 'highlight_marker': self._highlight_marker, 'uncover': self._uncover, 'trail': self._trail, 'consider_for_limits': self._consider_for_limits} @property def axes_c(self): # currently no setter as this really should be handle by axes.add_call return self._axes_c @property def axes_s(self): # currently no setter as this really should be handle by axes.add_call return self._axes_s @property def do_sizescale(self): x = self.x.get_value() y = self.y.get_value() z = self.z.get_value() s = self.s.get_value() # DETERMINE WHICH SCALINGS WE NEED TO USE if x is not None and y is not None: return s is not None and not (isinstance(s, float) or isinstance(s, int)) else: return False @property def do_colorscale(self): x = self.x.get_value() y = self.y.get_value() z = self.z.get_value() c = self.c.get_value() # DETERMINE WHICH SCALINGS WE NEED TO USE if x is not None and y is not None: return c is not None and not isinstance(c, str) else: return False @property def highlight(self): return self._highlight @highlight.setter def highlight(self, highlight): if not isinstance(highlight, bool): raise TypeError("highlight must be of type bool") self._highlight = highlight @property def highlight_size(self): if self._highlight_size is None: # then default to twice the non-highlight size plus an offset # so that small markers still have a considerably larger marker # TODO: can we make this dependent on i? if self.s.mode == 'pt': return np.mean(self.get_sizes())*2 else: return np.mean(self.get_sizes())*2 return self._highlight_size @highlight_size.setter def highlight_size(self, highlight_size): if highlight_size is None: self._highlight_size = None return if not (isinstance(highlight_size, float) or isinstance(highlight_size, int)): raise TypeError("highlight_size must be of type float or int") if highlight_size <= 0: raise ValueError("highlight_size must be > 0") self._highlight_size = highlight_size @property def highlight_marker(self): if self._highlight_marker is None: return 'o' return self._highlight_marker @highlight_marker.setter def highlight_marker(self, highlight_marker): if highlight_marker is None: self._highlight_marker = None return if not isinstance(highlight_marker, str): raise TypeError("highlight_marker must be of type str") # TODO: make sure valid marker? self._highlight_marker = highlight_marker @property def highlight_color(self): # if self._highlight_color is None: # return self.get_color() return self._highlight_color @highlight_color.setter def highlight_color(self, highlight_color): if highlight_color is None: self._highlight_color = None return if not isinstance(highlight_color, str): raise TypeError("highlight_color must be of type str") self._highlight_color = common.coloralias.map(highlight_color) @property def highlight_linestyle(self): if self._highlight_linestyle is None: return 'None' return self._highlight_linestyle @highlight_linestyle.setter def highlight_linestyle(self, highlight_linestyle): if highlight_linestyle is None: self._highlight_linestyle = None return if not isinstance(highlight_linestyle, str): raise TypeError("highlight_linestyle must be of type str") # TODO: make sure value ls? self._highlight_linestyle = highlight_linestyle def get_sizes(self, i=None): s = self.s.get_value(i=i, unit=self.axes_s.unit if self.axes_s is not None else None) if self.do_sizescale: if self.axes_s is not None: sizes = self.axes_s.normalize(s, i=i) else: # fallback on 0.01-0.05 mapping for just this call sall = self.s.get_value(unit=self.axes_s.unit if self.axes_s is not None else None) norm = plt.Normalize(np.nanmin(sall), np.nanmax(sall)) sizes = norm(s) * 0.04+0.01 else: if s is not None: sizes = s elif self.s.mode == 'pt': sizes = 1 else: sizes = 0.02 return sizes @property def s(self): return self._s @property def c(self): return self._c def get_color(self, colorcycler=None): if isinstance(self.c.value, str): color = self.c.value else: # then we'll defer to the cycler. If we want to color by # the dimension, we should call self.c directly color = None if color is None and colorcycler is not None: color = colorcycler.next_tmp return color @property def color(self): return self.get_color() @color.setter def color(self, color): # TODO: type and cycler checks color = common.coloralias.map(_map_none(color)) if self.axes is not None: self.axes._colorcycler.replace_used(self.get_color(), color) self._c.value = color def get_cmap(self, cmapcycler=None): if isinstance(self.c.value, str): return None if self.c.value is None: return None cmap = self.c.cmap if cmap is None and cmapcycler is not None: cmap = cmapcycler.next_tmp return cmap def get_marker(self, markercycler=None): marker = self._marker if marker is None: if markercycler is not None: marker = markercycler.next_tmp else: marker = '.' return marker @property def marker(self): return self.get_marker() @marker.setter def marker(self, marker): # TODO: type and cycler checks marker = _map_none(marker) if self.axes is not None: self.axes._markercycler.replace_used(self.get_marker(), marker) self._marker = marker def get_linestyle(self, linestylecycler=None): ls = self._linestyle if ls is None and linestylecycler is not None: ls = linestylecycler.next_tmp return ls @property def linestyle(self): return self.get_linestyle() @linestyle.setter def linestyle(self, linestyle): # TODO: type and cycler checks linestyle = common.linestylealias.map(_map_none(linestyle)) if self.axes is not None: self.axes._linestylecycler.replace_used(self.get_linestyle(), linestyle) self._linestyle = linestyle @property def linebreak(self): if self._linebreak is None: return False return self._linebreak @linebreak.setter def linebreak(self, linebreak): if linebreak is None: self._linebreak = linebreak return if not isinstance(linebreak, str): raise TypeError("linebreak must be of type str, found {} {}".format(type(linebreak), linebreak)) if not len(linebreak)==2: raise ValueError("linebreak must be of length 2") if linebreak[0] not in common.dimensions: raise ValueError("linebreak must start with one of {}".format(common.dimensions)) acceptable_ends = ['+', '-'] if linebreak[1] not in acceptable_ends: raise ValueError("linebreak must end with one of {}".format(acceptable_ends)) self._linebreak = linebreak def draw(self, ax=None, i=None, colorcycler=None, markercycler=None, linestylecycler=None): """ See also: * <autofig.draw> * <autofig.figure.Figure.draw> * <autofig.axes.Axes.draw> * <autofig.call.Mesh.draw> Arguments ----------- * `ax` * `i` * `colorcycler` * `markercycler` * `linestylecycler` """ # Plot.draw if ax is None: ax = plt.gca() else: if not isinstance(ax, plt.Axes): raise TypeError("ax must be of type plt.Axes") if not (i is None or isinstance(i, float) or isinstance(i, int) or isinstance(i, u.Quantity) or isinstance(i, list) or isinstance(i, np.ndarray)): raise TypeError("i must be of type float/int/list/None") kwargs = self.kwargs.copy() # determine 2D or 3D axes_3d = isinstance(ax, Axes3D) if (axes_3d and self.axes.projection=='2d') or (not axes_3d and self.axes.projection=='3d'): raise ValueError("axes and projection do not agree") # marker marker = self.get_marker(markercycler=markercycler) # linestyle - 'linestyle' has priority over 'ls' ls = self.get_linestyle(linestylecycler=linestylecycler) # color (NOTE: not necessarily the dimension c) color = self.get_color(colorcycler=colorcycler) # PREPARE FOR PLOTTING AND GET DATA return_artists = [] # TODO: handle getting in correct units (possibly passed from axes?) x = self.x.get_value(i=i, unit=self.axes.x.unit) xerr = self.x.get_error(i=i, unit=self.axes.x.unit) y = self.y.get_value(i=i, unit=self.axes.y.unit) yerr = self.y.get_error(i=i, unit=self.axes.y.unit) z = self.z.get_value(i=i, unit=self.axes.z.unit) # zerr is handled below, only if axes_3ds c = self.c.get_value(i=i, unit=self.axes_c.unit if self.axes_c is not None else None) s = self.s.get_value(i=i, unit=self.axes_s.unit if self.axes_s is not None else None) # bail on cases where we can't plot. This could possibly be due to # sending Nones or Nans # if x is None and y is None: # return [] # if x is None and len(y) > 1: # return [] # if y is None and len(x) > 1: # return [] if axes_3d: zerr = self.z.get_error(i=i, unit=self.axes.z.unit) else: zerr = None # then we need to loop over the linebreaks if isinstance(x, list) or isinstance(y, list): linebreak_n = len(x) if isinstance(x, list) else len(y) else: linebreak_n = 1 xs = _to_linebreak_list(x, linebreak_n) xerrs = _to_linebreak_list(xerr, linebreak_n) ys = _to_linebreak_list(y, linebreak_n) yerrs = _to_linebreak_list(yerr, linebreak_n) zs = _to_linebreak_list(z, linebreak_n) # zerrs = _to_linebreak_list(zerr, linebreak_n) cs = _to_linebreak_list(c, linebreak_n) ss = _to_linebreak_list(s, linebreak_n) for loop1,(x,xerr,y,yerr,z,c,s) in enumerate(zip(xs, xerrs, ys, yerrs, zs, cs, ss)): if axes_3d: data = np.array([x, y, z]) points = np.array([x, y, z]).T.reshape(-1, 1, 3) else: data = np.array([x, y]) points = np.array([x, y]).T.reshape(-1, 1, 2) # segments are used for LineCollection segments = np.concatenate([points[:-1], points[1:]], axis=1) # DETERMINE WHICH SCALINGS WE NEED TO USE do_colorscale = self.do_colorscale do_sizescale = self.do_sizescale if x is not None and y is not None: do_colorscale = c is not None and not isinstance(c, str) do_sizescale = s is not None and not (isinstance(s, float) or isinstance(s, int)) else: do_colorscale = False do_sizescale = False # DETERMINE PER-DATAPOINT Z-ORDERS zorders, do_zorder = self.axes.z.get_zorders(z, i=i) if axes_3d: # TODO: we probably want to re-implement zorder, but then we need to # sort in the *projected* z rather than data-z. We'll also need to # figure out why LineCollection is complaining about the input shape do_zorder = False # ALLOW ACCESS TO COLOR FOR I OR LOOP # TODO: in theory these could be exposed (maybe not the loop, but i) def get_color_i(i, default=color): if do_colorscale and self.axes_c is not None: cmap = self.axes_c.cmap norm = self.axes_c.get_norm(i=i) ci = self.axes.c.get_value(i=i) return plt.get_cmap(cmap)(norm(ci)) else: return default def get_color_loop(loop, do_zorder, default=color): if do_colorscale and self.axes_c is not None: cmap = self.axes_c.cmap norm = self.axes_c.get_norm(i=i) if do_zorder: cloop = c[loop] else: cloop = c return plt.get_cmap(cmap)(norm(cloop)) else: return default # BUILD KWARGS NEEDED FOR EACH CALL TO ERRORBAR def error_kwargs_loop(xerr, yerr, zerr, loop, do_zorder): def _get_error(errorarray, loop, do_zorder): if errorarray is None: return None elif do_zorder: return errorarray[loop] else: return errorarray error_kwargs = {'xerr': _get_error(xerr, loop, do_zorder), 'yerr': _get_error(yerr, loop, do_zorder)} if axes_3d: error_kwargs['zerr'] = _get_error(zerr, loop, do_zorder) error_kwargs['ecolor'] = get_color_loop(loop, do_zorder) # not so sure that we want the errorbar linewidth to adjust based # on size-scaling... but in theory we could do something like this: # error_kwargs['elinewidth'] = sizes[loop] return error_kwargs # BUILD KWARGS NEEDED FOR EACH CALL TO LINECOLLECTION lc_kwargs_const = {} lc_kwargs_const['linestyle'] = ls if do_colorscale: lc_kwargs_const['norm'] = self.axes_c.get_norm(i=i) if self.axes_c is not None else None lc_kwargs_const['cmap'] = self.axes_c.cmap if self.axes_c is not None else None else: lc_kwargs_const['color'] = color # also set self._sizes so its accessible from the callback which # will actually handle setting the sizes sizes = self.get_sizes(i) self._sizes = sizes def sizes_loop(loop, do_zorder): if do_zorder: if isinstance(sizes, float): return sizes return sizes[loop] else: return sizes def lc_kwargs_loop(lc_kwargs, loop, do_zorder): if do_colorscale: # nothing to do here, the norm and map are passed rather than values pass if do_sizescale: # linewidth is handled by the callback pass return lc_kwargs # BUILD KWARGS NEEDED FOR EACH CALL TO SCATTER sc_kwargs_const = {} sc_kwargs_const['marker'] = marker sc_kwargs_const['linewidths'] = 0 # linewidths = 0 removes the black edge sc_kwargs_const['edgecolors'] = 'none' if do_colorscale: sc_kwargs_const['norm'] = self.axes_c.get_norm(i=i) if self.axes_c is not None else None sc_kwargs_const['cmap'] = self.axes_c.cmap if self.axes_c is not None else None # we'll set sc_kwargs['cmap'] per-loop in the function below else: sc_kwargs_const['c'] = color def sc_kwargs_loop(sc_kwargs, loop, do_zorder): if do_colorscale: if do_zorder: sc_kwargs['c'] = c[loop] else: sc_kwargs['c'] = c # if do_sizescale: # if do_zorder: # sc_kwargs['s'] = self.get_markersize(sizes[loop], scatter=True) # else: # sc_kwargs['s'] = self.get_markersize(sizes, scatter=True) return sc_kwargs # DRAW IF X AND Y ARE ARRAYS if isinstance(x, np.ndarray) and isinstance(y, np.ndarray): # LOOP OVER DATAPOINTS so that each can be drawn with its own zorder if do_zorder: datas = data.T segments = segments zorders = zorders else: datas = [data] zorders = [zorders] segments = [segments] for loop2, (datapoint, segment, zorder) in enumerate(zip(datas, segments, zorders)): return_artists_this_loop = [] # DRAW ERRORBARS, if applicable # NOTE: we never pass a label here to avoid duplicate entries # the actual datapoints are handled and labeled separately. # Unfortunately this means the error bar will not be included # in the styling of the legend. if xerr is not None or yerr is not None or zerr is not None: artists = ax.errorbar(*datapoint, fmt='', linestyle='None', zorder=zorder, label=None, **error_kwargs_loop(xerr, yerr, zerr, loop2, do_zorder)) # NOTE: these are currently not included in return_artists # so they don't scale according to per-element sizes. # But we may want to return them for completeness and may # want some way of setting the size of the errobars, # maybe similar to how highlight_size is handled # errorbar actually returns a Container object of artists, # so we need to cast to a list # for artist_list in list(artists): # if isinstance(artist_list, tuple): # return_artists += list(artist_list) # else: # return_artists += [artist_list] if do_colorscale or do_sizescale or do_zorder or marker in ['x', '+']: # DRAW LINECOLLECTION, if applicable if ls.lower() != 'none': # TODO: color and zorder are assigned from the LEFT point in # the segment. It may be nice to interpolate from LEFT-RIGHT # by accessing zorder[loop+1] and c[loop+1] if do_zorder: segments = (segment,) else: segments = segment if axes_3d: lccall = Line3DCollection else: lccall = LineCollection # we'll only include this in the legend for the first loop # and if the marker isn't going to get its own entry. # Unfortunately this means in these cases the # marker will get precedent in the legend if both # marker and linestyle are present lc = lccall(segments, zorder=zorder, label=self.label if loop1==0 and loop2==0 and marker.lower()=='none' else None, **lc_kwargs_loop(lc_kwargs_const, loop2, do_zorder)) if do_colorscale: if do_zorder: lc.set_array(np.array([c[loop2]])) else: lc.set_array(c) return_artists_this_loop.append(lc) ax.add_collection(lc) # DRAW SCATTER, if applicable if marker.lower() != 'none': artist = ax.scatter(*datapoint, zorder=zorder, label=self.label if loop1==0 and loop2==0 else None, **sc_kwargs_loop(sc_kwargs_const, loop2, do_zorder)) return_artists_this_loop.append(artist) else: # let's use plot whenever possible... it'll be faster # and will guarantee that the linestyle looks correct artists = ax.plot(*datapoint, marker=marker, ls=ls, mec='none', color=color, label=self.label if loop1==0 and loop2==0 else None) return_artists_this_loop += artists size_this_loop = sizes_loop(loop2, do_zorder) for artist in return_artists_this_loop: # store the sizes so they can be rescaled appropriately by # the callback artist._af_sizes = size_this_loop return_artists += return_artists_this_loop # DRAW IF X OR Y ARE NOT ARRAYS if not (isinstance(x, np.ndarray) and isinstance(y, np.ndarray)): # TODO: can we do anything in 3D? if x is not None: artist = ax.axvline(x, ls=ls, color=color, label=self.label) return_artists += [artist] if y is not None: artist = ax.axhline(y, ls=ls, color=color, label=self.label) return_artists += [artist] # DRAW HIGHLIGHT, if applicable (outside per-datapoint loop) if self.highlight and i is not None: if self.highlight_linestyle != 'None' and self.i.is_reference: i_direction = self.i.reference if i_direction == 'x': linefunc = 'axvline' elif i_direction == 'y': linefunc = 'axhline' else: # TODO: can we do anything if in z? linefunc = None if linefunc is not None: artist = getattr(ax, linefunc)(i, ls=self.highlight_linestyle, color=self.highlight_color if self.highlight_color is not None else color) artist._af_highlight = True return_artists += [artist] if axes_3d: # I do not understand why, but matplotlib requires these to be # iterable when in 3d projection highlight_data = ([self.x.highlight_at_i(i)], [self.y.highlight_at_i(i)], [self.z.highlight_at_i(i)]) else: highlight_data = (self.x.highlight_at_i(i), self.y.highlight_at_i(i)) artists = ax.plot(*highlight_data, marker=self.highlight_marker, ls=self.highlight_linestyle, color=self.highlight_color if self.highlight_color is not None else color) for artist in artists: artist._af_highlight=True return_artists += artists self._backend_objects = return_artists for artist in return_artists: callbacks._connect_to_autofig(self, artist) for callback in self.callbacks: callback_callable = getattr(callbacks, callback) callback_callable(artist, self) return return_artists class FillBetween(Call): def __init__(self, x=None, y=None, c=None, i=None, xunit=None, xlabel=None, yunit=None, ylabel=None, cunit=None, clabel=None, cmap=None, iunit=None, itol=0.0, axorder=None, axpos=None, title=None, label=None, linebreak=None, uncover=False, trail=False, consider_for_limits=True, **kwargs): """ Create a <autofig.call.FillBetween> object which defines a single call to matplotlib. See also: * <autofig.call.Plot> * <autofig.call.Mesh> Arguments ------------- * `x` (list/array, optional, default=None): array of values for the x-axes. Access via <autofig.call.FillBetween.x>. * `y` (list/array, optional, default=None): array of values for the y-axes. Must have shape (len(x), 2) Access via <autofig.call.FillBetween.y>. * `c` or `color` (list/array, optional, default=None): array of values for the color-direction. Access via <autofig.call.FillBetween.c>. Note: `color` takes precedence over `c` if both are provided. * `i` (list/array or string, optional, default=None): array of values for the independent-variable. If a string, can be one of: 'x', 'y', 'z', 'c', 's' to reference an existing array. Access via <autofig.call.FillBetween.i>. * `xunit` (string or astropy unit, optional, default=None): units for `x`. See <autofig.call.FillBetween.x> and <autofig.call.CallDimensionX.unit>. * `xlabel` (strong, optional, default=None): label for `x`. See <autofig.call.FillBetween.x> and <autofig.call.CallDimensionX.label>. * `yunit` (string or astropy unit, optional, default=None): units for `y`. See <autofig.call.FillBetween.y> and <autofig.call.CallDimensionY.unit>. * `ylabel` (strong, optional, default=None): label for `y`. See <autofig.call.FillBetween.y> and <autofig.call.CallDimensionY.label>. * `iunit` (string or astropy unit, optional, default=None): units for `i`. See <autofig.call.FillBetween.i> and <autofig.call.CallDimensionI.unit>. * `itol` (float, optional, default=0.0): see <autofig.call.DimensionI.tol>. * `axorder` (int, optional, default=None): see <autofig.call.FillBetween.axorder>. * `axpos` (tuple, optional, default=None): see <autofig.call.FillBetween.axpos>. * `title` (string, optional, default=None): see <autofig.call.FillBetween.title>. * `label` (string, optional, default=None): see <autofig.call.FillBetween.label>. * `linebreak` (string, optional, default=None): see <autofig.call.FillBetween.linebreak>. * `consider_for_limits` (bool, optional, default=True): see <autofig.call.Call.consider_for_limits>. * `uncover` (bool, optional, default=False): see <autofig.call.Call.uncover>. * `trail` (bool or Float, optional, default=False): see <autofig.call.Call.trail>. * `**kwargs`: additional keyword arguments are stored and passed on when attaching to a parent axes. See <autofig.axes.Axes.add_call>. Returns --------- * the instantiated <autofig.call.FillBetween> object. """ color = kwargs.pop('color', None) c = color if color is not None else c cmap = kwargs.pop('colormap', cmap) self._c = CallDimensionC(self, c, None, cunit, clabel, cmap=cmap) self._axes = None # super will do this again, but we need it for setting marker, etc self._axes_c = None color = kwargs.pop('color', None) c = color if color is not None else c cmap = kwargs.pop('colormap', cmap) self._c = CallDimensionC(self, c, None, cunit, clabel, cmap=cmap) self.linebreak = linebreak if x is None: raise TypeError("x cannot be None for FillBetween") x = np.asarray(x) if y is None: raise TypeError("y cannot be None for FillBetween") y = np.asarray(y) if y.shape not in [(len(x), 2), (len(x), 3)]: raise ValueError("y must be of shape ({}, 2) or ({}, 3), not {}".format(len(x), len(x), y.shape)) super(FillBetween, self).__init__(i=i, iunit=iunit, itol=itol, x=x, xunit=xunit, xlabel=xlabel, y=y, yunit=yunit, ylabel=ylabel, consider_for_limits=consider_for_limits, uncover=uncover, trail=trail, axorder=axorder, axpos=axpos, title=title, label=label, **kwargs ) # self.connect_callback(callbacks.update_sizes) def __repr__(self): dirs = [] for direction in ['i', 'x', 'y', 'c']: if getattr(self, direction).value is not None: dirs.append(direction) return "<Call:FillBetween | dims: {}>".format(", ".join(dirs)) @classmethod def from_dict(cls, dict): return cls(**dict) def to_dict(self): return {'classname': self.__class__.__name__, 'x': self.x.to_dict(), 'y': self.y.to_dict(), 'c': self.c.to_dict(), 'i': self.i.to_dict(), 'axorder': self._axorder, 'axpos': self._axpos, 'title': self._title, 'label': self._label, 'uncover': self._uncover, 'trail': self._trail, 'consider_for_limits': self._consider_for_limits} @property def axes_c(self): # currently no setter as this really should be handle by axes.add_call return self._axes_c @property def do_colorscale(self): x = self.x.get_value() y = self.y.get_value() c = self.c.get_value() # DETERMINE WHICH SCALINGS WE NEED TO USE if x is not None and y is not None: return c is not None and not isinstance(c, str) else: return False @property def c(self): return self._c def get_color(self, colorcycler=None): if isinstance(self.c.value, str): color = self.c.value else: # then we'll defer to the cycler. If we want to color by # the dimension, we should call self.c directly color = None if color is None and colorcycler is not None: color = colorcycler.next_tmp return color @property def color(self): return self.get_color() @color.setter def color(self, color): # TODO: type and cycler checks color = common.coloralias.map(_map_none(color)) if self.axes is not None: self.axes._colorcycler.replace_used(self.get_color(), color) self._c.value = color def get_cmap(self, cmapcycler=None): if isinstance(self.c.value, str): return None if self.c.value is None: return None cmap = self.c.cmap if cmap is None and cmapcycler is not None: cmap = cmapcycler.next_tmp return cmap @property def linebreak(self): if self._linebreak is None: return False return self._linebreak @linebreak.setter def linebreak(self, linebreak): if linebreak is None: self._linebreak = linebreak return if not isinstance(linebreak, str): raise TypeError("linebreak must be of type str, found {} {}".format(type(linebreak), linebreak)) if not len(linebreak)==2: raise ValueError("linebreak must be of length 2") if linebreak[0] not in common.dimensions: raise ValueError("linebreak must start with one of {}".format(common.dimensions)) acceptable_ends = ['+', '-'] if linebreak[1] not in acceptable_ends: raise ValueError("linebreak must end with one of {}".format(acceptable_ends)) self._linebreak = linebreak def draw(self, ax=None, i=None, colorcycler=None, markercycler=None, linestylecycler=None): """ See also: * <autofig.draw> * <autofig.figure.Figure.draw> * <autofig.axes.Axes.draw> Arguments ----------- * `ax` * `i` * `colorcycler` * `markercycler`: ignored * `linestylecycler`: ignored """ # Plot.draw if ax is None: ax = plt.gca() else: if not isinstance(ax, plt.Axes): raise TypeError("ax must be of type plt.Axes") if not (i is None or isinstance(i, float) or isinstance(i, int) or isinstance(i, u.Quantity) or isinstance(i, list) or isinstance(i, np.ndarray)): raise TypeError("i must be of type float/int/list/None") kwargs = self.kwargs.copy() # determine 2D or 3D axes_3d = isinstance(ax, Axes3D) if (axes_3d and self.axes.projection=='2d') or (not axes_3d and self.axes.projection=='3d'): raise ValueError("axes and projection do not agree") # color (NOTE: not necessarily the dimension c) color = self.get_color(colorcycler=colorcycler) # PREPARE FOR PLOTTING AND GET DATA return_artists = [] # TODO: handle getting in correct units (possibly passed from axes?) x = self.x.get_value(i=i, unit=self.axes.x.unit) y = self.y.get_value(i=i, unit=self.axes.y.unit) if isinstance(y, list): y = [yi.T for yi in y] else: y = y.T c = self.c.get_value(i=i, unit=self.axes_c.unit if self.axes_c is not None else None) # then we need to loop over the linebreaks if isinstance(x, list) or isinstance(y, list): linebreak_n = len(x) if isinstance(x, list) else len(y) else: linebreak_n = 1 xs = _to_linebreak_list(x, linebreak_n) ys = _to_linebreak_list(y, linebreak_n) cs = _to_linebreak_list(c, linebreak_n) for loop1,(x,y,c) in enumerate(zip(xs, ys, cs)): data = np.array([x, y[0], y[-1]]) if len(y) == 3: data_middle = np.array([x, y[1]]) else: data_middle = None # points = np.array([x, y1, y2]).T.reshape(-1, 1, 3) # segments are used for LineCollection # segments = np.concatenate([points[:-1], points[1:]], axis=1) # DETERMINE WHICH SCALINGS WE NEED TO USE do_colorscale = self.do_colorscale if x is not None and y is not None: do_colorscale = c is not None and not isinstance(c, str) else: do_colorscale = False # ALLOW ACCESS TO COLOR FOR I OR LOOP # TODO: in theory these could be exposed (maybe not the loop, but i) # def get_color_i(i, default=color): # if do_colorscale and self.axes_c is not None: # cmap = self.axes_c.cmap # norm = self.axes_c.get_norm(i=i) # ci = self.axes.c.get_value(i=i) # return plt.get_cmap(cmap)(norm(ci)) # else: # return default # # def get_color_loop(loop, do_zorder, default=color): # if do_colorscale and self.axes_c is not None: # cmap = self.axes_c.cmap # norm = self.axes_c.get_norm(i=i) # if do_zorder: # cloop = c[loop] # else: # cloop = c # return plt.get_cmap(cmap)(norm(cloop)) # else: # return default fb_kwargs = {} fb_kwargs['color'] = color fb_kwargs['alpha'] = 0.6 # TODO: make this an option if do_colorscale: fb_kwargs['norm'] = self.axes_c.get_norm(i=i) if self.axes_c is not None else None fb_kwargs['cmap'] = self.axes_c.cmap if self.axes_c is not None else None artist = ax.fill_between(*data, **fb_kwargs) return_artists += [artist] if data_middle is not None: _ = fb_kwargs.pop('alpha') fb_kwargs['linestyle'] = 'solid' fb_kwargs['marker'] = 'None' artists = ax.plot(*data_middle, **fb_kwargs) return_artists += artists self._backend_objects = return_artists for artist in return_artists: callbacks._connect_to_autofig(self, artist) for callback in self.callbacks: callback_callable = getattr(callbacks, callback) callback_callable(artist, self) return return_artists class Mesh(Call): def __init__(self, x=None, y=None, z=None, fc=None, ec=None, i=None, xerror=None, xunit=None, xlabel=None, xnormals=None, yerror=None, yunit=None, ylabel=None, ynormals=None, zerror=None, zunit=None, zlabel=None, znormals=None, fcunit=None, fclabel=None, fcmap=None, ecunit=None, eclabel=None, ecmap=None, iunit=None, itol=0.0, axorder=None, axpos=None, title=None, label=None, linestyle=None, consider_for_limits=True, uncover=True, trail=0, exclude_back=False, **kwargs): """ Create a <autofig.call.Mesh> object which defines a single call to matplotlib. See also: * <autofig.call.Plot> Arguments ------------- * `x` (list/array, optional, default=None): array of values for the x-axes. Access via <autofig.call.Mesh.x>. * `y` (list/array, optional, default=None): array of values for the y-axes. Access via <autofig.call.Mesh.y>. * `z` (list/array, optional, default=None): array of values for the z-axes. Access via <autofig.call.Mesh.z> * `fc` or `facecolor` (list/array, optional, default=None): array of values for the facecolor-direction. Access via <autofig.call.Mesh.fc>. Note: `facecolor` takes precedence over `fc` if both are provided. * `ec` or `edgecolor` (list/array, optional, default=None): array of values for the edgecolor-direction. Access via <autofig.call.Mesh.ec>. Note: `edgecolor` takes precedence over `ec` if both are provided. * `i` (list/array or string, optional, default=None): array of values for the independent-variable. If a string, can be one of: 'x', 'y', 'z', 'fc', 'ec' to reference an existing array. Access via <autofig.call.Mesh.i>. * `xerror` (float or list/array, optional, default=None): errors for `x`. See <autofig.call.Mesh.x> and <autofig.call.CallDimensionX.error>. * `xunit` (string or astropy unit, optional, default=None): units for `x`. See <autofig.call.Mesh.x> and <autofig.call.CallDimensionX.unit>. * `xlabel` (strong, optional, default=None): label for `x`. See <autofig.call.Mesh.x> and <autofig.call.CallDimensionX.label>. * `xnormals` (list/array, optional, default=None): normals for `x`. Currently ignored. See <autofig.call.Mesh.x> and <autofig.call.CallDimensionX.normals>. * `yerror` (float or list/array, optional, default=None): errors for `y`. See <autofig.call.Mesh.y> and <autofig.call.CallDimensionY.error>. * `yunit` (string or astropy unit, optional, default=None): units for `y`. See <autofig.call.Mesh.y> and <autofig.call.CallDimensionY.unit>. * `ylabel` (strong, optional, default=None): label for `y`. See <autofig.call.Mesh.y> and <autofig.call.CallDimensionY.label>. * `ynormals` (list/array, optional, default=None): normals for `y`. Currently ignored. See <autofig.call.Mesh.y> and <autofig.call.CallDimensionY.normals>. * `zerror` (float or list/array, optional, default=None): errors for `z`. See <autofig.call.Mesh.z> and <autofig.call.CallDimensionZ.error>. * `zunit` (string or astropy unit, optional, default=None): units for `z`. See <autofig.call.Mesh.z> and <autofig.call.CallDimensionZ.unit>. * `zlabel` (strong, optional, default=None): label for `x`. See <autofig.call.Mesh.z> and <autofig.call.CallDimensionZ.label>. * `znormals` (list/array, optional, default=None): normals for `z`. If provided then the back of the mesh can be ignored by setting `exclude_back=True`. See <autofig.call.Mesh.z> and <autofig.call.CallDimensionZ.normals>. * `fcerror` (float or list/array, optional, default=None): errors for `fc`. See <autofig.call.Mesh.fc> and <autofig.call.CallDimensionC.error>. * `fcunit` (string or astropy unit, optional, default=None): units for `fc`. See <autofig.call.Mesh.fc> and <autofig.call.CallDimensionC.unit>. * `fclabel` (strong, optional, default=None): label for `fc`. See <autofig.call.Mesh.fc> and <autofig.call.CallDimensionC.label>. * `ecerror` (float or list/array, optional, default=None): errors for `ec`. See <autofig.call.Mesh.ec> and <autofig.call.CallDimensionC.error>. * `ecunit` (string or astropy unit, optional, default=None): units for `ec`. See <autofig.call.Mesh.ec> and <autofig.call.CallDimensionC.unit>. * `eclabel` (strong, optional, default=None): label for `ec`. See <autofig.call.Mesh.ec> and <autofig.call.CallDimensionC.label>. * `iunit` (string or astropy unit, optional, default=None): units for `i`. See <autofig.call.Mesh.i> and <autofig.call.CallDimensionI.unit>. * `itol` (float, optional, default=0.0): see <autofig.call.DimensionI.tol>. * `axorder` (int, optional, default=None): see <autofig.call.Mesh.axorder>. * `axpos` (tuple, optional, default=None): see <autofig.call.Mesh.axpos>. * `title` (string, optional, default=None): see <autofig.call.Mesh.title>. * `label` (string, optional, default=None): see <autofig.call.Mesh.label>. * `linestyle` or `ls` (string, optional, default='solid'): see <autofig.call.Mesh.linestyle>. Note: `linestyle` takes precedence over `ls` if both are provided. So technically `ls` defaults to 'solid' and `linestyle` defaults to None. * `consider_for_limits` (bool, optional, default=True): see <autofig.call.Call.consider_for_limits>. * `exclude_back` (bool, optional, default=False): whether to exclude any elements pointing away from the screen. This will be ignored for 3d projections or if `znormals` is not provided. Setting this to True can save significant time in drawing the mesh in matplotlib, and is especially useful for closed surfaces if `fc` is not 'none'. * `**kwargs`: additional keyword arguments are stored and passed on when attaching to a parent axes. See <autofig.axes.Axes.add_call>. Returns --------- * the instantiated <autofig.call.Mesh> object. """ self._axes_fc = None self._axes_ec = None facecolor = kwargs.pop('facecolor', None) fc = facecolor if facecolor is not None else fc self._fc = CallDimensionC(self, fc, None, fcunit, fclabel, cmap=fcmap) edgecolor = kwargs.pop('edgecolor', None) ec = edgecolor if edgecolor is not None else ec self._ec = CallDimensionC(self, ec, None, ecunit, eclabel, cmap=ecmap) ls = kwargs.pop('ls', 'solid') self.linestyle = linestyle if linestyle is not None else ls self.linebreak = False self.exclude_back = exclude_back if hasattr(i, '__iter__') and not isinstance(i, u.Quantity): raise ValueError("i as an iterable not supported for Meshes, make separate calls for each value of i") super(Mesh, self).__init__(i=i, iunit=iunit, itol=itol, x=x, xerror=xerror, xunit=xunit, xlabel=xlabel, xnormals=xnormals, y=y, yerror=yerror, yunit=yunit, ylabel=ylabel, ynormals=ynormals, z=z, zerror=zerror, zunit=zunit, zlabel=zlabel, znormals=znormals, consider_for_limits=consider_for_limits, uncover=uncover, trail=trail, axorder=axorder, axpos=axpos, title=title, label=label, **kwargs ) def __repr__(self): dirs = [] for direction in ['i', 'x', 'y', 'z', 'fc', 'ec']: if getattr(self, direction).value is not None: dirs.append(direction) return "<Call:Mesh | dims: {}>".format(", ".join(dirs)) @classmethod def from_dict(cls, dict): return cls(**dict) def to_dict(self): return {'classname': self.__class__.__name__, 'x': self.x.to_dict(), 'y': self.y.to_dict(), 'z': self.z.to_dict(), 'fc': self.fc.to_dict(), 'ec': self.ec.to_dict(), 'i': self.i.to_dict(), 'axorder': self._axorder, 'axpos': self._axpos, 'title': self._title, 'label': self._label, 'uncover': self._uncover, 'trail': self._trail, 'consider_for_limits': self._consider_for_limits, 'exclude_back': self._exclude_back} @property def axes_fc(self): # currently no setter as this really should be handle by axes.add_call return self._axes_fc @property def axes_ec(self): # currently no setter as this really should be handle by axes.add_call return self._axes_ec @property def c(self): """ Returns --------- * <autofig.call.CallDimensionCGroup> of <autofig.call.Mesh.fc> and <autofig.call.Mesh.ec> """ return CallDimensionCGroup([self.fc, self.ec]) @property def fc(self): """ See also: * <autofig.call.Mesh.get_facecolor> Returns ---------- * <autofig.call.CallDimensionC> """ return self._fc def get_facecolor(self, colorcycler=None): """ See also: * <autofig.call.Mesh.fc> Arguments ----------- * `colorcycler` (optional, default=None): **IGNORED** (only included to have a similar calling signature as other methods that do account for color cyclers) Returns ---------- * (string): 'none' if <autofig.call.Mesh.fc> is not a string. """ if isinstance(self.fc.value, str): color = self.fc.value else: # then we'll default to 'none'. If we want to color by # the dimension, we should call self.c directly color = 'none' # we won't use the colorcycler for facecolor return color @property def facecolor(self): """ Shortcut to <autofig.call.Mesh.get_facecolor>. See also: * <autofig.call.Mesh.fc> Returns ---------- * (string) """ return self.get_facecolor() @facecolor.setter def facecolor(self, facecolor): # TODO: type and cycler checks facecolor = common.coloralias.map(_map_none(facecolor)) if self.axes is not None: self.axes._colorcycler.replace_used(self.get_facecolor(), facecolor) self._fc.value = facecolor def get_fcmap(self, cmapcycler=None): if isinstance(self.fc.value, str): return None if self.fc.value is None: return None cmap = self.fc.cmap if cmap is None and cmapcycler is not None: cmap = cmapcycler.next_tmp return cmap @property def ec(self): """ See also: * <autofig.call.Mesh.get_edgecolor> Returns ---------- * <autofig.call.CallDimensionC> """ return self._ec def get_edgecolor(self, colorcycler=None): """ See also: * <autofig.call.Mesh.ec> Arguments ----------- * `colorcycler` (optional, default=None): **IGNORED** (only included to have a similar calling signature as other methods that do account for color cyclers) Returns ---------- * (string): 'black' if <autofig.call.Mesh.ec> is not a string. """ if isinstance(self.ec.value, str): color = self.ec.value else: # then we'll default to black. If we want to color by # the dimension, we should call self.c directly color = 'black' # we won't use the colorcycler for edgecolor return color @property def edgecolor(self): """ Shortcut to <autofig.call.Mesh.get_edgecolor>. See also: * <autofig.call.Mesh.ec> Returns ---------- * (string) """ return self.get_edgecolor() @edgecolor.setter def edgecolor(self, edgecolor): # TODO: type and cycler checks if edgecolor in ['face']: self._ec.value = edgecolor return edgecolor = common.coloralias.map(_map_none(edgecolor)) if self.axes is not None: self.axes._colorcycler.replace_used(self.get_edgecolor(), edgecolor) self._ec.value = edgecolor def get_ecmap(self, cmapcycler=None): if isinstance(self.ec.value, str): return None if self.ec.value is None: return None cmap = self.ec.cmap if cmap is None and cmapcycler is not None: cmap = cmapcycler.next_tmp return cmap @property def exclude_back(self): return self._exclude_back @exclude_back.setter def exclude_back(self, exclude_back): if not isinstance(exclude_back, bool): raise TypeError("exclude back must be of type bool") self._exclude_back = exclude_back def draw(self, ax=None, i=None, colorcycler=None, markercycler=None, linestylecycler=None): """ See also: * <autofig.draw> * <autofig.figure.Figure.draw> * <autofig.axes.Axes.draw> * <autofig.call.Plot.draw> Arguments ---------- * `ax` * `i` * `colorcycler` * `markercycler` * `linestylecycler` """ # Mesh.draw if ax is None: ax = plt.gca() else: if not isinstance(ax, plt.Axes): raise TypeError("ax must be of type plt.Axes") if not (i is None or isinstance(i, float) or isinstance(i, int) or isinstance(i, u.Quantity)): raise TypeError("i must be of type float/int/None") # determine 2D or 3D axes_3d = isinstance(ax, Axes3D) kwargs = self.kwargs.copy() # PLOTTING return_artists = [] x = self.x.get_value(i=i, sort_by_indep=False, exclude_back=self.exclude_back, unit=self.axes.x.unit) y = self.y.get_value(i=i, sort_by_indep=False, exclude_back=self.exclude_back, unit=self.axes.y.unit) z = self.z.get_value(i=i, sort_by_indep=False, exclude_back=self.exclude_back, unit=self.axes.z.unit) fc = self.fc.get_value(i=i, sort_by_indep=False, exclude_back=self.exclude_back, unit=self.axes_fc.unit if self.axes_fc is not None else None) ec = self.ec.get_value(i=i, sort_by_indep=False, exclude_back=self.exclude_back, unit=self.axes_ec.unit if self.axes_ec is not None else None) # DETERMINE PER-DATAPOINT Z-ORDERS zorders, do_zorder = self.axes.z.get_zorders(z, i=i) if do_zorder: # we can perhaps skip doing the zorder loop if there are no other # calls within the axes if len(self.axes.calls) == 1: do_zorder = False zorders = np.mean(zorders) if axes_3d: if x is not None and y is not None and z is not None: polygons = np.concatenate((x[:,:,np.newaxis], y[:,:,np.newaxis], z[:,:,np.newaxis]), axis=2) else: # there isn't anything to plot here, the current i probably # filtered this call out return [] pccall = Poly3DCollection else: if x is not None and y is not None: polygons = np.concatenate((x[:,:,np.newaxis], y[:,:,np.newaxis]), axis=2) if not do_zorder and z is not None: # then we'll handle zorder within this Mesh call by # sorting instead of looping. This is MUCH quicking # and less memory instensive sortinds = np.mean(z, axis=1).argsort() polygons = polygons[sortinds, :, :] if isinstance(fc, np.ndarray): fc = fc[sortinds] if isinstance(ec, np.ndarray): ec = ec[sortinds] else: # there isn't anything to plot here, the current i probably # filtered this call out return [] pccall = PolyCollection do_facecolorscale = fc is not None and not isinstance(fc, str) do_edgecolorscale = ec is not None and not isinstance(ec, str) if do_edgecolorscale: if self.axes_ec is None: raise NotImplementedError("currently only support edgecolor once attached to axes") else: edgenorm = self.axes_ec.get_norm(i=i) edgecmap = self.axes_ec.cmap edgecolors = plt.get_cmap(edgecmap)(edgenorm(ec)) else: edgecolors = self.get_edgecolor(colorcycler=colorcycler) if do_facecolorscale: if self.axes_fc is None: raise NotImplementedError("currently only support facecolor once attached to axes") else: facenorm = self.axes_fc.get_norm(i=i) facecmap = self.axes_fc.cmap facecolors = plt.get_cmap(facecmap)(facenorm(fc)) else: facecolors = self.get_facecolor(colorcycler=colorcycler) if do_zorder: # LOOP THROUGH POLYGONS so each can be assigned its own zorder if isinstance(edgecolors, str): edgecolors = [edgecolors] * len(zorders) if isinstance(facecolors, str): facecolors = [facecolors] * len(zorders) for loop, (polygon, zorder, edgecolor, facecolor) in enumerate(zip(polygons, zorders, edgecolors, facecolors)): pc = pccall((polygon,), linestyle=self.linestyle, edgecolors=edgecolor, facecolors=facecolor, zorder=zorder, label=self.label if loop==0 else None) ax.add_collection(pc) return_artists += [pc] else: # DON'T LOOP as all have the same zorder, this should be faster pc = pccall(polygons, linestyle=self.linestyle, edgecolors=edgecolors, facecolors=facecolors, zorder=zorders, label=self.label) ax.add_collection(pc) return_artists += [pc] self._backend_objects = return_artists for artist in return_artists: callbacks._connect_to_autofig(self, artist) return return_artists class CallDimensionGroup(common.Group): def __init__(self, items): super(CallDimensionGroup, self).__init__(CallDimension, [], items) @property def value(self): """ Returns --------- * (list) a list of <autofig.call.CallDimension.value> for each child <autofig.call.CallDimension> """ return np.array([c.value for c in self._items]).flatten() @property def units(self): """ """ return [c.unit for c in self._items] @property def unit(self): units = list(set(self.units)) if len(units) > 1: raise ValueError("more than 1 units, see units") else: return units[0] @property def labels(self): """ """ return [c.label for c in self._items] @property def label(self): labels = list(set(self.labels)) if len(labels) > 1: raise ValueError("more than 1 labels, see labels") else: return labels[0] class CallDimensionCGroup(CallDimensionGroup): @property def cmap(self): """ Returns --------- * (list) a list of <autofig.call.CallDimensionC.cmap> for each child <autofig.call.CallDimensionC> """ return self._get_attrs('cmap') @cmap.setter def cmap(self, smap): return self._set_attrs('cmap', cmap) class CallDimensionSGroup(CallDimensionGroup): @property def smap(self): """ Returns --------- * (list) a list of <autofig.call.CallDimensionS.smap> for each child <autofig.call.CallDimensionS> """ return self._get_attrs('smap') @smap.setter def smap(self, smap): return self._set_attrs('smap', smap) @property def mode(self): """ Returns --------- * (list) a list of <autofig.call.CallDimensionS.mode> for each child <autofig.call.CallDimensionS> """ return self._get_attrs('mode') @mode.setter def mode(self, mode): return self._set_attrs('mode', mode) def make_calldimensiongroup(items): if np.all([isinstance(item, CallDimensionC) for item in items]): return CallDimensionCGroup(items) elif np.all([isinstance(item, CallDimensionS) for item in items]): return CallDimensionSGroup(items) else: return CallDimensionGroup(items) class CallDimension(object): def __init__(self, direction, call, value, error=None, unit=None, label=None, normals=None): if isinstance(value, dict): error = value.get('error', error) unit = value.get('unit', unit) label = value.get('label', label) normals = value.get('normals', normals) value = value.get('value') self._call = call self.direction = direction # unit must be set before value as setting value pulls the appropriate # unit for CallDimensionI self.unit = unit self.value = value self.error = error self.label = label self.normals = normals # self.lim = lim def __repr__(self): if isinstance(self.value, np.ndarray): info = "len: {}".format(len(self.value)) else: info = "value: {}".format(self.value) return "<{} | {} | type: {} | label: {}>".format(self.direction, info, self.unit.physical_type, self.label) @classmethod def from_dict(cls, dict): return cls(**dict) def to_dict(self): return {'direction': self.direction, 'unit': self.unit.to_string(), 'value': common.arraytolistrecursive(self._value), 'error': common.arraytolistrecursive(self._error), 'label': self._label, 'normals': common.arraytolistrecursive(self._normals)} @property def call(self): """ Returns --------- * <autofig.call.Call> (<autofig.call.Plot> or <autofig.call.Mesh>): the parent call object. """ return self._call @property def direction(self): """ Returns ------------- * (str) one of 'i', 'x', 'y', 'z', 's', 'c' """ return self._direction @direction.setter def direction(self, direction): """ set the direction """ if not isinstance(direction, str): raise TypeError("direction must be of type str") accepted_values = ['i', 'x', 'y', 'z', 's', 'c'] if direction not in accepted_values: raise ValueError("must be one of: {}".format(accepted_values)) self._direction = direction def _to_unit(self, value, unit=None): if isinstance(value, str): return value if value is None: return value if unit is not None and unit!=u.dimensionless_unscaled: unit = common._convert_unit(unit) value = value*self.unit.to(unit) return value def interpolate_at_i(self, i, unit=None): """ Access the interpolated value at a given value of `i` (independent-variable). Arguments ----------- `i` `unit` (unit or string, optional, default=None) Returns ------------- * (float): the interpolated value Raises ------------ * ValueError: if there is a lenght mismatch """ if isinstance(self.call.i._value, float): if self.call.i._value==i: return self._to_unit(self._value, unit) else: return None # we can't call i._value here because that may point to a string, and # we want this to resolve the array i_value = self.call.i.get_value(linebreak=False, sort_by_indep=False) if len(i_value) != len(self._value): raise ValueError("length mismatch with independent-variable") sort_inds = i_value.argsort() indep_value = i_value[sort_inds] this_value = self._value[sort_inds] if len(self._value.shape) > 1: return np.asarray([self._to_unit(np.interp(i, indep_value, this_value_col, left=np.nan, right=np.nan), unit) for this_value_col in this_value.T]).T return self._to_unit(np.interp(i, indep_value, this_value, left=np.nan, right=np.nan), unit) def highlight_at_i(self, i, unit=None): """ """ if len(self._value.shape)==1 and isinstance(self.call.i.value, np.ndarray): return self.interpolate_at_i(i, unit=unit) else: return self._to_unit(self._value[self._filter_at_i(i, uncover=True, trail=0)].T, unit) def _do_linebreak(self, func='get_value', i=None, unit=None, uncover=None, trail=None, linebreak=None, sort_by_indep=None): """ """ if linebreak is None: linebreak = self.linebreak this_array = getattr(self, func)(i=i, unit=unit, uncover=uncover, trail=trail, linebreak=False) if linebreak is False: return this_array break_direction = linebreak[0] # NOTE: we don't need the unit here since we just use it to find # breakpoints break_array = getattr(self.call, break_direction).get_value(i=i, unit=None, uncover=uncover, trail=trail, linebreak=False, sort_by_indep=sort_by_indep) if linebreak[1] == '+': split_inds = np.where(break_array[1:]-break_array[:-1]>0)[0] elif linebreak[1] == '-': split_inds = np.where(break_array[1:]-break_array[:-1]<0)[0] else: raise NotImplementedError("linebreak='{}' not supported".format(linebreak)) return np.split(this_array, split_inds+1) def _sort_by_indep(self, func='get_value', i=None, iunit=None, unit=None, uncover=None, trail=None, linebreak=None, sort_by_indep=None): """ must be called before (or within) _do_linebreak """ if sort_by_indep is None: # TODO: add property of the call? sort_by_indep = True indep_array = self.call.i.get_value(i=i, unit=iunit, uncover=uncover, trail=trail, linebreak=False, sort_by_indep=False) this_array = getattr(self, func)(i=i, unit=unit, uncover=uncover, trail=trail, linebreak=False, sort_by_indep=False) if not (isinstance(indep_array, np.ndarray) and len(indep_array)==len(this_array)): sort_by_indep = False if sort_by_indep: # TODO: it might be nice to buffer this at the call level, so making # multiple get_value calls doesn't have to recompute the sort-order sort_inds = indep_array.argsort() return this_array[sort_inds] else: return this_array def _get_trail_min(self, i, trail=None): trail = self.call.trail if trail is None else trail # determine length of the trail (if applicable) if trail is not False: if trail is True: # then fallback on 10% default trail_perc = 0.1 else: trail_perc = float(trail) if trail_perc == 0.0: trail_i = i else: all_i = np.hstack(self.call.axes.calls.i.value) trail_i = i - trail_perc*(np.nanmax(all_i) - np.nanmin(all_i)) if trail_i < np.nanmin(self.call.i.get_value(linebreak=False, sort_by_indep=False)): # don't allow extraploating below the lower range trail_i = np.nanmin(self.call.i.get_value(linebreak=False, sort_by_indep=False)) else: trail_i = None return trail_i def _filter_at_i(self, i, uncover=None, trail=None): uncover = self.call.uncover if uncover is None else uncover trail = self.call.trail if trail is None else trail # we can't call i._value here because that may point to a string, and # we want this to resolve the array i_value = self.call.i.get_value(linebreak=False, sort_by_indep=False) if isinstance(i_value, np.ndarray): trues = np.ones(i_value.shape, dtype=bool) else: trues = True if trail is not False: trail_i = self._get_trail_min(i=i, trail=trail) left_filter = i_value >= trail_i - self.call.i.tol else: left_filter = trues if uncover is not False: right_filter = i_value <= i + self.call.i.tol else: right_filter = trues return (left_filter & right_filter) def get_value(self, i=None, unit=None, uncover=None, trail=None, linebreak=None, sort_by_indep=None, exclude_back=False, attr='_value'): """ Access the value for a given value of `i` (independent-variable) depending on which effects (i.e. uncover) are enabled. If `uncover`, `trail`, or `linebreak` are None (default), then the value from the parent <autofig.call.Call> from <autofig.call.CallDimension.call> (probably (<autofig.call.Plot>) will be used. See <autofig.call.Plot.uncover>, <autofig.call.Plot.trail>, <autofig.call.Plot.linebreak>. Arguments ----------- * `i` * `unit` * `uncover` * `trail` * `linebreak` * `sort_by_indep` * `exclude_back` * `attr` Returns ---------- * (array or None) """ value = getattr(self, attr) # could be self._value or self._error if value is None: return None if uncover is None: uncover = self.call.uncover if trail is None: trail = self.call.trail if linebreak is None: linebreak = self.call.linebreak if sort_by_indep is None: # TODO: make this a property of the call? sort_by_indep = True if isinstance(value, str) or isinstance(value, float): if i is None: return self._to_unit(value, unit) elif isinstance(self.call.i.value, float): # then we still want to "select" based on the value of i if self._filter_at_i(i): return value else: return None else: # then we should show either way. For example - a color or # axhline even with i given won't change in i return self._to_unit(value, unit) if isinstance(value, list) or isinstance(value, tuple): value = np.asarray(value) # from here on we're assuming the value is an array, so let's just check # to be sure if not isinstance(value, np.ndarray): raise NotImplementedError("value/error must be a numpy array") if exclude_back and self.call.z.normals is not None and self.call.axes.projection == '2d': value = value[self.call.z.normals >= 0] if linebreak is not False: return self._do_linebreak(func='get{}'.format(attr), i=i, unit=unit, uncover=uncover, trail=trail, linebreak=linebreak, sort_by_indep=sort_by_indep) if sort_by_indep is not False: # if we've made it here, linebreak should already be False (if # linebreak was True, then we'd be within _do_linebreak and those # get_value calls pass linebreak=False) return self._sort_by_indep(func='get{}'.format(attr), i=i, unit=unit, uncover=uncover, trail=trail, linebreak=False, sort_by_indep=sort_by_indep) # from here on, linebreak==False and sort_by_indep==False (if either # were True, then we're within those functions and asking for the original # array) if i is None: if len(value.shape)==1: return self._to_unit(value, unit) else: if isinstance(self.call, Plot): return self._to_unit(value.T, unit) else: return self._to_unit(value, unit) # filter the data as necessary filter_ = self._filter_at_i(i, uncover=uncover, trail=trail) if isinstance(self.call.i.value, float): if filter_: return self._to_unit(value, unit) else: return None if len(value.shape)==1 or isinstance(self.call, FillBetween): # then we're dealing with a flat 1D array if attr == '_value': if trail is not False: trail_i = self._get_trail_min(i) first_point = self.interpolate_at_i(trail_i) if uncover: last_point = self.interpolate_at_i(i) else: first_point = np.nan last_point = np.nan if uncover and trail is not False: concat = (np.array([first_point]), value[filter_], np.array([last_point])) elif uncover: concat = (value[filter_], np.array([last_point])) elif trail: concat = (np.array([first_point]), value[filter_]) else: return self._to_unit(value[filter_], unit) return self._to_unit(np.concatenate(concat), unit) else: # then we need to "select" based on the indep and the value if isinstance(self.call, Plot): return self._to_unit(value[filter_].T, unit) else: return self._to_unit(value[filter_], unit) # for value we need to define the property without decorators because of # this: https://stackoverflow.com/questions/13595607/using-super-in-a-propertys-setter-method-when-using-the-property-decorator-r # and the need to override these in the CallDimensionI class def _get_value(self): """ access the value """ return self.get_value(i=None, unit=None) def _set_value(self, value): """ set the value """ if value is None: self._value = value return # handle casting to acceptable types if isinstance(value, list) or isinstance(value, tuple): value = np.asarray(value) elif isinstance(value, int): value = float(value) if isinstance(value, u.Quantity): if self.unit == u.dimensionless_unscaled: # then take the unit from quantity and apply it self.unit = value.unit value = value.value else: # then convert to the requested unit value = value.to(self.unit).value # handle setting based on type if isinstance(value, np.ndarray): # if len(value.shape) != 1: # raise ValueError("value must be a flat array") self._value = value elif isinstance(value, float): # TODO: do we want to cast to np.array([value])?? # this will most likely be used for axhline/axvline self._value = value elif self.direction=='c' and isinstance(value, str): self._value = common.coloralias.map(value) else: raise TypeError("value must be of type array (or similar), found {} {}".format(type(value), value)) value = property(_get_value, _set_value) def get_error(self, i=None, unit=None, uncover=None, trail=None, linebreak=None, sort_by_indep=None): """ access the error for a given value of i (independent-variable) depending on which effects (i.e. uncover) are enabled. """ return self.get_value(i=i, unit=unit, uncover=uncover, trail=trail, linebreak=linebreak, sort_by_indep=sort_by_indep, attr='_error') @property def error(self): """ access the error """ return self._error @error.setter def error(self, error): """ set the error """ # TODO: check length with value? # TODO: type checks (similar to value) if self.direction not in ['x', 'y', 'z'] and error is not None: raise ValueError("error only accepted for x, y, z dimensions") if isinstance(error, u.Quantity): error = error.to(self.unit).value if isinstance(error, list) or isinstance(error, tuple): error = np.asarray(error) self._error = error @property def unit(self): """ access the unit """ return self._unit @unit.setter def unit(self, unit): """ set the unit """ unit = common._convert_unit(unit) self._unit = unit @property def label(self): """ access the label """ return self._label @label.setter def label(self, label): """ set the label """ if self.direction in ['i'] and label is not None: raise ValueError("label not accepted for indep dimension") if label is None: self._label = label return if not isinstance(label, str): try: label = str(label) except: raise TypeError("label must be of type str") self._label = label @property def normals(self): """ access the normals """ return self._normals @normals.setter def normals(self, normals): """ set the normals """ if self.direction not in ['x', 'y', 'z'] and normals is not None: raise ValueError("normals only accepted for x, y, z dimensions") if normals is None: self._normals = None return if not (isinstance(normals, list) or isinstance(normals, np.ndarray)): raise TypeError("normals must be of type list or array") self._normals = normals class CallDimensionI(CallDimension): def __init__(self, call, value, unit, tol): if isinstance(value, dict): tol = value.get('tol', tol) self.tol = tol super(CallDimensionI, self).__init__('i', call, value, unit) @classmethod def from_dict(cls, dict): return cls(**dict) def to_dict(self): return {'direction': self.direction, 'unit': self.unit.to_string(), 'value': common.arraytolistrecursive(self._value), 'tol': self._tol} @property def tol(self): """ Returns ----------- * (float) tolerance to use when selecting/uncover/trail """ if self._tol is None: return 0.0 return self._tol @tol.setter def tol(self, tol): if not isinstance(tol, float): raise TypeError("tol must be of type float") # TODO: handle units? self._tol = tol @property def value(self): """ access the value """ if isinstance(self._value, str): dimension = self._value return getattr(self.call, dimension).value return super(CallDimensionI, self)._get_value() @value.setter def value(self, value): """ set the value """ # for the indep direction we also allow a string which points to one # of the other available dimensions # TODO: support c, fc, ec? if isinstance(value, common.basestring) and value in ['x', 'y', 'z']: # we'll cast just to get rid of any python2 unicodes self._value = str(value) dimension = value self._unit = getattr(self.call, dimension).unit return # NOTE: cannot do super on setter directly, see this python # bug: https://bugs.python.org/issue14965 and discussion: # https://mail.python.org/pipermail/python-dev/2010-April/099672.html super(CallDimensionI, self)._set_value(value) def get_value(self, *args, **kwargs): if isinstance(self._value, str): dimension = self._value return getattr(self.call, dimension).get_value(*args, **kwargs) return super(CallDimensionI, self).get_value(*args, **kwargs) @property def is_reference(self): """ whether referencing another dimension or its own """ return isinstance(self._value, str) @property def reference(self): """ reference (will return None if not is_reference) """ if self.is_reference: return self._value else: return None class CallDimensionX(CallDimension): def __init__(self, *args): super(CallDimensionX, self).__init__('x', *args) class CallDimensionY(CallDimension): def __init__(self, *args): super(CallDimensionY, self).__init__('y', *args) class CallDimensionZ(CallDimension): def __init__(self, *args): super(CallDimensionZ, self).__init__('z', *args) class CallDimensionS(CallDimension): def __init__(self, call, value, error=None, unit=None, label=None, smap=None, mode=None): if isinstance(value, dict): error = value.get('error', error) smap = value.get('smap', smap) mode = value.get('mode', mode) if error is not None: raise ValueError("error not supported for 's' dimension") self.smap = smap self.mode = mode super(CallDimensionS, self).__init__('s', call, value, error, unit, label) @classmethod def from_dict(cls, dict): return cls(**dict) def to_dict(self): return {'direction': self.direction, 'unit': self.unit.to_string(), 'value': common.arraytolistrecursive(self._value), 'error': common.arraytolistrecursive(self._error), 'label': self._label, 'smap': self._smap, 'mode': self._mode} @property def smap(self): return self._smap @smap.setter def smap(self, smap): if smap is None: self._smap = smap return if not isinstance(smap, tuple): try: smap = tuple(smap) except: raise TypeError('smap must be of type tuple') if not len(smap)==2: raise ValueError('smap must have length 2') self._smap = smap def _mode_split(self, mode=None): if mode is None: mode = self.mode split = mode.split(':') mode_dims = split[0] mode_obj = split[1] if len(split) > 1 else 'axes' mode_mode = split[2] if len(split) > 2 else 'fixed' return mode_dims, mode_obj, mode_mode @property def mode(self): if self._mode is None: return 'xy:figure:fixed' return self._mode @mode.setter def mode(self, mode): if mode is None: self._mode = None return if not isinstance(mode, str): raise TypeError("mode must be of type str") split = mode.split(':') mode_dims, mode_obj, mode_mode = self._mode_split(mode) if len(split) > 3: raise ValueError("mode not recognized") if mode_dims == 'pt' and len(split) > 1: raise ValueError("mode not recognized") if mode_dims not in ['x', 'y', 'xy', 'pt']: raise ValueError("mode not recognized") if mode_obj not in ['axes', 'figure']: raise ValueError("mode not recognized") if mode_mode not in ['fixed', 'current', 'original']: raise ValueError("mode not recognized") if mode_dims == 'pt': self._mode = mode else: self._mode = '{}:{}:{}'.format(mode_dims, mode_obj, mode_mode) class CallDimensionC(CallDimension): def __init__(self, call, value, error=None, unit=None, label=None, cmap=None): if isinstance(value, dict): error = value.get('error', error) cmap = value.get('cmap', cmap) if error is not None: raise ValueError("error not supported for 'c' dimension") self.cmap = cmap super(CallDimensionC, self).__init__('c', call, value, error, unit, label) @classmethod def from_dict(cls, dict): return cls(**dict) def to_dict(self): return {'direction': self.direction, 'unit': self.unit.to_string(), 'value': common.arraytolistrecursive(self._value), 'error': common.arraytolistrecursive(self._error), 'label': self._label, 'cmap': self._cmap} @property def cmap(self): return self._cmap @cmap.setter def cmap(self, cmap): # print("setting call cmap: {}".format(cmap)) try: cmap_ = plt.get_cmap(cmap) except: raise TypeError("could not find cmap") self._cmap = cmap
gpl-3.0
CforED/Machine-Learning
sklearn/gaussian_process/tests/test_kernels.py
23
11813
"""Testing for kernels for Gaussian processes.""" # Author: Jan Hendrik Metzen <[email protected]> # Licence: BSD 3 clause from collections import Hashable from sklearn.externals.funcsigs import signature import numpy as np from scipy.optimize import approx_fprime from sklearn.metrics.pairwise \ import PAIRWISE_KERNEL_FUNCTIONS, euclidean_distances, pairwise_kernels from sklearn.gaussian_process.kernels \ import (RBF, Matern, RationalQuadratic, ExpSineSquared, DotProduct, ConstantKernel, WhiteKernel, PairwiseKernel, KernelOperator, Exponentiation) from sklearn.base import clone from sklearn.utils.testing import (assert_equal, assert_almost_equal, assert_not_equal, assert_array_equal, assert_array_almost_equal) X = np.random.RandomState(0).normal(0, 1, (10, 2)) Y = np.random.RandomState(0).normal(0, 1, (11, 2)) kernel_white = RBF(length_scale=2.0) + WhiteKernel(noise_level=3.0) kernels = [RBF(length_scale=2.0), RBF(length_scale_bounds=(0.5, 2.0)), ConstantKernel(constant_value=10.0), 2.0 * RBF(length_scale=0.33, length_scale_bounds="fixed"), 2.0 * RBF(length_scale=0.5), kernel_white, 2.0 * RBF(length_scale=[0.5, 2.0]), 2.0 * Matern(length_scale=0.33, length_scale_bounds="fixed"), 2.0 * Matern(length_scale=0.5, nu=0.5), 2.0 * Matern(length_scale=1.5, nu=1.5), 2.0 * Matern(length_scale=2.5, nu=2.5), 2.0 * Matern(length_scale=[0.5, 2.0], nu=0.5), 3.0 * Matern(length_scale=[2.0, 0.5], nu=1.5), 4.0 * Matern(length_scale=[0.5, 0.5], nu=2.5), RationalQuadratic(length_scale=0.5, alpha=1.5), ExpSineSquared(length_scale=0.5, periodicity=1.5), DotProduct(sigma_0=2.0), DotProduct(sigma_0=2.0) ** 2] for metric in PAIRWISE_KERNEL_FUNCTIONS: if metric in ["additive_chi2", "chi2"]: continue kernels.append(PairwiseKernel(gamma=1.0, metric=metric)) def test_kernel_gradient(): """ Compare analytic and numeric gradient of kernels. """ for kernel in kernels: K, K_gradient = kernel(X, eval_gradient=True) assert_equal(K_gradient.shape[0], X.shape[0]) assert_equal(K_gradient.shape[1], X.shape[0]) assert_equal(K_gradient.shape[2], kernel.theta.shape[0]) K_gradient_approx = np.empty_like(K_gradient) for i in range(K.shape[0]): for j in range(K.shape[1]): def eval_kernel_ij_for_theta(theta): kernel_clone = kernel.clone_with_theta(theta) K = kernel_clone(X, eval_gradient=False) return K[i, j] K_gradient_approx[i, j] = \ approx_fprime(kernel.theta, eval_kernel_ij_for_theta, 1e-10) assert_almost_equal(K_gradient, K_gradient_approx, 4) def test_kernel_theta(): """ Check that parameter vector theta of kernel is set correctly. """ for kernel in kernels: if isinstance(kernel, KernelOperator) \ or isinstance(kernel, Exponentiation): # skip non-basic kernels continue theta = kernel.theta _, K_gradient = kernel(X, eval_gradient=True) # Determine kernel parameters that contribute to theta init_sign = signature(kernel.__class__.__init__).parameters.values() args = [p.name for p in init_sign if p.name != 'self'] theta_vars = map(lambda s: s.rstrip("_bounds"), filter(lambda s: s.endswith("_bounds"), args)) assert_equal( set(hyperparameter.name for hyperparameter in kernel.hyperparameters), set(theta_vars)) # Check that values returned in theta are consistent with # hyperparameter values (being their logarithms) for i, hyperparameter in enumerate(kernel.hyperparameters): assert_equal(theta[i], np.log(getattr(kernel, hyperparameter.name))) # Fixed kernel parameters must be excluded from theta and gradient. for i, hyperparameter in enumerate(kernel.hyperparameters): # create copy with certain hyperparameter fixed params = kernel.get_params() params[hyperparameter.name + "_bounds"] = "fixed" kernel_class = kernel.__class__ new_kernel = kernel_class(**params) # Check that theta and K_gradient are identical with the fixed # dimension left out _, K_gradient_new = new_kernel(X, eval_gradient=True) assert_equal(theta.shape[0], new_kernel.theta.shape[0] + 1) assert_equal(K_gradient.shape[2], K_gradient_new.shape[2] + 1) if i > 0: assert_equal(theta[:i], new_kernel.theta[:i]) assert_array_equal(K_gradient[..., :i], K_gradient_new[..., :i]) if i + 1 < len(kernel.hyperparameters): assert_equal(theta[i+1:], new_kernel.theta[i:]) assert_array_equal(K_gradient[..., i+1:], K_gradient_new[..., i:]) # Check that values of theta are modified correctly for i, hyperparameter in enumerate(kernel.hyperparameters): theta[i] = np.log(42) kernel.theta = theta assert_almost_equal(getattr(kernel, hyperparameter.name), 42) setattr(kernel, hyperparameter.name, 43) assert_almost_equal(kernel.theta[i], np.log(43)) def test_auto_vs_cross(): """ Auto-correlation and cross-correlation should be consistent. """ for kernel in kernels: if kernel == kernel_white: continue # Identity is not satisfied on diagonal K_auto = kernel(X) K_cross = kernel(X, X) assert_almost_equal(K_auto, K_cross, 5) def test_kernel_diag(): """ Test that diag method of kernel returns consistent results. """ for kernel in kernels: K_call_diag = np.diag(kernel(X)) K_diag = kernel.diag(X) assert_almost_equal(K_call_diag, K_diag, 5) def test_kernel_operator_commutative(): """ Adding kernels and multiplying kernels should be commutative. """ # Check addition assert_almost_equal((RBF(2.0) + 1.0)(X), (1.0 + RBF(2.0))(X)) # Check multiplication assert_almost_equal((3.0 * RBF(2.0))(X), (RBF(2.0) * 3.0)(X)) def test_kernel_anisotropic(): """ Anisotropic kernel should be consistent with isotropic kernels.""" kernel = 3.0 * RBF([0.5, 2.0]) K = kernel(X) X1 = np.array(X) X1[:, 0] *= 4 K1 = 3.0 * RBF(2.0)(X1) assert_almost_equal(K, K1) X2 = np.array(X) X2[:, 1] /= 4 K2 = 3.0 * RBF(0.5)(X2) assert_almost_equal(K, K2) # Check getting and setting via theta kernel.theta = kernel.theta + np.log(2) assert_array_equal(kernel.theta, np.log([6.0, 1.0, 4.0])) assert_array_equal(kernel.k2.length_scale, [1.0, 4.0]) def test_kernel_stationary(): """ Test stationarity of kernels.""" for kernel in kernels: if not kernel.is_stationary(): continue K = kernel(X, X + 1) assert_almost_equal(K[0, 0], np.diag(K)) def test_kernel_clone(): """ Test that sklearn's clone works correctly on kernels. """ for kernel in kernels: kernel_cloned = clone(kernel) assert_equal(kernel, kernel_cloned) assert_not_equal(id(kernel), id(kernel_cloned)) for attr in kernel.__dict__.keys(): attr_value = getattr(kernel, attr) attr_value_cloned = getattr(kernel_cloned, attr) if attr.startswith("hyperparameter_"): assert_equal(attr_value.name, attr_value_cloned.name) assert_equal(attr_value.value_type, attr_value_cloned.value_type) assert_array_equal(attr_value.bounds, attr_value_cloned.bounds) assert_equal(attr_value.n_elements, attr_value_cloned.n_elements) elif np.iterable(attr_value): for i in range(len(attr_value)): if np.iterable(attr_value[i]): assert_array_equal(attr_value[i], attr_value_cloned[i]) else: assert_equal(attr_value[i], attr_value_cloned[i]) else: assert_equal(attr_value, attr_value_cloned) if not isinstance(attr_value, Hashable): # modifiable attributes must not be identical assert_not_equal(id(attr_value), id(attr_value_cloned)) def test_matern_kernel(): """ Test consistency of Matern kernel for special values of nu. """ K = Matern(nu=1.5, length_scale=1.0)(X) # the diagonal elements of a matern kernel are 1 assert_array_almost_equal(np.diag(K), np.ones(X.shape[0])) # matern kernel for coef0==0.5 is equal to absolute exponential kernel K_absexp = np.exp(-euclidean_distances(X, X, squared=False)) K = Matern(nu=0.5, length_scale=1.0)(X) assert_array_almost_equal(K, K_absexp) # test that special cases of matern kernel (coef0 in [0.5, 1.5, 2.5]) # result in nearly identical results as the general case for coef0 in # [0.5 + tiny, 1.5 + tiny, 2.5 + tiny] tiny = 1e-10 for nu in [0.5, 1.5, 2.5]: K1 = Matern(nu=nu, length_scale=1.0)(X) K2 = Matern(nu=nu + tiny, length_scale=1.0)(X) assert_array_almost_equal(K1, K2) def test_kernel_versus_pairwise(): """Check that GP kernels can also be used as pairwise kernels.""" for kernel in kernels: # Test auto-kernel if kernel != kernel_white: # For WhiteKernel: k(X) != k(X,X). This is assumed by # pairwise_kernels K1 = kernel(X) K2 = pairwise_kernels(X, metric=kernel) assert_array_almost_equal(K1, K2) # Test cross-kernel K1 = kernel(X, Y) K2 = pairwise_kernels(X, Y, metric=kernel) assert_array_almost_equal(K1, K2) def test_set_get_params(): """Check that set_params()/get_params() is consistent with kernel.theta.""" for kernel in kernels: # Test get_params() index = 0 params = kernel.get_params() for hyperparameter in kernel.hyperparameters: if hyperparameter.bounds is "fixed": continue size = hyperparameter.n_elements if size > 1: # anisotropic kernels assert_almost_equal(np.exp(kernel.theta[index:index+size]), params[hyperparameter.name]) index += size else: assert_almost_equal(np.exp(kernel.theta[index]), params[hyperparameter.name]) index += 1 # Test set_params() index = 0 value = 10 # arbitrary value for hyperparameter in kernel.hyperparameters: if hyperparameter.bounds is "fixed": continue size = hyperparameter.n_elements if size > 1: # anisotropic kernels kernel.set_params(**{hyperparameter.name: [value]*size}) assert_almost_equal(np.exp(kernel.theta[index:index+size]), [value]*size) index += size else: kernel.set_params(**{hyperparameter.name: value}) assert_almost_equal(np.exp(kernel.theta[index]), value) index += 1
bsd-3-clause
brandsoulmates/incubator-airflow
airflow/contrib/plugins/metastore_browser/main.py
62
5773
# -*- coding: utf-8 -*- # # 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. from datetime import datetime import json from flask import Blueprint, request from flask_admin import BaseView, expose import pandas as pd from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook import MySqlHook from airflow.hooks.presto_hook import PrestoHook from airflow.plugins_manager import AirflowPlugin from airflow.www import utils as wwwutils METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB = 'default' DB_WHITELIST = None DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT = 2000 # Keeping pandas from truncating long strings pd.set_option('display.max_colwidth', -1) # Creating a flask admin BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def index(self): sql = """ SELECT a.name as db, db_location_uri as location, count(1) as object_count, a.desc as description FROM DBS a JOIN TBLS b ON a.DB_ID = b.DB_ID GROUP BY a.name, db_location_uri, a.desc """.format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) df.db = ( '<a href="/admin/metastorebrowserview/db/?db=' + df.db + '">' + df.db + '</a>') table = df.to_html( classes="table table-striped table-bordered table-hover", index=False, escape=False, na_rep='',) return self.render( "metastore_browser/dbs.html", table=table) @expose('/table/') def table(self): table_name = request.args.get("table") m = HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name) return self.render( "metastore_browser/table.html", table=table, table_name=table_name, datetime=datetime, int=int) @expose('/db/') def db(self): db = request.args.get("db") m = HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db), key=lambda x: x.tableName) return self.render( "metastore_browser/db.html", tables=tables, db=db) @wwwutils.gzipped @expose('/partitions/') def partitions(self): schema, table = request.args.get("table").split('.') sql = """ SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS a JOIN TBLS b ON a.TBL_ID = b.TBL_ID JOIN DBS d ON b.DB_ID = d.DB_ID JOIN SDS c ON a.SD_ID = c.SD_ID WHERE b.TBL_NAME like '{table}' AND d.NAME like '{schema}' ORDER BY PART_NAME DESC """.format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes="table table-striped table-bordered table-hover", index=False, na_rep='',) @wwwutils.gzipped @expose('/objects/') def objects(self): where_clause = '' if DB_WHITELIST: dbs = ",".join(["'" + db + "'" for db in DB_WHITELIST]) where_clause = "AND b.name IN ({})".format(dbs) if DB_BLACKLIST: dbs = ",".join(["'" + db + "'" for db in DB_BLACKLIST]) where_clause = "AND b.name NOT IN ({})".format(dbs) sql = """ SELECT CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE FROM TBLS a JOIN DBS b ON a.DB_ID = b.DB_ID WHERE a.TBL_NAME NOT LIKE '%tmp%' AND a.TBL_NAME NOT LIKE '%temp%' AND b.NAME NOT LIKE '%tmp%' AND b.NAME NOT LIKE '%temp%' {where_clause} LIMIT {LIMIT}; """.format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID) d = [ {'id': row[0], 'text': row[0]} for row in h.get_records(sql)] return json.dumps(d) @wwwutils.gzipped @expose('/data/') def data(self): table = request.args.get("table") sql = "SELECT * FROM {table} LIMIT 1000;".format(table=table) h = PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes="table table-striped table-bordered table-hover", index=False, na_rep='',) @expose('/ddl/') def ddl(self): table = request.args.get("table") sql = "SHOW CREATE TABLE {table};".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v = MetastoreBrowserView(category="Plugins", name="Hive Metadata Browser") # Creating a flask blueprint to intergrate the templates and static folder bp = Blueprint( "metastore_browser", __name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') # Defining the plugin class class MetastoreBrowserPlugin(AirflowPlugin): name = "metastore_browser" flask_blueprints = [bp] admin_views = [v]
apache-2.0
AartGoossens/wblib
wblib/models.py
1
6916
import matplotlib.pyplot as plt import numpy as np import pandas as pd from pandas.core.accessor import AccessorProperty import pandas.plotting._core as gfx from .client import WattbikeHubClient from .tools import polar_force_column_labels, flatten class WattbikeFramePlotMethods(gfx.FramePlotMethods): polar_angles = np.arange(90, 451) / (180 / np.pi) polar_force_columns = polar_force_column_labels() def _plot_single_polar(self, ax, polar_forces, mean, *args, **kwargs): if 'linewidth' in kwargs: linewidth = kwargs.pop('linewidth') elif mean: linewidth = 3 else: linewidth = 0.5 ax.plot(self.polar_angles, polar_forces, linewidth=linewidth, *args, **kwargs) def polar(self, full=False, mean=True, *args, **kwargs): ax = plt.subplot(111, projection='polar') if full: for i in range(0, len(self._data) - 50, 50): forces = self._data.iloc[i:i + 50, self._data.columns.get_indexer(self.polar_force_columns)].mean() self._plot_single_polar(ax, forces, mean=False, *args, **kwargs) if mean: forces = self._data[self.polar_force_columns].mean() self._plot_single_polar(ax, forces, mean=True, *args, **kwargs) xticks_num = 8 xticks = np.arange(0, xticks_num, 2 * np.pi / xticks_num) ax.set_xticks(xticks) rad_to_label = lambda i: '{}°'.format(int(i / (2 * np.pi) * 360 - 90) % 180) ax.set_xticklabels([rad_to_label(i) for i in xticks]) ax.set_yticklabels([]) return ax class WattbikeDataFrame(pd.DataFrame): @property def _constructor(self): return WattbikeDataFrame def load(self, session_id): client = WattbikeHubClient() if not isinstance(session_id, list): session_id = [session_id] for session in session_id: session_data, ride_session = client.get_session(session) wdf = self._raw_session_to_wdf(session_data, ride_session) self = self.append(wdf) return self def load_for_user(self, user_id, before=None, after=None): client = WattbikeHubClient() if not isinstance(user_id, list): user_id = [user_id] for ID in user_id: sessions = client.get_sessions_for_user( user_id=ID, before=before, after=after ) for session_data, ride_session in sessions: wdf = self._raw_session_to_wdf(session_data, ride_session) self = self.append(wdf) return self def _raw_session_to_wdf(self, session_data, ride_session): wdf = WattbikeDataFrame( [flatten(rev) for lap in session_data['laps'] for rev in lap['data']]) wdf['time'] = wdf.time.cumsum() wdf['user_id'] = ride_session.get_user_id() wdf['session_id'] = ride_session.get_session_id() self._process(wdf) return wdf def _process(self, wdf): wdf = wdf._columns_to_numeric() wdf = wdf._add_polar_forces() wdf = wdf._add_min_max_angles() wdf = self._enrich_with_athlete_performance_state(wdf) return wdf def _columns_to_numeric(self): for col in self.columns: try: self.iloc[:, self.columns.get_loc(col)] = pd.to_numeric(self.iloc[:, self.columns.get_loc(col)]) except ValueError: continue return self def _add_polar_forces(self): _df = pd.DataFrame() new_angles = np.arange(0.0, 361.0) column_labels = polar_force_column_labels() if not '_0' in self.columns: for label in column_labels: self[label] = np.nan for index, pf in self.polar_force.iteritems(): if not isinstance(pf, str): continue forces = [int(i) for i in pf.split(',')] forces = np.array(forces + [forces[0]]) forces = forces/np.mean(forces) angle_dx = 360.0 / (len(forces)-1) forces_interp = np.interp( x=new_angles, xp=np.arange(0, 360.01, angle_dx), fp=forces) _df[index] = forces_interp _df['angle'] = column_labels _df.set_index('angle', inplace=True) _df = _df.transpose() for angle in column_labels: self[angle] = _df[angle] return self def _add_min_max_angles(self): # @TODO this method is quite memory inefficient. Row by row calculation is better pf_columns = polar_force_column_labels() pf_T = self.loc[:, pf_columns].transpose().reset_index(drop=True) left_max_angle = pf_T.iloc[:180].idxmax() right_max_angle = pf_T.iloc[180:].idxmax() - 180 left_min_angle = pd.concat([pf_T.iloc[:135], pf_T.iloc[315:]]).idxmin() right_min_angle = pf_T.iloc[135:315].idxmin() - 180 self['left_max_angle'] = pd.DataFrame(left_max_angle) self['right_max_angle'] = pd.DataFrame(right_max_angle) self['left_min_angle'] = pd.DataFrame(left_min_angle) self['right_min_angle'] = pd.DataFrame(right_min_angle) return self def _enrich_with_athlete_performance_state(self, wdf): if not hasattr(self, 'peformance_states'): self.performance_states = {} percentage_of_mhr = [] percentage_of_mmp = [] percentage_of_ftp = [] for index, row in wdf.iterrows(): if row.user_id not in self.performance_states: self.performance_states[row.user_id] = \ WattbikeHubClient().get_user_performance_state(row.user_id) ps = self.performance_states[row.user_id] percentage_of_mmp.append(row.power/ps.get_max_minute_power()) percentage_of_ftp.append(row.power/ps.get_ftp()) try: percentage_of_mhr.append(row.heartrate/ps.get_max_hr()) except AttributeError: percentage_of_mhr.append(np.nan) wdf['percentage_of_mhr'] = percentage_of_mhr wdf['percentage_of_mmp'] = percentage_of_mmp wdf['percentage_of_ftp'] = percentage_of_ftp return wdf def average_by_session(self): averaged = self._average_by_column('session_id') averaged['user_id'] = averaged.session_id.apply( lambda x: self.loc[self.session_id == x].iloc[0].user_id) return averaged def average_by_user(self): return self._average_by_column('user_id') def _average_by_column(self, column_name): averaged_self = self.groupby(column_name).mean().reset_index() return WattbikeDataFrame(averaged_self) WattbikeDataFrame.plot = AccessorProperty(WattbikeFramePlotMethods, WattbikeFramePlotMethods)
mit
thilbern/scikit-learn
sklearn/utils/validation.py
11
13372
"""Utilities for input validation""" # Authors: Olivier Grisel # Gael Varoquaux # Andreas Mueller # Lars Buitinck # Alexandre Gramfort # Nicolas Tresegnie # License: BSD 3 clause import warnings import numbers import numpy as np import scipy.sparse as sp from ..externals import six from inspect import getargspec class DataConversionWarning(UserWarning): "A warning on implicit data conversions happening in the code" pass warnings.simplefilter("always", DataConversionWarning) class NonBLASDotWarning(UserWarning): "A warning on implicit dispatch to numpy.dot" pass # Silenced by default to reduce verbosity. Turn on at runtime for # performance profiling. warnings.simplefilter('ignore', NonBLASDotWarning) def _assert_all_finite(X): """Like assert_all_finite, but only for ndarray.""" X = np.asanyarray(X) # First try an O(n) time, O(1) space solution for the common case that # everything is finite; fall back to O(n) space np.isfinite to prevent # false positives from overflow in sum method. if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum()) and not np.isfinite(X).all()): raise ValueError("Input contains NaN, infinity" " or a value too large for %r." % X.dtype) def assert_all_finite(X): """Throw a ValueError if X contains NaN or infinity. Input MUST be an np.ndarray instance or a scipy.sparse matrix.""" _assert_all_finite(X.data if sp.issparse(X) else X) def as_float_array(X, copy=True, force_all_finite=True): """Converts an array-like to an array of floats The new dtype will be np.float32 or np.float64, depending on the original type. The function can create a copy or modify the argument depending on the argument copy. Parameters ---------- X : {array-like, sparse matrix} copy : bool, optional If True, a copy of X will be created. If False, a copy may still be returned if X's dtype is not a floating point type. Returns ------- XT : {array, sparse matrix} An array of type np.float """ if isinstance(X, np.matrix) or (not isinstance(X, np.ndarray) and not sp.issparse(X)): return check_array(X, ['csr', 'csc', 'coo'], dtype=np.float64, copy=copy, force_all_finite=force_all_finite, ensure_2d=False) elif sp.issparse(X) and X.dtype in [np.float32, np.float64]: return X.copy() if copy else X elif X.dtype in [np.float32, np.float64]: # is numpy array return X.copy('F' if X.flags['F_CONTIGUOUS'] else 'C') if copy else X else: return X.astype(np.float32 if X.dtype == np.int32 else np.float64) def _num_samples(x): """Return number of samples in array-like x.""" if not hasattr(x, '__len__') and not hasattr(x, 'shape'): if hasattr(x, '__array__'): x = np.asarray(x) else: raise TypeError("Expected sequence or array-like, got %r" % x) return x.shape[0] if hasattr(x, 'shape') else len(x) def check_consistent_length(*arrays): """Check that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. Parameters ---------- arrays : list or tuple of input objects. Objects that will be checked for consistent length. """ uniques = np.unique([_num_samples(X) for X in arrays if X is not None]) if len(uniques) > 1: raise ValueError("Found arrays with inconsistent numbers of samples: %s" % str(uniques)) def indexable(*iterables): """Make arrays indexable for cross-validation. Checks consistent length, passes through None, and ensures that everything can be indexed by converting sparse matrices to csr and converting non-interable objects to arrays. Parameters ---------- iterables : lists, dataframes, arrays, sparse matrices List of objects to ensure sliceability. """ result = [] for X in iterables: if sp.issparse(X): result.append(X.tocsr()) elif hasattr(X, "__getitem__") or hasattr(X, "iloc"): result.append(X) elif X is None: result.append(X) else: result.append(np.array(X)) check_consistent_length(*result) return result def _ensure_sparse_format(spmatrix, accept_sparse, dtype, order, copy, force_all_finite): """Convert a sparse matrix to a given format. Checks the sparse format of spmatrix and converts if necessary. Parameters ---------- spmatrix : scipy sparse matrix Input to validate and convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats ('csc', 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default=none) Data type of result. If None, the dtype of the input is preserved. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. Returns ------- spmatrix_converted : scipy sparse matrix. Matrix that is ensured to have an allowed type. """ if accept_sparse is None: raise TypeError('A sparse matrix was passed, but dense ' 'data is required. Use X.toarray() to ' 'convert to a dense numpy array.') sparse_type = spmatrix.format if dtype is None: dtype = spmatrix.dtype if sparse_type in accept_sparse: # correct type if dtype == spmatrix.dtype: # correct dtype if copy: spmatrix = spmatrix.copy() else: # convert dtype spmatrix = spmatrix.astype(dtype) else: # create new spmatrix = spmatrix.asformat(accept_sparse[0]).astype(dtype) if force_all_finite: if not hasattr(spmatrix, "data"): warnings.warn("Can't check %s sparse matrix for nan or inf." % spmatrix.format) else: _assert_all_finite(spmatrix.data) if hasattr(spmatrix, "data"): spmatrix.data = np.array(spmatrix.data, copy=False, order=order) return spmatrix def check_array(array, accept_sparse=None, dtype=None, order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False): """Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. Parameters ---------- array : object Input object to check / convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default=none) Data type of result. If None, the dtype of the input is preserved. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. ensure_2d : boolean (default=True) Whether to make X at least 2d. allow_nd : boolean (default=False) Whether to allow X.ndim > 2. Returns ------- X_converted : object The converted and validated X. """ if isinstance(accept_sparse, str): accept_sparse = [accept_sparse] if sp.issparse(array): array = _ensure_sparse_format(array, accept_sparse, dtype, order, copy, force_all_finite) else: if ensure_2d: array = np.atleast_2d(array) array = np.array(array, dtype=dtype, order=order, copy=copy) if not allow_nd and array.ndim >= 3: raise ValueError("Found array with dim %d. Expected <= 2" % array.ndim) if force_all_finite: _assert_all_finite(array) return array def check_X_y(X, y, accept_sparse=None, dtype=None, order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, multi_output=False): """Input validation for standard estimators. Checks X and y for consistent length, enforces X 2d and y 1d. Standard input checks are only applied to y. For multi-label y, set multi_ouput=True to allow 2d and sparse y. Parameters ---------- X : nd-array, list or sparse matrix Input data. y : nd-array, list or sparse matrix Labels. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default=none) Data type of result. If None, the dtype of the input is preserved. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. ensure_2d : boolean (default=True) Whether to make X at least 2d. allow_nd : boolean (default=False) Whether to allow X.ndim > 2. multi_output : boolean (default=False) Whether to allow 2-d y (array or sparse matrix). If false, y will be validated as a vector. Returns ------- X_converted : object The converted and validated X. """ X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd) if multi_output: y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False) else: y = column_or_1d(y, warn=True) _assert_all_finite(y) check_consistent_length(X, y) return X, y def column_or_1d(y, warn=False): """ Ravel column or 1d numpy array, else raises an error Parameters ---------- y : array-like Returns ------- y : array """ shape = np.shape(y) if len(shape) == 1: return np.ravel(y) if len(shape) == 2 and shape[1] == 1: if warn: warnings.warn("A column-vector y was passed when a 1d array was" " expected. Please change the shape of y to " "(n_samples, ), for example using ravel().", DataConversionWarning, stacklevel=2) return np.ravel(y) raise ValueError("bad input shape {0}".format(shape)) def warn_if_not_float(X, estimator='This algorithm'): """Warning utility function to check that data type is floating point. Returns True if a warning was raised (i.e. the input is not float) and False otherwise, for easier input validation. """ if not isinstance(estimator, six.string_types): estimator = estimator.__class__.__name__ if X.dtype.kind != 'f': warnings.warn("%s assumes floating point values as input, " "got %s" % (estimator, X.dtype)) return True return False def check_random_state(seed): """Turn seed into a np.random.RandomState instance If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (numbers.Integral, np.integer)): return np.random.RandomState(seed) if isinstance(seed, np.random.RandomState): return seed raise ValueError('%r cannot be used to seed a numpy.random.RandomState' ' instance' % seed) def has_fit_parameter(estimator, parameter): """ Checks whether the estimator's fit method supports the given parameter. Example ------- >>> from sklearn.svm import SVC >>> has_fit_parameter(SVC(), "sample_weight") True """ return parameter in getargspec(estimator.fit)[0]
bsd-3-clause
jkarnows/scikit-learn
examples/classification/plot_lda_qda.py
164
4806
""" ==================================================================== Linear and Quadratic Discriminant Analysis with confidence ellipsoid ==================================================================== Plot the confidence ellipsoids of each class and decision boundary """ print(__doc__) from scipy import linalg import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import colors from sklearn.lda import LDA from sklearn.qda import QDA ############################################################################### # colormap cmap = colors.LinearSegmentedColormap( 'red_blue_classes', {'red': [(0, 1, 1), (1, 0.7, 0.7)], 'green': [(0, 0.7, 0.7), (1, 0.7, 0.7)], 'blue': [(0, 0.7, 0.7), (1, 1, 1)]}) plt.cm.register_cmap(cmap=cmap) ############################################################################### # generate datasets def dataset_fixed_cov(): '''Generate 2 Gaussians samples with the same covariance matrix''' n, dim = 300, 2 np.random.seed(0) C = np.array([[0., -0.23], [0.83, .23]]) X = np.r_[np.dot(np.random.randn(n, dim), C), np.dot(np.random.randn(n, dim), C) + np.array([1, 1])] y = np.hstack((np.zeros(n), np.ones(n))) return X, y def dataset_cov(): '''Generate 2 Gaussians samples with different covariance matrices''' n, dim = 300, 2 np.random.seed(0) C = np.array([[0., -1.], [2.5, .7]]) * 2. X = np.r_[np.dot(np.random.randn(n, dim), C), np.dot(np.random.randn(n, dim), C.T) + np.array([1, 4])] y = np.hstack((np.zeros(n), np.ones(n))) return X, y ############################################################################### # plot functions def plot_data(lda, X, y, y_pred, fig_index): splot = plt.subplot(2, 2, fig_index) if fig_index == 1: plt.title('Linear Discriminant Analysis') plt.ylabel('Data with fixed covariance') elif fig_index == 2: plt.title('Quadratic Discriminant Analysis') elif fig_index == 3: plt.ylabel('Data with varying covariances') tp = (y == y_pred) # True Positive tp0, tp1 = tp[y == 0], tp[y == 1] X0, X1 = X[y == 0], X[y == 1] X0_tp, X0_fp = X0[tp0], X0[~tp0] X1_tp, X1_fp = X1[tp1], X1[~tp1] xmin, xmax = X[:, 0].min(), X[:, 0].max() ymin, ymax = X[:, 1].min(), X[:, 1].max() # class 0: dots plt.plot(X0_tp[:, 0], X0_tp[:, 1], 'o', color='red') plt.plot(X0_fp[:, 0], X0_fp[:, 1], '.', color='#990000') # dark red # class 1: dots plt.plot(X1_tp[:, 0], X1_tp[:, 1], 'o', color='blue') plt.plot(X1_fp[:, 0], X1_fp[:, 1], '.', color='#000099') # dark blue # class 0 and 1 : areas nx, ny = 200, 100 x_min, x_max = plt.xlim() y_min, y_max = plt.ylim() xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx), np.linspace(y_min, y_max, ny)) Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()]) Z = Z[:, 1].reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap='red_blue_classes', norm=colors.Normalize(0., 1.)) plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='k') # means plt.plot(lda.means_[0][0], lda.means_[0][1], 'o', color='black', markersize=10) plt.plot(lda.means_[1][0], lda.means_[1][1], 'o', color='black', markersize=10) return splot def plot_ellipse(splot, mean, cov, color): v, w = linalg.eigh(cov) u = w[0] / linalg.norm(w[0]) angle = np.arctan(u[1] / u[0]) angle = 180 * angle / np.pi # convert to degrees # filled Gaussian at 2 standard deviation ell = mpl.patches.Ellipse(mean, 2 * v[0] ** 0.5, 2 * v[1] ** 0.5, 180 + angle, color=color) ell.set_clip_box(splot.bbox) ell.set_alpha(0.5) splot.add_artist(ell) splot.set_xticks(()) splot.set_yticks(()) def plot_lda_cov(lda, splot): plot_ellipse(splot, lda.means_[0], lda.covariance_, 'red') plot_ellipse(splot, lda.means_[1], lda.covariance_, 'blue') def plot_qda_cov(qda, splot): plot_ellipse(splot, qda.means_[0], qda.covariances_[0], 'red') plot_ellipse(splot, qda.means_[1], qda.covariances_[1], 'blue') ############################################################################### for i, (X, y) in enumerate([dataset_fixed_cov(), dataset_cov()]): # LDA lda = LDA(solver="svd", store_covariance=True) y_pred = lda.fit(X, y).predict(X) splot = plot_data(lda, X, y, y_pred, fig_index=2 * i + 1) plot_lda_cov(lda, splot) plt.axis('tight') # QDA qda = QDA() y_pred = qda.fit(X, y, store_covariances=True).predict(X) splot = plot_data(qda, X, y, y_pred, fig_index=2 * i + 2) plot_qda_cov(qda, splot) plt.axis('tight') plt.suptitle('LDA vs QDA') plt.show()
bsd-3-clause
liqiangnlp/LiNMT
scripts/bar.figure/systems-bleu-score-cwmt.py
1
3227
#!/usr/bin/env python #-*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams from matplotlib.ticker import MultipleLocator, FormatStrFormatter rcParams['grid.linestyle'] = ':' def autolabel(rects): for rect in rects: height = rect.get_height() plt.text(rect.get_x()+rect.get_width()/4, height + 1.5, '%s' % float(height), rotation=90, fontsize=10) def drawBarChartPoseRatio(): n_groups = 2 ''' bleu-4 / bleu-sbp-5 newsdev2017 cwmt2011 cwmt2009 2-2 NiuSMT.biglm : 14.20 17.59 30.90 31.29 31.50 32.61 3 NMT-UM-baseline : 17.40 20.44 37.71 36.85 39.75 38.88 4 NMT-UM-bpe : 17.60 20.91 37.30 36.66 39.90 39.43 4-1 NMT-UM-bpe-finetune : 17.70 20.86 37.80 37.18 40.00 39.53 5 NMT-UM-bpe-finetune-synthetic: 17.89 21.44 36.21 36.26 38.46 38.78 5-1 ensemble-4 &4-1&5 : 18.41 21.81 38.65 38.03 40.76 41.89 5-2 avg-4&4-1&5 : 18.24 21.61 38.28 37.67 40.88 40.39 9 NMT-NEU-bpe (nematus) : 16.73 20.73 34.06 36.51 40.27 39.94 ''' smt_um_biglm = (31.29, 32.61) nmt_um_baseline = (36.85, 38.88) nmt_um_bpe = (36.66, 39.43) nmt_um_bpe_finetune = (37.18, 39.53) nmt_um_bpe_finetune_syn = (36.26, 38.78) nmt_um_ensemble = (38.03, 41.89) nematus = (36.51, 39.94) fig, ax = plt.subplots() index = np.arange(n_groups) bar_width = 0.2 #opacity = 0.4 opacity = 1 #plt.grid() yminorLocator = MultipleLocator(1) ax.yaxis.set_minor_locator(yminorLocator) ax.yaxis.grid(True, which='minor') rects1 = plt.bar(index, nmt_um_baseline, bar_width / 2, alpha=opacity, color='m', label='$li-baseline$') rects2 = plt.bar(index + bar_width / 2, nmt_um_bpe, bar_width / 2, alpha=opacity, color='g', label='$li-bpe$') rects3 = plt.bar(index + bar_width, nmt_um_bpe_finetune, bar_width / 2, alpha=opacity, color='c', label='$li-bpe-fine$') rects4 = plt.bar(index + 1.5 * bar_width, nmt_um_bpe_finetune_syn, bar_width / 2, alpha=opacity, color='b', label='$li-bpe-fine-syn$') rects5 = plt.bar(index + 2 * bar_width, nmt_um_ensemble, bar_width / 2, alpha=opacity, color='r', label='$li-ensemble$') rects6 = plt.bar(index + 2.5 * bar_width, nematus, bar_width / 2, alpha=0.4, color='r', label='$ben-nematus$') rects7 = plt.bar(index + 3 * bar_width, smt_um_biglm, bar_width / 2, alpha=0.2, color='r', label='$li-smt-biglm$') autolabel(rects1) autolabel(rects2) autolabel(rects3) autolabel(rects4) autolabel(rects5) autolabel(rects6) autolabel(rects7) #plt.xlabel('Category', fontsize=16) plt.ylabel('BLEU-SBP-5', fontsize=16) #plt.title('Scores by group and Category') # plt.xticks(index - 0.2+ 2*bar_width, ('balde', 'bunny', 'dragon', 'happy', 'pillow')) plt.xticks(index - 0.2 + 2.5 * bar_width, ('cwmt2011', 'cwmt2009'), fontsize = 16) plt.yticks(fontsize=14) # change the num axis size plt.ylim(30, 45) # The ceil plt.legend() #plt.tight_layout() plt.show() drawBarChartPoseRatio()
mit
fredhusser/scikit-learn
examples/exercises/plot_cv_diabetes.py
231
2527
""" =============================================== Cross-validation on diabetes Dataset Exercise =============================================== A tutorial exercise which uses cross-validation with linear models. This exercise is used in the :ref:`cv_estimators_tut` part of the :ref:`model_selection_tut` section of the :ref:`stat_learn_tut_index`. """ from __future__ import print_function print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import cross_validation, datasets, linear_model diabetes = datasets.load_diabetes() X = diabetes.data[:150] y = diabetes.target[:150] lasso = linear_model.Lasso() alphas = np.logspace(-4, -.5, 30) scores = list() scores_std = list() for alpha in alphas: lasso.alpha = alpha this_scores = cross_validation.cross_val_score(lasso, X, y, n_jobs=1) scores.append(np.mean(this_scores)) scores_std.append(np.std(this_scores)) plt.figure(figsize=(4, 3)) plt.semilogx(alphas, scores) # plot error lines showing +/- std. errors of the scores plt.semilogx(alphas, np.array(scores) + np.array(scores_std) / np.sqrt(len(X)), 'b--') plt.semilogx(alphas, np.array(scores) - np.array(scores_std) / np.sqrt(len(X)), 'b--') plt.ylabel('CV score') plt.xlabel('alpha') plt.axhline(np.max(scores), linestyle='--', color='.5') ############################################################################## # Bonus: how much can you trust the selection of alpha? # To answer this question we use the LassoCV object that sets its alpha # parameter automatically from the data by internal cross-validation (i.e. it # performs cross-validation on the training data it receives). # We use external cross-validation to see how much the automatically obtained # alphas differ across different cross-validation folds. lasso_cv = linear_model.LassoCV(alphas=alphas) k_fold = cross_validation.KFold(len(X), 3) print("Answer to the bonus question:", "how much can you trust the selection of alpha?") print() print("Alpha parameters maximising the generalization score on different") print("subsets of the data:") for k, (train, test) in enumerate(k_fold): lasso_cv.fit(X[train], y[train]) print("[fold {0}] alpha: {1:.5f}, score: {2:.5f}". format(k, lasso_cv.alpha_, lasso_cv.score(X[test], y[test]))) print() print("Answer: Not very much since we obtained different alphas for different") print("subsets of the data and moreover, the scores for these alphas differ") print("quite substantially.") plt.show()
bsd-3-clause
cgre-aachen/gempy
test/test_anisotropies/test_anisotropies.py
1
4796
import numpy as np import pytest import gempy as gp import matplotlib.pyplot as plt import os # Input files root = 'https://raw.githubusercontent.com/cgre-aachen/gempy_data/master/data/input_data/turner_syncline/' path = os.path.dirname(__file__) + '/../input_data/' orientations_file = root + 'orientations_clean.csv' contacts_file = root + 'contacts_clean.csv' fp = path + 'dtm_rp.tif' series_file = root + 'all_sorts_clean.csv' bbox = (500000, 7490000, 545000, 7520000) model_base = -1500 # Original 3200 model_top = 800 gdal = pytest.importorskip("gdal") @pytest.fixture(scope='module') def model(): geo_model = gp.create_model('test_map2Loop') gp.init_data( geo_model, extent=[bbox[0], bbox[2], bbox[1], bbox[3], model_base, model_top], resolution=[50, 50, 80], path_o=orientations_file, path_i=contacts_file ) # Load Topology geo_model.set_topography(source='gdal', filepath=fp) # Stack Processing contents = np.genfromtxt(series_file, delimiter=',', dtype='U100')[1:, 4:-1] map_series_to_surfaces = {} for pair in contents: map_series_to_surfaces.setdefault(pair[1], []).append(pair[0]) gp.map_stack_to_surfaces(geo_model, map_series_to_surfaces, remove_unused_series=False) gp.plot_3d(geo_model, ve=None, show_topography=False , image=True, show_lith=False, kwargs_plot_data={'arrow_size': 300}) return geo_model def test_axial_anisotropy_type_data(model): geo_model = model geo_model._rescaling.toggle_axial_anisotropy() # gp.compute_model(geo_model, compute_mesh_options={'mask_topography': False}) geo_model.surface_points.df[['X', 'Y', 'Z']] = geo_model.surface_points.df[['X_c', 'Y_c', 'Z_c']] geo_model.orientations.df[['X', 'Y', 'Z']] = geo_model.orientations.df[['X_c', 'Y_c', 'Z_c']] # This is a hack geo_model._grid.topography.extent = geo_model._grid.extent_c geo_model.set_regular_grid(geo_model._grid.extent_c, [50, 50, 50]) gp.plot_3d(geo_model, ve=None, show_topography=False , image=True, show_lith=False, kwargs_plot_data={'arrow_size': 10}) def test_axial_anisotropy_type_extent(model): geo_model = model geo_model._rescaling.toggle_axial_anisotropy(type='extent') # gp.compute_model(geo_model, compute_mesh_options={'mask_topography': False}) geo_model.surface_points.df[['X', 'Y', 'Z']] = geo_model.surface_points.df[['X_c', 'Y_c', 'Z_c']] geo_model.orientations.df[['X', 'Y', 'Z']] = geo_model.orientations.df[['X_c', 'Y_c', 'Z_c']] # This is a hack geo_model._grid.topography.extent = geo_model._grid.extent_c geo_model.set_regular_grid(geo_model._grid.extent_c, [50, 50, 50]) gp.plot_3d(geo_model, ve=None, show_topography=False , image=True, show_lith=False, kwargs_plot_data={'arrow_size': 10}) def test_axial_anisotropy(model): # Location box geo_model = model geo_model._rescaling.toggle_axial_anisotropy() # gp.compute_model(geo_model, compute_mesh_options={'mask_topography': False}) geo_model.surface_points.df[['X', 'Y', 'Z']] = geo_model.surface_points.df[['X_c', 'Y_c', 'Z_c']] geo_model.orientations.df[['X', 'Y', 'Z']] = geo_model.orientations.df[['X_c', 'Y_c', 'Z_c']] # This is a hack geo_model._grid.topography.extent = geo_model._grid.extent_c geo_model.set_regular_grid(geo_model._grid.extent_c, [50, 50, 50]) geo_model.modify_kriging_parameters('range', 0.1) geo_model.modify_kriging_parameters('drift equations', [9, 9, 9, 9, 9]) geo_model.modify_surface_points( geo_model.surface_points.df.index, smooth=0.001 ) gp.set_interpolator(geo_model, theano_optimizer='fast_run', dtype='float64') gp.compute_model(geo_model, compute_mesh_options={'mask_topography': False, 'masked_marching_cubes': False}) gp.plot_2d(geo_model, section_names=['topography'], show_topography=True, ) plt.show() gp.plot_3d(geo_model, ve=None, show_topography=False, image=True, show_lith=False, kwargs_plot_data={'arrow_size': 10} )
lgpl-3.0
MechCoder/scikit-learn
sklearn/decomposition/truncated_svd.py
13
8301
"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA). """ # Author: Lars Buitinck # Olivier Grisel <[email protected]> # Michael Becker <[email protected]> # License: 3-clause BSD. import numpy as np import scipy.sparse as sp from scipy.sparse.linalg import svds from ..base import BaseEstimator, TransformerMixin from ..utils import check_array, check_random_state from ..utils.extmath import randomized_svd, safe_sparse_dot, svd_flip from ..utils.sparsefuncs import mean_variance_axis __all__ = ["TruncatedSVD"] class TruncatedSVD(BaseEstimator, TransformerMixin): """Dimensionality reduction using truncated SVD (aka LSA). This transformer performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). Contrary to PCA, this estimator does not center the data before computing the singular value decomposition. This means it can work with scipy.sparse matrices efficiently. In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA). This estimator supports two algorithms: a fast randomized SVD solver, and a "naive" algorithm that uses ARPACK as an eigensolver on (X * X.T) or (X.T * X), whichever is more efficient. Read more in the :ref:`User Guide <LSA>`. Parameters ---------- n_components : int, default = 2 Desired dimensionality of output data. Must be strictly less than the number of features. The default value is useful for visualisation. For LSA, a value of 100 is recommended. algorithm : string, default = "randomized" SVD solver to use. Either "arpack" for the ARPACK wrapper in SciPy (scipy.sparse.linalg.svds), or "randomized" for the randomized algorithm due to Halko (2009). n_iter : int, optional (default 5) Number of iterations for randomized SVD solver. Not used by ARPACK. The default is larger than the default in `randomized_svd` to handle sparse matrices that may have large slowly decaying spectrum. random_state : int, RandomState instance or None, optional, default = None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. tol : float, optional Tolerance for ARPACK. 0 means machine precision. Ignored by randomized SVD solver. Attributes ---------- components_ : array, shape (n_components, n_features) explained_variance_ : array, shape (n_components,) The variance of the training samples transformed by a projection to each component. explained_variance_ratio_ : array, shape (n_components,) Percentage of variance explained by each of the selected components. singular_values_ : array, shape (n_components,) The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the ``n_components`` variables in the lower-dimensional space. Examples -------- >>> from sklearn.decomposition import TruncatedSVD >>> from sklearn.random_projection import sparse_random_matrix >>> X = sparse_random_matrix(100, 100, density=0.01, random_state=42) >>> svd = TruncatedSVD(n_components=5, n_iter=7, random_state=42) >>> svd.fit(X) # doctest: +NORMALIZE_WHITESPACE TruncatedSVD(algorithm='randomized', n_components=5, n_iter=7, random_state=42, tol=0.0) >>> print(svd.explained_variance_ratio_) # doctest: +ELLIPSIS [ 0.0606... 0.0584... 0.0497... 0.0434... 0.0372...] >>> print(svd.explained_variance_ratio_.sum()) # doctest: +ELLIPSIS 0.249... >>> print(svd.singular_values_) # doctest: +ELLIPSIS [ 2.5841... 2.5245... 2.3201... 2.1753... 2.0443...] See also -------- PCA RandomizedPCA References ---------- Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) http://arxiv.org/pdf/0909.4061 Notes ----- SVD suffers from a problem called "sign indeterminancy", which means the sign of the ``components_`` and the output from transform depend on the algorithm and random state. To work around this, fit instances of this class to data once, then keep the instance around to do transformations. """ def __init__(self, n_components=2, algorithm="randomized", n_iter=5, random_state=None, tol=0.): self.algorithm = algorithm self.n_components = n_components self.n_iter = n_iter self.random_state = random_state self.tol = tol def fit(self, X, y=None): """Fit LSI model on training data X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- self : object Returns the transformer object. """ self.fit_transform(X) return self def fit_transform(self, X, y=None): """Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced version of X. This will always be a dense array. """ X = check_array(X, accept_sparse=['csr', 'csc']) random_state = check_random_state(self.random_state) if self.algorithm == "arpack": U, Sigma, VT = svds(X, k=self.n_components, tol=self.tol) # svds doesn't abide by scipy.linalg.svd/randomized_svd # conventions, so reverse its outputs. Sigma = Sigma[::-1] U, VT = svd_flip(U[:, ::-1], VT[::-1]) elif self.algorithm == "randomized": k = self.n_components n_features = X.shape[1] if k >= n_features: raise ValueError("n_components must be < n_features;" " got %d >= %d" % (k, n_features)) U, Sigma, VT = randomized_svd(X, self.n_components, n_iter=self.n_iter, random_state=random_state) else: raise ValueError("unknown algorithm %r" % self.algorithm) self.components_ = VT # Calculate explained variance & explained variance ratio X_transformed = U * Sigma self.explained_variance_ = exp_var = np.var(X_transformed, axis=0) if sp.issparse(X): _, full_var = mean_variance_axis(X, axis=0) full_var = full_var.sum() else: full_var = np.var(X, axis=0).sum() self.explained_variance_ratio_ = exp_var / full_var self.singular_values_ = Sigma # Store the singular values. return X_transformed def transform(self, X): """Perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) New data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced version of X. This will always be a dense array. """ X = check_array(X, accept_sparse='csr') return safe_sparse_dot(X, self.components_.T) def inverse_transform(self, X): """Transform X back to its original space. Returns an array X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data. Returns ------- X_original : array, shape (n_samples, n_features) Note that this is always a dense array. """ X = check_array(X) return np.dot(X, self.components_)
bsd-3-clause
spark-test/spark
python/pyspark/sql/tests/test_pandas_udf_grouped_agg.py
6
20725
# # 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 from pyspark.rdd import PythonEvalType from pyspark.sql import Row from pyspark.sql.functions import array, explode, col, lit, mean, sum, \ udf, pandas_udf, PandasUDFType from pyspark.sql.types import * from pyspark.sql.utils import AnalysisException from pyspark.testing.sqlutils import ReusedSQLTestCase, have_pandas, have_pyarrow, \ pandas_requirement_message, pyarrow_requirement_message from pyspark.testing.utils import QuietTest if have_pandas: import pandas as pd from pandas.util.testing import assert_frame_equal @unittest.skipIf( not have_pandas or not have_pyarrow, pandas_requirement_message or pyarrow_requirement_message) class GroupedAggPandasUDFTests(ReusedSQLTestCase): @property def data(self): return self.spark.range(10).toDF('id') \ .withColumn("vs", array([lit(i * 1.0) + col('id') for i in range(20, 30)])) \ .withColumn("v", explode(col('vs'))) \ .drop('vs') \ .withColumn('w', lit(1.0)) @property def python_plus_one(self): @udf('double') def plus_one(v): assert isinstance(v, (int, float)) return v + 1 return plus_one @property def pandas_scalar_plus_two(self): @pandas_udf('double', PandasUDFType.SCALAR) def plus_two(v): assert isinstance(v, pd.Series) return v + 2 return plus_two @property def pandas_agg_mean_udf(self): @pandas_udf('double', PandasUDFType.GROUPED_AGG) def avg(v): return v.mean() return avg @property def pandas_agg_sum_udf(self): @pandas_udf('double', PandasUDFType.GROUPED_AGG) def sum(v): return v.sum() return sum @property def pandas_agg_weighted_mean_udf(self): import numpy as np @pandas_udf('double', PandasUDFType.GROUPED_AGG) def weighted_mean(v, w): return np.average(v, weights=w) return weighted_mean def test_manual(self): df = self.data sum_udf = self.pandas_agg_sum_udf mean_udf = self.pandas_agg_mean_udf mean_arr_udf = pandas_udf( self.pandas_agg_mean_udf.func, ArrayType(self.pandas_agg_mean_udf.returnType), self.pandas_agg_mean_udf.evalType) result1 = df.groupby('id').agg( sum_udf(df.v), mean_udf(df.v), mean_arr_udf(array(df.v))).sort('id') expected1 = self.spark.createDataFrame( [[0, 245.0, 24.5, [24.5]], [1, 255.0, 25.5, [25.5]], [2, 265.0, 26.5, [26.5]], [3, 275.0, 27.5, [27.5]], [4, 285.0, 28.5, [28.5]], [5, 295.0, 29.5, [29.5]], [6, 305.0, 30.5, [30.5]], [7, 315.0, 31.5, [31.5]], [8, 325.0, 32.5, [32.5]], [9, 335.0, 33.5, [33.5]]], ['id', 'sum(v)', 'avg(v)', 'avg(array(v))']) assert_frame_equal(expected1.toPandas(), result1.toPandas()) def test_basic(self): df = self.data weighted_mean_udf = self.pandas_agg_weighted_mean_udf # Groupby one column and aggregate one UDF with literal result1 = df.groupby('id').agg(weighted_mean_udf(df.v, lit(1.0))).sort('id') expected1 = df.groupby('id').agg(mean(df.v).alias('weighted_mean(v, 1.0)')).sort('id') assert_frame_equal(expected1.toPandas(), result1.toPandas()) # Groupby one expression and aggregate one UDF with literal result2 = df.groupby((col('id') + 1)).agg(weighted_mean_udf(df.v, lit(1.0)))\ .sort(df.id + 1) expected2 = df.groupby((col('id') + 1))\ .agg(mean(df.v).alias('weighted_mean(v, 1.0)')).sort(df.id + 1) assert_frame_equal(expected2.toPandas(), result2.toPandas()) # Groupby one column and aggregate one UDF without literal result3 = df.groupby('id').agg(weighted_mean_udf(df.v, df.w)).sort('id') expected3 = df.groupby('id').agg(mean(df.v).alias('weighted_mean(v, w)')).sort('id') assert_frame_equal(expected3.toPandas(), result3.toPandas()) # Groupby one expression and aggregate one UDF without literal result4 = df.groupby((col('id') + 1).alias('id'))\ .agg(weighted_mean_udf(df.v, df.w))\ .sort('id') expected4 = df.groupby((col('id') + 1).alias('id'))\ .agg(mean(df.v).alias('weighted_mean(v, w)'))\ .sort('id') assert_frame_equal(expected4.toPandas(), result4.toPandas()) def test_unsupported_types(self): with QuietTest(self.sc): with self.assertRaisesRegexp(NotImplementedError, 'not supported'): pandas_udf( lambda x: x, ArrayType(ArrayType(TimestampType())), PandasUDFType.GROUPED_AGG) with QuietTest(self.sc): with self.assertRaisesRegexp(NotImplementedError, 'not supported'): @pandas_udf('mean double, std double', PandasUDFType.GROUPED_AGG) def mean_and_std_udf(v): return v.mean(), v.std() with QuietTest(self.sc): with self.assertRaisesRegexp(NotImplementedError, 'not supported'): @pandas_udf(MapType(DoubleType(), DoubleType()), PandasUDFType.GROUPED_AGG) def mean_and_std_udf(v): return {v.mean(): v.std()} def test_alias(self): df = self.data mean_udf = self.pandas_agg_mean_udf result1 = df.groupby('id').agg(mean_udf(df.v).alias('mean_alias')) expected1 = df.groupby('id').agg(mean(df.v).alias('mean_alias')) assert_frame_equal(expected1.toPandas(), result1.toPandas()) def test_mixed_sql(self): """ Test mixing group aggregate pandas UDF with sql expression. """ df = self.data sum_udf = self.pandas_agg_sum_udf # Mix group aggregate pandas UDF with sql expression result1 = (df.groupby('id') .agg(sum_udf(df.v) + 1) .sort('id')) expected1 = (df.groupby('id') .agg(sum(df.v) + 1) .sort('id')) # Mix group aggregate pandas UDF with sql expression (order swapped) result2 = (df.groupby('id') .agg(sum_udf(df.v + 1)) .sort('id')) expected2 = (df.groupby('id') .agg(sum(df.v + 1)) .sort('id')) # Wrap group aggregate pandas UDF with two sql expressions result3 = (df.groupby('id') .agg(sum_udf(df.v + 1) + 2) .sort('id')) expected3 = (df.groupby('id') .agg(sum(df.v + 1) + 2) .sort('id')) assert_frame_equal(expected1.toPandas(), result1.toPandas()) assert_frame_equal(expected2.toPandas(), result2.toPandas()) assert_frame_equal(expected3.toPandas(), result3.toPandas()) def test_mixed_udfs(self): """ Test mixing group aggregate pandas UDF with python UDF and scalar pandas UDF. """ df = self.data plus_one = self.python_plus_one plus_two = self.pandas_scalar_plus_two sum_udf = self.pandas_agg_sum_udf # Mix group aggregate pandas UDF and python UDF result1 = (df.groupby('id') .agg(plus_one(sum_udf(df.v))) .sort('id')) expected1 = (df.groupby('id') .agg(plus_one(sum(df.v))) .sort('id')) # Mix group aggregate pandas UDF and python UDF (order swapped) result2 = (df.groupby('id') .agg(sum_udf(plus_one(df.v))) .sort('id')) expected2 = (df.groupby('id') .agg(sum(plus_one(df.v))) .sort('id')) # Mix group aggregate pandas UDF and scalar pandas UDF result3 = (df.groupby('id') .agg(sum_udf(plus_two(df.v))) .sort('id')) expected3 = (df.groupby('id') .agg(sum(plus_two(df.v))) .sort('id')) # Mix group aggregate pandas UDF and scalar pandas UDF (order swapped) result4 = (df.groupby('id') .agg(plus_two(sum_udf(df.v))) .sort('id')) expected4 = (df.groupby('id') .agg(plus_two(sum(df.v))) .sort('id')) # Wrap group aggregate pandas UDF with two python UDFs and use python UDF in groupby result5 = (df.groupby(plus_one(df.id)) .agg(plus_one(sum_udf(plus_one(df.v)))) .sort('plus_one(id)')) expected5 = (df.groupby(plus_one(df.id)) .agg(plus_one(sum(plus_one(df.v)))) .sort('plus_one(id)')) # Wrap group aggregate pandas UDF with two scala pandas UDF and user scala pandas UDF in # groupby result6 = (df.groupby(plus_two(df.id)) .agg(plus_two(sum_udf(plus_two(df.v)))) .sort('plus_two(id)')) expected6 = (df.groupby(plus_two(df.id)) .agg(plus_two(sum(plus_two(df.v)))) .sort('plus_two(id)')) assert_frame_equal(expected1.toPandas(), result1.toPandas()) assert_frame_equal(expected2.toPandas(), result2.toPandas()) assert_frame_equal(expected3.toPandas(), result3.toPandas()) assert_frame_equal(expected4.toPandas(), result4.toPandas()) assert_frame_equal(expected5.toPandas(), result5.toPandas()) assert_frame_equal(expected6.toPandas(), result6.toPandas()) def test_multiple_udfs(self): """ Test multiple group aggregate pandas UDFs in one agg function. """ df = self.data mean_udf = self.pandas_agg_mean_udf sum_udf = self.pandas_agg_sum_udf weighted_mean_udf = self.pandas_agg_weighted_mean_udf result1 = (df.groupBy('id') .agg(mean_udf(df.v), sum_udf(df.v), weighted_mean_udf(df.v, df.w)) .sort('id') .toPandas()) expected1 = (df.groupBy('id') .agg(mean(df.v), sum(df.v), mean(df.v).alias('weighted_mean(v, w)')) .sort('id') .toPandas()) assert_frame_equal(expected1, result1) def test_complex_groupby(self): df = self.data sum_udf = self.pandas_agg_sum_udf plus_one = self.python_plus_one plus_two = self.pandas_scalar_plus_two # groupby one expression result1 = df.groupby(df.v % 2).agg(sum_udf(df.v)) expected1 = df.groupby(df.v % 2).agg(sum(df.v)) # empty groupby result2 = df.groupby().agg(sum_udf(df.v)) expected2 = df.groupby().agg(sum(df.v)) # groupby one column and one sql expression result3 = df.groupby(df.id, df.v % 2).agg(sum_udf(df.v)).orderBy(df.id, df.v % 2) expected3 = df.groupby(df.id, df.v % 2).agg(sum(df.v)).orderBy(df.id, df.v % 2) # groupby one python UDF result4 = df.groupby(plus_one(df.id)).agg(sum_udf(df.v)) expected4 = df.groupby(plus_one(df.id)).agg(sum(df.v)) # groupby one scalar pandas UDF result5 = df.groupby(plus_two(df.id)).agg(sum_udf(df.v)).sort('sum(v)') expected5 = df.groupby(plus_two(df.id)).agg(sum(df.v)).sort('sum(v)') # groupby one expression and one python UDF result6 = df.groupby(df.v % 2, plus_one(df.id)).agg(sum_udf(df.v)) expected6 = df.groupby(df.v % 2, plus_one(df.id)).agg(sum(df.v)) # groupby one expression and one scalar pandas UDF result7 = (df.groupby(df.v % 2, plus_two(df.id)) .agg(sum_udf(df.v)).sort(['sum(v)', 'plus_two(id)'])) expected7 = (df.groupby(df.v % 2, plus_two(df.id)) .agg(sum(df.v)).sort(['sum(v)', 'plus_two(id)'])) assert_frame_equal(expected1.toPandas(), result1.toPandas()) assert_frame_equal(expected2.toPandas(), result2.toPandas()) assert_frame_equal(expected3.toPandas(), result3.toPandas()) assert_frame_equal(expected4.toPandas(), result4.toPandas()) assert_frame_equal(expected5.toPandas(), result5.toPandas()) assert_frame_equal(expected6.toPandas(), result6.toPandas()) assert_frame_equal(expected7.toPandas(), result7.toPandas()) def test_complex_expressions(self): df = self.data plus_one = self.python_plus_one plus_two = self.pandas_scalar_plus_two sum_udf = self.pandas_agg_sum_udf # Test complex expressions with sql expression, python UDF and # group aggregate pandas UDF result1 = (df.withColumn('v1', plus_one(df.v)) .withColumn('v2', df.v + 2) .groupby(df.id, df.v % 2) .agg(sum_udf(col('v')), sum_udf(col('v1') + 3), sum_udf(col('v2')) + 5, plus_one(sum_udf(col('v1'))), sum_udf(plus_one(col('v2')))) .sort(['id', '(v % 2)']) .toPandas().sort_values(by=['id', '(v % 2)'])) expected1 = (df.withColumn('v1', df.v + 1) .withColumn('v2', df.v + 2) .groupby(df.id, df.v % 2) .agg(sum(col('v')), sum(col('v1') + 3), sum(col('v2')) + 5, plus_one(sum(col('v1'))), sum(plus_one(col('v2')))) .sort(['id', '(v % 2)']) .toPandas().sort_values(by=['id', '(v % 2)'])) # Test complex expressions with sql expression, scala pandas UDF and # group aggregate pandas UDF result2 = (df.withColumn('v1', plus_one(df.v)) .withColumn('v2', df.v + 2) .groupby(df.id, df.v % 2) .agg(sum_udf(col('v')), sum_udf(col('v1') + 3), sum_udf(col('v2')) + 5, plus_two(sum_udf(col('v1'))), sum_udf(plus_two(col('v2')))) .sort(['id', '(v % 2)']) .toPandas().sort_values(by=['id', '(v % 2)'])) expected2 = (df.withColumn('v1', df.v + 1) .withColumn('v2', df.v + 2) .groupby(df.id, df.v % 2) .agg(sum(col('v')), sum(col('v1') + 3), sum(col('v2')) + 5, plus_two(sum(col('v1'))), sum(plus_two(col('v2')))) .sort(['id', '(v % 2)']) .toPandas().sort_values(by=['id', '(v % 2)'])) # Test sequential groupby aggregate result3 = (df.groupby('id') .agg(sum_udf(df.v).alias('v')) .groupby('id') .agg(sum_udf(col('v'))) .sort('id') .toPandas()) expected3 = (df.groupby('id') .agg(sum(df.v).alias('v')) .groupby('id') .agg(sum(col('v'))) .sort('id') .toPandas()) assert_frame_equal(expected1, result1) assert_frame_equal(expected2, result2) assert_frame_equal(expected3, result3) def test_retain_group_columns(self): with self.sql_conf({"spark.sql.retainGroupColumns": False}): df = self.data sum_udf = self.pandas_agg_sum_udf result1 = df.groupby(df.id).agg(sum_udf(df.v)) expected1 = df.groupby(df.id).agg(sum(df.v)) assert_frame_equal(expected1.toPandas(), result1.toPandas()) def test_array_type(self): df = self.data array_udf = pandas_udf(lambda x: [1.0, 2.0], 'array<double>', PandasUDFType.GROUPED_AGG) result1 = df.groupby('id').agg(array_udf(df['v']).alias('v2')) self.assertEquals(result1.first()['v2'], [1.0, 2.0]) def test_invalid_args(self): df = self.data plus_one = self.python_plus_one mean_udf = self.pandas_agg_mean_udf with QuietTest(self.sc): with self.assertRaisesRegexp( AnalysisException, 'nor.*aggregate function'): df.groupby(df.id).agg(plus_one(df.v)).collect() with QuietTest(self.sc): with self.assertRaisesRegexp( AnalysisException, 'aggregate function.*argument.*aggregate function'): df.groupby(df.id).agg(mean_udf(mean_udf(df.v))).collect() with QuietTest(self.sc): with self.assertRaisesRegexp( AnalysisException, 'mixture.*aggregate function.*group aggregate pandas UDF'): df.groupby(df.id).agg(mean_udf(df.v), mean(df.v)).collect() def test_register_vectorized_udf_basic(self): sum_pandas_udf = pandas_udf( lambda v: v.sum(), "integer", PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF) self.assertEqual(sum_pandas_udf.evalType, PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF) group_agg_pandas_udf = self.spark.udf.register("sum_pandas_udf", sum_pandas_udf) self.assertEqual(group_agg_pandas_udf.evalType, PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF) q = "SELECT sum_pandas_udf(v1) FROM VALUES (3, 0), (2, 0), (1, 1) tbl(v1, v2) GROUP BY v2" actual = sorted(map(lambda r: r[0], self.spark.sql(q).collect())) expected = [1, 5] self.assertEqual(actual, expected) def test_grouped_with_empty_partition(self): data = [Row(id=1, x=2), Row(id=1, x=3), Row(id=2, x=4)] expected = [Row(id=1, sum=5), Row(id=2, x=4)] num_parts = len(data) + 1 df = self.spark.createDataFrame(self.sc.parallelize(data, numSlices=num_parts)) f = pandas_udf(lambda x: x.sum(), 'int', PandasUDFType.GROUPED_AGG) result = df.groupBy('id').agg(f(df['x']).alias('sum')).collect() self.assertEqual(result, expected) def test_grouped_without_group_by_clause(self): @pandas_udf('double', PandasUDFType.GROUPED_AGG) def max_udf(v): return v.max() df = self.spark.range(0, 100) self.spark.udf.register('max_udf', max_udf) with self.tempView("table"): df.createTempView('table') agg1 = df.agg(max_udf(df['id'])) agg2 = self.spark.sql("select max_udf(id) from table") assert_frame_equal(agg1.toPandas(), agg2.toPandas()) def test_no_predicate_pushdown_through(self): # SPARK-30921: We should not pushdown predicates of PythonUDFs through Aggregate. import numpy as np @pandas_udf('float', PandasUDFType.GROUPED_AGG) def mean(x): return np.mean(x) df = self.spark.createDataFrame([ Row(id=1, foo=42), Row(id=2, foo=1), Row(id=2, foo=2) ]) agg = df.groupBy('id').agg(mean('foo').alias("mean")) filtered = agg.filter(agg['mean'] > 40.0) assert(filtered.collect()[0]["mean"] == 42.0) if __name__ == "__main__": from pyspark.sql.tests.test_pandas_udf_grouped_agg import * try: import xmlrunner testRunner = xmlrunner.XMLTestRunner(output='target/test-reports', verbosity=2) except ImportError: testRunner = None unittest.main(testRunner=testRunner, verbosity=2)
apache-2.0
wronk/mne-python
examples/preprocessing/plot_resample.py
12
3439
""" =============== Resampling data =============== When performing experiments where timing is critical, a signal with a high sampling rate is desired. However, having a signal with a much higher sampling rate than is necessary needlessly consumes memory and slows down computations operating on the data. This example downsamples from 600 Hz to 100 Hz. This achieves a 6-fold reduction in data size, at the cost of an equal loss of temporal resolution. """ # Authors: Marijn van Vliet <[email protected]> # # License: BSD (3-clause) # from __future__ import print_function from matplotlib import pyplot as plt import mne from mne.datasets import sample ############################################################################### # Setting up data paths and loading raw data (skip some data for speed) data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' raw = mne.io.read_raw_fif(raw_fname).crop(120, 240).load_data() ############################################################################### # Since downsampling reduces the timing precision of events, we recommend # first extracting epochs and downsampling the Epochs object: events = mne.find_events(raw) epochs = mne.Epochs(raw, events, event_id=2, tmin=-0.1, tmax=0.8, preload=True) # Downsample to 100 Hz print('Original sampling rate:', epochs.info['sfreq'], 'Hz') epochs_resampled = epochs.copy().resample(100, npad='auto') print('New sampling rate:', epochs_resampled.info['sfreq'], 'Hz') # Plot a piece of data to see the effects of downsampling plt.figure(figsize=(7, 3)) n_samples_to_plot = int(0.5 * epochs.info['sfreq']) # plot 0.5 seconds of data plt.plot(epochs.times[:n_samples_to_plot], epochs.get_data()[0, 0, :n_samples_to_plot], color='black') n_samples_to_plot = int(0.5 * epochs_resampled.info['sfreq']) plt.plot(epochs_resampled.times[:n_samples_to_plot], epochs_resampled.get_data()[0, 0, :n_samples_to_plot], '-o', color='red') plt.xlabel('time (s)') plt.legend(['original', 'downsampled'], loc='best') plt.title('Effect of downsampling') mne.viz.tight_layout() ############################################################################### # When resampling epochs is unwanted or impossible, for example when the data # doesn't fit into memory or your analysis pipeline doesn't involve epochs at # all, the alternative approach is to resample the continuous data. This # can also be done on non-preloaded data. # Resample to 300 Hz raw_resampled = raw.copy().resample(300, npad='auto') ############################################################################### # Because resampling also affects the stim channels, some trigger onsets might # be lost in this case. While MNE attempts to downsample the stim channels in # an intelligent manner to avoid this, the recommended approach is to find # events on the original data before downsampling. print('Number of events before resampling:', len(mne.find_events(raw))) # Resample to 100 Hz (generates warning) raw_resampled = raw.copy().resample(100, npad='auto') print('Number of events after resampling:', len(mne.find_events(raw_resampled))) # To avoid losing events, jointly resample the data and event matrix events = mne.find_events(raw) raw_resampled, events_resampled = raw.copy().resample( 100, npad='auto', events=events) print('Number of events after resampling:', len(events_resampled))
bsd-3-clause
MJuddBooth/pandas
pandas/tests/scalar/timedelta/test_formats.py
9
1068
# -*- coding: utf-8 -*- import pytest from pandas import Timedelta @pytest.mark.parametrize('td, expected_repr', [ (Timedelta(10, unit='d'), "Timedelta('10 days 00:00:00')"), (Timedelta(10, unit='s'), "Timedelta('0 days 00:00:10')"), (Timedelta(10, unit='ms'), "Timedelta('0 days 00:00:00.010000')"), (Timedelta(-10, unit='ms'), "Timedelta('-1 days +23:59:59.990000')")]) def test_repr(td, expected_repr): assert repr(td) == expected_repr @pytest.mark.parametrize('td, expected_iso', [ (Timedelta(days=6, minutes=50, seconds=3, milliseconds=10, microseconds=10, nanoseconds=12), 'P6DT0H50M3.010010012S'), (Timedelta(days=4, hours=12, minutes=30, seconds=5), 'P4DT12H30M5S'), (Timedelta(nanoseconds=123), 'P0DT0H0M0.000000123S'), # trim nano (Timedelta(microseconds=10), 'P0DT0H0M0.00001S'), # trim micro (Timedelta(milliseconds=1), 'P0DT0H0M0.001S'), # don't strip every 0 (Timedelta(minutes=1), 'P0DT0H1M0S')]) def test_isoformat(td, expected_iso): assert td.isoformat() == expected_iso
bsd-3-clause
saketkc/statsmodels
statsmodels/regression/tests/test_regression.py
18
38246
""" Test functions for models.regression """ # TODO: Test for LM from statsmodels.compat.python import long, lrange import warnings import pandas import numpy as np from numpy.testing import (assert_almost_equal, assert_approx_equal, assert_, assert_raises, assert_equal, assert_allclose) from scipy.linalg import toeplitz from statsmodels.tools.tools import add_constant, categorical from statsmodels.compat.numpy import np_matrix_rank from statsmodels.regression.linear_model import OLS, WLS, GLS, yule_walker from statsmodels.datasets import longley from scipy.stats import t as student_t DECIMAL_4 = 4 DECIMAL_3 = 3 DECIMAL_2 = 2 DECIMAL_1 = 1 DECIMAL_7 = 7 DECIMAL_0 = 0 class CheckRegressionResults(object): """ res2 contains results from Rmodelwrap or were obtained from a statistical packages such as R, Stata, or SAS and were written to model_results """ decimal_params = DECIMAL_4 def test_params(self): assert_almost_equal(self.res1.params, self.res2.params, self.decimal_params) decimal_standarderrors = DECIMAL_4 def test_standarderrors(self): assert_almost_equal(self.res1.bse,self.res2.bse, self.decimal_standarderrors) decimal_confidenceintervals = DECIMAL_4 def test_confidenceintervals(self): #NOTE: stata rounds residuals (at least) to sig digits so approx_equal conf1 = self.res1.conf_int() conf2 = self.res2.conf_int() for i in range(len(conf1)): assert_approx_equal(conf1[i][0], conf2[i][0], self.decimal_confidenceintervals) assert_approx_equal(conf1[i][1], conf2[i][1], self.decimal_confidenceintervals) decimal_conf_int_subset = DECIMAL_4 def test_conf_int_subset(self): if len(self.res1.params) > 1: ci1 = self.res1.conf_int(cols=(1,2)) ci2 = self.res1.conf_int()[1:3] assert_almost_equal(ci1, ci2, self.decimal_conf_int_subset) else: pass decimal_scale = DECIMAL_4 def test_scale(self): assert_almost_equal(self.res1.scale, self.res2.scale, self.decimal_scale) decimal_rsquared = DECIMAL_4 def test_rsquared(self): assert_almost_equal(self.res1.rsquared, self.res2.rsquared, self.decimal_rsquared) decimal_rsquared_adj = DECIMAL_4 def test_rsquared_adj(self): assert_almost_equal(self.res1.rsquared_adj, self.res2.rsquared_adj, self.decimal_rsquared_adj) def test_degrees(self): assert_equal(self.res1.model.df_model, self.res2.df_model) assert_equal(self.res1.model.df_resid, self.res2.df_resid) decimal_ess = DECIMAL_4 def test_ess(self): #Explained Sum of Squares assert_almost_equal(self.res1.ess, self.res2.ess, self.decimal_ess) decimal_ssr = DECIMAL_4 def test_sumof_squaredresids(self): assert_almost_equal(self.res1.ssr, self.res2.ssr, self.decimal_ssr) decimal_mse_resid = DECIMAL_4 def test_mse_resid(self): #Mean squared error of residuals assert_almost_equal(self.res1.mse_model, self.res2.mse_model, self.decimal_mse_resid) decimal_mse_model = DECIMAL_4 def test_mse_model(self): assert_almost_equal(self.res1.mse_resid, self.res2.mse_resid, self.decimal_mse_model) decimal_mse_total = DECIMAL_4 def test_mse_total(self): assert_almost_equal(self.res1.mse_total, self.res2.mse_total, self.decimal_mse_total, err_msg="Test class %s" % self) decimal_fvalue = DECIMAL_4 def test_fvalue(self): #didn't change this, not sure it should complain -inf not equal -inf #if not (np.isinf(self.res1.fvalue) and np.isinf(self.res2.fvalue)): assert_almost_equal(self.res1.fvalue, self.res2.fvalue, self.decimal_fvalue) decimal_loglike = DECIMAL_4 def test_loglike(self): assert_almost_equal(self.res1.llf, self.res2.llf, self.decimal_loglike) decimal_aic = DECIMAL_4 def test_aic(self): assert_almost_equal(self.res1.aic, self.res2.aic, self.decimal_aic) decimal_bic = DECIMAL_4 def test_bic(self): assert_almost_equal(self.res1.bic, self.res2.bic, self.decimal_bic) decimal_pvalues = DECIMAL_4 def test_pvalues(self): assert_almost_equal(self.res1.pvalues, self.res2.pvalues, self.decimal_pvalues) decimal_wresid = DECIMAL_4 def test_wresid(self): assert_almost_equal(self.res1.wresid, self.res2.wresid, self.decimal_wresid) decimal_resids = DECIMAL_4 def test_resids(self): assert_almost_equal(self.res1.resid, self.res2.resid, self.decimal_resids) decimal_norm_resids = DECIMAL_4 def test_norm_resids(self): assert_almost_equal(self.res1.resid_pearson, self.res2.resid_pearson, self.decimal_norm_resids) #TODO: test fittedvalues and what else? class TestOLS(CheckRegressionResults): @classmethod def setupClass(cls): from .results.results_regression import Longley data = longley.load() data.exog = add_constant(data.exog, prepend=False) res1 = OLS(data.endog, data.exog).fit() res2 = Longley() res2.wresid = res1.wresid # workaround hack cls.res1 = res1 cls.res2 = res2 res_qr = OLS(data.endog, data.exog).fit(method="qr") model_qr = OLS(data.endog, data.exog) Q, R = np.linalg.qr(data.exog) model_qr.exog_Q, model_qr.exog_R = Q, R model_qr.normalized_cov_params = np.linalg.inv(np.dot(R.T, R)) model_qr.rank = np_matrix_rank(R) res_qr2 = model_qr.fit(method="qr") cls.res_qr = res_qr cls.res_qr_manual = res_qr2 def test_eigenvalues(self): eigenval_perc_diff = (self.res_qr.eigenvals - self.res_qr_manual.eigenvals) eigenval_perc_diff /= self.res_qr.eigenvals zeros = np.zeros_like(eigenval_perc_diff) assert_almost_equal(eigenval_perc_diff, zeros, DECIMAL_7) # Robust error tests. Compare values computed with SAS def test_HC0_errors(self): #They are split up because the copied results do not have any DECIMAL_4 #places for the last place. assert_almost_equal(self.res1.HC0_se[:-1], self.res2.HC0_se[:-1], DECIMAL_4) assert_approx_equal(np.round(self.res1.HC0_se[-1]), self.res2.HC0_se[-1]) def test_HC1_errors(self): assert_almost_equal(self.res1.HC1_se[:-1], self.res2.HC1_se[:-1], DECIMAL_4) assert_approx_equal(self.res1.HC1_se[-1], self.res2.HC1_se[-1]) def test_HC2_errors(self): assert_almost_equal(self.res1.HC2_se[:-1], self.res2.HC2_se[:-1], DECIMAL_4) assert_approx_equal(self.res1.HC2_se[-1], self.res2.HC2_se[-1]) def test_HC3_errors(self): assert_almost_equal(self.res1.HC3_se[:-1], self.res2.HC3_se[:-1], DECIMAL_4) assert_approx_equal(self.res1.HC3_se[-1], self.res2.HC3_se[-1]) def test_qr_params(self): assert_almost_equal(self.res1.params, self.res_qr.params, 6) def test_qr_normalized_cov_params(self): #todo: need assert_close assert_almost_equal(np.ones_like(self.res1.normalized_cov_params), self.res1.normalized_cov_params / self.res_qr.normalized_cov_params, 5) def test_missing(self): data = longley.load() data.exog = add_constant(data.exog, prepend=False) data.endog[[3, 7, 14]] = np.nan mod = OLS(data.endog, data.exog, missing='drop') assert_equal(mod.endog.shape[0], 13) assert_equal(mod.exog.shape[0], 13) def test_rsquared_adj_overfit(self): # Test that if df_resid = 0, rsquared_adj = 0. # This is a regression test for user issue: # https://github.com/statsmodels/statsmodels/issues/868 with warnings.catch_warnings(record=True): x = np.random.randn(5) y = np.random.randn(5, 6) results = OLS(x, y).fit() rsquared_adj = results.rsquared_adj assert_equal(rsquared_adj, np.nan) def test_qr_alternatives(self): assert_allclose(self.res_qr.params, self.res_qr_manual.params, rtol=5e-12) def test_norm_resid(self): resid = self.res1.wresid norm_resid = resid / np.sqrt(np.sum(resid**2.0) / self.res1.df_resid) model_norm_resid = self.res1.resid_pearson assert_almost_equal(model_norm_resid, norm_resid, DECIMAL_7) def test_norm_resid_zero_variance(self): with warnings.catch_warnings(record=True): y = self.res1.model.endog res = OLS(y,y).fit() assert_allclose(res.scale, 0, atol=1e-20) assert_allclose(res.wresid, res.resid_pearson, atol=5e-11) class TestRTO(CheckRegressionResults): @classmethod def setupClass(cls): from .results.results_regression import LongleyRTO data = longley.load() res1 = OLS(data.endog, data.exog).fit() res2 = LongleyRTO() res2.wresid = res1.wresid # workaround hack cls.res1 = res1 cls.res2 = res2 res_qr = OLS(data.endog, data.exog).fit(method="qr") cls.res_qr = res_qr class TestFtest(object): """ Tests f_test vs. RegressionResults """ @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) cls.res1 = OLS(data.endog, data.exog).fit() R = np.identity(7)[:-1,:] cls.Ftest = cls.res1.f_test(R) def test_F(self): assert_almost_equal(self.Ftest.fvalue, self.res1.fvalue, DECIMAL_4) def test_p(self): assert_almost_equal(self.Ftest.pvalue, self.res1.f_pvalue, DECIMAL_4) def test_Df_denom(self): assert_equal(self.Ftest.df_denom, self.res1.model.df_resid) def test_Df_num(self): assert_equal(self.Ftest.df_num, 6) class TestFTest2(object): """ A joint test that the coefficient on GNP = the coefficient on UNEMP and that the coefficient on POP = the coefficient on YEAR for the Longley dataset. Ftest1 is from statsmodels. Results are from Rpy using R's car library. """ @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) res1 = OLS(data.endog, data.exog).fit() R2 = [[0,1,-1,0,0,0,0],[0, 0, 0, 0, 1, -1, 0]] cls.Ftest1 = res1.f_test(R2) hyp = 'x2 = x3, x5 = x6' cls.NewFtest1 = res1.f_test(hyp) def test_new_ftest(self): assert_equal(self.NewFtest1.fvalue, self.Ftest1.fvalue) def test_fvalue(self): assert_almost_equal(self.Ftest1.fvalue, 9.7404618732968196, DECIMAL_4) def test_pvalue(self): assert_almost_equal(self.Ftest1.pvalue, 0.0056052885317493459, DECIMAL_4) def test_df_denom(self): assert_equal(self.Ftest1.df_denom, 9) def test_df_num(self): assert_equal(self.Ftest1.df_num, 2) class TestFtestQ(object): """ A joint hypothesis test that Rb = q. Coefficient tests are essentially made up. Test values taken from Stata. """ @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) res1 = OLS(data.endog, data.exog).fit() R = np.array([[0,1,1,0,0,0,0], [0,1,0,1,0,0,0], [0,1,0,0,0,0,0], [0,0,0,0,1,0,0], [0,0,0,0,0,1,0]]) q = np.array([0,0,0,1,0]) cls.Ftest1 = res1.f_test((R,q)) def test_fvalue(self): assert_almost_equal(self.Ftest1.fvalue, 70.115557, 5) def test_pvalue(self): assert_almost_equal(self.Ftest1.pvalue, 6.229e-07, 10) def test_df_denom(self): assert_equal(self.Ftest1.df_denom, 9) def test_df_num(self): assert_equal(self.Ftest1.df_num, 5) class TestTtest(object): """ Test individual t-tests. Ie., are the coefficients significantly different than zero. """ @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) cls.res1 = OLS(data.endog, data.exog).fit() R = np.identity(7) cls.Ttest = cls.res1.t_test(R) hyp = 'x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0, x6 = 0, const = 0' cls.NewTTest = cls.res1.t_test(hyp) def test_new_tvalue(self): assert_equal(self.NewTTest.tvalue, self.Ttest.tvalue) def test_tvalue(self): assert_almost_equal(self.Ttest.tvalue, self.res1.tvalues, DECIMAL_4) def test_sd(self): assert_almost_equal(self.Ttest.sd, self.res1.bse, DECIMAL_4) def test_pvalue(self): assert_almost_equal(self.Ttest.pvalue, student_t.sf( np.abs(self.res1.tvalues), self.res1.model.df_resid)*2, DECIMAL_4) def test_df_denom(self): assert_equal(self.Ttest.df_denom, self.res1.model.df_resid) def test_effect(self): assert_almost_equal(self.Ttest.effect, self.res1.params) class TestTtest2(object): """ Tests the hypothesis that the coefficients on POP and YEAR are equal. Results from RPy using 'car' package. """ @classmethod def setupClass(cls): R = np.zeros(7) R[4:6] = [1,-1] data = longley.load() data.exog = add_constant(data.exog, prepend=False) res1 = OLS(data.endog, data.exog).fit() cls.Ttest1 = res1.t_test(R) def test_tvalue(self): assert_almost_equal(self.Ttest1.tvalue, -4.0167754636397284, DECIMAL_4) def test_sd(self): assert_almost_equal(self.Ttest1.sd, 455.39079425195314, DECIMAL_4) def test_pvalue(self): assert_almost_equal(self.Ttest1.pvalue, 2*0.0015163772380932246, DECIMAL_4) def test_df_denom(self): assert_equal(self.Ttest1.df_denom, 9) def test_effect(self): assert_almost_equal(self.Ttest1.effect, -1829.2025687186533, DECIMAL_4) class TestGLS(object): """ These test results were obtained by replication with R. """ @classmethod def setupClass(cls): from .results.results_regression import LongleyGls data = longley.load() exog = add_constant(np.column_stack((data.exog[:,1], data.exog[:,4])), prepend=False) tmp_results = OLS(data.endog, exog).fit() rho = np.corrcoef(tmp_results.resid[1:], tmp_results.resid[:-1])[0][1] # by assumption order = toeplitz(np.arange(16)) sigma = rho**order GLS_results = GLS(data.endog, exog, sigma=sigma).fit() cls.res1 = GLS_results cls.res2 = LongleyGls() # attach for test_missing cls.sigma = sigma cls.exog = exog cls.endog = data.endog def test_aic(self): assert_approx_equal(self.res1.aic+2, self.res2.aic, 3) def test_bic(self): assert_approx_equal(self.res1.bic, self.res2.bic, 2) def test_loglike(self): assert_almost_equal(self.res1.llf, self.res2.llf, DECIMAL_0) def test_params(self): assert_almost_equal(self.res1.params, self.res2.params, DECIMAL_1) def test_resid(self): assert_almost_equal(self.res1.resid, self.res2.resid, DECIMAL_4) def test_scale(self): assert_almost_equal(self.res1.scale, self.res2.scale, DECIMAL_4) def test_tvalues(self): assert_almost_equal(self.res1.tvalues, self.res2.tvalues, DECIMAL_4) def test_standarderrors(self): assert_almost_equal(self.res1.bse, self.res2.bse, DECIMAL_4) def test_fittedvalues(self): assert_almost_equal(self.res1.fittedvalues, self.res2.fittedvalues, DECIMAL_4) def test_pvalues(self): assert_almost_equal(self.res1.pvalues, self.res2.pvalues, DECIMAL_4) def test_missing(self): endog = self.endog.copy() # copy or changes endog for other methods endog[[4,7,14]] = np.nan mod = GLS(endog, self.exog, sigma=self.sigma, missing='drop') assert_equal(mod.endog.shape[0], 13) assert_equal(mod.exog.shape[0], 13) assert_equal(mod.sigma.shape, (13,13)) class TestGLS_alt_sigma(CheckRegressionResults): """ Test that GLS with no argument is equivalent to OLS. """ @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) ols_res = OLS(data.endog, data.exog).fit() gls_res = GLS(data.endog, data.exog).fit() gls_res_scalar = GLS(data.endog, data.exog, sigma=1) cls.endog = data.endog cls.exog = data.exog cls.res1 = gls_res cls.res2 = ols_res cls.res3 = gls_res_scalar # self.res2.conf_int = self.res2.conf_int() def test_wrong_size_sigma_1d(self): n = len(self.endog) assert_raises(ValueError, GLS, self.endog, self.exog, sigma=np.ones(n-1)) def test_wrong_size_sigma_2d(self): n = len(self.endog) assert_raises(ValueError, GLS, self.endog, self.exog, sigma=np.ones((n-1,n-1))) # def check_confidenceintervals(self, conf1, conf2): # assert_almost_equal(conf1, conf2, DECIMAL_4) class TestLM(object): @classmethod def setupClass(cls): # TODO: Test HAC method X = np.random.randn(100,3) b = np.ones((3,1)) e = np.random.randn(100,1) y = np.dot(X,b) + e # Cases? # Homoskedastic # HC0 cls.res1_full = OLS(y,X).fit() cls.res1_restricted = OLS(y,X[:,0]).fit() cls.res2_full = cls.res1_full.get_robustcov_results('HC0') cls.res2_restricted = cls.res1_restricted.get_robustcov_results('HC0') cls.X = X cls.Y = y def test_LM_homoskedastic(self): resid = self.res1_restricted.wresid n = resid.shape[0] X = self.X S = np.dot(resid,resid) / n * np.dot(X.T,X) / n Sinv = np.linalg.inv(S) s = np.mean(X * resid[:,None], 0) LMstat = n * np.dot(np.dot(s,Sinv),s.T) LMstat_OLS = self.res1_full.compare_lm_test(self.res1_restricted) LMstat2 = LMstat_OLS[0] assert_almost_equal(LMstat, LMstat2, DECIMAL_7) def test_LM_heteroskedastic_nodemean(self): resid = self.res1_restricted.wresid n = resid.shape[0] X = self.X scores = X * resid[:,None] S = np.dot(scores.T,scores) / n Sinv = np.linalg.inv(S) s = np.mean(scores, 0) LMstat = n * np.dot(np.dot(s,Sinv),s.T) LMstat_OLS = self.res2_full.compare_lm_test(self.res2_restricted, demean=False) LMstat2 = LMstat_OLS[0] assert_almost_equal(LMstat, LMstat2, DECIMAL_7) def test_LM_heteroskedastic_demean(self): resid = self.res1_restricted.wresid n = resid.shape[0] X = self.X scores = X * resid[:,None] scores_demean = scores - scores.mean(0) S = np.dot(scores_demean.T,scores_demean) / n Sinv = np.linalg.inv(S) s = np.mean(scores, 0) LMstat = n * np.dot(np.dot(s,Sinv),s.T) LMstat_OLS = self.res2_full.compare_lm_test(self.res2_restricted) LMstat2 = LMstat_OLS[0] assert_almost_equal(LMstat, LMstat2, DECIMAL_7) def test_LM_heteroskedastic_LRversion(self): resid = self.res1_restricted.wresid resid_full = self.res1_full.wresid n = resid.shape[0] X = self.X scores = X * resid[:,None] s = np.mean(scores, 0) scores = X * resid_full[:,None] S = np.dot(scores.T,scores) / n Sinv = np.linalg.inv(S) LMstat = n * np.dot(np.dot(s,Sinv),s.T) LMstat_OLS = self.res2_full.compare_lm_test(self.res2_restricted, use_lr = True) LMstat2 = LMstat_OLS[0] assert_almost_equal(LMstat, LMstat2, DECIMAL_7) def test_LM_nonnested(self): assert_raises(ValueError, self.res2_restricted.compare_lm_test, self.res2_full) class TestOLS_GLS_WLS_equivalence(object): @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) y = data.endog X = data.exog n = y.shape[0] w = np.ones(n) cls.results = [] cls.results.append(OLS(y, X).fit()) cls.results.append(WLS(y, X, w).fit()) cls.results.append(GLS(y, X, 100*w).fit()) cls.results.append(GLS(y, X, np.diag(0.1*w)).fit()) def test_ll(self): llf = np.array([r.llf for r in self.results]) llf_1 = np.ones_like(llf) * self.results[0].llf assert_almost_equal(llf, llf_1, DECIMAL_7) ic = np.array([r.aic for r in self.results]) ic_1 = np.ones_like(ic) * self.results[0].aic assert_almost_equal(ic, ic_1, DECIMAL_7) ic = np.array([r.bic for r in self.results]) ic_1 = np.ones_like(ic) * self.results[0].bic assert_almost_equal(ic, ic_1, DECIMAL_7) def test_params(self): params = np.array([r.params for r in self.results]) params_1 = np.array([self.results[0].params] * len(self.results)) assert_allclose(params, params_1) def test_ss(self): bse = np.array([r.bse for r in self.results]) bse_1 = np.array([self.results[0].bse] * len(self.results)) assert_allclose(bse, bse_1) def test_rsquared(self): rsquared = np.array([r.rsquared for r in self.results]) rsquared_1 = np.array([self.results[0].rsquared] * len(self.results)) assert_almost_equal(rsquared, rsquared_1, DECIMAL_7) class TestGLS_WLS_equivalence(TestOLS_GLS_WLS_equivalence): # reuse test methods @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) y = data.endog X = data.exog n = y.shape[0] np.random.seed(5) w = np.random.uniform(0.5, 1, n) w_inv = 1. / w cls.results = [] cls.results.append(WLS(y, X, w).fit()) cls.results.append(WLS(y, X, 0.01 * w).fit()) cls.results.append(GLS(y, X, 100 * w_inv).fit()) cls.results.append(GLS(y, X, np.diag(0.1 * w_inv)).fit()) def test_rsquared(self): # TODO: WLS rsquared is ok, GLS might have wrong centered_tss # We only check that WLS and GLS rsquared is invariant to scaling # WLS and GLS have different rsquared assert_almost_equal(self.results[1].rsquared, self.results[0].rsquared, DECIMAL_7) assert_almost_equal(self.results[3].rsquared, self.results[2].rsquared, DECIMAL_7) class TestNonFit(object): @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) cls.endog = data.endog cls.exog = data.exog cls.ols_model = OLS(data.endog, data.exog) def test_df_resid(self): df_resid = self.endog.shape[0] - self.exog.shape[1] assert_equal(self.ols_model.df_resid, long(9)) class TestWLS_CornerCases(object): @classmethod def setupClass(cls): cls.exog = np.ones((1,)) cls.endog = np.ones((1,)) weights = 1 cls.wls_res = WLS(cls.endog, cls.exog, weights=weights).fit() def test_wrong_size_weights(self): weights = np.ones((10,10)) assert_raises(ValueError, WLS, self.endog, self.exog, weights=weights) class TestWLSExogWeights(CheckRegressionResults): #Test WLS with Greene's credit card data #reg avgexp age income incomesq ownrent [aw=1/incomesq] def __init__(self): from .results.results_regression import CCardWLS from statsmodels.datasets.ccard import load dta = load() dta.exog = add_constant(dta.exog, prepend=False) nobs = 72. weights = 1/dta.exog[:,2] # for comparison with stata analytic weights scaled_weights = ((weights * nobs)/weights.sum()) self.res1 = WLS(dta.endog, dta.exog, weights=scaled_weights).fit() self.res2 = CCardWLS() self.res2.wresid = scaled_weights ** .5 * self.res2.resid # correction because we use different definition for loglike/llf corr_ic = 2 * (self.res1.llf - self.res2.llf) self.res2.aic -= corr_ic self.res2.bic -= corr_ic self.res2.llf += 0.5 * np.sum(np.log(self.res1.model.weights)) def test_wls_example(): #example from the docstring, there was a note about a bug, should #be fixed now Y = [1,3,4,5,2,3,4] X = lrange(1,8) X = add_constant(X, prepend=False) wls_model = WLS(Y,X, weights=lrange(1,8)).fit() #taken from R lm.summary assert_almost_equal(wls_model.fvalue, 0.127337843215, 6) assert_almost_equal(wls_model.scale, 2.44608530786**2, 6) def test_wls_tss(): y = np.array([22, 22, 22, 23, 23, 23]) X = [[1, 0], [1, 0], [1, 1], [0, 1], [0, 1], [0, 1]] ols_mod = OLS(y, add_constant(X, prepend=False)).fit() yw = np.array([22, 22, 23.]) Xw = [[1,0],[1,1],[0,1]] w = np.array([2, 1, 3.]) wls_mod = WLS(yw, add_constant(Xw, prepend=False), weights=w).fit() assert_equal(ols_mod.centered_tss, wls_mod.centered_tss) class TestWLSScalarVsArray(CheckRegressionResults): @classmethod def setupClass(cls): from statsmodels.datasets.longley import load dta = load() dta.exog = add_constant(dta.exog, prepend=True) wls_scalar = WLS(dta.endog, dta.exog, weights=1./3).fit() weights = [1/3.] * len(dta.endog) wls_array = WLS(dta.endog, dta.exog, weights=weights).fit() cls.res1 = wls_scalar cls.res2 = wls_array #class TestWLS_GLS(CheckRegressionResults): # @classmethod # def setupClass(cls): # from statsmodels.datasets.ccard import load # data = load() # cls.res1 = WLS(data.endog, data.exog, weights = 1/data.exog[:,2]).fit() # cls.res2 = GLS(data.endog, data.exog, sigma = data.exog[:,2]).fit() # # def check_confidenceintervals(self, conf1, conf2): # assert_almost_equal(conf1, conf2(), DECIMAL_4) def test_wls_missing(): from statsmodels.datasets.ccard import load data = load() endog = data.endog endog[[10, 25]] = np.nan mod = WLS(data.endog, data.exog, weights = 1/data.exog[:,2], missing='drop') assert_equal(mod.endog.shape[0], 70) assert_equal(mod.exog.shape[0], 70) assert_equal(mod.weights.shape[0], 70) class TestWLS_OLS(CheckRegressionResults): @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) cls.res1 = OLS(data.endog, data.exog).fit() cls.res2 = WLS(data.endog, data.exog).fit() def check_confidenceintervals(self, conf1, conf2): assert_almost_equal(conf1, conf2(), DECIMAL_4) class TestGLS_OLS(CheckRegressionResults): @classmethod def setupClass(cls): data = longley.load() data.exog = add_constant(data.exog, prepend=False) cls.res1 = GLS(data.endog, data.exog).fit() cls.res2 = OLS(data.endog, data.exog).fit() def check_confidenceintervals(self, conf1, conf2): assert_almost_equal(conf1, conf2(), DECIMAL_4) #TODO: test AR # why the two-stage in AR? #class test_ar(object): # from statsmodels.datasets.sunspots import load # data = load() # model = AR(data.endog, rho=4).fit() # R_res = RModel(data.endog, aic="FALSE", order_max=4) # def test_params(self): # assert_almost_equal(self.model.rho, # pass # def test_order(self): # In R this can be defined or chosen by minimizing the AIC if aic=True # pass class TestYuleWalker(object): @classmethod def setupClass(cls): from statsmodels.datasets.sunspots import load data = load() cls.rho, cls.sigma = yule_walker(data.endog, order=4, method="mle") cls.R_params = [1.2831003105694765, -0.45240924374091945, -0.20770298557575195, 0.047943648089542337] def test_params(self): assert_almost_equal(self.rho, self.R_params, DECIMAL_4) class TestDataDimensions(CheckRegressionResults): @classmethod def setupClass(cls): np.random.seed(54321) cls.endog_n_ = np.random.uniform(0,20,size=30) cls.endog_n_one = cls.endog_n_[:,None] cls.exog_n_ = np.random.uniform(0,20,size=30) cls.exog_n_one = cls.exog_n_[:,None] cls.degen_exog = cls.exog_n_one[:-1] cls.mod1 = OLS(cls.endog_n_one, cls.exog_n_one) cls.mod1.df_model += 1 cls.res1 = cls.mod1.fit() # Note that these are created for every subclass.. # A little extra overhead probably cls.mod2 = OLS(cls.endog_n_one, cls.exog_n_one) cls.mod2.df_model += 1 cls.res2 = cls.mod2.fit() def check_confidenceintervals(self, conf1, conf2): assert_almost_equal(conf1, conf2(), DECIMAL_4) class TestGLS_large_data(TestDataDimensions): @classmethod def setupClass(cls): nobs = 1000 y = np.random.randn(nobs,1) X = np.random.randn(nobs,20) sigma = np.ones_like(y) cls.gls_res = GLS(y, X, sigma=sigma).fit() cls.gls_res_scalar = GLS(y, X, sigma=1).fit() cls.gls_res_none= GLS(y, X).fit() cls.ols_res = OLS(y, X).fit() def test_large_equal_params(self): assert_almost_equal(self.ols_res.params, self.gls_res.params, DECIMAL_7) def test_large_equal_loglike(self): assert_almost_equal(self.ols_res.llf, self.gls_res.llf, DECIMAL_7) def test_large_equal_params_none(self): assert_almost_equal(self.gls_res.params, self.gls_res_none.params, DECIMAL_7) class TestNxNx(TestDataDimensions): @classmethod def setupClass(cls): super(TestNxNx, cls).setupClass() cls.mod2 = OLS(cls.endog_n_, cls.exog_n_) cls.mod2.df_model += 1 cls.res2 = cls.mod2.fit() class TestNxOneNx(TestDataDimensions): @classmethod def setupClass(cls): super(TestNxOneNx, cls).setupClass() cls.mod2 = OLS(cls.endog_n_one, cls.exog_n_) cls.mod2.df_model += 1 cls.res2 = cls.mod2.fit() class TestNxNxOne(TestDataDimensions): @classmethod def setupClass(cls): super(TestNxNxOne, cls).setupClass() cls.mod2 = OLS(cls.endog_n_, cls.exog_n_one) cls.mod2.df_model += 1 cls.res2 = cls.mod2.fit() def test_bad_size(): np.random.seed(54321) data = np.random.uniform(0,20,31) assert_raises(ValueError, OLS, data, data[1:]) def test_const_indicator(): np.random.seed(12345) X = np.random.randint(0, 3, size=30) X = categorical(X, drop=True) y = np.dot(X, [1., 2., 3.]) + np.random.normal(size=30) modc = OLS(y, add_constant(X[:,1:], prepend=True)).fit() mod = OLS(y, X, hasconst=True).fit() assert_almost_equal(modc.rsquared, mod.rsquared, 12) def test_706(): # make sure one regressor pandas Series gets passed to DataFrame # for conf_int. y = pandas.Series(np.random.randn(10)) x = pandas.Series(np.ones(10)) res = OLS(y,x).fit() conf_int = res.conf_int() np.testing.assert_equal(conf_int.shape, (1, 2)) np.testing.assert_(isinstance(conf_int, pandas.DataFrame)) def test_summary(): # test 734 import re dta = longley.load_pandas() X = dta.exog X["constant"] = 1 y = dta.endog with warnings.catch_warnings(record=True): res = OLS(y, X).fit() table = res.summary().as_latex() # replace the date and time table = re.sub("(?<=\n\\\\textbf\{Date:\} &).+?&", " Sun, 07 Apr 2013 &", table) table = re.sub("(?<=\n\\\\textbf\{Time:\} &).+?&", " 13:46:07 &", table) expected = """\\begin{center} \\begin{tabular}{lclc} \\toprule \\textbf{Dep. Variable:} & TOTEMP & \\textbf{ R-squared: } & 0.995 \\\\ \\textbf{Model:} & OLS & \\textbf{ Adj. R-squared: } & 0.992 \\\\ \\textbf{Method:} & Least Squares & \\textbf{ F-statistic: } & 330.3 \\\\ \\textbf{Date:} & Sun, 07 Apr 2013 & \\textbf{ Prob (F-statistic):} & 4.98e-10 \\\\ \\textbf{Time:} & 13:46:07 & \\textbf{ Log-Likelihood: } & -109.62 \\\\ \\textbf{No. Observations:} & 16 & \\textbf{ AIC: } & 233.2 \\\\ \\textbf{Df Residuals:} & 9 & \\textbf{ BIC: } & 238.6 \\\\ \\textbf{Df Model:} & 6 & \\textbf{ } & \\\\ \\bottomrule \\end{tabular} \\begin{tabular}{lcccccc} & \\textbf{coef} & \\textbf{std err} & \\textbf{t} & \\textbf{P$>$$|$t$|$} & \\textbf{[0.025} & \\textbf{0.975]} \\\\ \\midrule \\textbf{GNPDEFL} & 15.0619 & 84.915 & 0.177 & 0.863 & -177.029 & 207.153 \\\\ \\textbf{GNP} & -0.0358 & 0.033 & -1.070 & 0.313 & -0.112 & 0.040 \\\\ \\textbf{UNEMP} & -2.0202 & 0.488 & -4.136 & 0.003 & -3.125 & -0.915 \\\\ \\textbf{ARMED} & -1.0332 & 0.214 & -4.822 & 0.001 & -1.518 & -0.549 \\\\ \\textbf{POP} & -0.0511 & 0.226 & -0.226 & 0.826 & -0.563 & 0.460 \\\\ \\textbf{YEAR} & 1829.1515 & 455.478 & 4.016 & 0.003 & 798.788 & 2859.515 \\\\ \\textbf{constant} & -3.482e+06 & 8.9e+05 & -3.911 & 0.004 & -5.5e+06 & -1.47e+06 \\\\ \\bottomrule \\end{tabular} \\begin{tabular}{lclc} \\textbf{Omnibus:} & 0.749 & \\textbf{ Durbin-Watson: } & 2.559 \\\\ \\textbf{Prob(Omnibus):} & 0.688 & \\textbf{ Jarque-Bera (JB): } & 0.684 \\\\ \\textbf{Skew:} & 0.420 & \\textbf{ Prob(JB): } & 0.710 \\\\ \\textbf{Kurtosis:} & 2.434 & \\textbf{ Cond. No. } & 4.86e+09 \\\\ \\bottomrule \\end{tabular} %\\caption{OLS Regression Results} \\end{center}""" assert_equal(table, expected) class TestRegularizedFit(object): # Make sure there are no issues when there are no selected # variables. def test_empty_model(self): np.random.seed(742) n = 100 endog = np.random.normal(size=n) exog = np.random.normal(size=(n, 3)) model = OLS(endog, exog) result = model.fit_regularized(alpha=1000) assert_equal(result.params, 0.) assert_equal(result.bse, 0.) def test_regularized(self): import os from . import glmnet_r_results cur_dir = os.path.dirname(os.path.abspath(__file__)) data = np.loadtxt(os.path.join(cur_dir, "results", "lasso_data.csv"), delimiter=",") tests = [x for x in dir(glmnet_r_results) if x.startswith("rslt_")] for test in tests: vec = getattr(glmnet_r_results, test) n = vec[0] p = vec[1] L1_wt = float(vec[2]) lam = float(vec[3]) params = vec[4:].astype(np.float64) endog = data[0:int(n), 0] exog = data[0:int(n), 1:(int(p)+1)] endog = endog - endog.mean() endog /= endog.std(ddof=1) exog = exog - exog.mean(0) exog /= exog.std(0, ddof=1) mod = OLS(endog, exog) rslt = mod.fit_regularized(L1_wt=L1_wt, alpha=lam) assert_almost_equal(rslt.params, params, decimal=3) # Smoke test for summary smry = rslt.summary() def test_formula_missing_cat(): # gh-805 import statsmodels.api as sm from statsmodels.formula.api import ols from patsy import PatsyError dta = sm.datasets.grunfeld.load_pandas().data dta.ix[0, 'firm'] = np.nan mod = ols(formula='value ~ invest + capital + firm + year', data=dta.dropna()) res = mod.fit() mod2 = ols(formula='value ~ invest + capital + firm + year', data=dta) res2 = mod2.fit() assert_almost_equal(res.params.values, res2.params.values) assert_raises(PatsyError, ols, 'value ~ invest + capital + firm + year', data=dta, missing='raise') def test_missing_formula_predict(): # see 2171 nsample = 30 data = pandas.DataFrame({'x': np.linspace(0, 10, nsample)}) null = pandas.DataFrame({'x': np.array([np.nan])}) data = pandas.concat([data, null]) beta = np.array([1, 0.1]) e = np.random.normal(size=nsample+1) data['y'] = beta[0] + beta[1] * data['x'] + e model = OLS.from_formula('y ~ x', data=data) fit = model.fit() pred = fit.predict(exog=data[:-1]) def test_fvalue_implicit_constant(): nobs = 100 np.random.seed(2) x = np.random.randn(nobs, 1) x = ((x > 0) == [True, False]).astype(int) y = x.sum(1) + np.random.randn(nobs) w = 1 + 0.25 * np.random.rand(nobs) from statsmodels.regression.linear_model import OLS, WLS res = OLS(y, x).fit(cov_type='HC1') assert_(np.isnan(res.fvalue)) assert_(np.isnan(res.f_pvalue)) res.summary() res = WLS(y, x).fit(cov_type='HC1') assert_(np.isnan(res.fvalue)) assert_(np.isnan(res.f_pvalue)) res.summary() if __name__=="__main__": import nose # run_module_suite() nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'], exit=False) # nose.runmodule(argv=[__file__,'-vvs','-x'], exit=False) #, '--pdb'
bsd-3-clause
serendio-labs/diskoveror-ta
src/main/python/Topics/Seeds22/labeledCluster.py
3
3944
''' Copyright 2015 Serendio Inc. Author - Satish Palaniappan 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__ = "Satish Palaniappan" import numpy as np from sklearn import cluster, datasets, preprocessing import pickle import gensim import time import re import tokenize from scipy import spatial def save_obj(obj, name ): with open( name + '.pkl', 'wb') as f: pickle.dump(obj, f, protocol=2) def load_obj(name ): with open( name + '.pkl', 'rb') as f: return pickle.load(f) # 3M word google dataset of pretrained 300D vectors model = gensim.models.Word2Vec.load_word2vec_format('vectors.bin', binary=True) model.init_sims(replace=True) #### getting all vecs from w2v using the inbuilt syn0 list see code # X = model.syn0 # ### scaling feature vecs # min_max_scaler = preprocessing.MinMaxScaler() # X_Scaled_Feature_Vecs = min_max_scaler.fit_transform(X) # X_Scaled_Feature_Vecs = X # W2V = dict(zip(model.vocab, X_Scaled_Feature_Vecs)) #Cosine Distance # from scipy import spatial # dataSetI = model["travel"] # dataSetII = model["travelling"] # result = 1 - spatial.distance.cosine(dataSetI, dataSetII) # print(result) X_Scaled_Feature_Vecs=[] for word in model.vocab: X_Scaled_Feature_Vecs.append(model[word]) # ######## Interested Categories cat = [ "advertising", "beauty", "business", "celebrity", "diy craft", "entertainment", "family", "fashion", "food", "general", "health", "lifestyle", "music", "news", "pop", "culture", "social", "media", "sports", "technology", "travel", "video games" ] nums = range(0,22) num2cat = dict(zip(nums, cat)) catVec=[] # load from C file output for c in cat: try: catVec.append(model[c.lower()]) except: words = c.split() A = np.add(np.array(model[words[0].lower()]),np.array(model[words[1].lower()])) M = np.multiply(A,A) lent=0 for i in M: lent+=i V = np.divide(A,lent) catVec.append(list(V)) # kmeans ##### better code t0 = time.time() # Assign Max_Iter to 1 (ONE) if u just want to fit vectors around seeds kmeans = cluster.KMeans(n_clusters=22, init=np.array(catVec), max_iter=1).fit(X_Scaled_Feature_Vecs) #kmeans = cluster.KMeans(n_clusters=22, init=np.array(catVec), max_iter=900).fit(X_Scaled_Feature_Vecs) print(str(time.time()-t0)) print(kmeans.inertia_) ###### After Fiting the Cluster Centers are recomputed : update catVec (Order Preserved) catVec = kmeans.cluster_centers_ # #test # for c in catVec: # print(num2cat[kmeans.predict(c)[0]]) ##### save best for future use save_obj(kmeans,"clusterSmall") KM = load_obj("clusterSmall") # Cluster_lookUP = dict(zip(model.vocab, KM.labels_)) Cluster_lookUP = dict() for word in model.vocab: Cluster_lookUP[word] = KM.predict(model[word])[0] ## Precomputing the cosine similarities Cosine_Similarity = dict() for k in Cluster_lookUP.keys(): Cosine_Similarity[k] = 1 - spatial.distance.cosine(model[k], catVec[Cluster_lookUP[k]]) #check print(num2cat[Cluster_lookUP["flight"]] + " "+str(Cosine_Similarity["flight"])) print(num2cat[Cluster_lookUP["gamecube"]] +" "+str(Cosine_Similarity["gamecube"])) #Saving Models save_obj(Cluster_lookUP,"Cluster_lookUP") save_obj(Cosine_Similarity,"Cosine_Similarity") save_obj(num2cat,"num2cat") save_obj(catVec,"catVec")
apache-2.0
Vimos/scikit-learn
sklearn/decomposition/tests/test_pca.py
9
21107
import numpy as np import scipy as sp from itertools import product from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_no_warnings from sklearn.utils.testing import assert_warns_message from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_less from sklearn import datasets from sklearn.decomposition import PCA from sklearn.decomposition import RandomizedPCA from sklearn.decomposition.pca import _assess_dimension_ from sklearn.decomposition.pca import _infer_dimension_ iris = datasets.load_iris() solver_list = ['full', 'arpack', 'randomized', 'auto'] def test_pca(): # PCA on dense arrays X = iris.data for n_comp in np.arange(X.shape[1]): pca = PCA(n_components=n_comp, svd_solver='full') X_r = pca.fit(X).transform(X) np.testing.assert_equal(X_r.shape[1], n_comp) X_r2 = pca.fit_transform(X) assert_array_almost_equal(X_r, X_r2) X_r = pca.transform(X) X_r2 = pca.fit_transform(X) assert_array_almost_equal(X_r, X_r2) # Test get_covariance and get_precision cov = pca.get_covariance() precision = pca.get_precision() assert_array_almost_equal(np.dot(cov, precision), np.eye(X.shape[1]), 12) # test explained_variance_ratio_ == 1 with all components pca = PCA(svd_solver='full') pca.fit(X) assert_almost_equal(pca.explained_variance_ratio_.sum(), 1.0, 3) def test_pca_arpack_solver(): # PCA on dense arrays X = iris.data d = X.shape[1] # Loop excluding the extremes, invalid inputs for arpack for n_comp in np.arange(1, d): pca = PCA(n_components=n_comp, svd_solver='arpack', random_state=0) X_r = pca.fit(X).transform(X) np.testing.assert_equal(X_r.shape[1], n_comp) X_r2 = pca.fit_transform(X) assert_array_almost_equal(X_r, X_r2) X_r = pca.transform(X) assert_array_almost_equal(X_r, X_r2) # Test get_covariance and get_precision cov = pca.get_covariance() precision = pca.get_precision() assert_array_almost_equal(np.dot(cov, precision), np.eye(d), 12) pca = PCA(n_components=0, svd_solver='arpack', random_state=0) assert_raises(ValueError, pca.fit, X) # Check internal state assert_equal(pca.n_components, PCA(n_components=0, svd_solver='arpack', random_state=0).n_components) assert_equal(pca.svd_solver, PCA(n_components=0, svd_solver='arpack', random_state=0).svd_solver) pca = PCA(n_components=d, svd_solver='arpack', random_state=0) assert_raises(ValueError, pca.fit, X) assert_equal(pca.n_components, PCA(n_components=d, svd_solver='arpack', random_state=0).n_components) assert_equal(pca.svd_solver, PCA(n_components=0, svd_solver='arpack', random_state=0).svd_solver) def test_pca_randomized_solver(): # PCA on dense arrays X = iris.data # Loop excluding the 0, invalid for randomized for n_comp in np.arange(1, X.shape[1]): pca = PCA(n_components=n_comp, svd_solver='randomized', random_state=0) X_r = pca.fit(X).transform(X) np.testing.assert_equal(X_r.shape[1], n_comp) X_r2 = pca.fit_transform(X) assert_array_almost_equal(X_r, X_r2) X_r = pca.transform(X) assert_array_almost_equal(X_r, X_r2) # Test get_covariance and get_precision cov = pca.get_covariance() precision = pca.get_precision() assert_array_almost_equal(np.dot(cov, precision), np.eye(X.shape[1]), 12) pca = PCA(n_components=0, svd_solver='randomized', random_state=0) assert_raises(ValueError, pca.fit, X) pca = PCA(n_components=0, svd_solver='randomized', random_state=0) assert_raises(ValueError, pca.fit, X) # Check internal state assert_equal(pca.n_components, PCA(n_components=0, svd_solver='randomized', random_state=0).n_components) assert_equal(pca.svd_solver, PCA(n_components=0, svd_solver='randomized', random_state=0).svd_solver) def test_no_empty_slice_warning(): # test if we avoid numpy warnings for computing over empty arrays n_components = 10 n_features = n_components + 2 # anything > n_comps triggered it in 0.16 X = np.random.uniform(-1, 1, size=(n_components, n_features)) pca = PCA(n_components=n_components) assert_no_warnings(pca.fit, X) def test_whitening(): # Check that PCA output has unit-variance rng = np.random.RandomState(0) n_samples = 100 n_features = 80 n_components = 30 rank = 50 # some low rank data with correlated features X = np.dot(rng.randn(n_samples, rank), np.dot(np.diag(np.linspace(10.0, 1.0, rank)), rng.randn(rank, n_features))) # the component-wise variance of the first 50 features is 3 times the # mean component-wise variance of the remaining 30 features X[:, :50] *= 3 assert_equal(X.shape, (n_samples, n_features)) # the component-wise variance is thus highly varying: assert_greater(X.std(axis=0).std(), 43.8) for solver, copy in product(solver_list, (True, False)): # whiten the data while projecting to the lower dim subspace X_ = X.copy() # make sure we keep an original across iterations. pca = PCA(n_components=n_components, whiten=True, copy=copy, svd_solver=solver, random_state=0, iterated_power=7) # test fit_transform X_whitened = pca.fit_transform(X_.copy()) assert_equal(X_whitened.shape, (n_samples, n_components)) X_whitened2 = pca.transform(X_) assert_array_almost_equal(X_whitened, X_whitened2) assert_almost_equal(X_whitened.std(axis=0), np.ones(n_components), decimal=6) assert_almost_equal(X_whitened.mean(axis=0), np.zeros(n_components)) X_ = X.copy() pca = PCA(n_components=n_components, whiten=False, copy=copy, svd_solver=solver).fit(X_) X_unwhitened = pca.transform(X_) assert_equal(X_unwhitened.shape, (n_samples, n_components)) # in that case the output components still have varying variances assert_almost_equal(X_unwhitened.std(axis=0).std(), 74.1, 1) # we always center, so no test for non-centering. # Ignore warnings from switching to more power iterations in randomized_svd @ignore_warnings def test_explained_variance(): # Check that PCA output has unit-variance rng = np.random.RandomState(0) n_samples = 100 n_features = 80 X = rng.randn(n_samples, n_features) pca = PCA(n_components=2, svd_solver='full').fit(X) apca = PCA(n_components=2, svd_solver='arpack', random_state=0).fit(X) assert_array_almost_equal(pca.explained_variance_, apca.explained_variance_, 1) assert_array_almost_equal(pca.explained_variance_ratio_, apca.explained_variance_ratio_, 3) rpca = PCA(n_components=2, svd_solver='randomized', random_state=42).fit(X) assert_array_almost_equal(pca.explained_variance_, rpca.explained_variance_, 1) assert_array_almost_equal(pca.explained_variance_ratio_, rpca.explained_variance_ratio_, 1) # compare to empirical variances X_pca = pca.transform(X) assert_array_almost_equal(pca.explained_variance_, np.var(X_pca, axis=0)) X_pca = apca.transform(X) assert_array_almost_equal(apca.explained_variance_, np.var(X_pca, axis=0)) X_rpca = rpca.transform(X) assert_array_almost_equal(rpca.explained_variance_, np.var(X_rpca, axis=0), decimal=1) # Same with correlated data X = datasets.make_classification(n_samples, n_features, n_informative=n_features-2, random_state=rng)[0] pca = PCA(n_components=2).fit(X) rpca = PCA(n_components=2, svd_solver='randomized', random_state=rng).fit(X) assert_array_almost_equal(pca.explained_variance_ratio_, rpca.explained_variance_ratio_, 5) def test_singular_values(): # Check that the PCA output has the correct singular values rng = np.random.RandomState(0) n_samples = 100 n_features = 80 X = rng.randn(n_samples, n_features) pca = PCA(n_components=2, svd_solver='full', random_state=rng).fit(X) apca = PCA(n_components=2, svd_solver='arpack', random_state=rng).fit(X) rpca = PCA(n_components=2, svd_solver='randomized', random_state=rng).fit(X) assert_array_almost_equal(pca.singular_values_, apca.singular_values_, 12) assert_array_almost_equal(pca.singular_values_, rpca.singular_values_, 1) assert_array_almost_equal(apca.singular_values_, rpca.singular_values_, 1) # Compare to the Frobenius norm X_pca = pca.transform(X) X_apca = apca.transform(X) X_rpca = rpca.transform(X) assert_array_almost_equal(np.sum(pca.singular_values_**2.0), np.linalg.norm(X_pca, "fro")**2.0, 12) assert_array_almost_equal(np.sum(apca.singular_values_**2.0), np.linalg.norm(X_apca, "fro")**2.0, 12) assert_array_almost_equal(np.sum(rpca.singular_values_**2.0), np.linalg.norm(X_rpca, "fro")**2.0, 0) # Compare to the 2-norms of the score vectors assert_array_almost_equal(pca.singular_values_, np.sqrt(np.sum(X_pca**2.0, axis=0)), 12) assert_array_almost_equal(apca.singular_values_, np.sqrt(np.sum(X_apca**2.0, axis=0)), 12) assert_array_almost_equal(rpca.singular_values_, np.sqrt(np.sum(X_rpca**2.0, axis=0)), 2) # Set the singular values and see what we get back rng = np.random.RandomState(0) n_samples = 100 n_features = 110 X = rng.randn(n_samples, n_features) pca = PCA(n_components=3, svd_solver='full', random_state=rng) apca = PCA(n_components=3, svd_solver='arpack', random_state=rng) rpca = PCA(n_components=3, svd_solver='randomized', random_state=rng) X_pca = pca.fit_transform(X) X_pca /= np.sqrt(np.sum(X_pca**2.0, axis=0)) X_pca[:, 0] *= 3.142 X_pca[:, 1] *= 2.718 X_hat = np.dot(X_pca, pca.components_) pca.fit(X_hat) apca.fit(X_hat) rpca.fit(X_hat) assert_array_almost_equal(pca.singular_values_, [3.142, 2.718, 1.0], 14) assert_array_almost_equal(apca.singular_values_, [3.142, 2.718, 1.0], 14) assert_array_almost_equal(rpca.singular_values_, [3.142, 2.718, 1.0], 14) def test_pca_check_projection(): # Test that the projection of data is correct rng = np.random.RandomState(0) n, p = 100, 3 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5]) Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) for solver in solver_list: Yt = PCA(n_components=2, svd_solver=solver).fit(X).transform(Xt) Yt /= np.sqrt((Yt ** 2).sum()) assert_almost_equal(np.abs(Yt[0][0]), 1., 1) def test_pca_inverse(): # Test that the projection of data can be inverted rng = np.random.RandomState(0) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed # signal (since the data is almost of rank n_components) pca = PCA(n_components=2, svd_solver='full').fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=3) # same as above with whitening (approximate reconstruction) for solver in solver_list: pca = PCA(n_components=2, whiten=True, svd_solver=solver) pca.fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=3) def test_pca_validation(): X = [[0, 1], [1, 0]] for solver in solver_list: for n_components in [-1, 3]: assert_raises(ValueError, PCA(n_components, svd_solver=solver).fit, X) def test_randomized_pca_check_projection(): # Test that the projection by randomized PCA on dense data is correct rng = np.random.RandomState(0) n, p = 100, 3 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5]) Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) Yt = PCA(n_components=2, svd_solver='randomized', random_state=0).fit(X).transform(Xt) Yt /= np.sqrt((Yt ** 2).sum()) assert_almost_equal(np.abs(Yt[0][0]), 1., 1) def test_randomized_pca_check_list(): # Test that the projection by randomized PCA on list data is correct X = [[1.0, 0.0], [0.0, 1.0]] X_transformed = PCA(n_components=1, svd_solver='randomized', random_state=0).fit(X).transform(X) assert_equal(X_transformed.shape, (2, 1)) assert_almost_equal(X_transformed.mean(), 0.00, 2) assert_almost_equal(X_transformed.std(), 0.71, 2) def test_randomized_pca_inverse(): # Test that randomized PCA is inversible on dense data rng = np.random.RandomState(0) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed signal # (since the data is almost of rank n_components) pca = PCA(n_components=2, svd_solver='randomized', random_state=0).fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=2) # same as above with whitening (approximate reconstruction) pca = PCA(n_components=2, whiten=True, svd_solver='randomized', random_state=0).fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) relative_max_delta = (np.abs(X - Y_inverse) / np.abs(X).mean()).max() assert_less(relative_max_delta, 1e-5) def test_pca_dim(): # Check automated dimensionality setting rng = np.random.RandomState(0) n, p = 100, 5 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5, 1, 2]) pca = PCA(n_components='mle', svd_solver='full').fit(X) assert_equal(pca.n_components, 'mle') assert_equal(pca.n_components_, 1) def test_infer_dim_1(): # TODO: explain what this is testing # Or at least use explicit variable names... n, p = 1000, 5 rng = np.random.RandomState(0) X = (rng.randn(n, p) * .1 + rng.randn(n, 1) * np.array([3, 4, 5, 1, 2]) + np.array([1, 0, 7, 4, 6])) pca = PCA(n_components=p, svd_solver='full') pca.fit(X) spect = pca.explained_variance_ ll = [] for k in range(p): ll.append(_assess_dimension_(spect, k, n, p)) ll = np.array(ll) assert_greater(ll[1], ll.max() - .01 * n) def test_infer_dim_2(): # TODO: explain what this is testing # Or at least use explicit variable names... n, p = 1000, 5 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5, 1, 2]) X[10:20] += np.array([6, 0, 7, 2, -1]) pca = PCA(n_components=p, svd_solver='full') pca.fit(X) spect = pca.explained_variance_ assert_greater(_infer_dimension_(spect, n, p), 1) def test_infer_dim_3(): n, p = 100, 5 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5, 1, 2]) X[10:20] += np.array([6, 0, 7, 2, -1]) X[30:40] += 2 * np.array([-1, 1, -1, 1, -1]) pca = PCA(n_components=p, svd_solver='full') pca.fit(X) spect = pca.explained_variance_ assert_greater(_infer_dimension_(spect, n, p), 2) def test_infer_dim_by_explained_variance(): X = iris.data pca = PCA(n_components=0.95, svd_solver='full') pca.fit(X) assert_equal(pca.n_components, 0.95) assert_equal(pca.n_components_, 2) pca = PCA(n_components=0.01, svd_solver='full') pca.fit(X) assert_equal(pca.n_components, 0.01) assert_equal(pca.n_components_, 1) rng = np.random.RandomState(0) # more features than samples X = rng.rand(5, 20) pca = PCA(n_components=.5, svd_solver='full').fit(X) assert_equal(pca.n_components, 0.5) assert_equal(pca.n_components_, 2) def test_pca_score(): # Test that probabilistic PCA scoring yields a reasonable score n, p = 1000, 3 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 + np.array([3, 4, 5]) for solver in solver_list: pca = PCA(n_components=2, svd_solver=solver) pca.fit(X) ll1 = pca.score(X) h = -0.5 * np.log(2 * np.pi * np.exp(1) * 0.1 ** 2) * p np.testing.assert_almost_equal(ll1 / h, 1, 0) def test_pca_score2(): # Test that probabilistic PCA correctly separated different datasets n, p = 100, 3 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 + np.array([3, 4, 5]) for solver in solver_list: pca = PCA(n_components=2, svd_solver=solver) pca.fit(X) ll1 = pca.score(X) ll2 = pca.score(rng.randn(n, p) * .2 + np.array([3, 4, 5])) assert_greater(ll1, ll2) # Test that it gives different scores if whiten=True pca = PCA(n_components=2, whiten=True, svd_solver=solver) pca.fit(X) ll2 = pca.score(X) assert_true(ll1 > ll2) def test_pca_score3(): # Check that probabilistic PCA selects the right model n, p = 200, 3 rng = np.random.RandomState(0) Xl = (rng.randn(n, p) + rng.randn(n, 1) * np.array([3, 4, 5]) + np.array([1, 0, 7])) Xt = (rng.randn(n, p) + rng.randn(n, 1) * np.array([3, 4, 5]) + np.array([1, 0, 7])) ll = np.zeros(p) for k in range(p): pca = PCA(n_components=k, svd_solver='full') pca.fit(Xl) ll[k] = pca.score(Xt) assert_true(ll.argmax() == 1) def test_svd_solver_auto(): rng = np.random.RandomState(0) X = rng.uniform(size=(1000, 50)) # case: n_components in (0,1) => 'full' pca = PCA(n_components=.5) pca.fit(X) pca_test = PCA(n_components=.5, svd_solver='full') pca_test.fit(X) assert_array_almost_equal(pca.components_, pca_test.components_) # case: max(X.shape) <= 500 => 'full' pca = PCA(n_components=5, random_state=0) Y = X[:10, :] pca.fit(Y) pca_test = PCA(n_components=5, svd_solver='full', random_state=0) pca_test.fit(Y) assert_array_almost_equal(pca.components_, pca_test.components_) # case: n_components >= .8 * min(X.shape) => 'full' pca = PCA(n_components=50) pca.fit(X) pca_test = PCA(n_components=50, svd_solver='full') pca_test.fit(X) assert_array_almost_equal(pca.components_, pca_test.components_) # n_components >= 1 and n_components < .8 * min(X.shape) => 'randomized' pca = PCA(n_components=10, random_state=0) pca.fit(X) pca_test = PCA(n_components=10, svd_solver='randomized', random_state=0) pca_test.fit(X) assert_array_almost_equal(pca.components_, pca_test.components_) def test_deprecation_randomized_pca(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) depr_message = ("Class RandomizedPCA is deprecated; RandomizedPCA was " "deprecated in 0.18 and will be " "removed in 0.20. Use PCA(svd_solver='randomized') " "instead. The new implementation DOES NOT store " "whiten ``components_``. Apply transform to get them.") def fit_deprecated(X): global Y rpca = RandomizedPCA(random_state=0) Y = rpca.fit_transform(X) assert_warns_message(DeprecationWarning, depr_message, fit_deprecated, X) Y_pca = PCA(svd_solver='randomized', random_state=0).fit_transform(X) assert_array_almost_equal(Y, Y_pca) def test_pca_sparse_input(): X = np.random.RandomState(0).rand(5, 4) X = sp.sparse.csr_matrix(X) assert(sp.sparse.issparse(X)) for svd_solver in solver_list: pca = PCA(n_components=3, svd_solver=svd_solver) assert_raises(TypeError, pca.fit, X) def test_pca_bad_solver(): X = np.random.RandomState(0).rand(5, 4) pca = PCA(n_components=3, svd_solver='bad_argument') assert_raises(ValueError, pca.fit, X)
bsd-3-clause
daniaki/pyPPI
pyppi/models/binary_relevance.py
1
8033
""" A classifier implementing the Binary Relevance approach to multi-label learning. """ __all__ = [ "MixedBinaryRelevanceClassifier" ] import logging import numpy as np from joblib import Parallel, delayed from sklearn.base import clone, BaseEstimator from sklearn.metrics import ( hamming_loss, label_ranking_loss, f1_score, precision_score, recall_score ) from pyppi.model_selection.scoring import fdr_score, specificity logger = logging.getLogger("pyppi") def _fit_label(estimator, X, y, label_idx, n_labels, verbose, **fit_params): if verbose: logger.info("Fitting label {}/{}.".format(label_idx+1, n_labels)) return estimator.fit(X, y, **fit_params) def _predict_proba_label(estimator, X): return estimator.predict_proba(X) def _predict_label(estimator, X): return estimator.predict(X) class MixedBinaryRelevanceClassifier(object): """Mimics the `OneVsRest` classifier from Sklearn allowing a different type of classifier for each label as opposed to one classifier for all labels. Parameters: ---------- estimators : `list` List of `Scikit-Learn` estimators supporting `fit`, `predict` and `predict_proba`. n_jobs : int, optional, default: 1 Number of processes to use when fitting each label. verbose : bool, optional, default: False Logs messages regarding fitting progress. """ def __init__(self, estimators, n_jobs=1, verbose=False): if not isinstance(estimators, list): raise TypeError("estimators must be a list.") self.estimators = estimators self.n_jobs = n_jobs self.verbose = verbose def __repr__(self): return ( "MixedBinaryRelevanceClassifier(estimators={}, n_jobs={})".format( self.estimators, self.n_jobs ) ) def _check_y_shape(self, y): try: if y.shape[1] <= 1: raise ValueError( "y must be in multi-label indicator matrix format. " "For binary or multi-class classification use scikit-learn." ) if y.shape[1] != len(self.estimators): raise ValueError( "Shape of y {} along dim 1 does not match {}.".format( y.shape, len(self.estimators) ) ) except IndexError: raise ValueError( "y must be in multi-label indicator matrix format. " "For binary or multi-class classification use scikit-learn." ) def clone(self, deep=True): params = self.get_params(deep) return self.__class__(**params) def _check_fitted(self): if not hasattr(self, 'estimators_'): raise ValueError("This estimator has not yet been fit.") if not hasattr(self, 'n_labels_'): raise ValueError("This estimator has not yet been fit.") def get_params(self, deep=True): return { "estimators": [clone(e) for e in self.estimators], "n_jobs": self.n_jobs, "verbose": self.verbose } def set_params(self, **params): for key, value in params.items(): if key not in self.get_params().keys(): raise ValueError( "'{}' is not a valid param for {}.".format( key, self.__class__.__name__ ) ) elif key == 'estimators': if not isinstance(value, list): raise TypeError("'estimators' must be a list.") self.estimators = [clone(e) for e in value] if hasattr(self, 'n_labels_'): delattr(self, 'n_labels_') if hasattr(self, 'estimators_'): delattr(self, 'estimators_') else: setattr(self, key, value) return self def fit(self, X, y, **fit_params): """ Fit the model according to the given training data. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples, n_labels) Target vector relative to X. Returns ------- self : object Returns self. """ self._check_y_shape(y) n_labels = len(self.estimators) self.estimators_ = Parallel(n_jobs=self.n_jobs)( delayed(_fit_label)( estimator=clone(estimator), X=X, y=y[:, i], label_idx=i, n_labels=n_labels, verbose=self.verbose, **fit_params ) for i, estimator in enumerate(self.estimators) ) self.n_labels_ = len(self.estimators_) return self def predict(self, X): """ Predict class labels for samples in X. Parameters ---------- X : {array-like, sparse matrix}, shape = (n_samples, n_features) Samples. Returns ------- C : array, shape = (n_samples, n_labels) Predicted class labels per sample. """ self._check_fitted() predictions = np.vstack(Parallel(n_jobs=self.n_jobs)( delayed(_predict_label)( estimator=estimator, X=X ) for estimator in self.estimators_ )).T return predictions def predict_proba(self, X): """ Probability estimates for each label. Parameters ---------- X : array-like, shape = (n_samples, n_features) Returns ------- T : array-like, shape = (n_samples, n_labels) Returns the probability of the sample for each label in the model, where labels are ordered as the indices of 'y' used during fit. """ self._check_fitted() probas = Parallel(n_jobs=self.n_jobs)( delayed(_predict_proba_label)( estimator=estimator, X=X ) for estimator in self.estimators_ ) probas = np.vstack([x[:, 1] for x in probas]).T return probas def score(self, X, y, sample_weight=None, use_proba=False, scorer=hamming_loss, **score_params): """ Returns the score as determined by `scoring` on the given test data and labels. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test samples. y : array-like, shape = (n_samples, n_labels) True labels for X. sample_weight : array-like, shape = [n_samples], optional Sample weights. use_proba : boolean, default: False If True, apply scoring function to probability estimates. scorer : function, optional The scoring method to apply to predictions. score_params : dict, optional Keyword arguments for scorer. Returns ------- `float` or array-like (n_labels, ) if scoring uses binary. Mean score of self.predict(X) wrt. y. """ self._check_y_shape(y) self._check_fitted() if use_proba: y_pred = self.predict_proba(X) else: y_pred = self.predict(X) average = score_params.get("average", None) if average == "binary": return np.asarray([ scorer( y[:, i], y_pred[:, i], sample_weight=sample_weight, **score_params ) for i in range(self.n_labels_) ]) else: return scorer( y, y_pred, sample_weight=sample_weight, **score_params )
mit
hitszxp/scikit-learn
sklearn/tree/export.py
30
4529
""" This module defines export functions for decision trees. """ # Authors: Gilles Louppe <[email protected]> # Peter Prettenhofer <[email protected]> # Brian Holt <[email protected]> # Noel Dawe <[email protected]> # Satrajit Gosh <[email protected]> # Licence: BSD 3 clause from ..externals import six from . import _tree def export_graphviz(decision_tree, out_file="tree.dot", feature_names=None, max_depth=None): """Export a decision tree in DOT format. This function generates a GraphViz representation of the decision tree, which is then written into `out_file`. Once exported, graphical renderings can be generated using, for example:: $ dot -Tps tree.dot -o tree.ps (PostScript format) $ dot -Tpng tree.dot -o tree.png (PNG format) The sample counts that are shown are weighted with any sample_weights that might be present. Parameters ---------- decision_tree : decision tree classifier The decision tree to be exported to GraphViz. out_file : file object or string, optional (default="tree.dot") Handle or name of the output file. feature_names : list of strings, optional (default=None) Names of each of the features. max_depth : int, optional (default=None) The maximum depth of the representation. If None, the tree is fully generated. Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn import tree >>> clf = tree.DecisionTreeClassifier() >>> iris = load_iris() >>> clf = clf.fit(iris.data, iris.target) >>> tree.export_graphviz(clf, ... out_file='tree.dot') # doctest: +SKIP """ def node_to_str(tree, node_id, criterion): if not isinstance(criterion, six.string_types): criterion = "impurity" value = tree.value[node_id] if tree.n_outputs == 1: value = value[0, :] if tree.children_left[node_id] == _tree.TREE_LEAF: return "%s = %.4f\\nsamples = %s\\nvalue = %s" \ % (criterion, tree.impurity[node_id], tree.n_node_samples[node_id], value) else: if feature_names is not None: feature = feature_names[tree.feature[node_id]] else: feature = "X[%s]" % tree.feature[node_id] return "%s <= %.4f\\n%s = %s\\nsamples = %s" \ % (feature, tree.threshold[node_id], criterion, tree.impurity[node_id], tree.n_node_samples[node_id]) def recurse(tree, node_id, criterion, parent=None, depth=0): if node_id == _tree.TREE_LEAF: raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF) left_child = tree.children_left[node_id] right_child = tree.children_right[node_id] # Add node with description if max_depth is None or depth <= max_depth: out_file.write('%d [label="%s", shape="box"] ;\n' % (node_id, node_to_str(tree, node_id, criterion))) if parent is not None: # Add edge to parent out_file.write('%d -> %d ;\n' % (parent, node_id)) if left_child != _tree.TREE_LEAF: recurse(tree, left_child, criterion=criterion, parent=node_id, depth=depth + 1) recurse(tree, right_child, criterion=criterion, parent=node_id, depth=depth + 1) else: out_file.write('%d [label="(...)", shape="box"] ;\n' % node_id) if parent is not None: # Add edge to parent out_file.write('%d -> %d ;\n' % (parent, node_id)) own_file = False try: if isinstance(out_file, six.string_types): if six.PY3: out_file = open(out_file, "w", encoding="utf-8") else: out_file = open(out_file, "wb") own_file = True out_file.write("digraph Tree {\n") if isinstance(decision_tree, _tree.Tree): recurse(decision_tree, 0, criterion="impurity") else: recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion) out_file.write("}") finally: if own_file: out_file.close()
bsd-3-clause
flumotion-mirror/flumotion
tools/theora-bench.py
3
6965
#!/usr/bin/env python # -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Public License version 2.1 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.LGPL" in the source distribution for more information. # # Headers in this file shall remain intact. import gobject gobject.threads_init() import pygst pygst.require('0.10') import gst import time import sys class SlidingWindow: def __init__(self, size): self._window = [0.0] * size self._windowPtr = 0 self._first = True # Maintain the current average, and the max of our current average self.max = 0.0 self.average = 0.0 self.windowSize = size def addValue(self, val): self._window[self._windowPtr] = val self._windowPtr = (self._windowPtr + 1) % self.windowSize if self._first: if self._windowPtr == 0: self._first = False return self.average = sum(self._window) / self.windowSize if self.average > self.max: self.max = self.average class TheoraBench: def __init__(self, filename, outTemplate, width=None, height=None, framerate=None): self.framerate = None self.width = None self.height = None self.outfileTemplate = outTemplate # TODO: What's a reasonable windowSize to use? windowSize = 20 self.window = SlidingWindow(windowSize) self.samples = 0 self.data = ([], [], []) self.pipeline = pipeline = gst.Pipeline() self.bus = pipeline.get_bus() filesrc = gst.element_factory_make("filesrc") decodebin = gst.element_factory_make("decodebin") self.ffmpegcolorspace = gst.element_factory_make("ffmpegcolorspace") videorate = gst.element_factory_make("videorate") videoscale = gst.element_factory_make("videoscale") self.theoraenc = gst.element_factory_make("theoraenc") fakesink = gst.element_factory_make("fakesink") filesrc.set_property("location", filename) pipeline.add(filesrc, decodebin, self.ffmpegcolorspace, videorate, videoscale, self.theoraenc, fakesink) filesrc.link(decodebin) gst.element_link_many(self.ffmpegcolorspace, videorate, videoscale) structure = gst.Structure("video/x-raw-yuv") if height: structure['height'] = height if width: structure['width'] = width if framerate: structure['framerate'] = framerate caps = gst.Caps(structure) videoscale.link(self.theoraenc, caps) self.theoraenc.link(fakesink) decodebin.connect("new-decoded-pad", self._pad_added_cb) def _eos_cb(self, bus, msg): print "Done" fn = self.outfileTemplate % (self.width, self.height, float(self.framerate)) print "Writing file: ", fn self.writeGraph(fn, self.data, "Frame number", "CPU Percentage required", ("Frame)", "Sliding Average (%d frames)" % self.window.windowSize, "Sliding Average Peak")) self.mainloop.quit() def writeGraph(self, filename, data, xlabel, ylabel, dataNames): # data is ([time], [average], [average_peak]) as percentages (floats) #out = open(filename, "w") #out.close() import matplotlib matplotlib.use('Agg') from matplotlib import pylab length = len(data[0]) pylab.plot(xrange(length), data[1]) pylab.plot(xrange(length), data[2]) pylab.axis([0, length-1, 0, 110]) pylab.savefig(filename, dpi=72) pass def _error_cb(self, bus, msg): error = msg.parse_error() print "Error: ", error[1] self.mainloop.quit() def run(self): self.mainloop = gobject.MainLoop() self.bus.add_signal_watch() self.bus.connect("message::eos", self._eos_cb) self.bus.connect("message::error", self._eos_cb) self.pipeline.set_state(gst.STATE_PLAYING) self.mainloop.run() def _pad_added_cb(self, decodebin, pad, last): structure = pad.get_caps()[0] name = structure.get_name() if name.startswith('video/x-raw-'): sinkpad = self.ffmpegcolorspace.get_pad("sink") pad.link(sinkpad) #self.framerate = structure['framerate'] sinkpad = self.theoraenc.get_pad("sink") srcpad = self.theoraenc.get_pad("src") sinkpad.add_buffer_probe(self._buffer_probe_sink_cb) srcpad.add_buffer_probe(self._buffer_probe_src_cb) def _buffer_probe_sink_cb(self, pad, buf): if not self.framerate: self.framerate = buf.get_caps()[0]['framerate'] self.width = buf.get_caps()[0]['width'] self.height = buf.get_caps()[0]['height'] self._last_ts = time.time() return True def _buffer_probe_src_cb(self, pad, buf): processing_time = time.time() - self._last_ts self.window.addValue(processing_time) self.samples += 1 if self.samples <= self.window.windowSize: return True # Ignore these, our sliding window isn't very smart self.data[0].append(processing_time * float(self.framerate) * 100.0) self.data[1].append(self.window.average * float( self.framerate) * 100.0) self.data[2].append(self.window.max * float(self.framerate) * 100.0) print "This frame: %.2f: %.2f%%. Average: %.2f%%. Peak: %.2f%%" % ( processing_time, processing_time * float(self.framerate) * 100.0, self.window.average * float(self.framerate) * 100.0, self.window.max * float(self.framerate) * 100.0) return True if len(sys.argv) == 2: framerates = [(30, 1), (25, 1), (25, 2), (None, None)] sizes = [(800, 600), (400, 300), (None, None)] # Other useful sizes here for framerate in framerates: for size in sizes: if framerate[1]: fr = gst.Fraction(framerate[0], framerate[1]) else: fr = None infile = sys.argv[1] outfileTemplate = sys.argv[1] + ".%dx%d@%.2f.png" bench = TheoraBench(sys.argv[1], outfileTemplate, size[0], size[1], fr) bench.run() else: print "Usage: %s filename.ogg" % sys.argv[0]
lgpl-2.1
yavalvas/yav_com
build/matplotlib/lib/mpl_examples/user_interfaces/embedding_in_wx3.py
9
4849
#!/usr/bin/env python """ Copyright (C) 2003-2004 Andrew Straw, Jeremy O'Donoghue and others License: This work is licensed under the PSF. A copy should be included with this source code, and is also available at http://www.python.org/psf/license.html This is yet another example of using matplotlib with wx. Hopefully this is pretty full-featured: - both matplotlib toolbar and WX buttons manipulate plot - full wxApp framework, including widget interaction - XRC (XML wxWidgets resource) file to create GUI (made with XRCed) This was derived from embedding_in_wx and dynamic_image_wxagg. Thanks to matplotlib and wx teams for creating such great software! """ from __future__ import print_function # Used to guarantee to use at least Wx2.8 import wxversion wxversion.ensureMinimal('2.8') import sys, time, os, gc import matplotlib matplotlib.use('WXAgg') import matplotlib.cm as cm import matplotlib.cbook as cbook from matplotlib.backends.backend_wxagg import Toolbar, FigureCanvasWxAgg from matplotlib.figure import Figure import numpy as np import wx import wx.xrc as xrc ERR_TOL = 1e-5 # floating point slop for peak-detection matplotlib.rc('image', origin='lower') class PlotPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.Fit() def init_plot_data(self): a = self.fig.add_subplot(111) x = np.arange(120.0)*2*np.pi/60.0 y = np.arange(100.0)*2*np.pi/50.0 self.x, self.y = np.meshgrid(x, y) z = np.sin(self.x) + np.cos(self.y) self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') zmax = np.amax(z) - ERR_TOL ymax_i, xmax_i = np.nonzero(z >= zmax) if self.im.origin == 'upper': ymax_i = z.shape[0]-ymax_i self.lines = a.plot(xmax_i,ymax_i,'ko') self.toolbar.update() # Not sure why this is needed - ADS def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def OnWhiz(self,evt): self.x += np.pi/15 self.y += np.pi/20 z = np.sin(self.x) + np.cos(self.y) self.im.set_array(z) zmax = np.amax(z) - ERR_TOL ymax_i, xmax_i = np.nonzero(z >= zmax) if self.im.origin == 'upper': ymax_i = z.shape[0]-ymax_i self.lines[0].set_data(xmax_i,ymax_i) self.canvas.draw() def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass class MyApp(wx.App): def OnInit(self): xrcfile = cbook.get_sample_data('embedding_in_wx3.xrc', asfileobj=False) print('loading', xrcfile) self.res = xrc.XmlResource(xrcfile) # main frame and panel --------- self.frame = self.res.LoadFrame(None,"MainFrame") self.panel = xrc.XRCCTRL(self.frame,"MainPanel") # matplotlib panel ------------- # container for matplotlib panel (I like to make a container # panel for our panel so I know where it'll go when in XRCed.) plot_container = xrc.XRCCTRL(self.frame,"plot_container_panel") sizer = wx.BoxSizer(wx.VERTICAL) # matplotlib panel itself self.plotpanel = PlotPanel(plot_container) self.plotpanel.init_plot_data() # wx boilerplate sizer.Add(self.plotpanel, 1, wx.EXPAND) plot_container.SetSizer(sizer) # whiz button ------------------ whiz_button = xrc.XRCCTRL(self.frame,"whiz_button") wx.EVT_BUTTON(whiz_button, whiz_button.GetId(), self.plotpanel.OnWhiz) # bang button ------------------ bang_button = xrc.XRCCTRL(self.frame,"bang_button") wx.EVT_BUTTON(bang_button, bang_button.GetId(), self.OnBang) # final setup ------------------ sizer = self.panel.GetSizer() self.frame.Show(1) self.SetTopWindow(self.frame) return True def OnBang(self,event): bang_count = xrc.XRCCTRL(self.frame,"bang_count") bangs = bang_count.GetValue() bangs = int(bangs)+1 bang_count.SetValue(str(bangs)) if __name__ == '__main__': app = MyApp(0) app.MainLoop()
mit
LACMTA/folium
folium/folium.py
1
49682
# -*- coding: utf-8 -*- """ Folium ------- Make beautiful, interactive maps with Python and Leaflet.js """ from __future__ import absolute_import from __future__ import print_function from __future__ import division import codecs import functools import json from uuid import uuid4 from jinja2 import Environment, PackageLoader from pkg_resources import resource_string from folium import utilities from folium.six import text_type, binary_type, iteritems import sys import base64 ENV = Environment(loader=PackageLoader('folium', 'templates')) def initialize_notebook(): """Initialize the IPython notebook display elements.""" try: from IPython.core.display import display, HTML except ImportError: print("IPython Notebook could not be loaded.") lib_css = ENV.get_template('ipynb_init_css.html') lib_js = ENV.get_template('ipynb_init_js.html') leaflet_dvf = ENV.get_template('leaflet-dvf.markers.min.js') display(HTML(lib_css.render())) display(HTML(lib_js.render({'leaflet_dvf': leaflet_dvf.render()}))) def iter_obj(type): """Decorator to keep count of different map object types in self.mk_cnt.""" def decorator(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): self.mark_cnt[type] = self.mark_cnt.get(type, 0) + 1 func_result = func(self, *args, **kwargs) return func_result return wrapper return decorator class Map(object): """Create a Map with Folium.""" def __init__(self, location=None, width='100%', height='100%', tiles='OpenStreetMap', API_key=None, max_zoom=18, min_zoom=1, zoom_start=10, attr=None, min_lat=-90, max_lat=90, min_lon=-180, max_lon=180): """Create a Map with Folium and Leaflet.js Generate a base map of given width and height with either default tilesets or a custom tileset URL. The following tilesets are built-in to Folium. Pass any of the following to the "tiles" keyword: - "OpenStreetMap" - "MapQuest Open" - "MapQuest Open Aerial" - "Mapbox Bright" (Limited levels of zoom for free tiles) - "Mapbox Control Room" (Limited levels of zoom for free tiles) - "Stamen" (Terrain, Toner, and Watercolor) - "Cloudmade" (Must pass API key) - "Mapbox" (Must pass API key) - "CartoDB" (positron and dark_matter) You can pass a custom tileset to Folium by passing a Leaflet-style URL to the tiles parameter: http://{s}.yourtiles.com/{z}/{x}/{y}.png Parameters ---------- location: tuple or list, default None Latitude and Longitude of Map (Northing, Easting). width: pixel int or percentage string (default: '100%') Width of the map. height: pixel int or percentage string (default: '100%') Height of the map. tiles: str, default 'OpenStreetMap' Map tileset to use. Can use defaults or pass a custom URL. API_key: str, default None API key for Cloudmade or Mapbox tiles. max_zoom: int, default 18 Maximum zoom depth for the map. zoom_start: int, default 10 Initial zoom level for the map. attr: string, default None Map tile attribution; only required if passing custom tile URL. Returns ------- Folium Map Object Examples -------- >>>map = folium.Map(location=[45.523, -122.675], width=750, height=500) >>>map = folium.Map(location=[45.523, -122.675], tiles='Mapbox Control Room') >>>map = folium.Map(location=(45.523, -122.675), max_zoom=20, tiles='Cloudmade', API_key='YourKey') >>>map = folium.Map(location=[45.523, -122.675], zoom_start=2, tiles=('http://{s}.tiles.mapbox.com/v3/' 'mapbox.control-room/{z}/{x}/{y}.png'), attr='Mapbox attribution') """ # Inits. self.map_path = None self.render_iframe = False self.map_type = 'base' self.map_id = '_'.join(['folium', uuid4().hex]) # Mark counter, JSON, Plugins. self.mark_cnt = {} self.json_data = {} self.plugins = {} # No location means we will use automatic bounds and ignore zoom self.location = location # If location is not passed, we center the map at 0,0 if not location: location = [0, 0] zoom_start = min_zoom # Map Size Parameters. try: if isinstance(width, int): width_type = 'px' assert width > 0 else: width_type = '%' width = int(width.strip('%')) assert 0 <= width <= 100 except: msg = "Cannot parse width {!r} as {!r}".format raise ValueError(msg(width, width_type)) self.width = width try: if isinstance(height, int): height_type = 'px' assert height > 0 else: height_type = '%' height = int(height.strip('%')) assert 0 <= height <= 100 except: msg = "Cannot parse height {!r} as {!r}".format raise ValueError(msg(height, height_type)) self.height = height self.map_size = {'width': width, 'height': height} self._size = ('style="width: {0}{1}; height: {2}{3}"' .format(width, width_type, height, height_type)) # Templates. self.env = ENV self.template_vars = dict(lat=location[0], lon=location[1], size=self._size, max_zoom=max_zoom, zoom_level=zoom_start, map_id=self.map_id, min_zoom=min_zoom, min_lat=min_lat, max_lat=max_lat, min_lon=min_lon, max_lon=max_lon) # Tiles. self.tiles = ''.join(tiles.lower().strip().split()) if self.tiles in ('cloudmade', 'mapbox') and not API_key: raise ValueError('You must pass an API key if using Cloudmade' ' or non-default Mapbox tiles.') self.default_tiles = ['openstreetmap', 'mapboxcontrolroom', 'mapquestopen', 'mapquestopenaerial', 'mapboxbright', 'mapbox', 'cloudmade', 'stamenterrain', 'stamentoner', 'stamenwatercolor', 'cartodbpositron', 'cartodbdark_matter'] self.tile_types = {} for tile in self.default_tiles: tile_path = 'tiles/%s' % tile self.tile_types[tile] = { 'templ': self.env.get_template('%s/%s' % (tile_path, 'tiles.txt')), 'attr': self.env.get_template('%s/%s' % (tile_path, 'attr.txt')), } if self.tiles in self.tile_types: self.template_vars['Tiles'] = (self.tile_types[self.tiles]['templ'] .render(API_key=API_key)) self.template_vars['attr'] = (self.tile_types[self.tiles]['attr'] .render()) else: self.template_vars['Tiles'] = tiles if not attr: raise ValueError('Custom tiles must' ' also be passed an attribution') if isinstance(attr, binary_type): attr = text_type(attr, 'utf8') self.template_vars['attr'] = attr self.tile_types.update({'Custom': {'template': tiles, 'attr': attr}}) self.added_layers = [] self.template_vars.setdefault('wms_layers', []) self.template_vars.setdefault('tile_layers', []) self.template_vars.setdefault('image_layers', []) @iter_obj('simple') def add_tile_layer(self, tile_name=None, tile_url=None, active=False): """Adds a simple tile layer. Parameters ---------- tile_name: string name of the tile layer tile_url: string url location of the tile layer active: boolean should the layer be active when added """ if tile_name not in self.added_layers: tile_name = tile_name.replace(" ", "_") tile_temp = self.env.get_template('tile_layer.js') tile = tile_temp.render({'tile_name': tile_name, 'tile_url': tile_url}) self.template_vars.setdefault('tile_layers', []).append((tile)) self.added_layers.append({tile_name: tile_url}) @iter_obj('simple') def add_wms_layer(self, wms_name=None, wms_url=None, wms_format=None, wms_layers=None, wms_transparent=True): """Adds a simple tile layer. Parameters ---------- wms_name: string name of wms layer wms_url : string url of wms layer """ if wms_name not in self.added_layers: wms_name = wms_name.replace(" ", "_") wms_temp = self.env.get_template('wms_layer.js') wms = wms_temp.render({ 'wms_name': wms_name, 'wms_url': wms_url, 'wms_format': wms_format, 'wms_layer_names': wms_layers, 'wms_transparent': str(wms_transparent).lower()}) self.template_vars.setdefault('wms_layers', []).append((wms)) self.added_layers.append({wms_name: wms_url}) @iter_obj('simple') def add_layers_to_map(self): """ Required function to actually add the layers to the HTML packet. """ layers_temp = self.env.get_template('add_layers.js') data_string = '' for i, layer in enumerate(self.added_layers): name = list(layer.keys())[0] if i < len(self.added_layers)-1: term_string = ",\n" else: term_string += "\n" data_string += '\"{}\": {}'.format(name, name, term_string) data_layers = layers_temp.render({'layers': data_string}) self.template_vars.setdefault('data_layers', []).append((data_layers)) @iter_obj('simple') def simple_marker(self, location=None, popup=None, marker_color='blue', marker_icon='info-sign', clustered_marker=False, icon_angle=0, popup_width=300): """Create a simple stock Leaflet marker on the map, with optional popup text or Vincent visualization. Parameters ---------- location: tuple or list, default None Latitude and Longitude of Marker (Northing, Easting) popup: string or tuple, default 'Pop Text' Input text or visualization for object. Can pass either text, or a tuple of the form (Vincent object, 'vis_path.json') It is possible to adjust the width of text/HTML popups using the optional keywords `popup_width` (default is 300px). marker_color color of marker you want marker_icon icon from (http://getbootstrap.com/components/) you want on the marker clustered_marker boolean of whether or not you want the marker clustered with other markers Returns ------- Marker names and HTML in obj.template_vars Example ------- >>>map.simple_marker(location=[45.5, -122.3], popup='Portland, OR') >>>map.simple_marker(location=[45.5, -122.3], popup=(vis, 'vis.json')) """ count = self.mark_cnt['simple'] mark_temp = self.env.get_template('simple_marker.js') marker_num = 'marker_{0}'.format(count) add_line = "{'icon':"+marker_num+"_icon}" icon_temp = self.env.get_template('simple_icon.js') icon = icon_temp.render({'icon': marker_icon, 'icon_name': marker_num+"_icon", 'markerColor': marker_color, 'icon_angle': icon_angle}) # Get marker and popup. marker = mark_temp.render({'marker': 'marker_' + str(count), 'lat': location[0], 'lon': location[1], 'icon': add_line }) popup_out = self._popup_render(popup=popup, mk_name='marker_', count=count, width=popup_width) if clustered_marker: add_mark = 'clusteredmarkers.addLayer(marker_{0})'.format(count) name = 'cluster_markers' else: add_mark = 'map.addLayer(marker_{0})'.format(count) name = 'custom_markers' append = (icon, marker, popup_out, add_mark) self.template_vars.setdefault(name, []).append(append) @iter_obj('div_mark') def div_markers(self, locations=None, popups=None, marker_size=10, popup_width=300): """Create a simple div marker on the map, with optional popup text or Vincent visualization. Useful for marking points along a line. Parameters ---------- locations: list of locations, where each location is an array Latitude and Longitude of Marker (Northing, Easting) popup: list of popups, each popup should be a string or tuple, default 'Pop Text' Input text or visualization for object. Can pass either text, or a tuple of the form (Vincent object, 'vis_path.json') It is possible to adjust the width of text/HTML popups using the optional keywords `popup_width`. (Leaflet default is 300px.) marker_size default is 5 Returns ------- Marker names and HTML in obj.template_vars Example ------- >>>map.div_markers(locations=[[37.421114, -122.128314], [37.391637, -122.085416], [37.388832, -122.087709]], popups=['1437494575531', '1437492135937', '1437493590434']) """ call_cnt = self.mark_cnt['div_mark'] if locations is None or popups is None: raise RuntimeError("Both locations and popups are mandatory") for (point_cnt, (location, popup)) in enumerate(zip(locations, popups)): marker_num = 'div_marker_{0}_{1}'.format(call_cnt, point_cnt) icon_temp = self.env.get_template('static_div_icon.js') icon_name = marker_num+"_icon" icon = icon_temp.render({'icon_name': icon_name, 'size': marker_size}) mark_temp = self.env.get_template('simple_marker.js') # Get marker and popup. marker = mark_temp.render({'marker': marker_num, 'lat': location[0], 'lon': location[1], 'icon': "{'icon':"+icon_name+"}" }) popup_out = self._popup_render(popup=popup, mk_name='div_marker_{0}_'.format(call_cnt), count=point_cnt, width=popup_width) add_mark = 'map.addLayer(div_marker_{0}_{1})'.format(call_cnt, point_cnt) append = (icon, marker, popup_out, add_mark) self.template_vars.setdefault('div_markers', []).append(append) @iter_obj('line') def line(self, locations, line_color=None, line_opacity=None, line_weight=None, popup=None, popup_width=300): """Add a line to the map with optional styles. Parameters ---------- locations: list of points (latitude, longitude) Latitude and Longitude of line (Northing, Easting) line_color: string, default Leaflet's default ('#03f') line_opacity: float, default Leaflet's default (0.5) line_weight: float, default Leaflet's default (5) popup: string or tuple, default 'Pop Text' Input text or visualization for object. Can pass either text, or a tuple of the form (Vincent object, 'vis_path.json') It is possible to adjust the width of text/HTML popups using the optional keywords `popup_width` (default is 300px). Note: If the optional styles are omitted, they will not be included in the HTML output and will obtain the Leaflet defaults listed above. Example ------- >>>map.line(locations=[(45.5, -122.3), (42.3, -71.0)]) >>>map.line(locations=[(45.5, -122.3), (42.3, -71.0)], line_color='red', line_opacity=1.0) """ count = self.mark_cnt['line'] line_temp = self.env.get_template('polyline.js') polyline_opts = {'color': line_color, 'weight': line_weight, 'opacity': line_opacity} varname = 'line_{}'.format(count) line_rendered = line_temp.render({'line': varname, 'locations': locations, 'options': polyline_opts}) popup_out = self._popup_render(popup=popup, mk_name='line_', count=count, width=popup_width) add_line = 'map.addLayer({});'.format(varname) append = (line_rendered, popup_out, add_line) self.template_vars.setdefault('lines', []).append((append)) @iter_obj('multiline') def multiline(self, locations, line_color=None, line_opacity=None, line_weight=None): """Add a multiPolyline to the map with optional styles. A multiPolyline is single layer that consists of several polylines that share styling/popup. Parameters ---------- locations: list of lists of points (latitude, longitude) Latitude and Longitude of line (Northing, Easting) line_color: string, default Leaflet's default ('#03f') line_opacity: float, default Leaflet's default (0.5) line_weight: float, default Leaflet's default (5) Note: If the optional styles are omitted, they will not be included in the HTML output and will obtain the Leaflet defaults listed above. Example ------- # FIXME: Add another example. >>> m.multiline(locations=[[(45.5236, -122.675), (45.5236, -122.675)], [(45.5237, -122.675), (45.5237, -122.675)], [(45.5238, -122.675), (45.5238, -122.675)]]) >>> m.multiline(locations=[[(45.5236, -122.675), (45.5236, -122.675)], [(45.5237, -122.675), (45.5237, -122.675)], [(45.5238, -122.675), (45.5238, -122.675)]], line_color='red', line_weight=2, line_opacity=1.0) """ count = self.mark_cnt['multiline'] multiline_temp = self.env.get_template('multi_polyline.js') multiline_opts = {'color': line_color, 'weight': line_weight, 'opacity': line_opacity} varname = 'multiline_{}'.format(count) multiline_rendered = multiline_temp.render({'multiline': varname, 'locations': locations, 'options': multiline_opts}) add_multiline = 'map.addLayer({});'.format(varname) append = (multiline_rendered, add_multiline) self.template_vars.setdefault('multilines', []).append(append) @iter_obj('circle') def circle_marker(self, location=None, radius=500, popup=None, line_color='black', fill_color='black', fill_opacity=0.6, popup_width=300): """Create a simple circle marker on the map, with optional popup text or Vincent visualization. Parameters ---------- location: tuple or list, default None Latitude and Longitude of Marker (Northing, Easting) radius: int, default 500 Circle radius, in pixels popup: string or tuple, default 'Pop Text' Input text or visualization for object. Can pass either text, or a tuple of the form (Vincent object, 'vis_path.json') It is possible to adjust the width of text/HTML popups using the optional keywords `popup_width` (default is 300px). line_color: string, default black Line color. Can pass hex value here as well. fill_color: string, default black Fill color. Can pass hex value here as well. fill_opacity: float, default 0.6 Circle fill opacity Returns ------- Circle names and HTML in obj.template_vars Example ------- >>>map.circle_marker(location=[45.5, -122.3], radius=1000, popup='Portland, OR') >>>map.circle_marker(location=[45.5, -122.3], radius=1000, popup=(bar_chart, 'bar_data.json')) """ count = self.mark_cnt['circle'] circle_temp = self.env.get_template('circle_marker.js') circle = circle_temp.render({'circle': 'circle_' + str(count), 'radius': radius, 'lat': location[0], 'lon': location[1], 'line_color': line_color, 'fill_color': fill_color, 'fill_opacity': fill_opacity}) popup_out = self._popup_render(popup=popup, mk_name='circle_', count=count, width=popup_width) add_mark = 'map.addLayer(circle_{0})'.format(count) self.template_vars.setdefault('markers', []).append((circle, popup_out, add_mark)) @iter_obj('polygon') def polygon_marker(self, location=None, line_color='black', line_opacity=1, line_weight=2, fill_color='blue', fill_opacity=1, num_sides=4, rotation=0, radius=15, popup=None, popup_width=300): """Custom markers using the Leaflet Data Vis Framework. Parameters ---------- location: tuple or list, default None Latitude and Longitude of Marker (Northing, Easting) line_color: string, default 'black' Marker line color line_opacity: float, default 1 Line opacity, scale 0-1 line_weight: int, default 2 Stroke weight in pixels fill_color: string, default 'blue' Marker fill color fill_opacity: float, default 1 Marker fill opacity num_sides: int, default 4 Number of polygon sides rotation: int, default 0 Rotation angle in degrees radius: int, default 15 Marker radius, in pixels popup: string or tuple, default 'Pop Text' Input text or visualization for object. Can pass either text, or a tuple of the form (Vincent object, 'vis_path.json') It is possible to adjust the width of text/HTML popups using the optional keywords `popup_width` (default is 300px). Returns ------- Polygon marker names and HTML in obj.template_vars """ count = self.mark_cnt['polygon'] poly_temp = self.env.get_template('poly_marker.js') polygon = poly_temp.render({'marker': 'polygon_' + str(count), 'lat': location[0], 'lon': location[1], 'line_color': line_color, 'line_opacity': line_opacity, 'line_weight': line_weight, 'fill_color': fill_color, 'fill_opacity': fill_opacity, 'num_sides': num_sides, 'rotation': rotation, 'radius': radius}) popup_out = self._popup_render(popup=popup, mk_name='polygon_', count=count, width=popup_width) add_mark = 'map.addLayer(polygon_{0})'.format(count) self.template_vars.setdefault('markers', []).append((polygon, popup_out, add_mark)) # Update JS/CSS and other Plugin files. js_temp = self.env.get_template('dvf_js_ref.txt').render() self.template_vars.update({'dvf_js': js_temp}) polygon_js = resource_string('folium', 'plugins/leaflet-dvf.markers.min.js') self.plugins.update({'leaflet-dvf.markers.min.js': polygon_js}) def lat_lng_popover(self): """Enable popovers to display Lat and Lon on each click.""" latlng_temp = self.env.get_template('lat_lng_popover.js') self.template_vars.update({'lat_lng_pop': latlng_temp.render()}) def click_for_marker(self, popup=None): """Enable the addition of markers via clicking on the map. The marker popup defaults to Lat/Lon, but custom text can be passed via the popup parameter. Double click markers to remove them. Parameters ---------- popup: Custom popup text Example ------- >>>map.click_for_marker(popup='Your Custom Text') """ latlng = '"Latitude: " + lat + "<br>Longitude: " + lng ' click_temp = self.env.get_template('click_for_marker.js') if popup: popup_txt = ''.join(['"', popup, '"']) else: popup_txt = latlng click_str = click_temp.render({'popup': popup_txt}) self.template_vars.update({'click_pop': click_str}) def fit_bounds(self, bounds, padding_top_left=None, padding_bottom_right=None, padding=None, max_zoom=None): """Fit the map to contain a bounding box with the maximum zoom level possible. Parameters ---------- bounds: list of (latitude, longitude) points Bounding box specified as two points [southwest, northeast] padding_top_left: (x, y) point, default None Padding in the top left corner. Useful if some elements in the corner, such as controls, might obscure objects you're zooming to. padding_bottom_right: (x, y) point, default None Padding in the bottom right corner. padding: (x, y) point, default None Equivalent to setting both top left and bottom right padding to the same value. max_zoom: int, default None Maximum zoom to be used. Example ------- >>> map.fit_bounds([[52.193636, -2.221575], [52.636878, -1.139759]]) """ options = { 'paddingTopLeft': padding_top_left, 'paddingBottomRight': padding_bottom_right, 'padding': padding, 'maxZoom': max_zoom, } fit_bounds_options = {} for key, opt in options.items(): if opt: fit_bounds_options[key] = opt fit_bounds = self.env.get_template('fit_bounds.js') fit_bounds_str = fit_bounds.render({ 'bounds': json.dumps(bounds), 'fit_bounds_options': json.dumps(fit_bounds_options, sort_keys=True), }) self.template_vars.update({'fit_bounds': fit_bounds_str}) def add_plugin(self, plugin): """Adds a plugin to the map. Parameters ---------- plugin: folium.plugins object A plugin to be added to the map. It has to implement the methods `render_html`, `render_css` and `render_js`. """ plugin.add_to_map(self) def _auto_bounds(self): if 'fit_bounds' in self.template_vars: return # Get count for each feature type ft_names = ["marker", "line", "circle", "polygon", "multiline"] ft_names = [i for i in ft_names if i in self.mark_cnt] # Make a comprehensive list of all the features we want to fit feat_str = ["{name}_{count}".format(name=ft_name, count=self.mark_cnt[ft_name]) for ft_name in ft_names for count in range(1, self.mark_cnt[ft_name]+1)] feat_str = "[" + ', '.join(feat_str) + "]" fit_bounds = self.env.get_template('fit_bounds.js') fit_bounds_str = fit_bounds.render({ 'autobounds': not self.location, 'features': feat_str, 'fit_bounds_options': json.dumps({'padding': [30, 30]}), }) self.template_vars.update({'fit_bounds': fit_bounds_str.strip()}) def _popup_render(self, popup=None, mk_name=None, count=None, width=300): """Popup renderer: either text or Vincent/Vega. Parameters ---------- popup: str or Vincent tuple, default None String for text popup, or tuple of (Vincent object, json_path) mk_name: str, default None Type of marker. Simple, Circle, etc. count: int, default None Count of marker """ if not popup: return '' else: if sys.version_info >= (3, 0): utype, stype = str, bytes else: utype, stype = unicode, str if isinstance(popup, (utype, stype)): popup_temp = self.env.get_template('simple_popup.js') if isinstance(popup, utype): popup_txt = popup.encode('ascii', 'xmlcharrefreplace') else: popup_txt = popup if sys.version_info >= (3, 0): popup_txt = popup_txt.decode() pop_txt = json.dumps(str(popup_txt)) return popup_temp.render({'pop_name': mk_name + str(count), 'pop_txt': pop_txt, 'width': width}) elif isinstance(popup, tuple): # Update template with JS libs. vega_temp = self.env.get_template('vega_ref.txt').render() jquery_temp = self.env.get_template('jquery_ref.txt').render() d3_temp = self.env.get_template('d3_ref.txt').render() vega_parse = self.env.get_template('vega_parse.js').render() self.template_vars.update({'vega': vega_temp, 'd3': d3_temp, 'jquery': jquery_temp, 'vega_parse': vega_parse}) # Parameters for Vega template. vega = popup[0] mark = ''.join([mk_name, str(count)]) json_out = popup[1] div_id = popup[1].split('.')[0] width = vega.width height = vega.height if isinstance(vega.padding, dict): width += vega.padding['left']+vega.padding['right'] height += vega.padding['top']+vega.padding['bottom'] else: width += 75 height += 50 max_width = self.map_size['width'] vega_id = '#' + div_id popup_temp = self.env.get_template('vega_marker.js') return popup_temp.render({'mark': mark, 'div_id': div_id, 'width': width, 'height': height, 'max_width': max_width, 'json_out': json_out, 'vega_id': vega_id}) else: raise TypeError("Unrecognized popup type: {!r}".format(popup)) @iter_obj('geojson') def geo_json(self, geo_path=None, geo_str=None, data_out='data.json', data=None, columns=None, key_on=None, threshold_scale=None, fill_color='blue', fill_opacity=0.6, line_color='black', line_weight=1, line_opacity=1, legend_name=None, topojson=None, reset=False): """Apply a GeoJSON overlay to the map. Plot a GeoJSON overlay on the base map. There is no requirement to bind data (passing just a GeoJSON plots a single-color overlay), but there is a data binding option to map your columnar data to different feature objects with a color scale. If data is passed as a Pandas dataframe, the "columns" and "key-on" keywords must be included, the first to indicate which DataFrame columns to use, the second to indicate the layer in the GeoJSON on which to key the data. The 'columns' keyword does not need to be passed for a Pandas series. Colors are generated from color brewer (http://colorbrewer2.org/) sequential palettes on a D3 threshold scale. The scale defaults to the following quantiles: [0, 0.5, 0.75, 0.85, 0.9]. A custom scale can be passed to `threshold_scale` of length <=6, in order to match the color brewer range. TopoJSONs can be passed as "geo_path", but the "topojson" keyword must also be passed with the reference to the topojson objects to convert. See the topojson.feature method in the TopoJSON API reference: https://github.com/mbostock/topojson/wiki/API-Reference Parameters ---------- geo_path: string, default None URL or File path to your GeoJSON data geo_str: string, default None String of GeoJSON, alternative to geo_path data_out: string, default 'data.json' Path to write Pandas DataFrame/Series to JSON if binding data data: Pandas DataFrame or Series, default None Data to bind to the GeoJSON. columns: dict or tuple, default None If the data is a Pandas DataFrame, the columns of data to be bound. Must pass column 1 as the key, and column 2 the values. key_on: string, default None Variable in the GeoJSON file to bind the data to. Must always start with 'feature' and be in JavaScript objection notation. Ex: 'feature.id' or 'feature.properties.statename'. threshold_scale: list, default None Data range for D3 threshold scale. Defaults to the following range of quantiles: [0, 0.5, 0.75, 0.85, 0.9], rounded to the nearest order-of-magnitude integer. Ex: 270 rounds to 200, 5600 to 6000. fill_color: string, default 'blue' Area fill color. Can pass a hex code, color name, or if you are binding data, one of the following color brewer palettes: 'BuGn', 'BuPu', 'GnBu', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'RdPu', 'YlGn', 'YlGnBu', 'YlOrBr', and 'YlOrRd'. fill_opacity: float, default 0.6 Area fill opacity, range 0-1. line_color: string, default 'black' GeoJSON geopath line color. line_weight: int, default 1 GeoJSON geopath line weight. line_opacity: float, default 1 GeoJSON geopath line opacity, range 0-1. legend_name: string, default None Title for data legend. If not passed, defaults to columns[1]. topojson: string, default None If using a TopoJSON, passing "objects.yourfeature" to the topojson keyword argument will enable conversion to GeoJSON. reset: boolean, default False Remove all current geoJSON layers, start with new layer Output ------ GeoJSON data layer in obj.template_vars Example ------- >>> m.geo_json(geo_path='us-states.json', line_color='blue', line_weight=3) >>> m.geo_json(geo_path='geo.json', data=df, columns=['Data 1', 'Data 2'], key_on='feature.properties.myvalue', fill_color='PuBu', threshold_scale=[0, 20, 30, 40, 50, 60]) >>> m.geo_json(geo_path='countries.json', topojson='objects.countries') """ if reset: reset_vars = ['json_paths', 'func_vars', 'color_scales', 'geo_styles', 'gjson_layers', 'map_legends', 'topo_convert'] for var in reset_vars: self.template_vars.update({var: []}) self.mark_cnt['geojson'] = 1 def json_style(style_cnt, line_color, line_weight, line_opacity, fill_color, fill_opacity, quant_fill): """Generate JSON styling function from template""" style_temp = self.env.get_template('geojson_style.js') style = style_temp.render({'style': style_cnt, 'line_color': line_color, 'line_weight': line_weight, 'line_opacity': line_opacity, 'fill_color': fill_color, 'fill_opacity': fill_opacity, 'quantize_fill': quant_fill}) return style # Set map type to geojson. self.map_type = 'geojson' # Get JSON map layer template pieces, convert TopoJSON if necessary. # geo_str is really a hack. if geo_path: geo_path = ".defer(d3.json, '{0}')".format(geo_path) elif geo_str: fmt = (".defer(function(callback)" "{{callback(null, JSON.parse('{}'))}})").format geo_path = fmt(geo_str) if topojson is None: map_var = '_'.join(['gjson', str(self.mark_cnt['geojson'])]) layer_var = map_var else: map_var = '_'.join(['tjson', str(self.mark_cnt['geojson'])]) topo_obj = '.'.join([map_var, topojson]) layer_var = '_'.join(['topo', str(self.mark_cnt['geojson'])]) topo_templ = self.env.get_template('topo_func.js') topo_func = topo_templ.render({'map_var': layer_var, 't_var': map_var, 't_var_obj': topo_obj}) topo_lib = self.env.get_template('topojson_ref.txt').render() self.template_vars.update({'topojson': topo_lib}) self.template_vars.setdefault('topo_convert', []).append(topo_func) style_count = '_'.join(['style', str(self.mark_cnt['geojson'])]) # Get Data binding pieces if available. if data is not None: import pandas as pd # Create DataFrame with only the relevant columns. if isinstance(data, pd.DataFrame): data = pd.concat([data[columns[0]], data[columns[1]]], axis=1) # Save data to JSON. self.json_data[data_out] = utilities.transform_data(data) # Add data to queue. d_path = ".defer(d3.json, '{0}')".format(data_out) self.template_vars.setdefault('json_paths', []).append(d_path) # Add data variable to makeMap function. data_var = '_'.join(['data', str(self.mark_cnt['geojson'])]) self.template_vars.setdefault('func_vars', []).append(data_var) # D3 Color scale. series = data[columns[1]] if threshold_scale and len(threshold_scale) > 6: raise ValueError domain = threshold_scale or utilities.split_six(series=series) if len(domain) > 253: raise ValueError('The threshold scale must be length <= 253') if not utilities.color_brewer(fill_color): raise ValueError('Please pass a valid color brewer code to ' 'fill_local. See docstring for valid codes.') palette = utilities.color_brewer(fill_color, len(domain)) d3range = palette[0: len(domain) + 1] tick_labels = utilities.legend_scaler(domain) color_temp = self.env.get_template('d3_threshold.js') d3scale = color_temp.render({'domain': domain, 'range': d3range}) self.template_vars.setdefault('color_scales', []).append(d3scale) # Create legend. name = legend_name or columns[1] leg_templ = self.env.get_template('d3_map_legend.js') legend = leg_templ.render({'lin_max': int(domain[-1]*1.1), 'tick_labels': tick_labels, 'caption': name}) self.template_vars.setdefault('map_legends', []).append(legend) # Style with color brewer colors. matchColor = 'color(matchKey({0}, {1}))'.format(key_on, data_var) style = json_style(style_count, line_color, line_weight, line_opacity, None, fill_opacity, matchColor) else: style = json_style(style_count, line_color, line_weight, line_opacity, fill_color, fill_opacity, None) layer = ('gJson_layer_{0} = L.geoJson({1}, {{style: {2},' 'onEachFeature: onEachFeature}}).addTo(map)' .format(self.mark_cnt['geojson'], layer_var, style_count)) self.template_vars.setdefault('json_paths', []).append(geo_path) self.template_vars.setdefault('func_vars', []).append(map_var) self.template_vars.setdefault('geo_styles', []).append(style) self.template_vars.setdefault('gjson_layers', []).append(layer) @iter_obj('image_overlay') def image_overlay(self, data, opacity=0.25, min_lat=-90.0, max_lat=90.0, min_lon=-180.0, max_lon=180.0, image_name=None, filename=None): """Simple image overlay of raster data from a numpy array. This is a lightweight way to overlay geospatial data on top of a map. If your data is high res, consider implementing a WMS server and adding a WMS layer. This function works by generating a PNG file from a numpy array. If you do not specifiy a filename, it will embed the image inline. Otherwise, it saves the file in the current directory, and then adds it as an image overlay layer in leaflet.js. By default, the image is placed and stretched using bounds that cover the entire globe. Parameters ---------- data: numpy array OR url string, required. if numpy array, must be a image format, i.e., NxM (mono), NxMx3 (rgb), or NxMx4 (rgba) if url, must be a valid url to a image (local or external) opacity: float, default 0.25 Image layer opacity in range 0 (completely transparent) to 1 (opaque) min_lat: float, default -90.0 max_lat: float, default 90.0 min_lon: float, default -180.0 max_lon: float, default 180.0 image_name: string, default None The name of the layer object in leaflet.js filename: string, default None Optional file name of output.png for image overlay. If None, we use a inline PNG. Output ------ Image overlay data layer in obj.template_vars Examples ------- # assumes a map object `m` has been created >>> import numpy as np >>> data = np.random.random((100,100)) # to make a rgba from a specific matplotlib colormap: >>> import matplotlib.cm as cm >>> cmapper = cm.cm.ColorMapper('jet') >>> data2 = cmapper.to_rgba(np.random.random((100,100))) # place the data over all of the globe (will be pretty pixelated!) >>> m.image_overlay(data) # put it only over a single city (Paris) >>> m.image_overlay(data, min_lat=48.80418, max_lat=48.90970, min_lon=2.25214, max_lon=2.44731) """ if isinstance(data, str): filename = data else: try: png_str = utilities.write_png(data) except Exception as e: raise e if filename is not None: with open(filename, 'wb') as fd: fd.write(png_str) else: filename = "data:image/png;base64,"+base64.b64encode(png_str).decode('utf-8') if image_name not in self.added_layers: if image_name is None: image_name = "Image_Overlay" else: image_name = image_name.replace(" ", "_") image_url = filename image_bounds = [[min_lat, min_lon], [max_lat, max_lon]] image_opacity = opacity image_temp = self.env.get_template('image_layer.js') image = image_temp.render({'image_name': image_name, 'image_url': image_url, 'image_bounds': image_bounds, 'image_opacity': image_opacity}) self.template_vars['image_layers'].append(image) self.added_layers.append(image_name) def _build_map(self, html_templ=None, templ_type='string'): self._auto_bounds() """Build HTML/JS/CSS from Templates given current map type.""" if html_templ is None: map_types = {'base': 'fol_template.html', 'geojson': 'geojson_template.html'} # Check current map type. type_temp = map_types[self.map_type] html_templ = self.env.get_template(type_temp) else: if templ_type == 'string': html_templ = self.env.from_string(html_templ) self.HTML = html_templ.render(self.template_vars, plugins=self.plugins) def create_map(self, path='map.html', plugin_data_out=True, template=None): """Write Map output to HTML and data output to JSON if available. Parameters: ----------- path: string, default 'map.html' Path for HTML output for map plugin_data_out: boolean, default True If using plugins such as awesome markers, write all plugin data such as JS/CSS/images to path template: string, default None Custom template to render """ self.map_path = path self._build_map(template) with codecs.open(path, 'w', 'utf8') as f: f.write(self.HTML) if self.json_data: for path, data in iteritems(self.json_data): with open(path, 'w') as g: json.dump(data, g) if self.plugins and plugin_data_out: for name, plugin in iteritems(self.plugins): with open(name, 'w') as f: if isinstance(plugin, binary_type): plugin = text_type(plugin, 'utf8') f.write(plugin) def _repr_html_(self): """Build the HTML representation for IPython.""" map_types = {'base': 'ipynb_repr.html', 'geojson': 'ipynb_iframe.html'} # Check current map type. type_temp = map_types[self.map_type] if self.render_iframe: type_temp = 'ipynb_iframe.html' templ = self.env.get_template(type_temp) self._build_map(html_templ=templ, templ_type='temp') if self.map_type == 'geojson' or self.render_iframe: if not self.map_path: raise ValueError('Use create_map to set the path!') return templ.render(path=self.map_path, width=self.width, height=self.height) return self.HTML def display(self): """Display the visualization inline in the IPython notebook. This is deprecated, use the following instead:: from IPython.display import display display(viz) """ from IPython.core.display import display, HTML display(HTML(self._repr_html_()))
mit
sumspr/scikit-learn
sklearn/cluster/tests/test_bicluster.py
226
9457
"""Testing for Spectral Biclustering methods""" import numpy as np from scipy.sparse import csr_matrix, issparse from sklearn.grid_search import ParameterGrid from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_true from sklearn.utils.testing import SkipTest from sklearn.base import BaseEstimator, BiclusterMixin from sklearn.cluster.bicluster import SpectralCoclustering from sklearn.cluster.bicluster import SpectralBiclustering from sklearn.cluster.bicluster import _scale_normalize from sklearn.cluster.bicluster import _bistochastic_normalize from sklearn.cluster.bicluster import _log_normalize from sklearn.metrics import consensus_score from sklearn.datasets import make_biclusters, make_checkerboard class MockBiclustering(BaseEstimator, BiclusterMixin): # Mock object for testing get_submatrix. def __init__(self): pass def get_indices(self, i): # Overridden to reproduce old get_submatrix test. return (np.where([True, True, False, False, True])[0], np.where([False, False, True, True])[0]) def test_get_submatrix(): data = np.arange(20).reshape(5, 4) model = MockBiclustering() for X in (data, csr_matrix(data), data.tolist()): submatrix = model.get_submatrix(0, X) if issparse(submatrix): submatrix = submatrix.toarray() assert_array_equal(submatrix, [[2, 3], [6, 7], [18, 19]]) submatrix[:] = -1 if issparse(X): X = X.toarray() assert_true(np.all(X != -1)) def _test_shape_indices(model): # Test get_shape and get_indices on fitted model. for i in range(model.n_clusters): m, n = model.get_shape(i) i_ind, j_ind = model.get_indices(i) assert_equal(len(i_ind), m) assert_equal(len(j_ind), n) def test_spectral_coclustering(): # Test Dhillon's Spectral CoClustering on a simple problem. param_grid = {'svd_method': ['randomized', 'arpack'], 'n_svd_vecs': [None, 20], 'mini_batch': [False, True], 'init': ['k-means++'], 'n_init': [10], 'n_jobs': [1]} random_state = 0 S, rows, cols = make_biclusters((30, 30), 3, noise=0.5, random_state=random_state) S -= S.min() # needs to be nonnegative before making it sparse S = np.where(S < 1, 0, S) # threshold some values for mat in (S, csr_matrix(S)): for kwargs in ParameterGrid(param_grid): model = SpectralCoclustering(n_clusters=3, random_state=random_state, **kwargs) model.fit(mat) assert_equal(model.rows_.shape, (3, 30)) assert_array_equal(model.rows_.sum(axis=0), np.ones(30)) assert_array_equal(model.columns_.sum(axis=0), np.ones(30)) assert_equal(consensus_score(model.biclusters_, (rows, cols)), 1) _test_shape_indices(model) def test_spectral_biclustering(): # Test Kluger methods on a checkerboard dataset. S, rows, cols = make_checkerboard((30, 30), 3, noise=0.5, random_state=0) non_default_params = {'method': ['scale', 'log'], 'svd_method': ['arpack'], 'n_svd_vecs': [20], 'mini_batch': [True]} for mat in (S, csr_matrix(S)): for param_name, param_values in non_default_params.items(): for param_value in param_values: model = SpectralBiclustering( n_clusters=3, n_init=3, init='k-means++', random_state=0, ) model.set_params(**dict([(param_name, param_value)])) if issparse(mat) and model.get_params().get('method') == 'log': # cannot take log of sparse matrix assert_raises(ValueError, model.fit, mat) continue else: model.fit(mat) assert_equal(model.rows_.shape, (9, 30)) assert_equal(model.columns_.shape, (9, 30)) assert_array_equal(model.rows_.sum(axis=0), np.repeat(3, 30)) assert_array_equal(model.columns_.sum(axis=0), np.repeat(3, 30)) assert_equal(consensus_score(model.biclusters_, (rows, cols)), 1) _test_shape_indices(model) def _do_scale_test(scaled): """Check that rows sum to one constant, and columns to another.""" row_sum = scaled.sum(axis=1) col_sum = scaled.sum(axis=0) if issparse(scaled): row_sum = np.asarray(row_sum).squeeze() col_sum = np.asarray(col_sum).squeeze() assert_array_almost_equal(row_sum, np.tile(row_sum.mean(), 100), decimal=1) assert_array_almost_equal(col_sum, np.tile(col_sum.mean(), 100), decimal=1) def _do_bistochastic_test(scaled): """Check that rows and columns sum to the same constant.""" _do_scale_test(scaled) assert_almost_equal(scaled.sum(axis=0).mean(), scaled.sum(axis=1).mean(), decimal=1) def test_scale_normalize(): generator = np.random.RandomState(0) X = generator.rand(100, 100) for mat in (X, csr_matrix(X)): scaled, _, _ = _scale_normalize(mat) _do_scale_test(scaled) if issparse(mat): assert issparse(scaled) def test_bistochastic_normalize(): generator = np.random.RandomState(0) X = generator.rand(100, 100) for mat in (X, csr_matrix(X)): scaled = _bistochastic_normalize(mat) _do_bistochastic_test(scaled) if issparse(mat): assert issparse(scaled) def test_log_normalize(): # adding any constant to a log-scaled matrix should make it # bistochastic generator = np.random.RandomState(0) mat = generator.rand(100, 100) scaled = _log_normalize(mat) + 1 _do_bistochastic_test(scaled) def test_fit_best_piecewise(): model = SpectralBiclustering(random_state=0) vectors = np.array([[0, 0, 0, 1, 1, 1], [2, 2, 2, 3, 3, 3], [0, 1, 2, 3, 4, 5]]) best = model._fit_best_piecewise(vectors, n_best=2, n_clusters=2) assert_array_equal(best, vectors[:2]) def test_project_and_cluster(): model = SpectralBiclustering(random_state=0) data = np.array([[1, 1, 1], [1, 1, 1], [3, 6, 3], [3, 6, 3]]) vectors = np.array([[1, 0], [0, 1], [0, 0]]) for mat in (data, csr_matrix(data)): labels = model._project_and_cluster(data, vectors, n_clusters=2) assert_array_equal(labels, [0, 0, 1, 1]) def test_perfect_checkerboard(): raise SkipTest("This test is failing on the buildbot, but cannot" " reproduce. Temporarily disabling it until it can be" " reproduced and fixed.") model = SpectralBiclustering(3, svd_method="arpack", random_state=0) S, rows, cols = make_checkerboard((30, 30), 3, noise=0, random_state=0) model.fit(S) assert_equal(consensus_score(model.biclusters_, (rows, cols)), 1) S, rows, cols = make_checkerboard((40, 30), 3, noise=0, random_state=0) model.fit(S) assert_equal(consensus_score(model.biclusters_, (rows, cols)), 1) S, rows, cols = make_checkerboard((30, 40), 3, noise=0, random_state=0) model.fit(S) assert_equal(consensus_score(model.biclusters_, (rows, cols)), 1) def test_errors(): data = np.arange(25).reshape((5, 5)) model = SpectralBiclustering(n_clusters=(3, 3, 3)) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_clusters='abc') assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_clusters=(3, 'abc')) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(method='unknown') assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(svd_method='unknown') assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_components=0) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_best=0) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_components=3, n_best=4) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering() data = np.arange(27).reshape((3, 3, 3)) assert_raises(ValueError, model.fit, data)
bsd-3-clause
wesm/arrow
python/pyarrow/feather.py
1
9058
# 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 os from pyarrow.pandas_compat import _pandas_api # noqa from pyarrow.lib import (Codec, FeatherError, Table, # noqa concat_tables, schema) import pyarrow.lib as ext from pyarrow.vendored.version import Version def _check_pandas_version(): if _pandas_api.loose_version < Version('0.17.0'): raise ImportError("feather requires pandas >= 0.17.0") class FeatherDataset: """ Encapsulates details of reading a list of Feather files. Parameters ---------- path_or_paths : List[str] A list of file names validate_schema : bool, default True Check that individual file schemas are all the same / compatible """ def __init__(self, path_or_paths, validate_schema=True): self.paths = path_or_paths self.validate_schema = validate_schema def read_table(self, columns=None): """ Read multiple feather files as a single pyarrow.Table Parameters ---------- columns : List[str] Names of columns to read from the file Returns ------- pyarrow.Table Content of the file as a table (of columns) """ _fil = read_table(self.paths[0], columns=columns) self._tables = [_fil] self.schema = _fil.schema for path in self.paths[1:]: table = read_table(path, columns=columns) if self.validate_schema: self.validate_schemas(path, table) self._tables.append(table) return concat_tables(self._tables) def validate_schemas(self, piece, table): if not self.schema.equals(table.schema): raise ValueError('Schema in {!s} was different. \n' '{!s}\n\nvs\n\n{!s}' .format(piece, self.schema, table.schema)) def read_pandas(self, columns=None, use_threads=True): """ Read multiple Parquet files as a single pandas DataFrame Parameters ---------- columns : List[str] Names of columns to read from the file use_threads : bool, default True Use multiple threads when converting to pandas Returns ------- pandas.DataFrame Content of the file as a pandas DataFrame (of columns) """ _check_pandas_version() return self.read_table(columns=columns).to_pandas( use_threads=use_threads) def check_chunked_overflow(name, col): if col.num_chunks == 1: return if col.type in (ext.binary(), ext.string()): raise ValueError("Column '{}' exceeds 2GB maximum capacity of " "a Feather binary column. This restriction may be " "lifted in the future".format(name)) else: # TODO(wesm): Not sure when else this might be reached raise ValueError("Column '{}' of type {} was chunked on conversion " "to Arrow and cannot be currently written to " "Feather format".format(name, str(col.type))) _FEATHER_SUPPORTED_CODECS = {'lz4', 'zstd', 'uncompressed'} def write_feather(df, dest, compression=None, compression_level=None, chunksize=None, version=2): """ Write a pandas.DataFrame to Feather format. Parameters ---------- df : pandas.DataFrame or pyarrow.Table Data to write out as Feather format. dest : str Local destination path. compression : string, default None Can be one of {"zstd", "lz4", "uncompressed"}. The default of None uses LZ4 for V2 files if it is available, otherwise uncompressed. compression_level : int, default None Use a compression level particular to the chosen compressor. If None use the default compression level chunksize : int, default None For V2 files, the internal maximum size of Arrow RecordBatch chunks when writing the Arrow IPC file format. None means use the default, which is currently 64K version : int, default 2 Feather file version. Version 2 is the current. Version 1 is the more limited legacy format """ if _pandas_api.have_pandas: _check_pandas_version() if (_pandas_api.has_sparse and isinstance(df, _pandas_api.pd.SparseDataFrame)): df = df.to_dense() if _pandas_api.is_data_frame(df): table = Table.from_pandas(df, preserve_index=False) if version == 1: # Version 1 does not chunking for i, name in enumerate(table.schema.names): col = table[i] check_chunked_overflow(name, col) else: table = df if version == 1: if len(table.column_names) > len(set(table.column_names)): raise ValueError("cannot serialize duplicate column names") if compression is not None: raise ValueError("Feather V1 files do not support compression " "option") if chunksize is not None: raise ValueError("Feather V1 files do not support chunksize " "option") else: if compression is None and Codec.is_available('lz4_frame'): compression = 'lz4' elif (compression is not None and compression not in _FEATHER_SUPPORTED_CODECS): raise ValueError('compression="{}" not supported, must be ' 'one of {}'.format(compression, _FEATHER_SUPPORTED_CODECS)) try: ext.write_feather(table, dest, compression=compression, compression_level=compression_level, chunksize=chunksize, version=version) except Exception: if isinstance(dest, str): try: os.remove(dest) except os.error: pass raise def read_feather(source, columns=None, use_threads=True, memory_map=True): """ Read a pandas.DataFrame from Feather format. To read as pyarrow.Table use feather.read_table. Parameters ---------- source : str file path, or file-like object columns : sequence, optional Only read a specific set of columns. If not provided, all columns are read. use_threads: bool, default True Whether to parallelize reading using multiple threads. memory_map : boolean, default True Use memory mapping when opening file on disk Returns ------- df : pandas.DataFrame """ _check_pandas_version() return (read_table(source, columns=columns, memory_map=memory_map) .to_pandas(use_threads=use_threads)) def read_table(source, columns=None, memory_map=True): """ Read a pyarrow.Table from Feather format Parameters ---------- source : str file path, or file-like object columns : sequence, optional Only read a specific set of columns. If not provided, all columns are read. memory_map : boolean, default True Use memory mapping when opening file on disk Returns ------- table : pyarrow.Table """ reader = ext.FeatherReader() reader.open(source, use_memory_map=memory_map) if columns is None: return reader.read() column_types = [type(column) for column in columns] if all(map(lambda t: t == int, column_types)): table = reader.read_indices(columns) elif all(map(lambda t: t == str, column_types)): table = reader.read_names(columns) else: column_type_names = [t.__name__ for t in column_types] raise TypeError("Columns must be indices or names. " "Got columns {} of types {}" .format(columns, column_type_names)) # Feather v1 already respects the column selection if reader.version < 3: return table # Feather v2 reads with sorted / deduplicated selection elif sorted(set(columns)) == columns: return table else: # follow exact order / selection of names return table.select(columns)
apache-2.0
kmiernik/Pyspectr
other/spectrum_profiler.py
2
2296
#!/usr/bin/env python3 """ K. Miernik 2012 [email protected] Performes fit to the decay part for all channels in E vs time spectrum """ import sys import argparse import math import numpy from lmfit import minimize, Parameters, report_errors import matplotlib.pyplot as plt import Pyspectr.hisfile as hisfile class GeneralError(Exception): """General error class """ def __init__(self, msg = ''): self.msg = msg def __str__(self): return repr(self.msg) def decay(params, data_x): T1 = params['T1'].value A = params['A'].value tau = params['tau'].value return A * numpy.exp(-(data_x - T1) / tau) def residual(params, data_x, data_y, data_dy): model = fitfunc(params, data_x) return (data_y - model) / data_dy if __name__ == "__main__": parser = argparse.ArgumentParser(description='') parser.add_argument('in_file', help='Input file') args = parser.parse_args() hisId = 2681 T1 = 200 T2 = 300 his = hisfile.HisFile(args.in_file) dim, xaxis, yaxis, data = his.load_histogram(hisId) #data = data.transpose() fitfunc = decay params = Parameters() params.add('T1', value=T1, vary=False) params.add('A', value=100.0, min=0.0) params.add('tau', value=100.0, min=0.0) sys.stderr.write('.') symbol = 0 for E in range(2, data.shape[0] - 1, 3): symbol += 1 data_slice = sum(data[E-1:E+2])[T1:T2] dy = numpy.sqrt(numpy.abs(data_slice)) for i, v in enumerate(dy): if dy[i] == 0: dy[i] = 1.0 data_sum_err = math.sqrt(dy.sum()) if data_slice.sum() - data_sum_err <= 0: continue params['A'].value = 100.0 params['tau'].value = 100.0 result = minimize(residual, params, args=(yaxis[T1:T2], data_slice, dy)) scale = 0.01 print(E, result.params['tau'].value * scale * math.log(2), result.params['tau'].stderr * scale * math.log(2)) sys.stderr.write('\r') if symbol % 3 == 0: sys.stderr.write('.') elif symbol % 3 == 1: sys.stderr.write('o') else: sys.stderr.write('*') sys.stderr.write('\n')
gpl-3.0
nkmk/python-snippets
notebook/sklearn_precision_score_average.py
1
1571
from sklearn.metrics import precision_score from sklearn.metrics import confusion_matrix y_true = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] y_pred = [0, 1, 1, 1, 1, 0, 0, 0, 1, 1] print(precision_score(y_true, y_pred)) # 0.3333333333333333 print(precision_score(y_true, y_pred, pos_label=0)) # 0.25 print(precision_score(y_true, y_pred, average=None)) # [0.25 0.33333333] print(precision_score(y_true, y_pred, average='macro')) # 0.29166666666666663 print(precision_score(y_true, y_pred, average='micro')) # 0.3 print(confusion_matrix(y_true, y_pred)) # [[1 4] # [3 2]] print(confusion_matrix(y_true, y_pred, labels=[1, 0])) # [[2 3] # [4 1]] print(precision_score(y_true, y_pred, average='weighted')) # 0.29166666666666663 y_true_2 = [0, 1, 1, 1, 1] y_pred_2 = [0, 0, 0, 0, 1] print(confusion_matrix(y_true_2, y_pred_2)) # [[1 0] # [3 1]] print(confusion_matrix(y_true_2, y_pred_2, labels=[1, 0])) # [[1 3] # [0 1]] print(precision_score(y_true_2, y_pred_2)) # 1.0 print(precision_score(y_true_2, y_pred_2, pos_label=0)) # 0.25 print(precision_score(y_true_2, y_pred_2, average='macro')) # 0.625 print(precision_score(y_true_2, y_pred_2, average='micro')) # 0.4 print(precision_score(y_true_2, y_pred_2, average='weighted')) # 0.85 y_true_ab = ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'] y_pred_ab = ['A', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'B', 'B'] # print(precision_score(y_true_ab, y_pred_ab)) # ValueError: pos_label=1 is not a valid label: array(['A', 'B'], dtype='<U1') print(precision_score(y_true_ab, y_pred_ab, pos_label='A')) # 0.25
mit
Lawrence-Liu/scikit-learn
sklearn/tree/tests/test_export.py
130
9950
""" Testing for export functions of decision trees (sklearn.tree.export). """ from re import finditer from numpy.testing import assert_equal from nose.tools import assert_raises from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.ensemble import GradientBoostingClassifier from sklearn.tree import export_graphviz from sklearn.externals.six import StringIO from sklearn.utils.testing import assert_in # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [-1, -1, -1, 1, 1, 1] y2 = [[-1, 1], [-1, 2], [-1, 3], [1, 1], [1, 2], [1, 3]] w = [1, 1, 1, .5, .5, .5] def test_graphviz_toy(): # Check correctness of export_graphviz clf = DecisionTreeClassifier(max_depth=3, min_samples_split=1, criterion="gini", random_state=2) clf.fit(X, y) # Test export code out = StringIO() export_graphviz(clf, out_file=out) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box] ;\n' \ '0 [label="X[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]"] ;\n' \ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n' \ '0 -> 1 [labeldistance=2.5, labelangle=45, ' \ 'headlabel="True"] ;\n' \ '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]"] ;\n' \ '0 -> 2 [labeldistance=2.5, labelangle=-45, ' \ 'headlabel="False"] ;\n' \ '}' assert_equal(contents1, contents2) # Test with feature_names out = StringIO() export_graphviz(clf, out_file=out, feature_names=["feature0", "feature1"]) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box] ;\n' \ '0 [label="feature0 <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]"] ;\n' \ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n' \ '0 -> 1 [labeldistance=2.5, labelangle=45, ' \ 'headlabel="True"] ;\n' \ '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]"] ;\n' \ '0 -> 2 [labeldistance=2.5, labelangle=-45, ' \ 'headlabel="False"] ;\n' \ '}' assert_equal(contents1, contents2) # Test with class_names out = StringIO() export_graphviz(clf, out_file=out, class_names=["yes", "no"]) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box] ;\n' \ '0 [label="X[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]\\nclass = yes"] ;\n' \ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]\\n' \ 'class = yes"] ;\n' \ '0 -> 1 [labeldistance=2.5, labelangle=45, ' \ 'headlabel="True"] ;\n' \ '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]\\n' \ 'class = no"] ;\n' \ '0 -> 2 [labeldistance=2.5, labelangle=-45, ' \ 'headlabel="False"] ;\n' \ '}' assert_equal(contents1, contents2) # Test plot_options out = StringIO() export_graphviz(clf, out_file=out, filled=True, impurity=False, proportion=True, special_characters=True, rounded=True) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box, style="filled, rounded", color="black", ' \ 'fontname=helvetica] ;\n' \ 'edge [fontname=helvetica] ;\n' \ '0 [label=<X<SUB>0</SUB> &le; 0.0<br/>samples = 100.0%<br/>' \ 'value = [0.5, 0.5]>, fillcolor="#e5813900"] ;\n' \ '1 [label=<samples = 50.0%<br/>value = [1.0, 0.0]>, ' \ 'fillcolor="#e58139ff"] ;\n' \ '0 -> 1 [labeldistance=2.5, labelangle=45, ' \ 'headlabel="True"] ;\n' \ '2 [label=<samples = 50.0%<br/>value = [0.0, 1.0]>, ' \ 'fillcolor="#399de5ff"] ;\n' \ '0 -> 2 [labeldistance=2.5, labelangle=-45, ' \ 'headlabel="False"] ;\n' \ '}' assert_equal(contents1, contents2) # Test max_depth out = StringIO() export_graphviz(clf, out_file=out, max_depth=0, class_names=True) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box] ;\n' \ '0 [label="X[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]\\nclass = y[0]"] ;\n' \ '1 [label="(...)"] ;\n' \ '0 -> 1 ;\n' \ '2 [label="(...)"] ;\n' \ '0 -> 2 ;\n' \ '}' assert_equal(contents1, contents2) # Test max_depth with plot_options out = StringIO() export_graphviz(clf, out_file=out, max_depth=0, filled=True, node_ids=True) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box, style="filled", color="black"] ;\n' \ '0 [label="node #0\\nX[0] <= 0.0\\ngini = 0.5\\n' \ 'samples = 6\\nvalue = [3, 3]", fillcolor="#e5813900"] ;\n' \ '1 [label="(...)", fillcolor="#C0C0C0"] ;\n' \ '0 -> 1 ;\n' \ '2 [label="(...)", fillcolor="#C0C0C0"] ;\n' \ '0 -> 2 ;\n' \ '}' assert_equal(contents1, contents2) # Test multi-output with weighted samples clf = DecisionTreeClassifier(max_depth=2, min_samples_split=1, criterion="gini", random_state=2) clf = clf.fit(X, y2, sample_weight=w) out = StringIO() export_graphviz(clf, out_file=out, filled=True, impurity=False) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box, style="filled", color="black"] ;\n' \ '0 [label="X[0] <= 0.0\\nsamples = 6\\n' \ 'value = [[3.0, 1.5, 0.0]\\n' \ '[1.5, 1.5, 1.5]]", fillcolor="#e5813900"] ;\n' \ '1 [label="X[1] <= -1.5\\nsamples = 3\\n' \ 'value = [[3, 0, 0]\\n[1, 1, 1]]", ' \ 'fillcolor="#e5813965"] ;\n' \ '0 -> 1 [labeldistance=2.5, labelangle=45, ' \ 'headlabel="True"] ;\n' \ '2 [label="samples = 1\\nvalue = [[1, 0, 0]\\n' \ '[0, 0, 1]]", fillcolor="#e58139ff"] ;\n' \ '1 -> 2 ;\n' \ '3 [label="samples = 2\\nvalue = [[2, 0, 0]\\n' \ '[1, 1, 0]]", fillcolor="#e581398c"] ;\n' \ '1 -> 3 ;\n' \ '4 [label="X[0] <= 1.5\\nsamples = 3\\n' \ 'value = [[0.0, 1.5, 0.0]\\n[0.5, 0.5, 0.5]]", ' \ 'fillcolor="#e5813965"] ;\n' \ '0 -> 4 [labeldistance=2.5, labelangle=-45, ' \ 'headlabel="False"] ;\n' \ '5 [label="samples = 2\\nvalue = [[0.0, 1.0, 0.0]\\n' \ '[0.5, 0.5, 0.0]]", fillcolor="#e581398c"] ;\n' \ '4 -> 5 ;\n' \ '6 [label="samples = 1\\nvalue = [[0.0, 0.5, 0.0]\\n' \ '[0.0, 0.0, 0.5]]", fillcolor="#e58139ff"] ;\n' \ '4 -> 6 ;\n' \ '}' assert_equal(contents1, contents2) # Test regression output with plot_options clf = DecisionTreeRegressor(max_depth=3, min_samples_split=1, criterion="mse", random_state=2) clf.fit(X, y) out = StringIO() export_graphviz(clf, out_file=out, filled=True, leaves_parallel=True, rotate=True, rounded=True) contents1 = out.getvalue() contents2 = 'digraph Tree {\n' \ 'node [shape=box, style="filled, rounded", color="black", ' \ 'fontname=helvetica] ;\n' \ 'graph [ranksep=equally, splines=polyline] ;\n' \ 'edge [fontname=helvetica] ;\n' \ 'rankdir=LR ;\n' \ '0 [label="X[0] <= 0.0\\nmse = 1.0\\nsamples = 6\\n' \ 'value = 0.0", fillcolor="#e581397f"] ;\n' \ '1 [label="mse = 0.0\\nsamples = 3\\nvalue = -1.0", ' \ 'fillcolor="#e5813900"] ;\n' \ '0 -> 1 [labeldistance=2.5, labelangle=-45, ' \ 'headlabel="True"] ;\n' \ '2 [label="mse = 0.0\\nsamples = 3\\nvalue = 1.0", ' \ 'fillcolor="#e58139ff"] ;\n' \ '0 -> 2 [labeldistance=2.5, labelangle=45, ' \ 'headlabel="False"] ;\n' \ '{rank=same ; 0} ;\n' \ '{rank=same ; 1; 2} ;\n' \ '}' assert_equal(contents1, contents2) def test_graphviz_errors(): # Check for errors of export_graphviz clf = DecisionTreeClassifier(max_depth=3, min_samples_split=1) clf.fit(X, y) # Check feature_names error out = StringIO() assert_raises(IndexError, export_graphviz, clf, out, feature_names=[]) # Check class_names error out = StringIO() assert_raises(IndexError, export_graphviz, clf, out, class_names=[]) def test_friedman_mse_in_graphviz(): clf = DecisionTreeRegressor(criterion="friedman_mse", random_state=0) clf.fit(X, y) dot_data = StringIO() export_graphviz(clf, out_file=dot_data) clf = GradientBoostingClassifier(n_estimators=2, random_state=0) clf.fit(X, y) for estimator in clf.estimators_: export_graphviz(estimator[0], out_file=dot_data) for finding in finditer("\[.*?samples.*?\]", dot_data.getvalue()): assert_in("friedman_mse", finding.group())
bsd-3-clause
madjelan/scikit-learn
sklearn/gaussian_process/tests/test_gaussian_process.py
267
6813
""" Testing for Gaussian Process module (sklearn.gaussian_process) """ # Author: Vincent Dubourg <[email protected]> # Licence: BSD 3 clause from nose.tools import raises from nose.tools import assert_true import numpy as np from sklearn.gaussian_process import GaussianProcess from sklearn.gaussian_process import regression_models as regression from sklearn.gaussian_process import correlation_models as correlation from sklearn.datasets import make_regression from sklearn.utils.testing import assert_greater f = lambda x: x * np.sin(x) X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T X2 = np.atleast_2d([2., 4., 5.5, 6.5, 7.5]).T y = f(X).ravel() def test_1d(regr=regression.constant, corr=correlation.squared_exponential, random_start=10, beta0=None): # MLE estimation of a one-dimensional Gaussian Process model. # Check random start optimization. # Test the interpolating property. gp = GaussianProcess(regr=regr, corr=corr, beta0=beta0, theta0=1e-2, thetaL=1e-4, thetaU=1e-1, random_start=random_start, verbose=False).fit(X, y) y_pred, MSE = gp.predict(X, eval_MSE=True) y2_pred, MSE2 = gp.predict(X2, eval_MSE=True) assert_true(np.allclose(y_pred, y) and np.allclose(MSE, 0.) and np.allclose(MSE2, 0., atol=10)) def test_2d(regr=regression.constant, corr=correlation.squared_exponential, random_start=10, beta0=None): # MLE estimation of a two-dimensional Gaussian Process model accounting for # anisotropy. Check random start optimization. # Test the interpolating property. b, kappa, e = 5., .5, .1 g = lambda x: b - x[:, 1] - kappa * (x[:, 0] - e) ** 2. X = np.array([[-4.61611719, -6.00099547], [4.10469096, 5.32782448], [0.00000000, -0.50000000], [-6.17289014, -4.6984743], [1.3109306, -6.93271427], [-5.03823144, 3.10584743], [-2.87600388, 6.74310541], [5.21301203, 4.26386883]]) y = g(X).ravel() thetaL = [1e-4] * 2 thetaU = [1e-1] * 2 gp = GaussianProcess(regr=regr, corr=corr, beta0=beta0, theta0=[1e-2] * 2, thetaL=thetaL, thetaU=thetaU, random_start=random_start, verbose=False) gp.fit(X, y) y_pred, MSE = gp.predict(X, eval_MSE=True) assert_true(np.allclose(y_pred, y) and np.allclose(MSE, 0.)) eps = np.finfo(gp.theta_.dtype).eps assert_true(np.all(gp.theta_ >= thetaL - eps)) # Lower bounds of hyperparameters assert_true(np.all(gp.theta_ <= thetaU + eps)) # Upper bounds of hyperparameters def test_2d_2d(regr=regression.constant, corr=correlation.squared_exponential, random_start=10, beta0=None): # MLE estimation of a two-dimensional Gaussian Process model accounting for # anisotropy. Check random start optimization. # Test the GP interpolation for 2D output b, kappa, e = 5., .5, .1 g = lambda x: b - x[:, 1] - kappa * (x[:, 0] - e) ** 2. f = lambda x: np.vstack((g(x), g(x))).T X = np.array([[-4.61611719, -6.00099547], [4.10469096, 5.32782448], [0.00000000, -0.50000000], [-6.17289014, -4.6984743], [1.3109306, -6.93271427], [-5.03823144, 3.10584743], [-2.87600388, 6.74310541], [5.21301203, 4.26386883]]) y = f(X) gp = GaussianProcess(regr=regr, corr=corr, beta0=beta0, theta0=[1e-2] * 2, thetaL=[1e-4] * 2, thetaU=[1e-1] * 2, random_start=random_start, verbose=False) gp.fit(X, y) y_pred, MSE = gp.predict(X, eval_MSE=True) assert_true(np.allclose(y_pred, y) and np.allclose(MSE, 0.)) @raises(ValueError) def test_wrong_number_of_outputs(): gp = GaussianProcess() gp.fit([[1, 2, 3], [4, 5, 6]], [1, 2, 3]) def test_more_builtin_correlation_models(random_start=1): # Repeat test_1d and test_2d for several built-in correlation # models specified as strings. all_corr = ['absolute_exponential', 'squared_exponential', 'cubic', 'linear'] for corr in all_corr: test_1d(regr='constant', corr=corr, random_start=random_start) test_2d(regr='constant', corr=corr, random_start=random_start) test_2d_2d(regr='constant', corr=corr, random_start=random_start) def test_ordinary_kriging(): # Repeat test_1d and test_2d with given regression weights (beta0) for # different regression models (Ordinary Kriging). test_1d(regr='linear', beta0=[0., 0.5]) test_1d(regr='quadratic', beta0=[0., 0.5, 0.5]) test_2d(regr='linear', beta0=[0., 0.5, 0.5]) test_2d(regr='quadratic', beta0=[0., 0.5, 0.5, 0.5, 0.5, 0.5]) test_2d_2d(regr='linear', beta0=[0., 0.5, 0.5]) test_2d_2d(regr='quadratic', beta0=[0., 0.5, 0.5, 0.5, 0.5, 0.5]) def test_no_normalize(): gp = GaussianProcess(normalize=False).fit(X, y) y_pred = gp.predict(X) assert_true(np.allclose(y_pred, y)) def test_random_starts(): # Test that an increasing number of random-starts of GP fitting only # increases the reduced likelihood function of the optimal theta. n_samples, n_features = 50, 3 np.random.seed(0) rng = np.random.RandomState(0) X = rng.randn(n_samples, n_features) * 2 - 1 y = np.sin(X).sum(axis=1) + np.sin(3 * X).sum(axis=1) best_likelihood = -np.inf for random_start in range(1, 5): gp = GaussianProcess(regr="constant", corr="squared_exponential", theta0=[1e-0] * n_features, thetaL=[1e-4] * n_features, thetaU=[1e+1] * n_features, random_start=random_start, random_state=0, verbose=False).fit(X, y) rlf = gp.reduced_likelihood_function()[0] assert_greater(rlf, best_likelihood - np.finfo(np.float32).eps) best_likelihood = rlf def test_mse_solving(): # test the MSE estimate to be sane. # non-regression test for ignoring off-diagonals of feature covariance, # testing with nugget that renders covariance useless, only # using the mean function, with low effective rank of data gp = GaussianProcess(corr='absolute_exponential', theta0=1e-4, thetaL=1e-12, thetaU=1e-2, nugget=1e-2, optimizer='Welch', regr="linear", random_state=0) X, y = make_regression(n_informative=3, n_features=60, noise=50, random_state=0, effective_rank=1) gp.fit(X, y) assert_greater(1000, gp.predict(X, eval_MSE=True)[1].mean())
bsd-3-clause
kgullikson88/HET-Scripts
Search2.py
1
15434
from scipy.interpolate import InterpolatedUnivariateSpline as interp import os import sys import numpy as np import DataStructures import matplotlib.pyplot as plt import Correlate import FitsUtils import FindContinuum # import Units from astropy import units, constants import FittingUtilities homedir = os.environ["HOME"] modeldir = homedir + "/School/Research/Models/Sorted/Stellar/Vband/" #Define regions contaminated by telluric residuals or other defects. We will not use those regions in the cross-correlation badregions = [[588.8, 589.9], [627.1, 635.4]] badregions = [[0, 466], #badregions = [[0, 540], [567.5, 575.5], [587.5, 593], [627, 634.5], [686, 706], [716, 742], [759, 9e9]] #Set up model list model_list = [modeldir + "lte30-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte32-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte34-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte35-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte36-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte37-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte38-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte39-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte40-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte42-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte44-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte46-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte48-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte50-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte51-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte52-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte53-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte54-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte55-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte56-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte57-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte58-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte59-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte60-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte61-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte62-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte63-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte64-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte65-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte66-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte67-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte68-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte69-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte69-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte70-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte70-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte72-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte74-4.00-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte74-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte76-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte78-4.50-0.0.AGS.Cond.PHOENIX-ACES-2009.HighRes.7.sorted", modeldir + "lte30-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte30-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte31-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte31-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte32-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte32-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte33-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte33-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte34-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte34-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte35-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte35-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte36-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte36-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte37-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte37-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte38-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte38-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte39-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte39-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte40-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte40-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte41-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte41-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte42-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte42-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte43-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte43-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte44-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte44-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte45-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte45-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte46-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte46-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte47-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte47-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte48-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte48-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte49-4.0-0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte49-4.0+0.5.Cond.PHOENIX2004.tab.7.sorted", modeldir + "lte50-3.5-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte50-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte51-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte51-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte52-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte52-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte53-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte54-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte54-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte55-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte55-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte56-3.5-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte56-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte57-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte57-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte58-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte58-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte59-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte60-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte61-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte61-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte62-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte63-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte63-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte64-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte64-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte65-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte66-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte66-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte67-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte68-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte68-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte69-4.0-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte69-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte70-3.5-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte70-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte72-3.5-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte72-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte74-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte76-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte78-3.5-0.5.Cond.PHOENIX2004.direct.7.sorted", modeldir + "lte78-4.0+0.5.Cond.PHOENIX2004.direct.7.sorted"] star_list = [] temp_list = [] gravity_list = [] metal_list = [] model_data = [] for fname in model_list: if "PHOENIX2004" in fname: temp = int(fname.split("lte")[-1][:2]) * 100 gravity = float(fname.split("lte")[-1][3:6]) metallicity = float(fname.split("lte")[-1][6:10]) elif "PHOENIX-ACES" in fname: temp = int(fname.split("lte")[-1][:2]) * 100 gravity = float(fname.split("lte")[-1][3:7]) metallicity = float(fname.split("lte")[-1][7:11]) print "Reading in file %s" % fname x, y = np.loadtxt(fname, usecols=(0, 1), unpack=True) model_data.append(DataStructures.xypoint(x=x * units.angstrom.to(units.nm) / 1.00026, y=10 ** y)) star_list.append(str(temp)) temp_list.append(temp) gravity_list.append(gravity) metal_list.append(metallicity) if __name__ == "__main__": #Parse command line arguments: fileList = [] extensions = True tellurics = False trimsize = 100 smooth = False for arg in sys.argv[1:]: if "-e" in arg: extensions = False if "-t" in arg: tellurics = True #telluric lines modeled but not removed if "-s" in arg: smooth = True else: fileList.append(arg) for fname in fileList: if extensions: orders = FitsUtils.MakeXYpoints(fname, extensions=extensions, x="wavelength", y="flux", errors="error") if tellurics: model_orders = FitsUtils.MakeXYpoints(fname, extensions=extensions, x="wavelength", y="model") for i, order in enumerate(orders): orders[i].cont = FindContinuum.Continuum(order.x, order.y, lowreject=2, highreject=2) orders[i].y /= model_orders[i].y else: orders = FitsUtils.MakeXYpoints(fname, errors=2) numorders = len(orders) for i, order in enumerate(orders[::-1]): #Only use the middle half of each order (lots of noise on the edges) DATA = interp(order.x, order.y) CONT = interp(order.x, order.cont) ERROR = interp(order.x, order.err) left = int(order.size() / 4.0) right = int(order.size() * 3.0 / 4.0 + 0.5) order.x = np.linspace(order.x[left], order.x[right], right - left + 1) order.y = DATA(order.x) order.cont = CONT(order.x) order.err = ERROR(order.x) #Remove bad regions from the data for region in badregions: left = np.searchsorted(order.x, region[0]) right = np.searchsorted(order.x, region[1]) if left == 0 or right == order.size(): order.x = np.delete(order.x, np.arange(left, right)) order.y = np.delete(order.y, np.arange(left, right)) order.cont = np.delete(order.cont, np.arange(left, right)) order.err = np.delete(order.err, np.arange(left, right)) else: print "Warning! Bad region covers the middle of order %i" % i print "Interpolating rather than removing" order.y[left:right] = order.cont[left:right] order.err[left:right] = 9e9 #Remove whole order if it is too small remove = False if order.x.size <= 1: remove = True else: velrange = 3e5 * (np.median(order.x) - order.x[0]) / np.median(order.x) if velrange <= 1050.0: remove = True if remove: print "Removing order %i" % (numorders - 1 - i) orders.pop(numorders - 1 - i) else: order.cont = FittingUtilities.Continuum(order.x, order.y, lowreject=3, highreject=3) orders[numorders - 1 - i] = order.copy() """ for i, order in enumerate(orders): plt.plot(order.x, order.y/order.cont+i) plt.show() sys.exit() """ #Smooth data if smooth: for order in orders: order.y /= FittingUtilities.savitzky_golay(order.y, 91, 5) output_dir = "Cross_correlations/" outfilebase = fname.split(".fits")[0] if "/" in fname: dirs = fname.split("/") output_dir = "" outfilebase = dirs[-1].split(".fits")[0] for directory in dirs[:-1]: output_dir = output_dir + directory + "/" output_dir = output_dir + "Cross_correlations/" #Do the cross-correlation for vsini in [10, 20, 30, 40]: Correlate.PyCorr2(orders, resolution=60000, outdir=output_dir, models=model_data, stars=star_list, temps=temp_list, gravities=gravity_list, metallicities=metal_list, vsini=vsini * units.km.to(units.cm), debug=False, outfilebase=outfilebase)
gpl-3.0
yipenggao/moose
python/peacock/tests/postprocessor_tab/test_LineGroupWidgetPostprocessor.py
4
5988
#!/usr/bin/env python import sys import os import unittest import shutil from PyQt5 import QtCore, QtWidgets from peacock.PostprocessorViewer.PostprocessorDataWidget import PostprocessorDataWidget from peacock.PostprocessorViewer.plugins.LineGroupWidget import main from peacock.utils import Testing import mooseutils class TestLineGroupWidgetPostprocessor(Testing.PeacockImageTestCase): """ Test class for the ArtistToggleWidget which toggles postprocessor lines. """ #: QApplication: The main App for QT, this must be static to work correctly. qapp = QtWidgets.QApplication(sys.argv) def copyfiles(self): """ Copy the data file to a local temporary. """ src = os.path.abspath(os.path.join(__file__, '../../input/white_elephant_jan_2016.csv')) shutil.copyfile(src, self._filename) def create(self, timer=False): """ Creates the widgets for testing. This is done here rather than in setUp to allow for testing of delayed loading. """ self._reader = mooseutils.PostprocessorReader(self._filename) self._data = PostprocessorDataWidget(self._reader, timer=timer) # Build the widgets self._control, self._widget, self._window = main(self._data) self._widget.currentWidget().FigurePlugin.setFixedSize(QtCore.QSize(625, 625)) def setUp(self): """ Creates the GUI containing the ArtistGroupWidget and the matplotlib figure axes. """ self._filename = '{}_{}'.format(self.__class__.__name__, 'test.csv') def tearDown(self): """ Clean up. """ if os.path.exists(self._filename): os.remove(self._filename) def testEmpty(self): """ Test that an empty plot is possible. """ self.copyfiles() self.create() self.assertImage('testEmpty.png') # Test that controls are initialized and disabled correctly self.assertEqual(self._control.AxisVariable.currentText(), "time") self.assertFalse(self._control._toggles['time'].isEnabled(), "Time toggle should be disabled.") def testSelect(self): """ Test that selecting variables works. """ self.copyfiles() self.create() vars = ['air_temp_set_1', 'precip_accum_set_1'] for var in vars: self._control._toggles[var].CheckBox.setCheckState(QtCore.Qt.Checked) self._control._toggles[var].clicked.emit() self.assertImage('testSelect.png') self.assertEqual('; '.join(vars), self._window.axes()[0].get_yaxis().get_label().get_text()) self.assertEqual('time', self._window.axes()[0].get_xaxis().get_label().get_text()) # Switch axis self._control._toggles[vars[0]].PlotAxis.setCurrentIndex(1) self._control._toggles[vars[0]].clicked.emit() self.assertImage('testSelect2.png') self.assertEqual(vars[0], self._window.axes()[1].get_yaxis().get_label().get_text()) self.assertEqual(vars[1], self._window.axes()[0].get_yaxis().get_label().get_text()) self.assertEqual('time', self._window.axes()[0].get_xaxis().get_label().get_text()) def testChangePrimaryVariable(self): """ Test that the primary variable may be modified. """ self.copyfiles() self.create() # Plot something x_var = 'snow_water_equiv_set_1' y_var = 'precip_accum_set_1' self._control._toggles[y_var].CheckBox.setCheckState(QtCore.Qt.Checked) self._control._toggles[y_var].clicked.emit() self.assertImage('testChangePrimaryVariable0.png') # Change the primary variable self._control.AxisVariable.setCurrentIndex(5) self._control.AxisVariable.currentIndexChanged.emit(5) self.assertEqual(self._control.AxisVariable.currentText(), x_var) self.assertFalse(self._control._toggles[x_var].isEnabled(), "Toggle should be disabled.") self.assertTrue(self._control._toggles['time'].isEnabled(), "Toggle should be enabled.") self.assertImage('testChangePrimaryVariable1.png') def testDelayLoadAndUnload(self): """ Test that delayed loading and removal of files works. """ self.create() # Plot should be empty and the message should be visible. self.assertImage('testEmpty.png') self.assertTrue(self._control.NoDataMessage.isVisible()) # Load data self.copyfiles() self._data.load() self.assertFalse(self._control.NoDataMessage.isVisible()) # Plot something var = 'air_temp_set_1' self._control._toggles[var].CheckBox.setCheckState(QtCore.Qt.Checked) self._control._toggles[var].clicked.emit() self.assertImage('testDelayLoadPlot.png') # Remove data os.remove(self._filename) self._data.load() self.assertTrue(self._control.NoDataMessage.isVisible()) self.assertImage('testEmpty.png') # Re-load data self.copyfiles() self._data.load() self.assertFalse(self._control.NoDataMessage.isVisible()) self._control._toggles[var].CheckBox.setCheckState(QtCore.Qt.Checked) self._control._toggles[var].clicked.emit() self.assertImage('testDelayLoadPlot2.png', allowed=0.98) # The line color/style is different because the cycle keeps going def testRepr(self): """ Test script creation. """ self.copyfiles() self.create() var = 'air_temp_set_1' self._control._toggles[var].CheckBox.setCheckState(QtCore.Qt.Checked) self._control._toggles[var].clicked.emit() output, imports = self._control.repr() self.assertIn("x = data('time')", output) self.assertIn("y = data('air_temp_set_1')", output) if __name__ == '__main__': unittest.main(module=__name__, verbosity=2)
lgpl-2.1
bnaul/scikit-learn
sklearn/utils/tests/test_stats.py
14
2429
import numpy as np from numpy.testing import assert_allclose from pytest import approx from sklearn.utils.stats import _weighted_percentile def test_weighted_percentile(): y = np.empty(102, dtype=np.float64) y[:50] = 0 y[-51:] = 2 y[-1] = 100000 y[50] = 1 sw = np.ones(102, dtype=np.float64) sw[-1] = 0.0 score = _weighted_percentile(y, sw, 50) assert approx(score) == 1 def test_weighted_percentile_equal(): y = np.empty(102, dtype=np.float64) y.fill(0.0) sw = np.ones(102, dtype=np.float64) sw[-1] = 0.0 score = _weighted_percentile(y, sw, 50) assert score == 0 def test_weighted_percentile_zero_weight(): y = np.empty(102, dtype=np.float64) y.fill(1.0) sw = np.ones(102, dtype=np.float64) sw.fill(0.0) score = _weighted_percentile(y, sw, 50) assert approx(score) == 1.0 def test_weighted_median_equal_weights(): # Checks weighted percentile=0.5 is same as median when weights equal rng = np.random.RandomState(0) # Odd size as _weighted_percentile takes lower weighted percentile x = rng.randint(10, size=11) weights = np.ones(x.shape) median = np.median(x) w_median = _weighted_percentile(x, weights) assert median == approx(w_median) def test_weighted_median_integer_weights(): # Checks weighted percentile=0.5 is same as median when manually weight # data rng = np.random.RandomState(0) x = rng.randint(20, size=10) weights = rng.choice(5, size=10) x_manual = np.repeat(x, weights) median = np.median(x_manual) w_median = _weighted_percentile(x, weights) assert median == approx(w_median) def test_weighted_percentile_2d(): # Check for when array 2D and sample_weight 1D rng = np.random.RandomState(0) x1 = rng.randint(10, size=10) w1 = rng.choice(5, size=10) x2 = rng.randint(20, size=10) x_2d = np.vstack((x1, x2)).T w_median = _weighted_percentile(x_2d, w1) p_axis_0 = [ _weighted_percentile(x_2d[:, i], w1) for i in range(x_2d.shape[1]) ] assert_allclose(w_median, p_axis_0) # Check when array and sample_weight boht 2D w2 = rng.choice(5, size=10) w_2d = np.vstack((w1, w2)).T w_median = _weighted_percentile(x_2d, w_2d) p_axis_0 = [ _weighted_percentile(x_2d[:, i], w_2d[:, i]) for i in range(x_2d.shape[1]) ] assert_allclose(w_median, p_axis_0)
bsd-3-clause
KennyCandy/HAR
HAR_v1.py
1
14532
# Thanks to Zhao Yu for converting the .ipynb notebook to # this simplified Python script that I edited a little. # Note that the dataset must be already downloaded for this script to work, do: # $ cd data/ # $ python download_dataset.py import tensorflow as tf import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn import metrics import os if __name__ == "__main__": # ----------------------------- # step1: load and prepare data # ----------------------------- # Those are separate normalised input features for the neural network INPUT_SIGNAL_TYPES = [ "body_acc_x_", "body_acc_y_", "body_acc_z_", "body_gyro_x_", "body_gyro_y_", "body_gyro_z_", "total_acc_x_", "total_acc_y_", "total_acc_z_" ] # Output classes to learn how to classify LABELS = [ "WALKING", "WALKING_UPSTAIRS", "WALKING_DOWNSTAIRS", "SITTING", "STANDING", "LAYING" ] DATA_PATH = "data/" DATASET_PATH = DATA_PATH + "UCI HAR Dataset/" print("\n" + "Dataset is now located at: " + DATASET_PATH) # Preparing data set: TRAIN = "train/" TEST = "test/" # Load "X" (the neural network's training and testing inputs) def load_X(X_signals_paths): X_signals = [] for signal_type_path in X_signals_paths: file = open(signal_type_path, 'rb') # Read dataset from disk, dealing with text files' syntax X_signals.append( [np.array(serie, dtype=np.float32) for serie in [ row.replace(' ', ' ').strip().split(' ') for row in file ]] ) file.close() """Examples -------- >> > x = np.arange(4).reshape((2, 2)) >> > x array([[0, 1], [2, 3]]) >> > np.transpose(x) array([[0, 2], [1, 3]]) >> > x = np.ones((1, 2, 3)) >> > np.transpose(x, (1, 0, 2)).shape (2, 1, 3) """ return np.transpose(np.array(X_signals), (1, 2, 0)) X_train_signals_paths = [ DATASET_PATH + TRAIN + "Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES ] X_test_signals_paths = [ DATASET_PATH + TEST + "Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES ] X_train = load_X(X_train_signals_paths) # [7352, 128, 9] X_test = load_X(X_test_signals_paths) # [7352, 128, 9] # print(X_train) print(len(X_train)) # 7352 print(len(X_train[0])) # 128 print(len(X_train[0][0])) # 9 print(type(X_train)) X_train = np.reshape(X_train, [-1, 32, 36]) X_test = np.reshape(X_test, [-1, 32, 36]) print("-----------------X_train---------------") # print(X_train) print(len(X_train)) # 7352 print(len(X_train[0])) # 32 print(len(X_train[0][0])) # 36 print(type(X_train)) # exit() y_train_path = DATASET_PATH + TRAIN + "y_train.txt" y_test_path = DATASET_PATH + TEST + "y_test.txt" def one_hot(label): """convert label from dense to one hot argument: label: ndarray dense label ,shape: [sample_num,1] return: one_hot_label: ndarray one hot, shape: [sample_num,n_class] """ label_num = len(label) new_label = label.reshape(label_num) # shape : [sample_num] # because max is 5, and we will create 6 columns n_values = np.max(new_label) + 1 return np.eye(n_values)[np.array(new_label, dtype=np.int32)] # Load "y" (the neural network's training and testing outputs) def load_y(y_path): file = open(y_path, 'rb') # Read dataset from disk, dealing with text file's syntax y_ = np.array( [elem for elem in [ row.replace(' ', ' ').strip().split(' ') for row in file ]], dtype=np.int32 ) file.close() # Subtract 1 to each output class for friendly 0-based indexing return y_ - 1 y_train = one_hot(load_y(y_train_path)) y_test = one_hot(load_y(y_test_path)) print("---------y_train----------") # print(y_train) print(len(y_train)) # 7352 print(len(y_train[0])) # 6 # exit() # ----------------------------------- # step2: define parameters for model # ----------------------------------- class Config(object): """ define a class to store parameters, the input should be feature mat of training and testing """ def __init__(self, X_train, X_test): # Input data self.train_count = len(X_train) # 7352 training series self.test_data_count = len(X_test) # 2947 testing series self.n_steps = len(X_train[0]) # 128 time_steps per series # Training self.learning_rate = 0.0025 self.lambda_loss_amount = 0.0015 self.training_epochs = 300 self.batch_size = 700 # LSTM structure self.n_inputs = len(X_train[0][0]) # Features count is of 9: three 3D sensors features over time self.n_hidden = 32 # nb of neurons inside the neural network self.n_classes = 6 # Final output classes self.W = { 'hidden': tf.Variable(tf.random_normal([self.n_inputs, self.n_hidden])), # [9, 32] 'output': tf.Variable(tf.random_normal([self.n_hidden, self.n_classes])) # [32, 6] } self.biases = { 'hidden': tf.Variable(tf.random_normal([self.n_hidden], mean=1.0)), # [32] 'output': tf.Variable(tf.random_normal([self.n_classes])) # [6] } config = Config(X_train, X_test) # print("Some useful info to get an insight on dataset's shape and normalisation:") # print("features shape, labels shape, each features mean, each features standard deviation") # print(X_test.shape, y_test.shape, # np.mean(X_test), np.std(X_test)) # print("the dataset is therefore properly normalised, as expected.") # # # ------------------------------------------------------ # step3: Let's get serious and build the neural network # ------------------------------------------------------ # [none, 128, 9] X = tf.placeholder(tf.float32, [None, config.n_steps, config.n_inputs]) # [none, 6] Y = tf.placeholder(tf.float32, [None, config.n_classes]) print("-------X Y----------") print(X) X = tf.reshape(X, shape=[-1, 32, 36]) print(X) print(Y) Y = tf.reshape(Y, shape=[-1, 6]) print(Y) # Weight Initialization def weight_variable(shape): # tra ve 1 gia tri random theo thuat toan truncated_ normal initial = tf.truncated_normal(shape, mean=0.0, stddev=0.1, dtype=tf.float32) return tf.Variable(initial) def bias_varibale(shape): initial = tf.constant(0.1, shape=shape, name='Bias') return tf.Variable(initial) # Convolution and Pooling def conv2d(x, W): # Must have `strides[0] = strides[3] = 1 `. # For the most common case of the same horizontal and vertices strides, `strides = [1, stride, stride, 1] `. return tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME', name='conv_2d') def max_pool_2x2(x): return tf.nn.max_pool(value=x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='max_pool') def LSTM_Network(feature_mat, config): """model a LSTM Network, it stacks 2 LSTM layers, each layer has n_hidden=32 cells and 1 output layer, it is a full connet layer argument: feature_mat: ndarray feature matrix, shape=[batch_size,time_steps,n_inputs] config: class containing config of network return: : matrix output shape [batch_size,n_classes] """ W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_varibale([32]) # x_image = tf.reshape(x, shape=[-1, 28, 28, 1]) feature_mat_image = tf.reshape(feature_mat, shape=[-1, 32, 36, 1]) h_conv1 = tf.nn.relu(conv2d(feature_mat_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # Second Convolutional Layer W_conv2 = weight_variable([5, 5, 32, 1]) b_conv2 = weight_variable([1]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) h_pool2 = tf.reshape(h_pool2, shape=[-1, 8, 9]) feature_mat = h_pool2 # print("----h_pool2-----") # print(feature_mat) # exit() # W_fc1 = weight_variable([8 * 9 * 1, 1024]) # b_fc1 = bias_varibale([1024]) # h_pool2_flat = tf.reshape(h_pool2, [-1, 8 * 9 * 1]) # h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # print("----h_fc1_drop-----") # print(h_fc1) # exit() # # # keep_prob = tf.placeholder(tf.float32) # keep_prob = tf.placeholder(1.0) # h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob=keep_prob) # print("----h_fc1_drop-----") # print(h_fc1_drop) # exit() # # W_fc2 = weight_variable([1024, 10]) # b_fc2 = bias_varibale([10]) # # y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 # print("----y_conv-----") # print(y_conv) # exit() # Exchange dim 1 and dim 0 # Ban dau: [0,1,2] = [batch_size, 128, 9] => [batch_size, 32, 36] feature_mat = tf.transpose(feature_mat, [1, 0, 2]) # New feature_mat's shape: [time_steps, batch_size, n_inputs] [128, batch_size, 9] # Temporarily crush the feature_mat's dimensions feature_mat = tf.reshape(feature_mat, [-1, config.n_inputs]) # 9 # New feature_mat's shape: [time_steps*batch_size, n_inputs] # 128 * batch_size # Linear activation, reshaping inputs to the LSTM's number of hidden: hidden = tf.nn.relu(tf.matmul( feature_mat, config.W['hidden'] ) + config.biases['hidden']) # New feature_mat (hidden) shape: [time_steps*batch_size, n_hidden] [128*batch_size, 32] print("--n_steps--") print(config.n_steps) print("--n_steps--") print(hidden) exit() # Split the series because the rnn cell needs time_steps features, each of shape: hidden = tf.split(0, config.n_steps, hidden) # New hidden's shape: a list of length "time_step" containing tensors of shape [batch_size, n_hidden] # Define LSTM cell of first hidden layer: lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(config.n_hidden, forget_bias=1.0) # Stack two LSTM layers, both layers has the same shape lsmt_layers = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * 2) # Get LSTM outputs, the states are internal to the LSTM cells,they are not our attention here outputs, _ = tf.nn.rnn(lsmt_layers, hidden, dtype=tf.float32) # outputs' shape: a list of lenght "time_step" containing tensors of shape [batch_size, n_hidden] print("------------------list-------------------") print(outputs) # Get last time step's output feature for a "many to one" style classifier, # as in the image describing RNNs at the top of this page lstm_last_output = outputs[-1] # Chi lay phan tu cuoi cung voi shape: [?, 32] print("------------------last outputs-------------------") print (lstm_last_output) # Linear activation return tf.matmul(lstm_last_output, config.W['output']) + config.biases['output'] pred_Y = LSTM_Network(X, config) # shape[?,6] print("------------------pred_Y-------------------") print(pred_Y) # exit() # Loss,train_step,evaluation l2 = config.lambda_loss_amount * \ sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) # Softmax loss and L2 cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(pred_Y, Y)) + l2 train_step = tf.train.AdamOptimizer( learning_rate=config.learning_rate).minimize(cost) correct_prediction = tf.equal(tf.argmax(pred_Y, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32)) # -------------------------------------------- # step4: Hooray, now train the neural network # -------------------------------------------- # Note that log_device_placement can be turned ON but will cause console spam. sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=False)) tf.initialize_all_variables().run() best_accuracy = 0.0 # Start training for each batch and loop epochs for i in range(config.training_epochs): for start, end in zip(range(0, config.train_count, config.batch_size), # (0, 7352, 1500) range(config.batch_size, config.train_count + 1, config.batch_size)): # (1500, 7353, 1500) print(start) print(end) sess.run(train_step, feed_dict={X: X_train[start:end], Y: y_train[start:end]}) # Test completely at every epoch: calculate accuracy pred_out, accuracy_out, loss_out = sess.run([pred_Y, accuracy, cost], feed_dict={ X: X_test, Y: y_test}) print("traing iter: {},".format(i) + \ " test accuracy : {},".format(accuracy_out) + \ " loss : {}".format(loss_out)) best_accuracy = max(best_accuracy, accuracy_out) print("") print("final test accuracy: {}".format(accuracy_out)) print("best epoch's test accuracy: {}".format(best_accuracy)) print("") # # #------------------------------------------------------------------ # # step5: Training is good, but having visual insight is even better # #------------------------------------------------------------------ # # The code is in the .ipynb # # #------------------------------------------------------------------ # # step6: And finally, the multi-class confusion matrix and metrics! # #------------------------------------------------------------------ # # The code is in the .ipynb
mit
kvoyager/GmdhPy
examples/iris_recognition.py
1
3189
# -*- coding: utf-8 -*- from __future__ import print_function import pylab as plt import numpy as np # Import datasets, classifiers and performance metrics from sklearn import datasets, metrics from sklearn.metrics import confusion_matrix from gmdhpy.gmdh import Regressor from gmdhpy.plot_model import PlotModel def iris_class(value): if value > 1.5: return 2 elif value <= 1.5 and value >= 0.5: return 1 else: return 0 def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(iris.target_names)) plt.xticks(tick_marks, iris.target_names, rotation=45) plt.yticks(tick_marks, iris.target_names) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') if __name__ == '__main__': iris = datasets.load_iris() viris_class = np.vectorize(iris_class, otypes=[np.int]) n_samples = iris.data.shape[0] data = np.empty_like(iris.data) target = np.empty_like(iris.target) j = 0 n = n_samples // 3 for i in range(0, n): data[j] = iris.data[i] data[j+1] = iris.data[i+n] data[j+2] = iris.data[i+2*n] target[j] = iris.target[i] target[j+1] = iris.target[i+n] target[j+2] = iris.target[i+2*n] j += 3 train_data_is_the_first_half = False n = n_samples // 2 if train_data_is_the_first_half: train_x = data[:n] train_y = target[:n] test_x = data[n:] test_y = target[n:] else: train_x = data[n:] train_y = target[n:] test_x = data[:n] test_y = target[:n] model = Regressor(ref_functions='linear_cov', feature_names=iris.feature_names, criterion_minimum_width=5, stop_train_epsilon_condition=0.0001, l2=0.5, n_jobs=4) model.fit(train_x, train_y) # Now predict the value of the second half: # predict with GMDH model pred_y_row = model.predict(test_x) pred_y = viris_class(pred_y_row) print(model.get_selected_features_indices()) print(model.get_unselected_features_indices()) print("Selected features: {}".format(model.get_selected_features())) print("Unselected features: {}".format(model.get_unselected_features())) fig = plt.figure() # Compute confusion matrix cm = confusion_matrix(test_y, pred_y) np.set_printoptions(precision=2) print('Confusion matrix, without normalization') print(cm) ax1 = fig.add_subplot(121) plot_confusion_matrix(cm) # Normalize the confusion matrix by row (i.e by the number of samples # in each class) cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print('Normalized confusion matrix') print(cm_normalized) ax2 = fig.add_subplot(122) plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix') model.plot_layer_error() plt.show() PlotModel(model, filename='iris_model', plot_neuron_name=True, view=True).plot()
mit
odlgroup/odl
odl/util/graphics.py
2
16516
# Copyright 2014-2017 The ODL contributors # # This file is part of ODL. # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. """Functions for graphical output.""" from __future__ import print_function, division, absolute_import import numpy as np import warnings from odl.util.testutils import run_doctests from odl.util.utility import is_real_dtype __all__ = ('show_discrete_data',) def warning_free_pause(): """Issue a matplotlib pause without the warning.""" import matplotlib.pyplot as plt with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Using default event loop until " "function specific to this GUI is " "implemented") plt.pause(0.0001) def _safe_minmax(values): """Calculate min and max of array with guards for nan and inf.""" # Nan and inf guarded min and max isfinite = np.isfinite(values) if np.any(isfinite): # Only use finite values values = values[isfinite] minval = np.min(values) maxval = np.max(values) return minval, maxval def _colorbar_ticks(minval, maxval): """Return the ticks (values show) in the colorbar.""" if not (np.isfinite(minval) and np.isfinite(maxval)): return [0, 0, 0] elif minval == maxval: return [minval] else: # Add eps to ensure values stay inside the range of the colorbar. # Otherwise they may occationally not display. eps = (maxval - minval) / 1e5 return [minval + eps, (maxval + minval) / 2., maxval - eps] def _digits(minval, maxval): """Digits needed to comforatbly display values in [minval, maxval]""" if minval == maxval: return 3 else: return min(10, max(2, int(1 + abs(np.log10(maxval - minval))))) def _colorbar_format(minval, maxval): """Return the format string for the colorbar.""" if not (np.isfinite(minval) and np.isfinite(maxval)): return str(maxval) else: return '%.{}f'.format(_digits(minval, maxval)) def _axes_info(grid, npoints=5): result = [] min_pt = grid.min() max_pt = grid.max() for axis in range(grid.ndim): xmin = min_pt[axis] xmax = max_pt[axis] points = np.linspace(xmin, xmax, npoints) indices = np.linspace(0, grid.shape[axis] - 1, npoints, dtype=int) tick_values = grid.coord_vectors[axis][indices] # Do not use corner point in case of a partition, use outer corner tick_values[[0, -1]] = xmin, xmax format_str = '{:.' + str(_digits(xmin, xmax)) + 'f}' tick_labels = [format_str.format(f) for f in tick_values] result += [(points, tick_labels)] return result def show_discrete_data(values, grid, title=None, method='', force_show=False, fig=None, **kwargs): """Display a discrete 1d or 2d function. Parameters ---------- values : `numpy.ndarray` The values to visualize. grid : `RectGrid` or `RectPartition` Grid of the values. title : string, optional Set the title of the figure. method : string, optional 1d methods: 'plot' : graph plot 'scatter' : scattered 2d points (2nd axis <-> value) 2d methods: 'imshow' : image plot with coloring according to value, including a colorbar. 'scatter' : cloud of scattered 3d points (3rd axis <-> value) 'wireframe', 'plot_wireframe' : surface plot force_show : bool, optional Whether the plot should be forced to be shown now or deferred until later. Note that some backends always displays the plot, regardless of this value. fig : `matplotlib.figure.Figure`, optional The figure to show in. Expected to be of same "style", as the figure given by this function. The most common usecase is that fig is the return value from an earlier call to this function. Default: New figure interp : {'nearest', 'linear'}, optional Interpolation method to use. Default: 'nearest' axis_labels : string, optional Axis labels, default: ['x', 'y'] update_in_place : bool, optional Update the content of the figure in-place. Intended for faster real time plotting, typically ~5 times faster. This is only performed for ``method == 'imshow'`` with real data and ``fig != None``. Otherwise this parameter is treated as False. Default: False axis_fontsize : int, optional Fontsize for the axes. Default: 16 colorbar : bool, optional Argument relevant for 2d plots using ``method='imshow'``. If ``True``, include a colorbar in the plot. Default: True kwargs : {'figsize', 'saveto', ...}, optional Extra keyword arguments passed on to display method See the Matplotlib functions for documentation of extra options. Returns ------- fig : `matplotlib.figure.Figure` The resulting figure. It is also shown to the user. See Also -------- matplotlib.pyplot.plot : Show graph plot matplotlib.pyplot.imshow : Show data as image matplotlib.pyplot.scatter : Show scattered 3d points """ # Importing pyplot takes ~2 sec, only import when needed. import matplotlib.pyplot as plt args_re = [] args_im = [] dsp_kwargs = {} sub_kwargs = {} arrange_subplots = (121, 122) # horzontal arrangement # Create axis labels which remember their original meaning axis_labels = kwargs.pop('axis_labels', ['x', 'y']) values_are_complex = not is_real_dtype(values.dtype) figsize = kwargs.pop('figsize', None) saveto = kwargs.pop('saveto', None) interp = kwargs.pop('interp', 'nearest') axis_fontsize = kwargs.pop('axis_fontsize', 16) colorbar = kwargs.pop('colorbar', True) # Normalize input interp, interp_in = str(interp).lower(), interp method, method_in = str(method).lower(), method # Check if we should and can update the plot in-place update_in_place = kwargs.pop('update_in_place', False) if (update_in_place and (fig is None or values_are_complex or values.ndim != 2 or (values.ndim == 2 and method not in ('', 'imshow')))): update_in_place = False if values.ndim == 1: # TODO: maybe a plotter class would be better if not method: if interp == 'nearest': method = 'step' dsp_kwargs['where'] = 'mid' elif interp == 'linear': method = 'plot' else: raise ValueError('`interp` {!r} not supported' ''.format(interp_in)) if method == 'plot' or method == 'step' or method == 'scatter': args_re += [grid.coord_vectors[0], values.real] args_im += [grid.coord_vectors[0], values.imag] else: raise ValueError('`method` {!r} not supported' ''.format(method_in)) elif values.ndim == 2: if not method: method = 'imshow' if method == 'imshow': args_re = [np.rot90(values.real)] args_im = [np.rot90(values.imag)] if values_are_complex else [] extent = [grid.min()[0], grid.max()[0], grid.min()[1], grid.max()[1]] if interp == 'nearest': interpolation = 'nearest' elif interp == 'linear': interpolation = 'bilinear' else: raise ValueError('`interp` {!r} not supported' ''.format(interp_in)) dsp_kwargs.update({'interpolation': interpolation, 'cmap': 'bone', 'extent': extent, 'aspect': 'auto'}) elif method == 'scatter': pts = grid.points() args_re = [pts[:, 0], pts[:, 1], values.ravel().real] args_im = ([pts[:, 0], pts[:, 1], values.ravel().imag] if values_are_complex else []) sub_kwargs.update({'projection': '3d'}) elif method in ('wireframe', 'plot_wireframe'): method = 'plot_wireframe' x, y = grid.meshgrid args_re = [x, y, np.rot90(values.real)] args_im = ([x, y, np.rot90(values.imag)] if values_are_complex else []) sub_kwargs.update({'projection': '3d'}) else: raise ValueError('`method` {!r} not supported' ''.format(method_in)) else: raise NotImplementedError('no method for {}d display implemented' ''.format(values.ndim)) # Additional keyword args are passed on to the display method dsp_kwargs.update(**kwargs) if fig is not None: # Reuse figure if given as input if not isinstance(fig, plt.Figure): raise TypeError('`fig` {} not a matplotlib figure'.format(fig)) if not plt.fignum_exists(fig.number): # If figure does not exist, user either closed the figure or # is using IPython, in this case we need a new figure. fig = plt.figure(figsize=figsize) updatefig = False else: # Set current figure to given input fig = plt.figure(fig.number) updatefig = True if values.ndim > 1 and not update_in_place: # If the figure is larger than 1d, we can clear it since we # dont reuse anything. Keeping it causes performance problems. fig.clf() else: fig = plt.figure(figsize=figsize) updatefig = False if values_are_complex: # Real if len(fig.axes) == 0: # Create new axis if needed sub_re = plt.subplot(arrange_subplots[0], **sub_kwargs) sub_re.set_title('Real part') sub_re.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub_re.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub_re.set_ylabel('value') else: sub_re = fig.axes[0] display_re = getattr(sub_re, method) csub_re = display_re(*args_re, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and len(fig.axes) < 2: # Create colorbar if none seems to exist # Use clim from kwargs if given if 'clim' not in kwargs: minval_re, maxval_re = _safe_minmax(values.real) else: minval_re, maxval_re = kwargs['clim'] ticks_re = _colorbar_ticks(minval_re, maxval_re) fmt_re = _colorbar_format(minval_re, maxval_re) plt.colorbar(csub_re, orientation='horizontal', ticks=ticks_re, format=fmt_re) # Imaginary if len(fig.axes) < 3: sub_im = plt.subplot(arrange_subplots[1], **sub_kwargs) sub_im.set_title('Imaginary part') sub_im.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub_im.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub_im.set_ylabel('value') else: sub_im = fig.axes[2] display_im = getattr(sub_im, method) csub_im = display_im(*args_im, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and len(fig.axes) < 4: # Create colorbar if none seems to exist # Use clim from kwargs if given if 'clim' not in kwargs: minval_im, maxval_im = _safe_minmax(values.imag) else: minval_im, maxval_im = kwargs['clim'] ticks_im = _colorbar_ticks(minval_im, maxval_im) fmt_im = _colorbar_format(minval_im, maxval_im) plt.colorbar(csub_im, orientation='horizontal', ticks=ticks_im, format=fmt_im) else: if len(fig.axes) == 0: # Create new axis object if needed sub = plt.subplot(111, **sub_kwargs) sub.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub.set_ylabel('value') try: # For 3d plots sub.set_zlabel('z') except AttributeError: pass else: sub = fig.axes[0] if update_in_place: import matplotlib as mpl imgs = [obj for obj in sub.get_children() if isinstance(obj, mpl.image.AxesImage)] if len(imgs) > 0 and updatefig: imgs[0].set_data(args_re[0]) csub = imgs[0] # Update min-max if 'clim' not in kwargs: minval, maxval = _safe_minmax(values) else: minval, maxval = kwargs['clim'] csub.set_clim(minval, maxval) else: display = getattr(sub, method) csub = display(*args_re, **dsp_kwargs) else: display = getattr(sub, method) csub = display(*args_re, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and colorbar: # Add colorbar # Use clim from kwargs if given if 'clim' not in kwargs: minval, maxval = _safe_minmax(values) else: minval, maxval = kwargs['clim'] ticks = _colorbar_ticks(minval, maxval) fmt = _colorbar_format(minval, maxval) if len(fig.axes) < 2: # Create colorbar if none seems to exist plt.colorbar(mappable=csub, ticks=ticks, format=fmt) elif update_in_place: # If it exists and we should update it csub.colorbar.set_clim(minval, maxval) csub.colorbar.set_ticks(ticks) if '%' not in fmt: labels = [fmt] * len(ticks) else: labels = [fmt % t for t in ticks] csub.colorbar.set_ticklabels(labels) csub.colorbar.draw_all() # Set title of window if title is not None: if not values_are_complex: # Do not overwrite title for complex values plt.title(title) fig.canvas.manager.set_window_title(title) # Fixes overlapping stuff at the expense of potentially squashed subplots if not update_in_place: fig.tight_layout() if updatefig or plt.isinteractive(): # If we are running in interactive mode, we can always show the fig # This causes an artifact, where users of `CallbackShow` without # interactive mode only shows the figure after the second iteration. plt.show(block=False) if not update_in_place: plt.draw() warning_free_pause() else: try: sub.draw_artist(csub) fig.canvas.blit(fig.bbox) fig.canvas.update() fig.canvas.flush_events() except AttributeError: plt.draw() warning_free_pause() if force_show: plt.show() if saveto is not None: fig.savefig(saveto) return fig if __name__ == '__main__': run_doctests()
mpl-2.0
adamrvfisher/TechnicalAnalysisLibrary
DefNormChaikinStratOpt.py
1
4250
# -*- coding: utf-8 -*- """ Created on Tue Apr 4 11:01:58 2017 @author: AmatVictoriaCuramIII """ def DefNormChaikinStratOpt(ticker,start,end): import numpy as np from pandas_datareader import data import random as rand import pandas as pd empty = [] #reusable list #set up desired number of datasets for different period analysis dataset = pd.DataFrame() iterations = range(0,1000) ticker = '^GSPC' s = data.DataReader(ticker, 'yahoo', start=start, end=end) s['LogRet'] = np.log(s['Adj Close']/s['Adj Close'].shift(1)) s['LogRet'] = s['LogRet'].fillna(0) s['CLV'] = (((s['Adj Close'] - s['Low']) - (s['High'] - s['Adj Close'])) / (s['High'] - s['Low'])) s['ADI'] = (s['Volume'] * s['CLV']).cumsum() for x in iterations: aa = rand.randint(1,30) bb = rand.randint(2,60) if aa > bb: continue c = rand.randint(2,60) d = 5.5 - rand.random() * 7 e = 5.5 - rand.random() * 7 f = 5.5 - rand.random() * 7 g = 5.5 - rand.random() * 7 a = aa #number of days for moving average window b = bb #numer of days for moving average window values = s['ADI'] weights = np.repeat(1.0, a)/a weights2 = np.repeat(1.0, b)/b smas = np.convolve(values, weights, 'valid') smas2 = np.convolve(values, weights2, 'valid') trim = len(s) - len(smas2) trim2 = len(smas) - len(smas2) replace = s[:trim] s = s[trim:] smas = smas[trim2:] s['ADIEMAsmall'] = smas s['ADIEMAlarge'] = smas2 s = replace.append(s) volumewindow = c s.loc[:,'AverageRollingVolume'] = s['Volume'].rolling(center=False, window=volumewindow).mean() s.loc[:,'Chaikin'] = s['ADIEMAsmall'] - s['ADIEMAlarge'] s.loc[:,'NormChaikin'] = s['Chaikin']/s['AverageRollingVolume'] kk = s[:volumewindow-1] s = s[volumewindow-1:] s.loc[:,'Touch'] = np.where(s['NormChaikin'] < d, 1,0) #long signal s.loc[:,'Touch'] = np.where(s['NormChaikin'] > e, -1, s['Touch']) #short signal s.loc[:,'Sustain'] = np.where(s['Touch'].shift(1) == 1, 1, 0) # never actually true when optimized s.loc[:,'Sustain'] = np.where(s['Sustain'].shift(1) == 1, 1, s['Sustain']) s.loc[:,'Sustain'] = np.where(s['Touch'].shift(1) == -1, -1, 0) #true when previous day touch is -1, and current RSI is > line 37 threshold s.loc[:,'Sustain'] = np.where(s['Sustain'].shift(1) == -1, -1, s['Sustain']) s.loc[:,'Sustain'] = np.where(s['NormChaikin'] > f, 0, s['Sustain']) #if RSI is greater than threshold, sustain is forced to 0 s.loc[:,'Sustain'] = np.where(s['NormChaikin'] < g, 0, s['Sustain']) #never actually true when optimized s.loc[:,'Regime'] = s['Touch'] + s['Sustain'] s.loc[:,'Strategy'] = (s['Regime']).shift(1)*s['LogRet'] s.loc[:,'Strategy'] = s['Strategy'].fillna(0) s = kk.append(s) if s['Strategy'].std() == 0: continue sharpe = (s['Strategy'].mean()-s['LogRet'].mean())/s['Strategy'].std() if np.isnan(sharpe) == True: continue if sharpe < 0.001: continue empty.append(a) empty.append(b) empty.append(c) empty.append(d) empty.append(e) empty.append(f) empty.append(g) empty.append(sharpe) emptyseries = pd.Series(empty) dataset[x] = emptyseries.values empty[:] = [] z1 = dataset.iloc[7] w1 = np.percentile(z1, 70) v1 = [] #this variable stores the Nth percentile of top performers DS1W = pd.DataFrame() #this variable stores your financial advisors for specific dataset for h in z1: if h > w1: v1.append(h) for j in v1: r = dataset.columns[(dataset == j).iloc[7]] DS1W = pd.concat([DS1W,dataset[r]], axis = 1) return DS1W
apache-2.0
pradyu1993/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
3
14807
""" Testing for the gradient boosting module (sklearn.ensemble.gradient_boosting). """ import numpy as np from numpy.testing import assert_array_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_equal from nose.tools import assert_raises from sklearn.metrics import mean_squared_error from sklearn.utils import check_random_state from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import GradientBoostingRegressor from sklearn import datasets # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [-1, -1, -1, 1, 1, 1] T = [[-1, -1], [2, 2], [3, 2]] true_result = [-1, 1, 1] rng = np.random.RandomState(0) # also load the boston dataset # and randomly permute it boston = datasets.load_boston() perm = rng.permutation(boston.target.size) boston.data = boston.data[perm] boston.target = boston.target[perm] # also load the iris dataset # and randomly permute it iris = datasets.load_iris() perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] def test_classification_toy(): """Check classification on a toy dataset.""" clf = GradientBoostingClassifier(n_estimators=100, random_state=1) assert_raises(ValueError, clf.predict, T) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) deviance_decrease = (clf.train_score_[:-1] - clf.train_score_[1:]) assert np.any(deviance_decrease >= 0.0), \ "Train deviance does not monotonically decrease." def test_parameter_checks(): """Check input parameter validation.""" assert_raises(ValueError, GradientBoostingClassifier, n_estimators=0) assert_raises(ValueError, GradientBoostingClassifier, n_estimators=-1) assert_raises(ValueError, GradientBoostingClassifier, learn_rate=0.0) assert_raises(ValueError, GradientBoostingClassifier, learn_rate=-1.0) assert_raises(ValueError, GradientBoostingRegressor, loss='foobar') assert_raises(ValueError, GradientBoostingClassifier, min_samples_split=0.0) assert_raises(ValueError, GradientBoostingClassifier, min_samples_split=-1.0) assert_raises(ValueError, GradientBoostingClassifier, min_samples_leaf=0) assert_raises(ValueError, GradientBoostingClassifier, min_samples_leaf=-1.) assert_raises(ValueError, GradientBoostingClassifier, subsample=0.0) assert_raises(ValueError, GradientBoostingClassifier, subsample=1.1) assert_raises(ValueError, GradientBoostingClassifier, subsample=-0.1) assert_raises(ValueError, GradientBoostingClassifier, max_depth=-0.1) assert_raises(ValueError, GradientBoostingClassifier, max_depth=0) assert_raises(ValueError, GradientBoostingClassifier, init={}) # test fit before feature importance assert_raises(ValueError, lambda: GradientBoostingClassifier().feature_importances_) # binomial deviance requires ``n_classes == 2``. assert_raises(ValueError, lambda X, y: GradientBoostingClassifier( loss='bdeviance').fit(X, y), X, [0, 0, 1, 1, 2, 2]) # multinomial deviance requires ``n_classes > 2``. assert_raises(ValueError, lambda X, y: GradientBoostingClassifier( loss='mdeviance').fit(X, y), X, [0, 0, 1, 1, 1, 0]) # deviance requires ``n_classes >= 2``. assert_raises(ValueError, lambda X, y: GradientBoostingClassifier( loss='deviance').fit(X, y), X, [0, 0, 0, 0]) def test_classification_synthetic(): """Test GradientBoostingClassifier on synthetic dataset used by Hastie et al. in ESLII Example 12.7. """ X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1) X_train, X_test = X[:2000], X[2000:] y_train, y_test = y[:2000], y[2000:] gbrt = GradientBoostingClassifier(n_estimators=100, min_samples_split=1, max_depth=1, learn_rate=1.0, random_state=0) gbrt.fit(X_train, y_train) error_rate = (1.0 - gbrt.score(X_test, y_test)) assert error_rate < 0.085, \ "GB failed with error %.4f" % error_rate gbrt = GradientBoostingClassifier(n_estimators=200, min_samples_split=1, max_depth=1, learn_rate=1.0, subsample=0.5, random_state=0) gbrt.fit(X_train, y_train) error_rate = (1.0 - gbrt.score(X_test, y_test)) assert error_rate < 0.08, \ "Stochastic GB failed with error %.4f" % error_rate def test_boston(): """Check consistency on dataset boston house prices with least squares and least absolute deviation. """ for loss in ("ls", "lad", "huber"): clf = GradientBoostingRegressor(n_estimators=100, loss=loss, max_depth=4, min_samples_split=1, random_state=1) assert_raises(ValueError, clf.predict, boston.data) clf.fit(boston.data, boston.target) y_pred = clf.predict(boston.data) mse = mean_squared_error(boston.target, y_pred) assert mse < 6.0, "Failed with loss %s and mse = %.4f" % (loss, mse) def test_iris(): """Check consistency on dataset iris.""" for subsample in (1.0, 0.5): clf = GradientBoostingClassifier(n_estimators=100, loss='deviance', random_state=1, subsample=subsample) clf.fit(iris.data, iris.target) score = clf.score(iris.data, iris.target) assert score > 0.9, "Failed with subsample %.1f " \ "and score = %f" % (subsample, score) def test_regression_synthetic(): """Test on synthetic regression datasets used in Leo Breiman, `Bagging Predictors?. Machine Learning 24(2): 123-140 (1996). """ random_state = check_random_state(1) regression_params = {'n_estimators': 100, 'max_depth': 4, 'min_samples_split': 1, 'learn_rate': 0.1, 'loss': 'ls'} # Friedman1 X, y = datasets.make_friedman1(n_samples=1200, random_state=random_state, noise=1.0) X_train, y_train = X[:200], y[:200] X_test, y_test = X[200:], y[200:] clf = GradientBoostingRegressor() clf.fit(X_train, y_train) mse = mean_squared_error(y_test, clf.predict(X_test)) assert mse < 5.0, "Failed on Friedman1 with mse = %.4f" % mse # Friedman2 X, y = datasets.make_friedman2(n_samples=1200, random_state=random_state) X_train, y_train = X[:200], y[:200] X_test, y_test = X[200:], y[200:] clf = GradientBoostingRegressor(**regression_params) clf.fit(X_train, y_train) mse = mean_squared_error(y_test, clf.predict(X_test)) assert mse < 1700.0, "Failed on Friedman2 with mse = %.4f" % mse # Friedman3 X, y = datasets.make_friedman3(n_samples=1200, random_state=random_state) X_train, y_train = X[:200], y[:200] X_test, y_test = X[200:], y[200:] clf = GradientBoostingRegressor(**regression_params) clf.fit(X_train, y_train) mse = mean_squared_error(y_test, clf.predict(X_test)) assert mse < 0.015, "Failed on Friedman3 with mse = %.4f" % mse # def test_feature_importances(): # X = np.array(boston.data, dtype=np.float32) # y = np.array(boston.target, dtype=np.float32) # clf = GradientBoostingRegressor(n_estimators=100, max_depth=5, # min_samples_split=1, random_state=1) # clf.fit(X, y) # feature_importances = clf.feature_importances_ # # true feature importance ranking # true_ranking = np.array([3, 1, 8, 2, 10, 9, 4, 11, 0, 6, 7, 5, 12]) # assert_array_equal(true_ranking, feature_importances.argsort()) def test_probability(): """Predict probabilities.""" clf = GradientBoostingClassifier(n_estimators=100, random_state=1) assert_raises(ValueError, clf.predict_proba, T) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) # check if probabilities are in [0, 1]. y_proba = clf.predict_proba(T) assert np.all(y_proba >= 0.0) assert np.all(y_proba <= 1.0) # derive predictions from probabilities y_pred = clf.classes_.take(y_proba.argmax(axis=1), axis=0) assert_array_equal(y_pred, true_result) def test_check_inputs(): """Test input checks (shape and type of X and y).""" clf = GradientBoostingClassifier(n_estimators=100, random_state=1) assert_raises(ValueError, clf.fit, X, y + [0, 1]) from scipy import sparse X_sparse = sparse.csr_matrix(X) clf = GradientBoostingClassifier(n_estimators=100, random_state=1) assert_raises(TypeError, clf.fit, X_sparse, y) clf = GradientBoostingClassifier().fit(X, y) assert_raises(TypeError, clf.predict, X_sparse) def test_check_inputs_predict(): """X has wrong shape """ clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X, y) x = np.array([1.0, 2.0])[:, np.newaxis] assert_raises(ValueError, clf.predict, x) x = np.array([]) assert_raises(ValueError, clf.predict, x) x = np.array([1.0, 2.0, 3.0])[:, np.newaxis] assert_raises(ValueError, clf.predict, x) clf = GradientBoostingRegressor(n_estimators=100, random_state=1) clf.fit(X, rng.rand(len(X))) x = np.array([1.0, 2.0])[:, np.newaxis] assert_raises(ValueError, clf.predict, x) x = np.array([]) assert_raises(ValueError, clf.predict, x) x = np.array([1.0, 2.0, 3.0])[:, np.newaxis] assert_raises(ValueError, clf.predict, x) def test_check_max_features(): """test if max_features is valid. """ clf = GradientBoostingRegressor(n_estimators=100, random_state=1, max_features=0) assert_raises(ValueError, clf.fit, X, y) clf = GradientBoostingRegressor(n_estimators=100, random_state=1, max_features=(len(X[0]) + 1)) assert_raises(ValueError, clf.fit, X, y) def test_staged_predict(): """Test whether staged decision function eventually gives the same prediction. """ X, y = datasets.make_friedman1(n_samples=1200, random_state=1, noise=1.0) X_train, y_train = X[:200], y[:200] X_test, y_test = X[200:], y[200:] clf = GradientBoostingRegressor() # test raise ValueError if not fitted assert_raises(ValueError, lambda X: np.fromiter( clf.staged_predict(X), dtype=np.float64), X_test) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) # test if prediction for last stage equals ``predict`` for y in clf.staged_predict(X_test): assert_equal(y.shape, y_pred.shape) assert_array_equal(y_pred, y) def test_serialization(): """Check model serialization.""" clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) try: import cPickle as pickle except ImportError: import pickle serialized_clf = pickle.dumps(clf, protocol=pickle.HIGHEST_PROTOCOL) clf = None clf = pickle.loads(serialized_clf) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) def test_degenerate_targets(): """Check if we can fit even though all targets are equal. """ clf = GradientBoostingClassifier(n_estimators=100, random_state=1) # classifier should raise exception assert_raises(ValueError, clf.fit, X, np.ones(len(X))) clf = GradientBoostingRegressor(n_estimators=100, random_state=1) clf.fit(X, np.ones(len(X))) clf.predict(rng.rand(2)) assert_array_equal(np.ones((1,), dtype=np.float64), clf.predict(rng.rand(2))) def test_quantile_loss(): """Check if quantile loss with alpha=0.5 equals lad. """ clf_quantile = GradientBoostingRegressor(n_estimators=100, loss='quantile', max_depth=4, alpha=0.5, random_state=7) clf_quantile.fit(boston.data, boston.target) y_quantile = clf_quantile.predict(boston.data) clf_lad = GradientBoostingRegressor(n_estimators=100, loss='lad', max_depth=4, random_state=7) clf_lad.fit(boston.data, boston.target) y_lad = clf_lad.predict(boston.data) assert_array_almost_equal(y_quantile, y_lad, decimal=4) def test_symbol_labels(): """Test with non-integer class labels. """ clf = GradientBoostingClassifier(n_estimators=100, random_state=1) symbol_y = map(str, y) clf.fit(X, symbol_y) assert_array_equal(clf.predict(T), map(str, true_result)) assert_equal(100, len(clf.estimators_)) def test_float_class_labels(): """Test with float class labels. """ clf = GradientBoostingClassifier(n_estimators=100, random_state=1) float_y = np.asarray(y, dtype=np.float32) clf.fit(X, float_y) assert_array_equal(clf.predict(T), np.asarray(true_result, dtype=np.float32)) assert_equal(100, len(clf.estimators_)) def test_shape_y(): """Test with float class labels. """ clf = GradientBoostingClassifier(n_estimators=100, random_state=1) y_ = np.asarray(y, dtype=np.int32) y_ = y_[:, np.newaxis] clf.fit(X, y_) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) def test_mem_layout(): """Test with different memory layouts of X and y""" X_ = np.asfortranarray(X) clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X_, y) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) X_ = np.ascontiguousarray(X) clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X_, y) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) y_ = np.asarray(y, dtype=np.int32) y_ = y_[:, np.newaxis] y_ = np.ascontiguousarray(y_) clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X, y_) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) y_ = np.asarray(y, dtype=np.int32) y_ = y_[:, np.newaxis] y_ = np.asfortranarray(y_) clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X, y_) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_))
bsd-3-clause
louispotok/pandas
pandas/core/accessor.py
4
7483
# -*- coding: utf-8 -*- """ accessor.py contains base classes for implementing accessor properties that can be mixed into or pinned onto other pandas classes. """ import warnings from pandas.util._decorators import Appender class DirNamesMixin(object): _accessors = frozenset([]) _deprecations = frozenset( ['asobject', 'base', 'data', 'flags', 'itemsize', 'strides']) def _dir_deletions(self): """ delete unwanted __dir__ for this object """ return self._accessors | self._deprecations def _dir_additions(self): """ add additional __dir__ for this object """ rv = set() for accessor in self._accessors: try: getattr(self, accessor) rv.add(accessor) except AttributeError: pass return rv def __dir__(self): """ Provide method name lookup and completion Only provide 'public' methods """ rv = set(dir(type(self))) rv = (rv - self._dir_deletions()) | self._dir_additions() return sorted(rv) class PandasDelegate(object): """ an abstract base class for delegating methods/properties """ def _delegate_property_get(self, name, *args, **kwargs): raise TypeError("You cannot access the " "property {name}".format(name=name)) def _delegate_property_set(self, name, value, *args, **kwargs): raise TypeError("The property {name} cannot be set".format(name=name)) def _delegate_method(self, name, *args, **kwargs): raise TypeError("You cannot call method {name}".format(name=name)) @classmethod def _add_delegate_accessors(cls, delegate, accessors, typ, overwrite=False): """ add accessors to cls from the delegate class Parameters ---------- cls : the class to add the methods/properties to delegate : the class to get methods/properties & doc-strings acccessors : string list of accessors to add typ : 'property' or 'method' overwrite : boolean, default False overwrite the method/property in the target class if it exists """ def _create_delegator_property(name): def _getter(self): return self._delegate_property_get(name) def _setter(self, new_values): return self._delegate_property_set(name, new_values) _getter.__name__ = name _setter.__name__ = name return property(fget=_getter, fset=_setter, doc=getattr(delegate, name).__doc__) def _create_delegator_method(name): def f(self, *args, **kwargs): return self._delegate_method(name, *args, **kwargs) f.__name__ = name f.__doc__ = getattr(delegate, name).__doc__ return f for name in accessors: if typ == 'property': f = _create_delegator_property(name) else: f = _create_delegator_method(name) # don't overwrite existing methods/properties if overwrite or not hasattr(cls, name): setattr(cls, name, f) # Ported with modifications from xarray # https://github.com/pydata/xarray/blob/master/xarray/core/extensions.py # 1. We don't need to catch and re-raise AttributeErrors as RuntimeErrors # 2. We use a UserWarning instead of a custom Warning class CachedAccessor(object): """Custom property-like object (descriptor) for caching accessors. Parameters ---------- name : str The namespace this will be accessed under, e.g. ``df.foo`` accessor : cls The class with the extension methods. The class' __init__ method should expect one of a ``Series``, ``DataFrame`` or ``Index`` as the single argument ``data`` """ def __init__(self, name, accessor): self._name = name self._accessor = accessor def __get__(self, obj, cls): if obj is None: # we're accessing the attribute of the class, i.e., Dataset.geo return self._accessor accessor_obj = self._accessor(obj) # Replace the property with the accessor object. Inspired by: # http://www.pydanny.com/cached-property.html # We need to use object.__setattr__ because we overwrite __setattr__ on # NDFrame object.__setattr__(obj, self._name, accessor_obj) return accessor_obj def _register_accessor(name, cls): def decorator(accessor): if hasattr(cls, name): warnings.warn( 'registration of accessor {!r} under name {!r} for type ' '{!r} is overriding a preexisting attribute with the same ' 'name.'.format(accessor, name, cls), UserWarning, stacklevel=2) setattr(cls, name, CachedAccessor(name, accessor)) cls._accessors.add(name) return accessor return decorator _doc = """Register a custom accessor on %(klass)s objects. Parameters ---------- name : str Name under which the accessor should be registered. A warning is issued if this name conflicts with a preexisting attribute. Notes ----- When accessed, your accessor will be initialized with the pandas object the user is interacting with. So the signature must be .. code-block:: python def __init__(self, pandas_object): For consistency with pandas methods, you should raise an ``AttributeError`` if the data passed to your accessor has an incorrect dtype. >>> pd.Series(['a', 'b']).dt Traceback (most recent call last): ... AttributeError: Can only use .dt accessor with datetimelike values Examples -------- In your library code:: import pandas as pd @pd.api.extensions.register_dataframe_accessor("geo") class GeoAccessor(object): def __init__(self, pandas_obj): self._obj = pandas_obj @property def center(self): # return the geographic center point of this DataFrame lat = self._obj.latitude lon = self._obj.longitude return (float(lon.mean()), float(lat.mean())) def plot(self): # plot this array's data on a map, e.g., using Cartopy pass Back in an interactive IPython session: >>> ds = pd.DataFrame({'longitude': np.linspace(0, 10), ... 'latitude': np.linspace(0, 20)}) >>> ds.geo.center (5.0, 10.0) >>> ds.geo.plot() # plots data on a map See also -------- %(others)s """ @Appender(_doc % dict(klass="DataFrame", others=("register_series_accessor, " "register_index_accessor"))) def register_dataframe_accessor(name): from pandas import DataFrame return _register_accessor(name, DataFrame) @Appender(_doc % dict(klass="Series", others=("register_dataframe_accessor, " "register_index_accessor"))) def register_series_accessor(name): from pandas import Series return _register_accessor(name, Series) @Appender(_doc % dict(klass="Index", others=("register_dataframe_accessor, " "register_series_accessor"))) def register_index_accessor(name): from pandas import Index return _register_accessor(name, Index)
bsd-3-clause
newemailjdm/scipy
scipy/stats/kde.py
27
17303
#------------------------------------------------------------------------------- # # Define classes for (uni/multi)-variate kernel density estimation. # # Currently, only Gaussian kernels are implemented. # # Written by: Robert Kern # # Date: 2004-08-09 # # Modified: 2005-02-10 by Robert Kern. # Contributed to Scipy # 2005-10-07 by Robert Kern. # Some fixes to match the new scipy_core # # Copyright 2004-2005 by Enthought, Inc. # #------------------------------------------------------------------------------- from __future__ import division, print_function, absolute_import # Standard library imports. import warnings # Scipy imports. from scipy._lib.six import callable, string_types from scipy import linalg, special from numpy import atleast_2d, reshape, zeros, newaxis, dot, exp, pi, sqrt, \ ravel, power, atleast_1d, squeeze, sum, transpose import numpy as np from numpy.random import randint, multivariate_normal # Local imports. from . import mvn __all__ = ['gaussian_kde'] class gaussian_kde(object): """Representation of a kernel-density estimate using Gaussian kernels. Kernel density estimation is a way to estimate the probability density function (PDF) of a random variable in a non-parametric way. `gaussian_kde` works for both uni-variate and multi-variate data. It includes automatic bandwidth determination. The estimation works best for a unimodal distribution; bimodal or multi-modal distributions tend to be oversmoothed. Parameters ---------- dataset : array_like Datapoints to estimate from. In case of univariate data this is a 1-D array, otherwise a 2-D array with shape (# of dims, # of data). bw_method : str, scalar or callable, optional The method used to calculate the estimator bandwidth. This can be 'scott', 'silverman', a scalar constant or a callable. If a scalar, this will be used directly as `kde.factor`. If a callable, it should take a `gaussian_kde` instance as only parameter and return a scalar. If None (default), 'scott' is used. See Notes for more details. Attributes ---------- dataset : ndarray The dataset with which `gaussian_kde` was initialized. d : int Number of dimensions. n : int Number of datapoints. factor : float The bandwidth factor, obtained from `kde.covariance_factor`, with which the covariance matrix is multiplied. covariance : ndarray The covariance matrix of `dataset`, scaled by the calculated bandwidth (`kde.factor`). inv_cov : ndarray The inverse of `covariance`. Methods ------- evaluate __call__ integrate_gaussian integrate_box_1d integrate_box integrate_kde pdf logpdf resample set_bandwidth covariance_factor Notes ----- Bandwidth selection strongly influences the estimate obtained from the KDE (much more so than the actual shape of the kernel). Bandwidth selection can be done by a "rule of thumb", by cross-validation, by "plug-in methods" or by other means; see [3]_, [4]_ for reviews. `gaussian_kde` uses a rule of thumb, the default is Scott's Rule. Scott's Rule [1]_, implemented as `scotts_factor`, is:: n**(-1./(d+4)), with ``n`` the number of data points and ``d`` the number of dimensions. Silverman's Rule [2]_, implemented as `silverman_factor`, is:: (n * (d + 2) / 4.)**(-1. / (d + 4)). Good general descriptions of kernel density estimation can be found in [1]_ and [2]_, the mathematics for this multi-dimensional implementation can be found in [1]_. References ---------- .. [1] D.W. Scott, "Multivariate Density Estimation: Theory, Practice, and Visualization", John Wiley & Sons, New York, Chicester, 1992. .. [2] B.W. Silverman, "Density Estimation for Statistics and Data Analysis", Vol. 26, Monographs on Statistics and Applied Probability, Chapman and Hall, London, 1986. .. [3] B.A. Turlach, "Bandwidth Selection in Kernel Density Estimation: A Review", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993. .. [4] D.M. Bashtannyk and R.J. Hyndman, "Bandwidth selection for kernel conditional density estimation", Computational Statistics & Data Analysis, Vol. 36, pp. 279-298, 2001. Examples -------- Generate some random two-dimensional data: >>> from scipy import stats >>> def measure(n): ... "Measurement model, return two coupled measurements." ... m1 = np.random.normal(size=n) ... m2 = np.random.normal(scale=0.5, size=n) ... return m1+m2, m1-m2 >>> m1, m2 = measure(2000) >>> xmin = m1.min() >>> xmax = m1.max() >>> ymin = m2.min() >>> ymax = m2.max() Perform a kernel density estimate on the data: >>> X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] >>> positions = np.vstack([X.ravel(), Y.ravel()]) >>> values = np.vstack([m1, m2]) >>> kernel = stats.gaussian_kde(values) >>> Z = np.reshape(kernel(positions).T, X.shape) Plot the results: >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r, ... extent=[xmin, xmax, ymin, ymax]) >>> ax.plot(m1, m2, 'k.', markersize=2) >>> ax.set_xlim([xmin, xmax]) >>> ax.set_ylim([ymin, ymax]) >>> plt.show() """ def __init__(self, dataset, bw_method=None): self.dataset = atleast_2d(dataset) if not self.dataset.size > 1: raise ValueError("`dataset` input should have multiple elements.") self.d, self.n = self.dataset.shape self.set_bandwidth(bw_method=bw_method) def evaluate(self, points): """Evaluate the estimated pdf on a set of points. Parameters ---------- points : (# of dimensions, # of points)-array Alternatively, a (# of dimensions,) vector can be passed in and treated as a single point. Returns ------- values : (# of points,)-array The values at each point. Raises ------ ValueError : if the dimensionality of the input points is different than the dimensionality of the KDE. """ points = atleast_2d(points) d, m = points.shape if d != self.d: if d == 1 and m == self.d: # points was passed in as a row vector points = reshape(points, (self.d, 1)) m = 1 else: msg = "points have dimension %s, dataset has dimension %s" % (d, self.d) raise ValueError(msg) result = zeros((m,), dtype=float) if m >= self.n: # there are more points than data, so loop over data for i in range(self.n): diff = self.dataset[:, i, newaxis] - points tdiff = dot(self.inv_cov, diff) energy = sum(diff*tdiff,axis=0) / 2.0 result = result + exp(-energy) else: # loop over points for i in range(m): diff = self.dataset - points[:, i, newaxis] tdiff = dot(self.inv_cov, diff) energy = sum(diff * tdiff, axis=0) / 2.0 result[i] = sum(exp(-energy), axis=0) result = result / self._norm_factor return result __call__ = evaluate def integrate_gaussian(self, mean, cov): """ Multiply estimated density by a multivariate Gaussian and integrate over the whole space. Parameters ---------- mean : aray_like A 1-D array, specifying the mean of the Gaussian. cov : array_like A 2-D array, specifying the covariance matrix of the Gaussian. Returns ------- result : scalar The value of the integral. Raises ------ ValueError : If the mean or covariance of the input Gaussian differs from the KDE's dimensionality. """ mean = atleast_1d(squeeze(mean)) cov = atleast_2d(cov) if mean.shape != (self.d,): raise ValueError("mean does not have dimension %s" % self.d) if cov.shape != (self.d, self.d): raise ValueError("covariance does not have dimension %s" % self.d) # make mean a column vector mean = mean[:, newaxis] sum_cov = self.covariance + cov diff = self.dataset - mean tdiff = dot(linalg.inv(sum_cov), diff) energies = sum(diff * tdiff, axis=0) / 2.0 result = sum(exp(-energies), axis=0) / sqrt(linalg.det(2 * pi * sum_cov)) / self.n return result def integrate_box_1d(self, low, high): """ Computes the integral of a 1D pdf between two bounds. Parameters ---------- low : scalar Lower bound of integration. high : scalar Upper bound of integration. Returns ------- value : scalar The result of the integral. Raises ------ ValueError If the KDE is over more than one dimension. """ if self.d != 1: raise ValueError("integrate_box_1d() only handles 1D pdfs") stdev = ravel(sqrt(self.covariance))[0] normalized_low = ravel((low - self.dataset) / stdev) normalized_high = ravel((high - self.dataset) / stdev) value = np.mean(special.ndtr(normalized_high) - special.ndtr(normalized_low)) return value def integrate_box(self, low_bounds, high_bounds, maxpts=None): """Computes the integral of a pdf over a rectangular interval. Parameters ---------- low_bounds : array_like A 1-D array containing the lower bounds of integration. high_bounds : array_like A 1-D array containing the upper bounds of integration. maxpts : int, optional The maximum number of points to use for integration. Returns ------- value : scalar The result of the integral. """ if maxpts is not None: extra_kwds = {'maxpts': maxpts} else: extra_kwds = {} value, inform = mvn.mvnun(low_bounds, high_bounds, self.dataset, self.covariance, **extra_kwds) if inform: msg = ('An integral in mvn.mvnun requires more points than %s' % (self.d * 1000)) warnings.warn(msg) return value def integrate_kde(self, other): """ Computes the integral of the product of this kernel density estimate with another. Parameters ---------- other : gaussian_kde instance The other kde. Returns ------- value : scalar The result of the integral. Raises ------ ValueError If the KDEs have different dimensionality. """ if other.d != self.d: raise ValueError("KDEs are not the same dimensionality") # we want to iterate over the smallest number of points if other.n < self.n: small = other large = self else: small = self large = other sum_cov = small.covariance + large.covariance sum_cov_chol = linalg.cho_factor(sum_cov) result = 0.0 for i in range(small.n): mean = small.dataset[:, i, newaxis] diff = large.dataset - mean tdiff = linalg.cho_solve(sum_cov_chol, diff) energies = sum(diff * tdiff, axis=0) / 2.0 result += sum(exp(-energies), axis=0) result /= sqrt(linalg.det(2 * pi * sum_cov)) * large.n * small.n return result def resample(self, size=None): """ Randomly sample a dataset from the estimated pdf. Parameters ---------- size : int, optional The number of samples to draw. If not provided, then the size is the same as the underlying dataset. Returns ------- resample : (self.d, `size`) ndarray The sampled dataset. """ if size is None: size = self.n norm = transpose(multivariate_normal(zeros((self.d,), float), self.covariance, size=size)) indices = randint(0, self.n, size=size) means = self.dataset[:, indices] return means + norm def scotts_factor(self): return power(self.n, -1./(self.d+4)) def silverman_factor(self): return power(self.n*(self.d+2.0)/4.0, -1./(self.d+4)) # Default method to calculate bandwidth, can be overwritten by subclass covariance_factor = scotts_factor covariance_factor.__doc__ = """Computes the coefficient (`kde.factor`) that multiplies the data covariance matrix to obtain the kernel covariance matrix. The default is `scotts_factor`. A subclass can overwrite this method to provide a different method, or set it through a call to `kde.set_bandwidth`.""" def set_bandwidth(self, bw_method=None): """Compute the estimator bandwidth with given method. The new bandwidth calculated after a call to `set_bandwidth` is used for subsequent evaluations of the estimated density. Parameters ---------- bw_method : str, scalar or callable, optional The method used to calculate the estimator bandwidth. This can be 'scott', 'silverman', a scalar constant or a callable. If a scalar, this will be used directly as `kde.factor`. If a callable, it should take a `gaussian_kde` instance as only parameter and return a scalar. If None (default), nothing happens; the current `kde.covariance_factor` method is kept. Notes ----- .. versionadded:: 0.11 Examples -------- >>> import scipy.stats as stats >>> x1 = np.array([-7, -5, 1, 4, 5.]) >>> kde = stats.gaussian_kde(x1) >>> xs = np.linspace(-10, 10, num=50) >>> y1 = kde(xs) >>> kde.set_bandwidth(bw_method='silverman') >>> y2 = kde(xs) >>> kde.set_bandwidth(bw_method=kde.factor / 3.) >>> y3 = kde(xs) >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> ax.plot(x1, np.ones(x1.shape) / (4. * x1.size), 'bo', ... label='Data points (rescaled)') >>> ax.plot(xs, y1, label='Scott (default)') >>> ax.plot(xs, y2, label='Silverman') >>> ax.plot(xs, y3, label='Const (1/3 * Silverman)') >>> ax.legend() >>> plt.show() """ if bw_method is None: pass elif bw_method == 'scott': self.covariance_factor = self.scotts_factor elif bw_method == 'silverman': self.covariance_factor = self.silverman_factor elif np.isscalar(bw_method) and not isinstance(bw_method, string_types): self._bw_method = 'use constant' self.covariance_factor = lambda: bw_method elif callable(bw_method): self._bw_method = bw_method self.covariance_factor = lambda: self._bw_method(self) else: msg = "`bw_method` should be 'scott', 'silverman', a scalar " \ "or a callable." raise ValueError(msg) self._compute_covariance() def _compute_covariance(self): """Computes the covariance matrix for each Gaussian kernel using covariance_factor(). """ self.factor = self.covariance_factor() # Cache covariance and inverse covariance of the data if not hasattr(self, '_data_inv_cov'): self._data_covariance = atleast_2d(np.cov(self.dataset, rowvar=1, bias=False)) self._data_inv_cov = linalg.inv(self._data_covariance) self.covariance = self._data_covariance * self.factor**2 self.inv_cov = self._data_inv_cov / self.factor**2 self._norm_factor = sqrt(linalg.det(2*pi*self.covariance)) * self.n def pdf(self, x): """ Evaluate the estimated pdf on a provided set of points. Notes ----- This is an alias for `gaussian_kde.evaluate`. See the ``evaluate`` docstring for more details. """ return self.evaluate(x) def logpdf(self, x): """ Evaluate the log of the estimated pdf on a provided set of points. Notes ----- See `gaussian_kde.evaluate` for more details; this method simply returns ``np.log(gaussian_kde.evaluate(x))``. """ return np.log(self.evaluate(x))
bsd-3-clause
tombstone/models
research/namignizer/data_utils.py
19
4238
# Copyright 2016 Google Inc. 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. """Utilities for parsing Kaggle baby names files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import numpy as np import tensorflow as tf import pandas as pd # the default end of name rep will be zero _EON = 0 def read_names(names_path): """read data from downloaded file. See SmallNames.txt for example format or go to https://www.kaggle.com/kaggle/us-baby-names for full lists Args: names_path: path to the csv file similar to the example type Returns: Dataset: a namedtuple of two elements: deduped names and their associated counts. The names contain only 26 chars and are all lower case """ names_data = pd.read_csv(names_path) names_data.Name = names_data.Name.str.lower() name_data = names_data.groupby(by=["Name"])["Count"].sum() name_counts = np.array(name_data.tolist()) names_deduped = np.array(name_data.index.tolist()) Dataset = collections.namedtuple('Dataset', ['Name', 'Count']) return Dataset(names_deduped, name_counts) def _letter_to_number(letter): """converts letters to numbers between 1 and 27""" # ord of lower case 'a' is 97 return ord(letter) - 96 def namignizer_iterator(names, counts, batch_size, num_steps, epoch_size): """Takes a list of names and counts like those output from read_names, and makes an iterator yielding a batch_size by num_steps array of random names separated by an end of name token. The names are chosen randomly according to their counts. The batch may end mid-name Args: names: a set of lowercase names composed of 26 characters counts: a list of the frequency of those names batch_size: int num_steps: int epoch_size: number of batches to yield Yields: (x, y): a batch_size by num_steps array of ints representing letters, where x will be the input and y will be the target """ name_distribution = counts / counts.sum() for i in range(epoch_size): data = np.zeros(batch_size * num_steps + 1) samples = np.random.choice(names, size=batch_size * num_steps // 2, replace=True, p=name_distribution) data_index = 0 for sample in samples: if data_index >= batch_size * num_steps: break for letter in map(_letter_to_number, sample) + [_EON]: if data_index >= batch_size * num_steps: break data[data_index] = letter data_index += 1 x = data[:batch_size * num_steps].reshape((batch_size, num_steps)) y = data[1:batch_size * num_steps + 1].reshape((batch_size, num_steps)) yield (x, y) def name_to_batch(name, batch_size, num_steps): """ Takes a single name and fills a batch with it Args: name: lowercase composed of 26 characters batch_size: int num_steps: int Returns: x, y: a batch_size by num_steps array of ints representing letters, where x will be the input and y will be the target. The array is filled up to the length of the string, the rest is filled with zeros """ data = np.zeros(batch_size * num_steps + 1) data_index = 0 for letter in map(_letter_to_number, name) + [_EON]: data[data_index] = letter data_index += 1 x = data[:batch_size * num_steps].reshape((batch_size, num_steps)) y = data[1:batch_size * num_steps + 1].reshape((batch_size, num_steps)) return x, y
apache-2.0
nguyentu1602/statsmodels
statsmodels/datasets/spector/data.py
25
2000
"""Spector and Mazzeo (1980) - Program Effectiveness Data""" __docformat__ = 'restructuredtext' COPYRIGHT = """Used with express permission of the original author, who retains all rights. """ TITLE = __doc__ SOURCE = """ http://pages.stern.nyu.edu/~wgreene/Text/econometricanalysis.htm The raw data was downloaded from Bill Greene's Econometric Analysis web site, though permission was obtained from the original researcher, Dr. Lee Spector, Professor of Economics, Ball State University.""" DESCRSHORT = """Experimental data on the effectiveness of the personalized system of instruction (PSI) program""" DESCRLONG = DESCRSHORT NOTE = """:: Number of Observations - 32 Number of Variables - 4 Variable name definitions:: Grade - binary variable indicating whether or not a student's grade improved. 1 indicates an improvement. TUCE - Test score on economics test PSI - participation in program GPA - Student's grade point average """ import numpy as np from statsmodels.datasets import utils as du from os.path import dirname, abspath def load(): """ Load the Spector dataset and returns a Dataset class instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_recarray(data, endog_idx=3, dtype=float) def load_pandas(): """ Load the Spector dataset and returns a Dataset class instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_recarray_pandas(data, endog_idx=3, dtype=float) def _get_data(): filepath = dirname(abspath(__file__)) ##### EDIT THE FOLLOWING TO POINT TO DatasetName.csv ##### data = np.recfromtxt(open(filepath + '/spector.csv',"rb"), delimiter=" ", names=True, dtype=float, usecols=(1,2,3,4)) return data
bsd-3-clause
smsolivier/VEF
tex/pres/dvs.py
1
1898
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import ld as LD import mhfem_acc as MH from hidespines import * import sys ''' compares diffusion and transport ''' if (len(sys.argv) > 1): outfile = sys.argv[1:] else: outfile = None N = 100 xb = 2 xe = np.linspace(0, xb, N+1) n = 8 Sigmaa = lambda x: .1 Sigmat = lambda x: 1 q = lambda x, mu: 1 BCL = 0 BCR = 1 tol = 1e-8 ld = LD.LD(xe, n, Sigmaa, Sigmat, q, BCL, BCR) mh = MH.MHFEM(xe, Sigmaa, Sigmat, BCL, BCR, CENT=1) mh.discretize(np.ones(N)/3, np.ones(N)/2) xd, phid = mh.solve(np.ones(N), np.zeros(N)) x, phi, it = ld.sourceIteration(tol) edd = ld.getEddington(.5*(ld.psiL + ld.psiR)) psiEdge = ld.edgePsi() top = 0 for i in range(n): top += np.fabs(ld.mu[i])*psiEdge[i,:] * ld.w[i] B = top/ld.zeroMoment(psiEdge) mhc = MH.MHFEM(xe, Sigmaa, Sigmat, BCL, BCR, CENT=1) mhc.discretize(edd, B) xc, phic = mhc.solve(np.ones(N), np.zeros(N)) fsize = 20 plt.figure() plt.plot(x*Sigmat(x), phi, label='S$_8$') plt.plot(xd*Sigmat(xd), phid, label='Diffusion') plt.xlabel(r'$\Sigma_t x$', fontsize=fsize) plt.ylabel(r'$\phi(x)$', fontsize=fsize) plt.legend(loc='best', frameon=False) hidespines(plt.gca()) if (outfile != None): plt.savefig(outfile[0], transparent=True) plt.figure() plt.axhline(1/3, color='k', alpha=.4) plt.plot(x*Sigmat(x), edd) plt.xlabel(r'$\Sigma_t x$', fontsize=fsize) plt.ylabel(r'$\langle \mu^2 \rightangle(x)$', fontsize=fsize) hidespines(plt.gca()) if (outfile != None): plt.savefig(outfile[1], transparent=True) plt.figure() plt.plot(x*Sigmat(x), phi, '--', label='S$_8$') plt.plot(x*Sigmat(x), phic, label='Corrected Diffusion') plt.legend(loc='best', frameon=False) plt.xlabel(r'$\Sigma_t x$', fontsize=fsize) plt.ylabel(r'$\phi(x)$', fontsize=fsize) hidespines(plt.gca()) if (outfile != None): plt.savefig(outfile[2], transparent=True) else: plt.show()
mit
allentran/fed-rates-bot
fed_bot/model/data.py
1
8747
__author__ = 'allentran' import json import os import re import datetime import unidecode from spacy.en import English import requests import pandas as pd import numpy as np import allen_utils logger = allen_utils.get_logger(__name__) class Interval(object): def __init__(self, start, end): assert isinstance(start, datetime.date) and isinstance(end, datetime.date) self.start = start self.end = end def contains(self, new_date): assert isinstance(new_date, datetime.date) return (new_date >= self.start) and (new_date <= self.end) fed_regimes = { 0: Interval(datetime.date(1951, 4, 2), datetime.date(1970, 1, 31)), 1: Interval(datetime.date(1970, 2, 1), datetime.date(1978, 3, 7)), 2: Interval(datetime.date(1978, 3, 8), datetime.date(1979, 8, 6)), 3: Interval(datetime.date(1979, 8, 7), datetime.date(1987, 8, 11)), 4: Interval(datetime.date(1987, 8, 12), datetime.date(2006, 1, 31)), 5: Interval(datetime.date(2006, 2, 1), datetime.date(2020, 1, 31)), } def find_regime(date): for regime, interval in fed_regimes.iteritems(): if interval.contains(date): return regime raise ValueError("Could not find regime for date, %s", date) class PairedDocAndRates(object): def __init__(self, date, sentences, is_minutes): self.date = date self.sentences = sentences self.is_minutes = is_minutes self.rates = None self.regime = find_regime(date) def match_rates(self, rates_df, days = [30, 90, 180]): def get_closest_rate(days_to_add): future_date = self.date + datetime.timedelta(days=days_to_add) diff = abs(future_date - rates_df['date']) if (last_available_date - future_date).total_seconds() >= 0: closest_index = diff.argmin() return float(rates_df.iloc[closest_index]['value']) else: return None future_rates = {} last_available_date = rates_df['date'].iloc[-1] current_rate = get_closest_rate(0) if current_rate: future_rates['0'] = current_rate for add_days in days: future_rate = get_closest_rate(add_days) if future_rate: future_rates[str(add_days)] = future_rate self.rates = future_rates def to_dict(self): return dict( date = self.date.strftime('%Y-%m-%d'), sentences = self.sentences, rates = self.rates, is_minutes = self.is_minutes, regime = self.regime ) class Vocab(object): def __init__(self): self.vocab = {} self.special_words = [ '$CARDINAL$', '$DATE$', '$UNKNOWN$' ] def update_count(self, word): if word not in self.vocab: self.vocab[word] = 1 else: self.vocab[word] += 1 def to_dict(self, min_count=5): position_dict = {word: idx for idx, word in enumerate(self.special_words)} counter = len(self.special_words) for word, word_count in self.vocab.iteritems(): if word_count >= min_count: position_dict[word] = counter counter += 1 return position_dict class DataTransformer(object): def __init__(self, data_dir, min_sentence_length): self.url = 'https://api.stlouisfed.org/fred/series/observations' self.data_dir = data_dir self.min_sentence_length = min_sentence_length self.replace_entities = { 'DATE': '$DATE$', 'CARDINAL': '$CARDINAL$' } self.nlp = English() # custom token replacement self.regexes = [ (re.compile(r'\d{4}'), '$DATE$'), (re.compile(r'\d+[\.,]*\d+'), '$CARDINAL$') ] self.vocab = Vocab() self.word_positions = None self.rates = None self.docs = None def get_rates(self, api_key): params = dict( api_key=api_key, file_type='json', series_id='FEDFUNDS' ) r = requests.get(self.url, params=params) if r.status_code == 200: self.rates = pd.DataFrame(r.json()['observations']) self.rates['date'] = self.rates['date'].apply(lambda s: datetime.datetime.strptime(s, '%Y-%m-%d').date()) self.rates.sort('date') def build_vocab(self): def process_doc(doc_path): with open(doc_path, 'r') as f: text = unidecode.unidecode(unicode(f.read().decode('iso-8859-1'))) text = ' '.join(text.split()).strip() if len(text) > 0: doc = self.nlp(unicode(text.lower())) doc_words = set() for sent in doc.sents: if len(sent) > self.min_sentence_length: for token in doc: if token.text not in doc_words: self.vocab.update_count(token.text) doc_words.add(token.text) file_re = re.compile(r'\d{8}') for root, dirs, filenames in os.walk(self.data_dir): for filename in filenames: if file_re.search(filename): filepath = os.path.join(root, filename) process_doc(filepath) logger.info("Built vocab from: %s", filepath) self.word_positions = self.vocab.to_dict() def strip_text(self, text): doc = self.nlp(unicode(text).lower()) # spacy entity replacement ents_dict = {ent.text: self.replace_entities[ent.label_] for ent in doc.ents if ent.label_ in self.replace_entities.keys()} for ent in ents_dict: text = text.replace(ent, ents_dict[ent]) return text def get_docs(self, min_sentence_length=8): def parse_doc(doc_path): with open(doc_path, 'r') as f: text = unidecode.unidecode(unicode(f.read().decode('iso-8859-1'))) text = ' '.join(text.split()).strip() if len(text) > 0: date = datetime.datetime.strptime(date_re.search(doc_path).group(0), '%Y%m%d').date() stripped_text = self.strip_text(text) doc = self.nlp(unicode(stripped_text)) sentences = list(doc.sents) doc_sents = [] for sent in sentences[1:]: if len(sent) > min_sentence_length: sentence_as_idxes = [] for token in sent: skip = False for regex, replacement_token in self.regexes: match = regex.match(token.text) if match: sentence_as_idxes.append(self.word_positions[replacement_token]) skip = True if not skip: try: sentence_as_idxes.append(self.word_positions[token.text]) except KeyError: sentence_as_idxes.append(self.word_positions['$UNKNOWN$']) doc_sents.append(sentence_as_idxes) paired_doc = PairedDocAndRates(date, doc_sents, doc_path.find('minutes') > -1) paired_doc.match_rates(self.rates) return paired_doc date_re = re.compile(r'\d{8}') file_re = re.compile(r'\d{8}') docs = [] for root, dirs, filenames in os.walk(self.data_dir): for filename in filenames: if file_re.search(filename): filepath = os.path.join(root, filename) parsed_doc = parse_doc(filepath) if parsed_doc: logger.info("Parsed %s", filepath) docs.append(parsed_doc) self.docs = docs def save_output(self): with open(os.path.join(self.data_dir, 'paired_data.json'), 'w') as f: json.dump([doc.to_dict() for doc in self.docs], f, indent=2, sort_keys=True) with open(os.path.join(self.data_dir, 'dictionary.json'), 'w') as f: json.dump(self.vocab.to_dict(), f, indent=2, sort_keys=True) if __name__ == "__main__": data_transformer = DataTransformer('data', min_sentence_length=8) data_transformer.build_vocab() data_transformer.get_rates('51c09c6b8aa464671aa8ac96c76a8416') data_transformer.get_docs() data_transformer.save_output()
mit
tomlof/scikit-learn
sklearn/utils/multiclass.py
41
14732
# Author: Arnaud Joly, Joel Nothman, Hamzeh Alsalhi # # License: BSD 3 clause """ Multi-class / multi-label utility function ========================================== """ from __future__ import division from collections import Sequence from itertools import chain from scipy.sparse import issparse from scipy.sparse.base import spmatrix from scipy.sparse import dok_matrix from scipy.sparse import lil_matrix import numpy as np from ..externals.six import string_types from .validation import check_array from ..utils.fixes import bincount from ..utils.fixes import array_equal def _unique_multiclass(y): if hasattr(y, '__array__'): return np.unique(np.asarray(y)) else: return set(y) def _unique_indicator(y): return np.arange(check_array(y, ['csr', 'csc', 'coo']).shape[1]) _FN_UNIQUE_LABELS = { 'binary': _unique_multiclass, 'multiclass': _unique_multiclass, 'multilabel-indicator': _unique_indicator, } def unique_labels(*ys): """Extract an ordered array of unique labels We don't allow: - mix of multilabel and multiclass (single label) targets - mix of label indicator matrix and anything else, because there are no explicit labels) - mix of label indicator matrices of different sizes - mix of string and integer labels At the moment, we also don't allow "multiclass-multioutput" input type. Parameters ---------- *ys : array-likes, Returns ------- out : numpy array of shape [n_unique_labels] An ordered array of unique labels. Examples -------- >>> from sklearn.utils.multiclass import unique_labels >>> unique_labels([3, 5, 5, 5, 7, 7]) array([3, 5, 7]) >>> unique_labels([1, 2, 3, 4], [2, 2, 3, 4]) array([1, 2, 3, 4]) >>> unique_labels([1, 2, 10], [5, 11]) array([ 1, 2, 5, 10, 11]) """ if not ys: raise ValueError('No argument has been passed.') # Check that we don't mix label format ys_types = set(type_of_target(x) for x in ys) if ys_types == set(["binary", "multiclass"]): ys_types = set(["multiclass"]) if len(ys_types) > 1: raise ValueError("Mix type of y not allowed, got types %s" % ys_types) label_type = ys_types.pop() # Check consistency for the indicator format if (label_type == "multilabel-indicator" and len(set(check_array(y, ['csr', 'csc', 'coo']).shape[1] for y in ys)) > 1): raise ValueError("Multi-label binary indicator input with " "different numbers of labels") # Get the unique set of labels _unique_labels = _FN_UNIQUE_LABELS.get(label_type, None) if not _unique_labels: raise ValueError("Unknown label type: %s" % repr(ys)) ys_labels = set(chain.from_iterable(_unique_labels(y) for y in ys)) # Check that we don't mix string type with number type if (len(set(isinstance(label, string_types) for label in ys_labels)) > 1): raise ValueError("Mix of label input types (string and number)") return np.array(sorted(ys_labels)) def _is_integral_float(y): return y.dtype.kind == 'f' and np.all(y.astype(int) == y) def is_multilabel(y): """ Check if ``y`` is in a multilabel format. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- out : bool, Return ``True``, if ``y`` is in a multilabel format, else ```False``. Examples -------- >>> import numpy as np >>> from sklearn.utils.multiclass import is_multilabel >>> is_multilabel([0, 1, 0, 1]) False >>> is_multilabel([[1], [0, 2], []]) False >>> is_multilabel(np.array([[1, 0], [0, 0]])) True >>> is_multilabel(np.array([[1], [0], [0]])) False >>> is_multilabel(np.array([[1, 0, 0]])) True """ if hasattr(y, '__array__'): y = np.asarray(y) if not (hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1): return False if issparse(y): if isinstance(y, (dok_matrix, lil_matrix)): y = y.tocsr() return (len(y.data) == 0 or np.unique(y.data).size == 1 and (y.dtype.kind in 'biu' or # bool, int, uint _is_integral_float(np.unique(y.data)))) else: labels = np.unique(y) return len(labels) < 3 and (y.dtype.kind in 'biu' or # bool, int, uint _is_integral_float(labels)) def check_classification_targets(y): """Ensure that target y is of a non-regression type. Only the following target types (as defined in type_of_target) are allowed: 'binary', 'multiclass', 'multiclass-multioutput', 'multilabel-indicator', 'multilabel-sequences' Parameters ---------- y : array-like """ y_type = type_of_target(y) if y_type not in ['binary', 'multiclass', 'multiclass-multioutput', 'multilabel-indicator', 'multilabel-sequences']: raise ValueError("Unknown label type: %r" % y_type) def type_of_target(y): """Determine the type of data indicated by target `y` Parameters ---------- y : array-like Returns ------- target_type : string One of: * 'continuous': `y` is an array-like of floats that are not all integers, and is 1d or a column vector. * 'continuous-multioutput': `y` is a 2d array of floats that are not all integers, and both dimensions are of size > 1. * 'binary': `y` contains <= 2 discrete values and is 1d or a column vector. * 'multiclass': `y` contains more than two discrete values, is not a sequence of sequences, and is 1d or a column vector. * 'multiclass-multioutput': `y` is a 2d array that contains more than two discrete values, is not a sequence of sequences, and both dimensions are of size > 1. * 'multilabel-indicator': `y` is a label indicator matrix, an array of two dimensions with at least two columns, and at most 2 unique values. * 'unknown': `y` is array-like but none of the above, such as a 3d array, sequence of sequences, or an array of non-sequence objects. Examples -------- >>> import numpy as np >>> type_of_target([0.1, 0.6]) 'continuous' >>> type_of_target([1, -1, -1, 1]) 'binary' >>> type_of_target(['a', 'b', 'a']) 'binary' >>> type_of_target([1.0, 2.0]) 'binary' >>> type_of_target([1, 0, 2]) 'multiclass' >>> type_of_target([1.0, 0.0, 3.0]) 'multiclass' >>> type_of_target(['a', 'b', 'c']) 'multiclass' >>> type_of_target(np.array([[1, 2], [3, 1]])) 'multiclass-multioutput' >>> type_of_target([[1, 2]]) 'multiclass-multioutput' >>> type_of_target(np.array([[1.5, 2.0], [3.0, 1.6]])) 'continuous-multioutput' >>> type_of_target(np.array([[0, 1], [1, 1]])) 'multilabel-indicator' """ valid = ((isinstance(y, (Sequence, spmatrix)) or hasattr(y, '__array__')) and not isinstance(y, string_types)) if not valid: raise ValueError('Expected array-like (array or non-string sequence), ' 'got %r' % y) if is_multilabel(y): return 'multilabel-indicator' try: y = np.asarray(y) except ValueError: # Known to fail in numpy 1.3 for array of arrays return 'unknown' # The old sequence of sequences format try: if (not hasattr(y[0], '__array__') and isinstance(y[0], Sequence) and not isinstance(y[0], string_types)): raise ValueError('You appear to be using a legacy multi-label data' ' representation. Sequence of sequences are no' ' longer supported; use a binary array or sparse' ' matrix instead.') except IndexError: pass # Invalid inputs if y.ndim > 2 or (y.dtype == object and len(y) and not isinstance(y.flat[0], string_types)): return 'unknown' # [[[1, 2]]] or [obj_1] and not ["label_1"] if y.ndim == 2 and y.shape[1] == 0: return 'unknown' # [[]] if y.ndim == 2 and y.shape[1] > 1: suffix = "-multioutput" # [[1, 2], [1, 2]] else: suffix = "" # [1, 2, 3] or [[1], [2], [3]] # check float and contains non-integer float values if y.dtype.kind == 'f' and np.any(y != y.astype(int)): # [.1, .2, 3] or [[.1, .2, 3]] or [[1., .2]] and not [1., 2., 3.] return 'continuous' + suffix if (len(np.unique(y)) > 2) or (y.ndim >= 2 and len(y[0]) > 1): return 'multiclass' + suffix # [1, 2, 3] or [[1., 2., 3]] or [[1, 2]] else: return 'binary' # [1, 2] or [["a"], ["b"]] def _check_partial_fit_first_call(clf, classes=None): """Private helper function for factorizing common classes param logic Estimators that implement the ``partial_fit`` API need to be provided with the list of possible classes at the first call to partial_fit. Subsequent calls to partial_fit should check that ``classes`` is still consistent with a previous value of ``clf.classes_`` when provided. This function returns True if it detects that this was the first call to ``partial_fit`` on ``clf``. In that case the ``classes_`` attribute is also set on ``clf``. """ if getattr(clf, 'classes_', None) is None and classes is None: raise ValueError("classes must be passed on the first call " "to partial_fit.") elif classes is not None: if getattr(clf, 'classes_', None) is not None: if not array_equal(clf.classes_, unique_labels(classes)): raise ValueError( "`classes=%r` is not the same as on last call " "to partial_fit, was: %r" % (classes, clf.classes_)) else: # This is the first call to partial_fit clf.classes_ = unique_labels(classes) return True # classes is None and clf.classes_ has already previously been set: # nothing to do return False def class_distribution(y, sample_weight=None): """Compute class priors from multioutput-multiclass target data Parameters ---------- y : array like or sparse matrix of size (n_samples, n_outputs) The labels for each example. sample_weight : array-like of shape = (n_samples,), optional Sample weights. Returns ------- classes : list of size n_outputs of arrays of size (n_classes,) List of classes for each column. n_classes : list of integers of size n_outputs Number of classes in each column class_prior : list of size n_outputs of arrays of size (n_classes,) Class distribution of each column. """ classes = [] n_classes = [] class_prior = [] n_samples, n_outputs = y.shape if issparse(y): y = y.tocsc() y_nnz = np.diff(y.indptr) for k in range(n_outputs): col_nonzero = y.indices[y.indptr[k]:y.indptr[k + 1]] # separate sample weights for zero and non-zero elements if sample_weight is not None: nz_samp_weight = np.asarray(sample_weight)[col_nonzero] zeros_samp_weight_sum = (np.sum(sample_weight) - np.sum(nz_samp_weight)) else: nz_samp_weight = None zeros_samp_weight_sum = y.shape[0] - y_nnz[k] classes_k, y_k = np.unique(y.data[y.indptr[k]:y.indptr[k + 1]], return_inverse=True) class_prior_k = bincount(y_k, weights=nz_samp_weight) # An explicit zero was found, combine its weight with the weight # of the implicit zeros if 0 in classes_k: class_prior_k[classes_k == 0] += zeros_samp_weight_sum # If an there is an implicit zero and it is not in classes and # class_prior, make an entry for it if 0 not in classes_k and y_nnz[k] < y.shape[0]: classes_k = np.insert(classes_k, 0, 0) class_prior_k = np.insert(class_prior_k, 0, zeros_samp_weight_sum) classes.append(classes_k) n_classes.append(classes_k.shape[0]) class_prior.append(class_prior_k / class_prior_k.sum()) else: for k in range(n_outputs): classes_k, y_k = np.unique(y[:, k], return_inverse=True) classes.append(classes_k) n_classes.append(classes_k.shape[0]) class_prior_k = bincount(y_k, weights=sample_weight) class_prior.append(class_prior_k / class_prior_k.sum()) return (classes, n_classes, class_prior) def _ovr_decision_function(predictions, confidences, n_classes): """Compute a continuous, tie-breaking ovr decision function. It is important to include a continuous value, not only votes, to make computing AUC or calibration meaningful. Parameters ---------- predictions : array-like, shape (n_samples, n_classifiers) Predicted classes for each binary classifier. confidences : array-like, shape (n_samples, n_classifiers) Decision functions or predicted probabilities for positive class for each binary classifier. n_classes : int Number of classes. n_classifiers must be ``n_classes * (n_classes - 1 ) / 2`` """ n_samples = predictions.shape[0] votes = np.zeros((n_samples, n_classes)) sum_of_confidences = np.zeros((n_samples, n_classes)) k = 0 for i in range(n_classes): for j in range(i + 1, n_classes): sum_of_confidences[:, i] -= confidences[:, k] sum_of_confidences[:, j] += confidences[:, k] votes[predictions[:, k] == 0, i] += 1 votes[predictions[:, k] == 1, j] += 1 k += 1 max_confidences = sum_of_confidences.max() min_confidences = sum_of_confidences.min() if max_confidences == min_confidences: return votes # Scale the sum_of_confidences to (-0.5, 0.5) and add it with votes. # The motivation is to use confidence levels as a way to break ties in # the votes without switching any decision made based on a difference # of 1 vote. eps = np.finfo(sum_of_confidences.dtype).eps max_abs_confidence = max(abs(max_confidences), abs(min_confidences)) scale = (0.5 - eps) / max_abs_confidence return votes + sum_of_confidences * scale
bsd-3-clause
pratapvardhan/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
25
25114
# Authors: Olivier Grisel <[email protected]> # Alexandre Gramfort <[email protected]> # License: BSD 3 clause from sys import version_info import numpy as np from scipy import interpolate, sparse from copy import deepcopy from sklearn.datasets import load_boston from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import SkipTest from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_warns from sklearn.utils.testing import assert_warns_message from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import TempMemmap from sklearn.linear_model.coordinate_descent import Lasso, \ LassoCV, ElasticNet, ElasticNetCV, MultiTaskLasso, MultiTaskElasticNet, \ MultiTaskElasticNetCV, MultiTaskLassoCV, lasso_path, enet_path from sklearn.linear_model import LassoLarsCV, lars_path from sklearn.utils import check_array def check_warnings(): if version_info < (2, 6): raise SkipTest("Testing for warnings is not supported in versions \ older than Python 2.6") def test_lasso_zero(): # Check that the lasso can handle zero data without crashing X = [[0], [0], [0]] y = [0, 0, 0] clf = Lasso(alpha=0.1).fit(X, y) pred = clf.predict([[1], [2], [3]]) assert_array_almost_equal(clf.coef_, [0]) assert_array_almost_equal(pred, [0, 0, 0]) assert_almost_equal(clf.dual_gap_, 0) def test_lasso_toy(): # Test Lasso on a toy example for various values of alpha. # When validating this against glmnet notice that glmnet divides it # against nobs. X = [[-1], [0], [1]] Y = [-1, 0, 1] # just a straight line T = [[2], [3], [4]] # test sample clf = Lasso(alpha=1e-8) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [1]) assert_array_almost_equal(pred, [2, 3, 4]) assert_almost_equal(clf.dual_gap_, 0) clf = Lasso(alpha=0.1) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [.85]) assert_array_almost_equal(pred, [1.7, 2.55, 3.4]) assert_almost_equal(clf.dual_gap_, 0) clf = Lasso(alpha=0.5) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [.25]) assert_array_almost_equal(pred, [0.5, 0.75, 1.]) assert_almost_equal(clf.dual_gap_, 0) clf = Lasso(alpha=1) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [.0]) assert_array_almost_equal(pred, [0, 0, 0]) assert_almost_equal(clf.dual_gap_, 0) def test_enet_toy(): # Test ElasticNet for various parameters of alpha and l1_ratio. # Actually, the parameters alpha = 0 should not be allowed. However, # we test it as a border case. # ElasticNet is tested with and without precomputed Gram matrix X = np.array([[-1.], [0.], [1.]]) Y = [-1, 0, 1] # just a straight line T = [[2.], [3.], [4.]] # test sample # this should be the same as lasso clf = ElasticNet(alpha=1e-8, l1_ratio=1.0) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [1]) assert_array_almost_equal(pred, [2, 3, 4]) assert_almost_equal(clf.dual_gap_, 0) clf = ElasticNet(alpha=0.5, l1_ratio=0.3, max_iter=100, precompute=False) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.50819], decimal=3) assert_array_almost_equal(pred, [1.0163, 1.5245, 2.0327], decimal=3) assert_almost_equal(clf.dual_gap_, 0) clf.set_params(max_iter=100, precompute=True) clf.fit(X, Y) # with Gram pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.50819], decimal=3) assert_array_almost_equal(pred, [1.0163, 1.5245, 2.0327], decimal=3) assert_almost_equal(clf.dual_gap_, 0) clf.set_params(max_iter=100, precompute=np.dot(X.T, X)) clf.fit(X, Y) # with Gram pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.50819], decimal=3) assert_array_almost_equal(pred, [1.0163, 1.5245, 2.0327], decimal=3) assert_almost_equal(clf.dual_gap_, 0) clf = ElasticNet(alpha=0.5, l1_ratio=0.5) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.45454], 3) assert_array_almost_equal(pred, [0.9090, 1.3636, 1.8181], 3) assert_almost_equal(clf.dual_gap_, 0) def build_dataset(n_samples=50, n_features=200, n_informative_features=10, n_targets=1): """ build an ill-posed linear regression problem with many noisy features and comparatively few samples """ random_state = np.random.RandomState(0) if n_targets > 1: w = random_state.randn(n_features, n_targets) else: w = random_state.randn(n_features) w[n_informative_features:] = 0.0 X = random_state.randn(n_samples, n_features) y = np.dot(X, w) X_test = random_state.randn(n_samples, n_features) y_test = np.dot(X_test, w) return X, y, X_test, y_test def test_lasso_cv(): X, y, X_test, y_test = build_dataset() max_iter = 150 clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter).fit(X, y) assert_almost_equal(clf.alpha_, 0.056, 2) clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter, precompute=True) clf.fit(X, y) assert_almost_equal(clf.alpha_, 0.056, 2) # Check that the lars and the coordinate descent implementation # select a similar alpha lars = LassoLarsCV(normalize=False, max_iter=30).fit(X, y) # for this we check that they don't fall in the grid of # clf.alphas further than 1 assert_true(np.abs( np.searchsorted(clf.alphas_[::-1], lars.alpha_) - np.searchsorted(clf.alphas_[::-1], clf.alpha_)) <= 1) # check that they also give a similar MSE mse_lars = interpolate.interp1d(lars.cv_alphas_, lars.cv_mse_path_.T) np.testing.assert_approx_equal(mse_lars(clf.alphas_[5]).mean(), clf.mse_path_[5].mean(), significant=2) # test set assert_greater(clf.score(X_test, y_test), 0.99) def test_lasso_cv_positive_constraint(): X, y, X_test, y_test = build_dataset() max_iter = 500 # Ensure the unconstrained fit has a negative coefficient clf_unconstrained = LassoCV(n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1) clf_unconstrained.fit(X, y) assert_true(min(clf_unconstrained.coef_) < 0) # On same data, constrained fit has non-negative coefficients clf_constrained = LassoCV(n_alphas=3, eps=1e-1, max_iter=max_iter, positive=True, cv=2, n_jobs=1) clf_constrained.fit(X, y) assert_true(min(clf_constrained.coef_) >= 0) def test_lasso_path_return_models_vs_new_return_gives_same_coefficients(): # Test that lasso_path with lars_path style output gives the # same result # Some toy data X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T y = np.array([1, 2, 3.1]) alphas = [5., 1., .5] # Use lars_path and lasso_path(new output) with 1D linear interpolation # to compute the same path alphas_lars, _, coef_path_lars = lars_path(X, y, method='lasso') coef_path_cont_lars = interpolate.interp1d(alphas_lars[::-1], coef_path_lars[:, ::-1]) alphas_lasso2, coef_path_lasso2, _ = lasso_path(X, y, alphas=alphas, return_models=False) coef_path_cont_lasso = interpolate.interp1d(alphas_lasso2[::-1], coef_path_lasso2[:, ::-1]) assert_array_almost_equal( coef_path_cont_lasso(alphas), coef_path_cont_lars(alphas), decimal=1) def test_enet_path(): # We use a large number of samples and of informative features so that # the l1_ratio selected is more toward ridge than lasso X, y, X_test, y_test = build_dataset(n_samples=200, n_features=100, n_informative_features=100) max_iter = 150 # Here we have a small number of iterations, and thus the # ElasticNet might not converge. This is to speed up tests clf = ElasticNetCV(alphas=[0.01, 0.05, 0.1], eps=2e-3, l1_ratio=[0.5, 0.7], cv=3, max_iter=max_iter) ignore_warnings(clf.fit)(X, y) # Well-conditioned settings, we should have selected our # smallest penalty assert_almost_equal(clf.alpha_, min(clf.alphas_)) # Non-sparse ground truth: we should have selected an elastic-net # that is closer to ridge than to lasso assert_equal(clf.l1_ratio_, min(clf.l1_ratio)) clf = ElasticNetCV(alphas=[0.01, 0.05, 0.1], eps=2e-3, l1_ratio=[0.5, 0.7], cv=3, max_iter=max_iter, precompute=True) ignore_warnings(clf.fit)(X, y) # Well-conditioned settings, we should have selected our # smallest penalty assert_almost_equal(clf.alpha_, min(clf.alphas_)) # Non-sparse ground truth: we should have selected an elastic-net # that is closer to ridge than to lasso assert_equal(clf.l1_ratio_, min(clf.l1_ratio)) # We are in well-conditioned settings with low noise: we should # have a good test-set performance assert_greater(clf.score(X_test, y_test), 0.99) # Multi-output/target case X, y, X_test, y_test = build_dataset(n_features=10, n_targets=3) clf = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7], cv=3, max_iter=max_iter) ignore_warnings(clf.fit)(X, y) # We are in well-conditioned settings with low noise: we should # have a good test-set performance assert_greater(clf.score(X_test, y_test), 0.99) assert_equal(clf.coef_.shape, (3, 10)) # Mono-output should have same cross-validated alpha_ and l1_ratio_ # in both cases. X, y, _, _ = build_dataset(n_features=10) clf1 = ElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) clf1.fit(X, y) clf2 = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) clf2.fit(X, y[:, np.newaxis]) assert_almost_equal(clf1.l1_ratio_, clf2.l1_ratio_) assert_almost_equal(clf1.alpha_, clf2.alpha_) def test_path_parameters(): X, y, _, _ = build_dataset() max_iter = 100 clf = ElasticNetCV(n_alphas=50, eps=1e-3, max_iter=max_iter, l1_ratio=0.5, tol=1e-3) clf.fit(X, y) # new params assert_almost_equal(0.5, clf.l1_ratio) assert_equal(50, clf.n_alphas) assert_equal(50, len(clf.alphas_)) def test_warm_start(): X, y, _, _ = build_dataset() clf = ElasticNet(alpha=0.1, max_iter=5, warm_start=True) ignore_warnings(clf.fit)(X, y) ignore_warnings(clf.fit)(X, y) # do a second round with 5 iterations clf2 = ElasticNet(alpha=0.1, max_iter=10) ignore_warnings(clf2.fit)(X, y) assert_array_almost_equal(clf2.coef_, clf.coef_) def test_lasso_alpha_warning(): X = [[-1], [0], [1]] Y = [-1, 0, 1] # just a straight line clf = Lasso(alpha=0) assert_warns(UserWarning, clf.fit, X, Y) def test_lasso_positive_constraint(): X = [[-1], [0], [1]] y = [1, 0, -1] # just a straight line with negative slope lasso = Lasso(alpha=0.1, max_iter=1000, positive=True) lasso.fit(X, y) assert_true(min(lasso.coef_) >= 0) lasso = Lasso(alpha=0.1, max_iter=1000, precompute=True, positive=True) lasso.fit(X, y) assert_true(min(lasso.coef_) >= 0) def test_enet_positive_constraint(): X = [[-1], [0], [1]] y = [1, 0, -1] # just a straight line with negative slope enet = ElasticNet(alpha=0.1, max_iter=1000, positive=True) enet.fit(X, y) assert_true(min(enet.coef_) >= 0) def test_enet_cv_positive_constraint(): X, y, X_test, y_test = build_dataset() max_iter = 500 # Ensure the unconstrained fit has a negative coefficient enetcv_unconstrained = ElasticNetCV(n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1) enetcv_unconstrained.fit(X, y) assert_true(min(enetcv_unconstrained.coef_) < 0) # On same data, constrained fit has non-negative coefficients enetcv_constrained = ElasticNetCV(n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, positive=True, n_jobs=1) enetcv_constrained.fit(X, y) assert_true(min(enetcv_constrained.coef_) >= 0) def test_uniform_targets(): enet = ElasticNetCV(fit_intercept=True, n_alphas=3) m_enet = MultiTaskElasticNetCV(fit_intercept=True, n_alphas=3) lasso = LassoCV(fit_intercept=True, n_alphas=3) m_lasso = MultiTaskLassoCV(fit_intercept=True, n_alphas=3) models_single_task = (enet, lasso) models_multi_task = (m_enet, m_lasso) rng = np.random.RandomState(0) X_train = rng.random_sample(size=(10, 3)) X_test = rng.random_sample(size=(10, 3)) y1 = np.empty(10) y2 = np.empty((10, 2)) for model in models_single_task: for y_values in (0, 5): y1.fill(y_values) assert_array_equal(model.fit(X_train, y1).predict(X_test), y1) assert_array_equal(model.alphas_, [np.finfo(float).resolution]*3) for model in models_multi_task: for y_values in (0, 5): y2[:, 0].fill(y_values) y2[:, 1].fill(2 * y_values) assert_array_equal(model.fit(X_train, y2).predict(X_test), y2) assert_array_equal(model.alphas_, [np.finfo(float).resolution]*3) def test_multi_task_lasso_and_enet(): X, y, X_test, y_test = build_dataset() Y = np.c_[y, y] # Y_test = np.c_[y_test, y_test] clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y) assert_true(0 < clf.dual_gap_ < 1e-5) assert_array_almost_equal(clf.coef_[0], clf.coef_[1]) clf = MultiTaskElasticNet(alpha=1, tol=1e-8).fit(X, Y) assert_true(0 < clf.dual_gap_ < 1e-5) assert_array_almost_equal(clf.coef_[0], clf.coef_[1]) def test_lasso_readonly_data(): X = np.array([[-1], [0], [1]]) Y = np.array([-1, 0, 1]) # just a straight line T = np.array([[2], [3], [4]]) # test sample with TempMemmap((X, Y)) as (X, Y): clf = Lasso(alpha=0.5) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [.25]) assert_array_almost_equal(pred, [0.5, 0.75, 1.]) assert_almost_equal(clf.dual_gap_, 0) def test_multi_task_lasso_readonly_data(): X, y, X_test, y_test = build_dataset() Y = np.c_[y, y] with TempMemmap((X, Y)) as (X, Y): Y = np.c_[y, y] clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y) assert_true(0 < clf.dual_gap_ < 1e-5) assert_array_almost_equal(clf.coef_[0], clf.coef_[1]) def test_enet_multitarget(): n_targets = 3 X, y, _, _ = build_dataset(n_samples=10, n_features=8, n_informative_features=10, n_targets=n_targets) estimator = ElasticNet(alpha=0.01, fit_intercept=True) estimator.fit(X, y) coef, intercept, dual_gap = (estimator.coef_, estimator.intercept_, estimator.dual_gap_) for k in range(n_targets): estimator.fit(X, y[:, k]) assert_array_almost_equal(coef[k, :], estimator.coef_) assert_array_almost_equal(intercept[k], estimator.intercept_) assert_array_almost_equal(dual_gap[k], estimator.dual_gap_) def test_multioutput_enetcv_error(): X = np.random.randn(10, 2) y = np.random.randn(10, 2) clf = ElasticNetCV() assert_raises(ValueError, clf.fit, X, y) def test_multitask_enet_and_lasso_cv(): X, y, _, _ = build_dataset(n_features=50, n_targets=3) clf = MultiTaskElasticNetCV().fit(X, y) assert_almost_equal(clf.alpha_, 0.00556, 3) clf = MultiTaskLassoCV().fit(X, y) assert_almost_equal(clf.alpha_, 0.00278, 3) X, y, _, _ = build_dataset(n_targets=3) clf = MultiTaskElasticNetCV(n_alphas=10, eps=1e-3, max_iter=100, l1_ratio=[0.3, 0.5], tol=1e-3) clf.fit(X, y) assert_equal(0.5, clf.l1_ratio_) assert_equal((3, X.shape[1]), clf.coef_.shape) assert_equal((3, ), clf.intercept_.shape) assert_equal((2, 10, 3), clf.mse_path_.shape) assert_equal((2, 10), clf.alphas_.shape) X, y, _, _ = build_dataset(n_targets=3) clf = MultiTaskLassoCV(n_alphas=10, eps=1e-3, max_iter=100, tol=1e-3) clf.fit(X, y) assert_equal((3, X.shape[1]), clf.coef_.shape) assert_equal((3, ), clf.intercept_.shape) assert_equal((10, 3), clf.mse_path_.shape) assert_equal(10, len(clf.alphas_)) def test_1d_multioutput_enet_and_multitask_enet_cv(): X, y, _, _ = build_dataset(n_features=10) y = y[:, np.newaxis] clf = ElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) clf.fit(X, y[:, 0]) clf1 = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) clf1.fit(X, y) assert_almost_equal(clf.l1_ratio_, clf1.l1_ratio_) assert_almost_equal(clf.alpha_, clf1.alpha_) assert_almost_equal(clf.coef_, clf1.coef_[0]) assert_almost_equal(clf.intercept_, clf1.intercept_[0]) def test_1d_multioutput_lasso_and_multitask_lasso_cv(): X, y, _, _ = build_dataset(n_features=10) y = y[:, np.newaxis] clf = LassoCV(n_alphas=5, eps=2e-3) clf.fit(X, y[:, 0]) clf1 = MultiTaskLassoCV(n_alphas=5, eps=2e-3) clf1.fit(X, y) assert_almost_equal(clf.alpha_, clf1.alpha_) assert_almost_equal(clf.coef_, clf1.coef_[0]) assert_almost_equal(clf.intercept_, clf1.intercept_[0]) def test_sparse_input_dtype_enet_and_lassocv(): X, y, _, _ = build_dataset(n_features=10) clf = ElasticNetCV(n_alphas=5) clf.fit(sparse.csr_matrix(X), y) clf1 = ElasticNetCV(n_alphas=5) clf1.fit(sparse.csr_matrix(X, dtype=np.float32), y) assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6) assert_almost_equal(clf.coef_, clf1.coef_, decimal=6) clf = LassoCV(n_alphas=5) clf.fit(sparse.csr_matrix(X), y) clf1 = LassoCV(n_alphas=5) clf1.fit(sparse.csr_matrix(X, dtype=np.float32), y) assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6) assert_almost_equal(clf.coef_, clf1.coef_, decimal=6) def test_precompute_invalid_argument(): X, y, _, _ = build_dataset() for clf in [ElasticNetCV(precompute="invalid"), LassoCV(precompute="invalid")]: assert_raises(ValueError, clf.fit, X, y) def test_warm_start_convergence(): X, y, _, _ = build_dataset() model = ElasticNet(alpha=1e-3, tol=1e-3).fit(X, y) n_iter_reference = model.n_iter_ # This dataset is not trivial enough for the model to converge in one pass. assert_greater(n_iter_reference, 2) # Check that n_iter_ is invariant to multiple calls to fit # when warm_start=False, all else being equal. model.fit(X, y) n_iter_cold_start = model.n_iter_ assert_equal(n_iter_cold_start, n_iter_reference) # Fit the same model again, using a warm start: the optimizer just performs # a single pass before checking that it has already converged model.set_params(warm_start=True) model.fit(X, y) n_iter_warm_start = model.n_iter_ assert_equal(n_iter_warm_start, 1) def test_warm_start_convergence_with_regularizer_decrement(): boston = load_boston() X, y = boston.data, boston.target # Train a model to converge on a lightly regularized problem final_alpha = 1e-5 low_reg_model = ElasticNet(alpha=final_alpha).fit(X, y) # Fitting a new model on a more regularized version of the same problem. # Fitting with high regularization is easier it should converge faster # in general. high_reg_model = ElasticNet(alpha=final_alpha * 10).fit(X, y) assert_greater(low_reg_model.n_iter_, high_reg_model.n_iter_) # Fit the solution to the original, less regularized version of the # problem but from the solution of the highly regularized variant of # the problem as a better starting point. This should also converge # faster than the original model that starts from zero. warm_low_reg_model = deepcopy(high_reg_model) warm_low_reg_model.set_params(warm_start=True, alpha=final_alpha) warm_low_reg_model.fit(X, y) assert_greater(low_reg_model.n_iter_, warm_low_reg_model.n_iter_) def test_random_descent(): # Test that both random and cyclic selection give the same results. # Ensure that the test models fully converge and check a wide # range of conditions. # This uses the coordinate descent algo using the gram trick. X, y, _, _ = build_dataset(n_samples=50, n_features=20) clf_cyclic = ElasticNet(selection='cyclic', tol=1e-8) clf_cyclic.fit(X, y) clf_random = ElasticNet(selection='random', tol=1e-8, random_state=42) clf_random.fit(X, y) assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) # This uses the descent algo without the gram trick clf_cyclic = ElasticNet(selection='cyclic', tol=1e-8) clf_cyclic.fit(X.T, y[:20]) clf_random = ElasticNet(selection='random', tol=1e-8, random_state=42) clf_random.fit(X.T, y[:20]) assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) # Sparse Case clf_cyclic = ElasticNet(selection='cyclic', tol=1e-8) clf_cyclic.fit(sparse.csr_matrix(X), y) clf_random = ElasticNet(selection='random', tol=1e-8, random_state=42) clf_random.fit(sparse.csr_matrix(X), y) assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) # Multioutput case. new_y = np.hstack((y[:, np.newaxis], y[:, np.newaxis])) clf_cyclic = MultiTaskElasticNet(selection='cyclic', tol=1e-8) clf_cyclic.fit(X, new_y) clf_random = MultiTaskElasticNet(selection='random', tol=1e-8, random_state=42) clf_random.fit(X, new_y) assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) # Raise error when selection is not in cyclic or random. clf_random = ElasticNet(selection='invalid') assert_raises(ValueError, clf_random.fit, X, y) def test_enet_path_positive(): # Test that the coefs returned by positive=True in enet_path are positive X, y, _, _ = build_dataset(n_samples=50, n_features=50) for path in [enet_path, lasso_path]: pos_path_coef = path(X, y, positive=True)[1] assert_true(np.all(pos_path_coef >= 0)) def test_sparse_dense_descent_paths(): # Test that dense and sparse input give the same input for descent paths. X, y, _, _ = build_dataset(n_samples=50, n_features=20) csr = sparse.csr_matrix(X) for path in [enet_path, lasso_path]: _, coefs, _ = path(X, y, fit_intercept=False) _, sparse_coefs, _ = path(csr, y, fit_intercept=False) assert_array_almost_equal(coefs, sparse_coefs) def test_check_input_false(): X, y, _, _ = build_dataset(n_samples=20, n_features=10) X = check_array(X, order='F', dtype='float64') y = check_array(X, order='F', dtype='float64') clf = ElasticNet(selection='cyclic', tol=1e-8) # Check that no error is raised if data is provided in the right format clf.fit(X, y, check_input=False) X = check_array(X, order='F', dtype='float32') clf.fit(X, y, check_input=True) # Check that an error is raised if data is provided in the wrong dtype, # because of check bypassing assert_raises(ValueError, clf.fit, X, y, check_input=False) # With no input checking, providing X in C order should result in false # computation X = check_array(X, order='C', dtype='float64') assert_raises(ValueError, clf.fit, X, y, check_input=False) def test_overrided_gram_matrix(): X, y, _, _ = build_dataset(n_samples=20, n_features=10) Gram = X.T.dot(X) clf = ElasticNet(selection='cyclic', tol=1e-8, precompute=Gram, fit_intercept=True) assert_warns_message(UserWarning, "Gram matrix was provided but X was centered" " to fit intercept, " "or X was normalized : recomputing Gram matrix.", clf.fit, X, y) def test_lasso_non_float_y(): X = [[0, 0], [1, 1], [-1, -1]] y = [0, 1, 2] y_float = [0.0, 1.0, 2.0] for model in [ElasticNet, Lasso]: clf = model(fit_intercept=False) clf.fit(X, y) clf_float = model(fit_intercept=False) clf_float.fit(X, y_float) assert_array_equal(clf.coef_, clf_float.coef_)
bsd-3-clause
zasdfgbnm/tensorflow
tensorflow/contrib/factorization/python/ops/kmeans.py
5
17810
# 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. # ============================================================================== """A canned Estimator for k-means clustering.""" # TODO(ccolby): Move clustering_ops.py into this file and streamline the code. from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from tensorflow.contrib.factorization.python.ops import clustering_ops from tensorflow.python.estimator import estimator from tensorflow.python.estimator import model_fn as model_fn_lib from tensorflow.python.estimator.export import export_output from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import metrics from tensorflow.python.ops import state_ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import signature_constants from tensorflow.python.summary import summary from tensorflow.python.training import session_run_hook from tensorflow.python.training import training_util class _LossRelativeChangeHook(session_run_hook.SessionRunHook): """Stops when the change in loss goes below a tolerance.""" def __init__(self, loss_tensor, tolerance): """Creates a _LossRelativeChangeHook. Args: loss_tensor: A scalar tensor of the loss value. tolerance: A relative tolerance of loss change between iterations. """ self._loss_tensor = loss_tensor self._tolerance = tolerance self._prev_loss = None def before_run(self, run_context): del run_context # unused return session_run_hook.SessionRunArgs(self._loss_tensor) def after_run(self, run_context, run_values): loss = run_values.results assert loss is not None if self._prev_loss: relative_change = (abs(loss - self._prev_loss) / (1 + abs(self._prev_loss))) if relative_change < self._tolerance: run_context.request_stop() self._prev_loss = loss class _InitializeClustersHook(session_run_hook.SessionRunHook): """Initializes the cluster centers. The chief repeatedly invokes an initialization op until all cluster centers are initialized. The workers wait for the initialization phase to complete. """ def __init__(self, init_op, is_initialized_var, is_chief): """Creates an _InitializeClustersHook. Args: init_op: An op that, when run, will choose some initial cluster centers. This op may need to be run multiple times to choose all the centers. is_initialized_var: A boolean variable reporting whether all initial centers have been chosen. is_chief: A boolean specifying whether this task is the chief. """ self._init_op = init_op self._is_initialized_var = is_initialized_var self._is_chief = is_chief def after_create_session(self, session, coord): del coord # unused assert self._init_op.graph is ops.get_default_graph() assert self._is_initialized_var.graph is self._init_op.graph while True: try: if session.run(self._is_initialized_var): break elif self._is_chief: session.run(self._init_op) else: time.sleep(1) except RuntimeError as e: logging.info(e) def _parse_tensor_or_dict(features): """Helper function to convert the input points into a usable format. Args: features: The input points. Returns: If `features` is a dict of `k` features, each of which is a vector of `n` scalars, the return value is a Tensor of shape `(n, k)` representing `n` input points, where the items in the `k` dimension are sorted lexicographically by `features` key. If `features` is not a dict, it is returned unmodified. """ if isinstance(features, dict): keys = sorted(features.keys()) with ops.colocate_with(features[keys[0]]): features = array_ops.concat([features[k] for k in keys], axis=1) return features class _ModelFn(object): """Model function for the estimator.""" def __init__(self, num_clusters, initial_clusters, distance_metric, random_seed, use_mini_batch, mini_batch_steps_per_iteration, kmeans_plus_plus_num_retries, relative_tolerance): self._num_clusters = num_clusters self._initial_clusters = initial_clusters self._distance_metric = distance_metric self._random_seed = random_seed self._use_mini_batch = use_mini_batch self._mini_batch_steps_per_iteration = mini_batch_steps_per_iteration self._kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries self._relative_tolerance = relative_tolerance def model_fn(self, features, mode, config): """Model function for the estimator. Note that this does not take a `labels` arg. This works, but `input_fn` must return either `features` or, equivalently, `(features, None)`. Args: features: The input points. See @{tf.estimator.Estimator}. mode: See @{tf.estimator.Estimator}. config: See @{tf.estimator.Estimator}. Returns: A @{tf.estimator.EstimatorSpec} (see @{tf.estimator.Estimator}) specifying this behavior: * `train_op`: Execute one mini-batch or full-batch run of Lloyd's algorithm. * `loss`: The sum of the squared distances from each input point to its closest center. * `eval_metric_ops`: Maps `SCORE` to `loss`. * `predictions`: Maps `ALL_DISTANCES` to the distance from each input point to each cluster center; maps `CLUSTER_INDEX` to the index of the closest cluster center for each input point. """ # input_points is a single Tensor. Therefore, the sharding functionality # in clustering_ops is unused, and some of the values below are lists of a # single item. input_points = _parse_tensor_or_dict(features) # Let N = the number of input_points. # all_distances: A list of one matrix of shape (N, num_clusters). Each value # is the distance from an input point to a cluster center. # model_predictions: A list of one vector of shape (N). Each value is the # cluster id of an input point. # losses: Similar to cluster_idx but provides the distance to the cluster # center. # is_initialized: scalar indicating whether the initial cluster centers # have been chosen; see init_op. # cluster_centers_var: a Variable containing the cluster centers. # init_op: an op to choose the initial cluster centers. A single worker # repeatedly executes init_op until is_initialized becomes True. # training_op: an op that runs an iteration of training, either an entire # Lloyd iteration or a mini-batch of a Lloyd iteration. Multiple workers # may execute this op, but only after is_initialized becomes True. (all_distances, model_predictions, losses, is_initialized, init_op, training_op) = clustering_ops.KMeans( inputs=input_points, num_clusters=self._num_clusters, initial_clusters=self._initial_clusters, distance_metric=self._distance_metric, use_mini_batch=self._use_mini_batch, mini_batch_steps_per_iteration=self._mini_batch_steps_per_iteration, random_seed=self._random_seed, kmeans_plus_plus_num_retries=self._kmeans_plus_plus_num_retries ).training_graph() loss = math_ops.reduce_sum(losses) summary.scalar('loss/raw', loss) incr_step = state_ops.assign_add(training_util.get_global_step(), 1) training_op = control_flow_ops.with_dependencies([training_op, incr_step], loss) training_hooks = [ _InitializeClustersHook(init_op, is_initialized, config.is_chief) ] if self._relative_tolerance is not None: training_hooks.append( _LossRelativeChangeHook(loss, self._relative_tolerance)) export_outputs = { KMeansClustering.ALL_DISTANCES: export_output.PredictOutput(all_distances[0]), KMeansClustering.CLUSTER_INDEX: export_output.PredictOutput(model_predictions[0]), signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: export_output.PredictOutput(model_predictions[0]) } return model_fn_lib.EstimatorSpec( mode=mode, predictions={ KMeansClustering.ALL_DISTANCES: all_distances[0], KMeansClustering.CLUSTER_INDEX: model_predictions[0], }, loss=loss, train_op=training_op, eval_metric_ops={KMeansClustering.SCORE: metrics.mean(loss)}, training_hooks=training_hooks, export_outputs=export_outputs) # TODO(agarwal,ands): support sharded input. class KMeansClustering(estimator.Estimator): """An Estimator for K-Means clustering.""" # Valid values for the distance_metric constructor argument. SQUARED_EUCLIDEAN_DISTANCE = clustering_ops.SQUARED_EUCLIDEAN_DISTANCE COSINE_DISTANCE = clustering_ops.COSINE_DISTANCE # Values for initial_clusters constructor argument. RANDOM_INIT = clustering_ops.RANDOM_INIT KMEANS_PLUS_PLUS_INIT = clustering_ops.KMEANS_PLUS_PLUS_INIT # Metric returned by evaluate(): The sum of the squared distances from each # input point to its closest center. SCORE = 'score' # Keys returned by predict(). # ALL_DISTANCES: The distance from each input point to each cluster center. # CLUSTER_INDEX: The index of the closest cluster center for each input point. CLUSTER_INDEX = 'cluster_index' ALL_DISTANCES = 'all_distances' def __init__(self, num_clusters, model_dir=None, initial_clusters=RANDOM_INIT, distance_metric=SQUARED_EUCLIDEAN_DISTANCE, random_seed=0, use_mini_batch=True, mini_batch_steps_per_iteration=1, kmeans_plus_plus_num_retries=2, relative_tolerance=None, config=None): """Creates an Estimator for running KMeans training and inference. This Estimator implements the following variants of the K-means algorithm: If `use_mini_batch` is False, it runs standard full batch K-means. Each training step runs a single iteration of K-Means and must process the full input at once. To run in this mode, the `input_fn` passed to `train` must return the entire input dataset. If `use_mini_batch` is True, it runs a generalization of the mini-batch K-means algorithm. It runs multiple iterations, where each iteration is composed of `mini_batch_steps_per_iteration` steps. Each training step accumulates the contribution from one mini-batch into temporary storage. Every `mini_batch_steps_per_iteration` steps, the cluster centers are updated and the temporary storage cleared for the next iteration. Note that: * If `mini_batch_steps_per_iteration=1`, the algorithm reduces to the standard K-means mini-batch algorithm. * If `mini_batch_steps_per_iteration = num_inputs / batch_size`, the algorithm becomes an asynchronous version of the full-batch algorithm. However, there is no guarantee by this implementation that each input is seen exactly once per iteration. Also, different updates are applied asynchronously without locking. So this asynchronous version may not behave exactly like a full-batch version. Args: num_clusters: An integer tensor specifying the number of clusters. This argument is ignored if `initial_clusters` is a tensor or numpy array. model_dir: The directory to save the model results and log files. initial_clusters: Specifies how the initial cluster centers are chosen. One of the following: * a tensor or numpy array with the initial cluster centers. * a callable `f(inputs, k)` that selects and returns up to `k` centers from an input batch. `f` is free to return any number of centers from `0` to `k`. It will be invoked on successive input batches as necessary until all `num_clusters` centers are chosen. * `KMeansClustering.RANDOM_INIT`: Choose centers randomly from an input batch. If the batch size is less than `num_clusters` then the entire batch is chosen to be initial cluster centers and the remaining centers are chosen from successive input batches. * `KMeansClustering.KMEANS_PLUS_PLUS_INIT`: Use kmeans++ to choose centers from the first input batch. If the batch size is less than `num_clusters`, a TensorFlow runtime error occurs. distance_metric: The distance metric used for clustering. One of: * `KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE`: Euclidean distance between vectors `u` and `v` is defined as `||u - v||_2` which is the square root of the sum of the absolute squares of the elements' difference. * `KMeansClustering.COSINE_DISTANCE`: Cosine distance between vectors `u` and `v` is defined as `1 - (u . v) / (||u||_2 ||v||_2)`. random_seed: Python integer. Seed for PRNG used to initialize centers. use_mini_batch: A boolean specifying whether to use the mini-batch k-means algorithm. See explanation above. mini_batch_steps_per_iteration: The number of steps after which the updated cluster centers are synced back to a master copy. Used only if `use_mini_batch=True`. See explanation above. kmeans_plus_plus_num_retries: For each point that is sampled during kmeans++ initialization, this parameter specifies the number of additional points to draw from the current distribution before selecting the best. If a negative value is specified, a heuristic is used to sample `O(log(num_to_sample))` additional points. Used only if `initial_clusters=KMeansClustering.KMEANS_PLUS_PLUS_INIT`. relative_tolerance: A relative tolerance of change in the loss between iterations. Stops learning if the loss changes less than this amount. This may not work correctly if `use_mini_batch=True`. config: See @{tf.estimator.Estimator}. Raises: ValueError: An invalid argument was passed to `initial_clusters` or `distance_metric`. """ if isinstance(initial_clusters, str) and initial_clusters not in [ KMeansClustering.RANDOM_INIT, KMeansClustering.KMEANS_PLUS_PLUS_INIT ]: raise ValueError( "Unsupported initialization algorithm '%s'" % initial_clusters) if distance_metric not in [ KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, KMeansClustering.COSINE_DISTANCE ]: raise ValueError("Unsupported distance metric '%s'" % distance_metric) super(KMeansClustering, self).__init__( model_fn=_ModelFn( num_clusters, initial_clusters, distance_metric, random_seed, use_mini_batch, mini_batch_steps_per_iteration, kmeans_plus_plus_num_retries, relative_tolerance).model_fn, model_dir=model_dir, config=config) def _predict_one_key(self, input_fn, predict_key): for result in self.predict(input_fn=input_fn, predict_keys=[predict_key]): yield result[predict_key] def predict_cluster_index(self, input_fn): """Finds the index of the closest cluster center to each input point. Args: input_fn: Input points. See @{tf.estimator.Estimator.predict}. Yields: The index of the closest cluster center for each input point. """ for index in self._predict_one_key(input_fn, KMeansClustering.CLUSTER_INDEX): yield index def score(self, input_fn): """Returns the sum of squared distances to nearest clusters. Note that this function is different from the corresponding one in sklearn which returns the negative sum. Args: input_fn: Input points. See @{tf.estimator.Estimator.evaluate}. Only one batch is retrieved. Returns: The sum of the squared distance from each point in the first batch of inputs to its nearest cluster center. """ return self.evaluate(input_fn=input_fn, steps=1)[KMeansClustering.SCORE] def transform(self, input_fn): """Transforms each input point to its distances to all cluster centers. Note that if `distance_metric=KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE`, this function returns the squared Euclidean distance while the corresponding sklearn function returns the Euclidean distance. Args: input_fn: Input points. See @{tf.estimator.Estimator.predict}. Yields: The distances from each input point to each cluster center. """ for distances in self._predict_one_key(input_fn, KMeansClustering.ALL_DISTANCES): yield distances def cluster_centers(self): """Returns the cluster centers.""" return self.get_variable_value(clustering_ops.CLUSTERS_VAR_NAME)
apache-2.0
thorwhalen/ut
ppi/naive_bayes_graph.py
1
8556
__author__ = 'thor' import copy import re # import pandas as pd # import numpy as np # import ut as ut # # import ut.daf.get class BipartiteStats(object): """ The class that manages the count data. """ # _count # a # b # ab # ba def __init__(self, get_a_list_from_item=None, get_b_list_from_item=None): self._count = CountVal(0.0) self.a = KeyVal() self.b = KeyVal() self.ab = KeyVal() self.ba = KeyVal() self.get_a_list_from_item = get_a_list_from_item or get_a_list_from_item_default self.get_b_list_from_item = get_b_list_from_item or get_b_list_from_item_default def count_data(self, item_iterator, get_a_list_from_item=None, get_b_list_from_item=None): self.__init__(get_a_list_from_item=get_a_list_from_item, get_b_list_from_item=get_b_list_from_item) for item in item_iterator: self._count.increment() a_list = self.get_a_list_from_item(item) b_list = self.get_b_list_from_item(item) for a in a_list: self.a.add(KeyVal({a: Val(1.0)})) for b in b_list: self.b.add(KeyVal({b: Val(1.0)})) for a in a_list: for b in b_list: self.ab.add(KeyVal({a: KeyVal({b: Val(1.0)})})) self.ba.add(KeyVal({b: KeyVal({a: Val(1.0)})})) # def normalize(self, alpha=1, beta=1): # prior_num = Val(float(alpha)) # prior_denom = Val(float(alpha + beta)) # self.ab = (self.ab + prior_num) / (self.b + prior_denom) # self.ba = (self.ab + prior_num) / (self.a + prior_denom) # self.a = (self.a + prior_num) / (self._count + prior_denom) # self.b = (self.b + prior_num) / (self._count + prior_denom) # default functions def get_a_list_from_item_default(pair_set): return pair_set[0] def get_b_list_from_item_default(pair_set): return pair_set[1] class BipartiteEdgeCounts(object): """ The class that manages the count data. """ # _count # a_count # b_count # ab_count # ba_count def __init__(self, get_a_list_from_item=None, get_b_list_from_item=None): self._count = CountVal(0.0) self.a_count = KeyCount() self.b_count = KeyCount() self.ab_count = KeyCount() self.ba_count = KeyCount() self.get_a_list_from_item = get_a_list_from_item or get_a_list_from_item_default self.get_b_list_from_item = get_b_list_from_item or get_b_list_from_item_default def learn(self, item_iterator): self.__init__() for item in item_iterator: self._count.increment() a_list = self.get_a_list_from_item(item) b_list = self.get_b_list_from_item(item) for a in a_list: self.a_count.increment(a) for b in b_list: self.b_count.increment(b) for a in a_list: for b in b_list: self.ab_count.add(KeyVal({a: KeyVal({b: Val(1.0)})})) self.ba_count.add(KeyVal({b: KeyVal({a: Val(1.0)})})) class Val(object): """ The mother class of other Val classes. A Val should hold a value and be able to add and subtract from it. This mother class implements normal addition of floats, but should be overridden to implement other types of values such as multiplication, addition of vectors, merging of likelihoods etc. Most of the time, you'll only need to override the add() and the sub() methods. You may also want to override the default value. This value should act as the 'unit' or 'neutral' value of the add operation (therefore the sub operation as well). For example, the unit value of multiplication (which will still be called "add") is 1.0. """ v = 0.0 def __init__(self, v): if isinstance(v, Val): self.v = copy.deepcopy(v.v) else: self.v = copy.deepcopy(v) def add(self, y): self.v = self.v + y.v def sub(self, y): self.v = self.v - y.v def mul(self, y): self.v = self.v * y.v def div(self, y): self.v = self.v / y.v def unwrapped(self): if hasattr(self.v, 'v'): return self.v.unwrapped() else: return self.v def __add__(self, y): x = copy.deepcopy(self) x.add(y) return x def __sub__(self, y): x = copy.deepcopy(self) x.sub(y) return x def __mul__(self, y): x = copy.deepcopy(self) x.mul(y) return x def __div__(self, y): x = copy.deepcopy(self) x.div(y) return x def __str__(self): return str(self.v) def __repr__(self): return str(self.v) class CountVal(Val): v = 0.0 def __init__(self, v=0.0): super(CountVal, self).__init__(v) self.v = float(v) def increment(self): self.v += 1.0 class LHVal(Val): """ An LHVal manages a binary likelihood. That is, it holds (as a single float) the binary likelihood distribution and allows one to merge two such distributions. """ v = .5; # where the value will be stored def __init__(self, v=.5): super(LHVal, self).__init__(v) self.v = float(v) def add(self, y): self.v = (self.v * y.v) / (self.v * y.v + (1 - self.v) * (1 - y.v)) def sub(self, y): self.v = (self.v / y.v) / (self.v / y.v + (1 - self.v) / (1 - y.v)) class KeyVal(Val): """ Here the type of the value is a dict (to implement a map). The addition of two dicts (therefore the add() method) v and w. The add(val) method will here be defined to be a sum-update of the (key,value) pairs of the Extends a map so that one can add and subtract dict pairs by adding or subtracting the (key-aligned) values """ def __init__(self, v=None): if v is None: self.v = dict() else: super(KeyVal, self).__init__(v) def add(self, kv): if hasattr(kv.v, 'keys'): for k in list(kv.v.keys()): if k in list(self.v.keys()): self.v[k].add(kv.v[k]) else: self.v[k] = kv.v[k] else: for k in list(self.v.keys()): self.v[k].v = self.v[k].v + kv.v def sub(self, kv): if hasattr(kv.v, 'keys'): for k in list(kv.v.keys()): if k in list(self.v.keys()): self.v[k].sub(kv.v[k]) else: for k in list(self.v.keys()): self.v[k].v = self.v[k].v - kv.v def mul(self, kv): if hasattr(kv.v, 'keys'): for k in list(kv.v.keys()): if k in list(self.v.keys()): self.v[k].mul(kv.v[k]) else: self.v[k] = kv.v[k] else: for k in list(self.v.keys()): self.v[k].v = self.v[k].v * kv.v def div(self, kv): if hasattr(kv.v, 'keys'): for k in list(kv.v.keys()): if k in list(self.v.keys()): self.v[k].div(kv.v[k]) else: for k in list(self.v.keys()): self.v[k].v = self.v[k].v / kv.v def unwrapped(self): return {k: v.unwrapped() for k, v in self.v.items()} # d = dict() # for k in self.v.keys(): # this_v = self.v[k] # # print hasattr(this_v, 'v') # # d.update({k: this_v.unwrapped()}) # if hasattr(this_v, 'v'): # # print 'oh!' # d.update({k: this_v.unwrapped()}) # else: # # print 'ah?' # d.update({k: this_v}) # return d class KeyCount(KeyVal): # v = dict() # init_val_constructor = None; """ Extends a map so that one can add and subtract dict pairs by adding or subtracting the (key-aligned) values """ def __init__(self, v=None): if v is None: self.v = dict() else: super(KeyCount, self).__init__(v) def increment(self, k): if k in self.v: self.v[k].add(Val(1.0)) else: self.v[k] = Val(1.0) # if __name__ == "__main__": # d = ut.daf.get.rand(nrows=9) # s = d['A'].iloc[0:5] # ss = d['B'].iloc[3:8] # t = s + ss # print t
mit
shikhardb/scikit-learn
sklearn/datasets/tests/test_samples_generator.py
67
14842
from __future__ import division from collections import defaultdict from functools import partial import numpy as np from sklearn.externals.six.moves import zip from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_warns from sklearn.datasets import make_classification from sklearn.datasets import make_multilabel_classification from sklearn.datasets import make_hastie_10_2 from sklearn.datasets import make_regression from sklearn.datasets import make_blobs from sklearn.datasets import make_friedman1 from sklearn.datasets import make_friedman2 from sklearn.datasets import make_friedman3 from sklearn.datasets import make_low_rank_matrix from sklearn.datasets import make_sparse_coded_signal from sklearn.datasets import make_sparse_uncorrelated from sklearn.datasets import make_spd_matrix from sklearn.datasets import make_swiss_roll from sklearn.datasets import make_s_curve from sklearn.datasets import make_biclusters from sklearn.datasets import make_checkerboard from sklearn.utils.validation import assert_all_finite def test_make_classification(): X, y = make_classification(n_samples=100, n_features=20, n_informative=5, n_redundant=1, n_repeated=1, n_classes=3, n_clusters_per_class=1, hypercube=False, shift=None, scale=None, weights=[0.1, 0.25], random_state=0) assert_equal(X.shape, (100, 20), "X shape mismatch") assert_equal(y.shape, (100,), "y shape mismatch") assert_equal(np.unique(y).shape, (3,), "Unexpected number of classes") assert_equal(sum(y == 0), 10, "Unexpected number of samples in class #0") assert_equal(sum(y == 1), 25, "Unexpected number of samples in class #1") assert_equal(sum(y == 2), 65, "Unexpected number of samples in class #2") def test_make_classification_informative_features(): """Test the construction of informative features in make_classification Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and fully-specified `weights`. """ # Create very separate clusters; check that vertices are unique and # correspond to classes class_sep = 1e6 make = partial(make_classification, class_sep=class_sep, n_redundant=0, n_repeated=0, flip_y=0, shift=0, scale=1, shuffle=False) for n_informative, weights, n_clusters_per_class in [(2, [1], 1), (2, [1/3] * 3, 1), (2, [1/4] * 4, 1), (2, [1/2] * 2, 2), (2, [3/4, 1/4], 2), (10, [1/3] * 3, 10) ]: n_classes = len(weights) n_clusters = n_classes * n_clusters_per_class n_samples = n_clusters * 50 for hypercube in (False, True): X, y = make(n_samples=n_samples, n_classes=n_classes, weights=weights, n_features=n_informative, n_informative=n_informative, n_clusters_per_class=n_clusters_per_class, hypercube=hypercube, random_state=0) assert_equal(X.shape, (n_samples, n_informative)) assert_equal(y.shape, (n_samples,)) # Cluster by sign, viewed as strings to allow uniquing signs = np.sign(X) signs = signs.view(dtype='|S{0}'.format(signs.strides[0])) unique_signs, cluster_index = np.unique(signs, return_inverse=True) assert_equal(len(unique_signs), n_clusters, "Wrong number of clusters, or not in distinct " "quadrants") clusters_by_class = defaultdict(set) for cluster, cls in zip(cluster_index, y): clusters_by_class[cls].add(cluster) for clusters in clusters_by_class.values(): assert_equal(len(clusters), n_clusters_per_class, "Wrong number of clusters per class") assert_equal(len(clusters_by_class), n_classes, "Wrong number of classes") assert_array_almost_equal(np.bincount(y) / len(y) // weights, [1] * n_classes, err_msg="Wrong number of samples " "per class") # Ensure on vertices of hypercube for cluster in range(len(unique_signs)): centroid = X[cluster_index == cluster].mean(axis=0) if hypercube: assert_array_almost_equal(np.abs(centroid), [class_sep] * n_informative, decimal=0, err_msg="Clusters are not " "centered on hypercube " "vertices") else: assert_raises(AssertionError, assert_array_almost_equal, np.abs(centroid), [class_sep] * n_informative, decimal=0, err_msg="Clusters should not be cenetered " "on hypercube vertices") assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=5, n_clusters_per_class=1) assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=3, n_clusters_per_class=2) def test_make_multilabel_classification_return_sequences(): for allow_unlabeled, min_length in zip((True, False), (0, 1)): X, Y = assert_warns(DeprecationWarning, make_multilabel_classification, n_samples=100, n_features=20, n_classes=3, random_state=0, allow_unlabeled=allow_unlabeled) assert_equal(X.shape, (100, 20), "X shape mismatch") if not allow_unlabeled: assert_equal(max([max(y) for y in Y]), 2) assert_equal(min([len(y) for y in Y]), min_length) assert_true(max([len(y) for y in Y]) <= 3) def test_make_multilabel_classification_return_indicator(): for allow_unlabeled, min_length in zip((True, False), (0, 1)): X, Y = make_multilabel_classification(n_samples=25, n_features=20, n_classes=3, random_state=0, return_indicator=True, allow_unlabeled=allow_unlabeled) assert_equal(X.shape, (25, 20), "X shape mismatch") assert_equal(Y.shape, (25, 3), "Y shape mismatch") assert_true(np.all(np.sum(Y, axis=0) > min_length)) # Also test return_distributions X2, Y2, p_c, p_w_c = make_multilabel_classification( n_samples=25, n_features=20, n_classes=3, random_state=0, return_indicator=True, allow_unlabeled=allow_unlabeled, return_distributions=True) assert_array_equal(X, X2) assert_array_equal(Y, Y2) assert_equal(p_c.shape, (3,)) assert_almost_equal(p_c.sum(), 1) assert_equal(p_w_c.shape, (20, 3)) assert_almost_equal(p_w_c.sum(axis=0), [1] * 3) def test_make_hastie_10_2(): X, y = make_hastie_10_2(n_samples=100, random_state=0) assert_equal(X.shape, (100, 10), "X shape mismatch") assert_equal(y.shape, (100,), "y shape mismatch") assert_equal(np.unique(y).shape, (2,), "Unexpected number of classes") def test_make_regression(): X, y, c = make_regression(n_samples=100, n_features=10, n_informative=3, effective_rank=5, coef=True, bias=0.0, noise=1.0, random_state=0) assert_equal(X.shape, (100, 10), "X shape mismatch") assert_equal(y.shape, (100,), "y shape mismatch") assert_equal(c.shape, (10,), "coef shape mismatch") assert_equal(sum(c != 0.0), 3, "Unexpected number of informative features") # Test that y ~= np.dot(X, c) + bias + N(0, 1.0). assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1) # Test with small number of features. X, y = make_regression(n_samples=100, n_features=1) # n_informative=3 assert_equal(X.shape, (100, 1)) def test_make_regression_multitarget(): X, y, c = make_regression(n_samples=100, n_features=10, n_informative=3, n_targets=3, coef=True, noise=1., random_state=0) assert_equal(X.shape, (100, 10), "X shape mismatch") assert_equal(y.shape, (100, 3), "y shape mismatch") assert_equal(c.shape, (10, 3), "coef shape mismatch") assert_array_equal(sum(c != 0.0), 3, "Unexpected number of informative features") # Test that y ~= np.dot(X, c) + bias + N(0, 1.0) assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1) def test_make_blobs(): X, y = make_blobs(n_samples=50, n_features=2, centers=[[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]], random_state=0) assert_equal(X.shape, (50, 2), "X shape mismatch") assert_equal(y.shape, (50,), "y shape mismatch") assert_equal(np.unique(y).shape, (3,), "Unexpected number of blobs") def test_make_friedman1(): X, y = make_friedman1(n_samples=5, n_features=10, noise=0.0, random_state=0) assert_equal(X.shape, (5, 10), "X shape mismatch") assert_equal(y.shape, (5,), "y shape mismatch") assert_array_almost_equal(y, 10 * np.sin(np.pi * X[:, 0] * X[:, 1]) + 20 * (X[:, 2] - 0.5) ** 2 + 10 * X[:, 3] + 5 * X[:, 4]) def test_make_friedman2(): X, y = make_friedman2(n_samples=5, noise=0.0, random_state=0) assert_equal(X.shape, (5, 4), "X shape mismatch") assert_equal(y.shape, (5,), "y shape mismatch") assert_array_almost_equal(y, (X[:, 0] ** 2 + (X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) ** 2) ** 0.5) def test_make_friedman3(): X, y = make_friedman3(n_samples=5, noise=0.0, random_state=0) assert_equal(X.shape, (5, 4), "X shape mismatch") assert_equal(y.shape, (5,), "y shape mismatch") assert_array_almost_equal(y, np.arctan((X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) / X[:, 0])) def test_make_low_rank_matrix(): X = make_low_rank_matrix(n_samples=50, n_features=25, effective_rank=5, tail_strength=0.01, random_state=0) assert_equal(X.shape, (50, 25), "X shape mismatch") from numpy.linalg import svd u, s, v = svd(X) assert_less(sum(s) - 5, 0.1, "X rank is not approximately 5") def test_make_sparse_coded_signal(): Y, D, X = make_sparse_coded_signal(n_samples=5, n_components=8, n_features=10, n_nonzero_coefs=3, random_state=0) assert_equal(Y.shape, (10, 5), "Y shape mismatch") assert_equal(D.shape, (10, 8), "D shape mismatch") assert_equal(X.shape, (8, 5), "X shape mismatch") for col in X.T: assert_equal(len(np.flatnonzero(col)), 3, 'Non-zero coefs mismatch') assert_array_almost_equal(np.dot(D, X), Y) assert_array_almost_equal(np.sqrt((D ** 2).sum(axis=0)), np.ones(D.shape[1])) def test_make_sparse_uncorrelated(): X, y = make_sparse_uncorrelated(n_samples=5, n_features=10, random_state=0) assert_equal(X.shape, (5, 10), "X shape mismatch") assert_equal(y.shape, (5,), "y shape mismatch") def test_make_spd_matrix(): X = make_spd_matrix(n_dim=5, random_state=0) assert_equal(X.shape, (5, 5), "X shape mismatch") assert_array_almost_equal(X, X.T) from numpy.linalg import eig eigenvalues, _ = eig(X) assert_array_equal(eigenvalues > 0, np.array([True] * 5), "X is not positive-definite") def test_make_swiss_roll(): X, t = make_swiss_roll(n_samples=5, noise=0.0, random_state=0) assert_equal(X.shape, (5, 3), "X shape mismatch") assert_equal(t.shape, (5,), "t shape mismatch") assert_array_almost_equal(X[:, 0], t * np.cos(t)) assert_array_almost_equal(X[:, 2], t * np.sin(t)) def test_make_s_curve(): X, t = make_s_curve(n_samples=5, noise=0.0, random_state=0) assert_equal(X.shape, (5, 3), "X shape mismatch") assert_equal(t.shape, (5,), "t shape mismatch") assert_array_almost_equal(X[:, 0], np.sin(t)) assert_array_almost_equal(X[:, 2], np.sign(t) * (np.cos(t) - 1)) def test_make_biclusters(): X, rows, cols = make_biclusters( shape=(100, 100), n_clusters=4, shuffle=True, random_state=0) assert_equal(X.shape, (100, 100), "X shape mismatch") assert_equal(rows.shape, (4, 100), "rows shape mismatch") assert_equal(cols.shape, (4, 100,), "columns shape mismatch") assert_all_finite(X) assert_all_finite(rows) assert_all_finite(cols) X2, _, _ = make_biclusters(shape=(100, 100), n_clusters=4, shuffle=True, random_state=0) assert_array_almost_equal(X, X2) def test_make_checkerboard(): X, rows, cols = make_checkerboard( shape=(100, 100), n_clusters=(20, 5), shuffle=True, random_state=0) assert_equal(X.shape, (100, 100), "X shape mismatch") assert_equal(rows.shape, (100, 100), "rows shape mismatch") assert_equal(cols.shape, (100, 100,), "columns shape mismatch") X, rows, cols = make_checkerboard( shape=(100, 100), n_clusters=2, shuffle=True, random_state=0) assert_all_finite(X) assert_all_finite(rows) assert_all_finite(cols) X1, _, _ = make_checkerboard(shape=(100, 100), n_clusters=2, shuffle=True, random_state=0) X2, _, _ = make_checkerboard(shape=(100, 100), n_clusters=2, shuffle=True, random_state=0) assert_array_equal(X1, X2)
bsd-3-clause
paulorauber/rlnn
model/rl_ffnn.py
1
2771
import numpy as np from collections import deque from sklearn.utils import check_random_state def ffnn_batch_update(env, network, transition_buffer, gamma, batch_size, random_state=None): random_state = check_random_state(random_state) # Batch is a random sample of transitions indices = random_state.choice(len(transition_buffer), size=batch_size) batch = [transition_buffer[i] for i in indices] # Setting up targets X = np.zeros((batch_size, env.d_states)) Y = np.zeros((batch_size, env.n_actions)) mask = np.zeros((batch_size, env.n_actions)) for i, transition in enumerate(batch): (s, a, next_r, next_s) = transition X[i] = s mask[i, a] = 1 if next_s is None: Y[i, a] = next_r else: Y[i, a] = next_r + gamma*np.max(network.predict(next_s)) network.fit_batch(X, Y, mask) def q_ffnn(env, network, nepisodes, gamma=0.99, min_epsilon=0.1, max_epsilon=1.0, decay_epsilon=0.99, max_queue=8192, batch_size=128, verbose=0, random_state=None): random_state = check_random_state(random_state) transition_buffer = deque(maxlen=max_queue) if verbose > 0: episode_return = 0.0 episode_gamma = 1.0 epsilon = max(min_epsilon, max_epsilon) for episode in range(nepisodes): if verbose > 0: print('Episode {0}.'.format(episode + 1)) s = env.start() if verbose > 1: step = 0 print('Step {0}.'.format(step+1)) if verbose > 2: print(env) while not env.ended(): if random_state.uniform(0, 1) < epsilon: a = random_state.choice(env.n_actions) else: a = np.argmax(network.predict(s)) next_s, next_r = env.next_state_reward(a) if not env.ended(): transition_buffer.append((s, a, next_r, next_s)) else: transition_buffer.append((s, a, next_r, None)) s = next_s if len(transition_buffer) > batch_size: ffnn_batch_update(env, network, transition_buffer, gamma, batch_size, random_state=random_state) if verbose > 0: episode_return += episode_gamma*next_r episode_gamma *= gamma if verbose > 1: step += 1 print('Step {0}.'.format(step+1)) if verbose > 2: print(env) epsilon = max(min_epsilon, epsilon*decay_epsilon) if verbose > 0: print('Return: {0}.'.format(episode_return)) episode_return = 0.0 episode_gamma = 1.0 return network
mit
escherba/clustering-metrics
clustering_metrics/ranking.py
1
19888
""" Motivation ---------- Assume that there is a data set of mostly unique samples where a hidden binary variable is dependent on the number of similar samples that exist in the set (i.e. a sample is called positive if it has many neighbors) and that our goal is to label all samples in this set. Given sparse enough data, if a clustering method relies on the same sample property on which the ground truth similarity space is defined, it will naturally separate the samples into two groups -- those found in clusters and containing mostly positives, and those found outside clusters and containing mostly negatives. There would exist only one possible perfect clustering---one with a single, entirely homogeneous cluster C that covers all positives present in the data set. If we were to produce such a clustering, we could correctly label all positive samples in one step with the simple rule, *all positive samples belong to cluster C*. Under an imperfect clustering, however, the presence of the given sample in a cluster of size two or more implies the sample is only somewhat more likely to be positive, with the confidence of the positive call monotonously increasing with the size of the cluster. In other words, our expectation from a good clustering is that it will help us minimize the amount of work labeling samples. This idea for this metric originated when mining for positive spam examples in large data sets of short user-generated content. Given large enough data sets, spam content naturally forms clusters either because creative rewriting of every single individual spam message is too expensive for spammers to employ, or because, even if human or algorithmic rewriting is applied, one can still find features that link individual spam messages to their creator or to the product or service being promoted in the spam campaign. The finding was consistent with what is reported in literature [104]_. Algorithm --------- Given a clustering, we order the clusters from the largest one to the smallest one. We then plot a cumulative step function where the width of the bin under a given "step" is proportional to cluster size, and the height of the bin is proportional to the expected number of positive samples seen so far [103]_. If a sample is in a cluster of size one, we assume it is likely to be negative and is therefore checked on an individual basis (the specific setting of cluster size at which the expectation changes is our 'threshold' parameter. The result of this assumption is that the expected contribution from unclustered samples is equal to their actual contribution (we assume individual checking always gives a correct answer). After two-way normalization, a perfect clustering (i.e. where a single perfectly homogeneous cluster covers the entire set of positives) will have the AUL score of 1.0. A failure to will result in the AUL of 0.5. A perverse clustering, i.e. one where many negative samples fall into clusters whose size is above our threshold, or where many positive samples remain unclustered (fall into clusters of size below the threshold one) the AUL somewhere between 0.0 and 0.5. A special treatment is necessary for cases where clusters are tied by size. If one were to treat tied clusters as a single group, one would obtain AUL of 1.0 when no clusters at all are present, which is against our desiderata. On the other hand, if one were to treat tied clusters entirely separately, one would obtain different results depending on the properties of the sorting algorithm, also an undesirable situation. Always placing "heavy" clusters (i.e. those containing more positives) towards the beginning or towards the end of the tied group will result in, respectively, overestimating or underestimating the true AUL. The solution here is to average the positive counts among all clusters in a tied group, and then walk through them one by one, with the stepwise cumulative function asymptotically approaching a diagonal from the group's bottom left corner to the top right one. This way, a complete absence of clustering (i.e. all clusters are of size one) will always result in AUL of 0.5. The resulting AUL measure has some similarity with the Gini coefficient of inequality [105]_ except we plot the corresponding curve in the opposite direction (from "richest" to "poorest"), and do not subtract 0.5 from the resulting score. .. [103] We take the expected number of positives and not the actual number seen so far as the vertical scale in order to penalize non-homogeneous clusters. Otherwise the y=1.0 ceiling would be reached early in the process even in very bad cases, for example when there is only one giant non-homogeneous cluster. References ---------- .. [104] `Whissell, J. S., & Clarke, C. L. (2011, September). Clustering for semi-supervised spam filtering. In Proceedings of the 8th Annual Collaboration, Electronic messaging, Anti-Abuse and Spam Conference (pp. 125-134). ACM. <https://doi.org/10.1145/2030376.2030391>`_ .. [105] `Wikipedia entry for Gini coefficient of inequality <https://en.wikipedia.org/wiki/Gini_coefficient>`_ """ import warnings import numpy as np from itertools import izip, chain from operator import itemgetter from pymaptools.iter import aggregate_tuples from pymaptools.containers import labels_to_clusters from clustering_metrics.skutils import auc, roc_curve def num2bool(num): """True if zero or positive real, False otherwise When binarizing class labels, this lets us be consistent with Scikit-Learn where binary labels can be {0, 1} with 0 being negative or {-1, 1} with -1 being negative. """ return num > 0 class LiftCurve(object): """Lift Curve for cluster-size correlated classification """ def __init__(self, score_groups): self._score_groups = list(score_groups) @classmethod def from_counts(cls, counts_true, counts_pred): """Instantiates class from arrays of true and predicted counts Parameters ---------- counts_true : array, shape = [n_clusters] Count of positives in cluster counts_pred : array, shape = [n_clusters] Predicted number of positives in each cluster """ # convert input to a series of tuples count_groups = izip(counts_pred, counts_true) # sort tuples by predicted count in descending order count_groups = sorted(count_groups, key=itemgetter(0), reverse=True) # group tuples by predicted count so as to handle ties correctly return cls(aggregate_tuples(count_groups)) @classmethod def from_clusters(cls, clusters, is_class_pos=num2bool): """Instantiates class from clusters of class-coded points Parameters ---------- clusters : collections.Iterable List of lists of class labels is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ # take all non-empty clusters, score them by size and by number of # ground truth positives data = ((len(cluster), sum(is_class_pos(class_label) for class_label in cluster)) for cluster in clusters if cluster) scores_pred, scores_true = zip(*data) or ([], []) return cls.from_counts(scores_true, scores_pred) @classmethod def from_labels(cls, labels_true, labels_pred, is_class_pos=num2bool): """Instantiates class from arrays of classes and cluster sizes Parameters ---------- labels_true : array, shape = [n_samples] Class labels. If binary, 'is_class_pos' is optional labels_pred : array, shape = [n_samples] Cluster labels to evaluate is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ clusters = labels_to_clusters(labels_true, labels_pred) return cls.from_clusters(clusters, is_class_pos=is_class_pos) def aul_score(self, threshold=1, plot=False): """Calculate AUL score Parameters ---------- threshold : int, optional (default=1) only predicted scores above this number considered accurate plot : bool, optional (default=False) whether to return X and Y data series for plotting """ total_any = 0 total_true = 0 assumed_vertical = 0 aul = 0.0 if plot: xs, ys = [], [] bin_height = 0.0 bin_right_edge = 0.0 # second pass: iterate over each group of predicted scores of the same # size and calculate the AUL metric for pred_score, true_scores in self._score_groups: # number of clusters num_true_scores = len(true_scores) # sum total of positives in all clusters of given size group_height = sum(true_scores) total_true += group_height # cluster size x number of clusters of given size group_width = pred_score * num_true_scores total_any += group_width if pred_score > threshold: # penalize non-homogeneous clusters simply by assuming that they # are homogeneous, in which case their expected vertical # contribution should be equal to their horizontal contribution. height_incr = group_width else: # clusters of size one are by definition homogeneous so their # expected vertical contribution equals sum total of any # remaining true positives. height_incr = group_height assumed_vertical += height_incr if plot: avg_true_score = group_height / float(num_true_scores) for _ in true_scores: bin_height += avg_true_score aul += bin_height * pred_score if plot: xs.append(bin_right_edge) bin_right_edge += pred_score xs.append(bin_right_edge) ys.append(bin_height) ys.append(bin_height) else: # if not tasked with generating plots, use a geometric method # instead of looping aul += (total_true * group_width - ((num_true_scores - 1) * pred_score * group_height) / 2.0) if total_true > total_any: warnings.warn( "Number of positives found (%d) exceeds total count of %d" % (total_true, total_any) ) rect_area = assumed_vertical * total_any # special case: since normalizing the AUL defines it as always smaller # than the bounding rectangle, when denominator in the expression below # is zero, the AUL score is also equal to zero. aul = 0.0 if rect_area == 0 else aul / rect_area if plot: xs = np.array(xs, dtype=float) / total_any ys = np.array(ys, dtype=float) / assumed_vertical return aul, xs, ys else: return aul def plot(self, threshold=1, fill=True, marker=None, save_to=None): # pragma: no cover """Create a graphical representation of Lift Curve Requires Matplotlib Parameters ---------- threshold : int, optional (default=1) only predicted scores above this number considered accurate marker : str, optional (default=None) Whether to draw marker at each bend save_to : str, optional (default=None) If specified, save the plot to path instead of displaying """ from matplotlib import pyplot as plt score, xs, ys = self.aul_score(threshold=threshold, plot=True) fig, ax = plt.subplots() ax.plot(xs, ys, marker=marker, linestyle='-') if fill: ax.fill([0.0] + list(xs) + [1.0], [0.0] + list(ys) + [0.0], 'b', alpha=0.2) ax.plot([0.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.plot([0.0, 1.0], [1.0, 1.0], linestyle='--', color='grey') ax.plot([1.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.set_xlim(xmin=0.0, xmax=1.03) ax.set_ylim(ymin=0.0, ymax=1.04) ax.set_xlabel("portion total") ax.set_ylabel("portion expected positive") ax.set_title("Lift Curve (AUL=%.3f)" % score) if save_to is None: fig.show() else: fig.savefig(save_to) plt.close(fig) def aul_score_from_clusters(clusters): """Calculate AUL score given clusters of class-coded points Parameters ---------- clusters : collections.Iterable List of clusters where each point is binary-coded according to true class. Returns ------- aul : float """ return LiftCurve.from_clusters(clusters).aul_score() def aul_score_from_labels(y_true, labels_pred): """AUL score given array of classes and array of cluster sizes Parameters ---------- y_true : array, shape = [n_samples] True binary labels in range {0, 1} labels_pred : array, shape = [n_samples] Cluster labels to evaluate Returns ------- aul : float """ return LiftCurve.from_labels(y_true, labels_pred).aul_score() class RocCurve(object): """Receiver Operating Characteristic (ROC) :: >>> c = RocCurve.from_labels([0, 0, 1, 1], ... [0.1, 0.4, 0.35, 0.8]) >>> c.auc_score() 0.75 >>> c.max_informedness() 0.5 """ def __init__(self, fprs, tprs, thresholds=None, pos_label=None, sample_weight=None): self.fprs = fprs self.tprs = tprs self.thresholds = thresholds self.pos_label = pos_label self.sample_weight = sample_weight def plot(self, fill=True, marker=None, save_to=None): # pragma: no cover """Plot the ROC curve """ from matplotlib import pyplot as plt score = self.auc_score() xs, ys = self.fprs, self.tprs fig, ax = plt.subplots() ax.plot(xs, ys, marker=marker, linestyle='-') if fill: ax.fill([0.0] + list(xs) + [1.0], [0.0] + list(ys) + [0.0], 'b', alpha=0.2) ax.plot([0.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.plot([0.0, 1.0], [1.0, 1.0], linestyle='--', color='grey') ax.plot([1.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.set_xlim(xmin=0.0, xmax=1.03) ax.set_ylim(ymin=0.0, ymax=1.04) ax.set_ylabel('TPR') ax.set_xlabel('FPR') ax.set_title("ROC Curve (AUC=%.3f)" % score) if save_to is None: fig.show() else: fig.savefig(save_to) plt.close(fig) @classmethod def from_scores(cls, scores_neg, scores_pos): """Instantiate given scores of two ground truth classes The score arrays don't have to be the same length. """ scores_pos = ((1, x) for x in scores_pos if not np.isnan(x)) scores_neg = ((0, x) for x in scores_neg if not np.isnan(x)) all_scores = zip(*chain(scores_neg, scores_pos)) or ([], []) return cls.from_labels(*all_scores) @classmethod def from_labels(cls, labels_true, y_score, is_class_pos=num2bool): """Instantiate assuming binary labeling of {0, 1} labels_true : array, shape = [n_samples] Class labels. If binary, 'is_class_pos' is optional y_score : array, shape = [n_samples] Predicted scores is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ # num2bool Y labels y_true = map(is_class_pos, labels_true) # calculate axes fprs, tprs, thresholds = roc_curve( y_true, y_score, pos_label=True) return cls(fprs, tprs, thresholds=thresholds) @classmethod def from_clusters(cls, clusters, is_class_pos=num2bool): """Instantiates class from clusters of class-coded points Parameters ---------- clusters : collections.Iterable List of lists of class labels is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ y_true = [] y_score = [] for cluster in clusters: pred_cluster = len(cluster) for point in cluster: true_cluster = is_class_pos(point) y_true.append(true_cluster) y_score.append(pred_cluster) return cls.from_labels(y_true, y_score) def auc_score(self): """Replacement for Scikit-Learn's method If number of Y classes is other than two, a warning will be triggered but no exception thrown (the return value will be a NaN). Also, we don't reorder arrays during ROC calculation since they are assumed to be in order. """ return auc(self.fprs, self.tprs, reorder=False) def optimal_cutoff(self, scoring_method): """Optimal cutoff point on ROC curve under scoring method The scoring method must take two arguments: fpr and tpr. """ max_index = np.NINF opt_pair = (np.nan, np.nan) for pair in izip(self.fprs, self.tprs): index = scoring_method(*pair) if index > max_index: opt_pair = pair max_index = index return opt_pair, max_index @staticmethod def _informedness(fpr, tpr): return tpr - fpr def max_informedness(self): """Maximum value of Informedness (TPR minus FPR) on a ROC curve A diagram of what this measure looks like is shown in [101]_. Note a correspondence between the definitions of this measure and that of Kolmogorov-Smirnov's supremum statistic. References ---------- .. [101] `Wikipedia entry for Youden's J statistic <https://en.wikipedia.org/wiki/Youden%27s_J_statistic>`_ """ return self.optimal_cutoff(self._informedness)[1] def roc_auc_score(y_true, y_score, sample_weight=None): """AUC score for a ROC curve Replaces Scikit Learn implementation (given binary ``y_true``). """ return RocCurve.from_labels(y_true, y_score).auc_score() def dist_auc(scores0, scores1): """AUC score for two distributions, with NaN correction Note: arithmetic mean appears to be appropriate here, as other means don't result in total of 1.0 when sides are switched. """ scores0_len = len(scores0) scores1_len = len(scores1) scores0p = [x for x in scores0 if not np.isnan(x)] scores1p = [x for x in scores1 if not np.isnan(x)] scores0n_len = scores0_len - len(scores0p) scores1n_len = scores1_len - len(scores1p) # ``nan_pairs`` are pairs for which it is impossible to define order, due # to at least one of the members of each being a NaN. ``def_pairs`` are # pairs for which order can be established. all_pairs = 2 * scores0_len * scores1_len nan_pairs = scores0n_len * scores1_len + scores1n_len * scores0_len def_pairs = all_pairs - nan_pairs # the final score is the average of the score for the defined portion and # of random-chance AUC (0.5), weighted according to the number of pairs in # each group. auc_score = RocCurve.from_scores(scores0p, scores1p).auc_score() return np.average([auc_score, 0.5], weights=[def_pairs, nan_pairs])
bsd-3-clause
ghislainv/deforestprob
forestatrisk/__init__.py
1
1461
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================== # author :Ghislain Vieilledent # email :[email protected], [email protected] # web :https://ecology.ghislainv.fr # python_version :>=2.7 # license :GPLv3 # ============================================================================== from __future__ import division, print_function # Python 3 compatibility import os import matplotlib if os.environ.get("DISPLAY", "") == "": print("no display found. Using non-interactive Agg backend") matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np # from data import country from .accuracy import confmat, accuracy from .interpolate_rho import interpolate_rho from .miscellaneous import invlogit, make_dir from . import plot from .model_binomial_iCAR import model_binomial_iCAR from .model_random_forest import model_random_forest from .sample import sample from .cellneigh import cellneigh, cellneigh_ctry from .predict_raster import predict_raster from .predict_raster_binomial_iCAR import predict_raster_binomial_iCAR from .resample_sum import resample_sum from .deforest import deforest from .validation import accuracy_indices, validation from .validation_npix import validation_npix from .emissions import emissions from .countpix import countpix from .diffproj import r_diffproj, mat_diffproj # End
gpl-3.0
chiahaoliu/2016_summer_XPD
XPD_view/plot_analysis.py
1
3819
import matplotlib.pyplot as plt from analysis_concurrent import analysis_concurrent #from file import get_files import multiprocessing class reducedRepPlot: def __init__(self, tif_list, x_start, x_stop, y_start, y_stop, selection): """ constructor for reducedRepPlot object :param file_path: path to file directory :type file_path: str :param x_start: start val for x analysis :param x_stop: stop val for x analysis :param y_start: :param y_stop: """ #self.tif_list = get_files(file_path) self.tif_list = tif_list assert x_start >= 0 and x_start < x_stop assert x_stop <= 2048 #TODO change so resolution is flexible assert y_start >= 0 and y_start < y_stop assert y_stop <= 2048 #TODO change so resolution is flexible self.x_start = x_start self.x_stop = x_stop self.y_start = y_start self.y_stop = y_stop self.selection = selection def selectionSort(self, alist): for fillslot in range(len(alist) - 1, 0, -1): positionOfMax = 0 for location in range(1, fillslot + 1): if alist[location][0] > alist[positionOfMax][0]: positionOfMax = location temp = alist[fillslot] alist[fillslot] = alist[positionOfMax] alist[positionOfMax] = temp for arr in alist: arr.pop(0) return alist # def check_lists(self, list, nested_list, cpu_num): # flattened_list = [val for sublist in nested_list for val in sublist] # for i in range(0,cpu_num): # flattened_list.remove(i) # # print(flattened_list == list) def plot(self): """ This function will plot analysis data as a funciton of the number of images. uses multiprocessing to speed things up :return: void """ a = analysis_concurrent(self.y_start, self.y_stop, self.x_start, self.x_stop, self.selection) trunc_list = [] cpu_count = 10 #multiprocessing.cpu_count() temp_list = [] for i in range(0, cpu_count): if i == cpu_count-1: temp_list = self.tif_list[(i*len(self.tif_list)//cpu_count) : (((1+i)*len(self.tif_list)//cpu_count) + (len(self.tif_list)%cpu_count))] temp_list.insert(0, i) else: temp_list = self.tif_list[(i*len(self.tif_list)//cpu_count) : ((1+i)*len(self.tif_list)//cpu_count)] temp_list.insert(0, i) trunc_list.append(temp_list) # print(self.check_lists(self.tif_list, trunc_list, cpu_count)) process_list = [] x = range(0,len(self.tif_list)) y = [] q = multiprocessing.Queue() #a = multiprocessing.Array() l = multiprocessing.Lock() #p = multiprocessing.Process(a.x_and_y_vals, args=(l,)) for i in range(0, cpu_count): process_list.append(multiprocessing.Process(target=a.x_and_y_vals, args=(l, q, trunc_list[i]))) for process in process_list: process.start() for process in process_list: y.append(q.get()) process.join() # for i in range(0,cpu_count): # y.append(q.get()) y = self.selectionSort(y) flattened_y = [val for sublist in y for val in sublist] assert len(flattened_y) == len(self.tif_list) plt.scatter(x, flattened_y) plt.xlabel("file num") plt.ylabel(self.selection) # plt.xscale() plt.show()
bsd-2-clause