repo_name
stringlengths
7
92
path
stringlengths
5
129
copies
stringclasses
201 values
size
stringlengths
4
6
content
stringlengths
1.03k
375k
license
stringclasses
15 values
edxnercel/edx-platform
.pycharm_helpers/pydev/pydev_ipython/inputhook.py
52
18411
# coding: utf-8 """ Inputhook management for GUI event loop integration. """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import sys import select #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Constants for identifying the GUI toolkits. GUI_WX = 'wx' GUI_QT = 'qt' GUI_QT4 = 'qt4' GUI_GTK = 'gtk' GUI_TK = 'tk' GUI_OSX = 'osx' GUI_GLUT = 'glut' GUI_PYGLET = 'pyglet' GUI_GTK3 = 'gtk3' GUI_NONE = 'none' # i.e. disable #----------------------------------------------------------------------------- # Utilities #----------------------------------------------------------------------------- def ignore_CTRL_C(): """Ignore CTRL+C (not implemented).""" pass def allow_CTRL_C(): """Take CTRL+C into account (not implemented).""" pass #----------------------------------------------------------------------------- # Main InputHookManager class #----------------------------------------------------------------------------- class InputHookManager(object): """Manage PyOS_InputHook for different GUI toolkits. This class installs various hooks under ``PyOSInputHook`` to handle GUI event loop integration. """ def __init__(self): self._return_control_callback = None self._apps = {} self._reset() self.pyplot_imported = False def _reset(self): self._callback_pyfunctype = None self._callback = None self._current_gui = None def set_return_control_callback(self, return_control_callback): self._return_control_callback = return_control_callback def get_return_control_callback(self): return self._return_control_callback def return_control(self): return self._return_control_callback() def get_inputhook(self): return self._callback def set_inputhook(self, callback): """Set inputhook to callback.""" # We don't (in the context of PyDev console) actually set PyOS_InputHook, but rather # while waiting for input on xmlrpc we run this code self._callback = callback def clear_inputhook(self, app=None): """Clear input hook. Parameters ---------- app : optional, ignored This parameter is allowed only so that clear_inputhook() can be called with a similar interface as all the ``enable_*`` methods. But the actual value of the parameter is ignored. This uniform interface makes it easier to have user-level entry points in the main IPython app like :meth:`enable_gui`.""" self._reset() def clear_app_refs(self, gui=None): """Clear IPython's internal reference to an application instance. Whenever we create an app for a user on qt4 or wx, we hold a reference to the app. This is needed because in some cases bad things can happen if a user doesn't hold a reference themselves. This method is provided to clear the references we are holding. Parameters ---------- gui : None or str If None, clear all app references. If ('wx', 'qt4') clear the app for that toolkit. References are not held for gtk or tk as those toolkits don't have the notion of an app. """ if gui is None: self._apps = {} elif gui in self._apps: del self._apps[gui] def enable_wx(self, app=None): """Enable event loop integration with wxPython. Parameters ---------- app : WX Application, optional. Running application to use. If not given, we probe WX for an existing application object, and create a new one if none is found. Notes ----- This methods sets the ``PyOS_InputHook`` for wxPython, which allows the wxPython to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`wx.App` as follows:: import wx app = wx.App(redirect=False, clearSigInt=False) """ import wx from distutils.version import LooseVersion as V wx_version = V(wx.__version__).version if wx_version < [2, 8]: raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__) from pydev_ipython.inputhookwx import inputhook_wx self.set_inputhook(inputhook_wx) self._current_gui = GUI_WX if app is None: app = wx.GetApp() if app is None: app = wx.App(redirect=False, clearSigInt=False) app._in_event_loop = True self._apps[GUI_WX] = app return app def disable_wx(self): """Disable event loop integration with wxPython. This merely sets PyOS_InputHook to NULL. """ if GUI_WX in self._apps: self._apps[GUI_WX]._in_event_loop = False self.clear_inputhook() def enable_qt4(self, app=None): """Enable event loop integration with PyQt4. Parameters ---------- app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Notes ----- This methods sets the PyOS_InputHook for PyQt4, which allows the PyQt4 to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`QApplication` as follows:: from PyQt4 import QtCore app = QtGui.QApplication(sys.argv) """ from pydev_ipython.inputhookqt4 import create_inputhook_qt4 app, inputhook_qt4 = create_inputhook_qt4(self, app) self.set_inputhook(inputhook_qt4) self._current_gui = GUI_QT4 app._in_event_loop = True self._apps[GUI_QT4] = app return app def disable_qt4(self): """Disable event loop integration with PyQt4. This merely sets PyOS_InputHook to NULL. """ if GUI_QT4 in self._apps: self._apps[GUI_QT4]._in_event_loop = False self.clear_inputhook() def enable_gtk(self, app=None): """Enable event loop integration with PyGTK. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for PyGTK, which allows the PyGTK to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookgtk import create_inputhook_gtk self.set_inputhook(create_inputhook_gtk(self._stdin_file)) self._current_gui = GUI_GTK def disable_gtk(self): """Disable event loop integration with PyGTK. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_tk(self, app=None): """Enable event loop integration with Tk. Parameters ---------- app : toplevel :class:`Tkinter.Tk` widget, optional. Running toplevel widget to use. If not given, we probe Tk for an existing one, and create a new one if none is found. Notes ----- If you have already created a :class:`Tkinter.Tk` object, the only thing done by this method is to register with the :class:`InputHookManager`, since creating that object automatically sets ``PyOS_InputHook``. """ self._current_gui = GUI_TK if app is None: try: import Tkinter as _TK except: # Python 3 import tkinter as _TK app = _TK.Tk() app.withdraw() self._apps[GUI_TK] = app from pydev_ipython.inputhooktk import create_inputhook_tk self.set_inputhook(create_inputhook_tk(app)) return app def disable_tk(self): """Disable event loop integration with Tkinter. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_glut(self, app=None): """ Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to integrate with terminal based applications like IPython. Due to GLUT limitations, it is currently not possible to start the event loop without first creating a window. You should thus not create another window but use instead the created one. See 'gui-glut.py' in the docs/examples/lib directory. The default screen mode is set to: glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH """ import OpenGL.GLUT as glut from pydev_ipython.inputhookglut import glut_display_mode, \ glut_close, glut_display, \ glut_idle, inputhook_glut if GUI_GLUT not in self._apps: glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut_display_mode) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS) glut.glutCreateWindow(sys.argv[0]) glut.glutReshapeWindow(1, 1) glut.glutHideWindow() glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) else: glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) self.set_inputhook(inputhook_glut) self._current_gui = GUI_GLUT self._apps[GUI_GLUT] = True def disable_glut(self): """Disable event loop integration with glut. This sets PyOS_InputHook to NULL and set the display function to a dummy one and set the timer to a dummy timer that will be triggered very far in the future. """ import OpenGL.GLUT as glut from glut_support import glutMainLoopEvent # @UnresolvedImport glut.glutHideWindow() # This is an event to be processed below glutMainLoopEvent() self.clear_inputhook() def enable_pyglet(self, app=None): """Enable event loop integration with pyglet. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the ``PyOS_InputHook`` for pyglet, which allows pyglet to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookpyglet import inputhook_pyglet self.set_inputhook(inputhook_pyglet) self._current_gui = GUI_PYGLET return app def disable_pyglet(self): """Disable event loop integration with pyglet. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_gtk3(self, app=None): """Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for Gtk3, which allows the Gtk3 to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3 self.set_inputhook(create_inputhook_gtk3(self._stdin_file)) self._current_gui = GUI_GTK def disable_gtk3(self): """Disable event loop integration with PyGTK. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_mac(self, app=None): """ Enable event loop integration with MacOSX. We call function pyplot.pause, which updates and displays active figure during pause. It's not MacOSX-specific, but it enables to avoid inputhooks in native MacOSX backend. Also we shouldn't import pyplot, until user does it. Cause it's possible to choose backend before importing pyplot for the first time only. """ def inputhook_mac(app=None): if self.pyplot_imported: pyplot = sys.modules['matplotlib.pyplot'] try: pyplot.pause(0.01) except: pass else: if 'matplotlib.pyplot' in sys.modules: self.pyplot_imported = True self.set_inputhook(inputhook_mac) self._current_gui = GUI_OSX def disable_mac(self): self.clear_inputhook() def current_gui(self): """Return a string indicating the currently active GUI or None.""" return self._current_gui inputhook_manager = InputHookManager() enable_wx = inputhook_manager.enable_wx disable_wx = inputhook_manager.disable_wx enable_qt4 = inputhook_manager.enable_qt4 disable_qt4 = inputhook_manager.disable_qt4 enable_gtk = inputhook_manager.enable_gtk disable_gtk = inputhook_manager.disable_gtk enable_tk = inputhook_manager.enable_tk disable_tk = inputhook_manager.disable_tk enable_glut = inputhook_manager.enable_glut disable_glut = inputhook_manager.disable_glut enable_pyglet = inputhook_manager.enable_pyglet disable_pyglet = inputhook_manager.disable_pyglet enable_gtk3 = inputhook_manager.enable_gtk3 disable_gtk3 = inputhook_manager.disable_gtk3 enable_mac = inputhook_manager.enable_mac disable_mac = inputhook_manager.disable_mac clear_inputhook = inputhook_manager.clear_inputhook set_inputhook = inputhook_manager.set_inputhook current_gui = inputhook_manager.current_gui clear_app_refs = inputhook_manager.clear_app_refs # We maintain this as stdin_ready so that the individual inputhooks # can diverge as little as possible from their IPython sources stdin_ready = inputhook_manager.return_control set_return_control_callback = inputhook_manager.set_return_control_callback get_return_control_callback = inputhook_manager.get_return_control_callback get_inputhook = inputhook_manager.get_inputhook # Convenience function to switch amongst them def enable_gui(gui=None, app=None): """Switch amongst GUI input hooks by name. This is just a utility wrapper around the methods of the InputHookManager object. Parameters ---------- gui : optional, string or None If None (or 'none'), clears input hook, otherwise it must be one of the recognized GUI names (see ``GUI_*`` constants in module). app : optional, existing application object. For toolkits that have the concept of a global app, you can supply an existing one. If not given, the toolkit will be probed for one, and if none is found, a new one will be created. Note that GTK does not have this concept, and passing an app if ``gui=="GTK"`` will raise an error. Returns ------- The output of the underlying gui switch routine, typically the actual PyOS_InputHook wrapper object or the GUI toolkit app created, if there was one. """ if get_return_control_callback() is None: raise ValueError("A return_control_callback must be supplied as a reference before a gui can be enabled") guis = {GUI_NONE: clear_inputhook, GUI_OSX: enable_mac, GUI_TK: enable_tk, GUI_GTK: enable_gtk, GUI_WX: enable_wx, GUI_QT: enable_qt4, # qt3 not supported GUI_QT4: enable_qt4, GUI_GLUT: enable_glut, GUI_PYGLET: enable_pyglet, GUI_GTK3: enable_gtk3, } try: gui_hook = guis[gui] except KeyError: if gui is None or gui == '': gui_hook = clear_inputhook else: e = "Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys()) raise ValueError(e) return gui_hook(app) __all__ = [ "GUI_WX", "GUI_QT", "GUI_QT4", "GUI_GTK", "GUI_TK", "GUI_OSX", "GUI_GLUT", "GUI_PYGLET", "GUI_GTK3", "GUI_NONE", "ignore_CTRL_C", "allow_CTRL_C", "InputHookManager", "inputhook_manager", "enable_wx", "disable_wx", "enable_qt4", "disable_qt4", "enable_gtk", "disable_gtk", "enable_tk", "disable_tk", "enable_glut", "disable_glut", "enable_pyglet", "disable_pyglet", "enable_gtk3", "disable_gtk3", "enable_mac", "disable_mac", "clear_inputhook", "set_inputhook", "current_gui", "clear_app_refs", "stdin_ready", "set_return_control_callback", "get_return_control_callback", "get_inputhook", "enable_gui"]
agpl-3.0
tcarmelveilleux/IcarusAltimeter
Analysis/altitude_analysis.py
1
1202
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 19:34:31 2015 @author: Tennessee """ import numpy as np import matplotlib.pyplot as plt def altitude(atm_hpa, sea_level_hpa): return 44330 * (1.0 - np.power(atm_hpa / sea_level_hpa, 0.1903)) def plot_alt(): default_msl = 101300.0 pressure = np.linspace(97772.58 / 100.0, 79495.0 / 100.0, 2000) alt_nominal = altitude(pressure, default_msl) - altitude(97772.58 / 100.0, default_msl) alt_too_high = altitude(pressure, default_msl + (1000 / 100.0)) - altitude(97772.58 / 100.0, default_msl + (1000 / 100.0)) alt_too_low = altitude(pressure, default_msl - (1000 / 100.0)) - altitude(97772.58 / 100.0, default_msl - (1000 / 100.0)) f1 = plt.figure() ax = f1.gca() ax.plot(pressure, alt_nominal, "b-", label="nom") ax.plot(pressure, alt_too_high, "r-", label="high") ax.plot(pressure, alt_too_low, "g-", label="low") ax.legend() f1.show() f2 = plt.figure() ax = f2.gca() ax.plot(pressure, alt_too_high - alt_nominal, "r-", label="high") ax.plot(pressure, alt_too_low - alt_nominal, "g-", label="low") ax.legend() f2.show()
mit
PatrickOReilly/scikit-learn
examples/plot_johnson_lindenstrauss_bound.py
67
7474
r""" ===================================================================== The Johnson-Lindenstrauss bound for embedding with random projections ===================================================================== The `Johnson-Lindenstrauss lemma`_ states that any high dimensional dataset can be randomly projected into a lower dimensional Euclidean space while controlling the distortion in the pairwise distances. .. _`Johnson-Lindenstrauss lemma`: https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma Theoretical bounds ================== The distortion introduced by a random projection `p` is asserted by the fact that `p` is defining an eps-embedding with good probability as defined by: .. math:: (1 - eps) \|u - v\|^2 < \|p(u) - p(v)\|^2 < (1 + eps) \|u - v\|^2 Where u and v are any rows taken from a dataset of shape [n_samples, n_features] and p is a projection by a random Gaussian N(0, 1) matrix with shape [n_components, n_features] (or a sparse Achlioptas matrix). The minimum number of components to guarantees the eps-embedding is given by: .. math:: n\_components >= 4 log(n\_samples) / (eps^2 / 2 - eps^3 / 3) The first plot shows that with an increasing number of samples ``n_samples``, the minimal number of dimensions ``n_components`` increased logarithmically in order to guarantee an ``eps``-embedding. The second plot shows that an increase of the admissible distortion ``eps`` allows to reduce drastically the minimal number of dimensions ``n_components`` for a given number of samples ``n_samples`` Empirical validation ==================== We validate the above bounds on the digits dataset or on the 20 newsgroups text document (TF-IDF word frequencies) dataset: - for the digits dataset, some 8x8 gray level pixels data for 500 handwritten digits pictures are randomly projected to spaces for various larger number of dimensions ``n_components``. - for the 20 newsgroups dataset some 500 documents with 100k features in total are projected using a sparse random matrix to smaller euclidean spaces with various values for the target number of dimensions ``n_components``. The default dataset is the digits dataset. To run the example on the twenty newsgroups dataset, pass the --twenty-newsgroups command line argument to this script. For each value of ``n_components``, we plot: - 2D distribution of sample pairs with pairwise distances in original and projected spaces as x and y axis respectively. - 1D histogram of the ratio of those distances (projected / original). We can see that for low values of ``n_components`` the distribution is wide with many distorted pairs and a skewed distribution (due to the hard limit of zero ratio on the left as distances are always positives) while for larger values of n_components the distortion is controlled and the distances are well preserved by the random projection. Remarks ======= According to the JL lemma, projecting 500 samples without too much distortion will require at least several thousands dimensions, irrespective of the number of features of the original dataset. Hence using random projections on the digits dataset which only has 64 features in the input space does not make sense: it does not allow for dimensionality reduction in this case. On the twenty newsgroups on the other hand the dimensionality can be decreased from 56436 down to 10000 while reasonably preserving pairwise distances. """ print(__doc__) import sys from time import time import numpy as np import matplotlib.pyplot as plt from sklearn.random_projection import johnson_lindenstrauss_min_dim from sklearn.random_projection import SparseRandomProjection from sklearn.datasets import fetch_20newsgroups_vectorized from sklearn.datasets import load_digits from sklearn.metrics.pairwise import euclidean_distances # Part 1: plot the theoretical dependency between n_components_min and # n_samples # range of admissible distortions eps_range = np.linspace(0.1, 0.99, 5) colors = plt.cm.Blues(np.linspace(0.3, 1.0, len(eps_range))) # range of number of samples (observation) to embed n_samples_range = np.logspace(1, 9, 9) plt.figure() for eps, color in zip(eps_range, colors): min_n_components = johnson_lindenstrauss_min_dim(n_samples_range, eps=eps) plt.loglog(n_samples_range, min_n_components, color=color) plt.legend(["eps = %0.1f" % eps for eps in eps_range], loc="lower right") plt.xlabel("Number of observations to eps-embed") plt.ylabel("Minimum number of dimensions") plt.title("Johnson-Lindenstrauss bounds:\nn_samples vs n_components") # range of admissible distortions eps_range = np.linspace(0.01, 0.99, 100) # range of number of samples (observation) to embed n_samples_range = np.logspace(2, 6, 5) colors = plt.cm.Blues(np.linspace(0.3, 1.0, len(n_samples_range))) plt.figure() for n_samples, color in zip(n_samples_range, colors): min_n_components = johnson_lindenstrauss_min_dim(n_samples, eps=eps_range) plt.semilogy(eps_range, min_n_components, color=color) plt.legend(["n_samples = %d" % n for n in n_samples_range], loc="upper right") plt.xlabel("Distortion eps") plt.ylabel("Minimum number of dimensions") plt.title("Johnson-Lindenstrauss bounds:\nn_components vs eps") # Part 2: perform sparse random projection of some digits images which are # quite low dimensional and dense or documents of the 20 newsgroups dataset # which is both high dimensional and sparse if '--twenty-newsgroups' in sys.argv: # Need an internet connection hence not enabled by default data = fetch_20newsgroups_vectorized().data[:500] else: data = load_digits().data[:500] n_samples, n_features = data.shape print("Embedding %d samples with dim %d using various random projections" % (n_samples, n_features)) n_components_range = np.array([300, 1000, 10000]) dists = euclidean_distances(data, squared=True).ravel() # select only non-identical samples pairs nonzero = dists != 0 dists = dists[nonzero] for n_components in n_components_range: t0 = time() rp = SparseRandomProjection(n_components=n_components) projected_data = rp.fit_transform(data) print("Projected %d samples from %d to %d in %0.3fs" % (n_samples, n_features, n_components, time() - t0)) if hasattr(rp, 'components_'): n_bytes = rp.components_.data.nbytes n_bytes += rp.components_.indices.nbytes print("Random matrix with size: %0.3fMB" % (n_bytes / 1e6)) projected_dists = euclidean_distances( projected_data, squared=True).ravel()[nonzero] plt.figure() plt.hexbin(dists, projected_dists, gridsize=100, cmap=plt.cm.PuBu) plt.xlabel("Pairwise squared distances in original space") plt.ylabel("Pairwise squared distances in projected space") plt.title("Pairwise distances distribution for n_components=%d" % n_components) cb = plt.colorbar() cb.set_label('Sample pairs counts') rates = projected_dists / dists print("Mean distances rate: %0.2f (%0.2f)" % (np.mean(rates), np.std(rates))) plt.figure() plt.hist(rates, bins=50, normed=True, range=(0., 2.)) plt.xlabel("Squared distances rate: projected / original") plt.ylabel("Distribution of samples pairs") plt.title("Histogram of pairwise distance rates for n_components=%d" % n_components) # TODO: compute the expected value of eps and add them to the previous plot # as vertical lines / region plt.show()
bsd-3-clause
do-mpc/do-mpc
testing/test_oscillating_masses_discrete_dae.py
1
3206
# # This file is part of do-mpc # # do-mpc: An environment for the easy, modular and efficient implementation of # robust nonlinear model predictive control # # Copyright (c) 2014-2019 Sergio Lucia, Alexandru Tatulea-Codrean # TU Dortmund. All rights reserved # # do-mpc is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # # do-mpc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU General Public License # along with do-mpc. If not, see <http://www.gnu.org/licenses/>. import numpy as np import matplotlib.pyplot as plt from casadi import * from casadi.tools import * import pdb import sys import unittest sys.path.append('../') import do_mpc sys.path.pop(-1) sys.path.append('../examples/oscillating_masses_discrete_dae/') from template_model import template_model from template_mpc import template_mpc from template_simulator import template_simulator sys.path.pop(-1) class TestOscillatingMassesDiscrete(unittest.TestCase): def test_oscillating_masses_discrete(self): """ Get configured do-mpc modules: """ model = template_model() mpc = template_mpc(model) simulator = template_simulator(model) estimator = do_mpc.estimator.StateFeedback(model) """ Set initial state """ np.random.seed(99) x0 = np.random.rand(model.n_x)-0.5 mpc.x0 = x0 simulator.x0 = x0 estimator.x0 = x0 # Use initial state to set the initial guess. mpc.set_initial_guess() # This is only meaningful for DAE systems. simulator.set_initial_guess() """ Run some steps: """ for k in range(5): u0 = mpc.make_step(x0) y_next = simulator.make_step(u0) x0 = estimator.make_step(y_next) """ Store results (from reference run): """ #do_mpc.data.save_results([mpc, simulator, estimator], 'results_oscillatingMasses_dae', overwrite=True) """ Compare results to reference run: """ ref = do_mpc.data.load_results('./results/results_oscillatingMasses_dae.pkl') test = ['_x', '_u', '_aux', '_time', '_z'] for test_i in test: # Check MPC check = np.allclose(mpc.data.__dict__[test_i], ref['mpc'].__dict__[test_i]) self.assertTrue(check) # Check Simulator check = np.allclose(simulator.data.__dict__[test_i], ref['simulator'].__dict__[test_i]) self.assertTrue(check) # Estimator check = np.allclose(estimator.data.__dict__[test_i], ref['estimator'].__dict__[test_i]) self.assertTrue(check) if __name__ == '__main__': unittest.main()
lgpl-3.0
mdmueller/ascii-profiling
parallel.py
1
4245
import timeit import time from astropy.io import ascii import pandas import numpy as np from astropy.table import Table, Column from tempfile import NamedTemporaryFile import random import string import matplotlib.pyplot as plt import webbrowser def make_table(table, size=10000, n_floats=10, n_ints=0, n_strs=0, float_format=None, str_val=None): if str_val is None: str_val = "abcde12345" cols = [] for i in xrange(n_floats): dat = np.random.uniform(low=1, high=10, size=size) cols.append(Column(dat, name='f{}'.format(i))) for i in xrange(n_ints): dat = np.random.randint(low=-9999999, high=9999999, size=size) cols.append(Column(dat, name='i{}'.format(i))) for i in xrange(n_strs): if str_val == 'random': dat = np.array([''.join([random.choice(string.letters) for j in range(10)]) for k in range(size)]) else: dat = np.repeat(str_val, size) cols.append(Column(dat, name='s{}'.format(i))) t = Table(cols) if float_format is not None: for col in t.columns.values(): if col.name.startswith('f'): col.format = float_format t.write(table.name, format='ascii') output_text = [] def plot_case(n_floats=10, n_ints=0, n_strs=0, float_format=None, str_val=None): global table1, output_text n_rows = (10000, 20000, 50000, 100000, 200000) # include 200000 for publish run numbers = (1, 1, 1, 1, 1) repeats = (3, 2, 1, 1, 1) times_fast = [] times_fast_parallel = [] times_pandas = [] for n_row, number, repeat in zip(n_rows, numbers, repeats): table1 = NamedTemporaryFile() make_table(table1, n_row, n_floats, n_ints, n_strs, float_format, str_val) t = timeit.repeat("ascii.read(table1.name, format='basic', guess=False, use_fast_converter=True)", setup='from __main__ import ascii, table1', number=number, repeat=repeat) times_fast.append(min(t) / number) t = timeit.repeat("ascii.read(table1.name, format='basic', guess=False, parallel=True, use_fast_converter=True)", setup='from __main__ import ascii, table1', number=number, repeat=repeat) times_fast_parallel.append(min(t) / number) t = timeit.repeat("pandas.read_csv(table1.name, sep=' ', header=0)", setup='from __main__ import table1, pandas', number=number, repeat=repeat) times_pandas.append(min(t) / number) plt.loglog(n_rows, times_fast, '-or', label='io.ascii Fast-c') plt.loglog(n_rows, times_fast_parallel, '-og', label='io.ascii Parallel Fast-c') plt.loglog(n_rows, times_pandas, '-oc', label='Pandas') plt.grid() plt.legend(loc='best') plt.title('n_floats={} n_ints={} n_strs={} float_format={} str_val={}'.format( n_floats, n_ints, n_strs, float_format, str_val)) plt.xlabel('Number of rows') plt.ylabel('Time (sec)') img_file = 'graph{}.png'.format(len(output_text) + 1) plt.savefig(img_file) plt.clf() text = 'Pandas to io.ascii Fast-C speed ratio: {:.2f} : 1<br/>'.format(times_fast[-1] / times_pandas[-1]) text += 'io.ascii parallel to Pandas speed ratio: {:.2f} : 1'.format(times_pandas[-1] / times_fast_parallel[-1]) output_text.append((img_file, text)) plot_case(n_floats=10, n_ints=0, n_strs=0) plot_case(n_floats=10, n_ints=10, n_strs=10) plot_case(n_floats=10, n_ints=10, n_strs=10, float_format='%.4f') plot_case(n_floats=10, n_ints=0, n_strs=0, float_format='%.4f') plot_case(n_floats=0, n_ints=0, n_strs=10) plot_case(n_floats=0, n_ints=0, n_strs=10, str_val="'asdf asdfa'") plot_case(n_floats=0, n_ints=0, n_strs=10, str_val="random") plot_case(n_floats=0, n_ints=10, n_strs=0) html_file = open('out.html', 'w') html_file.write('<html><head><meta charset="utf-8"/><meta content="text/html;charset=UTF-8" http-equiv="Content-type"/>') html_file.write('</html><body><h1 style="text-align:center;">Profile of io.ascii</h1>') for img, descr in output_text: html_file.write('<img src="{}"><p style="font-weight:bold;">{}</p><hr>'.format(img, descr)) html_file.write('</body></html>') html_file.close() webbrowser.open('out.html')
mit
gtcasl/eiger
Eiger.py
1
20400
#!/usr/bin/python # # \file Eiger.py # \author Eric Anger <eanger@gatech.edu> # \date July 6, 2012 # # \brief Command line interface into Eiger modeling framework # # \changes Added more plot functionality; Benjamin Allan, SNL 5/2013 # import argparse import matplotlib.pyplot as plt import numpy as np import math import tempfile import shutil import os from ast import literal_eval import json import sys from collections import namedtuple from tabulate import tabulate from sklearn.cluster import KMeans from eiger import database, PCA, LinearRegression Model = namedtuple('Model', ['metric_names', 'means', 'stdevs', 'rotation_matrix', 'kmeans', 'models']) def import_model(args): database.addModelFromFile(args.database, args.file, args.source_name, args.description) def export_model(args): database.dumpModelToFile(args.database, args.file, args.id) def list_models(args): all_models = database.getModels(args.database) print tabulate(all_models, headers=['ID', 'Description', 'Created', 'Source']) def trainModel(args): print "Training the model..." training_DC = database.DataCollection(args.training_dc, args.database) try: performance_metric_id = [m[0] for m in training_DC.metrics].index(args.target) except ValueError: print "Unable to find target metric '%s', " \ "please specify a valid one: " % (args.target,) for (my_name,my_desc,my_type) in training_DC.metrics: print "\t%s" % (my_name,) return training_performance = training_DC.profile[:,performance_metric_id] metric_names = [m[0] for m in training_DC.metrics if m[0] != args.target] if args.predictor_metrics != None: metric_names = filter(lambda x: x in args.predictor_metrics, metric_names) metric_ids = [[m[0] for m in training_DC.metrics].index(n) for n in metric_names] if not metric_ids: print "Unable to make model for empty data collection. Aborting..." return training_profile = training_DC.profile[:,metric_ids] #pca training_pca = PCA.PCA(training_profile) nonzero_components = training_pca.nonzeroComponents() rotation_matrix = training_pca.components[:,nonzero_components] rotated_training_profile = np.dot(training_profile, rotation_matrix) #kmeans n_clusters = args.clusters kmeans = KMeans(n_clusters) means = np.mean(rotated_training_profile, axis=0) stdevs = np.std(rotated_training_profile - means, axis=0, ddof=1) stdevs[stdevs==0.0] = 1.0 clusters = kmeans.fit_predict((rotated_training_profile - means)/stdevs) # reserve a vector for each model created per cluster models = [0] * len(clusters) print "Modeling..." for i in range(n_clusters): cluster_profile = rotated_training_profile[clusters==i,:] cluster_performance = training_performance[clusters==i] regression = LinearRegression.LinearRegression(cluster_profile, cluster_performance) pool = [LinearRegression.identityFunction()] for col in range(cluster_profile.shape[1]): if('inv_quadratic' in args.regressor_functions): pool.append(LinearRegression.powerFunction(col, -2)) if('inv_linear' in args.regressor_functions): pool.append(LinearRegression.powerFunction(col, -1)) if('inv_sqrt' in args.regressor_functions): pool.append(LinearRegression.powerFunction(col, -.5)) if('sqrt' in args.regressor_functions): pool.append(LinearRegression.powerFunction(col, .5)) if('linear' in args.regressor_functions): pool.append(LinearRegression.powerFunction(col, 1)) if('quadratic' in args.regressor_functions): pool.append(LinearRegression.powerFunction(col, 2)) if('log' in args.regressor_functions): pool.append(LinearRegression.logFunction(col)) if('cross' in args.regressor_functions): for xcol in range(col, cluster_profile.shape[1]): pool.append(LinearRegression.crossFunction(col, xcol)) if('div' in args.regressor_functions): for xcol in range(col, cluster_profile.shape[1]): pool.append(LinearRegression.divFunction(col,xcol)) pool.append(LinearRegression.divFunction(xcol,col)) (models[i], r_squared, r_squared_adj) = regression.select(pool, threshold=args.threshold, folds=args.nfolds) print "Index\tMetric Name" print '\n'.join("%s\t%s" % metric for metric in enumerate(metric_names)) print "PCA matrix:" print rotation_matrix print "Model:\n" + str(models[i]) print "Finished modeling cluster %s:" % (i,) print "r squared = %s" % (r_squared,) print "adjusted r squared = %s" % (r_squared_adj,) model = Model(metric_names, means, stdevs, rotation_matrix, kmeans, models) # if we want to save the model file, copy it now outfilename = training_DC.name + '.model' if args.output == None else args.output if args.json == True: writeToFileJSON(model, outfilename) else: writeToFile(model, outfilename) if args.test_fit: args.experiment_dc = args.training_dc args.model = outfilename testModel(args) def dumpCSV(args): training_DC = database.DataCollection(args.training_dc, args.database) names = [met[0] for met in training_DC.metrics] if args.metrics != None: names = args.metrics header = ','.join(names) idxs = training_DC.metricIndexByName(names) profile = training_DC.profile[:,idxs] outfile = sys.stdout if args.output == None else args.output np.savetxt(outfile, profile, delimiter=',', header=header, comments='') def testModel(args): print "Testing the model fit..." test_DC = database.DataCollection(args.experiment_dc, args.database) model = readFile(args.model) _runExperiment(model.kmeans, model.means, model.stdevs, model.models, model.rotation_matrix, test_DC, args, model.metric_names) def readFile(infile): with open(infile, 'r') as modelfile: first_char = modelfile.readline()[0] if first_char == '{': return readJSONFile(infile) else: return readBespokeFile(infile) def plotModel(args): print "Plotting model..." model = readFile(args.model) if args.plot_pcs_per_metric: PCA.PlotPCsPerMetric(rotation_matrix, metric_names, title="PCs Per Metric") if args.plot_metrics_per_pc: PCA.PlotMetricsPerPC(rotation_matrix, metric_names, title="Metrics Per PC") def _stringToArray(string): """ Parse string of form [len](number,number,number,...) to a numpy array. """ length = string[:string.find('(')] values = string[string.find('('):] arr = np.array(literal_eval(values)) return np.reshape(arr, literal_eval(length)) def _runExperiment(kmeans, means, stdevs, models, rotation_matrix, experiment_DC, args, metric_names): unordered_metric_ids = experiment_DC.metricIndexByType('deterministic', 'nondeterministic') unordered_metric_names = [experiment_DC.metrics[mid][0] for mid in unordered_metric_ids] # make sure all metric_names are in experiment_DC.metrics[:][0] have_metrics = [x in unordered_metric_names for x in metric_names] if not all(have_metrics): print("Experiment DC does not have matching metrics. Aborting...") return # set the correct ordering expr_metric_ids = [unordered_metric_ids[unordered_metric_names.index(name)] for name in metric_names] for idx,metric in enumerate(experiment_DC.metrics): if(metric[0] == args.target): performance_metric_id = idx performance = experiment_DC.profile[:,performance_metric_id] profile = experiment_DC.profile[:,expr_metric_ids] rotated_profile = np.dot(profile, rotation_matrix) means = np.mean(rotated_profile, axis=0) stdevs = np.std(rotated_profile - means, axis=0, ddof=1) stdevs = np.nan_to_num(stdevs) stdevs[stdevs==0.0] = 1.0 clusters = kmeans.predict((rotated_profile - means)/stdevs) prediction = np.empty_like(performance) for i in range(len(kmeans.cluster_centers_)): prediction[clusters==i] = abs(models[i].poll(rotated_profile[clusters==i])) if args.show_prediction: print "Actual\t\tPredicted" print '\n'.join("%s\t%s" % x for x in zip(performance,prediction)) mse = sum([(a-p)**2 for a,p in zip(performance, prediction)]) / len(performance) rmse = math.sqrt(mse) mape = 100 * sum([abs((a-p)/a) for a,p in zip(performance,prediction)]) / len(performance) print "Number of experiment trials: %s" % len(performance) print "Mean Average Percent Error: %s" % mape print "Mean Squared Error: %s" % mse print "Root Mean Squared Error: %s" % rmse def writeToFileJSON(model, outfile): # Let's assume model has all the attributes we care about json_root = {} json_root["metric_names"] = [name for name in model.metric_names] json_root["means"] = [mean for mean in model.means.tolist()] json_root["std_devs"] = [stdev for stdev in model.stdevs.tolist()] json_root["rotation_matrix"] = [[elem for elem in row] for row in model.rotation_matrix.tolist()] json_root["clusters"] = [] for i in range(len(model.kmeans.cluster_centers_)): json_cluster = {} json_cluster["center"] = [center for center in model.kmeans.cluster_centers_[i].tolist()] # get models in json format json_cluster["regressors"] = model.models[i].toJSONObject() json_root["clusters"].append(json_cluster) with open(outfile, 'w') as out: json.dump(json_root, out, indent=4) def readJSONFile(infile): with open(infile, 'r') as modelfile: json_root = json.load(modelfile) metric_names = json_root['metric_names'] means = np.array(json_root['means']) stdevs = np.array(json_root['std_devs']) rotation_matrix = np.array(json_root['rotation_matrix']) empty_kmeans = KMeans(n_clusters=len(json_root['clusters']), n_init=1) centers = [] models = [] for cluster in json_root['clusters']: centers.append(np.array(cluster['center'])) models.append(LinearRegression.Model.fromJSONObject(cluster['regressors'])) kmeans = empty_kmeans.fit(centers) return Model(metric_names, means, stdevs, rotation_matrix, kmeans, models) def writeToFile(model, outfile): with open(outfile, 'w') as modelfile: # For printing the original model file encoding modelfile.write("%s\n%s\n" % (len(model.metric_names), '\n'.join(model.metric_names))) modelfile.write("[%s](%s)\n" % (len(model.means), ','.join([str(mean) for mean in model.means.tolist()]))) modelfile.write("[%s](%s)\n" % (len(model.stdevs), ','.join([str(stdev) for stdev in model.stdevs.tolist()]))) modelfile.write("[%s,%s]" % model.rotation_matrix.shape) modelfile.write("(%s)\n" % ','.join(["(%s)" % ','.join([str(elem) for elem in row]) for row in model.rotation_matrix.tolist()])) for i in range(len(model.kmeans.cluster_centers_)): modelfile.write('Model %s\n' % i) modelfile.write("[%s](%s)\n" % (model.rotation_matrix.shape[1], ','.join([str(center) for center in model.kmeans.cluster_centers_[i].tolist()]))) modelfile.write(repr(model.models[i])) modelfile.write('\n') # need a trailing newline def readBespokeFile(infile): """Returns a Model namedtuple with all the model parts""" with open(infile, 'r') as modelfile: lines = iter(modelfile.read().splitlines()) n_params = int(lines.next()) metric_names = [lines.next() for i in range(n_params)] means = _stringToArray(lines.next()) stdevs = _stringToArray(lines.next()) rotation_matrix = _stringToArray(lines.next()) models = [] centroids = [] try: while True: name = lines.next() # kill a line centroids.append(_stringToArray(lines.next())) weights = _stringToArray(lines.next()) functions = [LinearRegression.stringToFunction(lines.next()) for i in range(weights.shape[0])] models.append(LinearRegression.Model(functions, weights)) except StopIteration: pass kmeans = KMeans(len(centroids)) kmeans.cluster_centers_ = np.array(centroids) return Model(metric_names, means, stdevs, rotation_matrix, kmeans, models) def convert(args): print "Converting model..." with open(args.input, 'r') as modelfile: first_char = modelfile.readline()[0] if first_char == '{': model = readJSONFile(args.input) writeToFile(model, args.output) else: model = readBespokeFile(args.input) writeToFileJSON(model, args.output) if __name__ == "__main__": parser = argparse.ArgumentParser(description = \ 'Command line interface into Eiger performance modeling framework \ for all model generation, polling, and serialization tasks.', argument_default=None, fromfile_prefix_chars='@') subparsers = parser.add_subparsers(title='subcommands') train_parser = subparsers.add_parser('train', help='train a model with data from the database', description='Train a model with data from the database') train_parser.set_defaults(func=trainModel) dump_parser = subparsers.add_parser('dump', help='dump data collection to CSV', description='Dump data collection as CSV') dump_parser.set_defaults(func=dumpCSV) test_parser = subparsers.add_parser('test', help='test how well a model predicts a data collection', description='Test how well a model predicts a data collection') test_parser.set_defaults(func=testModel) plot_parser = subparsers.add_parser('plot', help='plot the behavior of a model', description='Plot the behavior of a model') plot_parser.set_defaults(func=plotModel) convert_parser = subparsers.add_parser('convert', help='transform a model into a different file format', description='Transform a model into a different file format') convert_parser.set_defaults(func=convert) list_model_parser = subparsers.add_parser('list', help='list available models in the Eiger DB', description='List available models in the Eiger DB') list_model_parser.set_defaults(func=list_models) import_model_parser = subparsers.add_parser('import', help='import model file into the Eiger DB', description='Import model file into the Eiger DB') import_model_parser.set_defaults(func=import_model) export_model_parser = subparsers.add_parser('export', help='export model from Eiger DB to file', description='Export model from Eiger DB to file') export_model_parser.set_defaults(func=export_model) """TRAINING ARGUMENTS""" train_parser.add_argument('database', type=str, help='Name of the database file') train_parser.add_argument('training_dc', type=str, help='Name of the training data collection') train_parser.add_argument('target', type=str, help='Name of the target metric to predict') train_parser.add_argument('--test-fit', action='store_true', default=False, help='If set will test the model fit against the training data.') train_parser.add_argument('--show-prediction', action='store_true', default=False, help='If set, send the actual and predicted values to stdout.') train_parser.add_argument('--predictor-metrics', nargs='*', help='Only use these metrics when building a model.') train_parser.add_argument('--output', type=str, help='Filename to output file to, otherwise use "<training_dc>.model"') train_parser.add_argument('--clusters', '-k', type=int, default=1, help='Number of clusters for kmeans') train_parser.add_argument('--threshold', type=float, help='Cutoff threshold of increase in adjusted R-squared value when' ' adding new predictors to the model') train_parser.add_argument('--nfolds', type=int, help='Number of folds to use in k-fold cross validation.') train_parser.add_argument('--regressor-functions', nargs='*', default=['inv_quadratic', 'inv_linear', 'inv_sqrt', 'sqrt', 'linear', 'quadratic', 'log', 'cross', 'div'], help='Regressor functions to use. Options are linear, quadratic, ' 'sqrt, inv_linear, inv_quadratic, inv_sqrt, log, cross, and div. ' 'Defaults to all.') train_parser.add_argument('--json', action='store_true', default=False, help='Output model in JSON format, rather than bespoke') """DUMP CSV ARGUMENTS""" dump_parser.add_argument('database', type=str, help='Name of the database file') dump_parser.add_argument('training_dc', type=str, help='Name of the data collection to dump') dump_parser.add_argument('--metrics', nargs='*', help='Only dump these metrics.') dump_parser.add_argument('--output', type=str, help='Name of file to dump CSV to') """TEST ARGUMENTS""" test_parser.add_argument('database', type=str, help='Name of the database file') test_parser.add_argument('experiment_dc', type=str, help='Name of the data collection to experiment on') test_parser.add_argument('model', type=str, help='Name of the model to use') test_parser.add_argument('target', type=str, help='Name of the target metric to predict') test_parser.add_argument('--show-prediction', action='store_true', default=False, help='If set, send the actual and predicted values to stdout.') """PLOT ARGUMENTS""" plot_parser.add_argument('model', type=str, help='Name of the model to use') plot_parser.add_argument('--plot-pcs-per-metric', action='store_true', default=False, help='If set, plots the breakdown of principal components per metric.') plot_parser.add_argument('--plot-metrics-per-pc', action='store_true', default=False, help='If set, plots the breakdown of metrics per principal component.') """CONVERT ARGUMENTS""" convert_parser.add_argument('input', type=str, help='Name of input model to convert from') convert_parser.add_argument('output', type=str, help='Name of output model to convert to') """LIST ARGUMENTS""" list_model_parser.add_argument('database', type=str, help='Name of the database file') """IMPORT ARGUMENTS""" import_model_parser.add_argument('database', type=str, help='Name of the database file') import_model_parser.add_argument('file', type=str, help='Name of the model file to import') import_model_parser.add_argument('source_name', type=str, help='Name of the source of the model (ie Eiger)') import_model_parser.add_argument('--description', type=str, default='', help='String to describe the model') """EXPORT ARGUMENTS""" export_model_parser.add_argument('database', type=str, help='Name of the database file') export_model_parser.add_argument('id', type=int, help='ID number identifying which model in the database to export ') export_model_parser.add_argument('file', type=str, help='Name of the file to export into') args = parser.parse_args() args.func(args) print "Done."
bsd-3-clause
droundy/deft
talks/colloquium/figs/plot-walls.py
1
3242
#!/usr/bin/python # We need the following two lines in order for matplotlib to work # without access to an X server. from __future__ import division import matplotlib matplotlib.use('Agg') import pylab, numpy, sys xmax = 2.5 xmin = -0.4 def plotit(dftdata, mcdata): dft_len = len(dftdata[:,0]) dft_dr = dftdata[2,0] - dftdata[1,0] mcdata = numpy.insert(mcdata,0,0,0) mcdata[0,0]=-10 mcoffset = 10/2 offset = -3/2 n0 = dftdata[:,6] nA = dftdata[:,8] nAmc = mcdata[:,11] n0mc = mcdata[:,10] pylab.figure(figsize=(6, 6)) pylab.subplots_adjust(hspace=0.001) n_plt = pylab.subplot(3,1,3) n_plt.plot(mcdata[:,0]/2+mcoffset,mcdata[:,1]*4*numpy.pi/3,"b-",label='$n$ Monte Carlo') n_plt.plot(dftdata[:,0]/2+offset,dftdata[:,1]*4*numpy.pi/3,"b--",label='$n$ DFT') n_plt.legend(loc='best', ncol=1).draw_frame(False) #.get_frame().set_alpha(0.5) n_plt.yaxis.set_major_locator(pylab.MaxNLocator(6,steps=[1,5,10],prune='upper')) pylab.ylim(ymin=0) pylab.xlim(xmin, xmax) pylab.xlabel("$z/\sigma$") pylab.ylabel("$n(\mathbf{r})$") n_plt.axvline(x=0, color='k', linestyle=':') n = len(mcdata[:,0]) #pylab.twinx() dftr = dftdata[:,0]/2+offset thiswork = dftdata[:,5] gross = dftdata[:,7] stop_here = int(dft_len - 1/dft_dr) print stop_here start_here = int(2.5/dft_dr) off = 1 me = 40 A_plt = pylab.subplot(3,1,1) A_plt.axvline(x=0, color='k', linestyle=':') A_plt.plot(mcdata[:,0]/2+mcoffset,mcdata[:,2+2*off]/nAmc,"r-",label="$g_\sigma^A$ Monte Carlo") A_plt.plot(dftr[dftr>=0],thiswork[dftr>=0],"ro",markevery=me*.8,label="$g_\sigma^A$ this work") A_plt.plot(dftr[dftr>=0],gross[dftr>=0],"rx",markevery=me,label="Gross", markerfacecolor='none',markeredgecolor='red', markeredgewidth=1) A_plt.legend(loc='best', ncol=1).draw_frame(False) #.get_frame().set_alpha(0.5) A_plt.yaxis.set_major_locator(pylab.MaxNLocator(integer=True,prune='upper')) pylab.ylim(ymin=0) pylab.ylabel("$g_\sigma^A$") pylab.xlim(xmin, xmax) n0mc[0]=1 mcdata[0,10]=1 S_plt = pylab.subplot(3,1,2) S_plt.axvline(x=0, color='k', linestyle=':') S_plt.plot(mcdata[:,0]/2+mcoffset,mcdata[:,3+2*off]/n0mc,"g-",label="$g_\sigma^S$ Monte Carlo") S_plt.plot(dftdata[:,0]/2+offset,dftdata[:,4],"gx",markevery=me/2,label="Yu and Wu") S_plt.legend(loc='best', ncol=1).draw_frame(False) #.get_frame().set_alpha(0.5) #pylab.ylim(ymax=12) S_plt.yaxis.set_major_locator(pylab.MaxNLocator(5,integer=True,prune='upper')) pylab.xlim(xmin, xmax) pylab.ylim(ymin=0) pylab.ylabel("$g_\sigma^S$") xticklabels = A_plt.get_xticklabels() + S_plt.get_xticklabels() pylab.setp(xticklabels, visible=False) mcdata10 = numpy.loadtxt('../../papers/contact/figs/mc-walls-20-196.dat') dftdata10 = numpy.loadtxt('../../papers/contact/figs/wallsWB-0.10.dat') mcdata40 = numpy.loadtxt('../../papers/contact/figs/mc-walls-20-817.dat') dftdata40 = numpy.loadtxt('../../papers/contact/figs/wallsWB-0.40.dat') plotit(dftdata10, mcdata10) pylab.savefig('figs/walls-10.pdf', transparent=True) plotit(dftdata40, mcdata40) pylab.savefig('figs/walls-40.pdf', transparent=True)
gpl-2.0
chintak/scikit-image
skimage/feature/util.py
1
4726
import numpy as np from skimage.util import img_as_float class FeatureDetector(object): def __init__(self): self.keypoints_ = np.array([]) def detect(self, image): """Detect keypoints in image. Parameters ---------- image : 2D array Input image. """ raise NotImplementedError() class DescriptorExtractor(object): def __init__(self): self.descriptors_ = np.array([]) def extract(self, image, keypoints): """Extract feature descriptors in image for given keypoints. Parameters ---------- image : 2D array Input image. keypoints : (N, 2) array Keypoint locations as ``(row, col)``. """ raise NotImplementedError() def plot_matches(ax, image1, image2, keypoints1, keypoints2, matches, keypoints_color='k', matches_color=None, only_matches=False): """Plot matched features. Parameters ---------- ax : matplotlib.axes.Axes Matches and image are drawn in this ax. image1 : (N, M [, 3]) array First grayscale or color image. image2 : (N, M [, 3]) array Second grayscale or color image. keypoints1 : (K1, 2) array First keypoint coordinates as ``(row, col)``. keypoints2 : (K2, 2) array Second keypoint coordinates as ``(row, col)``. matches : (Q, 2) array Indices of corresponding matches in first and second set of descriptors, where ``matches[:, 0]`` denote the indices in the first and ``matches[:, 1]`` the indices in the second set of descriptors. keypoints_color : matplotlib color, optional Color for keypoint locations. matches_color : matplotlib color, optional Color for lines which connect keypoint matches. By default the color is chosen randomly. only_matches : bool, optional Whether to only plot matches and not plot the keypoint locations. """ image1 = img_as_float(image1) image2 = img_as_float(image2) new_shape1 = list(image1.shape) new_shape2 = list(image2.shape) if image1.shape[0] < image2.shape[0]: new_shape1[0] = image2.shape[0] elif image1.shape[0] > image2.shape[0]: new_shape2[0] = image1.shape[0] if image1.shape[1] < image2.shape[1]: new_shape1[1] = image2.shape[1] elif image1.shape[1] > image2.shape[1]: new_shape2[1] = image1.shape[1] if new_shape1 != image1.shape: new_image1 = np.zeros(new_shape1, dtype=image1.dtype) new_image1[:image1.shape[0], :image1.shape[1]] = image1 image1 = new_image1 if new_shape2 != image2.shape: new_image2 = np.zeros(new_shape2, dtype=image2.dtype) new_image2[:image2.shape[0], :image2.shape[1]] = image2 image2 = new_image2 image = np.concatenate([image1, image2], axis=1) offset = image1.shape if not only_matches: ax.scatter(keypoints1[:, 1], keypoints1[:, 0], facecolors='none', edgecolors=keypoints_color) ax.scatter(keypoints2[:, 1] + offset[1], keypoints2[:, 0], facecolors='none', edgecolors=keypoints_color) ax.imshow(image) ax.axis((0, 2 * offset[1], offset[0], 0)) for i in range(matches.shape[0]): idx1 = matches[i, 0] idx2 = matches[i, 1] if matches_color is None: color = np.random.rand(3, 1) else: color = matches_color ax.plot((keypoints1[idx1, 1], keypoints2[idx2, 1] + offset[1]), (keypoints1[idx1, 0], keypoints2[idx2, 0]), '-', color=color) def _prepare_grayscale_input_2D(image): image = np.squeeze(image) if image.ndim != 2: raise ValueError("Only 2-D gray-scale images supported.") return img_as_float(image) def _mask_border_keypoints(image_shape, keypoints, distance): """Mask coordinates that are within certain distance from the image border. Parameters ---------- image_shape : (2, ) array_like Shape of the image as ``(rows, cols)``. keypoints : (N, 2) array Keypoint coordinates as ``(rows, cols)``. distance : int Image border distance. Returns ------- mask : (N, ) bool array Mask indicating if pixels are within the image (``True``) or in the border region of the image (``False``). """ rows = image_shape[0] cols = image_shape[1] mask = (((distance - 1) < keypoints[:, 0]) & (keypoints[:, 0] < (rows - distance + 1)) & ((distance - 1) < keypoints[:, 1]) & (keypoints[:, 1] < (cols - distance + 1))) return mask
bsd-3-clause
NicWayand/xray
xarray/plot/utils.py
1
6442
import pkg_resources import numpy as np import pandas as pd from ..core.pycompat import basestring def _load_default_cmap(fname='default_colormap.csv'): """ Returns viridis color map """ from matplotlib.colors import LinearSegmentedColormap # Not sure what the first arg here should be f = pkg_resources.resource_stream(__name__, fname) cm_data = pd.read_csv(f, header=None).values return LinearSegmentedColormap.from_list('viridis', cm_data) def _determine_extend(calc_data, vmin, vmax): extend_min = calc_data.min() < vmin extend_max = calc_data.max() > vmax if extend_min and extend_max: extend = 'both' elif extend_min: extend = 'min' elif extend_max: extend = 'max' else: extend = 'neither' return extend def _build_discrete_cmap(cmap, levels, extend, filled): """ Build a discrete colormap and normalization of the data. """ import matplotlib as mpl if not filled: # non-filled contour plots extend = 'max' if extend == 'both': ext_n = 2 elif extend in ['min', 'max']: ext_n = 1 else: ext_n = 0 n_colors = len(levels) + ext_n - 1 pal = _color_palette(cmap, n_colors) new_cmap, cnorm = mpl.colors.from_levels_and_colors( levels, pal, extend=extend) # copy the old cmap name, for easier testing new_cmap.name = getattr(cmap, 'name', cmap) return new_cmap, cnorm def _color_palette(cmap, n_colors): import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap colors_i = np.linspace(0, 1., n_colors) if isinstance(cmap, (list, tuple)): # we have a list of colors try: # first try to turn it into a palette with seaborn from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except ImportError: # if that fails, use matplotlib # in this case, is there any difference between mpl and seaborn? cmap = ListedColormap(cmap, N=n_colors) pal = cmap(colors_i) elif isinstance(cmap, basestring): # we have some sort of named palette try: # first try to turn it into a palette with seaborn from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except (ImportError, ValueError): # ValueError is raised when seaborn doesn't like a colormap # (e.g. jet). If that fails, use matplotlib try: # is this a matplotlib cmap? cmap = plt.get_cmap(cmap) except ValueError: # or maybe we just got a single color as a string cmap = ListedColormap([cmap], N=n_colors) pal = cmap(colors_i) else: # cmap better be a LinearSegmentedColormap (e.g. viridis) pal = cmap(colors_i) return pal def _determine_cmap_params(plot_data, vmin=None, vmax=None, cmap=None, center=None, robust=False, extend=None, levels=None, filled=True, cnorm=None): """ Use some heuristics to set good defaults for colorbar and range. Adapted from Seaborn: https://github.com/mwaskom/seaborn/blob/v0.6/seaborn/matrix.py#L158 Parameters ========== plot_data: Numpy array Doesn't handle xarray objects Returns ======= cmap_params : dict Use depends on the type of the plotting function """ ROBUST_PERCENTILE = 2.0 import matplotlib as mpl calc_data = np.ravel(plot_data[~pd.isnull(plot_data)]) # Setting center=False prevents a divergent cmap possibly_divergent = center is not False # Set center to 0 so math below makes sense but remember its state center_is_none = False if center is None: center = 0 center_is_none = True # Setting both vmin and vmax prevents a divergent cmap if (vmin is not None) and (vmax is not None): possibly_divergent = False # vlim might be computed below vlim = None if vmin is None: if robust: vmin = np.percentile(calc_data, ROBUST_PERCENTILE) else: vmin = calc_data.min() elif possibly_divergent: vlim = abs(vmin - center) if vmax is None: if robust: vmax = np.percentile(calc_data, 100 - ROBUST_PERCENTILE) else: vmax = calc_data.max() elif possibly_divergent: vlim = abs(vmax - center) if possibly_divergent: # kwargs not specific about divergent or not: infer defaults from data divergent = ((vmin < 0) and (vmax > 0)) or not center_is_none else: divergent = False # A divergent map should be symmetric around the center value if divergent: if vlim is None: vlim = max(abs(vmin - center), abs(vmax - center)) vmin, vmax = -vlim, vlim # Now add in the centering value and set the limits vmin += center vmax += center # Choose default colormaps if not provided if cmap is None: if divergent: cmap = "RdBu_r" else: cmap = "viridis" # Allow viridis before matplotlib 1.5 if cmap == "viridis": cmap = _load_default_cmap() # Handle discrete levels if levels is not None: if isinstance(levels, int): ticker = mpl.ticker.MaxNLocator(levels) levels = ticker.tick_values(vmin, vmax) vmin, vmax = levels[0], levels[-1] if extend is None: extend = _determine_extend(calc_data, vmin, vmax) if levels is not None: cmap, cnorm = _build_discrete_cmap(cmap, levels, extend, filled) return dict(vmin=vmin, vmax=vmax, cmap=cmap, extend=extend, levels=levels, norm=cnorm) def _infer_xy_labels(darray, x, y): """ Determine x and y labels. For use in _plot2d darray must be a 2 dimensional data array. """ if x is None and y is None: if darray.ndim != 2: raise ValueError('DataArray must be 2d') y, x = darray.dims elif x is None or y is None: raise ValueError('cannot supply only one of x and y') elif any(k not in darray.coords for k in (x, y)): raise ValueError('x and y must be coordinate variables') return x, y
apache-2.0
sinhrks/seaborn
seaborn/matrix.py
5
40890
"""Functions to visualize matrices of data.""" import itertools import colorsys import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np import pandas as pd from scipy.spatial import distance from scipy.cluster import hierarchy from .axisgrid import Grid from .palettes import cubehelix_palette from .utils import despine, axis_ticklabels_overlap from .external.six.moves import range def _index_to_label(index): """Convert a pandas index or multiindex to an axis label.""" if isinstance(index, pd.MultiIndex): return "-".join(map(str, index.names)) else: return index.name def _index_to_ticklabels(index): """Convert a pandas index or multiindex into ticklabels.""" if isinstance(index, pd.MultiIndex): return ["-".join(map(str, i)) for i in index.values] else: return index.values def _convert_colors(colors): """Convert either a list of colors or nested lists of colors to RGB.""" to_rgb = mpl.colors.colorConverter.to_rgb try: to_rgb(colors[0]) # If this works, there is only one level of colors return list(map(to_rgb, colors)) except ValueError: # If we get here, we have nested lists return [list(map(to_rgb, l)) for l in colors] def _matrix_mask(data, mask): """Ensure that data and mask are compatabile and add missing values. Values will be plotted for cells where ``mask`` is ``False``. ``data`` is expected to be a DataFrame; ``mask`` can be an array or a DataFrame. """ if mask is None: mask = np.zeros(data.shape, np.bool) if isinstance(mask, np.ndarray): # For array masks, ensure that shape matches data then convert if mask.shape != data.shape: raise ValueError("Mask must have the same shape as data.") mask = pd.DataFrame(mask, index=data.index, columns=data.columns, dtype=np.bool) elif isinstance(mask, pd.DataFrame): # For DataFrame masks, ensure that semantic labels match data if not mask.index.equals(data.index) \ and mask.columns.equals(data.columns): err = "Mask must have the same index and columns as data." raise ValueError(err) # Add any cells with missing data to the mask # This works around an issue where `plt.pcolormesh` doesn't represent # missing data properly mask = mask | pd.isnull(data) return mask class _HeatMapper(object): """Draw a heatmap plot of a matrix with nice labels and colormaps.""" def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels=True, yticklabels=True, mask=None): """Initialize the plotting object.""" # We always want to have a DataFrame with semantic information # and an ndarray to pass to matplotlib if isinstance(data, pd.DataFrame): plot_data = data.values else: plot_data = np.asarray(data) data = pd.DataFrame(plot_data) # Validate the mask and convet to DataFrame mask = _matrix_mask(data, mask) # Reverse the rows so the plot looks like the matrix plot_data = plot_data[::-1] data = data.ix[::-1] mask = mask.ix[::-1] plot_data = np.ma.masked_where(np.asarray(mask), plot_data) # Get good names for the rows and columns xtickevery = 1 if isinstance(xticklabels, int) and xticklabels > 1: xtickevery = xticklabels xticklabels = _index_to_ticklabels(data.columns) elif isinstance(xticklabels, bool) and xticklabels: xticklabels = _index_to_ticklabels(data.columns) elif isinstance(xticklabels, bool) and not xticklabels: xticklabels = ['' for _ in range(data.shape[1])] ytickevery = 1 if isinstance(yticklabels, int) and yticklabels > 1: ytickevery = yticklabels yticklabels = _index_to_ticklabels(data.index) elif isinstance(yticklabels, bool) and yticklabels: yticklabels = _index_to_ticklabels(data.index) elif isinstance(yticklabels, bool) and not yticklabels: yticklabels = ['' for _ in range(data.shape[0])] else: yticklabels = yticklabels[::-1] # Get the positions and used label for the ticks nx, ny = data.T.shape xstart, xend, xstep = 0, nx, xtickevery self.xticks = np.arange(xstart, xend, xstep) + .5 self.xticklabels = xticklabels[xstart:xend:xstep] ystart, yend, ystep = (ny - 1) % ytickevery, ny, ytickevery self.yticks = np.arange(ystart, yend, ystep) + .5 self.yticklabels = yticklabels[ystart:yend:ystep] # Get good names for the axis labels xlabel = _index_to_label(data.columns) ylabel = _index_to_label(data.index) self.xlabel = xlabel if xlabel is not None else "" self.ylabel = ylabel if ylabel is not None else "" # Determine good default values for the colormapping self._determine_cmap_params(plot_data, vmin, vmax, cmap, center, robust) # Save other attributes to the object self.data = data self.plot_data = plot_data self.annot = annot self.fmt = fmt self.annot_kws = {} if annot_kws is None else annot_kws self.cbar = cbar self.cbar_kws = {} if cbar_kws is None else cbar_kws def _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust): """Use some heuristics to set good defaults for colorbar and range.""" calc_data = plot_data.data[~np.isnan(plot_data.data)] if vmin is None: vmin = np.percentile(calc_data, 2) if robust else calc_data.min() if vmax is None: vmax = np.percentile(calc_data, 98) if robust else calc_data.max() # Simple heuristics for whether these data should have a divergent map divergent = ((vmin < 0) and (vmax > 0)) or center is not None # Now set center to 0 so math below makes sense if center is None: center = 0 # A divergent map should be symmetric around the center value if divergent: vlim = max(abs(vmin - center), abs(vmax - center)) vmin, vmax = -vlim, vlim self.divergent = divergent # Now add in the centering value and set the limits vmin += center vmax += center self.vmin = vmin self.vmax = vmax # Choose default colormaps if not provided if cmap is None: if divergent: self.cmap = "RdBu_r" else: self.cmap = cubehelix_palette(light=.95, as_cmap=True) else: self.cmap = cmap def _annotate_heatmap(self, ax, mesh): """Add textual labels with the value in each cell.""" xpos, ypos = np.meshgrid(ax.get_xticks(), ax.get_yticks()) for x, y, val, color in zip(xpos.flat, ypos.flat, mesh.get_array(), mesh.get_facecolors()): if val is not np.ma.masked: _, l, _ = colorsys.rgb_to_hls(*color[:3]) text_color = ".15" if l > .5 else "w" val = ("{:" + self.fmt + "}").format(val) ax.text(x, y, val, color=text_color, ha="center", va="center", **self.annot_kws) def plot(self, ax, cax, kws): """Draw the heatmap on the provided Axes.""" # Remove all the Axes spines despine(ax=ax, left=True, bottom=True) # Draw the heatmap mesh = ax.pcolormesh(self.plot_data, vmin=self.vmin, vmax=self.vmax, cmap=self.cmap, **kws) # Set the axis limits ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0])) # Add row and column labels ax.set(xticks=self.xticks, yticks=self.yticks) xtl = ax.set_xticklabels(self.xticklabels) ytl = ax.set_yticklabels(self.yticklabels, rotation="vertical") # Possibly rotate them if they overlap plt.draw() if axis_ticklabels_overlap(xtl): plt.setp(xtl, rotation="vertical") if axis_ticklabels_overlap(ytl): plt.setp(ytl, rotation="horizontal") # Add the axis labels ax.set(xlabel=self.xlabel, ylabel=self.ylabel) # Annotate the cells with the formatted values if self.annot: self._annotate_heatmap(ax, mesh) # Possibly add a colorbar if self.cbar: ticker = mpl.ticker.MaxNLocator(6) cb = ax.figure.colorbar(mesh, cax, ax, ticks=ticker, **self.cbar_kws) cb.outline.set_linewidth(0) def heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=False, fmt=".2g", annot_kws=None, linewidths=0, linecolor="white", cbar=True, cbar_kws=None, cbar_ax=None, square=False, ax=None, xticklabels=True, yticklabels=True, mask=None, **kwargs): """Plot rectangular data as a color-encoded matrix. This function tries to infer a good colormap to use from the data, but this is not guaranteed to work, so take care to make sure the kind of colormap (sequential or diverging) and its limits are appropriate. This is an Axes-level function and will draw the heatmap into the currently-active Axes if none is provided to the ``ax`` argument. Part of this Axes space will be taken and used to plot a colormap, unless ``cbar`` is False or a separate Axes is provided to ``cbar_ax``. Parameters ---------- data : rectangular dataset 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame is provided, the index/column information will be used to label the columns and rows. vmin, vmax : floats, optional Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments. When a diverging dataset is inferred, one of these values may be ignored. cmap : matplotlib colormap name or object, optional The mapping from data values to color space. If not provided, this will be either a cubehelix map (if the function infers a sequential dataset) or ``RdBu_r`` (if the function infers a diverging dataset). center : float, optional The value at which to center the colormap. Passing this value implies use of a diverging colormap. robust : bool, optional If True and ``vmin`` or ``vmax`` are absent, the colormap range is computed with robust quantiles instead of the extreme values. annot : bool, optional If True, write the data value in each cell. fmt : string, optional String formatting code to use when ``annot`` is True. annot_kws : dict of key, value mappings, optional Keyword arguments for ``ax.text`` when ``annot`` is True. linewidths : float, optional Width of the lines that will divide each cell. linecolor : color, optional Color of the lines that will divide each cell. cbar : boolean, optional Whether to draw a colorbar. cbar_kws : dict of key, value mappings, optional Keyword arguments for `fig.colorbar`. cbar_ax : matplotlib Axes, optional Axes in which to draw the colorbar, otherwise take space from the main Axes. square : boolean, optional If True, set the Axes aspect to "equal" so each cell will be square-shaped. ax : matplotlib Axes, optional Axes in which to draw the plot, otherwise use the currently-active Axes. xticklabels : list-like, int, or bool, optional If True, plot the column names of the dataframe. If False, don't plot the column names. If list-like, plot these alternate labels as the xticklabels. If an integer, use the column names but plot only every n label. yticklabels : list-like, int, or bool, optional If True, plot the row names of the dataframe. If False, don't plot the row names. If list-like, plot these alternate labels as the yticklabels. If an integer, use the index names but plot only every n label. mask : boolean array or DataFrame, optional If passed, data will not be shown in cells where ``mask`` is True. Cells with missing values are automatically masked. kwargs : other keyword arguments All other keyword arguments are passed to ``ax.pcolormesh``. Returns ------- ax : matplotlib Axes Axes object with the heatmap. Examples -------- Plot a heatmap for a numpy array: .. plot:: :context: close-figs >>> import numpy as np; np.random.seed(0) >>> import seaborn as sns; sns.set() >>> uniform_data = np.random.rand(10, 12) >>> ax = sns.heatmap(uniform_data) Change the limits of the colormap: .. plot:: :context: close-figs >>> ax = sns.heatmap(uniform_data, vmin=0, vmax=1) Plot a heatmap for data centered on 0: .. plot:: :context: close-figs >>> normal_data = np.random.randn(10, 12) >>> ax = sns.heatmap(normal_data) Plot a dataframe with meaningful row and column labels: .. plot:: :context: close-figs >>> flights = sns.load_dataset("flights") >>> flights = flights.pivot("month", "year", "passengers") >>> ax = sns.heatmap(flights) Annotate each cell with the numeric value using integer formatting: .. plot:: :context: close-figs >>> ax = sns.heatmap(flights, annot=True, fmt="d") Add lines between each cell: .. plot:: :context: close-figs >>> ax = sns.heatmap(flights, linewidths=.5) Use a different colormap: .. plot:: :context: close-figs >>> ax = sns.heatmap(flights, cmap="YlGnBu") Center the colormap at a specific value: .. plot:: :context: close-figs >>> ax = sns.heatmap(flights, center=flights.loc["January", 1955]) Plot every other column label and don't plot row labels: .. plot:: :context: close-figs >>> data = np.random.randn(50, 20) >>> ax = sns.heatmap(data, xticklabels=2, yticklabels=False) Don't draw a colorbar: .. plot:: :context: close-figs >>> ax = sns.heatmap(flights, cbar=False) Use different axes for the colorbar: .. plot:: :context: close-figs >>> grid_kws = {"height_ratios": (.9, .05), "hspace": .3} >>> f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws) >>> ax = sns.heatmap(flights, ax=ax, ... cbar_ax=cbar_ax, ... cbar_kws={"orientation": "horizontal"}) Use a mask to plot only part of a matrix .. plot:: :context: close-figs >>> corr = np.corrcoef(np.random.randn(10, 200)) >>> mask = np.zeros_like(corr) >>> mask[np.triu_indices_from(mask)] = True >>> with sns.axes_style("white"): ... ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True) """ # Initialize the plotter object plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask) # Add the pcolormesh kwargs here kwargs["linewidths"] = linewidths kwargs["edgecolor"] = linecolor # Draw the plot and return the Axes if ax is None: ax = plt.gca() if square: ax.set_aspect("equal") plotter.plot(ax, cbar_ax, kwargs) return ax class _DendrogramPlotter(object): """Object for drawing tree of similarities between data rows/columns""" def __init__(self, data, linkage, metric, method, axis, label, rotate): """Plot a dendrogram of the relationships between the columns of data Parameters ---------- data : pandas.DataFrame Rectangular data """ self.axis = axis if self.axis == 1: data = data.T if isinstance(data, pd.DataFrame): array = data.values else: array = np.asarray(data) data = pd.DataFrame(array) self.array = array self.data = data self.shape = self.data.shape self.metric = metric self.method = method self.axis = axis self.label = label self.rotate = rotate if linkage is None: self.linkage = self.calculated_linkage else: self.linkage = linkage self.dendrogram = self.calculate_dendrogram() # Dendrogram ends are always at multiples of 5, who knows why ticks = 10 * np.arange(self.data.shape[0]) + 5 if self.label: ticklabels = _index_to_ticklabels(self.data.index) ticklabels = [ticklabels[i] for i in self.reordered_ind] if self.rotate: self.xticks = [] self.yticks = ticks self.xticklabels = [] self.yticklabels = ticklabels self.ylabel = _index_to_label(self.data.index) self.xlabel = '' else: self.xticks = ticks self.yticks = [] self.xticklabels = ticklabels self.yticklabels = [] self.ylabel = '' self.xlabel = _index_to_label(self.data.index) else: self.xticks, self.yticks = [], [] self.yticklabels, self.xticklabels = [], [] self.xlabel, self.ylabel = '', '' if self.rotate: self.X = self.dendrogram['dcoord'] self.Y = self.dendrogram['icoord'] else: self.X = self.dendrogram['icoord'] self.Y = self.dendrogram['dcoord'] def _calculate_linkage_scipy(self): if np.product(self.shape) >= 10000: UserWarning('This will be slow... (gentle suggestion: ' '"pip install fastcluster")') pairwise_dists = distance.pdist(self.array, metric=self.metric) linkage = hierarchy.linkage(pairwise_dists, method=self.method) del pairwise_dists return linkage def _calculate_linkage_fastcluster(self): import fastcluster # Fastcluster has a memory-saving vectorized version, but only # with certain linkage methods, and mostly with euclidean metric vector_methods = ('single', 'centroid', 'median', 'ward') euclidean_methods = ('centroid', 'median', 'ward') euclidean = self.metric == 'euclidean' and self.method in \ euclidean_methods if euclidean or self.method == 'single': return fastcluster.linkage_vector(self.array, method=self.method, metric=self.metric) else: pairwise_dists = distance.pdist(self.array, metric=self.metric) linkage = fastcluster.linkage(pairwise_dists, method=self.method) del pairwise_dists return linkage @property def calculated_linkage(self): try: return self._calculate_linkage_fastcluster() except ImportError: return self._calculate_linkage_scipy() def calculate_dendrogram(self): """Calculates a dendrogram based on the linkage matrix Made a separate function, not a property because don't want to recalculate the dendrogram every time it is accessed. Returns ------- dendrogram : dict Dendrogram dictionary as returned by scipy.cluster.hierarchy .dendrogram. The important key-value pairing is "reordered_ind" which indicates the re-ordering of the matrix """ return hierarchy.dendrogram(self.linkage, no_plot=True, color_list=['k'], color_threshold=-np.inf) @property def reordered_ind(self): """Indices of the matrix, reordered by the dendrogram""" return self.dendrogram['leaves'] def plot(self, ax): """Plots a dendrogram of the similarities between data on the axes Parameters ---------- ax : matplotlib.axes.Axes Axes object upon which the dendrogram is plotted """ for x, y in zip(self.X, self.Y): ax.plot(x, y, color='k', linewidth=.5) if self.rotate and self.axis == 0: ax.invert_xaxis() ax.yaxis.set_ticks_position('right') ymax = min(map(min, self.Y)) + max(map(max, self.Y)) ax.set_ylim(0, ymax) ax.invert_yaxis() else: xmax = min(map(min, self.X)) + max(map(max, self.X)) ax.set_xlim(0, xmax) despine(ax=ax, bottom=True, left=True) ax.set(xticks=self.xticks, yticks=self.yticks, xlabel=self.xlabel, ylabel=self.ylabel) xtl = ax.set_xticklabels(self.xticklabels) ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical') # Force a draw of the plot to avoid matplotlib window error plt.draw() if len(ytl) > 0 and axis_ticklabels_overlap(ytl): plt.setp(ytl, rotation="horizontal") if len(xtl) > 0 and axis_ticklabels_overlap(xtl): plt.setp(xtl, rotation="vertical") return self def dendrogram(data, linkage=None, axis=1, label=True, metric='euclidean', method='average', rotate=False, ax=None): """Draw a tree diagram of relationships within a matrix Parameters ---------- data : pandas.DataFrame Rectangular data linkage : numpy.array, optional Linkage matrix axis : int, optional Which axis to use to calculate linkage. 0 is rows, 1 is columns. label : bool, optional If True, label the dendrogram at leaves with column or row names metric : str, optional Distance metric. Anything valid for scipy.spatial.distance.pdist method : str, optional Linkage method to use. Anything valid for scipy.cluster.hierarchy.linkage rotate : bool, optional When plotting the matrix, whether to rotate it 90 degrees counter-clockwise, so the leaves face right ax : matplotlib axis, optional Axis to plot on, otherwise uses current axis Returns ------- dendrogramplotter : _DendrogramPlotter A Dendrogram plotter object. Notes ----- Access the reordered dendrogram indices with dendrogramplotter.reordered_ind """ plotter = _DendrogramPlotter(data, linkage=linkage, axis=axis, metric=metric, method=method, label=label, rotate=rotate) if ax is None: ax = plt.gca() return plotter.plot(ax=ax) class ClusterGrid(Grid): def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None, figsize=None, row_colors=None, col_colors=None, mask=None): """Grid object for organizing clustered heatmap input on to axes""" if isinstance(data, pd.DataFrame): self.data = data else: self.data = pd.DataFrame(data) self.data2d = self.format_data(self.data, pivot_kws, z_score, standard_scale) self.mask = _matrix_mask(self.data2d, mask) if figsize is None: width, height = 10, 10 figsize = (width, height) self.fig = plt.figure(figsize=figsize) if row_colors is not None: row_colors = _convert_colors(row_colors) self.row_colors = row_colors if col_colors is not None: col_colors = _convert_colors(col_colors) self.col_colors = col_colors width_ratios = self.dim_ratios(self.row_colors, figsize=figsize, axis=1) height_ratios = self.dim_ratios(self.col_colors, figsize=figsize, axis=0) nrows = 3 if self.col_colors is None else 4 ncols = 3 if self.row_colors is None else 4 self.gs = gridspec.GridSpec(nrows, ncols, wspace=0.01, hspace=0.01, width_ratios=width_ratios, height_ratios=height_ratios) self.ax_row_dendrogram = self.fig.add_subplot(self.gs[nrows - 1, 0:2], axisbg="white") self.ax_col_dendrogram = self.fig.add_subplot(self.gs[0:2, ncols - 1], axisbg="white") self.ax_row_colors = None self.ax_col_colors = None if self.row_colors is not None: self.ax_row_colors = self.fig.add_subplot( self.gs[nrows - 1, ncols - 2]) if self.col_colors is not None: self.ax_col_colors = self.fig.add_subplot( self.gs[nrows - 2, ncols - 1]) self.ax_heatmap = self.fig.add_subplot(self.gs[nrows - 1, ncols - 1]) # colorbar for scale to left corner self.cax = self.fig.add_subplot(self.gs[0, 0]) self.dendrogram_row = None self.dendrogram_col = None def format_data(self, data, pivot_kws, z_score=None, standard_scale=None): """Extract variables from data or use directly.""" # Either the data is already in 2d matrix format, or need to do a pivot if pivot_kws is not None: data2d = data.pivot(**pivot_kws) else: data2d = data if z_score is not None and standard_scale is not None: raise ValueError( 'Cannot perform both z-scoring and standard-scaling on data') if z_score is not None: data2d = self.z_score(data2d, z_score) if standard_scale is not None: data2d = self.standard_scale(data2d, standard_scale) return data2d @staticmethod def z_score(data2d, axis=1): """Standarize the mean and variance of the data axis Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- normalized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. """ if axis == 1: z_scored = data2d else: z_scored = data2d.T z_scored = (z_scored - z_scored.mean()) / z_scored.std() if axis == 1: return z_scored else: return z_scored.T @staticmethod def standard_scale(data2d, axis=1): """Divide the data by the difference between the max and min Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. vmin : int If 0, then subtract the minimum of the data before dividing by the range. Returns ------- standardized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. >>> import numpy as np >>> d = np.arange(5, 8, 0.5) >>> ClusterGrid.standard_scale(d) array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ]) """ # Normalize these values to range from 0 to 1 if axis == 1: standardized = data2d else: standardized = data2d.T subtract = standardized.min() standardized = (standardized - subtract) / ( standardized.max() - standardized.min()) if axis == 1: return standardized else: return standardized.T def dim_ratios(self, side_colors, axis, figsize, side_colors_ratio=0.05): """Get the proportions of the figure taken up by each axes """ figdim = figsize[axis] # Get resizing proportion of this figure for the dendrogram and # colorbar, so only the heatmap gets bigger but the dendrogram stays # the same size. dendrogram = min(2. / figdim, .2) # add the colorbar colorbar_width = .8 * dendrogram colorbar_height = .2 * dendrogram if axis == 0: ratios = [colorbar_width, colorbar_height] else: ratios = [colorbar_height, colorbar_width] if side_colors is not None: # Add room for the colors ratios += [side_colors_ratio] # Add the ratio for the heatmap itself ratios += [.8] return ratios @staticmethod def color_list_to_matrix_and_cmap(colors, ind, axis=0): """Turns a list of colors into a numpy matrix and matplotlib colormap These arguments can now be plotted using heatmap(matrix, cmap) and the provided colors will be plotted. Parameters ---------- colors : list of matplotlib colors Colors to label the rows or columns of a dataframe. ind : list of ints Ordering of the rows or columns, to reorder the original colors by the clustered dendrogram order axis : int Which axis this is labeling Returns ------- matrix : numpy.array A numpy array of integer values, where each corresponds to a color from the originally provided list of colors cmap : matplotlib.colors.ListedColormap """ # check for nested lists/color palettes. # Will fail if matplotlib color is list not tuple if any(issubclass(type(x), list) for x in colors): all_colors = set(itertools.chain(*colors)) n = len(colors) m = len(colors[0]) else: all_colors = set(colors) n = 1 m = len(colors) colors = [colors] color_to_value = dict((col, i) for i, col in enumerate(all_colors)) matrix = np.array([color_to_value[c] for color in colors for c in color]) shape = (n, m) matrix = matrix.reshape(shape) matrix = matrix[:, ind] if axis == 0: # row-side: matrix = matrix.T cmap = mpl.colors.ListedColormap(all_colors) return matrix, cmap def savefig(self, *args, **kwargs): if 'bbox_inches' not in kwargs: kwargs['bbox_inches'] = 'tight' self.fig.savefig(*args, **kwargs) def plot_dendrograms(self, row_cluster, col_cluster, metric, method, row_linkage, col_linkage): # Plot the row dendrogram if row_cluster: self.dendrogram_row = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=0, ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage) else: self.ax_row_dendrogram.set_xticks([]) self.ax_row_dendrogram.set_yticks([]) # PLot the column dendrogram if col_cluster: self.dendrogram_col = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage) else: self.ax_col_dendrogram.set_xticks([]) self.ax_col_dendrogram.set_yticks([]) despine(ax=self.ax_row_dendrogram, bottom=True, left=True) despine(ax=self.ax_col_dendrogram, bottom=True, left=True) def plot_colors(self, xind, yind, **kws): """Plots color labels between the dendrogram and the heatmap Parameters ---------- heatmap_kws : dict Keyword arguments heatmap """ # Remove any custom colormap and centering kws = kws.copy() kws.pop('cmap', None) kws.pop('center', None) kws.pop('vmin', None) kws.pop('vmax', None) kws.pop('xticklabels', None) kws.pop('yticklabels', None) if self.row_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.row_colors, yind, axis=0) heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors, xticklabels=False, yticklabels=False, **kws) else: despine(self.ax_row_colors, left=True, bottom=True) if self.col_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.col_colors, xind, axis=1) heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors, xticklabels=False, yticklabels=False, **kws) else: despine(self.ax_col_colors, left=True, bottom=True) def plot_matrix(self, colorbar_kws, xind, yind, **kws): self.data2d = self.data2d.iloc[yind, xind] self.mask = self.mask.iloc[yind, xind] # Try to reorganize specified tick labels, if provided xtl = kws.pop("xticklabels", True) try: xtl = np.asarray(xtl)[xind] except (TypeError, IndexError): pass ytl = kws.pop("yticklabels", True) try: ytl = np.asarray(ytl)[yind] except (TypeError, IndexError): pass heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.cax, cbar_kws=colorbar_kws, mask=self.mask, xticklabels=xtl, yticklabels=ytl, **kws) self.ax_heatmap.yaxis.set_ticks_position('right') self.ax_heatmap.yaxis.set_label_position('right') def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, **kws): colorbar_kws = {} if colorbar_kws is None else colorbar_kws self.plot_dendrograms(row_cluster, col_cluster, metric, method, row_linkage=row_linkage, col_linkage=col_linkage) try: xind = self.dendrogram_col.reordered_ind except AttributeError: xind = np.arange(self.data2d.shape[1]) try: yind = self.dendrogram_row.reordered_ind except AttributeError: yind = np.arange(self.data2d.shape[0]) self.plot_colors(xind, yind, **kws) self.plot_matrix(colorbar_kws, xind, yind, **kws) return self def clustermap(data, pivot_kws=None, method='average', metric='euclidean', z_score=None, standard_scale=None, figsize=None, cbar_kws=None, row_cluster=True, col_cluster=True, row_linkage=None, col_linkage=None, row_colors=None, col_colors=None, mask=None, **kwargs): """Plot a hierarchically clustered heatmap of a pandas DataFrame Parameters ---------- data: pandas.DataFrame Rectangular data for clustering. Cannot contain NAs. pivot_kws : dict, optional If `data` is a tidy dataframe, can provide keyword arguments for pivot to create a rectangular dataframe. method : str, optional Linkage method to use for calculating clusters. See scipy.cluster.hierarchy.linkage documentation for more information: http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html metric : str, optional Distance metric to use for the data. See scipy.spatial.distance.pdist documentation for more options http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html z_score : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores for the rows or the columns. Z scores are: z = (x - mean)/std, so values in each row (column) will get the mean of the row (column) subtracted, then divided by the standard deviation of the row (column). This ensures that each row (column) has mean of 0 and variance of 1. standard_scale : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to standardize that dimension, meaning for each row or column, subtract the minimum and divide each by its maximum. figsize: tuple of two ints, optional Size of the figure to create. cbar_kws : dict, optional Keyword arguments to pass to ``cbar_kws`` in ``heatmap``, e.g. to add a label to the colorbar. {row,col}_cluster : bool, optional If True, cluster the {rows, columns}. {row,col}_linkage : numpy.array, optional Precomputed linkage matrix for the rows or columns. See scipy.cluster.hierarchy.linkage for specific formats. {row,col}_colors : list-like, optional List of colors to label for either the rows or columns. Useful to evaluate whether samples within a group are clustered together. Can use nested lists for multiple color levels of labeling. mask : boolean array or DataFrame, optional If passed, data will not be shown in cells where ``mask`` is True. Cells with missing values are automatically masked. Only used for visualizing, not for calculating. kwargs : other keyword arguments All other keyword arguments are passed to ``sns.heatmap`` Returns ------- clustergrid : ClusterGrid A ClusterGrid instance. Notes ----- The returned object has a ``savefig`` method that should be used if you want to save the figure object without clipping the dendrograms. To access the reordered row indices, use: ``clustergrid.dendrogram_row.reordered_ind`` Column indices, use: ``clustergrid.dendrogram_col.reordered_ind`` Examples -------- Plot a clustered heatmap: .. plot:: :context: close-figs >>> import seaborn as sns; sns.set() >>> flights = sns.load_dataset("flights") >>> flights = flights.pivot("month", "year", "passengers") >>> g = sns.clustermap(flights) Don't cluster one of the axes: .. plot:: :context: close-figs >>> g = sns.clustermap(flights, col_cluster=False) Use a different colormap and add lines to separate the cells: .. plot:: :context: close-figs >>> cmap = sns.cubehelix_palette(as_cmap=True, rot=-.3, light=1) >>> g = sns.clustermap(flights, cmap=cmap, linewidths=.5) Use a different figure size: .. plot:: :context: close-figs >>> g = sns.clustermap(flights, cmap=cmap, figsize=(7, 5)) Standardize the data across the columns: .. plot:: :context: close-figs >>> g = sns.clustermap(flights, standard_scale=1) Normalize the data across the rows: .. plot:: :context: close-figs >>> g = sns.clustermap(flights, z_score=0) Use a different clustering method: .. plot:: :context: close-figs >>> g = sns.clustermap(flights, method="single", metric="cosine") Add colored labels on one of the axes: .. plot:: :context: close-figs >>> season_colors = (sns.color_palette("BuPu", 3) + ... sns.color_palette("RdPu", 3) + ... sns.color_palette("YlGn", 3) + ... sns.color_palette("OrRd", 3)) >>> g = sns.clustermap(flights, row_colors=season_colors) """ plotter = ClusterGrid(data, pivot_kws=pivot_kws, figsize=figsize, row_colors=row_colors, col_colors=col_colors, z_score=z_score, standard_scale=standard_scale, mask=mask) return plotter.plot(metric=metric, method=method, colorbar_kws=cbar_kws, row_cluster=row_cluster, col_cluster=col_cluster, row_linkage=row_linkage, col_linkage=col_linkage, **kwargs)
bsd-3-clause
i-namekawa/TopSideMonitor
plotting.py
1
37323
import os, sys, time from glob import glob import cv2 from pylab import * from mpl_toolkits.mplot3d import Axes3D from matplotlib.backends.backend_pdf import PdfPages matplotlib.rcParams['figure.facecolor'] = 'w' from scipy.signal import argrelextrema import scipy.stats as stats import scipy.io as sio from scipy import signal from xlwt import Workbook # specify these in mm to match your behavior chamber. CHMAMBER_LENGTH=235 WATER_HIGHT=40 # quick plot should also show xy_within and location_one_third etc # summary PDF: handle exception when a pickle file missing some fish in other pickle file ## these three taken from http://stackoverflow.com/a/18420730/566035 def strided_sliding_std_dev(data, radius=5): windowed = rolling_window(data, (2*radius, 2*radius)) shape = windowed.shape windowed = windowed.reshape(shape[0], shape[1], -1) return windowed.std(axis=-1) def rolling_window(a, window): """Takes a numpy array *a* and a sequence of (or single) *window* lengths and returns a view of *a* that represents a moving window.""" if not hasattr(window, '__iter__'): return rolling_window_lastaxis(a, window) for i, win in enumerate(window): if win > 1: a = a.swapaxes(i, -1) a = rolling_window_lastaxis(a, win) a = a.swapaxes(-2, i) return a def rolling_window_lastaxis(a, window): """Directly taken from Erik Rigtorp's post to numpy-discussion. <http://www.mail-archive.com/numpy-discussion@scipy.org/msg29450.html>""" if window < 1: raise ValueError, "`window` must be at least 1." if window > a.shape[-1]: raise ValueError, "`window` is too long." shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) ## stealing ends here... // def filterheadxy(headx,heady,thrs_denom=10): b, a = signal.butter(8, 0.125) dhy = np.abs(np.hstack((0, np.diff(heady,1)))) thrs = np.nanstd(dhy)/thrs_denom ind2remove = dhy>thrs headx[ind2remove] = np.nan heady[ind2remove] = np.nan headx = interp_nan(headx) heady = interp_nan(heady) headx = signal.filtfilt(b, a, headx, padlen=150) heady = signal.filtfilt(b, a, heady, padlen=150) return headx,heady def smoothRad(theta, thrs=np.pi/4*3): jumps = (np.diff(theta) > thrs).nonzero()[0] print 'jumps.size', jumps.size while jumps.size: # print '%d/%d' % (jumps[0], theta.size) theta[jumps+1] -= np.pi jumps = (np.diff(theta) > thrs).nonzero()[0] return theta def datadct2array(data, key1, key2): # put these in a MATLAB CELL trialN = len(data[key1][key2]) matchedUSnameP = np.zeros((trialN,), dtype=np.object) fnameP = np.zeros((trialN,), dtype=np.object) # others to append to a list eventsP = [] speed3DP = [] movingSTDP = [] d2inflowP = [] xP, yP, zP = [], [], [] XP, YP, ZP = [], [], [] ringpixelsP = [] peaks_withinP = [] swimdir_withinP = [] xy_withinP = [] location_one_thirdP = [] dtheta_shapeP = [] dtheta_velP = [] turns_shapeP = [] turns_velP = [] for n, dct in enumerate(data[key1][key2]): # MATLAB CELL matchedUSnameP[n] = dct['matchedUSname'] fnameP[n] = dct['fname'] # 2D array eventsP.append([ele if type(ele) is not list else ele[0] for ele in dct['events']]) speed3DP.append(dct['speed3D']) movingSTDP.append(dct['movingSTD']) d2inflowP.append(dct['d2inflow']) xP.append(dct['x']) yP.append(dct['y']) zP.append(dct['z']) XP.append(dct['X']) YP.append(dct['Y']) ZP.append(dct['Z']) ringpixelsP.append(dct['ringpixels']) peaks_withinP.append(dct['peaks_within']) swimdir_withinP.append(dct['swimdir_within']) xy_withinP.append(dct['xy_within']) location_one_thirdP.append(dct['location_one_third']) dtheta_shapeP.append(dct['dtheta_shape']) dtheta_velP.append(dct['dtheta_vel']) turns_shapeP.append(dct['turns_shape']) turns_velP.append(dct['turns_vel']) TVroi = np.array(dct['TVroi']) SVroi = np.array(dct['SVroi']) return matchedUSnameP, fnameP, np.array(eventsP), np.array(speed3DP), np.array(d2inflowP), \ np.array(xP), np.array(yP), np.array(zP), np.array(XP), np.array(YP), np.array(ZP), \ np.array(ringpixelsP), np.array(peaks_withinP), np.array(swimdir_withinP), \ np.array(xy_withinP), np.array(dtheta_shapeP), np.array(dtheta_velP), \ np.array(turns_shapeP), np.array(turns_velP), TVroi, SVroi def pickle2mat(fp, data=None): # fp : full path to pickle file # data : option to provide data to skip np.load(fp) if not data: data = np.load(fp) for key1 in data.keys(): for key2 in data[key1].keys(): matchedUSname, fname, events, speed3D, d2inflow, x, y, z, X, Y, Z, \ ringpixels, peaks_within, swimdir_within, xy_within, dtheta_shape, dtheta_vel, \ turns_shape, turns_vel, TVroi, SVroi = datadct2array(data, key1, key2) datadict = { 'matchedUSname' : matchedUSname, 'fname' : fname, 'events' : events, 'speed3D' : speed3D, 'd2inflow' : d2inflow, 'x' : x, 'y' : y, 'z' : z, 'X' : X, 'Y' : Y, 'Z' : Z, 'ringpixels' : ringpixels, 'peaks_within' : peaks_within, 'swimdir_within' : swimdir_within, 'xy_within' : xy_within, 'dtheta_shape' : dtheta_shape, 'dtheta_vel' : dtheta_vel, 'turns_shape' : turns_shape, 'turns_vel' : turns_vel, 'TVroi' : TVroi, 'SVroi' : SVroi, } outfp = '%s_%s_%s.mat' % (fp[:-7],key1,key2) sio.savemat(outfp, datadict, oned_as='row', do_compression=True) def interp_nan(x): ''' Replace nan by interporation http://stackoverflow.com/questions/6518811/interpolate-nan-values-in-a-numpy-array ''' ok = -np.isnan(x) if (ok == False).all(): return x else: xp = ok.ravel().nonzero()[0] fp = x[ok] _x = np.isnan(x).ravel().nonzero()[0] x[-ok] = np.interp(_x, xp, fp) return x def polytest(x,y,rx,ry,rw,rh,rang): points=cv2.ellipse2Poly( (rx,ry), axes=(rw/2,rh/2), angle=rang, arcStart=0, arcEnd=360, delta=3 ) return cv2.pointPolygonTest(np.array(points), (x,y), measureDist=1) def depthCorrection(z,x,TVx1,TVx2,SVy1,SVy2,SVy3): z0 = z - SVy1 x0 = x - TVx1 mid = (SVy2-SVy1)/2 adj = (z0 - mid) / (SVy2-SVy1) * (SVy2-SVy3) * (1-(x0)/float(TVx2-TVx1)) return z0 + adj + SVy1 # back to abs coord def putNp2xls(array, ws): for r, row in enumerate(array): for c, val in enumerate(row): ws.write(r, c, val) def drawLines(mi, ma, events, fps=30.0): CS, USs, preRange = events plot([CS-preRange, CS-preRange], [mi,ma], '--c') # 2 min prior odor plot([CS , CS ], [mi,ma], '--g', linewidth=2) # CS onset if USs: if len(USs) > 3: colors = 'r' * len(USs) else: colors = [_ for _ in ['r','b','c'][:len(USs)]] for c,us in zip(colors, USs): plot([us, us],[mi,ma], linestyle='--', color=c, linewidth=2) # US onset plot([USs[0]+preRange/2,USs[0]+preRange/2], [mi,ma], linestyle='--', color=c, linewidth=2) # end of US window xtck = np.arange(0, max(CS+preRange, max(USs)), 0.5*60*fps) # every 0.5 min tick else: xtck = np.arange(0, CS+preRange, 0.5*60*fps) # every 0.5 min tick xticks(xtck, xtck/fps/60) gca().xaxis.set_minor_locator(MultipleLocator(5*fps)) # 5 s minor ticks def approachevents(x,y,z, ringpolyTVArray, ringpolySVArray, fishlength=134, thrs=None): ''' fishlength: some old scrits may call this with fishlength thrs: multitrack GUI provides this by ringAppearochLevel spin control. can be an numpy array (to track water level change etc) ''' smoothedz = np.convolve(np.hanning(10)/np.hanning(10).sum(), z, 'same') peaks = argrelextrema(smoothedz, np.less)[0] # less because 0 is top in image. # now filter peaks by height. ringLevel = ringpolySVArray[:,1] if thrs is None: thrs = ringLevel+fishlength/2 if type(thrs) == int: # can be numpy array or int thrs = ringLevel.mean() + thrs peaks = peaks[ z[peaks] < thrs ] else: # numpy array should be ready to use peaks = peaks[ z[peaks] < thrs[peaks] ] # now filter out by TVringCenter peaks_within = get_withinring(ringpolyTVArray, peaks, x, y) return smoothedz, peaks_within def get_withinring(ringpolyTVArray, timepoints, x, y): rx = ringpolyTVArray[:,0].astype(np.int) ry = ringpolyTVArray[:,1].astype(np.int) rw = ringpolyTVArray[:,2].astype(np.int) rh = ringpolyTVArray[:,3].astype(np.int) rang = ringpolyTVArray[:,4].astype(np.int) # poly test peaks_within = [] for p in timepoints: points=cv2.ellipse2Poly( (rx[p],ry[p]), axes=(rw[p]/2,rh[p]/2), angle=rang[p], arcStart=0, arcEnd=360, delta=3 ) inout = cv2.pointPolygonTest(np.array(points), (x[p],y[p]), measureDist=1) if inout > 0: peaks_within.append(p) return peaks_within def location_ring(x,y,ringpolyTVArray): rx = ringpolyTVArray[:,0].astype(np.int) ry = ringpolyTVArray[:,1].astype(np.int) rw = ringpolyTVArray[:,2].astype(np.int) rh = ringpolyTVArray[:,3].astype(np.int) d2ringcenter = np.sqrt((x-rx)**2 + (y-ry)**2) # filter by radius 20% buffer in case the ring moves around indices = (d2ringcenter < 1.2*max(rw.max(), rh.max())).nonzero()[0] xy_within = get_withinring(ringpolyTVArray, indices, x, y) return xy_within def swimdir_analysis(x,y,z,ringpolyTVArray,ringpolySVArray,TVx1,TVy1,TVx2,TVy2,fps=30.0): # smoothing # z = np.convolve(np.hanning(16)/np.hanning(16).sum(), z, 'same') # two cameras have different zoom settings. So, distance per pixel is different. But, for # swim direction, it does not matter how much x,y are compressed relative to z. # ring z level from SV rz = ringpolySVArray[:,1].astype(np.int) # ring all other params from TV rx = ringpolyTVArray[:,0].astype(np.int) ry = ringpolyTVArray[:,1].astype(np.int) rw = ringpolyTVArray[:,2].astype(np.int) rh = ringpolyTVArray[:,3].astype(np.int) rang = ringpolyTVArray[:,4].astype(np.int) speed3D = np.sqrt( np.diff(x)**2 + np.diff(y)**2 + np.diff(z)**2 ) speed3D = np.hstack(([0], speed3D)) # line in 3D http://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx # x-x0 y-y0 z-z0 # ---- = ---- = ---- # a b c # solve them for z = rz. x0,y0,z0 are tvx, tvy, svy # x = (a * (rz-z)) / c + x0 dt = 3 # define slope as diff between current and dt frame before a = np.hstack( (np.ones(dt), x[dt:]-x[:-dt]) ) b = np.hstack( (np.ones(dt), y[dt:]-y[:-dt]) ) c = np.hstack( (np.ones(dt), z[dt:]-z[:-dt]) ) c[c==0] = np.nan # avoid zero division water_x = (a * (rz-z) / c) + x water_y = (b * (rz-z) / c) + y upwards = c<-2/30.0*fps # not accurate when c is small or negative xok = (TVx1 < water_x) & (water_x < TVx2) yok = (TVy1 < water_y) & (water_y < TVy2) filtered = upwards & xok & yok# & -np.isinf(water_x) & -np.isinf(water_y) water_x[-filtered] = np.nan water_y[-filtered] = np.nan # figure() # ax = subplot(111) # ax.imshow(npData['TVbg'], cmap=cm.gray) # clip out from TVx1,TVy1 # ax.plot(x-TVx1, y-TVy1, 'c') # ax.plot(water_x-TVx1, water_y-TVy1, 'r.') # xlim([0, TVx2-TVx1]); ylim([TVy2-TVy1, 0]) # draw(); show() SwimDir = [] for n in filtered.nonzero()[0]: inout = polytest(water_x[n],water_y[n],rx[n],ry[n],rw[n],rh[n],rang[n]) SwimDir.append((n, inout, speed3D[n])) # inout>0 are inside return SwimDir, water_x, water_y def plot_eachTr(events, x, y, z, inflowpos, ringpixels, peaks_within, swimdir_within=None, pp=None, _title=None, fps=30.0, inmm=False): CS, USs, preRange = events # preRange = 3600 2 min prior and 1 min after CS. +900 for 0.5 min if USs: xmin, xmax = CS-preRange-10*fps, USs[0]+preRange/2+10*fps else: xmin, xmax = CS-preRange-10*fps, CS+preRange/2+(23+10)*fps fig = figure(figsize=(12,8), facecolor='w') subplot(511) # Swimming speed speed3D = np.sqrt( np.diff(x)**2 + np.diff(y)**2 + np.diff(z)**2 ) drawLines(np.nanmin(speed3D), np.nanmax(speed3D), events, fps) # go behind plot(speed3D) movingSTD = np.append( np.zeros(fps*10), strided_sliding_std_dev(speed3D, fps*10) ) plot(movingSTD, linewidth=2) plot(np.ones_like(speed3D) * speed3D.std()*6, '-.', color='gray') ylim([-5, speed3D[xmin:xmax].max()]) xlim([xmin,xmax]); title(_title) if inmm: ylabel('Speed 3D (mm),\n6SD thr'); else: ylabel('Speed 3D, 6SD thr'); ax = subplot(512) # z level drawLines(z.min(), z.max(), events) plot(z, 'b') pkx = peaks_within.nonzero()[0] if inmm: plot(pkx, peaks_within[pkx]*z[xmin:xmax].max()*0.97, 'mo') if swimdir_within is not None: ___x = swimdir_within.nonzero()[0] plot(___x, swimdir_within[___x]*z[xmin:xmax].max()*0.96, 'g+') ylim([z[xmin:xmax].min()*0.95, z[xmin:xmax].max()]) xlim([xmin,xmax]); ylabel('Z (mm)') else: plot(pkx, peaks_within[pkx]*z[xmin:xmax].min()*0.97, 'mo') if swimdir_within is not None: ___x = swimdir_within.nonzero()[0] plot(___x, swimdir_within[___x]*z[xmin:xmax].min()*0.96, 'g+') ylim([z[xmin:xmax].min()*0.95, z[xmin:xmax].max()]) ax.invert_yaxis(); xlim([xmin,xmax]); ylabel('z') subplot(513) # x drawLines(x.min(), x.max(), events) plot(x, 'b') plot(y, 'g') xlim([xmin,xmax]); ylabel('x,y') subplot(514) # Distance to the inflow tube xin, yin, zin = inflowpos d2inflow = np.sqrt((x-xin) ** 2 + (y-yin) ** 2 + (z-zin) ** 2 ) drawLines(d2inflow.min(), d2inflow.max(), events) plot(d2inflow) ylim([d2inflow[xmin:xmax].min(), d2inflow[xmin:xmax].max()]) xlim([xmin,xmax]); ylabel('distance to\ninflow tube') subplot(515) # ringpixels: it seems i never considered TV x,y for this rpmax, rpmin = np.nanmax(ringpixels[xmin:xmax]), np.nanmin(ringpixels[xmin:xmax]) drawLines(rpmin, rpmax, events) plot(ringpixels) plot(pkx, peaks_within[pkx]*rpmax*1.06, 'mo') if swimdir_within is not None: plot(___x, swimdir_within[___x]*rpmax*1.15, 'g+') ylim([-100, rpmax*1.2]) xlim([xmin,xmax]); ylabel('ringpixels') tight_layout() if pp: fig.savefig(pp, format='pdf') rng = np.arange(CS-preRange, CS+preRange, dtype=np.int) return speed3D[rng], movingSTD[rng], d2inflow[rng], ringpixels[rng] def plot_turnrates(events, dthetasum_shape,dthetasum_vel,turns_shape,turns_vel, pp=None, _title=None, thrs=np.pi/4*(133.33333333333334/120), fps=30.0): CS, USs, preRange = events # preRange = 3600 2 min prior and 1 min after CS. +900 for 0.5 min if USs: xmin, xmax = CS-preRange-10*fps, USs[0]+preRange/2+10*fps else: xmin, xmax = CS-preRange-10*fps, CS+preRange/2+(23+10)*fps fig = figure(figsize=(12,8), facecolor='w') subplot(211) drawLines(dthetasum_shape.min(), dthetasum_shape.max(), events) plot(np.ones_like(dthetasum_shape)*thrs,'gray',linestyle='--') plot(-np.ones_like(dthetasum_shape)*thrs,'gray',linestyle='--') plot(dthetasum_shape) dmax = dthetasum_shape[xmin:xmax].max() plot(turns_shape, (0.5+dmax)*np.ones_like(turns_shape), 'o') temp = np.zeros_like(dthetasum_shape) temp[turns_shape] = 1 shape_cumsum = np.cumsum(temp) shape_cumsum -= shape_cumsum[xmin] plot( shape_cumsum / shape_cumsum[xmax] * (dmax-dthetasum_shape.min()) + dthetasum_shape.min()) xlim([xmin,xmax]); ylabel('Shape based'); title('Orientation change per 4 frames: ' + _title) ylim([dthetasum_shape[xmin:xmax].min()-1, dmax+1]) subplot(212) drawLines(dthetasum_vel.min(), dthetasum_vel.max(), events) plot(np.ones_like(dthetasum_vel)*thrs,'gray',linestyle='--') plot(-np.ones_like(dthetasum_vel)*thrs,'gray',linestyle='--') plot(dthetasum_vel) dmax = dthetasum_vel[xmin:xmax].max() plot(turns_vel, (0.5+dmax)*np.ones_like(turns_vel), 'o') temp = np.zeros_like(dthetasum_vel) temp[turns_vel] = 1 vel_cumsum = np.cumsum(temp) vel_cumsum -= vel_cumsum[xmin] plot( vel_cumsum / vel_cumsum[xmax] * (dmax-dthetasum_shape.min()) + dthetasum_shape.min()) ylim([dthetasum_vel[xmin:xmax].min()-1, dmax+1]) xlim([xmin,xmax]); ylabel('Velocity based') tight_layout() if pp: fig.savefig(pp, format='pdf') def trajectory(x, y, z, rng, ax, _xlim=[0,640], _ylim=[480,480+300], _zlim=[150,340], color='b', fps=30.0, ringpolygon=None): ax.plot(x[rng],y[rng],z[rng], color=color) ax.view_init(azim=-75, elev=-180+15) if ringpolygon: rx, ry, rz = ringpolygon ax.plot(rx, ry, rz, color='gray') ax.set_xlim(_xlim[0],_xlim[1]) ax.set_ylim(_ylim[0],_ylim[1]) ax.set_zlim(_zlim[0],_zlim[1]) title(("(%2.1f min to %2.1f min)" % (rng[0]/fps/60.0,(rng[-1]+1)/60.0/fps))) draw() def plotTrajectory(x, y, z, events, _xlim=None, _ylim=None, _zlim=None, fps=30.0, pp=None, ringpolygon=None): CS, USs, preRange = events rng1 = np.arange(CS-preRange, CS-preRange/2, dtype=int) rng2 = np.arange(CS-preRange/2, CS, dtype=int) if USs: rng3 = np.arange(CS, min(USs), dtype=int) rng4 = np.arange(min(USs), min(USs)+preRange/2, dtype=int) combined = np.hstack((rng1,rng2,rng3,rng4)) else: combined = np.hstack((rng1,rng2)) if _xlim is None: _xlim = map( int, ( x[combined].min(), x[combined].max() ) ) if _ylim is None: _ylim = map( int, ( y[combined].min(), y[combined].max() ) ) if _zlim is None: _zlim = map( int, ( z[combined].min(), z[combined].max() ) ) if ringpolygon: _zlim[0] = min( _zlim[0], int(ringpolygon[2][0]) ) fig3D = plt.figure(figsize=(12,8), facecolor='w') ax = fig3D.add_subplot(221, projection='3d'); trajectory(x,y,z,rng1,ax,_xlim,_ylim,_zlim,'c',fps,ringpolygon) ax = fig3D.add_subplot(222, projection='3d'); trajectory(x,y,z,rng2,ax,_xlim,_ylim,_zlim,'c',fps,ringpolygon) if USs: ax = fig3D.add_subplot(223, projection='3d'); trajectory(x,y,z,rng3,ax,_xlim,_ylim,_zlim,'g',fps,ringpolygon) ax = fig3D.add_subplot(224, projection='3d'); trajectory(x,y,z,rng4,ax,_xlim,_ylim,_zlim,'r',fps,ringpolygon) tight_layout() if pp: fig3D.savefig(pp, format='pdf') def add2DataAndPlot(fp, fish, data, createPDF): if createPDF: pp = PdfPages(fp[:-7]+'_'+fish+'.pdf') else: pp = None params = np.load(fp) fname = os.path.basename(fp).split('.')[0] + '.avi' dirname = os.path.dirname(fp) preRange = params[(fname, 'mog')]['preRange'] fps = params[(fname, 'mog')]['fps'] TVx1 = params[(fname, fish)]['TVx1'] TVy1 = params[(fname, fish)]['TVy1'] TVx2 = params[(fname, fish)]['TVx2'] TVy2 = params[(fname, fish)]['TVy2'] SVx1 = params[(fname, fish)]['SVx1'] SVx2 = params[(fname, fish)]['SVx2'] SVx3 = params[(fname, fish)]['SVx3'] SVy1 = params[(fname, fish)]['SVy1'] SVy2 = params[(fname, fish)]['SVy2'] SVy3 = params[(fname, fish)]['SVy3'] ringAppearochLevel = params[(fname, fish)]['ringAppearochLevel'] _npz = os.path.join(dirname, os.path.join('%s_%s.npz' % (fname[:-4], fish))) # if os.path.exists(_npz): npData = np.load(_npz) tvx = npData['TVtracking'][:,0] # x with nan tvy = npData['TVtracking'][:,1] # y headx = npData['TVtracking'][:,3] # headx heady = npData['TVtracking'][:,4] # heady svy = npData['SVtracking'][:,1] # z InflowTubeTVArray = npData['InflowTubeTVArray'] InflowTubeSVArray = npData['InflowTubeSVArray'] inflowpos = InflowTubeTVArray[:,0], InflowTubeTVArray[:,1], InflowTubeSVArray[:,1] ringpixels = npData['ringpixel'] ringpolyTVArray = npData['ringpolyTVArray'] ringpolySVArray = npData['ringpolySVArray'] TVbg = npData['TVbg'] print os.path.basename(_npz), 'loaded.' x,y,z = map(interp_nan, [tvx,tvy,svy]) # z level correction by depth (x) z = depthCorrection(z,x,TVx1,TVx2,SVy1,SVy2,SVy3) smoothedz, peaks_within = approachevents(x, y, z, ringpolyTVArray, ringpolySVArray, thrs=ringAppearochLevel) # convert to numpy array from list temp = np.zeros_like(x) temp[peaks_within] = 1 peaks_within = temp # normalize to mm longaxis = float(max((TVx2-TVx1), (TVy2-TVy1))) # before rotation H is applied they are orthogonal waterlevel = float(SVy2-SVy1) X = (x-TVx1) / longaxis * CHMAMBER_LENGTH Y = (TVy2-y) / longaxis * CHMAMBER_LENGTH Z = (SVy2-z) / waterlevel * WATER_HIGHT # bottom of chamber = 0, higher more positive inflowpos_mm = ((inflowpos[0]-TVx1) / longaxis * CHMAMBER_LENGTH, (TVy2-inflowpos[1]) / longaxis * CHMAMBER_LENGTH, (SVy2-inflowpos[2]) / waterlevel * WATER_HIGHT ) # do the swim direction analysis here swimdir, water_x, water_y = swimdir_analysis(x,y,z, ringpolyTVArray,ringpolySVArray,TVx1,TVy1,TVx2,TVy2,fps) # all of swimdir are within ROI (frame#, inout, speed) but not necessary within ring sdir = np.array(swimdir) withinRing = sdir[:,1]>0 # inout>0 are inside ring temp = np.zeros_like(x) temp[ sdir[withinRing,0].astype(int) ] = 1 swimdir_within = temp # location_ring xy_within = location_ring(x,y, ringpolyTVArray) temp = np.zeros_like(x) temp[xy_within] = 1 xy_within = temp # location_one_third if (TVx2-TVx1) > (TVy2-TVy1): if np.abs(np.arange(TVx1, longaxis+TVx1, longaxis/3) + longaxis/6 - inflowpos[0].mean()).argmin() == 2: location_one_third = x-TVx1 > longaxis/3*2 else: location_one_third = x < longaxis/3 else: if np.abs(np.arange(TVy1, longaxis+TVy1, longaxis/3) + longaxis/6 - inflowpos[1].mean()).argmin() == 2: location_one_third = y-TVy1 > longaxis/3*2 else: location_one_third = y < longaxis/3 # turn rate analysis (shape based) heady, headx = map(interp_nan, [heady, headx]) headx, heady = filterheadxy(headx, heady) dy = heady - y dx = headx - x theta_shape = np.arctan2(dy, dx) # velocity based cx, cy = filterheadxy(x.copy(), y.copy()) # centroid x,y vx = np.append(0, np.diff(cx)) vy = np.append(0, np.diff(cy)) theta_vel = np.arctan2(vy, vx) # prepare ringpolygon for trajectory plot rx, ry, rw, rh, rang = ringpolyTVArray.mean(axis=0).astype(int) # use mm ver above rz = ringpolySVArray.mean(axis=0)[1].astype(int) RX = (rx-TVx1) / longaxis * CHMAMBER_LENGTH RY = (TVy2-ry) / longaxis * CHMAMBER_LENGTH RW = rw / longaxis * CHMAMBER_LENGTH / 2 RH = rh / longaxis * CHMAMBER_LENGTH / 2 RZ = (SVy2-rz) / waterlevel * WATER_HIGHT points = cv2.ellipse2Poly( (RX.astype(int),RY.astype(int)), axes=(RW.astype(int),RH.astype(int)), angle=rang, arcStart=0, arcEnd=360, delta=3 ) ringpolygon = [points[:,0], points[:,1], np.ones(points.shape[0]) * RZ] eventTypeKeys = params[(fname, fish)]['EventData'].keys() CSs = [_ for _ in eventTypeKeys if _.startswith('CS')] USs = [_ for _ in eventTypeKeys if _.startswith('US')] # print CSs, USs # events for CS in CSs: CS_Timings = params[(fname, fish)]['EventData'][CS] CS_Timings.sort() # initialize when needed if CS not in data[fish].keys(): data[fish][CS] = [] # now look around for US after it within preRange for t in CS_Timings: tr = len(data[fish][CS])+1 rng = np.arange(t-preRange, t+preRange, dtype=np.int) matchedUSname = None for us in USs: us_Timings = params[(fname, fish)]['EventData'][us] matched = [_ for _ in us_Timings if t-preRange < _ < t+preRange] if matched: events = [t, matched, preRange] # ex. CS+ matchedUSname = us break else: continue _title = '(%s, %s) trial#%02d %s (%s)' % (CS, matchedUSname[0], tr, fname, fish) print _title, events _speed3D, _movingSTD, _d2inflow, _ringpixels = plot_eachTr(events, X, Y, Z, inflowpos_mm, ringpixels, peaks_within, swimdir_within, pp, _title, fps, inmm=True) # 3d trajectory _xlim = (0, CHMAMBER_LENGTH) _zlim = (RZ.max(),0) plotTrajectory(X, Y, Z, events, _xlim=_xlim, _zlim=_zlim, fps=fps, pp=pp, ringpolygon=ringpolygon) # turn rate analysis # shape based theta_shape[rng] = smoothRad(theta_shape[rng].copy(), thrs=np.pi/2) dtheta_shape = np.append(0, np.diff(theta_shape)) # full length kernel = np.ones(4) dthetasum_shape = np.convolve(dtheta_shape, kernel, 'same') # 4 frames = 1000/30.0*4 = 133.3 ms thrs = (np.pi / 2) * (133.33333333333334/120) # Braubach et al 2009 90 degree in 120 ms peaks_shape = argrelextrema(abs(dthetasum_shape), np.greater)[0] turns_shape = peaks_shape[ (abs(dthetasum_shape[peaks_shape]) > thrs).nonzero()[0] ] # velocity based theta_vel[rng] = smoothRad(theta_vel[rng].copy(), thrs=np.pi/2) dtheta_vel = np.append(0, np.diff(theta_vel)) dthetasum_vel = np.convolve(dtheta_vel, kernel, 'same') peaks_vel = argrelextrema(abs(dthetasum_vel), np.greater)[0] turns_vel = peaks_vel[ (abs(dthetasum_vel[peaks_vel]) > thrs).nonzero()[0] ] plot_turnrates(events, dthetasum_shape, dthetasum_vel, turns_shape, turns_vel, pp, _title, fps=fps) _temp = np.zeros_like(dtheta_shape) _temp[turns_shape] = 1 turns_shape_array = _temp _temp = np.zeros_like(dtheta_vel) _temp[turns_vel] = 1 turns_vel_array = _temp # plot swim direction analysis fig = figure(figsize=(12,8), facecolor='w') ax1 = subplot(211) ax1.imshow(TVbg, cmap=cm.gray) # TVbg is clip out of ROI ax1.plot(x[rng]-TVx1, y[rng]-TVy1, 'gray') ax1.plot(water_x[t-preRange:t]-TVx1, water_y[t-preRange:t]-TVy1, 'c.') if matched: ax1.plot( water_x[t:matched[0]]-TVx1, water_y[t:matched[0]]-TVy1, 'g.') ax1.plot( water_x[matched[0]:matched[0]+preRange/4]-TVx1, water_y[matched[0]:matched[0]+preRange/4]-TVy1, 'r.') xlim([0, TVx2-TVx1]); ylim([TVy2-TVy1, 0]) title(_title) ax2 = subplot(212) ax2.plot( swimdir_within ) ax2.plot( peaks_within*1.15-0.1, 'mo' ) if matched: xmin, xmax = t-preRange-10*fps, matched[0]+preRange/4 else: xmin, xmax = t-preRange-10*fps, t+preRange/2+10*fps gzcs = np.cumsum(swimdir_within) gzcs -= gzcs[xmin] ax2.plot( gzcs/gzcs[xmax] ) drawLines(0,1.2, events) ylim([0,1.2]) xlim([xmin, xmax]) ylabel('|: SwimDirection\no: approach events') data[fish][CS].append( { 'fname' : fname, 'x': x[rng], 'y': y[rng], 'z': z[rng], 'X': X[rng], 'Y': Y[rng], 'Z': Z[rng], # calibrate space (mm) 'speed3D': _speed3D, # calibrate space (mm) 'movingSTD' : _movingSTD, # calibrate space (mm) 'd2inflow': _d2inflow, # calibrate space (mm) 'ringpixels': _ringpixels, 'peaks_within': peaks_within[rng], 'xy_within': xy_within[rng], 'location_one_third' : location_one_third[rng], 'swimdir_within' : swimdir_within[rng], 'dtheta_shape': dtheta_shape[rng], 'dtheta_vel': dtheta_vel[rng], 'turns_shape': turns_shape_array[rng], # already +/- preRange 'turns_vel': turns_vel_array[rng], 'events' : events, 'matchedUSname' : matchedUSname, 'TVroi' : (TVx1,TVy1,TVx2,TVy2), 'SVroi' : (SVx1,SVy1,SVx2,SVy2), } ) if pp: fig.savefig(pp, format='pdf') close('all') # release memory ASAP! if pp: pp.close() def getPDFs(pickle_files, fishnames=None, createPDF=True): # type checking args if type(pickle_files) is str: pickle_files = [pickle_files] # convert to a list or set of fish names if type(fishnames) is str: fishnames = [fishnames] elif not fishnames: fishnames = set() # re-organize trials into a dict "data" data = {} # figure out trial number (sometime many trials in one files) for each fish # go through all pickle_files and use timestamps of file to sort events. timestamps = [] for fp in pickle_files: # collect ctime of pickled files fname = os.path.basename(fp).split('.')[0] + '.avi' timestamps.append( time.strptime(fname, "%b-%d-%Y_%H_%M_%S.avi") ) # look into the pickle and collect fish analyzed params = np.load(fp) # loading pickled file! if type(fishnames) is set: for fish in [fs for fl,fs in params.keys() if fl == fname and fs != 'mog']: fishnames.add(fish) timestamps = sorted(range(len(timestamps)), key=timestamps.__getitem__) # For each fish, go thru all pickled files for fish in fishnames: data[fish] = {} # now go thru the sorted for ind in timestamps: fp = pickle_files[ind] print 'processing #%d\n%s' % (ind, fp) add2DataAndPlot(fp, fish, data, createPDF) return data def plotTrials(data, fish, CSname, key, step, offset=0, pp=None): fig = figure(figsize=(12,8), facecolor='w') ax1 = fig.add_subplot(121) # raw trace ax2 = fig.add_subplot(222) # learning curve ax3 = fig.add_subplot(224) # bar plot preP, postP, postP2 = [], [], [] longestUS = 0 for n, measurement in enumerate(data[fish][CSname]): tr = n+1 CS, USs, preRange = measurement['events'] subplot(ax1) mi = -step*(tr-1) ma = mi + step drawLines(mi, ma, (preRange, [preRange+(USs[0]-CS)], preRange)) longestUS = max([us-CS+preRange*3/2 for us in USs]+[longestUS]) # 'measurement[key]': vector around the CS timing (+/-) preRange. i.e., preRange is the center ax1.plot(measurement[key]-step*(tr-1)+offset) title(CSname+': '+key) # cf. preRange = 3600 frames pre = measurement[key][:preRange].mean()+offset # 2 min window post = measurement[key][preRange:preRange+(USs[0]-CS)].mean()+offset # 23 s window post2 = measurement[key][preRange+(USs[0]-CS):preRange*3/2+(USs[0]-CS)].mean()+offset # 1 min window after US preP.append(pre) postP.append(post) postP2.append(post2) ax3.plot([1, 2, 3], [pre, post, post2],'o-') ax1.set_xlim([0,longestUS]) ax1.axis('off') subplot(ax2) x = range(1, tr+1) y = np.diff((preP,postP), axis=0).ravel() ax2.plot( x, y, 'ko-', linewidth=2 ) ax2.plot( x, np.zeros_like(x), '-.', linewidth=1, color='gray' ) # grid() slope, intercept, rvalue, pval, stderr = stats.stats.linregress(x,y) title('slope = zero? p-value = %f' % pval) ax2.set_xlabel("Trial#") ax2.set_xlim([0.5,tr+0.5]) ax2.set_ylabel('CS - pre') subplot(ax3) ax3.bar([0.6, 1.6, 2.6], [np.nanmean(preP), np.nanmean(postP), np.nanmean(postP2)], facecolor='none') t, pval = stats.ttest_rel(postP, preP) title('paired t p-value = %f' % pval) ax3.set_xticks([1,2,3]) ax3.set_xticklabels(['pre', CSname, measurement['matchedUSname']]) ax3.set_xlim([0.5,3.5]) ax3.set_ylabel('Raw mean values') tight_layout(2, h_pad=1, w_pad=1) if pp: fig.savefig(pp, format='pdf') close('all') return np.vstack((preP, postP, postP2)) def getSummary(data, dirname=None): for fish in data.keys(): for CSname in data[fish].keys(): if dirname: pp = PdfPages(os.path.join(dirname, '%s_for_%s.pdf' % (CSname,fish))) print 'generating %s_for_%s.pdf' % (CSname,fish) book = Workbook() sheet1 = book.add_sheet('speed3D') avgs = plotTrials(data, fish, CSname, 'speed3D', 30, pp=pp) putNp2xls(avgs, sheet1) sheet2 = book.add_sheet('d2inflow') avgs = plotTrials(data, fish, CSname, 'd2inflow', 200, pp=pp) putNp2xls(avgs, sheet2) # sheet3 = book.add_sheet('smoothedz') sheet3 = book.add_sheet('Z') # avgs = plotTrials(data, fish, CSname, 'smoothedz', 100, pp=pp) avgs = plotTrials(data, fish, CSname, 'Z', 30, pp=pp) putNp2xls(avgs, sheet3) sheet4 = book.add_sheet('ringpixels') avgs = plotTrials(data, fish, CSname, 'ringpixels', 1200, pp=pp) putNp2xls(avgs, sheet4) sheet5 = book.add_sheet('peaks_within') avgs = plotTrials(data, fish, CSname, 'peaks_within', 1.5, pp=pp) putNp2xls(avgs, sheet5) sheet6 = book.add_sheet('swimdir_within') avgs = plotTrials(data, fish, CSname, 'swimdir_within', 1.5, pp=pp) putNp2xls(avgs, sheet6) sheet7 = book.add_sheet('xy_within') avgs = plotTrials(data, fish, CSname, 'xy_within', 1.5, pp=pp) putNp2xls(avgs, sheet7) sheet8 = book.add_sheet('turns_shape') avgs = plotTrials(data, fish, CSname, 'turns_shape', 1.5, pp=pp) putNp2xls(avgs, sheet8) sheet9 = book.add_sheet('turns_vel') avgs = plotTrials(data, fish, CSname, 'turns_vel', 1.5, pp=pp) putNp2xls(avgs, sheet9) if dirname: pp.close() book.save(os.path.join(dirname, '%s_for_%s.xls' % (CSname,fish))) close('all') else: show() def add2Pickles(dirname, pickle_files): # dirname : folder to look for pickle files # pickle_files : output, a list to be concatenated. pattern = os.path.join(dirname, '*.pickle') temp = [_ for _ in glob(pattern) if not _.endswith('- Copy.pickle') and not os.path.basename(_).startswith('Summary')] pickle_files += temp if __name__ == '__main__': pickle_files = [] # small test data # add2Pickles('R:/Data/itoiori/behav/adult whitlock/conditioning/NeuroD/Aug4/test', pickle_files) # outputdir = 'R:/Data/itoiori/behav/adult whitlock/conditioning/NeuroD/Aug4/test' # show me what you got for pf in pickle_files: print pf fp = os.path.join(outputdir, 'Summary.pickle') createPDF = True # useful when plotting etc code updated if 1: # refresh analysis data = getPDFs(pickle_files, createPDF=createPDF) import cPickle as pickle with open(os.path.join(outputdir, 'Summary.pickle'), 'wb') as f: pickle.dump(data, f) else: # or reuse previous data = np.load(fp) getSummary(data, outputdir) pickle2mat(fp, data)
bsd-3-clause
francisco-dlp/hyperspy
hyperspy/drawing/utils.py
1
57321
# -*- coding: utf-8 -*- # Copyright 2007-2016 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # HyperSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HyperSpy. If not, see <http://www.gnu.org/licenses/>. import copy import itertools import textwrap from traits import trait_base import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.backend_bases import key_press_handler import warnings import numpy as np from distutils.version import LooseVersion import logging import hyperspy as hs _logger = logging.getLogger(__name__) def contrast_stretching(data, saturated_pixels): """Calculate bounds that leaves out a given percentage of the data. Parameters ---------- data: numpy array saturated_pixels: scalar, None The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range. If None, set the value to 0. Returns ------- vmin, vmax: scalar The low and high bounds Raises ------ ValueError if the value of `saturated_pixels` is out of the valid range. """ # Sanity check if saturated_pixels is None: saturated_pixels = 0 if not 0 <= saturated_pixels <= 100: raise ValueError( "saturated_pixels must be a scalar in the range[0, 100]") vmin = np.nanpercentile(data, saturated_pixels / 2.) vmax = np.nanpercentile(data, 100 - saturated_pixels / 2.) return vmin, vmax MPL_DIVERGING_COLORMAPS = [ "BrBG", "bwr", "coolwarm", "PiYG", "PRGn", "PuOr", "RdBu", "RdGy", "RdYIBu", "RdYIGn", "seismic", "Spectral", ] # Add reversed colormaps MPL_DIVERGING_COLORMAPS += [cmap + "_r" for cmap in MPL_DIVERGING_COLORMAPS] def centre_colormap_values(vmin, vmax): """Calculate vmin and vmax to set the colormap midpoint to zero. Parameters ---------- vmin, vmax : scalar The range of data to display. Returns ------- cvmin, cvmax : scalar The values to obtain a centre colormap. """ absmax = max(abs(vmin), abs(vmax)) return -absmax, absmax def create_figure(window_title=None, _on_figure_window_close=None, disable_xyscale_keys=False, **kwargs): """Create a matplotlib figure. This function adds the possibility to execute another function when the figure is closed and to easily set the window title. Any keyword argument is passed to the plt.figure function Parameters ---------- window_title : string _on_figure_window_close : function disable_xyscale_keys : bool, disable the `k`, `l` and `L` shortcuts which toggle the x or y axis between linear and log scale. Returns ------- fig : plt.figure """ fig = plt.figure(**kwargs) if window_title is not None: # remove non-alphanumeric characters to prevent file saving problems # This is a workaround for: # https://github.com/matplotlib/matplotlib/issues/9056 reserved_characters = r'<>"/\|?*' for c in reserved_characters: window_title = window_title.replace(c, '') window_title = window_title.replace('\n', ' ') window_title = window_title.replace(':', ' -') fig.canvas.set_window_title(window_title) if disable_xyscale_keys and hasattr(fig.canvas, 'toolbar'): # hack the `key_press_handler` to disable the `k`, `l`, `L` shortcuts manager = fig.canvas.manager fig.canvas.mpl_disconnect(manager.key_press_handler_id) manager.key_press_handler_id = manager.canvas.mpl_connect( 'key_press_event', lambda event: key_press_handler_custom(event, manager.canvas)) if _on_figure_window_close is not None: on_figure_window_close(fig, _on_figure_window_close) return fig def key_press_handler_custom(event, canvas): if event.key not in ['k', 'l', 'L']: key_press_handler(event, canvas, canvas.manager.toolbar) def on_figure_window_close(figure, function): """Connects a close figure signal to a given function. Parameters ---------- figure : mpl figure instance function : function """ def function_wrapper(evt): function() figure.canvas.mpl_connect('close_event', function_wrapper) def plot_RGB_map(im_list, normalization='single', dont_plot=False): """Plot 2 or 3 maps in RGB. Parameters ---------- im_list : list of Signal2D instances normalization : {'single', 'global'} dont_plot : bool Returns ------- array: RGB matrix """ # from widgets import cursors height, width = im_list[0].data.shape[:2] rgb = np.zeros((height, width, 3)) rgb[:, :, 0] = im_list[0].data.squeeze() rgb[:, :, 1] = im_list[1].data.squeeze() if len(im_list) == 3: rgb[:, :, 2] = im_list[2].data.squeeze() if normalization == 'single': for i in range(len(im_list)): rgb[:, :, i] /= rgb[:, :, i].max() elif normalization == 'global': rgb /= rgb.max() rgb = rgb.clip(0, rgb.max()) if not dont_plot: figure = plt.figure() ax = figure.add_subplot(111) ax.frameon = False ax.set_axis_off() ax.imshow(rgb, interpolation='nearest') # cursors.set_mpl_ax(ax) figure.canvas.draw_idle() else: return rgb def subplot_parameters(fig): """Returns a list of the subplot parameters of a mpl figure. Parameters ---------- fig : mpl figure Returns ------- tuple : (left, bottom, right, top, wspace, hspace) """ wspace = fig.subplotpars.wspace hspace = fig.subplotpars.hspace left = fig.subplotpars.left right = fig.subplotpars.right top = fig.subplotpars.top bottom = fig.subplotpars.bottom return left, bottom, right, top, wspace, hspace class ColorCycle: _color_cycle = [mpl.colors.colorConverter.to_rgba(color) for color in ('b', 'g', 'r', 'c', 'm', 'y', 'k')] def __init__(self): self.color_cycle = copy.copy(self._color_cycle) def __call__(self): if not self.color_cycle: self.color_cycle = copy.copy(self._color_cycle) return self.color_cycle.pop(0) def plot_signals(signal_list, sync=True, navigator="auto", navigator_list=None, **kwargs): """Plot several signals at the same time. Parameters ---------- signal_list : list of BaseSignal instances If sync is set to True, the signals must have the same navigation shape, but not necessarily the same signal shape. sync : True or False, default "True" If True: the signals will share navigation, all the signals must have the same navigation shape for this to work, but not necessarily the same signal shape. navigator : {"auto", None, "spectrum", "slider", BaseSignal}, default "auto" See signal.plot docstring for full description navigator_list : {List of navigator arguments, None}, default None Set different navigator options for the signals. Must use valid navigator arguments: "auto", None, "spectrum", "slider", or a hyperspy Signal. The list must have the same size as signal_list. If None, the argument specified in navigator will be used. **kwargs Any extra keyword arguments are passed to each signal `plot` method. Example ------- >>> s_cl = hs.load("coreloss.dm3") >>> s_ll = hs.load("lowloss.dm3") >>> hs.plot.plot_signals([s_cl, s_ll]) Specifying the navigator: >>> s_cl = hs.load("coreloss.dm3") >>> s_ll = hs.load("lowloss.dm3") >>> hs.plot.plot_signals([s_cl, s_ll], navigator="slider") Specifying the navigator for each signal: >>> s_cl = hs.load("coreloss.dm3") >>> s_ll = hs.load("lowloss.dm3") >>> s_edx = hs.load("edx.dm3") >>> s_adf = hs.load("adf.dm3") >>> hs.plot.plot_signals( [s_cl, s_ll, s_edx], navigator_list=["slider",None,s_adf]) """ import hyperspy.signal if navigator_list: if not (len(signal_list) == len(navigator_list)): raise ValueError( "signal_list and navigator_list must" " have the same size") if sync: axes_manager_list = [] for signal in signal_list: axes_manager_list.append(signal.axes_manager) if not navigator_list: navigator_list = [] if navigator is None: navigator_list.extend([None] * len(signal_list)) elif isinstance(navigator, hyperspy.signal.BaseSignal): navigator_list.append(navigator) navigator_list.extend([None] * (len(signal_list) - 1)) elif navigator == "slider": navigator_list.append("slider") navigator_list.extend([None] * (len(signal_list) - 1)) elif navigator == "spectrum": navigator_list.extend(["spectrum"] * len(signal_list)) elif navigator == "auto": navigator_list.extend(["auto"] * len(signal_list)) else: raise ValueError( "navigator must be one of \"spectrum\",\"auto\"," " \"slider\", None, a Signal instance") # Check to see if the spectra have the same navigational shapes temp_shape_first = axes_manager_list[0].navigation_shape for i, axes_manager in enumerate(axes_manager_list): temp_shape = axes_manager.navigation_shape if not (temp_shape_first == temp_shape): raise ValueError( "The spectra does not have the same navigation shape") axes_manager_list[i] = axes_manager.deepcopy() if i > 0: for axis0, axisn in zip(axes_manager_list[0].navigation_axes, axes_manager_list[i].navigation_axes): axes_manager_list[i]._axes[axisn.index_in_array] = axis0 del axes_manager for signal, navigator, axes_manager in zip(signal_list, navigator_list, axes_manager_list): signal.plot(axes_manager=axes_manager, navigator=navigator, **kwargs) # If sync is False else: if not navigator_list: navigator_list = [] navigator_list.extend([navigator] * len(signal_list)) for signal, navigator in zip(signal_list, navigator_list): signal.plot(navigator=navigator, **kwargs) def _make_heatmap_subplot(spectra): from hyperspy._signals.signal2d import Signal2D im = Signal2D(spectra.data, axes=spectra.axes_manager._get_axes_dicts()) im.metadata.General.title = spectra.metadata.General.title im.plot() return im._plot.signal_plot.ax def set_xaxis_lims(mpl_ax, hs_axis): """ Set the matplotlib axis limits to match that of a HyperSpy axis Parameters ---------- mpl_ax : :class:`matplotlib.axis.Axis` The ``matplotlib`` axis to change hs_axis : :class:`~hyperspy.axes.DataAxis` The data axis that contains the values that control the scaling """ x_axis_lower_lim = hs_axis.axis[0] x_axis_upper_lim = hs_axis.axis[-1] mpl_ax.set_xlim(x_axis_lower_lim, x_axis_upper_lim) def _make_overlap_plot(spectra, ax, color="blue", line_style='-'): if isinstance(color, str): color = [color] * len(spectra) if isinstance(line_style, str): line_style = [line_style] * len(spectra) for spectrum_index, (spectrum, color, line_style) in enumerate( zip(spectra, color, line_style)): x_axis = spectrum.axes_manager.signal_axes[0] spectrum = _transpose_if_required(spectrum, 1) ax.plot(x_axis.axis, spectrum.data, color=color, ls=line_style) set_xaxis_lims(ax, x_axis) _set_spectrum_xlabel(spectra if isinstance(spectra, hs.signals.BaseSignal) else spectra[-1], ax) ax.set_ylabel('Intensity') ax.autoscale(tight=True) def _make_cascade_subplot( spectra, ax, color="blue", line_style='-', padding=1): max_value = 0 for spectrum in spectra: spectrum_yrange = (np.nanmax(spectrum.data) - np.nanmin(spectrum.data)) if spectrum_yrange > max_value: max_value = spectrum_yrange if isinstance(color, str): color = [color] * len(spectra) if isinstance(line_style, str): line_style = [line_style] * len(spectra) for spectrum_index, (spectrum, color, line_style) in enumerate( zip(spectra, color, line_style)): x_axis = spectrum.axes_manager.signal_axes[0] spectrum = _transpose_if_required(spectrum, 1) data_to_plot = ((spectrum.data - spectrum.data.min()) / float(max_value) + spectrum_index * padding) ax.plot(x_axis.axis, data_to_plot, color=color, ls=line_style) set_xaxis_lims(ax, x_axis) _set_spectrum_xlabel(spectra if isinstance(spectra, hs.signals.BaseSignal) else spectra[-1], ax) ax.set_yticks([]) ax.autoscale(tight=True) def _plot_spectrum(spectrum, ax, color="blue", line_style='-'): x_axis = spectrum.axes_manager.signal_axes[0] ax.plot(x_axis.axis, spectrum.data, color=color, ls=line_style) set_xaxis_lims(ax, x_axis) def _set_spectrum_xlabel(spectrum, ax): x_axis = spectrum.axes_manager.signal_axes[0] ax.set_xlabel("%s (%s)" % (x_axis.name, x_axis.units)) def _transpose_if_required(signal, expected_dimension): # EDS profiles or maps have signal dimension = 0 and navigation dimension # 1 or 2. For convenience transpose the signal if possible if (signal.axes_manager.signal_dimension == 0 and signal.axes_manager.navigation_dimension == expected_dimension): return signal.T else: return signal def plot_images(images, cmap=None, no_nans=False, per_row=3, label='auto', labelwrap=30, suptitle=None, suptitle_fontsize=18, colorbar='multi', centre_colormap="auto", saturated_pixels=0, scalebar=None, scalebar_color='white', axes_decor='all', padding=None, tight_layout=False, aspect='auto', min_asp=0.1, namefrac_thresh=0.4, fig=None, vmin=None, vmax=None, *args, **kwargs): """Plot multiple images as sub-images in one figure. Extra keyword arguments are passed to `matplotlib.figure`. Parameters ---------- images : list of Signal2D or BaseSignal `images` should be a list of Signals to plot. For `BaseSignal` with navigation dimensions 2 and signal dimension 0, the signal will be tranposed to form a `Signal2D`. Multi-dimensional images will have each plane plotted as a separate image. If any signal shape is not suitable, a ValueError will be raised. cmap : matplotlib colormap, list, or ``'mpl_colors'``, *optional* The colormap used for the images, by default read from ``pyplot``. A list of colormaps can also be provided, and the images will cycle through them. Optionally, the value ``'mpl_colors'`` will cause the cmap to loop through the default ``matplotlib`` colors (to match with the default output of the :py:func:`~.drawing.utils.plot_spectra` method. Note: if using more than one colormap, using the ``'single'`` option for ``colorbar`` is disallowed. no_nans : bool, optional If True, set nans to zero for plotting. per_row : int, optional The number of plots in each row label : None, str, or list of str, optional Control the title labeling of the plotted images. If None, no titles will be shown. If 'auto' (default), function will try to determine suitable titles using Signal2D titles, falling back to the 'titles' option if no good short titles are detected. Works best if all images to be plotted have the same beginning to their titles. If 'titles', the title from each image's metadata.General.title will be used. If any other single str, images will be labeled in sequence using that str as a prefix. If a list of str, the list elements will be used to determine the labels (repeated, if necessary). labelwrap : int, optional integer specifying the number of characters that will be used on one line If the function returns an unexpected blank figure, lower this value to reduce overlap of the labels between each figure suptitle : str, optional Title to use at the top of the figure. If called with label='auto', this parameter will override the automatically determined title. suptitle_fontsize : int, optional Font size to use for super title at top of figure colorbar : {'multi', None, 'single'} Controls the type of colorbars that are plotted. If None, no colorbar is plotted. If 'multi' (default), individual colorbars are plotted for each (non-RGB) image If 'single', all (non-RGB) images are plotted on the same scale, and one colorbar is shown for all centre_colormap : {"auto", True, False} If True the centre of the color scheme is set to zero. This is specially useful when using diverging color schemes. If "auto" (default), diverging color schemes are automatically centred. saturated_pixels: None, scalar or list of scalar, optional, default: 0 If list of scalar, the length should match the number of images to show. If provide in the list, set the value to 0. The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range. scalebar : {None, 'all', list of ints}, optional If None (or False), no scalebars will be added to the images. If 'all', scalebars will be added to all images. If list of ints, scalebars will be added to each image specified. scalebar_color : str, optional A valid MPL color string; will be used as the scalebar color axes_decor : {'all', 'ticks', 'off', None}, optional Controls how the axes are displayed on each image; default is 'all' If 'all', both ticks and axis labels will be shown If 'ticks', no axis labels will be shown, but ticks/labels will If 'off', all decorations and frame will be disabled If None, no axis decorations will be shown, but ticks/frame will padding : None or dict, optional This parameter controls the spacing between images. If None, default options will be used Otherwise, supply a dictionary with the spacing options as keywords and desired values as values Values should be supplied as used in pyplot.subplots_adjust(), and can be: 'left', 'bottom', 'right', 'top', 'wspace' (width), and 'hspace' (height) tight_layout : bool, optional If true, hyperspy will attempt to improve image placement in figure using matplotlib's tight_layout If false, repositioning images inside the figure will be left as an exercise for the user. aspect : str or numeric, optional If 'auto', aspect ratio is auto determined, subject to min_asp. If 'square', image will be forced onto square display. If 'equal', aspect ratio of 1 will be enforced. If float (or int/long), given value will be used. min_asp : float, optional Minimum aspect ratio to be used when plotting images namefrac_thresh : float, optional Threshold to use for auto-labeling. This parameter controls how much of the titles must be the same for the auto-shortening of labels to activate. Can vary from 0 to 1. Smaller values encourage shortening of titles by auto-labeling, while larger values will require more overlap in titles before activing the auto-label code. fig : mpl figure, optional If set, the images will be plotted to an existing MPL figure vmin, vmax : scalar or list of scalar, optional, default: None If list of scalar, the length should match the number of images to show. A list of scalar is not compatible with a single colorbar. See vmin, vmax of matplotlib.imshow() for more details. *args, **kwargs, optional Additional arguments passed to matplotlib.imshow() Returns ------- axes_list : list a list of subplot axes that hold the images See Also -------- plot_spectra : Plotting of multiple spectra plot_signals : Plotting of multiple signals plot_histograms : Compare signal histograms Notes ----- `interpolation` is a useful parameter to provide as a keyword argument to control how the space between pixels is interpolated. A value of ``'nearest'`` will cause no interpolation between pixels. `tight_layout` is known to be quite brittle, so an option is provided to disable it. Turn this option off if output is not as expected, or try adjusting `label`, `labelwrap`, or `per_row` """ def __check_single_colorbar(cbar): if cbar == 'single': raise ValueError('Cannot use a single colorbar with multiple ' 'colormaps. Please check for compatible ' 'arguments.') from hyperspy.drawing.widgets import ScaleBar from hyperspy.misc import rgb_tools from hyperspy.signal import BaseSignal # Check that we have a hyperspy signal im = [images] if not isinstance(images, (list, tuple)) else images for image in im: if not isinstance(image, BaseSignal): raise ValueError("`images` must be a list of image signals or a " "multi-dimensional signal." " " + repr(type(images)) + " was given.") # For list of EDS maps, transpose the BaseSignal if isinstance(images, (list, tuple)): images = [_transpose_if_required(image, 2) for image in images] # If input is >= 1D signal (e.g. for multi-dimensional plotting), # copy it and put it in a list so labeling works out as (x,y) when plotting if isinstance(images, BaseSignal) and images.axes_manager.navigation_dimension > 0: images = [images._deepcopy_with_new_data(images.data)] n = 0 for i, sig in enumerate(images): if sig.axes_manager.signal_dimension != 2: raise ValueError("This method only plots signals that are images. " "The signal dimension must be equal to 2. " "The signal at position " + repr(i) + " was " + repr(sig) + ".") # increment n by the navigation size, or by 1 if the navigation size is # <= 0 n += (sig.axes_manager.navigation_size if sig.axes_manager.navigation_size > 0 else 1) # If no cmap given, get default colormap from pyplot: if cmap is None: cmap = [plt.get_cmap().name] elif cmap == 'mpl_colors': for n_color, c in enumerate(mpl.rcParams['axes.prop_cycle']): make_cmap(colors=['#000000', c['color']], name='mpl{}'.format(n_color)) cmap = ['mpl{}'.format(i) for i in range(len(mpl.rcParams['axes.prop_cycle']))] __check_single_colorbar(colorbar) # cmap is list, tuple, or something else iterable (but not string): elif hasattr(cmap, '__iter__') and not isinstance(cmap, str): try: cmap = [c.name for c in cmap] # convert colormap to string except AttributeError: cmap = [c for c in cmap] # c should be string if not colormap __check_single_colorbar(colorbar) elif isinstance(cmap, mpl.colors.Colormap): cmap = [cmap.name] # convert single colormap to list with string elif isinstance(cmap, str): cmap = [cmap] # cmap is single string, so make it a list else: # Didn't understand cmap input, so raise error raise ValueError('The provided cmap value was not understood. Please ' 'check input values.') # If any of the cmaps given are diverging, and auto-centering, set the # appropriate flag: if centre_colormap == "auto": centre_colormaps = [] for c in cmap: if c in MPL_DIVERGING_COLORMAPS: centre_colormaps.append(True) else: centre_colormaps.append(False) # if it was True, just convert to list elif centre_colormap: centre_colormaps = [True] # likewise for false elif not centre_colormap: centre_colormaps = [False] # finally, convert lists to cycle generators for adaptive length: centre_colormaps = itertools.cycle(centre_colormaps) cmap = itertools.cycle(cmap) def _check_arg(arg, default_value, arg_name): if isinstance(arg, list): if len(arg) != n: _logger.warning('The provided {} values are ignored because the ' 'length of the list does not match the number of ' 'images'.format(arg_name)) arg = [default_value] * n else: arg = [arg] * n return arg vmin = _check_arg(vmin, None, 'vmin') vmax = _check_arg(vmax, None, 'vmax') saturated_pixels = _check_arg(saturated_pixels, 0, 'saturated_pixels') # Sort out the labeling: div_num = 0 all_match = False shared_titles = False user_labels = False if label is None: pass elif label == 'auto': # Use some heuristics to try to get base string of similar titles label_list = [x.metadata.General.title for x in images] # Find the shortest common string between the image titles # and pull that out as the base title for the sequence of images # array in which to store arrays res = np.zeros((len(label_list), len(label_list[0]) + 1)) res[:, 0] = 1 # j iterates the strings for j in range(len(label_list)): # i iterates length of substring test for i in range(1, len(label_list[0]) + 1): # stores whether or not characters in title match res[j, i] = label_list[0][:i] in label_list[j] # sum up the results (1 is True, 0 is False) and create # a substring based on the minimum value (this will be # the "smallest common string" between all the titles if res.all(): basename = label_list[0] div_num = len(label_list[0]) all_match = True else: div_num = int(min(np.sum(res, 1))) basename = label_list[0][:div_num - 1] all_match = False # trim off any '(' or ' ' characters at end of basename if div_num > 1: while True: if basename[len(basename) - 1] == '(': basename = basename[:-1] elif basename[len(basename) - 1] == ' ': basename = basename[:-1] else: break # namefrac is ratio of length of basename to the image name # if it is high (e.g. over 0.5), we can assume that all images # share the same base if len(label_list[0]) > 0: namefrac = float(len(basename)) / len(label_list[0]) else: # If label_list[0] is empty, it means there was probably no # title set originally, so nothing to share namefrac = 0 if namefrac > namefrac_thresh: # there was a significant overlap of label beginnings shared_titles = True # only use new suptitle if one isn't specified already if suptitle is None: suptitle = basename else: # there was not much overlap, so default back to 'titles' mode shared_titles = False label = 'titles' div_num = 0 elif label == 'titles': # Set label_list to each image's pre-defined title label_list = [x.metadata.General.title for x in images] elif isinstance(label, str): # Set label_list to an indexed list, based off of label label_list = [label + " " + repr(num) for num in range(n)] elif isinstance(label, list) and all( isinstance(x, str) for x in label): label_list = label user_labels = True # If list of labels is longer than the number of images, just use the # first n elements if len(label_list) > n: del label_list[n:] if len(label_list) < n: label_list *= (n // len(label_list)) + 1 del label_list[n:] else: raise ValueError("Did not understand input of labels.") # Determine appropriate number of images per row rows = int(np.ceil(n / float(per_row))) if n < per_row: per_row = n # Set overall figure size and define figure (if not pre-existing) if fig is None: k = max(plt.rcParams['figure.figsize']) / max(per_row, rows) f = plt.figure(figsize=(tuple(k * i for i in (per_row, rows)))) else: f = fig # Initialize list to hold subplot axes axes_list = [] # Initialize list of rgb tags isrgb = [False] * len(images) # Check to see if there are any rgb images in list # and tag them using the isrgb list for i, img in enumerate(images): if rgb_tools.is_rgbx(img.data): isrgb[i] = True # Determine how many non-rgb Images there are non_rgb = list(itertools.compress(images, [not j for j in isrgb])) if len(non_rgb) == 0 and colorbar is not None: colorbar = None warnings.warn("Sorry, colorbar is not implemented for RGB images.") # Find global min and max values of all the non-rgb images for use with # 'single' scalebar if colorbar == 'single': # get a g_saturated_pixels from saturated_pixels if isinstance(saturated_pixels, list): g_saturated_pixels = min(np.array([v for v in saturated_pixels])) else: g_saturated_pixels = saturated_pixels # estimate a g_vmin and g_max from saturated_pixels g_vmin, g_vmax = contrast_stretching(np.concatenate( [i.data.flatten() for i in non_rgb]), g_saturated_pixels) # if vmin and vmax are provided, override g_min and g_max if isinstance(vmin, list): _logger.warning('vmin have to be a scalar to be compatible with a ' 'single colorbar') else: g_vmin = vmin if vmin is not None else g_vmin if isinstance(vmax, list): _logger.warning('vmax have to be a scalar to be compatible with a ' 'single colorbar') else: g_vmax = vmax if vmax is not None else g_vmax if next(centre_colormaps): g_vmin, g_vmax = centre_colormap_values(g_vmin, g_vmax) # Check if we need to add a scalebar for some of the images if isinstance(scalebar, list) and all(isinstance(x, int) for x in scalebar): scalelist = True else: scalelist = False idx = 0 ax_im_list = [0] * len(isrgb) # Replot: create a list to store references to the images replot_ims = [] # Loop through each image, adding subplot for each one for i, ims in enumerate(images): # Get handles for the signal axes and axes_manager axes_manager = ims.axes_manager if axes_manager.navigation_dimension > 0: ims = ims._deepcopy_with_new_data(ims.data) for j, im in enumerate(ims): ax = f.add_subplot(rows, per_row, idx + 1) axes_list.append(ax) data = im.data centre = next(centre_colormaps) # get next value for centreing # Enable RGB plotting if rgb_tools.is_rgbx(data): data = rgb_tools.rgbx2regular_array(data, plot_friendly=True) l_vmin, l_vmax = None, None else: data = im.data # Find min and max for contrast l_vmin, l_vmax = contrast_stretching( data, saturated_pixels[idx]) l_vmin = vmin[idx] if vmin[idx] is not None else l_vmin l_vmax = vmax[idx] if vmax[idx] is not None else l_vmax if centre: l_vmin, l_vmax = centre_colormap_values(l_vmin, l_vmax) # Remove NaNs (if requested) if no_nans: data = np.nan_to_num(data) # Get handles for the signal axes and axes_manager axes_manager = im.axes_manager axes = axes_manager.signal_axes # Set dimensions of images xaxis = axes[0] yaxis = axes[1] extent = ( xaxis.low_value, xaxis.high_value, yaxis.high_value, yaxis.low_value, ) if not isinstance(aspect, (int, float)) and aspect not in [ 'auto', 'square', 'equal']: _logger.warning("Did not understand aspect ratio input. " "Using 'auto' as default.") aspect = 'auto' if aspect == 'auto': if float(yaxis.size) / xaxis.size < min_asp: factor = min_asp * float(xaxis.size) / yaxis.size elif float(yaxis.size) / xaxis.size > min_asp ** -1: factor = min_asp ** -1 * float(xaxis.size) / yaxis.size else: factor = 1 asp = np.abs(factor * float(xaxis.scale) / yaxis.scale) elif aspect == 'square': asp = abs(extent[1] - extent[0]) / abs(extent[3] - extent[2]) elif aspect == 'equal': asp = 1 elif isinstance(aspect, (int, float)): asp = aspect if 'interpolation' not in kwargs.keys(): kwargs['interpolation'] = 'nearest' # Get colormap for this image: cm = next(cmap) # Plot image data, using vmin and vmax to set bounds, # or allowing them to be set automatically if using individual # colorbars if colorbar == 'single' and not isrgb[i]: axes_im = ax.imshow(data, cmap=cm, extent=extent, vmin=g_vmin, vmax=g_vmax, aspect=asp, *args, **kwargs) ax_im_list[i] = axes_im else: axes_im = ax.imshow(data, cmap=cm, extent=extent, vmin=l_vmin, vmax=l_vmax, aspect=asp, *args, **kwargs) ax_im_list[i] = axes_im # If an axis trait is undefined, shut off : if isinstance(xaxis.units, trait_base._Undefined) or \ isinstance(yaxis.units, trait_base._Undefined) or \ isinstance(xaxis.name, trait_base._Undefined) or \ isinstance(yaxis.name, trait_base._Undefined): if axes_decor == 'all': _logger.warning( 'Axes labels were requested, but one ' 'or both of the ' 'axes units and/or name are undefined. ' 'Axes decorations have been set to ' '\'ticks\' instead.') axes_decor = 'ticks' # If all traits are defined, set labels as appropriate: else: ax.set_xlabel(axes[0].name + " axis (" + axes[0].units + ")") ax.set_ylabel(axes[1].name + " axis (" + axes[1].units + ")") if label: if all_match: title = '' elif shared_titles: title = label_list[i][div_num - 1:] else: if len(ims) == n: # This is true if we are plotting just 1 # multi-dimensional Signal2D title = label_list[idx] elif user_labels: title = label_list[idx] else: title = label_list[i] if ims.axes_manager.navigation_size > 1 and not user_labels: title += " %s" % str(ims.axes_manager.indices) ax.set_title(textwrap.fill(title, labelwrap)) # Set axes decorations based on user input set_axes_decor(ax, axes_decor) # If using independent colorbars, add them if colorbar == 'multi' and not isrgb[i]: div = make_axes_locatable(ax) cax = div.append_axes("right", size="5%", pad=0.05) plt.colorbar(axes_im, cax=cax) # Add scalebars as necessary if (scalelist and idx in scalebar) or scalebar == 'all': ax.scalebar = ScaleBar( ax=ax, units=axes[0].units, color=scalebar_color, ) # Replot: store references to the images replot_ims.append(im) idx += 1 # If using a single colorbar, add it, and do tight_layout, ensuring that # a colorbar is only added based off of non-rgb Images: if colorbar == 'single': foundim = None for i in range(len(isrgb)): if (not isrgb[i]) and foundim is None: foundim = i if foundim is not None: f.subplots_adjust(right=0.8) cbar_ax = f.add_axes([0.9, 0.1, 0.03, 0.8]) f.colorbar(ax_im_list[foundim], cax=cbar_ax) if tight_layout: # tight_layout, leaving room for the colorbar plt.tight_layout(rect=[0, 0, 0.9, 1]) elif tight_layout: plt.tight_layout() elif tight_layout: plt.tight_layout() # Set top bounds for shared titles and add suptitle if suptitle: f.subplots_adjust(top=0.85) f.suptitle(suptitle, fontsize=suptitle_fontsize) # If we want to plot scalebars, loop through the list of axes and add them if scalebar is None or scalebar is False: # Do nothing if no scalebars are called for pass elif scalebar == 'all': # scalebars were taken care of in the plotting loop pass elif scalelist: # scalebars were taken care of in the plotting loop pass else: raise ValueError("Did not understand scalebar input. Must be None, " "\'all\', or list of ints.") # Adjust subplot spacing according to user's specification if padding is not None: plt.subplots_adjust(**padding) # Replot: connect function def on_dblclick(event): # On the event of a double click, replot the selected subplot if not event.inaxes: return if not event.dblclick: return subplots = [axi for axi in f.axes if isinstance(axi, mpl.axes.Subplot)] inx = list(subplots).index(event.inaxes) im = replot_ims[inx] # Use some of the info in the subplot cm = subplots[inx].images[0].get_cmap() clim = subplots[inx].images[0].get_clim() sbar = False if (scalelist and inx in scalebar) or scalebar == 'all': sbar = True im.plot(colorbar=bool(colorbar), vmin=clim[0], vmax=clim[1], no_nans=no_nans, aspect=asp, scalebar=sbar, scalebar_color=scalebar_color, cmap=cm) f.canvas.mpl_connect('button_press_event', on_dblclick) return axes_list def set_axes_decor(ax, axes_decor): if axes_decor == 'off': ax.axis('off') elif axes_decor == 'ticks': ax.set_xlabel('') ax.set_ylabel('') elif axes_decor == 'all': pass elif axes_decor is None: ax.set_xlabel('') ax.set_ylabel('') ax.set_xticklabels([]) ax.set_yticklabels([]) def make_cmap(colors, name='my_colormap', position=None, bit=False, register=True): """ Create a matplotlib colormap with customized colors, optionally registering it with matplotlib for simplified use. Adapted from Chris Slocum's code at: https://github.com/CSlocumWX/custom_colormap/blob/master/custom_colormaps.py and used under the terms of that code's BSD-3 license Parameters ---------- colors : iterable list of either tuples containing rgb values, or html strings Colors should be arranged so that the first color is the lowest value for the colorbar and the last is the highest. name : str name of colormap to use when registering with matplotlib position : None or iterable list containing the values (from [0,1]) that dictate the position of each color within the colormap. If None (default), the colors will be equally-spaced within the colorbar. bit : boolean True if RGB colors are given in 8-bit [0 to 255] or False if given in arithmetic basis [0 to 1] (default) register : boolean switch to control whether or not to register the custom colormap with matplotlib in order to enable use by just the name string """ def _html_color_to_rgb(color_string): """ convert #RRGGBB to an (R, G, B) tuple """ color_string = color_string.strip() if color_string[0] == '#': color_string = color_string[1:] if len(color_string) != 6: raise ValueError( "input #{} is not in #RRGGBB format".format(color_string)) r, g, b = color_string[:2], color_string[2:4], color_string[4:] r, g, b = [int(n, 16) / 255 for n in (r, g, b)] return r, g, b bit_rgb = np.linspace(0, 1, 256) if position is None: position = np.linspace(0, 1, len(colors)) else: if len(position) != len(colors): raise ValueError("position length must be the same as colors") elif position[0] != 0 or position[-1] != 1: raise ValueError("position must start with 0 and end with 1") cdict = {'red': [], 'green': [], 'blue': []} for pos, color in zip(position, colors): if isinstance(color, str): color = _html_color_to_rgb(color) elif bit: color = (bit_rgb[color[0]], bit_rgb[color[1]], bit_rgb[color[2]]) cdict['red'].append((pos, color[0], color[0])) cdict['green'].append((pos, color[1], color[1])) cdict['blue'].append((pos, color[2], color[2])) cmap = mpl.colors.LinearSegmentedColormap(name, cdict, 256) if register: mpl.cm.register_cmap(name, cmap) return cmap def plot_spectra( spectra, style='overlap', color=None, line_style=None, padding=1., legend=None, legend_picking=True, legend_loc='upper right', fig=None, ax=None, **kwargs): """Plot several spectra in the same figure. Extra keyword arguments are passed to `matplotlib.figure`. Parameters ---------- spectra : list of Signal1D or BaseSignal Ordered spectra list of signal to plot. If `style` is "cascade" or "mosaic" the spectra can have different size and axes. For `BaseSignal` with navigation dimensions 1 and signal dimension 0, the signal will be tranposed to form a `Signal1D`. style : {'overlap', 'cascade', 'mosaic', 'heatmap'} The style of the plot. color : matplotlib color or a list of them or `None` Sets the color of the lines of the plots (no action on 'heatmap'). If a list, if its length is less than the number of spectra to plot, the colors will be cycled. If `None`, use default matplotlib color cycle. line_style: matplotlib line style or a list of them or `None` Sets the line style of the plots (no action on 'heatmap'). The main line style are '-','--','steps','-.',':'. If a list, if its length is less than the number of spectra to plot, line_style will be cycled. If If `None`, use continuous lines, eg: ('-','--','steps','-.',':') padding : float, optional, default 0.1 Option for "cascade". 1 guarantees that there is not overlapping. However, in many cases a value between 0 and 1 can produce a tighter plot without overlapping. Negative values have the same effect but reverse the order of the spectra without reversing the order of the colors. legend: None or list of str or 'auto' If list of string, legend for "cascade" or title for "mosaic" is displayed. If 'auto', the title of each spectra (metadata.General.title) is used. legend_picking: bool If true, a spectrum can be toggle on and off by clicking on the legended line. legend_loc : str or int This parameter controls where the legend is placed on the figure; see the pyplot.legend docstring for valid values fig : matplotlib figure or None If None, a default figure will be created. Specifying fig will not work for the 'heatmap' style. ax : matplotlib ax (subplot) or None If None, a default ax will be created. Will not work for 'mosaic' or 'heatmap' style. **kwargs remaining keyword arguments are passed to matplotlib.figure() or matplotlib.subplots(). Has no effect on 'heatmap' style. Example ------- >>> s = hs.load("some_spectra") >>> hs.plot.plot_spectra(s, style='cascade', color='red', padding=0.5) To save the plot as a png-file >>> hs.plot.plot_spectra(s).figure.savefig("test.png") Returns ------- ax: matplotlib axes or list of matplotlib axes An array is returned when `style` is "mosaic". """ import hyperspy.signal def _reverse_legend(ax_, legend_loc_): """ Reverse the ordering of a matplotlib legend (to be more consistent with the default ordering of plots in the 'cascade' and 'overlap' styles Parameters ---------- ax_: matplotlib axes legend_loc_: str or int This parameter controls where the legend is placed on the figure; see the pyplot.legend docstring for valid values """ l = ax_.get_legend() labels = [lb.get_text() for lb in list(l.get_texts())] handles = l.legendHandles ax_.legend(handles[::-1], labels[::-1], loc=legend_loc_) # Before v1.3 default would read the value from prefereces. if style == "default": style = "overlap" if color is not None: if isinstance(color, str): color = itertools.cycle([color]) elif hasattr(color, "__iter__"): color = itertools.cycle(color) else: raise ValueError("Color must be None, a valid matplotlib color " "string or a list of valid matplotlib colors.") else: if LooseVersion(mpl.__version__) >= "1.5.3": color = itertools.cycle( plt.rcParams['axes.prop_cycle'].by_key()["color"]) else: color = itertools.cycle(plt.rcParams['axes.color_cycle']) if line_style is not None: if isinstance(line_style, str): line_style = itertools.cycle([line_style]) elif hasattr(line_style, "__iter__"): line_style = itertools.cycle(line_style) else: raise ValueError("line_style must be None, a valid matplotlib" " line_style string or a list of valid matplotlib" " line_style.") else: line_style = ['-'] * len(spectra) if legend is not None: if isinstance(legend, str): if legend == 'auto': legend = [spec.metadata.General.title for spec in spectra] else: raise ValueError("legend must be None, 'auto' or a list of" " string") elif hasattr(legend, "__iter__"): legend = itertools.cycle(legend) if style == 'overlap': if fig is None: fig = plt.figure(**kwargs) if ax is None: ax = fig.add_subplot(111) _make_overlap_plot(spectra, ax, color=color, line_style=line_style,) if legend is not None: ax.legend(legend, loc=legend_loc) _reverse_legend(ax, legend_loc) if legend_picking is True: animate_legend(fig=fig, ax=ax) elif style == 'cascade': if fig is None: fig = plt.figure(**kwargs) if ax is None: ax = fig.add_subplot(111) _make_cascade_subplot(spectra, ax, color=color, line_style=line_style, padding=padding) if legend is not None: plt.legend(legend, loc=legend_loc) _reverse_legend(ax, legend_loc) elif style == 'mosaic': default_fsize = plt.rcParams["figure.figsize"] figsize = (default_fsize[0], default_fsize[1] * len(spectra)) fig, subplots = plt.subplots( len(spectra), 1, figsize=figsize, **kwargs) if legend is None: legend = [legend] * len(spectra) for spectrum, ax, color, line_style, legend in zip( spectra, subplots, color, line_style, legend): spectrum = _transpose_if_required(spectrum, 1) _plot_spectrum(spectrum, ax, color=color, line_style=line_style) ax.set_ylabel('Intensity') if legend is not None: ax.set_title(legend) if not isinstance(spectra, hyperspy.signal.BaseSignal): _set_spectrum_xlabel(spectrum, ax) if isinstance(spectra, hyperspy.signal.BaseSignal): _set_spectrum_xlabel(spectrum, ax) fig.tight_layout() elif style == 'heatmap': if not isinstance(spectra, hyperspy.signal.BaseSignal): import hyperspy.utils spectra = [_transpose_if_required(spectrum, 1) for spectrum in spectra] spectra = hyperspy.utils.stack(spectra) with spectra.unfolded(): ax = _make_heatmap_subplot(spectra) ax.set_ylabel('Spectra') ax = ax if style != "mosaic" else subplots return ax def animate_legend(fig=None, ax=None): """Animate the legend of a figure. A spectrum can be toggle on and off by clicking on the legended line. Parameters ---------- fig: None | matplotlib.figure If None pick the current figure using "plt.gcf" ax: None | matplotlib.axes If None pick the current axes using "plt.gca". Note ---- Code inspired from legend_picking.py in the matplotlib gallery """ if fig is None: fig = plt.gcf() if ax is None: ax = plt.gca() lines = ax.lines[::-1] lined = dict() leg = ax.get_legend() for legline, origline in zip(leg.get_lines(), lines): legline.set_picker(5) # 5 pts tolerance lined[legline] = origline def onpick(event): # on the pick event, find the orig line corresponding to the # legend proxy line, and toggle the visibility legline = event.artist if legline.axes == ax: origline = lined[legline] vis = not origline.get_visible() origline.set_visible(vis) # Change the alpha on the line in the legend so we can see what lines # have been toggled if vis: legline.set_alpha(1.0) else: legline.set_alpha(0.2) fig.canvas.draw_idle() fig.canvas.mpl_connect('pick_event', onpick) def plot_histograms(signal_list, bins='freedman', range_bins=None, color=None, line_style=None, legend='auto', fig=None, **kwargs): """Plot the histogram of every signal in the list in the same figure. This function creates a histogram for each signal and plot the list with the `utils.plot.plot_spectra` function. Parameters ---------- signal_list : iterable Ordered spectra list to plot. If `style` is "cascade" or "mosaic" the spectra can have different size and axes. bins : int or list or str, optional If bins is a string, then it must be one of: 'knuth' : use Knuth's rule to determine bins 'scotts' : use Scott's rule to determine bins 'freedman' : use the Freedman-diaconis rule to determine bins 'blocks' : use bayesian blocks for dynamic bin widths range_bins : tuple or None, optional. the minimum and maximum range for the histogram. If not specified, it will be (x.min(), x.max()) color : valid matplotlib color or a list of them or `None`, optional. Sets the color of the lines of the plots. If a list, if its length is less than the number of spectra to plot, the colors will be cycled. If If `None`, use default matplotlib color cycle. line_style: valid matplotlib line style or a list of them or `None`, optional. The main line style are '-','--','steps','-.',':'. If a list, if its length is less than the number of spectra to plot, line_style will be cycled. If If `None`, use continuous lines, eg: ('-','--','steps','-.',':') legend: None or list of str or 'auto', optional. Display a legend. If 'auto', the title of each spectra (metadata.General.title) is used. legend_picking: bool, optional. If true, a spectrum can be toggle on and off by clicking on the legended line. fig : matplotlib figure or None, optional. If None, a default figure will be created. **kwargs other keyword arguments (weight and density) are described in np.histogram(). Example ------- Histograms of two random chi-square distributions >>> img = hs.signals.Signal2D(np.random.chisquare(1,[10,10,100])) >>> img2 = hs.signals.Signal2D(np.random.chisquare(2,[10,10,100])) >>> hs.plot.plot_histograms([img,img2],legend=['hist1','hist2']) Returns ------- ax: matplotlib axes or list of matplotlib axes An array is returned when `style` is "mosaic". """ hists = [] for obj in signal_list: hists.append(obj.get_histogram(bins=bins, range_bins=range_bins, **kwargs)) if line_style is None: line_style = 'steps' return plot_spectra(hists, style='overlap', color=color, line_style=line_style, legend=legend, fig=fig)
gpl-3.0
linegpe/FYS3150
Project4/expect_random_T1.py
1
3161
import numpy as np import matplotlib.pyplot as plt data1 = np.loadtxt("expect_random_T1.00.dat") data2 = np.loadtxt("expect_ordered_T1.00.dat") data3 = np.loadtxt("expect_random2_T2.40.dat") data4 = np.loadtxt("expect_ordered2_T2.40.dat") values1 = data1[0::1] values2 = data2[0::1] values3 = data3[0::1] values4 = data4[0::1] N1 = len(values1) x1 = np.linspace(0,N1,N1) N2 = len(values3) x2 = np.linspace(0,N2,N2) figure1 = plt.figure() labels = figure1.add_subplot(111) # Turn off axis lines and ticks of the big subplot labels.spines['top'].set_color('none') labels.spines['bottom'].set_color('none') labels.spines['left'].set_color('none') labels.spines['right'].set_color('none') labels.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off') plt.xlabel("Number of Monte Carlo cycles",fontsize=15) plt.ylabel("Mean energy per spin",fontsize=15) #figure1.yaxis.set_ticks_position(right) #figure1.ylabel.set_ticks_position('left') #figure1.yaxis.tick_right() fig1 = figure1.add_subplot(211) fig1.plot(x1,values1[:,0],label="Random initial spins, T=1") fig1.plot(x1,values2[:,0],label="Ordered initial spins, T=1") fig1.tick_params(axis='x', labelsize=15) #HOW TO PUT THIS ON THE RIGHT SIDE? fig1.tick_params(axis='y', labelsize=15) fig1.yaxis.tick_right() #plt.ylabel(r"$\langle E\rangle /L^2$",fontsize=17) #plt.xlabel("Number of Monte Carlo cycles",fontsize=15) plt.legend() plt.axis([0,N1,-3,0]) #plt.show() fig2 = figure1.add_subplot(212) fig2.plot(x2,values3[:,0],label="Random initial spins, T=2.4") fig2.plot(x2,values4[:,0],label="Ordered initial spins, T=2.4") fig2.tick_params(axis='x', labelsize=15) fig2.tick_params(axis='y', labelsize=15) fig2.yaxis.tick_right() #plt.ylabel(r"$\langle E\rangle /L^2$",fontsize=15) #plt.xlabel("Number of Monte Carlo cycles",fontsize=15) plt.legend() plt.axis([0,50000,-2,-0.4]) plt.show() figure2 = plt.figure() labels = figure2.add_subplot(111) labels.spines['top'].set_color('none') labels.spines['bottom'].set_color('none') labels.spines['left'].set_color('none') labels.spines['right'].set_color('none') labels.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off') plt.xlabel("Number of Monte Carlo cycles",fontsize=15) plt.ylabel("Absolute magnetization per spin",fontsize=15) fig1 = figure2.add_subplot(211) fig1.plot(x1,values1[:,1],label="Random initial spins, T=1") fig1.plot(x1,values2[:,1],label="Ordered initial spins, T=1") fig1.tick_params(axis='x', labelsize=15) fig1.tick_params(axis='y', labelsize=15) fig1.yaxis.tick_right() #fig2.ylabel(r"$abs(\langle M \rangle /L^2)$",fontsize=15) #fig2.xlabel("Number of Monte Carlo cycles",fontsize=15) plt.legend() plt.axis([0,N1,0.2,1.6]) #plt.show() fig2 = figure2.add_subplot(212) fig2.plot(x2,values3[:,1],label="Random initial spins, T=2.4") fig2.plot(x2,values4[:,1],label="Ordered initial spins, T=2.4") fig2.tick_params(axis='x', labelsize=15) fig2.tick_params(axis='y', labelsize=15) fig2.yaxis.tick_right() #plt.ylabel(r"$abs(\langle M\rangle / L^2)$",fontsize=15) #plt.xlabel("Number of Monte Carlo cycles",fontsize=15) plt.legend() #plt.axis([0,8e6,-0.1,1.4]) plt.show()
gpl-3.0
abimannans/scikit-learn
examples/tree/plot_tree_regression_multioutput.py
206
1800
""" =================================================================== Multi-output Decision Tree Regression =================================================================== An example to illustrate multi-output regression with decision tree. The :ref:`decision trees <tree>` is used to predict simultaneously the noisy x and y observations of a circle given a single underlying feature. As a result, it learns local linear regressions approximating the circle. We can see that if the maximum depth of the tree (controlled by the `max_depth` parameter) is set too high, the decision trees learn too fine details of the training data and learn from the noise, i.e. they overfit. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeRegressor # Create a random dataset rng = np.random.RandomState(1) X = np.sort(200 * rng.rand(100, 1) - 100, axis=0) y = np.array([np.pi * np.sin(X).ravel(), np.pi * np.cos(X).ravel()]).T y[::5, :] += (0.5 - rng.rand(20, 2)) # Fit regression model regr_1 = DecisionTreeRegressor(max_depth=2) regr_2 = DecisionTreeRegressor(max_depth=5) regr_3 = DecisionTreeRegressor(max_depth=8) regr_1.fit(X, y) regr_2.fit(X, y) regr_3.fit(X, y) # Predict X_test = np.arange(-100.0, 100.0, 0.01)[:, np.newaxis] y_1 = regr_1.predict(X_test) y_2 = regr_2.predict(X_test) y_3 = regr_3.predict(X_test) # Plot the results plt.figure() plt.scatter(y[:, 0], y[:, 1], c="k", label="data") plt.scatter(y_1[:, 0], y_1[:, 1], c="g", label="max_depth=2") plt.scatter(y_2[:, 0], y_2[:, 1], c="r", label="max_depth=5") plt.scatter(y_3[:, 0], y_3[:, 1], c="b", label="max_depth=8") plt.xlim([-6, 6]) plt.ylim([-6, 6]) plt.xlabel("data") plt.ylabel("target") plt.title("Multi-output Decision Tree Regression") plt.legend() plt.show()
bsd-3-clause
darshanthaker/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
kpespinosa/BuildingMachineLearningSystemsWithPython
ch04/blei_lda.py
21
2601
# This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License from __future__ import print_function from wordcloud import create_cloud try: from gensim import corpora, models, matutils except: print("import gensim failed.") print() print("Please install it") raise import matplotlib.pyplot as plt import numpy as np from os import path NUM_TOPICS = 100 # Check that data exists if not path.exists('./data/ap/ap.dat'): print('Error: Expected data to be present at data/ap/') print('Please cd into ./data & run ./download_ap.sh') # Load the data corpus = corpora.BleiCorpus('./data/ap/ap.dat', './data/ap/vocab.txt') # Build the topic model model = models.ldamodel.LdaModel( corpus, num_topics=NUM_TOPICS, id2word=corpus.id2word, alpha=None) # Iterate over all the topics in the model for ti in range(model.num_topics): words = model.show_topic(ti, 64) tf = sum(f for f, w in words) with open('topics.txt', 'w') as output: output.write('\n'.join('{}:{}'.format(w, int(1000. * f / tf)) for f, w in words)) output.write("\n\n\n") # We first identify the most discussed topic, i.e., the one with the # highest total weight topics = matutils.corpus2dense(model[corpus], num_terms=model.num_topics) weight = topics.sum(1) max_topic = weight.argmax() # Get the top 64 words for this topic # Without the argument, show_topic would return only 10 words words = model.show_topic(max_topic, 64) # This function will actually check for the presence of pytagcloud and is otherwise a no-op create_cloud('cloud_blei_lda.png', words) num_topics_used = [len(model[doc]) for doc in corpus] fig,ax = plt.subplots() ax.hist(num_topics_used, np.arange(42)) ax.set_ylabel('Nr of documents') ax.set_xlabel('Nr of topics') fig.tight_layout() fig.savefig('Figure_04_01.png') # Now, repeat the same exercise using alpha=1.0 # You can edit the constant below to play around with this parameter ALPHA = 1.0 model1 = models.ldamodel.LdaModel( corpus, num_topics=NUM_TOPICS, id2word=corpus.id2word, alpha=ALPHA) num_topics_used1 = [len(model1[doc]) for doc in corpus] fig,ax = plt.subplots() ax.hist([num_topics_used, num_topics_used1], np.arange(42)) ax.set_ylabel('Nr of documents') ax.set_xlabel('Nr of topics') # The coordinates below were fit by trial and error to look good ax.text(9, 223, r'default alpha') ax.text(26, 156, 'alpha=1.0') fig.tight_layout() fig.savefig('Figure_04_02.png')
mit
samchrisinger/osf.io
scripts/analytics/tasks.py
14
1913
import os import matplotlib from framework.celery_tasks import app as celery_app from scripts import utils as script_utils from scripts.analytics import settings from scripts.analytics import utils from website import models from website import settings as website_settings from website.app import init_app from .logger import logger @celery_app.task(name='scripts.analytics.tasks') def analytics(): matplotlib.use('Agg') init_app(routes=False) script_utils.add_file_logger(logger, __file__) from scripts.analytics import ( logs, addons, comments, folders, links, watch, email_invites, permissions, profile, benchmarks ) modules = ( logs, addons, comments, folders, links, watch, email_invites, permissions, profile, benchmarks ) for module in modules: logger.info('Starting: {}'.format(module.__name__)) module.main() logger.info('Finished: {}'.format(module.__name__)) upload_analytics() def upload_analytics(local_path=None, remote_path='/'): node = models.Node.load(settings.TABULATE_LOGS_NODE_ID) user = models.User.load(settings.TABULATE_LOGS_USER_ID) if not local_path: local_path = website_settings.ANALYTICS_PATH for name in os.listdir(local_path): if not os.path.isfile(os.path.join(local_path, name)): logger.info('create directory: {}'.format(os.path.join(local_path, name))) metadata = utils.create_object(name, 'folder-update', node, user, kind='folder', path=remote_path) upload_analytics(os.path.join(local_path, name), metadata['attributes']['path']) else: logger.info('update file: {}'.format(os.path.join(local_path, name))) with open(os.path.join(local_path, name), 'rb') as fp: utils.create_object(name, 'file-update', node, user, stream=fp, kind='file', path=remote_path)
apache-2.0
Akson/RemoteConsolePlus3
RemoteConsolePlus3/RCP3/Backends/Processors/Graphs/Plot1D.py
1
2341
#Created by Dmytro Konobrytskyi, 2014 (github.com/Akson) import numpy as np import matplotlib import matplotlib.pyplot from RCP3.Infrastructure import TmpFilesStorage class Backend(object): def __init__(self, parentNode): self._parentNode = parentNode def Delete(self): """ This method is called when a parent node is deleted. """ pass def GetParameters(self): """ Returns a dictionary with object parameters, their values, limits and ways to change them. """ return {} def SetParameters(self, parameters): """ Gets a dictionary with parameter values and update object parameters accordingly """ pass def ProcessMessage(self, message): """ This message is called when a new message comes. If an incoming message should be processed by following nodes, the 'self._parentNode.SendMessage(message)' should be called with an appropriate message. """ dataArray = np.asarray(message["Data"]) fig = matplotlib.pyplot.figure(figsize=(6, 4), dpi=float(96)) ax=fig.add_subplot(111) #n, bins, patches = ax.hist(dataArray, bins=50) ax.plot(range(len(dataArray)), dataArray) processedMessage = {"Stream":message["Stream"], "Info":message["Info"]} filePath, link = TmpFilesStorage.NewTemporaryFile("png") fig.savefig(filePath,format='png') matplotlib.pyplot.close(fig) html = '<img src="http://{}" alt="Image should come here">'.format(link) processedMessage["Data"] = html self._parentNode.SendMessage(processedMessage) """ print len(message["Data"]) import numpy as np import matplotlib.pyplot as plt x = np.array(message["Data"]) num_bins = 50 # the histogram of the data n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) plt.subplots_adjust(left=0.15) plt.show() """ def AppendContextMenuItems(self, menu): """ Append backend specific menu items to a context menu that user will see when he clicks on a node. """ pass
lgpl-3.0
kevin-intel/scikit-learn
examples/multioutput/plot_classifier_chain_yeast.py
23
4637
""" ============================ Classifier Chain ============================ Example of using classifier chain on a multilabel dataset. For this example we will use the `yeast <https://www.openml.org/d/40597>`_ dataset which contains 2417 datapoints each with 103 features and 14 possible labels. Each data point has at least one label. As a baseline we first train a logistic regression classifier for each of the 14 labels. To evaluate the performance of these classifiers we predict on a held-out test set and calculate the :ref:`jaccard score <jaccard_similarity_score>` for each sample. Next we create 10 classifier chains. Each classifier chain contains a logistic regression model for each of the 14 labels. The models in each chain are ordered randomly. In addition to the 103 features in the dataset, each model gets the predictions of the preceding models in the chain as features (note that by default at training time each model gets the true labels as features). These additional features allow each chain to exploit correlations among the classes. The Jaccard similarity score for each chain tends to be greater than that of the set independent logistic models. Because the models in each chain are arranged randomly there is significant variation in performance among the chains. Presumably there is an optimal ordering of the classes in a chain that will yield the best performance. However we do not know that ordering a priori. Instead we can construct an voting ensemble of classifier chains by averaging the binary predictions of the chains and apply a threshold of 0.5. The Jaccard similarity score of the ensemble is greater than that of the independent models and tends to exceed the score of each chain in the ensemble (although this is not guaranteed with randomly ordered chains). """ # Author: Adam Kleczewski # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_openml from sklearn.multioutput import ClassifierChain from sklearn.model_selection import train_test_split from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import jaccard_score from sklearn.linear_model import LogisticRegression print(__doc__) # Load a multi-label dataset from https://www.openml.org/d/40597 X, Y = fetch_openml('yeast', version=4, return_X_y=True) Y = Y == 'TRUE' X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.2, random_state=0) # Fit an independent logistic regression model for each class using the # OneVsRestClassifier wrapper. base_lr = LogisticRegression() ovr = OneVsRestClassifier(base_lr) ovr.fit(X_train, Y_train) Y_pred_ovr = ovr.predict(X_test) ovr_jaccard_score = jaccard_score(Y_test, Y_pred_ovr, average='samples') # Fit an ensemble of logistic regression classifier chains and take the # take the average prediction of all the chains. chains = [ClassifierChain(base_lr, order='random', random_state=i) for i in range(10)] for chain in chains: chain.fit(X_train, Y_train) Y_pred_chains = np.array([chain.predict(X_test) for chain in chains]) chain_jaccard_scores = [jaccard_score(Y_test, Y_pred_chain >= .5, average='samples') for Y_pred_chain in Y_pred_chains] Y_pred_ensemble = Y_pred_chains.mean(axis=0) ensemble_jaccard_score = jaccard_score(Y_test, Y_pred_ensemble >= .5, average='samples') model_scores = [ovr_jaccard_score] + chain_jaccard_scores model_scores.append(ensemble_jaccard_score) model_names = ('Independent', 'Chain 1', 'Chain 2', 'Chain 3', 'Chain 4', 'Chain 5', 'Chain 6', 'Chain 7', 'Chain 8', 'Chain 9', 'Chain 10', 'Ensemble') x_pos = np.arange(len(model_names)) # Plot the Jaccard similarity scores for the independent model, each of the # chains, and the ensemble (note that the vertical axis on this plot does # not begin at 0). fig, ax = plt.subplots(figsize=(7, 4)) ax.grid(True) ax.set_title('Classifier Chain Ensemble Performance Comparison') ax.set_xticks(x_pos) ax.set_xticklabels(model_names, rotation='vertical') ax.set_ylabel('Jaccard Similarity Score') ax.set_ylim([min(model_scores) * .9, max(model_scores) * 1.1]) colors = ['r'] + ['b'] * len(chain_jaccard_scores) + ['g'] ax.bar(x_pos, model_scores, alpha=0.5, color=colors) plt.tight_layout() plt.show()
bsd-3-clause
trankmichael/scikit-learn
examples/cluster/plot_agglomerative_clustering_metrics.py
402
4492
""" Agglomerative clustering with different metrics =============================================== Demonstrates the effect of different metrics on the hierarchical clustering. The example is engineered to show the effect of the choice of different metrics. It is applied to waveforms, which can be seen as high-dimensional vector. Indeed, the difference between metrics is usually more pronounced in high dimension (in particular for euclidean and cityblock). We generate data from three groups of waveforms. Two of the waveforms (waveform 1 and waveform 2) are proportional one to the other. The cosine distance is invariant to a scaling of the data, as a result, it cannot distinguish these two waveforms. Thus even with no noise, clustering using this distance will not separate out waveform 1 and 2. We add observation noise to these waveforms. We generate very sparse noise: only 6% of the time points contain noise. As a result, the l1 norm of this noise (ie "cityblock" distance) is much smaller than it's l2 norm ("euclidean" distance). This can be seen on the inter-class distance matrices: the values on the diagonal, that characterize the spread of the class, are much bigger for the Euclidean distance than for the cityblock distance. When we apply clustering to the data, we find that the clustering reflects what was in the distance matrices. Indeed, for the Euclidean distance, the classes are ill-separated because of the noise, and thus the clustering does not separate the waveforms. For the cityblock distance, the separation is good and the waveform classes are recovered. Finally, the cosine distance does not separate at all waveform 1 and 2, thus the clustering puts them in the same cluster. """ # Author: Gael Varoquaux # License: BSD 3-Clause or CC-0 import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import AgglomerativeClustering from sklearn.metrics import pairwise_distances np.random.seed(0) # Generate waveform data n_features = 2000 t = np.pi * np.linspace(0, 1, n_features) def sqr(x): return np.sign(np.cos(x)) X = list() y = list() for i, (phi, a) in enumerate([(.5, .15), (.5, .6), (.3, .2)]): for _ in range(30): phase_noise = .01 * np.random.normal() amplitude_noise = .04 * np.random.normal() additional_noise = 1 - 2 * np.random.rand(n_features) # Make the noise sparse additional_noise[np.abs(additional_noise) < .997] = 0 X.append(12 * ((a + amplitude_noise) * (sqr(6 * (t + phi + phase_noise))) + additional_noise)) y.append(i) X = np.array(X) y = np.array(y) n_clusters = 3 labels = ('Waveform 1', 'Waveform 2', 'Waveform 3') # Plot the ground-truth labelling plt.figure() plt.axes([0, 0, 1, 1]) for l, c, n in zip(range(n_clusters), 'rgb', labels): lines = plt.plot(X[y == l].T, c=c, alpha=.5) lines[0].set_label(n) plt.legend(loc='best') plt.axis('tight') plt.axis('off') plt.suptitle("Ground truth", size=20) # Plot the distances for index, metric in enumerate(["cosine", "euclidean", "cityblock"]): avg_dist = np.zeros((n_clusters, n_clusters)) plt.figure(figsize=(5, 4.5)) for i in range(n_clusters): for j in range(n_clusters): avg_dist[i, j] = pairwise_distances(X[y == i], X[y == j], metric=metric).mean() avg_dist /= avg_dist.max() for i in range(n_clusters): for j in range(n_clusters): plt.text(i, j, '%5.3f' % avg_dist[i, j], verticalalignment='center', horizontalalignment='center') plt.imshow(avg_dist, interpolation='nearest', cmap=plt.cm.gnuplot2, vmin=0) plt.xticks(range(n_clusters), labels, rotation=45) plt.yticks(range(n_clusters), labels) plt.colorbar() plt.suptitle("Interclass %s distances" % metric, size=18) plt.tight_layout() # Plot clustering results for index, metric in enumerate(["cosine", "euclidean", "cityblock"]): model = AgglomerativeClustering(n_clusters=n_clusters, linkage="average", affinity=metric) model.fit(X) plt.figure() plt.axes([0, 0, 1, 1]) for l, c in zip(np.arange(model.n_clusters), 'rgbk'): plt.plot(X[model.labels_ == l].T, c=c, alpha=.5) plt.axis('tight') plt.axis('off') plt.suptitle("AgglomerativeClustering(affinity=%s)" % metric, size=20) plt.show()
bsd-3-clause
advancedplotting/aplot
python/plotserv/api_annotations.py
1
8009
# Copyright (c) 2014-2015, Heliosphere Research LLC # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Handles VIs in "api_annotations". """ import numpy as np from matplotlib import pyplot as plt from .core import resource from .terminals import remove_none from . import filters from . import errors @resource('text') def text(ctx, a): """ Display text on the plot """ plotid = a.plotid() x = a.float('x') y = a.float('y') s = a.string('s') relative = a.bool('coordinates') textprops = a.text() display = a.display() ctx.set(plotid) ax = plt.gca() # None-finite values here mean we skip the plot if x is None or y is None: return k = textprops._k() k.update(display._k()) k['clip_on'] = True if relative: k['transform'] = ax.transAxes remove_none(k) plt.text(x, y, s, **k) @resource('hline') def hline(ctx, a): """ Plot a horizontal line """ plotid = a.plotid() y = a.float('y') xmin = a.float('xmin') xmax = a.float('xmax') line = a.line() display = a.display() ctx.set(plotid) ctx.fail_if_polar() # Non-finite value provided if y is None: return k = { 'xmin': xmin, 'xmax': xmax, 'linewidth': line.width, 'linestyle': line.style, 'color': line.color if line.color is not None else 'k', } k.update(display._k()) remove_none(k) plt.axhline(y, **k) @resource('vline') def vline(ctx, a): """ Plot a vertical line """ plotid = a.plotid() x = a.float('x') ymin = a.float('ymin') ymax = a.float('ymax') line = a.line() display = a.display() ctx.set(plotid) ctx.fail_if_polar() # Non-finite value provided if x is None: return k = { 'ymin': ymin, 'ymax': ymax, 'linewidth': line.width, 'linestyle': line.style, 'color': line.color if line.color is not None else 'k', } k.update(display._k()) remove_none(k) plt.axvline(x, **k) @resource('colorbar') def colorbar(ctx, a): """ Display a colorbar """ plotid = a.plotid() label = a.string('label') ticks = a.dbl_1d('ticks') ticklabels = a.string_1d('ticklabels') ctx.set(plotid) # If no colormapped object has been plotted, MPL complains. # We permit this, and simply don't add the colorbar. if ctx.mappable is None: return c = plt.colorbar(ctx.mappable) # Don't bother setting an empty label if len(label) > 0: c.set_label(label) # Both specified if len(ticks) > 0 and len(ticklabels) > 0: ticks, ticklabels = filters.filter_1d(ticks, ticklabels) c.set_ticks(ticks) c.set_ticklabels(ticklabels) # Just ticks specified elif len(ticks) > 0: ticks = ticks[np.isfinite(ticks)] c.set_ticks(ticks) # Just ticklabels specified else: # Providing zero-length "ticks" array invokes auto-ticking, in which # case any ticklabels are ignored. pass @resource('legend') def legend(ctx, a): """ Represents Legend.vi. Note that there is no Positions enum on the Python side; the MPL values are hard-coded into the LabView control. """ POSITIONS = { 0: 0, 1: 1, 2: 9, 3: 2, 4: 6, 5: 3, 6: 8, 7: 4, 8: 7, 9: 10 } plotid = a.plotid() position = a.enum('position', POSITIONS) ctx.set(plotid) k = {'loc': position, 'fontsize': 'medium'} remove_none(k) if len(ctx.legend_entries) > 0: objects, labels = zip(*ctx.legend_entries) plt.legend(objects, labels, **k) @resource('label') def label(ctx, a): """ Title, X axis and Y axis labels. """ LOCATIONS = {0: 'title', 1: 'xlabel', 2: 'ylabel'} plotid = a.plotid() location = a.enum('kind', LOCATIONS) label = a.string('label') text = a.text() ctx.set(plotid) k = text._k() if location == 'title': plt.title(label, **k) elif location == 'xlabel': plt.xlabel(label, **k) elif location == 'ylabel': ctx.fail_if_polar() plt.ylabel(label, **k) else: pass @resource('circle') def circle(ctx, a): """ Draw a circle on a rectangular plot """ plotid = a.plotid() x = a.float('x') y = a.float('y') radius = a.float('radius') color = a.color('color') line = a.line() display = a.display() f = ctx.set(plotid) ctx.fail_if_polar() ctx.fail_if_log_symlog() # Like Text.vi, if any critical input is Nan we do nothing if x is None or y is None or radius is None: return # Catch this before MPL complains if radius <= 0: return k = { 'edgecolor': line.color, 'linestyle': line.style, 'linewidth': line.width, 'facecolor': color if color is not None else '#bbbbbb', } k.update(display._k()) remove_none(k) c = plt.Circle((x,y), radius, **k) f.gca().add_artist(c) @resource('rectangle') def rectangle(ctx, a): """ Draw a rectangle """ plotid = a.plotid() x = a.float('x') y = a.float('y') width = a.float('width') height = a.float('height') color = a.color('color') line = a.line() display = a.display() f = ctx.set(plotid) ctx.fail_if_symlog() # Like Text.vi, if any critical input is Nan we do nothing if x is None or y is None or width is None or height is None: return if width == 0 or height == 0: return k = { 'edgecolor': line.color, 'linestyle': line.style, 'linewidth': line.width, 'facecolor': color if color is not None else '#bbbbbb', } k.update(display._k()) remove_none(k) r = plt.Rectangle((x,y), width, height, **k) f.gca().add_artist(r)
bsd-3-clause
macioosch/dynamo-hard-spheres-sim
convergence-plot.py
1
6346
#!/usr/bin/env python2 # encoding=utf-8 from __future__ import division, print_function from glob import glob from itertools import izip from matplotlib import pyplot as plt import numpy as np input_files = glob("csv/convergence-256000-0.*.csv") #input_files = glob("csv/convergence-500000-0.*.csv") #input_files = glob("csv/convergence-1000188-0.*.csv") #plotted_parameter = "msds_diffusion" plotted_parameter = "pressures_collision" #plotted_parameter = "pressures_virial" #plotted_parameter = "msds_val" #plotted_parameter = "times" legend_names = [] tight_layout = False show_legend = False for file_number, file_name in enumerate(sorted(input_files)): data = np.genfromtxt(file_name, delimiter='\t', names=[ "packings","densities","collisions","n_atoms","pressures_virial", "pressures_collision","msds_val","msds_diffusion","times", "std_pressures_virial","std_pressures_collision","std_msds_val", "std_msds_diffusion","std_times"]) n_atoms = data["n_atoms"][0] density = data["densities"][0] equilibrated_collisions = data["collisions"] - 2*data["collisions"][0] \ + data["collisions"][1] """ ### 5 graphs: D(CPS) ### tight_layout = True skip_points = 0 ax = plt.subplot(3, 2, file_number+1) plt.fill_between((equilibrated_collisions / n_atoms)[skip_points:], data[plotted_parameter][skip_points:] - data["std_" + plotted_parameter][skip_points:], data[plotted_parameter][skip_points:] + data["std_" + plotted_parameter][skip_points:], alpha=0.3) plt.plot((equilibrated_collisions / n_atoms)[skip_points:], data[plotted_parameter][skip_points:], lw=2) if plotted_parameter == "msds_diffusion": plt.ylim(0.990*data[plotted_parameter][-1], 1.005*data[plotted_parameter][-1]) plt.xlim([0, 1e5]) plt.legend(["Density {}".format(data["densities"][0])], loc="lower right") ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.4f')) plt.xlabel("Collisions per sphere") plt.ylabel("D") """ ### 5 graphs: relative D(CPS) ### tight_layout = True skip_points = 0 ax = plt.subplot(3, 2, file_number+1) plt.fill_between((equilibrated_collisions / n_atoms)[skip_points:], -1 + (data[plotted_parameter][skip_points:] - data["std_" + plotted_parameter][skip_points:])/data[plotted_parameter][-1], -1 + (data[plotted_parameter][skip_points:] + data["std_" + plotted_parameter][skip_points:])/data[plotted_parameter][-1], alpha=0.3) plt.plot((equilibrated_collisions / n_atoms)[skip_points:], -1 + data[plotted_parameter][skip_points:]/data[plotted_parameter][-1], lw=2) plt.ylim(data["std_" + plotted_parameter][-1]*20*np.array([-1, 1])/data[plotted_parameter][-1]) #plt.xscale("log") plt.xlim([0, 1e5]) plt.legend(["$\\rho\\sigma^3=\\ {}$".format(data["densities"][0])], loc="lower right") ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2e')) plt.xlabel("$C/N$") plt.ylabel("$[Z_{MD}(C) / Z_{MD}(C=10^5 N)] - 1$") """ ### 1 graph: D(t) ### show_legend = True skip_points = 0 plt.title("D(t) for 5 densities") plt.loglog(data["times"][skip_points:], data[plotted_parameter][skip_points:]) legend_names.append(data["densities"][0]) plt.xlabel("Time") plt.ylabel("D") """ """ ### 1 graph: D(t) / Dinf ### show_legend = True skip_points = 0 #plt.fill_between(data["times"][skip_points:], # (data[plotted_parameter] - data["std_" + plotted_parameter]) # / data[plotted_parameter][-1] - 1, # (data[plotted_parameter] + data["std_" + plotted_parameter]) # / data[plotted_parameter][-1] - 1, color="grey", alpha=0.4) plt.plot(data["times"][skip_points:], data[plotted_parameter] / data[plotted_parameter][-1] - 1, lw=1) legend_names.append(data["densities"][0]) #plt.xscale("log") plt.xlabel("Time") plt.ylabel("D / D(t --> inf)") """ """ ### 5 graphs: D(1/CPS) ### tight_layout = True skip_points = 40 ax = plt.subplot(3, 2, file_number+1) plt.fill_between((n_atoms / equilibrated_collisions)[skip_points:], data[plotted_parameter][skip_points:] - data["std_" + plotted_parameter][skip_points:], data[plotted_parameter][skip_points:] + data["std_" + plotted_parameter][skip_points:], alpha=0.3) plt.plot((n_atoms / equilibrated_collisions)[skip_points:], data[plotted_parameter][skip_points:], lw=2) plt.title("Density {}:".format(data["densities"][0])) ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.7f')) plt.xlim(xmin=0) plt.xlabel("1 / Collisions per sphere") plt.ylabel("D") """ """ ### 1 graph: D(CPS) / Dinf ### show_legend = True plt.fill_between(equilibrated_collisions / n_atoms, (data[plotted_parameter] - data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, (data[plotted_parameter] + data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, color="grey", alpha=0.4) plt.plot(equilibrated_collisions / n_atoms, data[plotted_parameter] / data[plotted_parameter][-1] - 1, lw=2) legend_names.append(data["densities"][0]) plt.xlabel("Collisions per sphere") plt.ylabel("D / D(t --> inf)") """ """ ### 1 graph: D(1/CPS) / Dinf ### show_legend = True plt.fill_between(n_atoms / equilibrated_collisions, (data[plotted_parameter] - data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, (data[plotted_parameter] + data["std_" + plotted_parameter]) / data[plotted_parameter][-1] - 1, color="grey", alpha=0.4) plt.plot( n_atoms / equilibrated_collisions, data[plotted_parameter] / data[plotted_parameter][-1] - 1) legend_names.append(data["densities"][0]) plt.xlabel(" 1 / Collisions per sphere") plt.ylabel(plotted_parameter) """ #if tight_layout: # plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0) if show_legend: plt.legend(legend_names, title="Density:", loc="lower right") plt.show()
gpl-3.0
srio/shadow3-scripts
transfocator_id30b.py
1
25823
import numpy import xraylib """ transfocator_id30b : transfocator for id13b: It can: 1) guess the lens configuration (number of lenses for each type) for a given photon energy and target image size. Use transfocator_compute_configuration() for this task 2) for a given transfocator configuration, compute the main optical parameters (image size, focal distance, focal position and divergence). Use transfocator_compute_parameters() for this task 3) Performs full ray tracing. Use id30b_ray_tracing() for this task Note that for the optimization and parameters calculations the transfocator configuration is given in keywords. For ray tracing calculations many parameters of the transfocator are hard coded with the values of id30b See main program for examples. Dependencies: Numpy xraylib (to compute refracion indices) Shadow (for ray tracing only) matplotlib (for some plots of ray=tracing) Side effects: When running ray tracing some files are created. MODIFICATION HISTORY: 2015-03-25 srio@esrf.eu, written """ __author__ = "Manuel Sanchez del Rio" __contact__ = "srio@esrf.eu" __copyright__ = "ESRF, 2015" def transfocator_compute_configuration(photon_energy_ev,s_target,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800, verbose=1 ): """ Computes the optimum transfocator configuration for a given photon energy and target image size. All length units are cm :param photon_energy_ev: the photon energy in eV :param s_target: the target image size in cm. :param symbol: the chemical symbol of the lens material of each type. Default symbol=["Be","Be","Be"] :param density: the density of each type of lens. Default: density=[1.845,1.845,1.845] :param nlenses_max: the maximum allowed number of lenases for each type of lens. nlenses_max = [15,3,1] :param nlenses_radii: the radii in cm of each type of lens. Default: nlenses_radii = [500e-4,1000e-4,1500e-4] :param lens_diameter: the physical diameter (acceptance) in cm of the lenses. If different for each type of lens, consider the smaller one. Default: lens_diameter=0.05 :param sigmaz: the sigma (standard deviation) of the source in cm :param alpha: an adjustable parameter in [0,1](see doc). Default: 0.55 (it is 0.76 for pure Gaussian beams) :param tf_p: the distance source-transfocator in cm :param tf_q: the distance transfocator-image in cm :param:verbose: set to 1 for verbose text output :return: a list with the number of lenses of each type. """ if s_target < 2.35*sigmaz*tf_q/tf_p: print("Source size FWHM is: %f um"%(1e4*2.35*sigmaz)) print("Maximum Demagnifications is: %f um"%(tf_p/tf_q)) print("Minimum possible size is: %f um"%(1e4*2.35*sigmaz*tf_q/tf_p)) print("Error: redefine size") return None deltas = [(1.0 - xraylib.Refractive_Index_Re(symbol[i],photon_energy_ev*1e-3,density[i])) \ for i in range(len(symbol))] focal_q_target = _tansfocator_guess_focal_position( s_target, p=tf_p, q=tf_q, sigmaz=sigmaz, alpha=alpha, \ lens_diameter=lens_diameter,method=2) focal_f_target = 1.0 / (1.0/focal_q_target + 1.0/tf_p) div_q_target = alpha * lens_diameter / focal_q_target #corrections for extreme cases source_demagnified = 2.35*sigmaz*focal_q_target/tf_p if source_demagnified > lens_diameter: source_demagnified = lens_diameter s_target_calc = numpy.sqrt( (div_q_target*(tf_q-focal_q_target))**2 + source_demagnified**2) nlenses_target = _transfocator_guess_configuration(focal_f_target,deltas=deltas,\ nlenses_max=nlenses_max,radii=nlenses_radii, ) if verbose: print("transfocator_compute_configuration: focal_f_target: %f"%(focal_f_target)) print("transfocator_compute_configuration: focal_q_target: %f cm"%(focal_q_target)) print("transfocator_compute_configuration: s_target: %f um"%(s_target_calc*1e4)) print("transfocator_compute_configuration: nlenses_target: ",nlenses_target) return nlenses_target def transfocator_compute_parameters(photon_energy_ev, nlenses_target,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800 ): """ Computes the parameters of the optical performances of a given transgocator configuration. returns a l All length units are cm :param photon_energy_ev: :param nlenses_target: a list with the lens configuration, i.e. the number of lenses of each type. :param symbol: the chemical symbol of the lens material of each type. Default symbol=["Be","Be","Be"] :param density: the density of each type of lens. Default: density=[1.845,1.845,1.845] :param nlenses_max: the maximum allowed number of lenases for each type of lens. nlenses_max = [15,3,1] TODO: remove (not used) :param nlenses_radii: the radii in cm of each type of lens. Default: nlenses_radii = [500e-4,1000e-4,1500e-4] :param lens_diameter: the physical diameter (acceptance) in cm of the lenses. If different for each type of lens, consider the smaller one. Default: lens_diameter=0.05 :param sigmaz: the sigma (standard deviation) of the source in cm :param alpha: an adjustable parameter in [0,1](see doc). Default: 0.55 (it is 0.76 for pure Gaussian beams) :param tf_p: the distance source-transfocator in cm :param tf_q: the distance transfocator-image in cm :return: a list with parameters (image_siza, lens_focal_distance, focal_position from transfocator center, divergence of beam after the transfocator) """ deltas = [(1.0 - xraylib.Refractive_Index_Re(symbol[i],photon_energy_ev*1e-3,density[i])) \ for i in range(len(symbol))] focal_f = _transfocator_calculate_focal_distance( deltas=deltas,\ nlenses=nlenses_target,radii=nlenses_radii) focal_q = 1.0 / (1.0/focal_f - 1.0/tf_p) div_q = alpha * lens_diameter / focal_q #corrections source_demagnified = 2.35*sigmaz*focal_q/tf_p if source_demagnified > lens_diameter: source_demagnified = lens_diameter s_target = numpy.sqrt( (div_q*(tf_q-focal_q))**2 + (source_demagnified)**2 ) return (s_target,focal_f,focal_q,div_q) def transfocator_nlenses_to_slots(nlenses,nlenses_max=None): """ converts the transfocator configuration from a list of the number of lenses of each type, into a list of active (1) or inactive (0) actuators for the slots. :param nlenses: the list with number of lenses (e.g., [5,2,0] :param nlenses_max: the maximum number of lenses of each type, usually powers of two minus one. E.g. [15,3,1] :return: a list of on (1) and off (0) slots, e.g., [1, 0, 1, 0, 0, 1, 0] (first type: 1*1+0*2+1*4+0*8=5, second type: 0*1+1*2=2, third type: 0*1=0) """ if nlenses_max == None: nlenses_max = nlenses ss = [] for i,iopt in enumerate(nlenses): if iopt > nlenses_max[i]: print("Error: i:%d, nlenses: %d, nlenses_max: %d"%(i,iopt,nlenses_max[i])) ncharacters = len("{0:b}".format(nlenses_max[i])) si = list( ("{0:0%db}"%(ncharacters)).format(int(iopt)) ) si.reverse() ss += si on_off = [int(i) for i in ss] #print("transfocator_nlenses_to_slots: nlenses_max: ",nlenses_max," nlenses: ",nlenses," slots: ",on_off) return on_off def _transfocator_calculate_focal_distance(deltas=[0.999998],nlenses=[1],radii=[500e-4]): inverse_focal_distance = 0.0 for i,nlensesi in enumerate(nlenses): if nlensesi > 0: focal_distance_i = radii[i] / (2.*nlensesi*deltas[i]) inverse_focal_distance += 1.0/focal_distance_i if inverse_focal_distance == 0: return 99999999999999999999999999. else: return 1.0/inverse_focal_distance def _tansfocator_guess_focal_position( s_target, p=5960., q=3800.0, sigmaz=6.46e-4, \ alpha=0.66, lens_diameter=0.05, method=2): x = 1e15 if method == 1: # simple sum AA = 2.35*sigmaz/p BB = -(s_target + alpha * lens_diameter) CC = alpha*lens_diameter*q cc = numpy.roots([AA,BB,CC]) x = cc[1] return x if method == 2: # sum in quadrature AA = ( (2.35*sigmaz)**2)/(p**2) BB = 0.0 CC = alpha**2 * lens_diameter**2 - s_target**2 DD = - 2.0 * alpha**2 * lens_diameter**2 * q EE = alpha**2 * lens_diameter**2 * q**2 cc = numpy.roots([AA,BB,CC,DD,EE]) for i,cci in enumerate(cc): if numpy.imag(cci) == 0: return numpy.real(cci) return x def _transfocator_guess_configuration(focal_f_target,deltas=[0.999998],nlenses_max=[15],radii=[500e-4]): nn = len(nlenses_max) ncombinations = (1+nlenses_max[0]) * (1+nlenses_max[1]) * (1+nlenses_max[2]) icombinations = 0 aa = numpy.zeros((3,ncombinations),dtype=int) bb = numpy.zeros(ncombinations) for i0 in range(1+nlenses_max[0]): for i1 in range(1+nlenses_max[1]): for i2 in range(1+nlenses_max[2]): aa[0,icombinations] = i0 aa[1,icombinations] = i1 aa[2,icombinations] = i2 bb[icombinations] = focal_f_target - _transfocator_calculate_focal_distance(deltas=deltas,nlenses=[i0,i1,i2],radii=radii) icombinations += 1 bb1 = numpy.abs(bb) ibest = bb1.argmin() return (aa[:,ibest]).tolist() # # # def id30b_ray_tracing(emittH=4e-9,emittV=1e-11,betaH=35.6,betaV=3.0,number_of_rays=50000,\ density=1.845,symbol="Be",tf_p=1000.0,tf_q=1000.0,lens_diameter=0.05,\ slots_max=None,slots_on_off=None,photon_energy_ev=14000.0,\ slots_lens_thickness=None,slots_steps=None,slots_radii=None,\ s_target=10e-4,focal_f=10.0,focal_q=10.0,div_q=1e-6): #======================================================================================================================= # Gaussian undulator source #======================================================================================================================= import Shadow #import Shadow.ShadowPreprocessorsXraylib as sx sigmaXp = numpy.sqrt(emittH/betaH) sigmaZp = numpy.sqrt(emittV/betaV) sigmaX = emittH/sigmaXp sigmaZ = emittV/sigmaZp print("\n\nElectron sizes H:%f um, V:%fu m;\nelectron divergences: H:%f urad, V:%f urad"%\ (sigmaX*1e6, sigmaZ*1e6, sigmaXp*1e6, sigmaZp*1e6)) # set Gaussian source src = Shadow.Source() src.set_energy_monochromatic(photon_energy_ev) src.set_gauss(sigmaX*1e2,sigmaZ*1e2,sigmaXp,sigmaZp) print("\n\nElectron sizes stored H:%f um, V:%f um;\nelectron divergences: H:%f urad, V:%f urad"%\ (src.SIGMAX*1e4,src.SIGMAZ*1e4,src.SIGDIX*1e6,src.SIGDIZ*1e6)) src.apply_gaussian_undulator(undulator_length_in_m=2.8, user_unit_to_m=1e-2, verbose=1) print("\n\nElectron sizes stored (undulator) H:%f um, V:%f um;\nelectron divergences: H:%f urad, V:%f urad"%\ (src.SIGMAX*1e4,src.SIGMAZ*1e4,src.SIGDIX*1e6,src.SIGDIZ*1e6)) print("\n\nSource size in vertical FWHM: %f um\n"%\ (2.35*src.SIGMAZ*1e4)) src.NPOINT = number_of_rays src.ISTAR1 = 0 # 677543155 src.write("start.00") # create source beam = Shadow.Beam() beam.genSource(src) beam.write("begin.dat") src.write("end.00") #======================================================================================================================= # complete the (detailed) transfocator description #======================================================================================================================= print("\nSetting detailed Transfocator for ID30B") slots_nlenses = numpy.array(slots_max)*numpy.array(slots_on_off) slots_empty = (numpy.array(slots_max)-slots_nlenses) # ####interactive=True, SYMBOL="SiC",DENSITY=3.217,FILE="prerefl.dat",E_MIN=100.0,E_MAX=20000.0,E_STEP=100.0 Shadow.ShadowPreprocessorsXraylib.prerefl(interactive=False,E_MIN=2000.0,E_MAX=55000.0,E_STEP=100.0,\ DENSITY=density,SYMBOL=symbol,FILE="Be2_55.dat" ) nslots = len(slots_max) prerefl_file = ["Be2_55.dat" for i in range(nslots)] print("slots_max: ",slots_max) #print("slots_target: ",slots_target) print("slots_on_off: ",slots_on_off) print("slots_steps: ",slots_steps) print("slots_radii: ",slots_radii) print("slots_nlenses: ",slots_nlenses) print("slots_empty: ",slots_empty) #calculate distances, nlenses and slots_empty # these are distances p and q with TF length removed tf_length = numpy.array(slots_steps).sum() #tf length in cm tf_fs_before = tf_p - 0.5*tf_length #distance from source to center of transfocator tf_fs_after = tf_q - 0.5*tf_length # distance from center of transfocator to image # for each slot, these are the empty distances before and after the lenses tf_p0 = numpy.zeros(nslots) tf_q0 = numpy.array(slots_steps) - (numpy.array(slots_max) * slots_lens_thickness) # add now the p q distances tf_p0[0] += tf_fs_before tf_q0[-1] += tf_fs_after print("tf_p0: ",tf_p0) print("tf_q0: ",tf_q0) print("tf_length: %f cm"%(tf_length)) # build transfocator tf = Shadow.CompoundOE(name='TF ID30B') tf.append_transfocator(tf_p0.tolist(), tf_q0.tolist(), \ nlenses=slots_nlenses.tolist(), radius=slots_radii, slots_empty=slots_empty.tolist(),\ thickness=slots_lens_thickness, prerefl_file=prerefl_file,\ surface_shape=4, convex_to_the_beam=0, diameter=lens_diameter,\ cylinder_angle=0.0,interthickness=50e-4,use_ccc=0) itmp = input("SHADOW Source complete. Do you want to run SHADOR trace? [1=Yes,0=No]: ") if str(itmp) != "1": return #trace system tf.dump_systemfile() beam.traceCompoundOE(tf,write_start_files=0,write_end_files=0,write_star_files=0, write_mirr_files=0) #write only last result file beam.write("star_tf.dat") print("\nFile written to disk: star_tf.dat") # # #ideal calculations # print("\n\n\n") print("=============================================== TRANSFOCATOR OUTPUTS ==========================================") print("\nTHEORETICAL results: ") print("REMIND-----With these lenses we obtained (analytically): ") print("REMIND----- focal_f: %f cm"%(focal_f)) print("REMIND----- focal_q: %f cm"%(focal_q)) print("REMIND----- s_target: %f um"%(s_target*1e4)) demagnification_factor = tf_p/focal_q theoretical_focal_size = src.SIGMAZ*2.35/demagnification_factor # analyze shadow results print("\nSHADOW results: ") st1 = beam.get_standard_deviation(3,ref=0) st2 = beam.get_standard_deviation(3,ref=1) print(" stDev*2.35: unweighted: %f um, weighted: %f um "%(st1*2.35*1e4,st2*2.35*1e4)) tk = beam.histo1(3, nbins=75, ref=1, nolost=1, write="HISTO1") print(" Histogram FWHM: %f um "%(1e4*tk["fwhm"])) print(" Transmitted intensity: %f (source was: %d) (transmission is %f %%) "%(beam.intensity(nolost=1), src.NPOINT, beam.intensity(nolost=1)/src.NPOINT*100)) #scan around image xx1 = numpy.linspace(0.0,1.1*tf_fs_after,11) # position from TF exit plane #xx0 = focal_q - tf_length*0.5 xx0 = focal_q - tf_length*0.5 # position of focus from TF exit plane xx2 = numpy.linspace(xx0-100.0,xx0+100,21) # position from TF exit plane xx3 = numpy.array([tf_fs_after]) xx = numpy.concatenate(([-0.5*tf_length],xx1,xx2,[tf_fs_after])) xx.sort() f = open("id30b.spec","w") f.write("#F id30b.spec\n") f.write("\n#S 1 calculations for id30b transfocator\n") f.write("#N 8\n") labels = " %18s %18s %18s %18s %18s %18s %18s %18s"%\ ("pos from source","pos from image","[pos from TF]", "pos from TF center", "pos from focus",\ "fwhm shadow(stdev)","fwhm shadow(histo)","fwhm theoretical") f.write("#L "+labels+"\n") out = numpy.zeros((8,xx.size)) for i,pos in enumerate(xx): beam2 = beam.duplicate() beam2.retrace(-tf_fs_after+pos) fwhm1 = 2.35*1e4*beam2.get_standard_deviation(3,ref=1,nolost=1) tk = beam2.histo1(3, nbins=75, ref=1, nolost=1) fwhm2 = 1e4*tk["fwhm"] #fwhm_th = 1e4*transfocator_calculate_estimated_size(pos,diameter=diameter,focal_distance=focal_q) fwhm_th2 = 1e4*numpy.sqrt( (div_q*(pos+0.5*tf_length-focal_q))**2 + theoretical_focal_size**2 ) #fwhm_th2 = 1e4*( numpy.abs(div_q*(pos-focal_q+0.5*tf_length)) + theoretical_focal_size ) out[0,i] = tf_fs_before+tf_length+pos out[1,i] = -tf_fs_after+pos out[2,i] = pos out[3,i] = pos+0.5*tf_length out[4,i] = pos+0.5*tf_length-focal_q out[5,i] = fwhm1 out[6,i] = fwhm2 out[7,i] = fwhm_th2 f.write(" %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f %18.3f \n"%\ (tf_fs_before+tf_length+pos,\ -tf_fs_after+pos,\ pos,\ pos+0.5*tf_length,\ pos+0.5*tf_length-focal_q,\ fwhm1,fwhm2,fwhm_th2)) f.close() print("File with beam evolution written to disk: id30b.spec") # # plots # itmp = input("Do you want to plot the intensity distribution and beam evolution? [1=yes,0=No]") if str(itmp) != "1": return import matplotlib.pylab as plt plt.figure(1) plt.plot(out[1,:],out[5,:],'blue',label="fwhm shadow(stdev)") plt.plot(out[1,:],out[6,:],'green',label="fwhm shadow(histo1)") plt.plot(out[1,:],out[7,:],'red',label="fwhm theoretical") plt.xlabel("Distance from image plane [cm]") plt.ylabel("spot size [um] ") ax = plt.subplot(111) ax.legend(bbox_to_anchor=(1.1, 1.05)) print("Kill graphic to continue.") plt.show() Shadow.ShadowTools.histo1(beam,3,nbins=75,ref=1,nolost=1,calfwhm=1) input("<Enter> to finish.") return None def id30b_full_simulation(photon_energy_ev=14000.0,s_target=20.0e-4,nlenses_target=None): if nlenses_target == None: force_nlenses = 0 else: force_nlenses = 1 # # define lens setup (general) # xrl_symbol = ["Be","Be","Be"] xrl_density = [1.845,1.845,1.845] lens_diameter = 0.05 nlenses_max = [15,3,1] nlenses_radii = [500e-4,1000e-4,1500e-4] sigmaz=6.46e-4 alpha = 0.55 tf_p = 5960 # position of the TF measured from the center of the transfocator tf_q = 9760 - tf_p # position of the image plane measured from the center of the transfocator if s_target < 2.35*sigmaz*tf_q/tf_p: print("Source size FWHM is: %f um"%(1e4*2.35*sigmaz)) print("Maximum Demagnifications is: %f um"%(tf_p/tf_q)) print("Minimum possible size is: %f um"%(1e4*2.35*sigmaz*tf_q/tf_p)) print("Error: redefine size") return print("================================== TRANSFOCATOR INPUTS ") print("Photon energy: %f eV"%(photon_energy_ev)) if force_nlenses: print("Forced_nlenses: ",nlenses_target) else: print("target size: %f cm"%(s_target)) print("materials: ",xrl_symbol) print("densities: ",xrl_density) print("Lens diameter: %f cm"%(lens_diameter)) print("nlenses_max:",nlenses_max,"nlenses_radii: ",nlenses_radii) print("Source size (sigma): %f um, FWHM: %f um"%(1e4*sigmaz,2.35*1e4*sigmaz)) print("Distances: tf_p: %f cm, tf_q: %f cm"%(tf_p,tf_q)) print("alpha: %f"%(alpha)) print("========================================================") if force_nlenses != 1: nlenses_target = transfocator_compute_configuration(photon_energy_ev,s_target,\ symbol=xrl_symbol,density=xrl_density,\ nlenses_max=nlenses_max, nlenses_radii=nlenses_radii, lens_diameter=lens_diameter, \ sigmaz=sigmaz, alpha=alpha, \ tf_p=tf_p,tf_q=tf_q, verbose=1) (s_target,focal_f,focal_q,div_q) = \ transfocator_compute_parameters(photon_energy_ev, nlenses_target,\ symbol=xrl_symbol,density=xrl_density,\ nlenses_max=nlenses_max, nlenses_radii=nlenses_radii, \ lens_diameter=lens_diameter,\ sigmaz=sigmaz, alpha=alpha,\ tf_p=tf_p,tf_q=tf_q) slots_max = [ 1, 2, 4, 8, 1, 2, 1] # slots slots_on_off = transfocator_nlenses_to_slots(nlenses_target,nlenses_max=nlenses_max) print("=============================== TRANSFOCATOR SET") #print("deltas: ",deltas) if force_nlenses != 1: print("nlenses_target (optimized): ",nlenses_target) else: print("nlenses_target (forced): ",nlenses_target) print("With these lenses we obtain: ") print(" focal_f: %f cm"%(focal_f)) print(" focal_q: %f cm"%(focal_q)) print(" s_target: %f um"%(s_target*1e4)) print(" slots_max: ",slots_max) print(" slots_on_off: ",slots_on_off) print("==================================================") # for theoretical calculations use the focal position and distances given by the target nlenses itmp = input("Start SHADOW simulation? [1=yes,0=No]: ") if str(itmp) != "1": return #======================================================================================================================= # Inputs #======================================================================================================================= emittH = 3.9e-9 emittV = 10e-12 betaH = 35.6 betaV = 3.0 number_of_rays = 50000 nslots = len(slots_max) slots_lens_thickness = [0.3 for i in range(nslots)] #total thickness of a single lens in cm # for each slot, positional gap of the first lens in cm slots_steps = [ 4, 4, 1.9, 6.1, 4, 4, slots_lens_thickness[-1]] slots_radii = [.05, .05, .05, .05, 0.1, 0.1, 0.15] # radii of the lenses in cm AAA= 333 id30b_ray_tracing(emittH=emittH,emittV=emittV,betaH=betaH,betaV=betaV,number_of_rays=number_of_rays,\ density=xrl_density[0],symbol=xrl_symbol[0],tf_p=tf_p,tf_q=tf_q,lens_diameter=lens_diameter,\ slots_max=slots_max,slots_on_off=slots_on_off,photon_energy_ev=photon_energy_ev,\ slots_lens_thickness=slots_lens_thickness,slots_steps=slots_steps,slots_radii=slots_radii,\ s_target=s_target,focal_f=focal_f,focal_q=focal_q,div_q=div_q) def main(): # this performs the full simulation: calculates the optimum configuration and do the ray-tracing itmp = input("Enter: \n 0 = optimization calculation only \n 1 = full simulation (ray tracing) \n?> ") photon_energy_kev = float(input("Enter photon energy in keV: ")) s_target_um = float(input("Enter target focal dimension in microns: ")) if str(itmp) == "1": id30b_full_simulation(photon_energy_ev=photon_energy_kev*1e3,s_target=s_target_um*1e-4,nlenses_target=None) #id30b_full_simulation(photon_energy_ev=14000.0,s_target=20.0e-4,nlenses_target=[3,1,1]) else: #this performs the calculation of the optimizad configuration nlenses_optimum = transfocator_compute_configuration(photon_energy_kev*1e3,s_target_um*1e-4,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800, verbose=0 ) print("Optimum lens configuration is: ",nlenses_optimum) if nlenses_optimum == None: return print("Activate slots: ",transfocator_nlenses_to_slots(nlenses_optimum,nlenses_max=[15,3,1])) # this calculates the parameters (image size, etc) for a given lens configuration (size, f, q_f, div) = transfocator_compute_parameters(photon_energy_kev*1e3, nlenses_optimum,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q=3800 ) print("For given configuration ",nlenses_optimum," we get: ") print(" size: %f cm, focal length: %f cm, focal distance: %f cm, divergence: %f rad: "%(size, f, q_f, div)) if __name__ == "__main__": main()
mit
RAJSD2610/SDNopenflowSwitchAnalysis
TotalFlowPlot.py
1
2742
import os import pandas as pd import matplotlib.pyplot as plt import seaborn seaborn.set() path= os.path.expanduser("~/Desktop/ece671/udpt8") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) u8=[] i=0 def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 while i<(num_files/2) : # df+=[] j=i+1 path ="/home/vetri/Desktop/ece671/udpt8/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 u8.append(y) i+=1 print(u8) path= os.path.expanduser("~/Desktop/ece671/udpnone") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) i=0 j=0 u=[] while i<(num_files/2): j=i+1 path ="/home/vetri/Desktop/ece671/udpnone/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 u.append(y) i+=1 print(u) path= os.path.expanduser("~/Desktop/ece671/tcpnone") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) i=0 j=0 t=[] while i<(num_files/2): j=i+1 path ="/home/vetri/Desktop/ece671/tcpnone/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 t.append(y) i+=1 print(t) path= os.path.expanduser("~/Desktop/ece671/tcpt8") num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) print(num_files) i=0 j=0 t8=[] while i<(num_files/2): j=i+1 path ="/home/vetri/Desktop/ece671/tcpt8/ftotal."+str(j)+".csv" y = file_len(path) # except: pass #df.append(pd.read_csv(path,header=None)) # a+=[] #y=len(df[i].index)-1 #1 row added by default so that table has a entry if y<0: y=0 t8.append(y) i+=1 print(t8) #plt.figure(figsize=(4, 5)) plt.plot(list(range(1,len(u8)+1)),u8, '.-',label="udpt8") plt.plot(list(range(1,len(u)+1)),u, '.-',label="udpnone") plt.plot(list(range(1,len(t)+1)),t, '.-',label="tcpnone") plt.plot(list(range(1,len(t8)+1)),t8, '.-',label="tcpt8") plt.title("Total Flows Present after 1st flow") plt.xlabel("time(s)") plt.ylabel("flows") #plt.frameon=True plt.legend() plt.show()
gpl-3.0
JackKelly/neuralnilm_prototype
scripts/e307.py
2
6092
from __future__ import print_function, division import matplotlib import logging from sys import stdout matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import (Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer, BidirectionalRecurrentLayer) from neuralnilm.source import standardise, discretize, fdiff, power_and_fdiff from neuralnilm.experiment import run_experiment, init_experiment from neuralnilm.net import TrainingError from neuralnilm.layers import MixtureDensityLayer from neuralnilm.objectives import scaled_cost, mdn_nll, scaled_cost_ignore_inactive, ignore_inactive from neuralnilm.plot import MDNPlotter from lasagne.nonlinearities import sigmoid, rectify, tanh from lasagne.objectives import mse from lasagne.init import Uniform, Normal from lasagne.layers import (LSTMLayer, DenseLayer, Conv1DLayer, ReshapeLayer, FeaturePoolLayer, RecurrentLayer) from lasagne.updates import nesterov_momentum, momentum from functools import partial import os import __main__ from copy import deepcopy from math import sqrt import numpy as np import theano.tensor as T NAME = os.path.splitext(os.path.split(__main__.__file__)[1])[0] PATH = "/homes/dk3810/workspace/python/neuralnilm/figures" SAVE_PLOT_INTERVAL = 250 GRADIENT_STEPS = 100 SEQ_LENGTH = 512 source_dict = dict( filename='/data/dk3810/ukdale.h5', appliances=[ ['fridge freezer', 'fridge', 'freezer'], 'hair straighteners', 'television' # 'dish washer', # ['washer dryer', 'washing machine'] ], max_appliance_powers=[300, 500, 200, 2500, 2400], on_power_thresholds=[5] * 5, max_input_power=5900, min_on_durations=[60, 60, 60, 1800, 1800], min_off_durations=[12, 12, 12, 1800, 600], window=("2013-06-01", "2014-07-01"), seq_length=SEQ_LENGTH, output_one_appliance=False, boolean_targets=False, train_buildings=[1], validation_buildings=[1], skip_probability=0.0, n_seq_per_batch=16, subsample_target=4, include_diff=False, clip_appliance_power=True, target_is_prediction=False, independently_center_inputs = True, standardise_input=True, standardise_targets=True, input_padding=0, lag=0, reshape_target_to_2D=False, input_stats={'mean': np.array([ 0.05526326], dtype=np.float32), 'std': np.array([ 0.12636775], dtype=np.float32)}, target_stats={ 'mean': np.array([ 0.04066789, 0.01881946, 0.24639061, 0.17608672, 0.10273963], dtype=np.float32), 'std': np.array([ 0.11449792, 0.07338708, 0.26608968, 0.33463112, 0.21250485], dtype=np.float32)} ) N = 50 net_dict = dict( save_plot_interval=SAVE_PLOT_INTERVAL, # loss_function=partial(ignore_inactive, loss_func=mdn_nll, seq_length=SEQ_LENGTH), # loss_function=lambda x, t: mdn_nll(x, t).mean(), loss_function=lambda x, t: mse(x, t).mean(), # loss_function=partial(scaled_cost, loss_func=mse), updates_func=momentum, learning_rate=1e-02, learning_rate_changes_by_iteration={ 500: 5e-03 # 4000: 1e-03, # 6000: 5e-06, # 7000: 1e-06 # 2000: 5e-06 # 3000: 1e-05 # 7000: 5e-06, # 10000: 1e-06, # 15000: 5e-07, # 50000: 1e-07 }, do_save_activations=True ) def callback(net, epoch): net.source.reshape_target_to_2D = True net.plotter = MDNPlotter(net) net.generate_validation_data_and_set_shapes() net.loss_function = lambda x, t: mdn_nll(x, t).mean() net.learning_rate.set_value(1e-05) def exp_a(name): # 3 appliances global source source_dict_copy = deepcopy(source_dict) source_dict_copy['reshape_target_to_2D'] = False source = RealApplianceSource(**source_dict_copy) source.reshape_target_to_2D = False net_dict_copy = deepcopy(net_dict) net_dict_copy.update(dict( experiment_name=name, source=source )) N = 50 net_dict_copy['layers_config'] = [ { 'type': BidirectionalRecurrentLayer, 'num_units': N, 'gradient_steps': GRADIENT_STEPS, 'W_in_to_hid': Normal(std=1.), 'nonlinearity': tanh }, { 'type': FeaturePoolLayer, 'ds': 4, # number of feature maps to be pooled together 'axis': 1, # pool over the time axis 'pool_function': T.max }, { 'type': BidirectionalRecurrentLayer, 'num_units': N, 'gradient_steps': GRADIENT_STEPS, 'W_in_to_hid': Normal(std=1/sqrt(N)), 'nonlinearity': tanh }, { 'type': DenseLayer, 'W': Normal(std=1/sqrt(N)), 'num_units': source.n_outputs, 'nonlinearity': None } ] net_dict_copy['layer_changes'] = { 1001: { 'remove_from': -2, 'callback': callback, 'new_layers': [ { 'type': MixtureDensityLayer, 'num_units': source.n_outputs, 'num_components': 2 } ] } } net = Net(**net_dict_copy) return net def main(): # EXPERIMENTS = list('abcdefghijklmnopqrstuvwxyz') EXPERIMENTS = list('a') for experiment in EXPERIMENTS: full_exp_name = NAME + experiment func_call = init_experiment(PATH, experiment, full_exp_name) logger = logging.getLogger(full_exp_name) try: net = eval(func_call) run_experiment(net, epochs=None) except KeyboardInterrupt: logger.info("KeyboardInterrupt") break except Exception as exception: logger.exception("Exception") raise finally: logging.shutdown() if __name__ == "__main__": main()
mit
ARudiuk/mne-python
examples/inverse/plot_label_from_stc.py
31
3963
""" ================================================= Generate a functional label from source estimates ================================================= Threshold source estimates and produce a functional label. The label is typically the region of interest that contains high values. Here we compare the average time course in the anatomical label obtained by FreeSurfer segmentation and the average time course from the functional label. As expected the time course in the functional label yields higher values. """ # Author: Luke Bloy <luke.bloy@gmail.com> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.minimum_norm import read_inverse_operator, apply_inverse from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' subjects_dir = data_path + '/subjects' subject = 'sample' snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Compute a label/ROI based on the peak power between 80 and 120 ms. # The label bankssts-lh is used for the comparison. aparc_label_name = 'bankssts-lh' tmin, tmax = 0.080, 0.120 # Load data evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) src = inverse_operator['src'] # get the source space # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori='normal') # Make an STC in the time interval of interest and take the mean stc_mean = stc.copy().crop(tmin, tmax).mean() # use the stc_mean to generate a functional label # region growing is halted at 60% of the peak value within the # anatomical label / ROI specified by aparc_label_name label = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=subjects_dir, regexp=aparc_label_name)[0] stc_mean_label = stc_mean.in_label(label) data = np.abs(stc_mean_label.data) stc_mean_label.data[data < 0.6 * np.max(data)] = 0. func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=True, subjects_dir=subjects_dir, connected=True) # take first as func_labels are ordered based on maximum values in stc func_label = func_labels[0] # load the anatomical ROI for comparison anat_label = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=subjects_dir, regexp=aparc_label_name)[0] # extract the anatomical time course for each label stc_anat_label = stc.in_label(anat_label) pca_anat = stc.extract_label_time_course(anat_label, src, mode='pca_flip')[0] stc_func_label = stc.in_label(func_label) pca_func = stc.extract_label_time_course(func_label, src, mode='pca_flip')[0] # flip the pca so that the max power between tmin and tmax is positive pca_anat *= np.sign(pca_anat[np.argmax(np.abs(pca_anat))]) pca_func *= np.sign(pca_func[np.argmax(np.abs(pca_anat))]) ############################################################################### # plot the time courses.... plt.figure() plt.plot(1e3 * stc_anat_label.times, pca_anat, 'k', label='Anatomical %s' % aparc_label_name) plt.plot(1e3 * stc_func_label.times, pca_func, 'b', label='Functional %s' % aparc_label_name) plt.legend() plt.show() ############################################################################### # plot brain in 3D with PySurfer if available brain = stc_mean.plot(hemi='lh', subjects_dir=subjects_dir) brain.show_view('lateral') # show both labels brain.add_label(anat_label, borders=True, color='k') brain.add_label(func_label, borders=True, color='b')
bsd-3-clause
SU-ECE-17-7/hotspotter
hsviz/draw_func2.py
1
54605
''' Lots of functions for drawing and plotting visiony things ''' # TODO: New naming scheme # viz_<func_name> will clear everything. The current axes and fig: clf, cla. # Will add annotations # interact_<func_name> will clear everything and start user interactions. # show_<func_name> will always clear the current axes, but not fig: cla # Might # add annotates? # plot_<func_name> will not clear the axes or figure. More useful for graphs # draw_<func_name> same as plot for now. More useful for images from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile, printDBG) = __common__.init(__name__, '[df2]', DEBUG=False, initmpl=True) # Python from itertools import izip from os.path import splitext, split, join, normpath, exists import colorsys import itertools import pylab import sys import textwrap import time import warnings # Matplotlib / Qt import matplotlib import matplotlib as mpl # NOQA from matplotlib.collections import PatchCollection, LineCollection from matplotlib.font_manager import FontProperties from matplotlib.patches import Rectangle, Circle, FancyArrow from matplotlib.transforms import Affine2D from matplotlib.backends import backend_qt4 import matplotlib.pyplot as plt # Qt from PyQt4 import QtCore, QtGui from PyQt4.QtCore import Qt # Scientific import numpy as np import scipy.stats import cv2 # HotSpotter from hscom import helpers from hscom import tools from hscom.Printable import DynStruct #================ # GLOBALS #================ TMP_mevent = None QT4_WINS = [] plotWidget = None # GENERAL FONTS SMALLER = 8 SMALL = 10 MED = 12 LARGE = 14 #fpargs = dict(family=None, style=None, variant=None, stretch=None, fname=None) FONTS = DynStruct() FONTS.small = FontProperties(weight='light', size=SMALL) FONTS.smaller = FontProperties(weight='light', size=SMALLER) FONTS.med = FontProperties(weight='light', size=MED) FONTS.large = FontProperties(weight='light', size=LARGE) FONTS.medbold = FontProperties(weight='bold', size=MED) FONTS.largebold = FontProperties(weight='bold', size=LARGE) # SPECIFIC FONTS FONTS.legend = FONTS.small FONTS.figtitle = FONTS.med FONTS.axtitle = FONTS.med FONTS.subtitle = FONTS.med FONTS.xlabel = FONTS.smaller FONTS.ylabel = FONTS.small FONTS.relative = FONTS.smaller # COLORS ORANGE = np.array((255, 127, 0, 255)) / 255.0 RED = np.array((255, 0, 0, 255)) / 255.0 GREEN = np.array(( 0, 255, 0, 255)) / 255.0 BLUE = np.array(( 0, 0, 255, 255)) / 255.0 YELLOW = np.array((255, 255, 0, 255)) / 255.0 BLACK = np.array(( 0, 0, 0, 255)) / 255.0 WHITE = np.array((255, 255, 255, 255)) / 255.0 GRAY = np.array((127, 127, 127, 255)) / 255.0 DEEP_PINK = np.array((255, 20, 147, 255)) / 255.0 PINK = np.array((255, 100, 100, 255)) / 255.0 FALSE_RED = np.array((255, 51, 0, 255)) / 255.0 TRUE_GREEN = np.array(( 0, 255, 0, 255)) / 255.0 DARK_ORANGE = np.array((127, 63, 0, 255)) / 255.0 DARK_YELLOW = np.array((127, 127, 0, 255)) / 255.0 PURPLE = np.array((102, 0, 153, 255)) / 255.0 UNKNOWN_PURP = PURPLE # FIGURE GEOMETRY DPI = 80 #DPI = 160 #FIGSIZE = (24) # default windows fullscreen FIGSIZE_MED = (12, 6) FIGSIZE_SQUARE = (12, 12) FIGSIZE_BIGGER = (24, 12) FIGSIZE_HUGE = (32, 16) FIGSIZE = FIGSIZE_MED # Quality drawings #FIGSIZE = FIGSIZE_SQUARE #DPI = 120 tile_within = (-1, 30, 969, 1041) if helpers.get_computer_name() == 'Ooo': TILE_WITHIN = (-1912, 30, -969, 1071) # DEFAULTS. (TODO: Can these be cleaned up?) DISTINCT_COLORS = True # and False DARKEN = None ELL_LINEWIDTH = 1.5 if DISTINCT_COLORS: ELL_ALPHA = .6 LINE_ALPHA = .35 else: ELL_ALPHA = .4 LINE_ALPHA = .4 LINE_ALPHA_OVERRIDE = helpers.get_arg('--line-alpha-override', type_=float, default=None) ELL_ALPHA_OVERRIDE = helpers.get_arg('--ell-alpha-override', type_=float, default=None) #LINE_ALPHA_OVERRIDE = None #ELL_ALPHA_OVERRIDE = None ELL_COLOR = BLUE LINE_COLOR = RED LINE_WIDTH = 1.4 SHOW_LINES = True # True SHOW_ELLS = True POINT_SIZE = 2 base_fnum = 9001 def next_fnum(): global base_fnum base_fnum += 1 return base_fnum def my_prefs(): global LINE_COLOR global ELL_COLOR global ELL_LINEWIDTH global ELL_ALPHA LINE_COLOR = (1, 0, 0) ELL_COLOR = (0, 0, 1) ELL_LINEWIDTH = 2 ELL_ALPHA = .5 def execstr_global(): execstr = ['global' + key for key in globals().keys()] return execstr def register_matplotlib_widget(plotWidget_): 'talks to PyQt4 guis' global plotWidget plotWidget = plotWidget_ #fig = plotWidget.figure #axes_list = fig.get_axes() #ax = axes_list[0] #plt.sca(ax) def unregister_qt4_win(win): global QT4_WINS if win == 'all': QT4_WINS = [] def register_qt4_win(win): global QT4_WINS QT4_WINS.append(win) def OooScreen2(): nRows = 1 nCols = 1 x_off = 30 * 4 y_off = 30 * 4 x_0 = -1920 y_0 = 30 w = (1912 - x_off) / nRows h = (1080 - y_off) / nCols return dict(num_rc=(1, 1), wh=(w, h), xy_off=(x_0, y_0), wh_off=(0, 10), row_first=True, no_tile=False) def deterministic_shuffle(list_): randS = int(np.random.rand() * np.uint(0 - 2) / 2) np.random.seed(len(list_)) np.random.shuffle(list_) np.random.seed(randS) def distinct_colors(N, brightness=.878): # http://blog.jianhuashao.com/2011/09/generate-n-distinct-colors.html sat = brightness val = brightness HSV_tuples = [(x * 1.0 / N, sat, val) for x in xrange(N)] RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples) deterministic_shuffle(RGB_tuples) return RGB_tuples def add_alpha(colors): return [list(color) + [1] for color in colors] def _axis_xy_width_height(ax, xaug=0, yaug=0, waug=0, haug=0): 'gets geometry of a subplot' autoAxis = ax.axis() xy = (autoAxis[0] + xaug, autoAxis[2] + yaug) width = (autoAxis[1] - autoAxis[0]) + waug height = (autoAxis[3] - autoAxis[2]) + haug return xy, width, height def draw_border(ax, color=GREEN, lw=2, offset=None): 'draws rectangle border around a subplot' xy, width, height = _axis_xy_width_height(ax, -.7, -.2, 1, .4) if offset is not None: xoff, yoff = offset xy = [xoff, yoff] height = - height - yoff width = width - xoff rect = matplotlib.patches.Rectangle(xy, width, height, lw=lw) rect = ax.add_patch(rect) rect.set_clip_on(False) rect.set_fill(False) rect.set_edgecolor(color) def draw_roi(roi, label=None, bbox_color=(1, 0, 0), lbl_bgcolor=(0, 0, 0), lbl_txtcolor=(1, 1, 1), theta=0, ax=None): if ax is None: ax = gca() (rx, ry, rw, rh) = roi #cos_ = np.cos(theta) #sin_ = np.sin(theta) #rot_t = Affine2D([( cos_, -sin_, 0), #( sin_, cos_, 0), #( 0, 0, 1)]) #scale_t = Affine2D([( rw, 0, 0), #( 0, rh, 0), #( 0, 0, 1)]) #trans_t = Affine2D([( 1, 0, rx + rw / 2), #( 0, 1, ry + rh / 2), #( 0, 0, 1)]) #t_end = scale_t + rot_t + trans_t + t_start # Transformations are specified in backwards order. trans_roi = Affine2D() trans_roi.scale(rw, rh) trans_roi.rotate(theta) trans_roi.translate(rx + rw / 2, ry + rh / 2) t_end = trans_roi + ax.transData bbox = matplotlib.patches.Rectangle((-.5, -.5), 1, 1, lw=2, transform=t_end) arw_x, arw_y, arw_dx, arw_dy = (-0.5, -0.5, 1.0, 0.0) arrowargs = dict(head_width=.1, transform=t_end, length_includes_head=True) arrow = FancyArrow(arw_x, arw_y, arw_dx, arw_dy, **arrowargs) bbox.set_fill(False) #bbox.set_transform(trans) bbox.set_edgecolor(bbox_color) arrow.set_edgecolor(bbox_color) arrow.set_facecolor(bbox_color) ax.add_patch(bbox) ax.add_patch(arrow) #ax.add_patch(arrow2) if label is not None: ax_absolute_text(rx, ry, label, ax=ax, horizontalalignment='center', verticalalignment='center', color=lbl_txtcolor, backgroundcolor=lbl_bgcolor) # ---- GENERAL FIGURE COMMANDS ---- def sanatize_img_fname(fname): fname_clean = fname search_replace_list = [(' ', '_'), ('\n', '--'), ('\\', ''), ('/', '')] for old, new in search_replace_list: fname_clean = fname_clean.replace(old, new) fname_noext, ext = splitext(fname_clean) fname_clean = fname_noext + ext.lower() # Check for correct extensions if not ext.lower() in helpers.IMG_EXTENSIONS: fname_clean += '.png' return fname_clean def sanatize_img_fpath(fpath): [dpath, fname] = split(fpath) fname_clean = sanatize_img_fname(fname) fpath_clean = join(dpath, fname_clean) fpath_clean = normpath(fpath_clean) return fpath_clean def set_geometry(fnum, x, y, w, h): fig = get_fig(fnum) qtwin = fig.canvas.manager.window qtwin.setGeometry(x, y, w, h) def get_geometry(fnum): fig = get_fig(fnum) qtwin = fig.canvas.manager.window (x1, y1, x2, y2) = qtwin.geometry().getCoords() (x, y, w, h) = (x1, y1, x2 - x1, y2 - y1) return (x, y, w, h) def get_screen_info(): from PyQt4 import Qt, QtGui # NOQA desktop = QtGui.QDesktopWidget() mask = desktop.mask() # NOQA layout_direction = desktop.layoutDirection() # NOQA screen_number = desktop.screenNumber() # NOQA normal_geometry = desktop.normalGeometry() # NOQA num_screens = desktop.screenCount() # NOQA avail_rect = desktop.availableGeometry() # NOQA screen_rect = desktop.screenGeometry() # NOQA QtGui.QDesktopWidget().availableGeometry().center() # NOQA normal_geometry = desktop.normalGeometry() # NOQA def get_all_figures(): all_figures_ = [manager.canvas.figure for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] all_figures = [] # Make sure you dont show figures that this module closed for fig in iter(all_figures_): if not 'df2_closed' in fig.__dict__.keys() or not fig.df2_closed: all_figures.append(fig) # Return all the figures sorted by their number all_figures = sorted(all_figures, key=lambda fig: fig.number) return all_figures def get_all_qt4_wins(): return QT4_WINS def all_figures_show(): if plotWidget is not None: plotWidget.figure.show() plotWidget.figure.canvas.draw() for fig in iter(get_all_figures()): time.sleep(.1) fig.show() fig.canvas.draw() def all_figures_tight_layout(): for fig in iter(get_all_figures()): fig.tight_layout() #adjust_subplots() time.sleep(.1) def get_monitor_geom(monitor_num=0): from PyQt4 import QtGui # NOQA desktop = QtGui.QDesktopWidget() rect = desktop.availableGeometry() geom = (rect.x(), rect.y(), rect.width(), rect.height()) return geom def golden_wh(x): 'returns a width / height with a golden aspect ratio' return map(int, map(round, (x * .618, x * .312))) def all_figures_tile(num_rc=(3, 4), wh=1000, xy_off=(0, 0), wh_off=(0, 10), row_first=True, no_tile=False, override1=False): 'Lays out all figures in a grid. if wh is a scalar, a golden ratio is used' # RCOS TODO: # I want this function to layout all the figures and qt windows within the # bounds of a rectangle. (taken from the get_monitor_geom, or specified by # the user i.e. left half of monitor 0). It should lay them out # rectangularly and choose figure sizes such that all of them will fit. if no_tile: return if not np.iterable(wh): wh = golden_wh(wh) all_figures = get_all_figures() all_qt4wins = get_all_qt4_wins() if override1: if len(all_figures) == 1: fig = all_figures[0] win = fig.canvas.manager.window win.setGeometry(0, 0, 900, 900) update() return #nFigs = len(all_figures) + len(all_qt4_wins) num_rows, num_cols = num_rc w, h = wh x_off, y_off = xy_off w_off, h_off = wh_off x_pad, y_pad = (0, 0) printDBG('[df2] Tile all figures: ') printDBG('[df2] wh = %r' % ((w, h),)) printDBG('[df2] xy_offsets = %r' % ((x_off, y_off),)) printDBG('[df2] wh_offsets = %r' % ((w_off, h_off),)) printDBG('[df2] xy_pads = %r' % ((x_pad, y_pad),)) if sys.platform == 'win32': h_off += 0 w_off += 40 x_off += 40 y_off += 40 x_pad += 0 y_pad += 100 def position_window(i, win): isqt4_mpl = isinstance(win, backend_qt4.MainWindow) isqt4_back = isinstance(win, QtGui.QMainWindow) if not isqt4_mpl and not isqt4_back: raise NotImplementedError('%r-th Backend %r is not a Qt Window' % (i, win)) if row_first: y = (i % num_rows) * (h + h_off) + 40 x = (int(i / num_rows)) * (w + w_off) + x_pad else: x = (i % num_cols) * (w + w_off) + 40 y = (int(i / num_cols)) * (h + h_off) + y_pad x += x_off y += y_off win.setGeometry(x, y, w, h) ioff = 0 for i, win in enumerate(all_qt4wins): position_window(i, win) ioff += 1 for i, fig in enumerate(all_figures): win = fig.canvas.manager.window position_window(i + ioff, win) def all_figures_bring_to_front(): all_figures = get_all_figures() for fig in iter(all_figures): bring_to_front(fig) def close_all_figures(): all_figures = get_all_figures() for fig in iter(all_figures): close_figure(fig) def close_figure(fig): fig.clf() fig.df2_closed = True qtwin = fig.canvas.manager.window qtwin.close() def bring_to_front(fig): #what is difference between show and show normal? qtwin = fig.canvas.manager.window qtwin.raise_() qtwin.activateWindow() qtwin.setWindowFlags(Qt.WindowStaysOnTopHint) qtwin.setWindowFlags(Qt.WindowFlags(0)) qtwin.show() def show(): all_figures_show() all_figures_bring_to_front() plt.show() def reset(): close_all_figures() def draw(): all_figures_show() def update(): draw() all_figures_bring_to_front() def present(*args, **kwargs): 'execing present should cause IPython magic' print('[df2] Presenting figures...') with warnings.catch_warnings(): warnings.simplefilter("ignore") all_figures_tile(*args, **kwargs) all_figures_show() all_figures_bring_to_front() # Return an exec string execstr = helpers.ipython_execstr() execstr += textwrap.dedent(''' if not embedded: print('[df2] Presenting in normal shell.') print('[df2] ... plt.show()') plt.show() ''') return execstr def save_figure(fnum=None, fpath=None, usetitle=False, overwrite=True): #import warnings #warnings.simplefilter("error") # Find the figure if fnum is None: fig = gcf() else: fig = plt.figure(fnum, figsize=FIGSIZE, dpi=DPI) # Enforce inches and DPI fig.set_size_inches(FIGSIZE[0], FIGSIZE[1]) fnum = fig.number if fpath is None: # Find the title fpath = sanatize_img_fname(fig.canvas.get_window_title()) if usetitle: title = sanatize_img_fname(fig.canvas.get_window_title()) fpath = join(fpath, title) # Add in DPI information fpath_noext, ext = splitext(fpath) size_suffix = '_DPI=%r_FIGSIZE=%d,%d' % (DPI, FIGSIZE[0], FIGSIZE[1]) fpath = fpath_noext + size_suffix + ext # Sanatize the filename fpath_clean = sanatize_img_fpath(fpath) #fname_clean = split(fpath_clean)[1] print('[df2] save_figure() %r' % (fpath_clean,)) #adjust_subplots() with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=DeprecationWarning) if not exists(fpath_clean) or overwrite: fig.savefig(fpath_clean, dpi=DPI) def set_ticks(xticks, yticks): ax = gca() ax.set_xticks(xticks) ax.set_yticks(yticks) def set_xticks(tick_set): ax = gca() ax.set_xticks(tick_set) def set_yticks(tick_set): ax = gca() ax.set_yticks(tick_set) def set_xlabel(lbl, ax=None): if ax is None: ax = gca() ax.set_xlabel(lbl, fontproperties=FONTS.xlabel) def set_title(title, ax=None): if ax is None: ax = gca() ax.set_title(title, fontproperties=FONTS.axtitle) def set_ylabel(lbl): ax = gca() ax.set_ylabel(lbl, fontproperties=FONTS.xlabel) def plot(*args, **kwargs): return plt.plot(*args, **kwargs) def plot2(x_data, y_data, marker='o', title_pref='', x_label='x', y_label='y', *args, **kwargs): do_plot = True ax = gca() if len(x_data) != len(y_data): warnstr = '[df2] ! Warning: len(x_data) != len(y_data). Cannot plot2' warnings.warn(warnstr) draw_text(warnstr) do_plot = False if len(x_data) == 0: warnstr = '[df2] ! Warning: len(x_data) == 0. Cannot plot2' warnings.warn(warnstr) draw_text(warnstr) do_plot = False if do_plot: ax.plot(x_data, y_data, marker, *args, **kwargs) min_ = min(x_data.min(), y_data.min()) max_ = max(x_data.max(), y_data.max()) # Equal aspect ratio ax.set_xlim(min_, max_) ax.set_ylim(min_, max_) ax.set_aspect('equal') ax.set_xlabel(x_label, fontproperties=FONTS.xlabel) ax.set_ylabel(y_label, fontproperties=FONTS.xlabel) ax.set_title(title_pref + ' ' + x_label + ' vs ' + y_label, fontproperties=FONTS.axtitle) def adjust_subplots_xlabels(): adjust_subplots(left=.03, right=.97, bottom=.2, top=.9, hspace=.15) def adjust_subplots_xylabels(): adjust_subplots(left=.03, right=1, bottom=.1, top=.9, hspace=.15) def adjust_subplots_safe(left=.1, right=.9, bottom=.1, top=.9, wspace=.3, hspace=.5): adjust_subplots(left, bottom, right, top, wspace, hspace) def adjust_subplots(left=0.02, bottom=0.02, right=0.98, top=0.90, wspace=0.1, hspace=0.15): ''' left = 0.125 # the left side of the subplots of the figure right = 0.9 # the right side of the subplots of the figure bottom = 0.1 # the bottom of the subplots of the figure top = 0.9 # the top of the subplots of the figure wspace = 0.2 # the amount of width reserved for blank space between subplots hspace = 0.2 ''' #print('[df2] adjust_subplots(%r)' % locals()) plt.subplots_adjust(left, bottom, right, top, wspace, hspace) #======================= # TEXT FUNCTIONS # TODO: I have too many of these. Need to consolidate #======================= def upperleft_text(txt): txtargs = dict(horizontalalignment='left', verticalalignment='top', #fontsize='smaller', #fontweight='ultralight', backgroundcolor=(0, 0, 0, .5), color=ORANGE) ax_relative_text(.02, .02, txt, **txtargs) def upperright_text(txt, offset=None): txtargs = dict(horizontalalignment='right', verticalalignment='top', #fontsize='smaller', #fontweight='ultralight', backgroundcolor=(0, 0, 0, .5), color=ORANGE, offset=offset) ax_relative_text(.98, .02, txt, **txtargs) def lowerright_text(txt): txtargs = dict(horizontalalignment='right', verticalalignment='top', #fontsize='smaller', #fontweight='ultralight', backgroundcolor=(0, 0, 0, .5), color=ORANGE) ax_relative_text(.98, .92, txt, **txtargs) def absolute_lbl(x_, y_, txt, roffset=(-.02, -.02), **kwargs): txtargs = dict(horizontalalignment='right', verticalalignment='top', backgroundcolor=(0, 0, 0, .5), color=ORANGE, **kwargs) ax_absolute_text(x_, y_, txt, roffset=roffset, **txtargs) def ax_relative_text(x, y, txt, ax=None, offset=None, **kwargs): if ax is None: ax = gca() xy, width, height = _axis_xy_width_height(ax) x_, y_ = ((xy[0]) + x * width, (xy[1] + height) - y * height) if offset is not None: xoff, yoff = offset x_ += xoff y_ += yoff ax_absolute_text(x_, y_, txt, ax=ax, **kwargs) def ax_absolute_text(x_, y_, txt, ax=None, roffset=None, **kwargs): if ax is None: ax = gca() if 'fontproperties' in kwargs: kwargs['fontproperties'] = FONTS.relative if roffset is not None: xroff, yroff = roffset xy, width, height = _axis_xy_width_height(ax) x_ += xroff * width y_ += yroff * height ax.text(x_, y_, txt, **kwargs) def fig_relative_text(x, y, txt, **kwargs): kwargs['horizontalalignment'] = 'center' kwargs['verticalalignment'] = 'center' fig = gcf() #xy, width, height = _axis_xy_width_height(ax) #x_, y_ = ((xy[0]+width)+x*width, (xy[1]+height)-y*height) fig.text(x, y, txt, **kwargs) def draw_text(text_str, rgb_textFG=(0, 0, 0), rgb_textBG=(1, 1, 1)): ax = gca() xy, width, height = _axis_xy_width_height(ax) text_x = xy[0] + (width / 2) text_y = xy[1] + (height / 2) ax.text(text_x, text_y, text_str, horizontalalignment='center', verticalalignment='center', color=rgb_textFG, backgroundcolor=rgb_textBG) def set_figtitle(figtitle, subtitle='', forcefignum=True, incanvas=True): if figtitle is None: figtitle = '' fig = gcf() if incanvas: if subtitle != '': subtitle = '\n' + subtitle fig.suptitle(figtitle + subtitle, fontsize=14, fontweight='bold') #fig.suptitle(figtitle, x=.5, y=.98, fontproperties=FONTS.figtitle) #fig_relative_text(.5, .96, subtitle, fontproperties=FONTS.subtitle) else: fig.suptitle('') window_figtitle = ('fig(%d) ' % fig.number) + figtitle fig.canvas.set_window_title(window_figtitle) def convert_keypress_event_mpl_to_qt4(mevent): global TMP_mevent TMP_mevent = mevent # Grab the key from the mpl.KeyPressEvent key = mevent.key print('[df2] convert event mpl -> qt4') print('[df2] key=%r' % key) # dicts modified from backend_qt4.py mpl2qtkey = {'control': Qt.Key_Control, 'shift': Qt.Key_Shift, 'alt': Qt.Key_Alt, 'super': Qt.Key_Meta, 'enter': Qt.Key_Return, 'left': Qt.Key_Left, 'up': Qt.Key_Up, 'right': Qt.Key_Right, 'down': Qt.Key_Down, 'escape': Qt.Key_Escape, 'f1': Qt.Key_F1, 'f2': Qt.Key_F2, 'f3': Qt.Key_F3, 'f4': Qt.Key_F4, 'f5': Qt.Key_F5, 'f6': Qt.Key_F6, 'f7': Qt.Key_F7, 'f8': Qt.Key_F8, 'f9': Qt.Key_F9, 'f10': Qt.Key_F10, 'f11': Qt.Key_F11, 'f12': Qt.Key_F12, 'home': Qt.Key_Home, 'end': Qt.Key_End, 'pageup': Qt.Key_PageUp, 'pagedown': Qt.Key_PageDown} # Reverse the control and super (aka cmd/apple) keys on OSX if sys.platform == 'darwin': mpl2qtkey.update({'super': Qt.Key_Control, 'control': Qt.Key_Meta, }) # Try to reconstruct QtGui.KeyEvent type_ = QtCore.QEvent.Type(QtCore.QEvent.KeyPress) # The type should always be KeyPress text = '' # Try to extract the original modifiers modifiers = QtCore.Qt.NoModifier # initialize to no modifiers if key.find(u'ctrl+') >= 0: modifiers = modifiers | QtCore.Qt.ControlModifier key = key.replace(u'ctrl+', u'') print('[df2] has ctrl modifier') text += 'Ctrl+' if key.find(u'alt+') >= 0: modifiers = modifiers | QtCore.Qt.AltModifier key = key.replace(u'alt+', u'') print('[df2] has alt modifier') text += 'Alt+' if key.find(u'super+') >= 0: modifiers = modifiers | QtCore.Qt.MetaModifier key = key.replace(u'super+', u'') print('[df2] has super modifier') text += 'Super+' if key.isupper(): modifiers = modifiers | QtCore.Qt.ShiftModifier print('[df2] has shift modifier') text += 'Shift+' # Try to extract the original key try: if key in mpl2qtkey: key_ = mpl2qtkey[key] else: key_ = ord(key.upper()) # Qt works with uppercase keys text += key.upper() except Exception as ex: print('[df2] ERROR key=%r' % key) print('[df2] ERROR %r' % ex) raise autorep = False # default false count = 1 # default 1 text = QtCore.QString(text) # The text is somewhat arbitrary # Create the QEvent print('----------------') print('[df2] Create event') print('[df2] type_ = %r' % type_) print('[df2] text = %r' % text) print('[df2] modifiers = %r' % modifiers) print('[df2] autorep = %r' % autorep) print('[df2] count = %r ' % count) print('----------------') qevent = QtGui.QKeyEvent(type_, key_, modifiers, text, autorep, count) return qevent def test_build_qkeyevent(): import draw_func2 as df2 qtwin = df2.QT4_WINS[0] # This reconstructs an test mplevent canvas = df2.figure(1).canvas mevent = matplotlib.backend_bases.KeyEvent('key_press_event', canvas, u'ctrl+p', x=672, y=230.0) qevent = df2.convert_keypress_event_mpl_to_qt4(mevent) app = qtwin.backend.app app.sendEvent(qtwin.ui, mevent) #type_ = QtCore.QEvent.Type(QtCore.QEvent.KeyPress) # The type should always be KeyPress #text = QtCore.QString('A') # The text is somewhat arbitrary #modifiers = QtCore.Qt.NoModifier # initialize to no modifiers #modifiers = modifiers | QtCore.Qt.ControlModifier #modifiers = modifiers | QtCore.Qt.AltModifier #key_ = ord('A') # Qt works with uppercase keys #autorep = False # default false #count = 1 # default 1 #qevent = QtGui.QKeyEvent(type_, key_, modifiers, text, autorep, count) return qevent # This actually doesn't matter def on_key_press_event(event): 'redirects keypress events to main window' global QT4_WINS print('[df2] %r' % event) print('[df2] %r' % str(event.__dict__)) for qtwin in QT4_WINS: qevent = convert_keypress_event_mpl_to_qt4(event) app = qtwin.backend.app print('[df2] attempting to send qevent to qtwin') app.sendEvent(qtwin, qevent) # TODO: FINISH ME #PyQt4.QtGui.QKeyEvent #qtwin.keyPressEvent(event) #fig.canvas.manager.window.keyPressEvent() def customize_figure(fig, docla): if not 'user_stat_list' in fig.__dict__.keys() or docla: fig.user_stat_list = [] fig.user_notes = [] # We dont need to catch keypress events because you just need to set it as # an application level shortcut # Catch key press events #key_event_cbid = fig.__dict__.get('key_event_cbid', None) #if key_event_cbid is not None: #fig.canvas.mpl_disconnect(key_event_cbid) #fig.key_event_cbid = fig.canvas.mpl_connect('key_press_event', on_key_press_event) fig.df2_closed = False def gcf(): if plotWidget is not None: #print('is plotwidget visible = %r' % plotWidget.isVisible()) fig = plotWidget.figure return fig return plt.gcf() def gca(): if plotWidget is not None: #print('is plotwidget visible = %r' % plotWidget.isVisible()) axes_list = plotWidget.figure.get_axes() current = 0 ax = axes_list[current] return ax return plt.gca() def cla(): return plt.cla() def clf(): return plt.clf() def get_fig(fnum=None): printDBG('[df2] get_fig(fnum=%r)' % fnum) fig_kwargs = dict(figsize=FIGSIZE, dpi=DPI) if plotWidget is not None: return gcf() if fnum is None: try: fig = gcf() except Exception as ex: printDBG('[df2] get_fig(): ex=%r' % ex) fig = plt.figure(**fig_kwargs) fnum = fig.number else: try: fig = plt.figure(fnum, **fig_kwargs) except Exception as ex: print(repr(ex)) warnings.warn(repr(ex)) fig = gcf() return fig def get_ax(fnum=None, pnum=None): figure(fnum=fnum, pnum=pnum) ax = gca() return ax def figure(fnum=None, docla=False, title=None, pnum=(1, 1, 1), figtitle=None, doclf=False, **kwargs): ''' fnum = fignum = figure number pnum = plotnum = plot tuple ''' #matplotlib.pyplot.xkcd() fig = get_fig(fnum) axes_list = fig.get_axes() # Ensure my customized settings customize_figure(fig, docla) # Convert pnum to tuple format if tools.is_int(pnum): nr = pnum // 100 nc = pnum // 10 - (nr * 10) px = pnum - (nr * 100) - (nc * 10) pnum = (nr, nc, px) if doclf: # a bit hacky. Need to rectify docla and doclf fig.clf() # Get the subplot if docla or len(axes_list) == 0: printDBG('[df2] *** NEW FIGURE %r.%r ***' % (fnum, pnum)) if not pnum is None: #ax = plt.subplot(*pnum) ax = fig.add_subplot(*pnum) ax.cla() else: ax = gca() else: printDBG('[df2] *** OLD FIGURE %r.%r ***' % (fnum, pnum)) if not pnum is None: ax = plt.subplot(*pnum) # fig.add_subplot fails here #ax = fig.add_subplot(*pnum) else: ax = gca() #ax = axes_list[0] # Set the title if not title is None: ax = gca() ax.set_title(title, fontproperties=FONTS.axtitle) # Add title to figure if figtitle is None and pnum == (1, 1, 1): figtitle = title if not figtitle is None: set_figtitle(figtitle, incanvas=False) return fig def plot_pdf(data, draw_support=True, scale_to=None, label=None, color=0, nYTicks=3): fig = gcf() ax = gca() data = np.array(data) if len(data) == 0: warnstr = '[df2] ! Warning: len(data) = 0. Cannot visualize pdf' warnings.warn(warnstr) draw_text(warnstr) return bw_factor = .05 if isinstance(color, (int, float)): colorx = color line_color = plt.get_cmap('gist_rainbow')(colorx) else: line_color = color # Estimate a pdf data_pdf = estimate_pdf(data, bw_factor) # Get probability of seen data prob_x = data_pdf(data) # Get probability of unseen data data x_data = np.linspace(0, data.max(), 500) y_data = data_pdf(x_data) # Scale if requested if not scale_to is None: scale_factor = scale_to / y_data.max() y_data *= scale_factor prob_x *= scale_factor #Plot the actual datas on near the bottom perterbed in Y if draw_support: pdfrange = prob_x.max() - prob_x.min() perb = (np.random.randn(len(data))) * pdfrange / 30. preb_y_data = np.abs([pdfrange / 50. for _ in data] + perb) ax.plot(data, preb_y_data, 'o', color=line_color, figure=fig, alpha=.1) # Plot the pdf (unseen data) ax.plot(x_data, y_data, color=line_color, label=label) if nYTicks is not None: yticks = np.linspace(min(y_data), max(y_data), nYTicks) ax.set_yticks(yticks) def estimate_pdf(data, bw_factor): try: data_pdf = scipy.stats.gaussian_kde(data, bw_factor) data_pdf.covariance_factor = bw_factor except Exception as ex: print('[df2] ! Exception while estimating kernel density') print('[df2] data=%r' % (data,)) print('[df2] ex=%r' % (ex,)) raise return data_pdf def show_histogram(data, bins=None, **kwargs): print('[df2] show_histogram()') dmin = int(np.floor(data.min())) dmax = int(np.ceil(data.max())) if bins is None: bins = dmax - dmin fig = figure(**kwargs) ax = gca() ax.hist(data, bins=bins, range=(dmin, dmax)) #help(np.bincount) fig.show() def show_signature(sig, **kwargs): fig = figure(**kwargs) plt.plot(sig) fig.show() def plot_stems(x_data=None, y_data=None): if y_data is not None and x_data is None: x_data = np.arange(len(y_data)) pass if len(x_data) != len(y_data): print('[df2] WARNING plot_stems(): len(x_data)!=len(y_data)') if len(x_data) == 0: print('[df2] WARNING plot_stems(): len(x_data)=len(y_data)=0') x_data_ = np.array(x_data) y_data_ = np.array(y_data) x_data_sort = x_data_[y_data_.argsort()[::-1]] y_data_sort = y_data_[y_data_.argsort()[::-1]] markerline, stemlines, baseline = pylab.stem(x_data_sort, y_data_sort, linefmt='-') pylab.setp(markerline, 'markerfacecolor', 'b') pylab.setp(baseline, 'linewidth', 0) ax = gca() ax.set_xlim(min(x_data) - 1, max(x_data) + 1) ax.set_ylim(min(y_data) - 1, max(max(y_data), max(x_data)) + 1) def plot_sift_signature(sift, title='', fnum=None, pnum=None): figure(fnum=fnum, pnum=pnum) ax = gca() plot_bars(sift, 16) ax.set_xlim(0, 128) ax.set_ylim(0, 256) space_xticks(9, 16) space_yticks(5, 64) ax.set_title(title) dark_background(ax) return ax def dark_background(ax=None, doubleit=False): if ax is None: ax = gca() xy, width, height = _axis_xy_width_height(ax) if doubleit: halfw = (doubleit) * (width / 2) halfh = (doubleit) * (height / 2) xy = (xy[0] - halfw, xy[1] - halfh) width *= (doubleit + 1) height *= (doubleit + 1) rect = matplotlib.patches.Rectangle(xy, width, height, lw=0, zorder=0) rect.set_clip_on(True) rect.set_fill(True) rect.set_color(BLACK * .9) rect = ax.add_patch(rect) def space_xticks(nTicks=9, spacing=16, ax=None): if ax is None: ax = gca() ax.set_xticks(np.arange(nTicks) * spacing) small_xticks(ax) def space_yticks(nTicks=9, spacing=32, ax=None): if ax is None: ax = gca() ax.set_yticks(np.arange(nTicks) * spacing) small_yticks(ax) def small_xticks(ax=None): for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(8) def small_yticks(ax=None): for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(8) def plot_bars(y_data, nColorSplits=1): width = 1 nDims = len(y_data) nGroup = nDims // nColorSplits ori_colors = distinct_colors(nColorSplits) x_data = np.arange(nDims) ax = gca() for ix in xrange(nColorSplits): xs = np.arange(nGroup) + (nGroup * ix) color = ori_colors[ix] x_dat = x_data[xs] y_dat = y_data[xs] ax.bar(x_dat, y_dat, width, color=color, edgecolor=np.array(color) * .8) def phantom_legend_label(label, color, loc='upper right'): 'adds a legend label without displaying an actor' pass #phantom_actor = plt.Circle((0, 0), 1, fc=color, prop=FONTS.legend, loc=loc) #plt.legend(phant_actor, label, framealpha=.2) #plt.legend(*zip(*legend_tups), framealpha=.2) #legend_tups = [] #legend_tups.append((phantom_actor, label)) def legend(loc='upper right'): ax = gca() ax.legend(prop=FONTS.legend, loc=loc) def plot_histpdf(data, label=None, draw_support=False, nbins=10): freq, _ = plot_hist(data, nbins=nbins) plot_pdf(data, draw_support=draw_support, scale_to=freq.max(), label=label) def plot_hist(data, bins=None, nbins=10, weights=None): if isinstance(data, list): data = np.array(data) if bins is None: dmin = data.min() dmax = data.max() bins = dmax - dmin ax = gca() freq, bins_, patches = ax.hist(data, bins=nbins, weights=weights, range=(dmin, dmax)) return freq, bins_ def variation_trunctate(data): ax = gca() data = np.array(data) if len(data) == 0: warnstr = '[df2] ! Warning: len(data) = 0. Cannot variation_truncate' warnings.warn(warnstr) return trunc_max = data.mean() + data.std() * 2 trunc_min = np.floor(data.min()) ax.set_xlim(trunc_min, trunc_max) #trunc_xticks = np.linspace(0, int(trunc_max),11) #trunc_xticks = trunc_xticks[trunc_xticks >= trunc_min] #trunc_xticks = np.append([int(trunc_min)], trunc_xticks) #no_zero_yticks = ax.get_yticks()[ax.get_yticks() > 0] #ax.set_xticks(trunc_xticks) #ax.set_yticks(no_zero_yticks) #_----------------- HELPERS ^^^ --------- # ---- IMAGE CREATION FUNCTIONS ---- @tools.debug_exception def draw_sift(desc, kp=None): # TODO: There might be a divide by zero warning in here. ''' desc = np.random.rand(128) desc = desc / np.sqrt((desc**2).sum()) desc = np.round(desc * 255) ''' # This is draw, because it is an overlay ax = gca() tau = 2 * np.pi DSCALE = .25 XYSCALE = .5 XYSHIFT = -.75 ORI_SHIFT = 0 # -tau #1/8 * tau # SIFT CONSTANTS NORIENTS = 8 NX = 4 NY = 4 NBINS = NX * NY def cirlce_rad2xy(radians, mag): return np.cos(radians) * mag, np.sin(radians) * mag discrete_ori = (np.arange(0, NORIENTS) * (tau / NORIENTS) + ORI_SHIFT) # Build list of plot positions # Build an "arm" for each sift measurement arm_mag = desc / 255.0 arm_ori = np.tile(discrete_ori, (NBINS, 1)).flatten() # The offset x,y's for each sift measurment arm_dxy = np.array(zip(*cirlce_rad2xy(arm_ori, arm_mag))) yxt_gen = itertools.product(xrange(NY), xrange(NX), xrange(NORIENTS)) yx_gen = itertools.product(xrange(NY), xrange(NX)) # Transform the drawing of the SIFT descriptor to the its elliptical patch axTrans = ax.transData kpTrans = None if kp is None: kp = [0, 0, 1, 0, 1] kp = np.array(kp) kpT = kp.T x, y, a, c, d = kpT[:, 0] kpTrans = Affine2D([( a, 0, x), ( c, d, y), ( 0, 0, 1)]) axTrans = ax.transData # Draw 8 directional arms in each of the 4x4 grid cells arrow_patches = [] arrow_patches2 = [] for y, x, t in yxt_gen: index = y * NX * NORIENTS + x * NORIENTS + t (dx, dy) = arm_dxy[index] arw_x = x * XYSCALE + XYSHIFT arw_y = y * XYSCALE + XYSHIFT arw_dy = dy * DSCALE * 1.5 # scale for viz Hack arw_dx = dx * DSCALE * 1.5 #posA = (arw_x, arw_y) #posB = (arw_x+arw_dx, arw_y+arw_dy) _args = [arw_x, arw_y, arw_dx, arw_dy] _kwargs = dict(head_width=.0001, transform=kpTrans, length_includes_head=False) arrow_patches += [FancyArrow(*_args, **_kwargs)] arrow_patches2 += [FancyArrow(*_args, **_kwargs)] # Draw circles around each of the 4x4 grid cells circle_patches = [] for y, x in yx_gen: circ_xy = (x * XYSCALE + XYSHIFT, y * XYSCALE + XYSHIFT) circ_radius = DSCALE circle_patches += [Circle(circ_xy, circ_radius, transform=kpTrans)] # Efficiently draw many patches with PatchCollections circ_collection = PatchCollection(circle_patches) circ_collection.set_facecolor('none') circ_collection.set_transform(axTrans) circ_collection.set_edgecolor(BLACK) circ_collection.set_alpha(.5) # Body of arrows arw_collection = PatchCollection(arrow_patches) arw_collection.set_transform(axTrans) arw_collection.set_linewidth(.5) arw_collection.set_color(RED) arw_collection.set_alpha(1) # Border of arrows arw_collection2 = matplotlib.collections.PatchCollection(arrow_patches2) arw_collection2.set_transform(axTrans) arw_collection2.set_linewidth(1) arw_collection2.set_color(BLACK) arw_collection2.set_alpha(1) # Add artists to axes ax.add_collection(circ_collection) ax.add_collection(arw_collection2) ax.add_collection(arw_collection) def feat_scores_to_color(fs, cmap_='hot'): assert len(fs.shape) == 1, 'score must be 1d' cmap = plt.get_cmap(cmap_) mins = fs.min() rnge = fs.max() - mins if rnge == 0: return [cmap(.5) for fx in xrange(len(fs))] score2_01 = lambda score: .1 + .9 * (float(score) - mins) / (rnge) colors = [cmap(score2_01(score)) for score in fs] return colors def colorbar(scalars, colors): 'adds a color bar next to the axes' orientation = ['vertical', 'horizontal'][0] TICK_FONTSIZE = 8 # Put colors and scalars in correct order sorted_scalars = sorted(scalars) sorted_colors = [x for (y, x) in sorted(zip(scalars, colors))] # Make a listed colormap and mappable object listed_cmap = mpl.colors.ListedColormap(sorted_colors) sm = plt.cm.ScalarMappable(cmap=listed_cmap) sm.set_array(sorted_scalars) # Use mapable object to create the colorbar cb = plt.colorbar(sm, orientation=orientation) # Add the colorbar to the correct label axis = cb.ax.xaxis if orientation == 'horizontal' else cb.ax.yaxis position = 'bottom' if orientation == 'horizontal' else 'right' axis.set_ticks_position(position) axis.set_ticks([0, .5, 1]) cb.ax.tick_params(labelsize=TICK_FONTSIZE) def draw_lines2(kpts1, kpts2, fm=None, fs=None, kpts2_offset=(0, 0), color_list=None, **kwargs): if not DISTINCT_COLORS: color_list = None # input data if not SHOW_LINES: return if fm is None: # assume kpts are in director correspondence assert kpts1.shape == kpts2.shape if len(fm) == 0: return ax = gca() woff, hoff = kpts2_offset # Draw line collection kpts1_m = kpts1[fm[:, 0]].T kpts2_m = kpts2[fm[:, 1]].T xxyy_iter = iter(zip(kpts1_m[0], kpts2_m[0] + woff, kpts1_m[1], kpts2_m[1] + hoff)) if color_list is None: if fs is None: # Draw with solid color color_list = [ LINE_COLOR for fx in xrange(len(fm))] else: # Draw with colors proportional to score difference color_list = feat_scores_to_color(fs) segments = [((x1, y1), (x2, y2)) for (x1, x2, y1, y2) in xxyy_iter] linewidth = [LINE_WIDTH for fx in xrange(len(fm))] line_alpha = LINE_ALPHA if LINE_ALPHA_OVERRIDE is not None: line_alpha = LINE_ALPHA_OVERRIDE line_group = LineCollection(segments, linewidth, color_list, alpha=line_alpha) #plt.colorbar(line_group, ax=ax) ax.add_collection(line_group) #figure(100) #plt.hexbin(x,y, cmap=plt.cm.YlOrRd_r) def draw_kpts(kpts, *args, **kwargs): draw_kpts2(kpts, *args, **kwargs) def draw_kpts2(kpts, offset=(0, 0), ell=SHOW_ELLS, pts=False, pts_color=ORANGE, pts_size=POINT_SIZE, ell_alpha=ELL_ALPHA, ell_linewidth=ELL_LINEWIDTH, ell_color=ELL_COLOR, color_list=None, rect=None, arrow=False, **kwargs): if not DISTINCT_COLORS: color_list = None printDBG('drawkpts2: Drawing Keypoints! ell=%r pts=%r' % (ell, pts)) # get matplotlib info ax = gca() pltTrans = ax.transData ell_actors = [] # data kpts = np.array(kpts) kptsT = kpts.T x = kptsT[0, :] + offset[0] y = kptsT[1, :] + offset[1] printDBG('[df2] draw_kpts()----------') printDBG('[df2] draw_kpts() ell=%r pts=%r' % (ell, pts)) printDBG('[df2] draw_kpts() drawing kpts.shape=%r' % (kpts.shape,)) if rect is None: rect = ell rect = False if pts is True: rect = False if ell or rect: printDBG('[df2] draw_kpts() drawing ell kptsT.shape=%r' % (kptsT.shape,)) # We have the transformation from unit circle to ellipse here. (inv(A)) a = kptsT[2] b = np.zeros(len(a)) c = kptsT[3] d = kptsT[4] kpts_iter = izip(x, y, a, b, c, d) aff_list = [Affine2D([( a_, b_, x_), ( c_, d_, y_), ( 0, 0, 1)]) for (x_, y_, a_, b_, c_, d_) in kpts_iter] patch_list = [] ell_actors = [Circle( (0, 0), 1, transform=aff) for aff in aff_list] if ell: patch_list += ell_actors if rect: rect_actors = [Rectangle( (-1, -1), 2, 2, transform=aff) for aff in aff_list] patch_list += rect_actors if arrow: _kwargs = dict(head_width=.01, length_includes_head=False) arrow_actors1 = [FancyArrow(0, 0, 0, 1, transform=aff, **_kwargs) for aff in aff_list] arrow_actors2 = [FancyArrow(0, 0, 1, 0, transform=aff, **_kwargs) for aff in aff_list] patch_list += arrow_actors1 patch_list += arrow_actors2 ellipse_collection = matplotlib.collections.PatchCollection(patch_list) ellipse_collection.set_facecolor('none') ellipse_collection.set_transform(pltTrans) if ELL_ALPHA_OVERRIDE is not None: ell_alpha = ELL_ALPHA_OVERRIDE ellipse_collection.set_alpha(ell_alpha) ellipse_collection.set_linewidth(ell_linewidth) if not color_list is None: ell_color = color_list if ell_color == 'distinct': ell_color = distinct_colors(len(kpts)) ellipse_collection.set_edgecolor(ell_color) ax.add_collection(ellipse_collection) if pts: printDBG('[df2] draw_kpts() drawing pts x.shape=%r y.shape=%r' % (x.shape, y.shape)) if color_list is None: color_list = [pts_color for _ in xrange(len(x))] ax.autoscale(enable=False) ax.scatter(x, y, c=color_list, s=2 * pts_size, marker='o', edgecolor='none') #ax.autoscale(enable=False) #ax.plot(x, y, linestyle='None', marker='o', markerfacecolor=pts_color, markersize=pts_size, markeredgewidth=0) # ---- CHIP DISPLAY COMMANDS ---- def imshow(img, fnum=None, title=None, figtitle=None, pnum=None, interpolation='nearest', **kwargs): 'other interpolations = nearest, bicubic, bilinear' #printDBG('[df2] ----- IMSHOW ------ ') #printDBG('[***df2.imshow] fnum=%r pnum=%r title=%r *** ' % (fnum, pnum, title)) #printDBG('[***df2.imshow] img.shape = %r ' % (img.shape,)) #printDBG('[***df2.imshow] img.stats = %r ' % (helpers.printable_mystats(img),)) fig = figure(fnum=fnum, pnum=pnum, title=title, figtitle=figtitle, **kwargs) ax = gca() if not DARKEN is None: imgdtype = img.dtype img = np.array(img, dtype=float) * DARKEN img = np.array(img, dtype=imgdtype) plt_imshow_kwargs = { 'interpolation': interpolation, #'cmap': plt.get_cmap('gray'), 'vmin': 0, 'vmax': 255, } try: if len(img.shape) == 3 and img.shape[2] == 3: # img is in a color format imgBGR = img if imgBGR.dtype == np.float64: if imgBGR.max() <= 1: imgBGR = np.array(imgBGR, dtype=np.float32) else: imgBGR = np.array(imgBGR, dtype=np.uint8) imgRGB = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB) ax.imshow(imgRGB, **plt_imshow_kwargs) elif len(img.shape) == 2: # img is in grayscale imgGRAY = img ax.imshow(imgGRAY, cmap=plt.get_cmap('gray'), **plt_imshow_kwargs) else: raise Exception('unknown image format') except TypeError as te: print('[df2] imshow ERROR %r' % te) raise except Exception as ex: print('[df2] img.dtype = %r' % (img.dtype,)) print('[df2] type(img) = %r' % (type(img),)) print('[df2] img.shape = %r' % (img.shape,)) print('[df2] imshow ERROR %r' % ex) raise #plt.set_cmap('gray') ax.set_xticks([]) ax.set_yticks([]) #ax.set_autoscale(False) #try: #if pnum == 111: #fig.tight_layout() #except Exception as ex: #print('[df2] !! Exception durring fig.tight_layout: '+repr(ex)) #raise return fig, ax def get_num_channels(img): ndims = len(img.shape) if ndims == 2: nChannels = 1 elif ndims == 3 and img.shape[2] == 3: nChannels = 3 elif ndims == 3 and img.shape[2] == 1: nChannels = 1 else: raise Exception('Cannot determine number of channels') return nChannels def stack_images(img1, img2, vert=None): nChannels = get_num_channels(img1) nChannels2 = get_num_channels(img2) assert nChannels == nChannels2 (h1, w1) = img1.shape[0: 2] # get chip dimensions (h2, w2) = img2.shape[0: 2] woff, hoff = 0, 0 vert_wh = max(w1, w2), h1 + h2 horiz_wh = w1 + w2, max(h1, h2) if vert is None: # Display the orientation with the better (closer to 1) aspect ratio vert_ar = max(vert_wh) / min(vert_wh) horiz_ar = max(horiz_wh) / min(horiz_wh) vert = vert_ar < horiz_ar if vert: wB, hB = vert_wh hoff = h1 else: wB, hB = horiz_wh woff = w1 # concatentate images if nChannels == 3: imgB = np.zeros((hB, wB, 3), np.uint8) imgB[0:h1, 0:w1, :] = img1 imgB[hoff:(hoff + h2), woff:(woff + w2), :] = img2 elif nChannels == 1: imgB = np.zeros((hB, wB), np.uint8) imgB[0:h1, 0:w1] = img1 imgB[hoff:(hoff + h2), woff:(woff + w2)] = img2 return imgB, woff, hoff def show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm=None, fs=None, title=None, vert=None, fnum=None, pnum=None, **kwargs): '''Draws two chips and the feature matches between them. feature matches kpts1 and kpts2 use the (x,y,a,c,d) ''' printDBG('[df2] draw_matches2() fnum=%r, pnum=%r' % (fnum, pnum)) # get matching keypoints + offset (h1, w1) = rchip1.shape[0:2] # get chip (h, w) dimensions (h2, w2) = rchip2.shape[0:2] # Stack the compared chips match_img, woff, hoff = stack_images(rchip1, rchip2, vert) xywh1 = (0, 0, w1, h1) xywh2 = (woff, hoff, w2, h2) # Show the stacked chips fig, ax = imshow(match_img, title=title, fnum=fnum, pnum=pnum) # Overlay feature match nnotations draw_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs, **kwargs) return ax, xywh1, xywh2 # draw feature match def draw_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs=None, lbl1=None, lbl2=None, fnum=None, pnum=None, rect=False, colorbar_=True, **kwargs): '''Draws the matching features. This is draw because it is an overlay xywh1 - location of rchip1 in the axes xywh2 - location or rchip2 in the axes ''' if fm is None: assert kpts1.shape == kpts2.shape, 'shapes different or fm not none' fm = np.tile(np.arange(0, len(kpts1)), (2, 1)).T pts = kwargs.get('draw_pts', False) ell = kwargs.get('draw_ell', True) lines = kwargs.get('draw_lines', True) ell_alpha = kwargs.get('ell_alpha', .4) nMatch = len(fm) #printDBG('[df2.draw_fnmatch] nMatch=%r' % nMatch) x1, y1, w1, h1 = xywh1 x2, y2, w2, h2 = xywh2 offset2 = (x2, y2) # Custom user label for chips 1 and 2 if lbl1 is not None: absolute_lbl(x1 + w1, y1, lbl1) if lbl2 is not None: absolute_lbl(x2 + w2, y2, lbl2) # Plot the number of matches if kwargs.get('show_nMatches', False): upperleft_text('#match=%d' % nMatch) # Draw all keypoints in both chips as points if kwargs.get('all_kpts', False): all_args = dict(ell=False, pts=pts, pts_color=GREEN, pts_size=2, ell_alpha=ell_alpha, rect=rect) all_args.update(kwargs) draw_kpts2(kpts1, **all_args) draw_kpts2(kpts2, offset=offset2, **all_args) # Draw Lines and Ellipses and Points oh my if nMatch > 0: colors = [kwargs['colors']] * nMatch if 'colors' in kwargs else distinct_colors(nMatch) if fs is not None: colors = feat_scores_to_color(fs, 'hot') acols = add_alpha(colors) # Helper functions def _drawkpts(**_kwargs): _kwargs.update(kwargs) fxs1 = fm[:, 0] fxs2 = fm[:, 1] draw_kpts2(kpts1[fxs1], rect=rect, **_kwargs) draw_kpts2(kpts2[fxs2], offset=offset2, rect=rect, **_kwargs) def _drawlines(**_kwargs): _kwargs.update(kwargs) draw_lines2(kpts1, kpts2, fm, fs, kpts2_offset=offset2, **_kwargs) # User helpers if ell: _drawkpts(pts=False, ell=True, color_list=colors) if pts: _drawkpts(pts_size=8, pts=True, ell=False, pts_color=BLACK) _drawkpts(pts_size=6, pts=True, ell=False, color_list=acols) if lines: _drawlines(color_list=colors) else: draw_boxedX(xywh2) if fs is not None and colorbar_ and 'colors' in vars() and colors is not None: colorbar(fs, colors) #legend() return None def draw_boxedX(xywh, color=RED, lw=2, alpha=.5, theta=0): 'draws a big red x. redx' ax = gca() x1, y1, w, h = xywh x2, y2 = x1 + w, y1 + h segments = [((x1, y1), (x2, y2)), ((x1, y2), (x2, y1))] trans = Affine2D() trans.rotate(theta) trans = trans + ax.transData width_list = [lw] * len(segments) color_list = [color] * len(segments) line_group = LineCollection(segments, width_list, color_list, alpha=alpha, transOffset=trans) ax.add_collection(line_group) def disconnect_callback(fig, callback_type, **kwargs): #print('[df2] disconnect %r callback' % callback_type) axes = kwargs.get('axes', []) for ax in axes: ax._hs_viewtype = '' cbid_type = callback_type + '_cbid' cbfn_type = callback_type + '_func' cbid = fig.__dict__.get(cbid_type, None) cbfn = fig.__dict__.get(cbfn_type, None) if cbid is not None: fig.canvas.mpl_disconnect(cbid) else: cbfn = None fig.__dict__[cbid_type] = None return cbid, cbfn def connect_callback(fig, callback_type, callback_fn): #print('[df2] register %r callback' % callback_type) if callback_fn is None: return cbid_type = callback_type + '_cbid' cbfn_type = callback_type + '_func' fig.__dict__[cbid_type] = fig.canvas.mpl_connect(callback_type, callback_fn) fig.__dict__[cbfn_type] = callback_fn
apache-2.0
kevin-coder/tensorflow-fork
tensorflow/lite/experimental/micro/examples/micro_speech/apollo3/captured_data_to_wav.py
11
1442
# Copyright 2018 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. # ============================================================================== """Converts values pulled from the microcontroller into audio files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import struct # import matplotlib.pyplot as plt import numpy as np import soundfile as sf def new_data_to_array(fn): vals = [] with open(fn) as f: for n, line in enumerate(f): if n != 0: vals.extend([int(v, 16) for v in line.split()]) b = ''.join(map(chr, vals)) y = struct.unpack('<' + 'h' * int(len(b) / 2), b) return y data = 'captured_data.txt' values = np.array(new_data_to_array(data)).astype(float) # plt.plot(values, 'o-') # plt.show(block=False) wav = values / np.max(np.abs(values)) sf.write('captured_data.wav', wav, 16000)
apache-2.0
waynenilsen/statsmodels
statsmodels/examples/ex_kde_confint.py
34
1973
# -*- coding: utf-8 -*- """ Created on Mon Dec 16 11:02:59 2013 Author: Josef Perktold """ from __future__ import print_function import numpy as np from scipy import stats import matplotlib.pyplot as plt import statsmodels.nonparametric.api as npar from statsmodels.sandbox.nonparametric import kernels from statsmodels.distributions.mixture_rvs import mixture_rvs # example from test_kde.py mixture of two normal distributions np.random.seed(12345) x = mixture_rvs([.25,.75], size=200, dist=[stats.norm, stats.norm], kwargs = (dict(loc=-1, scale=.5),dict(loc=1, scale=.5))) x.sort() # not needed kde = npar.KDEUnivariate(x) kde.fit('gau') ci = kde.kernel.density_confint(kde.density, len(x)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.hist(x, bins=15, normed=True, alpha=0.25) ax.plot(kde.support, kde.density, lw=2, color='red') ax.fill_between(kde.support, ci[:,0], ci[:,1], color='grey', alpha='0.7') ax.set_title('Kernel Density Gaussian (bw = %4.2f)' % kde.bw) # use all kernels directly x_grid = np.linspace(np.min(x), np.max(x), 51) x_grid = np.linspace(-3, 3, 51) kernel_names = ['Biweight', 'Cosine', 'Epanechnikov', 'Gaussian', 'Triangular', 'Triweight', #'Uniform', ] fig = plt.figure() for ii, kn in enumerate(kernel_names): ax = fig.add_subplot(2, 3, ii+1) # without uniform ax.hist(x, bins=10, normed=True, alpha=0.25) #reduce bandwidth for Gaussian and Uniform which are to large in example if kn in ['Gaussian', 'Uniform']: args = (0.5,) else: args = () kernel = getattr(kernels, kn)(*args) kde_grid = [kernel.density(x, xi) for xi in x_grid] confint_grid = kernel.density_confint(kde_grid, len(x)) ax.plot(x_grid, kde_grid, lw=2, color='red', label=kn) ax.fill_between(x_grid, confint_grid[:,0], confint_grid[:,1], color='grey', alpha='0.7') ax.legend(loc='upper left') plt.show()
bsd-3-clause
pratapvardhan/scikit-learn
examples/plot_multilabel.py
236
4157
# Authors: Vlad Niculae, Mathieu Blondel # License: BSD 3 clause """ ========================= Multilabel classification ========================= This example simulates a multi-label document classification problem. The dataset is generated randomly based on the following process: - pick the number of labels: n ~ Poisson(n_labels) - n times, choose a class c: c ~ Multinomial(theta) - pick the document length: k ~ Poisson(length) - k times, choose a word: w ~ Multinomial(theta_c) In the above process, rejection sampling is used to make sure that n is more than 2, and that the document length is never zero. Likewise, we reject classes which have already been chosen. The documents that are assigned to both classes are plotted surrounded by two colored circles. The classification is performed by projecting to the first two principal components found by PCA and CCA for visualisation purposes, followed by using the :class:`sklearn.multiclass.OneVsRestClassifier` metaclassifier using two SVCs with linear kernels to learn a discriminative model for each class. Note that PCA is used to perform an unsupervised dimensionality reduction, while CCA is used to perform a supervised one. Note: in the plot, "unlabeled samples" does not mean that we don't know the labels (as in semi-supervised learning) but that the samples simply do *not* have a label. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_multilabel_classification from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC from sklearn.preprocessing import LabelBinarizer from sklearn.decomposition import PCA from sklearn.cross_decomposition import CCA def plot_hyperplane(clf, min_x, max_x, linestyle, label): # get the separating hyperplane w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(min_x - 5, max_x + 5) # make sure the line is long enough yy = a * xx - (clf.intercept_[0]) / w[1] plt.plot(xx, yy, linestyle, label=label) def plot_subfigure(X, Y, subplot, title, transform): if transform == "pca": X = PCA(n_components=2).fit_transform(X) elif transform == "cca": X = CCA(n_components=2).fit(X, Y).transform(X) else: raise ValueError min_x = np.min(X[:, 0]) max_x = np.max(X[:, 0]) min_y = np.min(X[:, 1]) max_y = np.max(X[:, 1]) classif = OneVsRestClassifier(SVC(kernel='linear')) classif.fit(X, Y) plt.subplot(2, 2, subplot) plt.title(title) zero_class = np.where(Y[:, 0]) one_class = np.where(Y[:, 1]) plt.scatter(X[:, 0], X[:, 1], s=40, c='gray') plt.scatter(X[zero_class, 0], X[zero_class, 1], s=160, edgecolors='b', facecolors='none', linewidths=2, label='Class 1') plt.scatter(X[one_class, 0], X[one_class, 1], s=80, edgecolors='orange', facecolors='none', linewidths=2, label='Class 2') plot_hyperplane(classif.estimators_[0], min_x, max_x, 'k--', 'Boundary\nfor class 1') plot_hyperplane(classif.estimators_[1], min_x, max_x, 'k-.', 'Boundary\nfor class 2') plt.xticks(()) plt.yticks(()) plt.xlim(min_x - .5 * max_x, max_x + .5 * max_x) plt.ylim(min_y - .5 * max_y, max_y + .5 * max_y) if subplot == 2: plt.xlabel('First principal component') plt.ylabel('Second principal component') plt.legend(loc="upper left") plt.figure(figsize=(8, 6)) X, Y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=True, random_state=1) plot_subfigure(X, Y, 1, "With unlabeled samples + CCA", "cca") plot_subfigure(X, Y, 2, "With unlabeled samples + PCA", "pca") X, Y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=False, random_state=1) plot_subfigure(X, Y, 3, "Without unlabeled samples + CCA", "cca") plot_subfigure(X, Y, 4, "Without unlabeled samples + PCA", "pca") plt.subplots_adjust(.04, .02, .97, .94, .09, .2) plt.show()
bsd-3-clause
zachcp/qiime
qiime/quality_scores_plot.py
9
6918
#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "William.A.Walters@colorado.edu" from matplotlib import use use('Agg', warn=False) from skbio.parse.sequences import parse_fasta from numpy import arange, std, average from pylab import plot, savefig, xlabel, ylabel, text, \ hist, figure, legend, title, show, xlim, ylim, xticks, yticks,\ scatter, subplot from matplotlib.font_manager import fontManager, FontProperties from qiime.util import gzip_open from qiime.parse import parse_qual_score def bin_qual_scores(qual_scores): """ Bins qual score according to nucleotide position qual_scores: Dict of label: numpy array of base scores """ qual_bins = [] qual_lens = [] for l in qual_scores.values(): qual_lens.append(len(l)) max_seq_size = max(qual_lens) for base_position in range(max_seq_size): qual_bins.append([]) for scores in qual_scores.values(): # Add score if exists in base position, otherwise skip try: qual_bins[base_position].append(scores[base_position]) except IndexError: continue return qual_bins def get_qual_stats(qual_bins, score_min): """ Generates bins of averages, std devs, total NT from quality bins""" ave_bins = [] std_dev_bins = [] total_bases_bins = [] found_first_poor_qual_pos = False suggested_trunc_pos = None for base_position in qual_bins: total_bases_bins.append(len(base_position)) std_dev_bins.append(std(base_position)) ave_bins.append(average(base_position)) if not found_first_poor_qual_pos: if average(base_position) < score_min: suggested_trunc_pos = qual_bins.index(base_position) found_first_poor_qual_pos = True return ave_bins, std_dev_bins, total_bases_bins, suggested_trunc_pos def plot_qual_report(ave_bins, std_dev_bins, total_bases_bins, score_min, output_dir): """ Plots, saves graph showing quality score averages, stddev. Additionally, the total nucleotide count for each position is shown on a second subplot ave_bins: list with average quality score for each base position std_dev_bins: list with standard deviation for each base position total_bases_bins: list with total counts of bases for each position score_min: lowest value that a given base call can be and still be acceptable. Used to generate a dotted line on the graph for easy assay of the poor scoring positions. output_dir: output directory """ t = arange(0, len(ave_bins), 1) std_dev_plus = [] std_dev_minus = [] for n in range(len(ave_bins)): std_dev_plus.append(ave_bins[n] + std_dev_bins[n]) std_dev_minus.append(ave_bins[n] - std_dev_bins[n]) figure_num = 0 f = figure(figure_num, figsize=(8, 10)) figure_title = "Quality Scores Report" f.text(.5, .93, figure_title, horizontalalignment='center', size="large") subplot(2, 1, 1) plot(t, ave_bins, linewidth=2.0, color="black") plot(t, std_dev_plus, linewidth=0.5, color="red") dashed_line = [score_min] * len(ave_bins) l, = plot(dashed_line, '--', color='gray') plot(t, std_dev_minus, linewidth=0.5, color="red") legend( ('Quality Score Average', 'Std Dev', 'Score Threshold'), loc='lower left') xlabel("Nucleotide Position") ylabel("Quality Score") subplot(2, 1, 2) plot(t, total_bases_bins, linewidth=2.0, color="blue") xlabel("Nucleotide Position") ylabel("Nucleotide Counts") outfile_name = output_dir + "/quality_scores_plot.pdf" savefig(outfile_name) def write_qual_report(ave_bins, std_dev_bins, total_bases_bins, output_dir, suggested_trunc_pos): """ Writes data in bins to output text file ave_bins: list with average quality score for each base position std_dev_bins: list with standard deviation for each base position total_bases_bins: list with total counts of bases for each position output_dir: output directory suggested_trunc_pos: Position where average quality score dropped below the score minimum (25 by default) """ outfile_name = output_dir + "/quality_bins.txt" outfile = open(outfile_name, "w") outfile.write("# Suggested nucleotide truncation position (None if " + "quality score average did not drop below the score minimum threshold)" + ": %s\n" % suggested_trunc_pos) outfile.write("# Average quality score bins\n") outfile.write(",".join(str("%2.3f" % ave) for ave in ave_bins) + "\n") outfile.write("# Standard deviation bins\n") outfile.write(",".join(str("%2.3f" % std) for std in std_dev_bins) + "\n") outfile.write("# Total bases per nucleotide position bins\n") outfile.write(",".join(str("%d" % total_bases) for total_bases in total_bases_bins)) def generate_histogram(qual_fp, output_dir, score_min=25, verbose=True, qual_parser=parse_qual_score): """ Main program function for generating quality score histogram qual_fp: quality score filepath output_dir: output directory score_min: minimum score to be considered a reliable base call, used to generate dotted line on histogram for easy visualization of poor quality scores. qual_parser : function to apply to extract quality scores """ if qual_fp.endswith('.gz'): qual_lines = gzip_open(qual_fp) else: qual_lines = open(qual_fp, "U") qual_scores = qual_parser(qual_lines) # Sort bins according to base position qual_bins = bin_qual_scores(qual_scores) # Get average, std dev, and total nucleotide counts for each base position ave_bins, std_dev_bins, total_bases_bins, suggested_trunc_pos =\ get_qual_stats(qual_bins, score_min) plot_qual_report(ave_bins, std_dev_bins, total_bases_bins, score_min, output_dir) # Save values to output text file write_qual_report(ave_bins, std_dev_bins, total_bases_bins, output_dir, suggested_trunc_pos) if verbose: print "Suggested nucleotide truncation position (None if quality " +\ "score average did not fall below the minimum score parameter): %s\n" %\ suggested_trunc_pos
gpl-2.0
barbagroup/PetIBM
examples/ibpm/cylinder2dRe40/scripts/plotVorticity.py
4
1401
""" Computes, plots, and saves the 2D vorticity field from a PetIBM simulation after 2000 time steps (20 non-dimensional time-units). """ import pathlib import h5py import numpy from matplotlib import pyplot simu_dir = pathlib.Path(__file__).absolute().parents[1] data_dir = simu_dir / 'output' # Read vorticity field and its grid from files. name = 'wz' filepath = data_dir / 'grid.h5' f = h5py.File(filepath, 'r') x, y = f[name]['x'][:], f[name]['y'][:] X, Y = numpy.meshgrid(x, y) timestep = 2000 filepath = data_dir / '{:0>7}.h5'.format(timestep) f = h5py.File(filepath, 'r') wz = f[name][:] # Read body coordinates from file. filepath = simu_dir / 'circle.body' with open(filepath, 'r') as infile: xb, yb = numpy.loadtxt(infile, dtype=numpy.float64, unpack=True, skiprows=1) pyplot.rc('font', family='serif', size=16) # Plot the filled contour of the vorticity. fig, ax = pyplot.subplots(figsize=(6.0, 6.0)) ax.grid() ax.set_xlabel('x') ax.set_ylabel('y') levels = numpy.linspace(-3.0, 3.0, 16) ax.contour(X, Y, wz, levels=levels, colors='black') ax.plot(xb, yb, color='red') ax.set_xlim(-1.0, 4.0) ax.set_ylim(-2.0, 2.0) ax.set_aspect('equal') fig.tight_layout() pyplot.show() # Save figure. fig_dir = simu_dir / 'figures' fig_dir.mkdir(parents=True, exist_ok=True) filepath = fig_dir / 'wz{:0>7}.png'.format(timestep) fig.savefig(str(filepath), dpi=300)
bsd-3-clause
jonyroda97/redbot-amigosprovaveis
lib/matplotlib/units.py
2
6084
""" The classes here provide support for using custom classes with matplotlib, e.g., those that do not expose the array interface but know how to convert themselves to arrays. It also supports classes with units and units conversion. Use cases include converters for custom objects, e.g., a list of datetime objects, as well as for objects that are unit aware. We don't assume any particular units implementation; rather a units implementation must provide the register with the Registry converter dictionary and a ConversionInterface. For example, here is a complete implementation which supports plotting with native datetime objects:: import matplotlib.units as units import matplotlib.dates as dates import matplotlib.ticker as ticker import datetime class DateConverter(units.ConversionInterface): @staticmethod def convert(value, unit, axis): 'convert value to a scalar or array' return dates.date2num(value) @staticmethod def axisinfo(unit, axis): 'return major and minor tick locators and formatters' if unit!='date': return None majloc = dates.AutoDateLocator() majfmt = dates.AutoDateFormatter(majloc) return AxisInfo(majloc=majloc, majfmt=majfmt, label='date') @staticmethod def default_units(x, axis): 'return the default unit for x or None' return 'date' # finally we register our object type with a converter units.registry[datetime.date] = DateConverter() """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from matplotlib.cbook import iterable, is_numlike, safe_first_element import numpy as np class AxisInfo(object): """information to support default axis labeling and tick labeling, and default limits""" def __init__(self, majloc=None, minloc=None, majfmt=None, minfmt=None, label=None, default_limits=None): """ majloc and minloc: TickLocators for the major and minor ticks majfmt and minfmt: TickFormatters for the major and minor ticks label: the default axis label default_limits: the default min, max of the axis if no data is present If any of the above are None, the axis will simply use the default """ self.majloc = majloc self.minloc = minloc self.majfmt = majfmt self.minfmt = minfmt self.label = label self.default_limits = default_limits class ConversionInterface(object): """ The minimal interface for a converter to take custom instances (or sequences) and convert them to values mpl can use """ @staticmethod def axisinfo(unit, axis): 'return an units.AxisInfo instance for axis with the specified units' return None @staticmethod def default_units(x, axis): 'return the default unit for x or None for the given axis' return None @staticmethod def convert(obj, unit, axis): """ convert obj using unit for the specified axis. If obj is a sequence, return the converted sequence. The output must be a sequence of scalars that can be used by the numpy array layer """ return obj @staticmethod def is_numlike(x): """ The matplotlib datalim, autoscaling, locators etc work with scalars which are the units converted to floats given the current unit. The converter may be passed these floats, or arrays of them, even when units are set. Derived conversion interfaces may opt to pass plain-ol unitless numbers through the conversion interface and this is a helper function for them. """ if iterable(x): for thisx in x: return is_numlike(thisx) else: return is_numlike(x) class Registry(dict): """ register types with conversion interface """ def __init__(self): dict.__init__(self) self._cached = {} def get_converter(self, x): 'get the converter interface instance for x, or None' if not len(self): return None # nothing registered # DISABLED idx = id(x) # DISABLED cached = self._cached.get(idx) # DISABLED if cached is not None: return cached converter = None classx = getattr(x, '__class__', None) if classx is not None: converter = self.get(classx) if isinstance(x, np.ndarray) and x.size: xravel = x.ravel() try: # pass the first value of x that is not masked back to # get_converter if not np.all(xravel.mask): # some elements are not masked converter = self.get_converter( xravel[np.argmin(xravel.mask)]) return converter except AttributeError: # not a masked_array # Make sure we don't recurse forever -- it's possible for # ndarray subclasses to continue to return subclasses and # not ever return a non-subclass for a single element. next_item = xravel[0] if (not isinstance(next_item, np.ndarray) or next_item.shape != x.shape): converter = self.get_converter(next_item) return converter if converter is None: try: thisx = safe_first_element(x) except (TypeError, StopIteration): pass else: if classx and classx != getattr(thisx, '__class__', None): converter = self.get_converter(thisx) return converter # DISABLED self._cached[idx] = converter return converter registry = Registry()
gpl-3.0
xiaoxiamii/scikit-learn
benchmarks/bench_plot_svd.py
325
2899
"""Benchmarks of Singular Value Decomposition (Exact and Approximate) The data is mostly low rank but is a fat infinite tail. """ import gc from time import time import numpy as np from collections import defaultdict from scipy.linalg import svd from sklearn.utils.extmath import randomized_svd from sklearn.datasets.samples_generator import make_low_rank_matrix def compute_bench(samples_range, features_range, n_iter=3, rank=50): it = 0 results = defaultdict(lambda: []) max_it = len(samples_range) * len(features_range) for n_samples in samples_range: for n_features in features_range: it += 1 print('====================') print('Iteration %03d of %03d' % (it, max_it)) print('====================') X = make_low_rank_matrix(n_samples, n_features, effective_rank=rank, tail_strength=0.2) gc.collect() print("benchmarking scipy svd: ") tstart = time() svd(X, full_matrices=False) results['scipy svd'].append(time() - tstart) gc.collect() print("benchmarking scikit-learn randomized_svd: n_iter=0") tstart = time() randomized_svd(X, rank, n_iter=0) results['scikit-learn randomized_svd (n_iter=0)'].append( time() - tstart) gc.collect() print("benchmarking scikit-learn randomized_svd: n_iter=%d " % n_iter) tstart = time() randomized_svd(X, rank, n_iter=n_iter) results['scikit-learn randomized_svd (n_iter=%d)' % n_iter].append(time() - tstart) return results if __name__ == '__main__': from mpl_toolkits.mplot3d import axes3d # register the 3d projection import matplotlib.pyplot as plt samples_range = np.linspace(2, 1000, 4).astype(np.int) features_range = np.linspace(2, 1000, 4).astype(np.int) results = compute_bench(samples_range, features_range) label = 'scikit-learn singular value decomposition benchmark results' fig = plt.figure(label) ax = fig.gca(projection='3d') for c, (label, timings) in zip('rbg', sorted(results.iteritems())): X, Y = np.meshgrid(samples_range, features_range) Z = np.asarray(timings).reshape(samples_range.shape[0], features_range.shape[0]) # plot the actual surface ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3, color=c) # dummy point plot to stick the legend to since surface plot do not # support legends (yet?) ax.plot([1], [1], [1], color=c, label=label) ax.set_xlabel('n_samples') ax.set_ylabel('n_features') ax.set_zlabel('Time (s)') ax.legend() plt.show()
bsd-3-clause
mcocdawc/chemopt
src/chemopt/utilities/_print_versions.py
2
4591
# The following code was taken from the pandas project and modified. # http://pandas.pydata.org/ import codecs import importlib import locale import os import platform import struct import sys def get_sys_info(): "Returns system information as a dict" blob = [] # commit = cc._git_hash # blob.append(('commit', commit)) try: (sysname, nodename, release, version, machine, processor) = platform.uname() blob.extend([ ("python", "%d.%d.%d.%s.%s" % sys.version_info[:]), ("python-bits", struct.calcsize("P") * 8), ("OS", "%s" % (sysname)), ("OS-release", "%s" % (release)), # ("Version", "%s" % (version)), ("machine", "%s" % (machine)), ("processor", "%s" % (processor)), # ("byteorder", "%s" % sys.byteorder), ("LC_ALL", "%s" % os.environ.get('LC_ALL', "None")), ("LANG", "%s" % os.environ.get('LANG', "None")), ("LOCALE", "%s.%s" % locale.getlocale()), ]) except Exception: pass return blob def show_versions(as_json=False): sys_info = get_sys_info() deps = [ # (MODULE_NAME, f(mod) -> mod version) ("chemcoord", lambda mod: mod.__version__), ("numpy", lambda mod: mod.version.version), ("scipy", lambda mod: mod.version.version), ("pandas", lambda mod: mod.__version__), ("numba", lambda mod: mod.__version__), ("sortedcontainers", lambda mod: mod.__version__), ("sympy", lambda mod: mod.__version__), ("pytest", lambda mod: mod.__version__), ("pip", lambda mod: mod.__version__), ("setuptools", lambda mod: mod.__version__), ("IPython", lambda mod: mod.__version__), ("sphinx", lambda mod: mod.__version__), # ("tables", lambda mod: mod.__version__), # ("matplotlib", lambda mod: mod.__version__), # ("Cython", lambda mod: mod.__version__), # ("xarray", lambda mod: mod.__version__), # ("patsy", lambda mod: mod.__version__), # ("dateutil", lambda mod: mod.__version__), # ("pytz", lambda mod: mod.VERSION), # ("blosc", lambda mod: mod.__version__), # ("bottleneck", lambda mod: mod.__version__), # ("numexpr", lambda mod: mod.__version__), # ("feather", lambda mod: mod.__version__), # ("openpyxl", lambda mod: mod.__version__), # ("xlrd", lambda mod: mod.__VERSION__), # ("xlwt", lambda mod: mod.__VERSION__), # ("xlsxwriter", lambda mod: mod.__version__), # ("lxml", lambda mod: mod.etree.__version__), # ("bs4", lambda mod: mod.__version__), # ("html5lib", lambda mod: mod.__version__), # ("sqlalchemy", lambda mod: mod.__version__), # ("pymysql", lambda mod: mod.__version__), # ("psycopg2", lambda mod: mod.__version__), # ("jinja2", lambda mod: mod.__version__), # ("s3fs", lambda mod: mod.__version__), # ("pandas_gbq", lambda mod: mod.__version__), # ("pandas_datareader", lambda mod: mod.__version__) ] deps_blob = list() for (modname, ver_f) in deps: try: if modname in sys.modules: mod = sys.modules[modname] else: mod = importlib.import_module(modname) ver = ver_f(mod) deps_blob.append((modname, ver)) except Exception: deps_blob.append((modname, None)) if (as_json): try: import json except Exception: import simplejson as json j = dict(system=dict(sys_info), dependencies=dict(deps_blob)) if as_json is True: print(j) else: with codecs.open(as_json, "wb", encoding='utf8') as f: json.dump(j, f, indent=2) else: print("\nINSTALLED VERSIONS") print("------------------") for k, stat in sys_info: print("%s: %s" % (k, stat)) print("") for k, stat in deps_blob: print("%s: %s" % (k, stat)) def main(): from optparse import OptionParser parser = OptionParser() parser.add_option("-j", "--json", metavar="FILE", nargs=1, help="Save output as JSON into file, pass in " "'-' to output to stdout") options = parser.parse_args()[0] if options.json == "-": options.json = True show_versions(as_json=options.json) return 0 if __name__ == "__main__": sys.exit(main())
lgpl-3.0
lscheinkman/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/units.py
70
4810
""" The classes here provide support for using custom classes with matplotlib, eg those that do not expose the array interface but know how to converter themselves to arrays. It also supoprts classes with units and units conversion. Use cases include converters for custom objects, eg a list of datetime objects, as well as for objects that are unit aware. We don't assume any particular units implementation, rather a units implementation must provide a ConversionInterface, and the register with the Registry converter dictionary. For example, here is a complete implementation which support plotting with native datetime objects import matplotlib.units as units import matplotlib.dates as dates import matplotlib.ticker as ticker import datetime class DateConverter(units.ConversionInterface): def convert(value, unit): 'convert value to a scalar or array' return dates.date2num(value) convert = staticmethod(convert) def axisinfo(unit): 'return major and minor tick locators and formatters' if unit!='date': return None majloc = dates.AutoDateLocator() majfmt = dates.AutoDateFormatter(majloc) return AxisInfo(majloc=majloc, majfmt=majfmt, label='date') axisinfo = staticmethod(axisinfo) def default_units(x): 'return the default unit for x or None' return 'date' default_units = staticmethod(default_units) # finally we register our object type with a converter units.registry[datetime.date] = DateConverter() """ import numpy as np from matplotlib.cbook import iterable, is_numlike class AxisInfo: 'information to support default axis labeling and tick labeling' def __init__(self, majloc=None, minloc=None, majfmt=None, minfmt=None, label=None): """ majloc and minloc: TickLocators for the major and minor ticks majfmt and minfmt: TickFormatters for the major and minor ticks label: the default axis label If any of the above are None, the axis will simply use the default """ self.majloc = majloc self.minloc = minloc self.majfmt = majfmt self.minfmt = minfmt self.label = label class ConversionInterface: """ The minimal interface for a converter to take custom instances (or sequences) and convert them to values mpl can use """ def axisinfo(unit): 'return an units.AxisInfo instance for unit' return None axisinfo = staticmethod(axisinfo) def default_units(x): 'return the default unit for x or None' return None default_units = staticmethod(default_units) def convert(obj, unit): """ convert obj using unit. If obj is a sequence, return the converted sequence. The ouput must be a sequence of scalars that can be used by the numpy array layer """ return obj convert = staticmethod(convert) def is_numlike(x): """ The matplotlib datalim, autoscaling, locators etc work with scalars which are the units converted to floats given the current unit. The converter may be passed these floats, or arrays of them, even when units are set. Derived conversion interfaces may opt to pass plain-ol unitless numbers through the conversion interface and this is a helper function for them. """ if iterable(x): for thisx in x: return is_numlike(thisx) else: return is_numlike(x) is_numlike = staticmethod(is_numlike) class Registry(dict): """ register types with conversion interface """ def __init__(self): dict.__init__(self) self._cached = {} def get_converter(self, x): 'get the converter interface instance for x, or None' if not len(self): return None # nothing registered #DISABLED idx = id(x) #DISABLED cached = self._cached.get(idx) #DISABLED if cached is not None: return cached converter = None classx = getattr(x, '__class__', None) if classx is not None: converter = self.get(classx) if converter is None and iterable(x): # if this is anything but an object array, we'll assume # there are no custom units if isinstance(x, np.ndarray) and x.dtype != np.object: return None for thisx in x: converter = self.get_converter( thisx ) return converter #DISABLED self._cached[idx] = converter return converter registry = Registry()
agpl-3.0
plaes/numpy
doc/source/conf.py
6
8773
# -*- coding: utf-8 -*- import sys, os, re # Check Sphinx version import sphinx if sphinx.__version__ < "0.5": raise RuntimeError("Sphinx 0.5.dev or newer required") # ----------------------------------------------------------------------------- # General configuration # ----------------------------------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. sys.path.insert(0, os.path.abspath('../sphinxext')) extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'numpydoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'plot_directive'] if sphinx.__version__ >= "0.7": extensions.append('sphinx.ext.autosummary') else: extensions.append('autosummary') extensions.append('only_directives') # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. #master_doc = 'index' # General substitutions. project = 'NumPy' copyright = '2008-2009, The Scipy community' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # import numpy # The short X.Y version (including .devXXXX, rcX, b1 suffixes if present) version = re.sub(r'(\d+\.\d+)\.\d+(.*)', r'\1\2', numpy.__version__) version = re.sub(r'(\.dev\d+).*?$', r'\1', version) # The full version, including alpha/beta/rc tags. release = numpy.__version__ print version, release # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # The reST default role (used for this markup: `text`) to use for all documents. default_role = "autolink" # List of directories, relative to source directories, that shouldn't be searched # for source files. exclude_dirs = [] # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = False # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # ----------------------------------------------------------------------------- # HTML output # ----------------------------------------------------------------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'scipy.css' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = "%s v%s Manual (DRAFT)" % (project, version) # The name of an image file (within the static path) to place at the top of # the sidebar. html_logo = 'scipyshiny_small.png' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { 'index': 'indexsidebar.html' } # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = { 'index': 'indexcontent.html', } # If false, no module index is generated. html_use_modindex = True # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".html"). #html_file_suffix = '.html' # Output file base name for HTML help builder. htmlhelp_basename = 'numpy' # Pngmath should try to align formulas properly pngmath_use_preview = True # ----------------------------------------------------------------------------- # LaTeX output # ----------------------------------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). _stdauthor = 'Written by the NumPy community' latex_documents = [ ('reference/index', 'numpy-ref.tex', 'NumPy Reference', _stdauthor, 'manual'), ('user/index', 'numpy-user.tex', 'NumPy User Guide', _stdauthor, 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. latex_preamble = r''' \usepackage{amsmath} \DeclareUnicodeCharacter{00A0}{\nobreakspace} % In the parameters section, place a newline after the Parameters % header \usepackage{expdlist} \let\latexdescription=\description \def\description{\latexdescription{}{} \breaklabel} % Make Examples/etc section headers smaller and more compact \makeatletter \titleformat{\paragraph}{\normalsize\py@HeaderFamily}% {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor} \titlespacing*{\paragraph}{0pt}{1ex}{0pt} \makeatother % Fix footer/header \renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\thechapter.\ #1}}{}} \renewcommand{\sectionmark}[1]{\markright{\MakeUppercase{\thesection.\ #1}}} ''' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_use_modindex = False # ----------------------------------------------------------------------------- # Intersphinx configuration # ----------------------------------------------------------------------------- intersphinx_mapping = {'http://docs.python.org/dev': None} # ----------------------------------------------------------------------------- # Numpy extensions # ----------------------------------------------------------------------------- # If we want to do a phantom import from an XML file for all autodocs phantom_import_file = 'dump.xml' # Make numpydoc to generate plots for example sections numpydoc_use_plots = True # ----------------------------------------------------------------------------- # Autosummary # ----------------------------------------------------------------------------- if sphinx.__version__ >= "0.7": import glob autosummary_generate = glob.glob("reference/*.rst") # ----------------------------------------------------------------------------- # Coverage checker # ----------------------------------------------------------------------------- coverage_ignore_modules = r""" """.split() coverage_ignore_functions = r""" test($|_) (some|all)true bitwise_not cumproduct pkgload generic\. """.split() coverage_ignore_classes = r""" """.split() coverage_c_path = [] coverage_c_regexes = {} coverage_ignore_c_items = {} # ----------------------------------------------------------------------------- # Plots # ----------------------------------------------------------------------------- plot_pre_code = """ import numpy as np np.random.seed(0) """ plot_include_source = True plot_formats = [('png', 100), 'pdf'] import math phi = (math.sqrt(5) + 1)/2 import matplotlib matplotlib.rcParams.update({ 'font.size': 8, 'axes.titlesize': 8, 'axes.labelsize': 8, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 8, 'figure.figsize': (3*phi, 3), 'figure.subplot.bottom': 0.2, 'figure.subplot.left': 0.2, 'figure.subplot.right': 0.9, 'figure.subplot.top': 0.85, 'figure.subplot.wspace': 0.4, 'text.usetex': False, })
bsd-3-clause
tequa/ammisoft
ammimain/WinPython-64bit-2.7.13.1Zero/python-2.7.13.amd64/Lib/site-packages/matplotlib/axis.py
4
85084
""" Classes for the ticks and x and y axis """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from matplotlib import rcParams import matplotlib.artist as artist from matplotlib.artist import allow_rasterization import matplotlib.cbook as cbook import matplotlib.font_manager as font_manager import matplotlib.lines as mlines import matplotlib.patches as mpatches import matplotlib.scale as mscale import matplotlib.text as mtext import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.units as munits import numpy as np import warnings GRIDLINE_INTERPOLATION_STEPS = 180 class Tick(artist.Artist): """ Abstract base class for the axis ticks, grid lines and labels 1 refers to the bottom of the plot for xticks and the left for yticks 2 refers to the top of the plot for xticks and the right for yticks Publicly accessible attributes: :attr:`tick1line` a Line2D instance :attr:`tick2line` a Line2D instance :attr:`gridline` a Line2D instance :attr:`label1` a Text instance :attr:`label2` a Text instance :attr:`gridOn` a boolean which determines whether to draw the tickline :attr:`tick1On` a boolean which determines whether to draw the 1st tickline :attr:`tick2On` a boolean which determines whether to draw the 2nd tickline :attr:`label1On` a boolean which determines whether to draw tick label :attr:`label2On` a boolean which determines whether to draw tick label """ def __init__(self, axes, loc, label, size=None, # points width=None, color=None, tickdir=None, pad=None, labelsize=None, labelcolor=None, zorder=None, gridOn=None, # defaults to axes.grid depending on # axes.grid.which tick1On=True, tick2On=True, label1On=True, label2On=False, major=True, ): """ bbox is the Bound2D bounding box in display coords of the Axes loc is the tick location in data coords size is the tick size in points """ artist.Artist.__init__(self) if gridOn is None: if major and (rcParams['axes.grid.which'] in ('both', 'major')): gridOn = rcParams['axes.grid'] elif (not major) and (rcParams['axes.grid.which'] in ('both', 'minor')): gridOn = rcParams['axes.grid'] else: gridOn = False self.set_figure(axes.figure) self.axes = axes name = self.__name__.lower() self._name = name self._loc = loc if size is None: if major: size = rcParams['%s.major.size' % name] else: size = rcParams['%s.minor.size' % name] self._size = size if width is None: if major: width = rcParams['%s.major.width' % name] else: width = rcParams['%s.minor.width' % name] self._width = width if color is None: color = rcParams['%s.color' % name] self._color = color if pad is None: if major: pad = rcParams['%s.major.pad' % name] else: pad = rcParams['%s.minor.pad' % name] self._base_pad = pad if labelcolor is None: labelcolor = rcParams['%s.color' % name] self._labelcolor = labelcolor if labelsize is None: labelsize = rcParams['%s.labelsize' % name] self._labelsize = labelsize if zorder is None: if major: zorder = mlines.Line2D.zorder + 0.01 else: zorder = mlines.Line2D.zorder self._zorder = zorder self.apply_tickdir(tickdir) self.tick1line = self._get_tick1line() self.tick2line = self._get_tick2line() self.gridline = self._get_gridline() self.label1 = self._get_text1() self.label = self.label1 # legacy name self.label2 = self._get_text2() self.gridOn = gridOn self.tick1On = tick1On self.tick2On = tick2On self.label1On = label1On self.label2On = label2On self.update_position(loc) def apply_tickdir(self, tickdir): """ Calculate self._pad and self._tickmarkers """ pass def get_tickdir(self): return self._tickdir def get_tick_padding(self): """ Get the length of the tick outside of the axes. """ padding = { 'in': 0.0, 'inout': 0.5, 'out': 1.0 } return self._size * padding[self._tickdir] def get_children(self): children = [self.tick1line, self.tick2line, self.gridline, self.label1, self.label2] return children def set_clip_path(self, clippath, transform=None): artist.Artist.set_clip_path(self, clippath, transform) self.gridline.set_clip_path(clippath, transform) self.stale = True set_clip_path.__doc__ = artist.Artist.set_clip_path.__doc__ def get_pad_pixels(self): return self.figure.dpi * self._base_pad / 72.0 def contains(self, mouseevent): """ Test whether the mouse event occurred in the Tick marks. This function always returns false. It is more useful to test if the axis as a whole contains the mouse rather than the set of tick marks. """ if six.callable(self._contains): return self._contains(self, mouseevent) return False, {} def set_pad(self, val): """ Set the tick label pad in points ACCEPTS: float """ self._apply_params(pad=val) self.stale = True def get_pad(self): 'Get the value of the tick label pad in points' return self._base_pad def _get_text1(self): 'Get the default Text 1 instance' pass def _get_text2(self): 'Get the default Text 2 instance' pass def _get_tick1line(self): 'Get the default line2D instance for tick1' pass def _get_tick2line(self): 'Get the default line2D instance for tick2' pass def _get_gridline(self): 'Get the default grid Line2d instance for this tick' pass def get_loc(self): 'Return the tick location (data coords) as a scalar' return self._loc @allow_rasterization def draw(self, renderer): if not self.get_visible(): self.stale = False return renderer.open_group(self.__name__) if self.gridOn: self.gridline.draw(renderer) if self.tick1On: self.tick1line.draw(renderer) if self.tick2On: self.tick2line.draw(renderer) if self.label1On: self.label1.draw(renderer) if self.label2On: self.label2.draw(renderer) renderer.close_group(self.__name__) self.stale = False def set_label1(self, s): """ Set the text of ticklabel ACCEPTS: str """ self.label1.set_text(s) self.stale = True set_label = set_label1 def set_label2(self, s): """ Set the text of ticklabel2 ACCEPTS: str """ self.label2.set_text(s) self.stale = True def _set_artist_props(self, a): a.set_figure(self.figure) def get_view_interval(self): 'return the view Interval instance for the axis this tick is ticking' raise NotImplementedError('Derived must override') def _apply_params(self, **kw): switchkw = ['gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On'] switches = [k for k in kw if k in switchkw] for k in switches: setattr(self, k, kw.pop(k)) newmarker = [k for k in kw if k in ['size', 'width', 'pad', 'tickdir']] if newmarker: self._size = kw.pop('size', self._size) # Width could be handled outside this block, but it is # convenient to leave it here. self._width = kw.pop('width', self._width) self._base_pad = kw.pop('pad', self._base_pad) # apply_tickdir uses _size and _base_pad to make _pad, # and also makes _tickmarkers. self.apply_tickdir(kw.pop('tickdir', self._tickdir)) self.tick1line.set_marker(self._tickmarkers[0]) self.tick2line.set_marker(self._tickmarkers[1]) for line in (self.tick1line, self.tick2line): line.set_markersize(self._size) line.set_markeredgewidth(self._width) # _get_text1_transform uses _pad from apply_tickdir. trans = self._get_text1_transform()[0] self.label1.set_transform(trans) trans = self._get_text2_transform()[0] self.label2.set_transform(trans) tick_kw = dict([kv for kv in six.iteritems(kw) if kv[0] in ['color', 'zorder']]) if tick_kw: self.tick1line.set(**tick_kw) self.tick2line.set(**tick_kw) for k, v in six.iteritems(tick_kw): setattr(self, '_' + k, v) label_list = [k for k in six.iteritems(kw) if k[0] in ['labelsize', 'labelcolor']] if label_list: label_kw = dict([(k[5:], v) for (k, v) in label_list]) self.label1.set(**label_kw) self.label2.set(**label_kw) for k, v in six.iteritems(label_kw): # for labelsize the text objects covert str ('small') # -> points. grab the integer from the `Text` object # instead of saving the string representation v = getattr(self.label1, 'get_' + k)() setattr(self, '_label' + k, v) def update_position(self, loc): 'Set the location of tick in data coords with scalar *loc*' raise NotImplementedError('Derived must override') def _get_text1_transform(self): raise NotImplementedError('Derived must override') def _get_text2_transform(self): raise NotImplementedError('Derived must override') class XTick(Tick): """ Contains all the Artists needed to make an x tick - the tick line, the label text and the grid line """ __name__ = 'xtick' def _get_text1_transform(self): return self.axes.get_xaxis_text1_transform(self._pad) def _get_text2_transform(self): return self.axes.get_xaxis_text2_transform(self._pad) def apply_tickdir(self, tickdir): if tickdir is None: tickdir = rcParams['%s.direction' % self._name] self._tickdir = tickdir if self._tickdir == 'in': self._tickmarkers = (mlines.TICKUP, mlines.TICKDOWN) elif self._tickdir == 'inout': self._tickmarkers = ('|', '|') else: self._tickmarkers = (mlines.TICKDOWN, mlines.TICKUP) self._pad = self._base_pad + self.get_tick_padding() self.stale = True def _get_text1(self): 'Get the default Text instance' # the y loc is 3 points below the min of y axis # get the affine as an a,b,c,d,tx,ty list # x in data coords, y in axes coords trans, vert, horiz = self._get_text1_transform() t = mtext.Text( x=0, y=0, fontproperties=font_manager.FontProperties(size=self._labelsize), color=self._labelcolor, verticalalignment=vert, horizontalalignment=horiz, ) t.set_transform(trans) self._set_artist_props(t) return t def _get_text2(self): 'Get the default Text 2 instance' # x in data coords, y in axes coords trans, vert, horiz = self._get_text2_transform() t = mtext.Text( x=0, y=1, fontproperties=font_manager.FontProperties(size=self._labelsize), color=self._labelcolor, verticalalignment=vert, horizontalalignment=horiz, ) t.set_transform(trans) self._set_artist_props(t) return t def _get_tick1line(self): 'Get the default line2D instance' # x in data coords, y in axes coords l = mlines.Line2D(xdata=(0,), ydata=(0,), color=self._color, linestyle='None', marker=self._tickmarkers[0], markersize=self._size, markeredgewidth=self._width, zorder=self._zorder) l.set_transform(self.axes.get_xaxis_transform(which='tick1')) self._set_artist_props(l) return l def _get_tick2line(self): 'Get the default line2D instance' # x in data coords, y in axes coords l = mlines.Line2D(xdata=(0,), ydata=(1,), color=self._color, linestyle='None', marker=self._tickmarkers[1], markersize=self._size, markeredgewidth=self._width, zorder=self._zorder) l.set_transform(self.axes.get_xaxis_transform(which='tick2')) self._set_artist_props(l) return l def _get_gridline(self): 'Get the default line2D instance' # x in data coords, y in axes coords l = mlines.Line2D(xdata=(0.0, 0.0), ydata=(0, 1.0), color=rcParams['grid.color'], linestyle=rcParams['grid.linestyle'], linewidth=rcParams['grid.linewidth'], alpha=rcParams['grid.alpha'], markersize=0) l.set_transform(self.axes.get_xaxis_transform(which='grid')) l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self._set_artist_props(l) return l def update_position(self, loc): 'Set the location of tick in data coords with scalar *loc*' x = loc nonlinear = (hasattr(self.axes, 'yaxis') and self.axes.yaxis.get_scale() != 'linear' or hasattr(self.axes, 'xaxis') and self.axes.xaxis.get_scale() != 'linear') if self.tick1On: self.tick1line.set_xdata((x,)) if self.tick2On: self.tick2line.set_xdata((x,)) if self.gridOn: self.gridline.set_xdata((x,)) if self.label1On: self.label1.set_x(x) if self.label2On: self.label2.set_x(x) if nonlinear: self.tick1line._invalid = True self.tick2line._invalid = True self.gridline._invalid = True self._loc = loc self.stale = True def get_view_interval(self): 'return the Interval instance for this axis view limits' return self.axes.viewLim.intervalx class YTick(Tick): """ Contains all the Artists needed to make a Y tick - the tick line, the label text and the grid line """ __name__ = 'ytick' def _get_text1_transform(self): return self.axes.get_yaxis_text1_transform(self._pad) def _get_text2_transform(self): return self.axes.get_yaxis_text2_transform(self._pad) def apply_tickdir(self, tickdir): if tickdir is None: tickdir = rcParams['%s.direction' % self._name] self._tickdir = tickdir if self._tickdir == 'in': self._tickmarkers = (mlines.TICKRIGHT, mlines.TICKLEFT) elif self._tickdir == 'inout': self._tickmarkers = ('_', '_') else: self._tickmarkers = (mlines.TICKLEFT, mlines.TICKRIGHT) self._pad = self._base_pad + self.get_tick_padding() self.stale = True # how far from the y axis line the right of the ticklabel are def _get_text1(self): 'Get the default Text instance' # x in axes coords, y in data coords trans, vert, horiz = self._get_text1_transform() t = mtext.Text( x=0, y=0, fontproperties=font_manager.FontProperties(size=self._labelsize), color=self._labelcolor, verticalalignment=vert, horizontalalignment=horiz, ) t.set_transform(trans) self._set_artist_props(t) return t def _get_text2(self): 'Get the default Text instance' # x in axes coords, y in data coords trans, vert, horiz = self._get_text2_transform() t = mtext.Text( x=1, y=0, fontproperties=font_manager.FontProperties(size=self._labelsize), color=self._labelcolor, verticalalignment=vert, horizontalalignment=horiz, ) t.set_transform(trans) self._set_artist_props(t) return t def _get_tick1line(self): 'Get the default line2D instance' # x in axes coords, y in data coords l = mlines.Line2D((0,), (0,), color=self._color, marker=self._tickmarkers[0], linestyle='None', markersize=self._size, markeredgewidth=self._width, zorder=self._zorder) l.set_transform(self.axes.get_yaxis_transform(which='tick1')) self._set_artist_props(l) return l def _get_tick2line(self): 'Get the default line2D instance' # x in axes coords, y in data coords l = mlines.Line2D((1,), (0,), color=self._color, marker=self._tickmarkers[1], linestyle='None', markersize=self._size, markeredgewidth=self._width, zorder=self._zorder) l.set_transform(self.axes.get_yaxis_transform(which='tick2')) self._set_artist_props(l) return l def _get_gridline(self): 'Get the default line2D instance' # x in axes coords, y in data coords l = mlines.Line2D(xdata=(0, 1), ydata=(0, 0), color=rcParams['grid.color'], linestyle=rcParams['grid.linestyle'], linewidth=rcParams['grid.linewidth'], alpha=rcParams['grid.alpha'], markersize=0) l.set_transform(self.axes.get_yaxis_transform(which='grid')) l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self._set_artist_props(l) return l def update_position(self, loc): 'Set the location of tick in data coords with scalar loc' y = loc nonlinear = (hasattr(self.axes, 'yaxis') and self.axes.yaxis.get_scale() != 'linear' or hasattr(self.axes, 'xaxis') and self.axes.xaxis.get_scale() != 'linear') if self.tick1On: self.tick1line.set_ydata((y,)) if self.tick2On: self.tick2line.set_ydata((y,)) if self.gridOn: self.gridline.set_ydata((y, )) if self.label1On: self.label1.set_y(y) if self.label2On: self.label2.set_y(y) if nonlinear: self.tick1line._invalid = True self.tick2line._invalid = True self.gridline._invalid = True self._loc = loc self.stale = True def get_view_interval(self): 'return the Interval instance for this axis view limits' return self.axes.viewLim.intervaly class Ticker(object): locator = None formatter = None class Axis(artist.Artist): """ Public attributes * :attr:`axes.transData` - transform data coords to display coords * :attr:`axes.transAxes` - transform axis coords to display coords * :attr:`labelpad` - number of points between the axis and its label """ OFFSETTEXTPAD = 3 def __str__(self): return self.__class__.__name__ \ + "(%f,%f)" % tuple(self.axes.transAxes.transform_point((0, 0))) def __init__(self, axes, pickradius=15): """ Init the axis with the parent Axes instance """ artist.Artist.__init__(self) self.set_figure(axes.figure) # Keep track of setting to the default value, this allows use to know # if any of the following values is explicitly set by the user, so as # to not overwrite their settings with any of our 'auto' settings. self.isDefault_majloc = True self.isDefault_minloc = True self.isDefault_majfmt = True self.isDefault_minfmt = True self.isDefault_label = True self.axes = axes self.major = Ticker() self.minor = Ticker() self.callbacks = cbook.CallbackRegistry() self._autolabelpos = True self._smart_bounds = False self.label = self._get_label() self.labelpad = rcParams['axes.labelpad'] self.offsetText = self._get_offset_text() self.majorTicks = [] self.minorTicks = [] self.pickradius = pickradius # Initialize here for testing; later add API self._major_tick_kw = dict() self._minor_tick_kw = dict() self.cla() self._set_scale('linear') def set_label_coords(self, x, y, transform=None): """ Set the coordinates of the label. By default, the x coordinate of the y label is determined by the tick label bounding boxes, but this can lead to poor alignment of multiple ylabels if there are multiple axes. Ditto for the y coodinate of the x label. You can also specify the coordinate system of the label with the transform. If None, the default coordinate system will be the axes coordinate system (0,0) is (left,bottom), (0.5, 0.5) is middle, etc """ self._autolabelpos = False if transform is None: transform = self.axes.transAxes self.label.set_transform(transform) self.label.set_position((x, y)) self.stale = True def get_transform(self): return self._scale.get_transform() def get_scale(self): return self._scale.name def _set_scale(self, value, **kwargs): self._scale = mscale.scale_factory(value, self, **kwargs) self._scale.set_default_locators_and_formatters(self) self.isDefault_majloc = True self.isDefault_minloc = True self.isDefault_majfmt = True self.isDefault_minfmt = True def limit_range_for_scale(self, vmin, vmax): return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos()) def get_children(self): children = [self.label, self.offsetText] majorticks = self.get_major_ticks() minorticks = self.get_minor_ticks() children.extend(majorticks) children.extend(minorticks) return children def cla(self): 'clear the current axis' self.set_major_locator(mticker.AutoLocator()) self.set_major_formatter(mticker.ScalarFormatter()) self.set_minor_locator(mticker.NullLocator()) self.set_minor_formatter(mticker.NullFormatter()) self.set_label_text('') self._set_artist_props(self.label) # Keep track of setting to the default value, this allows use to know # if any of the following values is explicitly set by the user, so as # to not overwrite their settings with any of our 'auto' settings. self.isDefault_majloc = True self.isDefault_minloc = True self.isDefault_majfmt = True self.isDefault_minfmt = True self.isDefault_label = True # Clear the callback registry for this axis, or it may "leak" self.callbacks = cbook.CallbackRegistry() # whether the grids are on self._gridOnMajor = (rcParams['axes.grid'] and rcParams['axes.grid.which'] in ('both', 'major')) self._gridOnMinor = (rcParams['axes.grid'] and rcParams['axes.grid.which'] in ('both', 'minor')) self.label.set_text('') self._set_artist_props(self.label) self.reset_ticks() self.converter = None self.units = None self.set_units(None) self.stale = True def reset_ticks(self): # build a few default ticks; grow as necessary later; only # define 1 so properties set on ticks will be copied as they # grow cbook.popall(self.majorTicks) cbook.popall(self.minorTicks) self.majorTicks.extend([self._get_tick(major=True)]) self.minorTicks.extend([self._get_tick(major=False)]) self._lastNumMajorTicks = 1 self._lastNumMinorTicks = 1 def set_tick_params(self, which='major', reset=False, **kw): """ Set appearance parameters for ticks and ticklabels. For documentation of keyword arguments, see :meth:`matplotlib.axes.Axes.tick_params`. """ dicts = [] if which == 'major' or which == 'both': dicts.append(self._major_tick_kw) if which == 'minor' or which == 'both': dicts.append(self._minor_tick_kw) kwtrans = self._translate_tick_kw(kw, to_init_kw=True) for d in dicts: if reset: d.clear() d.update(kwtrans) if reset: self.reset_ticks() else: if which == 'major' or which == 'both': for tick in self.majorTicks: tick._apply_params(**self._major_tick_kw) if which == 'minor' or which == 'both': for tick in self.minorTicks: tick._apply_params(**self._minor_tick_kw) if 'labelcolor' in kwtrans: self.offsetText.set_color(kwtrans['labelcolor']) self.stale = True @staticmethod def _translate_tick_kw(kw, to_init_kw=True): # We may want to move the following function to # a more visible location; or maybe there already # is something like this. def _bool(arg): if cbook.is_string_like(arg): if arg.lower() == 'on': return True if arg.lower() == 'off': return False raise ValueError('String "%s" should be "on" or "off"' % arg) return bool(arg) # The following lists may be moved to a more # accessible location. kwkeys0 = ['size', 'width', 'color', 'tickdir', 'pad', 'labelsize', 'labelcolor', 'zorder', 'gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On'] kwkeys1 = ['length', 'direction', 'left', 'bottom', 'right', 'top', 'labelleft', 'labelbottom', 'labelright', 'labeltop'] kwkeys = kwkeys0 + kwkeys1 kwtrans = dict() if to_init_kw: if 'length' in kw: kwtrans['size'] = kw.pop('length') if 'direction' in kw: kwtrans['tickdir'] = kw.pop('direction') if 'left' in kw: kwtrans['tick1On'] = _bool(kw.pop('left')) if 'bottom' in kw: kwtrans['tick1On'] = _bool(kw.pop('bottom')) if 'right' in kw: kwtrans['tick2On'] = _bool(kw.pop('right')) if 'top' in kw: kwtrans['tick2On'] = _bool(kw.pop('top')) if 'labelleft' in kw: kwtrans['label1On'] = _bool(kw.pop('labelleft')) if 'labelbottom' in kw: kwtrans['label1On'] = _bool(kw.pop('labelbottom')) if 'labelright' in kw: kwtrans['label2On'] = _bool(kw.pop('labelright')) if 'labeltop' in kw: kwtrans['label2On'] = _bool(kw.pop('labeltop')) if 'colors' in kw: c = kw.pop('colors') kwtrans['color'] = c kwtrans['labelcolor'] = c # Maybe move the checking up to the caller of this method. for key in kw: if key not in kwkeys: raise ValueError( "keyword %s is not recognized; valid keywords are %s" % (key, kwkeys)) kwtrans.update(kw) else: raise NotImplementedError("Inverse translation is deferred") return kwtrans def set_clip_path(self, clippath, transform=None): artist.Artist.set_clip_path(self, clippath, transform) for child in self.majorTicks + self.minorTicks: child.set_clip_path(clippath, transform) self.stale = True def get_view_interval(self): 'return the Interval instance for this axis view limits' raise NotImplementedError('Derived must override') def set_view_interval(self, vmin, vmax, ignore=False): raise NotImplementedError('Derived must override') def get_data_interval(self): 'return the Interval instance for this axis data limits' raise NotImplementedError('Derived must override') def set_data_interval(self): '''set the axis data limits''' raise NotImplementedError('Derived must override') def set_default_intervals(self): '''set the default limits for the axis data and view interval if they are not mutated''' # this is mainly in support of custom object plotting. For # example, if someone passes in a datetime object, we do not # know automagically how to set the default min/max of the # data and view limits. The unit conversion AxisInfo # interface provides a hook for custom types to register # default limits through the AxisInfo.default_limits # attribute, and the derived code below will check for that # and use it if is available (else just use 0..1) pass def _set_artist_props(self, a): if a is None: return a.set_figure(self.figure) def iter_ticks(self): """ Iterate through all of the major and minor ticks. """ majorLocs = self.major.locator() majorTicks = self.get_major_ticks(len(majorLocs)) self.major.formatter.set_locs(majorLocs) majorLabels = [self.major.formatter(val, i) for i, val in enumerate(majorLocs)] minorLocs = self.minor.locator() minorTicks = self.get_minor_ticks(len(minorLocs)) self.minor.formatter.set_locs(minorLocs) minorLabels = [self.minor.formatter(val, i) for i, val in enumerate(minorLocs)] major_minor = [ (majorTicks, majorLocs, majorLabels), (minorTicks, minorLocs, minorLabels)] for group in major_minor: for tick in zip(*group): yield tick def get_ticklabel_extents(self, renderer): """ Get the extents of the tick labels on either side of the axes. """ ticks_to_draw = self._update_ticks(renderer) ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, renderer) if len(ticklabelBoxes): bbox = mtransforms.Bbox.union(ticklabelBoxes) else: bbox = mtransforms.Bbox.from_extents(0, 0, 0, 0) if len(ticklabelBoxes2): bbox2 = mtransforms.Bbox.union(ticklabelBoxes2) else: bbox2 = mtransforms.Bbox.from_extents(0, 0, 0, 0) return bbox, bbox2 def set_smart_bounds(self, value): """set the axis to have smart bounds""" self._smart_bounds = value self.stale = True def get_smart_bounds(self): """get whether the axis has smart bounds""" return self._smart_bounds def _update_ticks(self, renderer): """ Update ticks (position and labels) using the current data interval of the axes. Returns a list of ticks that will be drawn. """ interval = self.get_view_interval() tick_tups = [t for t in self.iter_ticks()] if self._smart_bounds: # handle inverted limits view_low, view_high = min(*interval), max(*interval) data_low, data_high = self.get_data_interval() if data_low > data_high: data_low, data_high = data_high, data_low locs = [ti[1] for ti in tick_tups] locs.sort() locs = np.array(locs) if len(locs): if data_low <= view_low: # data extends beyond view, take view as limit ilow = view_low else: # data stops within view, take best tick cond = locs <= data_low good_locs = locs[cond] if len(good_locs) > 0: # last tick prior or equal to first data point ilow = good_locs[-1] else: # No ticks (why not?), take first tick ilow = locs[0] if data_high >= view_high: # data extends beyond view, take view as limit ihigh = view_high else: # data stops within view, take best tick cond = locs >= data_high good_locs = locs[cond] if len(good_locs) > 0: # first tick after or equal to last data point ihigh = good_locs[0] else: # No ticks (why not?), take last tick ihigh = locs[-1] tick_tups = [ti for ti in tick_tups if (ti[1] >= ilow) and (ti[1] <= ihigh)] # so that we don't lose ticks on the end, expand out the interval ever # so slightly. The "ever so slightly" is defined to be the width of a # half of a pixel. We don't want to draw a tick that even one pixel # outside of the defined axis interval. if interval[0] <= interval[1]: interval_expanded = interval else: interval_expanded = interval[1], interval[0] if hasattr(self, '_get_pixel_distance_along_axis'): # normally, one does not want to catch all exceptions that # could possibly happen, but it is not clear exactly what # exceptions might arise from a user's projection (their # rendition of the Axis object). So, we catch all, with # the idea that one would rather potentially lose a tick # from one side of the axis or another, rather than see a # stack trace. # We also catch users warnings here. These are the result of # invalid numpy calculations that may be the result of out of # bounds on axis with finite allowed intervals such as geo # projections i.e. Mollweide. with np.errstate(invalid='ignore'): try: ds1 = self._get_pixel_distance_along_axis( interval_expanded[0], -0.5) except: warnings.warn("Unable to find pixel distance along axis " "for interval padding of ticks; assuming no " "interval padding needed.") ds1 = 0.0 if np.isnan(ds1): ds1 = 0.0 try: ds2 = self._get_pixel_distance_along_axis( interval_expanded[1], +0.5) except: warnings.warn("Unable to find pixel distance along axis " "for interval padding of ticks; assuming no " "interval padding needed.") ds2 = 0.0 if np.isnan(ds2): ds2 = 0.0 interval_expanded = (interval_expanded[0] - ds1, interval_expanded[1] + ds2) ticks_to_draw = [] for tick, loc, label in tick_tups: if tick is None: continue if not mtransforms.interval_contains(interval_expanded, loc): continue tick.update_position(loc) tick.set_label1(label) tick.set_label2(label) ticks_to_draw.append(tick) return ticks_to_draw def _get_tick_bboxes(self, ticks, renderer): """ Given the list of ticks, return two lists of bboxes. One for tick lable1's and another for tick label2's. """ ticklabelBoxes = [] ticklabelBoxes2 = [] for tick in ticks: if tick.label1On and tick.label1.get_visible(): extent = tick.label1.get_window_extent(renderer) ticklabelBoxes.append(extent) if tick.label2On and tick.label2.get_visible(): extent = tick.label2.get_window_extent(renderer) ticklabelBoxes2.append(extent) return ticklabelBoxes, ticklabelBoxes2 def get_tightbbox(self, renderer): """ Return a bounding box that encloses the axis. It only accounts tick labels, axis label, and offsetText. """ if not self.get_visible(): return ticks_to_draw = self._update_ticks(renderer) ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, renderer) self._update_label_position(ticklabelBoxes, ticklabelBoxes2) self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2) self.offsetText.set_text(self.major.formatter.get_offset()) bb = [] for a in [self.label, self.offsetText]: if a.get_visible(): bb.append(a.get_window_extent(renderer)) bb.extend(ticklabelBoxes) bb.extend(ticklabelBoxes2) bb = [b for b in bb if b.width != 0 or b.height != 0] if bb: _bbox = mtransforms.Bbox.union(bb) return _bbox else: return None def get_tick_padding(self): values = [] if len(self.majorTicks): values.append(self.majorTicks[0].get_tick_padding()) if len(self.minorTicks): values.append(self.minorTicks[0].get_tick_padding()) if len(values): return max(values) return 0.0 @allow_rasterization def draw(self, renderer, *args, **kwargs): 'Draw the axis lines, grid lines, tick lines and labels' if not self.get_visible(): return renderer.open_group(__name__) ticks_to_draw = self._update_ticks(renderer) ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, renderer) for tick in ticks_to_draw: tick.draw(renderer) # scale up the axis label box to also find the neighbors, not # just the tick labels that actually overlap note we need a # *copy* of the axis label box because we don't wan't to scale # the actual bbox self._update_label_position(ticklabelBoxes, ticklabelBoxes2) self.label.draw(renderer) self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2) self.offsetText.set_text(self.major.formatter.get_offset()) self.offsetText.draw(renderer) if 0: # draw the bounding boxes around the text for debug for tick in self.majorTicks: label = tick.label1 mpatches.bbox_artist(label, renderer) mpatches.bbox_artist(self.label, renderer) renderer.close_group(__name__) self.stale = False def _get_label(self): raise NotImplementedError('Derived must override') def _get_offset_text(self): raise NotImplementedError('Derived must override') def get_gridlines(self): 'Return the grid lines as a list of Line2D instance' ticks = self.get_major_ticks() return cbook.silent_list('Line2D gridline', [tick.gridline for tick in ticks]) def get_label(self): 'Return the axis label as a Text instance' return self.label def get_offset_text(self): 'Return the axis offsetText as a Text instance' return self.offsetText def get_pickradius(self): 'Return the depth of the axis used by the picker' return self.pickradius def get_majorticklabels(self): 'Return a list of Text instances for the major ticklabels' ticks = self.get_major_ticks() labels1 = [tick.label1 for tick in ticks if tick.label1On] labels2 = [tick.label2 for tick in ticks if tick.label2On] return cbook.silent_list('Text major ticklabel', labels1 + labels2) def get_minorticklabels(self): 'Return a list of Text instances for the minor ticklabels' ticks = self.get_minor_ticks() labels1 = [tick.label1 for tick in ticks if tick.label1On] labels2 = [tick.label2 for tick in ticks if tick.label2On] return cbook.silent_list('Text minor ticklabel', labels1 + labels2) def get_ticklabels(self, minor=False, which=None): """ Get the x tick labels as a list of :class:`~matplotlib.text.Text` instances. Parameters ---------- minor : bool If True return the minor ticklabels, else return the major ticklabels which : None, ('minor', 'major', 'both') Overrides `minor`. Selects which ticklabels to return Returns ------- ret : list List of :class:`~matplotlib.text.Text` instances. """ if which is not None: if which == 'minor': return self.get_minorticklabels() elif which == 'major': return self.get_majorticklabels() elif which == 'both': return self.get_majorticklabels() + self.get_minorticklabels() else: raise ValueError("`which` must be one of ('minor', 'major', " "'both') not " + str(which)) if minor: return self.get_minorticklabels() return self.get_majorticklabels() def get_majorticklines(self): 'Return the major tick lines as a list of Line2D instances' lines = [] ticks = self.get_major_ticks() for tick in ticks: lines.append(tick.tick1line) lines.append(tick.tick2line) return cbook.silent_list('Line2D ticklines', lines) def get_minorticklines(self): 'Return the minor tick lines as a list of Line2D instances' lines = [] ticks = self.get_minor_ticks() for tick in ticks: lines.append(tick.tick1line) lines.append(tick.tick2line) return cbook.silent_list('Line2D ticklines', lines) def get_ticklines(self, minor=False): 'Return the tick lines as a list of Line2D instances' if minor: return self.get_minorticklines() return self.get_majorticklines() def get_majorticklocs(self): "Get the major tick locations in data coordinates as a numpy array" return self.major.locator() def get_minorticklocs(self): "Get the minor tick locations in data coordinates as a numpy array" return self.minor.locator() def get_ticklocs(self, minor=False): "Get the tick locations in data coordinates as a numpy array" if minor: return self.minor.locator() return self.major.locator() def _get_tick(self, major): 'return the default tick instance' raise NotImplementedError('derived must override') def _copy_tick_props(self, src, dest): 'Copy the props from src tick to dest tick' if src is None or dest is None: return dest.label1.update_from(src.label1) dest.label2.update_from(src.label2) dest.tick1line.update_from(src.tick1line) dest.tick2line.update_from(src.tick2line) dest.gridline.update_from(src.gridline) dest.tick1On = src.tick1On dest.tick2On = src.tick2On dest.label1On = src.label1On dest.label2On = src.label2On def get_label_text(self): 'Get the text of the label' return self.label.get_text() def get_major_locator(self): 'Get the locator of the major ticker' return self.major.locator def get_minor_locator(self): 'Get the locator of the minor ticker' return self.minor.locator def get_major_formatter(self): 'Get the formatter of the major ticker' return self.major.formatter def get_minor_formatter(self): 'Get the formatter of the minor ticker' return self.minor.formatter def get_major_ticks(self, numticks=None): 'get the tick instances; grow as necessary' if numticks is None: numticks = len(self.get_major_locator()()) if len(self.majorTicks) < numticks: # update the new tick label properties from the old for i in range(numticks - len(self.majorTicks)): tick = self._get_tick(major=True) self.majorTicks.append(tick) if self._lastNumMajorTicks < numticks: protoTick = self.majorTicks[0] for i in range(self._lastNumMajorTicks, len(self.majorTicks)): tick = self.majorTicks[i] if self._gridOnMajor: tick.gridOn = True self._copy_tick_props(protoTick, tick) self._lastNumMajorTicks = numticks ticks = self.majorTicks[:numticks] return ticks def get_minor_ticks(self, numticks=None): 'get the minor tick instances; grow as necessary' if numticks is None: numticks = len(self.get_minor_locator()()) if len(self.minorTicks) < numticks: # update the new tick label properties from the old for i in range(numticks - len(self.minorTicks)): tick = self._get_tick(major=False) self.minorTicks.append(tick) if self._lastNumMinorTicks < numticks: protoTick = self.minorTicks[0] for i in range(self._lastNumMinorTicks, len(self.minorTicks)): tick = self.minorTicks[i] if self._gridOnMinor: tick.gridOn = True self._copy_tick_props(protoTick, tick) self._lastNumMinorTicks = numticks ticks = self.minorTicks[:numticks] return ticks def grid(self, b=None, which='major', **kwargs): """ Set the axis grid on or off; b is a boolean. Use *which* = 'major' | 'minor' | 'both' to set the grid for major or minor ticks. If *b* is *None* and len(kwargs)==0, toggle the grid state. If *kwargs* are supplied, it is assumed you want the grid on and *b* will be set to True. *kwargs* are used to set the line properties of the grids, e.g., xax.grid(color='r', linestyle='-', linewidth=2) """ if len(kwargs): b = True which = which.lower() if which in ['minor', 'both']: if b is None: self._gridOnMinor = not self._gridOnMinor else: self._gridOnMinor = b for tick in self.minorTicks: # don't use get_ticks here! if tick is None: continue tick.gridOn = self._gridOnMinor if len(kwargs): tick.gridline.update(kwargs) self._minor_tick_kw['gridOn'] = self._gridOnMinor if which in ['major', 'both']: if b is None: self._gridOnMajor = not self._gridOnMajor else: self._gridOnMajor = b for tick in self.majorTicks: # don't use get_ticks here! if tick is None: continue tick.gridOn = self._gridOnMajor if len(kwargs): tick.gridline.update(kwargs) self._major_tick_kw['gridOn'] = self._gridOnMajor self.stale = True def update_units(self, data): """ introspect *data* for units converter and update the axis.converter instance if necessary. Return *True* if *data* is registered for unit conversion. """ converter = munits.registry.get_converter(data) if converter is None: return False neednew = self.converter != converter self.converter = converter default = self.converter.default_units(data, self) if default is not None and self.units is None: self.set_units(default) if neednew: self._update_axisinfo() self.stale = True return True def _update_axisinfo(self): """ check the axis converter for the stored units to see if the axis info needs to be updated """ if self.converter is None: return info = self.converter.axisinfo(self.units, self) if info is None: return if info.majloc is not None and \ self.major.locator != info.majloc and self.isDefault_majloc: self.set_major_locator(info.majloc) self.isDefault_majloc = True if info.minloc is not None and \ self.minor.locator != info.minloc and self.isDefault_minloc: self.set_minor_locator(info.minloc) self.isDefault_minloc = True if info.majfmt is not None and \ self.major.formatter != info.majfmt and self.isDefault_majfmt: self.set_major_formatter(info.majfmt) self.isDefault_majfmt = True if info.minfmt is not None and \ self.minor.formatter != info.minfmt and self.isDefault_minfmt: self.set_minor_formatter(info.minfmt) self.isDefault_minfmt = True if info.label is not None and self.isDefault_label: self.set_label_text(info.label) self.isDefault_label = True self.set_default_intervals() def have_units(self): return self.converter is not None or self.units is not None def convert_units(self, x): if self.converter is None: self.converter = munits.registry.get_converter(x) if self.converter is None: return x ret = self.converter.convert(x, self.units, self) return ret def set_units(self, u): """ set the units for axis ACCEPTS: a units tag """ pchanged = False if u is None: self.units = None pchanged = True else: if u != self.units: self.units = u pchanged = True if pchanged: self._update_axisinfo() self.callbacks.process('units') self.callbacks.process('units finalize') self.stale = True def get_units(self): 'return the units for axis' return self.units def set_label_text(self, label, fontdict=None, **kwargs): """ Sets the text value of the axis label ACCEPTS: A string value for the label """ self.isDefault_label = False self.label.set_text(label) if fontdict is not None: self.label.update(fontdict) self.label.update(kwargs) self.stale = True return self.label def set_major_formatter(self, formatter): """ Set the formatter of the major ticker ACCEPTS: A :class:`~matplotlib.ticker.Formatter` instance """ self.isDefault_majfmt = False self.major.formatter = formatter formatter.set_axis(self) self.stale = True def set_minor_formatter(self, formatter): """ Set the formatter of the minor ticker ACCEPTS: A :class:`~matplotlib.ticker.Formatter` instance """ self.isDefault_minfmt = False self.minor.formatter = formatter formatter.set_axis(self) self.stale = True def set_major_locator(self, locator): """ Set the locator of the major ticker ACCEPTS: a :class:`~matplotlib.ticker.Locator` instance """ self.isDefault_majloc = False self.major.locator = locator locator.set_axis(self) self.stale = True def set_minor_locator(self, locator): """ Set the locator of the minor ticker ACCEPTS: a :class:`~matplotlib.ticker.Locator` instance """ self.isDefault_minloc = False self.minor.locator = locator locator.set_axis(self) self.stale = True def set_pickradius(self, pickradius): """ Set the depth of the axis used by the picker ACCEPTS: a distance in points """ self.pickradius = pickradius def set_ticklabels(self, ticklabels, *args, **kwargs): """ Set the text values of the tick labels. Return a list of Text instances. Use *kwarg* *minor=True* to select minor ticks. All other kwargs are used to update the text object properties. As for get_ticklabels, label1 (left or bottom) is affected for a given tick only if its label1On attribute is True, and similarly for label2. The list of returned label text objects consists of all such label1 objects followed by all such label2 objects. The input *ticklabels* is assumed to match the set of tick locations, regardless of the state of label1On and label2On. ACCEPTS: sequence of strings or Text objects """ get_labels = [] for t in ticklabels: # try calling get_text() to check whether it is Text object # if it is Text, get label content try: get_labels.append(t.get_text()) # otherwise add the label to the list directly except AttributeError: get_labels.append(t) # replace the ticklabels list with the processed one ticklabels = get_labels minor = kwargs.pop('minor', False) if minor: self.set_minor_formatter(mticker.FixedFormatter(ticklabels)) ticks = self.get_minor_ticks() else: self.set_major_formatter(mticker.FixedFormatter(ticklabels)) ticks = self.get_major_ticks() ret = [] for tick_label, tick in zip(ticklabels, ticks): # deal with label1 tick.label1.set_text(tick_label) tick.label1.update(kwargs) # deal with label2 tick.label2.set_text(tick_label) tick.label2.update(kwargs) # only return visible tick labels if tick.label1On: ret.append(tick.label1) if tick.label2On: ret.append(tick.label2) self.stale = True return ret def set_ticks(self, ticks, minor=False): """ Set the locations of the tick marks from sequence ticks ACCEPTS: sequence of floats """ # XXX if the user changes units, the information will be lost here ticks = self.convert_units(ticks) if len(ticks) > 1: xleft, xright = self.get_view_interval() if xright > xleft: self.set_view_interval(min(ticks), max(ticks)) else: self.set_view_interval(max(ticks), min(ticks)) if minor: self.set_minor_locator(mticker.FixedLocator(ticks)) return self.get_minor_ticks(len(ticks)) else: self.set_major_locator(mticker.FixedLocator(ticks)) return self.get_major_ticks(len(ticks)) def _update_label_position(self, bboxes, bboxes2): """ Update the label position based on the bounding box enclosing all the ticklabels and axis spine """ raise NotImplementedError('Derived must override') def _update_offset_text_postion(self, bboxes, bboxes2): """ Update the label position based on the sequence of bounding boxes of all the ticklabels """ raise NotImplementedError('Derived must override') def pan(self, numsteps): 'Pan *numsteps* (can be positive or negative)' self.major.locator.pan(numsteps) def zoom(self, direction): "Zoom in/out on axis; if *direction* is >0 zoom in, else zoom out" self.major.locator.zoom(direction) def axis_date(self, tz=None): """ Sets up x-axis ticks and labels that treat the x data as dates. *tz* is a :class:`tzinfo` instance or a timezone string. This timezone is used to create date labels. """ # By providing a sample datetime instance with the desired # timezone, the registered converter can be selected, # and the "units" attribute, which is the timezone, can # be set. import datetime if isinstance(tz, six.string_types): import pytz tz = pytz.timezone(tz) self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz)) def get_tick_space(self): """ Return the estimated number of ticks that can fit on the axis. """ # Must be overridden in the subclass raise NotImplementedError() def get_label_position(self): """ Return the label position (top or bottom) """ return self.label_position def set_label_position(self, position): """ Set the label position (top or bottom) ACCEPTS: [ 'top' | 'bottom' ] """ raise NotImplementedError() def get_minpos(self): raise NotImplementedError() class XAxis(Axis): __name__ = 'xaxis' axis_name = 'x' def contains(self, mouseevent): """Test whether the mouse event occured in the x axis. """ if six.callable(self._contains): return self._contains(self, mouseevent) x, y = mouseevent.x, mouseevent.y try: trans = self.axes.transAxes.inverted() xaxes, yaxes = trans.transform_point((x, y)) except ValueError: return False, {} l, b = self.axes.transAxes.transform_point((0, 0)) r, t = self.axes.transAxes.transform_point((1, 1)) inaxis = xaxes >= 0 and xaxes <= 1 and ( (y < b and y > b - self.pickradius) or (y > t and y < t + self.pickradius)) return inaxis, {} def _get_tick(self, major): if major: tick_kw = self._major_tick_kw else: tick_kw = self._minor_tick_kw return XTick(self.axes, 0, '', major=major, **tick_kw) def _get_label(self): # x in axes coords, y in display coords (to be updated at draw # time by _update_label_positions) label = mtext.Text(x=0.5, y=0, fontproperties=font_manager.FontProperties( size=rcParams['axes.labelsize'], weight=rcParams['axes.labelweight']), color=rcParams['axes.labelcolor'], verticalalignment='top', horizontalalignment='center') label.set_transform(mtransforms.blended_transform_factory( self.axes.transAxes, mtransforms.IdentityTransform())) self._set_artist_props(label) self.label_position = 'bottom' return label def _get_offset_text(self): # x in axes coords, y in display coords (to be updated at draw time) offsetText = mtext.Text(x=1, y=0, fontproperties=font_manager.FontProperties( size=rcParams['xtick.labelsize']), color=rcParams['xtick.color'], verticalalignment='top', horizontalalignment='right') offsetText.set_transform(mtransforms.blended_transform_factory( self.axes.transAxes, mtransforms.IdentityTransform()) ) self._set_artist_props(offsetText) self.offset_text_position = 'bottom' return offsetText def _get_pixel_distance_along_axis(self, where, perturb): """ Returns the amount, in data coordinates, that a single pixel corresponds to in the locality given by "where", which is also given in data coordinates, and is an x coordinate. "perturb" is the amount to perturb the pixel. Usually +0.5 or -0.5. Implementing this routine for an axis is optional; if present, it will ensure that no ticks are lost due to round-off at the extreme ends of an axis. """ # Note that this routine does not work for a polar axis, because of # the 1e-10 below. To do things correctly, we need to use rmax # instead of 1e-10 for a polar axis. But since we do not have that # kind of information at this point, we just don't try to pad anything # for the theta axis of a polar plot. if self.axes.name == 'polar': return 0.0 # # first figure out the pixel location of the "where" point. We use # 1e-10 for the y point, so that we remain compatible with log axes. # transformation from data coords to display coords trans = self.axes.transData # transformation from display coords to data coords transinv = trans.inverted() pix = trans.transform_point((where, 1e-10)) # perturb the pixel ptp = transinv.transform_point((pix[0] + perturb, pix[1])) dx = abs(ptp[0] - where) return dx def set_label_position(self, position): """ Set the label position (top or bottom) ACCEPTS: [ 'top' | 'bottom' ] """ if position == 'top': self.label.set_verticalalignment('baseline') elif position == 'bottom': self.label.set_verticalalignment('top') else: msg = "Position accepts only [ 'top' | 'bottom' ]" raise ValueError(msg) self.label_position = position self.stale = True def _update_label_position(self, bboxes, bboxes2): """ Update the label position based on the bounding box enclosing all the ticklabels and axis spine """ if not self._autolabelpos: return x, y = self.label.get_position() if self.label_position == 'bottom': try: spine = self.axes.spines['bottom'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() except KeyError: # use axes if spine doesn't exist spinebbox = self.axes.bbox bbox = mtransforms.Bbox.union(bboxes + [spinebbox]) bottom = bbox.y0 self.label.set_position( (x, bottom - self.labelpad * self.figure.dpi / 72.0) ) else: try: spine = self.axes.spines['top'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() except KeyError: # use axes if spine doesn't exist spinebbox = self.axes.bbox bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox]) top = bbox.y1 self.label.set_position( (x, top + self.labelpad * self.figure.dpi / 72.0) ) def _update_offset_text_position(self, bboxes, bboxes2): """ Update the offset_text position based on the sequence of bounding boxes of all the ticklabels """ x, y = self.offsetText.get_position() if not len(bboxes): bottom = self.axes.bbox.ymin else: bbox = mtransforms.Bbox.union(bboxes) bottom = bbox.y0 self.offsetText.set_position( (x, bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72.0) ) def get_text_heights(self, renderer): """ Returns the amount of space one should reserve for text above and below the axes. Returns a tuple (above, below) """ bbox, bbox2 = self.get_ticklabel_extents(renderer) # MGDTODO: Need a better way to get the pad padPixels = self.majorTicks[0].get_pad_pixels() above = 0.0 if bbox2.height: above += bbox2.height + padPixels below = 0.0 if bbox.height: below += bbox.height + padPixels if self.get_label_position() == 'top': above += self.label.get_window_extent(renderer).height + padPixels else: below += self.label.get_window_extent(renderer).height + padPixels return above, below def set_ticks_position(self, position): """ Set the ticks position (top, bottom, both, default or none) both sets the ticks to appear on both positions, but does not change the tick labels. 'default' resets the tick positions to the default: ticks on both positions, labels at bottom. 'none' can be used if you don't want any ticks. 'none' and 'both' affect only the ticks, not the labels. ACCEPTS: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ] """ if position == 'top': self.set_tick_params(which='both', top=True, labeltop=True, bottom=False, labelbottom=False) elif position == 'bottom': self.set_tick_params(which='both', top=False, labeltop=False, bottom=True, labelbottom=True) elif position == 'both': self.set_tick_params(which='both', top=True, bottom=True) elif position == 'none': self.set_tick_params(which='both', top=False, bottom=False) elif position == 'default': self.set_tick_params(which='both', top=True, labeltop=False, bottom=True, labelbottom=True) else: raise ValueError("invalid position: %s" % position) self.stale = True def tick_top(self): 'use ticks only on top' self.set_ticks_position('top') def tick_bottom(self): 'use ticks only on bottom' self.set_ticks_position('bottom') def get_ticks_position(self): """ Return the ticks position (top, bottom, default or unknown) """ majt = self.majorTicks[0] mT = self.minorTicks[0] majorTop = ((not majt.tick1On) and majt.tick2On and (not majt.label1On) and majt.label2On) minorTop = ((not mT.tick1On) and mT.tick2On and (not mT.label1On) and mT.label2On) if majorTop and minorTop: return 'top' MajorBottom = (majt.tick1On and (not majt.tick2On) and majt.label1On and (not majt.label2On)) MinorBottom = (mT.tick1On and (not mT.tick2On) and mT.label1On and (not mT.label2On)) if MajorBottom and MinorBottom: return 'bottom' majorDefault = (majt.tick1On and majt.tick2On and majt.label1On and (not majt.label2On)) minorDefault = (mT.tick1On and mT.tick2On and mT.label1On and (not mT.label2On)) if majorDefault and minorDefault: return 'default' return 'unknown' def get_view_interval(self): 'return the Interval instance for this axis view limits' return self.axes.viewLim.intervalx def set_view_interval(self, vmin, vmax, ignore=False): """ If *ignore* is *False*, the order of vmin, vmax does not matter; the original axis orientation will be preserved. In addition, the view limits can be expanded, but will not be reduced. This method is for mpl internal use; for normal use, see :meth:`~matplotlib.axes.Axes.set_xlim`. """ if ignore: self.axes.viewLim.intervalx = vmin, vmax else: Vmin, Vmax = self.get_view_interval() if Vmin < Vmax: self.axes.viewLim.intervalx = (min(vmin, vmax, Vmin), max(vmin, vmax, Vmax)) else: self.axes.viewLim.intervalx = (max(vmin, vmax, Vmin), min(vmin, vmax, Vmax)) def get_minpos(self): return self.axes.dataLim.minposx def get_data_interval(self): 'return the Interval instance for this axis data limits' return self.axes.dataLim.intervalx def set_data_interval(self, vmin, vmax, ignore=False): 'set the axis data limits' if ignore: self.axes.dataLim.intervalx = vmin, vmax else: Vmin, Vmax = self.get_data_interval() self.axes.dataLim.intervalx = min(vmin, Vmin), max(vmax, Vmax) self.stale = True def set_default_intervals(self): 'set the default limits for the axis interval if they are not mutated' xmin, xmax = 0., 1. dataMutated = self.axes.dataLim.mutatedx() viewMutated = self.axes.viewLim.mutatedx() if not dataMutated or not viewMutated: if self.converter is not None: info = self.converter.axisinfo(self.units, self) if info.default_limits is not None: valmin, valmax = info.default_limits xmin = self.converter.convert(valmin, self.units, self) xmax = self.converter.convert(valmax, self.units, self) if not dataMutated: self.axes.dataLim.intervalx = xmin, xmax if not viewMutated: self.axes.viewLim.intervalx = xmin, xmax self.stale = True def get_tick_space(self): ends = self.axes.transAxes.transform([[0, 0], [1, 0]]) length = ((ends[1][0] - ends[0][0]) / self.axes.figure.dpi) * 72.0 tick = self._get_tick(True) # There is a heuristic here that the aspect ratio of tick text # is no more than 3:1 size = tick.label1.get_size() * 3 if size > 0: return int(np.floor(length / size)) else: return 2**31 - 1 class YAxis(Axis): __name__ = 'yaxis' axis_name = 'y' def contains(self, mouseevent): """Test whether the mouse event occurred in the y axis. Returns *True* | *False* """ if six.callable(self._contains): return self._contains(self, mouseevent) x, y = mouseevent.x, mouseevent.y try: trans = self.axes.transAxes.inverted() xaxes, yaxes = trans.transform_point((x, y)) except ValueError: return False, {} l, b = self.axes.transAxes.transform_point((0, 0)) r, t = self.axes.transAxes.transform_point((1, 1)) inaxis = yaxes >= 0 and yaxes <= 1 and ( (x < l and x > l - self.pickradius) or (x > r and x < r + self.pickradius)) return inaxis, {} def _get_tick(self, major): if major: tick_kw = self._major_tick_kw else: tick_kw = self._minor_tick_kw return YTick(self.axes, 0, '', major=major, **tick_kw) def _get_label(self): # x in display coords (updated by _update_label_position) # y in axes coords label = mtext.Text(x=0, y=0.5, # todo: get the label position fontproperties=font_manager.FontProperties( size=rcParams['axes.labelsize'], weight=rcParams['axes.labelweight']), color=rcParams['axes.labelcolor'], verticalalignment='bottom', horizontalalignment='center', rotation='vertical', rotation_mode='anchor') label.set_transform(mtransforms.blended_transform_factory( mtransforms.IdentityTransform(), self.axes.transAxes)) self._set_artist_props(label) self.label_position = 'left' return label def _get_offset_text(self): # x in display coords, y in axes coords (to be updated at draw time) offsetText = mtext.Text(x=0, y=0.5, fontproperties=font_manager.FontProperties( size=rcParams['ytick.labelsize'] ), color=rcParams['ytick.color'], verticalalignment='baseline', horizontalalignment='left') offsetText.set_transform(mtransforms.blended_transform_factory( self.axes.transAxes, mtransforms.IdentityTransform()) ) self._set_artist_props(offsetText) self.offset_text_position = 'left' return offsetText def _get_pixel_distance_along_axis(self, where, perturb): """ Returns the amount, in data coordinates, that a single pixel corresponds to in the locality given by *where*, which is also given in data coordinates, and is a y coordinate. *perturb* is the amount to perturb the pixel. Usually +0.5 or -0.5. Implementing this routine for an axis is optional; if present, it will ensure that no ticks are lost due to round-off at the extreme ends of an axis. """ # # first figure out the pixel location of the "where" point. We use # 1e-10 for the x point, so that we remain compatible with log axes. # transformation from data coords to display coords trans = self.axes.transData # transformation from display coords to data coords transinv = trans.inverted() pix = trans.transform_point((1e-10, where)) # perturb the pixel ptp = transinv.transform_point((pix[0], pix[1] + perturb)) dy = abs(ptp[1] - where) return dy def set_label_position(self, position): """ Set the label position (left or right) ACCEPTS: [ 'left' | 'right' ] """ self.label.set_rotation_mode('anchor') self.label.set_horizontalalignment('center') if position == 'left': self.label.set_verticalalignment('bottom') elif position == 'right': self.label.set_verticalalignment('top') else: msg = "Position accepts only [ 'left' | 'right' ]" raise ValueError(msg) self.label_position = position self.stale = True def _update_label_position(self, bboxes, bboxes2): """ Update the label position based on the bounding box enclosing all the ticklabels and axis spine """ if not self._autolabelpos: return x, y = self.label.get_position() if self.label_position == 'left': try: spine = self.axes.spines['left'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() except KeyError: # use axes if spine doesn't exist spinebbox = self.axes.bbox bbox = mtransforms.Bbox.union(bboxes + [spinebbox]) left = bbox.x0 self.label.set_position( (left - self.labelpad * self.figure.dpi / 72.0, y) ) else: try: spine = self.axes.spines['right'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() except KeyError: # use axes if spine doesn't exist spinebbox = self.axes.bbox bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox]) right = bbox.x1 self.label.set_position( (right + self.labelpad * self.figure.dpi / 72.0, y) ) def _update_offset_text_position(self, bboxes, bboxes2): """ Update the offset_text position based on the sequence of bounding boxes of all the ticklabels """ x, y = self.offsetText.get_position() top = self.axes.bbox.ymax self.offsetText.set_position( (x, top + self.OFFSETTEXTPAD * self.figure.dpi / 72.0) ) def set_offset_position(self, position): x, y = self.offsetText.get_position() if position == 'left': x = 0 elif position == 'right': x = 1 else: msg = "Position accepts only [ 'left' | 'right' ]" raise ValueError(msg) self.offsetText.set_ha(position) self.offsetText.set_position((x, y)) self.stale = True def get_text_widths(self, renderer): bbox, bbox2 = self.get_ticklabel_extents(renderer) # MGDTODO: Need a better way to get the pad padPixels = self.majorTicks[0].get_pad_pixels() left = 0.0 if bbox.width: left += bbox.width + padPixels right = 0.0 if bbox2.width: right += bbox2.width + padPixels if self.get_label_position() == 'left': left += self.label.get_window_extent(renderer).width + padPixels else: right += self.label.get_window_extent(renderer).width + padPixels return left, right def set_ticks_position(self, position): """ Set the ticks position (left, right, both, default or none) 'both' sets the ticks to appear on both positions, but does not change the tick labels. 'default' resets the tick positions to the default: ticks on both positions, labels at left. 'none' can be used if you don't want any ticks. 'none' and 'both' affect only the ticks, not the labels. ACCEPTS: [ 'left' | 'right' | 'both' | 'default' | 'none' ] """ if position == 'right': self.set_tick_params(which='both', right=True, labelright=True, left=False, labelleft=False) self.set_offset_position(position) elif position == 'left': self.set_tick_params(which='both', right=False, labelright=False, left=True, labelleft=True) self.set_offset_position(position) elif position == 'both': self.set_tick_params(which='both', right=True, left=True) elif position == 'none': self.set_tick_params(which='both', right=False, left=False) elif position == 'default': self.set_tick_params(which='both', right=True, labelright=False, left=True, labelleft=True) else: raise ValueError("invalid position: %s" % position) self.stale = True def tick_right(self): 'use ticks only on right' self.set_ticks_position('right') def tick_left(self): 'use ticks only on left' self.set_ticks_position('left') def get_ticks_position(self): """ Return the ticks position (left, right, both or unknown) """ majt = self.majorTicks[0] mT = self.minorTicks[0] majorRight = ((not majt.tick1On) and majt.tick2On and (not majt.label1On) and majt.label2On) minorRight = ((not mT.tick1On) and mT.tick2On and (not mT.label1On) and mT.label2On) if majorRight and minorRight: return 'right' majorLeft = (majt.tick1On and (not majt.tick2On) and majt.label1On and (not majt.label2On)) minorLeft = (mT.tick1On and (not mT.tick2On) and mT.label1On and (not mT.label2On)) if majorLeft and minorLeft: return 'left' majorDefault = (majt.tick1On and majt.tick2On and majt.label1On and (not majt.label2On)) minorDefault = (mT.tick1On and mT.tick2On and mT.label1On and (not mT.label2On)) if majorDefault and minorDefault: return 'default' return 'unknown' def get_view_interval(self): 'return the Interval instance for this axis view limits' return self.axes.viewLim.intervaly def set_view_interval(self, vmin, vmax, ignore=False): """ If *ignore* is *False*, the order of vmin, vmax does not matter; the original axis orientation will be preserved. In addition, the view limits can be expanded, but will not be reduced. This method is for mpl internal use; for normal use, see :meth:`~matplotlib.axes.Axes.set_ylim`. """ if ignore: self.axes.viewLim.intervaly = vmin, vmax else: Vmin, Vmax = self.get_view_interval() if Vmin < Vmax: self.axes.viewLim.intervaly = (min(vmin, vmax, Vmin), max(vmin, vmax, Vmax)) else: self.axes.viewLim.intervaly = (max(vmin, vmax, Vmin), min(vmin, vmax, Vmax)) self.stale = True def get_minpos(self): return self.axes.dataLim.minposy def get_data_interval(self): 'return the Interval instance for this axis data limits' return self.axes.dataLim.intervaly def set_data_interval(self, vmin, vmax, ignore=False): 'set the axis data limits' if ignore: self.axes.dataLim.intervaly = vmin, vmax else: Vmin, Vmax = self.get_data_interval() self.axes.dataLim.intervaly = min(vmin, Vmin), max(vmax, Vmax) self.stale = True def set_default_intervals(self): 'set the default limits for the axis interval if they are not mutated' ymin, ymax = 0., 1. dataMutated = self.axes.dataLim.mutatedy() viewMutated = self.axes.viewLim.mutatedy() if not dataMutated or not viewMutated: if self.converter is not None: info = self.converter.axisinfo(self.units, self) if info.default_limits is not None: valmin, valmax = info.default_limits ymin = self.converter.convert(valmin, self.units, self) ymax = self.converter.convert(valmax, self.units, self) if not dataMutated: self.axes.dataLim.intervaly = ymin, ymax if not viewMutated: self.axes.viewLim.intervaly = ymin, ymax self.stale = True def get_tick_space(self): ends = self.axes.transAxes.transform([[0, 0], [0, 1]]) length = ((ends[1][1] - ends[0][1]) / self.axes.figure.dpi) * 72.0 tick = self._get_tick(True) # Having a spacing of at least 2 just looks good. size = tick.label1.get_size() * 2.0 if size > 0: return int(np.floor(length / size)) else: return 2**31 - 1
bsd-3-clause
ryfeus/lambda-packs
Tensorflow_LightGBM_Scipy_nightly/source/scipy/stats/_binned_statistic.py
10
25912
from __future__ import division, print_function, absolute_import import numpy as np from scipy._lib.six import callable, xrange from scipy._lib._numpy_compat import suppress_warnings from collections import namedtuple __all__ = ['binned_statistic', 'binned_statistic_2d', 'binned_statistic_dd'] BinnedStatisticResult = namedtuple('BinnedStatisticResult', ('statistic', 'bin_edges', 'binnumber')) def binned_statistic(x, values, statistic='mean', bins=10, range=None): """ Compute a binned statistic for one or more sets of data. This is a generalization of a histogram function. A histogram divides the space into bins, and returns the count of the number of points in each bin. This function allows the computation of the sum, mean, median, or other statistic of the values (or set of values) within each bin. Parameters ---------- x : (N,) array_like A sequence of values to be binned. values : (N,) array_like or list of (N,) array_like The data on which the statistic will be computed. This must be the same shape as `x`, or a set of sequences - each the same shape as `x`. If `values` is a set of sequences, the statistic will be computed on each independently. statistic : string or callable, optional The statistic to compute (default is 'mean'). The following statistics are available: * 'mean' : compute the mean of values for points within each bin. Empty bins will be represented by NaN. * 'median' : compute the median of values for points within each bin. Empty bins will be represented by NaN. * 'count' : compute the count of points within each bin. This is identical to an unweighted histogram. `values` array is not referenced. * 'sum' : compute the sum of values for points within each bin. This is identical to a weighted histogram. * 'min' : compute the minimum of values for points within each bin. Empty bins will be represented by NaN. * 'max' : compute the maximum of values for point within each bin. Empty bins will be represented by NaN. * function : a user-defined function which takes a 1D array of values, and outputs a single numerical statistic. This function will be called on the values in each bin. Empty bins will be represented by function([]), or NaN if this returns an error. bins : int or sequence of scalars, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10 by default). If `bins` is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. Values in `x` that are smaller than lowest bin edge are assigned to bin number 0, values beyond the highest bin are assigned to ``bins[-1]``. If the bin edges are specified, the number of bins will be, (nx = len(bins)-1). range : (float, float) or [(float, float)], optional The lower and upper range of the bins. If not provided, range is simply ``(x.min(), x.max())``. Values outside the range are ignored. Returns ------- statistic : array The values of the selected statistic in each bin. bin_edges : array of dtype float Return the bin edges ``(length(statistic)+1)``. binnumber: 1-D ndarray of ints Indices of the bins (corresponding to `bin_edges`) in which each value of `x` belongs. Same length as `values`. A binnumber of `i` means the corresponding value is between (bin_edges[i-1], bin_edges[i]). See Also -------- numpy.digitize, numpy.histogram, binned_statistic_2d, binned_statistic_dd Notes ----- All but the last (righthand-most) bin is half-open. In other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. .. versionadded:: 0.11.0 Examples -------- >>> from scipy import stats >>> import matplotlib.pyplot as plt First some basic examples: Create two evenly spaced bins in the range of the given sample, and sum the corresponding values in each of those bins: >>> values = [1.0, 1.0, 2.0, 1.5, 3.0] >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2) (array([ 4. , 4.5]), array([ 1., 4., 7.]), array([1, 1, 1, 2, 2])) Multiple arrays of values can also be passed. The statistic is calculated on each set independently: >>> values = [[1.0, 1.0, 2.0, 1.5, 3.0], [2.0, 2.0, 4.0, 3.0, 6.0]] >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2) (array([[ 4. , 4.5], [ 8. , 9. ]]), array([ 1., 4., 7.]), array([1, 1, 1, 2, 2])) >>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean', ... bins=3) (array([ 1., 2., 4.]), array([ 1., 2., 3., 4.]), array([1, 2, 1, 2, 3])) As a second example, we now generate some random data of sailing boat speed as a function of wind speed, and then determine how fast our boat is for certain wind speeds: >>> windspeed = 8 * np.random.rand(500) >>> boatspeed = .3 * windspeed**.5 + .2 * np.random.rand(500) >>> bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed, ... boatspeed, statistic='median', bins=[1,2,3,4,5,6,7]) >>> plt.figure() >>> plt.plot(windspeed, boatspeed, 'b.', label='raw data') >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5, ... label='binned statistic of data') >>> plt.legend() Now we can use ``binnumber`` to select all datapoints with a windspeed below 1: >>> low_boatspeed = boatspeed[binnumber == 0] As a final example, we will use ``bin_edges`` and ``binnumber`` to make a plot of a distribution that shows the mean and distribution around that mean per bin, on top of a regular histogram and the probability distribution function: >>> x = np.linspace(0, 5, num=500) >>> x_pdf = stats.maxwell.pdf(x) >>> samples = stats.maxwell.rvs(size=10000) >>> bin_means, bin_edges, binnumber = stats.binned_statistic(x, x_pdf, ... statistic='mean', bins=25) >>> bin_width = (bin_edges[1] - bin_edges[0]) >>> bin_centers = bin_edges[1:] - bin_width/2 >>> plt.figure() >>> plt.hist(samples, bins=50, normed=True, histtype='stepfilled', ... alpha=0.2, label='histogram of data') >>> plt.plot(x, x_pdf, 'r-', label='analytical pdf') >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=2, ... label='binned statistic of data') >>> plt.plot((binnumber - 0.5) * bin_width, x_pdf, 'g.', alpha=0.5) >>> plt.legend(fontsize=10) >>> plt.show() """ try: N = len(bins) except TypeError: N = 1 if N != 1: bins = [np.asarray(bins, float)] if range is not None: if len(range) == 2: range = [range] medians, edges, binnumbers = binned_statistic_dd( [x], values, statistic, bins, range) return BinnedStatisticResult(medians, edges[0], binnumbers) BinnedStatistic2dResult = namedtuple('BinnedStatistic2dResult', ('statistic', 'x_edge', 'y_edge', 'binnumber')) def binned_statistic_2d(x, y, values, statistic='mean', bins=10, range=None, expand_binnumbers=False): """ Compute a bidimensional binned statistic for one or more sets of data. This is a generalization of a histogram2d function. A histogram divides the space into bins, and returns the count of the number of points in each bin. This function allows the computation of the sum, mean, median, or other statistic of the values (or set of values) within each bin. Parameters ---------- x : (N,) array_like A sequence of values to be binned along the first dimension. y : (N,) array_like A sequence of values to be binned along the second dimension. values : (N,) array_like or list of (N,) array_like The data on which the statistic will be computed. This must be the same shape as `x`, or a list of sequences - each with the same shape as `x`. If `values` is such a list, the statistic will be computed on each independently. statistic : string or callable, optional The statistic to compute (default is 'mean'). The following statistics are available: * 'mean' : compute the mean of values for points within each bin. Empty bins will be represented by NaN. * 'median' : compute the median of values for points within each bin. Empty bins will be represented by NaN. * 'count' : compute the count of points within each bin. This is identical to an unweighted histogram. `values` array is not referenced. * 'sum' : compute the sum of values for points within each bin. This is identical to a weighted histogram. * 'min' : compute the minimum of values for points within each bin. Empty bins will be represented by NaN. * 'max' : compute the maximum of values for point within each bin. Empty bins will be represented by NaN. * function : a user-defined function which takes a 1D array of values, and outputs a single numerical statistic. This function will be called on the values in each bin. Empty bins will be represented by function([]), or NaN if this returns an error. bins : int or [int, int] or array_like or [array, array], optional The bin specification: * the number of bins for the two dimensions (nx = ny = bins), * the number of bins in each dimension (nx, ny = bins), * the bin edges for the two dimensions (x_edge = y_edge = bins), * the bin edges in each dimension (x_edge, y_edge = bins). If the bin edges are specified, the number of bins will be, (nx = len(x_edge)-1, ny = len(y_edge)-1). range : (2,2) array_like, optional The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the `bins` parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram. expand_binnumbers : bool, optional 'False' (default): the returned `binnumber` is a shape (N,) array of linearized bin indices. 'True': the returned `binnumber` is 'unraveled' into a shape (2,N) ndarray, where each row gives the bin numbers in the corresponding dimension. See the `binnumber` returned value, and the `Examples` section. .. versionadded:: 0.17.0 Returns ------- statistic : (nx, ny) ndarray The values of the selected statistic in each two-dimensional bin. x_edge : (nx + 1) ndarray The bin edges along the first dimension. y_edge : (ny + 1) ndarray The bin edges along the second dimension. binnumber : (N,) array of ints or (2,N) ndarray of ints This assigns to each element of `sample` an integer that represents the bin in which this observation falls. The representation depends on the `expand_binnumbers` argument. See `Notes` for details. See Also -------- numpy.digitize, numpy.histogram2d, binned_statistic, binned_statistic_dd Notes ----- Binedges: All but the last (righthand-most) bin is half-open. In other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. `binnumber`: This returned argument assigns to each element of `sample` an integer that represents the bin in which it belongs. The representation depends on the `expand_binnumbers` argument. If 'False' (default): The returned `binnumber` is a shape (N,) array of linearized indices mapping each element of `sample` to its corresponding bin (using row-major ordering). If 'True': The returned `binnumber` is a shape (2,N) ndarray where each row indicates bin placements for each dimension respectively. In each dimension, a binnumber of `i` means the corresponding value is between (D_edge[i-1], D_edge[i]), where 'D' is either 'x' or 'y'. .. versionadded:: 0.11.0 Examples -------- >>> from scipy import stats Calculate the counts with explicit bin-edges: >>> x = [0.1, 0.1, 0.1, 0.6] >>> y = [2.1, 2.6, 2.1, 2.1] >>> binx = [0.0, 0.5, 1.0] >>> biny = [2.0, 2.5, 3.0] >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx,biny]) >>> ret.statistic array([[ 2., 1.], [ 1., 0.]]) The bin in which each sample is placed is given by the `binnumber` returned parameter. By default, these are the linearized bin indices: >>> ret.binnumber array([5, 6, 5, 9]) The bin indices can also be expanded into separate entries for each dimension using the `expand_binnumbers` parameter: >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx,biny], ... expand_binnumbers=True) >>> ret.binnumber array([[1, 1, 1, 2], [1, 2, 1, 1]]) Which shows that the first three elements belong in the xbin 1, and the fourth into xbin 2; and so on for y. """ # This code is based on np.histogram2d try: N = len(bins) except TypeError: N = 1 if N != 1 and N != 2: xedges = yedges = np.asarray(bins, float) bins = [xedges, yedges] medians, edges, binnumbers = binned_statistic_dd( [x, y], values, statistic, bins, range, expand_binnumbers=expand_binnumbers) return BinnedStatistic2dResult(medians, edges[0], edges[1], binnumbers) BinnedStatisticddResult = namedtuple('BinnedStatisticddResult', ('statistic', 'bin_edges', 'binnumber')) def binned_statistic_dd(sample, values, statistic='mean', bins=10, range=None, expand_binnumbers=False): """ Compute a multidimensional binned statistic for a set of data. This is a generalization of a histogramdd function. A histogram divides the space into bins, and returns the count of the number of points in each bin. This function allows the computation of the sum, mean, median, or other statistic of the values within each bin. Parameters ---------- sample : array_like Data to histogram passed as a sequence of D arrays of length N, or as an (N,D) array. values : (N,) array_like or list of (N,) array_like The data on which the statistic will be computed. This must be the same shape as `x`, or a list of sequences - each with the same shape as `x`. If `values` is such a list, the statistic will be computed on each independently. statistic : string or callable, optional The statistic to compute (default is 'mean'). The following statistics are available: * 'mean' : compute the mean of values for points within each bin. Empty bins will be represented by NaN. * 'median' : compute the median of values for points within each bin. Empty bins will be represented by NaN. * 'count' : compute the count of points within each bin. This is identical to an unweighted histogram. `values` array is not referenced. * 'sum' : compute the sum of values for points within each bin. This is identical to a weighted histogram. * 'min' : compute the minimum of values for points within each bin. Empty bins will be represented by NaN. * 'max' : compute the maximum of values for point within each bin. Empty bins will be represented by NaN. * function : a user-defined function which takes a 1D array of values, and outputs a single numerical statistic. This function will be called on the values in each bin. Empty bins will be represented by function([]), or NaN if this returns an error. bins : sequence or int, optional The bin specification must be in one of the following forms: * A sequence of arrays describing the bin edges along each dimension. * The number of bins for each dimension (nx, ny, ... = bins). * The number of bins for all dimensions (nx = ny = ... = bins). range : sequence, optional A sequence of lower and upper bin edges to be used if the edges are not given explicitely in `bins`. Defaults to the minimum and maximum values along each dimension. expand_binnumbers : bool, optional 'False' (default): the returned `binnumber` is a shape (N,) array of linearized bin indices. 'True': the returned `binnumber` is 'unraveled' into a shape (D,N) ndarray, where each row gives the bin numbers in the corresponding dimension. See the `binnumber` returned value, and the `Examples` section of `binned_statistic_2d`. .. versionadded:: 0.17.0 Returns ------- statistic : ndarray, shape(nx1, nx2, nx3,...) The values of the selected statistic in each two-dimensional bin. bin_edges : list of ndarrays A list of D arrays describing the (nxi + 1) bin edges for each dimension. binnumber : (N,) array of ints or (D,N) ndarray of ints This assigns to each element of `sample` an integer that represents the bin in which this observation falls. The representation depends on the `expand_binnumbers` argument. See `Notes` for details. See Also -------- numpy.digitize, numpy.histogramdd, binned_statistic, binned_statistic_2d Notes ----- Binedges: All but the last (righthand-most) bin is half-open in each dimension. In other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. `binnumber`: This returned argument assigns to each element of `sample` an integer that represents the bin in which it belongs. The representation depends on the `expand_binnumbers` argument. If 'False' (default): The returned `binnumber` is a shape (N,) array of linearized indices mapping each element of `sample` to its corresponding bin (using row-major ordering). If 'True': The returned `binnumber` is a shape (D,N) ndarray where each row indicates bin placements for each dimension respectively. In each dimension, a binnumber of `i` means the corresponding value is between (bin_edges[D][i-1], bin_edges[D][i]), for each dimension 'D'. .. versionadded:: 0.11.0 """ known_stats = ['mean', 'median', 'count', 'sum', 'std','min','max'] if not callable(statistic) and statistic not in known_stats: raise ValueError('invalid statistic %r' % (statistic,)) # `Ndim` is the number of dimensions (e.g. `2` for `binned_statistic_2d`) # `Dlen` is the length of elements along each dimension. # This code is based on np.histogramdd try: # `sample` is an ND-array. Dlen, Ndim = sample.shape except (AttributeError, ValueError): # `sample` is a sequence of 1D arrays. sample = np.atleast_2d(sample).T Dlen, Ndim = sample.shape # Store initial shape of `values` to preserve it in the output values = np.asarray(values) input_shape = list(values.shape) # Make sure that `values` is 2D to iterate over rows values = np.atleast_2d(values) Vdim, Vlen = values.shape # Make sure `values` match `sample` if(statistic != 'count' and Vlen != Dlen): raise AttributeError('The number of `values` elements must match the ' 'length of each `sample` dimension.') nbin = np.empty(Ndim, int) # Number of bins in each dimension edges = Ndim * [None] # Bin edges for each dim (will be 2D array) dedges = Ndim * [None] # Spacing between edges (will be 2D array) try: M = len(bins) if M != Ndim: raise AttributeError('The dimension of bins must be equal ' 'to the dimension of the sample x.') except TypeError: bins = Ndim * [bins] # Select range for each dimension # Used only if number of bins is given. if range is None: smin = np.atleast_1d(np.array(sample.min(axis=0), float)) smax = np.atleast_1d(np.array(sample.max(axis=0), float)) else: smin = np.zeros(Ndim) smax = np.zeros(Ndim) for i in xrange(Ndim): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in xrange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in xrange(Ndim): if np.isscalar(bins[i]): nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = np.linspace(smin[i], smax[i], nbin[i] - 1) else: edges[i] = np.asarray(bins[i], float) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = np.diff(edges[i]) nbin = np.asarray(nbin) # Compute the bin number each sample falls into, in each dimension sampBin = [ np.digitize(sample[:, i], edges[i]) for i in xrange(Ndim) ] # Using `digitize`, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. for i in xrange(Ndim): # Find the rounding precision decimal = int(-np.log10(dedges[i].min())) + 6 # Find which points are on the rightmost edge. on_edge = np.where(np.around(sample[:, i], decimal) == np.around(edges[i][-1], decimal))[0] # Shift these points one bin to the left. sampBin[i][on_edge] -= 1 # Compute the sample indices in the flattened statistic matrix. binnumbers = np.ravel_multi_index(sampBin, nbin) result = np.empty([Vdim, nbin.prod()], float) if statistic == 'mean': result.fill(np.nan) flatcount = np.bincount(binnumbers, None) a = flatcount.nonzero() for vv in xrange(Vdim): flatsum = np.bincount(binnumbers, values[vv]) result[vv, a] = flatsum[a] / flatcount[a] elif statistic == 'std': result.fill(0) flatcount = np.bincount(binnumbers, None) a = flatcount.nonzero() for vv in xrange(Vdim): flatsum = np.bincount(binnumbers, values[vv]) flatsum2 = np.bincount(binnumbers, values[vv] ** 2) result[vv, a] = np.sqrt(flatsum2[a] / flatcount[a] - (flatsum[a] / flatcount[a]) ** 2) elif statistic == 'count': result.fill(0) flatcount = np.bincount(binnumbers, None) a = np.arange(len(flatcount)) result[:, a] = flatcount[np.newaxis, :] elif statistic == 'sum': result.fill(0) for vv in xrange(Vdim): flatsum = np.bincount(binnumbers, values[vv]) a = np.arange(len(flatsum)) result[vv, a] = flatsum elif statistic == 'median': result.fill(np.nan) for i in np.unique(binnumbers): for vv in xrange(Vdim): result[vv, i] = np.median(values[vv, binnumbers == i]) elif statistic == 'min': result.fill(np.nan) for i in np.unique(binnumbers): for vv in xrange(Vdim): result[vv, i] = np.min(values[vv, binnumbers == i]) elif statistic == 'max': result.fill(np.nan) for i in np.unique(binnumbers): for vv in xrange(Vdim): result[vv, i] = np.max(values[vv, binnumbers == i]) elif callable(statistic): with np.errstate(invalid='ignore'), suppress_warnings() as sup: sup.filter(RuntimeWarning) try: null = statistic([]) except: null = np.nan result.fill(null) for i in np.unique(binnumbers): for vv in xrange(Vdim): result[vv, i] = statistic(values[vv, binnumbers == i]) # Shape into a proper matrix result = result.reshape(np.append(Vdim, nbin)) # Remove outliers (indices 0 and -1 for each bin-dimension). core = [slice(None)] + Ndim * [slice(1, -1)] result = result[core] # Unravel binnumbers into an ndarray, each row the bins for each dimension if(expand_binnumbers and Ndim > 1): binnumbers = np.asarray(np.unravel_index(binnumbers, nbin)) if np.any(result.shape[1:] != nbin - 2): raise RuntimeError('Internal Shape Error') # Reshape to have output (`reulst`) match input (`values`) shape result = result.reshape(input_shape[:-1] + list(nbin-2)) return BinnedStatisticddResult(result, edges, binnumbers)
mit
jeffery-do/Vizdoombot
doom/lib/python3.5/site-packages/scipy/stats/_stats_mstats_common.py
12
8157
from collections import namedtuple import numpy as np from . import distributions __all__ = ['_find_repeats', 'linregress', 'theilslopes'] def linregress(x, y=None): """ Calculate a linear least-squares regression for two sets of measurements. Parameters ---------- x, y : array_like Two sets of measurements. Both arrays should have the same length. If only x is given (and y=None), then it must be a two-dimensional array where one dimension has length 2. The two sets of measurements are then found by splitting the array along the length-2 dimension. Returns ------- slope : float slope of the regression line intercept : float intercept of the regression line rvalue : float correlation coefficient pvalue : float two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero. stderr : float Standard error of the estimated gradient. See also -------- optimize.curve_fit : Use non-linear least squares to fit a function to data. optimize.leastsq : Minimize the sum of squares of a set of equations. Examples -------- >>> from scipy import stats >>> np.random.seed(12345678) >>> x = np.random.random(10) >>> y = np.random.random(10) >>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) # To get coefficient of determination (r_squared) >>> print("r-squared:", r_value**2) ('r-squared:', 0.080402268539028335) """ TINY = 1.0e-20 if y is None: # x is a (2, N) or (N, 2) shaped array_like x = np.asarray(x) if x.shape[0] == 2: x, y = x elif x.shape[1] == 2: x, y = x.T else: msg = ("If only `x` is given as input, it has to be of shape " "(2, N) or (N, 2), provided shape was %s" % str(x.shape)) raise ValueError(msg) else: x = np.asarray(x) y = np.asarray(y) if x.size == 0 or y.size == 0: raise ValueError("Inputs must not be empty.") n = len(x) xmean = np.mean(x, None) ymean = np.mean(y, None) # average sum of squares: ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat r_num = ssxym r_den = np.sqrt(ssxm * ssym) if r_den == 0.0: r = 0.0 else: r = r_num / r_den # test for numerical error propagation if r > 1.0: r = 1.0 elif r < -1.0: r = -1.0 df = n - 2 t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY))) prob = 2 * distributions.t.sf(np.abs(t), df) slope = r_num / ssxm intercept = ymean - slope*xmean sterrest = np.sqrt((1 - r**2) * ssym / ssxm / df) LinregressResult = namedtuple('LinregressResult', ('slope', 'intercept', 'rvalue', 'pvalue', 'stderr')) return LinregressResult(slope, intercept, r, prob, sterrest) def theilslopes(y, x=None, alpha=0.95): r""" Computes the Theil-Sen estimator for a set of points (x, y). `theilslopes` implements a method for robust linear regression. It computes the slope as the median of all slopes between paired values. Parameters ---------- y : array_like Dependent variable. x : array_like or None, optional Independent variable. If None, use ``arange(len(y))`` instead. alpha : float, optional Confidence degree between 0 and 1. Default is 95% confidence. Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are interpreted as "find the 90% confidence interval". Returns ------- medslope : float Theil slope. medintercept : float Intercept of the Theil line, as ``median(y) - medslope*median(x)``. lo_slope : float Lower bound of the confidence interval on `medslope`. up_slope : float Upper bound of the confidence interval on `medslope`. Notes ----- The implementation of `theilslopes` follows [1]_. The intercept is not defined in [1]_, and here it is defined as ``median(y) - medslope*median(x)``, which is given in [3]_. Other definitions of the intercept exist in the literature. A confidence interval for the intercept is not given as this question is not addressed in [1]_. References ---------- .. [1] P.K. Sen, "Estimates of the regression coefficient based on Kendall's tau", J. Am. Stat. Assoc., Vol. 63, pp. 1379-1389, 1968. .. [2] H. Theil, "A rank-invariant method of linear and polynomial regression analysis I, II and III", Nederl. Akad. Wetensch., Proc. 53:, pp. 386-392, pp. 521-525, pp. 1397-1412, 1950. .. [3] W.L. Conover, "Practical nonparametric statistics", 2nd ed., John Wiley and Sons, New York, pp. 493. Examples -------- >>> from scipy import stats >>> import matplotlib.pyplot as plt >>> x = np.linspace(-5, 5, num=150) >>> y = x + np.random.normal(size=x.size) >>> y[11:15] += 10 # add outliers >>> y[-5:] -= 7 Compute the slope, intercept and 90% confidence interval. For comparison, also compute the least-squares fit with `linregress`: >>> res = stats.theilslopes(y, x, 0.90) >>> lsq_res = stats.linregress(x, y) Plot the results. The Theil-Sen regression line is shown in red, with the dashed red lines illustrating the confidence interval of the slope (note that the dashed red lines are not the confidence interval of the regression as the confidence interval of the intercept is not included). The green line shows the least-squares fit for comparison. >>> fig = plt.figure() >>> ax = fig.add_subplot(111) >>> ax.plot(x, y, 'b.') >>> ax.plot(x, res[1] + res[0] * x, 'r-') >>> ax.plot(x, res[1] + res[2] * x, 'r--') >>> ax.plot(x, res[1] + res[3] * x, 'r--') >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-') >>> plt.show() """ # We copy both x and y so we can use _find_repeats. y = np.array(y).flatten() if x is None: x = np.arange(len(y), dtype=float) else: x = np.array(x, dtype=float).flatten() if len(x) != len(y): raise ValueError("Incompatible lengths ! (%s<>%s)" % (len(y), len(x))) # Compute sorted slopes only when deltax > 0 deltax = x[:, np.newaxis] - x deltay = y[:, np.newaxis] - y slopes = deltay[deltax > 0] / deltax[deltax > 0] slopes.sort() medslope = np.median(slopes) medinter = np.median(y) - medslope * np.median(x) # Now compute confidence intervals if alpha > 0.5: alpha = 1. - alpha z = distributions.norm.ppf(alpha / 2.) # This implements (2.6) from Sen (1968) _, nxreps = _find_repeats(x) _, nyreps = _find_repeats(y) nt = len(slopes) # N in Sen (1968) ny = len(y) # n in Sen (1968) # Equation 2.6 in Sen (1968): sigsq = 1/18. * (ny * (ny-1) * (2*ny+5) - np.sum(k * (k-1) * (2*k + 5) for k in nxreps) - np.sum(k * (k-1) * (2*k + 5) for k in nyreps)) # Find the confidence interval indices in `slopes` sigma = np.sqrt(sigsq) Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1) Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0) delta = slopes[[Rl, Ru]] return medslope, medinter, delta[0], delta[1] def _find_repeats(arr): # This function assumes it may clobber its input. if len(arr) == 0: return np.array(0, np.float64), np.array(0, np.intp) # XXX This cast was previously needed for the Fortran implementation, # should we ditch it? arr = np.asarray(arr, np.float64).ravel() arr.sort() # Taken from NumPy 1.9's np.unique. change = np.concatenate(([True], arr[1:] != arr[:-1])) unique = arr[change] change_idx = np.concatenate(np.nonzero(change) + ([arr.size],)) freq = np.diff(change_idx) atleast2 = freq > 1 return unique[atleast2], freq[atleast2]
mit
vshtanko/scikit-learn
examples/cluster/plot_agglomerative_clustering_metrics.py
402
4492
""" Agglomerative clustering with different metrics =============================================== Demonstrates the effect of different metrics on the hierarchical clustering. The example is engineered to show the effect of the choice of different metrics. It is applied to waveforms, which can be seen as high-dimensional vector. Indeed, the difference between metrics is usually more pronounced in high dimension (in particular for euclidean and cityblock). We generate data from three groups of waveforms. Two of the waveforms (waveform 1 and waveform 2) are proportional one to the other. The cosine distance is invariant to a scaling of the data, as a result, it cannot distinguish these two waveforms. Thus even with no noise, clustering using this distance will not separate out waveform 1 and 2. We add observation noise to these waveforms. We generate very sparse noise: only 6% of the time points contain noise. As a result, the l1 norm of this noise (ie "cityblock" distance) is much smaller than it's l2 norm ("euclidean" distance). This can be seen on the inter-class distance matrices: the values on the diagonal, that characterize the spread of the class, are much bigger for the Euclidean distance than for the cityblock distance. When we apply clustering to the data, we find that the clustering reflects what was in the distance matrices. Indeed, for the Euclidean distance, the classes are ill-separated because of the noise, and thus the clustering does not separate the waveforms. For the cityblock distance, the separation is good and the waveform classes are recovered. Finally, the cosine distance does not separate at all waveform 1 and 2, thus the clustering puts them in the same cluster. """ # Author: Gael Varoquaux # License: BSD 3-Clause or CC-0 import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import AgglomerativeClustering from sklearn.metrics import pairwise_distances np.random.seed(0) # Generate waveform data n_features = 2000 t = np.pi * np.linspace(0, 1, n_features) def sqr(x): return np.sign(np.cos(x)) X = list() y = list() for i, (phi, a) in enumerate([(.5, .15), (.5, .6), (.3, .2)]): for _ in range(30): phase_noise = .01 * np.random.normal() amplitude_noise = .04 * np.random.normal() additional_noise = 1 - 2 * np.random.rand(n_features) # Make the noise sparse additional_noise[np.abs(additional_noise) < .997] = 0 X.append(12 * ((a + amplitude_noise) * (sqr(6 * (t + phi + phase_noise))) + additional_noise)) y.append(i) X = np.array(X) y = np.array(y) n_clusters = 3 labels = ('Waveform 1', 'Waveform 2', 'Waveform 3') # Plot the ground-truth labelling plt.figure() plt.axes([0, 0, 1, 1]) for l, c, n in zip(range(n_clusters), 'rgb', labels): lines = plt.plot(X[y == l].T, c=c, alpha=.5) lines[0].set_label(n) plt.legend(loc='best') plt.axis('tight') plt.axis('off') plt.suptitle("Ground truth", size=20) # Plot the distances for index, metric in enumerate(["cosine", "euclidean", "cityblock"]): avg_dist = np.zeros((n_clusters, n_clusters)) plt.figure(figsize=(5, 4.5)) for i in range(n_clusters): for j in range(n_clusters): avg_dist[i, j] = pairwise_distances(X[y == i], X[y == j], metric=metric).mean() avg_dist /= avg_dist.max() for i in range(n_clusters): for j in range(n_clusters): plt.text(i, j, '%5.3f' % avg_dist[i, j], verticalalignment='center', horizontalalignment='center') plt.imshow(avg_dist, interpolation='nearest', cmap=plt.cm.gnuplot2, vmin=0) plt.xticks(range(n_clusters), labels, rotation=45) plt.yticks(range(n_clusters), labels) plt.colorbar() plt.suptitle("Interclass %s distances" % metric, size=18) plt.tight_layout() # Plot clustering results for index, metric in enumerate(["cosine", "euclidean", "cityblock"]): model = AgglomerativeClustering(n_clusters=n_clusters, linkage="average", affinity=metric) model.fit(X) plt.figure() plt.axes([0, 0, 1, 1]) for l, c in zip(np.arange(model.n_clusters), 'rgbk'): plt.plot(X[model.labels_ == l].T, c=c, alpha=.5) plt.axis('tight') plt.axis('off') plt.suptitle("AgglomerativeClustering(affinity=%s)" % metric, size=20) plt.show()
bsd-3-clause
bmazin/ARCONS-pipeline
examples/Pal2014-J0337/hTestLimit.py
1
8356
#Filename: hTestLimit.py #Author: Matt Strader # #This script opens a list of observed photon phases, import numpy as np import tables import numexpr import matplotlib.pyplot as plt import multiprocessing import functools import time from kuiper.kuiper import kuiper,kuiper_FPP from kuiper.htest import h_test,h_fpp,h_test2 from pulsarUtils import nSigma,plotPulseProfile from histMetrics import kuiperFpp,hTestFpp from inverseTransformSampling import inverseTransformSampler def hTestTrial(iTrial,nPhotons,photonPulseFraction,pulseModel,pulseModelQueryPoints): np.random.seed(int((time.time()+iTrial)*1e6)) modelSampler = inverseTransformSampler(pdf=pulseModel,queryPoints=pulseModelQueryPoints) nPulsePhotons = int(np.floor(photonPulseFraction*nPhotons)) nBackgroundPhotons = int(np.ceil((1.-photonPulseFraction) * nPhotons)) simPulsePhotons = modelSampler(nPulsePhotons) #background photons come from a uniform distribution simBackgroundPhotons = np.random.random(nBackgroundPhotons) simPhases = np.append(simPulsePhotons,simBackgroundPhotons) simHDict = h_test2(simPhases) simH,simM,simPval,simFourierCoeffs = simHDict['H'],simHDict['M'],simHDict['fpp'],simHDict['cs'] print '{} - H,M,fpp,sig:'.format(iTrial),simH,simM,simPval return {'H':simH,'M':simM,'fpp':simPval} if __name__=='__main__': path = '/Scratch/dataProcessing/J0337/masterPhotons3.h5' wvlStart = 4000. wvlEnd = 5500. bLoadFromPl = True nPhaseBins = 20 hTestPath = '/Scratch/dataProcessing/J0337/hTestResults_withProfiles_{}-{}.npz'.format(wvlStart,wvlEnd) phaseBinEdges = np.linspace(0.,1.,nPhaseBins+1) if bLoadFromPl: photFile = tables.openFile(path,'r') photTable = photFile.root.photons.photTable phases = photTable.readWhere('(wvlStart < wavelength) & (wavelength < wvlEnd)')['phase'] photFile.close() print 'cut wavelengths to range ({},{})'.format(wvlStart,wvlEnd) nPhotons = len(phases) print nPhotons,'real photons read' observedProfile,_ = np.histogram(phases,bins=phaseBinEdges) observedProfile = 1.0*observedProfile observedProfileErrors = np.sqrt(observedProfile) #Do H-test hDict = h_test2(phases) H,M,pval,fourierCoeffs = hDict['H'],hDict['M'],hDict['fpp'],hDict['cs'] print 'h-test on real data' print 'H,M,fpp:',H,M,pval print nSigma(1-pval),'sigmas' #h_test2 calculates all fourierCoeffs out to 20, but for the fourier model, we only want the ones out to order M, which optimizes the Zm^2 metric truncatedFourierCoeffs = fourierCoeffs[0:M] print 'fourier coeffs:',truncatedFourierCoeffs #for the model, we want the negative modes as well as positve, so add them modelFourierCoeffs = np.concatenate([truncatedFourierCoeffs[::-1],[1.],np.conj(truncatedFourierCoeffs)]) #make array of mode numbers modes = np.arange(-len(truncatedFourierCoeffs),len(truncatedFourierCoeffs)+1) #save so next time we can set bLoadFromPl=False np.savez(hTestPath,H=H,M=M,pval=pval,fourierCoeffs=fourierCoeffs,nPhotons=nPhotons,wvlRange=(wvlStart,wvlEnd),modelFourierCoeffs=modelFourierCoeffs,modes=modes,observedProfile=observedProfile,observedProfileErrors=observedProfileErrors,phaseBinEdges=phaseBinEdges) else: #Load values from previous run, when we had bLoadFromPl=True hTestDict = np.load(hTestPath) H,M,pval,fourierCoeffs,nPhotons,modelFourierCoeffs,modes = hTestDict['H'],hTestDict['M'],hTestDict['pval'],hTestDict['fourierCoeffs'],hTestDict['nPhotons'],hTestDict['modelFourierCoeffs'],hTestDict['modes'] observedProfile,observedProfileErrors,phaseBinEdges = hTestDict['observedProfile'],hTestDict['observedProfileErrors'],hTestDict['phaseBinEdges'] print 'h-test on real data' print 'H,M,fpp:',H,M,pval print nSigma(1-pval),'sigmas' #Plot the observed profile fig,ax = plt.subplots(1,1) plotPulseProfile(phaseBinEdges,observedProfile,profileErrors=observedProfileErrors,color='k',plotDoublePulse=False,label='observed',ax=ax) ax.set_ylabel('counts') ax.set_xlabel('phase') ax.set_title('Observed Folded Light Curve {}-{} nm'.format(wvlStart/10.,wvlEnd/10.)) #make as set of x points for the pulse model we'll make #Do NOT include x=0, or the inverted function will have a jump that causes an excess of samples #at phase=0 nSmoothPlotPoints=1000 pulseModelQueryPoints = np.linspace(1./nSmoothPlotPoints,1,nSmoothPlotPoints) def modelProfile(thetas): return np.sum( modelFourierCoeffs * np.exp(2.j*np.pi*modes*thetas[:,np.newaxis]),axis=1) lightCurveModel = np.abs(modelProfile(pulseModelQueryPoints)) #for this test we only want the model to be the pulsed component. We will add a DC offset later pulseModel = lightCurveModel - np.min(lightCurveModel) #initialPhotonPulseFraction = 1.*np.sum(pulseModel) / np.sum(lightCurveModel) photonPulseFraction=15400./nPhotons #skip to previously determined answer print 'photon fraction',photonPulseFraction #get samples with distribution of the modelProfile #modelSampler = inverseTransformSampler(pdf=lightCurveModel,queryPoints=pulseModelQueryPoints) modelSampler = inverseTransformSampler(pdf=pulseModel,queryPoints=pulseModelQueryPoints) nTrials = 1 #for each trial run the h test on a set of photon phases with our model profile, and with the pulse fraction specified #we want to make a distribution of H values for this pulse fraction, model, and number of photons #make a function that only takes the trial number (as an identifier) mappableHTestTrial = functools.partial(hTestTrial,pulseModel=pulseModel, pulseModelQueryPoints=pulseModelQueryPoints,nPhotons=nPhotons, photonPulseFraction=photonPulseFraction) pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()-3)#leave a few processors for other people outDicts = pool.map(mappableHTestTrial,np.arange(nTrials)) simHs = np.array([out['H'] for out in outDicts]) simPvals = np.array([out['fpp'] for out in outDicts]) #save the resulting list of H vals np.savez('sim3-h-{}.npz'.format(nTrials),simHs=simHs,simPvals=simPvals,pval=pval,H=H,photonPulseFraction=photonPulseFraction,nPhotons=nPhotons) #make a model profile once more for a plot modelSampler = inverseTransformSampler(pdf=pulseModel,queryPoints=pulseModelQueryPoints) nPulsePhotons = int(np.floor(photonPulseFraction*nPhotons)) nBackgroundPhotons = int(np.ceil((1.-photonPulseFraction) * nPhotons)) simPulsePhotons = modelSampler(nPulsePhotons) #background photons come from a uniform distribution simBackgroundPhotons = np.random.random(nBackgroundPhotons) #put them together for the full profile simPhases = np.append(simPulsePhotons,simBackgroundPhotons) #make a binned phase profile to plot simProfile,_ = np.histogram(simPhases,bins=phaseBinEdges) simProfileErrors = np.sqrt(simProfile)#assume Poisson errors meanLevel = np.mean(simProfile) fig,ax = plt.subplots(1,1) ax.plot(pulseModelQueryPoints,meanLevel*lightCurveModel,color='r') plotPulseProfile(phaseBinEdges,simProfile,profileErrors=simProfileErrors,color='b',plotDoublePulse=False,label='sim',ax=ax) ax.set_title('Simulated profile') # #plt.show() print '{} trials'.format(len(simHs)) print 'observed fpp:',pval frac = 1.*np.sum(simPvals<pval)/len(simPvals) print 'fraction of trials with H below observed fpp:',frac #hHist,hBinEdges = np.histogram(simHs,bins=100,density=True) fppHist,fppBinEdges = np.histogram(simPvals,bins=100,density=True) if nTrials > 1: fig,ax = plt.subplots(1,1) ax.plot(fppBinEdges[0:-1],fppHist,drawstyle='steps-post',color='k') ax.axvline(pval,color='r') ax.set_xlabel('fpp') ax.set_ylabel('frequency') ax.set_title('Distribution of H for model profile') magG = 17.93 sineMagDiff = -2.5*np.log10(photonPulseFraction) print 'SDSS magnitude g: {:.2f}'.format(magG) print 'magnitude difference: {:.2f}'.format(sineMagDiff) print 'limiting g mag: {:.2f}'.format(magG+sineMagDiff) plt.show()
gpl-2.0
stefco/geco_data
geco_irig_plot.py
1
5662
#!/usr/bin/env python # (c) Stefan Countryman, 2016-2017 DESC="""Plot an IRIG-B signal read from stdin. Assumes that the timeseries is a sequence of newline-delimited float literals.""" FAST_CHANNEL_BITRATE = 16384 # for IRIG-B, DuoTone, etc. # THE REST OF THE IMPORTS ARE AFTER THIS IF STATEMENT. # Quits immediately on --help or -h flags to skip slow imports when you just # want to read the help documentation. if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description=DESC) # TODO: make this -i and --ifo instead of detector. parser.add_argument("--detector", help=("the detector; used in the title of the output " "plot")) parser.add_argument("-O", "--outfile", help="the filename of the generated plot") parser.add_argument("-T", "--timeseries", help="copy from stdin to stdout while reading", action="store_true") parser.add_argument("-A", "--actualtime", help=("actual time signal was recorded " "(appears in title)")) args = parser.parse_args() # Force matplotlib to not use any Xwindows backend. NECESSARY ON CLUSTER. import matplotlib matplotlib.use('Agg') import sys import time import numpy as np import matplotlib.pyplot as plt import geco_irig_decode def read_timeseries_stdin(num_lines, cat_to_stdout=False): """Read in newline-delimited numerical data from stdin; don't read more than a second worth of data. If cat_to_stdout is True, print data that has been read in back to stdout (useful for piped commands).""" timeseries = np.zeros(num_lines) line = "" i = 0 while i < num_lines: line = float(sys.stdin.readline()) timeseries[i] = line if cat_to_stdout: print(line) i += 1 return timeseries def irigb_decoded_title(timeseries, IFO=None, actual_time=None): """Get a title for an IRIG-B timeseries plot that includes the decoded time in the timeseries itself.""" # get the detector name if IFO is None: detector_suffix = "" else: detector_suffix = " at " + IFO # get the actual time of recording, if provided if actual_time is None: actual_time_str = "" else: actual_time_str = "\nActual Time: {}".format(actual_time) # add title and so on try: decoded_time = geco_irig_decode.get_date_from_timeseries(timeseries) decoded_time_str = decoded_time.strftime('%a %b %d %X %Y') except ValueError as e: decoded_time_str = "COULD NOT DECODE TIME" fmt = "One Second of IRIG-B Signal{}\nDecoded Time: {}{}" return fmt.format(detector_suffix, decoded_time_str, actual_time_str) def irigb_output_filename(outfile=None): """Get the output filename for an IRIG-B plot.""" if outfile is None: output_filename = "irigb-plot-made-at-" + str(time.time()) + ".png" else: output_filename = outfile # append .png if not already there if output_filename.split(".")[-1] != "png": output_filename += ".png" return output_filename def plot_with_zoomed_views(timeseries, title, num_subdivs=5, dt=1., output_filename=None, overlay=False, linewidth=1): """Plot a timeseries and produce num_subdivs subplots that show equal-sized subdivisions of the full timeseries data to show details (good for high-bitrate timeseries). If you want to keep plotting data to the same figure, set 'overlay=True', and the current figure will be plotted to.""" bitrate = int(len(timeseries) / float(dt)) times = np.linspace(0, 1, num=bitrate, endpoint=False) # find max and min values in timeseries; use these to set plot boundaries yrange = timeseries.max() - timeseries.min() ymax = timeseries.max() + 0.1*yrange ymin = timeseries.min() - 0.1*yrange if not overlay: plt.figure() # print("making plot") plt.gcf().set_figwidth(7) plt.gcf().set_figheight(4+1.2*num_subdivs) # ~1.2in height per zoomed plot # plot the full second on the first row; lines should be black ('k' option). plt.subplot(num_subdivs + 1, 1, 1) plt.ylim(ymin, ymax) plt.plot(times, timeseries, 'k', linewidth=linewidth) plt.tick_params(axis='y', labelsize='small') # make num_subdivs subplots to better show the full second for i in range(num_subdivs): # print("making plot " + str(i)) plt.subplot(num_subdivs+1, 1, i+2) plt.ylim(ymin, ymax) plt.xlim(float(i)/num_subdivs, (float(i)+1)/num_subdivs) start = bitrate*i // num_subdivs end = bitrate*(i+1) // num_subdivs plt.plot(times[start:end], timeseries[start:end], 'k', linewidth=linewidth) plt.tick_params(axis='y', labelsize='small') plt.suptitle(title) plt.xlabel("Time since start of second [$s$]") # print("saving plot") plt.subplots_adjust(left=0.125, right=0.9, bottom=0.1, top=0.9, wspace=0.2, hspace=0.5) if not (output_filename is None): plt.savefig(output_filename) return plt if __name__ == '__main__': timeseries = read_timeseries_stdin(FAST_CHANNEL_BITRATE, cat_to_stdout=args.timeseries) title = irigb_decoded_title(timeseries, args.detector, args.actualtime) output_filename = irigb_output_filename(args.outfile) plot_with_zoomed_views(timeseries, title, num_subdivs=5, dt=1., output_filename=output_filename)
mit
olologin/scikit-learn
examples/svm/plot_iris.py
225
3252
""" ================================================== Plot different SVM classifiers in the iris dataset ================================================== Comparison of different linear SVM classifiers on a 2D projection of the iris dataset. We only consider the first 2 features of this dataset: - Sepal length - Sepal width This example shows how to plot the decision surface for four SVM classifiers with different kernels. The linear models ``LinearSVC()`` and ``SVC(kernel='linear')`` yield slightly different decision boundaries. This can be a consequence of the following differences: - ``LinearSVC`` minimizes the squared hinge loss while ``SVC`` minimizes the regular hinge loss. - ``LinearSVC`` uses the One-vs-All (also known as One-vs-Rest) multiclass reduction while ``SVC`` uses the One-vs-One multiclass reduction. Both linear models have linear decision boundaries (intersecting hyperplanes) while the non-linear kernel models (polynomial or Gaussian RBF) have more flexible non-linear decision boundaries with shapes that depend on the kind of kernel and its parameters. .. NOTE:: while plotting the decision function of classifiers for toy 2D datasets can help get an intuitive understanding of their respective expressive power, be aware that those intuitions don't always generalize to more realistic high-dimensional problems. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim dataset y = iris.target h = .02 # step size in the mesh # we create an instance of SVM and fit out data. We do not scale our # data since we want to plot the support vectors C = 1.0 # SVM regularization parameter svc = svm.SVC(kernel='linear', C=C).fit(X, y) rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, y) poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, y) lin_svc = svm.LinearSVC(C=C).fit(X, y) # create a mesh to plot in x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # title for the plots titles = ['SVC with linear kernel', 'LinearSVC (linear kernel)', 'SVC with RBF kernel', 'SVC with polynomial (degree 3) kernel'] for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)): # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. plt.subplot(2, 2, i + 1) plt.subplots_adjust(wspace=0.4, hspace=0.4) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, 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.title(titles[i]) plt.show()
bsd-3-clause
mnip91/proactive-component-monitoring
dev/scripts/perf/perf_graph.py
12
2516
#!/usr/bin/env python import sys import os import string import numpy as np import matplotlib.pyplot as plt import re def main(): dir = sys.argv[1] if len(sys.argv) == 1: dict = create_dict(dir) draw_graph(dict) else: for i in range(2, len(sys.argv)): dict = create_dict(dir, sys.argv[i]) draw_graph(dict, sys.argv[i]) def create_dict(rootdir, match='.*'): pattern = re.compile(match) dict = {} for branch in os.listdir(rootdir): branch_dict = {} for test in os.listdir(os.path.join(rootdir, branch)): if pattern.match(test): file = open(os.path.join(rootdir, branch, test)) str = file.readline() str = str.strip() start = str.find("=") if start != -1: branch_dict[test] = round(string.atof(str[start+1:]),2) else: branch_dict[test] = -1. dict[branch] = branch_dict return dict def get_all_test_name(dict): for branch in dict: return dict[branch].keys() def get_branches(dict): return dict.keys() def compare_by_branch(dict): def local_print(test, d): print test for t in d: print "\t" + t + "\t" + str(d[t]) print for test in get_all_test_name(dict): local_dict = {} for branch in dict: local_dict[branch] = dict[branch][test] local_print(test, local_dict) ### Unused ### def short_test_name(long_name): return long_name[long_name.rfind('.Test')+5:] def draw_graph(dict, title): def autolabel(rects): for rect in rects: height = rect.get_height() ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height), ha='center', va='bottom') def set_legend(bars, branches): bs = () for bar in bars: bs = bs + (bar[0],) ax.legend( bs, branches) colors = ['b', 'g', 'r', 'c', 'm', 'y', 'b'] branches = get_branches(dict) all_tests = get_all_test_name(dict) N = len(all_tests) ind = np.arange(N) width = 0.35 fig = plt.figure() ax = fig.add_subplot(111) data_sets = [] for branch in branches: data =() for test in all_tests: data = data + (dict[branch].get(test, 0),) data_sets.append(data) bars = [] counter = 0 for data in data_sets: bar = ax.bar(ind + (counter*width), data, width, color=colors[counter]) bars.append(bar) counter += 1 # add some ax.set_ylabel('Perf') ax.set_title('Branch perf comparison for ' + title) ax.set_xticks(ind+width) ax.set_xticklabels(map(short_test_name, all_tests)) set_legend(bars, branches) for bar in bars: autolabel(bar) plt.savefig(title + ".png") if __name__ == "__main__": main()
agpl-3.0
rgerkin/pyNeuroML
pyneuroml/tune/NeuroMLSimulation.py
1
5357
''' A class for running a single instance of a NeuroML model by generating a LEMS file and using pyNeuroML to run in a chosen simulator ''' import sys import time from pyneuroml import pynml from pyneuroml.lems import generate_lems_file_for_neuroml try: import pyelectro # Not used here, just for checking installation except: print('>> Note: pyelectro from https://github.com/pgleeson/pyelectro is required!') exit() try: import neurotune # Not used here, just for checking installation except: print('>> Note: neurotune from https://github.com/pgleeson/neurotune is required!') exit() class NeuroMLSimulation(object): def __init__(self, reference, neuroml_file, target, sim_time=1000, dt=0.05, simulator='jNeuroML', generate_dir = './', cleanup = True, nml_doc = None): self.sim_time = sim_time self.dt = dt self.simulator = simulator self.generate_dir = generate_dir if generate_dir.endswith('/') else generate_dir+'/' self.reference = reference self.target = target self.neuroml_file = neuroml_file self.nml_doc = nml_doc self.cleanup = cleanup self.already_run = False def show(self): """ Plot the result of the simulation once it's been intialized """ from matplotlib import pyplot as plt if self.already_run: for ref in self.volts.keys(): plt.plot(self.t, self.volts[ref], label=ref) plt.title("Simulation voltage vs time") plt.legend() plt.xlabel("Time [ms]") plt.ylabel("Voltage [mV]") else: pynml.print_comment("First you have to 'go()' the simulation.", True) plt.show() def go(self): lems_file_name = 'LEMS_%s.xml'%(self.reference) generate_lems_file_for_neuroml(self.reference, self.neuroml_file, self.target, self.sim_time, self.dt, lems_file_name = lems_file_name, target_dir = self.generate_dir, nml_doc = self.nml_doc) pynml.print_comment_v("Running a simulation of %s ms with timestep %s ms: %s"%(self.sim_time, self.dt, lems_file_name)) self.already_run = True start = time.time() if self.simulator == 'jNeuroML': results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=False, exec_in_dir = self.generate_dir, verbose=False, cleanup=self.cleanup) elif self.simulator == 'jNeuroML_NEURON': results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=False, exec_in_dir = self.generate_dir, verbose=False, cleanup=self.cleanup) else: pynml.print_comment_v('Unsupported simulator: %s'%self.simulator) exit() secs = time.time()-start pynml.print_comment_v("Ran simulation in %s in %f seconds (%f mins)\n\n"%(self.simulator, secs, secs/60.0)) self.t = [t*1000 for t in results['t']] self.volts = {} for key in results.keys(): if key != 't': self.volts[key] = [v*1000 for v in results[key]] if __name__ == '__main__': sim_time = 700 dt = 0.05 if len(sys.argv) == 2 and sys.argv[1] == '-net': sim = NeuroMLSimulation('TestNet', '../../examples/test_data/simplenet.nml', 'simplenet', sim_time, dt, 'jNeuroML', 'temp/') sim.go() sim.show() else: sim = NeuroMLSimulation('TestHH', '../../examples/test_data/HHCellNetwork.net.nml', 'HHCellNetwork', sim_time, dt, 'jNeuroML', 'temp') sim.go() sim.show()
lgpl-3.0
0x0all/scikit-learn
examples/plot_multioutput_face_completion.py
330
3019
""" ============================================== Face completion with a multi-output estimators ============================================== This example shows the use of multi-output estimator to complete images. The goal is to predict the lower half of a face given its upper half. The first column of images shows true faces. The next columns illustrate how extremely randomized trees, k nearest neighbors, linear regression and ridge regression complete the lower half of those faces. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_olivetti_faces from sklearn.utils.validation import check_random_state from sklearn.ensemble import ExtraTreesRegressor from sklearn.neighbors import KNeighborsRegressor from sklearn.linear_model import LinearRegression from sklearn.linear_model import RidgeCV # Load the faces datasets data = fetch_olivetti_faces() targets = data.target data = data.images.reshape((len(data.images), -1)) train = data[targets < 30] test = data[targets >= 30] # Test on independent people # Test on a subset of people n_faces = 5 rng = check_random_state(4) face_ids = rng.randint(test.shape[0], size=(n_faces, )) test = test[face_ids, :] n_pixels = data.shape[1] X_train = train[:, :np.ceil(0.5 * n_pixels)] # Upper half of the faces y_train = train[:, np.floor(0.5 * n_pixels):] # Lower half of the faces X_test = test[:, :np.ceil(0.5 * n_pixels)] y_test = test[:, np.floor(0.5 * n_pixels):] # Fit estimators ESTIMATORS = { "Extra trees": ExtraTreesRegressor(n_estimators=10, max_features=32, random_state=0), "K-nn": KNeighborsRegressor(), "Linear regression": LinearRegression(), "Ridge": RidgeCV(), } y_test_predict = dict() for name, estimator in ESTIMATORS.items(): estimator.fit(X_train, y_train) y_test_predict[name] = estimator.predict(X_test) # Plot the completed faces image_shape = (64, 64) n_cols = 1 + len(ESTIMATORS) plt.figure(figsize=(2. * n_cols, 2.26 * n_faces)) plt.suptitle("Face completion with multi-output estimators", size=16) for i in range(n_faces): true_face = np.hstack((X_test[i], y_test[i])) if i: sub = plt.subplot(n_faces, n_cols, i * n_cols + 1) else: sub = plt.subplot(n_faces, n_cols, i * n_cols + 1, title="true faces") sub.axis("off") sub.imshow(true_face.reshape(image_shape), cmap=plt.cm.gray, interpolation="nearest") for j, est in enumerate(sorted(ESTIMATORS)): completed_face = np.hstack((X_test[i], y_test_predict[est][i])) if i: sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j) else: sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j, title=est) sub.axis("off") sub.imshow(completed_face.reshape(image_shape), cmap=plt.cm.gray, interpolation="nearest") plt.show()
bsd-3-clause
offbye/paparazzi
sw/tools/calibration/calibrate_gyro.py
87
4686
#! /usr/bin/env python # Copyright (C) 2010 Antoine Drouin # # This file is part of Paparazzi. # # Paparazzi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # Paparazzi 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 Paparazzi; see the file COPYING. If not, write to # the Free Software Foundation, 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # # calibrate gyrometers using turntable measurements # from __future__ import print_function, division from optparse import OptionParser import os import sys from scipy import linspace, polyval, stats import matplotlib.pyplot as plt import calibration_utils # # lisa 3 # p : a=-4511.16 b=31948.34, std error= 0.603 # q : a=-4598.46 b=31834.48, std error= 0.734 # r : a=-4525.63 b=32687.95, std error= 0.624 # # lisa 4 # p : a=-4492.05 b=32684.94, std error= 0.600 # q : a=-4369.63 b=33260.96, std error= 0.710 # r : a=-4577.13 b=32707.72, std error= 0.730 # # crista # p : a= 3864.82 b=31288.09, std error= 0.866 # q : a= 3793.71 b=32593.89, std error= 3.070 # r : a= 3817.11 b=32709.70, std error= 3.296 # def main(): usage = "usage: %prog --id <ac_id> --tt_id <tt_id> --axis <axis> [options] log_filename.data" + "\n" + "Run %prog --help to list the options." parser = OptionParser(usage) parser.add_option("-i", "--id", dest="ac_id", action="store", type=int, default=-1, help="aircraft id to use") parser.add_option("-t", "--tt_id", dest="tt_id", action="store", type=int, default=-1, help="turntable id to use") parser.add_option("-a", "--axis", dest="axis", type="choice", choices=['p', 'q', 'r'], help="axis to calibrate (p, q, r)", action="store") parser.add_option("-v", "--verbose", action="store_true", dest="verbose") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") else: if os.path.isfile(args[0]): filename = args[0] else: print(args[0] + " not found") sys.exit(1) if not filename.endswith(".data"): parser.error("Please specify a *.data log file") if options.ac_id < 0 or options.ac_id > 255: parser.error("Specify a valid aircraft id number!") if options.tt_id < 0 or options.tt_id > 255: parser.error("Specify a valid turntable id number!") if options.verbose: print("reading file "+filename+" for aircraft "+str(options.ac_id)+" and turntable "+str(options.tt_id)) samples = calibration_utils.read_turntable_log(options.ac_id, options.tt_id, filename, 1, 7) if len(samples) == 0: print("Error: found zero matching messages in log file!") print("Was looking for IMU_TURNTABLE from id: "+str(options.tt_id)+" and IMU_GYRO_RAW from id: "+str(options.ac_id)+" in file "+filename) sys.exit(1) if options.verbose: print("found "+str(len(samples))+" records") if options.axis == 'p': axis_idx = 1 elif options.axis == 'q': axis_idx = 2 elif options.axis == 'r': axis_idx = 3 else: parser.error("Specify a valid axis!") #Linear regression using stats.linregress t = samples[:, 0] xn = samples[:, axis_idx] (a_s, b_s, r, tt, stderr) = stats.linregress(t, xn) print('Linear regression using stats.linregress') print(('regression: a=%.2f b=%.2f, std error= %.3f' % (a_s, b_s, stderr))) print(('<define name="GYRO_X_NEUTRAL" value="%d"/>' % (b_s))) print(('<define name="GYRO_X_SENS" value="%f" integer="16"/>' % (pow(2, 12)/a_s))) # # overlay fited value # ovl_omega = linspace(1, 7.5, 10) ovl_adc = polyval([a_s, b_s], ovl_omega) plt.title('Linear Regression Example') plt.subplot(3, 1, 1) plt.plot(samples[:, 1]) plt.plot(samples[:, 2]) plt.plot(samples[:, 3]) plt.legend(['p', 'q', 'r']) plt.subplot(3, 1, 2) plt.plot(samples[:, 0]) plt.subplot(3, 1, 3) plt.plot(samples[:, 0], samples[:, axis_idx], 'b.') plt.plot(ovl_omega, ovl_adc, 'r') plt.show() if __name__ == "__main__": main()
gpl-2.0
stevenwudi/Kernelized_Correlation_Filter
CNN_training.py
1
3640
import numpy as np from keras.optimizers import SGD from models.CNN_CIFAR import cnn_cifar_batchnormalisation, cnn_cifar_small, cnn_cifar_nodropout, \ cnn_cifar_small_batchnormalisation from models.DataLoader import DataLoader from scripts.progress_bar import printProgress from time import time, localtime # this is a predefined dataloader loader = DataLoader(batch_size=32) # construct the model here (pre-defined model) model = cnn_cifar_small_batchnormalisation(loader.image_shape) print(model.name) nb_epoch = 200 early_stopping = True early_stopping_count = 0 early_stopping_wait = 3 train_loss = [] valid_loss = [] learning_rate = [0.0001, 0.001, 0.01] # let's train the model using SGD + momentum (how original). sgd = SGD(lr=learning_rate[-1], decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd) # load validation data from the h5py file (heavy lifting here) x_valid, y_valid = loader.get_valid() best_valid = np.inf for e in range(nb_epoch): print("epoch %d" % e) loss_list = [] time_list = [] time_start = time() for i in range(loader.n_iter_train): time_start_batch = time() X_batch, Y_batch = loader.next_train_batch() loss_list.append(model.train_on_batch(X_batch, Y_batch)) # calculate some time information time_list.append(time() - time_start_batch) eta = (loader.n_iter_train - i) * np.array(time_list).mean() printProgress(i, loader.n_iter_train-1, prefix='Progress:', suffix='batch error: %0.5f, ETA: %0.2f sec.'%(np.array(loss_list).mean(), eta), barLength=50) printProgress(i, loader.n_iter_train - 1, prefix='Progress:', suffix='batch error: %0.5f' % (np.array(loss_list).mean()), barLength=50) train_loss.append(np.asarray(loss_list).mean()) print('training loss is %f, one epoch uses: %0.2f sec' % (train_loss[-1], time() - time_start)) valid_loss.append(model.evaluate(x_valid, y_valid)) print('valid loss is %f' % valid_loss[-1]) if best_valid > valid_loss[-1]: early_stopping_count = 0 print('saving best valid result...') best_valid = valid_loss[-1] model.save('./models/CNN_Model_OBT100_multi_cnn_best_valid_'+model.name+'.h5') else: # we wait for early stopping loop until a certain time early_stopping_count += 1 if early_stopping_count > early_stopping_wait: early_stopping_count = 0 if len(learning_rate) > 1: learning_rate.pop() print('decreasing the learning rate to: %f'%learning_rate[-1]) model.optimizer.lr.set_value(learning_rate[-1]) else: break lt = localtime() lt_str = str(lt.tm_year)+"."+str(lt.tm_mon).zfill(2)+"." \ +str(lt.tm_mday).zfill(2)+"."+str(lt.tm_hour).zfill(2)+"."\ +str(lt.tm_min).zfill(2)+"."+str(lt.tm_sec).zfill(2) np.savetxt('./models/train_loss_'+model.name+'_'+lt_str+'.txt', train_loss) np.savetxt('./models/valid_loss_'+model.name+'_'+lt_str+'.txt', valid_loss) model.save('./models/CNN_Model_OBT100_multi_cnn_'+model.name+'_final.h5') print("done") #### we show some visualisation here import matplotlib.pyplot as plt import matplotlib.patches as mpatches train_loss = np.loadtxt('./models/train_loss_'+model.name+'_'+lt_str+'.txt') valid_loss = np.loadtxt('./models/valid_loss_'+model.name+'_'+lt_str+'.txt') plt.plot(train_loss, 'b') plt.plot(valid_loss, 'r') blue_label = mpatches.Patch(color='blue', label='train_loss') red_label = mpatches.Patch(color='red', label='valid_loss') plt.legend(handles=[blue_label, red_label])
gpl-3.0
dhhagan/PAM
Python/PAM.py
1
5037
#PAM.py import re import glob, os, time from numpy import * from pylab import * def analyzeFile(fileName,delim): cols = {} indexToName = {} lineNum = 0 goodLines = 0 shortLines = 0 FILE = open(fileName,'r') for line in FILE: line = line.strip() if lineNum < 1: lineNum += 1 continue elif lineNum == 1: headings = line.split(delim) i = 0 for heading in headings: heading = heading.strip() cols[heading] = [] indexToName[i] = heading i += 1 lineNum += 1 lineLength = len(cols) else: data = line.split(delim) if len(data) == lineLength: goodLines += 1 i = 0 for point in data: point = point.strip() cols[indexToName[i]] += [point] i += 1 lineNum += 1 else: shortLines += 1 lineNum += 1 continue FILE.close return cols, indexToName, lineNum, shortLines def numericalSort(value): numbers = re.compile(r'(\d+)') parts = numbers.split(value) parts[1::2] = map(int, parts[1::2]) return parts def popDate(fileName): run = fileName.split('.')[0] runNo = run.split('_')[-1] return runNo def getFile(date,regex):#Works files = [] files = sorted((glob.glob('*'+regex+'*')),key=numericalSort,reverse=False) if date.lower() == 'last': files = files.pop() else: files = [item for item in files if re.search(date,item)] return files def plotConc(data,ozone,times): # This function plots data versus time import datetime as dt from matplotlib import pyplot as plt from matplotlib.dates import date2num #time = [dt.datetime.strptime(time,"%m/%d/%Y %I:%M:%S %p") for time in times] time = [dt.datetime.strptime(time,"%m/%d/%Y %I:%M:%S %p") for time in times] x = date2num(time) legend1 = [] legend2 = [] fig = plt.figure('Gas Concentration Readings for East St.Louis') ax1 = fig.add_subplot(111) ax2 = twinx() for key,value in data.items(): ax1.plot_date(x,data[key],'-',xdate=True) legend1.append(key) for key, value in ozone.items(): ax2.plot_date(x,ozone[key],'-.',xdate=True) legend2.append(key) title('Gas Concentrations for East St. Louis', fontsize = 12) ax1.set_ylabel(r'$Concentration(ppb)$', fontsize = 12) ax2.set_ylabel(r'$Concentration(ppb)$', fontsize = 12) xlabel(r"$Time \, Stamp$", fontsize = 12) ax1.legend(legend1,loc='upper right') ax2.legend(legend2,loc='lower right') grid(True) return def plotBankRelays(data,relays,times): # This function plots data versus time import datetime as dt from matplotlib import pyplot as plt from matplotlib.dates import date2num time = [dt.datetime.strptime(time,"%m/%d/%Y %I:%M:%S %p") for time in times] x = date2num(time) #x1 = [date.strftime("%m-%d %H:%M:%S") for date in time] legend1 = [] legend2 = [] #plt.locator_params(axis='x', nbins=4) fig = plt.figure('VAPS Thermocouple Readings: Chart 2') ax1 = fig.add_subplot(111) ax2 = twinx() for key,value in data.items(): ax1.plot_date(x,data[key],'-',xdate=True) legend1.append(key) for key,value in relays.items(): ax2.plot_date(x,relays[key],'--',xdate=True) legend2.append(key) title('VAPS Temperatures: Chart 2', fontsize = 12) ax1.set_ylabel(r'$Temperature(^oC)$', fontsize = 12) ax2.set_ylabel(r'$Relay \, States$', fontsize = 12) ax1.set_xlabel(r"$Time \, Stamp$", fontsize = 12) #print [num2date(item) for item in ax1.get_xticks()] #ax1.set_xticks(x) #ax1.set_xticklabels([date.strftime("%m-%d %H:%M %p") for date in time]) #ax1.legend(bbox_to_anchor=(0.,1.02,1.,.102),loc=3,ncol=2,mode="expand",borderaxespad=0.) ax1.legend(legend1,loc='upper right') ax2.legend(legend2,loc='lower right') #ax1.xaxis.set_major_formatter(FormatStrFormatter(date.strftime("%m-%d %H:%M:%S"))) plt.subplots_adjust(bottom=0.15) grid(True) return def goodFiles(files,goodHeaders,delim): # Good irregFiles = 0 goodFiles = [] for file in files: lineNo = 0 falseCount = 0 FILE = open(file,'r') for line in FILE: line = line.strip() if lineNo == 5: # Check all the headings to make sure the file is good head = line.split(delim) for item in head: if item in goodHeaders: continue else: falseCount += 1 if falseCount == 0: goodFiles.append(file) else: irregFiles += 1 lineNo += 1 else: lineNo += 1 continue FILE.close return goodFiles, irregFiles
mit
shadowk29/cusumtools
legacy/minimal_psd.py
1
12009
## COPYRIGHT ## Copyright (C) 2015 Kyle Briggs (kbrig035<at>uottawa.ca) ## ## This file is part of cusumtools. ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. import matplotlib matplotlib.use('TkAgg') import numpy as np import tkinter.filedialog import tkinter as tk from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg import scipy.io as sio from scipy.signal import bessel, filtfilt, welch from scikits.samplerate import resample import pylab as pl import glob import os import time import pandas as pd from pandasql import sqldf import re def make_format(current, other): # current and other are axes def format_coord(x, y): # x, y are data coordinates # convert to display coords display_coord = current.transData.transform((x,y)) inv = other.transData.inverted() # convert back to data coords with respect to ax ax_coord = inv.transform(display_coord) coords = [ax_coord, (x, y)] return ('Left: {:<40} Right: {:<}' .format(*['({:.3f}, {:.3f})'.format(x, y) for x,y in coords])) return format_coord class App(tk.Frame): def __init__(self, parent,file_path): tk.Frame.__init__(self, parent) parent.deiconify() self.events_flag = False self.baseline_flag = False self.file_path = file_path ##### Trace plotting widgets ##### self.trace_frame = tk.LabelFrame(parent,text='Current Trace') self.trace_fig = Figure(figsize=(7,5), dpi=100) self.trace_canvas = FigureCanvasTkAgg(self.trace_fig, master=self.trace_frame) self.trace_toolbar_frame = tk.Frame(self.trace_frame) self.trace_toolbar = NavigationToolbar2TkAgg(self.trace_canvas, self.trace_toolbar_frame) self.trace_toolbar.update() self.trace_frame.grid(row=0,column=0,columnspan=6,sticky=tk.N+tk.S) self.trace_toolbar_frame.grid(row=1,column=0,columnspan=6) self.trace_canvas.get_tk_widget().grid(row=0,column=0,columnspan=6) ##### PSD plotting widgets ##### self.psd_frame = tk.LabelFrame(parent,text='Power Spectrum') self.psd_fig = Figure(figsize=(7,5), dpi=100) self.psd_canvas = FigureCanvasTkAgg(self.psd_fig, master=self.psd_frame) self.psd_toolbar_frame = tk.Frame(self.psd_frame) self.psd_toolbar = NavigationToolbar2TkAgg(self.psd_canvas, self.psd_toolbar_frame) self.psd_toolbar.update() self.psd_frame.grid(row=0,column=6,columnspan=6,sticky=tk.N+tk.S) self.psd_toolbar_frame.grid(row=1,column=6,columnspan=6) self.psd_canvas.get_tk_widget().grid(row=0,column=6,columnspan=6) ##### Control widgets ##### self.control_frame = tk.LabelFrame(parent, text='Controls') self.control_frame.grid(row=2,column=0,columnspan=6,sticky=tk.N+tk.S+tk.E+tk.W) self.start_entry = tk.Entry(self.control_frame) self.start_entry.insert(0,'0') self.start_label = tk.Label(self.control_frame, text='Start Time (s)') self.start_label.grid(row=0,column=0,sticky=tk.E+tk.W) self.start_entry.grid(row=0,column=1,sticky=tk.E+tk.W) self.end_entry = tk.Entry(self.control_frame) self.end_entry.insert(0,'10') self.end_label = tk.Label(self.control_frame, text='End Time (s)') self.end_label.grid(row=0,column=2,sticky=tk.E+tk.W) self.end_entry.grid(row=0,column=3,sticky=tk.E+tk.W) self.cutoff_entry = tk.Entry(self.control_frame) self.cutoff_entry.insert(0,'') self.cutoff_label = tk.Label(self.control_frame, text='Cutoff (Hz)') self.cutoff_label.grid(row=1,column=0,sticky=tk.E+tk.W) self.cutoff_entry.grid(row=1,column=1,sticky=tk.E+tk.W) self.order_entry = tk.Entry(self.control_frame) self.order_entry.insert(0,'') self.order_label = tk.Label(self.control_frame, text='Filter Order') self.order_label.grid(row=1,column=2,sticky=tk.E+tk.W) self.order_entry.grid(row=1,column=3,sticky=tk.E+tk.W) self.samplerate_entry = tk.Entry(self.control_frame) self.samplerate_entry.insert(0,'250000') self.samplerate_label = tk.Label(self.control_frame, text='Sampling Frequency (Hz)') self.samplerate_label.grid(row=1,column=4,sticky=tk.E+tk.W) self.samplerate_entry.grid(row=1,column=5,sticky=tk.E+tk.W) self.savegain_entry = tk.Entry(self.control_frame) self.savegain_entry.insert(0,'1') self.savegain_label = tk.Label(self.control_frame, text='Sampling Frequency (Hz)') self.savegain_label.grid(row=0,column=4,sticky=tk.E+tk.W) self.savegain_entry.grid(row=0,column=5,sticky=tk.E+tk.W) self.plot_trace = tk.Button(self.control_frame, text='Update Trace', command=self.update_trace) self.plot_trace.grid(row=2,column=0,columnspan=2,sticky=tk.E+tk.W) self.normalize = tk.IntVar() self.normalize.set(0) self.normalize_check = tk.Checkbutton(self.control_frame, text='Normalize', variable = self.normalize) self.normalize_check.grid(row=2,column=2,sticky=tk.E+tk.W) self.plot_psd = tk.Button(self.control_frame, text='Update PSD', command=self.update_psd) self.plot_psd.grid(row=2,column=3,sticky=tk.E+tk.W) ##### Feedback Widgets ##### self.feedback_frame = tk.LabelFrame(parent, text='Status') self.feedback_frame.grid(row=2,column=6,columnspan=6,sticky=tk.N+tk.S+tk.E+tk.W) self.export_psd = tk.Button(self.feedback_frame, text='Export PSD',command=self.export_psd) self.export_psd.grid(row=1,column=0,columnspan=6,sticky=tk.E+tk.W) self.export_trace = tk.Button(self.feedback_frame, text='Export Trace',command=self.export_trace) self.export_trace.grid(row=2,column=0,columnspan=6,sticky=tk.E+tk.W) self.load_memmap() self.initialize_samplerate() def export_psd(self): try: data_path = tkinter.filedialog.asksaveasfilename(defaultextension='.csv',initialdir='G:\PSDs for Sam') np.savetxt(data_path,np.c_[self.f, self.Pxx, self.rms],delimiter=',') except AttributeError: self.wildcard.set('Plot the PSD first') def export_trace(self): try: data_path = tkinter.filedialog.asksaveasfilename(defaultextension='.csv',initialdir='G:\Analysis\Pores\NPN\PSDs') np.savetxt(data_path,self.plot_data,delimiter=',') except AttributeError: self.wildcard.set('Plot the trace first') def load_mapped_data(self): self.total_samples = len(self.map) self.samplerate = int(self.samplerate_entry.get()) if self.start_entry.get()!='': self.start_time = float(self.start_entry.get()) start_index = int((float(self.start_entry.get())*self.samplerate)) else: self.start_time = 0 start_index = 0 if self.end_entry.get()!='': self.end_time = float(self.end_entry.get()) end_index = int((float(self.end_entry.get())*self.samplerate)) if end_index > self.total_samples: end_index = self.total_samples self.data = self.map[start_index:end_index] self.data = float(self.savegain_entry.get()) * self.data def load_memmap(self): columntypes = np.dtype([('current', '>i2'), ('voltage', '>i2')]) self.map = np.memmap(self.file_path, dtype=columntypes, mode='r')['current'] def integrate_noise(self, f, Pxx): df = f[1]-f[0] return np.sqrt(np.cumsum(Pxx * df)) def filter_data(self): cutoff = float(self.cutoff_entry.get()) order = int(self.order_entry.get()) Wn = 2.0 * cutoff/float(self.samplerate) b, a = bessel(order,Wn,'low') padding = 1000 padded = np.pad(self.data, pad_width=padding, mode='median') self.filtered_data = filtfilt(b, a, padded, padtype=None)[padding:-padding] def initialize_samplerate(self): self.samplerate = float(self.samplerate_entry.get()) ##### Plot Updating functions ##### def update_trace(self): self.initialize_samplerate() self.load_mapped_data() self.filtered_data = self.data self.plot_data = self.filtered_data plot_samplerate = self.samplerate if self.cutoff_entry.get()!='' and self.order_entry!='': self.filter_data() self.plot_data = self.filtered_data self.trace_fig.clf() a = self.trace_fig.add_subplot(111) time = np.linspace(1.0/self.samplerate,len(self.plot_data)/float(self.samplerate),len(self.plot_data))+self.start_time a.set_xlabel(r'Time ($\mu s$)') a.set_ylabel('Current (pA)') self.trace_fig.subplots_adjust(bottom=0.14,left=0.21) a.plot(time*1e6,self.plot_data,'.',markersize=1) self.trace_canvas.show() def update_psd(self): self.initialize_samplerate() self.load_mapped_data() self.filtered_data = self.data self.plot_data = self.filtered_data plot_samplerate = self.samplerate if self.cutoff_entry.get()!='' and self.order_entry!='': self.filter_data() self.plot_data = self.filtered_data maxf = 2*float(self.cutoff_entry.get()) else: maxf = 2*float(self.samplerate_entry.get()) length = np.minimum(2**18,len(self.filtered_data)) end_index = int(np.floor(len(self.filtered_data)/length)*length) current = np.average(self.filtered_data[:end_index]) f, Pxx = welch(self.filtered_data, plot_samplerate,nperseg=length) self.rms = self.integrate_noise(f, Pxx) if self.normalize.get(): Pxx /= current**2 Pxx *= maxf/2.0 self.rms /= np.absolute(current) self.f = f self.Pxx = Pxx minf = 1 BW_index = np.searchsorted(f, maxf/2) logPxx = np.log10(Pxx[1:BW_index]) minP = 10**np.floor(np.amin(logPxx)) maxP = 10**np.ceil(np.amax(logPxx)) self.psd_fig.clf() a = self.psd_fig.add_subplot(111) a.set_xlabel('Frequency (Hz)') a.set_ylabel(r'Spectral Power ($\mathrm{pA}^2/\mathrm{Hz}$)') a.set_xlim(minf, maxf) a.set_ylim(minP, maxP) self.psd_fig.subplots_adjust(bottom=0.14,left=0.21) a.loglog(f[1:],Pxx[1:],'b-') for tick in a.get_yticklabels(): tick.set_color('b') a2 = a.twinx() a2.semilogx(f, self.rms, 'r-') a2.set_ylabel('RMS Noise (pA)') a2.set_xlim(minf, maxf) for tick in a2.get_yticklabels(): tick.set_color('r') a2.format_coord = make_format(a2, a) self.psd_canvas.show() def main(): root=tk.Tk() root.withdraw() file_path = tkinter.filedialog.askopenfilename(initialdir='C:/Data/') App(root,file_path).grid(row=0,column=0) root.mainloop() if __name__=="__main__": main()
gpl-3.0
tienjunhsu/trading-with-python
lib/widgets.py
78
3012
# -*- coding: utf-8 -*- """ A collection of widgets for gui building Copyright: Jev Kuznetsov License: BSD """ from __future__ import division import sys from PyQt4.QtCore import * from PyQt4.QtGui import * import numpy as np from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from matplotlib.figure import Figure import matplotlib.pyplot as plt class MatplotlibWidget(QWidget): def __init__(self,parent=None,grid=True): QWidget.__init__(self,parent) self.grid = grid self.fig = Figure() self.canvas =FigureCanvas(self.fig) self.canvas.setParent(self) self.canvas.mpl_connect('button_press_event', self.onPick) # bind pick event #self.axes = self.fig.add_subplot(111) margins = [0.05,0.1,0.9,0.8] self.axes = self.fig.add_axes(margins) self.toolbar = NavigationToolbar(self.canvas,self) #self.initFigure() layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.setLayout(layout) def onPick(self,event): print 'Pick event' print 'you pressed', event.button, event.xdata, event.ydata def update(self): self.canvas.draw() def plot(self,*args,**kwargs): self.axes.plot(*args,**kwargs) self.axes.grid(self.grid) self.update() def clear(self): self.axes.clear() def initFigure(self): self.axes.grid(True) x = np.linspace(-1,1) y = x**2 self.axes.plot(x,y,'o-') class PlotWindow(QMainWindow): ''' a stand-alone window with embedded matplotlib widget ''' def __init__(self,parent=None): super(PlotWindow,self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) self.mplWidget = MatplotlibWidget() self.setCentralWidget(self.mplWidget) def plot(self,dataFrame): ''' plot dataframe ''' dataFrame.plot(ax=self.mplWidget.axes) def getAxes(self): return self.mplWidget.axes def getFigure(self): return self.mplWidget.fig def update(self): self.mplWidget.update() class MainForm(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowTitle('Demo: PyQt with matplotlib') self.plot = MatplotlibWidget() self.setCentralWidget(self.plot) self.plot.clear() self.plot.plot(np.random.rand(10),'x-') #--------------------- if __name__=='__main__': app = QApplication(sys.argv) form = MainForm() form.show() app.exec_()
bsd-3-clause
daniel20162016/my-first
read_xml_all/calcul_matrix_compare_je_good_192matrix.py
1
6357
# -*- coding: utf-8 -*- """ Created on Mon Oct 31 15:45:22 2016 @author: wang """ #from matplotlib import pylab as plt #from numpy import fft, fromstring, int16, linspace #import wave from read_wav_xml_good_1 import* from matrix_24_2 import* from max_matrix_norm import* import numpy as np # open a wave file filename = 'francois_filon_pure_3.wav' filename_1 ='francois_filon_pure_3.xml' word ='je' wave_signal_float,framerate, word_start_point, word_length_point, word_end_point= read_wav_xml_good_1(filename,filename_1,word) #print 'word_start_point=',word_start_point #print 'word_length_point=',word_length_point #print 'word_end_point=',word_end_point XJ_1 =wave_signal_float t_step=1920; t_entre_step=1440; t_du_1_1 = int(word_start_point[0]); t_du_1_2 = int(word_end_point[0]); t_du_2_1 = int(word_start_point[1]); t_du_2_2 = int(word_end_point[1]); t_du_3_1 = int(word_start_point[2]); t_du_3_2 = int(word_end_point[2]); t_du_4_1 = int(word_start_point[3]); t_du_4_2 = int(word_end_point[3]); t_du_5_1 = int(word_start_point[4]); t_du_5_2 = int(word_end_point[4]); fs=framerate #XJ_du_1 = wave_signal_float[(t_du_1_1-1):t_du_1_2]; #length_XJ_du_1 = int(word_length_point[0]+1); #x1,y1,z1=matrix_24_2(XJ_du_1,fs) #x1=max_matrix_norm(x1) #============================================================================== # this part is to calcul the first matrix #============================================================================== XJ_du_1_2 = XJ_1[(t_du_1_1-1):(t_du_1_1+t_step)]; x1_1,y1_1,z1_1=matrix_24_2(XJ_du_1_2 ,fs) x1_1=max_matrix_norm(x1_1) matrix_all_step_new_1 = np.zeros([192]) for i in range(0,24): matrix_all_step_new_1[i]=x1_1[i] #============================================================================== # the other colonne is the all fft #============================================================================== for i in range(1,8): XJ_du_1_total = XJ_1[(t_du_1_1+t_entre_step*(i)-1):(t_du_1_1+t_step+t_entre_step*(i) )]; x1_all,y1_all,z1_all=matrix_24_2(XJ_du_1_total,fs) x1_all=max_matrix_norm(x1_all) for j in range(0,24): matrix_all_step_new_1[24*i+j]=x1_all[j] #============================================================================== # this part is to calcul the second matrix #============================================================================== for k in range (1,2): t_start=t_du_2_1 XJ_du_1_2 = XJ_1[(t_start-1):(t_start+t_step)]; x1_1,y1_1,z1_1=matrix_24_2(XJ_du_1_2 ,fs) x1_1=max_matrix_norm(x1_1) matrix_all_step_new_2 = np.zeros([192]) for i in range(0,24): matrix_all_step_new_2[i]=x1_1[i] #============================================================================== # the other colonne is the all fft #============================================================================== for i in range(1,8): XJ_du_1_total = XJ_1[(t_start+t_entre_step*(i)-1):(t_start+t_step+t_entre_step*(i) )]; x1_all,y1_all,z1_all=matrix_24_2(XJ_du_1_total,fs) x1_all=max_matrix_norm(x1_all) for j in range(0,24): matrix_all_step_new_2[24*i+j]=x1_all[j] #============================================================================== # this part is to calcul the 3 matrix #============================================================================== for k in range (1,2): t_start=t_du_3_1 XJ_du_1_2 = XJ_1[(t_start-1):(t_start+t_step)]; x1_1,y1_1,z1_1=matrix_24_2(XJ_du_1_2 ,fs) x1_1=max_matrix_norm(x1_1) matrix_all_step_new_3 = np.zeros([192]) for i in range(0,24): matrix_all_step_new_3[i]=x1_1[i] #============================================================================== # the other colonne is the all fft #============================================================================== for i in range(1,8): XJ_du_1_total = XJ_1[(t_start+t_entre_step*(i)-1):(t_start+t_step+t_entre_step*(i) )]; x1_all,y1_all,z1_all=matrix_24_2(XJ_du_1_total,fs) x1_all=max_matrix_norm(x1_all) for j in range(0,24): matrix_all_step_new_3[24*i+j]=x1_all[j] #============================================================================== # this part is to calcul the 4 matrix #============================================================================== for k in range (1,2): t_start=t_du_4_1 XJ_du_1_2 = XJ_1[(t_start-1):(t_start+t_step)]; x1_1,y1_1,z1_1=matrix_24_2(XJ_du_1_2 ,fs) x1_1=max_matrix_norm(x1_1) matrix_all_step_new_4 = np.zeros([192]) for i in range(0,24): matrix_all_step_new_4[i]=x1_1[i] #============================================================================== # the other colonne is the all fft #============================================================================== for i in range(1,8): # print i XJ_du_1_total = XJ_1[(t_start+t_entre_step*(i)-1):(t_start+t_step+t_entre_step*(i) )]; x1_all,y1_all,z1_all=matrix_24_2(XJ_du_1_total,fs) x1_all=max_matrix_norm(x1_all) for j in range(0,24): matrix_all_step_new_4[24*i+j]=x1_all[j] #print 'matrix_all_step_4=',matrix_all_step_4 #============================================================================== # this part is to calcul the 5 matrix #============================================================================== for k in range (1,2): t_start=t_du_5_1 XJ_du_1_2 = XJ_1[(t_start-1):(t_start+t_step)]; x1_1,y1_1,z1_1=matrix_24_2(XJ_du_1_2 ,fs) x1_1=max_matrix_norm(x1_1) matrix_all_step_new_5 = np.zeros([192]) for i in range(0,24): matrix_all_step_new_5[i]=x1_1[i] #============================================================================== # the other colonne is the all fft #============================================================================== for i in range(1,8): # print i XJ_du_1_total = XJ_1[(t_start+t_entre_step*(i)-1):(t_start+t_step+t_entre_step*(i) )]; x1_all,y1_all,z1_all=matrix_24_2(XJ_du_1_total,fs) x1_all=max_matrix_norm(x1_all) for j in range(0,24): matrix_all_step_new_5[24*i+j]=x1_all[j] #print 'matrix_all_step_5=',matrix_all_step_5 np.savez('je_compare_192_matrix.npz',matrix_all_step_new_1,matrix_all_step_new_2,matrix_all_step_new_3,matrix_all_step_new_4,matrix_all_step_new_5)
mit
mringel/ThinkStats2
code/timeseries.py
66
18035
"""This file contains code for use with "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2014 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from __future__ import print_function import pandas import numpy as np import statsmodels.formula.api as smf import statsmodels.tsa.stattools as smtsa import matplotlib.pyplot as pyplot import thinkplot import thinkstats2 FORMATS = ['png'] def ReadData(): """Reads data about cannabis transactions. http://zmjones.com/static/data/mj-clean.csv returns: DataFrame """ transactions = pandas.read_csv('mj-clean.csv', parse_dates=[5]) return transactions def tmean(series): """Computes a trimmed mean. series: Series returns: float """ t = series.values n = len(t) if n <= 3: return t.mean() trim = max(1, n/10) return np.mean(sorted(t)[trim:n-trim]) def GroupByDay(transactions, func=np.mean): """Groups transactions by day and compute the daily mean ppg. transactions: DataFrame of transactions returns: DataFrame of daily prices """ groups = transactions[['date', 'ppg']].groupby('date') daily = groups.aggregate(func) daily['date'] = daily.index start = daily.date[0] one_year = np.timedelta64(1, 'Y') daily['years'] = (daily.date - start) / one_year return daily def GroupByQualityAndDay(transactions): """Divides transactions by quality and computes mean daily price. transaction: DataFrame of transactions returns: map from quality to time series of ppg """ groups = transactions.groupby('quality') dailies = {} for name, group in groups: dailies[name] = GroupByDay(group) return dailies def PlotDailies(dailies): """Makes a plot with daily prices for different qualities. dailies: map from name to DataFrame """ thinkplot.PrePlot(rows=3) for i, (name, daily) in enumerate(dailies.items()): thinkplot.SubPlot(i+1) title = 'price per gram ($)' if i == 0 else '' thinkplot.Config(ylim=[0, 20], title=title) thinkplot.Scatter(daily.ppg, s=10, label=name) if i == 2: pyplot.xticks(rotation=30) else: thinkplot.Config(xticks=[]) thinkplot.Save(root='timeseries1', formats=FORMATS) def RunLinearModel(daily): """Runs a linear model of prices versus years. daily: DataFrame of daily prices returns: model, results """ model = smf.ols('ppg ~ years', data=daily) results = model.fit() return model, results def PlotFittedValues(model, results, label=''): """Plots original data and fitted values. model: StatsModel model object results: StatsModel results object """ years = model.exog[:, 1] values = model.endog thinkplot.Scatter(years, values, s=15, label=label) thinkplot.Plot(years, results.fittedvalues, label='model') def PlotResiduals(model, results): """Plots the residuals of a model. model: StatsModel model object results: StatsModel results object """ years = model.exog[:, 1] thinkplot.Plot(years, results.resid, linewidth=0.5, alpha=0.5) def PlotResidualPercentiles(model, results, index=1, num_bins=20): """Plots percentiles of the residuals. model: StatsModel model object results: StatsModel results object index: which exogenous variable to use num_bins: how many bins to divide the x-axis into """ exog = model.exog[:, index] resid = results.resid.values df = pandas.DataFrame(dict(exog=exog, resid=resid)) bins = np.linspace(np.min(exog), np.max(exog), num_bins) indices = np.digitize(exog, bins) groups = df.groupby(indices) means = [group.exog.mean() for _, group in groups][1:-1] cdfs = [thinkstats2.Cdf(group.resid) for _, group in groups][1:-1] thinkplot.PrePlot(3) for percent in [75, 50, 25]: percentiles = [cdf.Percentile(percent) for cdf in cdfs] label = '%dth' % percent thinkplot.Plot(means, percentiles, label=label) def SimulateResults(daily, iters=101, func=RunLinearModel): """Run simulations based on resampling residuals. daily: DataFrame of daily prices iters: number of simulations func: function that fits a model to the data returns: list of result objects """ _, results = func(daily) fake = daily.copy() result_seq = [] for _ in range(iters): fake.ppg = results.fittedvalues + thinkstats2.Resample(results.resid) _, fake_results = func(fake) result_seq.append(fake_results) return result_seq def SimulateIntervals(daily, iters=101, func=RunLinearModel): """Run simulations based on different subsets of the data. daily: DataFrame of daily prices iters: number of simulations func: function that fits a model to the data returns: list of result objects """ result_seq = [] starts = np.linspace(0, len(daily), iters).astype(int) for start in starts[:-2]: subset = daily[start:] _, results = func(subset) fake = subset.copy() for _ in range(iters): fake.ppg = (results.fittedvalues + thinkstats2.Resample(results.resid)) _, fake_results = func(fake) result_seq.append(fake_results) return result_seq def GeneratePredictions(result_seq, years, add_resid=False): """Generates an array of predicted values from a list of model results. When add_resid is False, predictions represent sampling error only. When add_resid is True, they also include residual error (which is more relevant to prediction). result_seq: list of model results years: sequence of times (in years) to make predictions for add_resid: boolean, whether to add in resampled residuals returns: sequence of predictions """ n = len(years) d = dict(Intercept=np.ones(n), years=years, years2=years**2) predict_df = pandas.DataFrame(d) predict_seq = [] for fake_results in result_seq: predict = fake_results.predict(predict_df) if add_resid: predict += thinkstats2.Resample(fake_results.resid, n) predict_seq.append(predict) return predict_seq def GenerateSimplePrediction(results, years): """Generates a simple prediction. results: results object years: sequence of times (in years) to make predictions for returns: sequence of predicted values """ n = len(years) inter = np.ones(n) d = dict(Intercept=inter, years=years, years2=years**2) predict_df = pandas.DataFrame(d) predict = results.predict(predict_df) return predict def PlotPredictions(daily, years, iters=101, percent=90, func=RunLinearModel): """Plots predictions. daily: DataFrame of daily prices years: sequence of times (in years) to make predictions for iters: number of simulations percent: what percentile range to show func: function that fits a model to the data """ result_seq = SimulateResults(daily, iters=iters, func=func) p = (100 - percent) / 2 percents = p, 100-p predict_seq = GeneratePredictions(result_seq, years, add_resid=True) low, high = thinkstats2.PercentileRows(predict_seq, percents) thinkplot.FillBetween(years, low, high, alpha=0.3, color='gray') predict_seq = GeneratePredictions(result_seq, years, add_resid=False) low, high = thinkstats2.PercentileRows(predict_seq, percents) thinkplot.FillBetween(years, low, high, alpha=0.5, color='gray') def PlotIntervals(daily, years, iters=101, percent=90, func=RunLinearModel): """Plots predictions based on different intervals. daily: DataFrame of daily prices years: sequence of times (in years) to make predictions for iters: number of simulations percent: what percentile range to show func: function that fits a model to the data """ result_seq = SimulateIntervals(daily, iters=iters, func=func) p = (100 - percent) / 2 percents = p, 100-p predict_seq = GeneratePredictions(result_seq, years, add_resid=True) low, high = thinkstats2.PercentileRows(predict_seq, percents) thinkplot.FillBetween(years, low, high, alpha=0.2, color='gray') def Correlate(dailies): """Compute the correlation matrix between prices for difference qualities. dailies: map from quality to time series of ppg returns: correlation matrix """ df = pandas.DataFrame() for name, daily in dailies.items(): df[name] = daily.ppg return df.corr() def CorrelateResid(dailies): """Compute the correlation matrix between residuals. dailies: map from quality to time series of ppg returns: correlation matrix """ df = pandas.DataFrame() for name, daily in dailies.items(): _, results = RunLinearModel(daily) df[name] = results.resid return df.corr() def TestCorrelateResid(dailies, iters=101): """Tests observed correlations. dailies: map from quality to time series of ppg iters: number of simulations """ t = [] names = ['high', 'medium', 'low'] for name in names: daily = dailies[name] t.append(SimulateResults(daily, iters=iters)) corr = CorrelateResid(dailies) arrays = [] for result_seq in zip(*t): df = pandas.DataFrame() for name, results in zip(names, result_seq): df[name] = results.resid opp_sign = corr * df.corr() < 0 arrays.append((opp_sign.astype(int))) print(np.sum(arrays)) def RunModels(dailies): """Runs linear regression for each group in dailies. dailies: map from group name to DataFrame """ rows = [] for daily in dailies.values(): _, results = RunLinearModel(daily) intercept, slope = results.params p1, p2 = results.pvalues r2 = results.rsquared s = r'%0.3f (%0.2g) & %0.3f (%0.2g) & %0.3f \\' row = s % (intercept, p1, slope, p2, r2) rows.append(row) # print results in a LaTeX table print(r'\begin{tabular}{|c|c|c|}') print(r'\hline') print(r'intercept & slope & $R^2$ \\ \hline') for row in rows: print(row) print(r'\hline') print(r'\end{tabular}') def FillMissing(daily, span=30): """Fills missing values with an exponentially weighted moving average. Resulting DataFrame has new columns 'ewma' and 'resid'. daily: DataFrame of daily prices span: window size (sort of) passed to ewma returns: new DataFrame of daily prices """ dates = pandas.date_range(daily.index.min(), daily.index.max()) reindexed = daily.reindex(dates) ewma = pandas.ewma(reindexed.ppg, span=span) resid = (reindexed.ppg - ewma).dropna() fake_data = ewma + thinkstats2.Resample(resid, len(reindexed)) reindexed.ppg.fillna(fake_data, inplace=True) reindexed['ewma'] = ewma reindexed['resid'] = reindexed.ppg - ewma return reindexed def AddWeeklySeasonality(daily): """Adds a weekly pattern. daily: DataFrame of daily prices returns: new DataFrame of daily prices """ frisat = (daily.index.dayofweek==4) | (daily.index.dayofweek==5) fake = daily.copy() fake.ppg[frisat] += np.random.uniform(0, 2, frisat.sum()) return fake def PrintSerialCorrelations(dailies): """Prints a table of correlations with different lags. dailies: map from category name to DataFrame of daily prices """ filled_dailies = {} for name, daily in dailies.items(): filled_dailies[name] = FillMissing(daily, span=30) # print serial correlations for raw price data for name, filled in filled_dailies.items(): corr = thinkstats2.SerialCorr(filled.ppg, lag=1) print(name, corr) rows = [] for lag in [1, 7, 30, 365]: row = [str(lag)] for name, filled in filled_dailies.items(): corr = thinkstats2.SerialCorr(filled.resid, lag) row.append('%.2g' % corr) rows.append(row) print(r'\begin{tabular}{|c|c|c|c|}') print(r'\hline') print(r'lag & high & medium & low \\ \hline') for row in rows: print(' & '.join(row) + r' \\') print(r'\hline') print(r'\end{tabular}') filled = filled_dailies['high'] acf = smtsa.acf(filled.resid, nlags=365, unbiased=True) print('%0.3f, %0.3f, %0.3f, %0.3f, %0.3f' % (acf[0], acf[1], acf[7], acf[30], acf[365])) def SimulateAutocorrelation(daily, iters=1001, nlags=40): """Resample residuals, compute autocorrelation, and plot percentiles. daily: DataFrame iters: number of simulations to run nlags: maximum lags to compute autocorrelation """ # run simulations t = [] for _ in range(iters): filled = FillMissing(daily, span=30) resid = thinkstats2.Resample(filled.resid) acf = smtsa.acf(resid, nlags=nlags, unbiased=True)[1:] t.append(np.abs(acf)) high = thinkstats2.PercentileRows(t, [97.5])[0] low = -high lags = range(1, nlags+1) thinkplot.FillBetween(lags, low, high, alpha=0.2, color='gray') def PlotAutoCorrelation(dailies, nlags=40, add_weekly=False): """Plots autocorrelation functions. dailies: map from category name to DataFrame of daily prices nlags: number of lags to compute add_weekly: boolean, whether to add a simulated weekly pattern """ thinkplot.PrePlot(3) daily = dailies['high'] SimulateAutocorrelation(daily) for name, daily in dailies.items(): if add_weekly: daily = AddWeeklySeasonality(daily) filled = FillMissing(daily, span=30) acf = smtsa.acf(filled.resid, nlags=nlags, unbiased=True) lags = np.arange(len(acf)) thinkplot.Plot(lags[1:], acf[1:], label=name) def MakeAcfPlot(dailies): """Makes a figure showing autocorrelation functions. dailies: map from category name to DataFrame of daily prices """ axis = [0, 41, -0.2, 0.2] thinkplot.PrePlot(cols=2) PlotAutoCorrelation(dailies, add_weekly=False) thinkplot.Config(axis=axis, loc='lower right', ylabel='correlation', xlabel='lag (day)') thinkplot.SubPlot(2) PlotAutoCorrelation(dailies, add_weekly=True) thinkplot.Save(root='timeseries9', axis=axis, loc='lower right', xlabel='lag (days)', formats=FORMATS) def PlotRollingMean(daily, name): """Plots rolling mean and EWMA. daily: DataFrame of daily prices """ dates = pandas.date_range(daily.index.min(), daily.index.max()) reindexed = daily.reindex(dates) thinkplot.PrePlot(cols=2) thinkplot.Scatter(reindexed.ppg, s=15, alpha=0.1, label=name) roll_mean = pandas.rolling_mean(reindexed.ppg, 30) thinkplot.Plot(roll_mean, label='rolling mean') pyplot.xticks(rotation=30) thinkplot.Config(ylabel='price per gram ($)') thinkplot.SubPlot(2) thinkplot.Scatter(reindexed.ppg, s=15, alpha=0.1, label=name) ewma = pandas.ewma(reindexed.ppg, span=30) thinkplot.Plot(ewma, label='EWMA') pyplot.xticks(rotation=30) thinkplot.Save(root='timeseries10', formats=FORMATS) def PlotFilled(daily, name): """Plots the EWMA and filled data. daily: DataFrame of daily prices """ filled = FillMissing(daily, span=30) thinkplot.Scatter(filled.ppg, s=15, alpha=0.3, label=name) thinkplot.Plot(filled.ewma, label='EWMA', alpha=0.4) pyplot.xticks(rotation=30) thinkplot.Save(root='timeseries8', ylabel='price per gram ($)', formats=FORMATS) def PlotLinearModel(daily, name): """Plots a linear fit to a sequence of prices, and the residuals. daily: DataFrame of daily prices name: string """ model, results = RunLinearModel(daily) PlotFittedValues(model, results, label=name) thinkplot.Save(root='timeseries2', title='fitted values', xlabel='years', xlim=[-0.1, 3.8], ylabel='price per gram ($)', formats=FORMATS) PlotResidualPercentiles(model, results) thinkplot.Save(root='timeseries3', title='residuals', xlabel='years', ylabel='price per gram ($)', formats=FORMATS) #years = np.linspace(0, 5, 101) #predict = GenerateSimplePrediction(results, years) def main(name): thinkstats2.RandomSeed(18) transactions = ReadData() dailies = GroupByQualityAndDay(transactions) PlotDailies(dailies) RunModels(dailies) PrintSerialCorrelations(dailies) MakeAcfPlot(dailies) name = 'high' daily = dailies[name] PlotLinearModel(daily, name) PlotRollingMean(daily, name) PlotFilled(daily, name) years = np.linspace(0, 5, 101) thinkplot.Scatter(daily.years, daily.ppg, alpha=0.1, label=name) PlotPredictions(daily, years) xlim = years[0]-0.1, years[-1]+0.1 thinkplot.Save(root='timeseries4', title='predictions', xlabel='years', xlim=xlim, ylabel='price per gram ($)', formats=FORMATS) name = 'medium' daily = dailies[name] thinkplot.Scatter(daily.years, daily.ppg, alpha=0.1, label=name) PlotIntervals(daily, years) PlotPredictions(daily, years) xlim = years[0]-0.1, years[-1]+0.1 thinkplot.Save(root='timeseries5', title='predictions', xlabel='years', xlim=xlim, ylabel='price per gram ($)', formats=FORMATS) if __name__ == '__main__': import sys main(*sys.argv)
gpl-3.0
JamiiTech/mplh5canvas
examples/multi_plot.py
4
1357
#!/usr/bin/python """Testbed for the animation functionality of the backend, with multiple figures. It basically produces an long series of frames that get animated on the client browser side, this time with two figures. """ import matplotlib matplotlib.use('module://mplh5canvas.backend_h5canvas') from pylab import * import time def refresh_data(ax): t = arange(0.0 + count, 2.0 + count, 0.01) s = sin(2*pi*t) ax.lines[0].set_xdata(t) ax.lines[0].set_ydata(s) ax.set_xlim(t[0],t[-1]) t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) plot(t, s, linewidth=1.0) xlabel('time (s)') ylabel('voltage (mV)') title('Frist Post') f = gcf() ax = f.gca() count = 0 f2 = figure() ax2 = f2.gca() ax2.set_xlabel('IMDB rating') ax2.set_ylabel('South African Connections') ax2.set_title('Luds chart...') ax2.plot(arange(0.0, 5 + count, 0.01), arange(0.0, 5 + count, 0.01)) show(block=False, layout=2) # show the figure manager but don't block script execution so animation works.. # layout=2 overrides the default layout manager which only shows a single plot in the browser window while True: refresh_data(ax) d = arange(0.0, 5 + count, 0.01) ax2.lines[0].set_xdata(d) ax2.lines[0].set_ydata(d) ax2.set_xlim(d[0],d[-1]) ax2.set_ylim(d[0],d[-1]) f.canvas.draw() f2.canvas.draw() count += 0.01 time.sleep(1)
bsd-3-clause
xiawei0000/Kinectforactiondetect
ChalearnLAPSample.py
1
41779
# coding=gbk #------------------------------------------------------------------------------- # Name: Chalearn LAP sample # Purpose: Provide easy access to Chalearn LAP challenge data samples # # Author: Xavier Baro # # Created: 21/01/2014 # Copyright: (c) Xavier Baro 2014 # Licence: <your licence> #------------------------------------------------------------------------------- import os import zipfile import shutil import cv2 import numpy import csv from PIL import Image, ImageDraw from scipy.misc import imresize class Skeleton(object): """ Class that represents the skeleton information """ """¹Ç¼ÜÀ࣬ÊäÈë¹Ç¼ÜÊý¾Ý£¬½¨Á¢Àà""" #define a class to encode skeleton data def __init__(self,data): """ Constructor. Reads skeleton information from given raw data """ # Create an object from raw data self.joins=dict(); pos=0 self.joins['HipCenter']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['Spine']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['ShoulderCenter']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['Head']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['ShoulderLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['ElbowLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['WristLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['HandLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['ShoulderRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['ElbowRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['WristRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['HandRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['HipLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['KneeLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['AnkleLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['FootLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['HipRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['KneeRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['AnkleRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['FootRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) def getAllData(self): """ Return a dictionary with all the information for each skeleton node """ return self.joins def getWorldCoordinates(self): """ Get World coordinates for each skeleton node """ skel=dict() for key in self.joins.keys(): skel[key]=self.joins[key][0] return skel def getJoinOrientations(self): """ Get orientations of all skeleton nodes """ skel=dict() for key in self.joins.keys(): skel[key]=self.joins[key][1] return skel def getPixelCoordinates(self): """ Get Pixel coordinates for each skeleton node """ skel=dict() for key in self.joins.keys(): skel[key]=self.joins[key][2] return skel def toImage(self,width,height,bgColor): """ Create an image for the skeleton information """ SkeletonConnectionMap = (['HipCenter','Spine'],['Spine','ShoulderCenter'],['ShoulderCenter','Head'],['ShoulderCenter','ShoulderLeft'], \ ['ShoulderLeft','ElbowLeft'],['ElbowLeft','WristLeft'],['WristLeft','HandLeft'],['ShoulderCenter','ShoulderRight'], \ ['ShoulderRight','ElbowRight'],['ElbowRight','WristRight'],['WristRight','HandRight'],['HipCenter','HipRight'], \ ['HipRight','KneeRight'],['KneeRight','AnkleRight'],['AnkleRight','FootRight'],['HipCenter','HipLeft'], \ ['HipLeft','KneeLeft'],['KneeLeft','AnkleLeft'],['AnkleLeft','FootLeft']) im = Image.new('RGB', (width, height), bgColor) draw = ImageDraw.Draw(im) for link in SkeletonConnectionMap: p=self.getPixelCoordinates()[link[1]] p.extend(self.getPixelCoordinates()[link[0]]) draw.line(p, fill=(255,0,0), width=5) for node in self.getPixelCoordinates().keys(): p=self.getPixelCoordinates()[node] r=5 draw.ellipse((p[0]-r,p[1]-r,p[0]+r,p[1]+r),fill=(0,0,255)) del draw image = numpy.array(im) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) return image ##ÊÖÊÆÊý¾ÝµÄÀ࣬ÊäÈë·¾¶£¬½¨Á¢ÊÖÊÆÊý¾ÝÀà class GestureSample(object): """ Class that allows to access all the information for a certain gesture database sample """ #define class to access gesture data samples #³õʼ»¯£¬¶ÁÈ¡Îļþ def __init__ (self,fileName): """ Constructor. Read the sample file and unzip it if it is necessary. All the data is loaded. sample=GestureSample('Sample0001.zip') """ # Check the given file if not os.path.exists(fileName): #or not os.path.isfile(fileName): raise Exception("Sample path does not exist: " + fileName) # Prepare sample information self.fullFile = fileName self.dataPath = os.path.split(fileName)[0] self.file=os.path.split(fileName)[1] self.seqID=os.path.splitext(self.file)[0] self.samplePath=self.dataPath + os.path.sep + self.seqID; #ÅжÏÊÇzip»¹ÊÇĿ¼ # Unzip sample if it is necessary if os.path.isdir(self.samplePath) : self.unzip = False else: self.unzip = True zipFile=zipfile.ZipFile(self.fullFile,"r") zipFile.extractall(self.samplePath) # Open video access for RGB information rgbVideoPath=self.samplePath + os.path.sep + self.seqID + '_color.mp4' if not os.path.exists(rgbVideoPath): raise Exception("Invalid sample file. RGB data is not available") self.rgb = cv2.VideoCapture(rgbVideoPath) while not self.rgb.isOpened(): self.rgb = cv2.VideoCapture(rgbVideoPath) cv2.waitKey(500) # Open video access for Depth information depthVideoPath=self.samplePath + os.path.sep + self.seqID + '_depth.mp4' if not os.path.exists(depthVideoPath): raise Exception("Invalid sample file. Depth data is not available") self.depth = cv2.VideoCapture(depthVideoPath) while not self.depth.isOpened(): self.depth = cv2.VideoCapture(depthVideoPath) cv2.waitKey(500) # Open video access for User segmentation information userVideoPath=self.samplePath + os.path.sep + self.seqID + '_user.mp4' if not os.path.exists(userVideoPath): raise Exception("Invalid sample file. User segmentation data is not available") self.user = cv2.VideoCapture(userVideoPath) while not self.user.isOpened(): self.user = cv2.VideoCapture(userVideoPath) cv2.waitKey(500) # Read skeleton data skeletonPath=self.samplePath + os.path.sep + self.seqID + '_skeleton.csv' if not os.path.exists(skeletonPath): raise Exception("Invalid sample file. Skeleton data is not available") self.skeletons=[] with open(skeletonPath, 'rb') as csvfile: filereader = csv.reader(csvfile, delimiter=',') for row in filereader: self.skeletons.append(Skeleton(row)) del filereader # Read sample data sampleDataPath=self.samplePath + os.path.sep + self.seqID + '_data.csv' if not os.path.exists(sampleDataPath): raise Exception("Invalid sample file. Sample data is not available") self.data=dict() with open(sampleDataPath, 'rb') as csvfile: filereader = csv.reader(csvfile, delimiter=',') for row in filereader: self.data['numFrames']=int(row[0]) self.data['fps']=int(row[1]) self.data['maxDepth']=int(row[2]) del filereader # Read labels data labelsPath=self.samplePath + os.path.sep + self.seqID + '_labels.csv' if not os.path.exists(labelsPath): #warnings.warn("Labels are not available", Warning) self.labels=[] else: self.labels=[] with open(labelsPath, 'rb') as csvfile: filereader = csv.reader(csvfile, delimiter=',') for row in filereader: self.labels.append(map(int,row)) del filereader #Îö¹¹º¯Êý def __del__(self): """ Destructor. If the object unziped the sample, it remove the temporal data """ if self.unzip: self.clean() def clean(self): """ Clean temporal unziped data """ del self.rgb; del self.depth; del self.user; shutil.rmtree(self.samplePath) #´ÓvideoÖжÁÈ¡Ò»Ö¡·µ»Ø def getFrame(self,video, frameNum): """ Get a single frame from given video object """ # Check frame number # Get total number of frames numFrames = video.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT) # Check the given file if frameNum<1 or frameNum>numFrames: raise Exception("Invalid frame number <" + str(frameNum) + ">. Valid frames are values between 1 and " + str(int(numFrames))) # Set the frame index video.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,frameNum-1) ret,frame=video.read() if ret==False: raise Exception("Cannot read the frame") return frame #ÏÂÃæµÄº¯Êý¶¼ÊÇÕë¶ÔÊý¾Ý³ÉÔ±£¬µÄÌض¨Ö¡²Ù×÷µÄ def getRGB(self, frameNum): """ Get the RGB color image for the given frame """ #get RGB frame return self.getFrame(self.rgb,frameNum) #·µ»ØÉî¶Èͼ£¬Ê¹ÓÃ16int±£´æµÄ def getDepth(self, frameNum): """ Get the depth image for the given frame """ #get Depth frame depthData=self.getFrame(self.depth,frameNum) # Convert to grayscale depthGray=cv2.cvtColor(depthData,cv2.cv.CV_RGB2GRAY) # Convert to float point depth=depthGray.astype(numpy.float32) # Convert to depth values depth=depth/255.0*float(self.data['maxDepth']) depth=depth.round() depth=depth.astype(numpy.uint16) return depth def getUser(self, frameNum): """ Get user segmentation image for the given frame """ #get user segmentation frame return self.getFrame(self.user,frameNum) def getSkeleton(self, frameNum): """ Get the skeleton information for a given frame. It returns a Skeleton object """ #get user skeleton for a given frame # Check frame number # Get total number of frames numFrames = len(self.skeletons) # Check the given file if frameNum<1 or frameNum>numFrames: raise Exception("Invalid frame number <" + str(frameNum) + ">. Valid frames are values between 1 and " + str(int(numFrames))) return self.skeletons[frameNum-1] def getSkeletonImage(self, frameNum): """ Create an image with the skeleton image for a given frame """ return self.getSkeleton(frameNum).toImage(640,480,(255,255,255)) def getNumFrames(self): """ Get the number of frames for this sample """ return self.data['numFrames'] #½«ËùÓеÄÒ»Ö¡Êý¾Ý ´ò°üµ½Ò»¸ö´óµÄ¾ØÕóÀï def getComposedFrame(self, frameNum): """ Get a composition of all the modalities for a given frame """ # get sample modalities rgb=self.getRGB(frameNum) depthValues=self.getDepth(frameNum) user=self.getUser(frameNum) skel=self.getSkeletonImage(frameNum) # Build depth image depth = depthValues.astype(numpy.float32) depth = depth*255.0/float(self.data['maxDepth']) depth = depth.round() depth = depth.astype(numpy.uint8) depth = cv2.applyColorMap(depth,cv2.COLORMAP_JET) # Build final image compSize1=(max(rgb.shape[0],depth.shape[0]),rgb.shape[1]+depth.shape[1]) compSize2=(max(user.shape[0],skel.shape[0]),user.shape[1]+skel.shape[1]) comp = numpy.zeros((compSize1[0]+ compSize2[0],max(compSize1[1],compSize2[1]),3), numpy.uint8) # Create composition comp[:rgb.shape[0],:rgb.shape[1],:]=rgb comp[:depth.shape[0],rgb.shape[1]:rgb.shape[1]+depth.shape[1],:]=depth comp[compSize1[0]:compSize1[0]+user.shape[0],:user.shape[1],:]=user comp[compSize1[0]:compSize1[0]+skel.shape[0],user.shape[1]:user.shape[1]+skel.shape[1],:]=skel return comp def getComposedFrameOverlapUser(self, frameNum): """ Get a composition of all the modalities for a given frame """ # get sample modalities rgb=self.getRGB(frameNum) depthValues=self.getDepth(frameNum) user=self.getUser(frameNum) mask = numpy.mean(user, axis=2) > 150 mask = numpy.tile(mask, (3,1,1)) mask = mask.transpose((1,2,0)) # Build depth image depth = depthValues.astype(numpy.float32) depth = depth*255.0/float(self.data['maxDepth']) depth = depth.round() depth = depth.astype(numpy.uint8) depth = cv2.applyColorMap(depth,cv2.COLORMAP_JET) # Build final image compSize=(max(rgb.shape[0],depth.shape[0]),rgb.shape[1]+depth.shape[1]) comp = numpy.zeros((compSize[0]+ compSize[0],max(compSize[1],compSize[1]),3), numpy.uint8) # Create composition comp[:rgb.shape[0],:rgb.shape[1],:]=rgb comp[:depth.shape[0],rgb.shape[1]:rgb.shape[1]+depth.shape[1],:]= depth comp[compSize[0]:compSize[0]+user.shape[0],:user.shape[1],:]= mask * rgb comp[compSize[0]:compSize[0]+user.shape[0],user.shape[1]:user.shape[1]+user.shape[1],:]= mask * depth return comp def getComposedFrame_480(self, frameNum, ratio=0.5, topCut=60, botCut=140): """ Get a composition of all the modalities for a given frame """ # get sample modalities rgb=self.getRGB(frameNum) rgb = rgb[topCut:-topCut,botCut:-botCut,:] rgb = imresize(rgb, ratio, interp='bilinear') depthValues=self.getDepth(frameNum) user=self.getUser(frameNum) user = user[topCut:-topCut,botCut:-botCut,:] user = imresize(user, ratio, interp='bilinear') mask = numpy.mean(user, axis=2) > 150 mask = numpy.tile(mask, (3,1,1)) mask = mask.transpose((1,2,0)) # Build depth image depth = depthValues.astype(numpy.float32) depth = depth*255.0/float(self.data['maxDepth']) depth = depth.round() depth = depth[topCut:-topCut,botCut:-botCut] depth = imresize(depth, ratio, interp='bilinear') depth = depth.astype(numpy.uint8) depth = cv2.applyColorMap(depth,cv2.COLORMAP_JET) # Build final image compSize=(max(rgb.shape[0],depth.shape[0]),rgb.shape[1]+depth.shape[1]) comp = numpy.zeros((compSize[0]+ compSize[0],max(compSize[1],compSize[1]),3), numpy.uint8) # Create composition comp[:rgb.shape[0],:rgb.shape[1],:]=rgb comp[:depth.shape[0],rgb.shape[1]:rgb.shape[1]+depth.shape[1],:]= depth comp[compSize[0]:compSize[0]+user.shape[0],:user.shape[1],:]= mask * rgb comp[compSize[0]:compSize[0]+user.shape[0],user.shape[1]:user.shape[1]+user.shape[1],:]= mask * depth return comp def getDepth3DCNN(self, frameNum, ratio=0.5, topCut=60, botCut=140): """ Get a composition of all the modalities for a given frame """ # get sample modalities depthValues=self.getDepth(frameNum) user=self.getUser(frameNum) user = user[topCut:-topCut,botCut:-botCut,:] user = imresize(user, ratio, interp='bilinear') mask = numpy.mean(user, axis=2) > 150 # Build depth image depth = depthValues.astype(numpy.float32) depth = depth*255.0/float(self.data['maxDepth']) depth = depth.round() depth = depth[topCut:-topCut,botCut:-botCut] depth = imresize(depth, ratio, interp='bilinear') depth = depth.astype(numpy.uint8) return mask * depth def getDepthOverlapUser(self, frameNum, x_centre, y_centre, pixel_value, extractedFrameSize=224, upshift = 0): """ Get a composition of all the modalities for a given frame """ halfFrameSize = extractedFrameSize/2 user=self.getUser(frameNum) mask = numpy.mean(user, axis=2) > 150 ratio = pixel_value/ 3000 # Build depth image # get sample modalities depthValues=self.getDepth(frameNum) depth = depthValues.astype(numpy.float32) depth = depth*255.0/float(self.data['maxDepth']) mask = imresize(mask, ratio, interp='nearest') depth = imresize(depth, ratio, interp='bilinear') depth_temp = depth * mask depth_extracted = depth_temp[x_centre-halfFrameSize-upshift:x_centre+halfFrameSize-upshift, y_centre-halfFrameSize: y_centre+halfFrameSize] depth = depth.round() depth = depth.astype(numpy.uint8) depth = cv2.applyColorMap(depth,cv2.COLORMAP_JET) depth_extracted = depth_extracted.round() depth_extracted = depth_extracted.astype(numpy.uint8) depth_extracted = cv2.applyColorMap(depth_extracted,cv2.COLORMAP_JET) # Build final image compSize=(depth.shape[0],depth.shape[1]) comp = numpy.zeros((compSize[0] + extractedFrameSize,compSize[1]+compSize[1],3), numpy.uint8) # Create composition comp[:depth.shape[0],:depth.shape[1],:]=depth mask_new = numpy.tile(mask, (3,1,1)) mask_new = mask_new.transpose((1,2,0)) comp[:depth.shape[0],depth.shape[1]:depth.shape[1]+depth.shape[1],:]= mask_new * depth comp[compSize[0]:,:extractedFrameSize,:]= depth_extracted return comp def getDepthCentroid(self, startFrame, endFrame): """ Get a composition of all the modalities for a given frame """ x_centre = [] y_centre = [] pixel_value = [] for frameNum in range(startFrame, endFrame): user=self.getUser(frameNum) depthValues=self.getDepth(frameNum) depth = depthValues.astype(numpy.float32) #depth = depth*255.0/float(self.data['maxDepth']) mask = numpy.mean(user, axis=2) > 150 width, height = mask.shape XX, YY, count, pixel_sum = 0, 0, 0, 0 for x in range(width): for y in range(height): if mask[x, y]: XX += x YY += y count += 1 pixel_sum += depth[x, y] if count>0: x_centre.append(XX/count) y_centre.append(YY/count) pixel_value.append(pixel_sum/count) return [numpy.mean(x_centre), numpy.mean(y_centre), numpy.mean(pixel_value)] def getGestures(self): """ Get the list of gesture for this sample. Each row is a gesture, with the format (gestureID,startFrame,endFrame) """ return self.labels def getGestureName(self,gestureID): """ Get the gesture label from a given gesture ID """ names=('vattene','vieniqui','perfetto','furbo','cheduepalle','chevuoi','daccordo','seipazzo', \ 'combinato','freganiente','ok','cosatifarei','basta','prendere','noncenepiu','fame','tantotempo', \ 'buonissimo','messidaccordo','sonostufo') # Check the given file if gestureID<1 or gestureID>20: raise Exception("Invalid gesture ID <" + str(gestureID) + ">. Valid IDs are values between 1 and 20") return names[gestureID-1] def exportPredictions(self, prediction,predPath): """ Export the given prediction to the correct file in the given predictions path """ if not os.path.exists(predPath): os.makedirs(predPath) output_filename = os.path.join(predPath, self.seqID + '_prediction.csv') output_file = open(output_filename, 'wb') for row in prediction: output_file.write(repr(int(row[0])) + "," + repr(int(row[1])) + "," + repr(int(row[2])) + "\n") output_file.close() def play_video(self): """ play the video, Wudi adds this """ # Open video access for RGB information rgbVideoPath=self.samplePath + os.path.sep + self.seqID + '_color.mp4' if not os.path.exists(rgbVideoPath): raise Exception("Invalid sample file. RGB data is not available") self.rgb = cv2.VideoCapture(rgbVideoPath) while (self.rgb.isOpened()): ret, frame = self.rgb.read() cv2.imshow('frame',frame) if cv2.waitKey(5) & 0xFF == ord('q'): break self.rgb.release() cv2.destroyAllWindows() def evaluate(self,csvpathpred): """ Evaluate this sample agains the ground truth file """ maxGestures=11 seqLength=self.getNumFrames() # Get the list of gestures from the ground truth and frame activation predGestures = [] binvec_pred = numpy.zeros((maxGestures, seqLength)) gtGestures = [] binvec_gt = numpy.zeros((maxGestures, seqLength)) with open(csvpathpred, 'rb') as csvfilegt: csvgt = csv.reader(csvfilegt) for row in csvgt: binvec_pred[int(row[0])-1, int(row[1])-1:int(row[2])-1] = 1 predGestures.append(int(row[0])) # Get the list of gestures from prediction and frame activation for row in self.getActions(): binvec_gt[int(row[0])-1, int(row[1])-1:int(row[2])-1] = 1 gtGestures.append(int(row[0])) # Get the list of gestures without repetitions for ground truth and predicton gtGestures = numpy.unique(gtGestures) predGestures = numpy.unique(predGestures) # Find false positives falsePos=numpy.setdiff1d(gtGestures, numpy.union1d(gtGestures,predGestures)) # Get overlaps for each gesture overlaps = [] for idx in gtGestures: intersec = sum(binvec_gt[idx-1] * binvec_pred[idx-1]) aux = binvec_gt[idx-1] + binvec_pred[idx-1] union = sum(aux > 0) overlaps.append(intersec/union) # Use real gestures and false positive gestures to calculate the final score return sum(overlaps)/(len(overlaps)+len(falsePos)) def get_shift_scale(self, template, ref_depth, start_frame=10, end_frame=20, debug_show=False): """ Wudi add this method for extracting normalizing depth wrt Sample0003 """ from skimage.feature import match_template Feature_all = numpy.zeros(shape=(480, 640, end_frame-start_frame), dtype=numpy.uint16 ) count = 0 for frame_num in range(start_frame,end_frame): depth_original = self.getDepth(frame_num) mask = numpy.mean(self.getUser(frame_num), axis=2) > 150 Feature_all[:, :, count] = depth_original * mask count += 1 depth_image = Feature_all.mean(axis = 2) depth_image_normalized = depth_image * 1.0 / float(self.data['maxDepth']) depth_image_normalized /= depth_image_normalized.max() result = match_template(depth_image_normalized, template, pad_input=True) #############plot x, y = numpy.unravel_index(numpy.argmax(result), result.shape) shift = [depth_image.shape[0]/2-x, depth_image.shape[1]/2-y] subsize = 25 # we use 25 by 25 region as a measurement for median of distance minX = max(x - subsize,0) minY = max(y - subsize,0) maxX = min(x + subsize,depth_image.shape[0]) maxY = min(y + subsize,depth_image.shape[1]) subregion = depth_image[minX:maxX, minY:maxY] distance = numpy.median(subregion[subregion>0]) scaling = distance*1.0 / ref_depth from matplotlib import pyplot as plt print "[x, y, shift, distance, scaling]" print str([x, y, shift, distance, scaling]) if debug_show: fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4, figsize=(8, 4)) ax1.imshow(template) ax1.set_axis_off() ax1.set_title('template') ax2.imshow(depth_image_normalized) ax2.set_axis_off() ax2.set_title('image') # highlight matched region hcoin, wcoin = template.shape rect = plt.Rectangle((y-hcoin/2, x-wcoin/2), wcoin, hcoin, edgecolor='r', facecolor='none') ax2.add_patch(rect) import cv2 from scipy.misc import imresize rows,cols = depth_image_normalized.shape M = numpy.float32([[1,0, shift[1]],[0,1, shift[0]]]) affine_image = cv2.warpAffine(depth_image_normalized, M, (cols, rows)) resize_image = imresize(affine_image, scaling) resize_image_median = cv2.medianBlur(resize_image,5) ax3.imshow(resize_image_median) ax3.set_axis_off() ax3.set_title('image_transformed') # highlight matched region hcoin, wcoin = resize_image_median.shape rect = plt.Rectangle((wcoin/2-160, hcoin/2-160), 320, 320, edgecolor='r', facecolor='none') ax3.add_patch(rect) ax4.imshow(result) ax4.set_axis_off() ax4.set_title('`match_template`\nresult') # highlight matched region ax4.autoscale(False) ax4.plot(x, y, 'o', markeredgecolor='r', markerfacecolor='none', markersize=10) plt.show() return [shift, scaling] def get_shift_scale_depth(self, shift, scale, framenumber, IM_SZ, show_flag=False): """ Wudi added this method to extract segmented depth frame, by a shift and scale """ depth_original = self.getDepth(framenumber) mask = numpy.mean(self.getUser(framenumber), axis=2) > 150 resize_final_out = numpy.zeros((IM_SZ,IM_SZ)) if mask.sum() < 1000: # Kinect detect nothing print "skip "+ str(framenumber) flag = False else: flag = True depth_user = depth_original * mask depth_user_normalized = depth_user * 1.0 / float(self.data['maxDepth']) depth_user_normalized = depth_user_normalized *255 /depth_user_normalized.max() rows,cols = depth_user_normalized.shape M = numpy.float32([[1,0, shift[1]],[0,1, shift[0]]]) affine_image = cv2.warpAffine(depth_user_normalized, M,(cols, rows)) resize_image = imresize(affine_image, scale) resize_image_median = cv2.medianBlur(resize_image,5) rows, cols = resize_image_median.shape image_crop = resize_image_median[rows/2-160:rows/2+160, cols/2-160:cols/2+160] resize_final_out = imresize(image_crop, (IM_SZ,IM_SZ)) if show_flag: # show the segmented images here cv2.imshow('image',image_crop) cv2.waitKey(10) return [resize_final_out, flag] #¶¯×÷Êý¾ÝÀà class ActionSample(object): """ Class that allows to access all the information for a certain action database sample """ #define class to access actions data samples def __init__ (self,fileName): """ Constructor. Read the sample file and unzip it if it is necessary. All the data is loaded. sample=ActionSample('Sec01.zip') """ # Check the given file if not os.path.exists(fileName) and not os.path.isfile(fileName): raise Exception("Sample path does not exist: " + fileName) # Prepare sample information self.fullFile = fileName self.dataPath = os.path.split(fileName)[0] self.file=os.path.split(fileName)[1] self.seqID=os.path.splitext(self.file)[0] self.samplePath=self.dataPath + os.path.sep + self.seqID; # Unzip sample if it is necessary if os.path.isdir(self.samplePath) : self.unzip = False else: self.unzip = True zipFile=zipfile.ZipFile(self.fullFile,"r") zipFile.extractall(self.samplePath) # Open video access for RGB information rgbVideoPath=self.samplePath + os.path.sep + self.seqID + '_color.mp4' if not os.path.exists(rgbVideoPath): raise Exception("Invalid sample file. RGB data is not available") self.rgb = cv2.VideoCapture(rgbVideoPath) while not self.rgb.isOpened(): self.rgb = cv2.VideoCapture(rgbVideoPath) cv2.waitKey(500) # Read sample data sampleDataPath=self.samplePath + os.path.sep + self.seqID + '_data.csv' if not os.path.exists(sampleDataPath): raise Exception("Invalid sample file. Sample data is not available") self.data=dict() with open(sampleDataPath, 'rb') as csvfile: filereader = csv.reader(csvfile, delimiter=',') for row in filereader: self.data['numFrames']=int(row[0]) del filereader # Read labels data labelsPath=self.samplePath + os.path.sep + self.seqID + '_labels.csv' self.labels=[] if not os.path.exists(labelsPath): warnings.warn("Labels are not available", Warning) else: with open(labelsPath, 'rb') as csvfile: filereader = csv.reader(csvfile, delimiter=',') for row in filereader: self.labels.append(map(int,row)) del filereader def __del__(self): """ Destructor. If the object unziped the sample, it remove the temporal data """ if self.unzip: self.clean() def clean(self): """ Clean temporal unziped data """ del self.rgb; shutil.rmtree(self.samplePath) def getFrame(self,video, frameNum): """ Get a single frame from given video object """ # Check frame number # Get total number of frames numFrames = video.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT) # Check the given file if frameNum<1 or frameNum>numFrames: raise Exception("Invalid frame number <" + str(frameNum) + ">. Valid frames are values between 1 and " + str(int(numFrames))) # Set the frame index video.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,frameNum-1) ret,frame=video.read() if ret==False: raise Exception("Cannot read the frame") return frame def getNumFrames(self): """ Get the number of frames for this sample """ return self.data['numFrames'] def getRGB(self, frameNum): """ Get the RGB color image for the given frame """ #get RGB frame return self.getFrame(self.rgb,frameNum) def getActions(self): """ Get the list of gesture for this sample. Each row is an action, with the format (actionID,startFrame,endFrame) """ return self.labels def getActionsName(self,actionID): """ Get the action label from a given action ID """ names=('wave','point','clap','crouch','jump','walk','run','shake hands', \ 'hug','kiss','fight') # Check the given file if actionID<1 or actionID>11: raise Exception("Invalid action ID <" + str(actionID) + ">. Valid IDs are values between 1 and 11") return names[actionID-1] def exportPredictions(self, prediction,predPath): """ Export the given prediction to the correct file in the given predictions path """ if not os.path.exists(predPath): os.makedirs(predPath) output_filename = os.path.join(predPath, self.seqID + '_prediction.csv') output_file = open(output_filename, 'wb') for row in prediction: output_file.write(repr(int(row[0])) + "," + repr(int(row[1])) + "," + repr(int(row[2])) + "\n") output_file.close() def evaluate(self,csvpathpred): """ Evaluate this sample agains the ground truth file """ maxGestures=11 seqLength=self.getNumFrames() # Get the list of gestures from the ground truth and frame activation predGestures = [] binvec_pred = numpy.zeros((maxGestures, seqLength)) gtGestures = [] binvec_gt = numpy.zeros((maxGestures, seqLength)) with open(csvpathpred, 'rb') as csvfilegt: csvgt = csv.reader(csvfilegt) for row in csvgt: binvec_pred[int(row[0])-1, int(row[1])-1:int(row[2])-1] = 1 predGestures.append(int(row[0])) # Get the list of gestures from prediction and frame activation for row in self.getActions(): binvec_gt[int(row[0])-1, int(row[1])-1:int(row[2])-1] = 1 gtGestures.append(int(row[0])) # Get the list of gestures without repetitions for ground truth and predicton gtGestures = numpy.unique(gtGestures) predGestures = numpy.unique(predGestures) # Find false positives falsePos=numpy.setdiff1d(gtGestures, numpy.union1d(gtGestures,predGestures)) # Get overlaps for each gesture overlaps = [] for idx in gtGestures: intersec = sum(binvec_gt[idx-1] * binvec_pred[idx-1]) aux = binvec_gt[idx-1] + binvec_pred[idx-1] union = sum(aux > 0) overlaps.append(intersec/union) # Use real gestures and false positive gestures to calculate the final score return sum(overlaps)/(len(overlaps)+len(falsePos)) #×Ë̬Êý¾ÝÀà class PoseSample(object): """ Class that allows to access all the information for a certain pose database sample """ #define class to access gesture data samples def __init__ (self,fileName): """ Constructor. Read the sample file and unzip it if it is necessary. All the data is loaded. sample=PoseSample('Seq01.zip') """ # Check the given file if not os.path.exists(fileName) and not os.path.isfile(fileName): raise Exception("Sequence path does not exist: " + fileName) # Prepare sample information self.fullFile = fileName self.dataPath = os.path.split(fileName)[0] self.file=os.path.split(fileName)[1] self.seqID=os.path.splitext(self.file)[0] self.samplePath=self.dataPath + os.path.sep + self.seqID; # Unzip sample if it is necessary if os.path.isdir(self.samplePath): self.unzip = False else: self.unzip = True zipFile=zipfile.ZipFile(self.fullFile,"r") zipFile.extractall(self.samplePath) # Set path for rgb images rgbPath=self.samplePath + os.path.sep + 'imagesjpg'+ os.path.sep if not os.path.exists(rgbPath): raise Exception("Invalid sample file. RGB data is not available") self.rgbpath = rgbPath # Set path for gt images gtPath=self.samplePath + os.path.sep + 'maskspng'+ os.path.sep if not os.path.exists(gtPath): self.gtpath= "empty" else: self.gtpath = gtPath frames=os.listdir(self.rgbpath) self.numberFrames=len(frames) def __del__(self): """ Destructor. If the object unziped the sample, it remove the temporal data """ if self.unzip: self.clean() def clean(self): """ Clean temporal unziped data """ shutil.rmtree(self.samplePath) def getRGB(self, frameNum): """ Get the RGB color image for the given frame """ #get RGB frame if frameNum>self.numberFrames: raise Exception("Number of frame has to be less than: "+ self.numberFrames) framepath=self.rgbpath+self.seqID[3:5]+'_'+ '%04d' %frameNum+'.jpg' if not os.path.isfile(framepath): raise Exception("RGB file does not exist: " + framepath) return cv2.imread(framepath) def getNumFrames(self): return self.numberFrames def getLimb(self, frameNum, actorID,limbID): """ Get the BW limb image for a certain frame and a certain limbID """ if self.gtpath == "empty": raise Exception("Limb labels are not available for this sequence. This sequence belong to the validation set.") else: limbpath=self.gtpath+self.seqID[3:5]+'_'+ '%04d' %frameNum+'_'+str(actorID)+'_'+str(limbID)+'.png' if frameNum>self.numberFrames: raise Exception("Number of frame has to be less than: "+ self.numberFrames) if actorID<1 or actorID>2: raise Exception("Invalid actor ID <" + str(actorID) + ">. Valid frames are values between 1 and 2 ") if limbID<1 or limbID>14: raise Exception("Invalid limb ID <" + str(limbID) + ">. Valid frames are values between 1 and 14") return cv2.imread(limbpath,cv2.CV_LOAD_IMAGE_GRAYSCALE) def getLimbsName(self,limbID): """ Get the limb label from a given limb ID """ names=('head','torso','lhand','rhand','lforearm','rforearm','larm','rarm', \ 'lfoot','rfoot','lleg','rleg','lthigh','rthigh') # Check the given file if limbID<1 or limbID>14: raise Exception("Invalid limb ID <" + str(limbID) + ">. Valid IDs are values between 1 and 14") return names[limbID-1] def overlap_images(self, gtimage, predimage): """ this function computes the hit measure of overlap between two binary images im1 and im2 """ [ret, im1] = cv2.threshold(gtimage, 127, 255, cv2.THRESH_BINARY) [ret, im2] = cv2.threshold(predimage, 127, 255, cv2.THRESH_BINARY) intersec = cv2.bitwise_and(im1, im2) intersec_val = float(numpy.sum(intersec)) union = cv2.bitwise_or(im1, im2) union_val = float(numpy.sum(union)) if union_val == 0: return 0 else: if float(intersec_val / union_val)>0.5: return 1 else: return 0 def exportPredictions(self, prediction,frame,actor,limb,predPath): """ Export the given prediction to the correct file in the given predictions path """ if not os.path.exists(predPath): os.makedirs(predPath) prediction_filename = predPath+os.path.sep+ self.seqID[3:5] +'_'+ '%04d' %frame +'_'+str(actor)+'_'+str(limb)+'_prediction.png' cv2.imwrite(prediction_filename,prediction) def evaluate(self, predpath): """ Evaluate this sample agains the ground truth file """ # Get the list of videos from ground truth gt_list = os.listdir(self.gtpath) # For each sample on the GT, search the given prediction score = 0.0 nevals = 0 for gtlimbimage in gt_list: # Avoid double check, use only labels file if not gtlimbimage.lower().endswith(".png"): continue # Build paths for prediction and ground truth files aux = gtlimbimage.split('.') parts = aux[0].split('_') seqID = parts[0] gtlimbimagepath = os.path.join(self.gtpath,gtlimbimage) predlimbimagepath= os.path.join(predpath) + os.path.sep + seqID+'_'+parts[1]+'_'+parts[2]+'_'+parts[3]+"_prediction.png" #check predfile exists if not os.path.exists(predlimbimagepath) or not os.path.isfile(predlimbimagepath): raise Exception("Invalid video limb prediction file. Not all limb predictions are available") #Load images gtimage=cv2.imread(gtlimbimagepath, cv2.CV_LOAD_IMAGE_GRAYSCALE) predimage=cv2.imread(predlimbimagepath, cv2.CV_LOAD_IMAGE_GRAYSCALE) if cv2.cv.CountNonZero(cv2.cv.fromarray(gtimage)) >= 1: score += self.overlap_images(gtimage, predimage) nevals += 1 #release videos and return mean overlap return score/nevals
mit
heli522/scikit-learn
examples/cluster/plot_lena_ward_segmentation.py
271
1998
""" =============================================================== A demo of structured Ward hierarchical clustering on Lena image =============================================================== Compute the segmentation of a 2D image with Ward hierarchical clustering. The clustering is spatially constrained in order for each segmented region to be in one piece. """ # Author : Vincent Michel, 2010 # Alexandre Gramfort, 2011 # License: BSD 3 clause print(__doc__) import time as time import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn.feature_extraction.image import grid_to_graph from sklearn.cluster import AgglomerativeClustering ############################################################################### # Generate data lena = sp.misc.lena() # Downsample the image by a factor of 4 lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2] X = np.reshape(lena, (-1, 1)) ############################################################################### # Define the structure A of the data. Pixels connected to their neighbors. connectivity = grid_to_graph(*lena.shape) ############################################################################### # Compute clustering print("Compute structured hierarchical clustering...") st = time.time() n_clusters = 15 # number of regions ward = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward', connectivity=connectivity).fit(X) label = np.reshape(ward.labels_, lena.shape) print("Elapsed time: ", time.time() - st) print("Number of pixels: ", label.size) print("Number of clusters: ", np.unique(label).size) ############################################################################### # Plot the results on an image plt.figure(figsize=(5, 5)) plt.imshow(lena, cmap=plt.cm.gray) for l in range(n_clusters): plt.contour(label == l, contours=1, colors=[plt.cm.spectral(l / float(n_clusters)), ]) plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
burjorjee/evolve-parities
evolveparities.py
1
5098
from contextlib import closing from matplotlib.pyplot import plot, figure, hold, axis, ylabel, xlabel, savefig, title from numpy import sort, logical_xor, transpose, logical_not from numpy.numarray.functions import cumsum, zeros from numpy.random import rand, shuffle from numpy import mod, floor import time import cloud from durus.file_storage import FileStorage from durus.connection import Connection def bitFreqVisualizer(effectiveAttrIndices, bitFreqs, gen): f = figure(1) n = len(bitFreqs) hold(False) plot(range(n), bitFreqs,'b.', markersize=10) hold(True) plot(effectiveAttrIndices, bitFreqs[effectiveAttrIndices],'r.', markersize=10) axis([0, n-1, 0, 1]) title("Generation = %s" % (gen,)) ylabel('Frequency of the Bit 1') xlabel('Locus') f.canvas.draw() f.show() def showExperimentTimeStamps(): with closing(FileStorage("results.durus")) as durus: conn = Connection(durus) return conn.get_root().keys() def neap_uga(m, n, gens, probMutation, effectiveAttrIndices, probMisclassification, bitFreqVisualizer=None): """ neap = "noisy effective attribute parity" """ pop = rand(m,n)<0.5 bitFreqHist= zeros((n,gens+1)) for t in range(gens+1): print "Generation %s" % t bitFreqs = pop.astype('float').sum(axis=0)/m bitFreqHist[:,t] = transpose(bitFreqs) if bitFreqVisualizer: bitFreqVisualizer(bitFreqs,t) fitnessVals = mod(pop[:, effectiveAttrIndices].astype('byte').sum(axis=1) + (rand(m) < probMisclassification).astype('byte'),2) totalFitness = sum (fitnessVals) cumNormFitnessVals = cumsum(fitnessVals).astype('float')/totalFitness parentIndices = zeros(2*m, dtype='int16') markers = sort(rand(2*m)) ctr = 0 for idx in xrange(2*m): while markers[idx]>cumNormFitnessVals[ctr]: ctr += 1 parentIndices[idx] = ctr shuffle(parentIndices) crossoverMasks = rand(m, n) < 0.5 newPop = zeros((m, n), dtype='bool') newPop[crossoverMasks] = pop[parentIndices[:m], :][crossoverMasks] newPop[logical_not(crossoverMasks)] = pop[parentIndices[m:], :][logical_not(crossoverMasks)] mutationMasks = rand(m, n)<probMutation pop = logical_xor(newPop,mutationMasks) return bitFreqHist[0, :], bitFreqHist[-1, :] def f(gens): k = 7 n= k + 1 effectiveAttrIndices = range(k) probMutation = 0.004 probMisclassification = 0.20 popSize = 1500 jid = cloud.call(neap_uga, **dict(m=popSize, n=n, gens=gens, probMutation=probMutation, effectiveAttrIndices=effectiveAttrIndices, probMisclassification=probMisclassification)) print "Kicked off trial %s" % jid return jid def cloud_result(jid): result = cloud.result(jid) print "Retrieved results for trial %s" % jid return result def run_trials(): numTrials = 3000 gens = 1000 from multiprocessing.pool import ThreadPool as Pool pool = Pool(50) jids = pool.map(f,[gens]*numTrials) print "Done spawning trials. Retrieving results..." results = pool.map(cloud_result, jids) firstLocusFreqsHists = zeros((numTrials,gens+1), dtype='float') lastLocusFreqsHists = zeros((numTrials,gens+1), dtype='float') print "Done retrieving results. Press Enter to serialize..." raw_input() for i, result in enumerate(results): firstLocusFreqsHists[i, :], lastLocusFreqsHists[i, :] = result with closing(FileStorage("results.durus")) as durus: conn = Connection(durus) conn.get_root()[str(int(floor(time.time())))] = (firstLocusFreqsHists, lastLocusFreqsHists) conn.commit() pool.close() pool.join() def render_results(timestamp=None): with closing(FileStorage("results.durus")) as durus: conn = Connection(durus) db = conn.get_root() if not timestamp: timestamp = sorted(db.keys())[-1] firstLocusFreqsHists, lastLocusFreqsHists = db[timestamp] print "Done deserializing results. Plotting..." x = [(2, 'First', firstLocusFreqsHists, "effective"), (3, 'Last', lastLocusFreqsHists, "non-effective")] for i, pos, freqsHists, filename in x : freqsHists = freqsHists[:,:801] f = figure(i) hold(False) plot(transpose(freqsHists), color='grey') hold(True) maxGens = freqsHists.shape[1]-1 plot([0, maxGens], [.05,.05], 'k--') plot([0, maxGens], [.95,.95], 'k--') axis([0, maxGens, 0, 1]) xlabel('Generation') ylabel('1-Frequency of the '+pos+' Locus') f.canvas.draw() f.show() savefig(filename+'.png', format='png', dpi=200) if __name__ == "__main__": cloud.start_simulator() run_trials() render_results() print "Done plotting results. Press Enter to end..." raw_input()
gpl-3.0
matthiasrichter/AliceO2
Analysis/Scripts/update_ccdb.py
3
6042
#!/usr/bin/env python3 # Copyright 2019-2020 CERN and copyright holders of ALICE O2. # See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. # All rights not expressly granted are reserved. # # This software is distributed under the terms of the GNU General Public # License v3 (GPL Version 3), copied verbatim in the file "COPYING". # # In applying this license CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or submit itself to any jurisdiction. """ Script to update the CCDB with timestamp non-overlapping objects. If an object is found in the range specified, the object is split into two. If the requested range was overlapping three objects are uploaded on CCDB: 1) latest object with requested timestamp validity 2) old object with validity [old_lower_validity-requested_lower_bound] 3) old object with validity [requested_upper_bound, old_upper_validity] Author: Nicolo' Jacazio on 2020-06-22 TODO add support for 3 files update """ import subprocess from datetime import datetime import matplotlib.pyplot as plt import argparse def convert_timestamp(ts): """ Converts the timestamp in milliseconds in human readable format """ return datetime.utcfromtimestamp(ts/1000).strftime('%Y-%m-%d %H:%M:%S') def get_ccdb_obj(path, timestamp, dest="/tmp/", verbose=0): """ Gets the ccdb object from 'path' and 'timestamp' and downloads it into 'dest' """ if verbose: print("Getting obj", path, "with timestamp", timestamp, convert_timestamp(timestamp)) cmd = f"o2-ccdb-downloadccdbfile --path {path} --dest {dest} --timestamp {timestamp}" subprocess.run(cmd.split()) def get_ccdb_obj_validity(path, dest="/tmp/", verbose=0): """ Gets the timestamp validity for an object downloaded from CCDB. Returns a list with the initial and end timestamps. """ cmd = f"o2-ccdb-inspectccdbfile {dest}{path}/snapshot.root" process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) output, error = process.communicate() output = output.decode("utf-8").split("\n") error = error.decode("utf-8").split("\n") if error is not None else error if verbose: print("out:") print(*output, "\n") print("err:") print(error) result = list(filter(lambda x: x.startswith('Valid-'), output)) ValidFrom = result[0].split() ValidUntil = result[1].split() return [int(ValidFrom[-1]), int(ValidUntil[-1])] def upload_ccdb_obj(path, timestamp_from, timestamp_until, dest="/tmp/", meta=""): """ Uploads a new object to CCDB in the 'path' using the validity timestamp specified """ print("Uploading obj", path, "with timestamp", [timestamp_from, timestamp_until], convert_timestamp(timestamp_from), convert_timestamp(timestamp_until)) key = path.split("/")[-1] cmd = f"o2-ccdb-upload -f {dest}{path}/snapshot.root " cmd += f"--key {key} --path {path} " cmd += f"--starttimestamp {timestamp_from} --endtimestamp {timestamp_until} --meta \"{meta}\"" subprocess.run(cmd.split()) def main(path, timestamp_from, timestamp_until, verbose=0, show=False): """ Used to upload a new object to CCDB in 'path' valid from 'timestamp_from' to 'timestamp_until' Gets the object from CCDB specified in 'path' and for 'timestamp_from-1' Gets the object from CCDB specified in 'path' and for 'timestamp_until+1' If required plots the situation before and after the update """ get_ccdb_obj(path, timestamp_from-1) val_before = get_ccdb_obj_validity(path, verbose=verbose) get_ccdb_obj(path, timestamp_until+1) val_after = get_ccdb_obj_validity(path, verbose=verbose) overlap_before = val_before[1] > timestamp_from overlap_after = val_after[0] < timestamp_until if verbose: if overlap_before: print("Previous objects overalps") if overlap_after: print("Next objects overalps") trimmed_before = val_before if not overlap_before else [ val_before[0], timestamp_from - 1] trimmed_after = val_after if not overlap_after else [ timestamp_until+1, val_after[1]] if show: fig, ax = plt.subplots() fig def bef_af(v, y): return [v[0] - 1] + v + [v[1] + 1], [0, y, y, 0] if True: ax.plot(*bef_af(val_before, 0.95), label='before') ax.plot(*bef_af(val_after, 1.05), label='after') if False: ax.plot(*bef_af(trimmed_before, 0.9), label='trimmed before') ax.plot(*bef_af(trimmed_after, 1.1), label='trimmed after') ax.plot(*bef_af([timestamp_from, timestamp_until], 1), label='object') xlim = 10000000 plt.xlim([timestamp_from-xlim, timestamp_until+xlim]) plt.ylim(0, 2) plt.xlabel('Timestamp') plt.ylabel('Validity') plt.legend() plt.show() if __name__ == "__main__": parser = argparse.ArgumentParser( description="Uploads timestamp non overlapping objects to CCDB." "Basic example: `./update_ccdb.py qc/TOF/TOFTaskCompressed/hDiagnostic 1588956517161 1588986517161 --show --verbose`") parser.add_argument('path', metavar='path_to_object', type=str, help='Path of the object in the CCDB repository') parser.add_argument('timestamp_from', metavar='from_timestamp', type=int, help='Timestamp of start for the new object to use') parser.add_argument('timestamp_until', metavar='until_timestamp', type=int, help='Timestamp of stop for the new object to use') parser.add_argument('--verbose', '-v', action='count', default=0) parser.add_argument('--show', '-s', action='count', default=0) args = parser.parse_args() main(path=args.path, timestamp_from=args.timestamp_from, timestamp_until=args.timestamp_until, verbose=args.verbose, show=args.show)
gpl-3.0
annahs/atmos_research
WHI_long_term_2min_data_to_db.py
1
8596
import sys import os import numpy as np from pprint import pprint from datetime import datetime from datetime import timedelta import mysql.connector import math import calendar import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib import dates start = datetime(2009,7,15,4) #2009 - 20090628 2010 - 20100610 2012 - 20100405 end = datetime(2009,8,17) #2009 - 20090816 2010 - 20100726 2012 - 20100601 timestep = 6.#1./30 #hours sample_min = 117 #117 for all 2009-2012 sample_max = 123 #123 for all 2009-2012 yag_min = 3.8 #3.8 for all 2009-2012 yag_max = 6 #6 for all 2009-2012 BC_VED_min = 70 BC_VED_max = 220 min_scat_pkht = 20 mass_min = ((BC_VED_min/(10.**7))**3)*(math.pi/6.)*1.8*(10.**15) mass_max = ((BC_VED_max/(10.**7))**3)*(math.pi/6.)*1.8*(10.**15) lag_threshold_2009 = 0.1 lag_threshold_2010 = 0.25 lag_threshold_2012 = 1.5 print 'mass limits', mass_min, mass_max cnx = mysql.connector.connect(user='root', password='Suresh15', host='localhost', database='black_carbon') cursor = cnx.cursor() def check_spike_times(particle_start_time,particle_end_time): cursor.execute('''SELECT count(*) FROM whi_spike_times_2009to2012 WHERE (spike_start_UTC <= %s AND spike_end_UTC > %s) OR (spike_start_UTC <= %s AND spike_end_UTC > %s) ''', (particle_start_time,particle_start_time,particle_end_time,particle_end_time)) spike_count = cursor.fetchall()[0][0] return spike_count def get_hysplit_id(particle_start_time): cursor.execute('''SELECT id FROM whi_hysplit_hourly_data WHERE (UNIX_UTC_start_time <= %s AND UNIX_UTC_end_time > %s) ''', (particle_start_time,particle_start_time)) hy_id_list = cursor.fetchall() if hy_id_list == []: hy_id = None else: hy_id = hy_id_list[0][0] return hy_id def get_met_info(particle_start_time): cursor.execute('''SELECT id,pressure_Pa,room_temp_C FROM whi_sampling_conditions WHERE (UNIX_UTC_start_time <= %s AND UNIX_UTC_end_time > %s) ''', (particle_start_time,particle_start_time)) met_list = cursor.fetchall() if met_list == []: met_list = [[np.nan,np.nan,np.nan]] return met_list[0] def get_gc_id(particle_start_time): cursor.execute('''SELECT id FROM whi_gc_hourly_bc_data WHERE (UNIX_UTC_start_time <= %s AND UNIX_UTC_end_time > %s) ''', (particle_start_time,particle_start_time)) gc_id_list = cursor.fetchall() if gc_id_list == []: gc_id = None else: gc_id = gc_id_list[0][0] return gc_id def get_sample_factor(UNIX_start): date_time = datetime.utcfromtimestamp(UNIX_start) sample_factors_2012 = [ [datetime(2012,4,4,19,43,4), datetime(2012,4,5,13,47,9), 3.0], [datetime(2012,4,5,13,47,9), datetime(2012,4,10,3,3,25), 1.0], [datetime(2012,4,10,3,3,25), datetime(2012,5,16,6,9,13), 3.0], [datetime(2012,5,16,6,9,13), datetime(2012,6,7,18,14,39), 10.0], ] if date_time.year in [2009,2010]: sample_factor = 1.0 if date_time.year == 2012: for date_range in sample_factors_2012: start_date = date_range[0] end_date = date_range[1] range_sample_factor = date_range[2] if start_date<= date_time < end_date: sample_factor = range_sample_factor return sample_factor def lag_time_calc(BB_incand_pk_pos,BB_scat_pk_pos): long_lags = 0 short_lags = 0 lag_time = np.nan if (-10 < lag_time < 10): lag_time = (BB_incand_pk_pos-BB_scat_pk_pos)*0.2 #us if start_dt.year == 2009 and lag_time > lag_threshold_2009: long_lags = 1 elif start_dt.year == 2010 and lag_time > lag_threshold_2010: long_lags = 1 elif start_dt.year == 2012 and lag_time > lag_threshold_2012: long_lags = 1 else: short_lags = 1 return [lag_time,long_lags,short_lags] #query to add 1h mass conc data add_data = ('''INSERT INTO whi_sp2_2min_data (UNIX_UTC_start_time,UNIX_UTC_end_time,number_particles,rBC_mass_conc,rBC_mass_conc_err,volume_air_sampled,sampling_duration,mean_lag_time,sample_factor,hysplit_hourly_id,whi_sampling_cond_id,gc_hourly_id) VALUES (%(UNIX_UTC_start_time)s,%(UNIX_UTC_end_time)s,%(number_particles)s,%(rBC_mass_conc)s,%(rBC_mass_conc_err)s,%(volume_air_sampled)s,%(sampling_duration)s,%(mean_lag_time)s,%(sample_factor)s,%(hysplit_hourly_id)s,%(whi_sampling_cond_id)s,%(gc_hourly_id)s)''' ) # multiple_records = [] i=1 while start <= end: long_lags = 0 short_lags = 0 if (4 <= start.hour < 16): UNIX_start = calendar.timegm(start.utctimetuple()) UNIX_end = UNIX_start + timestep*3600.0 print start, UNIX_start+60 print datetime.utcfromtimestamp(UNIX_end) #filter on hk data here cursor.execute('''(SELECT mn.UNIX_UTC_ts_int_start, mn.UNIX_UTC_ts_int_end, mn.rBC_mass_fg_BBHG, mn.rBC_mass_fg_BBHG_err, mn.BB_incand_pk_pos, mn.BB_scat_pk_pos, mn.BB_scat_pkht, hk.sample_flow, mn.BB_incand_HG FROM whi_sp2_particle_data mn FORCE INDEX (hourly_binning) JOIN whi_hk_data hk on mn.HK_id = hk.id WHERE mn.UNIX_UTC_ts_int_start >= %s AND mn.UNIX_UTC_ts_int_end < %s AND hk.sample_flow >= %s AND hk.sample_flow < %s AND hk.yag_power >= %s AND hk.yag_power < %s)''', (UNIX_start,UNIX_end,sample_min,sample_max,yag_min,yag_max)) ind_data = cursor.fetchall() data={ 'rBC_mass_fg':[], 'rBC_mass_fg_err':[], 'lag_time':[] } total_sample_vol = 0 for row in ind_data: ind_start_time = float(row[0]) ind_end_time = float(row[1]) bbhg_mass_corr11 = float(row[2]) bbhg_mass_corr_err = float(row[3]) BB_incand_pk_pos = float(row[4]) BB_scat_pk_pos = float(row[5]) BB_scat_pk_ht = float(row[6]) sample_flow = float(row[7]) #in vccm incand_pkht = float(row[8]) #filter spike times here if check_spike_times(ind_start_time,ind_end_time): print 'spike' continue #skip the long interval if (ind_end_time - ind_start_time) > 540: print 'long interval' continue #skip if no sample flow if sample_flow == None: print 'no flow' continue #get sampling conditions id and met conditions met_data = get_met_info(UNIX_start) met_id = met_data[0] pressure = met_data[1] temperature = met_data[2]+273.15 correction_factor_for_STP = (273*pressure)/(101325*temperature) sample_vol = (sample_flow*(ind_end_time-ind_start_time)/60)*correction_factor_for_STP #/60 b/c sccm and time in secs total_sample_vol = total_sample_vol + sample_vol bbhg_mass_corr = 0.01244+0.0172*incand_pkht if (mass_min <= bbhg_mass_corr < mass_max): #get sample factor sample_factor = get_sample_factor(UNIX_start) data['rBC_mass_fg'].append(bbhg_mass_corr*sample_factor) data['rBC_mass_fg_err'].append(bbhg_mass_corr_err) #only calc lag time if there is a scattering signal if BB_scat_pk_ht > min_scat_pkht: lags = lag_time_calc(BB_incand_pk_pos,BB_scat_pk_pos) data['lag_time'].append(lags[0]) long_lags += lags[1] short_lags += lags[2] tot_rBC_mass_fg = sum(data['rBC_mass_fg']) tot_rBC_mass_uncer = sum(data['rBC_mass_fg_err']) rBC_number = len(data['rBC_mass_fg']) mean_lag = float(np.mean(data['lag_time'])) if np.isnan(mean_lag): mean_lag = None #get hysplit_id hysplit_id = None #get_hysplit_id(UNIX_start) #get GC id gc_id = None #get_gc_id(UNIX_start) if total_sample_vol != 0: mass_conc = (tot_rBC_mass_fg/total_sample_vol) mass_conc_uncer = (tot_rBC_mass_uncer/total_sample_vol) #add to db single_record = { 'UNIX_UTC_start_time' :UNIX_start, 'UNIX_UTC_end_time' :UNIX_end, 'number_particles' :rBC_number, 'rBC_mass_conc' :mass_conc, 'rBC_mass_conc_err' :mass_conc_uncer, 'volume_air_sampled' :total_sample_vol, 'sampling_duration' :(total_sample_vol/2), 'mean_lag_time' :mean_lag, 'number_long_lag' :long_lags, 'number_short_lag' :short_lags, 'sample_factor' :sample_factor, 'hysplit_hourly_id' :hysplit_id, 'whi_sampling_cond_id' :met_id, 'gc_hourly_id' :gc_id, } multiple_records.append((single_record)) #bulk insert to db table if i%1 == 0: cursor.executemany(add_data, multiple_records) cnx.commit() multiple_records = [] #increment count i+= 1 start += timedelta(hours = timestep) #bulk insert of remaining records to db if multiple_records != []: cursor.executemany(add_data, multiple_records) cnx.commit() multiple_records = [] cnx.close()
mit
inviwo/inviwo
data/scripts/matplotlib_create_transferfunction.py
2
1270
# Inviwo Python script import matplotlib.cm as cm import matplotlib.pyplot as plt import inviwopy from inviwopy.glm import vec2,vec3,vec4 #http://matplotlib.org/examples/color/colormaps_reference.html #Perceptually Uniform Sequential : #['viridis', 'inferno', 'plasma', 'magma'] #Sequential : #['Blues', 'BuGn', 'BuPu','GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu','Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd'] #Diverging : #['afmhot', 'autumn', 'bone', 'cool','copper', 'gist_heat', 'gray', 'hot','pink', 'spring', 'summer', 'winter'] #Qualitative : #['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'seismic'] #Miscellaneous : #['Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3'] #Sequential : #['gist_earth', 'terrain', 'ocean', 'gist_stern','brg', 'CMRmap', 'cubehelix','gnuplot', 'gnuplot2', 'gist_ncar', 'nipy_spectral', 'jet', 'rainbow', 'gist_rainbow', 'hsv', 'flag', 'prism'] tf = inviwopy.app.network.VolumeRaycaster.transferFunction tf.clear() cmapName = "viridis" cmap=plt.get_cmap(cmapName) N = 128 for i in range(0,N,1): x = i / (N-1) a = 1.0 color = cmap(x) tf.add(x, vec4(color[0],color[1],color[2], a))
bsd-2-clause
xyguo/scikit-learn
examples/svm/plot_svm_nonlinear.py
268
1091
""" ============== Non-linear SVM ============== Perform binary classification using non-linear SVC with RBF kernel. The target to predict is a XOR of the inputs. The color map illustrates the decision function learned by the SVC. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm xx, yy = np.meshgrid(np.linspace(-3, 3, 500), np.linspace(-3, 3, 500)) np.random.seed(0) X = np.random.randn(300, 2) Y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0) # fit the model clf = svm.NuSVC() clf.fit(X, Y) # plot the decision function for each datapoint on the grid Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.imshow(Z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto', origin='lower', cmap=plt.cm.PuOr_r) contours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, linetypes='--') plt.scatter(X[:, 0], X[:, 1], s=30, c=Y, cmap=plt.cm.Paired) plt.xticks(()) plt.yticks(()) plt.axis([-3, 3, -3, 3]) plt.show()
bsd-3-clause
acimmarusti/isl_exercises
chap3/chap3ex8.py
1
1315
from __future__ import print_function, division import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from pandas.tools.plotting import scatter_matrix import statsmodels.formula.api as smf #from sklearn.linear_model import LinearRegression #import scipy, scipy.stats #from statsmodels.sandbox.regression.predstd import wls_prediction_std from statsmodels.stats.outliers_influence import variance_inflation_factor, summary_table filename = '../Auto.csv' data = pd.read_csv(filename, na_values='?').dropna() #Quantitative and qualitative predictors# print(data.dtypes) #Simple linear regression# slinreg = smf.ols('mpg ~ horsepower', data=data).fit() print(slinreg.summary()) st, fitdat, ss2 = summary_table(slinreg, alpha=0.05) fittedvalues = fitdat[:,2] predict_mean_se = fitdat[:,3] predict_mean_ci_low, predict_mean_ci_upp = fitdat[:,4:6].T predict_ci_low, predict_ci_upp = fitdat[:,6:8].T x = data['horsepower'] y = data['mpg'] #Residuals# resd1 = y - fittedvalues f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot(x, y, 'o') ax1.plot(x, fittedvalues, 'g-') ax1.plot(x, predict_ci_low, 'r--') ax1.plot(x, predict_ci_upp, 'r--') ax1.plot(x, predict_mean_ci_low, 'b--') ax1.plot(x, predict_mean_ci_upp, 'b--') ax2.plot(resd1, fittedvalues, 'o') plt.show()
gpl-3.0