repo_name
stringlengths
6
67
path
stringlengths
5
185
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
1.02k
962k
license
stringclasses
15 values
donbright/piliko
experiment/bernoulli/pythbernlem2.py
1
1332
from fractions import Fraction as Fract import sys # rational paramterization / approximation of bernoulli's lemniscate # traditional form: ( x^2 + y^2 ) ^2 = 2*( x^2 - y^2 ) # chromogeometry form: # x = (blueq/redq) / blueq( blueq/redq, greenq/redq ) # y = (greenq/redq) / blueq( blueq/redq, greenq/redq ) # where q = quadrance between 0,0 and integer point m,n # please see pythbernlem.py for full explanation def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] depth = 13 for m in range(-depth,depth): for n in range(-depth,depth): if redq(0,0,m,n)==0: continue bq,rq,gq = blueq(0,0,m,n),redq(0,0,m,n),greenq(0,0,m,n) x = Fract( Fract(bq,rq), blueq(0,0,Fract(bq,rq),Fract(gq,rq)) ) y = Fract( Fract(gq,rq), blueq(0,0,Fract(bq,rq),Fract(gq,rq)) ) xs += [x] ys += [y] max=max(xs+ys) for i in range(0,2): print xs[i],',',ys[i], print '....' for i in range(0,len(xs)): xs[i] = Fract( xs[i], max ) ys[i] = Fract( ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
bsd-3-clause
rsignell-usgs/notebook
OOI/from_ooi_json.py
1
2291
# coding: utf-8 # # Convert OOI Parsed JSON to NetCDF file # using CF-1.6, Discrete Sampling Geometry (DSG) conventions, **`featureType=timeSeries`** # In[2]: get_ipython().magic('matplotlib inline') import json import pandas as pd import numpy as np from pyaxiom.netcdf.sensors import TimeSeries # In[6]: infile = '/usgs/data2/notebook/data/20170130.superv.json' infile = '/sand/usgs/users/rsignell/data/ooi/endurance/cg_proc/ce02shsm/D00004/buoy/pwrsys/20170208.pwrsys.json' outfile = '/usgs/data2/notebook/data/20170130.superv.nc' with open(infile) as jf: js = json.load(jf) df = pd.DataFrame({}) for k, v in js.items(): df[k] = v df['time'] = pd.to_datetime(df.time, unit='s') df['depth'] = 0. df.head() # In[7]: df['solar_panel4_voltage'].plot(); # In[8]: df.index = df['time'] df['solar_panel4_voltage'].plot(); # ### Define the NetCDF global attributes # In[10]: global_attributes = { 'institution':'Oregon State University', 'title':'OOI CE02SHSM Pwrsys Data', 'summary':'OOI Pwrsys data from Coastal Endurance Oregon Shelf Surface Mooring', 'creator_name':'Chris Wingard', 'creator_email':'cwingard@coas.oregonstate.edu', 'creator_url':'http://ceoas.oregonstate.edu/ooi' } # ### Create initial file # In[11]: ts = TimeSeries( output_directory='.', latitude=44.64, longitude=-124.31, station_name='ce02shsm', global_attributes=global_attributes, times=df.time.values.astype(np.int64) // 10**9, verticals=df.depth.values, output_filename=outfile, vertical_positive='down' ) # ### Add data variables # In[12]: for c in df.columns: if c in ts._nc.variables: print("Skipping '{}' (already in file)".format(c)) continue if c in ['time', 'lat', 'lon', 'depth', 'cpm_date_time_string']: print("Skipping axis '{}' (already in file)".format(c)) continue ts.add_variable(c, df[c].values) print("Added {}".format(c)) # In[ ]: # ### Open the NetCDF file and inspect it # In[9]: import netCDF4 nc = netCDF4.Dataset(outfile) # In[10]: nc # In[11]: nc.close() # In[12]: import netCDF4 nc = netCDF4.Dataset(outfile) # In[15]: nc['z'] # In[16]: nc['crs'] # In[19]: nc['iridium_current'] # In[ ]:
mit
jkthompson/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/mathtext.py
69
101723
r""" :mod:`~matplotlib.mathtext` is a module for parsing a subset of the TeX math syntax and drawing them to a matplotlib backend. For a tutorial of its usage see :ref:`mathtext-tutorial`. This document is primarily concerned with implementation details. The module uses pyparsing_ to parse the TeX expression. .. _pyparsing: http://pyparsing.wikispaces.com/ The Bakoma distribution of the TeX Computer Modern fonts, and STIX fonts are supported. There is experimental support for using arbitrary fonts, but results may vary without proper tweaking and metrics for those fonts. If you find TeX expressions that don't parse or render properly, please email mdroe@stsci.edu, but please check KNOWN ISSUES below first. """ from __future__ import division import os from cStringIO import StringIO from math import ceil try: set except NameError: from sets import Set as set import unicodedata from warnings import warn from numpy import inf, isinf import numpy as np from matplotlib.pyparsing import Combine, Group, Optional, Forward, \ Literal, OneOrMore, ZeroOrMore, ParseException, Empty, \ ParseResults, Suppress, oneOf, StringEnd, ParseFatalException, \ FollowedBy, Regex, ParserElement # Enable packrat parsing ParserElement.enablePackrat() from matplotlib.afm import AFM from matplotlib.cbook import Bunch, get_realpath_and_stat, \ is_string_like, maxdict from matplotlib.ft2font import FT2Font, FT2Image, KERNING_DEFAULT, LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING from matplotlib.font_manager import findfont, FontProperties from matplotlib._mathtext_data import latex_to_bakoma, \ latex_to_standard, tex2uni, latex_to_cmex, stix_virtual_fonts from matplotlib import get_data_path, rcParams import matplotlib.colors as mcolors import matplotlib._png as _png #################### ############################################################################## # FONTS def get_unicode_index(symbol): """get_unicode_index(symbol) -> integer Return the integer index (from the Unicode table) of symbol. *symbol* can be a single unicode character, a TeX command (i.e. r'\pi'), or a Type1 symbol name (i.e. 'phi'). """ # From UTF #25: U+2212 minus sign is the preferred # representation of the unary and binary minus sign rather than # the ASCII-derived U+002D hyphen-minus, because minus sign is # unambiguous and because it is rendered with a more desirable # length, usually longer than a hyphen. if symbol == '-': return 0x2212 try:# This will succeed if symbol is a single unicode char return ord(symbol) except TypeError: pass try:# Is symbol a TeX symbol (i.e. \alpha) return tex2uni[symbol.strip("\\")] except KeyError: message = """'%(symbol)s' is not a valid Unicode character or TeX/Type1 symbol"""%locals() raise ValueError, message class MathtextBackend(object): """ The base class for the mathtext backend-specific code. The purpose of :class:`MathtextBackend` subclasses is to interface between mathtext and a specific matplotlib graphics backend. Subclasses need to override the following: - :meth:`render_glyph` - :meth:`render_filled_rect` - :meth:`get_results` And optionally, if you need to use a Freetype hinting style: - :meth:`get_hinting_type` """ def __init__(self): self.fonts_object = None def set_canvas_size(self, w, h, d): 'Dimension the drawing canvas' self.width = w self.height = h self.depth = d def render_glyph(self, ox, oy, info): """ Draw a glyph described by *info* to the reference point (*ox*, *oy*). """ raise NotImplementedError() def render_filled_rect(self, x1, y1, x2, y2): """ Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*). """ raise NotImplementedError() def get_results(self, box): """ Return a backend-specific tuple to return to the backend after all processing is done. """ raise NotImplementedError() def get_hinting_type(self): """ Get the Freetype hinting type to use with this particular backend. """ return LOAD_NO_HINTING class MathtextBackendBbox(MathtextBackend): """ A backend whose only purpose is to get a precise bounding box. Only required for the Agg backend. """ def __init__(self, real_backend): MathtextBackend.__init__(self) self.bbox = [0, 0, 0, 0] self.real_backend = real_backend def _update_bbox(self, x1, y1, x2, y2): self.bbox = [min(self.bbox[0], x1), min(self.bbox[1], y1), max(self.bbox[2], x2), max(self.bbox[3], y2)] def render_glyph(self, ox, oy, info): self._update_bbox(ox + info.metrics.xmin, oy - info.metrics.ymax, ox + info.metrics.xmax, oy - info.metrics.ymin) def render_rect_filled(self, x1, y1, x2, y2): self._update_bbox(x1, y1, x2, y2) def get_results(self, box): orig_height = box.height orig_depth = box.depth ship(0, 0, box) bbox = self.bbox bbox = [bbox[0] - 1, bbox[1] - 1, bbox[2] + 1, bbox[3] + 1] self._switch_to_real_backend() self.fonts_object.set_canvas_size( bbox[2] - bbox[0], (bbox[3] - bbox[1]) - orig_depth, (bbox[3] - bbox[1]) - orig_height) ship(-bbox[0], -bbox[1], box) return self.fonts_object.get_results(box) def get_hinting_type(self): return self.real_backend.get_hinting_type() def _switch_to_real_backend(self): self.fonts_object.mathtext_backend = self.real_backend self.real_backend.fonts_object = self.fonts_object self.real_backend.ox = self.bbox[0] self.real_backend.oy = self.bbox[1] class MathtextBackendAggRender(MathtextBackend): """ Render glyphs and rectangles to an FTImage buffer, which is later transferred to the Agg image by the Agg backend. """ def __init__(self): self.ox = 0 self.oy = 0 self.image = None MathtextBackend.__init__(self) def set_canvas_size(self, w, h, d): MathtextBackend.set_canvas_size(self, w, h, d) self.image = FT2Image(ceil(w), ceil(h + d)) def render_glyph(self, ox, oy, info): info.font.draw_glyph_to_bitmap( self.image, ox, oy - info.metrics.ymax, info.glyph) def render_rect_filled(self, x1, y1, x2, y2): height = max(int(y2 - y1) - 1, 0) if height == 0: center = (y2 + y1) / 2.0 y = int(center - (height + 1) / 2.0) else: y = int(y1) self.image.draw_rect_filled(int(x1), y, ceil(x2), y + height) def get_results(self, box): return (self.ox, self.oy, self.width, self.height + self.depth, self.depth, self.image, self.fonts_object.get_used_characters()) def get_hinting_type(self): return LOAD_FORCE_AUTOHINT def MathtextBackendAgg(): return MathtextBackendBbox(MathtextBackendAggRender()) class MathtextBackendBitmapRender(MathtextBackendAggRender): def get_results(self, box): return self.image, self.depth def MathtextBackendBitmap(): """ A backend to generate standalone mathtext images. No additional matplotlib backend is required. """ return MathtextBackendBbox(MathtextBackendBitmapRender()) class MathtextBackendPs(MathtextBackend): """ Store information to write a mathtext rendering to the PostScript backend. """ def __init__(self): self.pswriter = StringIO() self.lastfont = None def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset postscript_name = info.postscript_name fontsize = info.fontsize symbol_name = info.symbol_name if (postscript_name, fontsize) != self.lastfont: ps = """/%(postscript_name)s findfont %(fontsize)s scalefont setfont """ % locals() self.lastfont = postscript_name, fontsize self.pswriter.write(ps) ps = """%(ox)f %(oy)f moveto /%(symbol_name)s glyphshow\n """ % locals() self.pswriter.write(ps) def render_rect_filled(self, x1, y1, x2, y2): ps = "%f %f %f %f rectfill\n" % (x1, self.height - y2, x2 - x1, y2 - y1) self.pswriter.write(ps) def get_results(self, box): ship(0, -self.depth, box) #print self.depth return (self.width, self.height + self.depth, self.depth, self.pswriter, self.fonts_object.get_used_characters()) class MathtextBackendPdf(MathtextBackend): """ Store information to write a mathtext rendering to the PDF backend. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): filename = info.font.fname oy = self.height - oy + info.offset self.glyphs.append( (ox, oy, filename, info.fontsize, info.num, info.symbol_name)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append((x1, self.height - y2, x2 - x1, y2 - y1)) def get_results(self, box): ship(0, -self.depth, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects, self.fonts_object.get_used_characters()) class MathtextBackendSvg(MathtextBackend): """ Store information to write a mathtext rendering to the SVG backend. """ def __init__(self): self.svg_glyphs = [] self.svg_rects = [] def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset thetext = unichr(info.num) self.svg_glyphs.append( (info.font, info.fontsize, thetext, ox, oy, info.metrics)) def render_rect_filled(self, x1, y1, x2, y2): self.svg_rects.append( (x1, self.height - y1 + 1, x2 - x1, y2 - y1)) def get_results(self, box): ship(0, -self.depth, box) svg_elements = Bunch(svg_glyphs = self.svg_glyphs, svg_rects = self.svg_rects) return (self.width, self.height + self.depth, self.depth, svg_elements, self.fonts_object.get_used_characters()) class MathtextBackendCairo(MathtextBackend): """ Store information to write a mathtext rendering to the Cairo backend. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): oy = oy - info.offset - self.height thetext = unichr(info.num) self.glyphs.append( (info.font, info.fontsize, thetext, ox, oy)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append( (x1, y1 - self.height, x2 - x1, y2 - y1)) def get_results(self, box): ship(0, -self.depth, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects) class Fonts(object): """ An abstract base class for a system of fonts to use for mathtext. The class must be able to take symbol keys and font file names and return the character metrics. It also delegates to a backend class to do the actual drawing. """ def __init__(self, default_font_prop, mathtext_backend): """ *default_font_prop*: A :class:`~matplotlib.font_manager.FontProperties` object to use for the default non-math font, or the base font for Unicode (generic) font rendering. *mathtext_backend*: A subclass of :class:`MathTextBackend` used to delegate the actual rendering. """ self.default_font_prop = default_font_prop self.mathtext_backend = mathtext_backend # Make these classes doubly-linked self.mathtext_backend.fonts_object = self self.used_characters = {} def destroy(self): """ Fix any cyclical references before the object is about to be destroyed. """ self.used_characters = None def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): """ Get the kerning distance for font between *sym1* and *sym2*. *fontX*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default (non-math) *fontclassX*: TODO *symX*: a symbol in raw TeX form. e.g. '1', 'x' or '\sigma' *fontsizeX*: the fontsize in points *dpi*: the current dots-per-inch """ return 0. def get_metrics(self, font, font_class, sym, fontsize, dpi): """ *font*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default (non-math) *font_class*: TODO *sym*: a symbol in raw TeX form. e.g. '1', 'x' or '\sigma' *fontsize*: font size in points *dpi*: current dots-per-inch Returns an object with the following attributes: - *advance*: The advance distance (in points) of the glyph. - *height*: The height of the glyph in points. - *width*: The width of the glyph in points. - *xmin*, *xmax*, *ymin*, *ymax* - the ink rectangle of the glyph - *iceberg* - the distance from the baseline to the top of the glyph. This corresponds to TeX's definition of "height". """ info = self._get_info(font, font_class, sym, fontsize, dpi) return info.metrics def set_canvas_size(self, w, h, d): """ Set the size of the buffer used to render the math expression. Only really necessary for the bitmap backends. """ self.width, self.height, self.depth = ceil(w), ceil(h), ceil(d) self.mathtext_backend.set_canvas_size(self.width, self.height, self.depth) def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi): """ Draw a glyph at - *ox*, *oy*: position - *facename*: One of the TeX face names - *font_class*: - *sym*: TeX symbol name or single character - *fontsize*: fontsize in points - *dpi*: The dpi to draw at. """ info = self._get_info(facename, font_class, sym, fontsize, dpi) realpath, stat_key = get_realpath_and_stat(info.font.fname) used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].add(info.num) self.mathtext_backend.render_glyph(ox, oy, info) def render_rect_filled(self, x1, y1, x2, y2): """ Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*). """ self.mathtext_backend.render_rect_filled(x1, y1, x2, y2) def get_xheight(self, font, fontsize, dpi): """ Get the xheight for the given *font* and *fontsize*. """ raise NotImplementedError() def get_underline_thickness(self, font, fontsize, dpi): """ Get the line thickness that matches the given font. Used as a base unit for drawing lines such as in a fraction or radical. """ raise NotImplementedError() def get_used_characters(self): """ Get the set of characters that were used in the math expression. Used by backends that need to subset fonts so they know which glyphs to include. """ return self.used_characters def get_results(self, box): """ Get the data needed by the backend to render the math expression. The return value is backend-specific. """ return self.mathtext_backend.get_results(box) def get_sized_alternatives_for_symbol(self, fontname, sym): """ Override if your font provides multiple sizes of the same symbol. Should return a list of symbols matching *sym* in various sizes. The expression renderer will select the most appropriate size for a given situation from this list. """ return [(fontname, sym)] class TruetypeFonts(Fonts): """ A generic base class for all font setups that use Truetype fonts (through FT2Font). """ class CachedFont: def __init__(self, font): self.font = font self.charmap = font.get_charmap() self.glyphmap = dict( [(glyphind, ccode) for ccode, glyphind in self.charmap.iteritems()]) def __repr__(self): return repr(self.font) def __init__(self, default_font_prop, mathtext_backend): Fonts.__init__(self, default_font_prop, mathtext_backend) self.glyphd = {} self._fonts = {} filename = findfont(default_font_prop) default_font = self.CachedFont(FT2Font(str(filename))) self._fonts['default'] = default_font def destroy(self): self.glyphd = None Fonts.destroy(self) def _get_font(self, font): if font in self.fontmap: basename = self.fontmap[font] else: basename = font cached_font = self._fonts.get(basename) if cached_font is None: font = FT2Font(basename) cached_font = self.CachedFont(font) self._fonts[basename] = cached_font self._fonts[font.postscript_name] = cached_font self._fonts[font.postscript_name.lower()] = cached_font return cached_font def _get_offset(self, cached_font, glyph, fontsize, dpi): if cached_font.font.postscript_name == 'Cmex10': return glyph.height/64.0/2.0 + 256.0/64.0 * dpi/72.0 return 0. def _get_info(self, fontname, font_class, sym, fontsize, dpi): key = fontname, font_class, sym, fontsize, dpi bunch = self.glyphd.get(key) if bunch is not None: return bunch cached_font, num, symbol_name, fontsize, slanted = \ self._get_glyph(fontname, font_class, sym, fontsize) font = cached_font.font font.set_size(fontsize, dpi) glyph = font.load_char( num, flags=self.mathtext_backend.get_hinting_type()) xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] offset = self._get_offset(cached_font, glyph, fontsize, dpi) metrics = Bunch( advance = glyph.linearHoriAdvance/65536.0, height = glyph.height/64.0, width = glyph.width/64.0, xmin = xmin, xmax = xmax, ymin = ymin+offset, ymax = ymax+offset, # iceberg is the equivalent of TeX's "height" iceberg = glyph.horiBearingY/64.0 + offset, slanted = slanted ) result = self.glyphd[key] = Bunch( font = font, fontsize = fontsize, postscript_name = font.postscript_name, metrics = metrics, symbol_name = symbol_name, num = num, glyph = glyph, offset = offset ) return result def get_xheight(self, font, fontsize, dpi): cached_font = self._get_font(font) cached_font.font.set_size(fontsize, dpi) pclt = cached_font.font.get_sfnt_table('pclt') if pclt is None: # Some fonts don't store the xHeight, so we do a poor man's xHeight metrics = self.get_metrics(font, 'it', 'x', fontsize, dpi) return metrics.iceberg xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0) return xHeight def get_underline_thickness(self, font, fontsize, dpi): # This function used to grab underline thickness from the font # metrics, but that information is just too un-reliable, so it # is now hardcoded. return ((0.75 / 12.0) * fontsize * dpi) / 72.0 def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): if font1 == font2 and fontsize1 == fontsize2: info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) font = info1.font return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64.0 return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi) class BakomaFonts(TruetypeFonts): """ Use the Bakoma TrueType fonts for rendering. Symbols are strewn about a number of font files, each of which has its own proprietary 8-bit encoding. """ _fontmap = { 'cal' : 'cmsy10', 'rm' : 'cmr10', 'tt' : 'cmtt10', 'it' : 'cmmi10', 'bf' : 'cmb10', 'sf' : 'cmss10', 'ex' : 'cmex10' } fontmap = {} def __init__(self, *args, **kwargs): self._stix_fallback = StixFonts(*args, **kwargs) TruetypeFonts.__init__(self, *args, **kwargs) if not len(self.fontmap): for key, val in self._fontmap.iteritems(): fullpath = findfont(val) self.fontmap[key] = fullpath self.fontmap[val] = fullpath _slanted_symbols = set(r"\int \oint".split()) def _get_glyph(self, fontname, font_class, sym, fontsize): symbol_name = None if fontname in self.fontmap and sym in latex_to_bakoma: basename, num = latex_to_bakoma[sym] slanted = (basename == "cmmi10") or sym in self._slanted_symbols try: cached_font = self._get_font(basename) except RuntimeError: pass else: symbol_name = cached_font.font.get_glyph_name(num) num = cached_font.glyphmap[num] elif len(sym) == 1: slanted = (fontname == "it") try: cached_font = self._get_font(fontname) except RuntimeError: pass else: num = ord(sym) gid = cached_font.charmap.get(num) if gid is not None: symbol_name = cached_font.font.get_glyph_name( cached_font.charmap[num]) if symbol_name is None: return self._stix_fallback._get_glyph( fontname, font_class, sym, fontsize) return cached_font, num, symbol_name, fontsize, slanted # The Bakoma fonts contain many pre-sized alternatives for the # delimiters. The AutoSizedChar class will use these alternatives # and select the best (closest sized) glyph. _size_alternatives = { '(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'), ('ex', '\xb5'), ('ex', '\xc3')], ')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'), ('ex', '\xb6'), ('ex', '\x21')], '{' : [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'), ('ex', '\xbd'), ('ex', '\x28')], '}' : [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), ('ex', '\xbe'), ('ex', '\x29')], # The fourth size of '[' is mysteriously missing from the BaKoMa # font, so I've ommitted it for both '[' and ']' '[' : [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), ('ex', '\x22')], ']' : [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), ('ex', '\x23')], r'\lfloor' : [('ex', '\xa5'), ('ex', '\x6a'), ('ex', '\xb9'), ('ex', '\x24')], r'\rfloor' : [('ex', '\xa6'), ('ex', '\x6b'), ('ex', '\xba'), ('ex', '\x25')], r'\lceil' : [('ex', '\xa7'), ('ex', '\x6c'), ('ex', '\xbb'), ('ex', '\x26')], r'\rceil' : [('ex', '\xa8'), ('ex', '\x6d'), ('ex', '\xbc'), ('ex', '\x27')], r'\langle' : [('ex', '\xad'), ('ex', '\x44'), ('ex', '\xbf'), ('ex', '\x2a')], r'\rangle' : [('ex', '\xae'), ('ex', '\x45'), ('ex', '\xc0'), ('ex', '\x2b')], r'\__sqrt__' : [('ex', '\x70'), ('ex', '\x71'), ('ex', '\x72'), ('ex', '\x73')], r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'), ('ex', '\xc2'), ('ex', '\x2d')], r'/' : [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'), ('ex', '\xcb'), ('ex', '\x2c')], r'\widehat' : [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'), ('ex', '\x64')], r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'), ('ex', '\x67')], r'<' : [('cal', 'h'), ('ex', 'D')], r'>' : [('cal', 'i'), ('ex', 'E')] } for alias, target in [('\leftparen', '('), ('\rightparent', ')'), ('\leftbrace', '{'), ('\rightbrace', '}'), ('\leftbracket', '['), ('\rightbracket', ']')]: _size_alternatives[alias] = _size_alternatives[target] def get_sized_alternatives_for_symbol(self, fontname, sym): return self._size_alternatives.get(sym, [(fontname, sym)]) class UnicodeFonts(TruetypeFonts): """ An abstract base class for handling Unicode fonts. While some reasonably complete Unicode fonts (such as DejaVu) may work in some situations, the only Unicode font I'm aware of with a complete set of math symbols is STIX. This class will "fallback" on the Bakoma fonts when a required symbol can not be found in the font. """ fontmap = {} use_cmex = True def __init__(self, *args, **kwargs): # This must come first so the backend's owner is set correctly if rcParams['mathtext.fallback_to_cm']: self.cm_fallback = BakomaFonts(*args, **kwargs) else: self.cm_fallback = None TruetypeFonts.__init__(self, *args, **kwargs) if not len(self.fontmap): for texfont in "cal rm tt it bf sf".split(): prop = rcParams['mathtext.' + texfont] font = findfont(prop) self.fontmap[texfont] = font prop = FontProperties('cmex10') font = findfont(prop) self.fontmap['ex'] = font _slanted_symbols = set(r"\int \oint".split()) def _map_virtual_font(self, fontname, font_class, uniindex): return fontname, uniindex def _get_glyph(self, fontname, font_class, sym, fontsize): found_symbol = False if self.use_cmex: uniindex = latex_to_cmex.get(sym) if uniindex is not None: fontname = 'ex' found_symbol = True if not found_symbol: try: uniindex = get_unicode_index(sym) found_symbol = True except ValueError: uniindex = ord('?') warn("No TeX to unicode mapping for '%s'" % sym.encode('ascii', 'backslashreplace'), MathTextWarning) fontname, uniindex = self._map_virtual_font( fontname, font_class, uniindex) # Only characters in the "Letter" class should be italicized in 'it' # mode. Greek capital letters should be Roman. if found_symbol: new_fontname = fontname if fontname == 'it': if uniindex < 0x10000: unistring = unichr(uniindex) if (not unicodedata.category(unistring)[0] == "L" or unicodedata.name(unistring).startswith("GREEK CAPITAL")): new_fontname = 'rm' slanted = (new_fontname == 'it') or sym in self._slanted_symbols found_symbol = False try: cached_font = self._get_font(new_fontname) except RuntimeError: pass else: try: glyphindex = cached_font.charmap[uniindex] found_symbol = True except KeyError: pass if not found_symbol: if self.cm_fallback: warn("Substituting with a symbol from Computer Modern.", MathTextWarning) return self.cm_fallback._get_glyph( fontname, 'it', sym, fontsize) else: if fontname == 'it' and isinstance(self, StixFonts): return self._get_glyph('rm', font_class, sym, fontsize) warn("Font '%s' does not have a glyph for '%s'" % (fontname, sym.encode('ascii', 'backslashreplace')), MathTextWarning) warn("Substituting with a dummy symbol.", MathTextWarning) fontname = 'rm' new_fontname = fontname cached_font = self._get_font(fontname) uniindex = 0xA4 # currency character, for lack of anything better glyphindex = cached_font.charmap[uniindex] slanted = False symbol_name = cached_font.font.get_glyph_name(glyphindex) return cached_font, uniindex, symbol_name, fontsize, slanted def get_sized_alternatives_for_symbol(self, fontname, sym): if self.cm_fallback: return self.cm_fallback.get_sized_alternatives_for_symbol( fontname, sym) return [(fontname, sym)] class StixFonts(UnicodeFonts): """ A font handling class for the STIX fonts. In addition to what UnicodeFonts provides, this class: - supports "virtual fonts" which are complete alpha numeric character sets with different font styles at special Unicode code points, such as "Blackboard". - handles sized alternative characters for the STIXSizeX fonts. """ _fontmap = { 'rm' : 'STIXGeneral', 'it' : 'STIXGeneral:italic', 'bf' : 'STIXGeneral:weight=bold', 'nonunirm' : 'STIXNonUnicode', 'nonuniit' : 'STIXNonUnicode:italic', 'nonunibf' : 'STIXNonUnicode:weight=bold', 0 : 'STIXGeneral', 1 : 'STIXSize1', 2 : 'STIXSize2', 3 : 'STIXSize3', 4 : 'STIXSize4', 5 : 'STIXSize5' } fontmap = {} use_cmex = False cm_fallback = False _sans = False def __init__(self, *args, **kwargs): TruetypeFonts.__init__(self, *args, **kwargs) if not len(self.fontmap): for key, name in self._fontmap.iteritems(): fullpath = findfont(name) self.fontmap[key] = fullpath self.fontmap[name] = fullpath def _map_virtual_font(self, fontname, font_class, uniindex): # Handle these "fonts" that are actually embedded in # other fonts. mapping = stix_virtual_fonts.get(fontname) if self._sans and mapping is None: mapping = stix_virtual_fonts['sf'] doing_sans_conversion = True else: doing_sans_conversion = False if mapping is not None: if isinstance(mapping, dict): mapping = mapping[font_class] # Binary search for the source glyph lo = 0 hi = len(mapping) while lo < hi: mid = (lo+hi)//2 range = mapping[mid] if uniindex < range[0]: hi = mid elif uniindex <= range[1]: break else: lo = mid + 1 if uniindex >= range[0] and uniindex <= range[1]: uniindex = uniindex - range[0] + range[3] fontname = range[2] elif not doing_sans_conversion: # This will generate a dummy character uniindex = 0x1 fontname = 'it' # Handle private use area glyphs if (fontname in ('it', 'rm', 'bf') and uniindex >= 0xe000 and uniindex <= 0xf8ff): fontname = 'nonuni' + fontname return fontname, uniindex _size_alternatives = {} def get_sized_alternatives_for_symbol(self, fontname, sym): alternatives = self._size_alternatives.get(sym) if alternatives: return alternatives alternatives = [] try: uniindex = get_unicode_index(sym) except ValueError: return [(fontname, sym)] fix_ups = { ord('<'): 0x27e8, ord('>'): 0x27e9 } uniindex = fix_ups.get(uniindex, uniindex) for i in range(6): cached_font = self._get_font(i) glyphindex = cached_font.charmap.get(uniindex) if glyphindex is not None: alternatives.append((i, unichr(uniindex))) self._size_alternatives[sym] = alternatives return alternatives class StixSansFonts(StixFonts): """ A font handling class for the STIX fonts (that uses sans-serif characters by default). """ _sans = True class StandardPsFonts(Fonts): """ Use the standard postscript fonts for rendering to backend_ps Unlike the other font classes, BakomaFont and UnicodeFont, this one requires the Ps backend. """ basepath = os.path.join( get_data_path(), 'fonts', 'afm' ) fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery 'rm' : 'pncr8a', # New Century Schoolbook 'tt' : 'pcrr8a', # Courier 'it' : 'pncri8a', # New Century Schoolbook Italic 'sf' : 'phvr8a', # Helvetica 'bf' : 'pncb8a', # New Century Schoolbook Bold None : 'psyr' # Symbol } def __init__(self, default_font_prop): Fonts.__init__(self, default_font_prop, MathtextBackendPs()) self.glyphd = {} self.fonts = {} filename = findfont(default_font_prop, fontext='afm') default_font = AFM(file(filename, 'r')) default_font.fname = filename self.fonts['default'] = default_font self.pswriter = StringIO() def _get_font(self, font): if font in self.fontmap: basename = self.fontmap[font] else: basename = font cached_font = self.fonts.get(basename) if cached_font is None: fname = os.path.join(self.basepath, basename + ".afm") cached_font = AFM(file(fname, 'r')) cached_font.fname = fname self.fonts[basename] = cached_font self.fonts[cached_font.get_fontname()] = cached_font return cached_font def _get_info (self, fontname, font_class, sym, fontsize, dpi): 'load the cmfont, metrics and glyph with caching' key = fontname, sym, fontsize, dpi tup = self.glyphd.get(key) if tup is not None: return tup # Only characters in the "Letter" class should really be italicized. # This class includes greek letters, so we're ok if (fontname == 'it' and (len(sym) > 1 or not unicodedata.category(unicode(sym)).startswith("L"))): fontname = 'rm' found_symbol = False if sym in latex_to_standard: fontname, num = latex_to_standard[sym] glyph = chr(num) found_symbol = True elif len(sym) == 1: glyph = sym num = ord(glyph) found_symbol = True else: warn("No TeX to built-in Postscript mapping for '%s'" % sym, MathTextWarning) slanted = (fontname == 'it') font = self._get_font(fontname) if found_symbol: try: symbol_name = font.get_name_char(glyph) except KeyError: warn("No glyph in standard Postscript font '%s' for '%s'" % (font.postscript_name, sym), MathTextWarning) found_symbol = False if not found_symbol: glyph = sym = '?' num = ord(glyph) symbol_name = font.get_name_char(glyph) offset = 0 scale = 0.001 * fontsize xmin, ymin, xmax, ymax = [val * scale for val in font.get_bbox_char(glyph)] metrics = Bunch( advance = font.get_width_char(glyph) * scale, width = font.get_width_char(glyph) * scale, height = font.get_height_char(glyph) * scale, xmin = xmin, xmax = xmax, ymin = ymin+offset, ymax = ymax+offset, # iceberg is the equivalent of TeX's "height" iceberg = ymax + offset, slanted = slanted ) self.glyphd[key] = Bunch( font = font, fontsize = fontsize, postscript_name = font.get_fontname(), metrics = metrics, symbol_name = symbol_name, num = num, glyph = glyph, offset = offset ) return self.glyphd[key] def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): if font1 == font2 and fontsize1 == fontsize2: info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) font = info1.font return (font.get_kern_dist(info1.glyph, info2.glyph) * 0.001 * fontsize1) return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi) def get_xheight(self, font, fontsize, dpi): cached_font = self._get_font(font) return cached_font.get_xheight() * 0.001 * fontsize def get_underline_thickness(self, font, fontsize, dpi): cached_font = self._get_font(font) return cached_font.get_underline_thickness() * 0.001 * fontsize ############################################################################## # TeX-LIKE BOX MODEL # The following is based directly on the document 'woven' from the # TeX82 source code. This information is also available in printed # form: # # Knuth, Donald E.. 1986. Computers and Typesetting, Volume B: # TeX: The Program. Addison-Wesley Professional. # # The most relevant "chapters" are: # Data structures for boxes and their friends # Shipping pages out (Ship class) # Packaging (hpack and vpack) # Data structures for math mode # Subroutines for math mode # Typesetting math formulas # # Many of the docstrings below refer to a numbered "node" in that # book, e.g. node123 # # Note that (as TeX) y increases downward, unlike many other parts of # matplotlib. # How much text shrinks when going to the next-smallest level. GROW_FACTOR # must be the inverse of SHRINK_FACTOR. SHRINK_FACTOR = 0.7 GROW_FACTOR = 1.0 / SHRINK_FACTOR # The number of different sizes of chars to use, beyond which they will not # get any smaller NUM_SIZE_LEVELS = 4 # Percentage of x-height of additional horiz. space after sub/superscripts SCRIPT_SPACE = 0.2 # Percentage of x-height that sub/superscripts drop below the baseline SUBDROP = 0.3 # Percentage of x-height that superscripts drop below the baseline SUP1 = 0.5 # Percentage of x-height that subscripts drop below the baseline SUB1 = 0.0 # Percentage of x-height that superscripts are offset relative to the subscript DELTA = 0.18 class MathTextWarning(Warning): pass class Node(object): """ A node in the TeX box model """ def __init__(self): self.size = 0 def __repr__(self): return self.__internal_repr__() def __internal_repr__(self): return self.__class__.__name__ def get_kerning(self, next): return 0.0 def shrink(self): """ Shrinks one level smaller. There are only three levels of sizes, after which things will no longer get smaller. """ self.size += 1 def grow(self): """ Grows one level larger. There is no limit to how big something can get. """ self.size -= 1 def render(self, x, y): pass class Box(Node): """ Represents any node with a physical location. """ def __init__(self, width, height, depth): Node.__init__(self) self.width = width self.height = height self.depth = depth def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR def grow(self): Node.grow(self) self.width *= GROW_FACTOR self.height *= GROW_FACTOR self.depth *= GROW_FACTOR def render(self, x1, y1, x2, y2): pass class Vbox(Box): """ A box with only height (zero width). """ def __init__(self, height, depth): Box.__init__(self, 0., height, depth) class Hbox(Box): """ A box with only width (zero height and depth). """ def __init__(self, width): Box.__init__(self, width, 0., 0.) class Char(Node): """ Represents a single character. Unlike TeX, the font information and metrics are stored with each :class:`Char` to make it easier to lookup the font metrics when needed. Note that TeX boxes have a width, height, and depth, unlike Type1 and Truetype which use a full bounding box and an advance in the x-direction. The metrics must be converted to the TeX way, and the advance (if different from width) must be converted into a :class:`Kern` node when the :class:`Char` is added to its parent :class:`Hlist`. """ def __init__(self, c, state): Node.__init__(self) self.c = c self.font_output = state.font_output assert isinstance(state.font, (str, unicode, int)) self.font = state.font self.font_class = state.font_class self.fontsize = state.fontsize self.dpi = state.dpi # The real width, height and depth will be set during the # pack phase, after we know the real fontsize self._update_metrics() def __internal_repr__(self): return '`%s`' % self.c def _update_metrics(self): metrics = self._metrics = self.font_output.get_metrics( self.font, self.font_class, self.c, self.fontsize, self.dpi) if self.c == ' ': self.width = metrics.advance else: self.width = metrics.width self.height = metrics.iceberg self.depth = -(metrics.iceberg - metrics.height) def is_slanted(self): return self._metrics.slanted def get_kerning(self, next): """ Return the amount of kerning between this and the given character. Called when characters are strung together into :class:`Hlist` to create :class:`Kern` nodes. """ advance = self._metrics.advance - self.width kern = 0. if isinstance(next, Char): kern = self.font_output.get_kern( self.font, self.font_class, self.c, self.fontsize, next.font, next.font_class, next.c, next.fontsize, self.dpi) return advance + kern def render(self, x, y): """ Render the character to the canvas """ self.font_output.render_glyph( x, y, self.font, self.font_class, self.c, self.fontsize, self.dpi) def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.fontsize *= SHRINK_FACTOR self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR def grow(self): Node.grow(self) self.fontsize *= GROW_FACTOR self.width *= GROW_FACTOR self.height *= GROW_FACTOR self.depth *= GROW_FACTOR class Accent(Char): """ The font metrics need to be dealt with differently for accents, since they are already offset correctly from the baseline in TrueType fonts. """ def _update_metrics(self): metrics = self._metrics = self.font_output.get_metrics( self.font, self.font_class, self.c, self.fontsize, self.dpi) self.width = metrics.xmax - metrics.xmin self.height = metrics.ymax - metrics.ymin self.depth = 0 def shrink(self): Char.shrink(self) self._update_metrics() def grow(self): Char.grow(self) self._update_metrics() def render(self, x, y): """ Render the character to the canvas. """ self.font_output.render_glyph( x - self._metrics.xmin, y + self._metrics.ymin, self.font, self.font_class, self.c, self.fontsize, self.dpi) class List(Box): """ A list of nodes (either horizontal or vertical). """ def __init__(self, elements): Box.__init__(self, 0., 0., 0.) self.shift_amount = 0. # An arbitrary offset self.children = elements # The child nodes of this list # The following parameters are set in the vpack and hpack functions self.glue_set = 0. # The glue setting of this list self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching self.glue_order = 0 # The order of infinity (0 - 3) for the glue def __repr__(self): return '[%s <%.02f %.02f %.02f %.02f> %s]' % ( self.__internal_repr__(), self.width, self.height, self.depth, self.shift_amount, ' '.join([repr(x) for x in self.children])) def _determine_order(self, totals): """ A helper function to determine the highest order of glue used by the members of this list. Used by vpack and hpack. """ o = 0 for i in range(len(totals) - 1, 0, -1): if totals[i] != 0.0: o = i break return o def _set_glue(self, x, sign, totals, error_type): o = self._determine_order(totals) self.glue_order = o self.glue_sign = sign if totals[o] != 0.: self.glue_set = x / totals[o] else: self.glue_sign = 0 self.glue_ratio = 0. if o == 0: if len(self.children): warn("%s %s: %r" % (error_type, self.__class__.__name__, self), MathTextWarning) def shrink(self): for child in self.children: child.shrink() Box.shrink(self) if self.size < NUM_SIZE_LEVELS: self.shift_amount *= SHRINK_FACTOR self.glue_set *= SHRINK_FACTOR def grow(self): for child in self.children: child.grow() Box.grow(self) self.shift_amount *= GROW_FACTOR self.glue_set *= GROW_FACTOR class Hlist(List): """ A horizontal list of boxes. """ def __init__(self, elements, w=0., m='additional', do_kern=True): List.__init__(self, elements) if do_kern: self.kern() self.hpack() def kern(self): """ Insert :class:`Kern` nodes between :class:`Char` nodes to set kerning. The :class:`Char` nodes themselves determine the amount of kerning they need (in :meth:`~Char.get_kerning`), and this function just creates the linked list in the correct way. """ new_children = [] num_children = len(self.children) if num_children: for i in range(num_children): elem = self.children[i] if i < num_children - 1: next = self.children[i + 1] else: next = None new_children.append(elem) kerning_distance = elem.get_kerning(next) if kerning_distance != 0.: kern = Kern(kerning_distance) new_children.append(kern) self.children = new_children # This is a failed experiment to fake cross-font kerning. # def get_kerning(self, next): # if len(self.children) >= 2 and isinstance(self.children[-2], Char): # if isinstance(next, Char): # print "CASE A" # return self.children[-2].get_kerning(next) # elif isinstance(next, Hlist) and len(next.children) and isinstance(next.children[0], Char): # print "CASE B" # result = self.children[-2].get_kerning(next.children[0]) # print result # return result # return 0.0 def hpack(self, w=0., m='additional'): """ The main duty of :meth:`hpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. The computed sizes normally enclose all of the material inside the new box; but some items may stick out if negative glue is used, if the box is overfull, or if a ``\\vbox`` includes other boxes that have been shifted left. - *w*: specifies a width - *m*: is either 'exactly' or 'additional'. Thus, ``hpack(w, 'exactly')`` produces a box whose width is exactly *w*, while ``hpack(w, 'additional')`` yields a box whose width is the natural width plus *w*. The default values produce a box with the natural width. """ # I don't know why these get reset in TeX. Shift_amount is pretty # much useless if we do. #self.shift_amount = 0. h = 0. d = 0. x = 0. total_stretch = [0.] * 4 total_shrink = [0.] * 4 for p in self.children: if isinstance(p, Char): x += p.width h = max(h, p.height) d = max(d, p.depth) elif isinstance(p, Box): x += p.width if not isinf(p.height) and not isinf(p.depth): s = getattr(p, 'shift_amount', 0.) h = max(h, p.height - s) d = max(d, p.depth + s) elif isinstance(p, Glue): glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += p.width self.height = h self.depth = d if m == 'additional': w += x self.width = w x = w - x if x == 0.: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0. return if x > 0.: self._set_glue(x, 1, total_stretch, "Overfull") else: self._set_glue(x, -1, total_shrink, "Underfull") class Vlist(List): """ A vertical list of boxes. """ def __init__(self, elements, h=0., m='additional'): List.__init__(self, elements) self.vpack() def vpack(self, h=0., m='additional', l=float(inf)): """ The main duty of :meth:`vpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. - *h*: specifies a height - *m*: is either 'exactly' or 'additional'. - *l*: a maximum height Thus, ``vpack(h, 'exactly')`` produces a box whose height is exactly *h*, while ``vpack(h, 'additional')`` yields a box whose height is the natural height plus *h*. The default values produce a box with the natural width. """ # I don't know why these get reset in TeX. Shift_amount is pretty # much useless if we do. # self.shift_amount = 0. w = 0. d = 0. x = 0. total_stretch = [0.] * 4 total_shrink = [0.] * 4 for p in self.children: if isinstance(p, Box): x += d + p.height d = p.depth if not isinf(p.width): s = getattr(p, 'shift_amount', 0.) w = max(w, p.width + s) elif isinstance(p, Glue): x += d d = 0. glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += d + p.width d = 0. elif isinstance(p, Char): raise RuntimeError("Internal mathtext error: Char node found in Vlist.") self.width = w if d > l: x += d - l self.depth = l else: self.depth = d if m == 'additional': h += x self.height = h x = h - x if x == 0: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0. return if x > 0.: self._set_glue(x, 1, total_stretch, "Overfull") else: self._set_glue(x, -1, total_shrink, "Underfull") class Rule(Box): """ A :class:`Rule` node stands for a solid black rectangle; it has *width*, *depth*, and *height* fields just as in an :class:`Hlist`. However, if any of these dimensions is inf, the actual value will be determined by running the rule up to the boundary of the innermost enclosing box. This is called a "running dimension." The width is never running in an :class:`Hlist`; the height and depth are never running in a :class:`Vlist`. """ def __init__(self, width, height, depth, state): Box.__init__(self, width, height, depth) self.font_output = state.font_output def render(self, x, y, w, h): self.font_output.render_rect_filled(x, y, x + w, y + h) class Hrule(Rule): """ Convenience class to create a horizontal rule. """ def __init__(self, state): thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) height = depth = thickness * 0.5 Rule.__init__(self, inf, height, depth, state) class Vrule(Rule): """ Convenience class to create a vertical rule. """ def __init__(self, state): thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) Rule.__init__(self, thickness, inf, inf, state) class Glue(Node): """ Most of the information in this object is stored in the underlying :class:`GlueSpec` class, which is shared between multiple glue objects. (This is a memory optimization which probably doesn't matter anymore, but it's easier to stick to what TeX does.) """ def __init__(self, glue_type, copy=False): Node.__init__(self) self.glue_subtype = 'normal' if is_string_like(glue_type): glue_spec = GlueSpec.factory(glue_type) elif isinstance(glue_type, GlueSpec): glue_spec = glue_type else: raise ArgumentError("glue_type must be a glue spec name or instance.") if copy: glue_spec = glue_spec.copy() self.glue_spec = glue_spec def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: if self.glue_spec.width != 0.: self.glue_spec = self.glue_spec.copy() self.glue_spec.width *= SHRINK_FACTOR def grow(self): Node.grow(self) if self.glue_spec.width != 0.: self.glue_spec = self.glue_spec.copy() self.glue_spec.width *= GROW_FACTOR class GlueSpec(object): """ See :class:`Glue`. """ def __init__(self, width=0., stretch=0., stretch_order=0, shrink=0., shrink_order=0): self.width = width self.stretch = stretch self.stretch_order = stretch_order self.shrink = shrink self.shrink_order = shrink_order def copy(self): return GlueSpec( self.width, self.stretch, self.stretch_order, self.shrink, self.shrink_order) def factory(cls, glue_type): return cls._types[glue_type] factory = classmethod(factory) GlueSpec._types = { 'fil': GlueSpec(0., 1., 1, 0., 0), 'fill': GlueSpec(0., 1., 2, 0., 0), 'filll': GlueSpec(0., 1., 3, 0., 0), 'neg_fil': GlueSpec(0., 0., 0, 1., 1), 'neg_fill': GlueSpec(0., 0., 0, 1., 2), 'neg_filll': GlueSpec(0., 0., 0, 1., 3), 'empty': GlueSpec(0., 0., 0, 0., 0), 'ss': GlueSpec(0., 1., 1, -1., 1) } # Some convenient ways to get common kinds of glue class Fil(Glue): def __init__(self): Glue.__init__(self, 'fil') class Fill(Glue): def __init__(self): Glue.__init__(self, 'fill') class Filll(Glue): def __init__(self): Glue.__init__(self, 'filll') class NegFil(Glue): def __init__(self): Glue.__init__(self, 'neg_fil') class NegFill(Glue): def __init__(self): Glue.__init__(self, 'neg_fill') class NegFilll(Glue): def __init__(self): Glue.__init__(self, 'neg_filll') class SsGlue(Glue): def __init__(self): Glue.__init__(self, 'ss') class HCentered(Hlist): """ A convenience class to create an :class:`Hlist` whose contents are centered within its enclosing box. """ def __init__(self, elements): Hlist.__init__(self, [SsGlue()] + elements + [SsGlue()], do_kern=False) class VCentered(Hlist): """ A convenience class to create a :class:`Vlist` whose contents are centered within its enclosing box. """ def __init__(self, elements): Vlist.__init__(self, [SsGlue()] + elements + [SsGlue()]) class Kern(Node): """ A :class:`Kern` node has a width field to specify a (normally negative) amount of spacing. This spacing correction appears in horizontal lists between letters like A and V when the font designer said that it looks better to move them closer together or further apart. A kern node can also appear in a vertical list, when its *width* denotes additional spacing in the vertical direction. """ def __init__(self, width): Node.__init__(self) self.width = width def __repr__(self): return "k%.02f" % self.width def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR def grow(self): Node.grow(self) self.width *= GROW_FACTOR class SubSuperCluster(Hlist): """ :class:`SubSuperCluster` is a sort of hack to get around that fact that this code do a two-pass parse like TeX. This lets us store enough information in the hlist itself, namely the nucleus, sub- and super-script, such that if another script follows that needs to be attached, it can be reconfigured on the fly. """ def __init__(self): self.nucleus = None self.sub = None self.super = None Hlist.__init__(self, []) class AutoHeightChar(Hlist): """ :class:`AutoHeightChar` will create a character as close to the given height and depth as possible. When using a font with multiple height versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph. """ def __init__(self, c, height, depth, state, always=False): alternatives = state.font_output.get_sized_alternatives_for_symbol( state.font, c) state = state.copy() target_total = height + depth for fontname, sym in alternatives: state.font = fontname char = Char(sym, state) if char.height + char.depth >= target_total: break factor = target_total / (char.height + char.depth) state.fontsize *= factor char = Char(sym, state) shift = (depth - char.depth) Hlist.__init__(self, [char]) self.shift_amount = shift class AutoWidthChar(Hlist): """ :class:`AutoWidthChar` will create a character as close to the given width as possible. When using a font with multiple width versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph. """ def __init__(self, c, width, state, always=False, char_class=Char): alternatives = state.font_output.get_sized_alternatives_for_symbol( state.font, c) state = state.copy() for fontname, sym in alternatives: state.font = fontname char = char_class(sym, state) if char.width >= width: break factor = width / char.width state.fontsize *= factor char = char_class(sym, state) Hlist.__init__(self, [char]) self.width = char.width class Ship(object): """ Once the boxes have been set up, this sends them to output. Since boxes can be inside of boxes inside of boxes, the main work of :class:`Ship` is done by two mutually recursive routines, :meth:`hlist_out` and :meth:`vlist_out`, which traverse the :class:`Hlist` nodes and :class:`Vlist` nodes inside of horizontal and vertical boxes. The global variables used in TeX to store state as it processes have become member variables here. """ def __call__(self, ox, oy, box): self.max_push = 0 # Deepest nesting of push commands so far self.cur_s = 0 self.cur_v = 0. self.cur_h = 0. self.off_h = ox self.off_v = oy + box.height self.hlist_out(box) def clamp(value): if value < -1000000000.: return -1000000000. if value > 1000000000.: return 1000000000. return value clamp = staticmethod(clamp) def hlist_out(self, box): cur_g = 0 cur_glue = 0. glue_order = box.glue_order glue_sign = box.glue_sign base_line = self.cur_v left_edge = self.cur_h self.cur_s += 1 self.max_push = max(self.cur_s, self.max_push) clamp = self.clamp for p in box.children: if isinstance(p, Char): p.render(self.cur_h + self.off_h, self.cur_v + self.off_v) self.cur_h += p.width elif isinstance(p, Kern): self.cur_h += p.width elif isinstance(p, List): # node623 if len(p.children) == 0: self.cur_h += p.width else: edge = self.cur_h self.cur_v = base_line + p.shift_amount if isinstance(p, Hlist): self.hlist_out(p) else: # p.vpack(box.height + box.depth, 'exactly') self.vlist_out(p) self.cur_h = edge + p.width self.cur_v = base_line elif isinstance(p, Box): # node624 rule_height = p.height rule_depth = p.depth rule_width = p.width if isinf(rule_height): rule_height = box.height if isinf(rule_depth): rule_depth = box.depth if rule_height > 0 and rule_width > 0: self.cur_v = baseline + rule_depth p.render(self.cur_h + self.off_h, self.cur_v + self.off_v, rule_width, rule_height) self.cur_v = baseline self.cur_h += rule_width elif isinstance(p, Glue): # node625 glue_spec = p.glue_spec rule_width = glue_spec.width - cur_g if glue_sign != 0: # normal if glue_sign == 1: # stretching if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = round(clamp(float(box.glue_set) * cur_glue)) elif glue_spec.shrink_order == glue_order: cur_glue += glue_spec.shrink cur_g = round(clamp(float(box.glue_set) * cur_glue)) rule_width += cur_g self.cur_h += rule_width self.cur_s -= 1 def vlist_out(self, box): cur_g = 0 cur_glue = 0. glue_order = box.glue_order glue_sign = box.glue_sign self.cur_s += 1 self.max_push = max(self.max_push, self.cur_s) left_edge = self.cur_h self.cur_v -= box.height top_edge = self.cur_v clamp = self.clamp for p in box.children: if isinstance(p, Kern): self.cur_v += p.width elif isinstance(p, List): if len(p.children) == 0: self.cur_v += p.height + p.depth else: self.cur_v += p.height self.cur_h = left_edge + p.shift_amount save_v = self.cur_v p.width = box.width if isinstance(p, Hlist): self.hlist_out(p) else: self.vlist_out(p) self.cur_v = save_v + p.depth self.cur_h = left_edge elif isinstance(p, Box): rule_height = p.height rule_depth = p.depth rule_width = p.width if isinf(rule_width): rule_width = box.width rule_height += rule_depth if rule_height > 0 and rule_depth > 0: self.cur_v += rule_height p.render(self.cur_h + self.off_h, self.cur_v + self.off_v, rule_width, rule_height) elif isinstance(p, Glue): glue_spec = p.glue_spec rule_height = glue_spec.width - cur_g if glue_sign != 0: # normal if glue_sign == 1: # stretching if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = round(clamp(float(box.glue_set) * cur_glue)) elif glue_spec.shrink_order == glue_order: # shrinking cur_glue += glue_spec.shrink cur_g = round(clamp(float(box.glue_set) * cur_glue)) rule_height += cur_g self.cur_v += rule_height elif isinstance(p, Char): raise RuntimeError("Internal mathtext error: Char node found in vlist") self.cur_s -= 1 ship = Ship() ############################################################################## # PARSER def Error(msg): """ Helper class to raise parser errors. """ def raise_error(s, loc, toks): raise ParseFatalException(msg + "\n" + s) empty = Empty() empty.setParseAction(raise_error) return empty class Parser(object): """ This is the pyparsing-based parser for math expressions. It actually parses full strings *containing* math expressions, in that raw text may also appear outside of pairs of ``$``. The grammar is based directly on that in TeX, though it cuts a few corners. """ _binary_operators = set(r''' + * \pm \sqcap \rhd \mp \sqcup \unlhd \times \vee \unrhd \div \wedge \oplus \ast \setminus \ominus \star \wr \otimes \circ \diamond \oslash \bullet \bigtriangleup \odot \cdot \bigtriangledown \bigcirc \cap \triangleleft \dagger \cup \triangleright \ddagger \uplus \lhd \amalg'''.split()) _relation_symbols = set(r''' = < > : \leq \geq \equiv \models \prec \succ \sim \perp \preceq \succeq \simeq \mid \ll \gg \asymp \parallel \subset \supset \approx \bowtie \subseteq \supseteq \cong \Join \sqsubset \sqsupset \neq \smile \sqsubseteq \sqsupseteq \doteq \frown \in \ni \propto \vdash \dashv'''.split()) _arrow_symbols = set(r''' \leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow \Longrightarrow \Downarrow \leftrightarrow \longleftrightarrow \updownarrow \Leftrightarrow \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow \hookleftarrow \hookrightarrow \searrow \leftharpoonup \rightharpoonup \swarrow \leftharpoondown \rightharpoondown \nwarrow \rightleftharpoons \leadsto'''.split()) _spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols _punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split()) _overunder_symbols = set(r''' \sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee \bigwedge \bigodot \bigotimes \bigoplus \biguplus '''.split()) _overunder_functions = set( r"lim liminf limsup sup max min".split()) _dropsub_symbols = set(r'''\int \oint'''.split()) _fontnames = set("rm cal it tt sf bf default bb frak circled scr".split()) _function_names = set(""" arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan coth inf max tanh""".split()) _ambiDelim = set(r""" | \| / \backslash \uparrow \downarrow \updownarrow \Uparrow \Downarrow \Updownarrow .""".split()) _leftDelim = set(r"( [ { < \lfloor \langle \lceil".split()) _rightDelim = set(r") ] } > \rfloor \rangle \rceil".split()) def __init__(self): # All forward declarations are here font = Forward().setParseAction(self.font).setName("font") latexfont = Forward() subsuper = Forward().setParseAction(self.subsuperscript).setName("subsuper") placeable = Forward().setName("placeable") simple = Forward().setName("simple") autoDelim = Forward().setParseAction(self.auto_sized_delimiter) self._expression = Forward().setParseAction(self.finish).setName("finish") float = Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)") lbrace = Literal('{').suppress() rbrace = Literal('}').suppress() start_group = (Optional(latexfont) - lbrace) start_group.setParseAction(self.start_group) end_group = rbrace.copy() end_group.setParseAction(self.end_group) bslash = Literal('\\') accent = oneOf(self._accent_map.keys() + list(self._wide_accents)) function = oneOf(list(self._function_names)) fontname = oneOf(list(self._fontnames)) latex2efont = oneOf(['math' + x for x in self._fontnames]) space =(FollowedBy(bslash) + oneOf([r'\ ', r'\/', r'\,', r'\;', r'\quad', r'\qquad', r'\!']) ).setParseAction(self.space).setName('space') customspace =(Literal(r'\hspace') - (( lbrace - float - rbrace ) | Error(r"Expected \hspace{n}")) ).setParseAction(self.customspace).setName('customspace') unicode_range = u"\U00000080-\U0001ffff" symbol =(Regex(UR"([a-zA-Z0-9 +\-*/<>=:,.;!'@()\[\]|%s])|(\\[%%${}\[\]_|])" % unicode_range) | (Combine( bslash + oneOf(tex2uni.keys()) ) + FollowedBy(Regex("[^a-zA-Z]"))) ).setParseAction(self.symbol).leaveWhitespace() c_over_c =(Suppress(bslash) + oneOf(self._char_over_chars.keys()) ).setParseAction(self.char_over_chars) accent = Group( Suppress(bslash) + accent - placeable ).setParseAction(self.accent).setName("accent") function =(Suppress(bslash) + function ).setParseAction(self.function).setName("function") group = Group( start_group + ZeroOrMore( autoDelim ^ simple) - end_group ).setParseAction(self.group).setName("group") font <<(Suppress(bslash) + fontname) latexfont <<(Suppress(bslash) + latex2efont) frac = Group( Suppress(Literal(r"\frac")) + ((group + group) | Error(r"Expected \frac{num}{den}")) ).setParseAction(self.frac).setName("frac") sqrt = Group( Suppress(Literal(r"\sqrt")) + Optional( Suppress(Literal("[")) - Regex("[0-9]+") - Suppress(Literal("]")), default = None ) + (group | Error("Expected \sqrt{value}")) ).setParseAction(self.sqrt).setName("sqrt") placeable <<(accent ^ function ^ (c_over_c | symbol) ^ group ^ frac ^ sqrt ) simple <<(space | customspace | font | subsuper ) subsuperop = oneOf(["_", "^"]) subsuper << Group( ( Optional(placeable) + OneOrMore( subsuperop - placeable ) ) | placeable ) ambiDelim = oneOf(list(self._ambiDelim)) leftDelim = oneOf(list(self._leftDelim)) rightDelim = oneOf(list(self._rightDelim)) autoDelim <<(Suppress(Literal(r"\left")) + ((leftDelim | ambiDelim) | Error("Expected a delimiter")) + Group( autoDelim ^ OneOrMore(simple)) + Suppress(Literal(r"\right")) + ((rightDelim | ambiDelim) | Error("Expected a delimiter")) ) math = OneOrMore( autoDelim ^ simple ).setParseAction(self.math).setName("math") math_delim = ~bslash + Literal('$') non_math = Regex(r"(?:(?:\\[$])|[^$])*" ).setParseAction(self.non_math).setName("non_math").leaveWhitespace() self._expression << ( non_math + ZeroOrMore( Suppress(math_delim) + Optional(math) + (Suppress(math_delim) | Error("Expected end of math '$'")) + non_math ) ) + StringEnd() self.clear() def clear(self): """ Clear any state before parsing. """ self._expr = None self._state_stack = None self._em_width_cache = {} def parse(self, s, fonts_object, fontsize, dpi): """ Parse expression *s* using the given *fonts_object* for output, at the given *fontsize* and *dpi*. Returns the parse tree of :class:`Node` instances. """ self._state_stack = [self.State(fonts_object, 'default', 'rm', fontsize, dpi)] try: self._expression.parseString(s) except ParseException, err: raise ValueError("\n".join([ "", err.line, " " * (err.column - 1) + "^", str(err)])) return self._expr # The state of the parser is maintained in a stack. Upon # entering and leaving a group { } or math/non-math, the stack # is pushed and popped accordingly. The current state always # exists in the top element of the stack. class State(object): """ Stores the state of the parser. States are pushed and popped from a stack as necessary, and the "current" state is always at the top of the stack. """ def __init__(self, font_output, font, font_class, fontsize, dpi): self.font_output = font_output self._font = font self.font_class = font_class self.fontsize = fontsize self.dpi = dpi def copy(self): return Parser.State( self.font_output, self.font, self.font_class, self.fontsize, self.dpi) def _get_font(self): return self._font def _set_font(self, name): if name in ('it', 'rm', 'bf'): self.font_class = name self._font = name font = property(_get_font, _set_font) def get_state(self): """ Get the current :class:`State` of the parser. """ return self._state_stack[-1] def pop_state(self): """ Pop a :class:`State` off of the stack. """ self._state_stack.pop() def push_state(self): """ Push a new :class:`State` onto the stack which is just a copy of the current state. """ self._state_stack.append(self.get_state().copy()) def finish(self, s, loc, toks): #~ print "finish", toks self._expr = Hlist(toks) return [self._expr] def math(self, s, loc, toks): #~ print "math", toks hlist = Hlist(toks) self.pop_state() return [hlist] def non_math(self, s, loc, toks): #~ print "non_math", toks s = toks[0].replace(r'\$', '$') symbols = [Char(c, self.get_state()) for c in s] hlist = Hlist(symbols) # We're going into math now, so set font to 'it' self.push_state() self.get_state().font = 'it' return [hlist] def _make_space(self, percentage): # All spaces are relative to em width state = self.get_state() key = (state.font, state.fontsize, state.dpi) width = self._em_width_cache.get(key) if width is None: metrics = state.font_output.get_metrics( state.font, 'it', 'm', state.fontsize, state.dpi) width = metrics.advance self._em_width_cache[key] = width return Kern(width * percentage) _space_widths = { r'\ ' : 0.3, r'\,' : 0.4, r'\;' : 0.8, r'\quad' : 1.6, r'\qquad' : 3.2, r'\!' : -0.4, r'\/' : 0.4 } def space(self, s, loc, toks): assert(len(toks)==1) num = self._space_widths[toks[0]] box = self._make_space(num) return [box] def customspace(self, s, loc, toks): return [self._make_space(float(toks[1]))] def symbol(self, s, loc, toks): # print "symbol", toks c = toks[0] try: char = Char(c, self.get_state()) except ValueError: raise ParseFatalException("Unknown symbol: %s" % c) if c in self._spaced_symbols: return [Hlist( [self._make_space(0.2), char, self._make_space(0.2)] , do_kern = False)] elif c in self._punctuation_symbols: return [Hlist( [char, self._make_space(0.2)] , do_kern = False)] return [char] _char_over_chars = { # The first 2 entires in the tuple are (font, char, sizescale) for # the two symbols under and over. The third element is the space # (in multiples of underline height) r'AA' : ( ('rm', 'A', 1.0), (None, '\circ', 0.5), 0.0), } def char_over_chars(self, s, loc, toks): sym = toks[0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) under_desc, over_desc, space = \ self._char_over_chars.get(sym, (None, None, 0.0)) if under_desc is None: raise ParseFatalException("Error parsing symbol") over_state = state.copy() if over_desc[0] is not None: over_state.font = over_desc[0] over_state.fontsize *= over_desc[2] over = Accent(over_desc[1], over_state) under_state = state.copy() if under_desc[0] is not None: under_state.font = under_desc[0] under_state.fontsize *= under_desc[2] under = Char(under_desc[1], under_state) width = max(over.width, under.width) over_centered = HCentered([over]) over_centered.hpack(width, 'exactly') under_centered = HCentered([under]) under_centered.hpack(width, 'exactly') return Vlist([ over_centered, Vbox(0., thickness * space), under_centered ]) _accent_map = { r'hat' : r'\circumflexaccent', r'breve' : r'\combiningbreve', r'bar' : r'\combiningoverline', r'grave' : r'\combininggraveaccent', r'acute' : r'\combiningacuteaccent', r'ddot' : r'\combiningdiaeresis', r'tilde' : r'\combiningtilde', r'dot' : r'\combiningdotabove', r'vec' : r'\combiningrightarrowabove', r'"' : r'\combiningdiaeresis', r"`" : r'\combininggraveaccent', r"'" : r'\combiningacuteaccent', r'~' : r'\combiningtilde', r'.' : r'\combiningdotabove', r'^' : r'\circumflexaccent' } _wide_accents = set(r"widehat widetilde".split()) def accent(self, s, loc, toks): assert(len(toks)==1) state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) if len(toks[0]) != 2: raise ParseFatalException("Error parsing accent") accent, sym = toks[0] if accent in self._wide_accents: accent = AutoWidthChar( '\\' + accent, sym.width, state, char_class=Accent) else: accent = Accent(self._accent_map[accent], state) centered = HCentered([accent]) centered.hpack(sym.width, 'exactly') return Vlist([ centered, Vbox(0., thickness * 2.0), Hlist([sym]) ]) def function(self, s, loc, toks): #~ print "function", toks self.push_state() state = self.get_state() state.font = 'rm' hlist = Hlist([Char(c, state) for c in toks[0]]) self.pop_state() hlist.function_name = toks[0] return hlist def start_group(self, s, loc, toks): self.push_state() # Deal with LaTeX-style font tokens if len(toks): self.get_state().font = toks[0][4:] return [] def group(self, s, loc, toks): grp = Hlist(toks[0]) return [grp] def end_group(self, s, loc, toks): self.pop_state() return [] def font(self, s, loc, toks): assert(len(toks)==1) name = toks[0] self.get_state().font = name return [] def is_overunder(self, nucleus): if isinstance(nucleus, Char): return nucleus.c in self._overunder_symbols elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'): return nucleus.function_name in self._overunder_functions return False def is_dropsub(self, nucleus): if isinstance(nucleus, Char): return nucleus.c in self._dropsub_symbols return False def is_slanted(self, nucleus): if isinstance(nucleus, Char): return nucleus.is_slanted() return False def subsuperscript(self, s, loc, toks): assert(len(toks)==1) # print 'subsuperscript', toks nucleus = None sub = None super = None if len(toks[0]) == 1: return toks[0].asList() elif len(toks[0]) == 2: op, next = toks[0] nucleus = Hbox(0.0) if op == '_': sub = next else: super = next elif len(toks[0]) == 3: nucleus, op, next = toks[0] if op == '_': sub = next else: super = next elif len(toks[0]) == 5: nucleus, op1, next1, op2, next2 = toks[0] if op1 == op2: if op1 == '_': raise ParseFatalException("Double subscript") else: raise ParseFatalException("Double superscript") if op1 == '_': sub = next1 super = next2 else: super = next1 sub = next2 else: raise ParseFatalException( "Subscript/superscript sequence is too long. " "Use braces { } to remove ambiguity.") state = self.get_state() rule_thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) xHeight = state.font_output.get_xheight( state.font, state.fontsize, state.dpi) # Handle over/under symbols, such as sum or integral if self.is_overunder(nucleus): vlist = [] shift = 0. width = nucleus.width if super is not None: super.shrink() width = max(width, super.width) if sub is not None: sub.shrink() width = max(width, sub.width) if super is not None: hlist = HCentered([super]) hlist.hpack(width, 'exactly') vlist.extend([hlist, Kern(rule_thickness * 3.0)]) hlist = HCentered([nucleus]) hlist.hpack(width, 'exactly') vlist.append(hlist) if sub is not None: hlist = HCentered([sub]) hlist.hpack(width, 'exactly') vlist.extend([Kern(rule_thickness * 3.0), hlist]) shift = hlist.height + hlist.depth + rule_thickness * 2.0 vlist = Vlist(vlist) vlist.shift_amount = shift + nucleus.depth * 0.5 result = Hlist([vlist]) return [result] # Handle regular sub/superscripts shift_up = nucleus.height - SUBDROP * xHeight if self.is_dropsub(nucleus): shift_down = nucleus.depth + SUBDROP * xHeight else: shift_down = SUBDROP * xHeight if super is None: # node757 sub.shrink() x = Hlist([sub]) # x.width += SCRIPT_SPACE * xHeight shift_down = max(shift_down, SUB1) clr = x.height - (abs(xHeight * 4.0) / 5.0) shift_down = max(shift_down, clr) x.shift_amount = shift_down else: super.shrink() x = Hlist([super, Kern(SCRIPT_SPACE * xHeight)]) # x.width += SCRIPT_SPACE * xHeight clr = SUP1 * xHeight shift_up = max(shift_up, clr) clr = x.depth + (abs(xHeight) / 4.0) shift_up = max(shift_up, clr) if sub is None: x.shift_amount = -shift_up else: # Both sub and superscript sub.shrink() y = Hlist([sub]) # y.width += SCRIPT_SPACE * xHeight shift_down = max(shift_down, SUB1 * xHeight) clr = (2.0 * rule_thickness - ((shift_up - x.depth) - (y.height - shift_down))) if clr > 0.: shift_up += clr shift_down += clr if self.is_slanted(nucleus): x.shift_amount = DELTA * (shift_up + shift_down) x = Vlist([x, Kern((shift_up - x.depth) - (y.height - shift_down)), y]) x.shift_amount = shift_down result = Hlist([nucleus, x]) return [result] def frac(self, s, loc, toks): assert(len(toks)==1) assert(len(toks[0])==2) state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) num, den = toks[0] num.shrink() den.shrink() cnum = HCentered([num]) cden = HCentered([den]) width = max(num.width, den.width) + thickness * 10. cnum.hpack(width, 'exactly') cden.hpack(width, 'exactly') vlist = Vlist([cnum, # numerator Vbox(0, thickness * 2.0), # space Hrule(state), # rule Vbox(0, thickness * 4.0), # space cden # denominator ]) # Shift so the fraction line sits in the middle of the # equals sign metrics = state.font_output.get_metrics( state.font, 'it', '=', state.fontsize, state.dpi) shift = (cden.height - ((metrics.ymax + metrics.ymin) / 2 - thickness * 3.0)) vlist.shift_amount = shift hlist = Hlist([vlist, Hbox(thickness * 2.)]) return [hlist] def sqrt(self, s, loc, toks): #~ print "sqrt", toks root, body = toks[0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) # Determine the height of the body, and add a little extra to # the height so it doesn't seem cramped height = body.height - body.shift_amount + thickness * 5.0 depth = body.depth + body.shift_amount check = AutoHeightChar(r'\__sqrt__', height, depth, state, always=True) height = check.height - check.shift_amount depth = check.depth + check.shift_amount # Put a little extra space to the left and right of the body padded_body = Hlist([Hbox(thickness * 2.0), body, Hbox(thickness * 2.0)]) rightside = Vlist([Hrule(state), Fill(), padded_body]) # Stretch the glue between the hrule and the body rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), depth, 'exactly') # Add the root and shift it upward so it is above the tick. # The value of 0.6 is a hard-coded hack ;) if root is None: root = Box(check.width * 0.5, 0., 0.) else: root = Hlist([Char(x, state) for x in root]) root.shrink() root.shrink() root_vlist = Vlist([Hlist([root])]) root_vlist.shift_amount = -height * 0.6 hlist = Hlist([root_vlist, # Root # Negative kerning to put root over tick Kern(-check.width * 0.5), check, # Check rightside]) # Body return [hlist] def auto_sized_delimiter(self, s, loc, toks): #~ print "auto_sized_delimiter", toks front, middle, back = toks state = self.get_state() height = max([x.height for x in middle]) depth = max([x.depth for x in middle]) parts = [] # \left. and \right. aren't supposed to produce any symbols if front != '.': parts.append(AutoHeightChar(front, height, depth, state)) parts.extend(middle.asList()) if back != '.': parts.append(AutoHeightChar(back, height, depth, state)) hlist = Hlist(parts) return hlist ### ############################################################################## # MAIN class MathTextParser(object): _parser = None _backend_mapping = { 'bitmap': MathtextBackendBitmap, 'agg' : MathtextBackendAgg, 'ps' : MathtextBackendPs, 'pdf' : MathtextBackendPdf, 'svg' : MathtextBackendSvg, 'cairo' : MathtextBackendCairo, 'macosx': MathtextBackendAgg, } _font_type_mapping = { 'cm' : BakomaFonts, 'stix' : StixFonts, 'stixsans' : StixSansFonts, 'custom' : UnicodeFonts } def __init__(self, output): """ Create a MathTextParser for the given backend *output*. """ self._output = output.lower() self._cache = maxdict(50) def parse(self, s, dpi = 72, prop = None): """ Parse the given math expression *s* at the given *dpi*. If *prop* is provided, it is a :class:`~matplotlib.font_manager.FontProperties` object specifying the "default" font to use in the math expression, used for all non-math text. The results are cached, so multiple calls to :meth:`parse` with the same expression should be fast. """ if prop is None: prop = FontProperties() cacheKey = (s, dpi, hash(prop)) result = self._cache.get(cacheKey) if result is not None: return result if self._output == 'ps' and rcParams['ps.useafm']: font_output = StandardPsFonts(prop) else: backend = self._backend_mapping[self._output]() fontset = rcParams['mathtext.fontset'] fontset_class = self._font_type_mapping.get(fontset.lower()) if fontset_class is not None: font_output = fontset_class(prop, backend) else: raise ValueError( "mathtext.fontset must be either 'cm', 'stix', " "'stixsans', or 'custom'") fontsize = prop.get_size_in_points() # This is a class variable so we don't rebuild the parser # with each request. if self._parser is None: self.__class__._parser = Parser() box = self._parser.parse(s, font_output, fontsize, dpi) font_output.set_canvas_size(box.width, box.height, box.depth) result = font_output.get_results(box) self._cache[cacheKey] = result # Free up the transient data structures self._parser.clear() # Fix cyclical references font_output.destroy() font_output.mathtext_backend.fonts_object = None font_output.mathtext_backend = None return result def to_mask(self, texstr, dpi=120, fontsize=14): """ *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels. """ assert(self._output=="bitmap") prop = FontProperties(size=fontsize) ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) x = ftimage.as_array() return x, depth def to_rgba(self, texstr, color='black', dpi=120, fontsize=14): """ *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *color* Any matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels. """ x, depth = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) r, g, b = mcolors.colorConverter.to_rgb(color) RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8) RGBA[:,:,0] = int(255*r) RGBA[:,:,1] = int(255*g) RGBA[:,:,2] = int(255*b) RGBA[:,:,3] = x return RGBA, depth def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14): """ Writes a tex expression to a PNG file. Returns the offset of the baseline from the bottom of the image in pixels. *filename* A writable filename or fileobject *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *color* A valid matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns the offset of the baseline from the bottom of the image in pixels. """ rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) numrows, numcols, tmp = rgba.shape _png.write_png(rgba.tostring(), numcols, numrows, filename) return depth def get_depth(self, texstr, dpi=120, fontsize=14): """ Returns the offset of the baseline from the bottom of the image in pixels. *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *dpi* The dots-per-inch to render the text *fontsize* The font size in points """ assert(self._output=="bitmap") prop = FontProperties(size=fontsize) ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) return depth
gpl-3.0
beepee14/scikit-learn
sklearn/ensemble/tests/test_bagging.py
72
25573
""" Testing for the bagging ensemble module (sklearn.ensemble.bagging). """ # Author: Gilles Louppe # License: BSD 3 clause import numpy as np from sklearn.base import BaseEstimator from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_warns from sklearn.utils.testing import assert_warns_message from sklearn.dummy import DummyClassifier, DummyRegressor from sklearn.grid_search import GridSearchCV, ParameterGrid from sklearn.ensemble import BaggingClassifier, BaggingRegressor from sklearn.linear_model import Perceptron, LogisticRegression from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.svm import SVC, SVR from sklearn.pipeline import make_pipeline from sklearn.feature_selection import SelectKBest from sklearn.cross_validation import train_test_split from sklearn.datasets import load_boston, load_iris, make_hastie_10_2 from sklearn.utils import check_random_state from scipy.sparse import csc_matrix, csr_matrix rng = check_random_state(0) # also load the iris dataset # and randomly permute it iris = load_iris() perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # also load the boston dataset # and randomly permute it boston = load_boston() perm = rng.permutation(boston.target.size) boston.data = boston.data[perm] boston.target = boston.target[perm] def test_classification(): # Check classification for various parameter settings. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "max_features": [1, 2, 4], "bootstrap": [True, False], "bootstrap_features": [True, False]}) for base_estimator in [None, DummyClassifier(), Perceptron(), DecisionTreeClassifier(), KNeighborsClassifier(), SVC()]: for params in grid: BaggingClassifier(base_estimator=base_estimator, random_state=rng, **params).fit(X_train, y_train).predict(X_test) def test_sparse_classification(): # Check classification for various parameter settings on sparse input. class CustomSVC(SVC): """SVC variant that records the nature of the training set""" def fit(self, X, y): super(CustomSVC, self).fit(X, y) self.data_type_ = type(X) return self rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) parameter_sets = [ {"max_samples": 0.5, "max_features": 2, "bootstrap": True, "bootstrap_features": True}, {"max_samples": 1.0, "max_features": 4, "bootstrap": True, "bootstrap_features": True}, {"max_features": 2, "bootstrap": False, "bootstrap_features": True}, {"max_samples": 0.5, "bootstrap": True, "bootstrap_features": False}, ] for sparse_format in [csc_matrix, csr_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) for params in parameter_sets: for f in ['predict', 'predict_proba', 'predict_log_proba', 'decision_function']: # Trained on sparse format sparse_classifier = BaggingClassifier( base_estimator=CustomSVC(), random_state=1, **params ).fit(X_train_sparse, y_train) sparse_results = getattr(sparse_classifier, f)(X_test_sparse) # Trained on dense format dense_classifier = BaggingClassifier( base_estimator=CustomSVC(), random_state=1, **params ).fit(X_train, y_train) dense_results = getattr(dense_classifier, f)(X_test) assert_array_equal(sparse_results, dense_results) sparse_type = type(X_train_sparse) types = [i.data_type_ for i in sparse_classifier.estimators_] assert all([t == sparse_type for t in types]) def test_regression(): # Check regression for various parameter settings. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data[:50], boston.target[:50], random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "max_features": [0.5, 1.0], "bootstrap": [True, False], "bootstrap_features": [True, False]}) for base_estimator in [None, DummyRegressor(), DecisionTreeRegressor(), KNeighborsRegressor(), SVR()]: for params in grid: BaggingRegressor(base_estimator=base_estimator, random_state=rng, **params).fit(X_train, y_train).predict(X_test) def test_sparse_regression(): # Check regression for various parameter settings on sparse input. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data[:50], boston.target[:50], random_state=rng) class CustomSVR(SVR): """SVC variant that records the nature of the training set""" def fit(self, X, y): super(CustomSVR, self).fit(X, y) self.data_type_ = type(X) return self parameter_sets = [ {"max_samples": 0.5, "max_features": 2, "bootstrap": True, "bootstrap_features": True}, {"max_samples": 1.0, "max_features": 4, "bootstrap": True, "bootstrap_features": True}, {"max_features": 2, "bootstrap": False, "bootstrap_features": True}, {"max_samples": 0.5, "bootstrap": True, "bootstrap_features": False}, ] for sparse_format in [csc_matrix, csr_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) for params in parameter_sets: # Trained on sparse format sparse_classifier = BaggingRegressor( base_estimator=CustomSVR(), random_state=1, **params ).fit(X_train_sparse, y_train) sparse_results = sparse_classifier.predict(X_test_sparse) # Trained on dense format dense_results = BaggingRegressor( base_estimator=CustomSVR(), random_state=1, **params ).fit(X_train, y_train).predict(X_test) sparse_type = type(X_train_sparse) types = [i.data_type_ for i in sparse_classifier.estimators_] assert_array_equal(sparse_results, dense_results) assert all([t == sparse_type for t in types]) assert_array_equal(sparse_results, dense_results) def test_bootstrap_samples(): # Test that bootstraping samples generate non-perfect base estimators. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) base_estimator = DecisionTreeRegressor().fit(X_train, y_train) # without bootstrap, all trees are perfect on the training set ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_samples=1.0, bootstrap=False, random_state=rng).fit(X_train, y_train) assert_equal(base_estimator.score(X_train, y_train), ensemble.score(X_train, y_train)) # with bootstrap, trees are no longer perfect on the training set ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_samples=1.0, bootstrap=True, random_state=rng).fit(X_train, y_train) assert_greater(base_estimator.score(X_train, y_train), ensemble.score(X_train, y_train)) def test_bootstrap_features(): # Test that bootstraping features may generate dupplicate features. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_features=1.0, bootstrap_features=False, random_state=rng).fit(X_train, y_train) for features in ensemble.estimators_features_: assert_equal(boston.data.shape[1], np.unique(features).shape[0]) ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), max_features=1.0, bootstrap_features=True, random_state=rng).fit(X_train, y_train) for features in ensemble.estimators_features_: assert_greater(boston.data.shape[1], np.unique(features).shape[0]) def test_probability(): # Predict probabilities. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) with np.errstate(divide="ignore", invalid="ignore"): # Normal case ensemble = BaggingClassifier(base_estimator=DecisionTreeClassifier(), random_state=rng).fit(X_train, y_train) assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test), axis=1), np.ones(len(X_test))) assert_array_almost_equal(ensemble.predict_proba(X_test), np.exp(ensemble.predict_log_proba(X_test))) # Degenerate case, where some classes are missing ensemble = BaggingClassifier(base_estimator=LogisticRegression(), random_state=rng, max_samples=5).fit(X_train, y_train) assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test), axis=1), np.ones(len(X_test))) assert_array_almost_equal(ensemble.predict_proba(X_test), np.exp(ensemble.predict_log_proba(X_test))) def test_oob_score_classification(): # Check that oob prediction is a good estimation of the generalization # error. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) for base_estimator in [DecisionTreeClassifier(), SVC()]: clf = BaggingClassifier(base_estimator=base_estimator, n_estimators=100, bootstrap=True, oob_score=True, random_state=rng).fit(X_train, y_train) test_score = clf.score(X_test, y_test) assert_less(abs(test_score - clf.oob_score_), 0.1) # Test with few estimators assert_warns(UserWarning, BaggingClassifier(base_estimator=base_estimator, n_estimators=1, bootstrap=True, oob_score=True, random_state=rng).fit, X_train, y_train) def test_oob_score_regression(): # Check that oob prediction is a good estimation of the generalization # error. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) clf = BaggingRegressor(base_estimator=DecisionTreeRegressor(), n_estimators=50, bootstrap=True, oob_score=True, random_state=rng).fit(X_train, y_train) test_score = clf.score(X_test, y_test) assert_less(abs(test_score - clf.oob_score_), 0.1) # Test with few estimators assert_warns(UserWarning, BaggingRegressor(base_estimator=DecisionTreeRegressor(), n_estimators=1, bootstrap=True, oob_score=True, random_state=rng).fit, X_train, y_train) def test_single_estimator(): # Check singleton ensembles. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) clf1 = BaggingRegressor(base_estimator=KNeighborsRegressor(), n_estimators=1, bootstrap=False, bootstrap_features=False, random_state=rng).fit(X_train, y_train) clf2 = KNeighborsRegressor().fit(X_train, y_train) assert_array_equal(clf1.predict(X_test), clf2.predict(X_test)) def test_error(): # Test that it gives proper exception on deficient input. X, y = iris.data, iris.target base = DecisionTreeClassifier() # Test max_samples assert_raises(ValueError, BaggingClassifier(base, max_samples=-1).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples=0.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples=2.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples=1000).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_samples="foobar").fit, X, y) # Test max_features assert_raises(ValueError, BaggingClassifier(base, max_features=-1).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features=0.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features=2.0).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features=5).fit, X, y) assert_raises(ValueError, BaggingClassifier(base, max_features="foobar").fit, X, y) # Test support of decision_function assert_false(hasattr(BaggingClassifier(base).fit(X, y), 'decision_function')) def test_parallel_classification(): # Check parallel classification. rng = check_random_state(0) # Classification X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) ensemble = BaggingClassifier(DecisionTreeClassifier(), n_jobs=3, random_state=0).fit(X_train, y_train) # predict_proba ensemble.set_params(n_jobs=1) y1 = ensemble.predict_proba(X_test) ensemble.set_params(n_jobs=2) y2 = ensemble.predict_proba(X_test) assert_array_almost_equal(y1, y2) ensemble = BaggingClassifier(DecisionTreeClassifier(), n_jobs=1, random_state=0).fit(X_train, y_train) y3 = ensemble.predict_proba(X_test) assert_array_almost_equal(y1, y3) # decision_function ensemble = BaggingClassifier(SVC(), n_jobs=3, random_state=0).fit(X_train, y_train) ensemble.set_params(n_jobs=1) decisions1 = ensemble.decision_function(X_test) ensemble.set_params(n_jobs=2) decisions2 = ensemble.decision_function(X_test) assert_array_almost_equal(decisions1, decisions2) ensemble = BaggingClassifier(SVC(), n_jobs=1, random_state=0).fit(X_train, y_train) decisions3 = ensemble.decision_function(X_test) assert_array_almost_equal(decisions1, decisions3) def test_parallel_regression(): # Check parallel regression. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) ensemble = BaggingRegressor(DecisionTreeRegressor(), n_jobs=3, random_state=0).fit(X_train, y_train) ensemble.set_params(n_jobs=1) y1 = ensemble.predict(X_test) ensemble.set_params(n_jobs=2) y2 = ensemble.predict(X_test) assert_array_almost_equal(y1, y2) ensemble = BaggingRegressor(DecisionTreeRegressor(), n_jobs=1, random_state=0).fit(X_train, y_train) y3 = ensemble.predict(X_test) assert_array_almost_equal(y1, y3) def test_gridsearch(): # Check that bagging ensembles can be grid-searched. # Transform iris into a binary classification task X, y = iris.data, iris.target y[y == 2] = 1 # Grid search with scoring based on decision_function parameters = {'n_estimators': (1, 2), 'base_estimator__C': (1, 2)} GridSearchCV(BaggingClassifier(SVC()), parameters, scoring="roc_auc").fit(X, y) def test_base_estimator(): # Check base_estimator and its default values. rng = check_random_state(0) # Classification X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=rng) ensemble = BaggingClassifier(None, n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier)) ensemble = BaggingClassifier(DecisionTreeClassifier(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier)) ensemble = BaggingClassifier(Perceptron(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, Perceptron)) # Regression X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) ensemble = BaggingRegressor(None, n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor)) ensemble = BaggingRegressor(DecisionTreeRegressor(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor)) ensemble = BaggingRegressor(SVR(), n_jobs=3, random_state=0).fit(X_train, y_train) assert_true(isinstance(ensemble.base_estimator_, SVR)) def test_bagging_with_pipeline(): estimator = BaggingClassifier(make_pipeline(SelectKBest(k=1), DecisionTreeClassifier()), max_features=2) estimator.fit(iris.data, iris.target) class DummyZeroEstimator(BaseEstimator): def fit(self, X, y): self.classes_ = np.unique(y) return self def predict(self, X): return self.classes_[np.zeros(X.shape[0], dtype=int)] def test_bagging_sample_weight_unsupported_but_passed(): estimator = BaggingClassifier(DummyZeroEstimator()) rng = check_random_state(0) estimator.fit(iris.data, iris.target).predict(iris.data) assert_raises(ValueError, estimator.fit, iris.data, iris.target, sample_weight=rng.randint(10, size=(iris.data.shape[0]))) def test_warm_start(random_state=42): # Test if fitting incrementally with warm start gives a forest of the # right size and the same results as a normal fit. X, y = make_hastie_10_2(n_samples=20, random_state=1) clf_ws = None for n_estimators in [5, 10]: if clf_ws is None: clf_ws = BaggingClassifier(n_estimators=n_estimators, random_state=random_state, warm_start=True) else: clf_ws.set_params(n_estimators=n_estimators) clf_ws.fit(X, y) assert_equal(len(clf_ws), n_estimators) clf_no_ws = BaggingClassifier(n_estimators=10, random_state=random_state, warm_start=False) clf_no_ws.fit(X, y) assert_equal(set([tree.random_state for tree in clf_ws]), set([tree.random_state for tree in clf_no_ws])) def test_warm_start_smaller_n_estimators(): # Test if warm start'ed second fit with smaller n_estimators raises error. X, y = make_hastie_10_2(n_samples=20, random_state=1) clf = BaggingClassifier(n_estimators=5, warm_start=True) clf.fit(X, y) clf.set_params(n_estimators=4) assert_raises(ValueError, clf.fit, X, y) def test_warm_start_equal_n_estimators(): # Test that nothing happens when fitting without increasing n_estimators X, y = make_hastie_10_2(n_samples=20, random_state=1) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=43) clf = BaggingClassifier(n_estimators=5, warm_start=True, random_state=83) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) # modify X to nonsense values, this should not change anything X_train += 1. assert_warns_message(UserWarning, "Warm-start fitting without increasing n_estimators does not", clf.fit, X_train, y_train) assert_array_equal(y_pred, clf.predict(X_test)) def test_warm_start_equivalence(): # warm started classifier with 5+5 estimators should be equivalent to # one classifier with 10 estimators X, y = make_hastie_10_2(n_samples=20, random_state=1) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=43) clf_ws = BaggingClassifier(n_estimators=5, warm_start=True, random_state=3141) clf_ws.fit(X_train, y_train) clf_ws.set_params(n_estimators=10) clf_ws.fit(X_train, y_train) y1 = clf_ws.predict(X_test) clf = BaggingClassifier(n_estimators=10, warm_start=False, random_state=3141) clf.fit(X_train, y_train) y2 = clf.predict(X_test) assert_array_almost_equal(y1, y2) def test_warm_start_with_oob_score_fails(): # Check using oob_score and warm_start simultaneously fails X, y = make_hastie_10_2(n_samples=20, random_state=1) clf = BaggingClassifier(n_estimators=5, warm_start=True, oob_score=True) assert_raises(ValueError, clf.fit, X, y) def test_oob_score_removed_on_warm_start(): X, y = make_hastie_10_2(n_samples=2000, random_state=1) clf = BaggingClassifier(n_estimators=50, oob_score=True) clf.fit(X, y) clf.set_params(warm_start=True, oob_score=False, n_estimators=100) clf.fit(X, y) assert_raises(AttributeError, getattr, clf, "oob_score_")
bsd-3-clause
deeplycloudy/MetPy
metpy/plots/_mpl.py
1
13169
'This module fills in for functionality that we have (or will) upstreamed into matplotlib' # Copyright (c) 2008-2015 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause # See if we should monkey-patch Barbs for better pivot import matplotlib if float(matplotlib.__version__[:3]) < 2.1: import numpy as np from numpy import ma import matplotlib.transforms as transforms from matplotlib.patches import CirclePolygon from matplotlib.quiver import Barbs def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length, pivot, sizes, fill_empty, flip): 'Monkey-patched version of _make_barbs. Allows pivot to be a float value.' # These control the spacing and size of barb elements relative to the # length of the shaft spacing = length * sizes.get('spacing', 0.125) full_height = length * sizes.get('height', 0.4) full_width = length * sizes.get('width', 0.25) empty_rad = length * sizes.get('emptybarb', 0.15) # Controls y point where to pivot the barb. pivot_points = dict(tip=0.0, middle=-length / 2.) # Check for flip if flip: full_height = -full_height endx = 0.0 try: endy = float(pivot) except ValueError: endy = pivot_points[pivot.lower()] # Get the appropriate angle for the vector components. The offset is # due to the way the barb is initially drawn, going down the y-axis. # This makes sense in a meteorological mode of thinking since there 0 # degrees corresponds to north (the y-axis traditionally) angles = -(ma.arctan2(v, u) + np.pi / 2) # Used for low magnitude. We just get the vertices, so if we make it # out here, it can be reused. The center set here should put the # center of the circle at the location(offset), rather than at the # same point as the barb pivot; this seems more sensible. circ = CirclePolygon((0, 0), radius=empty_rad).get_verts() if fill_empty: empty_barb = circ else: # If we don't want the empty one filled, we make a degenerate # polygon that wraps back over itself empty_barb = np.concatenate((circ, circ[::-1])) barb_list = [] for index, angle in np.ndenumerate(angles): # If the vector magnitude is too weak to draw anything, plot an # empty circle instead if empty_flag[index]: # We can skip the transform since the circle has no preferred # orientation barb_list.append(empty_barb) continue poly_verts = [(endx, endy)] offset = length # Add vertices for each flag for i in range(nflags[index]): # The spacing that works for the barbs is a little to much for # the flags, but this only occurs when we have more than 1 # flag. if offset != length: offset += spacing / 2. poly_verts.extend( [[endx, endy + offset], [endx + full_height, endy - full_width / 2 + offset], [endx, endy - full_width + offset]]) offset -= full_width + spacing # Add vertices for each barb. These really are lines, but works # great adding 3 vertices that basically pull the polygon out and # back down the line for i in range(nbarbs[index]): poly_verts.extend( [(endx, endy + offset), (endx + full_height, endy + offset + full_width / 2), (endx, endy + offset)]) offset -= spacing # Add the vertices for half a barb, if needed if half_barb[index]: # If the half barb is the first on the staff, traditionally it # is offset from the end to make it easy to distinguish from a # barb with a full one if offset == length: poly_verts.append((endx, endy + offset)) offset -= 1.5 * spacing poly_verts.extend( [(endx, endy + offset), (endx + full_height / 2, endy + offset + full_width / 4), (endx, endy + offset)]) # Rotate the barb according the angle. Making the barb first and # then rotating it made the math for drawing the barb really easy. # Also, the transform framework makes doing the rotation simple. poly_verts = transforms.Affine2D().rotate(-angle).transform( poly_verts) barb_list.append(poly_verts) return barb_list # Replace existing method Barbs._make_barbs = _make_barbs # See if we need to patch in our own scattertext implementation from matplotlib.axes import Axes # noqa if not hasattr(Axes, 'scattertext'): import matplotlib.cbook as cbook import matplotlib.transforms as mtransforms from matplotlib import rcParams from matplotlib.artist import allow_rasterization from matplotlib.text import Text def scattertext(self, x, y, texts, loc=(0, 0), **kw): """ Add text to the axes. Add text in string `s` to axis at location `x`, `y`, data coordinates. Parameters ---------- x, y : array_like, shape (n, ) Input positions texts : array_like, shape (n, ) Collection of text that will be plotted at each (x,y) location loc : length-2 tuple Offset (in screen coordinates) from x,y position. Allows positioning text relative to original point. Other parameters ---------------- kwargs : `~matplotlib.text.TextCollection` properties. Other miscellaneous text parameters. Examples -------- Individual keyword arguments can be used to override any given parameter:: >>> scattertext(x, y, texts, fontsize=12) The default setting to to center the text at the specified x,y locations in data coordinates, and to take the data and format as float without any decimal places. The example below places the text above and to the right by 10 pixels, with 2 decimal places:: >>> scattertext([0.25, 0.75], [0.25, 0.75], [0.5, 1.0], ... loc=(10, 10)) """ # Start with default args and update from kw new_kw = { 'verticalalignment': 'center', 'horizontalalignment': 'center', 'transform': self.transData, 'clip_on': False} new_kw.update(kw) # Default to centered on point--special case it to keep transform # simpler. # t = new_kw['transform'] # if loc == (0, 0): # trans = t # else: # x0, y0 = loc # trans = t + mtransforms.Affine2D().translate(x0, y0) # new_kw['transform'] = trans # Handle masked arrays x, y, texts = cbook.delete_masked_points(x, y, texts) # If there is nothing left after deleting the masked points, return None if x.size == 0: return None # Make the TextCollection object text_obj = TextCollection(x, y, texts, offset=loc, **new_kw) # The margin adjustment is a hack to deal with the fact that we don't # want to transform all the symbols whose scales are in points # to data coords to get the exact bounding box for efficiency # reasons. It can be done right if this is deemed important. # Also, only bother with this padding if there is anything to draw. if self._xmargin < 0.05 and x.size > 0: self.set_xmargin(0.05) if self._ymargin < 0.05 and x.size > 0: self.set_ymargin(0.05) # Add it to the axes and update range self.add_artist(text_obj) self.update_datalim(text_obj.get_datalim(self.transData)) self.autoscale_view() return text_obj class TextCollection(Text): """Handles plotting a collection of text. Text Collection plots text with a collection of similar properties: font, color, and an offset relative to the x,y data location. """ def __init__(self, x, y, text, offset=(0, 0), **kwargs): Text.__init__(self, **kwargs) self.x = x self.y = y self.text = text self.offset = offset if not hasattr(self, '_usetex'): # Only needed for matplotlib 1.4 compatibility self._usetex = None def __str__(self): return "TextCollection" def get_datalim(self, transData): # noqa """Return the limits of the data. Parameters ---------- transData : matplotlib.transforms.Transform Returns ------- matplotlib.transforms.Bbox The bounding box of the data """ full_transform = self.get_transform() - transData XY = full_transform.transform(np.vstack((self.x, self.y)).T) # noqa bbox = transforms.Bbox.null() bbox.update_from_data_xy(XY, ignore=True) return bbox @allow_rasterization def draw(self, renderer): """ Draws the :class:`TextCollection` object to the given *renderer*. """ if renderer is not None: self._renderer = renderer if not self.get_visible(): return if not any(self.text): return renderer.open_group('text', self.get_gid()) trans = self.get_transform() if self.offset != (0, 0): scale = self.axes.figure.dpi / 72 xoff, yoff = self.offset trans += mtransforms.Affine2D().translate(scale * xoff, scale * yoff) posx = self.convert_xunits(self.x) posy = self.convert_yunits(self.y) pts = np.vstack((posx, posy)).T pts = trans.transform(pts) canvasw, canvash = renderer.get_canvas_width_height() gc = renderer.new_gc() gc.set_foreground(self.get_color()) gc.set_alpha(self.get_alpha()) gc.set_url(self._url) self._set_gc_clip(gc) angle = self.get_rotation() for (posx, posy), t in zip(pts, self.text): self._text = t # hack to allow self._get_layout to work bbox, info, descent = self._get_layout(renderer) self._text = '' for line, wh, x, y in info: mtext = self if len(info) == 1 else None x = x + posx y = y + posy if renderer.flipy(): y = canvash - y clean_line, ismath = self.is_math_text(line) if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer textrenderer = PathEffectRenderer( self.get_path_effects(), renderer) # noqa else: textrenderer = renderer if self.get_usetex(): textrenderer.draw_tex(gc, x, y, clean_line, self._fontproperties, angle, mtext=mtext) else: textrenderer.draw_text(gc, x, y, clean_line, self._fontproperties, angle, ismath=ismath, mtext=mtext) gc.restore() renderer.close_group('text') def set_usetex(self, usetex): """ Set this `Text` object to render using TeX (or not). If `None` is given, the option will be reset to use the value of `rcParams['text.usetex']` """ if usetex is None: self._usetex = None else: self._usetex = bool(usetex) self.stale = True def get_usetex(self): """ Return whether this `Text` object will render using TeX. If the user has not manually set this value, it will default to the value of `rcParams['text.usetex']` """ if self._usetex is None: return rcParams['text.usetex'] else: return self._usetex # Monkey-patch scattertext onto Axes Axes.scattertext = scattertext
bsd-3-clause
mayavanand/RMMAFinalProject
azimuth/predict.py
1
21358
import numpy as np import sklearn from sklearn.metrics import roc_curve, auc import sklearn.metrics import sklearn.cross_validation import copy import util import time import metrics as ranking_metrics import models.regression import models.ensembles import models.DNN import models.baselines import multiprocessing def fill_in_truth_and_predictions(truth, predictions, fold, y_all, y_pred, learn_options, test): truth[fold]['ranks'] = np.hstack((truth[fold]['ranks'], y_all[learn_options['rank-transformed target name']].values[test].flatten())) truth[fold]['thrs'] = np.hstack((truth[fold]['thrs'], y_all[learn_options['binary target name']].values[test].flatten())) if 'raw_target_name' in learn_options.keys(): truth[fold]['raw'] = np.hstack((truth[fold]['raw'], y_all[learn_options['raw target name']].values[test].flatten())) predictions[fold] = np.hstack((predictions[fold], y_pred.flatten())) return truth, predictions def construct_filename(learn_options, TEST): if learn_options.has_key("V"): filename = "V%s" % learn_options["V"] else: filename = "offV1" if TEST: filename = "TEST." filename += learn_options["method"] filename += '.order%d' % learn_options["order"] # try: # learn_options["target_name"] = ".%s" % learn_options["target_name"].split(" ")[1] # except: # pass filename += learn_options["target_name"] if learn_options["method"] == "GPy": pass # filename += ".R%d" % opt_options['num_restarts'] # filename += ".K%s" % learn_options['kerntype'] # if learn_options.has_key('degree'): # filename += "d%d" % learn_options['degree'] # if learn_options['warped']: # filename += ".Warp" elif learn_options["method"] == "linreg": filename += "." + learn_options["penalty"] filename += "." + learn_options["cv"] if learn_options["training_metric"] == "NDCG": filename += ".NDGC_%d" % learn_options["NDGC_k"] elif learn_options["training_metric"] == "AUC": filename += ".AUC" elif learn_options["training_metric"] == 'spearmanr': filename += ".spearman" print "filename = %s" % filename return filename def print_summary(global_metric, results, learn_options, feature_sets, flags): print "\nSummary:" print learn_options print "\t\tglobal %s=%.2f" % (learn_options['metric'], global_metric) print "\t\tmedian %s across folds=%.2f" % (learn_options['metric'], np.median(results[0])) print "\t\torder=%d" % learn_options["order"] if learn_options.has_key('kerntype'): "\t\tkern type = %s" % learn_options['kerntype'] if learn_options.has_key('degree'): print "\t\tdegree=%d" % learn_options['degree'] print "\t\ttarget_name=%s" % learn_options["target_name"] for k in flags.keys(): print '\t\t' + k + '=' + str(learn_options[k]) print "\t\tfeature set:" for set in feature_sets.keys(): print "\t\t\t%s" % set print "\t\ttotal # features=%d" % results[4] def extract_fpr_tpr_for_fold(aucs, fold, i, predictions, truth, y_binary, test, y_pred): assert len(np.unique(y_binary))<=2, "if using AUC need binary targets" fpr, tpr, _ = roc_curve(y_binary[test], y_pred) roc_auc = auc(fpr, tpr) aucs.append(roc_auc) def extract_NDCG_for_fold(metrics, fold, i, predictions, truth, y_ground_truth, test, y_pred, learn_options): NDCG_fold = ranking_metrics.ndcg_at_k_ties(y_ground_truth[test].flatten(), y_pred.flatten(), learn_options["NDGC_k"]) metrics.append(NDCG_fold) def extract_spearman_for_fold(metrics, fold, i, predictions, truth, y_ground_truth, test, y_pred, learn_options): spearman = util.spearmanr_nonan(y_ground_truth[test].flatten(), y_pred.flatten())[0] assert not np.isnan(spearman), "found nan spearman" metrics.append(spearman) def get_train_test(test_gene, y_all, train_genes=None): # this is a bit convoluted because the train_genes+test_genes may not add up to all genes # for e.g. when we load up V3, but then use only V2, etc. is_off_target = 'MutatedSequence' in y_all.index.names if is_off_target: train = (y_all.index.get_level_values('MutatedSequence').values != test_gene) test = None return train, test not_test = (y_all.index.get_level_values('Target gene').values != test_gene) if train_genes is not None: in_train_genes = np.zeros(not_test.shape, dtype=bool) for t_gene in train_genes: in_train_genes = np.logical_or(in_train_genes, (y_all.index.get_level_values('Target gene').values == t_gene)) train = np.logical_and(not_test, in_train_genes) else: train = not_test #y_all['test'] as to do with extra pairs in V2 test = (y_all.index.get_level_values('Target gene').values== test_gene) * (y_all['test'].values == 1.) # convert to indices test = np.where(test == True)[0] train = np.where(train == True)[0] return train, test def cross_validate(y_all, feature_sets, learn_options=None, TEST=False, train_genes=None, CV=True): ''' feature_sets is a dictionary of "set name" to pandas.DataFrame one set might be single-nucleotide, position-independent features of order X, for e.g. Method: "GPy" or "linreg" Metric: NDCG (learning to rank metric, Normalized Discounted Cumulative Gain); AUC Output: cv_score_median, gene_rocs When CV=False, it trains on everything (and tests on everything, just to fit the code) ''' print "range of y_all is [%f, %f]" % (np.min(y_all[learn_options['target_name']].values), np.max(y_all[learn_options['target_name']].values)) allowed_methods = ["GPy", "linreg", "AdaBoostRegressor", "AdaBoostClassifier", "DecisionTreeRegressor", "RandomForestRegressor", "ARDRegression", "GPy_fs", "mean", "random", "DNN", "lasso_ensemble", "doench", "logregL1", "sgrna_from_doench", 'SVC', 'xu_et_al'] assert learn_options["method"] in allowed_methods,"invalid method: %s" % learn_options["method"] assert learn_options["method"] == "linreg" and learn_options['penalty'] == 'L2' or learn_options["weighted"] is None, "weighted only works with linreg L2 right now" # construct filename from options filename = construct_filename(learn_options, TEST) print "Cross-validating genes..." t2 = time.time() y = np.array(y_all[learn_options["target_name"]].values[:,None],dtype=np.float64) # concatenate feature sets in to one nparray, and get dimension of each inputs, dim, dimsum, feature_names = util.concatenate_feature_sets(feature_sets) if not CV: assert learn_options['cv'] == 'gene', 'Must use gene-CV when CV is False (I need to use all of the genes and stratified complicates that)' # set-up for cross-validation ## for outer loop, the one Doench et al use genes for if learn_options["cv"] == "stratified": assert not learn_options.has_key("extra_pairs") or learn_options['extra pairs'], "can't use extra pairs with stratified CV, need to figure out how to properly account for genes affected by two drugs" label_encoder = sklearn.preprocessing.LabelEncoder() label_encoder.fit(y_all['Target gene'].values) gene_classes = label_encoder.transform(y_all['Target gene'].values) if 'n_folds' in learn_options.keys(): n_folds = learn_options['n_folds'] elif learn_options['train_genes'] is not None and learn_options["test_genes"] is not None: n_folds = len(learn_options["test_genes"]) else: n_folds = len(learn_options['all_genes']) cv = sklearn.cross_validation.StratifiedKFold(gene_classes, n_folds=n_folds, shuffle=True) fold_labels = ["fold%d" % i for i in range(1,n_folds+1)] if learn_options['num_genes_remove_train'] is not None: raise NotImplementedException() elif learn_options["cv"]=="gene": cv = [] if not CV: train_test_tmp = get_train_test('dummy', y_all) # get train, test split using a dummy gene train_tmp, test_tmp = train_test_tmp # not a typo, using training set to test on as well, just for this case. Test set is not used # for internal cross-val, etc. anyway. train_test_tmp = (train_tmp, train_tmp) cv.append(train_test_tmp) fold_labels = learn_options['all_genes'] elif learn_options['train_genes'] is not None and learn_options["test_genes"] is not None: assert learn_options['train_genes'] is not None and learn_options['test_genes'] is not None, "use both or neither" for i, gene in enumerate(learn_options['test_genes']): cv.append(get_train_test(gene, y_all, learn_options['train_genes'])) fold_labels = learn_options["test_genes"] # if train and test genes are seperate, there should be only one fold train_test_disjoint = set.isdisjoint(set(learn_options["train_genes"].tolist()), set(learn_options["test_genes"].tolist())) else: for i, gene in enumerate(learn_options['all_genes']): train_test_tmp = get_train_test(gene, y_all) cv.append(train_test_tmp) fold_labels = learn_options['all_genes'] if learn_options['num_genes_remove_train'] is not None: for i, (train,test) in enumerate(cv): unique_genes = np.random.permutation(np.unique(np.unique(y_all['Target gene'][train]))) genes_to_keep = unique_genes[0:len(unique_genes) - learn_options['num_genes_remove_train']] guides_to_keep = [] filtered_train = [] for j, gene in enumerate(y_all['Target gene']): if j in train and gene in genes_to_keep: filtered_train.append(j) cv_i_orig = copy.deepcopy(cv[i]) cv[i] = (filtered_train, test) if learn_options['num_genes_remove_train']==0: assert np.all(cv_i_orig[0]==cv[i][0]) assert np.all(cv_i_orig[1]==cv[i][1]) print "# train/train after/before is %s, %s" % (len(cv[i][0]), len(cv_i_orig[0])) print "# test/test after/before is %s, %s" % (len(cv[i][1]), len(cv_i_orig[1])) else: raise Exception("invalid cv options given: %s" % learn_options["cv"]) cv = [c for c in cv] #make list from generator, so can subset for TEST case if TEST: ind_to_use = [0]#[0,1] cv = [cv[i] for i in ind_to_use] fold_labels = [fold_labels[i] for i in ind_to_use] truth = dict([(t, dict([(m, np.array([])) for m in ['raw', 'ranks', 'thrs']])) for t in fold_labels]) predictions = dict([(t, np.array([])) for t in fold_labels]) m = {} metrics = [] #do the cross-validation num_proc = learn_options["num_proc"] if num_proc > 1: num_proc = np.min([num_proc,len(cv)]) print "using multiprocessing with %d procs--one for each fold" % num_proc jobs = [] pool = multiprocessing.Pool(processes=num_proc) for i,fold in enumerate(cv): train,test = fold print "working on fold %d of %d, with %d train and %d test" % (i, len(cv), len(train), len(test)) if learn_options["method"]=="GPy": job = pool.apply_async(models.GP.gp_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"]=="linreg": job = pool.apply_async(models.regression.linreg_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"]=="logregL1": job = pool.apply_async(models.regression.logreg_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"]=="AdaBoostRegressor": print "adaboostreg" job = pool.apply_async(models.ensembles.adaboost_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options, False)) elif learn_options["method"]=="AdaBoostClassifier": job = pool.apply_async(models.ensembles.adaboost_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options, True)) elif learn_options["method"]=="DecisionTreeRegressor": job = pool.apply_async(models.ensembles.decisiontree_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"]=="RandomForestRegressor": job = pool.apply_async(models.ensembles.randomforest_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"]=="ARDRegression": job = pool.apply_async(models.regression.ARDRegression_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "random": job = pool.apply_async(models.baselines.random_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "mean": job = pool.apply_async(models.baselines.mean_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "SVC": job = pool.apply_async(models.baselines.SVC_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "DNN": job = pool.apply_async(models.DNN.DNN_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "lasso_ensemble": job = pool.apply_async(models.ensembles.LASSOs_ensemble_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "doench": job = pool.apply_async(models.baselines.doench_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "sgrna_from_doench": job = pool.apply_async(models.baselines.sgrna_from_doench_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) elif learn_options["method"] == "xu_et_al": job = pool.apply_async(models.baselines.xu_et_al_on_fold, args=(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options)) else: raise Exception("did not find method=%s" % learn_options["method"]) jobs.append(job) pool.close() pool.join() for i,fold in enumerate(cv):#i in range(0,len(jobs)): y_pred, m[i] = jobs[i].get() train,test = fold if learn_options["training_metric"]=="AUC": extract_fpr_tpr_for_fold(metrics, fold_labels[i], i, predictions, truth, y_all[learn_options["ground_truth_label"]].values, test, y_pred) elif learn_options["training_metric"]=="NDCG": extract_NDCG_for_fold(metrics, fold_labels[i], i, predictions, truth, y_all[learn_options["ground_truth_label"]].values, test, y_pred, learn_options) elif learn_options["training_metric"] == 'spearmanr': extract_spearman_for_fold(metrics, fold_labels[i], i, predictions, truth, y_all[learn_options["ground_truth_label"]].values, test, y_pred, learn_options) else: raise Exception("invalid 'training_metric' in learn_options: %s" % learn_options["training_metric"]) truth, predictions = fill_in_truth_and_predictions(truth, predictions, fold_labels[i], y_all, y_pred, learn_options, test) pool.terminate() else: # non parallel version for i,fold in enumerate(cv): train,test = fold if learn_options["method"]=="GPy": y_pred, m[i] = gp_on_fold(models.GP.feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"]=="linreg": y_pred, m[i] = models.regression.linreg_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"]=="logregL1": y_pred, m[i] = models.regression.logreg_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"]=="AdaBoostRegressor": y_pred, m[i] = models.ensembles.adaboost_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options, classification=False) elif learn_options["method"]=="AdaBoostClassifier": y_pred, m[i] = models.ensembles.adaboost_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options, classification=True) elif learn_options["method"]=="DecisionTreeRegressor": y_pred, m[i] = models.ensembles.decisiontree_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"]=="RandomForestRegressor": y_pred, m[i] = models.ensembles.randomforest_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"]=="ARDRegression": y_pred, m[i] = models.regression.ARDRegression_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"]=="GPy_fs": y_pred, m[i] = models.GP.gp_with_fs_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "random": y_pred, m[i] = models.baselines.random_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "mean": y_pred, m[i] = models.baselines.mean_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "SVC": y_pred, m[i] = models.baselines.SVC_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "DNN": y_pred, m[i] = models.DNN.DNN_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "lasso_ensemble": y_pred, m[i] = models.ensembles.LASSOs_ensemble_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "doench": y_pred, m[i] = models.baselines.doench_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "sgrna_from_doench": y_pred, m[i] = models.baselines.sgrna_from_doench_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) elif learn_options["method"] == "xu_et_al": y_pred, m[i] = models.baselines.xu_et_al_on_fold(feature_sets, train, test, y, y_all, inputs, dim, dimsum, learn_options) else: raise Exception("invalid method found: %s" % learn_options["method"]) if learn_options["training_metric"]=="AUC": # fills in truth and predictions extract_fpr_tpr_for_fold(metrics, fold_labels[i], i, predictions, truth, y_all[learn_options['ground_truth_label']].values, test, y_pred) elif learn_options["training_metric"]=="NDCG": extract_NDCG_for_fold(metrics, fold_labels[i], i, predictions, truth, y_all[learn_options["ground_truth_label"]].values, test, y_pred, learn_options) elif learn_options["training_metric"] == 'spearmanr': extract_spearman_for_fold(metrics, fold_labels[i], i, predictions, truth, y_all[learn_options["ground_truth_label"]].values, test, y_pred, learn_options) truth, predictions = fill_in_truth_and_predictions(truth, predictions, fold_labels[i], y_all, y_pred, learn_options, test) print "\t\tRMSE: ", np.sqrt(((y_pred - y[test])**2).mean()) print "\t\tSpearman correlation: ", util.spearmanr_nonan(y[test], y_pred)[0] print "\t\tfinished fold/gene %i of %i" % (i, len(fold_labels)) cv_median_metric =[np.median(metrics)] gene_pred = [(truth, predictions)] print "\t\tmedian %s across gene folds: %.3f" % (learn_options["training_metric"], cv_median_metric[-1]) t3 = time.time() print "\t\tElapsed time for cv is %.2f seconds" % (t3-t2) return metrics, gene_pred, fold_labels, m, dimsum, filename, feature_names
bsd-3-clause
pythonvietnam/scikit-learn
examples/bicluster/bicluster_newsgroups.py
162
7103
""" ================================================================ Biclustering documents with the Spectral Co-clustering algorithm ================================================================ This example demonstrates the Spectral Co-clustering algorithm on the twenty newsgroups dataset. The 'comp.os.ms-windows.misc' category is excluded because it contains many posts containing nothing but data. The TF-IDF vectorized posts form a word frequency matrix, which is then biclustered using Dhillon's Spectral Co-Clustering algorithm. The resulting document-word biclusters indicate subsets words used more often in those subsets documents. For a few of the best biclusters, its most common document categories and its ten most important words get printed. The best biclusters are determined by their normalized cut. The best words are determined by comparing their sums inside and outside the bicluster. For comparison, the documents are also clustered using MiniBatchKMeans. The document clusters derived from the biclusters achieve a better V-measure than clusters found by MiniBatchKMeans. Output:: Vectorizing... Coclustering... Done in 9.53s. V-measure: 0.4455 MiniBatchKMeans... Done in 12.00s. V-measure: 0.3309 Best biclusters: ---------------- bicluster 0 : 1951 documents, 4373 words categories : 23% talk.politics.guns, 19% talk.politics.misc, 14% sci.med words : gun, guns, geb, banks, firearms, drugs, gordon, clinton, cdt, amendment bicluster 1 : 1165 documents, 3304 words categories : 29% talk.politics.mideast, 26% soc.religion.christian, 25% alt.atheism words : god, jesus, christians, atheists, kent, sin, morality, belief, resurrection, marriage bicluster 2 : 2219 documents, 2830 words categories : 18% comp.sys.mac.hardware, 16% comp.sys.ibm.pc.hardware, 16% comp.graphics words : voltage, dsp, board, receiver, circuit, shipping, packages, stereo, compression, package bicluster 3 : 1860 documents, 2745 words categories : 26% rec.motorcycles, 23% rec.autos, 13% misc.forsale words : bike, car, dod, engine, motorcycle, ride, honda, cars, bmw, bikes bicluster 4 : 12 documents, 155 words categories : 100% rec.sport.hockey words : scorer, unassisted, reichel, semak, sweeney, kovalenko, ricci, audette, momesso, nedved """ from __future__ import print_function print(__doc__) from collections import defaultdict import operator import re from time import time import numpy as np from sklearn.cluster.bicluster import SpectralCoclustering from sklearn.cluster import MiniBatchKMeans from sklearn.externals.six import iteritems from sklearn.datasets.twenty_newsgroups import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.cluster import v_measure_score def number_aware_tokenizer(doc): """ Tokenizer that maps all numeric tokens to a placeholder. For many applications, tokens that begin with a number are not directly useful, but the fact that such a token exists can be relevant. By applying this form of dimensionality reduction, some methods may perform better. """ token_pattern = re.compile(u'(?u)\\b\\w\\w+\\b') tokens = token_pattern.findall(doc) tokens = ["#NUMBER" if token[0] in "0123456789_" else token for token in tokens] return tokens # exclude 'comp.os.ms-windows.misc' categories = ['alt.atheism', 'comp.graphics', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc'] newsgroups = fetch_20newsgroups(categories=categories) y_true = newsgroups.target vectorizer = TfidfVectorizer(stop_words='english', min_df=5, tokenizer=number_aware_tokenizer) cocluster = SpectralCoclustering(n_clusters=len(categories), svd_method='arpack', random_state=0) kmeans = MiniBatchKMeans(n_clusters=len(categories), batch_size=20000, random_state=0) print("Vectorizing...") X = vectorizer.fit_transform(newsgroups.data) print("Coclustering...") start_time = time() cocluster.fit(X) y_cocluster = cocluster.row_labels_ print("Done in {:.2f}s. V-measure: {:.4f}".format( time() - start_time, v_measure_score(y_cocluster, y_true))) print("MiniBatchKMeans...") start_time = time() y_kmeans = kmeans.fit_predict(X) print("Done in {:.2f}s. V-measure: {:.4f}".format( time() - start_time, v_measure_score(y_kmeans, y_true))) feature_names = vectorizer.get_feature_names() document_names = list(newsgroups.target_names[i] for i in newsgroups.target) def bicluster_ncut(i): rows, cols = cocluster.get_indices(i) if not (np.any(rows) and np.any(cols)): import sys return sys.float_info.max row_complement = np.nonzero(np.logical_not(cocluster.rows_[i]))[0] col_complement = np.nonzero(np.logical_not(cocluster.columns_[i]))[0] weight = X[rows[:, np.newaxis], cols].sum() cut = (X[row_complement[:, np.newaxis], cols].sum() + X[rows[:, np.newaxis], col_complement].sum()) return cut / weight def most_common(d): """Items of a defaultdict(int) with the highest values. Like Counter.most_common in Python >=2.7. """ return sorted(iteritems(d), key=operator.itemgetter(1), reverse=True) bicluster_ncuts = list(bicluster_ncut(i) for i in range(len(newsgroups.target_names))) best_idx = np.argsort(bicluster_ncuts)[:5] print() print("Best biclusters:") print("----------------") for idx, cluster in enumerate(best_idx): n_rows, n_cols = cocluster.get_shape(cluster) cluster_docs, cluster_words = cocluster.get_indices(cluster) if not len(cluster_docs) or not len(cluster_words): continue # categories counter = defaultdict(int) for i in cluster_docs: counter[document_names[i]] += 1 cat_string = ", ".join("{:.0f}% {}".format(float(c) / n_rows * 100, name) for name, c in most_common(counter)[:3]) # words out_of_cluster_docs = cocluster.row_labels_ != cluster out_of_cluster_docs = np.where(out_of_cluster_docs)[0] word_col = X[:, cluster_words] word_scores = np.array(word_col[cluster_docs, :].sum(axis=0) - word_col[out_of_cluster_docs, :].sum(axis=0)) word_scores = word_scores.ravel() important_words = list(feature_names[cluster_words[i]] for i in word_scores.argsort()[:-11:-1]) print("bicluster {} : {} documents, {} words".format( idx, n_rows, n_cols)) print("categories : {}".format(cat_string)) print("words : {}\n".format(', '.join(important_words)))
bsd-3-clause
AlexanderFabisch/scikit-learn
examples/decomposition/plot_kernel_pca.py
353
2011
""" ========== Kernel PCA ========== This example shows that Kernel PCA is able to find a projection of the data that makes data linearly separable. """ print(__doc__) # Authors: Mathieu Blondel # Andreas Mueller # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA, KernelPCA from sklearn.datasets import make_circles np.random.seed(0) X, y = make_circles(n_samples=400, factor=.3, noise=.05) kpca = KernelPCA(kernel="rbf", fit_inverse_transform=True, gamma=10) X_kpca = kpca.fit_transform(X) X_back = kpca.inverse_transform(X_kpca) pca = PCA() X_pca = pca.fit_transform(X) # Plot results plt.figure() plt.subplot(2, 2, 1, aspect='equal') plt.title("Original space") reds = y == 0 blues = y == 1 plt.plot(X[reds, 0], X[reds, 1], "ro") plt.plot(X[blues, 0], X[blues, 1], "bo") plt.xlabel("$x_1$") plt.ylabel("$x_2$") X1, X2 = np.meshgrid(np.linspace(-1.5, 1.5, 50), np.linspace(-1.5, 1.5, 50)) X_grid = np.array([np.ravel(X1), np.ravel(X2)]).T # projection on the first principal component (in the phi space) Z_grid = kpca.transform(X_grid)[:, 0].reshape(X1.shape) plt.contour(X1, X2, Z_grid, colors='grey', linewidths=1, origin='lower') plt.subplot(2, 2, 2, aspect='equal') plt.plot(X_pca[reds, 0], X_pca[reds, 1], "ro") plt.plot(X_pca[blues, 0], X_pca[blues, 1], "bo") plt.title("Projection by PCA") plt.xlabel("1st principal component") plt.ylabel("2nd component") plt.subplot(2, 2, 3, aspect='equal') plt.plot(X_kpca[reds, 0], X_kpca[reds, 1], "ro") plt.plot(X_kpca[blues, 0], X_kpca[blues, 1], "bo") plt.title("Projection by KPCA") plt.xlabel("1st principal component in space induced by $\phi$") plt.ylabel("2nd component") plt.subplot(2, 2, 4, aspect='equal') plt.plot(X_back[reds, 0], X_back[reds, 1], "ro") plt.plot(X_back[blues, 0], X_back[blues, 1], "bo") plt.title("Original space after inverse transform") plt.xlabel("$x_1$") plt.ylabel("$x_2$") plt.subplots_adjust(0.02, 0.10, 0.98, 0.94, 0.04, 0.35) plt.show()
bsd-3-clause
grantjenks/pyannote-core
pyannote/core/annotation.py
1
39736
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014-2017 CNRS # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # AUTHORS # Hervé BREDIN - http://herve.niderb.fr """ ########## Annotation ########## .. plot:: pyplots/annotation.py :class:`pyannote.core.Annotation` instances are ordered sets of non-empty tracks: - ordered, because segments are sorted by start time (and end time in case of tie) - set, because one cannot add twice the same track - non-empty, because one cannot add empty track A track is a (support, name) pair where `support` is a Segment instance, and `name` is an additional identifier so that it is possible to add multiple tracks with the same support. To define the annotation depicted above: .. ipython:: In [1]: from pyannote.core import Annotation, Segment In [6]: annotation = Annotation() ...: annotation[Segment(1, 5)] = 'Carol' ...: annotation[Segment(6, 8)] = 'Bob' ...: annotation[Segment(12, 18)] = 'Carol' ...: annotation[Segment(7, 20)] = 'Alice' ...: which is actually a shortcut for .. ipython:: In [6]: annotation = Annotation() ...: annotation[Segment(1, 5), '_'] = 'Carol' ...: annotation[Segment(6, 8), '_'] = 'Bob' ...: annotation[Segment(12, 18), '_'] = 'Carol' ...: annotation[Segment(7, 20), '_'] = 'Alice' ...: where all tracks share the same (default) name ``'_'``. In case two tracks share the same support, use a different track name: .. ipython:: In [6]: annotation = Annotation(uri='my_video_file', modality='speaker') ...: annotation[Segment(1, 5), 1] = 'Carol' # track name = 1 ...: annotation[Segment(1, 5), 2] = 'Bob' # track name = 2 ...: annotation[Segment(12, 18)] = 'Carol' ...: The track name does not have to be unique over the whole set of tracks. .. note:: The optional *uri* and *modality* keywords argument can be used to remember which document and modality (e.g. speaker or face) it describes. Several convenient methods are available. Here are a few examples: .. ipython:: In [9]: annotation.labels() # sorted list of labels Out[9]: ['Bob', 'Carol'] In [10]: annotation.chart() # label duration chart Out[10]: [('Carol', 10), ('Bob', 4)] In [11]: list(annotation.itertracks()) Out[11]: [(<Segment(1, 5)>, 1), (<Segment(1, 5)>, 2), (<Segment(12, 18)>, u'_')] In [12]: annotation.label_timeline('Carol') Out[12]: <Timeline(uri=my_video_file, segments=[<Segment(1, 5)>, <Segment(12, 18)>])> See :class:`pyannote.core.Annotation` for the complete reference. """ from __future__ import unicode_literals import six import itertools import operator import warnings import numpy as np from . import PYANNOTE_URI, PYANNOTE_MODALITY, \ PYANNOTE_SEGMENT, PYANNOTE_TRACK, PYANNOTE_LABEL from xarray import DataArray from sortedcontainers import SortedDict from .segment import Segment from .timeline import Timeline from .json import PYANNOTE_JSON, PYANNOTE_JSON_CONTENT from .util import string_generator, int_generator class Annotation(object): """Annotation Parameters ---------- uri : string, optional name of annotated resource (e.g. audio or video file) modality : string, optional name of annotated modality Returns ------- annotation : Annotation New annotation """ @classmethod def from_df(cls, df, uri=None, modality=None): df = df[[PYANNOTE_SEGMENT, PYANNOTE_TRACK, PYANNOTE_LABEL]] annotation = cls(uri=uri, modality=modality) for row in df.itertuples(): if row[1] in annotation._tracks: annotation._tracks[row[1]][row[2]] = row[3] else: annotation._tracks[row[1]] = {row[2]: row[3]} annotation._labels = {label: None for label in df['label'].unique()} annotation._labelNeedsUpdate = { label: True for label in annotation._labels} annotation._timeline = None annotation._timelineNeedsUpdate = True return annotation def __init__(self, uri=None, modality=None): super(Annotation, self).__init__() self._uri = uri self.modality = modality # sorted dictionary # keys: annotated segments # values: {track: label} dictionary self._tracks = SortedDict() # dictionary # key: label # value: timeline self._labels = {} self._labelNeedsUpdate = {} # timeline meant to store all annotated segments self._timeline = None self._timelineNeedsUpdate = True def _get_uri(self): return self._uri def _set_uri(self, uri): # update uri for all internal timelines for label in self.labels(): timeline = self.label_timeline(label, copy=False) timeline.uri = uri timeline = self.get_timeline(copy=False) timeline.uri = uri self._uri = uri uri = property(_get_uri, fset=_set_uri, doc="Resource identifier") def _updateLabels(self): # list of labels that needs to be updated update = set( label for label, update in self._labelNeedsUpdate.items() if update) # accumulate segments for updated labels _segments = {label: [] for label in update} for segment, track, label in self.itertracks(label=True): if label in update: _segments[label].append(segment) # create timeline with accumulated segments for updated labels for label in update: if _segments[label]: self._labels[label] = Timeline( segments=_segments[label], uri=self.uri) self._labelNeedsUpdate[label] = False else: self._labels.pop(label, None) self._labelNeedsUpdate.pop(label, None) def __len__(self): """Number of segments >>> len(annotation) # annotation contains three segments 3 """ return len(self._tracks) def __nonzero__(self): return self.__bool__() def __bool__(self): """Emptiness >>> if annotation: ... # annotation is empty ... else: ... # annotation is not empty """ return len(self._tracks) > 0 def itersegments(self): """Iterate over segments (in chronological order) >>> for segment in annotation.itersegments(): ... # do something with the segment See also -------- :class:`pyannote.core.Segment` describes how segments are sorted. """ return iter(self._tracks) def itertracks(self, label=False, yield_label=False): """Iterate over tracks (in chronological order) Parameters ---------- yield_label : bool, optional When True, yield (segment, track, label) tuples, such that annotation[segment, track] == label. Defaults to yielding (segment, track) tuple. Examples -------- >>> for segment, track in annotation.itertracks(): ... # do something with the track >>> for segment, track, label in annotation.itertracks(yield_label=True): ... # do something with the track and its label """ if label: warnings.warn( '"label" parameter has been renamed to "yield_label".', DeprecationWarning ) yield_label = label for segment, tracks in self._tracks.items(): for track, lbl in sorted( six.iteritems(tracks), key=lambda tl: (str(tl[0]), str(tl[1]))): if yield_label: yield segment, track, lbl else: yield segment, track def _updateTimeline(self): self._timeline = Timeline(segments=self._tracks, uri=self.uri) self._timelineNeedsUpdate = False def get_timeline(self, copy=True): """Get timeline made of all annotated segments Parameters ---------- copy : bool, optional Defaults (True) to returning a copy of the internal timeline. Set to False to return the actual internal timeline (faster). Returns ------- timeline : Timeline Timeline made of all annotated segments. Note ---- In case copy is set to False, be careful **not** to modify the returned timeline, as it may lead to weird subsequent behavior of the annotation instance. """ if self._timelineNeedsUpdate: self._updateTimeline() if copy: return self._timeline.copy() return self._timeline def __eq__(self, other): """Equality >>> annotation == other Two annotations are equal if and only if their tracks and associated labels are equal. """ pairOfTracks = six.moves.zip_longest(self.itertracks(label=True), other.itertracks(label=True)) return all(t1 == t2 for t1, t2 in pairOfTracks) def __ne__(self, other): """Inequality""" pairOfTracks = six.moves.zip_longest(self.itertracks(label=True), other.itertracks(label=True)) return any(t1 != t2 for t1, t2 in pairOfTracks) def __contains__(self, included): """Inclusion Check whether every segment of `included` does exist in annotation. Parameters ---------- included : Segment or Timeline Segment or timeline being checked for inclusion Returns ------- contains : bool True if every segment in `included` exists in timeline, False otherwise """ return included in self.get_timeline(copy=False) def crop(self, support, mode='intersection'): """Crop annotation to new support Parameters ---------- support : Segment or Timeline If `support` is a `Timeline`, its support is used. mode : {'strict', 'loose', 'intersection'}, optional Controls how segments that are not fully included in `support` are handled. 'strict' mode only keeps fully included segments. 'loose' mode keeps any intersecting segment. 'intersection' mode keeps any intersecting segment but replace them by their actual intersection. Returns ------- cropped : Annotation Cropped annotation Note ---- In 'intersection' mode, the best is done to keep the track names unchanged. However, in some cases where two original segments are cropped into the same resulting segments, conflicting track names are modified to make sure no track is lost. """ # TODO speed things up by working directly with annotation internals if isinstance(support, Segment): support = Timeline(segments=[support], uri=self.uri) return self.crop(support, mode=mode) elif isinstance(support, Timeline): cropped = self.__class__(uri=self.uri, modality=self.modality) if mode == 'loose': _tracks = {} _labels = set([]) for segment, _ in \ self.get_timeline(copy=False).co_iter(support): tracks = dict(self._tracks[segment]) _tracks[segment] = tracks _labels.update(tracks.values()) cropped._tracks = SortedDict(_tracks) cropped._labelNeedsUpdate = {label: True for label in _labels} cropped._labels = {label: None for label in _labels} cropped._timelineNeedsUpdate = True cropped._timeline = None return cropped elif mode == 'strict': _tracks = {} _labels = set([]) for segment, other_segment in \ self.get_timeline(copy=False).co_iter(support): if segment not in other_segment: continue tracks = dict(self._tracks[segment]) _tracks[segment] = tracks _labels.update(tracks.values()) cropped._tracks = SortedDict(_tracks) cropped._labelNeedsUpdate = {label: True for label in _labels} cropped._labels = {label: None for label in _labels} cropped._timelineNeedsUpdate = True cropped._timeline = None return cropped elif mode == 'intersection': for segment, other_segment in \ self.get_timeline(copy=False).co_iter(support): intersection = segment & other_segment for track, label in six.iteritems(self._tracks[segment]): track = cropped.new_track(intersection, candidate=track) cropped[intersection, track] = label return cropped else: raise NotImplementedError("unsupported mode: '%s'" % mode) def get_tracks(self, segment): """Query tracks by segment Parameters ---------- segment : Segment Query Returns ------- tracks : set Set of tracks Note ---- This will return an empty set if segment does not exist. """ return set(self._tracks.get(segment, {})) def has_track(self, segment, track): """Check whether a given track exists Parameters ---------- segment : Segment Query segment track : Query track Returns ------- exists : bool True if track exists for segment """ return track in self._tracks.get(segment, {}) def copy(self): """Get a copy of the annotation Returns ------- annotation : Annotation Copy of the annotation """ # create new empty annotation copied = self.__class__(uri=self.uri, modality=self.modality) # deep copy internal track dictionary _tracks, _labels = [], set([]) for key, value in self._tracks.items(): _labels.update(value.values()) _tracks.append((key, dict(value))) copied._tracks = SortedDict(_tracks) copied._labels = {label: None for label in _labels} copied._labelNeedsUpdate = {label: True for label in _labels} copied._timeline = None copied._timelineNeedsUpdate = True return copied def new_track(self, segment, candidate=None, prefix=None): """Generate a new track name for given segment Ensures that the returned track name does not already exist for the given segment. Parameters ---------- segment : Segment Segment for which a new track name is generated. candidate : any valid track name, optional When provided, try this candidate name first. prefix : str, optional Track name prefix. Defaults to the empty string ''. Returns ------- name : str New track name """ # obtain list of existing tracks for segment existing_tracks = set(self._tracks.get(segment, {})) # if candidate is provided, check whether it already exists # in case it does not, use it if (candidate is not None) and (candidate not in existing_tracks): return candidate # no candidate was provided or the provided candidate already exists # we need to create a brand new one # by default (if prefix is not provided), use '' if prefix is None: prefix = '' # find first non-existing track name for segment # eg. if '0' exists, try '1', then '2', ... count = 0 while ('%s%d' % (prefix, count)) in existing_tracks: count += 1 # return first non-existing track name return '%s%d' % (prefix, count) def __str__(self): """Human-friendly representation""" # TODO: use pandas.DataFrame return "\n".join(["%s %s %s" % (s, t, l) for s, t, l in self.itertracks(label=True)]) def __delitem__(self, key): """Delete one track >>> del annotation[segment, track] Delete all tracks of a segment >>> del annotation[segment] """ # del annotation[segment] if isinstance(key, Segment): # Pop segment out of dictionary # and get corresponding tracks # Raises KeyError if segment does not exist tracks = self._tracks.pop(key) # mark timeline as modified self._timelineNeedsUpdate = True # mark every label in tracks as modified for track, label in six.iteritems(tracks): self._labelNeedsUpdate[label] = True # del annotation[segment, track] elif isinstance(key, tuple) and len(key) == 2: # get segment tracks as dictionary # if segment does not exist, get empty dictionary # Raises KeyError if segment does not exist tracks = self._tracks[key[0]] # pop track out of tracks dictionary # and get corresponding label # Raises KeyError if track does not exist label = tracks.pop(key[1]) # mark label as modified self._labelNeedsUpdate[label] = True # if tracks dictionary is now empty, # remove segment as well if not tracks: self._tracks.pop(key[0]) self._timelineNeedsUpdate = True else: raise NotImplementedError( 'Deletion only works with Segment or (Segment, track) keys.') # label = annotation[segment, track] def __getitem__(self, key): """Get track label >>> label = annotation[segment, track] Note ---- ``annotation[segment]`` is equivalent to ``annotation[segment, '_']`` """ if isinstance(key, Segment): key = (key, '_') return self._tracks[key[0]][key[1]] # annotation[segment, track] = label def __setitem__(self, key, label): """Add new or update existing track >>> annotation[segment, track] = label If (segment, track) does not exist, it is added. If (segment, track) already exists, it is updated. Note ---- ``annotation[segment] = label`` is equivalent to ``annotation[segment, '_'] = label`` Note ---- If `segment` is empty, it does nothing. """ if isinstance(key, Segment): key = (key, '_') segment, track = key # do not add empty track if not segment: return # in case we create a new segment # mark timeline as modified if segment not in self._tracks: self._tracks[segment] = {} self._timelineNeedsUpdate = True # in case we modify an existing track # mark old label as modified if track in self._tracks[segment]: old_label = self._tracks[segment][track] self._labelNeedsUpdate[old_label] = True # mark new label as modified self._tracks[segment][track] = label self._labelNeedsUpdate[label] = True def empty(self): """Return an empty copy Returns ------- empty : Annotation Empty annotation using the same 'uri' and 'modality' attributes. """ return self.__class__(uri=self.uri, modality=self.modality) def labels(self): """Get sorted list of labels Returns ------- labels : list Sorted list of labels """ if any([lnu for lnu in self._labelNeedsUpdate.values()]): self._updateLabels() return sorted(self._labels, key=str) def get_labels(self, segment, unique=True): """Query labels by segment Parameters ---------- segment : Segment Query unique : bool, optional When False, return the list of (possibly repeated) labels. Defaults to returning the set of labels. Returns ------- labels : set Set of labels for `segment` if it exists, empty set otherwise. Examples -------- >>> annotation = Annotation() >>> segment = Segment(0, 2) >>> annotation[segment, 'speaker1'] = 'Bernard' >>> annotation[segment, 'speaker2'] = 'John' >>> print sorted(annotation.get_labels(segment)) set(['Bernard', 'John']) >>> print annotation.get_labels(Segment(1, 2)) set([]) """ labels = self._tracks.get(segment, {}).values() if unique: return set(labels) return labels def subset(self, labels, invert=False): """Filter annotation by labels Parameters ---------- labels : iterable List of filtered labels invert : bool, optional If invert is True, extract all but requested labels Returns ------- filtered : Annotation Filtered annotation """ labels = set(labels) if invert: labels = set(self.labels()) - labels else: labels = labels & set(self.labels()) sub = self.__class__(uri=self.uri, modality=self.modality) _tracks, _labels = {}, set([]) for segment, tracks in self._tracks.items(): sub_tracks = {track: label for track, label in tracks.items() if label in labels} if sub_tracks: _tracks[segment] = sub_tracks _labels.update(sub_tracks.values()) sub._tracks = SortedDict(_tracks) sub._labelNeedsUpdate = {label: True for label in _labels} sub._labels = {label: None for label in _labels} sub._timelineNeedsUpdate = True sub._timeline = None return sub def update(self, annotation, copy=False): """Add every track of an existing annotation (in place) Parameters ---------- annotation : Annotation Annotation whose tracks are being added copy : bool, optional Return a copy of the annotation. Defaults to updating the annotation in-place. Returns ------- self : Annotation Updated annotation Note ---- Existing tracks are updated with the new label. """ result = self.copy() if copy else self # TODO speed things up by working directly with annotation internals for segment, track, label in annotation.itertracks(label=True): result[segment, track] = label return result def label_timeline(self, label, copy=True): """Query segments by label Parameters ---------- label : object Query copy : bool, optional Defaults (True) to returning a copy of the internal timeline. Set to False to return the actual internal timeline (faster). Returns ------- timeline : Timeline Timeline made of all segments for which at least one track is annotated as label Note ---- If label does not exist, this will return an empty timeline. Note ---- In case copy is set to False, be careful **not** to modify the returned timeline, as it may lead to weird subsequent behavior of the annotation instance. """ if label not in self.labels(): return Timeline(uri=self.uri) if self._labelNeedsUpdate[label]: self._updateLabels() if copy: return self._labels[label].copy() return self._labels[label] def label_coverage(self, label): warnings.warn( '"label_coverage" has been renamed to "label_support".', DeprecationWarning) return self.label_support(label) def label_support(self, label): """Label support Equivalent to ``Annotation.label_timeline(label).support()`` Parameters ---------- label : object Query Returns ------- support : Timeline Label support See also -------- :func:`~pyannote.core.Annotation.label_timeline` :func:`~pyannote.core.Timeline.support` """ return self.label_timeline(label, copy=False).support() def label_duration(self, label): """Label duration Equivalent to ``Annotation.label_timeline(label).duration()`` Parameters ---------- label : object Query Returns ------- duration : float Duration, in seconds. See also -------- :func:`~pyannote.core.Annotation.label_timeline` :func:`~pyannote.core.Timeline.duration` """ return self.label_timeline(label, copy=False).duration() def chart(self, percent=False): """Get labels chart (from longest to shortest duration) Parameters ---------- percent : bool, optional Return list of (label, percentage) tuples. Defaults to returning list of (label, duration) tuples. Returns ------- chart : list List of (label, duration), sorted by duration in decreasing order. """ chart = sorted(((L, self.label_duration(L)) for L in self.labels()), key=lambda x: x[1], reverse=True) if percent: total = np.sum([duration for _, duration in chart]) chart = [(label, duration / total) for (label, duration) in chart] return chart def argmax(self, support=None, segment=None): """Get label with longest duration Parameters ---------- support : Segment or Timeline, optional Find label with longest duration within provided support. Defaults to whole extent. Returns ------- label : any existing label or None Label with longest intersection Examples -------- >>> annotation = Annotation(modality='speaker') >>> annotation[Segment(0, 10), 'speaker1'] = 'Alice' >>> annotation[Segment(8, 20), 'speaker1'] = 'Bob' >>> print "%s is such a talker!" % annotation.argmax() Bob is such a talker! >>> segment = Segment(22, 23) >>> if not annotation.argmax(support): ... print "No label intersecting %s" % segment No label intersection [22 --> 23] """ if segment is not None: warnings.warn( '"segment" parameter has been renamed to "support".', DeprecationWarning) support = segment cropped = self if support is not None: cropped = cropped.crop(support, mode='intersection') if not cropped: return None return max(((_, cropped.label_duration(_)) for _ in cropped.labels()), key=lambda x: x[1])[0] def translate(self, translation): warnings.warn( '"translate" has been replaced by "rename_labels".', DeprecationWarning) return self.rename_labels(mapping=translation) def __mod__(self, translation): warnings.warn( 'support for "%" operator will be removed.', DeprecationWarning) return self.rename_labels(mapping=translation) def retrack(self): warnings.warn( '"retrack" has been renamed to "rename_tracks".', DeprecationWarning) return self.rename_tracks(generator='int') def rename_tracks(self, generator='string'): """Rename all tracks Parameters ---------- generator : 'string', 'int', or iterable, optional If 'string' (default) rename tracks to 'A', 'B', 'C', etc. If 'int', rename tracks to 0, 1, 2, etc. If iterable, use it to generate track names. Returns ------- renamed : Annotation Copy of the original annotation where tracks are renamed. Example ------- >>> annotation = Annotation() >>> annotation[Segment(0, 1), 'a'] = 'a' >>> annotation[Segment(0, 1), 'b'] = 'b' >>> annotation[Segment(1, 2), 'a'] = 'a' >>> annotation[Segment(1, 3), 'c'] = 'c' >>> print(annotation) [ 00:00:00.000 --> 00:00:01.000] a a [ 00:00:00.000 --> 00:00:01.000] b b [ 00:00:01.000 --> 00:00:02.000] a a [ 00:00:01.000 --> 00:00:03.000] c c >>> print(annotation.rename_tracks(generator='int')) [ 00:00:00.000 --> 00:00:01.000] 0 a [ 00:00:00.000 --> 00:00:01.000] 1 b [ 00:00:01.000 --> 00:00:02.000] 2 a [ 00:00:01.000 --> 00:00:03.000] 3 c """ renamed = self.__class__(uri=self.uri, modality=self.modality) if generator == 'string': generator = string_generator() elif generator == 'int': generator = int_generator() # TODO speed things up by working directly with annotation internals for s, _, label in self.itertracks(label=True): renamed[s, next(generator)] = label return renamed def rename_labels(self, mapping=None, generator='string', copy=True): """Rename labels Parameters ---------- mapping : dict, optional {old_name: new_name} mapping dictionary. generator : 'string', 'int' or iterable, optional If 'string' (default) rename label to 'A', 'B', 'C', ... If 'int', rename to 0, 1, 2, etc. If iterable, use it to generate labels. copy : bool, optional Return a copy of the annotation. Defaults to updating the annotation in-place. Returns ------- renamed : Annotation Annotation where labels have been renamed Note ---- Unmapped labels are kept unchanged. Note ---- Parameter `generator` has no effect when `mapping` is provided. """ if mapping is None: if generator == 'string': generator = string_generator() elif generator == 'int': generator = int_generator() # generate mapping mapping = {label: next(generator) for label in self.labels()} renamed = self.copy() if copy else self for old_label, new_label in mapping.items(): renamed._labelNeedsUpdate[old_label] = True renamed._labelNeedsUpdate[new_label] = True for segment, tracks in self._tracks.items(): new_tracks = {track: mapping.get(label, label) for track, label in tracks.items()} renamed._tracks[segment] = new_tracks return renamed def anonymize_labels(self, generator='string'): warnings.warn( "'anonymize_labels' has been replaced by 'rename_labels'", DeprecationWarning) return self.rename_labels(generator=generator) def relabel_tracks(self, generator='string'): """Relabel tracks Create a new annotation where each track has a unique label. Parameters ---------- generator : 'string', 'int' or iterable, optional If 'string' (default) relabel tracks to 'A', 'B', 'C', ... If 'int' relabel to 0, 1, 2, ... If iterable, use it to generate labels. Returns ------- renamed : Annotation New annotation with relabeled tracks. """ if generator == 'string': generator = string_generator() elif generator == 'int': generator = int_generator() relabeled = self.empty() for s, t, _ in self.itertracks(label=True): relabeled[s, t] = next(generator) return relabeled def anonymize_tracks(self, generator='string'): warnings.warn( "'anonymize_tracks' has been replaced by 'relabel_tracks'", DeprecationWarning) return self.relabel_tracks(generator=generator) def support(self, collar=0.): """Annotation support The support of an annotation is an annotation where contiguous tracks with same label are merged into one unique covering track. A picture is worth a thousand words:: collar |---| annotation |--A--| |--A--| |-B-| |-B-| |--C--| |----B-----| annotation.support(collar) |------A------| |------B------| |-B-| |--C--| Parameters ---------- collar : float, optional Merge tracks with same label and separated by less than `collar` seconds. This is why 'A' tracks are merged in above figure. Defaults to 0. Returns ------- support : Annotation Annotation support Note ---- Track names are lost in the process. """ generator = string_generator() # initialize an empty annotation # with same uri and modality as original support = self.empty() for label in self.labels(): # get timeline for current label timeline = self.label_timeline(label, copy=True) # fill the gaps shorter than collar if collar > 0.: gaps = timeline.gaps() for gap in gaps: if gap.duration < collar: timeline.add(gap) # reconstruct annotation with merged tracks for segment in timeline.support(): support[segment, next(generator)] = label return support def smooth(self, collar=0.): warnings.warn( '"smooth" has been renamed to "support".', DeprecationWarning) return self.support(collar=collar) def co_iter(self, other): """Iterate over pairs of intersecting tracks Parameters ---------- other : Annotation Second annotation Returns ------- iterable : (Segment, object), (Segment, object) iterable Yields pairs of intersectins tracks, in chronological (then alphabetical) order. See also -------- :func:`~pyannote.core.Timeline.co_iter` """ timeline = self.get_timeline(copy=False) other_timeline = other.get_timeline(copy=False) for s, S in timeline.co_iter(other_timeline): tracks = sorted(self.get_tracks(s), key=str) other_tracks = sorted(other.get_tracks(S), key=str) for t, T in itertools.product(tracks, other_tracks): yield (s, t), (S, T) def __mul__(self, other): """Cooccurrence (or confusion) matrix >>> matrix = annotation * other >>> matrix.loc['A', 'a'] # duration of cooccurrence between labels # 'A' from `annotation` and 'a' from `other` Parameters ---------- other : Annotation Second annotation Returns ------- cooccurrence : DataArray """ if not isinstance(other, Annotation): raise TypeError( 'computing cooccurrence matrix only works with Annotation ' 'instances.') # initialize matrix with one row per label in `self`, # and one column per label in `other` i = self.labels() j = other.labels() matrix = DataArray( np.zeros((len(i), len(j))), coords=[('i', i), ('j', j)]) # iterate over intersecting tracks and accumulate durations for (segment, track), (other_segment, other_track) in self.co_iter(other): label = self[segment, track] other_label = other[other_segment, other_track] duration = (segment & other_segment).duration matrix.loc[label, other_label] += duration return matrix def for_json(self): """Serialization See also -------- :mod:`pyannote.core.json` """ data = {PYANNOTE_JSON: self.__class__.__name__} content = [{PYANNOTE_SEGMENT: s.for_json(), PYANNOTE_TRACK: t, PYANNOTE_LABEL: l} for s, t, l in self.itertracks(label=True)] data[PYANNOTE_JSON_CONTENT] = content if self.uri: data[PYANNOTE_URI] = self.uri if self.modality: data[PYANNOTE_MODALITY] = self.modality return data @classmethod def from_json(cls, data): """Deserialization See also -------- :mod:`pyannote.core.json` """ uri = data.get(PYANNOTE_URI, None) modality = data.get(PYANNOTE_MODALITY, None) annotation = cls(uri=uri, modality=modality) for one in data[PYANNOTE_JSON_CONTENT]: segment = Segment.from_json(one[PYANNOTE_SEGMENT]) track = one[PYANNOTE_TRACK] label = one[PYANNOTE_LABEL] annotation[segment, track] = label return annotation def _repr_png_(self): """IPython notebook support See also -------- :mod:`pyannote.core.notebook` """ from .notebook import repr_annotation return repr_annotation(self)
mit
shahankhatch/scikit-learn
examples/manifold/plot_compare_methods.py
259
4031
""" ========================================= Comparison of Manifold Learning methods ========================================= An illustration of dimensionality reduction on the S-curve dataset with various manifold learning methods. For a discussion and comparison of these algorithms, see the :ref:`manifold module page <manifold>` For a similar example, where the methods are applied to a sphere dataset, see :ref:`example_manifold_plot_manifold_sphere.py` Note that the purpose of the MDS is to find a low-dimensional representation of the data (here 2D) in which the distances respect well the distances in the original high-dimensional space, unlike other manifold-learning algorithms, it does not seeks an isotropic representation of the data in the low-dimensional space. """ # Author: Jake Vanderplas -- <vanderplas@astro.washington.edu> print(__doc__) from time import time import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from sklearn import manifold, datasets # Next line to silence pyflakes. This import is needed. Axes3D n_points = 1000 X, color = datasets.samples_generator.make_s_curve(n_points, random_state=0) n_neighbors = 10 n_components = 2 fig = plt.figure(figsize=(15, 8)) plt.suptitle("Manifold Learning with %i points, %i neighbors" % (1000, n_neighbors), fontsize=14) try: # compatibility matplotlib < 1.0 ax = fig.add_subplot(251, projection='3d') ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral) ax.view_init(4, -72) except: ax = fig.add_subplot(251, projection='3d') plt.scatter(X[:, 0], X[:, 2], c=color, cmap=plt.cm.Spectral) methods = ['standard', 'ltsa', 'hessian', 'modified'] labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE'] for i, method in enumerate(methods): t0 = time() Y = manifold.LocallyLinearEmbedding(n_neighbors, n_components, eigen_solver='auto', method=method).fit_transform(X) t1 = time() print("%s: %.2g sec" % (methods[i], t1 - t0)) ax = fig.add_subplot(252 + i) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("%s (%.2g sec)" % (labels[i], t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() Y = manifold.Isomap(n_neighbors, n_components).fit_transform(X) t1 = time() print("Isomap: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(257) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("Isomap (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() mds = manifold.MDS(n_components, max_iter=100, n_init=1) Y = mds.fit_transform(X) t1 = time() print("MDS: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(258) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("MDS (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() se = manifold.SpectralEmbedding(n_components=n_components, n_neighbors=n_neighbors) Y = se.fit_transform(X) t1 = time() print("SpectralEmbedding: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(259) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("SpectralEmbedding (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() tsne = manifold.TSNE(n_components=n_components, init='pca', random_state=0) Y = tsne.fit_transform(X) t1 = time() print("t-SNE: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(250) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("t-SNE (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') plt.show()
bsd-3-clause
oduwa/Wheat-Count
PicNumero/count.py
2
1729
import os, sys import tqdm from scipy import misc from skimage.feature import blob_dog, blob_log, blob_doh from skimage.color import rgb2gray # Way to import from matplotlib without warning according to # https://github.com/matplotlib/matplotlib/issues/5836#issuecomment-223997114 import warnings; with warnings.catch_warnings(): warnings.simplefilter("ignore"); import matplotlib.pyplot as plt def main(): numberOfImages = 11; # TODO: AUTOMATICALLY GET NUMBER OF IMAGES # Get number of images. Remeber to divide by 2 as for every relevant image, # theres also the comparison image. # if ".DS_Store" in os.listdir("Wheat_ROIs"): # numberOfImages = (len(os.listdir("Wheat_ROIs")) - 1)/2; # else: # numberOfImages = len(os.listdir("Wheat_ROIs"))/2; # For each ROI image in folder for i in tqdm.tqdm(range(1, numberOfImages+1)): # Load image filename = "../Wheat_ROIs/{:03d}_ROI.png".format(i); img = misc.imread(filename); img_gray = rgb2gray(img); # Detect blobs. See http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_doh # for function documentation blobs = blob_doh(img_gray, min_sigma=1, max_sigma=100, threshold=.01) # Display blobs on image and save image fig, ax = plt.subplots() plt.title("Number of Blobs Detected: {}".format(blobs.shape[0])) plt.grid(False) ax.imshow(img, interpolation='nearest') for blob in blobs: y, x, r = blob c = plt.Circle((x, y), r, color='red', linewidth=2, fill=False) ax.add_patch(c) fig.savefig("../Wheat_ROIs/{:03d}_Blob.png".format(i)) main();
mit
liangfok/controlit_demos
dreamer_controlit_demos/nodes/Demo2_ChangingObjectPositions.py
1
31691
#!/usr/bin/env python ''' This uses both posture and orientation control. ''' import sys, getopt # for getting and parsing command line arguments import time import math import threading import rospy from std_msgs.msg import Float64, Float64MultiArray, MultiArrayDimension, Bool, Int32 import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import TrajectoryGeneratorCubicSpline ENABLE_USER_PROMPTS = True NUM_CARTESIAN_DOFS = 3 # Cartesian goal is x, y, z NUM_ORIENTATION_DOFS = 3 # Orientation is defined using a x, y, z vector NUM_ROBOT_DOFS = 16 # Shoulder abductors about 10 degrees away from body and elbows bent 90 degrees # DEFAULT_POSTURE = [0.0, 0.0, # torso # 0.0, 0.174532925, 0.0, 1.57, 0.0, 0.0, 0.0, # left arm # 0.0, 0.174532925, 0.0, 1.57, 0.0, 0.0, 0.0] # right arm # Shoulder abductors and elbows at about 10 degrees DEFAULT_POSTURE = [0.0, 0.0, # torso 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0] # right arm # PIPE_LOCATION = [0.28664480323526653, -0.1614844904659368, 0.9597645035426976] # original # PIPE_LOCATION = [0.33, -0.2, 0.9597645035426976] # displacement 1 # PIPE_LOCATION = [0.38, 0.0, 0.9597645035426976] # displacement 2 # PIPE_LOCATION = [0.2, -0.1, 0.9597645035426976] # displacement 3 # PIPE_LOCATION = [0.38, -0.16, 1.2] # displacement 4 # PIPE_LOCATION = [0.48, -0.16, 1.3] # displacement 5 # PIPE_LOCATION = [0.0, -0.16, 1.15] # displacement 6 # PIPE_LOCATION = [0.28, -0.3, 1.0] # displacement 7 # PIPE_LOCATION = [0.28, -0.3, 1.2] # displacement 8 PIPE_LOCATION = [0.35, -0.35, 1.1] # displacement 9 class Demo2_ChangingObjectPositions: def __init__(self): # Define the goal messages rightHandCartesianGoalMsgDim = MultiArrayDimension() rightHandCartesianGoalMsgDim.size = NUM_CARTESIAN_DOFS rightHandCartesianGoalMsgDim.label = "rightHandCartesianGoal" rightHandCartesianGoalMsgDim.stride = 1 self.rightHandCartesianGoalMsg = Float64MultiArray() for ii in range(0, NUM_CARTESIAN_DOFS): self.rightHandCartesianGoalMsg.data.append(0) self.rightHandCartesianGoalMsg.layout.dim.append(rightHandCartesianGoalMsgDim) self.rightHandCartesianGoalMsg.layout.data_offset = 0 #-----------------------------------------------------------------------------' rightHandOrientationGoalMsgDim = MultiArrayDimension() rightHandOrientationGoalMsgDim.size = NUM_ORIENTATION_DOFS rightHandOrientationGoalMsgDim.label = "rightHandOrientationGoal" rightHandOrientationGoalMsgDim.stride = 1 self.rightHandOrientationGoalMsg = Float64MultiArray() for ii in range(0, NUM_ORIENTATION_DOFS): self.rightHandOrientationGoalMsg.data.append(0) self.rightHandOrientationGoalMsg.layout.dim.append(rightHandOrientationGoalMsgDim) self.rightHandOrientationGoalMsg.layout.data_offset = 0 #-----------------------------------------------------------------------------' postureGoalMsgDim = MultiArrayDimension() postureGoalMsgDim.size = NUM_ROBOT_DOFS postureGoalMsgDim.label = "postureGoal" postureGoalMsgDim.stride = 1 self.postureGoalMsg = Float64MultiArray() for ii in range(0, NUM_ROBOT_DOFS): self.postureGoalMsg.data.append(0) self.postureGoalMsg.layout.dim.append(postureGoalMsgDim) self.postureGoalMsg.layout.data_offset = 0 #-----------------------------------------------------------------------------' self.rightHandCmdMsg = Bool() self.rightHandCmdMsg.data = False # relax hand self.rightIndexFingerCmdMsg = Bool() self.rightIndexFingerCmdMsg.data = True # include index finger in power grasp self.rightMiddleFingerCmdMsg = Bool() self.rightMiddleFingerCmdMsg.data = True # include middle finger in power grasp self.enableMsg = Int32() self.enableMsg.data = 1 #-----------------------------------------------------------------------------' # Initialize member variables self.currentPosture = None self.postureError = None self.currentRightCartesianPos = None self.rightCartesianPosError = None self.currentRightOrientation = None self.rightOrientationError = None # Create the ROS topic subscriptions self.postureTaskActualSubscriber = rospy.Subscriber("/dreamer_controller/JPosTask/actualPosition", Float64MultiArray, self.postureTaskActualCallback) self.postureTaskErrorSubscriber = rospy.Subscriber("/dreamer_controller/JPosTask/error", Float64MultiArray, self.postureTaskErrorCallback) self.rightCartesianTaskActualSubscriber = rospy.Subscriber("/dreamer_controller/RightHandPosition/actualWorldPosition", Float64MultiArray, self.rightCartesianTaskActualCallback) self.rightCartesianTaskErrorSubscriber = rospy.Subscriber("/dreamer_controller/RightHandPosition/error", Float64MultiArray, self.rightCartesianTaskErrorCallback) self.rightOrientationTaskActualSubscriber = rospy.Subscriber("/dreamer_controller/RightHandOrientation/actualHeading", Float64MultiArray, self.rightOrientationTaskActualCallback) self.rightOrientationTaskErrorSubscriber = rospy.Subscriber("/dreamer_controller/RightHandOrientation/errorAngle", Float64, self.rightOrientationTaskErrorCallback) # Create the ROS topic publishers self.postureTaskGoalPublisher = rospy.Publisher("/dreamer_controller/JPosTask/goalPosition", Float64MultiArray, queue_size=1) self.rightCartesianTaskGoalPublisher = rospy.Publisher("/dreamer_controller/RightHandPosition/goalPosition", Float64MultiArray, queue_size=1) self.rightCartesianTaskEnablePublisher = rospy.Publisher("/dreamer_controller/RightHandPosition/enabled", Int32, queue_size=1) self.rightOrientationTaskGoalPublisher = rospy.Publisher("/dreamer_controller/RightHandOrientation/goalVector", Float64MultiArray, queue_size=1) self.rightOrientationTaskEnablePublisher = rospy.Publisher("/dreamer_controller/RightHandOrientation/enabled", Int32, queue_size=1) self.rightHandCmdPublisher = rospy.Publisher("/dreamer_controller/controlit/rightHand/powerGrasp", Bool, queue_size=1) self.selectIndexFingerPublisher = rospy.Publisher("/dreamer_controller/controlit/rightHand/includeRightIndexFinger", Bool, queue_size=1) self.selectMiddleFingerPublisher = rospy.Publisher("/dreamer_controller/controlit/rightHand/includeRightMiddleFinger", Bool, queue_size=1) self.selectPinkyFingerPublisher = rospy.Publisher("/dreamer_controller/controlit/rightHand/includeRightPinkyFinger", Bool, queue_size=1) def postureTaskActualCallback(self, msg): self.currentPosture = msg.data def postureTaskErrorCallback(self, msg): self.postureError = msg.data def rightCartesianTaskActualCallback(self, msg): self.currentRightCartesianPos = msg.data def rightCartesianTaskErrorCallback(self, msg): self.rightCartesianPosError = msg.data def rightOrientationTaskActualCallback(self, msg): self.currentRightOrientation = msg.data def rightOrientationTaskErrorCallback(self, msg): self.rightOrientationError = msg.data def getTimeSeconds(self): """ Returns the current time in seconds. """ return rospy.get_time() def connectToControlIt(self): print "Connecting to ControlIt!..." # Wait for connection to ControlIt! pauseCount = 0 warningPrinted = False pauseCount = 0 warningPrinted = False while not rospy.is_shutdown() and ( self.rightCartesianTaskEnablePublisher.get_num_connections() == 0 or \ self.rightOrientationTaskEnablePublisher.get_num_connections() == 0): if warningPrinted: if self.rightCartesianTaskEnablePublisher.get_num_connections() == 0: print "Waiting on right cartesian enable subscriber..." if self.rightOrientationTaskEnablePublisher.get_num_connections() == 0: print "Waiting on right orientation enable subscriber..." time.sleep(0.5) pauseCount = pauseCount + 1 if pauseCount > 5 and not warningPrinted: print "Waiting for connection to ControlIt!..." warningPrinted = True if rospy.is_shutdown(): return # Enable the Cartesian position and orientation tasks enableMsg = Int32() enableMsg.data = 1 self.rightCartesianTaskEnablePublisher.publish(enableMsg) self.rightOrientationTaskEnablePublisher.publish(enableMsg) # Initialize the default posture self.postureGoalMsg.data = DEFAULT_POSTURE self.postureTaskGoalPublisher.publish(self.postureGoalMsg) # Wait for connection to ControlIt! pauseCount = 0 warningPrinted = False while not rospy.is_shutdown() and ( self.currentPosture == None or \ self.currentRightCartesianPos == None or self.currentRightOrientation == None): if warningPrinted: if self.currentRightCartesianPos == None: print "Waiting on right hand position state..." if self.currentRightOrientation == None: print "Waiting on right hand orientation state..." if self.currentPosture == None: print "Waiting on posture state..." time.sleep(0.5) pauseCount = pauseCount + 1 if pauseCount > 5 and not warningPrinted: print "Waiting for data from ControlIt!..." warningPrinted = True if rospy.is_shutdown(): return print "Done connecting to ControlIt!" return not rospy.is_shutdown() def goToReadyPosition(self): # print "Generating GoToReady trajectories..." # Define the waypoints # Note waypoints are formatted as: [[x, y, z], ...] rightHandCartesianWP = [] rightHandOrientationWP = [] jPosWP = [] # These are the initial values as specified in the YAML ControlIt! configuration file rightHandCartesianWP.append([0.033912978219317776, -0.29726881641499886, 0.82]) rightHandOrientationWP.append([1.0, 0.0, 0.0]) jPosWP.append(DEFAULT_POSTURE) # 2015.01.06 Trajectory rightHandCartesianWP.append([0.019903910090688474, -0.28423307267223147, 0.9179288590591458]) rightHandCartesianWP.append([-0.055152798770261954, -0.2907526623508046, 1.009663652974324]) rightHandCartesianWP.append([-0.03366873622218044, -0.40992725074781894, 1.1144948070701866]) rightHandCartesianWP.append([0.11866831717348489, -0.4101100845056917, 1.209699047600146]) rightHandCartesianWP.append([0.21649227857092893, -0.3006839904787592, 1.1140502834793191]) rightHandCartesianWP.append([0.25822435038901964, -0.1895604971725577, 1.0461857180093073]) rightHandOrientationWP.append([0.8950968852599132, 0.26432788250814326, 0.3590714922223199]) rightHandOrientationWP.append([0.8944226954968388, 0.33098423072776184, 0.3007615015086225]) rightHandOrientationWP.append([0.8994250702615956, 0.22626156457297464, 0.3739521993275524]) rightHandOrientationWP.append([0.19818667912613866, -0.8161433027447201, 0.5428002851895832]) rightHandOrientationWP.append([0.260956993686226, -0.8736061290033836, 0.4107478287392042]) rightHandOrientationWP.append([0.5409881394605172, -0.8191390472602035, 0.19063854336595773]) jPosWP.append([0.06826499288341317, 0.06826499288341317, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.6249282444166423, 0.3079607416653748, -0.1220981510225299, 1.3675006234559883, 0.06394316468492173, -0.20422693251592328, 0.06223224746326836]) jPosWP.append([0.0686363596318602, 0.0686363596318602, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -1.0914342991625676, 0.39040871074764566, -0.03720209764435387, 1.7583823306095314, 0.05438773164693069, -0.20257591921666193, 0.06386553930484179]) jPosWP.append([0.06804075180539401, 0.06804075180539401, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -1.3637873691001094, 0.3926057912988488, 0.575755053425441, 1.9732992187122156, 0.29999797251313004, -0.20309827518257023, 0.05586603055643467]) jPosWP.append([0.06818415549992426, 0.06818415549992426, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.8497599545494692, 0.47079074342878563, 0.8355038507753617, 2.2318590905389852, 1.8475059506175733, -0.405570582208143, -0.0277359315904628]) jPosWP.append([0.06794500584573498, 0.06794500584573498, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.24608246913199228, 0.13441397755549533, 0.2542869735593113, 2.0227000417984633, 1.3670468713459782, -0.45978204939890815, 0.030219082955597457]) jPosWP.append([0.06796522908004803, 0.06796522908004803, # torso 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.08569654146540764, 0.07021124925432169, -0.15649686418494702, 1.7194162945362514, 1.51, -0.07, -0.18]) # right arm # Create the trajectory generators rightHandCartesianTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(rightHandCartesianWP) rightHandOrientationTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(rightHandOrientationWP) jPosTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(jPosWP) TOTAL_TRAVEL_TIME = 10.0 # seconds rightHandCartesianTG.generateTrajectory(TOTAL_TRAVEL_TIME) rightHandOrientationTG.generateTrajectory(TOTAL_TRAVEL_TIME) jPosTG.generateTrajectory(TOTAL_TRAVEL_TIME) if ENABLE_USER_PROMPTS: index = raw_input("Go ready position? Y/n\n") if index == "N" or index == "n": return False # quit # Follow the trajectories startTime = self.getTimeSeconds() done = False while not done and not rospy.is_shutdown(): deltaTime = self.getTimeSeconds() - startTime if deltaTime >= TOTAL_TRAVEL_TIME: goalRightHandCartPos = rightHandCartesianTG.getLastPoint() goalRightHandOrientation = rightHandOrientationTG.getLastPoint() goalJPos = jPosTG.getLastPoint() done = True else: goalRightHandCartPos = rightHandCartesianTG.getPoint(deltaTime) goalRightHandOrientation = rightHandOrientationTG.getPoint(deltaTime) goalJPos = jPosTG.getPoint(deltaTime) # Save the new goals in ROS messages self.rightHandCartesianGoalMsg.data = goalRightHandCartPos self.rightHandOrientationGoalMsg.data = goalRightHandOrientation self.postureGoalMsg.data = goalJPos # Publish the ROS messages self.rightCartesianTaskGoalPublisher.publish(self.rightHandCartesianGoalMsg) self.rightOrientationTaskGoalPublisher.publish(self.rightHandOrientationGoalMsg) self.postureTaskGoalPublisher.publish(self.postureGoalMsg) if not done: rospy.sleep(0.01) # 100Hz # print "Done going to ready position!" return not rospy.is_shutdown() def grabMetalTube(self): """ Executes the trajectory that moves the right hand to be around the metal tube. """ rightHandCartesianWP = [] rightHandOrientationWP = [] jPosWP = [] originalCartesianPoint = [0.25822435038901964, -0.1895604971725577, 1.0461857180093073] # This is the last configuration of the gotToReady trajectory rightHandCartesianWP.append(originalCartesianPoint) # rightHandOrientationWP.append([0.5409881394605172, -0.8191390472602035, 0.19063854336595773]) # jPosWP.append([0.06796522908004803, 0.06796522908004803, # torso # 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm # -0.08569654146540764, 0.07021124925432169, -0.15649686418494702, 1.7194162945362514, 1.51, -0.07, -0.18]) # right arm # linearly interpolate four points between the original point and the pipe's location for ii in range(4): step = ii + 1.0 xx = (PIPE_LOCATION[0] - originalCartesianPoint[0]) / 4.0 * step + originalCartesianPoint[0] yy = (PIPE_LOCATION[1] - originalCartesianPoint[1]) / 4.0 * step + originalCartesianPoint[1] zz = (PIPE_LOCATION[2] - originalCartesianPoint[2]) / 4.0 * step + originalCartesianPoint[2] cartesianPos = [] cartesianPos.append(xx) cartesianPos.append(yy) cartesianPos.append(zz) rightHandCartesianWP.append(cartesianPos) # Create the WayPoints # rightHandCartesianWP.append([0.25822435038901964, -0.1895604971725577, 1.0461857180093073]) # rightHandCartesianWP.append([0.25822435038901964, -0.1895604971725577, 1.0461857180093073]) # rightHandCartesianWP.append([0.25822435038901964, -0.1895604971725577, 1.0461857180093073]) # rightHandCartesianWP.append([0.2926328098812538, -0.22212659727858264, 0.9685956358633105]) # rightHandCartesianWP.append([0.28750632029946943, -0.17027266952524717, 0.9597899484960192]) # rightHandCartesianWP.append([0.28664480323526653, -0.1614844904659368, 0.9597645035426976]) rightHandCartesianWP.append(PIPE_LOCATION) # displacement 1 # rightHandOrientationWP.append([0.5409881394605172, -0.8191390472602035, 0.19063854336595773]) # rightHandOrientationWP.append([0.5409881394605172, -0.8191390472602035, 0.19063854336595773]) # rightHandOrientationWP.append([0.5409881394605172, -0.8191390472602035, 0.19063854336595773]) # rightHandOrientationWP.append([0.6030193813610835, -0.6721560435204502, 0.42962062201648427]) # rightHandOrientationWP.append([0.6847262101203426, -0.7283419844816242, 0.025845131371348223]) # rightHandOrientationWP.append([0.8206856971797751, -0.5665754546656667, -0.0739407912788299]) # rightHandOrientationWP.append([0.830926574184253, -0.5512666962638427, -0.07527322169782114]) # jPosWP.append([0.09594703765058178, 0.09594703765058178, # 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm # 0.09817730939874109, 0.1020579374634571, 0.0836978735049272, 1.6235470575907778, 1.054005683347489, -0.6934016966989962, -0.4214573788290379]) # jPosWP.append([0.09578187031551673, 0.09578187031551673, # 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm # 0.07827516108651086, 0.06968225019914681, -0.0651398024593994, 1.3456921412703295, 1.3295641014614135, -0.6445024104856519, -0.4748814187628949]) # jPosWP.append([0.09578234092970726, 0.09578234092970726, # 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm # 0.09157211596703656, 0.041108271773515705, -0.22384970463739684, 1.3076704033792463, 1.353903257753508, -0.7185241326180924, -0.454150460888528]) # jPosWP.append([0.09590536736161434, 0.09590536736161434, # 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm # 0.09105753863890241, 0.023808037050859456, -0.23396990791158995, 1.3070320542599851, 1.336118787118036, -0.7220768168517259, -0.45385861652866377]) # Create the trajectory generators rightHandCartesianTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(rightHandCartesianWP) # rightHandOrientationTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(rightHandOrientationWP) # jPosTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(jPosWP) TOTAL_TRAVEL_TIME = 5.0 # seconds rightHandCartesianTG.generateTrajectory(TOTAL_TRAVEL_TIME) # rightHandOrientationTG.generateTrajectory(TOTAL_TRAVEL_TIME) # jPosTG.generateTrajectory(TOTAL_TRAVEL_TIME) if ENABLE_USER_PROMPTS: index = raw_input("Position right hand around metal tube? Y/n\n") if index == "N" or index == "n": return False # quit # Follow the trajectories startTime = self.getTimeSeconds() done = False while not done and not rospy.is_shutdown(): deltaTime = self.getTimeSeconds() - startTime if deltaTime >= TOTAL_TRAVEL_TIME: goalRightHandCartPos = rightHandCartesianTG.getLastPoint() # goalRightHandOrientation = rightHandOrientationTG.getLastPoint() # goalJPos = jPosTG.getLastPoint() done = True else: goalRightHandCartPos = rightHandCartesianTG.getPoint(deltaTime) # goalRightHandOrientation = rightHandOrientationTG.getPoint(deltaTime) # goalJPos = jPosTG.getPoint(deltaTime) # Save the new goals in ROS messages self.rightHandCartesianGoalMsg.data = goalRightHandCartPos # self.rightHandOrientationGoalMsg.data = goalRightHandOrientation # self.postureGoalMsg.data = goalJPos # Publish the ROS messages self.rightCartesianTaskGoalPublisher.publish(self.rightHandCartesianGoalMsg) # self.rightOrientationTaskGoalPublisher.publish(self.rightHandOrientationGoalMsg) # self.postureTaskGoalPublisher.publish(self.postureGoalMsg) if not done: rospy.sleep(0.01) # 100Hz doPowerGrasp = True if ENABLE_USER_PROMPTS: index = raw_input("Perform right hand power grasp? Y/n\n") if index == "N" or index == "n": doPowerGrasp = False if doPowerGrasp: # Exclude index finger from power grasp # self.rightIndexFingerCmdMsg.data = False # self.selectIndexFingerPublisher.publish(self.rightIndexFingerCmdMsg) # Exclude middle finger from power grasp # self.rightMiddleFingerCmdMsg.data = False # self.selectMiddleFingerPublisher.publish(self.rightMiddleFingerCmdMsg) self.rightHandCmdMsg.data = True self.rightHandCmdPublisher.publish(self.rightHandCmdMsg) # print "Done grabbing metal tube!" return not rospy.is_shutdown() def goToIdlePosition(self): # Define the waypoints # Note waypoints are formatted as: [[x, y, z], ...] rightHandCartesianWP = [] rightHandOrientationWP = [] jPosWP = [] # This is the last configuration of the grabMetalTube trajectory rightHandCartesianWP.append(PIPE_LOCATION) rightHandOrientationWP.append([0.5409881394605172, -0.8191390472602035, 0.19063854336595773]) jPosWP.append([0.06796522908004803, 0.06796522908004803, # torso 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.08569654146540764, 0.07021124925432169, -0.15649686418494702, 1.7194162945362514, 1.51, -0.07, -0.18]) # right arm # This is the last configuration of the grabMetalTube trajectory # rightHandCartesianWP.append(PIPE_LOCATION) # rightHandOrientationWP.append([0.830926574184253, -0.5512666962638427, -0.07527322169782114]) # jPosWP.append([0.09590536736161434, 0.09590536736161434, # 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm # 0.09105753863890241, 0.023808037050859456, -0.23396990791158995, 1.3070320542599851, 1.336118787118036, -0.7220768168517259, -0.45385861652866377]) # 2015.01.06 Trajectory rightHandCartesianWP.append([0.25822435038901964, -0.1895604971725577, 1.0461857180093073]) rightHandCartesianWP.append([0.21649227857092893, -0.3006839904787592, 1.1140502834793191]) rightHandCartesianWP.append([0.11866831717348489, -0.4101100845056917, 1.209699047600146]) rightHandCartesianWP.append([-0.03366873622218044, -0.40992725074781894, 1.1144948070701866]) rightHandCartesianWP.append([-0.055152798770261954, -0.2907526623508046, 1.009663652974324]) rightHandCartesianWP.append([0.019903910090688474, -0.28423307267223147, 0.9179288590591458]) rightHandOrientationWP.append([0.5409881394605172, -0.8191390472602035, 0.19063854336595773]) rightHandOrientationWP.append([0.260956993686226, -0.8736061290033836, 0.4107478287392042]) rightHandOrientationWP.append([0.19818667912613866, -0.8161433027447201, 0.5428002851895832]) rightHandOrientationWP.append([0.8994250702615956, 0.22626156457297464, 0.3739521993275524]) rightHandOrientationWP.append([0.8944226954968388, 0.33098423072776184, 0.3007615015086225]) rightHandOrientationWP.append([0.8950968852599132, 0.26432788250814326, 0.3590714922223199]) jPosWP.append([0.06796522908004803, 0.06796522908004803, # torso 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.08569654146540764, 0.07021124925432169, -0.15649686418494702, 1.7194162945362514, 1.51, -0.07, -0.18]) # right arm jPosWP.append([0.06794500584573498, 0.06794500584573498, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.24608246913199228, 0.13441397755549533, 0.2542869735593113, 2.0227000417984633, 1.3670468713459782, -0.45978204939890815, 0.030219082955597457]) jPosWP.append([0.06818415549992426, 0.06818415549992426, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.8497599545494692, 0.47079074342878563, 0.8355038507753617, 2.2318590905389852, 1.8475059506175733, -0.405570582208143, -0.0277359315904628]) jPosWP.append([0.06804075180539401, 0.06804075180539401, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -1.3637873691001094, 0.3926057912988488, 0.575755053425441, 1.9732992187122156, 0.29999797251313004, -0.20309827518257023, 0.05586603055643467]) jPosWP.append([0.0686363596318602, 0.0686363596318602, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -1.0914342991625676, 0.39040871074764566, -0.03720209764435387, 1.7583823306095314, 0.05438773164693069, -0.20257591921666193, 0.06386553930484179]) jPosWP.append([0.06826499288341317, 0.06826499288341317, 0.0, 0.174532925, 0.0, 0.174532925, 0.0, 0.0, 0.0, # left arm -0.6249282444166423, 0.3079607416653748, -0.1220981510225299, 1.3675006234559883, 0.06394316468492173, -0.20422693251592328, 0.06223224746326836]) # Create the trajectory generators rightHandCartesianTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(rightHandCartesianWP) rightHandOrientationTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(rightHandOrientationWP) jPosTG = TrajectoryGeneratorCubicSpline.TrajectoryGeneratorCubicSpline(jPosWP) TOTAL_TRAVEL_TIME = 10.0 # seconds rightHandCartesianTG.generateTrajectory(TOTAL_TRAVEL_TIME) rightHandOrientationTG.generateTrajectory(TOTAL_TRAVEL_TIME) jPosTG.generateTrajectory(TOTAL_TRAVEL_TIME) if ENABLE_USER_PROMPTS: index = raw_input("Go idle position? Y/n\n") if index == "N" or index == "n": return False # quit # Follow the trajectories startTime = self.getTimeSeconds() done = False while not done and not rospy.is_shutdown(): deltaTime = self.getTimeSeconds() - startTime if deltaTime >= TOTAL_TRAVEL_TIME: goalRightHandCartPos = rightHandCartesianTG.getLastPoint() goalRightHandOrientation = rightHandOrientationTG.getLastPoint() goalJPos = jPosTG.getLastPoint() done = True else: goalRightHandCartPos = rightHandCartesianTG.getPoint(deltaTime) goalRightHandOrientation = rightHandOrientationTG.getPoint(deltaTime) goalJPos = jPosTG.getPoint(deltaTime) # Save the new goals in ROS messages self.rightHandCartesianGoalMsg.data = goalRightHandCartPos self.rightHandOrientationGoalMsg.data = goalRightHandOrientation self.postureGoalMsg.data = goalJPos # Publish the ROS messages self.rightCartesianTaskGoalPublisher.publish(self.rightHandCartesianGoalMsg) self.rightOrientationTaskGoalPublisher.publish(self.rightHandOrientationGoalMsg) self.postureTaskGoalPublisher.publish(self.postureGoalMsg) if not done: rospy.sleep(0.01) # 100Hz releasePowerGrasp = True if ENABLE_USER_PROMPTS: index = raw_input("Release right hand power grasp? Y/n\n") if index == "N" or index == "n": releasePowerGrasp = False if releasePowerGrasp: self.rightHandCmdMsg.data = False # relax grasp self.rightHandCmdPublisher.publish(self.rightHandCmdMsg) print "Done going to idle position!" return True def run(self): """ Runs the demo 2 behavior. """ if not self.connectToControlIt(): return index = raw_input("Start demo 2? Y/n\n") if index == "N" or index == "n": return if not self.goToReadyPosition(): return if not self.grabMetalTube(): return if not self.goToIdlePosition(): return # Main method if __name__ == "__main__": rospy.init_node('Demo2_ChangingObjectPositions', anonymous=True) demo = Demo2_ChangingObjectPositions() # t = threading.Thread(target=demo.run) # t.start() demo.run() print "Demo 2 done, waiting until ctrl+c is hit..." rospy.spin() # just to prevent this node from exiting
lgpl-2.1
xiaoxiamii/scikit-learn
benchmarks/bench_sparsify.py
323
3372
""" Benchmark SGD prediction time with dense/sparse coefficients. Invoke with ----------- $ kernprof.py -l sparsity_benchmark.py $ python -m line_profiler sparsity_benchmark.py.lprof Typical output -------------- input data sparsity: 0.050000 true coef sparsity: 0.000100 test data sparsity: 0.027400 model sparsity: 0.000024 r^2 on test data (dense model) : 0.233651 r^2 on test data (sparse model) : 0.233651 Wrote profile results to sparsity_benchmark.py.lprof Timer unit: 1e-06 s File: sparsity_benchmark.py Function: benchmark_dense_predict at line 51 Total time: 0.532979 s Line # Hits Time Per Hit % Time Line Contents ============================================================== 51 @profile 52 def benchmark_dense_predict(): 53 301 640 2.1 0.1 for _ in range(300): 54 300 532339 1774.5 99.9 clf.predict(X_test) File: sparsity_benchmark.py Function: benchmark_sparse_predict at line 56 Total time: 0.39274 s Line # Hits Time Per Hit % Time Line Contents ============================================================== 56 @profile 57 def benchmark_sparse_predict(): 58 1 10854 10854.0 2.8 X_test_sparse = csr_matrix(X_test) 59 301 477 1.6 0.1 for _ in range(300): 60 300 381409 1271.4 97.1 clf.predict(X_test_sparse) """ from scipy.sparse.csr import csr_matrix import numpy as np from sklearn.linear_model.stochastic_gradient import SGDRegressor from sklearn.metrics import r2_score np.random.seed(42) def sparsity_ratio(X): return np.count_nonzero(X) / float(n_samples * n_features) n_samples, n_features = 5000, 300 X = np.random.randn(n_samples, n_features) inds = np.arange(n_samples) np.random.shuffle(inds) X[inds[int(n_features / 1.2):]] = 0 # sparsify input print("input data sparsity: %f" % sparsity_ratio(X)) coef = 3 * np.random.randn(n_features) inds = np.arange(n_features) np.random.shuffle(inds) coef[inds[n_features/2:]] = 0 # sparsify coef print("true coef sparsity: %f" % sparsity_ratio(coef)) y = np.dot(X, coef) # add noise y += 0.01 * np.random.normal((n_samples,)) # Split data in train set and test set n_samples = X.shape[0] X_train, y_train = X[:n_samples / 2], y[:n_samples / 2] X_test, y_test = X[n_samples / 2:], y[n_samples / 2:] print("test data sparsity: %f" % sparsity_ratio(X_test)) ############################################################################### clf = SGDRegressor(penalty='l1', alpha=.2, fit_intercept=True, n_iter=2000) clf.fit(X_train, y_train) print("model sparsity: %f" % sparsity_ratio(clf.coef_)) def benchmark_dense_predict(): for _ in range(300): clf.predict(X_test) def benchmark_sparse_predict(): X_test_sparse = csr_matrix(X_test) for _ in range(300): clf.predict(X_test_sparse) def score(y_test, y_pred, case): r2 = r2_score(y_test, y_pred) print("r^2 on test data (%s) : %f" % (case, r2)) score(y_test, clf.predict(X_test), 'dense model') benchmark_dense_predict() clf.sparsify() score(y_test, clf.predict(X_test), 'sparse model') benchmark_sparse_predict()
bsd-3-clause
IndraVikas/scikit-learn
examples/calibration/plot_compare_calibration.py
241
5008
""" ======================================== Comparison of Calibration of Classifiers ======================================== Well calibrated classifiers are probabilistic classifiers for which the output of the predict_proba method can be directly interpreted as a confidence level. For instance a well calibrated (binary) classifier should classify the samples such that among the samples to which it gave a predict_proba value close to 0.8, approx. 80% actually belong to the positive class. LogisticRegression returns well calibrated predictions as it directly optimizes log-loss. In contrast, the other methods return biased probilities, with different biases per method: * GaussianNaiveBayes tends to push probabilties to 0 or 1 (note the counts in the histograms). This is mainly because it makes the assumption that features are conditionally independent given the class, which is not the case in this dataset which contains 2 redundant features. * RandomForestClassifier shows the opposite behavior: the histograms show peaks at approx. 0.2 and 0.9 probability, while probabilities close to 0 or 1 are very rare. An explanation for this is given by Niculescu-Mizil and Caruana [1]: "Methods such as bagging and random forests that average predictions from a base set of models can have difficulty making predictions near 0 and 1 because variance in the underlying base models will bias predictions that should be near zero or one away from these values. Because predictions are restricted to the interval [0,1], errors caused by variance tend to be one- sided near zero and one. For example, if a model should predict p = 0 for a case, the only way bagging can achieve this is if all bagged trees predict zero. If we add noise to the trees that bagging is averaging over, this noise will cause some trees to predict values larger than 0 for this case, thus moving the average prediction of the bagged ensemble away from 0. We observe this effect most strongly with random forests because the base-level trees trained with random forests have relatively high variance due to feature subseting." As a result, the calibration curve shows a characteristic sigmoid shape, indicating that the classifier could trust its "intuition" more and return probabilties closer to 0 or 1 typically. * Support Vector Classification (SVC) shows an even more sigmoid curve as the RandomForestClassifier, which is typical for maximum-margin methods (compare Niculescu-Mizil and Caruana [1]), which focus on hard samples that are close to the decision boundary (the support vectors). .. topic:: References: .. [1] Predicting Good Probabilities with Supervised Learning, A. Niculescu-Mizil & R. Caruana, ICML 2005 """ print(__doc__) # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # License: BSD Style. import numpy as np np.random.seed(0) import matplotlib.pyplot as plt from sklearn import datasets from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.svm import LinearSVC from sklearn.calibration import calibration_curve X, y = datasets.make_classification(n_samples=100000, n_features=20, n_informative=2, n_redundant=2) train_samples = 100 # Samples used for training the models X_train = X[:train_samples] X_test = X[train_samples:] y_train = y[:train_samples] y_test = y[train_samples:] # Create classifiers lr = LogisticRegression() gnb = GaussianNB() svc = LinearSVC(C=1.0) rfc = RandomForestClassifier(n_estimators=100) ############################################################################### # Plot calibration plots plt.figure(figsize=(10, 10)) ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) ax2 = plt.subplot2grid((3, 1), (2, 0)) ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") for clf, name in [(lr, 'Logistic'), (gnb, 'Naive Bayes'), (svc, 'Support Vector Classification'), (rfc, 'Random Forest')]: clf.fit(X_train, y_train) if hasattr(clf, "predict_proba"): prob_pos = clf.predict_proba(X_test)[:, 1] else: # use decision function prob_pos = clf.decision_function(X_test) prob_pos = \ (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) fraction_of_positives, mean_predicted_value = \ calibration_curve(y_test, prob_pos, n_bins=10) ax1.plot(mean_predicted_value, fraction_of_positives, "s-", label="%s" % (name, )) ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, histtype="step", lw=2) ax1.set_ylabel("Fraction of positives") ax1.set_ylim([-0.05, 1.05]) ax1.legend(loc="lower right") ax1.set_title('Calibration plots (reliability curve)') ax2.set_xlabel("Mean predicted value") ax2.set_ylabel("Count") ax2.legend(loc="upper center", ncol=2) plt.tight_layout() plt.show()
bsd-3-clause
Vishruit/DDP_models
code/numpy_hist_eq.py
1
2013
from keras.models import Model, load_model from keras.models import load_model from keras.models import model_from_json from keras.utils.io_utils import HDF5Matrix import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import cPickle, gzip, pickle, h5py import argparse import os, time, sys # TODO remove temporary fix # train_file_name, dataset_keyword = '../data_small_100.h5', 'data_small' train_file_name, dataset_keyword = '../Exp_17.ptw.h5', 'data_float32' def hist_eq(): image_histogram, bins = np.histogram(image.flatten(), number_bins, normed=True) cdf = image_histogram.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # normalize # use linear interpolation of cdf to find new pixel values image_equalized = np.interp(image.flatten(), bins[:-1], cdf) def data_preprocess(data): flag_isMultipleVids = 0 if len(data.shape) == 4: sample,frames,height,width = data.shape data = data.reshape((sample*frames,height,width)) flag_isMultipleVids = 1 maxVal = np.max(data, axis = -1) maxVal = np.max(maxVal, axis = -1) minVal = np.min(data, axis = -1) minVal = np.min(minVal, axis = -1) for i in range(len(maxVal)): data[i,...] = (data[i,...]-minVal[i]) / (maxVal[i]- minVal[i]+0.001) if flag_isMultipleVids == 1: data = data.reshape((sample,frames,height,width)) return data # data_slice_size = 202 # train_split, valid_split, test_split = 7, 1.5, 1.5 train_set_data = HDF5Matrix(train_file_name, dataset_keyword) image = train_set_data[1000] hist,bins = np.histogram(image,500) cdf = hist.cumsum() cdf_normalized = cdf * hist.max()/ cdf.max() # plt.plot(cdf_normalized, color = 'b') # plt.hist(img.flatten(),1000, color = 'r') cdf_m = np.ma.masked_equal(cdf,0) cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min()) cdf = np.ma.filled(cdf_m,0).astype('uint32') image_equalized = np.interp(image, bins[:-1], cdf)
gpl-3.0
pyspace/pyspace
pySPACE/missions/nodes/decorators.py
2
30475
""" Define parameter distributions for pySPACE nodes. """ from __future__ import division import abc import copy import numpy from scipy import stats try: # noinspection PyPackageRequirements from matplotlib import pyplot as plt from matplotlib import ticker as mtick except ImportError: plt = None mtick = None PARAMETER_ATTRIBUTE = "__hyperparameters" class ParameterDecorator(object): """ Abstract base class for creating parameter decorators to declare the as optimization parameters. BE CAREFUL WHEN IMPLEMENTING NEW DECORATORS. THEY MUST BE WRAPPED AND SUPPORTED BY __ALL__ OPTIMIZATION ALGORITHMS. """ __metaclass__ = abc.ABCMeta def __init__(self, parameter_name): """ Create a new optimization parameter with `parameter_name` as name The names of parameters have to be unique, as they get identified by the name. :param parameter_name: The name of the parameter to create. :type parameter_name: str """ self.parameter_name = parameter_name @abc.abstractmethod def execute(self, class_, parameters): """ Execute the decorator This method will be called during creation of the class object and will update the given set of hyperparameters according to the implementation of the subclass. :param class_: The class object this parameter decorates :type class_: type :param parameters: The set of parameters to append to or delete from :type parameters: set(ParameterDecorator) """ raise NotImplementedError("Execute Method has to be overwritten by subclasses") @abc.abstractmethod def plot(self): """ Plot the given parameter distribution This method is used to plot the specified distribution of this decorator. For plotting either (if installed) the `matplotlib.pyplot` can be used and return a figure, or (if not installed) a string specifying the distribution can be returned. :returns: The figure where this distribution is plotted or a string specifying the distribution :rtype: matplotlib.figure.Figure | str """ raise NotImplementedError() def __call__(self, class_): if not hasattr(class_, PARAMETER_ATTRIBUTE): # No hyper parameter attribute, create a new one setattr(class_, PARAMETER_ATTRIBUTE, set()) # Deep copy the parameter attribute to avoid side-effects to super-classes parameters = copy.deepcopy(getattr(class_, PARAMETER_ATTRIBUTE)) # Execute the Decorator on the copy self.execute(class_, parameters) # And replace the attribute with the copy setattr(class_, PARAMETER_ATTRIBUTE, parameters) # Return the class object return class_ def __eq__(self, other): if hasattr(other, "parameter_name"): return self.parameter_name == other.parameter_name elif isinstance(other, basestring): return self.parameter_name == other return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.parameter_name) def __str__(self): return self.parameter_name def __repr__(self): return "{cls}<{name}>".format(cls=self.__class__.__name__, name=self.parameter_name) class AddedParameterDecorator(ParameterDecorator): """ This mixin adds an execute method to classes that inherit from it. This mixin will check if the given parameter is already defined and if so removes the old definition and adds the new one. """ __metaclass__ = abc.ABCMeta def execute(self, class_, parameters): if self in parameters: parameters.remove(self) parameters.add(self) class QMixin(object): """ This mixin adds a regulation parameter `q` to bind a distribution to discrete values. """ def __init__(self, q): """ Add the new regulation parameter. :param q: The regulation value :type q: float """ self.__q = q @property def q(self): return self.__q def round_to_q(self, value): """ Round a value to the next multiple of `q`. This is required for the plotting only. :param value: The value to round :type value: float """ return numpy.round(value / self.q) * self.q def calc_probability(self, value, pdf_func): # Integral borders a = value - self.q / 2 b = value + self.q / 2 # Create a linear space between these two borders x, dx = numpy.linspace(start=a, stop=b, num=10000, retstep=True) # Then calculate the PDF value for each of them y = numpy.vectorize(lambda v: pdf_func(v))(x) # And then integrate return numpy.trapz(y=y, x=x, dx=dx) class ChoiceParameter(AddedParameterDecorator): """ Defines a parameter as to be chosen from the given set of options. This parameter will be then chosen from this set during the optimization. ..code-block:: python >>> @ChoiceParameter("test", choices=["A", "B", "C"] ... class A(object): ... pass """ def __init__(self, parameter_name, choices): """ Create a new choice parameter with `parameter_name` as name and `choices` as the possible values. :param parameter_name: The name of the parameter to create. :type parameter_name: str :param choices: The possible values for this parameter. :type choices: str | List[str] """ super(ChoiceParameter, self).__init__(parameter_name=parameter_name) if not isinstance(choices, list): choices = [choices] self.__choices = choices @property def choices(self): return self.__choices def plot(self): return "{self!r}(choices={self.choices!s})".format(self=self) class BooleanParameter(ChoiceParameter): """ Defines a parameter as a being a boolean parameter. This parameter will either be "true" or "false" during the optimization. ..code-block:: python >>> @BooleanParameter("test") ... class A(object): ... pass """ def __init__(self, parameter_name): """ Creates a new boolean parameter with `parameter_name` as name. :param parameter_name: The name of the parameter to create. :type parameter_name: str """ super(BooleanParameter, self).__init__(parameter_name, [True, False]) class PChoiceParameter(ChoiceParameter): """ Defines a parameter as a probability choice. This parameter will sample each of the given choices with the according probability. ..code-block:: python >>> @PChoiceParameter("test", choices={"A": 0.5, "B": 0.25, "C": 0.25}) ... class A(object): ... pass """ def __init__(self, parameter_name, choices): """ Create a new probability choice parameter with `parameter_name` as name and `choices` as the possible values. Each choice must be a tuple containing first the probability in range from 0 to 1 for that choice and the value to choose as a second argument. The probabilities of all choices need to sum up to 1. :param parameter_name: The name of the parameter to create. :type parameter_name: str :param choices: A dictionary of tuples containing the value of each choice as keys and the corresponding probabilities as values. :type choices: dict[object, float] """ if sum(choices.values()) != 1: raise RuntimeError("The probabilities for parameter '%s'" "do not sum up to 1" % parameter_name) super(PChoiceParameter, self).__init__(parameter_name, choices.items()) class NormalParameter(AddedParameterDecorator): """ Defines a parameter as being normal distributed. A normal distributed parameter will be sampled from the defined distribution by the mean and standard deviation. This parameter will be sampled from a function like: normal(mu, sigma) This parameter is unbound. .. code-block:: python >>> @NormalParameter("test", mu=0, sigma=1) ... class A(object): ... pass """ class Normal(object): def __init__(self, mu, sigma): self.mu = mu self.sigma = sigma def pdf(self, x): sqrt = numpy.sqrt(2 * numpy.pi * (self.sigma ** 2)) return 1 / sqrt * numpy.e ** (-((x - self.mu) ** 2) / (2 * self.sigma ** 2)) def mean(self): return self.mu def __init__(self, parameter_name, mu, sigma): """ Create a new normal distributed parameter with `parameter_name` as name. The mean `mu` and standard deviation `sigma` are defining the distribution this parameter will be sampled from. :param parameter_name: The name of the parameter to create. :type parameter_name: str :param mu: The mean value of the distribution for this parameter :type mu: float :param sigma: The standard deviation of the distribution for this parameter :type sigma: float """ super(NormalParameter, self).__init__(parameter_name=parameter_name) self.__mu = mu self.__sigma = sigma @property def mu(self): return self.__mu @property def sigma(self): return self.__sigma def plot(self): if plt is not None: rv = self.Normal(self.mu, self.sigma) # mu +/- 3sigma => 99,7% confidence interval start = self.mu - 3 * self.sigma stop = self.mu + 3 * self.sigma # Min 1.000 samples, max 10.000 num = min(max(stop - start * 100, 1000), 10000) figure = plt.figure() plt.ylabel("PDF(x)") plt.xlabel("X") figure.suptitle("Normal distribution for Parameter {param!s}".format(param=self.parameter_name)) x = numpy.linspace(start=start, stop=stop, num=num) y = numpy.vectorize(lambda x_: rv.pdf(x_))(x) axes = plt.plot(x, y, label="mu={self.mu:g}, sigma={self.sigma:g}".format(self=self)) mean_x = rv.mean() mean_y = rv.pdf(mean_x) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=axes[0].get_color(), label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) return figure else: return "{self!r}(mu={self.mu:g}, sigma={self.sigma:g})".format(self=self) class UniformParameter(AddedParameterDecorator): """ Defines a parameter as being uniform distributed. A uniform distributed parameter will be sampled equally distributed between a given minimum and maximum value. The value of this parameter will be sampled from a function like: .. code-block:: python uniform(min, max) This parameter is bound to [min, max]. .. code-block:: python >>> @UniformParameter("test", min_value=1, max_value=10) ... class A(object): ... pass """ class Uniform(object): def __init__(self, a, b): self.a = a self.b = b self.__diff = b - a def pdf(self, x): if self.a > x or x > self.b: return 0.0 return 1.0 / self.__diff def cdf(self, x): if x <= self.a: return 0.0 elif x >= self.b: return 1.0 else: return (x - self.a) / self.__diff def mean(self): return .5 * (self.a + self.b) def __init__(self, parameter_name, min_value, max_value): """ Create a new uniform distributed parameter with `parameter_name` as name. The `min_value` and `max_value` define the borders for this distribution in between which the value will be sampled. :param min_value: The minimum value of the parameter :type min_value: float :param max_value: The maximum value of the parameter :type max_value: float """ super(UniformParameter, self).__init__(parameter_name=parameter_name) self.__min = min_value self.__max = max_value @property def min(self): return self.__min @property def max(self): return self.__max def plot(self): if plt is not None: rv = self.Uniform(self.min, self.max) # Min 1.000 samples, max 10.000 num = min(max(self.max - self.min, 1000), 10000) figure = plt.figure() plt.ylabel("PDF(x)") plt.xlabel("X") plt.suptitle("Uniform distribution of parameter {param!s}".format(param=self.parameter_name)) x = numpy.linspace(start=self.min - 1, stop=self.max + 1, num=num) y = numpy.vectorize(lambda value: rv.pdf(value))(x) axes = plt.plot(x, y, label="min={self.min:g}, max={self.max:g}".format(self=self)) mean_x = rv.mean() mean_y = rv.pdf(mean_x) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=axes[0].get_color(), label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) return figure else: return "{self!r}(min={self.min:g}, max={self.max:g})".format(self=self) class QNormalParameter(NormalParameter, QMixin): """ Defines a parameter as being normal distributed but to only take discrete values. A q-normal distributed parameter will be sampled from the distribution defined by a mean and a standard deviation but it will be bound to discrete values regularized by a regulation parameter. Therefore the value will be sampled from a function like this: round(normal(mu, sigma) / q) * q This parameter is unbound. .. code-block:: python >>> @QNormalParameter("test", mu=0, sigma=1, q=0.5) ... class A(object): ... pass """ def __init__(self, parameter_name, mu, sigma, q): """ Creates a new q-normal distributed parameter with `parameter_name` as name. The mean `mu` and standard deviation `sigma` are defining the distribution this parameter will be sampled from. But it will be bound to discrete values by the regulation parameter `q`. :param parameter_name: The name of the parameter to create. :type parameter_name: str :param mu: The mean value of the distribution for the parameter :type mu: float :param sigma: The standard deviation of the distribution for the parameter :type sigma: float :param q: The regulation parameter to bind the values with. :type q: float """ super(QNormalParameter, self).__init__(parameter_name=parameter_name, mu=mu, sigma=sigma) QMixin.__init__(self, q=q) def plot(self): # mu +/- 3sigma => 99,7% confidence interval if plt is not None: rv = self.Normal(self.mu, self.sigma) # mu +/- 3sigma => 99,7% confidence interval start = self.round_to_q(self.mu - 3 * self.sigma) stop = self.round_to_q(self.mu + 3 * self.sigma) figure = plt.figure() plt.ylabel("P(X=x)") plt.xlabel("X") figure.suptitle("Q-Normal distribution for Parameter {param!s}".format(param=self.parameter_name)) x = numpy.arange(start=start, stop=stop + self.q, step=self.q) y = numpy.vectorize(lambda x_: self.calc_probability(x_, rv.pdf))(x) axes = plt.scatter(x, y, label="mu={self.mu:g}, sigma={self.sigma:g}, q={self.q:g}".format(self=self)) mean_x = self.round_to_q(rv.mean()) mean_y = self.calc_probability(mean_x, rv.pdf) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=axes.get_facecolor()[0], label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) return figure else: return "{self!r}(mu={self.mu:g}, sigma={self.sigma:g}, q={self.q:g})".format(self=self) class QUniformParameter(UniformParameter, QMixin): """ Defines a parameter as being uniform distributed but to take only discrete values. A uniform distributed parameter will be sampled equally distributed between a given minimum and maximum value and will be bound by a regulation parameter. The value will be sampled from a function like this: round(uniform(min, max) / q) * q This parameter is bound to [floor(min), tail(max)]. .. code-block:: python >>> @QUniformParameter("test", min_value=0, max_value=10, q=0.5) ... class A(object): ... pass """ def __init__(self, parameter_name, min_value, max_value, q): """ Creates a new q-uniform distributed parameter with `parameter_name` as name. The `min_value` and `max_value` define the borders for this distribution in between which the value will be sampled. But this distribution will be bound to discrete values by the regulation parameter `q`. :param min_value: The minimum value of the parameter :type min_value: float :param max_value: The maximum value of the parameter :type max_value: float :param q: The regulation parameter to bind the values with. :type q: float """ super(QUniformParameter, self).__init__(parameter_name=parameter_name, min_value=min_value, max_value=max_value) QMixin.__init__(self, q=q) def plot(self): if plt is not None: start = self.round_to_q(self.min) - 2 * self.q stop = self.round_to_q(self.max) + 2 * self.q rv = self.Uniform(self.min - self.q / 2, self.max + self.q / 2) figure = plt.figure() plt.ylabel("P(X=x)") plt.xlabel("X") plt.suptitle("Q-Uniform distribution of parameter {param!s}".format(param=self.parameter_name)) x = numpy.arange(start=start, stop=stop + self.q, step=self.q) y = numpy.vectorize(lambda value: self.calc_probability(value, rv.pdf))(x) axes = plt.scatter(x, y, label="min={self.min:g}, max={self.max:g}, q={self.q:g}".format(self=self)) mean_x = self.round_to_q(rv.mean()) mean_y = self.calc_probability(mean_x, rv.pdf) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=axes.get_facecolor()[0], label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) return figure else: return "{self!r}(min={self.min:g}, max={self.max:g}, q={self.q:g})".format(self=self) class LogNormalParameter(AddedParameterDecorator): """ Defines a parameter as being drawn from the exponential of a normal distribution. A log-normal distributed parameter will be sampled from exponential of the defined distribution by a mean and a standard deviation. The values for this parameter will be sampled from a function like: exp(normal(mu, sigma)) This distribution causes that the logarithm of the samples values are being normal distributed. This parameter is bound to positive numbers only. .. code-block:: python >>> @LogNormalParameter("test", shape=1, scale=1) ... class A(object): ... pass """ def __init__(self, parameter_name, shape, scale): super(LogNormalParameter, self).__init__(parameter_name) self.__shape = shape self.__scale = scale @property def shape(self): return self.__shape @property def scale(self): return self.__scale def plot(self): if plt is not None: rv = stats.lognorm(s=self.shape, scale=self.scale) start, stop = rv.interval(0.99) # Min 1.000 samples, max 10.000 num = min(max(stop - start * 100, 1000), 10000) figure = plt.figure() plt.ylabel("PDF(x)") plt.xlabel("X") figure.suptitle("Log-Normal distribution for Parameter {param!s}".format(param=self.parameter_name)) x = numpy.logspace(start=numpy.log(start), stop=numpy.log(stop), base=numpy.e, num=num) y = rv.pdf(x) axes = plt.plot(x, y, label="shape={self.shape:g}, scale={self.scale:g}".format(self=self)) mean_x = rv.mean() mean_y = rv.pdf(mean_x) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=axes[0].get_color(), label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) plt.xscale("log") return figure else: return "{self!r}(shape={self.shape:g}, scale={self.scale:g})".format(self=self) class LogUniformParameter(UniformParameter): """ Defines a parameter as being drawn from the exponential of a uniform distribution. A log-uniform distributed parameter will be sampled from the exponential of equally distributed values between a given minimum and maximum value. The values for this parameter will be sampled from a function like: exp(uniform(min, max)) This distribution causes that the logarithm of the samples values are being uniform distributed. This parameter is bound to [exp(min), exp(max)]. .. code-block:: python >>> @LogUniformParameter("test", min_value=0, max_value=1000) ... class A(object): ... pass """ class LogUniform(object): log = numpy.log def __init__(self, a, b): self.__a = a self.__al = self.log(a) if a > 0 else self.log(1e-320) self.__b = b self.__bl = self.log(b) if b > 0 else self.log(1e-320) def pdf(self, x): if x >= 0 and self.__al <= self.log(x) <= self.__bl: return 1 / (x * (self.__bl - self.__al)) else: return 0.0 def cdf(self, x): xl = self.log(x) if xl < self.__al: return 0.0 elif xl > self.__bl: return 1 else: return (xl - self.__al) / (self.__bl - self.__al) def mean(self): return (self.__b - self.__a) / (self.__bl - self.__al) def plot(self): if plt is not None: rv = self.LogUniform(self.min, self.max) # Min 1.000 samples, max 100.000 num = min(max(self.max - self.min, 1000), 100000) figure = plt.figure() plt.ylabel("PDF(x)") plt.xlabel("X") plt.suptitle("Log-Uniform distribution of parameter {param!s}".format(param=self.parameter_name)) x = numpy.logspace(start=numpy.log10(max(self.min - 1, 1e-10)), stop=numpy.log10(self.max + 1), base=10, num=num) y = numpy.vectorize(lambda value: rv.pdf(value))(x) mean_x = rv.mean() mean_y = rv.pdf(mean_x) line, = plt.plot(x, y, label="min={self.min:g}, max={self.max:g}".format(self=self)) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=line.get_color(), label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) plt.xscale("log", basex=10) plt.yscale("log", basey=10) return figure else: return "{self!r}(min={self.min:g}, max={self.max:g})".format(self=self) class QLogNormalParameter(LogNormalParameter, QMixin): """ Defines a parameter as being drawn from the exponential of a normal distribution. A log-normal distributed parameter will be sampled from exponential of the defined distribution by a mean and a standard deviation but it will be bound to discrete values regularized by a regulation parameter. The values for this parameter will be sampled from a function like: round(exp(normal(mu, sigma)) / q) * q This distribution causes that the logarithm of the samples values are being normal distributed. This parameter is bound to positive number only. .. code-block:: python >>> @QLogNormalParameter("test", shape=1, scale=1, q=0.5) ... class A(object): ... pass """ def __init__(self, parameter_name, shape, scale, q): LogNormalParameter.__init__(self, parameter_name, shape, scale) QMixin.__init__(self, q) def plot(self): if plt is not None: rv = stats.lognorm(s=self.shape, scale=self.scale) start, stop = rv.interval(0.99) figure = plt.figure() plt.ylabel("P(X=x)") plt.xlabel("X") figure.suptitle("Q-Log-Normal distribution for Parameter {param!s}".format(param=self.parameter_name)) x = numpy.arange(start=self.round_to_q(start), stop=self.round_to_q(stop) + self.q, step=self.q) y = numpy.vectorize(lambda x_: self.calc_probability(x_, rv.pdf))(x) axes = plt.scatter(x, y, label="shape={self.shape:g}, scale={self.scale:g}, q={self.q:g}".format(self=self)) mean_x = self.round_to_q(rv.mean()) mean_y = self.calc_probability(mean_x, rv.pdf) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=axes.get_facecolor()[0], label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) plt.xscale("log") return figure else: return "{self!r}(shape={self.shape:g}, scale={self.scale:g}, q={self.q:g})".format(self=self) class QLogUniformParameter(LogUniformParameter, QMixin): """ Defines a parameter as being drawn from the exponential of a uniform distribution and being bound to discrete values only. A q-log-uniform distributed parameter will be sampled from the exponential of equally distributed values between a given minimum and maximum value and will be bound by a regulation parameter. The values for this parameter will be sampled from a function like: round(exp(uniform(min, max)) / q) * q This distribution causes that the logarithm of the samples values are being uniform distributed. This parameter is bound to [exp(min), exp(max)]. .. code-block:: python >>> @QLogUniformParameter("test", min_value=0, max_value=1000, q=0.5) ... class A(object): ... pass """ def __init__(self, parameter_name, min_value, max_value, q): LogUniformParameter.__init__(self, parameter_name, min_value, max_value) QMixin.__init__(self, q) def plot(self): rv = self.LogUniform(self.min - self.q / 2, self.max + self.q / 2) if plt is not None: start = self.round_to_q(self.min) - 2 * self.q stop = self.round_to_q(self.max) + 2 * self.q figure = plt.figure() plt.ylabel("P(X=x)") plt.xlabel("X") plt.suptitle("Q-Log-Uniform distribution of parameter {param!s}".format(param=self.parameter_name)) x = numpy.arange(start=start, stop=stop + self.q, step=self.q) y = numpy.vectorize(lambda value: self.calc_probability(value, rv.pdf))(x) mean_x = self.round_to_q(rv.mean()) mean_y = self.calc_probability(mean_x, rv.pdf) axes = plt.scatter(x, y, label="min={self.min:g}, max={self.max:g}, q={self.q:g}".format(self=self)) y_max = 1.0 / (plt.ylim()[1] - plt.ylim()[0]) * (mean_y - plt.ylim()[0]) plt.axvline(x=mean_x, ymax=y_max, linestyle="--", color=axes.get_facecolor()[0], label="Mean: %g" % mean_x) plt.legend(loc="best", fancybox=True, framealpha=0.2).draggable(True) plt.xscale("log", basex=10) plt.yscale("log", basey=10) return figure else: return "{self!r}(min={self.min:g}, max={self.max:g}, q={self.q:g})".format(self=self) class NoOptimizationParameter(AddedParameterDecorator): """ Defines a previously defined parameter as not being an optimization parameter at all. This decorator can be used in derived classes where optimization parameters of base classes are given concrete values or don't matter at all. .. code-block:: python >>> @NoOptimizationParameter("test") ... class A(object): ... pass """ def plot(self): return repr(self) PARAMETER_TYPES = { "Choice": ChoiceParameter, "Boolean": BooleanParameter, "PChoice": PChoiceParameter, "Normal": NormalParameter, "Uniform": UniformParameter, "QNormal": QNormalParameter, "QUniform": QUniformParameter, "LogNormal": LogNormalParameter, "LogUniform": LogUniformParameter, "QLogNormal": QLogNormalParameter, "QLogUniform": QLogUniformParameter, "NoOptimization": NoOptimizationParameter }
bsd-3-clause
CVML/scikit-learn
sklearn/feature_selection/tests/test_chi2.py
221
2398
""" Tests for chi2, currently the only feature selection function designed specifically to work with sparse matrices. """ import numpy as np from scipy.sparse import coo_matrix, csr_matrix import scipy.stats from sklearn.feature_selection import SelectKBest, chi2 from sklearn.feature_selection.univariate_selection import _chisquare from nose.tools import assert_raises from numpy.testing import assert_equal, assert_array_almost_equal # Feature 0 is highly informative for class 1; # feature 1 is the same everywhere; # feature 2 is a bit informative for class 2. X = [[2, 1, 2], [9, 1, 1], [6, 1, 2], [0, 1, 2]] y = [0, 1, 2, 2] def mkchi2(k): """Make k-best chi2 selector""" return SelectKBest(chi2, k=k) def test_chi2(): # Test Chi2 feature extraction chi2 = mkchi2(k=1).fit(X, y) chi2 = mkchi2(k=1).fit(X, y) assert_equal(chi2.get_support(indices=True), [0]) assert_equal(chi2.transform(X), np.array(X)[:, [0]]) chi2 = mkchi2(k=2).fit(X, y) assert_equal(sorted(chi2.get_support(indices=True)), [0, 2]) Xsp = csr_matrix(X, dtype=np.float) chi2 = mkchi2(k=2).fit(Xsp, y) assert_equal(sorted(chi2.get_support(indices=True)), [0, 2]) Xtrans = chi2.transform(Xsp) assert_equal(Xtrans.shape, [Xsp.shape[0], 2]) # == doesn't work on scipy.sparse matrices Xtrans = Xtrans.toarray() Xtrans2 = mkchi2(k=2).fit_transform(Xsp, y).toarray() assert_equal(Xtrans, Xtrans2) def test_chi2_coo(): # Check that chi2 works with a COO matrix # (as returned by CountVectorizer, DictVectorizer) Xcoo = coo_matrix(X) mkchi2(k=2).fit_transform(Xcoo, y) # if we got here without an exception, we're safe def test_chi2_negative(): # Check for proper error on negative numbers in the input X. X, y = [[0, 1], [-1e-20, 1]], [0, 1] for X in (X, np.array(X), csr_matrix(X)): assert_raises(ValueError, chi2, X, y) def test_chisquare(): # Test replacement for scipy.stats.chisquare against the original. obs = np.array([[2., 2.], [1., 1.]]) exp = np.array([[1.5, 1.5], [1.5, 1.5]]) # call SciPy first because our version overwrites obs chi_scp, p_scp = scipy.stats.chisquare(obs, exp) chi_our, p_our = _chisquare(obs, exp) assert_array_almost_equal(chi_scp, chi_our) assert_array_almost_equal(p_scp, p_our)
bsd-3-clause
mlperf/inference_results_v0.7
closed/Altos/code/dlrm/tensorrt/infer.py
18
4431
#! /usr/bin/env python3 # Copyright (c) 2020, NVIDIA CORPORATION. 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. import os, sys import ctypes sys.path.insert(0, os.getcwd()) # The plugin .so file has to be loaded at global scope and before `import torch` to avoid cuda version mismatch. DLRM_INTERACTIONS_PLUGIN_LIBRARY="build/plugins/DLRMInteractionsPlugin/libdlrminteractionsplugin.so" if not os.path.isfile(DLRM_INTERACTIONS_PLUGIN_LIBRARY): raise IOError("{}\n{}\n".format( "Failed to load library ({}).".format(DLRM_INTERACTIONS_PLUGIN_LIBRARY), "Please build the DLRM Interactions plugin." )) ctypes.CDLL(DLRM_INTERACTIONS_PLUGIN_LIBRARY) DLRM_BOTTOM_MLP_PLUGIN_LIBRARY="build/plugins/DLRMBottomMLPPlugin/libdlrmbottommlpplugin.so" if not os.path.isfile(DLRM_BOTTOM_MLP_PLUGIN_LIBRARY): raise IOError("{}\n{}\n".format( "Failed to load library ({}).".format(DLRM_BOTTOM_MLP_PLUGIN_LIBRARY), "Please build the DLRM Bottom MLP plugin." )) ctypes.CDLL(DLRM_BOTTOM_MLP_PLUGIN_LIBRARY) from code.common.runner import EngineRunner, get_input_format from code.common import logging import code.common.arguments as common_args import json import numpy as np from sklearn.metrics import roc_auc_score import tensorrt as trt import torch import time def evaluate(ground_truths, predictions): assert len(ground_truths) == len(predictions), "Number of ground truths are different from number of predictions" return roc_auc_score(ground_truths, predictions) def run_dlrm_accuracy(engine_file, batch_size, num_pairs=10000000, verbose=False): if verbose: logging.info("Running DLRM accuracy test with:") logging.info(" engine_file: {:}".format(engine_file)) logging.info(" batch_size: {:}".format(batch_size)) logging.info(" num_pairs: {:}".format(num_pairs)) runner = EngineRunner(engine_file, verbose=verbose) pair_dir = os.path.join(os.getenv("PREPROCESSED_DATA_DIR", "build/preprocessed_data"), "criteo", "full_recalib") input_dtype, input_format = get_input_format(runner.engine) if input_dtype == trt.DataType.FLOAT: format_string = "fp32" elif input_dtype == trt.DataType.HALF: format_string = "fp16" elif input_dtype == trt.DataType.INT8: format_string = "int8" if input_format == trt.TensorFormat.CHW4: format_string += "_chw4" else: raise NotImplementedError("Unsupported DataType {:}".format(input_dtype)) numerical_inputs = np.load(os.path.join(pair_dir, "numeric_{:}.npy".format(format_string))) categ_inputs = np.load(os.path.join(pair_dir, "categorical_int32.npy")) predictions = [] refs = [] batch_idx = 0 for pair_idx in range(0, int(num_pairs), batch_size): actual_batch_size = batch_size if pair_idx + batch_size <= num_pairs else num_pairs - pair_idx numerical_input = np.ascontiguousarray(numerical_inputs[pair_idx:pair_idx + actual_batch_size]) categ_input = np.ascontiguousarray(categ_inputs[pair_idx:pair_idx + actual_batch_size]) start_time = time.time() outputs = runner([numerical_input, categ_input], actual_batch_size) if verbose: logging.info("Batch {:d} (Size {:}) >> Inference time: {:f}".format(batch_idx, actual_batch_size, time.time() - start_time)) predictions.extend(outputs[0][:actual_batch_size]) batch_idx += 1 ground_truths = np.load(os.path.join(pair_dir, "ground_truth.npy"))[:num_pairs].tolist() return evaluate(ground_truths, predictions) def main(): args = common_args.parse_args(common_args.ACCURACY_ARGS) logging.info("Running accuracy test...") acc = run_dlrm_accuracy(args["engine_file"], args["batch_size"], args["num_samples"], verbose=args["verbose"]) logging.info("Accuracy: {:}".format(acc)) if __name__ == "__main__": main()
apache-2.0
andrescodas/casadi
docs/examples/python/dae_collocation.py
3
14838
# # This file is part of CasADi. # # CasADi -- A symbolic framework for dynamic optimization. # Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, # K.U. Leuven. All rights reserved. # Copyright (C) 2011-2014 Greg Horn # # CasADi 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. # # CasADi 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 Lesser General Public # License along with CasADi; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # # -*- coding: utf-8 -*- """ @author: Mario Zanon and Sebastien Gross, K.U. Leuven 2012 """ from casadi import * import numpy as np import matplotlib.pyplot as plt # ----------------------------------------------------------------------------- # Collocation setup # ----------------------------------------------------------------------------- nicp = 1 # Number of (intermediate) collocation points per control interval xref = 0.1 # chariot reference l = 1. #- -> crane, + -> pendulum m = 1. M = 1. g = 9.81 tf = 5.0 nk = 50 ndstate = 6 nastate = 1 ninput = 1 # Degree of interpolating polynomial deg = 4 # Radau collocation points cp = "radau" # Size of the finite elements h = tf/nk/nicp # Coefficients of the collocation equation C = np.zeros((deg+1,deg+1)) # Coefficients of the continuity equation D = np.zeros(deg+1) # Collocation point tau = SX.sym("tau") # All collocation time points tau_root = [0] + collocation_points(deg, cp) T = np.zeros((nk,deg+1)) for i in range(nk): for j in range(deg+1): T[i][j] = h*(i + tau_root[j]) # For all collocation points: eq 10.4 or 10.17 in Biegler's book # Construct Lagrange polynomials to get the polynomial basis at the collocation point for j in range(deg+1): L = 1 for j2 in range(deg+1): if j2 != j: L *= (tau-tau_root[j2])/(tau_root[j]-tau_root[j2]) # Evaluate the polynomial at the final time to get the coefficients of the continuity equation lfcn = Function('lfcn', [tau],[L]) D[j] = lfcn(1.0) # Evaluate the time derivative of the polynomial at all collocation points to get the coefficients of the continuity equation tfcn = Function('tfcn', [tau],[tangent(L,tau)]) for j2 in range(deg+1): C[j][j2] = tfcn(tau_root[j2]) # ----------------------------------------------------------------------------- # Model setup # ----------------------------------------------------------------------------- # Declare variables (use scalar graph) t = SX.sym("t") # time u = SX.sym("u") # control xd = SX.sym("xd",ndstate) # differential state xa = SX.sym("xa",nastate) # algebraic state xddot = SX.sym("xdot",ndstate) # differential state time derivative p = SX.sym("p",0,1) # parameters x = SX.sym("x") y = SX.sym("y") w = SX.sym("w") dx = SX.sym("dx") dy = SX.sym("dy") dw = SX.sym("dw") res = vertcat(xddot[0] - dx,\ xddot[1] - dy,\ xddot[2] - dw,\ m*xddot[3] + (x-w)*xa, \ m*xddot[4] + y*xa - g*m,\ M*xddot[5] + (w-x)*xa + u,\ (x-w)*(xddot[3] - xddot[5]) + y*xddot[4] + dy*dy + (dx-dw)*(dx-dw)) xd[0] = x xd[1] = y xd[2] = w xd[3] = dx xd[4] = dy xd[5] = dw # System dynamics (implicit formulation) ffcn = Function('ffcn', [t,xddot,xd,xa,u,p],[res]) # Objective function MayerTerm = Function('mayer', [t,xd,xa,u,p],[(x-xref)*(x-xref) + (w-xref)*(w-xref) + dx*dx + dy*dy]) LagrangeTerm = Function('lagrange', [t,xd,xa,u,p],[(x-xref)*(x-xref) + (w-xref)*(w-xref)]) # Control bounds u_min = np.array([-2]) u_max = np.array([ 2]) u_init = np.array((nk*nicp*(deg+1))*[[0.0]]) # needs to be specified for every time interval (even though it stays constant) # Differential state bounds #Path bounds xD_min = np.array([-inf, -inf, -inf, -inf, -inf, -inf]) xD_max = np.array([ inf, inf, inf, inf, inf, inf]) #Initial bounds xDi_min = np.array([ 0.0, l, 0.0, 0.0, 0.0, 0.0]) xDi_max = np.array([ 0.0, l, 0.0, 0.0, 0.0, 0.0]) #Final bounds xDf_min = np.array([-inf, -inf, -inf, -inf, -inf, -inf]) xDf_max = np.array([ inf, inf, inf, inf, inf, inf]) #Initial guess for differential states xD_init = np.array((nk*nicp*(deg+1))*[[ 0.0, l, 0.0, 0.0, 0.0, 0.0]]) # needs to be specified for every time interval # Algebraic state bounds and initial guess xA_min = np.array([-inf]) xA_max = np.array([ inf]) xAi_min = np.array([-inf]) xAi_max = np.array([ inf]) xAf_min = np.array([-inf]) xAf_max = np.array([ inf]) xA_init = np.array((nk*nicp*(deg+1))*[[sign(l)*9.81]]) # Parameter bounds and initial guess p_min = np.array([]) p_max = np.array([]) p_init = np.array([]) # ----------------------------------------------------------------------------- # Constraints setup # ----------------------------------------------------------------------------- # Initial constraint ic_min = np.array([]) ic_max = np.array([]) ic = SX() #ic.append(); ic_min = append(ic_min, 0.); ic_max = append(ic_max, 0.) icfcn = Function('icfcn', [t,xd,xa,u,p],[ic]) # Path constraint pc_min = np.array([]) pc_max = np.array([]) pc = SX() #pc.append(); pc_min = append(pc_min, 0.); pc_max = append(pc_max, 0.) pcfcn = Function('pcfcn', [t,xd,xa,u,p],[pc]) # Final constraint fc_min = np.array([]) fc_max = np.array([]) fc = SX() #fc.append(); fc_min = append(fc_min, 0.); fc_max = append(fc_max, 0.) fcfcn = Function('fcfcn', [t,xd,xa,u,p],[fc]) # ----------------------------------------------------------------------------- # NLP setup # ----------------------------------------------------------------------------- # Dimensions of the problem nx = xd.nnz() + xa.nnz() # total number of states #MODIF ndiff = xd.nnz() # number of differential states #MODIF nalg = xa.nnz() # number of algebraic states nu = u.nnz() # number of controls NP = p.nnz() # number of parameters # Total number of variables NXD = nicp*nk*(deg+1)*ndiff # Collocated differential states NXA = nicp*nk*deg*nalg # Collocated algebraic states NU = nk*nu # Parametrized controls NXF = ndiff # Final state (only the differential states) NV = NXD+NXA+NU+NXF+NP # NLP variable vector V = MX.sym("V",NV) # All variables with bounds and initial guess vars_lb = np.zeros(NV) vars_ub = np.zeros(NV) vars_init = np.zeros(NV) offset = 0 # Get the parameters P = V[offset:offset+NP] vars_init[offset:offset+NP] = p_init vars_lb[offset:offset+NP] = p_min vars_ub[offset:offset+NP] = p_max offset += NP # Get collocated states and parametrized control XD = np.resize(np.array([],dtype=MX),(nk+1,nicp,deg+1)) # NB: same name as above XA = np.resize(np.array([],dtype=MX),(nk,nicp,deg)) # NB: same name as above U = np.resize(np.array([],dtype=MX),nk) for k in range(nk): # Collocated states for i in range(nicp): # for j in range(deg+1): # Get the expression for the state vector XD[k][i][j] = V[offset:offset+ndiff] if j !=0: XA[k][i][j-1] = V[offset+ndiff:offset+ndiff+nalg] # Add the initial condition index = (deg+1)*(nicp*k+i) + j if k==0 and j==0 and i==0: vars_init[offset:offset+ndiff] = xD_init[index,:] vars_lb[offset:offset+ndiff] = xDi_min vars_ub[offset:offset+ndiff] = xDi_max offset += ndiff else: if j!=0: vars_init[offset:offset+nx] = np.append(xD_init[index,:],xA_init[index,:]) vars_lb[offset:offset+nx] = np.append(xD_min,xA_min) vars_ub[offset:offset+nx] = np.append(xD_max,xA_max) offset += nx else: vars_init[offset:offset+ndiff] = xD_init[index,:] vars_lb[offset:offset+ndiff] = xD_min vars_ub[offset:offset+ndiff] = xD_max offset += ndiff # Parametrized controls U[k] = V[offset:offset+nu] vars_lb[offset:offset+nu] = u_min vars_ub[offset:offset+nu] = u_max vars_init[offset:offset+nu] = u_init[index,:] offset += nu # State at end time XD[nk][0][0] = V[offset:offset+ndiff] vars_lb[offset:offset+ndiff] = xDf_min vars_ub[offset:offset+ndiff] = xDf_max vars_init[offset:offset+ndiff] = xD_init[-1,:] offset += ndiff assert(offset==NV) # Constraint function for the NLP g = [] lbg = [] ubg = [] # Initial constraints ick = icfcn(0., XD[0][0][0], XA[0][0][0], U[0], P) g += [ick] lbg.append(ic_min) ubg.append(ic_max) # For all finite elements for k in range(nk): for i in range(nicp): # For all collocation points for j in range(1,deg+1): # Get an expression for the state derivative at the collocation point xp_jk = 0 for j2 in range (deg+1): xp_jk += C[j2][j]*XD[k][i][j2] # get the time derivative of the differential states (eq 10.19b) # Add collocation equations to the NLP fk = ffcn(0., xp_jk/h, XD[k][i][j], XA[k][i][j-1], U[k], P) g += [fk[:ndiff]] # impose system dynamics (for the differential states (eq 10.19b)) lbg.append(np.zeros(ndiff)) # equality constraints ubg.append(np.zeros(ndiff)) # equality constraints g += [fk[ndiff:]] # impose system dynamics (for the algebraic states (eq 10.19b)) lbg.append(np.zeros(nalg)) # equality constraints ubg.append(np.zeros(nalg)) # equality constraints # Evaluate the path constraint function pck = pcfcn(0., XD[k][i][j], XA[k][i][j-1], U[k], P) g += [pck] lbg.append(pc_min) ubg.append(pc_max) # Get an expression for the state at the end of the finite element xf_k = 0 for j in range(deg+1): xf_k += D[j]*XD[k][i][j] # Add continuity equation to NLP if i==nicp-1: # print "a ", k, i g += [XD[k+1][0][0] - xf_k] else: # print "b ", k, i g += [XD[k][i+1][0] - xf_k] lbg.append(np.zeros(ndiff)) ubg.append(np.zeros(ndiff)) # Periodicity constraints # none # Final constraints (Const, dConst, ConstQ) fck = fcfcn(0., XD[k][i][j], XA[k][i][j-1], U[k], P) g += [fck] lbg.append(fc_min) ubg.append(fc_max) # Objective function of the NLP #Implement Mayer term Obj = 0 obj = MayerTerm(0., XD[k][i][j], XA[k][i][j-1], U[k], P) Obj += obj # Implement Lagrange term lDotAtTauRoot = C.T lAtOne = D ldInv = np.linalg.inv(lDotAtTauRoot[1:,1:]) ld0 = lDotAtTauRoot[1:,0] lagrangeTerm = 0 for k in range(nk): for i in range(nicp): dQs = h*veccat(*[LagrangeTerm(0., XD[k][i][j], XA[k][i][j-1], U[k], P) \ for j in range(1,deg+1)]) Qs = mtimes( ldInv, dQs) m = mtimes( Qs.T, lAtOne[1:]) lagrangeTerm += m Obj += lagrangeTerm # NLP nlp = {'x':V, 'f':Obj, 'g':vertcat(*g)} ## ---- ## SOLVE THE NLP ## ---- # NLP solver options opts = {} opts["expand"] = True opts["ipopt.max_iter"] = 1000 opts["ipopt.tol"] = 1e-4 opts["ipopt.linear_solver"] = 'ma27' # Allocate an NLP solver solver = nlpsol("solver", "ipopt", nlp, opts) arg = {} # Initial condition arg["x0"] = vars_init # Bounds on x arg["lbx"] = vars_lb arg["ubx"] = vars_ub # Bounds on g arg["lbg"] = np.concatenate(lbg) arg["ubg"] = np.concatenate(ubg) # Solve the problem res = solver(**arg) # Print the optimal cost print("optimal cost: ", float(res["f"])) # Retrieve the solution v_opt = np.array(res["x"]) ## ---- ## RETRIEVE THE SOLUTION ## ---- xD_opt = np.resize(np.array([],dtype=MX),(ndiff,(deg+1)*nicp*(nk)+1)) xA_opt = np.resize(np.array([],dtype=MX),(nalg,(deg)*nicp*(nk))) u_opt = np.resize(np.array([],dtype=MX),(nu,(deg+1)*nicp*(nk)+1)) offset = 0 offset2 = 0 offset3 = 0 offset4 = 0 for k in range(nk): for i in range(nicp): for j in range(deg+1): xD_opt[:,offset2] = v_opt[offset:offset+ndiff][:,0] offset2 += 1 offset += ndiff if j!=0: xA_opt[:,offset4] = v_opt[offset:offset+nalg][:,0] offset4 += 1 offset += nalg utemp = v_opt[offset:offset+nu][:,0] for i in range(nicp): for j in range(deg+1): u_opt[:,offset3] = utemp offset3 += 1 # u_opt += v_opt[offset:offset+nu] offset += nu xD_opt[:,-1] = v_opt[offset:offset+ndiff][:,0] # The algebraic states are not defined at the first collocation point of the finite elements: # with the polynomials we compute them at that point Da = np.zeros(deg) for j in range(1,deg+1): # Lagrange polynomials for the algebraic states: exclude the first point La = 1 for j2 in range(1,deg+1): if j2 != j: La *= (tau-tau_root[j2])/(tau_root[j]-tau_root[j2]) lafcn = Function('lafcn', [tau], [La]) Da[j-1] = lafcn(tau_root[0]) xA_plt = np.resize(np.array([],dtype=MX),(nalg,(deg+1)*nicp*(nk)+1)) offset4=0 offset5=0 for k in range(nk): for i in range(nicp): for j in range(deg+1): if j!=0: xA_plt[:,offset5] = xA_opt[:,offset4] offset4 += 1 offset5 += 1 else: xa0 = 0 for j in range(deg): xa0 += Da[j]*xA_opt[:,offset4+j] xA_plt[:,offset5] = xa0 #xA_plt[:,offset5] = xA_opt[:,offset4] offset5 += 1 xA_plt[:,-1] = xA_plt[:,-2] tg = np.array(tau_root)*h for k in range(nk*nicp): if k == 0: tgrid = tg else: tgrid = np.append(tgrid,tgrid[-1]+tg) tgrid = np.append(tgrid,tgrid[-1]) # Plot the results plt.figure(1) plt.clf() plt.subplot(2,2,1) plt.plot(tgrid,xD_opt[0,:],'--') plt.title("x") plt.grid plt.subplot(2,2,2) plt.plot(tgrid,xD_opt[1,:],'-') plt.title("y") plt.grid plt.subplot(2,2,3) plt.plot(tgrid,xD_opt[2,:],'-.') plt.title("w") plt.grid plt.figure(2) plt.clf() plt.plot(tgrid,u_opt[0,:],'-.') plt.title("Crane, inputs") plt.xlabel('time') plt.figure(3) plt.clf() plt.plot(tgrid,xA_plt[0,:],'-.') plt.title("Crane, lambda") plt.xlabel('time') plt.grid() plt.show()
lgpl-3.0
jeremiedecock/snippets
python/scikit_learn/datasets.py
1
2684
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # See: http://scikit-learn.org/stable/tutorial/basic/tutorial.html#loading-an-example-dataset # http://scikit-learn.org/stable/datasets/index.html#datasets from __future__ import print_function from sklearn import datasets import matplotlib.pyplot as plt def main(): # http://scikit-learn.org/stable/tutorial/basic/tutorial.html#loading-an-example-dataset # "A dataset is a dictionary-like object that holds all the data and some # metadata about the data. This data is stored in the .data member, which # is a n_samples, n_features array. In the case of supervised problem, one # or more response variables are stored in the .target member." # Toy datasets iris = datasets.load_iris() # The iris dataset (classification) digits = datasets.load_digits() # The digits dataset (classification) #boston = datasets.load_boston() # The boston house-prices dataset (regression) #diabetes = datasets.load_diabetes() # The diabetes dataset (regression) #linnerud = datasets.load_linnerud() # The linnerud dataset (multivariate regression) print(iris.feature_names) print(iris.data) print(iris.target_names) print(iris.target) print(digits.images[0]) print(digits.target_names) print(digits.target) plt.imshow(digits.images[0], cmap='gray', interpolation='nearest') plt.show() # Others datasets # See: http://scikit-learn.org/stable/datasets/index.html#datasets if __name__ == '__main__': main()
mit
dsm054/pandas
asv_bench/benchmarks/io/hdf.py
4
5067
import warnings import numpy as np from pandas import DataFrame, Panel, date_range, HDFStore, read_hdf import pandas.util.testing as tm from ..pandas_vb_common import BaseIO class HDFStoreDataFrame(BaseIO): def setup(self): N = 25000 index = tm.makeStringIndex(N) self.df = DataFrame({'float1': np.random.randn(N), 'float2': np.random.randn(N)}, index=index) self.df_mixed = DataFrame({'float1': np.random.randn(N), 'float2': np.random.randn(N), 'string1': ['foo'] * N, 'bool1': [True] * N, 'int1': np.random.randint(0, N, size=N)}, index=index) self.df_wide = DataFrame(np.random.randn(N, 100)) self.start_wide = self.df_wide.index[10000] self.stop_wide = self.df_wide.index[15000] self.df2 = DataFrame({'float1': np.random.randn(N), 'float2': np.random.randn(N)}, index=date_range('1/1/2000', periods=N)) self.start = self.df2.index[10000] self.stop = self.df2.index[15000] self.df_wide2 = DataFrame(np.random.randn(N, 100), index=date_range('1/1/2000', periods=N)) self.df_dc = DataFrame(np.random.randn(N, 10), columns=['C%03d' % i for i in range(10)]) self.fname = '__test__.h5' self.store = HDFStore(self.fname) self.store.put('fixed', self.df) self.store.put('fixed_mixed', self.df_mixed) self.store.append('table', self.df2) self.store.append('table_mixed', self.df_mixed) self.store.append('table_wide', self.df_wide) self.store.append('table_wide2', self.df_wide2) def teardown(self): self.store.close() self.remove(self.fname) def time_read_store(self): self.store.get('fixed') def time_read_store_mixed(self): self.store.get('fixed_mixed') def time_write_store(self): self.store.put('fixed_write', self.df) def time_write_store_mixed(self): self.store.put('fixed_mixed_write', self.df_mixed) def time_read_store_table_mixed(self): self.store.select('table_mixed') def time_write_store_table_mixed(self): self.store.append('table_mixed_write', self.df_mixed) def time_read_store_table(self): self.store.select('table') def time_write_store_table(self): self.store.append('table_write', self.df) def time_read_store_table_wide(self): self.store.select('table_wide') def time_write_store_table_wide(self): self.store.append('table_wide_write', self.df_wide) def time_write_store_table_dc(self): self.store.append('table_dc_write', self.df_dc, data_columns=True) def time_query_store_table_wide(self): self.store.select('table_wide', where="index > self.start_wide and " "index < self.stop_wide") def time_query_store_table(self): self.store.select('table', where="index > self.start and " "index < self.stop") def time_store_repr(self): repr(self.store) def time_store_str(self): str(self.store) def time_store_info(self): self.store.info() class HDFStorePanel(BaseIO): def setup(self): self.fname = '__test__.h5' with warnings.catch_warnings(record=True): self.p = Panel(np.random.randn(20, 1000, 25), items=['Item%03d' % i for i in range(20)], major_axis=date_range('1/1/2000', periods=1000), minor_axis=['E%03d' % i for i in range(25)]) self.store = HDFStore(self.fname) self.store.append('p1', self.p) def teardown(self): self.store.close() self.remove(self.fname) def time_read_store_table_panel(self): with warnings.catch_warnings(record=True): self.store.select('p1') def time_write_store_table_panel(self): with warnings.catch_warnings(record=True): self.store.append('p2', self.p) class HDF(BaseIO): params = ['table', 'fixed'] param_names = ['format'] def setup(self, format): self.fname = '__test__.h5' N = 100000 C = 5 self.df = DataFrame(np.random.randn(N, C), columns=['float{}'.format(i) for i in range(C)], index=date_range('20000101', periods=N, freq='H')) self.df['object'] = tm.makeStringIndex(N) self.df.to_hdf(self.fname, 'df', format=format) def time_read_hdf(self, format): read_hdf(self.fname, 'df') def time_write_hdf(self, format): self.df.to_hdf(self.fname, 'df', format=format) from ..pandas_vb_common import setup # noqa: F401
bsd-3-clause
kevin-intel/scikit-learn
examples/neighbors/plot_nca_dim_reduction.py
24
3839
""" ============================================================== Dimensionality Reduction with Neighborhood Components Analysis ============================================================== Sample usage of Neighborhood Components Analysis for dimensionality reduction. This example compares different (linear) dimensionality reduction methods applied on the Digits data set. The data set contains images of digits from 0 to 9 with approximately 180 samples of each class. Each image is of dimension 8x8 = 64, and is reduced to a two-dimensional data point. Principal Component Analysis (PCA) applied to this data identifies the combination of attributes (principal components, or directions in the feature space) that account for the most variance in the data. Here we plot the different samples on the 2 first principal components. Linear Discriminant Analysis (LDA) tries to identify attributes that account for the most variance *between classes*. In particular, LDA, in contrast to PCA, is a supervised method, using known class labels. Neighborhood Components Analysis (NCA) tries to find a feature space such that a stochastic nearest neighbor algorithm will give the best accuracy. Like LDA, it is a supervised method. One can see that NCA enforces a clustering of the data that is visually meaningful despite the large reduction in dimension. """ # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.neighbors import (KNeighborsClassifier, NeighborhoodComponentsAnalysis) from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler print(__doc__) n_neighbors = 3 random_state = 0 # Load Digits dataset X, y = datasets.load_digits(return_X_y=True) # Split into train/test X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.5, stratify=y, random_state=random_state) dim = len(X[0]) n_classes = len(np.unique(y)) # Reduce dimension to 2 with PCA pca = make_pipeline(StandardScaler(), PCA(n_components=2, random_state=random_state)) # Reduce dimension to 2 with LinearDiscriminantAnalysis lda = make_pipeline(StandardScaler(), LinearDiscriminantAnalysis(n_components=2)) # Reduce dimension to 2 with NeighborhoodComponentAnalysis nca = make_pipeline(StandardScaler(), NeighborhoodComponentsAnalysis(n_components=2, random_state=random_state)) # Use a nearest neighbor classifier to evaluate the methods knn = KNeighborsClassifier(n_neighbors=n_neighbors) # Make a list of the methods to be compared dim_reduction_methods = [('PCA', pca), ('LDA', lda), ('NCA', nca)] # plt.figure() for i, (name, model) in enumerate(dim_reduction_methods): plt.figure() # plt.subplot(1, 3, i + 1, aspect=1) # Fit the method's model model.fit(X_train, y_train) # Fit a nearest neighbor classifier on the embedded training set knn.fit(model.transform(X_train), y_train) # Compute the nearest neighbor accuracy on the embedded test set acc_knn = knn.score(model.transform(X_test), y_test) # Embed the data set in 2 dimensions using the fitted model X_embedded = model.transform(X) # Plot the projected points and show the evaluation score plt.scatter(X_embedded[:, 0], X_embedded[:, 1], c=y, s=30, cmap='Set1') plt.title("{}, KNN (k={})\nTest accuracy = {:.2f}".format(name, n_neighbors, acc_knn)) plt.show()
bsd-3-clause
bkahlert/seqan-research
raw/workshop13/workshop2013-data-20130926/trunk/extras/apps/ngs_roi/tool_shed/roi_details.py
18
3825
#!/usr/bin/env python """Generation of detailed ROI reports with larger plots. This report generation works for hundred of ROIs. """ try: import argparse except ImportError: import argparse26 as argparse import math import os.path import sys import Cheetah.Template import matplotlib.pyplot as plt import ngs_roi.app import ngs_roi.argparse import ngs_roi.io PAGE_TPL = """ <html> <head> <title>ROI Table</title> <style type="text/css"> div.plot { float: left; padding: 4px; margin: 2px; width: 420px; } .plot h2 { margin-top: 3px; margin-bottom: 3px; text-align: center; } .plot img { display: block; margin: 0 auto; } </style> </head> <body> <h1>Detailed ROI Report</h1> #for i, roi in enumerate($records) <div class="plot"> <h2>${roi.ref}:${roi.start_pos + 1}-${roi.end_pos+1}</h2> <a href="${href($roi)}" target="dead"><img src="plot_${i}.png" /></a> <p> <b>chr:start-end</b> <a href="${href($roi)}" target="dead">${roi.ref}:${roi.start_pos}-${roi.end_pos} ${roi.strand}</a>; <b>region name</b> ${roi.region_name}; <b>region length</b> ${roi.region_length}; </p> #if $roi.data <p>#for j, key in enumerate($data_keys)#<b>$key:</b> ${roi.data[$j]}; #end for#</p> #end if </div> #end for <iframe name="dead" height="0" width="0"></iframe> <div><code>$args</code></div> </body> </html> """ class DetailedRoiGenerator(ngs_roi.app.App): """Generate detailed ROI report. :ivar args:Arguments from the comment line. """ def __init__(self, args): self.args = args def run(self): """Run report generation, return status code. :return: integer with the result. """ print >>sys.stderr, 'Loading ROI' records = ngs_roi.io.load(self.args.in_file, self.args.max_rois) keys = records[0].data_keys self.writeHtml(keys, records) self.writePlots(records) return 0 def writePlots(self, records): COLOR = 'blue' LINE_WIDTH = .5 LINE_STYLE = '-' TICK_FONT_SIZE = 8 LABEL_FONT_SIZE = 10 for i, roi in enumerate(records): file_name = 'plot_%d.png' % i file_name = os.path.join(self.args.out_dir, file_name) print >>sys.stderr, 'Writing plot %s' % file_name plt.figure(figsize=(4, 2.5)) plt.gcf().subplots_adjust(bottom=0.16, left=0.15) plt.plot(roi.points, color=COLOR, linewidth=LINE_WIDTH, linestyle=LINE_STYLE) plt.ylim(ymin=0) if self.args.max_value: plt.ylim(ymax=self.args.max_value) plt.tick_params(labelsize=TICK_FONT_SIZE) plt.ylabel('coverage', fontsize=LABEL_FONT_SIZE, weight='semibold') plt.xlabel('ROI beginPos', fontsize=LABEL_FONT_SIZE, weight='semibold') plt.savefig(file_name) def writeHtml(self, keys, records): file_name = self.args.out_file print >>sys.stderr, 'Writing HTML file %s' % file_name vals = {'args': self.args, 'records': records, 'data_keys': keys, 'href': lambda x: self.buildHref(x.ref, x.start_pos, x.end_pos)} t = Cheetah.Template.Template(PAGE_TPL, searchList=vals) with open(file_name, 'wb') as f: f.write(str(t)) def main(): parser = argparse.ArgumentParser(description='Plot ROI file.') ngs_roi.argparse.addFileArguments(parser) ngs_roi.argparse.addPlotGridArguments(parser) ngs_roi.argparse.addLinkArguments(parser) args = parser.parse_args() ngs_roi.argparse.applyFileDefaults(args) app = DetailedRoiGenerator(args) return app.run() if __name__ == '__main__': sys.exit(main())
mit
sirikata/sirikata
tools/cdn/meshtool_progressive_analyze.py
1
13953
import list import pprint import sys import os import os.path import urllib2 import shutil from meshtool.filters import factory from meshtool.filters.print_filters.print_render_info import getRenderInfo import collada import unicodedata import math import traceback import itertools from multiprocessing import Process, Pool from multiprocessing import current_process from Queue import Queue from threading import Thread, Lock import gzip import matplotlib.pyplot as plt from matplotlib import rc, rcParams from matplotlib.lines import Line2D from matplotlib.font_manager import FontProperties import json import base64 import numpy rc('text', usetex=True) rc('font', family='serif') SERVER = 'http://open3dhub.com' DOWNLOAD = SERVER + '/download' DNS = SERVER + '/dns' #DATA_OUT = """71076005 805416474.359 11.3317634321 8.19903 27.240254 1.018211 #68951003 674983010.068 9.78931387072 6.577926 24.032948 0.841197 #68889178 602343056.445 8.74365283391 5.031103 23.3255493 0.695605 #68849516 553289057.267 8.03620837751 4.1197845 22.475401 0.615508 #68827972 527585146.555 7.66527229009 3.575544 21.6788579 0.567449 #68812736 515550764.675 7.49208351017 3.3456605 21.284081 0.491539 #68799250 513001945.94 7.45650491743 3.313815 21.284081 0.481598 #68782764 510430178.859 7.420902406 3.2873305 21.2206367 0.475875 #68764632 508582444.54 7.39598874811 3.269563 21.0836329 0.472489 #68735994 506220674.383 7.36471017474 3.2495345 21.058182 0.468956 #68696465 500867618.747 7.29102463638 3.201587 20.8095526 0.459344""" DATA_OUT = """78467628 898050454.086 11.4448528263 6.4171475 29.961459 0.0 76386666 704819299.397 9.22699387609 4.4762075 25.274798 0.0 76336783 596506038.71 7.81413645254 3.218848 22.7660624 0.0 76298845 520640735.77 6.82370402554 2.369781 20.417026 0.0 76278624 477993045.209 6.2664088593 1.974794 18.943688 0.0 76264341 457567769.496 5.99976035322 1.810844 18.221164 0.0 76251447 451546784.839 5.92181266853 1.810844 17.96473 0.0 76235306 447831899.655 5.87433727432 1.810844 17.7626415 0.0 76217359 445059006.946 5.839339132 1.810844 17.606025 0.0 76188961 442180199.453 5.80373053589 1.810844 17.471591 0.0 76149991 434765830.794 5.70933528795 1.797515 17.134251 0.0""" #DATA_OUT = """70284092 689604708.536 9.81167557142 5.213484 26.077159 0.630733 #68144821 562464543.412 8.25395877717 3.719422 22.770836 0.487914 #68072036 500691444.857 7.35531760586 2.838925 21.171333 0.400694 #68032818 463120050.852 6.80730365825 2.301201 20.064436 0.312665 #68009114 443307531.219 6.51835474903 2.0310935 19.541012 0.27483 #67991523 436375269.535 6.41808346513 1.92669 19.4096412 0.27483 #67986204 433214083.378 6.37208812803 1.9088815 19.224709 0.274139 #67973623 429874390.479 6.32413532643 1.900266 19.067663 0.272124 #67945586 426371368.669 6.27518862916 1.888988 18.825753 0.272124 #67909171 423025343.437 6.22928151246 1.877646 18.591086 0.272124 #67855016 414884585.299 6.11428026631 1.84367 18.07165 0.272124""" def get_gzip_size(base_dir, hash): file_path = os.path.join(base_dir, hash) if not os.path.isfile(file_path): f_data = urllib2.urlopen(DOWNLOAD + '/' + hash).read() f = gzip.open(file_path, 'wb') f.write(f_data) f.close() return os.path.getsize(file_path) def main(): if len(sys.argv) != 2 or not os.path.isdir(sys.argv[1]): print 'usage: python meshtool_regression.py directory' sys.exit(1) base_dir = sys.argv[1] diffs = [] cdn_list = list.grab_list(SERVER, 2000, '', '', 'dump') size_pairs = [] draw_calls_original = [] num_triangles = [] num_images = [] ram_usage = [] num_to_check = len([f for f in cdn_list if 'original' in f['metadata']['types'] and 'progressive' in f['metadata']['types']]) size_table = numpy.zeros((num_to_check, 5, 5), dtype=numpy.float32) table_index = 0 for f in cdn_list: types = f['metadata']['types'] if 'original' not in types or 'progressive' not in types: continue gzip_orig_size = get_gzip_size(base_dir, types['original']['hash']) gzip_progressive_size = get_gzip_size(base_dir, types['progressive']['hash']) for subfile in types['original']['subfiles']: mesh_path = f['base_path'] subfile_split = subfile.split('/') subfile_name = subfile_split[-2] version_num = f['version_num'] subfile_url = '%s%s/%s/%s/%s' % (DNS, mesh_path, 'original', version_num, subfile_name) hash_cache_name = base64.urlsafe_b64encode(subfile_url) hash_cache_file = os.path.join(base_dir, hash_cache_name) if not os.path.isfile(hash_cache_file): try: subfile_data = urllib2.urlopen(subfile_url).read() except urllib2.HTTPError: continue sf = open(hash_cache_file, 'w') sf.write(subfile_data) else: sf = open(hash_cache_file, 'r') subfile_data = sf.read() sf.close() subfile_info = json.loads(subfile_data) subfile_hash = subfile_info['Hash'] subfile_size = get_gzip_size(base_dir, subfile_hash) gzip_orig_size += subfile_size gzip_progressive_stream_size = get_gzip_size(base_dir, types['progressive']['progressive_stream']) if types['progressive']['progressive_stream'] else 0 mipmap_levels = next(types['progressive']['mipmaps'].itervalues())['byte_ranges'] for stream_percentage in range(5): for mipmap_level in range(5): current_stream_size = gzip_progressive_stream_size * (stream_percentage / 4.0) current_mipmap_size = [128,256,512,1024,2048][mipmap_level] all_mipmaps_size = 0 for mipmap in mipmap_levels: all_mipmaps_size += mipmap['length'] if mipmap['width'] >= current_mipmap_size or mipmap['height'] >= current_mipmap_size: break entrysize = gzip_progressive_size + current_stream_size + all_mipmaps_size size_table[table_index, stream_percentage, mipmap_level] = entrysize / gzip_orig_size progressive_mipmap_size = 0 for mipmap in mipmap_levels: progressive_mipmap_size = mipmap['length'] if mipmap['width'] >= 128 or mipmap['height'] >= 128: break gzip_progressive_size += progressive_mipmap_size size_pairs.append((gzip_orig_size, gzip_progressive_size)) draw_calls_original.append(types['original']['metadata']['num_draw_calls']) num_triangles.append(types['original']['metadata']['num_triangles']) num_images.append(types['original']['metadata']['num_images']) ram_usage.append(types['original']['metadata']['texture_ram_usage']) table_index += 1 #print numpy.mean(size_table, axis=0) #print numpy.min(size_table, axis=0) #print numpy.max(size_table, axis=0) size_table = numpy.median(size_table, axis=0) print 'Relative Median Size (rows=0,25,50,75,100, cols=128,256,512,1024,2048)' print size_table reductions = [(p[1] - p[0]) / 1024.0 for p in size_pairs] reductions = sorted(reductions) x_vals = numpy.arange(0, 1, 1.0 / len(reductions)) fig = plt.figure(figsize=(4,1.5)) ax = fig.add_subplot(1,1,1) ax.set_yscale('symlog') ax.scatter(x_vals,reductions,color='b', marker='+', s=1) plt.ylim(min(reductions),max(reductions)) plt.xlim(0, 1) #ax.set_title('Change in Download Size for First Display') ax.set_xlabel('Mesh') ax.set_ylabel('Change in KB') plt.gcf().subplots_adjust(bottom=0.26, left=0.18, right=0.95, top=0.98) plt.savefig('mesh_size_change.pdf', format='pdf', dpi=150) hist, bins = numpy.histogram(draw_calls_original, bins=[1,2,3,4,5,6,7,8,9,10,15,20,25,100,max(draw_calls_original)]) bin_labels = [1,2,3,4,5,6,7,8,9,10,'11-15','16-20','21-25','26+'] fig = plt.figure(figsize=(4,2)) ax = fig.add_subplot(1,1,1) #ax.set_xscale('symlog') #ax.hist(draw_calls_original, bins=[0,1,2,3,4,5,10,15,20,25,100,1500]) hist = hist / float(numpy.sum(hist)) ax.bar(range(1,len(hist)+1), hist, align='center') #plt.ylim(0,max(draw_calls_original)) plt.xlim(0,len(hist)+1) plt.xticks(range(1,len(hist)+1), bin_labels, rotation='vertical') plt.yticks([0,0.05,0.10,0.15,0.20], ['0','.05','.10','.15','.20']) #ax.set_title('Original Number of Draw Calls to Display Mesh') ax.set_xlabel('Number of Draw Calls') ax.set_ylabel('Frequency') plt.gcf().subplots_adjust(bottom=0.35, left=0.15, right=0.95, top=0.96) plt.savefig('num_draw_calls_hist.pdf', format='pdf', dpi=150) hist, bins = numpy.histogram(num_triangles, bins=[0,1000,10000,100000,max(num_triangles)]) bin_labels = ['\\textless1K','\\textless10K','\\textless100K','100K+'] fig = plt.figure(figsize=(4,2)) ax = fig.add_subplot(1,1,1) #ax.set_xscale('symlog') #ax.hist(draw_calls_original, bins=[0,1,2,3,4,5,10,15,20,25,100,1500]) hist = hist / float(numpy.sum(hist)) ax.bar(range(1,len(hist)+1), hist, align='center') #plt.ylim(0,max(draw_calls_original)) plt.xlim(0.4,len(hist)+0.6) plt.xticks(range(1,len(hist)+1), bin_labels) #, rotation=17) plt.yticks([0,0.05,0.10,0.15,0.20,0.25,0.3,0.35,0.4], ['0','.05','.10','.15','.20','.25','.30','.35','.40']) #ax.set_title('Original Number of Draw Calls to Display Mesh') ax.set_xlabel('Number of Triangles') ax.set_ylabel('Frequency') plt.gcf().subplots_adjust(bottom=0.21, left=0.15, right=0.95, top=0.96) plt.savefig('num_triangles_hist.pdf', format='pdf', dpi=150) hist, bins = numpy.histogram(ram_usage, bins=[0,1,100*1024,1024*1024,10*1024*1024,max(ram_usage)]) bin_labels = ['0','\\textless100KB','\\textless1MB','\\textless10MB','10MB+'] fig = plt.figure(figsize=(4,2)) ax = fig.add_subplot(1,1,1) #ax.set_xscale('symlog') #ax.hist(draw_calls_original, bins=[0,1,2,3,4,5,10,15,20,25,100,1500]) hist = hist / float(numpy.sum(hist)) ax.bar(range(1,len(hist)+1), hist, align='center') #plt.ylim(0,max(draw_calls_original)) plt.xlim(0.4,len(hist)+0.6) plt.xticks(range(1,len(hist)+1), bin_labels, rotation=17) plt.yticks([0,0.05,0.10,0.15,0.20,0.25,0.3,0.35], ['0','.05','.10','.15','.20','.25','.30','.35']) #ax.set_title('Original Number of Draw Calls to Display Mesh') ax.set_xlabel('Texture RAM Usage') ax.set_ylabel('Frequency') plt.gcf().subplots_adjust(bottom=0.3, left=0.15, right=0.95, top=0.96) plt.savefig('texture_ram_hist.pdf', format='pdf', dpi=150) chart_error_dir = os.path.join(os.path.dirname(__file__), 'chart_errors') for errdir in os.listdir(chart_error_dir): if errdir != 'duck': continue errfile = os.path.join(chart_error_dir, errdir, 'err.txt') maxerrfile = os.path.join(chart_error_dir, errdir, 'maxerr.txt') chart_errors = numpy.fromfile(errfile, sep='\n') chart_errors = numpy.sort(chart_errors) max_errors = numpy.fromfile(maxerrfile, sep='\n') max_errors = numpy.sort(max_errors) heuristic = numpy.log(chart_errors+1) / numpy.log(max_errors+1) stop_point = numpy.where(heuristic >= 0.90)[0][0] x_vals = numpy.arange(0, len(chart_errors)) fig = plt.figure(figsize=(4,3)) ax = fig.add_subplot(1,1,1) ax.set_yscale('symlog') ax.scatter(x_vals, chart_errors, color='b', marker='+', s=1) ax.scatter(x_vals, max_errors, color='r', marker='x', s=1) #ax.set_title('Change in Download Size for First Display') ax.set_xlabel('Merge Step') ax.set_ylabel('Error Value') plt.ylim(min(chart_errors),max(chart_errors)) axR = fig.add_subplot(1,1,1, sharex=ax, frameon=False) axR.yaxis.tick_right() axR.yaxis.set_label_position("right") axR.scatter(x_vals, heuristic, color='g', marker='s', s=1) axR.set_ylabel("Heuristic Value") plt.axvline(stop_point, linestyle='-', color='#333333') plt.xticks([0,1000,2000,3000,4000]) plt.xlim(0, len(chart_errors)) p1 = Line2D([0],[1], color="g", linewidth=2) p2 = Line2D([0],[1], color="r", linewidth=2) p3 = Line2D([0],[1], color="b", linewidth=2) prop = FontProperties(size=11) plt.legend((p1, p2, p3), ['Heuristic', 'Maximum', 'Current'], loc=0, prop=prop) plt.gcf().subplots_adjust(bottom=0.14, left=0.13, right=0.87, top=0.98) plt.savefig('chart_merge_error_%s.pdf' % errdir, format='pdf', dpi=150) percep_lines = DATA_OUT.split("\n") y_vals = [] y_vals2 = [] perc90_vals = [] perc10_vals = [] for line in percep_lines: ct, tot, avg, median, perc90, perc10 = map(float, line.split(" ")) y_vals.append(avg) y_vals2.append(median) perc10_vals.append(perc10) perc90_vals.append(perc90) x_vals = range(0,101,10) fig = plt.figure(figsize=(4,2)) ax = fig.add_subplot(1,1,1) #ax.set_yscale('symlog') ax.plot(x_vals, y_vals, color='b', marker='s', label='Mean') ax.plot(x_vals, y_vals2, color='r', marker='o', label='Median') plt.ylim(0, max(y_vals) * 1.05) plt.xlim(0, 100) plt.xticks(range(0, 101, 10)) #ax.set_title('Perceptual Difference from Original Mesh') ax.set_xlabel('Progressive Stream %') ax.set_ylabel('Delta E (CIE2000)') ax.legend() plt.gcf().subplots_adjust(bottom=0.2, left=0.13, right=0.95, top=0.96) plt.savefig('progressive_perceptual_difference.pdf', format='pdf', dpi=150) if __name__ == "__main__": main()
bsd-3-clause
ysekky/GPy
GPy/core/parameterization/variational.py
6
10216
''' Created on 6 Nov 2013 @author: maxz ''' import numpy as np from .parameterized import Parameterized from .param import Param from paramz.transformations import Logexp, Logistic,__fixed__ class VariationalPrior(Parameterized): def __init__(self, name='latent prior', **kw): super(VariationalPrior, self).__init__(name=name, **kw) def KL_divergence(self, variational_posterior): raise NotImplementedError("override this for variational inference of latent space") def update_gradients_KL(self, variational_posterior): """ updates the gradients for mean and variance **in place** """ raise NotImplementedError("override this for variational inference of latent space") class NormalPrior(VariationalPrior): def __init__(self, name='normal_prior', **kw): super(VariationalPrior, self).__init__(name=name, **kw) def KL_divergence(self, variational_posterior): var_mean = np.square(variational_posterior.mean).sum() var_S = (variational_posterior.variance - np.log(variational_posterior.variance)).sum() return 0.5 * (var_mean + var_S) - 0.5 * variational_posterior.input_dim * variational_posterior.num_data def update_gradients_KL(self, variational_posterior): # dL: variational_posterior.mean.gradient -= variational_posterior.mean variational_posterior.variance.gradient -= (1. - (1. / (variational_posterior.variance))) * 0.5 class SpikeAndSlabPrior(VariationalPrior): def __init__(self, pi=None, learnPi=False, variance = 1.0, group_spike=False, name='SpikeAndSlabPrior', **kw): super(SpikeAndSlabPrior, self).__init__(name=name, **kw) self.group_spike = group_spike self.variance = Param('variance',variance) self.learnPi = learnPi if learnPi: self.pi = Param('Pi', pi, Logistic(1e-10,1.-1e-10)) else: self.pi = Param('Pi', pi, __fixed__) self.link_parameter(self.pi) def KL_divergence(self, variational_posterior): mu = variational_posterior.mean S = variational_posterior.variance if self.group_spike: gamma = variational_posterior.gamma.values[0] else: gamma = variational_posterior.gamma.values if len(self.pi.shape)==2: idx = np.unique(variational_posterior.gamma._raveled_index()/gamma.shape[-1]) pi = self.pi[idx] else: pi = self.pi var_mean = np.square(mu)/self.variance var_S = (S/self.variance - np.log(S)) var_gamma = (gamma*np.log(gamma/pi)).sum()+((1-gamma)*np.log((1-gamma)/(1-pi))).sum() return var_gamma+ (gamma* (np.log(self.variance)-1. +var_mean + var_S)).sum()/2. def update_gradients_KL(self, variational_posterior): mu = variational_posterior.mean S = variational_posterior.variance if self.group_spike: gamma = variational_posterior.gamma.values[0] else: gamma = variational_posterior.gamma.values if len(self.pi.shape)==2: idx = np.unique(variational_posterior.gamma._raveled_index()/gamma.shape[-1]) pi = self.pi[idx] else: pi = self.pi if self.group_spike: dgamma = np.log((1-pi)/pi*gamma/(1.-gamma))/variational_posterior.num_data else: dgamma = np.log((1-pi)/pi*gamma/(1.-gamma)) variational_posterior.binary_prob.gradient -= dgamma+((np.square(mu)+S)/self.variance-np.log(S)+np.log(self.variance)-1.)/2. mu.gradient -= gamma*mu/self.variance S.gradient -= (1./self.variance - 1./S) * gamma /2. if self.learnPi: if len(self.pi)==1: self.pi.gradient = (gamma/self.pi - (1.-gamma)/(1.-self.pi)).sum() elif len(self.pi.shape)==1: self.pi.gradient = (gamma/self.pi - (1.-gamma)/(1.-self.pi)).sum(axis=0) else: self.pi[idx].gradient = (gamma/self.pi[idx] - (1.-gamma)/(1.-self.pi[idx])) class VariationalPosterior(Parameterized): def __init__(self, means=None, variances=None, name='latent space', *a, **kw): super(VariationalPosterior, self).__init__(name=name, *a, **kw) self.mean = Param("mean", means) self.variance = Param("variance", variances, Logexp()) self.ndim = self.mean.ndim self.shape = self.mean.shape self.num_data, self.input_dim = self.mean.shape self.link_parameters(self.mean, self.variance) self.num_data, self.input_dim = self.mean.shape if self.has_uncertain_inputs(): assert self.variance.shape == self.mean.shape, "need one variance per sample and dimenion" def set_gradients(self, grad): self.mean.gradient, self.variance.gradient = grad def _raveled_index(self): index = np.empty(dtype=int, shape=0) size = 0 for p in self.parameters: index = np.hstack((index, p._raveled_index()+size)) size += p._realsize_ if hasattr(p, '_realsize_') else p.size return index def has_uncertain_inputs(self): return not self.variance is None def __getitem__(self, s): if isinstance(s, (int, slice, tuple, list, np.ndarray)): import copy n = self.__new__(self.__class__, self.name) dc = self.__dict__.copy() dc['mean'] = self.mean[s] dc['variance'] = self.variance[s] dc['parameters'] = copy.copy(self.parameters) n.__dict__.update(dc) n.parameters[dc['mean']._parent_index_] = dc['mean'] n.parameters[dc['variance']._parent_index_] = dc['variance'] n._gradient_array_ = None oversize = self.size - self.mean.size - self.variance.size n.size = n.mean.size + n.variance.size + oversize n.ndim = n.mean.ndim n.shape = n.mean.shape n.num_data = n.mean.shape[0] n.input_dim = n.mean.shape[1] if n.ndim != 1 else 1 return n else: return super(VariationalPosterior, self).__getitem__(s) class NormalPosterior(VariationalPosterior): ''' NormalPosterior distribution for variational approximations. holds the means and variances for a factorizing multivariate normal distribution ''' def plot(self, *args, **kwargs): """ Plot latent space X in 1D: See GPy.plotting.matplot_dep.variational_plots """ import sys assert "matplotlib" in sys.modules, "matplotlib package has not been imported." from ...plotting.matplot_dep import variational_plots return variational_plots.plot(self, *args, **kwargs) def KL(self, other): """Compute the KL divergence to another NormalPosterior Object. This only holds, if the two NormalPosterior objects have the same shape, as we do computational tricks for the multivariate normal KL divergence. """ return .5*( np.sum(self.variance/other.variance) + ((other.mean-self.mean)**2/other.variance).sum() - self.num_data * self.input_dim + np.sum(np.log(other.variance)) - np.sum(np.log(self.variance)) ) class SpikeAndSlabPosterior(VariationalPosterior): ''' The SpikeAndSlab distribution for variational approximations. ''' def __init__(self, means, variances, binary_prob, group_spike=False, sharedX=False, name='latent space'): """ binary_prob : the probability of the distribution on the slab part. """ super(SpikeAndSlabPosterior, self).__init__(means, variances, name) self.group_spike = group_spike self.sharedX = sharedX if sharedX: self.mean.fix(warning=False) self.variance.fix(warning=False) if group_spike: self.gamma_group = Param("binary_prob_group",binary_prob.mean(axis=0),Logistic(1e-10,1.-1e-10)) self.gamma = Param("binary_prob",binary_prob, __fixed__) self.link_parameters(self.gamma_group,self.gamma) else: self.gamma = Param("binary_prob",binary_prob,Logistic(1e-10,1.-1e-10)) self.link_parameter(self.gamma) def propogate_val(self): if self.group_spike: self.gamma.values[:] = self.gamma_group.values def collate_gradient(self): if self.group_spike: self.gamma_group.gradient = self.gamma.gradient.reshape(self.gamma.shape).sum(axis=0) def set_gradients(self, grad): self.mean.gradient, self.variance.gradient, self.gamma.gradient = grad def __getitem__(self, s): if isinstance(s, (int, slice, tuple, list, np.ndarray)): import copy n = self.__new__(self.__class__, self.name) dc = self.__dict__.copy() dc['mean'] = self.mean[s] dc['variance'] = self.variance[s] dc['binary_prob'] = self.binary_prob[s] dc['parameters'] = copy.copy(self.parameters) n.__dict__.update(dc) n.parameters[dc['mean']._parent_index_] = dc['mean'] n.parameters[dc['variance']._parent_index_] = dc['variance'] n.parameters[dc['binary_prob']._parent_index_] = dc['binary_prob'] n._gradient_array_ = None oversize = self.size - self.mean.size - self.variance.size - self.gamma.size n.size = n.mean.size + n.variance.size + n.gamma.size + oversize n.ndim = n.mean.ndim n.shape = n.mean.shape n.num_data = n.mean.shape[0] n.input_dim = n.mean.shape[1] if n.ndim != 1 else 1 return n else: return super(SpikeAndSlabPosterior, self).__getitem__(s) def plot(self, *args, **kwargs): """ Plot latent space X in 1D: See GPy.plotting.matplot_dep.variational_plots """ import sys assert "matplotlib" in sys.modules, "matplotlib package has not been imported." from ...plotting.matplot_dep import variational_plots return variational_plots.plot_SpikeSlab(self,*args, **kwargs)
bsd-3-clause
sunzhxjs/JobGIS
lib/python2.7/site-packages/pandas/tests/test_common.py
9
44081
# -*- coding: utf-8 -*- import collections from datetime import datetime import re import nose from nose.tools import assert_equal, assert_true import numpy as np import pandas as pd from pandas.tslib import iNaT, NaT from pandas import Series, DataFrame, date_range, DatetimeIndex, Timestamp, Float64Index from pandas import compat from pandas.compat import range, long, lrange, lmap, u from pandas.core.common import notnull, isnull, array_equivalent import pandas.core.common as com import pandas.core.convert as convert import pandas.core.format as fmt import pandas.util.testing as tm import pandas.core.config as cf _multiprocess_can_split_ = True def test_mut_exclusive(): msg = "mutually exclusive arguments: '[ab]' and '[ab]'" with tm.assertRaisesRegexp(TypeError, msg): com._mut_exclusive(a=1, b=2) assert com._mut_exclusive(a=1, b=None) == 1 assert com._mut_exclusive(major=None, major_axis=None) is None def test_is_sequence(): is_seq = com.is_sequence assert(is_seq((1, 2))) assert(is_seq([1, 2])) assert(not is_seq("abcd")) assert(not is_seq(u("abcd"))) assert(not is_seq(np.int64)) class A(object): def __getitem__(self): return 1 assert(not is_seq(A())) def test_get_callable_name(): from functools import partial getname = com._get_callable_name def fn(x): return x lambda_ = lambda x: x part1 = partial(fn) part2 = partial(part1) class somecall(object): def __call__(self): return x assert getname(fn) == 'fn' assert getname(lambda_) assert getname(part1) == 'fn' assert getname(part2) == 'fn' assert getname(somecall()) == 'somecall' assert getname(1) is None #Issue 10859 class TestABCClasses(tm.TestCase): tuples = [[1, 2, 2], ['red', 'blue', 'red']] multi_index = pd.MultiIndex.from_arrays(tuples, names=('number', 'color')) datetime_index = pd.to_datetime(['2000/1/1', '2010/1/1']) timedelta_index = pd.to_timedelta(np.arange(5), unit='s') period_index = pd.period_range('2000/1/1', '2010/1/1/', freq='M') categorical = pd.Categorical([1, 2, 3], categories=[2, 3, 1]) categorical_df = pd.DataFrame({"values": [1, 2, 3]}, index=categorical) df = pd.DataFrame({'names': ['a', 'b', 'c']}, index=multi_index) sparse_series = pd.Series([1, 2, 3]).to_sparse() sparse_array = pd.SparseArray(np.random.randn(10)) def test_abc_types(self): self.assertIsInstance(pd.Index(['a', 'b', 'c']), com.ABCIndex) self.assertIsInstance(pd.Int64Index([1, 2, 3]), com.ABCInt64Index) self.assertIsInstance(pd.Float64Index([1, 2, 3]), com.ABCFloat64Index) self.assertIsInstance(self.multi_index, com.ABCMultiIndex) self.assertIsInstance(self.datetime_index, com.ABCDatetimeIndex) self.assertIsInstance(self.timedelta_index, com.ABCTimedeltaIndex) self.assertIsInstance(self.period_index, com.ABCPeriodIndex) self.assertIsInstance(self.categorical_df.index, com.ABCCategoricalIndex) self.assertIsInstance(pd.Index(['a', 'b', 'c']), com.ABCIndexClass) self.assertIsInstance(pd.Int64Index([1, 2, 3]), com.ABCIndexClass) self.assertIsInstance(pd.Series([1, 2, 3]), com.ABCSeries) self.assertIsInstance(self.df, com.ABCDataFrame) self.assertIsInstance(self.df.to_panel(), com.ABCPanel) self.assertIsInstance(self.sparse_series, com.ABCSparseSeries) self.assertIsInstance(self.sparse_array, com.ABCSparseArray) self.assertIsInstance(self.categorical, com.ABCCategorical) self.assertIsInstance(pd.Period('2012', freq='A-DEC'), com.ABCPeriod) class TestInferDtype(tm.TestCase): def test_infer_dtype_from_scalar(self): # Test that _infer_dtype_from_scalar is returning correct dtype for int and float. for dtypec in [ np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64, np.int64 ]: data = dtypec(12) dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, type(data)) data = 12 dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, np.int64) for dtypec in [ np.float16, np.float32, np.float64 ]: data = dtypec(12) dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, dtypec) data = np.float(12) dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, np.float64) for data in [ True, False ]: dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, np.bool_) for data in [ np.complex64(1), np.complex128(1) ]: dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, np.complex_) import datetime for data in [ np.datetime64(1,'ns'), pd.Timestamp(1), datetime.datetime(2000,1,1,0,0) ]: dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, 'M8[ns]') for data in [ np.timedelta64(1,'ns'), pd.Timedelta(1), datetime.timedelta(1) ]: dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, 'm8[ns]') for data in [ datetime.date(2000,1,1), pd.Timestamp(1,tz='US/Eastern'), 'foo' ]: dtype, val = com._infer_dtype_from_scalar(data) self.assertEqual(dtype, np.object_) def test_notnull(): assert notnull(1.) assert not notnull(None) assert not notnull(np.NaN) with cf.option_context("mode.use_inf_as_null", False): assert notnull(np.inf) assert notnull(-np.inf) arr = np.array([1.5, np.inf, 3.5, -np.inf]) result = notnull(arr) assert result.all() with cf.option_context("mode.use_inf_as_null", True): assert not notnull(np.inf) assert not notnull(-np.inf) arr = np.array([1.5, np.inf, 3.5, -np.inf]) result = notnull(arr) assert result.sum() == 2 with cf.option_context("mode.use_inf_as_null", False): for s in [tm.makeFloatSeries(),tm.makeStringSeries(), tm.makeObjectSeries(),tm.makeTimeSeries(),tm.makePeriodSeries()]: assert(isinstance(isnull(s), Series)) def test_isnull(): assert not isnull(1.) assert isnull(None) assert isnull(np.NaN) assert not isnull(np.inf) assert not isnull(-np.inf) # series for s in [tm.makeFloatSeries(),tm.makeStringSeries(), tm.makeObjectSeries(),tm.makeTimeSeries(),tm.makePeriodSeries()]: assert(isinstance(isnull(s), Series)) # frame for df in [tm.makeTimeDataFrame(),tm.makePeriodFrame(),tm.makeMixedDataFrame()]: result = isnull(df) expected = df.apply(isnull) tm.assert_frame_equal(result, expected) # panel for p in [ tm.makePanel(), tm.makePeriodPanel(), tm.add_nans(tm.makePanel()) ]: result = isnull(p) expected = p.apply(isnull) tm.assert_panel_equal(result, expected) # panel 4d for p in [ tm.makePanel4D(), tm.add_nans_panel4d(tm.makePanel4D()) ]: result = isnull(p) expected = p.apply(isnull) tm.assert_panel4d_equal(result, expected) def test_isnull_lists(): result = isnull([[False]]) exp = np.array([[False]]) assert(np.array_equal(result, exp)) result = isnull([[1], [2]]) exp = np.array([[False], [False]]) assert(np.array_equal(result, exp)) # list of strings / unicode result = isnull(['foo', 'bar']) assert(not result.any()) result = isnull([u('foo'), u('bar')]) assert(not result.any()) def test_isnull_nat(): result = isnull([NaT]) exp = np.array([True]) assert(np.array_equal(result, exp)) result = isnull(np.array([NaT], dtype=object)) exp = np.array([True]) assert(np.array_equal(result, exp)) def test_isnull_numpy_nat(): arr = np.array([NaT, np.datetime64('NaT'), np.timedelta64('NaT'), np.datetime64('NaT', 's')]) result = isnull(arr) expected = np.array([True] * 4) tm.assert_numpy_array_equal(result, expected) def test_isnull_datetime(): assert (not isnull(datetime.now())) assert notnull(datetime.now()) idx = date_range('1/1/1990', periods=20) assert(notnull(idx).all()) idx = np.asarray(idx) idx[0] = iNaT idx = DatetimeIndex(idx) mask = isnull(idx) assert(mask[0]) assert(not mask[1:].any()) # GH 9129 pidx = idx.to_period(freq='M') mask = isnull(pidx) assert(mask[0]) assert(not mask[1:].any()) mask = isnull(pidx[1:]) assert(not mask.any()) class TestIsNull(tm.TestCase): def test_0d_array(self): self.assertTrue(isnull(np.array(np.nan))) self.assertFalse(isnull(np.array(0.0))) self.assertFalse(isnull(np.array(0))) # test object dtype self.assertTrue(isnull(np.array(np.nan, dtype=object))) self.assertFalse(isnull(np.array(0.0, dtype=object))) self.assertFalse(isnull(np.array(0, dtype=object))) def test_downcast_conv(): # test downcasting arr = np.array([8.5, 8.6, 8.7, 8.8, 8.9999999999995]) result = com._possibly_downcast_to_dtype(arr, 'infer') assert (np.array_equal(result, arr)) arr = np.array([8., 8., 8., 8., 8.9999999999995]) result = com._possibly_downcast_to_dtype(arr, 'infer') expected = np.array([8, 8, 8, 8, 9]) assert (np.array_equal(result, expected)) arr = np.array([8., 8., 8., 8., 9.0000000000005]) result = com._possibly_downcast_to_dtype(arr, 'infer') expected = np.array([8, 8, 8, 8, 9]) assert (np.array_equal(result, expected)) # conversions expected = np.array([1,2]) for dtype in [np.float64,object,np.int64]: arr = np.array([1.0,2.0],dtype=dtype) result = com._possibly_downcast_to_dtype(arr,'infer') tm.assert_almost_equal(result, expected) expected = np.array([1.0,2.0,np.nan]) for dtype in [np.float64,object]: arr = np.array([1.0,2.0,np.nan],dtype=dtype) result = com._possibly_downcast_to_dtype(arr,'infer') tm.assert_almost_equal(result, expected) # empties for dtype in [np.int32,np.float64,np.float32,np.bool_,np.int64,object]: arr = np.array([],dtype=dtype) result = com._possibly_downcast_to_dtype(arr,'int64') tm.assert_almost_equal(result, np.array([],dtype=np.int64)) assert result.dtype == np.int64 def test_array_equivalent(): assert array_equivalent(np.array([np.nan, np.nan]), np.array([np.nan, np.nan])) assert array_equivalent(np.array([np.nan, 1, np.nan]), np.array([np.nan, 1, np.nan])) assert array_equivalent(np.array([np.nan, None], dtype='object'), np.array([np.nan, None], dtype='object')) assert array_equivalent(np.array([np.nan, 1+1j], dtype='complex'), np.array([np.nan, 1+1j], dtype='complex')) assert not array_equivalent(np.array([np.nan, 1+1j], dtype='complex'), np.array([np.nan, 1+2j], dtype='complex')) assert not array_equivalent(np.array([np.nan, 1, np.nan]), np.array([np.nan, 2, np.nan])) assert not array_equivalent(np.array(['a', 'b', 'c', 'd']), np.array(['e', 'e'])) assert array_equivalent(Float64Index([0, np.nan]), Float64Index([0, np.nan])) assert not array_equivalent(Float64Index([0, np.nan]), Float64Index([1, np.nan])) assert array_equivalent(DatetimeIndex([0, np.nan]), DatetimeIndex([0, np.nan])) assert not array_equivalent(DatetimeIndex([0, np.nan]), DatetimeIndex([1, np.nan])) def test_datetimeindex_from_empty_datetime64_array(): for unit in [ 'ms', 'us', 'ns' ]: idx = DatetimeIndex(np.array([], dtype='datetime64[%s]' % unit)) assert(len(idx) == 0) def test_nan_to_nat_conversions(): df = DataFrame(dict({ 'A' : np.asarray(lrange(10),dtype='float64'), 'B' : Timestamp('20010101') })) df.iloc[3:6,:] = np.nan result = df.loc[4,'B'].value assert(result == iNaT) s = df['B'].copy() s._data = s._data.setitem(indexer=tuple([slice(8,9)]),value=np.nan) assert(isnull(s[8])) # numpy < 1.7.0 is wrong from distutils.version import LooseVersion if LooseVersion(np.__version__) >= '1.7.0': assert(s[8].value == np.datetime64('NaT').astype(np.int64)) def test_any_none(): assert(com._any_none(1, 2, 3, None)) assert(not com._any_none(1, 2, 3, 4)) def test_all_not_none(): assert(com._all_not_none(1, 2, 3, 4)) assert(not com._all_not_none(1, 2, 3, None)) assert(not com._all_not_none(None, None, None, None)) def test_repr_binary_type(): import string letters = string.ascii_letters btype = compat.binary_type try: raw = btype(letters, encoding=cf.get_option('display.encoding')) except TypeError: raw = btype(letters) b = compat.text_type(compat.bytes_to_str(raw)) res = com.pprint_thing(b, quote_strings=True) assert_equal(res, repr(b)) res = com.pprint_thing(b, quote_strings=False) assert_equal(res, b) def test_adjoin(): data = [['a', 'b', 'c'], ['dd', 'ee', 'ff'], ['ggg', 'hhh', 'iii']] expected = 'a dd ggg\nb ee hhh\nc ff iii' adjoined = com.adjoin(2, *data) assert(adjoined == expected) class TestFormattBase(tm.TestCase): def test_adjoin(self): data = [['a', 'b', 'c'], ['dd', 'ee', 'ff'], ['ggg', 'hhh', 'iii']] expected = 'a dd ggg\nb ee hhh\nc ff iii' adjoined = com.adjoin(2, *data) self.assertEqual(adjoined, expected) def test_adjoin_unicode(self): data = [[u'あ', 'b', 'c'], ['dd', u'ええ', 'ff'], ['ggg', 'hhh', u'いいい']] expected = u'あ dd ggg\nb ええ hhh\nc ff いいい' adjoined = com.adjoin(2, *data) self.assertEqual(adjoined, expected) adj = fmt.EastAsianTextAdjustment() expected = u"""あ dd ggg b ええ hhh c ff いいい""" adjoined = adj.adjoin(2, *data) self.assertEqual(adjoined, expected) cols = adjoined.split('\n') self.assertEqual(adj.len(cols[0]), 13) self.assertEqual(adj.len(cols[1]), 13) self.assertEqual(adj.len(cols[2]), 16) expected = u"""あ dd ggg b ええ hhh c ff いいい""" adjoined = adj.adjoin(7, *data) self.assertEqual(adjoined, expected) cols = adjoined.split('\n') self.assertEqual(adj.len(cols[0]), 23) self.assertEqual(adj.len(cols[1]), 23) self.assertEqual(adj.len(cols[2]), 26) def test_justify(self): adj = fmt.EastAsianTextAdjustment() def just(x, *args, **kwargs): # wrapper to test single str return adj.justify([x], *args, **kwargs)[0] self.assertEqual(just('abc', 5, mode='left'), 'abc ') self.assertEqual(just('abc', 5, mode='center'), ' abc ') self.assertEqual(just('abc', 5, mode='right'), ' abc') self.assertEqual(just(u'abc', 5, mode='left'), 'abc ') self.assertEqual(just(u'abc', 5, mode='center'), ' abc ') self.assertEqual(just(u'abc', 5, mode='right'), ' abc') self.assertEqual(just(u'パンダ', 5, mode='left'), u'パンダ') self.assertEqual(just(u'パンダ', 5, mode='center'), u'パンダ') self.assertEqual(just(u'パンダ', 5, mode='right'), u'パンダ') self.assertEqual(just(u'パンダ', 10, mode='left'), u'パンダ ') self.assertEqual(just(u'パンダ', 10, mode='center'), u' パンダ ') self.assertEqual(just(u'パンダ', 10, mode='right'), u' パンダ') def test_east_asian_len(self): adj = fmt.EastAsianTextAdjustment() self.assertEqual(adj.len('abc'), 3) self.assertEqual(adj.len(u'abc'), 3) self.assertEqual(adj.len(u'パンダ'), 6) self.assertEqual(adj.len(u'パンダ'), 5) self.assertEqual(adj.len(u'パンダpanda'), 11) self.assertEqual(adj.len(u'パンダpanda'), 10) def test_ambiguous_width(self): adj = fmt.EastAsianTextAdjustment() self.assertEqual(adj.len(u'¡¡ab'), 4) with cf.option_context('display.unicode.ambiguous_as_wide', True): adj = fmt.EastAsianTextAdjustment() self.assertEqual(adj.len(u'¡¡ab'), 6) data = [[u'あ', 'b', 'c'], ['dd', u'ええ', 'ff'], ['ggg', u'¡¡ab', u'いいい']] expected = u'あ dd ggg \nb ええ ¡¡ab\nc ff いいい' adjoined = adj.adjoin(2, *data) self.assertEqual(adjoined, expected) def test_iterpairs(): data = [1, 2, 3, 4] expected = [(1, 2), (2, 3), (3, 4)] result = list(com.iterpairs(data)) assert(result == expected) def test_split_ranges(): def _bin(x, width): "return int(x) as a base2 string of given width" return ''.join(str((x >> i) & 1) for i in range(width - 1, -1, -1)) def test_locs(mask): nfalse = sum(np.array(mask) == 0) remaining = 0 for s, e in com.split_ranges(mask): remaining += e - s assert 0 not in mask[s:e] # make sure the total items covered by the ranges are a complete cover assert remaining + nfalse == len(mask) # exhaustively test all possible mask sequences of length 8 ncols = 8 for i in range(2 ** ncols): cols = lmap(int, list(_bin(i, ncols))) # count up in base2 mask = [cols[i] == 1 for i in range(len(cols))] test_locs(mask) # base cases test_locs([]) test_locs([0]) test_locs([1]) def test_indent(): s = 'a b c\nd e f' result = com.indent(s, spaces=6) assert(result == ' a b c\n d e f') def test_banner(): ban = com.banner('hi') assert(ban == ('%s\nhi\n%s' % ('=' * 80, '=' * 80))) def test_map_indices_py(): data = [4, 3, 2, 1] expected = {4: 0, 3: 1, 2: 2, 1: 3} result = com.map_indices_py(data) assert(result == expected) def test_union(): a = [1, 2, 3] b = [4, 5, 6] union = sorted(com.union(a, b)) assert((a + b) == union) def test_difference(): a = [1, 2, 3] b = [1, 2, 3, 4, 5, 6] inter = sorted(com.difference(b, a)) assert([4, 5, 6] == inter) def test_intersection(): a = [1, 2, 3] b = [1, 2, 3, 4, 5, 6] inter = sorted(com.intersection(a, b)) assert(a == inter) def test_groupby(): values = ['foo', 'bar', 'baz', 'baz2', 'qux', 'foo3'] expected = {'f': ['foo', 'foo3'], 'b': ['bar', 'baz', 'baz2'], 'q': ['qux']} grouped = com.groupby(values, lambda x: x[0]) for k, v in grouped: assert v == expected[k] def test_is_list_like(): passes = ([], [1], (1,), (1, 2), {'a': 1}, set([1, 'a']), Series([1]), Series([]), Series(['a']).str) fails = (1, '2', object()) for p in passes: assert com.is_list_like(p) for f in fails: assert not com.is_list_like(f) def test_is_named_tuple(): passes = (collections.namedtuple('Test',list('abc'))(1,2,3),) fails = ((1,2,3), 'a', Series({'pi':3.14})) for p in passes: assert com.is_named_tuple(p) for f in fails: assert not com.is_named_tuple(f) def test_is_hashable(): # all new-style classes are hashable by default class HashableClass(object): pass class UnhashableClass1(object): __hash__ = None class UnhashableClass2(object): def __hash__(self): raise TypeError("Not hashable") hashable = ( 1, 3.14, np.float64(3.14), 'a', tuple(), (1,), HashableClass(), ) not_hashable = ( [], UnhashableClass1(), ) abc_hashable_not_really_hashable = ( ([],), UnhashableClass2(), ) for i in hashable: assert com.is_hashable(i) for i in not_hashable: assert not com.is_hashable(i) for i in abc_hashable_not_really_hashable: assert not com.is_hashable(i) # numpy.array is no longer collections.Hashable as of # https://github.com/numpy/numpy/pull/5326, just test # pandas.common.is_hashable() assert not com.is_hashable(np.array([])) # old-style classes in Python 2 don't appear hashable to # collections.Hashable but also seem to support hash() by default if compat.PY2: class OldStyleClass(): pass c = OldStyleClass() assert not isinstance(c, collections.Hashable) assert com.is_hashable(c) hash(c) # this will not raise def test_ensure_int32(): values = np.arange(10, dtype=np.int32) result = com._ensure_int32(values) assert(result.dtype == np.int32) values = np.arange(10, dtype=np.int64) result = com._ensure_int32(values) assert(result.dtype == np.int32) def test_ensure_platform_int(): # verify that when we create certain types of indices # they remain the correct type under platform conversions from pandas.core.index import Int64Index # int64 x = Int64Index([1, 2, 3], dtype='int64') assert(x.dtype == np.int64) pi = com._ensure_platform_int(x) assert(pi.dtype == np.int_) # int32 x = Int64Index([1, 2, 3], dtype='int32') assert(x.dtype == np.int32) pi = com._ensure_platform_int(x) assert(pi.dtype == np.int_) # TODO: fix this broken test # def test_console_encode(): # """ # On Python 2, if sys.stdin.encoding is None (IPython with zmq frontend) # common.console_encode should encode things as utf-8. # """ # if compat.PY3: # raise nose.SkipTest # with tm.stdin_encoding(encoding=None): # result = com.console_encode(u"\u05d0") # expected = u"\u05d0".encode('utf-8') # assert (result == expected) def test_is_re(): passes = re.compile('ad'), fails = 'x', 2, 3, object() for p in passes: assert com.is_re(p) for f in fails: assert not com.is_re(f) def test_is_recompilable(): passes = (r'a', u('x'), r'asdf', re.compile('adsf'), u(r'\u2233\s*'), re.compile(r'')) fails = 1, [], object() for p in passes: assert com.is_re_compilable(p) for f in fails: assert not com.is_re_compilable(f) def test_random_state(): import numpy.random as npr # Check with seed state = com._random_state(5) assert_equal(state.uniform(), npr.RandomState(5).uniform()) # Check with random state object state2 = npr.RandomState(10) assert_equal(com._random_state(state2).uniform(), npr.RandomState(10).uniform()) # check with no arg random state assert isinstance(com._random_state(), npr.RandomState) # Error for floats or strings with tm.assertRaises(ValueError): com._random_state('test') with tm.assertRaises(ValueError): com._random_state(5.5) def test_maybe_match_name(): matched = com._maybe_match_name(Series([1], name='x'), Series([2], name='x')) assert(matched == 'x') matched = com._maybe_match_name(Series([1], name='x'), Series([2], name='y')) assert(matched is None) matched = com._maybe_match_name(Series([1]), Series([2], name='x')) assert(matched is None) matched = com._maybe_match_name(Series([1], name='x'), Series([2])) assert(matched is None) matched = com._maybe_match_name(Series([1], name='x'), [2]) assert(matched == 'x') matched = com._maybe_match_name([1], Series([2], name='y')) assert(matched == 'y') class TestTake(tm.TestCase): # standard incompatible fill error fill_error = re.compile("Incompatible type for fill_value") _multiprocess_can_split_ = True def test_1d_with_out(self): def _test_dtype(dtype, can_hold_na): data = np.random.randint(0, 2, 4).astype(dtype) indexer = [2, 1, 0, 1] out = np.empty(4, dtype=dtype) com.take_1d(data, indexer, out=out) expected = data.take(indexer) tm.assert_almost_equal(out, expected) indexer = [2, 1, 0, -1] out = np.empty(4, dtype=dtype) if can_hold_na: com.take_1d(data, indexer, out=out) expected = data.take(indexer) expected[3] = np.nan tm.assert_almost_equal(out, expected) else: with tm.assertRaisesRegexp(TypeError, self.fill_error): com.take_1d(data, indexer, out=out) # no exception o/w data.take(indexer, out=out) _test_dtype(np.float64, True) _test_dtype(np.float32, True) _test_dtype(np.uint64, False) _test_dtype(np.uint32, False) _test_dtype(np.uint16, False) _test_dtype(np.uint8, False) _test_dtype(np.int64, False) _test_dtype(np.int32, False) _test_dtype(np.int16, False) _test_dtype(np.int8, False) _test_dtype(np.object_, True) _test_dtype(np.bool, False) def test_1d_fill_nonna(self): def _test_dtype(dtype, fill_value, out_dtype): data = np.random.randint(0, 2, 4).astype(dtype) indexer = [2, 1, 0, -1] result = com.take_1d(data, indexer, fill_value=fill_value) assert((result[[0, 1, 2]] == data[[2, 1, 0]]).all()) assert(result[3] == fill_value) assert(result.dtype == out_dtype) indexer = [2, 1, 0, 1] result = com.take_1d(data, indexer, fill_value=fill_value) assert((result[[0, 1, 2, 3]] == data[indexer]).all()) assert(result.dtype == dtype) _test_dtype(np.int8, np.int16(127), np.int8) _test_dtype(np.int8, np.int16(128), np.int16) _test_dtype(np.int32, 1, np.int32) _test_dtype(np.int32, 2.0, np.float64) _test_dtype(np.int32, 3.0 + 4.0j, np.complex128) _test_dtype(np.int32, True, np.object_) _test_dtype(np.int32, '', np.object_) _test_dtype(np.float64, 1, np.float64) _test_dtype(np.float64, 2.0, np.float64) _test_dtype(np.float64, 3.0 + 4.0j, np.complex128) _test_dtype(np.float64, True, np.object_) _test_dtype(np.float64, '', np.object_) _test_dtype(np.complex128, 1, np.complex128) _test_dtype(np.complex128, 2.0, np.complex128) _test_dtype(np.complex128, 3.0 + 4.0j, np.complex128) _test_dtype(np.complex128, True, np.object_) _test_dtype(np.complex128, '', np.object_) _test_dtype(np.bool_, 1, np.object_) _test_dtype(np.bool_, 2.0, np.object_) _test_dtype(np.bool_, 3.0 + 4.0j, np.object_) _test_dtype(np.bool_, True, np.bool_) _test_dtype(np.bool_, '', np.object_) def test_2d_with_out(self): def _test_dtype(dtype, can_hold_na, writeable=True): data = np.random.randint(0, 2, (5, 3)).astype(dtype) data.flags.writeable = writeable indexer = [2, 1, 0, 1] out0 = np.empty((4, 3), dtype=dtype) out1 = np.empty((5, 4), dtype=dtype) com.take_nd(data, indexer, out=out0, axis=0) com.take_nd(data, indexer, out=out1, axis=1) expected0 = data.take(indexer, axis=0) expected1 = data.take(indexer, axis=1) tm.assert_almost_equal(out0, expected0) tm.assert_almost_equal(out1, expected1) indexer = [2, 1, 0, -1] out0 = np.empty((4, 3), dtype=dtype) out1 = np.empty((5, 4), dtype=dtype) if can_hold_na: com.take_nd(data, indexer, out=out0, axis=0) com.take_nd(data, indexer, out=out1, axis=1) expected0 = data.take(indexer, axis=0) expected1 = data.take(indexer, axis=1) expected0[3, :] = np.nan expected1[:, 3] = np.nan tm.assert_almost_equal(out0, expected0) tm.assert_almost_equal(out1, expected1) else: for i, out in enumerate([out0, out1]): with tm.assertRaisesRegexp(TypeError, self.fill_error): com.take_nd(data, indexer, out=out, axis=i) # no exception o/w data.take(indexer, out=out, axis=i) for writeable in [True, False]: # Check that take_nd works both with writeable arrays (in which # case fast typed memoryviews implementation) and read-only # arrays alike. _test_dtype(np.float64, True, writeable=writeable) _test_dtype(np.float32, True, writeable=writeable) _test_dtype(np.uint64, False, writeable=writeable) _test_dtype(np.uint32, False, writeable=writeable) _test_dtype(np.uint16, False, writeable=writeable) _test_dtype(np.uint8, False, writeable=writeable) _test_dtype(np.int64, False, writeable=writeable) _test_dtype(np.int32, False, writeable=writeable) _test_dtype(np.int16, False, writeable=writeable) _test_dtype(np.int8, False, writeable=writeable) _test_dtype(np.object_, True, writeable=writeable) _test_dtype(np.bool, False, writeable=writeable) def test_2d_fill_nonna(self): def _test_dtype(dtype, fill_value, out_dtype): data = np.random.randint(0, 2, (5, 3)).astype(dtype) indexer = [2, 1, 0, -1] result = com.take_nd(data, indexer, axis=0, fill_value=fill_value) assert((result[[0, 1, 2], :] == data[[2, 1, 0], :]).all()) assert((result[3, :] == fill_value).all()) assert(result.dtype == out_dtype) result = com.take_nd(data, indexer, axis=1, fill_value=fill_value) assert((result[:, [0, 1, 2]] == data[:, [2, 1, 0]]).all()) assert((result[:, 3] == fill_value).all()) assert(result.dtype == out_dtype) indexer = [2, 1, 0, 1] result = com.take_nd(data, indexer, axis=0, fill_value=fill_value) assert((result[[0, 1, 2, 3], :] == data[indexer, :]).all()) assert(result.dtype == dtype) result = com.take_nd(data, indexer, axis=1, fill_value=fill_value) assert((result[:, [0, 1, 2, 3]] == data[:, indexer]).all()) assert(result.dtype == dtype) _test_dtype(np.int8, np.int16(127), np.int8) _test_dtype(np.int8, np.int16(128), np.int16) _test_dtype(np.int32, 1, np.int32) _test_dtype(np.int32, 2.0, np.float64) _test_dtype(np.int32, 3.0 + 4.0j, np.complex128) _test_dtype(np.int32, True, np.object_) _test_dtype(np.int32, '', np.object_) _test_dtype(np.float64, 1, np.float64) _test_dtype(np.float64, 2.0, np.float64) _test_dtype(np.float64, 3.0 + 4.0j, np.complex128) _test_dtype(np.float64, True, np.object_) _test_dtype(np.float64, '', np.object_) _test_dtype(np.complex128, 1, np.complex128) _test_dtype(np.complex128, 2.0, np.complex128) _test_dtype(np.complex128, 3.0 + 4.0j, np.complex128) _test_dtype(np.complex128, True, np.object_) _test_dtype(np.complex128, '', np.object_) _test_dtype(np.bool_, 1, np.object_) _test_dtype(np.bool_, 2.0, np.object_) _test_dtype(np.bool_, 3.0 + 4.0j, np.object_) _test_dtype(np.bool_, True, np.bool_) _test_dtype(np.bool_, '', np.object_) def test_3d_with_out(self): def _test_dtype(dtype, can_hold_na): data = np.random.randint(0, 2, (5, 4, 3)).astype(dtype) indexer = [2, 1, 0, 1] out0 = np.empty((4, 4, 3), dtype=dtype) out1 = np.empty((5, 4, 3), dtype=dtype) out2 = np.empty((5, 4, 4), dtype=dtype) com.take_nd(data, indexer, out=out0, axis=0) com.take_nd(data, indexer, out=out1, axis=1) com.take_nd(data, indexer, out=out2, axis=2) expected0 = data.take(indexer, axis=0) expected1 = data.take(indexer, axis=1) expected2 = data.take(indexer, axis=2) tm.assert_almost_equal(out0, expected0) tm.assert_almost_equal(out1, expected1) tm.assert_almost_equal(out2, expected2) indexer = [2, 1, 0, -1] out0 = np.empty((4, 4, 3), dtype=dtype) out1 = np.empty((5, 4, 3), dtype=dtype) out2 = np.empty((5, 4, 4), dtype=dtype) if can_hold_na: com.take_nd(data, indexer, out=out0, axis=0) com.take_nd(data, indexer, out=out1, axis=1) com.take_nd(data, indexer, out=out2, axis=2) expected0 = data.take(indexer, axis=0) expected1 = data.take(indexer, axis=1) expected2 = data.take(indexer, axis=2) expected0[3, :, :] = np.nan expected1[:, 3, :] = np.nan expected2[:, :, 3] = np.nan tm.assert_almost_equal(out0, expected0) tm.assert_almost_equal(out1, expected1) tm.assert_almost_equal(out2, expected2) else: for i, out in enumerate([out0, out1, out2]): with tm.assertRaisesRegexp(TypeError, self.fill_error): com.take_nd(data, indexer, out=out, axis=i) # no exception o/w data.take(indexer, out=out, axis=i) _test_dtype(np.float64, True) _test_dtype(np.float32, True) _test_dtype(np.uint64, False) _test_dtype(np.uint32, False) _test_dtype(np.uint16, False) _test_dtype(np.uint8, False) _test_dtype(np.int64, False) _test_dtype(np.int32, False) _test_dtype(np.int16, False) _test_dtype(np.int8, False) _test_dtype(np.object_, True) _test_dtype(np.bool, False) def test_3d_fill_nonna(self): def _test_dtype(dtype, fill_value, out_dtype): data = np.random.randint(0, 2, (5, 4, 3)).astype(dtype) indexer = [2, 1, 0, -1] result = com.take_nd(data, indexer, axis=0, fill_value=fill_value) assert((result[[0, 1, 2], :, :] == data[[2, 1, 0], :, :]).all()) assert((result[3, :, :] == fill_value).all()) assert(result.dtype == out_dtype) result = com.take_nd(data, indexer, axis=1, fill_value=fill_value) assert((result[:, [0, 1, 2], :] == data[:, [2, 1, 0], :]).all()) assert((result[:, 3, :] == fill_value).all()) assert(result.dtype == out_dtype) result = com.take_nd(data, indexer, axis=2, fill_value=fill_value) assert((result[:, :, [0, 1, 2]] == data[:, :, [2, 1, 0]]).all()) assert((result[:, :, 3] == fill_value).all()) assert(result.dtype == out_dtype) indexer = [2, 1, 0, 1] result = com.take_nd(data, indexer, axis=0, fill_value=fill_value) assert((result[[0, 1, 2, 3], :, :] == data[indexer, :, :]).all()) assert(result.dtype == dtype) result = com.take_nd(data, indexer, axis=1, fill_value=fill_value) assert((result[:, [0, 1, 2, 3], :] == data[:, indexer, :]).all()) assert(result.dtype == dtype) result = com.take_nd(data, indexer, axis=2, fill_value=fill_value) assert((result[:, :, [0, 1, 2, 3]] == data[:, :, indexer]).all()) assert(result.dtype == dtype) _test_dtype(np.int8, np.int16(127), np.int8) _test_dtype(np.int8, np.int16(128), np.int16) _test_dtype(np.int32, 1, np.int32) _test_dtype(np.int32, 2.0, np.float64) _test_dtype(np.int32, 3.0 + 4.0j, np.complex128) _test_dtype(np.int32, True, np.object_) _test_dtype(np.int32, '', np.object_) _test_dtype(np.float64, 1, np.float64) _test_dtype(np.float64, 2.0, np.float64) _test_dtype(np.float64, 3.0 + 4.0j, np.complex128) _test_dtype(np.float64, True, np.object_) _test_dtype(np.float64, '', np.object_) _test_dtype(np.complex128, 1, np.complex128) _test_dtype(np.complex128, 2.0, np.complex128) _test_dtype(np.complex128, 3.0 + 4.0j, np.complex128) _test_dtype(np.complex128, True, np.object_) _test_dtype(np.complex128, '', np.object_) _test_dtype(np.bool_, 1, np.object_) _test_dtype(np.bool_, 2.0, np.object_) _test_dtype(np.bool_, 3.0 + 4.0j, np.object_) _test_dtype(np.bool_, True, np.bool_) _test_dtype(np.bool_, '', np.object_) def test_1d_other_dtypes(self): arr = np.random.randn(10).astype(np.float32) indexer = [1, 2, 3, -1] result = com.take_1d(arr, indexer) expected = arr.take(indexer) expected[-1] = np.nan tm.assert_almost_equal(result, expected) def test_2d_other_dtypes(self): arr = np.random.randn(10, 5).astype(np.float32) indexer = [1, 2, 3, -1] # axis=0 result = com.take_nd(arr, indexer, axis=0) expected = arr.take(indexer, axis=0) expected[-1] = np.nan tm.assert_almost_equal(result, expected) # axis=1 result = com.take_nd(arr, indexer, axis=1) expected = arr.take(indexer, axis=1) expected[:, -1] = np.nan tm.assert_almost_equal(result, expected) def test_1d_bool(self): arr = np.array([0, 1, 0], dtype=bool) result = com.take_1d(arr, [0, 2, 2, 1]) expected = arr.take([0, 2, 2, 1]) self.assert_numpy_array_equal(result, expected) result = com.take_1d(arr, [0, 2, -1]) self.assertEqual(result.dtype, np.object_) def test_2d_bool(self): arr = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 1]], dtype=bool) result = com.take_nd(arr, [0, 2, 2, 1]) expected = arr.take([0, 2, 2, 1], axis=0) self.assert_numpy_array_equal(result, expected) result = com.take_nd(arr, [0, 2, 2, 1], axis=1) expected = arr.take([0, 2, 2, 1], axis=1) self.assert_numpy_array_equal(result, expected) result = com.take_nd(arr, [0, 2, -1]) self.assertEqual(result.dtype, np.object_) def test_2d_float32(self): arr = np.random.randn(4, 3).astype(np.float32) indexer = [0, 2, -1, 1, -1] # axis=0 result = com.take_nd(arr, indexer, axis=0) result2 = np.empty_like(result) com.take_nd(arr, indexer, axis=0, out=result2) tm.assert_almost_equal(result, result2) expected = arr.take(indexer, axis=0) expected[[2, 4], :] = np.nan tm.assert_almost_equal(result, expected) #### this now accepts a float32! # test with float64 out buffer out = np.empty((len(indexer), arr.shape[1]), dtype='float32') com.take_nd(arr, indexer, out=out) # it works! # axis=1 result = com.take_nd(arr, indexer, axis=1) result2 = np.empty_like(result) com.take_nd(arr, indexer, axis=1, out=result2) tm.assert_almost_equal(result, result2) expected = arr.take(indexer, axis=1) expected[:, [2, 4]] = np.nan tm.assert_almost_equal(result, expected) def test_2d_datetime64(self): # 2005/01/01 - 2006/01/01 arr = np.random.randint(long(11045376), long(11360736), (5, 3))*100000000000 arr = arr.view(dtype='datetime64[ns]') indexer = [0, 2, -1, 1, -1] # axis=0 result = com.take_nd(arr, indexer, axis=0) result2 = np.empty_like(result) com.take_nd(arr, indexer, axis=0, out=result2) tm.assert_almost_equal(result, result2) expected = arr.take(indexer, axis=0) expected.view(np.int64)[[2, 4], :] = iNaT tm.assert_almost_equal(result, expected) result = com.take_nd(arr, indexer, axis=0, fill_value=datetime(2007, 1, 1)) result2 = np.empty_like(result) com.take_nd(arr, indexer, out=result2, axis=0, fill_value=datetime(2007, 1, 1)) tm.assert_almost_equal(result, result2) expected = arr.take(indexer, axis=0) expected[[2, 4], :] = datetime(2007, 1, 1) tm.assert_almost_equal(result, expected) # axis=1 result = com.take_nd(arr, indexer, axis=1) result2 = np.empty_like(result) com.take_nd(arr, indexer, axis=1, out=result2) tm.assert_almost_equal(result, result2) expected = arr.take(indexer, axis=1) expected.view(np.int64)[:, [2, 4]] = iNaT tm.assert_almost_equal(result, expected) result = com.take_nd(arr, indexer, axis=1, fill_value=datetime(2007, 1, 1)) result2 = np.empty_like(result) com.take_nd(arr, indexer, out=result2, axis=1, fill_value=datetime(2007, 1, 1)) tm.assert_almost_equal(result, result2) expected = arr.take(indexer, axis=1) expected[:, [2, 4]] = datetime(2007, 1, 1) tm.assert_almost_equal(result, expected) class TestMaybe(tm.TestCase): def test_maybe_convert_string_to_array(self): result = com._maybe_convert_string_to_object('x') tm.assert_numpy_array_equal(result, np.array(['x'], dtype=object)) self.assertTrue(result.dtype == object) result = com._maybe_convert_string_to_object(1) self.assertEqual(result, 1) arr = np.array(['x', 'y'], dtype=str) result = com._maybe_convert_string_to_object(arr) tm.assert_numpy_array_equal(result, np.array(['x', 'y'], dtype=object)) self.assertTrue(result.dtype == object) # unicode arr = np.array(['x', 'y']).astype('U') result = com._maybe_convert_string_to_object(arr) tm.assert_numpy_array_equal(result, np.array(['x', 'y'], dtype=object)) self.assertTrue(result.dtype == object) # object arr = np.array(['x', 2], dtype=object) result = com._maybe_convert_string_to_object(arr) tm.assert_numpy_array_equal(result, np.array(['x', 2], dtype=object)) self.assertTrue(result.dtype == object) def test_possibly_convert_objects_copy(): values = np.array([1, 2]) out = convert._possibly_convert_objects(values, copy=False) assert_true(values is out) out = convert._possibly_convert_objects(values, copy=True) assert_true(values is not out) values = np.array(['apply','banana']) out = convert._possibly_convert_objects(values, copy=False) assert_true(values is out) out = convert._possibly_convert_objects(values, copy=True) assert_true(values is not out) def test_dict_compat(): data_datetime64 = {np.datetime64('1990-03-15'): 1, np.datetime64('2015-03-15'): 2} data_unchanged = {1: 2, 3: 4, 5: 6} expected = {Timestamp('1990-3-15'): 1, Timestamp('2015-03-15'): 2} assert(com._dict_compat(data_datetime64) == expected) assert(com._dict_compat(expected) == expected) assert(com._dict_compat(data_unchanged) == data_unchanged) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
mit
sumanthjamadagni/OZ
WCA_Isotherms.py
1
2071
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import Potentials import OZ_Functions import matplotlib from itertools import cycle colors = ['red', 'blue', 'green', 'cyan', 'black', 'orange'] ColorCycler = cycle(colors) FS = 18 matplotlib.rc('xtick', labelsize=FS) matplotlib.rc('ytick', labelsize=FS) dr = 0.02 nr = 2048 r,k = OZ_Functions.Create_r_k(dr, nr) Ur = Potentials.WCAPotential(r,sig=1.0, eps=1.0) Fig = plt.figure() Fig1 = Fig.add_subplot(221) Fig2 = Fig.add_subplot(222) Fig3 = Fig.add_subplot(223) Fig4 = Fig.add_subplot(224) Fig1.set_xlabel('r', fontsize=FS) Fig2.set_xlabel('k', fontsize=FS) Fig1.set_ylabel('g(r)', fontsize=FS) Fig2.set_ylabel('S(k)', fontsize=FS) Fig1.set_xlim([0,4]) Fig2.set_xlim([0,30]) T = 1.0 B2 = Potentials.CalcB2(r,Ur,kT=T) nrho = 12 rhoArray = np.linspace(0.01,1.01,nrho) cr_guess = None rho_converged = [] Pressures = [] Compressibility = [] for irho in range(nrho): rho = rhoArray[irho] Flag, hr, cr, er, hk, Sk = OZ_Functions.OZSolver_HNC_Iterative(r, k, Ur, rho, kT=T, maxiter=10000, w_old_start=0.50,w_old_max=0.99,tol=1e-8, cr_guess=cr_guess) cr_guess = cr if Flag == 0: P = OZ_Functions.Calc_Pvirial(r,hr+1,Ur,rho,kT=T, rmin=0.15) print " P = ", P Pressures.append(P) rho_converged.append(rho) kappa = OZ_Functions.CalculateKappa(1+rho*hk, rho, kT=T) Compressibility.append(kappa) Fig1.plot(r, hr + 1.0) Fig2.plot(k, 1 + rho*hk) rho_converged = np.array(rho_converged) P_gas = rho_converged * T + rho_converged**2 * T * B2 Fig3.set_xlabel('Density', fontsize=FS) Fig4.set_xlabel('Density', fontsize=FS) Fig3.set_ylabel('Pressure', fontsize=FS) Fig4.set_ylabel('Compressibility', fontsize=FS) Fig4.set_yscale('log') Fig3.plot(rho_converged, Pressures, 'b-s') Fig3.plot(rho_converged, P_gas, 'g-d') Fig4.plot(rho_converged, Compressibility, 'r-d') Fig.suptitle("T = " + str(T), fontsize=FS + 2) Fig.tight_layout()
gpl-3.0
gpfreitas/bokeh
bokeh/compat/mplexporter/tools.py
75
1732
""" Tools for matplotlib plot exporting """ def ipynb_vega_init(): """Initialize the IPython notebook display elements This function borrows heavily from the excellent vincent package: http://github.com/wrobstory/vincent """ try: from IPython.core.display import display, HTML except ImportError: print('IPython Notebook could not be loaded.') require_js = ''' if (window['d3'] === undefined) {{ require.config({{ paths: {{d3: "http://d3js.org/d3.v3.min"}} }}); require(["d3"], function(d3) {{ window.d3 = d3; {0} }}); }}; if (window['topojson'] === undefined) {{ require.config( {{ paths: {{topojson: "http://d3js.org/topojson.v1.min"}} }} ); require(["topojson"], function(topojson) {{ window.topojson = topojson; }}); }}; ''' d3_geo_projection_js_url = "http://d3js.org/d3.geo.projection.v0.min.js" d3_layout_cloud_js_url = ("http://wrobstory.github.io/d3-cloud/" "d3.layout.cloud.js") topojson_js_url = "http://d3js.org/topojson.v1.min.js" vega_js_url = 'http://trifacta.github.com/vega/vega.js' dep_libs = '''$.getScript("%s", function() { $.getScript("%s", function() { $.getScript("%s", function() { $.getScript("%s", function() { $([IPython.events]).trigger("vega_loaded.vincent"); }) }) }) });''' % (d3_geo_projection_js_url, d3_layout_cloud_js_url, topojson_js_url, vega_js_url) load_js = require_js.format(dep_libs) html = '<script>'+load_js+'</script>' display(HTML(html))
bsd-3-clause
paulbrodersen/netgraph
netgraph/_utils.py
1
11262
#!/usr/bin/env python import numpy as np from scipy.interpolate import BSpline def _save_cast_float_to_int(num): if isinstance(num, (float, int)) and np.isclose(num, int(num)): return int(num) return num def _get_unique_nodes(edges): """ Using numpy.unique promotes nodes to numpy.float/numpy.int/numpy.str, and breaks for nodes that have a more complicated type such as a tuple. """ return list(set(_flatten(edges))) def _flatten(nested_list): return [item for sublist in nested_list for item in sublist] def _edge_list_to_adjacency_matrix(edges, edge_weights=None, unique_nodes=None): sources = [s for (s, _) in edges] targets = [t for (_, t) in edges] if edge_weights: weights = [edge_weights[edge] for edge in edges] else: weights = np.ones((len(edges))) if unique_nodes is None: # map nodes to consecutive integers nodes = sources + targets unique_nodes = set(nodes) indices = range(len(unique_nodes)) node_to_idx = dict(zip(unique_nodes, indices)) source_indices = [node_to_idx[source] for source in sources] target_indices = [node_to_idx[target] for target in targets] total_nodes = len(unique_nodes) adjacency_matrix = np.zeros((total_nodes, total_nodes)) adjacency_matrix[source_indices, target_indices] = weights return adjacency_matrix def _edge_list_to_adjacency_list(edges, directed=True): if not directed: edges = edges + [(target, source) for (source, target) in edges] # forces copy adjacency = dict() for source, target in edges: if source in adjacency: adjacency[source] |= set([target]) else: adjacency[source] = set([target]) return adjacency def _get_subgraph(edges, nodes): return [(source, target) for source, target in edges \ if (source in nodes) and (target in nodes)] def _bspline(cv, n=100, degree=5, periodic=False): """ Calculate n samples on a bspline cv : Array of control vertices n : Number of samples to return degree: Curve degree periodic: True - Curve is closed Adapted from https://stackoverflow.com/a/35007804/2912349 """ cv = np.asarray(cv) count = cv.shape[0] # Closed curve if periodic: kv = np.arange(-degree,count+degree+1) factor, fraction = divmod(count+degree+1, count) cv = np.roll(np.concatenate((cv,) * factor + (cv[:fraction],)),-1,axis=0) degree = np.clip(degree,1,degree) # Opened curve else: degree = np.clip(degree,1,count-1) kv = np.clip(np.arange(count+degree+1)-degree,0,count-degree) # Return samples max_param = count - (degree * (1-periodic)) spl = BSpline(kv, cv, degree) return spl(np.linspace(0,max_param,n)) def _get_angle(dx, dy, radians=False): """Angle of vector in 2D.""" angle = np.arctan2(dy, dx) if radians: angle *= 360 / (2.0 * np.pi) return angle def _get_interior_angle_between(v1, v2, radians=False): """ Returns the angle in radians between vectors 'v1' and 'v2':: >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 Adapted from: https://stackoverflow.com/a/13849249/2912349 """ v1_u = get_unit_vector(v1) v2_u = get_unit_vector(v2) angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) if radians: angle *= 360 / (2 * np.pi) return angle def get_unit_vector(vector): """ Returns the unit vector of the vector. """ return vector / np.linalg.norm(vector) def _get_signed_angle_between(v1, v2, radians=False): """ Compute the signed angle in radians between two vectors. Adapted from: https://stackoverflow.com/a/16544330/2912349 """ x1, y1 = v1 x2, y2 = v2 dot = x1*x2 + y1*y2 det = x1*y2 - y1*x2 angle = np.arctan2(det, dot) if radians: angle *= 360 / (2 * np.pi) return angle def _get_n_points_on_a_circle(xy, radius, n, start_angle=0): angles = np.linspace(0, 2*np.pi, n + 1)[:-1] angles = (angles + start_angle) % (2*np.pi) positions = np.array([_get_point_on_a_circle(xy, radius, angle) for angle in angles]) return positions def _get_point_on_a_circle(origin, radius, angle): x0, y0 = origin x = x0 + radius * np.cos(angle) y = y0 + radius * np.sin(angle) return np.array([x, y]) def _get_parallel_line(path, delta): # initialise output orthogonal_unit_vector = np.zeros_like(path) tangents = path[2:] - path[:-2] # using the central difference approximation orthogonal_unit_vector[1:-1] = _get_orthogonal_unit_vector(tangents) # handle start and end points orthogonal_unit_vector[ 0] = _get_orthogonal_unit_vector(np.atleast_2d([path[ 1] - path[ 0]])) orthogonal_unit_vector[-1] = _get_orthogonal_unit_vector(np.atleast_2d([path[-1] - path[-2]])) return path + delta * orthogonal_unit_vector def _get_orthogonal_unit_vector(v): # adapted from https://stackoverflow.com/a/16890776/2912349 v = v / np.linalg.norm(v, axis=-1)[:, None] # unit vector w = np.c_[-v[:,1], v[:,0]] # orthogonal vector w = w / np.linalg.norm(w, axis=-1)[:, None] # orthogonal unit vector return w def _shorten_line_by(path, distance): """ Cut path off at the end by `distance`. """ distance_to_end = np.linalg.norm(path - path[-1], axis=1) is_valid = (distance_to_end - distance) >= 0 if np.any(is_valid): idx = np.where(is_valid)[0][-1] # i.e. the last valid point else: idx = 0 # We could truncate the path using `path[:idx+1]` and return here. # However, if the path is not densely sampled, the error will be large. # Therefor, we compute a point that is on the line from the last valid point to # the end point, and append it to the truncated path. vector = path[idx] - path[-1] unit_vector = vector / np.linalg.norm(vector) new_end_point = path[-1] + distance * unit_vector return np.concatenate([path[:idx+1], new_end_point[None, :]], axis=0) def _get_point_along_spline(spline, fraction): assert 0 <= fraction <= 1, "Fraction has to be a value between 0 and 1." deltas = np.diff(spline, axis=0) successive_distances = np.sqrt(np.sum(deltas**2, axis=1)) cumulative_sum = np.cumsum(successive_distances) desired_length = cumulative_sum[-1] * fraction idx = np.where(cumulative_sum >= desired_length)[0][0] # upper bound overhang = cumulative_sum[idx] - desired_length x, y = spline[idx+1] - overhang/successive_distances[idx] * deltas[idx] return x, y def _get_tangent_at_point(spline, fraction): assert 0 <= fraction <= 1, "Fraction has to be a value between 0 and 1." deltas = np.diff(spline, axis=0) successive_distances = np.sqrt(np.sum(deltas**2, axis=1)) cumulative_sum = np.cumsum(successive_distances) desired_length = cumulative_sum[-1] * fraction idx = np.where(cumulative_sum >= desired_length)[0][0] # upper bound return deltas[idx] def _get_orthogonal_projection_onto_segment(point, segment): # Adapted from https://stackoverflow.com/a/61343727/2912349 p1, p2 = segment segment_length = np.sum((p1-p2)**2) # The line extending the segment is parameterized as p1 + t (p2 - p1). # The projection falls where t = [(point-p1) . (p2-p1)] / |p2-p1|^2 # Project onto line through p1 and p2. t = np.sum((point - p1) * (p2 - p1)) / segment_length # # Project onto line segment between p1 and p2 or closest point of the line segment. # t = max(0, t) return p1 + t * (p2 - p1) def _get_text_object_dimensions(ax, string, *args, **kwargs): text_object = ax.text(0., 0., string, *args, **kwargs) renderer = _find_renderer(text_object.get_figure()) bbox_in_display_coordinates = text_object.get_window_extent(renderer) bbox_in_data_coordinates = bbox_in_display_coordinates.transformed(ax.transData.inverted()) w, h = bbox_in_data_coordinates.width, bbox_in_data_coordinates.height text_object.remove() return w, h def _find_renderer(fig): """ https://stackoverflow.com/questions/22667224/matplotlib-get-text-bounding-box-independent-of-backend """ if hasattr(fig.canvas, "get_renderer"): # Some backends, such as TkAgg, have the get_renderer method, which # makes this easy. renderer = fig.canvas.get_renderer() else: # Other backends do not have the get_renderer method, so we have a work # around to find the renderer. Print the figure to a temporary file # object, and then grab the renderer that was used. # (I stole this trick from the matplotlib backend_bases.py # print_figure() method.) import io fig.canvas.print_pdf(io.BytesIO()) renderer = fig._cachedRenderer return(renderer) def _make_pretty(ax): ax.set_xticks([]) ax.set_yticks([]) ax.set_aspect('equal') ax.get_figure().set_facecolor('w') ax.set_frame_on(False) ax.get_figure().canvas.draw() def _rank(vec): tmp = np.argsort(vec) ranks = np.empty_like(vec) ranks[tmp] = np.arange(len(vec)) return ranks def _invert_dict(mydict): inverse = dict() for key, value in mydict.items(): inverse.setdefault(value, set()).add(key) return inverse def _get_connected_components(adjacency_list): """ Get the connected components given a graph in adjacency list format. Arguments: ---------- adjacency_list : dict node ID : set of node IDs Adjacency list, i.e. a mapping from each node to its neighbours. Returns: -------- components : list of sets of node IDs The unconnected components of the graph. """ components = [] not_visited = set(list(adjacency_list.keys())) while not_visited: # i.e. while stack is non-empty (empty set is interpreted as `False`) start = not_visited.pop() component = _dfs(adjacency_list, start) components.append(component) # remove nodes that are in the component that we just found for node in component: try: not_visited.remove(node) except KeyError: # KeyErrors occur when we try to remove # 1) the start node (which we already popped), or # 2) leaf nodes, i.e. nodes with no outgoing edges pass # Often, we are only interested in the largest component, # hence we return the list of components sorted by size, largest first. components = sorted(components, key=len, reverse=True) return components def _dfs(adjacency_list, start, visited=None): if visited is None: visited = set() visited.add(start) for node in adjacency_list[start] - visited: if node in adjacency_list: _dfs(adjacency_list, node, visited) else: # otherwise no outgoing edge visited.add(node) return visited
gpl-3.0
kashif/scikit-learn
sklearn/datasets/twenty_newsgroups.py
35
13626
"""Caching loader for the 20 newsgroups text classification dataset The description of the dataset is available on the official website at: http://people.csail.mit.edu/jrennie/20Newsgroups/ Quoting the introduction: The 20 Newsgroups data set is a collection of approximately 20,000 newsgroup documents, partitioned (nearly) evenly across 20 different newsgroups. To the best of my knowledge, it was originally collected by Ken Lang, probably for his Newsweeder: Learning to filter netnews paper, though he does not explicitly mention this collection. The 20 newsgroups collection has become a popular data set for experiments in text applications of machine learning techniques, such as text classification and text clustering. This dataset loader will download the recommended "by date" variant of the dataset and which features a point in time split between the train and test sets. The compressed dataset size is around 14 Mb compressed. Once uncompressed the train set is 52 MB and the test set is 34 MB. The data is downloaded, extracted and cached in the '~/scikit_learn_data' folder. The `fetch_20newsgroups` function will not vectorize the data into numpy arrays but the dataset lists the filenames of the posts and their categories as target labels. The `fetch_20newsgroups_vectorized` function will in addition do a simple tf-idf vectorization step. """ # Copyright (c) 2011 Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause import os import logging import tarfile import pickle import shutil import re import codecs import numpy as np import scipy.sparse as sp from .base import get_data_home from .base import Bunch from .base import load_files from .base import _pkl_filepath from ..utils import check_random_state from ..feature_extraction.text import CountVectorizer from ..preprocessing import normalize from ..externals import joblib, six if six.PY3: from urllib.request import urlopen else: from urllib2 import urlopen logger = logging.getLogger(__name__) URL = ("http://people.csail.mit.edu/jrennie/" "20Newsgroups/20news-bydate.tar.gz") ARCHIVE_NAME = "20news-bydate.tar.gz" CACHE_NAME = "20news-bydate.pkz" TRAIN_FOLDER = "20news-bydate-train" TEST_FOLDER = "20news-bydate-test" def download_20newsgroups(target_dir, cache_path): """Download the 20 newsgroups data and stored it as a zipped pickle.""" archive_path = os.path.join(target_dir, ARCHIVE_NAME) train_path = os.path.join(target_dir, TRAIN_FOLDER) test_path = os.path.join(target_dir, TEST_FOLDER) if not os.path.exists(target_dir): os.makedirs(target_dir) if os.path.exists(archive_path): # Download is not complete as the .tar.gz file is removed after # download. logger.warning("Download was incomplete, downloading again.") os.remove(archive_path) logger.warning("Downloading dataset from %s (14 MB)", URL) opener = urlopen(URL) with open(archive_path, 'wb') as f: f.write(opener.read()) logger.info("Decompressing %s", archive_path) tarfile.open(archive_path, "r:gz").extractall(path=target_dir) os.remove(archive_path) # Store a zipped pickle cache = dict(train=load_files(train_path, encoding='latin1'), test=load_files(test_path, encoding='latin1')) compressed_content = codecs.encode(pickle.dumps(cache), 'zlib_codec') with open(cache_path, 'wb') as f: f.write(compressed_content) shutil.rmtree(target_dir) return cache def strip_newsgroup_header(text): """ Given text in "news" format, strip the headers, by removing everything before the first blank line. """ _before, _blankline, after = text.partition('\n\n') return after _QUOTE_RE = re.compile(r'(writes in|writes:|wrote:|says:|said:' r'|^In article|^Quoted from|^\||^>)') def strip_newsgroup_quoting(text): """ Given text in "news" format, strip lines beginning with the quote characters > or |, plus lines that often introduce a quoted section (for example, because they contain the string 'writes:'.) """ good_lines = [line for line in text.split('\n') if not _QUOTE_RE.search(line)] return '\n'.join(good_lines) def strip_newsgroup_footer(text): """ Given text in "news" format, attempt to remove a signature block. As a rough heuristic, we assume that signatures are set apart by either a blank line or a line made of hyphens, and that it is the last such line in the file (disregarding blank lines at the end). """ lines = text.strip().split('\n') for line_num in range(len(lines) - 1, -1, -1): line = lines[line_num] if line.strip().strip('-') == '': break if line_num > 0: return '\n'.join(lines[:line_num]) else: return text def fetch_20newsgroups(data_home=None, subset='train', categories=None, shuffle=True, random_state=42, remove=(), download_if_missing=True): """Load the filenames and data from the 20 newsgroups dataset. Read more in the :ref:`User Guide <20newsgroups>`. Parameters ---------- subset: 'train' or 'test', 'all', optional Select the dataset to load: 'train' for the training set, 'test' for the test set, 'all' for both, with shuffled ordering. data_home: optional, default: None Specify a download and cache folder for the datasets. If None, all scikit-learn data is stored in '~/scikit_learn_data' subfolders. categories: None or collection of string or unicode If None (default), load all the categories. If not None, list of category names to load (other categories ignored). shuffle: bool, optional Whether or not to shuffle the data: might be important for models that make the assumption that the samples are independent and identically distributed (i.i.d.), such as stochastic gradient descent. random_state: numpy random number generator or seed integer Used to shuffle the dataset. download_if_missing: optional, True by default If False, raise an IOError if the data is not locally available instead of trying to download the data from the source site. remove: tuple May contain any subset of ('headers', 'footers', 'quotes'). Each of these are kinds of text that will be detected and removed from the newsgroup posts, preventing classifiers from overfitting on metadata. 'headers' removes newsgroup headers, 'footers' removes blocks at the ends of posts that look like signatures, and 'quotes' removes lines that appear to be quoting another post. 'headers' follows an exact standard; the other filters are not always correct. """ data_home = get_data_home(data_home=data_home) cache_path = _pkl_filepath(data_home, CACHE_NAME) twenty_home = os.path.join(data_home, "20news_home") cache = None if os.path.exists(cache_path): try: with open(cache_path, 'rb') as f: compressed_content = f.read() uncompressed_content = codecs.decode( compressed_content, 'zlib_codec') cache = pickle.loads(uncompressed_content) except Exception as e: print(80 * '_') print('Cache loading failed') print(80 * '_') print(e) if cache is None: if download_if_missing: cache = download_20newsgroups(target_dir=twenty_home, cache_path=cache_path) else: raise IOError('20Newsgroups dataset not found') if subset in ('train', 'test'): data = cache[subset] elif subset == 'all': data_lst = list() target = list() filenames = list() for subset in ('train', 'test'): data = cache[subset] data_lst.extend(data.data) target.extend(data.target) filenames.extend(data.filenames) data.data = data_lst data.target = np.array(target) data.filenames = np.array(filenames) else: raise ValueError( "subset can only be 'train', 'test' or 'all', got '%s'" % subset) data.description = 'the 20 newsgroups by date dataset' if 'headers' in remove: data.data = [strip_newsgroup_header(text) for text in data.data] if 'footers' in remove: data.data = [strip_newsgroup_footer(text) for text in data.data] if 'quotes' in remove: data.data = [strip_newsgroup_quoting(text) for text in data.data] if categories is not None: labels = [(data.target_names.index(cat), cat) for cat in categories] # Sort the categories to have the ordering of the labels labels.sort() labels, categories = zip(*labels) mask = np.in1d(data.target, labels) data.filenames = data.filenames[mask] data.target = data.target[mask] # searchsorted to have continuous labels data.target = np.searchsorted(labels, data.target) data.target_names = list(categories) # Use an object array to shuffle: avoids memory copy data_lst = np.array(data.data, dtype=object) data_lst = data_lst[mask] data.data = data_lst.tolist() if shuffle: random_state = check_random_state(random_state) indices = np.arange(data.target.shape[0]) random_state.shuffle(indices) data.filenames = data.filenames[indices] data.target = data.target[indices] # Use an object array to shuffle: avoids memory copy data_lst = np.array(data.data, dtype=object) data_lst = data_lst[indices] data.data = data_lst.tolist() return data def fetch_20newsgroups_vectorized(subset="train", remove=(), data_home=None): """Load the 20 newsgroups dataset and transform it into tf-idf vectors. This is a convenience function; the tf-idf transformation is done using the default settings for `sklearn.feature_extraction.text.Vectorizer`. For more advanced usage (stopword filtering, n-gram extraction, etc.), combine fetch_20newsgroups with a custom `Vectorizer` or `CountVectorizer`. Read more in the :ref:`User Guide <20newsgroups>`. Parameters ---------- subset: 'train' or 'test', 'all', optional Select the dataset to load: 'train' for the training set, 'test' for the test set, 'all' for both, with shuffled ordering. data_home: optional, default: None Specify an download and cache folder for the datasets. If None, all scikit-learn data is stored in '~/scikit_learn_data' subfolders. remove: tuple May contain any subset of ('headers', 'footers', 'quotes'). Each of these are kinds of text that will be detected and removed from the newsgroup posts, preventing classifiers from overfitting on metadata. 'headers' removes newsgroup headers, 'footers' removes blocks at the ends of posts that look like signatures, and 'quotes' removes lines that appear to be quoting another post. Returns ------- bunch : Bunch object bunch.data: sparse matrix, shape [n_samples, n_features] bunch.target: array, shape [n_samples] bunch.target_names: list, length [n_classes] """ data_home = get_data_home(data_home=data_home) filebase = '20newsgroup_vectorized' if remove: filebase += 'remove-' + ('-'.join(remove)) target_file = _pkl_filepath(data_home, filebase + ".pkl") # we shuffle but use a fixed seed for the memoization data_train = fetch_20newsgroups(data_home=data_home, subset='train', categories=None, shuffle=True, random_state=12, remove=remove) data_test = fetch_20newsgroups(data_home=data_home, subset='test', categories=None, shuffle=True, random_state=12, remove=remove) if os.path.exists(target_file): X_train, X_test = joblib.load(target_file) else: vectorizer = CountVectorizer(dtype=np.int16) X_train = vectorizer.fit_transform(data_train.data).tocsr() X_test = vectorizer.transform(data_test.data).tocsr() joblib.dump((X_train, X_test), target_file, compress=9) # the data is stored as int16 for compactness # but normalize needs floats X_train = X_train.astype(np.float64) X_test = X_test.astype(np.float64) normalize(X_train, copy=False) normalize(X_test, copy=False) target_names = data_train.target_names if subset == "train": data = X_train target = data_train.target elif subset == "test": data = X_test target = data_test.target elif subset == "all": data = sp.vstack((X_train, X_test)).tocsr() target = np.concatenate((data_train.target, data_test.target)) else: raise ValueError("%r is not a valid subset: should be one of " "['train', 'test', 'all']" % subset) return Bunch(data=data, target=target, target_names=target_names)
bsd-3-clause
sniemi/SamPy
sandbox/src1/examples/rc_traits.py
1
5746
# Here is some example code showing how to define some representative # rc properties and construct a matplotlib artist using traits. # Because matplotlib ships with enthought traits already, you can run # this script with just matplotlib. Unfortunately, we do not ship the # ex UI component so you can't test that part. I'm a bit of a traits # newbie so there are probably better ways to do what I have done # below. import sys, os, re import enthought.traits.api as traits from matplotlib.cbook import is_string_like from matplotlib.artist import Artist doprint = True flexible_true_trait = traits.Trait( True, { 'true': True, 't': True, 'yes': True, 'y': True, 'on': True, True: True, 'false': False, 'f': False, 'no': False, 'n': False, 'off': False, False: False } ) flexible_false_trait = traits.Trait( False, flexible_true_trait ) colors = { 'c' : '#00bfbf', 'b' : '#0000ff', 'g' : '#008000', 'k' : '#000000', 'm' : '#bf00bf', 'r' : '#ff0000', 'w' : '#ffffff', 'y' : '#bfbf00', 'gold' : '#FFD700', 'peachpuff' : '#FFDAB9', 'navajowhite' : '#FFDEAD', } def hex2color(s): "Convert hex string (like html uses, eg, #efefef) to a r,g,b tuple" return tuple([int(n, 16)/255.0 for n in (s[1:3], s[3:5], s[5:7])]) class RGBA(traits.HasTraits): # r,g,b,a in the range 0-1 with default color 0,0,0,1 (black) r = traits.Range(0., 1., 0.) g = traits.Range(0., 1., 0.) b = traits.Range(0., 1., 0.) a = traits.Range(0., 1., 1.) def __init__(self, r=0., g=0., b=0., a=1.): self.r = r self.g = g self.b = b self.a = a def __repr__(self): return 'r,g,b,a = (%1.2f, %1.2f, %1.2f, %1.2f)'%\ (self.r, self.g, self.b, self.a) def tuple_to_rgba(ob, name, val): tup = [float(x) for x in val] if len(tup)==3: r,g,b = tup return RGBA(r,g,b) elif len(tup)==4: r,g,b,a = tup return RGBA(r,g,b,a) else: raise ValueError tuple_to_rgba.info = 'a RGB or RGBA tuple of floats' def hex_to_rgba(ob, name, val): rgx = re.compile('^#[0-9A-Fa-f]{6}$') if not is_string_like(val): raise TypeError if rgx.match(val) is None: raise ValueError r,g,b = hex2color(val) return RGBA(r,g,b,1.0) hex_to_rgba.info = 'a hex color string' def colorname_to_rgba(ob, name, val): hex = colors[val.lower()] r,g,b = hex2color(hex) return RGBA(r,g,b,1.0) colorname_to_rgba.info = 'a named color' def float_to_rgba(ob, name, val): val = float(val) return RGBA(val, val, val, 1.) float_to_rgba.info = 'a grayscale intensity' Color = traits.Trait(RGBA(), float_to_rgba, colorname_to_rgba, RGBA, hex_to_rgba, tuple_to_rgba) def file_exists(ob, name, val): fh = file(val, 'r') return val def path_exists(ob, name, val): os.path.exists(val) linestyles = ('-', '--', '-.', ':', 'steps', 'None') TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN = range(4) linemarkers = (None, '.', ',', 'o', '^', 'v', '<', '>', 's', '+', 'x', 'd', 'D', '|', '_', 'h', 'H', 'p', '1', '2', '3', '4', TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN, 'None' ) class LineRC(traits.HasTraits): linewidth = traits.Float(0.5) linestyle = traits.Trait(*linestyles) color = Color marker = traits.Trait(*linemarkers) markerfacecolor = Color markeredgecolor = Color markeredgewidth = traits.Float(0.5) markersize = traits.Float(6) antialiased = flexible_true_trait data_clipping = flexible_false_trait class PatchRC(traits.HasTraits): linewidth = traits.Float(1.0) facecolor = Color edgecolor = Color antialiased = flexible_true_trait timezones = 'UTC', 'US/Central', 'ES/Eastern' # fixme: and many more backends = ('GTKAgg', 'Cairo', 'FltkAgg', 'GDK', 'GTK', 'Agg', 'GTKCairo', 'PS', 'SVG', 'Template', 'TkAgg', 'WX') class RC(traits.HasTraits): backend = traits.Trait(*backends) numerix = traits.Trait('Numeric', 'numarray') interactive = flexible_false_trait toolbar = traits.Trait('toolbar2', 'classic', None) timezone = traits.Trait(*timezones) lines = traits.Trait(LineRC()) patch = traits.Trait(PatchRC()) rc = RC() rc.lines.color = 'r' if doprint: print 'RC' rc.print_traits() print 'RC lines' rc.lines.print_traits() print 'RC patches' rc.patch.print_traits() class Patch(Artist, traits.HasTraits): linewidth = traits.Float(0.5) facecolor = Color fc = facecolor edgecolor = Color fill = flexible_true_trait def __init__(self, edgecolor=None, facecolor=None, linewidth=None, antialiased = None, fill=1, **kwargs ): Artist.__init__(self) if edgecolor is None: edgecolor = rc.patch.edgecolor if facecolor is None: facecolor = rc.patch.facecolor if linewidth is None: linewidth = rc.patch.linewidth if antialiased is None: antialiased = rc.patch.antialiased self.edgecolor = edgecolor self.facecolor = facecolor self.linewidth = linewidth self.antialiased = antialiased self.fill = fill p = Patch() p.facecolor = '#bfbf00' p.edgecolor = 'gold' p.facecolor = (1,.5,.5,.25) p.facecolor = 0.25 p.fill = 'f' print 'p.facecolor', type(p.facecolor), p.facecolor print 'p.fill', type(p.fill), p.fill if p.fill_: print 'fill' else: print 'no fill' if doprint: print print 'Patch' p.print_traits()
bsd-2-clause
MartinPyka/Pam-Utils
pamutils/nest_help.py
1
3082
""" Created on Wed Aug 20 17:06:00 2014 This is just a helping unit to collect all functions that I need to analyse NEST-networks @author: Martin Pyka """ import nest import io import csv from matplotlib import pyplot import numpy as np def getEventsFromSpikeDetector(spike_detector, t_range=[0, float("inf")]): """ Returns senders and times data from a spike-detector. This is for example helpful if you want to write your own plotter for the spikes or analyse those data further """ status = nest.GetStatus(spike_detector) times = status[0]['events']['times'] sender = status[0]['events']['senders'][(times >= t_range[0]) & (times < t_range[1])] times = times[(times >= t_range[0]) & (times < t_range[1])] return sender, times def scatter(spike_detector, area=3): sender, times = getEventsFromSpikeDetector(spike_detector) pyplot.scatter(times, sender, s=area ) def getPOA(ng, sd, interval=[0, float("inf")]): """ returns the percentage of neurons for a given neuron group that were active for a given time frame ng neurongroup which was observed by the spike detector sd spike detector interval start and end of the interval for which the percentage should be determined """ # get sender and time points sender, times = getEventsFromSpikeDetector(sd) # get number of active unique neurons for this particular time interval n_a = len(np.unique(sender[(times >= interval[0]) & (times < interval[1])])) return float(n_a) / float(len(ng)) def getPrePostNgs(m, ngs, c): ''' Returns pre- and post-neurongroup for a given connection index ''' pre_ngs = ngs[m['connections'][0][c][1]] post_ngs = ngs[m['connections'][0][c][2]] return pre_ngs, post_ngs def getConnInfo(m, ngs, c, info): ''' returns the weights as they are returned by GetConnections for a given connection-index c ''' pre_ngs, post_ngs = getPrePostNgs(m, ngs, c) connections = nest.GetConnections(pre_ngs, post_ngs) result = nest.GetStatus(connections, info) return result def exportSpikeDetectorData(filename, ngs, sd_list): """ Exports data from a list of spike detector ids into a given file in CSV-format """ sender = np.array((), dtype=int) times = np.array(()) indices = np.array((), dtype = int) for index, sd in enumerate(sd_list): s, t = getEventsFromSpikeDetector(sd) i = np.ones(len(s), dtype=int) * index sender = np.concatenate((sender, s)) times = np.concatenate((times, t)) indices = np.concatenate((indices, i)) f = open(filename + '.csv', 'w') writer = csv.writer( f, delimiter=";", quoting=csv.QUOTE_NONNUMERIC ) # compute permutation for sorting of times perm = sorted(range(len(times)), key=lambda k: times[k]) for i in perm: writer.writerow([sender[i] - ngs[indices[i]][0], indices[i], times[i]]) f.close()
gpl-2.0
mwillsey/crossbot
crossbot/commands/plot_wins.py
1
5358
import datetime import sqlite3 import statistics import numpy as np import html, re from collections import defaultdict, namedtuple from itertools import cycle, groupby, count from tempfile import NamedTemporaryFile # don't use matplotlib gui import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.dates as mdates import crossbot from crossbot.parser import date_fmt # TODO: why the hell is this here again??? def init(client): parser = client.parser.subparsers.add_parser('plot-wins', help='plot wins') parser.set_defaults( command=plot_wins, alpha=0.7, num_days=7, ) appearance = parser.add_argument_group('Plot appearance') appearance.add_argument( '--alpha', type=float, help='Transparency for plotted points.' ' Default %(default)s.' ) dates = parser.add_argument_group('Date range') def date_none(date_str): return crossbot.date(date_str, default=None) dates.add_argument( '--start-date', type=date_none, metavar='START', help='Date to start plotting from.' ) dates.add_argument( '--end-date', type=date_none, metavar='END', help='Date to end plotting at. Defaults to today.' ) dates.add_argument( '-n', '--num-days', type=int, metavar='N', help='Number of days since today to plot.' ' Ignored if both start-date and end-date given.' ' Default %(default)s.' ) parser.add_argument('users', nargs='+', help='Slack names of player') # a nice way to convert db entries into objects Entry = namedtuple('Entry', ['userid', 'date', 'seconds', 'timestamp']) def plot_wins(client, request): '''Plot wins example: cb plot-wins @mwillsey @doug -n 500 ''' args = request.args start_date = args.start_date end_date = args.end_date delta = datetime.timedelta(days=args.num_days) # if we have both dates, use them and correct num days # if we have one, use that and num_days # otherwise, end_date is today and use num_days if start_date: start_dt = date_dt(start_date) if end_date: end_dt = date_dt(end_date) args.num_days = (end_dt - start_dt).days else: end_dt = start_dt + delta else: end_dt = date_dt(end_date if end_date else crossbot.date('now')) start_dt = end_dt - delta # reformat the dates based on the above dt calculations start_date = start_dt.strftime(date_fmt) end_date = end_dt.strftime(date_fmt) if len(args.users) < 2: request.reply('I need 2 or more users', direct=True) return # get the users def replace_with_id(match): return match.group(1) userids = [] for u in args.users: s = html.unescape(u) uid = re.sub(r'<@(\w+)>', replace_with_id, s) # check user id client.user(uid) userids.append(uid) dt_range = [ start_dt + datetime.timedelta(days=i) for i in range(args.num_days + 1) ] date_range = [dt.strftime(date_fmt) for dt in dt_range] with sqlite3.connect(crossbot.db_path) as con: query = ''' SELECT userid, date, seconds, timestamp FROM {} WHERE '''.format(args.table) query += ' OR '.join('userid = "{}"'.format(u) for u in userids) cur = con.execute(query) entries = [Entry._make(tup) for tup in cur] # sort by timestamp if present, else date entries.sort(key=lambda e: e.timestamp or e.date) wins = {u: 0 for u in userids} points = [] def add_point(dt): points.append((dt, dict(wins))) by_date = defaultdict(dict) for e in entries: if e.timestamp: ts = datetime.datetime.strptime( e.timestamp, '%Y-%m-%d %H:%M:%S.%f' ) else: ts = datetime.datetime.strptime(e.date, '%Y-%m-%d') this_date = by_date[e.date] assert e.userid not in this_date this_date[e.userid] = e.seconds if len(this_date) != len(userids): add_point(ts) continue times = [t for t in this_date.values() if t != -1] if not times: # everyone failed, skip add_point(ts) continue best_time = min(times) winners = [u for u in userids if this_date[u] == best_time] for w in winners: wins[w] += 1 add_point(ts) width, height, dpi = (120 * args.num_days), 600, 100 width = max(400, min(width, 1000)) fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) ax = fig.add_subplot(1, 1, 1) x, ys = zip( *((dt, wins) for dt, wins in points if start_dt <= dt.date() and dt.date() <= end_dt) ) for u in userids: name = client.user(u) ax.plot_date( mdates.date2num(x), [y[u] for y in ys], linestyle='-', marker=None, label=name ) ax.legend(fontsize=6, loc='upper left') temp = NamedTemporaryFile(suffix='.pdf', delete=False) fig.savefig(temp, format='pdf', bbox_inches='tight') temp.close() plt.close(fig) request.upload('plot', temp.name)
gpl-3.0
equialgo/scikit-learn
sklearn/mixture/tests/test_dpgmm.py
84
7866
# Important note for the deprecation cleaning of 0.20 : # All the function and classes of this file have been deprecated in 0.18. # When you remove this file please also remove the related files # - 'sklearn/mixture/dpgmm.py' # - 'sklearn/mixture/gmm.py' # - 'sklearn/mixture/test_gmm.py' import unittest import sys import numpy as np from sklearn.mixture import DPGMM, VBGMM from sklearn.mixture.dpgmm import log_normalize from sklearn.datasets import make_blobs from sklearn.utils.testing import assert_array_less, assert_equal from sklearn.utils.testing import assert_warns_message, ignore_warnings from sklearn.mixture.tests.test_gmm import GMMTester from sklearn.externals.six.moves import cStringIO as StringIO from sklearn.mixture.dpgmm import digamma, gammaln from sklearn.mixture.dpgmm import wishart_log_det, wishart_logz np.seterr(all='warn') @ignore_warnings(category=DeprecationWarning) def test_class_weights(): # check that the class weights are updated # simple 3 cluster dataset X, y = make_blobs(random_state=1) for Model in [DPGMM, VBGMM]: dpgmm = Model(n_components=10, random_state=1, alpha=20, n_iter=50) dpgmm.fit(X) # get indices of components that are used: indices = np.unique(dpgmm.predict(X)) active = np.zeros(10, dtype=np.bool) active[indices] = True # used components are important assert_array_less(.1, dpgmm.weights_[active]) # others are not assert_array_less(dpgmm.weights_[~active], .05) @ignore_warnings(category=DeprecationWarning) def test_verbose_boolean(): # checks that the output for the verbose output is the same # for the flag values '1' and 'True' # simple 3 cluster dataset X, y = make_blobs(random_state=1) for Model in [DPGMM, VBGMM]: dpgmm_bool = Model(n_components=10, random_state=1, alpha=20, n_iter=50, verbose=True) dpgmm_int = Model(n_components=10, random_state=1, alpha=20, n_iter=50, verbose=1) old_stdout = sys.stdout sys.stdout = StringIO() try: # generate output with the boolean flag dpgmm_bool.fit(X) verbose_output = sys.stdout verbose_output.seek(0) bool_output = verbose_output.readline() # generate output with the int flag dpgmm_int.fit(X) verbose_output = sys.stdout verbose_output.seek(0) int_output = verbose_output.readline() assert_equal(bool_output, int_output) finally: sys.stdout = old_stdout @ignore_warnings(category=DeprecationWarning) def test_verbose_first_level(): # simple 3 cluster dataset X, y = make_blobs(random_state=1) for Model in [DPGMM, VBGMM]: dpgmm = Model(n_components=10, random_state=1, alpha=20, n_iter=50, verbose=1) old_stdout = sys.stdout sys.stdout = StringIO() try: dpgmm.fit(X) finally: sys.stdout = old_stdout @ignore_warnings(category=DeprecationWarning) def test_verbose_second_level(): # simple 3 cluster dataset X, y = make_blobs(random_state=1) for Model in [DPGMM, VBGMM]: dpgmm = Model(n_components=10, random_state=1, alpha=20, n_iter=50, verbose=2) old_stdout = sys.stdout sys.stdout = StringIO() try: dpgmm.fit(X) finally: sys.stdout = old_stdout @ignore_warnings(category=DeprecationWarning) def test_digamma(): assert_warns_message(DeprecationWarning, "The function digamma is" " deprecated in 0.18 and will be removed in 0.20. " "Use scipy.special.digamma instead.", digamma, 3) @ignore_warnings(category=DeprecationWarning) def test_gammaln(): assert_warns_message(DeprecationWarning, "The function gammaln" " is deprecated in 0.18 and will be removed" " in 0.20. Use scipy.special.gammaln instead.", gammaln, 3) @ignore_warnings(category=DeprecationWarning) def test_log_normalize(): v = np.array([0.1, 0.8, 0.01, 0.09]) a = np.log(2 * v) result = assert_warns_message(DeprecationWarning, "The function " "log_normalize is deprecated in 0.18 and" " will be removed in 0.20.", log_normalize, a) assert np.allclose(v, result, rtol=0.01) @ignore_warnings(category=DeprecationWarning) def test_wishart_log_det(): a = np.array([0.1, 0.8, 0.01, 0.09]) b = np.array([0.2, 0.7, 0.05, 0.1]) assert_warns_message(DeprecationWarning, "The function " "wishart_log_det is deprecated in 0.18 and" " will be removed in 0.20.", wishart_log_det, a, b, 2, 4) @ignore_warnings(category=DeprecationWarning) def test_wishart_logz(): assert_warns_message(DeprecationWarning, "The function " "wishart_logz is deprecated in 0.18 and " "will be removed in 0.20.", wishart_logz, 3, np.identity(3), 1, 3) @ignore_warnings(category=DeprecationWarning) def test_DPGMM_deprecation(): assert_warns_message( DeprecationWarning, "The `DPGMM` class is not working correctly and " "it's better to use `sklearn.mixture.BayesianGaussianMixture` class " "with parameter `weight_concentration_prior_type='dirichlet_process'` " "instead. DPGMM is deprecated in 0.18 and will be removed in 0.20.", DPGMM) def do_model(self, **kwds): return VBGMM(verbose=False, **kwds) class DPGMMTester(GMMTester): model = DPGMM do_test_eval = False def score(self, g, train_obs): _, z = g.score_samples(train_obs) return g.lower_bound(train_obs, z) class TestDPGMMWithSphericalCovars(unittest.TestCase, DPGMMTester): covariance_type = 'spherical' setUp = GMMTester._setUp class TestDPGMMWithDiagCovars(unittest.TestCase, DPGMMTester): covariance_type = 'diag' setUp = GMMTester._setUp class TestDPGMMWithTiedCovars(unittest.TestCase, DPGMMTester): covariance_type = 'tied' setUp = GMMTester._setUp class TestDPGMMWithFullCovars(unittest.TestCase, DPGMMTester): covariance_type = 'full' setUp = GMMTester._setUp def test_VBGMM_deprecation(): assert_warns_message( DeprecationWarning, "The `VBGMM` class is not working correctly and " "it's better to use `sklearn.mixture.BayesianGaussianMixture` class " "with parameter `weight_concentration_prior_type=" "'dirichlet_distribution'` instead. VBGMM is deprecated " "in 0.18 and will be removed in 0.20.", VBGMM) class VBGMMTester(GMMTester): model = do_model do_test_eval = False def score(self, g, train_obs): _, z = g.score_samples(train_obs) return g.lower_bound(train_obs, z) class TestVBGMMWithSphericalCovars(unittest.TestCase, VBGMMTester): covariance_type = 'spherical' setUp = GMMTester._setUp class TestVBGMMWithDiagCovars(unittest.TestCase, VBGMMTester): covariance_type = 'diag' setUp = GMMTester._setUp class TestVBGMMWithTiedCovars(unittest.TestCase, VBGMMTester): covariance_type = 'tied' setUp = GMMTester._setUp class TestVBGMMWithFullCovars(unittest.TestCase, VBGMMTester): covariance_type = 'full' setUp = GMMTester._setUp def test_vbgmm_no_modify_alpha(): alpha = 2. n_components = 3 X, y = make_blobs(random_state=1) vbgmm = VBGMM(n_components=n_components, alpha=alpha, n_iter=1) assert_equal(vbgmm.alpha, alpha) assert_equal(vbgmm.fit(X).alpha_, float(alpha) / n_components)
bsd-3-clause
datapythonista/pandas
pandas/tests/groupby/test_groupby_subclass.py
4
2682
from datetime import datetime import numpy as np import pytest from pandas import ( DataFrame, Series, ) import pandas._testing as tm @pytest.mark.parametrize( "obj", [ tm.SubclassedDataFrame({"A": np.arange(0, 10)}), tm.SubclassedSeries(np.arange(0, 10), name="A"), ], ) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_groupby_preserves_subclass(obj, groupby_func): # GH28330 -- preserve subclass through groupby operations if isinstance(obj, Series) and groupby_func in {"corrwith"}: pytest.skip("Not applicable") grouped = obj.groupby(np.arange(0, 10)) # Groups should preserve subclass type assert isinstance(grouped.get_group(0), type(obj)) args = [] if groupby_func in {"fillna", "nth"}: args.append(0) elif groupby_func == "corrwith": args.append(obj) elif groupby_func == "tshift": args.extend([0, 0]) result1 = getattr(grouped, groupby_func)(*args) result2 = grouped.agg(groupby_func, *args) # Reduction or transformation kernels should preserve type slices = {"ngroup", "cumcount", "size"} if isinstance(obj, DataFrame) and groupby_func in slices: assert isinstance(result1, obj._constructor_sliced) else: assert isinstance(result1, type(obj)) # Confirm .agg() groupby operations return same results if isinstance(result1, DataFrame): tm.assert_frame_equal(result1, result2) else: tm.assert_series_equal(result1, result2) def test_groupby_preserves_metadata(): # GH-37343 custom_df = tm.SubclassedDataFrame({"a": [1, 2, 3], "b": [1, 1, 2], "c": [7, 8, 9]}) assert "testattr" in custom_df._metadata custom_df.testattr = "hello" for _, group_df in custom_df.groupby("c"): assert group_df.testattr == "hello" @pytest.mark.parametrize("obj", [DataFrame, tm.SubclassedDataFrame]) def test_groupby_resample_preserves_subclass(obj): # GH28330 -- preserve subclass through groupby.resample() df = obj( { "Buyer": "Carl Carl Carl Carl Joe Carl".split(), "Quantity": [18, 3, 5, 1, 9, 3], "Date": [ datetime(2013, 9, 1, 13, 0), datetime(2013, 9, 1, 13, 5), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 3, 10, 0), datetime(2013, 12, 2, 12, 0), datetime(2013, 9, 2, 14, 0), ], } ) df = df.set_index("Date") # Confirm groupby.resample() preserves dataframe type result = df.groupby("Buyer").resample("5D").sum() assert isinstance(result, obj)
bsd-3-clause
kambysese/mne-python
mne/decoding/base.py
4
19234
"""Base class copy from sklearn.base.""" # Authors: Gael Varoquaux <gael.varoquaux@normalesup.org> # Romain Trachel <trachelr@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD (3-clause) import numpy as np import time import numbers from ..parallel import parallel_func from ..fixes import BaseEstimator, is_classifier, _get_check_scoring from ..utils import logger, warn, fill_doc class LinearModel(BaseEstimator): """Compute and store patterns from linear models. The linear model coefficients (filters) are used to extract discriminant neural sources from the measured data. This class computes the corresponding patterns of these linear filters to make them more interpretable :footcite:`HaufeEtAl2014`. Parameters ---------- model : object | None A linear model from scikit-learn with a fit method that updates a ``coef_`` attribute. If None the model will be LogisticRegression. Attributes ---------- filters_ : ndarray, shape ([n_targets], n_features) If fit, the filters used to decompose the data. patterns_ : ndarray, shape ([n_targets], n_features) If fit, the patterns used to restore M/EEG signals. See Also -------- CSP mne.preprocessing.ICA mne.preprocessing.Xdawn Notes ----- .. versionadded:: 0.10 References ---------- .. footbibliography:: """ def __init__(self, model=None): # noqa: D102 if model is None: from sklearn.linear_model import LogisticRegression model = LogisticRegression(solver='liblinear') self.model = model self._estimator_type = getattr(model, "_estimator_type", None) def fit(self, X, y, **fit_params): """Estimate the coefficients of the linear model. Save the coefficients in the attribute ``filters_`` and computes the attribute ``patterns_``. Parameters ---------- X : array, shape (n_samples, n_features) The training input samples to estimate the linear coefficients. y : array, shape (n_samples, [n_targets]) The target values. **fit_params : dict of string -> object Parameters to pass to the fit method of the estimator. Returns ------- self : instance of LinearModel Returns the modified instance. """ X, y = np.asarray(X), np.asarray(y) if X.ndim != 2: raise ValueError('LinearModel only accepts 2-dimensional X, got ' '%s instead.' % (X.shape,)) if y.ndim > 2: raise ValueError('LinearModel only accepts up to 2-dimensional y, ' 'got %s instead.' % (y.shape,)) # fit the Model self.model.fit(X, y, **fit_params) # Computes patterns using Haufe's trick: A = Cov_X . W . Precision_Y inv_Y = 1. X = X - X.mean(0, keepdims=True) if y.ndim == 2 and y.shape[1] != 1: y = y - y.mean(0, keepdims=True) inv_Y = np.linalg.pinv(np.cov(y.T)) self.patterns_ = np.cov(X.T).dot(self.filters_.T.dot(inv_Y)).T return self @property def filters_(self): if hasattr(self.model, 'coef_'): # Standard Linear Model filters = self.model.coef_ elif hasattr(self.model.best_estimator_, 'coef_'): # Linear Model with GridSearchCV filters = self.model.best_estimator_.coef_ else: raise ValueError('model does not have a `coef_` attribute.') if filters.ndim == 2 and filters.shape[0] == 1: filters = filters[0] return filters def transform(self, X): """Transform the data using the linear model. Parameters ---------- X : array, shape (n_samples, n_features) The data to transform. Returns ------- y_pred : array, shape (n_samples,) The predicted targets. """ return self.model.transform(X) def fit_transform(self, X, y): """Fit the data and transform it using the linear model. Parameters ---------- X : array, shape (n_samples, n_features) The training input samples to estimate the linear coefficients. y : array, shape (n_samples,) The target values. Returns ------- y_pred : array, shape (n_samples,) The predicted targets. """ return self.fit(X, y).transform(X) def predict(self, X): """Compute predictions of y from X. Parameters ---------- X : array, shape (n_samples, n_features) The data used to compute the predictions. Returns ------- y_pred : array, shape (n_samples,) The predictions. """ return self.model.predict(X) def predict_proba(self, X): """Compute probabilistic predictions of y from X. Parameters ---------- X : array, shape (n_samples, n_features) The data used to compute the predictions. Returns ------- y_pred : array, shape (n_samples, n_classes) The probabilities. """ return self.model.predict_proba(X) def decision_function(self, X): """Compute distance from the decision function of y from X. Parameters ---------- X : array, shape (n_samples, n_features) The data used to compute the predictions. Returns ------- y_pred : array, shape (n_samples, n_classes) The distances. """ return self.model.decision_function(X) def score(self, X, y): """Score the linear model computed on the given test data. Parameters ---------- X : array, shape (n_samples, n_features) The data to transform. y : array, shape (n_samples,) The target values. Returns ------- score : float Score of the linear model. """ return self.model.score(X, y) def _set_cv(cv, estimator=None, X=None, y=None): """Set the default CV depending on whether clf is classifier/regressor.""" # Detect whether classification or regression if estimator in ['classifier', 'regressor']: est_is_classifier = estimator == 'classifier' else: est_is_classifier = is_classifier(estimator) # Setup CV from sklearn import model_selection as models from sklearn.model_selection import (check_cv, StratifiedKFold, KFold) if isinstance(cv, (int, np.int64)): XFold = StratifiedKFold if est_is_classifier else KFold cv = XFold(n_splits=cv) elif isinstance(cv, str): if not hasattr(models, cv): raise ValueError('Unknown cross-validation') cv = getattr(models, cv) cv = cv() cv = check_cv(cv=cv, y=y, classifier=est_is_classifier) # Extract train and test set to retrieve them at predict time if hasattr(cv, 'split'): cv_splits = [(train, test) for train, test in cv.split(X=np.zeros_like(y), y=y)] else: # XXX support sklearn.cross_validation cv cv_splits = [(train, test) for train, test in cv] if not np.all([len(train) for train, _ in cv_splits]): raise ValueError('Some folds do not have any train epochs.') return cv, cv_splits def _check_estimator(estimator, get_params=True): """Check whether an object has the methods required by sklearn.""" valid_methods = ('predict', 'transform', 'predict_proba', 'decision_function') if ( (not hasattr(estimator, 'fit')) or (not any(hasattr(estimator, method) for method in valid_methods)) ): raise ValueError('estimator must be a scikit-learn transformer or ' 'an estimator with the fit and a predict-like (e.g. ' 'predict_proba) or a transform method.') if get_params and not hasattr(estimator, 'get_params'): raise ValueError('estimator must be a scikit-learn transformer or an ' 'estimator with the get_params method that allows ' 'cloning.') def _get_inverse_funcs(estimator, terminal=True): """Retrieve the inverse functions of an pipeline or an estimator.""" inverse_func = [False] if hasattr(estimator, 'steps'): # if pipeline, retrieve all steps by nesting inverse_func = list() for _, est in estimator.steps: inverse_func.extend(_get_inverse_funcs(est, terminal=False)) elif hasattr(estimator, 'inverse_transform'): # if not pipeline attempt to retrieve inverse function inverse_func = [estimator.inverse_transform] # If terminal node, check that that the last estimator is a classifier, # and remove it from the transformers. if terminal: last_is_estimator = inverse_func[-1] is False all_invertible = not(False in inverse_func[:-1]) if last_is_estimator and all_invertible: # keep all inverse transformation and remove last estimation inverse_func = inverse_func[:-1] else: inverse_func = list() return inverse_func def get_coef(estimator, attr='filters_', inverse_transform=False): """Retrieve the coefficients of an estimator ending with a Linear Model. This is typically useful to retrieve "spatial filters" or "spatial patterns" of decoding models :footcite:`HaufeEtAl2014`. Parameters ---------- estimator : object | None An estimator from scikit-learn. attr : str The name of the coefficient attribute to retrieve, typically ``'filters_'`` (default) or ``'patterns_'``. inverse_transform : bool If True, returns the coefficients after inverse transforming them with the transformer steps of the estimator. Returns ------- coef : array The coefficients. References ---------- .. footbibliography:: """ # Get the coefficients of the last estimator in case of nested pipeline est = estimator while hasattr(est, 'steps'): est = est.steps[-1][1] squeeze_first_dim = False # If SlidingEstimator, loop across estimators if hasattr(est, 'estimators_'): coef = list() for this_est in est.estimators_: coef.append(get_coef(this_est, attr, inverse_transform)) coef = np.transpose(coef) coef = coef[np.newaxis] # fake a sample dimension squeeze_first_dim = True elif not hasattr(est, attr): raise ValueError('This estimator does not have a %s attribute:\n%s' % (attr, est)) else: coef = getattr(est, attr) if coef.ndim == 1: coef = coef[np.newaxis] squeeze_first_dim = True # inverse pattern e.g. to get back physical units if inverse_transform: if not hasattr(estimator, 'steps') and not hasattr(est, 'estimators_'): raise ValueError('inverse_transform can only be applied onto ' 'pipeline estimators.') # The inverse_transform parameter will call this method on any # estimator contained in the pipeline, in reverse order. for inverse_func in _get_inverse_funcs(estimator)[::-1]: coef = inverse_func(coef) if squeeze_first_dim: coef = coef[0] return coef @fill_doc def cross_val_multiscore(estimator, X, y=None, groups=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): """Evaluate a score by cross-validation. Parameters ---------- estimator : instance of sklearn.base.BaseEstimator The object to use to fit the data. Must implement the 'fit' method. X : array-like, shape (n_samples, n_dimensional_features,) The data to fit. Can be, for example a list, or an array at least 2d. y : array-like, shape (n_samples, n_targets,) The target variable to try to predict in the case of supervised learning. groups : array-like, with shape (n_samples,) Group labels for the samples used while splitting the dataset into train/test set. scoring : str, callable | None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. Note that when using an estimator which inherently returns multidimensional output - in particular, SlidingEstimator or GeneralizingEstimator - you should set the scorer there, not here. cv : int, cross-validation generator | iterable Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross validation, - integer, to specify the number of folds in a ``(Stratified)KFold``, - An object to be used as a cross-validation generator. - An iterable yielding train, test splits. For integer/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`sklearn.model_selection.StratifiedKFold` is used. In all other cases, :class:`sklearn.model_selection.KFold` is used. %(n_jobs)s verbose : int, optional The verbosity level. fit_params : dict, optional Parameters to pass to the fit method of the estimator. pre_dispatch : int, or str, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' Returns ------- scores : array of float, shape (n_splits,) | shape (n_splits, n_scores) Array of scores of the estimator for each run of the cross validation. """ # This code is copied from sklearn from sklearn.base import clone from sklearn.utils import indexable from sklearn.model_selection._split import check_cv check_scoring = _get_check_scoring() X, y, groups = indexable(X, y, groups) cv = check_cv(cv, y, classifier=is_classifier(estimator)) cv_iter = list(cv.split(X, y, groups)) scorer = check_scoring(estimator, scoring=scoring) # We clone the estimator to make sure that all the folds are # independent, and that it is pickle-able. # Note: this parallelization is implemented using MNE Parallel parallel, p_func, n_jobs = parallel_func(_fit_and_score, n_jobs, pre_dispatch=pre_dispatch) scores = parallel(p_func(clone(estimator), X, y, scorer, train, test, 0, None, fit_params) for train, test in cv_iter) return np.array(scores)[:, 0, ...] # flatten over joblib output. def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score=False, return_parameters=False, return_n_test_samples=False, return_times=False, error_score='raise'): """Fit estimator and compute scores for a given dataset split.""" # This code is adapted from sklearn from ..fixes import _check_fit_params from sklearn.utils.metaestimators import _safe_split from sklearn.utils.validation import _num_samples if verbose > 1: if parameters is None: msg = '' else: msg = '%s' % (', '.join('%s=%s' % (k, v) for k, v in parameters.items())) print("[CV] %s %s" % (msg, (64 - len(msg)) * '.')) # Adjust length of sample weights fit_params = fit_params if fit_params is not None else {} fit_params = _check_fit_params(X, fit_params, train) if parameters is not None: estimator.set_params(**parameters) start_time = time.time() X_train, y_train = _safe_split(estimator, X, y, train) X_test, y_test = _safe_split(estimator, X, y, test, train) try: if y_train is None: estimator.fit(X_train, **fit_params) else: estimator.fit(X_train, y_train, **fit_params) except Exception as e: # Note fit time as time until error fit_time = time.time() - start_time score_time = 0.0 if error_score == 'raise': raise elif isinstance(error_score, numbers.Number): test_score = error_score if return_train_score: train_score = error_score warn("Classifier fit failed. The score on this train-test" " partition for these parameters will be set to %f. " "Details: \n%r" % (error_score, e)) else: raise ValueError("error_score must be the string 'raise' or a" " numeric value. (Hint: if using 'raise', please" " make sure that it has been spelled correctly.)") else: fit_time = time.time() - start_time test_score = _score(estimator, X_test, y_test, scorer) score_time = time.time() - start_time - fit_time if return_train_score: train_score = _score(estimator, X_train, y_train, scorer) if verbose > 2: msg += ", score=%f" % test_score if verbose > 1: total_time = score_time + fit_time end_msg = "%s, total=%s" % (msg, logger.short_format_time(total_time)) print("[CV] %s %s" % ((64 - len(end_msg)) * '.', end_msg)) ret = [train_score, test_score] if return_train_score else [test_score] if return_n_test_samples: ret.append(_num_samples(X_test)) if return_times: ret.extend([fit_time, score_time]) if return_parameters: ret.append(parameters) return ret def _score(estimator, X_test, y_test, scorer): """Compute the score of an estimator on a given test set. This code is the same as sklearn.model_selection._validation._score but accepts to output arrays instead of floats. """ if y_test is None: score = scorer(estimator, X_test) else: score = scorer(estimator, X_test, y_test) if hasattr(score, 'item'): try: # e.g. unwrap memmapped scalars score = score.item() except ValueError: # non-scalar? pass return score
bsd-3-clause
wanghaven/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/pylab.py
70
10245
""" This is a procedural interface to the matplotlib object-oriented plotting library. The following plotting commands are provided; the majority have Matlab(TM) analogs and similar argument. _Plotting commands acorr - plot the autocorrelation function annotate - annotate something in the figure arrow - add an arrow to the axes axes - Create a new axes axhline - draw a horizontal line across axes axvline - draw a vertical line across axes axhspan - draw a horizontal bar across axes axvspan - draw a vertical bar across axes axis - Set or return the current axis limits bar - make a bar chart barh - a horizontal bar chart broken_barh - a set of horizontal bars with gaps box - set the axes frame on/off state boxplot - make a box and whisker plot cla - clear current axes clabel - label a contour plot clf - clear a figure window clim - adjust the color limits of the current image close - close a figure window colorbar - add a colorbar to the current figure cohere - make a plot of coherence contour - make a contour plot contourf - make a filled contour plot csd - make a plot of cross spectral density delaxes - delete an axes from the current figure draw - Force a redraw of the current figure errorbar - make an errorbar graph figlegend - make legend on the figure rather than the axes figimage - make a figure image figtext - add text in figure coords figure - create or change active figure fill - make filled polygons findobj - recursively find all objects matching some criteria gca - return the current axes gcf - return the current figure gci - get the current image, or None getp - get a handle graphics property grid - set whether gridding is on hist - make a histogram hold - set the axes hold state ioff - turn interaction mode off ion - turn interaction mode on isinteractive - return True if interaction mode is on imread - load image file into array imshow - plot image data ishold - return the hold state of the current axes legend - make an axes legend loglog - a log log plot matshow - display a matrix in a new figure preserving aspect pcolor - make a pseudocolor plot pcolormesh - make a pseudocolor plot using a quadrilateral mesh pie - make a pie chart plot - make a line plot plot_date - plot dates plotfile - plot column data from an ASCII tab/space/comma delimited file pie - pie charts polar - make a polar plot on a PolarAxes psd - make a plot of power spectral density quiver - make a direction field (arrows) plot rc - control the default params rgrids - customize the radial grids and labels for polar savefig - save the current figure scatter - make a scatter plot setp - set a handle graphics property semilogx - log x axis semilogy - log y axis show - show the figures specgram - a spectrogram plot spy - plot sparsity pattern using markers or image stem - make a stem plot subplot - make a subplot (numrows, numcols, axesnum) subplots_adjust - change the params controlling the subplot positions of current figure subplot_tool - launch the subplot configuration tool suptitle - add a figure title table - add a table to the plot text - add some text at location x,y to the current axes thetagrids - customize the radial theta grids and labels for polar title - add a title to the current axes xcorr - plot the autocorrelation function of x and y xlim - set/get the xlimits ylim - set/get the ylimits xticks - set/get the xticks yticks - set/get the yticks xlabel - add an xlabel to the current axes ylabel - add a ylabel to the current axes autumn - set the default colormap to autumn bone - set the default colormap to bone cool - set the default colormap to cool copper - set the default colormap to copper flag - set the default colormap to flag gray - set the default colormap to gray hot - set the default colormap to hot hsv - set the default colormap to hsv jet - set the default colormap to jet pink - set the default colormap to pink prism - set the default colormap to prism spring - set the default colormap to spring summer - set the default colormap to summer winter - set the default colormap to winter spectral - set the default colormap to spectral _Event handling connect - register an event handler disconnect - remove a connected event handler _Matrix commands cumprod - the cumulative product along a dimension cumsum - the cumulative sum along a dimension detrend - remove the mean or besdt fit line from an array diag - the k-th diagonal of matrix diff - the n-th differnce of an array eig - the eigenvalues and eigen vectors of v eye - a matrix where the k-th diagonal is ones, else zero find - return the indices where a condition is nonzero fliplr - flip the rows of a matrix up/down flipud - flip the columns of a matrix left/right linspace - a linear spaced vector of N values from min to max inclusive logspace - a log spaced vector of N values from min to max inclusive meshgrid - repeat x and y to make regular matrices ones - an array of ones rand - an array from the uniform distribution [0,1] randn - an array from the normal distribution rot90 - rotate matrix k*90 degress counterclockwise squeeze - squeeze an array removing any dimensions of length 1 tri - a triangular matrix tril - a lower triangular matrix triu - an upper triangular matrix vander - the Vandermonde matrix of vector x svd - singular value decomposition zeros - a matrix of zeros _Probability levypdf - The levy probability density function from the char. func. normpdf - The Gaussian probability density function rand - random numbers from the uniform distribution randn - random numbers from the normal distribution _Statistics corrcoef - correlation coefficient cov - covariance matrix amax - the maximum along dimension m mean - the mean along dimension m median - the median along dimension m amin - the minimum along dimension m norm - the norm of vector x prod - the product along dimension m ptp - the max-min along dimension m std - the standard deviation along dimension m asum - the sum along dimension m _Time series analysis bartlett - M-point Bartlett window blackman - M-point Blackman window cohere - the coherence using average periodiogram csd - the cross spectral density using average periodiogram fft - the fast Fourier transform of vector x hamming - M-point Hamming window hanning - M-point Hanning window hist - compute the histogram of x kaiser - M length Kaiser window psd - the power spectral density using average periodiogram sinc - the sinc function of array x _Dates date2num - convert python datetimes to numeric representation drange - create an array of numbers for date plots num2date - convert numeric type (float days since 0001) to datetime _Other angle - the angle of a complex array griddata - interpolate irregularly distributed data to a regular grid load - load ASCII data into array polyfit - fit x, y to an n-th order polynomial polyval - evaluate an n-th order polynomial roots - the roots of the polynomial coefficients in p save - save an array to an ASCII file trapz - trapezoidal integration __end """ import sys, warnings from cbook import flatten, is_string_like, exception_to_str, popd, \ silent_list, iterable, dedent import numpy as np from numpy import ma from matplotlib import mpl # pulls in most modules from matplotlib.dates import date2num, num2date,\ datestr2num, strpdate2num, drange,\ epoch2num, num2epoch, mx2num,\ DateFormatter, IndexDateFormatter, DateLocator,\ RRuleLocator, YearLocator, MonthLocator, WeekdayLocator,\ DayLocator, HourLocator, MinuteLocator, SecondLocator,\ rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, MONTHLY,\ WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, relativedelta import matplotlib.dates # bring all the symbols in so folks can import them from # pylab in one fell swoop from matplotlib.mlab import window_hanning, window_none,\ conv, detrend, detrend_mean, detrend_none, detrend_linear,\ polyfit, polyval, entropy, normpdf, griddata,\ levypdf, find, trapz, prepca, rem, norm, orth, rank,\ sqrtm, prctile, center_matrix, rk4, exp_safe, amap,\ sum_flat, mean_flat, rms_flat, l1norm, l2norm, norm, frange,\ diagonal_matrix, base_repr, binary_repr, log2, ispower2,\ bivariate_normal, load, save from matplotlib.mlab import stineman_interp, slopes, \ stineman_interp, inside_poly, poly_below, poly_between, \ is_closed_polygon, path_length, distances_along_curve, vector_lengths from numpy import * from numpy.fft import * from numpy.random import * from numpy.linalg import * from matplotlib.mlab import window_hanning, window_none, conv, detrend, demean, \ detrend_mean, detrend_none, detrend_linear, entropy, normpdf, levypdf, \ find, longest_contiguous_ones, longest_ones, prepca, prctile, prctile_rank, \ center_matrix, rk4, bivariate_normal, get_xyz_where, get_sparse_matrix, dist, \ dist_point_to_segment, segments_intersect, fftsurr, liaupunov, movavg, \ save, load, exp_safe, \ amap, rms_flat, l1norm, l2norm, norm_flat, frange, diagonal_matrix, identity, \ base_repr, binary_repr, log2, ispower2, fromfunction_kw, rem, norm, orth, rank, sqrtm,\ mfuncC, approx_real, rec_append_field, rec_drop_fields, rec_join, csv2rec, rec2csv, isvector from matplotlib.pyplot import * # provide the recommended module abbrevs in the pylab namespace import matplotlib.pyplot as plt import numpy as np
agpl-3.0
rohinkumar/galsurveystudy
Quasar_AP_Test.py
1
3271
import healpix_util as hu import astropy as ap import numpy as np from astropy.io import fits from astropy.table import Table import astropy.io.ascii as ascii from astropy.constants import c import matplotlib.pyplot as plt import math import scipy.special as sp dr12q=fits.open('/home/rohin/Desktop/healpix/DR12Q.fits') hmq=fits.open('/home/rohin/Desktop/healpix/HMQ.fits/HMQ.fits') NSIDE=256 hmqhp=hu.HealPix("RING",NSIDE) hmqhppix=hmqhp.eq2pix(hmq[1].data['RA'],hmq[1].data['DEC']) hmqpixdat=np.array(np.zeros(hu.nside2npix(NSIDE))) for j in range(len(hmqhppix)): hmqpixdat[hmqhppix[j]]+=1 hu.orthview(hmqpixdat) outPDF='hmqpixorthview.pdf' plt.savefig(outPDF,dpi=300) hu.mollview(hmqpixdat) outPDF='hmqpixmollview.pdf' plt.savefig(outPDF,dpi=300) j=0 #for i in range(1,6): hmqdata = open("/home/rohin/Desktop/healpix/hmqdata_full.dat",'w') hmqdata.write("Z\t RA\t DEC\n") #for j in range(len(sdssdr72)): try: while j<=len(hmq[1].data['Z']): hmqdata.write("%f\t" %hmq[1].data[j]['Z']) hmqdata.write("%f\t" %hmq[1].data[j]['RA']) hmqdata.write("%f\n" %hmq[1].data[j]['DEC']) #hmqdata.write("%d\n" %dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec'])) #print dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec']) j=j+1 except: pass hmqdata.close() hmqdat=ascii.read("/home/rohin/Desktop/healpix/hmqdata_full.dat") hmqdat.colnames hmqdat.sort['Z'] hmqdatsorted=ascii.read("./hmqdata_full.csv") hmqdatsorted[5679]['Z'] hmq[1].data[0]['Z'] j=0 for i in range(1,7): hmqdata = open("./hmqdata%d.dat"%i,'w') hmqdata.write("Z\t RA\t DEC\n") #for j in range(len(sdssdr72)): try: while hmqdatsorted[j]['Z']<=i: hmqdata.write("%f\t" %hmqdatsorted[j]['Z']) hmqdata.write("%f\t" %hmqdatsorted[j]['RA']) hmqdata.write("%f\n" %hmqdatsorted[j]['DEC']) #hmqdata.write("%d\n" %dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec'])) #print dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec']) j=j+1 except: pass hmqdata.close() j=0 for i in range(1,14): hmqdata = open("./hmqdata_%d.dat"%i,'w') hmqdata.write("Z\t RA\t DEC\n") #for j in range(len(sdssdr72)): try: while hmqdatsorted[j]['Z']<=0.5*i: hmqdata.write("%f\t" %hmqdatsorted[j]['Z']) hmqdata.write("%f\t" %hmqdatsorted[j]['RA']) hmqdata.write("%f\n" %hmqdatsorted[j]['DEC']) #hmqdata.write("%d\n" %dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec'])) #print dt72hpix.eq2pix(sdssdr72[j]['ra'],sdssdr72[j]['dec']) j=j+1 except: pass hmqdata.close() NSIDE=256 hmqhp=hu.HealPix("RING",NSIDE) hmqdata={} hmqhppix={} for i in range(1,14): hmqdata[i] = ascii.read("./hmqdata_%d.dat"%i) hmqhppix[i]=hmqhp.eq2pix(hmqdata[i]['RA'],hmqdata[i]['DEC']) hmqpixdat=np.array(np.zeros(hu.nside2npix(NSIDE))) for j in range(len(hmqhppix[i])): hmqpixdat[hmqhppix[i][j]]+=1 outPDF='figureorth%d.pdf' %i hu.orthview(hmqpixdat) plt.savefig(outPDF,dpi=300) outPDF='figuremoll%d.pdf' %i hu.mollview(hmqpixdat) plt.savefig(outPDF,dpi=300) hmqdata[4] hmqhppix[5]
mit
johanvdw/niche_vlaanderen
niche_vlaanderen/vegetation.py
1
10006
from __future__ import division from pkg_resources import resource_filename import numpy as np import pandas as pd import warnings from .nutrient_level import NutrientLevel from .acidity import Acidity from .codetables import validate_tables_vegetation, check_codes_used from .exception import NicheException class Vegetation(object): """Helper class to calculate vegetation based on input arrays This class helps predicting vegetation based on a number of input arrays. On initialization the input codetables are parsed (and validated). Note that to use grid inputs (eg raster files) it is recommended to use the Niche Class Parameters ---------- ct_vegetation: filename, .csv optional alternative classification table Must contain the columns mentioned in the documentation: https://inbo.github.io/niche_vlaanderen/codetables.html """ nodata_veg = 255 # uint8 def __init__(self, ct_vegetation=None, ct_soil_code=None, ct_acidity=None, ct_management=None, ct_nutrient_level=None, ct_inundation=None): """ Initializes the Vegetation helper class This class initializes the Vegetation helper class. By default it uses the code tables supplied by the niche_vlaanderen package. It is possible to overwrite this by supplying the niche_vlaanderen parameter """ if ct_vegetation is None: ct_vegetation = resource_filename( "niche_vlaanderen", "system_tables/niche_vegetation.csv") # Note that the next code tables are only used for validation, they are # not part of the logic of the vegetation class if ct_soil_code is None: ct_soil_code = resource_filename( "niche_vlaanderen", "system_tables/soil_codes.csv") if ct_acidity is None: ct_acidity = resource_filename( "niche_vlaanderen", "system_tables/acidity.csv") if ct_nutrient_level is None: ct_nutrient_level = resource_filename( "niche_vlaanderen", "system_tables/nutrient_level.csv") if ct_management is None: ct_management = resource_filename( "niche_vlaanderen", "system_tables/management.csv") if ct_inundation is None: ct_inundation = resource_filename( "niche_vlaanderen", "system_tables/inundation.csv") self._ct_vegetation = pd.read_csv(ct_vegetation) self._ct_soil_code = pd.read_csv(ct_soil_code) self._ct_acidity = pd.read_csv(ct_acidity) self._ct_nutrient_level = pd.read_csv(ct_nutrient_level) self._ct_management = pd.read_csv(ct_management) self._ct_inundation = pd.read_csv(ct_inundation) # we check for inner joins if codetables are not overwritten # https://github.com/inbo/niche_vlaanderen/issues/106 inner = all(v is None for v in self.__init__.__code__.co_varnames[1:]) validate_tables_vegetation(ct_vegetation=self._ct_vegetation, ct_soil_code=self._ct_soil_code, ct_acidity=self._ct_acidity, ct_management=self._ct_management, ct_nutrient_level=self._ct_nutrient_level, ct_inundation=self._ct_inundation, inner=inner) # join soil_code to soil_name where needed self._ct_soil_code = self._ct_soil_code.set_index("soil_name") self._ct_vegetation["soil_code"] = \ self._ct_soil_code.soil_code[self._ct_vegetation["soil_name"]]\ .reset_index().soil_code def calculate(self, soil_code, mhw, mlw, nutrient_level=None, acidity=None, management=None, inundation=None, return_all=True, full_model=True): """ Calculate vegetation types based on input arrays Parameters ---------- return_all: boolean A boolean (default=True) whether all grids should be returned or only grids containing data. Returns ------- veg: dict A dictionary containing the different output arrays per veg_code value. -99 is used for nodata_veg values veg_occurrence: dict A dictionary containing the percentage of the area where the vegetation can occur. """ nodata = ((soil_code == -99) | np.isnan(mhw) | np.isnan(mlw)) if full_model: nodata = nodata | (nutrient_level == NutrientLevel.nodata) \ | (acidity == Acidity.nodata) if inundation is not None: nodata = nodata | (inundation == -99) if management is not None: nodata = nodata | (management == -99) if np.all(nodata): raise NicheException("only nodata values in prediction") if full_model: check_codes_used("acidity", acidity, self._ct_acidity["acidity"]) check_codes_used("nutrient_level", nutrient_level, self._ct_nutrient_level["code"]) if inundation is not None: check_codes_used("inundation", inundation, self._ct_inundation["inundation"]) if management is not None: check_codes_used("management", management, self._ct_management["code"]) veg_bands = dict() occurrence = dict() for veg_code, subtable in self._ct_vegetation.groupby(["veg_code"]): subtable = subtable.reset_index() # vegi is the prediction for the current veg_code # it is a logical or of the result of every row: # if a row is true for a pixel, that vegetation can occur vegi = np.zeros(soil_code.shape, dtype=bool) for row in subtable.itertuples(): warnings.simplefilter(action='ignore', category=RuntimeWarning) current_row = ((row.soil_code == soil_code) & (row.mhw_min >= mhw) & (row.mhw_max <= mhw) & (row.mlw_min >= mlw) & (row.mlw_max <= mlw)) warnings.simplefilter("default") if full_model: current_row = (current_row & (nutrient_level == row.nutrient_level) & (row.acidity == acidity)) if inundation is not None: current_row = current_row & (row.inundation == inundation) if management is not None: current_row = current_row & (row.management == management) vegi = vegi | current_row vegi = vegi.astype("uint8") vegi[nodata] = self.nodata_veg if return_all or np.any(vegi): veg_bands[veg_code] = vegi occurrence[veg_code] = np.asscalar( (np.sum(vegi == 1) / (vegi.size - np.sum(nodata)))) return veg_bands, occurrence def calculate_deviation(self, soil_code, mhw, mlw): """ Calculates the deviation between the mhw/mlw and the reference This function calculates the difference between the mhw and mlw and the reference values for each vegetation type. Positive values indicate too dry values, negative values indicate too wet values. Values of zero indicate that the vegetation type can occur based on soil type and the value under consideration (mhw or mlw) Returns ------- difference: dict A dictionary containing the difference between the vegetation value an the actual value. Keys are eg mhw_01 for mhw and vegetation type 01 """ nodata = ((soil_code == -99) | np.isnan(mhw) | np.isnan(mlw)) difference = dict() veg = self._ct_vegetation[["veg_code", "soil_code", "mhw_min", "mhw_max", "mlw_min", "mlw_max"]] veg = veg.drop_duplicates() warnings.simplefilter(action='ignore', category=RuntimeWarning) for veg_code, subtable in veg.groupby(["veg_code"]): subtable = subtable.reset_index() mhw_diff = np.full(soil_code.shape, np.nan) mlw_diff = np.full(soil_code.shape, np.nan) for row in subtable.itertuples(): # mhw smaller than maximum sel = (row.soil_code == soil_code) & (row.mhw_max > mhw) mhw_diff[sel] = (mhw - row.mhw_max)[sel] # mhw larger than minimum sel = (row.soil_code == soil_code) & (row.mhw_min < mhw) mhw_diff[sel] = (mhw - row.mhw_min)[sel] # mhw in range sel = ((row.soil_code == soil_code) & (row.mhw_min >= mhw) & (row.mhw_max <= mhw)) mhw_diff[sel] = (np.zeros(soil_code.shape))[sel] # mlw smaller than maximum sel = (row.soil_code == soil_code) & (row.mlw_max > mlw) mlw_diff[sel] = (mlw - row.mlw_max)[sel] # mlw larger than minimum sel = (row.soil_code == soil_code) & (row.mlw_min < mlw) mlw_diff[sel] = (mlw - row.mlw_min)[sel] # mlw in range sel = ((row.soil_code == soil_code) & (row.mlw_min >= mlw) & (row.mlw_max <= mlw)) mlw_diff[sel] = (np.zeros(soil_code.shape))[sel] mhw_diff[nodata] = np.NaN mlw_diff[nodata] = np.NaN difference["mhw_%02d" % veg_code] = mhw_diff difference["mlw_%02d" % veg_code] = mlw_diff warnings.simplefilter("default") return difference
mit
beiko-lab/gengis
bin/Lib/site-packages/matplotlib/backends/qt4_editor/formlayout.py
3
21226
# -*- coding: utf-8 -*- """ formlayout ========== Module creating Qt form dialogs/layouts to edit various type of parameters formlayout License Agreement (MIT License) ------------------------------------------ Copyright (c) 2009 Pierre Raybaut Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import print_function # History: # 1.0.10: added float validator (disable "Ok" and "Apply" button when not valid) # 1.0.7: added support for "Apply" button # 1.0.6: code cleaning __version__ = '1.0.10' __license__ = __doc__ DEBUG = False import sys STDERR = sys.stderr from matplotlib.backends.qt4_compat import QtGui,QtCore from matplotlib.colors import rgb2hex if not hasattr(QtGui,'QFormLayout'): raise ImportError, "Warning: formlayout requires PyQt4 >v4.3 or PySide" (QWidget, QLineEdit, QComboBox, QLabel, QSpinBox, QIcon,QStyle, QDialogButtonBox, QHBoxLayout, QVBoxLayout, QDialog, QColor, QPushButton, QCheckBox, QColorDialog, QPixmap, QTabWidget, QApplication, QStackedWidget, QDateEdit, QDateTimeEdit, QFont, QFontComboBox, QFontDatabase, QGridLayout, QFormLayout, QDoubleValidator) =\ (QtGui.QWidget, QtGui.QLineEdit, QtGui.QComboBox, QtGui.QLabel, QtGui.QSpinBox, QtGui.QIcon, QtGui.QStyle, QtGui.QDialogButtonBox, QtGui.QHBoxLayout, QtGui.QVBoxLayout, QtGui.QDialog, QtGui.QColor, QtGui.QPushButton, QtGui.QCheckBox, QtGui.QColorDialog, QtGui.QPixmap, QtGui.QTabWidget, QtGui.QApplication, QtGui.QStackedWidget, QtGui.QDateEdit, QtGui.QDateTimeEdit, QtGui.QFont, QtGui.QFontComboBox, QtGui.QFontDatabase, QtGui.QGridLayout, QtGui.QFormLayout, QtGui.QDoubleValidator) (Qt, SIGNAL, SLOT, QObject, QSize,pyqtSignature, pyqtProperty) =\ (QtCore.Qt, QtCore.SIGNAL, QtCore.SLOT, QtCore.QObject, QtCore.QSize, QtCore.Slot, QtCore.Property) import datetime class ColorButton(QPushButton): """ Color choosing push button """ __pyqtSignals__ = ("colorChanged(QColor)",) def __init__(self, parent=None): QPushButton.__init__(self, parent) self.setFixedSize(20, 20) self.setIconSize(QSize(12, 12)) self.connect(self, SIGNAL("clicked()"), self.choose_color) self._color = QColor() def choose_color(self): color = QColorDialog.getColor(self._color,self.parentWidget(),'') if color.isValid(): self.set_color(color) def get_color(self): return self._color @QtCore.Slot("QColor") def set_color(self, color): if color != self._color: self._color = color self.emit(SIGNAL("colorChanged(QColor)"), self._color) pixmap = QPixmap(self.iconSize()) pixmap.fill(color) self.setIcon(QtGui.QIcon(pixmap)) color = QtCore.Property("QColor", get_color, set_color) def col2hex(color): """Convert matplotlib color to hex before passing to Qt""" return rgb2hex(colorConverter.to_rgb(color)) def to_qcolor(color): """Create a QColor from a matplotlib color""" qcolor = QtGui.QColor() color = str(color) try: color = col2hex(color) except ValueError: #print('WARNING: ignoring invalid color %r' % color) return qcolor # return invalid QColor qcolor.setNamedColor(color) # set using hex color return qcolor # return valid QColor def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """ color = QColor() if isinstance(text, QObject): # actually a QString, which is not provided by the new PyQt4 API: text = str(text) if not isinstance(text, (unicode, str)): return color if text.startswith('#') and len(text)==7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color def is_matplotlib_color(value): """ Check if value is a color passed to us from matplotlib. It could either be a valid color string or a 3-tuple of floats between 0. and 1. """ if text_to_qcolor(value).isValid(): return True if isinstance(value,tuple) and len(value)==3 and all(map(lambda v: isinstance(v,float),value)): for c in value: if c < 0. or c > 1.: return False return True return False class ColorLayout(QHBoxLayout): """Color-specialized QLineEdit layout""" def __init__(self, color, parent=None): QHBoxLayout.__init__(self) assert isinstance(color, QColor) self.lineedit = QLineEdit(color.name(), parent) self.connect(self.lineedit, SIGNAL("textChanged(QString)"), self.update_color) self.addWidget(self.lineedit) self.colorbtn = ColorButton(parent) self.colorbtn.color = color self.connect(self.colorbtn, SIGNAL("colorChanged(QColor)"), self.update_text) self.addWidget(self.colorbtn) def update_color(self, text): color = text_to_qcolor(text) if color.isValid(): self.colorbtn.color = color def update_text(self, color): self.lineedit.setText(color.name()) def text(self): return self.lineedit.text() def font_is_installed(font): """Check if font is installed""" return [fam for fam in QFontDatabase().families() if unicode(fam)==font] def tuple_to_qfont(tup): """ Create a QFont from tuple: (family [string], size [int], italic [bool], bold [bool]) """ if not isinstance(tup, tuple) or len(tup) != 4 \ or not font_is_installed(tup[0]) \ or not isinstance(tup[1], int) \ or not isinstance(tup[2], bool) \ or not isinstance(tup[3], bool): return None font = QFont() family, size, italic, bold = tup font.setFamily(family) font.setPointSize(size) font.setItalic(italic) font.setBold(bold) return font def qfont_to_tuple(font): return (unicode(font.family()), int(font.pointSize()), font.italic(), font.bold()) class FontLayout(QGridLayout): """Font selection""" def __init__(self, value, parent=None): QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QFontComboBox(parent) self.family.setCurrentFont(font) self.addWidget(self.family, 0, 0, 1, -1) # Font size self.size = QComboBox(parent) self.size.setEditable(True) sizelist = range(6, 12) + range(12, 30, 2) + [36, 48, 72] size = font.pointSize() if size not in sizelist: sizelist.append(size) sizelist.sort() self.size.addItems([str(s) for s in sizelist]) self.size.setCurrentIndex(sizelist.index(size)) self.addWidget(self.size, 1, 0) # Italic or not self.italic = QCheckBox(self.tr("Italic"), parent) self.italic.setChecked(font.italic()) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QCheckBox(self.tr("Bold"), parent) self.bold.setChecked(font.bold()) self.addWidget(self.bold, 1, 2) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font) def is_edit_valid(edit): text = edit.text() state = edit.validator().validate(text, 0)[0] return state == QDoubleValidator.Acceptable class FormWidget(QWidget): def __init__(self, data, comment="", parent=None): QWidget.__init__(self, parent) from copy import deepcopy self.data = deepcopy(data) self.widgets = [] self.formlayout = QFormLayout(self) if comment: self.formlayout.addRow(QLabel(comment)) self.formlayout.addRow(QLabel(" ")) if DEBUG: print("\n"+("*"*80)) print("DATA:", self.data) print("*"*80) print("COMMENT:", comment) print("*"*80) def get_dialog(self): """Return FormDialog instance""" dialog = self.parent() while not isinstance(dialog, QDialog): dialog = dialog.parent() return dialog def setup(self): for label, value in self.data: if DEBUG: print("value:", value) if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QLabel(" "), QLabel(" ")) self.widgets.append(None) continue elif label is None: # Comment self.formlayout.addRow(QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif is_matplotlib_color(value): field = ColorLayout(QColor(value), self) elif isinstance(value, (str, unicode)): field = QLineEdit(value, self) elif isinstance(value, (list, tuple)): if isinstance(value, tuple): value = list(value) selindex = value.pop(0) field = QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [ key for key, _val in value ] value = [ val for _key, val in value ] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): print("Warning: '%s' index is invalid (label: " \ "%s, value: %s)" % (selindex, label, value), file=STDERR) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QCheckBox(self) if value: field.setCheckState(Qt.Checked) else : field.setCheckState(Qt.Unchecked) elif isinstance(value, float): field = QLineEdit(repr(value), self) field.setValidator(QDoubleValidator(field)) dialog = self.get_dialog() dialog.register_float_field(field) self.connect(field, SIGNAL('textChanged(QString)'), lambda text: dialog.update_buttons()) elif isinstance(value, int): field = QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QDateEdit(self) field.setDate(value) else: field = QLineEdit(repr(value), self) self.formlayout.addRow(label, field) self.widgets.append(field) def get(self): valuelist = [] for index, (label, value) in enumerate(self.data): field = self.widgets[index] if label is None: # Separator / Comment continue elif tuple_to_qfont(value) is not None: value = field.get_font() elif isinstance(value, (str, unicode)) or is_matplotlib_color(value): value = unicode(field.text()) elif isinstance(value, (list, tuple)): index = int(field.currentIndex()) if isinstance(value[0], (list, tuple)): value = value[index][0] else: value = value[index] elif isinstance(value, bool): value = field.checkState() == Qt.Checked elif isinstance(value, float): value = float(str(field.text())) elif isinstance(value, int): value = int(field.value()) elif isinstance(value, datetime.datetime): value = field.dateTime().toPyDateTime() elif isinstance(value, datetime.date): value = field.date().toPyDate() else: value = eval(str(field.text())) valuelist.append(value) return valuelist class FormComboWidget(QWidget): def __init__(self, datalist, comment="", parent=None): QWidget.__init__(self, parent) layout = QVBoxLayout() self.setLayout(layout) self.combobox = QComboBox() layout.addWidget(self.combobox) self.stackwidget = QStackedWidget(self) layout.addWidget(self.stackwidget) self.connect(self.combobox, SIGNAL("currentIndexChanged(int)"), self.stackwidget, SLOT("setCurrentIndex(int)")) self.widgetlist = [] for data, title, comment in datalist: self.combobox.addItem(title) widget = FormWidget(data, comment=comment, parent=self) self.stackwidget.addWidget(widget) self.widgetlist.append(widget) def setup(self): for widget in self.widgetlist: widget.setup() def get(self): return [ widget.get() for widget in self.widgetlist] class FormTabWidget(QWidget): def __init__(self, datalist, comment="", parent=None): QWidget.__init__(self, parent) layout = QVBoxLayout() self.tabwidget = QTabWidget() layout.addWidget(self.tabwidget) self.setLayout(layout) self.widgetlist = [] for data, title, comment in datalist: if len(data[0])==3: widget = FormComboWidget(data, comment=comment, parent=self) else: widget = FormWidget(data, comment=comment, parent=self) index = self.tabwidget.addTab(widget, title) self.tabwidget.setTabToolTip(index, comment) self.widgetlist.append(widget) def setup(self): for widget in self.widgetlist: widget.setup() def get(self): return [ widget.get() for widget in self.widgetlist] class FormDialog(QDialog): """Form Dialog""" def __init__(self, data, title="", comment="", icon=None, parent=None, apply=None): QDialog.__init__(self, parent) self.apply_callback = apply # Form if isinstance(data[0][0], (list, tuple)): self.formwidget = FormTabWidget(data, comment=comment, parent=self) elif len(data[0])==3: self.formwidget = FormComboWidget(data, comment=comment, parent=self) else: self.formwidget = FormWidget(data, comment=comment, parent=self) layout = QVBoxLayout() layout.addWidget(self.formwidget) self.float_fields = [] self.formwidget.setup() # Button box self.bbox = bbox = QDialogButtonBox(QDialogButtonBox.Ok |QDialogButtonBox.Cancel) self.connect(self.formwidget, SIGNAL('update_buttons()'), self.update_buttons) if self.apply_callback is not None: apply_btn = bbox.addButton(QDialogButtonBox.Apply) self.connect(apply_btn, SIGNAL("clicked()"), self.apply) self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()")) self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()")) layout.addWidget(bbox) self.setLayout(layout) self.setWindowTitle(title) if not isinstance(icon, QIcon): icon = QWidget().style().standardIcon(QStyle.SP_MessageBoxQuestion) self.setWindowIcon(icon) def register_float_field(self, field): self.float_fields.append(field) def update_buttons(self): valid = True for field in self.float_fields: if not is_edit_valid(field): valid = False for btn_type in (QDialogButtonBox.Ok, QDialogButtonBox.Apply): btn = self.bbox.button(btn_type) if btn is not None: btn.setEnabled(valid) def accept(self): self.data = self.formwidget.get() QDialog.accept(self) def reject(self): self.data = None QDialog.reject(self) def apply(self): self.apply_callback(self.formwidget.get()) def get(self): """Return form result""" return self.data def fedit(data, title="", comment="", icon=None, parent=None, apply=None): """ Create form dialog and return result (if Cancel button is pressed, return None) data: datalist, datagroup title: string comment: string icon: QIcon instance parent: parent QWidget apply: apply callback (function) datalist: list/tuple of (field_name, field_value) datagroup: list/tuple of (datalist *or* datagroup, title, comment) -> one field for each member of a datalist -> one tab for each member of a top-level datagroup -> one page (of a multipage widget, each page can be selected with a combo box) for each member of a datagroup inside a datagroup Supported types for field_value: - int, float, str, unicode, bool - colors: in Qt-compatible text form, i.e. in hex format or name (red,...) (automatically detected from a string) - list/tuple: * the first element will be the selected index (or value) * the other elements can be couples (key, value) or only values """ # Create a QApplication instance if no instance currently exists # (e.g., if the module is used directly from the interpreter) if QApplication.startingUp(): _app = QApplication([]) dialog = FormDialog(data, title, comment, icon, parent, apply) if dialog.exec_(): return dialog.get() if __name__ == "__main__": def create_datalist_example(): return [('str', 'this is a string'), ('list', [0, '1', '3', '4']), ('list2', ['--', ('none', 'None'), ('--', 'Dashed'), ('-.', 'DashDot'), ('-', 'Solid'), ('steps', 'Steps'), (':', 'Dotted')]), ('float', 1.2), (None, 'Other:'), ('int', 12), ('font', ('Arial', 10, False, True)), ('color', '#123409'), ('bool', True), ('date', datetime.date(2010, 10, 10)), ('datetime', datetime.datetime(2010, 10, 10)), ] def create_datagroup_example(): datalist = create_datalist_example() return ((datalist, "Category 1", "Category 1 comment"), (datalist, "Category 2", "Category 2 comment"), (datalist, "Category 3", "Category 3 comment")) #--------- datalist example datalist = create_datalist_example() def apply_test(data): print("data:", data) print("result:", fedit(datalist, title="Example", comment="This is just an <b>example</b>.", apply=apply_test)) #--------- datagroup example datagroup = create_datagroup_example() print("result:", fedit(datagroup, "Global title")) #--------- datagroup inside a datagroup example datalist = create_datalist_example() datagroup = create_datagroup_example() print("result:", fedit(((datagroup, "Title 1", "Tab 1 comment"), (datalist, "Title 2", "Tab 2 comment"), (datalist, "Title 3", "Tab 3 comment")), "Global title"))
gpl-3.0
kprestel/PyInvestment
pytech/fin/portfolio.py
2
21447
import logging import queue from abc import ABCMeta, abstractmethod from datetime import datetime from typing import Dict, List import pandas as pd import pytech.utils.dt_utils as dt_utils from pytech.backtest.event import SignalEvent from pytech.data.handler import DataHandler from pytech.fin.asset.owned_asset import OwnedAsset from pytech.mongo import ARCTIC_STORE, PortfolioStore from pytech.trading.blotter import Blotter from pytech.trading.trade import Trade from pytech.utils import pandas_utils as pd_utils from pytech.utils.enums import ( EventType, Position, SignalType, TradeAction ) from pytech.utils.exceptions import ( InsufficientFundsError, InvalidEventTypeError, InvalidSignalTypeError ) logger = logging.getLogger(__name__) class AbstractPortfolio(metaclass=ABCMeta): """ Base class for all portfolios. Any portfolio MUST inherit from this class an implement the following methods: * update_signal(self, event) * update_fill(self, event) Child portfolio classes must also call super().__init__() in order to set the class up correctly. """ bars: DataHandler events: queue.Queue blotter: Blotter start_date: datetime ticker_list: List[str] owned_assets: Dict[str, OwnedAsset] lib: PortfolioStore # stores all of the ticks portfolio position. POSITION_COLLECTION = 'portfolio' # stores the latest tick portfolio position. TICK_COLLECTION = 'portfolio_tick' def __init__(self, data_handler: DataHandler, events: queue.Queue, start_date: datetime, blotter: Blotter, initial_capital: float = 100000.00, raise_on_warnings=False): self.logger = logging.getLogger(__name__) self.bars = data_handler self.events = events self.blotter = blotter self.start_date = dt_utils.parse_date(start_date) self.initial_capital = initial_capital self.cash = initial_capital self.ticker_list = self.bars.tickers self.owned_assets = {} # holdings = mv self.all_holdings_mv = self._construct_all_holdings() # positions = qty self.all_positions_qty = self._construct_all_positions() self.total_commission = 0.0 self.lib = ARCTIC_STORE['pytech.portfolio'] self.positions_df = pd.DataFrame() self.raise_on_warnings = raise_on_warnings @property def total_value(self): """ A read only property to make getting the current total market value easier. **This includes cash.** """ return self.all_holdings_mv[-1]['total'] @property def total_asset_mv(self): """ A read only property to make getting the total market value of the owned assets easier. :return: The total market value of the owned assets in the portfolio. """ mv = 0.0 for asset in self.owned_assets.values(): mv += asset.total_position_value return mv @abstractmethod def update_signal(self, event): """ Acts on a :class:`SignalEvent` to generate new orders based on the portfolio logic. """ raise NotImplementedError('Must implement update_signal()') @abstractmethod def update_fill(self, event): """ Updates the portfolio current positions and holdings based on a :class:`FillEvent`. """ raise NotImplementedError('Must implement update_fill()') def _construct_all_positions(self): """ Constructs the position list using the start date to determine when the index will begin. This should only be called once. """ d = self._get_temp_dict() d['datetime'] = self.start_date return [d] def _construct_all_holdings(self): d = {k: v for k, v in [(ticker, 0.0) for ticker in self.ticker_list]} d['datetime'] = self.start_date d['cash'] = self.initial_capital d['commission'] = 0.0 d['total'] = self.initial_capital return [d] def _construct_current_holdings(self): """ Construct a dict which holds the instantaneous market value of the portfolio across all symbols. This should only be called once. """ d = {k: v for k, v in [(ticker, 0.0) for ticker in self.ticker_list]} return d def create_equity_curve_df(self): """Create a df from all_holdings_mv list of dicts.""" curve = pd.DataFrame(self.all_holdings_mv) curve.set_index('datetime', inplace=True) curve['returns'] = curve['total'].pct_change() curve['equity_curve'] = (1.0 + curve['returns']).cumprod() self.equity_curve = curve def _get_temp_dict(self): return {k: v for k, v in [(ticker, 0) for ticker in self.ticker_list]} def check_liquidity(self, avg_price_per_share, qty): """ Check if the portfolio has enough liquidity to actually make the trade. This method should be called before executing any trade. :param float avg_price_per_share: The price per share in the trade **AFTER** commission has been applied. :param int qty: The amount of shares to be traded. :return: True if there is enough cash to make the trade or if qty is negative indicating a sale. """ if qty < 0: return True cost = avg_price_per_share * qty cur_cash = self.cash post_trade_cash = cur_cash - cost return post_trade_cash > 0 def get_owned_asset_mv(self, ticker): """ Return the current market value for an :class:`OwnedAsset` :param str ticker: The ticker of the owned asset. :return: The current market value for the ticker. :raises: KeyError """ try: return self.owned_assets[ticker].total_position_value except KeyError: self.logger.exception( f'Ticker: {ticker} is not currently owned.') raise def update_timeindex(self, event): """ Adds a new record to the positions matrix for all the current market data bar. This reflects the PREVIOUS bar. Makes use of MarketEvent from the events queue. :param MarketEvent event: :raises InvalidEventTypeError: When the event type passed in is not a :class:`MarketEvent` """ if event.event_type is not EventType.MARKET: raise InvalidEventTypeError(expected=EventType.MARKET, event_type=event.event_type) self.blotter.check_order_triggers() # get an element from the set latest_dt = self.bars.get_latest_bar_dt(next(iter(self.ticker_list))) # update positions # dp = self._get_temp_dict() # dp['datetime'] = latest_dt dh = self._get_temp_dict() for ticker in self.ticker_list: try: dh[ticker] = self.owned_assets[ticker].shares_owned except KeyError: dh[ticker] = 0 # append current positions # self.all_positions_qty.append(dp) # update holdings # dh = self._get_temp_dict() index = [] dh['cash'] = self.cash dh['commission'] = self.total_commission dh['total'] = self.cash for ticker in self.ticker_list: try: owned_asset = self.owned_assets[ticker] except KeyError: market_value = 0 self.logger.debug(f'{ticker} is not currently owned, ' f'market value will be set to 0.') else: shares_owned = owned_asset.shares_owned adj_close = self.bars.get_latest_bar_value(ticker, pd_utils.ADJ_CLOSE_COL) market_value = shares_owned * adj_close owned_asset.update_total_position_value(adj_close, latest_dt) # approximate to real value. dh[ticker] = market_value dh['total'] += market_value index.append((latest_dt, ticker)) multi_index = pd.MultiIndex.from_tuples(index, names=['datetime', 'ticker']) df = pd.DataFrame(dh, index=multi_index) self.positions_df = pd.concat([self.positions_df, df]) self.logger.info('Writing current portfolio state to DB.') self.lib.write_snapshot(self.POSITION_COLLECTION, self.positions_df, latest_dt) self.lib.write_snapshot(self.TICK_COLLECTION, df, latest_dt) self.all_holdings_mv.append(dh) class BasicPortfolio(AbstractPortfolio): """Here for testing and stuff.""" def __init__(self, data_handler: DataHandler, events: queue.Queue, start_date: datetime, blotter: Blotter, initial_capital: float = 100000.00, raise_on_warnings=False): super().__init__(data_handler, events, start_date, blotter, initial_capital, raise_on_warnings) def _update_from_trade(self, trade: Trade): self.cash += trade.trade_cost() self.total_commission += trade.commission if trade.ticker in self.owned_assets: self._update_existing_owned_asset_from_trade(trade) else: self._create_new_owned_asset_from_trade(trade) def _update_existing_owned_asset_from_trade(self, trade): """ Update an existing owned asset or delete it if the trade results in all shares being sold. """ owned_asset = self.owned_assets[trade.ticker] updated_asset = owned_asset.make_trade( trade.qty, trade.avg_price_per_share) if updated_asset is None: del self.owned_assets[trade.ticker] else: self.owned_assets[trade.ticker] = updated_asset def _create_new_owned_asset_from_trade(self, trade): """Create a new owned asset based on the execution of a trade.""" if trade.action is TradeAction.SELL: asset_position = Position.SHORT else: asset_position = Position.LONG self.owned_assets[trade.ticker] = OwnedAsset.from_trade(trade, asset_position) def update_fill(self, event): if event.type is EventType.FILL: order = self.blotter[event.order_id] if self.check_liquidity(event.price, event.available_volume): trade = self.blotter.make_trade(order, event.price, event.dt, event.available_volume) self._update_from_trade(trade) else: self.logger.warning( 'Insufficient funds available to execute trade for ' f'ticker: {order.ticker}') if self.raise_on_warnings: raise InsufficientFundsError(ticker=order.ticker) def update_signal(self, event: SignalEvent): if event.event_type is EventType.SIGNAL: self._process_signal(event) # self.balancer(self, event) self.blotter.check_order_triggers() # self.events.put(self.generate_naive_order(event)) else: raise InvalidEventTypeError( expected=type(EventType.SIGNAL), event_type=type(event.event_type)) def _process_signal(self, signal: SignalEvent): """ Call different methods depending on the type of signal received. :param signal: :return: """ if signal.signal_type is SignalType.EXIT: self._handle_exit_signal(signal) elif signal.signal_type is SignalType.CANCEL: self._handle_cancel_signal(signal) elif signal.signal_type is SignalType.HOLD: self._handle_hold_signal(signal) elif signal.signal_type is SignalType.TRADE: self._handle_trade_signal(signal) elif signal.signal_type is SignalType.LONG: self._handle_long_signal(signal) elif signal.signal_type is SignalType.SHORT: self._handle_short_signal(signal) else: raise InvalidSignalTypeError(signal_type=type(signal.signal_type)) def _handle_trade_signal(self, signal: SignalEvent): """ Process a new trade signal and take the appropriate action. This could include opening a new order or taking no action at all. :param signal: The trade signal. :return: """ try: if signal.position is SignalType.LONG: self._handle_long_signal(signal) elif signal.position is SignalType.SHORT: self._handle_short_signal(signal) else: # default always to general trade signals. self._handle_general_trade_signal(signal) except AttributeError: self._handle_general_trade_signal(signal) def _handle_exit_signal(self, signal: SignalEvent): """ Create an order that will close out the position in the signal. :param signal: :return: """ qty = self.owned_assets[signal.ticker].shares_owned if qty > 0: action = TradeAction.SELL elif qty < 0: action = TradeAction.BUY else: raise ValueError( f'Cannot exit from a position that is not owned.' f'Owned qty is 0 for ticker: {signal.ticker}.') self.blotter.place_order(signal.ticker, qty, action, signal.order_type, signal.stop_price, signal.limit_price) def _handle_cancel_signal(self, signal: SignalEvent): """ Cancel all open orders for the asset in the signal. :param signal: """ self.blotter.cancel_all_orders_for_asset(signal.ticker, upper_price=signal.upper_price, lower_price=signal.lower_price, order_type=signal.order_type, trade_action=signal.action) def _handle_hold_signal(self, signal: SignalEvent): """ Place all open orders for the asset in the signal on hold. :param signal: :return: """ self.blotter.hold_all_orders_for_asset(signal.ticker) def _handle_long_signal(self, signal): """ Handle a long signal by placing an order to **BUY**. :param LongSignalEvent or SignalEvent signal: :return: """ def _handle_short_signal(self, signal): """ Handle a short signal. :param ShortSignalEvent or SignalEvent signal: :return: """ def _handle_general_trade_signal(self, signal: SignalEvent): """ Handle an ambiguous trade signal, meaning a trade signal that is not explicitly defined as **LONG** or **SHORT**. This most often means defaulting to whatever :class:``Balancer`` the portfolio has implemented. """ class Portfolio(object): """ Holds stocks and keeps tracks of the owner's cash as well and their :class:`OwnedAssets` and allows them to perform analysis on just the :class:`Asset` that they currently own. Ignore this part: This class inherits from :class:``AssetUniverse`` so that it has access to its analysis functions. It is important to note that :class:``Portfolio`` is its own table in the database as it represents the :class:``Asset`` that the user currently owns. An :class:``Asset`` can be in both the *asset_universe* table as well as the *portfolio* table but a :class:``Asset`` does have to be in the database to be traded """ LOGGER_NAME = 'portfolio' def __init__(self, starting_cash=1000000): """ :param datetime start_date: a date, the start date to start the simulation as of. (default: end_date - 365 days) :param datetime end_date: the end date to end the simulation as of. (default: ``datetime.now()``) :param str benchmark_ticker: the ticker of the market index or benchmark to compare the portfolio against. (default: *^GSPC*) :param float starting_cash: the amount of dollars to allocate to the portfolio initially (default: 10000000) :param str trading_cal: The name of the trading calendar to use. (default: NYSE) :param data_frequency: The frequency of how often data should be updated. """ self.owned_assets = {} self.cash = float(starting_cash) self.logger = logging.getLogger(self.LOGGER_NAME) def __getitem__(self, key): """Allow quick dictionary like access to the owned_assets dict""" if isinstance(key, OwnedAsset): return self.owned_assets[key.ticker] else: return self.owned_assets[key] def __setitem__(self, key, value): """Allow quick adding of :class:``OwnedAsset``s to the dict.""" if isinstance(key, OwnedAsset): self.owned_assets[key.ticker] = value else: self.owned_assets[key] = value self.owned_assets[key] = value def __iter__(self): """ Iterate over all the :class:`~.owned_asset.OwnedAsset`s in the portfolio. """ yield self.owned_assets.items() def check_liquidity(self, avg_price_per_share, qty): """ Check if the portfolio has enough liquidity to actually make the trade. This method should be called before executing any trade. :param float avg_price_per_share: The price per share in the trade **AFTER** commission has been applied. :param int qty: The amount of shares to be traded. :return: True if there is enough cash to make the trade or if qty is negative indicating a sale. """ if qty < 0: return True cost = avg_price_per_share * qty cur_cash = self.cash post_trade_cash = cur_cash - cost return post_trade_cash > 0 def update_from_trade(self, trade): """ Update the ``portfolio``'s state based on the execution of a trade. This includes updating the cash position as well as the ``owned_asset`` dictionary. :param Trade trade: The trade that was executed. :return: """ self.cash += trade.trade_cost() if trade.ticker in self.owned_assets: self._update_existing_owned_asset_from_trade(trade) else: self._create_new_owned_asset_from_trade(trade) def _update_existing_owned_asset_from_trade(self, trade): """ Update an existing owned asset or delete it if the trade results in all shares being sold. """ owned_asset = self.owned_assets[trade.ticker] updated_asset = owned_asset.make_trade(trade.qty, trade.avg_price_per_share) if updated_asset is None: del self.owned_assets[trade.ticker] else: self.owned_assets[trade.ticker] = updated_asset def _create_new_owned_asset_from_trade(self, trade): """Create a new owned asset based on the execution of a trade.""" if trade.action is TradeAction.SELL: asset_position = Position.SHORT else: asset_position = Position.LONG self.owned_assets[trade.ticker] = OwnedAsset.from_trade(trade, asset_position) def get_total_value(self, include_cash=True): """ Calculate the total value of the ``Portfolio`` owned_assets :param bool include_cash: Should cash be included in the calculation, or just get the total value of the owned_assets. :return: The total value of the portfolio at a given moment in time. :rtype: float """ total_value = 0.0 for asset in self.owned_assets.values(): asset.update_total_position_value() total_value += asset.total_position_value if include_cash: total_value += self.cash return total_value def return_on_owned_assets(self): """Get the total return of the portfolio's current owned assets""" roi = 0.0 for asset in self.owned_assets.values(): roi += asset.return_on_investment() return roi def sma(self): for ticker, stock in self.owned_assets.items(): yield stock.simple_moving_average()
mit
lucashtnguyen/wqreports
setup.py
3
1622
# Setup script for the wqreports package # # Usage: python setup.py install # import os from setuptools import setup, find_packages DESCRIPTION = "wqreports: Create reports from data analyzed with wqio" LONG_DESCRIPTION = DESCRIPTION NAME = "wqreports" VERSION = "0.1" AUTHOR = "Lucas Nguyen (Geosyntec Consultants)" AUTHOR_EMAIL = "lnguyen@geosyntec.com" URL = "https://github.com/Geosyntec/wqreports" DOWNLOAD_URL = URL LICENSE = "BSD 3-clause" PACKAGES = find_packages(exclude=[]) PLATFORMS = "Python 3.3 and later." CLASSIFIERS = [ "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Intended Audience :: Science/Research", "Topic :: Formats and Protocols :: Data Formats", "Topic :: Scientific/Engineering :: Earth Sciences", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ] INSTALL_REQUIRES = ['jinja2', 'seaborn', 'wqio'] PACKAGE_DATA = { 'wqreports.testing': ['*.txt'], } DATA_FILES = None if __name__ == "__main__": setup( name=NAME, version=VERSION, author=AUTHOR, author_email=AUTHOR_EMAIL, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, download_url=DOWNLOAD_URL, license=LICENSE, packages=PACKAGES, package_data=PACKAGE_DATA, data_files=DATA_FILES, platforms=PLATFORMS, classifiers=CLASSIFIERS, install_requires=INSTALL_REQUIRES, zip_safe=False )
bsd-3-clause
shogun-toolbox/shogun
examples/undocumented/python/graphical/classifier_gaussian_process_binary_classification.py
2
3589
# This software is distributed under BSD 3-clause license (see LICENSE file). # # Authors: Roman Votyakov import itertools import matplotlib.pyplot as plt import numpy as np def generate_toy_data(n_train=100, mean_a=np.asarray([0, 0]), std_dev_a=1.0, mean_b=3, std_dev_b=0.5): # positive examples are distributed normally X1 = (np.random.randn(n_train, 2) * std_dev_a + mean_a).T # negative examples have a "ring"-like form r = np.random.randn(n_train) * std_dev_b + mean_b angle = np.random.randn(n_train) * 2 * np.pi X2 = np.array([r * np.cos(angle) + mean_a[0], r * np.sin(angle) + mean_a[1]]) # stack positive and negative examples in a single array X_train = np.hstack((X1, X2)) # label positive examples with +1, negative with -1 y_train = np.zeros(n_train * 2) y_train[:n_train] = 1 y_train[n_train:] = -1 return [X_train, y_train] def gaussian_process_binary_classification_laplace(X_train, y_train, n_test=50): import shogun as sg # convert training data into Shogun representation train_features = sg.create_features(X_train) train_labels = sg.create_labels(y_train) # generate all pairs in 2d range of testing data x1 = np.linspace(X_train[0, :].min() - 1, X_train[0, :].max() + 1, n_test) x2 = np.linspace(X_train[1, :].min() - 1, X_train[1, :].max() + 1, n_test) X_test = np.asarray(list(itertools.product(x1, x2))).T # convert testing features into Shogun representation test_features = sg.create_features(X_test) # create Gaussian kernel with width = 2.0 kernel = sg.create_kernel('GaussianKernel', width=2.0) # create zero mean function mean = sg.gp_mean("ZeroMean") # you can easily switch between probit and logit likelihood models # by uncommenting/commenting the following lines: # create probit likelihood model # lik = ProbitLikelihood() # create logit likelihood model lik = sg.gp_likelihood("LogitLikelihood") # you can easily switch between Laplace and EP approximation by # uncommenting/commenting the following lines: # specify Laplace approximation inference method # inf = SingleLaplacianInferenceMethod(kernel, train_features, mean, train_labels, lik) # specify EP approximation inference method inf = sg.gp_inference("MultiLaplaceInferenceMethod", kernel=kernel, features=train_features, mean_function=mean, labels=train_labels, likelihood_model=lik) # create and train GP classifier, which uses Laplace approximation # gp = sg.machine('GaussianProcessClassification', inference_method=inf, labels=train_labels) gp = sg.gaussian_process("GaussianProcessClassification", inference_method=inf) gp.train() # get probabilities p(y*=1|x*) for each testing feature x* p_test = gp.get_probabilities(test_features) # create figure plt.title('Training examples, predictive probability and decision boundary') # plot training data plt.plot(X_train[0, np.argwhere(y_train == 1)], X_train[1, np.argwhere(y_train == 1)], 'ro') plt.plot(X_train[0, np.argwhere(y_train == -1)], X_train[1, np.argwhere(y_train == -1)], 'bo') # plot decision boundary plt.contour(x1, x2, np.reshape(p_test, (n_test, n_test)), levels=[0.5], colors='black') # plot probabilities plt.pcolor(x1, x2, np.reshape(p_test, (n_test, n_test))) # show color bar plt.colorbar() # show figure plt.show() if __name__ == '__main__': X_train, y_train = generate_toy_data() gaussian_process_binary_classification_laplace(X_train, y_train)
bsd-3-clause
fonnesbeck/geopandas
doc/source/conf.py
8
7967
# -*- coding: utf-8 -*- # # GeoPandas documentation build configuration file, created by # sphinx-quickstart on Tue Oct 15 08:08:14 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'GeoPandas' copyright = u'2013-2014, GeoPandas developers' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. d = {} try: execfile(os.path.join('..', '..', 'geopandas', 'version.py'), d) version = release = d['version'] except: # FIXME: This shouldn't be hardwired, but should be set one place only version = release = '0.2.0.dev' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # 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 patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # 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' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. if os.environ.get('READTHEDOCS', None) == 'True': html_theme = 'default' else: html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # 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 = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = 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 = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'GeoPandasdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'GeoPandas.tex', u'GeoPandas Documentation', u'Kelsey Jordahl', '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 # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'geopandas', u'GeoPandas Documentation', [u'Kelsey Jordahl'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'GeoPandas', u'GeoPandas Documentation', u'Kelsey Jordahl', 'GeoPandas', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
bsd-3-clause
paulscherrerinstitute/pshell
src/main/assembly/script/Lib/jeputils.py
1
4797
################################################################################################### # Facade to JEP: Embedded Python ################################################################################################### #Matplotlib won't work out of the box because it's default backend (Qt) uses signals, which only works in #the main thread. Ideally should find a fix, in order to mark the running thread as the main. #As a workaround, one can use the Tk backend: # #import matplotlib #matplotlib.use('TkAgg') #In principle just add JEP jar and library to the extensions folder. # #Alternatively on Linux: # Python 2: # - Add <python home>/lib/python3.X/site-packages/jep to LD_LIBRARY_PATH # - Add <python home>/lib/python3.X/site-packages/jep/jep-X.X.X.jar to the class path # #Python3: # - Add JEP library folder to LD_LIBRARY_PATH # - If using OpenJDK, add also python <python home>/lib folder to LD_LIBRARY_PATH # - Set LD_PRELOAD=<python home>/lib/libpython3.5m.so import sys import os import jep.Jep import jep.NDArray import java.lang.Thread from startup import to_array, get_context __jep = {} def __get_jep(): t = java.lang.Thread.currentThread() if not t in __jep: init_jep() return __jep[t] def __close_jep(): t = java.lang.Thread.currentThread() if t in __jep: __jep[t].close() def init_jep(): #TODO: Should do it but generates errors #__close_jep() j = jep.Jep(False) #Faster, but statements must be complete j.setInteractive(False) __jep[java.lang.Thread.currentThread()] = j j.eval("import sys") #sys.argv is not present in JEP and may be needed for certain modules (as Tkinter) j.eval("sys.argv = ['PShell']"); #Add standard script path to python path j.eval("sys.path.append('" + get_context().setup.getScriptPath() + "')") #Redirect stdout j.eval("class JepStdout:\n" + " def write(self, str):\n" + " self.str += str\n" + " def clear(self):\n" + " self.str = ''\n" + " def flush(self):\n" + " pass\n") j.eval("sys.stdout=JepStdout()"); j.eval("sys.stderr=JepStdout()"); j.eval("sys.stdout.clear()") j.eval("sys.stderr.clear()") #Import reload on Python 3 j.eval("try:\n" + " reload # Python 2.7\n" + "except NameError:\n" + " try:\n" + " from importlib import reload # Python 3.4+\n" + " except ImportError:\n" + " from imp import reload # Python 3.0 - 3.3\n") def __print_stdout(): j=__get_jep() output = j.getValue("sys.stdout.str") err = j.getValue("sys.stderr.str") j.eval("sys.stdout.clear()") j.eval("sys.stderr.clear()") if (output is not None) and len(output)>0: print output if (err is not None) and len(err)>0: print >> sys.stderr, err def run_jep(script_name, vars = {}): global __jep script = get_context().scriptManager.library.resolveFile(script_name) if script is None : script= os.path.abspath(script_name) j=__get_jep() for v in vars: j.set(v, vars[v]) try: j.runScript(script) finally: __print_stdout() def eval_jep(line): j=__get_jep() try: j.eval(line) finally: __print_stdout() def set_jep(var, value): j=__get_jep() j.set(var, value) def get_jep(var): j=__get_jep() return j.getValue(var) def call_jep(module, function, args = [], reload=False): j=__get_jep() if "/" in module: script = get_context().scriptManager.library.resolveFile(module) if "\\" in script: #Windows paths module_path = script[0:script.rfind("\\")] module = script[script.rfind("\\")+1:] else: #Linux paths module_path = script[0:script.rfind("/")] module = script[script.rfind("/")+1:] eval_jep("import sys") eval_jep("sys.path.append('" + module_path + "')") if module.endswith(".py"): module = module[0:-3] f = module+"_" + function+"_"+str(j.hashCode()) try: if reload: eval_jep("import " + module) eval_jep("reload(" + module+")") eval_jep("from " + module + " import " + function + " as " + f) ret = j.invoke(f, args) finally: __print_stdout() return ret #Converts pythonlist or Java array to numpy array def to_npa(data, dimensions = None, type = None): data = to_array(data,'d' if type is None else type) return jep.NDArray(data, dimensions)
gpl-3.0
bearing/dosenet-analysis
time_binning.py
1
4929
"""This file takes a URL as a command line argument and saves the data from the URL, then it bins the data by time and produces consistent timestamps for the data points. """ __author__ = 'Sagnik Bhattacharya (github.com/sagnibak)' import numpy as np import pandas as pd import argparse from time import time from datetime import datetime from math import isnan import os START_TIME = 1447986433 # (not) HARD-CODED VALUE TIME_INTERVAL = 2400 # seconds (40 minutes), (not) HARD-CODED VALUE class Bin(object): def __init__(self, start_time, end_time, items=None): self.start_time = start_time self.end_time = end_time if items: self.items = list(items) else: self.items = None def store(self, value): if isnan(value): value = 0. if self.items: self.items.append(value) else: self.items = [value] def average(self): if not self.items: return float('nan') return sum(self.items) / len(self.items) def has_time(self, time_): """ >>> a = Bin(100., 150.) >>> a.has_time(22) False >>> a.has_time(100.) True >>> a.has_time(149.999) True >>> a.has_time(150.) False >>> a.has_time(200) False """ return self.start_time <= time_ < self.end_time def to_list(self): """ >>> a = Bin(100, 150, [100., 200., 250, 200., 0.]) >>> a.to_list() [100, 150.0] >>> a.store(float('nan')) >>> a.to_list() [100, 125.0] """ return [self.start_time, self.average()] def __str__(self): return f'Start time: {self.start_time} | End time: {self.end_time} | Items: {self.items}' def store_in_bins(data: np.array): """Averages data over `time_interval` and makes all timestamps uniform. :param data: Nx2 dimensional Numpy array with N data points and accompanying unix timestamps :return: Mx2 dimensional Pandas DataFrame with M binned data points and accompanying unix timestamps """ n_bins = (int(time()) - START_TIME) // TIME_INTERVAL bins = np.empty((n_bins,), dtype=Bin) result_bins = np.empty((n_bins, 2), dtype=np.float) # make bins and store the values in the right bins last_idx = data.shape[0] - 1 # this makes the algorithm run in O(n) time instead of O(n^2) for i in range(n_bins): # loops M times bins[i] = Bin(start_time=START_TIME + i * TIME_INTERVAL, end_time=START_TIME + (i + 1) * TIME_INTERVAL) while bins[i].has_time(data[last_idx, 0]): bins[i].store(data[last_idx, 1]) last_idx -= 1 for idx, time_bin in enumerate(bins): result_bins[idx] = time_bin.to_list() df = pd.DataFrame(result_bins, columns=['unix_time', 'value']) return df def run_binner(url: str, col_name: str): try: df = pd.read_csv(url, sep=',') except ValueError as ve: if isinstance(url, pd.DataFrame): df = url else: raise ValueError('Cannot handle this data!') timestamps = df['deviceTime_unix'].astype(float) data = df[col_name].astype(float) df = pd.DataFrame(data={'timestamps': timestamps, 'data': data}) # make sure dataframe is sorted in descending order dg = df.sort_values(by='timestamps', axis=0, ascending=False) return store_in_bins(dg.values) def main(): global START_TIME, TIME_INTERVAL # command line arguments parser = argparse.ArgumentParser(description='Download data and bin it by time.') parser.add_argument('url', help='URL where you want to get data from') parser.add_argument('-c', '--col_name', help='name of the column from where data needs to be binned') parser.add_argument('-s', '--save_dir', help='directory where binned data should be saved') parser.add_argument('-i', '--time_interval', help='time interval to average data over', type=int) parser.add_argument('-t', '--start_time', help='date and to begin collecting data from (24-hour time format)', metavar='YYYY-MM-DD HH:mm:ss', type=str) args = parser.parse_args() print(f'Getting data from {args.url}') if not args.save_dir: args.save_dir = 'binned_data' print(f'Binned data will be saved in the directory {args.save_dir}') if args.time_interval: TIME_INTERVAL = args.time_interval if args.start_time: START_TIME = int(datetime.strptime(args.start_time, '%Y-%m-%d %H:%M:%S').timestamp()) df_to_save = run_binner(args.url, args.col_name) df_to_save.to_csv(os.path.join(args.save_dir, f'ws_data_{args.col_name}_{TIME_INTERVAL}.csv'), index=False, na_rep='nan') if __name__ == '__main__': main()
mit
TaxIPP-Life/Til
til/utilisations/Compar_Destinie_Patrimoine/run.py
2
4828
# -*- coding:utf-8 -*- ''' Ce programme compare la base Destinie et la base générée directement à partir de l'enquête patrimoine. Les tables issues de Destinie et de Patrimoine doivent déjà avoir été créées - data//data//Destinie//Patrimoine.py et data//data//Destinie//Destinie.py Pour Patrimoine, ça ne sert à rien de duppliquer pour comparer donc on part de la version Patrimoine_0 ''' import pdb from pgm.CONFIG import path_model from pandas import read_hdf, HDFStore import tables import numpy as np from scipy.stats import mstats # retourne une ficher stat qui permet la comparaison entre deux tables # d'abord on récupéère les stat de chaque table, # ensuite on fait la différence. list_var_num = ['agem','sali','rsti','choi'] list_var_qual = ['civilstate','workstate','civilstate','findet','quimen','quifoy','sexe'] pat = read_hdf(path_model + 'Patrimoine_400.h5', 'entities//person') dest = read_hdf(path_model + 'Destinie.h5', 'entities//person') table = pat table1 = 'Patrimoine_300' table2 = 'Destinie' def quantile10(x): return x.quantile(0.1) def quantile25(x): return x.quantile(0.25) def quantile50(x): return x.quantile(0.5) def quantile75(x): return x.quantile(0.75) stat_on_numeric = [np.mean, np.std, np.min, np.max, quantile10, quantile25, quantile50, quantile75] #I don't know how to add some lambda function class Comparaison_bases(object): ''' Organisation de la comparaison des deux bases de données Les deux bases ont des rôles symétriques, on présente toujours la différence de la seconde moins la premiere ''' def __init__(self, table1='', table2=''): self.name_tables = [table1, table2] self.tables = None self.stat_on_numeric = [np.mean, np.std, np.min, np.max, quantile10, quantile25, quantile50, quantile75] def load(self): self.tables = [] for name_table in self.name_tables: table = read_hdf(path_model + name_table + '.h5', 'entities//person') table['Total'] = 'Total' self.tables += [table] def get_stat_num(self, var_num, sous_cat=None): ''' retourne les stats sur des variables numérique (ou pseudo numériques) - les variables sont celle de list_var_num - les stats sont celle de la fonction get_stat_on_numeric (que l'on pourrait mettre en attribut de la class) - le résultats est une liste de deux series, une pour chaque table (on a une liste parce qu'on veut garder un ordre pour la différence - le dictionnaire de chaque table a une entrée par variable et comme valeur le resultat de tous les tests ''' if sous_cat is None: sous_cat = ['Total'] tab0, tab1 = self.tables return [tab0[[var_num] + sous_cat].groupby(sous_cat).agg(stat_on_numeric), tab1[[var_num] + sous_cat].groupby(sous_cat).agg(stat_on_numeric)] def get_stat_qual(self, var_qual, sous_cat=None): ''' retourne les stats sur des variables qualitative, en fait la fréquence - les variables sont celle de list_var_qual - le résultats est un dictionnaire avec une clé pour chaque variable et comme valeur une liste de deux tables qui sont les fréquences de la variable. ''' if sous_cat is None: sous_cat = ['Total'] tab0, tab1 = self.tables gp0 = tab0[[var_qual] + sous_cat].groupby(sous_cat) gp1 = tab1[[var_qual] + sous_cat].groupby(sous_cat) value0 = gp0[var_qual].value_counts() value0 = 100*value0/value0.sum() value1 = gp1[var_qual].value_counts() value1 = 100*value1/value1.sum() return value0, value1 def get_diff_num(self, var_num, sous_cat=None): ''' sort dans un dictionnaire la différence entre les statistiques sur les deux tables''' print var_num stat0, stat1 = self.get_stat_num(var_num, sous_cat) return stat1 - stat0 def get_diff_qual(self, var_qual, sous_cat=None): ''' sort dans un dictionnaire la différence entre les statistiques sur les deux tables''' stat = self.get_stat_qual(var_qual, sous_cat) return stat[1] - stat[0] if __name__ == '__main__': cc = Comparaison_bases('Patrimoine_400','Destinie') cc.load() tab0, tab1 = cc.tables for var_num in list_var_num: if var_num not in ['sexe']: print cc.get_diff_num(var_num, ['sexe']) for var_qual in list_var_qual: if var_qual not in ['sexe']: print var_qual print cc.get_diff_qual(var_qual, ['sexe']) self = cc cc.get_stat_qual('findet', ['sexe']) pdb.set_trace()
gpl-3.0
schen496/auditory-hallucinations
extract_image_features/old_code/audio_extractionUnitTest.py
1
2648
from skimage import transform, color, io import scipy.io as sio import skvideo.io import os import numpy as np import imageio import matplotlib.pyplot as plt import re from skimage import transform, color, io import warnings from tqdm import tqdm import h5py import pickle ########### ### LOADING VIDEOS ### video_dir = "/Volumes/SAMSUNG_SSD_256GB/ADV_CV/2-25_VIDAUD/EXPORTS" video_files = [os.path.join(video_dir, file_i) for file_i in os.listdir(video_dir) if file_i.endswith('.mp4')] num_videos = len(video_files) print("num_videos: ", num_videos) ############ ### LOADING AUDIO ### audio_feature_dir = "../audio_vectors" audio_f_files = [os.path.join(audio_feature_dir, file_i) for file_i in os.listdir(audio_feature_dir) if file_i.endswith('.mat')] num_audio_f = len(audio_f_files) print("num_audio_f: ", num_audio_f) ########### ### READING AUDIO VECTORS audio_f_file = audio_f_files[3] # Test with just one audio feature vector, and find all the corresponding movies mat_contents = sio.loadmat(audio_f_file) # 18 x n-2 audio_vectors = mat_contents['audio_vectors'] audio_vector_length = audio_vectors.shape[1] #print(audio_f_files[0]) print("audio_vectors.shape: ", audio_vectors.shape) # Extract the file prefix using regular expressions start = audio_f_file.find('seq') end = audio_f_file.find("_audio", start) audio_prefix = audio_f_file[start:end] ########## ### READING GREYSCALE VIDEO vid_extern_dest = '/Volumes/SAMSUNG_SSD_256GB/ADV_CV/videos_BW/' file_name = vid_extern_dest + audio_prefix + '_vid_BW.h5' with h5py.File(file_name, 'r') as hf: print("Reading data from file..") video_data = hf['videos_BW'][:] print("video_data.shape:", video_data.shape) ### TESTING this method def createAudioVectorDataset(audio_vectors, dataX_shape): # audio_vectors: a numpy array of the audio vector (18,8378) # dataX_shape: shape of the space time image (1, 8377, 224, 224, 3) (num_videos, num_frames, frame_h, frame_w, channels) = dataX_shape final_audio_vectors = np.zeros((num_videos, num_frames, audio_vectors.shape[0])) # (1, 18, 8377) single_audio_vector = audio_vectors[:, 0:num_frames] # Extract the corresponding audio vector, produces (18, 8377) from (18, 8379) for i in range(num_videos): final_audio_vectors[i] = single_audio_vector.T # Assign the audio_vector to each video angle in idx=0 , (1, 8377, 224, 224, 3). Need to transpose it here. return final_audio_vectors final_audio_vectors = createAudioVectorDataset(audio_vectors, (1, 8377, 224, 224, 3)) print ("final_audio_vectors.shape:", final_audio_vectors.shape)
apache-2.0
ebilionis/py-best
papers/gpcorr/ko_run_smc.py
1
1800
""" Train the GP correlations model for KO with MCMC. """ import sys sys.path.insert(0, '../..') import numpy as np from examples.ko import KOSolver import model import best import pymc import matplotlib.pyplot as plt import mpi4py.MPI as mpi import cPickle as pickle if __name__ == '__main__': # Set the sampling parameters k = 1 # Number of dimensions n_t = 20 # Number of time steps num_samples = 20 # Number of samples num_particles = 100 num_mcmc = 1 # Initialize the solver solver = KOSolver(k=k, n_t=n_t) # Collect data x = best.design.latin_center(num_samples, k) Y = [] for i in range(num_samples): Y.append(solver(x[i, :])) X = (x, solver.X_fixed[0]) H = tuple([np.ones((x.shape[0], 1)) for x in X]) Y = np.vstack(Y) # Save the data for later use data_file = 'ko_data_s=%d.pickle' % num_samples with open(data_file, 'wb') as fd: pickle.dump((X, H, Y), fd, pickle.HIGHEST_PROTOCOL) cgp_model = model.make_model(X, Y) smc_sampler = best.smc.SMC(cgp_model, num_particles=num_particles, num_mcmc=num_mcmc, verbose=1, gamma_is_an_exponent=True, mpi=mpi) smc_sampler.initialize(0.) pa = smc_sampler.get_particle_approximation() smc_sampler.move_to(1.) pa = smc_sampler.get_particle_approximation() # dump the result to a file to process later gpa = pa.allgather() if mpi.COMM_WORLD.Get_rank() == 0: out_file = 'ko_smc_s=%d_p=%d_m=%d.pickle' %(num_samples, num_particles, num_mcmc) with open(out_file, 'wb') as fd: pickle.dump(gpa, fd, pickle.HIGHEST_PROTOCOL)
lgpl-3.0
ueshin/apache-spark
python/pyspark/pandas/indexes/datetimes.py
15
24988
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import datetime from functools import partial from typing import Any, Optional, Union, cast, no_type_check import pandas as pd from pandas.api.types import is_hashable from pandas.tseries.offsets import DateOffset from pyspark._globals import _NoValue from pyspark import pandas as ps from pyspark.pandas.indexes.base import Index from pyspark.pandas.missing.indexes import MissingPandasLikeDatetimeIndex from pyspark.pandas.series import Series, first_series from pyspark.pandas.utils import verify_temp_column_name class DatetimeIndex(Index): """ Immutable ndarray-like of datetime64 data. Parameters ---------- data : array-like (1-dimensional), optional Optional datetime-like data to construct index with. freq : str or pandas offset object, optional One of pandas date offset strings or corresponding objects. The string 'infer' can be passed in order to set the frequency of the index as the inferred frequency upon creation. normalize : bool, default False Normalize start/end dates to midnight before generating date range. closed : {'left', 'right'}, optional Set whether to include `start` and `end` that are on the boundary. The default includes boundary points on either end. ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise' When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the `ambiguous` parameter dictates how ambiguous times should be handled. - 'infer' will attempt to infer fall dst-transition hours based on order - bool-ndarray where True signifies a DST time, False signifies a non-DST time (note that this flag is only applicable for ambiguous times) - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times. dayfirst : bool, default False If True, parse dates in `data` with the day first order. yearfirst : bool, default False If True parse dates in `data` with the year first order. dtype : numpy.dtype or str, default None Note that the only NumPy dtype allowed is ‘datetime64[ns]’. copy : bool, default False Make a copy of input ndarray. name : label, default None Name to be stored in the index. See Also -------- Index : The base pandas Index type. to_datetime : Convert argument to datetime. Examples -------- >>> ps.DatetimeIndex(['1970-01-01', '1970-01-01', '1970-01-01']) DatetimeIndex(['1970-01-01', '1970-01-01', '1970-01-01'], dtype='datetime64[ns]', freq=None) From a Series: >>> from datetime import datetime >>> s = ps.Series([datetime(2021, 3, 1), datetime(2021, 3, 2)], index=[10, 20]) >>> ps.DatetimeIndex(s) DatetimeIndex(['2021-03-01', '2021-03-02'], dtype='datetime64[ns]', freq=None) From an Index: >>> idx = ps.DatetimeIndex(['1970-01-01', '1970-01-01', '1970-01-01']) >>> ps.DatetimeIndex(idx) DatetimeIndex(['1970-01-01', '1970-01-01', '1970-01-01'], dtype='datetime64[ns]', freq=None) """ @no_type_check def __new__( cls, data=None, freq=_NoValue, normalize=False, closed=None, ambiguous="raise", dayfirst=False, yearfirst=False, dtype=None, copy=False, name=None, ) -> "DatetimeIndex": if not is_hashable(name): raise TypeError("Index.name must be a hashable type") if isinstance(data, (Series, Index)): if dtype is None: dtype = "datetime64[ns]" return cast(DatetimeIndex, Index(data, dtype=dtype, copy=copy, name=name)) kwargs = dict( data=data, normalize=normalize, closed=closed, ambiguous=ambiguous, dayfirst=dayfirst, yearfirst=yearfirst, dtype=dtype, copy=copy, name=name, ) if freq is not _NoValue: kwargs["freq"] = freq return cast(DatetimeIndex, ps.from_pandas(pd.DatetimeIndex(**kwargs))) def __getattr__(self, item: str) -> Any: if hasattr(MissingPandasLikeDatetimeIndex, item): property_or_func = getattr(MissingPandasLikeDatetimeIndex, item) if isinstance(property_or_func, property): return property_or_func.fget(self) # type: ignore else: return partial(property_or_func, self) raise AttributeError("'DatetimeIndex' object has no attribute '{}'".format(item)) # Properties @property def year(self) -> Index: """ The year of the datetime. """ return Index(self.to_series().dt.year) @property def month(self) -> Index: """ The month of the timestamp as January = 1 December = 12. """ return Index(self.to_series().dt.month) @property def day(self) -> Index: """ The days of the datetime. """ return Index(self.to_series().dt.day) @property def hour(self) -> Index: """ The hours of the datetime. """ return Index(self.to_series().dt.hour) @property def minute(self) -> Index: """ The minutes of the datetime. """ return Index(self.to_series().dt.minute) @property def second(self) -> Index: """ The seconds of the datetime. """ return Index(self.to_series().dt.second) @property def microsecond(self) -> Index: """ The microseconds of the datetime. """ return Index(self.to_series().dt.microsecond) @property def week(self) -> Index: """ The week ordinal of the year. """ return Index(self.to_series().dt.week) @property def weekofyear(self) -> Index: return Index(self.to_series().dt.weekofyear) weekofyear.__doc__ = week.__doc__ @property def dayofweek(self) -> Index: """ The day of the week with Monday=0, Sunday=6. Return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6. This method is available on both Series with datetime values (using the `dt` accessor) or DatetimeIndex. Returns ------- Series or Index Containing integers indicating the day number. See Also -------- Series.dt.dayofweek : Alias. Series.dt.weekday : Alias. Series.dt.day_name : Returns the name of the day of the week. Examples -------- >>> idx = ps.date_range('2016-12-31', '2017-01-08', freq='D') >>> idx.dayofweek Int64Index([5, 6, 0, 1, 2, 3, 4, 5, 6], dtype='int64') """ return Index(self.to_series().dt.dayofweek) @property def day_of_week(self) -> Index: return self.dayofweek day_of_week.__doc__ = dayofweek.__doc__ @property def weekday(self) -> Index: return Index(self.to_series().dt.weekday) weekday.__doc__ = dayofweek.__doc__ @property def dayofyear(self) -> Index: """ The ordinal day of the year. """ return Index(self.to_series().dt.dayofyear) @property def day_of_year(self) -> Index: return self.dayofyear day_of_year.__doc__ = dayofyear.__doc__ @property def quarter(self) -> Index: """ The quarter of the date. """ return Index(self.to_series().dt.quarter) @property def is_month_start(self) -> Index: """ Indicates whether the date is the first day of the month. Returns ------- Index Returns a Index with boolean values See Also -------- is_month_end : Return a boolean indicating whether the date is the last day of the month. Examples -------- >>> idx = ps.date_range("2018-02-27", periods=3) >>> idx.is_month_start Index([False, False, True], dtype='object') """ return Index(self.to_series().dt.is_month_start) @property def is_month_end(self) -> Index: """ Indicates whether the date is the last day of the month. Returns ------- Index Returns a Index with boolean values. See Also -------- is_month_start : Return a boolean indicating whether the date is the first day of the month. Examples -------- >>> idx = ps.date_range("2018-02-27", periods=3) >>> idx.is_month_end Index([False, True, False], dtype='object') """ return Index(self.to_series().dt.is_month_end) @property def is_quarter_start(self) -> Index: """ Indicator for whether the date is the first day of a quarter. Returns ------- is_quarter_start : Index Returns an Index with boolean values. See Also -------- quarter : Return the quarter of the date. is_quarter_end : Similar property for indicating the quarter start. Examples -------- >>> idx = ps.date_range('2017-03-30', periods=4) >>> idx.is_quarter_start Index([False, False, True, False], dtype='object') """ return Index(self.to_series().dt.is_quarter_start) @property def is_quarter_end(self) -> Index: """ Indicator for whether the date is the last day of a quarter. Returns ------- is_quarter_end : Index Returns an Index with boolean values. See Also -------- quarter : Return the quarter of the date. is_quarter_start : Similar property indicating the quarter start. Examples -------- >>> idx = ps.date_range('2017-03-30', periods=4) >>> idx.is_quarter_end Index([False, True, False, False], dtype='object') """ return Index(self.to_series().dt.is_quarter_end) @property def is_year_start(self) -> Index: """ Indicate whether the date is the first day of a year. Returns ------- Index Returns an Index with boolean values. See Also -------- is_year_end : Similar property indicating the last day of the year. Examples -------- >>> idx = ps.date_range("2017-12-30", periods=3) >>> idx.is_year_start Index([False, False, True], dtype='object') """ return Index(self.to_series().dt.is_year_start) @property def is_year_end(self) -> Index: """ Indicate whether the date is the last day of the year. Returns ------- Index Returns an Index with boolean values. See Also -------- is_year_start : Similar property indicating the start of the year. Examples -------- >>> idx = ps.date_range("2017-12-30", periods=3) >>> idx.is_year_end Index([False, True, False], dtype='object') """ return Index(self.to_series().dt.is_year_end) @property def is_leap_year(self) -> Index: """ Boolean indicator if the date belongs to a leap year. A leap year is a year, which has 366 days (instead of 365) including 29th of February as an intercalary day. Leap years are years which are multiples of four with the exception of years divisible by 100 but not by 400. Returns ------- Index Booleans indicating if dates belong to a leap year. Examples -------- >>> idx = ps.date_range("2012-01-01", "2015-01-01", freq="Y") >>> idx.is_leap_year Index([True, False, False], dtype='object') """ return Index(self.to_series().dt.is_leap_year) @property def daysinmonth(self) -> Index: """ The number of days in the month. """ return Index(self.to_series().dt.daysinmonth) @property def days_in_month(self) -> Index: return Index(self.to_series().dt.days_in_month) days_in_month.__doc__ = daysinmonth.__doc__ # Methods def ceil(self, freq: Union[str, DateOffset], *args: Any, **kwargs: Any) -> "DatetimeIndex": """ Perform ceil operation on the data to the specified freq. Parameters ---------- freq : str or Offset The frequency level to ceil the index to. Must be a fixed frequency like 'S' (second) not 'ME' (month end). Returns ------- DatetimeIndex Raises ------ ValueError if the `freq` cannot be converted. Examples -------- >>> rng = ps.date_range('1/1/2018 11:59:00', periods=3, freq='min') >>> rng.ceil('H') # doctest: +NORMALIZE_WHITESPACE DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00', '2018-01-01 13:00:00'], dtype='datetime64[ns]', freq=None) """ disallow_nanoseconds(freq) return DatetimeIndex(self.to_series().dt.ceil(freq, *args, **kwargs)) def floor(self, freq: Union[str, DateOffset], *args: Any, **kwargs: Any) -> "DatetimeIndex": """ Perform floor operation on the data to the specified freq. Parameters ---------- freq : str or Offset The frequency level to floor the index to. Must be a fixed frequency like 'S' (second) not 'ME' (month end). Returns ------- DatetimeIndex Raises ------ ValueError if the `freq` cannot be converted. Examples -------- >>> rng = ps.date_range('1/1/2018 11:59:00', periods=3, freq='min') >>> rng.floor("H") # doctest: +NORMALIZE_WHITESPACE DatetimeIndex(['2018-01-01 11:00:00', '2018-01-01 12:00:00', '2018-01-01 12:00:00'], dtype='datetime64[ns]', freq=None) """ disallow_nanoseconds(freq) return DatetimeIndex(self.to_series().dt.floor(freq, *args, **kwargs)) def round(self, freq: Union[str, DateOffset], *args: Any, **kwargs: Any) -> "DatetimeIndex": """ Perform round operation on the data to the specified freq. Parameters ---------- freq : str or Offset The frequency level to round the index to. Must be a fixed frequency like 'S' (second) not 'ME' (month end). Returns ------- DatetimeIndex Raises ------ ValueError if the `freq` cannot be converted. Examples -------- >>> rng = ps.date_range('1/1/2018 11:59:00', periods=3, freq='min') >>> rng.round("H") # doctest: +NORMALIZE_WHITESPACE DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00', '2018-01-01 12:00:00'], dtype='datetime64[ns]', freq=None) """ disallow_nanoseconds(freq) return DatetimeIndex(self.to_series().dt.round(freq, *args, **kwargs)) def month_name(self, locale: Optional[str] = None) -> Index: """ Return the month names of the DatetimeIndex with specified locale. Parameters ---------- locale : str, optional Locale determining the language in which to return the month name. Default is English locale. Returns ------- Index Index of month names. Examples -------- >>> idx = ps.date_range(start='2018-01', freq='M', periods=3) >>> idx.month_name() Index(['January', 'February', 'March'], dtype='object') """ return Index(self.to_series().dt.month_name(locale)) def day_name(self, locale: Optional[str] = None) -> Index: """ Return the day names of the series with specified locale. Parameters ---------- locale : str, optional Locale determining the language in which to return the day name. Default is English locale. Returns ------- Index Index of day names. Examples -------- >>> idx = ps.date_range(start='2018-01-01', freq='D', periods=3) >>> idx.day_name() Index(['Monday', 'Tuesday', 'Wednesday'], dtype='object') """ return Index(self.to_series().dt.day_name(locale)) def normalize(self) -> "DatetimeIndex": """ Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the ``.dt`` accessor. Returns ------- DatetimeIndex The same type as the original data. See Also -------- floor : Floor the series to the specified freq. ceil : Ceil the series to the specified freq. round : Round the series to the specified freq. Examples -------- >>> idx = ps.date_range(start='2014-08-01 10:00', freq='H', periods=3) >>> idx.normalize() DatetimeIndex(['2014-08-01', '2014-08-01', '2014-08-01'], dtype='datetime64[ns]', freq=None) """ return DatetimeIndex(self.to_series().dt.normalize()) def strftime(self, date_format: str) -> Index: """ Convert to a string Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in python string format doc. Parameters ---------- date_format : str Date format string (example: "%%Y-%%m-%%d"). Returns ------- Index Index of formatted strings. See Also -------- normalize : Return series with times to midnight. round : Round the series to the specified freq. floor : Floor the series to the specified freq. Examples -------- >>> idx = ps.date_range(pd.Timestamp("2018-03-10 09:00"), periods=3, freq='s') >>> idx.strftime('%B %d, %Y, %r') # doctest: +NORMALIZE_WHITESPACE Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM', 'March 10, 2018, 09:00:02 AM'], dtype='object') """ return Index(self.to_series().dt.strftime(date_format)) def indexer_between_time( self, start_time: Union[datetime.time, str], end_time: Union[datetime.time, str], include_start: bool = True, include_end: bool = True, ) -> Index: """ Return index locations of values between particular times of day (example: 9:00-9:30AM). Parameters ---------- start_time, end_time : datetime.time, str Time passed either as object (datetime.time) or as string in appropriate format ("%H:%M", "%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p","%I%M%S%p"). include_start : bool, default True include_end : bool, default True Returns ------- values_between_time : Index of integers Examples -------- >>> psidx = ps.date_range("2000-01-01", periods=3, freq="T") >>> psidx # doctest: +NORMALIZE_WHITESPACE DatetimeIndex(['2000-01-01 00:00:00', '2000-01-01 00:01:00', '2000-01-01 00:02:00'], dtype='datetime64[ns]', freq=None) >>> psidx.indexer_between_time("00:01", "00:02").sort_values() Int64Index([1, 2], dtype='int64') >>> psidx.indexer_between_time("00:01", "00:02", include_end=False) Int64Index([1], dtype='int64') >>> psidx.indexer_between_time("00:01", "00:02", include_start=False) Int64Index([2], dtype='int64') """ @no_type_check def pandas_between_time(pdf) -> ps.DataFrame[int]: return pdf.between_time(start_time, end_time, include_start, include_end) psdf = self.to_frame()[[]] id_column_name = verify_temp_column_name(psdf, "__id_column__") psdf = psdf.pandas_on_spark.attach_id_column("distributed-sequence", id_column_name) with ps.option_context("compute.default_index_type", "distributed"): # The attached index in the statement below will be dropped soon, # so we enforce “distributed” default index type psdf = psdf.pandas_on_spark.apply_batch(pandas_between_time) return ps.Index(first_series(psdf).rename(self.name)) def indexer_at_time(self, time: Union[datetime.time, str], asof: bool = False) -> Index: """ Return index locations of values at particular time of day (example: 9:30AM). Parameters ---------- time : datetime.time or str Time passed in either as object (datetime.time) or as string in appropriate format ("%H:%M", "%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p", "%I%M%S%p"). Returns ------- values_at_time : Index of integers Examples -------- >>> psidx = ps.date_range("2000-01-01", periods=3, freq="T") >>> psidx # doctest: +NORMALIZE_WHITESPACE DatetimeIndex(['2000-01-01 00:00:00', '2000-01-01 00:01:00', '2000-01-01 00:02:00'], dtype='datetime64[ns]', freq=None) >>> psidx.indexer_at_time("00:00") Int64Index([0], dtype='int64') >>> psidx.indexer_at_time("00:01") Int64Index([1], dtype='int64') """ if asof: raise NotImplementedError("'asof' argument is not supported") @no_type_check def pandas_at_time(pdf) -> ps.DataFrame[int]: return pdf.at_time(time, asof) psdf = self.to_frame()[[]] id_column_name = verify_temp_column_name(psdf, "__id_column__") psdf = psdf.pandas_on_spark.attach_id_column("distributed-sequence", id_column_name) with ps.option_context("compute.default_index_type", "distributed"): # The attached index in the statement below will be dropped soon, # so we enforce “distributed” default index type psdf = psdf.pandas_on_spark.apply_batch(pandas_at_time) return ps.Index(first_series(psdf).rename(self.name)) def disallow_nanoseconds(freq: Union[str, DateOffset]) -> None: if freq in ["N", "ns"]: raise ValueError("nanoseconds is not supported") def _test() -> None: import os import doctest import sys from pyspark.sql import SparkSession import pyspark.pandas.indexes.datetimes os.chdir(os.environ["SPARK_HOME"]) globs = pyspark.pandas.indexes.datetimes.__dict__.copy() globs["ps"] = pyspark.pandas spark = ( SparkSession.builder.master("local[4]") .appName("pyspark.pandas.indexes.datetimes tests") .getOrCreate() ) (failure_count, test_count) = doctest.testmod( pyspark.pandas.indexes.datetimes, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE, ) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
apache-2.0
nan86150/ImageFusion
lib/python2.7/site-packages/mpl_toolkits/axes_grid1/colorbar.py
8
27927
''' Colorbar toolkit with two classes and a function: :class:`ColorbarBase` the base class with full colorbar drawing functionality. It can be used as-is to make a colorbar for a given colormap; a mappable object (e.g., image) is not needed. :class:`Colorbar` the derived class for use with images or contour plots. :func:`make_axes` a function for resizing an axes and adding a second axes suitable for a colorbar The :meth:`~matplotlib.figure.Figure.colorbar` method uses :func:`make_axes` and :class:`Colorbar`; the :func:`~matplotlib.pyplot.colorbar` function is a thin wrapper over :meth:`~matplotlib.figure.Figure.colorbar`. ''' from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import xrange, zip import numpy as np import matplotlib as mpl import matplotlib.colors as colors import matplotlib.cm as cm from matplotlib import docstring import matplotlib.ticker as ticker import matplotlib.cbook as cbook import matplotlib.collections as collections import matplotlib.contour as contour from matplotlib.path import Path from matplotlib.patches import PathPatch from matplotlib.transforms import Bbox make_axes_kw_doc = ''' ============= ==================================================== Property Description ============= ==================================================== *orientation* vertical or horizontal *fraction* 0.15; fraction of original axes to use for colorbar *pad* 0.05 if vertical, 0.15 if horizontal; fraction of original axes between colorbar and new image axes *shrink* 1.0; fraction by which to shrink the colorbar *aspect* 20; ratio of long to short dimensions ============= ==================================================== ''' colormap_kw_doc = ''' =========== ==================================================== Property Description =========== ==================================================== *extend* [ 'neither' | 'both' | 'min' | 'max' ] If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. *spacing* [ 'uniform' | 'proportional' ] Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval. *ticks* [ None | list of ticks | Locator object ] If None, ticks are determined automatically from the input. *format* [ None | format string | Formatter object ] If None, the :class:`~matplotlib.ticker.ScalarFormatter` is used. If a format string is given, e.g., '%.3f', that is used. An alternative :class:`~matplotlib.ticker.Formatter` object may be given instead. *drawedges* [ False | True ] If true, draw lines at color boundaries. =========== ==================================================== The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances. ============ =================================================== Property Description ============ =================================================== *boundaries* None or a sequence *values* None or a sequence which must be of length 1 less than the sequence of *boundaries*. For each region delimited by adjacent entries in *boundaries*, the color mapped to the corresponding value in values will be used. ============ =================================================== ''' colorbar_doc = ''' Add a colorbar to a plot. Function signatures for the :mod:`~matplotlib.pyplot` interface; all but the first are also method signatures for the :meth:`~matplotlib.figure.Figure.colorbar` method:: colorbar(**kwargs) colorbar(mappable, **kwargs) colorbar(mappable, cax=cax, **kwargs) colorbar(mappable, ax=ax, **kwargs) arguments: *mappable* the :class:`~matplotlib.image.Image`, :class:`~matplotlib.contour.ContourSet`, etc. to which the colorbar applies; this argument is mandatory for the :meth:`~matplotlib.figure.Figure.colorbar` method but optional for the :func:`~matplotlib.pyplot.colorbar` function, which sets the default to the current image. keyword arguments: *cax* None | axes object into which the colorbar will be drawn *ax* None | parent axes object from which space for a new colorbar axes will be stolen Additional keyword arguments are of two kinds: axes properties: %s colorbar properties: %s If *mappable* is a :class:`~matplotlib.contours.ContourSet`, its *extend* kwarg is included automatically. Note that the *shrink* kwarg provides a simple way to keep a vertical colorbar, for example, from being taller than the axes of the mappable to which the colorbar is attached; but it is a manual method requiring some trial and error. If the colorbar is too tall (or a horizontal colorbar is too wide) use a smaller value of *shrink*. For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs. It is known that some vector graphics viewer (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers not matplotlib. As a workaround the colorbar can be rendered with overlapping segments:: cbar = colorbar() cbar.solids.set_edgecolor("face") draw() However this has negative consequences in other circumstances. Particularly with semi transparent images (alpha < 1) and colorbar extensions and is not enabled by default see (issue #1188). returns: :class:`~matplotlib.colorbar.Colorbar` instance; see also its base class, :class:`~matplotlib.colorbar.ColorbarBase`. Call the :meth:`~matplotlib.colorbar.ColorbarBase.set_label` method to label the colorbar. The transData of the *cax* is adjusted so that the limits in the longest axis actually corresponds to the limits in colorbar range. On the other hand, the shortest axis has a data limits of [1,2], whose unconventional value is to prevent underflow when log scale is used. ''' % (make_axes_kw_doc, colormap_kw_doc) docstring.interpd.update(colorbar_doc=colorbar_doc) class CbarAxesLocator(object): """ CbarAxesLocator is a axes_locator for colorbar axes. It adjust the position of the axes to make a room for extended ends, i.e., the extended ends are located outside the axes area. """ def __init__(self, locator=None, extend="neither", orientation="vertical"): """ *locator* : the bbox returned from the locator is used as a initial axes location. If None, axes.bbox is used. *extend* : same as in ColorbarBase *orientation* : same as in ColorbarBase """ self._locator = locator self.extesion_fraction = 0.05 self.extend = extend self.orientation = orientation def get_original_position(self, axes, renderer): """ get the original position of the axes. """ if self._locator is None: bbox = axes.get_position(original=True) else: bbox = self._locator(axes, renderer) return bbox def get_end_vertices(self): """ return a tuple of two vertices for the colorbar extended ends. The first vertices is for the minimum end, and the second is for the maximum end. """ # Note that concatenating two vertices needs to make a # vertices for the frame. extesion_fraction = self.extesion_fraction corx = extesion_fraction*2. cory = 1./(1. - corx) x1, y1, w, h = 0, 0, 1, 1 x2, y2 = x1 + w, y1 + h dw, dh = w*extesion_fraction, h*extesion_fraction*cory if self.extend in ["min", "both"]: bottom = [(x1, y1), (x1+w/2., y1-dh), (x2, y1)] else: bottom = [(x1, y1), (x2, y1)] if self.extend in ["max", "both"]: top = [(x2, y2), (x1+w/2., y2+dh), (x1, y2)] else: top = [(x2, y2), (x1, y2)] if self.orientation == "horizontal": bottom = [(y,x) for (x,y) in bottom] top = [(y,x) for (x,y) in top] return bottom, top def get_path_patch(self): """ get the path for axes patch """ end1, end2 = self.get_end_vertices() verts = [] + end1 + end2 + end1[:1] return Path(verts) def get_path_ends(self): """ get the paths for extended ends """ end1, end2 = self.get_end_vertices() return Path(end1), Path(end2) def __call__(self, axes, renderer): """ Return the adjusted position of the axes """ bbox0 = self.get_original_position(axes, renderer) bbox = bbox0 x1, y1, w, h = bbox.bounds extesion_fraction = self.extesion_fraction dw, dh = w*extesion_fraction, h*extesion_fraction if self.extend in ["min", "both"]: if self.orientation == "horizontal": x1 = x1 + dw else: y1 = y1+dh if self.extend in ["max", "both"]: if self.orientation == "horizontal": w = w-2*dw else: h = h-2*dh return Bbox.from_bounds(x1, y1, w, h) class ColorbarBase(cm.ScalarMappable): ''' Draw a colorbar in an existing axes. This is a base class for the :class:`Colorbar` class, which is the basis for the :func:`~matplotlib.pyplot.colorbar` method and pylab function. It is also useful by itself for showing a colormap. If the *cmap* kwarg is given but *boundaries* and *values* are left as None, then the colormap will be displayed on a 0-1 scale. To show the under- and over-value colors, specify the *norm* as:: colors.Normalize(clip=False) To show the colors versus index instead of on the 0-1 scale, use:: norm=colors.NoNorm. Useful attributes: :attr:`ax` the Axes instance in which the colorbar is drawn :attr:`lines` a LineCollection if lines were drawn, otherwise None :attr:`dividers` a LineCollection if *drawedges* is True, otherwise None Useful public methods are :meth:`set_label` and :meth:`add_lines`. ''' def __init__(self, ax, cmap=None, norm=None, alpha=1.0, values=None, boundaries=None, orientation='vertical', extend='neither', spacing='uniform', # uniform or proportional ticks=None, format=None, drawedges=False, filled=True, ): self.ax = ax if cmap is None: cmap = cm.get_cmap() if norm is None: norm = colors.Normalize() self.alpha = alpha cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm) self.values = values self.boundaries = boundaries self.extend = extend self.spacing = spacing self.orientation = orientation self.drawedges = drawedges self.filled = filled # artists self.solids = None self.lines = None self.dividers = None self.extension_patch1 = None self.extension_patch2 = None if orientation == "vertical": self.cbar_axis = self.ax.yaxis else: self.cbar_axis = self.ax.xaxis if format is None: if isinstance(self.norm, colors.LogNorm): # change both axis for proper aspect self.ax.xaxis.set_scale("log") self.ax.yaxis.set_scale("log") self.ax._update_transScale() self.cbar_axis.set_minor_locator(ticker.NullLocator()) formatter = ticker.LogFormatter() else: formatter = None elif cbook.is_string_like(format): formatter = ticker.FormatStrFormatter(format) else: formatter = format # Assume it is a Formatter if formatter is None: formatter = self.cbar_axis.get_major_formatter() else: self.cbar_axis.set_major_formatter(formatter) if cbook.iterable(ticks): self.cbar_axis.set_ticks(ticks) elif ticks is not None: self.cbar_axis.set_major_locator(ticks) else: self._select_locator(formatter) self._config_axes() self.update_artists() self.set_label_text('') def _get_colorbar_limits(self): """ initial limits for colorbar range. The returned min, max values will be used to create colorbar solid(?) and etc. """ if self.boundaries is not None: C = self.boundaries if self.extend in ["min", "both"]: C = C[1:] if self.extend in ["max", "both"]: C = C[:-1] return min(C), max(C) else: return self.get_clim() def _config_axes(self): ''' Adjust the properties of the axes to be adequate for colorbar display. ''' ax = self.ax axes_locator = CbarAxesLocator(ax.get_axes_locator(), extend=self.extend, orientation=self.orientation) ax.set_axes_locator(axes_locator) # override the get_data_ratio for the aspect works. def _f(): return 1. ax.get_data_ratio = _f ax.get_data_ratio_log = _f ax.set_frame_on(True) ax.set_navigate(False) self.ax.set_autoscalex_on(False) self.ax.set_autoscaley_on(False) if self.orientation == 'horizontal': ax.xaxis.set_label_position('bottom') ax.set_yticks([]) else: ax.set_xticks([]) ax.yaxis.set_label_position('right') ax.yaxis.set_ticks_position('right') def update_artists(self): """ Update the colorbar associated artists, *filled* and *ends*. Note that *lines* are not updated. This needs to be called whenever clim of associated image changes. """ self._process_values() self._add_ends() X, Y = self._mesh() if self.filled: C = self._values[:,np.newaxis] self._add_solids(X, Y, C) ax = self.ax vmin, vmax = self._get_colorbar_limits() if self.orientation == 'horizontal': ax.set_ylim(1, 2) ax.set_xlim(vmin, vmax) else: ax.set_xlim(1, 2) ax.set_ylim(vmin, vmax) def _add_ends(self): """ Create patches from extended ends and add them to the axes. """ del self.extension_patch1 del self.extension_patch2 path1, path2 = self.ax.get_axes_locator().get_path_ends() fc=mpl.rcParams['axes.facecolor'] ec=mpl.rcParams['axes.edgecolor'] linewidths=0.5*mpl.rcParams['axes.linewidth'] self.extension_patch1 = PathPatch(path1, fc=fc, ec=ec, lw=linewidths, zorder=2., transform=self.ax.transAxes, clip_on=False) self.extension_patch2 = PathPatch(path2, fc=fc, ec=ec, lw=linewidths, zorder=2., transform=self.ax.transAxes, clip_on=False) self.ax.add_artist(self.extension_patch1) self.ax.add_artist(self.extension_patch2) def _set_label_text(self): """ set label. """ self.cbar_axis.set_label_text(self._label, **self._labelkw) def set_label_text(self, label, **kw): ''' Label the long axis of the colorbar ''' self._label = label self._labelkw = kw self._set_label_text() def _edges(self, X, Y): ''' Return the separator line segments; helper for _add_solids. ''' N = X.shape[0] # Using the non-array form of these line segments is much # simpler than making them into arrays. if self.orientation == 'vertical': return [list(zip(X[i], Y[i])) for i in xrange(1, N-1)] else: return [list(zip(Y[i], X[i])) for i in xrange(1, N-1)] def _add_solids(self, X, Y, C): ''' Draw the colors using :meth:`~matplotlib.axes.Axes.pcolormesh`; optionally add separators. ''' ## Change to pcolorfast after fixing bugs in some backends... if self.extend in ["min", "both"]: cc = self.to_rgba([C[0][0]]) self.extension_patch1.set_fc(cc[0]) X, Y, C = X[1:], Y[1:], C[1:] if self.extend in ["max", "both"]: cc = self.to_rgba([C[-1][0]]) self.extension_patch2.set_fc(cc[0]) X, Y, C = X[:-1], Y[:-1], C[:-1] if self.orientation == 'vertical': args = (X, Y, C) else: args = (np.transpose(Y), np.transpose(X), np.transpose(C)) kw = {'cmap':self.cmap, 'norm':self.norm, 'shading':'flat', 'alpha':self.alpha, } del self.solids del self.dividers col = self.ax.pcolormesh(*args, **kw) self.solids = col if self.drawedges: self.dividers = collections.LineCollection(self._edges(X,Y), colors=(mpl.rcParams['axes.edgecolor'],), linewidths=(0.5*mpl.rcParams['axes.linewidth'],), ) self.ax.add_collection(self.dividers) else: self.dividers = None def add_lines(self, levels, colors, linewidths): ''' Draw lines on the colorbar. It deletes preexisting lines. ''' del self.lines N = len(levels) x = np.array([1.0, 2.0]) X, Y = np.meshgrid(x,levels) if self.orientation == 'vertical': xy = [list(zip(X[i], Y[i])) for i in xrange(N)] else: xy = [list(zip(Y[i], X[i])) for i in xrange(N)] col = collections.LineCollection(xy, linewidths=linewidths, ) self.lines = col col.set_color(colors) self.ax.add_collection(col) def _select_locator(self, formatter): ''' select a suitable locator ''' if self.boundaries is None: if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = 1 + int(nv/10) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator() else: locator = ticker.MaxNLocator(nbins=5) else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b) #, nbins=10) self.cbar_axis.set_major_locator(locator) def _process_values(self, b=None): ''' Set the :attr:`_boundaries` and :attr:`_values` attributes based on the input boundaries and values. Input boundaries can be *self.boundaries* or the argument *b*. ''' if b is None: b = self.boundaries if b is not None: self._boundaries = np.asarray(b, dtype=float) if self.values is None: self._values = 0.5*(self._boundaries[:-1] + self._boundaries[1:]) if isinstance(self.norm, colors.NoNorm): self._values = (self._values + 0.00001).astype(np.int16) return self._values = np.array(self.values) return if self.values is not None: self._values = np.array(self.values) if self.boundaries is None: b = np.zeros(len(self.values)+1, 'd') b[1:-1] = 0.5*(self._values[:-1] - self._values[1:]) b[0] = 2.0*b[1] - b[2] b[-1] = 2.0*b[-2] - b[-3] self._boundaries = b return self._boundaries = np.array(self.boundaries) return # Neither boundaries nor values are specified; # make reasonable ones based on cmap and norm. if isinstance(self.norm, colors.NoNorm): b = self._uniform_y(self.cmap.N+1) * self.cmap.N - 0.5 v = np.zeros((len(b)-1,), dtype=np.int16) v = np.arange(self.cmap.N, dtype=np.int16) self._boundaries = b self._values = v return elif isinstance(self.norm, colors.BoundaryNorm): b = np.array(self.norm.boundaries) v = np.zeros((len(b)-1,), dtype=float) bi = self.norm.boundaries v = 0.5*(bi[:-1] + bi[1:]) self._boundaries = b self._values = v return else: b = self._uniform_y(self.cmap.N+1) self._process_values(b) def _uniform_y(self, N): ''' Return colorbar data coordinates for *N* uniformly spaced boundaries. ''' vmin, vmax = self._get_colorbar_limits() if isinstance(self.norm, colors.LogNorm): y = np.logspace(np.log10(vmin), np.log10(vmax), N) else: y = np.linspace(vmin, vmax, N) return y def _mesh(self): ''' Return X,Y, the coordinate arrays for the colorbar pcolormesh. These are suitable for a vertical colorbar; swapping and transposition for a horizontal colorbar are done outside this function. ''' x = np.array([1.0, 2.0]) if self.spacing == 'uniform': y = self._uniform_y(len(self._boundaries)) else: y = self._boundaries self._y = y X, Y = np.meshgrid(x,y) return X, Y def set_alpha(self, alpha): """ set alpha value. """ self.alpha = alpha class Colorbar(ColorbarBase): def __init__(self, ax, mappable, **kw): mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax # are set when colorbar is called, # even if mappable.draw has not yet # been called. This will not change # vmin, vmax if they are already set. self.mappable = mappable kw['cmap'] = mappable.cmap kw['norm'] = mappable.norm kw['alpha'] = mappable.get_alpha() if isinstance(mappable, contour.ContourSet): CS = mappable kw['boundaries'] = CS._levels kw['values'] = CS.cvalues kw['extend'] = CS.extend #kw['ticks'] = CS._levels kw.setdefault('ticks', ticker.FixedLocator(CS.levels, nbins=10)) kw['filled'] = CS.filled ColorbarBase.__init__(self, ax, **kw) if not CS.filled: self.add_lines(CS) else: ColorbarBase.__init__(self, ax, **kw) def add_lines(self, CS): ''' Add the lines from a non-filled :class:`~matplotlib.contour.ContourSet` to the colorbar. ''' if not isinstance(CS, contour.ContourSet) or CS.filled: raise ValueError('add_lines is only for a ContourSet of lines') tcolors = [c[0] for c in CS.tcolors] tlinewidths = [t[0] for t in CS.tlinewidths] # The following was an attempt to get the colorbar lines # to follow subsequent changes in the contour lines, # but more work is needed: specifically, a careful # look at event sequences, and at how # to make one object track another automatically. #tcolors = [col.get_colors()[0] for col in CS.collections] #tlinewidths = [col.get_linewidth()[0] for lw in CS.collections] #print 'tlinewidths:', tlinewidths ColorbarBase.add_lines(self, CS.levels, tcolors, tlinewidths) def update_bruteforce(self, mappable): """ Update the colorbar artists to reflect the change of the associated mappable. """ self.update_artists() if isinstance(mappable, contour.ContourSet): if not mappable.filled: self.add_lines(mappable) @docstring.Substitution(make_axes_kw_doc) def make_axes(parent, **kw): ''' Resize and reposition a parent axes, and return a child axes suitable for a colorbar:: cax, kw = make_axes(parent, **kw) Keyword arguments may include the following (with defaults): *orientation* 'vertical' or 'horizontal' %s All but the first of these are stripped from the input kw set. Returns (cax, kw), the child axes and the reduced kw dictionary. ''' orientation = kw.setdefault('orientation', 'vertical') fraction = kw.pop('fraction', 0.15) shrink = kw.pop('shrink', 1.0) aspect = kw.pop('aspect', 20) #pb = transforms.PBox(parent.get_position()) pb = parent.get_position(original=True).frozen() if orientation == 'vertical': pad = kw.pop('pad', 0.05) x1 = 1.0-fraction pb1, pbx, pbcb = pb.splitx(x1-pad, x1) pbcb = pbcb.shrunk(1.0, shrink).anchored('C', pbcb) anchor = (0.0, 0.5) panchor = (1.0, 0.5) else: pad = kw.pop('pad', 0.15) pbcb, pbx, pb1 = pb.splity(fraction, fraction+pad) pbcb = pbcb.shrunk(shrink, 1.0).anchored('C', pbcb) aspect = 1.0/aspect anchor = (0.5, 1.0) panchor = (0.5, 0.0) parent.set_position(pb1) parent.set_anchor(panchor) fig = parent.get_figure() cax = fig.add_axes(pbcb) cax.set_aspect(aspect, anchor=anchor, adjustable='box') return cax, kw def colorbar(mappable, cax=None, ax=None, **kw): """ Create a colorbar for a ScalarMappable instance. Documentation for the pylab thin wrapper: %(colorbar_doc)s """ import matplotlib.pyplot as plt if ax is None: ax = plt.gca() if cax is None: cax, kw = make_axes(ax, **kw) cax.hold(True) cb = Colorbar(cax, mappable, **kw) def on_changed(m): cb.set_cmap(m.get_cmap()) cb.set_clim(m.get_clim()) cb.update_bruteforce(m) cbid = mappable.callbacksSM.connect('changed', on_changed) mappable.colorbar = cb ax.figure.sca(ax) return cb
mit
Delosari/dazer
bin/lib/cloudy_library/Cloudy_Launcher3.py
1
3449
import pandas as pd from numpy import log10 as nplog10, pi, power from collections import OrderedDict from cloudy_library.cloudy_methods import Cloudy_Tools def import_popstar_data(): FilesFolder = '/home/vital/Dropbox/Astrophysics/Lore/PopStar/' TableAddressn100 = 'mnras0403-2012-SD2_clusterTable2.txt' Frame_MetalsEmission = pd.read_csv(FilesFolder + TableAddressn100, delim_whitespace = True) nH = 10.0 #cm^-3 c = 29979245800.0 #cm/s pc_to_cm = 3.0856776e18 #cm/pc Frame_MetalsEmission['logR_cm'] = nplog10(Frame_MetalsEmission['logR'] * pc_to_cm) Frame_MetalsEmission['Q'] = nplog10(power(10, Frame_MetalsEmission['logU']) * 4 * pi * c * nH * power(Frame_MetalsEmission['logR'] * pc_to_cm, 2)) return Frame_MetalsEmission ct = Cloudy_Tools() #Define script name and location ScriptFolder = '/home/vital/Dropbox/Astrophysics/Tools/Cloudy/S_Ar_test/Total_Q_R_Grid/' Grid_Values = OrderedDict() Grid_Values['age'] = ['5.', '5.48', '5.7', '5.85', '6.', '6.18', '6.3', '6.4', '6.51', '6.57', '6.63', '6.68', '6.72' ] Grid_Values['clus_mass'] = ['12000.', '20000.', '60000.', '100000.', '200000.'] Grid_Values['zGas'] = ['0.0001', '0.0004', '0.004', '0.008'] Grid_Values['zStars'] = ['-2.1'] # Grid_Values = OrderedDict() # Grid_Values['age'] = ['5.'] # Grid_Values['clus_mass'] = ['100000.', '150000.', '200000.'] # Grid_Values['zGas'] = ['0.0001', '0.0004', '0.004', '0.008'] # Grid_Values['zStars'] = ['-2.1'] #Data from popstar Frame_MetalsEmission = import_popstar_data() #Generate the scripts with the lines we want to print the flux ct.lines_to_extract(ScriptFolder) #Fore the each grid point run a cloudy simulation Model_dict = OrderedDict() for age in Grid_Values['age']: for mass in Grid_Values['clus_mass']: for zGas in Grid_Values['zGas']: for zStar in Grid_Values['zStars']: Model_dict['Name'] = 'S_Ar_Test_' + 'age'+ age + '_zStar' + zStar + '_clusMass' + mass + '_zGas' + zGas Model_dict['age'] = age Model_dict['zGas'] = zGas Model_dict['Metals_frac'] = str(float(zGas) / 0.02) Model_dict['zGas'] = zGas Model_dict['zStars'] = zStar index = (Frame_MetalsEmission["Z"] == float(zGas)) & (Frame_MetalsEmission["M_Msun"] == float(mass)) & (Frame_MetalsEmission["t"] == float(age)) print '--Going for conditions: ', age, zGas, zStar, mass Model_dict['Q'] = Frame_MetalsEmission.loc[index, 'Q'].values[0] Model_dict['R'] = Frame_MetalsEmission.loc[index, 'logR_cm'].values[0] ScriptName = Model_dict['Name'] + '.in' print ScriptName #Generate the script ct.popstar_S_Ar_QR_grid(ScriptFolder, Model_dict) #Run the cloudy script ct.run_script(ScriptName, ScriptFolder) print 'Data treated'
mit
ContextLab/hypertools
hypertools/tools/analyze.py
1
2300
#!/usr/bin/env python from .reduce import reduce as reducer from .align import align as aligner from .normalize import normalize as normalizer def analyze(data, normalize=None, reduce=None, ndims=None, align=None, internal=False): """ Wrapper function for normalize -> reduce -> align transformations. Parameters ---------- data : numpy array, pandas df, or list of arrays/dfs The data to analyze normalize : str or False or None If set to 'across', the columns of the input data will be z-scored across lists (default). That is, the z-scores will be computed with with respect to column n across all arrays passed in the list. If set to 'within', the columns will be z-scored within each list that is passed. If set to 'row', each row of the input data will be z-scored. If set to False, the input data will be returned with no z-scoring. reduce : str or dict Decomposition/manifold learning model to use. Models supported: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be passed as a string, but for finer control of the model parameters, pass as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}. See scikit-learn specific model docs for details on parameters supported for each model. ndims : int Number of dimensions to reduce align : str or dict If str, either 'hyper' or 'SRM'. If 'hyper', alignment algorithm will be hyperalignment. If 'SRM', alignment algorithm will be shared response model. You can also pass a dictionary for finer control, where the 'model' key is a string that specifies the model and the params key is a dictionary of parameter values (default : 'hyper'). Returns ---------- analyzed_data : list of numpy arrays The processed data """ # return processed data return aligner(reducer(normalizer(data, normalize=normalize, internal=internal), reduce=reduce, ndims=ndims, internal=internal), align=align)
mit
fredhusser/scikit-learn
sklearn/metrics/tests/test_pairwise.py
17
24947
import numpy as np from numpy import linalg from scipy.sparse import dok_matrix, csr_matrix, issparse from scipy.spatial.distance import cosine, cityblock, minkowski, wminkowski from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.externals.six import iteritems from sklearn.metrics.pairwise import euclidean_distances from sklearn.metrics.pairwise import manhattan_distances from sklearn.metrics.pairwise import linear_kernel from sklearn.metrics.pairwise import chi2_kernel, additive_chi2_kernel from sklearn.metrics.pairwise import polynomial_kernel from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics.pairwise import sigmoid_kernel from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics.pairwise import cosine_distances from sklearn.metrics.pairwise import pairwise_distances from sklearn.metrics.pairwise import pairwise_distances_argmin_min from sklearn.metrics.pairwise import pairwise_distances_argmin from sklearn.metrics.pairwise import pairwise_kernels from sklearn.metrics.pairwise import PAIRWISE_KERNEL_FUNCTIONS from sklearn.metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS from sklearn.metrics.pairwise import PAIRED_DISTANCES from sklearn.metrics.pairwise import check_pairwise_arrays from sklearn.metrics.pairwise import check_paired_arrays from sklearn.metrics.pairwise import _parallel_pairwise from sklearn.metrics.pairwise import paired_distances from sklearn.metrics.pairwise import paired_euclidean_distances from sklearn.metrics.pairwise import paired_manhattan_distances from sklearn.preprocessing import normalize def test_pairwise_distances(): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)) S = pairwise_distances(X, metric="euclidean") S2 = euclidean_distances(X) assert_array_almost_equal(S, S2) # Euclidean distance, with Y != X. Y = rng.random_sample((2, 4)) S = pairwise_distances(X, Y, metric="euclidean") S2 = euclidean_distances(X, Y) assert_array_almost_equal(S, S2) # Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) S2 = pairwise_distances(X_tuples, Y_tuples, metric="euclidean") assert_array_almost_equal(S, S2) # "cityblock" uses sklearn metric, cityblock (function) is scipy.spatial. S = pairwise_distances(X, metric="cityblock") S2 = pairwise_distances(X, metric=cityblock) assert_equal(S.shape[0], S.shape[1]) assert_equal(S.shape[0], X.shape[0]) assert_array_almost_equal(S, S2) # The manhattan metric should be equivalent to cityblock. S = pairwise_distances(X, Y, metric="manhattan") S2 = pairwise_distances(X, Y, metric=cityblock) assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2) # Low-level function for manhattan can divide in blocks to avoid # using too much memory during the broadcasting S3 = manhattan_distances(X, Y, size_threshold=10) assert_array_almost_equal(S, S3) # Test cosine as a string metric versus cosine callable # "cosine" uses sklearn metric, cosine (function) is scipy.spatial S = pairwise_distances(X, Y, metric="cosine") S2 = pairwise_distances(X, Y, metric=cosine) assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2) # Test with sparse X and Y, # currently only supported for Euclidean, L1 and cosine. X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) S = pairwise_distances(X_sparse, Y_sparse, metric="euclidean") S2 = euclidean_distances(X_sparse, Y_sparse) assert_array_almost_equal(S, S2) S = pairwise_distances(X_sparse, Y_sparse, metric="cosine") S2 = cosine_distances(X_sparse, Y_sparse) assert_array_almost_equal(S, S2) S = pairwise_distances(X_sparse, Y_sparse.tocsc(), metric="manhattan") S2 = manhattan_distances(X_sparse.tobsr(), Y_sparse.tocoo()) assert_array_almost_equal(S, S2) S2 = manhattan_distances(X, Y) assert_array_almost_equal(S, S2) # Test with scipy.spatial.distance metric, with a kwd kwds = {"p": 2.0} S = pairwise_distances(X, Y, metric="minkowski", **kwds) S2 = pairwise_distances(X, Y, metric=minkowski, **kwds) assert_array_almost_equal(S, S2) # same with Y = None kwds = {"p": 2.0} S = pairwise_distances(X, metric="minkowski", **kwds) S2 = pairwise_distances(X, metric=minkowski, **kwds) assert_array_almost_equal(S, S2) # Test that scipy distance metrics throw an error if sparse matrix given assert_raises(TypeError, pairwise_distances, X_sparse, metric="minkowski") assert_raises(TypeError, pairwise_distances, X, Y_sparse, metric="minkowski") # Test that a value error is raised if the metric is unkown assert_raises(ValueError, pairwise_distances, X, Y, metric="blah") def test_pairwise_precomputed(): for func in [pairwise_distances, pairwise_kernels]: # Test correct shape assert_raises_regexp(ValueError, '.* shape .*', func, np.zeros((5, 3)), metric='precomputed') # with two args assert_raises_regexp(ValueError, '.* shape .*', func, np.zeros((5, 3)), np.zeros((4, 4)), metric='precomputed') # even if shape[1] agrees (although thus second arg is spurious) assert_raises_regexp(ValueError, '.* shape .*', func, np.zeros((5, 3)), np.zeros((4, 3)), metric='precomputed') # Test not copied (if appropriate dtype) S = np.zeros((5, 5)) S2 = func(S, metric="precomputed") assert_true(S is S2) # with two args S = np.zeros((5, 3)) S2 = func(S, np.zeros((3, 3)), metric="precomputed") assert_true(S is S2) # Test always returns float dtype S = func(np.array([[1]], dtype='int'), metric='precomputed') assert_equal('f', S.dtype.kind) # Test converts list to array-like S = func([[1]], metric='precomputed') assert_true(isinstance(S, np.ndarray)) def check_pairwise_parallel(func, metric, kwds): rng = np.random.RandomState(0) for make_data in (np.array, csr_matrix): X = make_data(rng.random_sample((5, 4))) Y = make_data(rng.random_sample((3, 4))) try: S = func(X, metric=metric, n_jobs=1, **kwds) except (TypeError, ValueError) as exc: # Not all metrics support sparse input # ValueError may be triggered by bad callable if make_data is csr_matrix: assert_raises(type(exc), func, X, metric=metric, n_jobs=2, **kwds) continue else: raise S2 = func(X, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) S = func(X, Y, metric=metric, n_jobs=1, **kwds) S2 = func(X, Y, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) def test_pairwise_parallel(): wminkowski_kwds = {'w': np.arange(1, 5).astype('double'), 'p': 1} metrics = [(pairwise_distances, 'euclidean', {}), (pairwise_distances, wminkowski, wminkowski_kwds), (pairwise_distances, 'wminkowski', wminkowski_kwds), (pairwise_kernels, 'polynomial', {'degree': 1}), (pairwise_kernels, callable_rbf_kernel, {'gamma': .1}), ] for func, metric, kwds in metrics: yield check_pairwise_parallel, func, metric, kwds def test_pairwise_callable_nonstrict_metric(): # paired_distances should allow callable metric where metric(x, x) != 0 # Knowing that the callable is a strict metric would allow the diagonal to # be left uncalculated and set to 0. assert_equal(pairwise_distances([[1]], metric=lambda x, y: 5)[0, 0], 5) def callable_rbf_kernel(x, y, **kwds): # Callable version of pairwise.rbf_kernel. K = rbf_kernel(np.atleast_2d(x), np.atleast_2d(y), **kwds) return K def test_pairwise_kernels(): # Test the pairwise_kernels helper function. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) # Test with all metrics that should be in PAIRWISE_KERNEL_FUNCTIONS. test_metrics = ["rbf", "sigmoid", "polynomial", "linear", "chi2", "additive_chi2"] for metric in test_metrics: function = PAIRWISE_KERNEL_FUNCTIONS[metric] # Test with Y=None K1 = pairwise_kernels(X, metric=metric) K2 = function(X) assert_array_almost_equal(K1, K2) # Test with Y=Y K1 = pairwise_kernels(X, Y=Y, metric=metric) K2 = function(X, Y=Y) assert_array_almost_equal(K1, K2) # Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) K2 = pairwise_kernels(X_tuples, Y_tuples, metric=metric) assert_array_almost_equal(K1, K2) # Test with sparse X and Y X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) if metric in ["chi2", "additive_chi2"]: # these don't support sparse matrices yet assert_raises(ValueError, pairwise_kernels, X_sparse, Y=Y_sparse, metric=metric) continue K1 = pairwise_kernels(X_sparse, Y=Y_sparse, metric=metric) assert_array_almost_equal(K1, K2) # Test with a callable function, with given keywords. metric = callable_rbf_kernel kwds = {} kwds['gamma'] = 0.1 K1 = pairwise_kernels(X, Y=Y, metric=metric, **kwds) K2 = rbf_kernel(X, Y=Y, **kwds) assert_array_almost_equal(K1, K2) # callable function, X=Y K1 = pairwise_kernels(X, Y=X, metric=metric, **kwds) K2 = rbf_kernel(X, Y=X, **kwds) assert_array_almost_equal(K1, K2) def test_pairwise_kernels_filter_param(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) K = rbf_kernel(X, Y, gamma=0.1) params = {"gamma": 0.1, "blabla": ":)"} K2 = pairwise_kernels(X, Y, metric="rbf", filter_params=True, **params) assert_array_almost_equal(K, K2) assert_raises(TypeError, pairwise_kernels, X, Y, "rbf", **params) def test_paired_distances(): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)) # Euclidean distance, with Y != X. Y = rng.random_sample((5, 4)) for metric, func in iteritems(PAIRED_DISTANCES): S = paired_distances(X, Y, metric=metric) S2 = func(X, Y) assert_array_almost_equal(S, S2) S3 = func(csr_matrix(X), csr_matrix(Y)) assert_array_almost_equal(S, S3) if metric in PAIRWISE_DISTANCE_FUNCTIONS: # Check the the pairwise_distances implementation # gives the same value distances = PAIRWISE_DISTANCE_FUNCTIONS[metric](X, Y) distances = np.diag(distances) assert_array_almost_equal(distances, S) # Check the callable implementation S = paired_distances(X, Y, metric='manhattan') S2 = paired_distances(X, Y, metric=lambda x, y: np.abs(x - y).sum(axis=0)) assert_array_almost_equal(S, S2) # Test that a value error is raised when the lengths of X and Y should not # differ Y = rng.random_sample((3, 4)) assert_raises(ValueError, paired_distances, X, Y) def test_pairwise_distances_argmin_min(): # Check pairwise minimum distances computation for any metric X = [[0], [1]] Y = [[-1], [2]] Xsp = dok_matrix(X) Ysp = csr_matrix(Y, dtype=np.float32) # euclidean metric D, E = pairwise_distances_argmin_min(X, Y, metric="euclidean") D2 = pairwise_distances_argmin(X, Y, metric="euclidean") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(D2, [0, 1]) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # sparse matrix case Dsp, Esp = pairwise_distances_argmin_min(Xsp, Ysp, metric="euclidean") assert_array_equal(Dsp, D) assert_array_equal(Esp, E) # We don't want np.matrix here assert_equal(type(Dsp), np.ndarray) assert_equal(type(Esp), np.ndarray) # Non-euclidean sklearn metric D, E = pairwise_distances_argmin_min(X, Y, metric="manhattan") D2 = pairwise_distances_argmin(X, Y, metric="manhattan") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(D2, [0, 1]) assert_array_almost_equal(E, [1., 1.]) D, E = pairwise_distances_argmin_min(Xsp, Ysp, metric="manhattan") D2 = pairwise_distances_argmin(Xsp, Ysp, metric="manhattan") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Non-euclidean Scipy distance (callable) D, E = pairwise_distances_argmin_min(X, Y, metric=minkowski, metric_kwargs={"p": 2}) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Non-euclidean Scipy distance (string) D, E = pairwise_distances_argmin_min(X, Y, metric="minkowski", metric_kwargs={"p": 2}) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Compare with naive implementation rng = np.random.RandomState(0) X = rng.randn(97, 149) Y = rng.randn(111, 149) dist = pairwise_distances(X, Y, metric="manhattan") dist_orig_ind = dist.argmin(axis=0) dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))] dist_chunked_ind, dist_chunked_val = pairwise_distances_argmin_min( X, Y, axis=0, metric="manhattan", batch_size=50) np.testing.assert_almost_equal(dist_orig_ind, dist_chunked_ind, decimal=7) np.testing.assert_almost_equal(dist_orig_val, dist_chunked_val, decimal=7) def test_euclidean_distances(): # Check the pairwise Euclidean distances computation X = [[0]] Y = [[1], [2]] D = euclidean_distances(X, Y) assert_array_almost_equal(D, [[1., 2.]]) X = csr_matrix(X) Y = csr_matrix(Y) D = euclidean_distances(X, Y) assert_array_almost_equal(D, [[1., 2.]]) rng = np.random.RandomState(0) X = rng.random_sample((10, 4)) Y = rng.random_sample((20, 4)) X_norm_sq = (X ** 2).sum(axis=1) Y_norm_sq = (Y ** 2).sum(axis=1) # check that we still get the right answers with {X,Y}_norm_squared D1 = euclidean_distances(X, Y) D2 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq) D3 = euclidean_distances(X, Y, Y_norm_squared=Y_norm_sq) D4 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq, Y_norm_squared=Y_norm_sq) assert_array_almost_equal(D2, D1) assert_array_almost_equal(D3, D1) assert_array_almost_equal(D4, D1) # check we get the wrong answer with wrong {X,Y}_norm_squared X_norm_sq *= 0.5 Y_norm_sq *= 0.5 wrong_D = euclidean_distances(X, Y, X_norm_squared=np.zeros_like(X_norm_sq), Y_norm_squared=np.zeros_like(Y_norm_sq)) assert_greater(np.max(np.abs(wrong_D - D1)), .01) # Paired distances def test_paired_euclidean_distances(): # Check the paired Euclidean distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_euclidean_distances(X, Y) assert_array_almost_equal(D, [1., 2.]) def test_paired_manhattan_distances(): # Check the paired manhattan distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_manhattan_distances(X, Y) assert_array_almost_equal(D, [1., 2.]) def test_chi_square_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((10, 4)) K_add = additive_chi2_kernel(X, Y) gamma = 0.1 K = chi2_kernel(X, Y, gamma=gamma) assert_equal(K.dtype, np.float) for i, x in enumerate(X): for j, y in enumerate(Y): chi2 = -np.sum((x - y) ** 2 / (x + y)) chi2_exp = np.exp(gamma * chi2) assert_almost_equal(K_add[i, j], chi2) assert_almost_equal(K[i, j], chi2_exp) # check diagonal is ones for data with itself K = chi2_kernel(Y) assert_array_equal(np.diag(K), 1) # check off-diagonal is < 1 but > 0: assert_true(np.all(K > 0)) assert_true(np.all(K - np.diag(np.diag(K)) < 1)) # check that float32 is preserved X = rng.random_sample((5, 4)).astype(np.float32) Y = rng.random_sample((10, 4)).astype(np.float32) K = chi2_kernel(X, Y) assert_equal(K.dtype, np.float32) # check integer type gets converted, # check that zeros are handled X = rng.random_sample((10, 4)).astype(np.int32) K = chi2_kernel(X, X) assert_true(np.isfinite(K).all()) assert_equal(K.dtype, np.float) # check that kernel of similar things is greater than dissimilar ones X = [[.3, .7], [1., 0]] Y = [[0, 1], [.9, .1]] K = chi2_kernel(X, Y) assert_greater(K[0, 0], K[0, 1]) assert_greater(K[1, 1], K[1, 0]) # test negative input assert_raises(ValueError, chi2_kernel, [[0, -1]]) assert_raises(ValueError, chi2_kernel, [[0, -1]], [[-1, -1]]) assert_raises(ValueError, chi2_kernel, [[0, 1]], [[-1, -1]]) # different n_features in X and Y assert_raises(ValueError, chi2_kernel, [[0, 1]], [[.2, .2, .6]]) # sparse matrices assert_raises(ValueError, chi2_kernel, csr_matrix(X), csr_matrix(Y)) assert_raises(ValueError, additive_chi2_kernel, csr_matrix(X), csr_matrix(Y)) def test_kernel_symmetry(): # Valid kernels should be symmetric rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, sigmoid_kernel, cosine_similarity): K = kernel(X, X) assert_array_almost_equal(K, K.T, 15) def test_kernel_sparse(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) X_sparse = csr_matrix(X) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, sigmoid_kernel, cosine_similarity): K = kernel(X, X) K2 = kernel(X_sparse, X_sparse) assert_array_almost_equal(K, K2) def test_linear_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = linear_kernel(X, X) # the diagonal elements of a linear kernel are their squared norm assert_array_almost_equal(K.flat[::6], [linalg.norm(x) ** 2 for x in X]) def test_rbf_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = rbf_kernel(X, X) # the diagonal elements of a rbf kernel are 1 assert_array_almost_equal(K.flat[::6], np.ones(5)) def test_cosine_similarity_sparse_output(): # Test if cosine_similarity correctly produces sparse output. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y) K1 = cosine_similarity(Xcsr, Ycsr, dense_output=False) assert_true(issparse(K1)) K2 = pairwise_kernels(Xcsr, Y=Ycsr, metric="cosine") assert_array_almost_equal(K1.todense(), K2) def test_cosine_similarity(): # Test the cosine_similarity. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y) for X_, Y_ in ((X, None), (X, Y), (Xcsr, None), (Xcsr, Ycsr)): # Test that the cosine is kernel is equal to a linear kernel when data # has been previously normalized by L2-norm. K1 = pairwise_kernels(X_, Y=Y_, metric="cosine") X_ = normalize(X_) if Y_ is not None: Y_ = normalize(Y_) K2 = pairwise_kernels(X_, Y=Y_, metric="linear") assert_array_almost_equal(K1, K2) def test_check_dense_matrices(): # Ensure that pairwise array check works for dense matrices. # Check that if XB is None, XB is returned as reference to XA XA = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert_true(XA_checked is XB_checked) assert_array_equal(XA, XA_checked) def test_check_XB_returned(): # Ensure that if XA and XB are given correctly, they return as equal. # Check that if XB is not None, it is returned equal. # Note that the second dimension of XB is the same as XA. XA = np.resize(np.arange(40), (5, 8)) XB = np.resize(np.arange(32), (4, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked) XB = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_paired_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked) def test_check_different_dimensions(): # Ensure an error is raised if the dimensions are different. XA = np.resize(np.arange(45), (5, 9)) XB = np.resize(np.arange(32), (4, 8)) assert_raises(ValueError, check_pairwise_arrays, XA, XB) XB = np.resize(np.arange(4 * 9), (4, 9)) assert_raises(ValueError, check_paired_arrays, XA, XB) def test_check_invalid_dimensions(): # Ensure an error is raised on 1D input arrays. XA = np.arange(45) XB = np.resize(np.arange(32), (4, 8)) assert_raises(ValueError, check_pairwise_arrays, XA, XB) XA = np.resize(np.arange(45), (5, 9)) XB = np.arange(32) assert_raises(ValueError, check_pairwise_arrays, XA, XB) def test_check_sparse_arrays(): # Ensures that checks return valid sparse matrices. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_sparse = csr_matrix(XA) XB = rng.random_sample((5, 4)) XB_sparse = csr_matrix(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_sparse, XB_sparse) # compare their difference because testing csr matrices for # equality with '==' does not work as expected. assert_true(issparse(XA_checked)) assert_equal(abs(XA_sparse - XA_checked).sum(), 0) assert_true(issparse(XB_checked)) assert_equal(abs(XB_sparse - XB_checked).sum(), 0) XA_checked, XA_2_checked = check_pairwise_arrays(XA_sparse, XA_sparse) assert_true(issparse(XA_checked)) assert_equal(abs(XA_sparse - XA_checked).sum(), 0) assert_true(issparse(XA_2_checked)) assert_equal(abs(XA_2_checked - XA_checked).sum(), 0) def tuplify(X): # Turns a numpy matrix (any n-dimensional array) into tuples. s = X.shape if len(s) > 1: # Tuplify each sub-array in the input. return tuple(tuplify(row) for row in X) else: # Single dimension input, just return tuple of contents. return tuple(r for r in X) def test_check_tuple_input(): # Ensures that checks return valid tuples. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_tuples = tuplify(XA) XB = rng.random_sample((5, 4)) XB_tuples = tuplify(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_tuples, XB_tuples) assert_array_equal(XA_tuples, XA_checked) assert_array_equal(XB_tuples, XB_checked) def test_check_preserve_type(): # Ensures that type float32 is preserved. XA = np.resize(np.arange(40), (5, 8)).astype(np.float32) XB = np.resize(np.arange(40), (5, 8)).astype(np.float32) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert_equal(XA_checked.dtype, np.float32) # both float32 XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert_equal(XA_checked.dtype, np.float32) assert_equal(XB_checked.dtype, np.float32) # mismatched A XA_checked, XB_checked = check_pairwise_arrays(XA.astype(np.float), XB) assert_equal(XA_checked.dtype, np.float) assert_equal(XB_checked.dtype, np.float) # mismatched B XA_checked, XB_checked = check_pairwise_arrays(XA, XB.astype(np.float)) assert_equal(XA_checked.dtype, np.float) assert_equal(XB_checked.dtype, np.float)
bsd-3-clause
madjelan/scikit-learn
examples/tree/plot_tree_regression.py
206
1476
""" =================================================================== Decision Tree Regression =================================================================== A 1D regression with decision tree. The :ref:`decision trees <tree>` is used to fit a sine curve with addition noisy observation. As a result, it learns local linear regressions approximating the sine curve. 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 the necessary modules and libraries import numpy as np from sklearn.tree import DecisionTreeRegressor import matplotlib.pyplot as plt # Create a random dataset rng = np.random.RandomState(1) X = np.sort(5 * rng.rand(80, 1), axis=0) y = np.sin(X).ravel() y[::5] += 3 * (0.5 - rng.rand(16)) # Fit regression model regr_1 = DecisionTreeRegressor(max_depth=2) regr_2 = DecisionTreeRegressor(max_depth=5) regr_1.fit(X, y) regr_2.fit(X, y) # Predict X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis] y_1 = regr_1.predict(X_test) y_2 = regr_2.predict(X_test) # Plot the results plt.figure() plt.scatter(X, y, c="k", label="data") plt.plot(X_test, y_1, c="g", label="max_depth=2", linewidth=2) plt.plot(X_test, y_2, c="r", label="max_depth=5", linewidth=2) plt.xlabel("data") plt.ylabel("target") plt.title("Decision Tree Regression") plt.legend() plt.show()
bsd-3-clause
elkingtonmcb/scikit-learn
examples/ensemble/plot_forest_iris.py
335
6271
""" ==================================================================== Plot the decision surfaces of ensembles of trees on the iris dataset ==================================================================== Plot the decision surfaces of forests of randomized trees trained on pairs of features of the iris dataset. This plot compares the decision surfaces learned by a decision tree classifier (first column), by a random forest classifier (second column), by an extra- trees classifier (third column) and by an AdaBoost classifier (fourth column). In the first row, the classifiers are built using the sepal width and the sepal length features only, on the second row using the petal length and sepal length only, and on the third row using the petal width and the petal length only. In descending order of quality, when trained (outside of this example) on all 4 features using 30 estimators and scored using 10 fold cross validation, we see:: ExtraTreesClassifier() # 0.95 score RandomForestClassifier() # 0.94 score AdaBoost(DecisionTree(max_depth=3)) # 0.94 score DecisionTree(max_depth=None) # 0.94 score Increasing `max_depth` for AdaBoost lowers the standard deviation of the scores (but the average score does not improve). See the console's output for further details about each model. In this example you might try to: 1) vary the ``max_depth`` for the ``DecisionTreeClassifier`` and ``AdaBoostClassifier``, perhaps try ``max_depth=3`` for the ``DecisionTreeClassifier`` or ``max_depth=None`` for ``AdaBoostClassifier`` 2) vary ``n_estimators`` It is worth noting that RandomForests and ExtraTrees can be fitted in parallel on many cores as each tree is built independently of the others. AdaBoost's samples are built sequentially and so do not use multiple cores. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import clone from sklearn.datasets import load_iris from sklearn.ensemble import (RandomForestClassifier, ExtraTreesClassifier, AdaBoostClassifier) from sklearn.externals.six.moves import xrange from sklearn.tree import DecisionTreeClassifier # Parameters n_classes = 3 n_estimators = 30 plot_colors = "ryb" cmap = plt.cm.RdYlBu plot_step = 0.02 # fine step width for decision surface contours plot_step_coarser = 0.5 # step widths for coarse classifier guesses RANDOM_SEED = 13 # fix the seed on each iteration # Load data iris = load_iris() plot_idx = 1 models = [DecisionTreeClassifier(max_depth=None), RandomForestClassifier(n_estimators=n_estimators), ExtraTreesClassifier(n_estimators=n_estimators), AdaBoostClassifier(DecisionTreeClassifier(max_depth=3), n_estimators=n_estimators)] for pair in ([0, 1], [0, 2], [2, 3]): for model in models: # We only take the two corresponding features X = iris.data[:, pair] y = iris.target # Shuffle idx = np.arange(X.shape[0]) np.random.seed(RANDOM_SEED) np.random.shuffle(idx) X = X[idx] y = y[idx] # Standardize mean = X.mean(axis=0) std = X.std(axis=0) X = (X - mean) / std # Train clf = clone(model) clf = model.fit(X, y) scores = clf.score(X, y) # Create a title for each column and the console by using str() and # slicing away useless parts of the string model_title = str(type(model)).split(".")[-1][:-2][:-len("Classifier")] model_details = model_title if hasattr(model, "estimators_"): model_details += " with {} estimators".format(len(model.estimators_)) print( model_details + " with features", pair, "has a score of", scores ) plt.subplot(3, 4, plot_idx) if plot_idx <= len(models): # Add a title at the top of each column plt.title(model_title) # Now plot the decision boundary using a fine mesh as input to a # filled contour plot 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, plot_step), np.arange(y_min, y_max, plot_step)) # Plot either a single DecisionTreeClassifier or alpha blend the # decision surfaces of the ensemble of classifiers if isinstance(model, DecisionTreeClassifier): Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=cmap) else: # Choose alpha blend level with respect to the number of estimators # that are in use (noting that AdaBoost can use fewer estimators # than its maximum if it achieves a good enough fit early on) estimator_alpha = 1.0 / len(model.estimators_) for tree in model.estimators_: Z = tree.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, alpha=estimator_alpha, cmap=cmap) # Build a coarser grid to plot a set of ensemble classifications # to show how these are different to what we see in the decision # surfaces. These points are regularly space and do not have a black outline xx_coarser, yy_coarser = np.meshgrid(np.arange(x_min, x_max, plot_step_coarser), np.arange(y_min, y_max, plot_step_coarser)) Z_points_coarser = model.predict(np.c_[xx_coarser.ravel(), yy_coarser.ravel()]).reshape(xx_coarser.shape) cs_points = plt.scatter(xx_coarser, yy_coarser, s=15, c=Z_points_coarser, cmap=cmap, edgecolors="none") # Plot the training points, these are clustered together and have a # black outline for i, c in zip(xrange(n_classes), plot_colors): idx = np.where(y == i) plt.scatter(X[idx, 0], X[idx, 1], c=c, label=iris.target_names[i], cmap=cmap) plot_idx += 1 # move on to the next plot in sequence plt.suptitle("Classifiers on feature subsets of the Iris dataset") plt.axis("tight") plt.show()
bsd-3-clause
ArteliaTelemac/PostTelemac
PostTelemac/meshlayer/caduc/posttelemac_util_animation.py
1
14450
# -*- coding: utf-8 -*- # unicode behaviour from __future__ import unicode_literals # import numpy import numpy as np import matplotlib # import matplotlib # import PyQT from PyQt4 import QtCore, QtGui import qgis.utils import qgis.core # imports divers import time import os import tempfile import subprocess import shutil class PostTelemacAnimation(QtCore.QObject): def __init__(self, slf): QtCore.QObject.__init__(self) self.pluginlayer = slf self.tempdir = None self.fig = None self.vline = None self.outputtype = 1 def makeFilm(self): try: self.pluginlayer.propertiesdialog.tabWidget.setCurrentIndex(2) qgis.utils.iface.mapCanvas().freeze(True) txt = time.ctime() + " Film - NE PAS MODIFIER L'ESPACE DESSIN DURANT L'OPERATION " if self.outputtype: self.pluginlayer.propertiesdialog.textBrowser_2.append(txt) else: self.status.emit(txt) # Cherche le composeur voulu for composeurview in qgis.utils.iface.activeComposers(): if ( composeurview.composerWindow().windowTitle() == self.pluginlayer.propertiesdialog.comboBox_compositions.currentText() ): composition = composeurview.composition() # Cree les paths souhaités self.tempdir = tempfile.mkdtemp() # path to temp dir where png are stored dir = os.path.dirname(self.pluginlayer.hydraufilepath) # dir of sl file where movie will be put" nameslf = os.path.basename(self.pluginlayer.hydraufilepath).split(".")[0] nameavi = os.path.join(dir, nameslf + ".avi") txt = time.ctime() + " - Film - creation du fichier " + str(nameavi) if self.outputtype: self.pluginlayer.propertiesdialog.textBrowser_2.append(txt) else: self.status.emit(txt) # init max, min , time step min1 = self.pluginlayer.propertiesdialog.spinBox_2.value() max1 = self.pluginlayer.propertiesdialog.spinBox_3.value() pas = self.pluginlayer.propertiesdialog.spinBox_4.value() fps = self.pluginlayer.propertiesdialog.spinBox_fps.value() # Init matplotlib things if an image is choosen ************************************************************************** ax = None matplotlibimagepath = None self.fig = None maps = [ item for item in composition.items() if item.type() == qgis.core.QgsComposerItem.ComposerMap and item.scene() ] images = [ item for item in composition.items() if item.type() == qgis.core.QgsComposerItem.ComposerPicture and item.scene() ] legends = [ item for item in composition.items() if item.type() == qgis.core.QgsComposerItem.ComposerLegend and item.scene() ] if self.pluginlayer.propertiesdialog.comboBox_8.currentIndex() != 0: for image in images: if image.id() == self.pluginlayer.propertiesdialog.comboBox_8.currentText(): composeurimage = image rectimage = np.array( [composeurimage.rectWithFrame().width(), composeurimage.rectWithFrame().height()] ) # size img in mm in composer width if self.pluginlayer.propertiesdialog.comboBox_9.currentIndex() == 0: self.fig = self.pluginlayer.propertiesdialog.figure1 canvas = self.pluginlayer.propertiesdialog.canvas1 ax = self.pluginlayer.propertiesdialog.ax elif self.pluginlayer.propertiesdialog.comboBox_9.currentIndex() == 1: self.fig = self.pluginlayer.propertiesdialog.figure2 canvas = self.pluginlayer.propertiesdialog.canvas2 ax = self.pluginlayer.propertiesdialog.ax2 # making the figure the size of the image rectfig = [self.fig.get_size_inches()[0], self.fig.get_size_inches()[1]] facteurconversion = float(composition.printResolution()) / 80.0 rectimage = rectimage / 25.4 * facteurconversion self.fig.set_size_inches(float(rectimage[0]), float(rectimage[1]), forward=True) # search matplotlib supported format tempmplsupportedfile = self.fig.canvas.get_supported_filetypes() if "svg" in tempmplsupportedfile: mplformat = "svg" elif "jpg" in tempmplsupportedfile: mplformat = "jpg" elif "png" in tempmplsupportedfile: mplformat = "png" # Main part : creating the png files ****************************************** compt = 0 for i in range(min1, max1 + 1): if i % pas == 0: if self.fig != None: try: if False: # modifying ax to show the time self.addtimelineonax(ax, self.pluginlayer.hydrauparser.getTimes()[i]) # saving the figure matplotlibimagepath = os.path.join(self.tempdir, "test" + "%04d" % compt + ".jpg") # print str(matplotlibimagepath) self.fig.savefig(matplotlibimagepath, format="jpg", dpi=80) # fig.savefig(matplotlibimagepath ) else: # modifying ax to show the time self.addtimelineonax(ax, self.pluginlayer.hydrauparser.getTimes()[i]) # saving the figure matplotlibimagepath = os.path.join( self.tempdir, "test" + "%04d" % compt + "." + mplformat ) # print str(matplotlibimagepath) # fig.savefig(matplotlibimagepath,format='png',dpi = 80 ) # fig.canvas.print_figure(matplotlibimagepath,format='png',dpi = 80 ) self.fig.canvas.print_figure(matplotlibimagepath, dpi=80) # fig.savefig(matplotlibimagepath ) # print 'ok1_2' composeurimage.setPicturePath(matplotlibimagepath) except Exception, e: # print 'saveimg ' + str(e) pass self.pluginlayer.changeTime(i) txt = time.ctime() + " - Film - iteration n " + str(self.pluginlayer.time_displayed) if self.outputtype: self.pluginlayer.propertiesdialog.textBrowser_2.append(txt) else: self.status.emit(txt) # print 'ok3' # Update drawing space and composer space self.pluginlayer.triggerRepaint() for map in maps: map.updateItem() # format='jpg' formatcomposer = "png" finlename = "img" + "%04d" % compt + "." + formatcomposer filename1 = os.path.join(self.tempdir, finlename) if True: image = composition.printPageAsRaster(0) else: # test width = composition.printResolution() * composition.paperWidth() / 25.4 height = composition.printResolution() * composition.paperHeight() / 25.4 image = QImage(QSize(width, height), QImage.Format_ARGB32) image.setDotsPerMeterX(composition.printResolution() / 25.4 * 1000) image.setDotsPerMeterY(composition.printResolution() / 25.4 * 1000) image.fill(0) imagePainter = QPainter(image) composition.renderPage(imagePainter, 0) for legend in legends: s = legend.paintAndDetermineSize(imagePainter) # image.save(filename1,format) image.save(filename1) if compt == 0: # image.save(os.path.join(dir,nameslf+'_preview.'+format),format) image.save(os.path.join(dir, nameslf + "_preview." + formatcomposer)) txt = ( time.ctime() + " - Film - previsulation du film ici : " + str(os.path.join(dir, nameslf + "_preview." + formatcomposer)) ) if self.outputtype: self.pluginlayer.propertiesdialog.textBrowser_2.append(txt) else: self.status.emit(txt) compt = compt + 1 tmp_img_dir = os.path.join(self.tempdir, "img%04d." + formatcomposer) # Create the video ***************************************** output_file = nameavi ffmpeg_res, logfile = self.images_to_video(tmp_img_dir, output_file, fps) if ffmpeg_res: shutil.rmtree(self.tempdir) txt = time.ctime() + " - Film - fichier cree " + str(nameavi) if self.outputtype: self.pluginlayer.propertiesdialog.textBrowser_2.append(txt) else: self.status.emit(txt) else: txt = time.ctime() + " - Film - erreur " if self.outputtype: self.pluginlayer.propertiesdialog.textBrowser_2.append(txt) else: self.status.emit(txt) qgis.utils.iface.mapCanvas().freeze(False) except Exception, e: txt = str(e) if self.outputtype: self.pluginlayer.propertiesdialog.textBrowser_2.append("make movie : " + txt) else: self.status.emit("make movie : " + txt) if self.fig: if self.vline: ax.lines.remove(self.vline) self.fig.set_size_inches(rectfig[0], rectfig[1], forward=True) canvas.draw() self.finished.emit() def images_to_video( self, tmp_img_dir="/tmp/vid/%03d.png", output_file="/tmp/vid/test.avi", fps=10, qual=1, ffmpeg_bin="ffmpeg" ): # print 'im ' + str(tmp_img_dir) + ' output ' + str(output_file) if qual == 0: # lossless opts = ["-vcodec", "ffv1"] else: bitrate = 10000 if qual == 1 else 2000 opts = ["-vcodec", "mpeg4", "-b", str(bitrate) + "K"] if False: # if images do not start with 1: -start_number 14 cmd = [ffmpeg_bin, "-f", "image2", "-framerate", str(fps), "-i", tmp_img_dir] cmd += opts cmd += ["-r", str(fps), "-f", "avi", "-y", output_file] # f = os.mknod(os.path.join(os.path.dirname(tmp_img_dir),"newfile.txt")) f = open(os.path.join(os.path.dirname(tmp_img_dir), "newfile.txt"), "a") # f.close() # f = tempfile.NamedTemporaryFile(prefix="crayfish",suffix=".txt") f.write(unicode(cmd).encode("utf8") + "\n\n") # stdin redirection is necessary in some cases on Windows res = subprocess.call(cmd, shell=True, stdin=subprocess.PIPE, stdout=f, stderr=f) else: # if images do not start with 1: -start_number 14 cmd = [ffmpeg_bin, "-f", "image2", "-framerate", str(fps), "-i", tmp_img_dir] cmd += opts cmd += ["-r", str(fps), "-f", "avi", "-y", output_file] # f = os.mknod(os.path.join(os.path.dirname(tmp_img_dir),"newfile.txt")) f = open(os.path.join(os.path.dirname(tmp_img_dir), "newfile.txt"), "a") # f.close() # f = tempfile.NamedTemporaryFile(prefix="crayfish",suffix=".txt") f.write(unicode(cmd).encode("utf8") + "\n\n") # stdin redirection is necessary in some cases on Windows res = subprocess.call(cmd, shell=False, stdin=subprocess.PIPE, stdout=f, stderr=f) if res != 0: # f.delete = False # keep the file on error f.close() return res == 0, f.name def addtimelineonax(self, ax1, time1): if self.vline: ax1.lines.remove(self.vline) self.vline = ax1.axvline(time1, linewidth=2, color="k") status = QtCore.pyqtSignal(str) finished = QtCore.pyqtSignal() printimage = QtCore.pyqtSignal(str, str, int, str) """ class initPostTelemacAnimation(QtCore.QObject): def __init__(self): QtCore.QObject.__init__(self) self.thread = QtCore.QThread() self.worker = None def start(self, selafin): #Launch worker self.worker = PostTelemacAnimation(selafin) self.worker.moveToThread(self.thread) self.thread.started.connect(self.worker.makeFilm) self.worker.status.connect(self.writeOutput) #self.worker.printimage.connect(self.printImage) self.worker.finished.connect(self.workerFinished) self.worker.finished.connect(self.worker.deleteLater) self.thread.finished.connect(self.thread.deleteLater) self.worker.finished.connect(self.thread.quit) self.thread.start() def writeOutput(self,str1): self.status.emit(str(str1)) def workerFinished(self): self.finished1.emit() def printImage(self,str1,str2,int1,str3): self.printimage.emit(str1,str2,int1,str3) printimage = QtCore.pyqtSignal(str,str,int,str) status = QtCore.pyqtSignal(str) finished1 = QtCore.pyqtSignal() """
gpl-3.0
TimeWz667/Kamanian
example/Chapter 7.1 TB model.py
1
8240
import complexism as cx import pandas as pd import numpy as np import numpy.random as rd mat = pd.read_csv('../data/SimFM.csv') ds = cx.DemographySex() ds.load_birth_data(mat, i_year='Year', i_f='BirthF', i_m='BirthM') ds.load_death_data(mat, i_year='Year', i_f='DeathF', i_m='DeathM') ds.load_migration_data(mat, i_year='Year', i_f='MigrationF', i_m='MigrationM') ds.load_population_data(mat, i_year='Year', i_f='PopF', i_m='PopM') ds.complete_loading() mat_a = pd.read_csv('../data/LCA/LCA.Age.csv') mat_t = pd.read_csv('../data/LCA/LCA.Time.csv') mat_bf = pd.read_csv('../data/LCA/BirR.Female.csv') mat_bm = pd.read_csv('../data/LCA/BirR.Male.csv') mat_af = pd.read_csv('../data/LCA/PopStart.Female.csv') mat_am = pd.read_csv('../data/LCA/PopStart.Male.csv') mat_af = mat_af.fillna(0) mat_am = mat_am.fillna(0) lcp = cx.DemographyLeeCarter() lcp.load_death_female(mat_a, mat_t, i_year='Year', i_age='Age', i_al='ax_f', i_be='bx_f', i_ka='female') lcp.load_death_male(mat_a, mat_t, i_year='Year', i_age='Age', i_al='ax_m', i_be='bx_m', i_ka='male') lcp.load_birth_female(mat_bf, i_year='Year', i_rate='br') lcp.load_birth_male(mat_bm, i_year='Year', i_rate='br') lcp.load_pop_female(mat_af, i_year='Year', ages=range(0, 101)) lcp.load_pop_male(mat_am, i_year='Year', ages=range(0, 101)) lcp.complete_loading() def TB_ODE(y, t, p, x): sus_f, sus_m, flat_f, flat_m, slat_f, slat_m, rec_f, rec_m = y n = y.sum() + x['N_abm'] n_f = sus_f + flat_f + slat_f + rec_f n_m = sus_m + flat_m + slat_m + rec_m foi = x['Inf'] * p['r_tr'] / n life = x['life'] brs = life.get_birth_rate(t) mrs = life.get_migration_rate(t) drs = life.get_death_rate(t) in_f = mrs['Female'] - drs['Female'] in_m = mrs['Male'] - drs['Male'] dy = [ n_f * brs['Female'] + sus_f * (foi + in_f), n_m * brs['Male'] + sus_m * (foi + in_m), sus_f * foi + flat_f * (- p['r_slat'] + in_f), sus_m * foi + flat_m * (- p['r_slat'] + in_m), flat_f * p['r_slat'] + slat_f * in_f, flat_m * p['r_slat'] + slat_m * in_m, rec_f * in_f, rec_m * in_m ] return np.array(dy) def TB_Measure(y, t, p, x): ne = y.sum() return { 'N_ebm': ne, 'Sus': y[0] + y[1], 'FLat': y[2] + y[3], 'SLat': y[4] + y[5], 'Rec': y[6] + y[7], 'N': ne + x['N_abm'] } class InfIn(cx.ImpulseResponse): def __init__(self): self.Last = None def initialise(self, ti): self.Last = ti def __call__(self, disclosure, model_foreign, model_local, ti): if self.Last: dt = ti - self.Last self.Last = ti if dt > 0: r_act = model_local.get_parameter('r_act') act_f = self.__calculate_birth_number(model_foreign.Y['LatFastF'], r_act, dt) act_m = self.__calculate_birth_number(model_foreign.Y['LatFastM'], r_act, dt) model_local.shock(ti, 'ActIn', n=act_f, Type='Activation', Sex='Female') model_local.shock(ti, 'ActIn', n=act_m, Type='Activation', Sex='Male') r_ract = model_local.get_parameter('r_ract') ract_f = self.__calculate_birth_number(model_foreign.Y['LatSlowF'], r_ract, dt) ract_m = self.__calculate_birth_number(model_foreign.Y['LatSlowM'], r_ract, dt) model_local.shock(ti, 'ActIn', n=ract_f, Type='Reactivation', Sex='Female') model_local.shock(ti, 'ActIn', n=ract_m, Type='Reactivation', Sex='Male') r_rel = model_local.get_parameter('r_rel') rel_f = self.__calculate_birth_number(model_foreign.Y['RecF'], r_rel, dt) rel_m = self.__calculate_birth_number(model_foreign.Y['RecM'], r_rel, dt) model_local.shock(ti, 'ActIn', n=rel_f, Type='Relapse', Sex='Female') model_local.shock(ti, 'ActIn', n=rel_m, Type='Relapse', Sex='Male') print(ti) # print(act_f+ract_f+rel_f) # return 'ActIn', {'n': act_f, } else: self.Last = ti def __calculate_birth_number(self, n, rate, dt): n = np.floor(n) if n <= 0: return 0 lam = rate * n * dt if lam < 5: nb = rd.poisson(lam) else: nb = rd.binomial(n, - np.expm1(-rate * dt)) return min(nb, n) class ToRecImpulse(cx.ImpulseResponse): def __call__(self, disclosure, model_foreign, model_local, ti): if disclosure['Sex'] == 'Female': return 'add', {'y': 'RecF', 'n': 1} else: return 'add', {'y': 'RecM', 'n': 1} ctrl = cx.Director() ctrl.load_bayes_net('scripts/tb/ptb.txt') ctrl.load_state_space_model('scripts/tb/dtb_cases.txt') ctrl.list_bayes_nets(), ctrl.list_state_spaces() # ABM definition mbp_i = ctrl.new_sim_model('I', 'StSpABM') mbp_i.set_agent(prefix='Ag', group='AgI', dynamics='Active') mbp_i.add_behaviour('Dead', 'CohortLeeCarter', s_death='Dead', t_die='Die', dlc=lcp) mbp_i.add_behaviour('Recovery', 'Cohort', s_death='PostCare') mbp_i.add_behaviour('ActIn', 'AgentImport', s_birth='Act') mbp_i.add_behaviour('StInf', 'StateTrack', s_src='Inf') mbp_i.set_observations(states=['Alive', 'PreCare', 'InCare'], transitions=['Treat', 'Die', 'Die_TB'], behaviours=['ActIn']) # EBM definition mbp_ser = ctrl.new_sim_model('SER', 'ODEEBM') ys = ['SusF', 'SusM', 'LatFastF', 'LatFastM', 'LatSlowF', 'LatSlowM', 'RecF', 'RecM'] mbp_ser.set_fn_ode(TB_ODE, ys) mbp_ser.set_external_variables({'Inf': 0, 'N_abm': 0, 'life': ds}) mbp_ser.set_dt(dt=0.05, odt=0.5) mbp_ser.add_observing_function(TB_Measure) scale = 0.01 y0_i = mbp_i.get_y0_proto() y0_i.define(st='Act', n=1) y0_ser = mbp_ser.get_y0_proto() ns = {k: v.sum() for k, v in ds.get_population(1990).items()} y0_ser.define(st='SusF', n=ns['Female'] * 0.75 * scale) y0_ser.define(st='SusM', n=ns['Male'] * 0.75 * scale) y0_ser.define(st='LatSlowF', n=ns['Female'] * 0.125 * scale) y0_ser.define(st='LatSlowM', n=ns['Male'] * 0.125 * scale) y0_ser.define(st='RecF', n=ns['Female'] * 0.125) y0_ser.define(st='RecM', n=ns['Male'] * 0.125) lyo = ctrl.new_sim_model('SEIR', 'MultiModel') lyo.add_entry('i', 'I', y0_i) lyo.add_entry('ser', 'SER', y0_ser) lyo.add_interaction('ser', cx.WhoStartWithChecker('StInf', 'update value'), cx.ValueImpulse('Inf', 'v1')) lyo.add_interaction('ser', cx.WhoStartWithChecker('Recovery', 'remove agent'), ToRecImpulse()) lyo.add_interaction('ser', cx.StartsWithAndMatchesChecker('add', {'Type': 'Activation', 'Sex': 'Female'}), cx.MinusNImpulse('LatFastF', 'n')) lyo.add_interaction('ser', cx.StartsWithAndMatchesChecker('add', {'Type': 'Activation', 'Sex': 'Male'}), cx.MinusNImpulse('LatFastM', 'n')) lyo.add_interaction('ser', cx.StartsWithAndMatchesChecker('add', {'Type': 'Reactivation', 'Sex': 'Female'}), cx.MinusNImpulse('LatSlowF', 'n')) lyo.add_interaction('ser', cx.StartsWithAndMatchesChecker('add', {'Type': 'Reactivation', 'Sex': 'Male'}), cx.MinusNImpulse('LatSlowM', 'n')) lyo.add_interaction('ser', cx.StartsWithAndMatchesChecker('add', {'Type': 'Relapse', 'Sex': 'Female'}), cx.MinusNImpulse('RecF', 'n')) lyo.add_interaction('ser', cx.StartsWithAndMatchesChecker('add', {'Type': 'Relapse', 'Sex': 'Male'}), cx.MinusNImpulse('RecM', 'n')) lyo.add_interaction('i', cx.IsChecker('update'), InfIn()) lyo.set_observations() model = ctrl.generate_model('M1', 'SEIR', bn='pTB') y0 = ctrl.get_y0s('SEIR') cx.start_counting() out = cx.simulate(model, y0, 1990, 2000, 1, log=False) cx.stop_counting() print(out) print(cx.get_counting_results())
mit
pv/scikit-learn
examples/applications/plot_species_distribution_modeling.py
254
7434
""" ============================= Species distribution modeling ============================= Modeling species' geographic distributions is an important problem in conservation biology. In this example we model the geographic distribution of two south american mammals given past observations and 14 environmental variables. Since we have only positive examples (there are no unsuccessful observations), we cast this problem as a density estimation problem and use the `OneClassSVM` provided by the package `sklearn.svm` as our modeling tool. The dataset is provided by Phillips et. al. (2006). If available, the example uses `basemap <http://matplotlib.sourceforge.net/basemap/doc/html/>`_ to plot the coast lines and national boundaries of South America. The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/apps/redlist/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/apps/redlist/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. References ---------- * `"Maximum entropy modeling of species geographic distributions" <http://www.cs.princeton.edu/~schapire/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. """ # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> # Jake Vanderplas <vanderplas@astro.washington.edu> # # License: BSD 3 clause from __future__ import print_function from time import time import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.base import Bunch from sklearn.datasets import fetch_species_distributions from sklearn.datasets.species_distributions import construct_grids from sklearn import svm, metrics # if basemap is available, we'll use it. # otherwise, we'll improvise later... try: from mpl_toolkits.basemap import Basemap basemap = True except ImportError: basemap = False print(__doc__) def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid): """Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name. """ bunch = Bunch(name=' '.join(species_name.split("_")[:2])) species_name = species_name.encode('ascii') points = dict(test=test, train=train) for label, pts in points.items(): # choose points associated with the desired species pts = pts[pts['species'] == species_name] bunch['pts_%s' % label] = pts # determine coverage values for each of the training & testing points ix = np.searchsorted(xgrid, pts['dd long']) iy = np.searchsorted(ygrid, pts['dd lat']) bunch['cov_%s' % label] = coverages[:, -iy, ix].T return bunch def plot_species_distribution(species=("bradypus_variegatus_0", "microryzomys_minutus_0")): """ Plot the species distribution. """ if len(species) > 2: print("Note: when more than two species are provided," " only the first two will be used") t0 = time() # Load the compressed data data = fetch_species_distributions() # Set up the data grid xgrid, ygrid = construct_grids(data) # The grid in x,y coordinates X, Y = np.meshgrid(xgrid, ygrid[::-1]) # create a bunch for each species BV_bunch = create_species_bunch(species[0], data.train, data.test, data.coverages, xgrid, ygrid) MM_bunch = create_species_bunch(species[1], data.train, data.test, data.coverages, xgrid, ygrid) # background points (grid coordinates) for evaluation np.random.seed(13) background_points = np.c_[np.random.randint(low=0, high=data.Ny, size=10000), np.random.randint(low=0, high=data.Nx, size=10000)].T # We'll make use of the fact that coverages[6] has measurements at all # land points. This will help us decide between land and water. land_reference = data.coverages[6] # Fit, predict, and plot for each species. for i, species in enumerate([BV_bunch, MM_bunch]): print("_" * 80) print("Modeling distribution of species '%s'" % species.name) # Standardize features mean = species.cov_train.mean(axis=0) std = species.cov_train.std(axis=0) train_cover_std = (species.cov_train - mean) / std # Fit OneClassSVM print(" - fit OneClassSVM ... ", end='') clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.5) clf.fit(train_cover_std) print("done.") # Plot map of South America plt.subplot(1, 2, i + 1) if basemap: print(" - plot coastlines using basemap") m = Basemap(projection='cyl', llcrnrlat=Y.min(), urcrnrlat=Y.max(), llcrnrlon=X.min(), urcrnrlon=X.max(), resolution='c') m.drawcoastlines() m.drawcountries() else: print(" - plot coastlines from coverage") plt.contour(X, Y, land_reference, levels=[-9999], colors="k", linestyles="solid") plt.xticks([]) plt.yticks([]) print(" - predict species distribution") # Predict species distribution using the training data Z = np.ones((data.Ny, data.Nx), dtype=np.float64) # We'll predict only for the land points. idx = np.where(land_reference > -9999) coverages_land = data.coverages[:, idx[0], idx[1]].T pred = clf.decision_function((coverages_land - mean) / std)[:, 0] Z *= pred.min() Z[idx[0], idx[1]] = pred levels = np.linspace(Z.min(), Z.max(), 25) Z[land_reference == -9999] = -9999 # plot contours of the prediction plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds) plt.colorbar(format='%.2f') # scatter training/testing points plt.scatter(species.pts_train['dd long'], species.pts_train['dd lat'], s=2 ** 2, c='black', marker='^', label='train') plt.scatter(species.pts_test['dd long'], species.pts_test['dd lat'], s=2 ** 2, c='black', marker='x', label='test') plt.legend() plt.title(species.name) plt.axis('equal') # Compute AUC with regards to background points pred_background = Z[background_points[0], background_points[1]] pred_test = clf.decision_function((species.cov_test - mean) / std)[:, 0] scores = np.r_[pred_test, pred_background] y = np.r_[np.ones(pred_test.shape), np.zeros(pred_background.shape)] fpr, tpr, thresholds = metrics.roc_curve(y, scores) roc_auc = metrics.auc(fpr, tpr) plt.text(-35, -70, "AUC: %.3f" % roc_auc, ha="right") print("\n Area under the ROC curve : %f" % roc_auc) print("\ntime elapsed: %.2fs" % (time() - t0)) plot_species_distribution() plt.show()
bsd-3-clause
rvraghav93/scikit-learn
sklearn/utils/tests/test_murmurhash.py
79
2849
# Author: Olivier Grisel <olivier.grisel@ensta.org> # # License: BSD 3 clause import numpy as np from sklearn.externals.six import b, u from sklearn.utils.murmurhash import murmurhash3_32 from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal from sklearn.utils.testing import assert_equal, assert_true def test_mmhash3_int(): assert_equal(murmurhash3_32(3), 847579505) assert_equal(murmurhash3_32(3, seed=0), 847579505) assert_equal(murmurhash3_32(3, seed=42), -1823081949) assert_equal(murmurhash3_32(3, positive=False), 847579505) assert_equal(murmurhash3_32(3, seed=0, positive=False), 847579505) assert_equal(murmurhash3_32(3, seed=42, positive=False), -1823081949) assert_equal(murmurhash3_32(3, positive=True), 847579505) assert_equal(murmurhash3_32(3, seed=0, positive=True), 847579505) assert_equal(murmurhash3_32(3, seed=42, positive=True), 2471885347) def test_mmhash3_int_array(): rng = np.random.RandomState(42) keys = rng.randint(-5342534, 345345, size=3 * 2 * 1).astype(np.int32) keys = keys.reshape((3, 2, 1)) for seed in [0, 42]: expected = np.array([murmurhash3_32(int(k), seed) for k in keys.flat]) expected = expected.reshape(keys.shape) assert_array_equal(murmurhash3_32(keys, seed), expected) for seed in [0, 42]: expected = np.array([murmurhash3_32(k, seed, positive=True) for k in keys.flat]) expected = expected.reshape(keys.shape) assert_array_equal(murmurhash3_32(keys, seed, positive=True), expected) def test_mmhash3_bytes(): assert_equal(murmurhash3_32(b('foo'), 0), -156908512) assert_equal(murmurhash3_32(b('foo'), 42), -1322301282) assert_equal(murmurhash3_32(b('foo'), 0, positive=True), 4138058784) assert_equal(murmurhash3_32(b('foo'), 42, positive=True), 2972666014) def test_mmhash3_unicode(): assert_equal(murmurhash3_32(u('foo'), 0), -156908512) assert_equal(murmurhash3_32(u('foo'), 42), -1322301282) assert_equal(murmurhash3_32(u('foo'), 0, positive=True), 4138058784) assert_equal(murmurhash3_32(u('foo'), 42, positive=True), 2972666014) def test_no_collision_on_byte_range(): previous_hashes = set() for i in range(100): h = murmurhash3_32(' ' * i, 0) assert_true(h not in previous_hashes, "Found collision on growing empty string") def test_uniform_distribution(): n_bins, n_samples = 10, 100000 bins = np.zeros(n_bins, dtype=np.float64) for i in range(n_samples): bins[murmurhash3_32(i, positive=True) % n_bins] += 1 means = bins / n_samples expected = np.ones(n_bins) / n_bins assert_array_almost_equal(means / expected, np.ones(n_bins), 2)
bsd-3-clause
shangwuhencc/scikit-learn
examples/svm/plot_separating_hyperplane.py
294
1273
""" ========================================= SVM: Maximum margin separating hyperplane ========================================= Plot the maximum margin separating hyperplane within a two-class separable dataset using a Support Vector Machine classifier with linear kernel. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm # we create 40 separable points np.random.seed(0) X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] Y = [0] * 20 + [1] * 20 # fit the model clf = svm.SVC(kernel='linear') clf.fit(X, Y) # get the separating hyperplane w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - (clf.intercept_[0]) / w[1] # plot the parallels to the separating hyperplane that pass through the # support vectors b = clf.support_vectors_[0] yy_down = a * xx + (b[1] - a * b[0]) b = clf.support_vectors_[-1] yy_up = a * xx + (b[1] - a * b[0]) # plot the line, the points, and the nearest vectors to the plane plt.plot(xx, yy, 'k-') plt.plot(xx, yy_down, 'k--') plt.plot(xx, yy_up, 'k--') plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors='none') plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) plt.axis('tight') plt.show()
bsd-3-clause
gandalf221553/CodeSection
compilare/avviacompilatore.py
1
1302
# -*- coding: utf-8 -*- """ Created on Wed Mar 15 16:30:29 2017 @author: Von Braun """ #import os #a=os.getcwd() #os.chdir("kivy-examples\\canvas") import PyInstaller.__main__ print(dir()) #PyInstaller.__main__.run(["-y", "-w","circle.py"]) #os.chdir(a) #import PyInstaller.__main__ PyInstaller.__main__.run(["-y", "-w","kivy_matplotlib.py"]) """ api-ms-win-core-errorhandling-l1-1-0.dll api-ms-win-core-file-l2-1-0.dll api-ms-win-core-processthreads-l1-1-1.dll api-ms-win-core-synch-l1-1-0.dll api-ms-win-core-localization-l1-2-0.dll api-ms-win-core-datetime-l1-1-0.dll api-ms-win-core-handle-l1-1-0.dll api-ms-win-core-interlocked-l1-1-0.dll api-ms-win-core-memory-l1-1-0.dll api-ms-win-core-processenvironment-l1-1-0.dll api-ms-win-core-namedpipe-l1-1-0.dll api-ms-win-core-processthreads-l1-1-0.dll api-ms-win-core-synch-l1-2-0.dll api-ms-win-core-profile-l1-1-0.dll api-ms-win-core-libraryloader-l1-1-0.dll api-ms-win-core-string-l1-1-0.dll api-ms-win-core-console-l1-1-0.dll api-ms-win-core-sysinfo-l1-1-0.dll api-ms-win-core-file-l1-2-0.dll api-ms-win-core-heap-l1-1-0.dll api-ms-win-core-debug-l1-1-0.dll api-ms-win-core-file-l1-1-0.dll api-ms-win-core-timezone-l1-1-0.dll api-ms-win-core-rtlsupport-l1-1-0.dll api-ms-win-core-util-l1-1-0.dll """
mit
tcstewar/nengo_plot
nengo_plot/time.py
1
6056
import core import numpy import matplotlib import scipy.ndimage import scipy.cluster class Time(core.Plot): def __init__(self, time, time_range=None, ylabel_rotation='vertical', **args): core.Plot.__init__(self,**args) self.time = time self.xlim = time_range self.ylabel_rotation = ylabel_rotation self.subplots = [] self.heights = [] def _fix_plots(self): totalh=float(sum(self.heights)) space=self.fig.subplotpars.top-self.fig.subplotpars.bottom y=self.fig.subplotpars.top for i,plot in enumerate(self.subplots): h=space/totalh*self.heights[i] plot.set_position((self.fig.subplotpars.left,y-h,self.fig.subplotpars.right-self.fig.subplotpars.left,h)) y-=h if i<len(self.subplots)-1: plot.set_xticklabels(['']*len(plot.get_xticks())) plot.set_xlabel('') else: plot.set_xlabel('time (s)') def _create_axes(self,label,height): self.heights.append(height) if len(self.subplots)==0: axes=self.axes else: axes=self.fig.add_subplot(len(self.subplots)+1,1,len(self.subplots)+1) if self.xlim is not None: axes.set_xlim(self.xlim) self.subplots.append(axes) self._fix_plots() axes.set_ylabel(label, rotation=self.ylabel_rotation) return axes def _add_overlays(self, axes, overlays): min, max = axes.get_ylim() mid = (min+max)/2 for t, text in overlays: axes.text(t, mid, text, ha='center', va='center', fontsize=12, weight='bold') def add(self, label, data, height=1, linewidth=1, range=None, overlays=[]): axes=self._create_axes(label,height) if len(data.shape)<2: data=numpy.array([data]) for i,line in enumerate(data.T): c=self.theme.line_color(i) axes.plot(self.time,line,color=c,linewidth=linewidth) if range is not None: axes.set_ylim(range) self._add_overlays(axes, overlays) def add_spikes(self, label, data, height=1, sample_by_variance=None, sample=None, sample_filter_width=20, cluster=False, cluster_filter_width=2, merge=None, contrast_scale=1.0, yticks=None, style='image', sample_index=None, cluster_index=None, overlays=[]): axes=self._create_axes(label,height) if sample_index: data = data[:, sample_index] elif sample_by_variance is not None and sample_by_variance<len(data.T): dd=scipy.ndimage.gaussian_filter1d(data.astype(float).T,sample_filter_width,axis=1) vard=numpy.var(dd,axis=1) threshold=sorted(vard)[-sample_by_variance] index=[k for k,v in enumerate(vard) if v>=threshold] data=data[:,index] self.sample_index = index if sample is not None and sample<len(data.T): stepsize=float(len(data.T))/sample data2=[] for k in range(sample): sub=data[:,int(k*stepsize):int((k+1)*stepsize)] count=numpy.sum(sub,axis=0) maxv=max(count) for i,v in enumerate(count): if v==maxv: data2.append(sub[:,i]) break data=numpy.array(data2).T if cluster_index: data = data[:, cluster_index] elif cluster: dd=scipy.ndimage.gaussian_filter1d(data.astype(float).T,cluster_filter_width,axis=1) z=scipy.cluster.hierarchy.linkage(dd) tree=scipy.cluster.hierarchy.to_tree(z) order=tree.pre_order() data=data[:,order] self.cluster_index = order if merge is not None and merge<len(data.T): stepsize=float(len(data.T))/merge data2=[] for k in range(merge): v=numpy.sum(data[:,int(k*stepsize):int((k+1)*stepsize)],axis=1) data2.append(v) data=numpy.array(data2).T if style=='image': imgplt=axes.imshow(data.T,aspect='auto',cmap=matplotlib.cm.gray_r,interpolation='nearest',extent=(self.time[0],self.time[-1],0,len(data.T))) imgplt.set_clim(0.0,numpy.max(data)*contrast_scale) elif style=='box': vmax=float(numpy.max(data)) N=len(data.T) dt=self.time[1][0]-self.time[0][0] for i,t in enumerate(self.time): t=t[0] for j in range(N): if data[i][j]>0: c=(1.0-data[i][j]/(vmax*contrast_scale)) if c<0: c=0 c='%0.2f'%c axes.axvspan(t,t+dt,1.0-(j+1)/float(N),1.0-(j)/float(N),fc=c,linewidth=0) axes.set_ylim((0,N)) elif style=='dot': vmax=float(numpy.max(data)) N=len(data.T) for i,t in enumerate(self.time): t=t[0] neurons=[] colors=[] for j in range(N): if data[i][j]>0: c=(1.0-data[i][j]/(vmax*contrast_scale)) if c<0: c=0 c='%0.2f'%c colors.append(c) neurons.append(N-j-1) if len(neurons)>0: axes.scatter([t]*len(neurons),neurons,s=1,c=colors,linewidths=0,marker='o') axes.set_ylim((0,N)) if yticks is None: axes.set_yticklabels(['']*len(axes.get_yticks())) else: delta=float(len(data.T))/len(yticks) vals=[(len(yticks)-i-0.5)*delta for i in range(len(yticks))] axes.set_yticks(vals) axes.set_yticklabels(yticks) self._add_overlays(axes, overlays)
gpl-2.0
virneo/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
arjoly/scikit-learn
sklearn/cross_decomposition/cca_.py
209
3150
from .pls_ import _PLS __all__ = ['CCA'] class CCA(_PLS): """CCA Canonical Correlation Analysis. CCA inherits from PLS with mode="B" and deflation_mode="canonical". Read more in the :ref:`User Guide <cross_decomposition>`. Parameters ---------- n_components : int, (default 2). number of components to keep. scale : boolean, (default True) whether to scale the data? max_iter : an integer, (default 500) the maximum number of iterations of the NIPALS inner loop tol : non-negative real, default 1e-06. the tolerance used in the iterative algorithm copy : boolean Whether the deflation be done on a copy. Let the default value to True unless you don't care about side effects Attributes ---------- x_weights_ : array, [p, n_components] X block weights vectors. y_weights_ : array, [q, n_components] Y block weights vectors. x_loadings_ : array, [p, n_components] X block loadings vectors. y_loadings_ : array, [q, n_components] Y block loadings vectors. x_scores_ : array, [n_samples, n_components] X scores. y_scores_ : array, [n_samples, n_components] Y scores. x_rotations_ : array, [p, n_components] X block to latents rotations. y_rotations_ : array, [q, n_components] Y block to latents rotations. n_iter_ : array-like Number of iterations of the NIPALS inner loop for each component. Notes ----- For each component k, find the weights u, v that maximizes max corr(Xk u, Yk v), such that ``|u| = |v| = 1`` Note that it maximizes only the correlations between the scores. The residual matrix of X (Xk+1) block is obtained by the deflation on the current X score: x_score. The residual matrix of Y (Yk+1) block is obtained by deflation on the current Y score. Examples -------- >>> from sklearn.cross_decomposition import CCA >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [3.,5.,4.]] >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]] >>> cca = CCA(n_components=1) >>> cca.fit(X, Y) ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE CCA(copy=True, max_iter=500, n_components=1, scale=True, tol=1e-06) >>> X_c, Y_c = cca.transform(X, Y) References ---------- Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with emphasis on the two-block case. Technical Report 371, Department of Statistics, University of Washington, Seattle, 2000. In french but still a reference: Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris: Editions Technic. See also -------- PLSCanonical PLSSVD """ def __init__(self, n_components=2, scale=True, max_iter=500, tol=1e-06, copy=True): _PLS.__init__(self, n_components=n_components, scale=scale, deflation_mode="canonical", mode="B", norm_y_weights=True, algorithm="nipals", max_iter=max_iter, tol=tol, copy=copy)
bsd-3-clause
smaegol/metaplasmid
plasflow/plasflow.py
1
6241
#!/usr/bin/env python ####################################################################################### ### ### ### PlasFlow 1.1 ### ### Copyright (C) 2017 Pawel Krawczyk (p.krawczyk@ibb.waw.pl) ### ### ### ### 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 os import sys import argparse import numpy as np import pandas as pd import re from Bio import SeqIO from os.path import join from .classifier import Tf_Classif from .vote_classifier import TF_Vote_Classifier from .constants import MODELS_PATH from .utils import re_select_columns def predict(seqs, labels, inputfile): vote_class = TF_Vote_Classifier(clfs=[ Tf_Classif(5, "20_20"), Tf_Classif(6, "20_20"), Tf_Classif(7, "30"), ]) vote_proba = vote_class.predict_proba(seqs, labels, inputfile) vote = vote_class.predict(seqs, labels, inputfile) # results pandas dataframe: pd_n = pd.DataFrame(vote) # add columns with contig_id pd_n.index.name = 'contig_id' pd_n.reset_index(inplace=True) pd_n.columns = ['contig_id', 'id'] pd_n_proba = pd.DataFrame(vote_proba) pd_n_proba.columns = labels_df['label'] pd_n_proba.index.name = 'contig_id' pd_n_proba.reset_index(inplace=True) return pd_n, pd_n_proba def parse_seqs(inputfile, min_length=1000): """Return a list of the seqs and a pandas dataframe with metadata.""" print("Importing sequences") seqs = [rec for rec in SeqIO.parse(inputfile, 'fasta') if len(rec.seq) >= min_length] print("Imported ", len(seqs), " sequences") contig_info = pd.DataFrame([ {'contig_id': i, 'contig_name': rec.id, 'contig_length': len(rec.seq)} for i, rec in enumerate(seqs) ]) return seqs, contig_info def write_seqs(inputfile, outputfile, results_merged): sequences_dict = SeqIO.index(inputfile, "fasta") plasmid_sequences, chromosome_sequences, unclassified_sequences = [], [], [] for index, row in results_merged.iterrows(): processed_sequence = sequences_dict[row.contig_name] processed_sequence.id = processed_sequence.id + " " + row.label if re.match(r'^chromosome.*', row.label): chromosome_sequences.append(processed_sequence) elif re.match(r'^plasmid.*', row.label): plasmid_sequences.append(processed_sequence) else: unclassified_sequences.append(processed_sequence) SeqIO.write(chromosome_sequences, outputfile + "_chromosomes.fasta", "fasta") SeqIO.write(plasmid_sequences, outputfile + "_plasmids.fasta", "fasta") SeqIO.write(unclassified_sequences, outputfile + "_unclassified.fasta", "fasta") def filter_results(results_merged, threshold): for index, row in results_merged.iterrows(): taxname = row.label.split(".", 1)[1] if row[row.label] > threshold: continue plasmids = re_select_columns(row, results_merged, r'^plasmid.*') chromosomes = re_select_columns(row, results_merged, r'^chromosom.*') taxnames = re_select_columns(row, results_merged, r".*" + re.escape(taxname) + r"") if plasmids.sum() > threshold: results_merged.at[index, 'label'] = 'plasmid.unclassified' elif chromosomes.sum() > threshold: results_merged.at[index, 'label'] = 'chromosome.unclassified' elif taxnames.sum() > threshold: results_merged.at[index, 'label'] = 'unclassified.' + taxname else: results_merged.at[index, 'label'] = 'unclassified.unclassified' return results_merged def main(labels, inputfile, outputfile, threshold, min_length=1000): seqs, contig_info = parse_seqs(inputfile, min_length=min_length) vote, vote_proba = predict(seqs, labels, inputfile) results_merged = pd.merge(vote, labels, on=['id']) results_merged = pd.merge(results_merged, vote_proba, on=['contig_id']) results_merged = pd.merge(contig_info, results_merged, on=['contig_id']) print("Filtering by probability threshold", threshold) results_merged = filter_results(results_merged, threshold) results_merged.to_csv(outputfile, sep='\t') taxons, plasmids = {}, {} for index, row in results_merged.iterrows(): plasmid, taxname = row.label.split(".", 1)[0], row.label.split(".", 1)[1] taxons[taxname] = taxons.get(taxname, 0) + 1 plasmids[plasmid] = plasmids.get(taxname, 0) + 1 plasmids = pd.DataFrame.from_dict(plasmids, orient="index").transpose() print("\nResulting plasmid sequences prediction:") print(plasmids) taxons = pd.DataFrame.from_dict(taxons, orient="index").transpose() print("\nResulting taxonomical assignment:") print(taxons) print("\nOutputting fasta files with classified sequences") write_seqs(inputfile, outputfile, results_merged)
gpl-3.0
jaredweiss/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/colorbar.py
69
27260
''' Colorbar toolkit with two classes and a function: :class:`ColorbarBase` the base class with full colorbar drawing functionality. It can be used as-is to make a colorbar for a given colormap; a mappable object (e.g., image) is not needed. :class:`Colorbar` the derived class for use with images or contour plots. :func:`make_axes` a function for resizing an axes and adding a second axes suitable for a colorbar The :meth:`~matplotlib.figure.Figure.colorbar` method uses :func:`make_axes` and :class:`Colorbar`; the :func:`~matplotlib.pyplot.colorbar` function is a thin wrapper over :meth:`~matplotlib.figure.Figure.colorbar`. ''' import numpy as np import matplotlib as mpl import matplotlib.colors as colors import matplotlib.cm as cm import matplotlib.ticker as ticker import matplotlib.cbook as cbook import matplotlib.lines as lines import matplotlib.patches as patches import matplotlib.collections as collections import matplotlib.contour as contour make_axes_kw_doc = ''' ========== ==================================================== Property Description ========== ==================================================== *fraction* 0.15; fraction of original axes to use for colorbar *pad* 0.05 if vertical, 0.15 if horizontal; fraction of original axes between colorbar and new image axes *shrink* 1.0; fraction by which to shrink the colorbar *aspect* 20; ratio of long to short dimensions ========== ==================================================== ''' colormap_kw_doc = ''' =========== ==================================================== Property Description =========== ==================================================== *extend* [ 'neither' | 'both' | 'min' | 'max' ] If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. *spacing* [ 'uniform' | 'proportional' ] Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval. *ticks* [ None | list of ticks | Locator object ] If None, ticks are determined automatically from the input. *format* [ None | format string | Formatter object ] If None, the :class:`~matplotlib.ticker.ScalarFormatter` is used. If a format string is given, e.g. '%.3f', that is used. An alternative :class:`~matplotlib.ticker.Formatter` object may be given instead. *drawedges* [ False | True ] If true, draw lines at color boundaries. =========== ==================================================== The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances. ============ =================================================== Property Description ============ =================================================== *boundaries* None or a sequence *values* None or a sequence which must be of length 1 less than the sequence of *boundaries*. For each region delimited by adjacent entries in *boundaries*, the color mapped to the corresponding value in values will be used. ============ =================================================== ''' colorbar_doc = ''' Add a colorbar to a plot. Function signatures for the :mod:`~matplotlib.pyplot` interface; all but the first are also method signatures for the :meth:`~matplotlib.figure.Figure.colorbar` method:: colorbar(**kwargs) colorbar(mappable, **kwargs) colorbar(mappable, cax=cax, **kwargs) colorbar(mappable, ax=ax, **kwargs) arguments: *mappable* the :class:`~matplotlib.image.Image`, :class:`~matplotlib.contour.ContourSet`, etc. to which the colorbar applies; this argument is mandatory for the :meth:`~matplotlib.figure.Figure.colorbar` method but optional for the :func:`~matplotlib.pyplot.colorbar` function, which sets the default to the current image. keyword arguments: *cax* None | axes object into which the colorbar will be drawn *ax* None | parent axes object from which space for a new colorbar axes will be stolen Additional keyword arguments are of two kinds: axes properties: %s colorbar properties: %s If *mappable* is a :class:`~matplotlib.contours.ContourSet`, its *extend* kwarg is included automatically. Note that the *shrink* kwarg provides a simple way to keep a vertical colorbar, for example, from being taller than the axes of the mappable to which the colorbar is attached; but it is a manual method requiring some trial and error. If the colorbar is too tall (or a horizontal colorbar is too wide) use a smaller value of *shrink*. For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs. returns: :class:`~matplotlib.colorbar.Colorbar` instance; see also its base class, :class:`~matplotlib.colorbar.ColorbarBase`. Call the :meth:`~matplotlib.colorbar.ColorbarBase.set_label` method to label the colorbar. ''' % (make_axes_kw_doc, colormap_kw_doc) class ColorbarBase(cm.ScalarMappable): ''' Draw a colorbar in an existing axes. This is a base class for the :class:`Colorbar` class, which is the basis for the :func:`~matplotlib.pyplot.colorbar` method and pylab function. It is also useful by itself for showing a colormap. If the *cmap* kwarg is given but *boundaries* and *values* are left as None, then the colormap will be displayed on a 0-1 scale. To show the under- and over-value colors, specify the *norm* as:: colors.Normalize(clip=False) To show the colors versus index instead of on the 0-1 scale, use:: norm=colors.NoNorm. Useful attributes: :attr:`ax` the Axes instance in which the colorbar is drawn :attr:`lines` a LineCollection if lines were drawn, otherwise None :attr:`dividers` a LineCollection if *drawedges* is True, otherwise None Useful public methods are :meth:`set_label` and :meth:`add_lines`. ''' _slice_dict = {'neither': slice(0,1000000), 'both': slice(1,-1), 'min': slice(1,1000000), 'max': slice(0,-1)} def __init__(self, ax, cmap=None, norm=None, alpha=1.0, values=None, boundaries=None, orientation='vertical', extend='neither', spacing='uniform', # uniform or proportional ticks=None, format=None, drawedges=False, filled=True, ): self.ax = ax if cmap is None: cmap = cm.get_cmap() if norm is None: norm = colors.Normalize() self.alpha = alpha cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm) self.values = values self.boundaries = boundaries self.extend = extend self._inside = self._slice_dict[extend] self.spacing = spacing self.orientation = orientation self.drawedges = drawedges self.filled = filled self.solids = None self.lines = None self.dividers = None self.set_label('') if cbook.iterable(ticks): self.locator = ticker.FixedLocator(ticks, nbins=len(ticks)) else: self.locator = ticks # Handle default in _ticker() if format is None: if isinstance(self.norm, colors.LogNorm): self.formatter = ticker.LogFormatter() else: self.formatter = ticker.ScalarFormatter() elif cbook.is_string_like(format): self.formatter = ticker.FormatStrFormatter(format) else: self.formatter = format # Assume it is a Formatter # The rest is in a method so we can recalculate when clim changes. self.draw_all() def draw_all(self): ''' Calculate any free parameters based on the current cmap and norm, and do all the drawing. ''' self._process_values() self._find_range() X, Y = self._mesh() C = self._values[:,np.newaxis] self._config_axes(X, Y) if self.filled: self._add_solids(X, Y, C) self._set_label() def _config_axes(self, X, Y): ''' Make an axes patch and outline. ''' ax = self.ax ax.set_frame_on(False) ax.set_navigate(False) xy = self._outline(X, Y) ax.update_datalim(xy) ax.set_xlim(*ax.dataLim.intervalx) ax.set_ylim(*ax.dataLim.intervaly) self.outline = lines.Line2D(xy[:, 0], xy[:, 1], color=mpl.rcParams['axes.edgecolor'], linewidth=mpl.rcParams['axes.linewidth']) ax.add_artist(self.outline) self.outline.set_clip_box(None) self.outline.set_clip_path(None) c = mpl.rcParams['axes.facecolor'] self.patch = patches.Polygon(xy, edgecolor=c, facecolor=c, linewidth=0.01, zorder=-1) ax.add_artist(self.patch) ticks, ticklabels, offset_string = self._ticker() if self.orientation == 'vertical': ax.set_xticks([]) ax.yaxis.set_label_position('right') ax.yaxis.set_ticks_position('right') ax.set_yticks(ticks) ax.set_yticklabels(ticklabels) ax.yaxis.get_major_formatter().set_offset_string(offset_string) else: ax.set_yticks([]) ax.xaxis.set_label_position('bottom') ax.set_xticks(ticks) ax.set_xticklabels(ticklabels) ax.xaxis.get_major_formatter().set_offset_string(offset_string) def _set_label(self): if self.orientation == 'vertical': self.ax.set_ylabel(self._label, **self._labelkw) else: self.ax.set_xlabel(self._label, **self._labelkw) def set_label(self, label, **kw): ''' Label the long axis of the colorbar ''' self._label = label self._labelkw = kw self._set_label() def _outline(self, X, Y): ''' Return *x*, *y* arrays of colorbar bounding polygon, taking orientation into account. ''' N = X.shape[0] ii = [0, 1, N-2, N-1, 2*N-1, 2*N-2, N+1, N, 0] x = np.take(np.ravel(np.transpose(X)), ii) y = np.take(np.ravel(np.transpose(Y)), ii) x = x.reshape((len(x), 1)) y = y.reshape((len(y), 1)) if self.orientation == 'horizontal': return np.hstack((y, x)) return np.hstack((x, y)) def _edges(self, X, Y): ''' Return the separator line segments; helper for _add_solids. ''' N = X.shape[0] # Using the non-array form of these line segments is much # simpler than making them into arrays. if self.orientation == 'vertical': return [zip(X[i], Y[i]) for i in range(1, N-1)] else: return [zip(Y[i], X[i]) for i in range(1, N-1)] def _add_solids(self, X, Y, C): ''' Draw the colors using :meth:`~matplotlib.axes.Axes.pcolor`; optionally add separators. ''' ## Change to pcolorfast after fixing bugs in some backends... if self.orientation == 'vertical': args = (X, Y, C) else: args = (np.transpose(Y), np.transpose(X), np.transpose(C)) kw = {'cmap':self.cmap, 'norm':self.norm, 'shading':'flat', 'alpha':self.alpha} # Save, set, and restore hold state to keep pcolor from # clearing the axes. Ordinarily this will not be needed, # since the axes object should already have hold set. _hold = self.ax.ishold() self.ax.hold(True) col = self.ax.pcolor(*args, **kw) self.ax.hold(_hold) #self.add_observer(col) # We should observe, not be observed... self.solids = col if self.drawedges: self.dividers = collections.LineCollection(self._edges(X,Y), colors=(mpl.rcParams['axes.edgecolor'],), linewidths=(0.5*mpl.rcParams['axes.linewidth'],) ) self.ax.add_collection(self.dividers) def add_lines(self, levels, colors, linewidths): ''' Draw lines on the colorbar. ''' N = len(levels) dummy, y = self._locate(levels) if len(y) <> N: raise ValueError("levels are outside colorbar range") x = np.array([0.0, 1.0]) X, Y = np.meshgrid(x,y) if self.orientation == 'vertical': xy = [zip(X[i], Y[i]) for i in range(N)] else: xy = [zip(Y[i], X[i]) for i in range(N)] col = collections.LineCollection(xy, linewidths=linewidths) self.lines = col col.set_color(colors) self.ax.add_collection(col) def _ticker(self): ''' Return two sequences: ticks (colorbar data locations) and ticklabels (strings). ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = 1 + int(nv/10) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator() else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.NoNorm): intv = self._values[0], self._values[-1] else: intv = self.vmin, self.vmax locator.create_dummy_axis() formatter.create_dummy_axis() locator.set_view_interval(*intv) locator.set_data_interval(*intv) formatter.set_view_interval(*intv) formatter.set_data_interval(*intv) b = np.array(locator()) b, ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t, i) for i, t in enumerate(b)] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string def _process_values(self, b=None): ''' Set the :attr:`_boundaries` and :attr:`_values` attributes based on the input boundaries and values. Input boundaries can be *self.boundaries* or the argument *b*. ''' if b is None: b = self.boundaries if b is not None: self._boundaries = np.asarray(b, dtype=float) if self.values is None: self._values = 0.5*(self._boundaries[:-1] + self._boundaries[1:]) if isinstance(self.norm, colors.NoNorm): self._values = (self._values + 0.00001).astype(np.int16) return self._values = np.array(self.values) return if self.values is not None: self._values = np.array(self.values) if self.boundaries is None: b = np.zeros(len(self.values)+1, 'd') b[1:-1] = 0.5*(self._values[:-1] - self._values[1:]) b[0] = 2.0*b[1] - b[2] b[-1] = 2.0*b[-2] - b[-3] self._boundaries = b return self._boundaries = np.array(self.boundaries) return # Neither boundaries nor values are specified; # make reasonable ones based on cmap and norm. if isinstance(self.norm, colors.NoNorm): b = self._uniform_y(self.cmap.N+1) * self.cmap.N - 0.5 v = np.zeros((len(b)-1,), dtype=np.int16) v[self._inside] = np.arange(self.cmap.N, dtype=np.int16) if self.extend in ('both', 'min'): v[0] = -1 if self.extend in ('both', 'max'): v[-1] = self.cmap.N self._boundaries = b self._values = v return elif isinstance(self.norm, colors.BoundaryNorm): b = list(self.norm.boundaries) if self.extend in ('both', 'min'): b = [b[0]-1] + b if self.extend in ('both', 'max'): b = b + [b[-1] + 1] b = np.array(b) v = np.zeros((len(b)-1,), dtype=float) bi = self.norm.boundaries v[self._inside] = 0.5*(bi[:-1] + bi[1:]) if self.extend in ('both', 'min'): v[0] = b[0] - 1 if self.extend in ('both', 'max'): v[-1] = b[-1] + 1 self._boundaries = b self._values = v return else: if not self.norm.scaled(): self.norm.vmin = 0 self.norm.vmax = 1 b = self.norm.inverse(self._uniform_y(self.cmap.N+1)) if self.extend in ('both', 'min'): b[0] = b[0] - 1 if self.extend in ('both', 'max'): b[-1] = b[-1] + 1 self._process_values(b) def _find_range(self): ''' Set :attr:`vmin` and :attr:`vmax` attributes to the first and last boundary excluding extended end boundaries. ''' b = self._boundaries[self._inside] self.vmin = b[0] self.vmax = b[-1] def _central_N(self): '''number of boundaries **before** extension of ends''' nb = len(self._boundaries) if self.extend == 'both': nb -= 2 elif self.extend in ('min', 'max'): nb -= 1 return nb def _extended_N(self): ''' Based on the colormap and extend variable, return the number of boundaries. ''' N = self.cmap.N + 1 if self.extend == 'both': N += 2 elif self.extend in ('min', 'max'): N += 1 return N def _uniform_y(self, N): ''' Return colorbar data coordinates for *N* uniformly spaced boundaries, plus ends if required. ''' if self.extend == 'neither': y = np.linspace(0, 1, N) else: if self.extend == 'both': y = np.zeros(N + 2, 'd') y[0] = -0.05 y[-1] = 1.05 elif self.extend == 'min': y = np.zeros(N + 1, 'd') y[0] = -0.05 else: y = np.zeros(N + 1, 'd') y[-1] = 1.05 y[self._inside] = np.linspace(0, 1, N) return y def _proportional_y(self): ''' Return colorbar data coordinates for the boundaries of a proportional colorbar. ''' if isinstance(self.norm, colors.BoundaryNorm): b = self._boundaries[self._inside] y = (self._boundaries - self._boundaries[0]) y = y / (self._boundaries[-1] - self._boundaries[0]) else: y = self.norm(self._boundaries.copy()) if self.extend in ('both', 'min'): y[0] = -0.05 if self.extend in ('both', 'max'): y[-1] = 1.05 yi = y[self._inside] norm = colors.Normalize(yi[0], yi[-1]) y[self._inside] = norm(yi) return y def _mesh(self): ''' Return X,Y, the coordinate arrays for the colorbar pcolormesh. These are suitable for a vertical colorbar; swapping and transposition for a horizontal colorbar are done outside this function. ''' x = np.array([0.0, 1.0]) if self.spacing == 'uniform': y = self._uniform_y(self._central_N()) else: y = self._proportional_y() self._y = y X, Y = np.meshgrid(x,y) if self.extend in ('min', 'both'): X[0,:] = 0.5 if self.extend in ('max', 'both'): X[-1,:] = 0.5 return X, Y def _locate(self, x): ''' Given a possible set of color data values, return the ones within range, together with their corresponding colorbar data coordinates. ''' if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)): b = self._boundaries xn = x xout = x else: # Do calculations using normalized coordinates so # as to make the interpolation more accurate. b = self.norm(self._boundaries, clip=False).filled() # We do our own clipping so that we can allow a tiny # bit of slop in the end point ticks to allow for # floating point errors. xn = self.norm(x, clip=False).filled() in_cond = (xn > -0.001) & (xn < 1.001) xn = np.compress(in_cond, xn) xout = np.compress(in_cond, x) # The rest is linear interpolation with clipping. y = self._y N = len(b) ii = np.minimum(np.searchsorted(b, xn), N-1) i0 = np.maximum(ii - 1, 0) #db = b[ii] - b[i0] db = np.take(b, ii) - np.take(b, i0) db = np.where(i0==ii, 1.0, db) #dy = y[ii] - y[i0] dy = np.take(y, ii) - np.take(y, i0) z = np.take(y, i0) + (xn-np.take(b,i0))*dy/db return xout, z def set_alpha(self, alpha): self.alpha = alpha class Colorbar(ColorbarBase): def __init__(self, ax, mappable, **kw): mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax # are set when colorbar is called, # even if mappable.draw has not yet # been called. This will not change # vmin, vmax if they are already set. self.mappable = mappable kw['cmap'] = mappable.cmap kw['norm'] = mappable.norm kw['alpha'] = mappable.get_alpha() if isinstance(mappable, contour.ContourSet): CS = mappable kw['boundaries'] = CS._levels kw['values'] = CS.cvalues kw['extend'] = CS.extend #kw['ticks'] = CS._levels kw.setdefault('ticks', ticker.FixedLocator(CS.levels, nbins=10)) kw['filled'] = CS.filled ColorbarBase.__init__(self, ax, **kw) if not CS.filled: self.add_lines(CS) else: ColorbarBase.__init__(self, ax, **kw) def add_lines(self, CS): ''' Add the lines from a non-filled :class:`~matplotlib.contour.ContourSet` to the colorbar. ''' if not isinstance(CS, contour.ContourSet) or CS.filled: raise ValueError('add_lines is only for a ContourSet of lines') tcolors = [c[0] for c in CS.tcolors] tlinewidths = [t[0] for t in CS.tlinewidths] # The following was an attempt to get the colorbar lines # to follow subsequent changes in the contour lines, # but more work is needed: specifically, a careful # look at event sequences, and at how # to make one object track another automatically. #tcolors = [col.get_colors()[0] for col in CS.collections] #tlinewidths = [col.get_linewidth()[0] for lw in CS.collections] #print 'tlinewidths:', tlinewidths ColorbarBase.add_lines(self, CS.levels, tcolors, tlinewidths) def update_bruteforce(self, mappable): ''' Manually change any contour line colors. This is called when the image or contour plot to which this colorbar belongs is changed. ''' # We are using an ugly brute-force method: clearing and # redrawing the whole thing. The problem is that if any # properties have been changed by methods other than the # colorbar methods, those changes will be lost. self.ax.cla() self.draw_all() #if self.vmin != self.norm.vmin or self.vmax != self.norm.vmax: # self.ax.cla() # self.draw_all() if isinstance(self.mappable, contour.ContourSet): CS = self.mappable if not CS.filled: self.add_lines(CS) #if self.lines is not None: # tcolors = [c[0] for c in CS.tcolors] # self.lines.set_color(tcolors) #Fixme? Recalculate boundaries, ticks if vmin, vmax have changed. #Fixme: Some refactoring may be needed; we should not # be recalculating everything if there was a simple alpha # change. def make_axes(parent, **kw): orientation = kw.setdefault('orientation', 'vertical') fraction = kw.pop('fraction', 0.15) shrink = kw.pop('shrink', 1.0) aspect = kw.pop('aspect', 20) #pb = transforms.PBox(parent.get_position()) pb = parent.get_position(original=True).frozen() if orientation == 'vertical': pad = kw.pop('pad', 0.05) x1 = 1.0-fraction pb1, pbx, pbcb = pb.splitx(x1-pad, x1) pbcb = pbcb.shrunk(1.0, shrink).anchored('C', pbcb) anchor = (0.0, 0.5) panchor = (1.0, 0.5) else: pad = kw.pop('pad', 0.15) pbcb, pbx, pb1 = pb.splity(fraction, fraction+pad) pbcb = pbcb.shrunk(shrink, 1.0).anchored('C', pbcb) aspect = 1.0/aspect anchor = (0.5, 1.0) panchor = (0.5, 0.0) parent.set_position(pb1) parent.set_anchor(panchor) fig = parent.get_figure() cax = fig.add_axes(pbcb) cax.set_aspect(aspect, anchor=anchor, adjustable='box') return cax, kw make_axes.__doc__ =''' Resize and reposition a parent axes, and return a child axes suitable for a colorbar:: cax, kw = make_axes(parent, **kw) Keyword arguments may include the following (with defaults): *orientation* 'vertical' or 'horizontal' %s All but the first of these are stripped from the input kw set. Returns (cax, kw), the child axes and the reduced kw dictionary. ''' % make_axes_kw_doc
gpl-3.0
olafhauk/mne-python
mne/viz/utils.py
1
88098
# -*- coding: utf-8 -*- """Utility functions for plotting M/EEG data.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Mainak Jas <mainak@neuro.hut.fi> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # Clemens Brunner <clemens.brunner@gmail.com> # Daniel McCloy <dan@mccloy.info> # # License: Simplified BSD from collections import defaultdict from contextlib import contextmanager from functools import partial import difflib import webbrowser import tempfile import math import numpy as np from copy import deepcopy from distutils.version import LooseVersion import warnings from ..defaults import _handle_default from ..fixes import _get_status from ..io import show_fiff, Info from ..io.constants import FIFF from ..io.pick import (channel_type, channel_indices_by_type, pick_channels, _pick_data_channels, _DATA_CH_TYPES_SPLIT, _DATA_CH_TYPES_ORDER_DEFAULT, _VALID_CHANNEL_TYPES, pick_info, _picks_by_type, pick_channels_cov, _contains_ch_type) from ..io.meas_info import create_info from ..rank import compute_rank from ..io.proj import setup_proj from ..utils import (verbose, get_config, warn, _check_ch_locs, _check_option, logger, fill_doc, _pl, _check_sphere, _ensure_int) from ..selection import (read_selection, _SELECTIONS, _EEG_SELECTIONS, _divide_to_regions) from ..transforms import apply_trans _channel_type_prettyprint = {'eeg': "EEG channel", 'grad': "Gradiometer", 'mag': "Magnetometer", 'seeg': "sEEG channel", 'eog': "EOG channel", 'ecg': "ECG sensor", 'emg': "EMG sensor", 'ecog': "ECoG channel", 'misc': "miscellaneous sensor"} def _setup_vmin_vmax(data, vmin, vmax, norm=False): """Handle vmin and vmax parameters for visualizing topomaps. For the normal use-case (when `vmin` and `vmax` are None), the parameter `norm` drives the computation. When norm=False, data is supposed to come from a mag and the output tuple (vmin, vmax) is symmetric range (-x, x) where x is the max(abs(data)). When norm=True (a.k.a. data is the L2 norm of a gradiometer pair) the output tuple corresponds to (0, x). Otherwise, vmin and vmax are callables that drive the operation. """ should_warn = False if vmax is None and vmin is None: vmax = np.abs(data).max() vmin = 0. if norm else -vmax if vmin == 0 and np.min(data) < 0: should_warn = True else: if callable(vmin): vmin = vmin(data) elif vmin is None: vmin = 0. if norm else np.min(data) if vmin == 0 and np.min(data) < 0: should_warn = True if callable(vmax): vmax = vmax(data) elif vmax is None: vmax = np.max(data) if should_warn: warn_msg = ("_setup_vmin_vmax output a (min={vmin}, max={vmax})" " range whereas the minimum of data is {data_min}") warn_val = {'vmin': vmin, 'vmax': vmax, 'data_min': np.min(data)} warn(warn_msg.format(**warn_val), UserWarning) return vmin, vmax def plt_show(show=True, fig=None, **kwargs): """Show a figure while suppressing warnings. Parameters ---------- show : bool Show the figure. fig : instance of Figure | None If non-None, use fig.show(). **kwargs : dict Extra arguments for :func:`matplotlib.pyplot.show`. """ from matplotlib import get_backend import matplotlib.pyplot as plt if show and get_backend() != 'agg': (fig or plt).show(**kwargs) def tight_layout(pad=1.2, h_pad=None, w_pad=None, fig=None): """Adjust subplot parameters to give specified padding. .. note:: For plotting please use this function instead of ``plt.tight_layout``. Parameters ---------- pad : float Padding between the figure edge and the edges of subplots, as a fraction of the font-size. h_pad : float Padding height between edges of adjacent subplots. Defaults to ``pad_inches``. w_pad : float Padding width between edges of adjacent subplots. Defaults to ``pad_inches``. fig : instance of Figure Figure to apply changes to. Notes ----- This will not force constrained_layout=False if the figure was created with that method. """ import matplotlib.pyplot as plt fig = plt.gcf() if fig is None else fig fig.canvas.draw() constrained = fig.get_constrained_layout() if constrained: return # no-op try: # see https://github.com/matplotlib/matplotlib/issues/2654 with warnings.catch_warnings(record=True) as ws: fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad) except Exception: try: with warnings.catch_warnings(record=True) as ws: fig.set_tight_layout(dict(pad=pad, h_pad=h_pad, w_pad=w_pad)) except Exception: warn('Matplotlib function "tight_layout" is not supported.' ' Skipping subplot adjustment.') return for w in ws: w_msg = str(w.message) if hasattr(w, 'message') else w.get_message() if not w_msg.startswith('This figure includes Axes'): warn(w_msg, w.category, 'matplotlib') def _check_delayed_ssp(container): """Handle interactive SSP selection.""" if container.proj is True or\ all(p['active'] for p in container.info['projs']): raise RuntimeError('Projs are already applied. Please initialize' ' the data with proj set to False.') elif len(container.info['projs']) < 1: raise RuntimeError('No projs found in evoked.') def _validate_if_list_of_axes(axes, obligatory_len=None): """Validate whether input is a list/array of axes.""" from matplotlib.axes import Axes if obligatory_len is not None and not isinstance(obligatory_len, int): raise ValueError('obligatory_len must be None or int, got %d', 'instead' % type(obligatory_len)) if not isinstance(axes, (list, np.ndarray)): raise ValueError('axes must be a list or numpy array of matplotlib ' 'axes objects, got %s instead.' % type(axes)) if isinstance(axes, np.ndarray) and axes.ndim > 1: raise ValueError('if input is a numpy array, it must be ' 'one-dimensional. The received numpy array has %d ' 'dimensions however. Try using ravel or flatten ' 'method of the array.' % axes.ndim) is_correct_type = np.array([isinstance(x, Axes) for x in axes]) if not np.all(is_correct_type): first_bad = np.where(np.logical_not(is_correct_type))[0][0] raise ValueError('axes must be a list or numpy array of matplotlib ' 'axes objects while one of the list elements is ' '%s.' % type(axes[first_bad])) if obligatory_len is not None and not len(axes) == obligatory_len: raise ValueError('axes must be a list/array of length %d, while the' ' length is %d' % (obligatory_len, len(axes))) def mne_analyze_colormap(limits=[5, 10, 15], format='mayavi'): """Return a colormap similar to that used by mne_analyze. Parameters ---------- limits : list (or array) of length 3 or 6 Bounds for the colormap, which will be mirrored across zero if length 3, or completely specified (and potentially asymmetric) if length 6. format : str Type of colormap to return. If 'matplotlib', will return a matplotlib.colors.LinearSegmentedColormap. If 'mayavi', will return an RGBA array of shape (256, 4). Returns ------- cmap : instance of colormap | array A teal->blue->gray->red->yellow colormap. See docstring of the 'format' argument for further details. Notes ----- For this will return a colormap that will display correctly for data that are scaled by the plotting function to span [-fmax, fmax]. """ # noqa: E501 # Ensure limits is an array limits = np.asarray(limits, dtype='float') if len(limits) != 3 and len(limits) != 6: raise ValueError('limits must have 3 or 6 elements') if len(limits) == 3 and any(limits < 0.): raise ValueError('if 3 elements, limits must all be non-negative') if any(np.diff(limits) <= 0): raise ValueError('limits must be monotonically increasing') if format == 'matplotlib': from matplotlib import colors if len(limits) == 3: limits = (np.concatenate((-np.flipud(limits), limits)) + limits[-1]) / (2 * limits[-1]) else: limits = (limits - np.min(limits)) / np.max(limits - np.min(limits)) cdict = {'red': ((limits[0], 0.0, 0.0), (limits[1], 0.0, 0.0), (limits[2], 0.5, 0.5), (limits[3], 0.5, 0.5), (limits[4], 1.0, 1.0), (limits[5], 1.0, 1.0)), 'green': ((limits[0], 1.0, 1.0), (limits[1], 0.0, 0.0), (limits[2], 0.5, 0.5), (limits[3], 0.5, 0.5), (limits[4], 0.0, 0.0), (limits[5], 1.0, 1.0)), 'blue': ((limits[0], 1.0, 1.0), (limits[1], 1.0, 1.0), (limits[2], 0.5, 0.5), (limits[3], 0.5, 0.5), (limits[4], 0.0, 0.0), (limits[5], 0.0, 0.0)), 'alpha': ((limits[0], 1.0, 1.0), (limits[1], 1.0, 1.0), (limits[2], 0.0, 0.0), (limits[3], 0.0, 0.0), (limits[4], 1.0, 1.0), (limits[5], 1.0, 1.0)), } return colors.LinearSegmentedColormap('mne_analyze', cdict) elif format == 'mayavi': if len(limits) == 3: limits = np.concatenate((-np.flipud(limits), [0], limits)) /\ limits[-1] else: limits = np.concatenate((limits[:3], [0], limits[3:])) limits /= np.max(np.abs(limits)) r = np.array([0, 0, 0, 0, 1, 1, 1]) g = np.array([1, 0, 0, 0, 0, 0, 1]) b = np.array([1, 1, 1, 0, 0, 0, 0]) a = np.array([1, 1, 0, 0, 0, 1, 1]) xp = (np.arange(256) - 128) / 128.0 colormap = np.r_[[np.interp(xp, limits, 255 * c) for c in [r, g, b, a]]].T return colormap else: raise ValueError('format must be either matplotlib or mayavi') @contextmanager def _events_off(obj): obj.eventson = False try: yield finally: obj.eventson = True def _toggle_proj(event, params, all_=False): """Perform operations when proj boxes clicked.""" # read options if possible if 'proj_checks' in params: bools = _get_status(params['proj_checks']) if all_: new_bools = [not all(bools)] * len(bools) with _events_off(params['proj_checks']): for bi, (old, new) in enumerate(zip(bools, new_bools)): if old != new: params['proj_checks'].set_active(bi) bools[bi] = new for bi, (b, p) in enumerate(zip(bools, params['projs'])): # see if they tried to deactivate an active one if not b and p['active']: bools[bi] = True else: proj = params.get('apply_proj', True) bools = [proj] * len(params['projs']) compute_proj = False if 'proj_bools' not in params: compute_proj = True elif not np.array_equal(bools, params['proj_bools']): compute_proj = True # if projectors changed, update plots if compute_proj is True: params['plot_update_proj_callback'](params, bools) def _get_channel_plotting_order(order, ch_types, picks=None): """Determine channel plotting order for browse-style Raw/Epochs plots.""" if order is None: # for backward compat, we swap the first two to keep grad before mag ch_type_order = list(_DATA_CH_TYPES_ORDER_DEFAULT) ch_type_order = tuple(['grad', 'mag'] + ch_type_order[2:]) order = [pick_idx for order_type in ch_type_order for pick_idx, pick_type in enumerate(ch_types) if order_type == pick_type] elif not isinstance(order, (np.ndarray, list, tuple)): raise ValueError('order should be array-like; got ' f'"{order}" ({type(order)}).') if picks is not None: order = [ch for ch in order if ch in picks] return np.asarray(order) def _make_event_color_dict(event_color, events=None, event_id=None): """Make or validate a dict mapping event ids to colors.""" from .misc import _handle_event_colors if isinstance(event_color, dict): # if event_color is a dict, validate it event_id = dict() if event_id is None else event_id event_color = {_ensure_int(event_id.get(key, key), 'event_color key'): value for key, value in event_color.items()} default = event_color.pop(-1, None) default_factory = None if default is None else lambda: default new_dict = defaultdict(default_factory) for key, value in event_color.items(): if key < 1: raise KeyError('event_color keys must be strictly positive, ' f'or -1 (cannot use {key})') new_dict[key] = value return new_dict elif event_color is None: # make a dict from color cycle uniq_events = set() if events is None else np.unique(events[:, 2]) return _handle_event_colors(event_color, uniq_events, event_id) else: # if event_color is a MPL color-like thing, use it for all events return defaultdict(lambda: event_color) def _prepare_trellis(n_cells, ncols, nrows='auto', title=False, colorbar=False, size=1.3): import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec if n_cells == 1: nrows = ncols = 1 elif isinstance(ncols, int) and n_cells <= ncols: nrows, ncols = 1, n_cells else: if ncols == 'auto' and nrows == 'auto': nrows = math.floor(math.sqrt(n_cells)) ncols = math.ceil(n_cells / nrows) elif ncols == 'auto': ncols = math.ceil(n_cells / nrows) elif nrows == 'auto': nrows = math.ceil(n_cells / ncols) else: naxes = ncols * nrows if naxes < n_cells: raise ValueError("Cannot plot {} axes in a {} by {} " "figure.".format(n_cells, nrows, ncols)) if colorbar: ncols += 1 width = size * ncols height = (size + max(0, 0.1 * (4 - size))) * nrows + bool(title) * 0.5 height_ratios = None g_kwargs = {} figure_nobar(figsize=(width * 1.5, height * 1.5)) gs = GridSpec(nrows, ncols, height_ratios=height_ratios, **g_kwargs) axes = [] if colorbar: # exclude last axis of each row except top row, which is for colorbar exclude = set(range(2 * ncols - 1, nrows * ncols, ncols)) ax_idxs = sorted(set(range(nrows * ncols)) - exclude)[:n_cells + 1] else: ax_idxs = range(n_cells) for ax_idx in ax_idxs: axes.append(plt.subplot(gs[ax_idx])) fig = axes[0].get_figure() return fig, axes, ncols, nrows def _draw_proj_checkbox(event, params, draw_current_state=True): """Toggle options (projectors) dialog.""" from matplotlib import widgets projs = params['projs'] # turn on options dialog labels = [p['desc'] for p in projs] actives = ([p['active'] for p in projs] if draw_current_state else params.get('proj_bools', [params['apply_proj']] * len(projs))) width = max([4., max([len(p['desc']) for p in projs]) / 6.0 + 0.5]) height = (len(projs) + 1) / 6.0 + 1.5 fig_proj = figure_nobar(figsize=(width, height)) _set_window_title(fig_proj, 'SSP projection vectors') offset = (1. / 6. / height) params['fig_proj'] = fig_proj # necessary for proper toggling ax_temp = fig_proj.add_axes((0, offset, 1, 0.8 - offset), frameon=False) ax_temp.set_title('Projectors marked with "X" are active') proj_checks = widgets.CheckButtons(ax_temp, labels=labels, actives=actives) # make edges around checkbox areas for rect in proj_checks.rectangles: rect.set_edgecolor('0.5') rect.set_linewidth(1.) # change already-applied projectors to red for ii, p in enumerate(projs): if p['active']: for x in proj_checks.lines[ii]: x.set_color('#ff0000') # make minimal size # pass key presses from option dialog over proj_checks.on_clicked(partial(_toggle_proj, params=params)) params['proj_checks'] = proj_checks fig_proj.canvas.mpl_connect('key_press_event', _key_press) # Toggle all ax_temp = fig_proj.add_axes((0, 0, 1, offset), frameon=False) proj_all = widgets.Button(ax_temp, 'Toggle all') proj_all.on_clicked(partial(_toggle_proj, params=params, all_=True)) params['proj_all'] = proj_all # this should work for non-test cases try: fig_proj.canvas.draw() plt_show(fig=fig_proj, warn=False) except Exception: pass def _simplify_float(label): # Heuristic to turn floats to ints where possible (e.g. -500.0 to -500) if isinstance(label, float) and np.isfinite(label) and \ float(str(label)) != round(label): label = round(label, 2) return label def _get_figsize_from_config(): """Get default / most recent figure size from config.""" figsize = get_config('MNE_BROWSE_RAW_SIZE') if figsize is not None: figsize = figsize.split(',') figsize = tuple([float(s) for s in figsize]) return figsize @verbose def compare_fiff(fname_1, fname_2, fname_out=None, show=True, indent=' ', read_limit=np.inf, max_str=30, verbose=None): """Compare the contents of two fiff files using diff and show_fiff. Parameters ---------- fname_1 : str First file to compare. fname_2 : str Second file to compare. fname_out : str | None Filename to store the resulting diff. If None, a temporary file will be created. show : bool If True, show the resulting diff in a new tab in a web browser. indent : str How to indent the lines. read_limit : int Max number of bytes of data to read from a tag. Can be np.inf to always read all data (helps test read completion). max_str : int Max number of characters of string representation to print for each tag's data. %(verbose)s Returns ------- fname_out : str The filename used for storing the diff. Could be useful for when a temporary file is used. """ file_1 = show_fiff(fname_1, output=list, indent=indent, read_limit=read_limit, max_str=max_str) file_2 = show_fiff(fname_2, output=list, indent=indent, read_limit=read_limit, max_str=max_str) diff = difflib.HtmlDiff().make_file(file_1, file_2, fname_1, fname_2) if fname_out is not None: f = open(fname_out, 'wb') else: f = tempfile.NamedTemporaryFile('wb', delete=False, suffix='.html') fname_out = f.name with f as fid: fid.write(diff.encode('utf-8')) if show is True: webbrowser.open_new_tab(fname_out) return fname_out def figure_nobar(*args, **kwargs): """Make matplotlib figure with no toolbar. Parameters ---------- *args : list Arguments to pass to :func:`matplotlib.pyplot.figure`. **kwargs : dict Keyword arguments to pass to :func:`matplotlib.pyplot.figure`. Returns ------- fig : instance of Figure The figure. """ from matplotlib import rcParams, pyplot as plt old_val = rcParams['toolbar'] try: rcParams['toolbar'] = 'none' fig = plt.figure(*args, **kwargs) # remove button press catchers (for toolbar) cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys()) for key in cbs: fig.canvas.callbacks.disconnect(key) finally: rcParams['toolbar'] = old_val return fig def _show_help(col1, col2, width, height): fig_help = figure_nobar(figsize=(width, height), dpi=80) _set_window_title(fig_help, 'Help') ax = fig_help.add_subplot(111) celltext = [[c1, c2] for c1, c2 in zip(col1.strip().split("\n"), col2.strip().split("\n"))] table = ax.table(cellText=celltext, loc="center", cellLoc="left") table.auto_set_font_size(False) table.set_fontsize(12) ax.set_axis_off() for (row, col), cell in table.get_celld().items(): cell.set_edgecolor(None) # remove cell borders # right justify, following: # https://stackoverflow.com/questions/48210749/matplotlib-table-assign-different-text-alignments-to-different-columns?rq=1 # noqa: E501 if col == 0: cell._loc = 'right' fig_help.canvas.mpl_connect('key_press_event', _key_press) # this should work for non-test cases try: fig_help.canvas.draw() plt_show(fig=fig_help, warn=False) except Exception: pass def _key_press(event): """Handle key press in dialog.""" import matplotlib.pyplot as plt if event.key == 'escape': plt.close(event.canvas.figure) class ClickableImage(object): """Display an image so you can click on it and store x/y positions. Takes as input an image array (can be any array that works with imshow, but will work best with images. Displays the image and lets you click on it. Stores the xy coordinates of each click, so now you can superimpose something on top of it. Upon clicking, the x/y coordinate of the cursor will be stored in self.coords, which is a list of (x, y) tuples. Parameters ---------- imdata : ndarray The image that you wish to click on for 2-d points. **kwargs : dict Keyword arguments. Passed to ax.imshow. Notes ----- .. versionadded:: 0.9.0 """ def __init__(self, imdata, **kwargs): """Display the image for clicking.""" import matplotlib.pyplot as plt self.coords = [] self.imdata = imdata self.fig = plt.figure() self.ax = self.fig.add_subplot(111) self.ymax = self.imdata.shape[0] self.xmax = self.imdata.shape[1] self.im = self.ax.imshow(imdata, extent=(0, self.xmax, 0, self.ymax), picker=True, **kwargs) self.ax.axis('off') self.fig.canvas.mpl_connect('pick_event', self.onclick) plt_show(block=True) def onclick(self, event): """Handle Mouse clicks. Parameters ---------- event : matplotlib.backend_bases.Event The matplotlib object that we use to get x/y position. """ mouseevent = event.mouseevent self.coords.append((mouseevent.xdata, mouseevent.ydata)) def plot_clicks(self, **kwargs): """Plot the x/y positions stored in self.coords. Parameters ---------- **kwargs : dict Arguments are passed to imshow in displaying the bg image. """ import matplotlib.pyplot as plt if len(self.coords) == 0: raise ValueError('No coordinates found, make sure you click ' 'on the image that is first shown.') f, ax = plt.subplots() ax.imshow(self.imdata, extent=(0, self.xmax, 0, self.ymax), **kwargs) xlim, ylim = [ax.get_xlim(), ax.get_ylim()] xcoords, ycoords = zip(*self.coords) ax.scatter(xcoords, ycoords, c='#ff0000') ann_text = np.arange(len(self.coords)).astype(str) for txt, coord in zip(ann_text, self.coords): ax.annotate(txt, coord, fontsize=20, color='#ff0000') ax.set_xlim(xlim) ax.set_ylim(ylim) plt_show() def to_layout(self, **kwargs): """Turn coordinates into an MNE Layout object. Normalizes by the image you used to generate clicks Parameters ---------- **kwargs : dict Arguments are passed to generate_2d_layout. Returns ------- layout : instance of Layout The layout. """ from ..channels.layout import generate_2d_layout coords = np.array(self.coords) lt = generate_2d_layout(coords, bg_image=self.imdata, **kwargs) return lt def _fake_click(fig, ax, point, xform='ax', button=1, kind='press'): """Fake a click at a relative point within axes.""" if xform == 'ax': x, y = ax.transAxes.transform_point(point) elif xform == 'data': x, y = ax.transData.transform_point(point) else: assert xform == 'pix' x, y = point if kind == 'press': func = partial(fig.canvas.button_press_event, x=x, y=y, button=button) elif kind == 'release': func = partial(fig.canvas.button_release_event, x=x, y=y, button=button) elif kind == 'motion': func = partial(fig.canvas.motion_notify_event, x=x, y=y) func(guiEvent=None) def add_background_image(fig, im, set_ratios=None): """Add a background image to a plot. Adds the image specified in ``im`` to the figure ``fig``. This is generally meant to be done with topo plots, though it could work for any plot. .. note:: This modifies the figure and/or axes in place. Parameters ---------- fig : Figure The figure you wish to add a bg image to. im : array, shape (M, N, {3, 4}) A background image for the figure. This must be a valid input to `matplotlib.pyplot.imshow`. Defaults to None. set_ratios : None | str Set the aspect ratio of any axes in fig to the value in set_ratios. Defaults to None, which does nothing to axes. Returns ------- ax_im : instance of Axes Axes created corresponding to the image you added. Notes ----- .. versionadded:: 0.9.0 """ if im is None: # Don't do anything and return nothing return None if set_ratios is not None: for ax in fig.axes: ax.set_aspect(set_ratios) ax_im = fig.add_axes([0, 0, 1, 1], label='background') ax_im.imshow(im, aspect='auto') ax_im.set_zorder(-1) return ax_im def _find_peaks(evoked, npeaks): """Find peaks from evoked data. Returns ``npeaks`` biggest peaks as a list of time points. """ from scipy.signal import argrelmax gfp = evoked.data.std(axis=0) order = len(evoked.times) // 30 if order < 1: order = 1 peaks = argrelmax(gfp, order=order, axis=0)[0] if len(peaks) > npeaks: max_indices = np.argsort(gfp[peaks])[-npeaks:] peaks = np.sort(peaks[max_indices]) times = evoked.times[peaks] if len(times) == 0: times = [evoked.times[gfp.argmax()]] return times def _process_times(inst, use_times, n_peaks=None, few=False): """Return a list of times for topomaps.""" if isinstance(use_times, str): if use_times == 'interactive': use_times, n_peaks = 'peaks', 1 if use_times == 'peaks': if n_peaks is None: n_peaks = min(3 if few else 7, len(inst.times)) use_times = _find_peaks(inst, n_peaks) elif use_times == 'auto': if n_peaks is None: n_peaks = min(5 if few else 10, len(use_times)) use_times = np.linspace(inst.times[0], inst.times[-1], n_peaks) else: raise ValueError("Got an unrecognized method for `times`. Only " "'peaks', 'auto' and 'interactive' are supported " "(or directly passing numbers).") elif np.isscalar(use_times): use_times = [use_times] use_times = np.array(use_times, float) if use_times.ndim != 1: raise ValueError('times must be 1D, got %d dimensions' % use_times.ndim) if len(use_times) > 25: warn('More than 25 topomaps plots requested. This might take a while.') return use_times @verbose def plot_sensors(info, kind='topomap', ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True, sphere=None, verbose=None): """Plot sensors positions. Parameters ---------- info : instance of Info Info structure containing the channel locations. kind : str Whether to plot the sensors as 3d, topomap or as an interactive sensor selection dialog. Available options 'topomap', '3d', 'select'. If 'select', a set of channels can be selected interactively by using lasso selector or clicking while holding control key. The selected channels are returned along with the figure instance. Defaults to 'topomap'. ch_type : None | str The channel type to plot. Available options 'mag', 'grad', 'eeg', 'seeg', 'ecog', 'all'. If ``'all'``, all the available mag, grad, eeg, seeg and ecog channels are plotted. If None (default), then channels are chosen in the order given above. title : str | None Title for the figure. If None (default), equals to ``'Sensor positions (%%s)' %% ch_type``. show_names : bool | array of str Whether to display all channel names. If an array, only the channel names in the array are shown. Defaults to False. ch_groups : 'position' | array of shape (n_ch_groups, n_picks) | None Channel groups for coloring the sensors. If None (default), default coloring scheme is used. If 'position', the sensors are divided into 8 regions. See ``order`` kwarg of :func:`mne.viz.plot_raw`. If array, the channels are divided by picks given in the array. .. versionadded:: 0.13.0 to_sphere : bool Whether to project the 3d locations to a sphere. When False, the sensor array appears similar as to looking downwards straight above the subject's head. Has no effect when kind='3d'. Defaults to True. .. versionadded:: 0.14.0 axes : instance of Axes | instance of Axes3D | None Axes to draw the sensors to. If ``kind='3d'``, axes must be an instance of Axes3D. If None (default), a new axes will be created. .. versionadded:: 0.13.0 block : bool Whether to halt program execution until the figure is closed. Defaults to False. .. versionadded:: 0.13.0 show : bool Show figure if True. Defaults to True. %(topomap_sphere_auto)s %(verbose)s Returns ------- fig : instance of Figure Figure containing the sensor topography. selection : list A list of selected channels. Only returned if ``kind=='select'``. See Also -------- mne.viz.plot_layout Notes ----- This function plots the sensor locations from the info structure using matplotlib. For drawing the sensors using mayavi see :func:`mne.viz.plot_alignment`. .. versionadded:: 0.12.0 """ from .evoked import _rgb _check_option('kind', kind, ['topomap', '3d', 'select']) if not isinstance(info, Info): raise TypeError('info must be an instance of Info not %s' % type(info)) ch_indices = channel_indices_by_type(info) allowed_types = _DATA_CH_TYPES_SPLIT if ch_type is None: for this_type in allowed_types: if _contains_ch_type(info, this_type): ch_type = this_type break picks = ch_indices[ch_type] elif ch_type == 'all': picks = list() for this_type in allowed_types: picks += ch_indices[this_type] elif ch_type in allowed_types: picks = ch_indices[ch_type] else: raise ValueError("ch_type must be one of %s not %s!" % (allowed_types, ch_type)) if len(picks) == 0: raise ValueError('Could not find any channels of type %s.' % ch_type) chs = [info['chs'][pick] for pick in picks] if not _check_ch_locs(chs): raise RuntimeError('No valid channel positions found') dev_head_t = info['dev_head_t'] pos = np.empty((len(chs), 3)) for ci, ch in enumerate(chs): pos[ci] = ch['loc'][:3] if ch['coord_frame'] == FIFF.FIFFV_COORD_DEVICE: if dev_head_t is None: warn('dev_head_t is None, transforming MEG sensors to head ' 'coordinate frame using identity transform') dev_head_t = np.eye(4) pos[ci] = apply_trans(dev_head_t, pos[ci]) del dev_head_t ch_names = np.array([ch['ch_name'] for ch in chs]) bads = [idx for idx, name in enumerate(ch_names) if name in info['bads']] if ch_groups is None: def_colors = _handle_default('color') colors = ['red' if i in bads else def_colors[channel_type(info, pick)] for i, pick in enumerate(picks)] else: if ch_groups in ['position', 'selection']: if ch_groups == 'position': ch_groups = _divide_to_regions(info, add_stim=False) ch_groups = list(ch_groups.values()) else: ch_groups, color_vals = list(), list() for selection in _SELECTIONS + _EEG_SELECTIONS: channels = pick_channels( info['ch_names'], read_selection(selection, info=info)) ch_groups.append(channels) color_vals = np.ones((len(ch_groups), 4)) for idx, ch_group in enumerate(ch_groups): color_picks = [np.where(picks == ch)[0][0] for ch in ch_group if ch in picks] if len(color_picks) == 0: continue x, y, z = pos[color_picks].T color = np.mean(_rgb(x, y, z), axis=0) color_vals[idx, :3] = color # mean of spatial color else: import matplotlib.pyplot as plt colors = np.linspace(0, 1, len(ch_groups)) color_vals = [plt.cm.jet(colors[i]) for i in range(len(ch_groups))] if not isinstance(ch_groups, (np.ndarray, list)): raise ValueError("ch_groups must be None, 'position', " "'selection', or an array. Got %s." % ch_groups) colors = np.zeros((len(picks), 4)) for pick_idx, pick in enumerate(picks): for ind, value in enumerate(ch_groups): if pick in value: colors[pick_idx] = color_vals[ind] break title = 'Sensor positions (%s)' % ch_type if title is None else title fig = _plot_sensors(pos, info, picks, colors, bads, ch_names, title, show_names, axes, show, kind, block, to_sphere, sphere) if kind == 'select': return fig, fig.lasso.selection return fig def _onpick_sensor(event, fig, ax, pos, ch_names, show_names): """Pick a channel in plot_sensors.""" if event.mouseevent.inaxes != ax: return if event.mouseevent.key == 'control' and fig.lasso is not None: for ind in event.ind: fig.lasso.select_one(ind) return if show_names: return # channel names already visible ind = event.ind[0] # Just take the first sensor. ch_name = ch_names[ind] this_pos = pos[ind] # XXX: Bug in matplotlib won't allow setting the position of existing # text item, so we create a new one. ax.texts.pop(0) if len(this_pos) == 3: ax.text(this_pos[0], this_pos[1], this_pos[2], ch_name) else: ax.text(this_pos[0], this_pos[1], ch_name) fig.canvas.draw() def _close_event(event, fig): """Listen for sensor plotter close event.""" if getattr(fig, 'lasso', None) is not None: fig.lasso.disconnect() def _plot_sensors(pos, info, picks, colors, bads, ch_names, title, show_names, ax, show, kind, block, to_sphere, sphere): """Plot sensors.""" from matplotlib import rcParams import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from .topomap import _get_pos_outlines, _draw_outlines sphere = _check_sphere(sphere, info) edgecolors = np.repeat(rcParams['axes.edgecolor'], len(colors)) edgecolors[bads] = 'red' axes_was_none = ax is None if axes_was_none: fig = plt.figure(figsize=(max(rcParams['figure.figsize']),) * 2) if kind == '3d': Axes3D(fig) ax = fig.gca(projection='3d') else: ax = fig.add_subplot(111) else: fig = ax.get_figure() if kind == '3d': ax.text(0, 0, 0, '', zorder=1) ax.scatter(pos[:, 0], pos[:, 1], pos[:, 2], picker=True, c=colors, s=75, edgecolor=edgecolors, linewidth=2) ax.azim = 90 ax.elev = 0 ax.xaxis.set_label_text('x (m)') ax.yaxis.set_label_text('y (m)') ax.zaxis.set_label_text('z (m)') else: # kind in 'select', 'topomap' ax.text(0, 0, '', zorder=1) pos, outlines = _get_pos_outlines(info, picks, sphere, to_sphere=to_sphere) _draw_outlines(ax, outlines) pts = ax.scatter(pos[:, 0], pos[:, 1], picker=True, clip_on=False, c=colors, edgecolors=edgecolors, s=25, lw=2) if kind == 'select': fig.lasso = SelectFromCollection(ax, pts, ch_names) else: fig.lasso = None # Equal aspect for 3D looks bad, so only use for 2D ax.set(aspect='equal') if axes_was_none: fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) ax.axis("off") # remove border around figure del sphere connect_picker = True if show_names: if isinstance(show_names, (list, np.ndarray)): # only given channels indices = [list(ch_names).index(name) for name in show_names] else: # all channels indices = range(len(pos)) for idx in indices: this_pos = pos[idx] if kind == '3d': ax.text(this_pos[0], this_pos[1], this_pos[2], ch_names[idx]) else: ax.text(this_pos[0] + 0.0025, this_pos[1], ch_names[idx], ha='left', va='center') connect_picker = (kind == 'select') if connect_picker: picker = partial(_onpick_sensor, fig=fig, ax=ax, pos=pos, ch_names=ch_names, show_names=show_names) fig.canvas.mpl_connect('pick_event', picker) ax.set(title=title) closed = partial(_close_event, fig=fig) fig.canvas.mpl_connect('close_event', closed) plt_show(show, block=block) return fig def _compute_scalings(scalings, inst, remove_dc=False, duration=10): """Compute scalings for each channel type automatically. Parameters ---------- scalings : dict The scalings for each channel type. If any values are 'auto', this will automatically compute a reasonable scaling for that channel type. Any values that aren't 'auto' will not be changed. inst : instance of Raw or Epochs The data for which you want to compute scalings. If data is not preloaded, this will read a subset of times / epochs up to 100mb in size in order to compute scalings. remove_dc : bool Whether to remove the mean (DC) before calculating the scalings. If True, the mean will be computed and subtracted for short epochs in order to compensate not only for global mean offset, but also for slow drifts in the signals. duration : float If remove_dc is True, the mean will be computed and subtracted on segments of length ``duration`` seconds. Returns ------- scalings : dict A scalings dictionary with updated values """ from ..io.base import BaseRaw from ..epochs import BaseEpochs scalings = _handle_default('scalings_plot_raw', scalings) if not isinstance(inst, (BaseRaw, BaseEpochs)): raise ValueError('Must supply either Raw or Epochs') ch_types = channel_indices_by_type(inst.info) ch_types = {i_type: i_ixs for i_type, i_ixs in ch_types.items() if len(i_ixs) != 0} scalings = deepcopy(scalings) if inst.preload is False: if isinstance(inst, BaseRaw): # Load a window of data from the center up to 100mb in size n_times = 1e8 // (len(inst.ch_names) * 8) n_times = np.clip(n_times, 1, inst.n_times) n_secs = n_times / float(inst.info['sfreq']) time_middle = np.mean(inst.times) tmin = np.clip(time_middle - n_secs / 2., inst.times.min(), None) tmax = np.clip(time_middle + n_secs / 2., None, inst.times.max()) data = inst._read_segment(tmin, tmax) elif isinstance(inst, BaseEpochs): # Load a random subset of epochs up to 100mb in size n_epochs = 1e8 // (len(inst.ch_names) * len(inst.times) * 8) n_epochs = int(np.clip(n_epochs, 1, len(inst))) ixs_epochs = np.random.choice(range(len(inst)), n_epochs, False) inst = inst.copy()[ixs_epochs].load_data() else: data = inst._data if isinstance(inst, BaseEpochs): data = inst._data.swapaxes(0, 1).reshape([len(inst.ch_names), -1]) # Iterate through ch types and update scaling if ' auto' for key, value in scalings.items(): if key not in ch_types: continue if not (isinstance(value, str) and value == 'auto'): try: scalings[key] = float(value) except Exception: raise ValueError( f'scalings must be "auto" or float, got scalings[{key!r}]=' f'{value!r} which could not be converted to float') continue this_data = data[ch_types[key]] if remove_dc and (this_data.shape[1] / inst.info["sfreq"] >= duration): length = int(duration * inst.info["sfreq"]) # segment length # truncate data so that we can divide into segments of equal length this_data = this_data[:, :this_data.shape[1] // length * length] shape = this_data.shape # original shape this_data = this_data.T.reshape(-1, length, shape[0]) # segment this_data -= np.nanmean(this_data, 0) # subtract segment means this_data = this_data.T.reshape(shape) # reshape into original this_data = this_data.ravel() this_data = this_data[np.isfinite(this_data)] if this_data.size: iqr = np.diff(np.percentile(this_data, [25, 75]))[0] else: iqr = 1. scalings[key] = iqr return scalings def _setup_cmap(cmap, n_axes=1, norm=False): """Set color map interactivity.""" if cmap == 'interactive': cmap = ('Reds' if norm else 'RdBu_r', True) elif not isinstance(cmap, tuple): if cmap is None: cmap = 'Reds' if norm else 'RdBu_r' cmap = (cmap, False if n_axes > 2 else True) return cmap def _prepare_joint_axes(n_maps, figsize=None): """Prepare axes for topomaps and colorbar in joint plot figure. Parameters ---------- n_maps: int Number of topomaps to include in the figure figsize: tuple Figure size, see plt.figsize Returns ------- fig : matplotlib.figure.Figure Figure with initialized axes main_ax: matplotlib.axes._subplots.AxesSubplot Axes in which to put the main plot map_ax: list List of axes for each topomap cbar_ax: matplotlib.axes._subplots.AxesSubplot Axes for colorbar next to topomaps """ import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) main_ax = fig.add_subplot(212) ts = n_maps + 2 map_ax = [plt.subplot(4, ts, x + 2 + ts) for x in range(n_maps)] # Position topomap subplots on the second row, starting on the # second column cbar_ax = plt.subplot(4, 5 * (ts + 1), 10 * (ts + 1)) # Position colorbar at the very end of a more finely divided # second row of subplots return fig, main_ax, map_ax, cbar_ax class DraggableColorbar(object): """Enable interactive colorbar. See http://www.ster.kuleuven.be/~pieterd/python/html/plotting/interactive_colorbar.html """ # noqa: E501 def __init__(self, cbar, mappable): import matplotlib.pyplot as plt self.cbar = cbar self.mappable = mappable self.press = None self.cycle = sorted([i for i in dir(plt.cm) if hasattr(getattr(plt.cm, i), 'N')]) self.cycle += [mappable.get_cmap().name] self.index = self.cycle.index(mappable.get_cmap().name) self.lims = (self.cbar.norm.vmin, self.cbar.norm.vmax) self.connect() def connect(self): """Connect to all the events we need.""" self.cidpress = self.cbar.patch.figure.canvas.mpl_connect( 'button_press_event', self.on_press) self.cidrelease = self.cbar.patch.figure.canvas.mpl_connect( 'button_release_event', self.on_release) self.cidmotion = self.cbar.patch.figure.canvas.mpl_connect( 'motion_notify_event', self.on_motion) self.keypress = self.cbar.patch.figure.canvas.mpl_connect( 'key_press_event', self.key_press) self.scroll = self.cbar.patch.figure.canvas.mpl_connect( 'scroll_event', self.on_scroll) def on_press(self, event): """Handle button press.""" if event.inaxes != self.cbar.ax: return self.press = event.y def key_press(self, event): """Handle key press.""" # print(event.key) scale = self.cbar.norm.vmax - self.cbar.norm.vmin perc = 0.03 if event.key == 'down': self.index += 1 elif event.key == 'up': self.index -= 1 elif event.key == ' ': # space key resets scale self.cbar.norm.vmin = self.lims[0] self.cbar.norm.vmax = self.lims[1] elif event.key == '+': self.cbar.norm.vmin -= (perc * scale) * -1 self.cbar.norm.vmax += (perc * scale) * -1 elif event.key == '-': self.cbar.norm.vmin -= (perc * scale) * 1 self.cbar.norm.vmax += (perc * scale) * 1 elif event.key == 'pageup': self.cbar.norm.vmin -= (perc * scale) * 1 self.cbar.norm.vmax -= (perc * scale) * 1 elif event.key == 'pagedown': self.cbar.norm.vmin -= (perc * scale) * -1 self.cbar.norm.vmax -= (perc * scale) * -1 else: return if self.index < 0: self.index = len(self.cycle) - 1 elif self.index >= len(self.cycle): self.index = 0 cmap = self.cycle[self.index] self.cbar.mappable.set_cmap(cmap) self.cbar.draw_all() self.mappable.set_cmap(cmap) self._update() def on_motion(self, event): """Handle mouse movements.""" if self.press is None: return if event.inaxes != self.cbar.ax: return yprev = self.press dy = event.y - yprev self.press = event.y scale = self.cbar.norm.vmax - self.cbar.norm.vmin perc = 0.03 if event.button == 1: self.cbar.norm.vmin -= (perc * scale) * np.sign(dy) self.cbar.norm.vmax -= (perc * scale) * np.sign(dy) elif event.button == 3: self.cbar.norm.vmin -= (perc * scale) * np.sign(dy) self.cbar.norm.vmax += (perc * scale) * np.sign(dy) self._update() def on_release(self, event): """Handle release.""" self.press = None self._update() def on_scroll(self, event): """Handle scroll.""" scale = 1.1 if event.step < 0 else 1. / 1.1 self.cbar.norm.vmin *= scale self.cbar.norm.vmax *= scale self._update() def _update(self): self.cbar.set_ticks(None, update_ticks=True) # use default self.cbar.draw_all() self.mappable.set_norm(self.cbar.norm) self.cbar.patch.figure.canvas.draw() class SelectFromCollection(object): """Select channels from a matplotlib collection using ``LassoSelector``. Selected channels are saved in the ``selection`` attribute. This tool highlights selected points by fading other points out (i.e., reducing their alpha values). Parameters ---------- ax : instance of Axes Axes to interact with. collection : instance of matplotlib collection Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to ``alpha_other``. Defaults to 0.3. linewidth_other : float Linewidth to use for non-selected sensors. Default is 1. Notes ----- This tool selects collection objects based on their *origins* (i.e., ``offsets``). Emits mpl event 'lasso_event' when selection is ready. """ def __init__(self, ax, collection, ch_names, alpha_other=0.5, linewidth_other=0.5, alpha_selected=1, linewidth_selected=1): from matplotlib import __version__ if LooseVersion(__version__) < LooseVersion('1.2.1'): raise ImportError('Interactive selection not possible for ' 'matplotlib versions < 1.2.1. Upgrade ' 'matplotlib.') from matplotlib.widgets import LassoSelector self.canvas = ax.figure.canvas self.collection = collection self.ch_names = ch_names self.alpha_other = alpha_other self.linewidth_other = linewidth_other self.alpha_selected = alpha_selected self.linewidth_selected = linewidth_selected self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() self.ec = collection.get_edgecolors() self.lw = collection.get_linewidths() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) self.ec = np.tile(self.ec, self.Npts).reshape(self.Npts, -1) self.fc[:, -1] = self.alpha_other # deselect in the beginning self.ec[:, -1] = self.alpha_other self.lw = np.full(self.Npts, self.linewidth_other) self.lasso = LassoSelector(ax, onselect=self.on_select, lineprops=dict(color='red', linewidth=0.5)) self.selection = list() def on_select(self, verts): """Select a subset from the collection.""" from matplotlib.path import Path if len(verts) <= 3: # Seems to be a good way to exclude single clicks. return path = Path(verts) inds = np.nonzero([path.contains_point(xy) for xy in self.xys])[0] if self.canvas._key == 'control': # Appending selection. sels = [np.where(self.ch_names == c)[0][0] for c in self.selection] inters = set(inds) - set(sels) inds = list(inters.union(set(sels) - set(inds))) self.selection[:] = np.array(self.ch_names)[inds].tolist() self.style_sensors(inds) self.canvas.callbacks.process('lasso_event') def select_one(self, ind): """Select or deselect one sensor.""" ch_name = self.ch_names[ind] if ch_name in self.selection: sel_ind = self.selection.index(ch_name) self.selection.pop(sel_ind) else: self.selection.append(ch_name) inds = np.in1d(self.ch_names, self.selection).nonzero()[0] self.style_sensors(inds) self.canvas.callbacks.process('lasso_event') def select_many(self, inds): """Select many sensors using indices (for predefined selections).""" self.selection[:] = np.array(self.ch_names)[inds].tolist() self.style_sensors(inds) def style_sensors(self, inds): """Style selected sensors as "active".""" # reset self.fc[:, -1] = self.alpha_other self.ec[:, -1] = self.alpha_other / 2 self.lw[:] = self.linewidth_other # style sensors at `inds` self.fc[inds, -1] = self.alpha_selected self.ec[inds, -1] = self.alpha_selected self.lw[inds] = self.linewidth_selected self.collection.set_facecolors(self.fc) self.collection.set_edgecolors(self.ec) self.collection.set_linewidths(self.lw) self.canvas.draw_idle() def disconnect(self): """Disconnect the lasso selector.""" self.lasso.disconnect_events() self.fc[:, -1] = self.alpha_selected self.ec[:, -1] = self.alpha_selected self.collection.set_facecolors(self.fc) self.collection.set_edgecolors(self.ec) self.canvas.draw_idle() def _get_color_list(annotations=False): """Get the current color list from matplotlib rcParams. Parameters ---------- annotations : boolean Has no influence on the function if false. If true, check if color "red" (#ff0000) is in the cycle and remove it. Returns ------- colors : list """ from matplotlib import rcParams color_cycle = rcParams.get('axes.prop_cycle') if not color_cycle: # Use deprecated color_cycle to avoid KeyErrors in environments # with Python 2.7 and Matplotlib < 1.5 # this will already be a list colors = rcParams.get('axes.color_cycle') else: # we were able to use the prop_cycle. Now just convert to list colors = color_cycle.by_key()['color'] # If we want annotations, red is reserved ... remove if present. This # checks for the reddish color in MPL dark background style, normal style, # and MPL "red", and defaults to the last of those if none are present for red in ('#fa8174', '#d62728', '#ff0000'): if annotations and red in colors: colors.remove(red) break return (colors, red) if annotations else colors def _merge_annotations(start, stop, description, annotations, current=()): """Handle drawn annotations.""" ends = annotations.onset + annotations.duration idx = np.intersect1d(np.where(ends >= start)[0], np.where(annotations.onset <= stop)[0]) idx = np.intersect1d(idx, np.where(annotations.description == description)[0]) new_idx = np.setdiff1d(idx, current) # don't include modified annotation end = max(np.append((annotations.onset[new_idx] + annotations.duration[new_idx]), stop)) onset = min(np.append(annotations.onset[new_idx], start)) duration = end - onset annotations.delete(idx) annotations.append(onset, duration, description) def _connection_line(x, fig, sourceax, targetax, y=1., y_source_transform="transAxes"): """Connect source and target plots with a line. Connect source and target plots with a line, such as time series (source) and topolots (target). Primarily used for plot_joint functions. """ from matplotlib.lines import Line2D trans_fig = fig.transFigure trans_fig_inv = fig.transFigure.inverted() xt, yt = trans_fig_inv.transform(targetax.transAxes.transform([.5, 0.])) xs, _ = trans_fig_inv.transform(sourceax.transData.transform([x, 0.])) _, ys = trans_fig_inv.transform(getattr(sourceax, y_source_transform ).transform([0., y])) return Line2D((xt, xs), (yt, ys), transform=trans_fig, color='grey', linestyle='-', linewidth=1.5, alpha=.66, zorder=1, clip_on=False) class DraggableLine(object): """Custom matplotlib line for moving around by drag and drop. Parameters ---------- line : instance of matplotlib Line2D Line to add interactivity to. callback : function Callback to call when line is released. """ def __init__(self, line, modify_callback, drag_callback): self.line = line self.press = None self.x0 = line.get_xdata()[0] self.modify_callback = modify_callback self.drag_callback = drag_callback self.cidpress = self.line.figure.canvas.mpl_connect( 'button_press_event', self.on_press) self.cidrelease = self.line.figure.canvas.mpl_connect( 'button_release_event', self.on_release) self.cidmotion = self.line.figure.canvas.mpl_connect( 'motion_notify_event', self.on_motion) def set_x(self, x): """Repoisition the line.""" self.line.set_xdata([x, x]) self.x0 = x def on_press(self, event): """Store button press if on top of the line.""" if event.inaxes != self.line.axes or not self.line.contains(event)[0]: return x0 = self.line.get_xdata() y0 = self.line.get_ydata() self.press = x0, y0, event.xdata, event.ydata def on_motion(self, event): """Move the line on drag.""" if self.press is None: return if event.inaxes != self.line.axes: return x0, y0, xpress, ypress = self.press dx = event.xdata - xpress self.line.set_xdata(x0 + dx) self.drag_callback((x0 + dx)[0]) self.line.figure.canvas.draw() def on_release(self, event): """Handle release.""" if event.inaxes != self.line.axes or self.press is None: return self.press = None self.line.figure.canvas.draw() self.modify_callback(self.x0, event.xdata) self.x0 = event.xdata def remove(self): """Remove the line.""" self.line.figure.canvas.mpl_disconnect(self.cidpress) self.line.figure.canvas.mpl_disconnect(self.cidrelease) self.line.figure.canvas.mpl_disconnect(self.cidmotion) self.line.figure.axes[0].lines.remove(self.line) def _setup_ax_spines(axes, vlines, xmin, xmax, ymin, ymax, invert_y=False, unit=None, truncate_xaxis=True, truncate_yaxis=True, skip_axlabel=False, hline=True): # don't show zero line if it coincides with x-axis (even if hline=True) if hline and ymin != 0.: axes.spines['top'].set_position('zero') else: axes.spines['top'].set_visible(False) # the axes can become very small with topo plotting. This prevents the # x-axis from shrinking to length zero if truncate_xaxis=True, by adding # new ticks that are nice round numbers close to (but less extreme than) # xmin and xmax vlines = [] if vlines is None else vlines xticks = _trim_ticks(axes.get_xticks(), xmin, xmax) xticks = np.array(sorted(set([x for x in xticks] + vlines))) if len(xticks) < 2: def log_fix(tval): exp = np.log10(np.abs(tval)) return np.sign(tval) * 10 ** (np.fix(exp) - (exp < 0)) xlims = np.array([xmin, xmax]) temp_ticks = log_fix(xlims) closer_idx = np.argmin(np.abs(xlims - temp_ticks)) further_idx = np.argmax(np.abs(xlims - temp_ticks)) start_stop = [temp_ticks[closer_idx], xlims[further_idx]] step = np.sign(np.diff(start_stop)) * np.max(np.abs(temp_ticks)) tts = np.arange(*start_stop, step) xticks = np.array(sorted(xticks + [tts[0], tts[-1]])) axes.set_xticks(xticks) # y-axis is simpler yticks = _trim_ticks(axes.get_yticks(), ymin, ymax) axes.set_yticks(yticks) # truncation case 1: truncate both if truncate_xaxis and truncate_yaxis: axes.spines['bottom'].set_bounds(*xticks[[0, -1]]) axes.spines['left'].set_bounds(*yticks[[0, -1]]) # case 2: truncate only x (only right side; connect to y at left) elif truncate_xaxis: xbounds = np.array(axes.get_xlim()) xbounds[1] = axes.get_xticks()[-1] axes.spines['bottom'].set_bounds(*xbounds) # case 3: truncate only y (only top; connect to x at bottom) elif truncate_yaxis: ybounds = np.array(axes.get_ylim()) if invert_y: ybounds[0] = axes.get_yticks()[0] else: ybounds[1] = axes.get_yticks()[-1] axes.spines['left'].set_bounds(*ybounds) # handle axis labels if skip_axlabel: axes.set_yticklabels([''] * len(yticks)) axes.set_xticklabels([''] * len(xticks)) else: if unit is not None: axes.set_ylabel(unit, rotation=90) axes.set_xlabel('Time (s)') # plot vertical lines if vlines: _ymin, _ymax = axes.get_ylim() axes.vlines(vlines, _ymax, _ymin, linestyles='--', colors='k', linewidth=1., zorder=1) # invert? if invert_y: axes.invert_yaxis() # changes we always make: axes.tick_params(direction='out') axes.tick_params(right=False) axes.spines['right'].set_visible(False) axes.spines['left'].set_zorder(0) def _handle_decim(info, decim, lowpass): """Handle decim parameter for plotters.""" from ..evoked import _check_decim from ..utils import _ensure_int if isinstance(decim, str) and decim == 'auto': lp = info['sfreq'] if info['lowpass'] is None else info['lowpass'] lp = min(lp, info['sfreq'] if lowpass is None else lowpass) info['lowpass'] = lp decim = max(int(info['sfreq'] / (lp * 3) + 1e-6), 1) decim = _ensure_int(decim, 'decim', must_be='an int or "auto"') if decim <= 0: raise ValueError('decim must be "auto" or a positive integer, got %s' % (decim,)) decim = _check_decim(info, decim, 0)[0] data_picks = _pick_data_channels(info, exclude=()) return decim, data_picks def _setup_plot_projector(info, noise_cov, proj=True, use_noise_cov=True, nave=1): from ..cov import compute_whitener projector = np.eye(len(info['ch_names'])) whitened_ch_names = [] if noise_cov is not None and use_noise_cov: # any channels in noise_cov['bads'] but not in info['bads'] get # set to nan, which means that they are not plotted. data_picks = _pick_data_channels(info, with_ref_meg=False, exclude=()) data_names = {info['ch_names'][pick] for pick in data_picks} # these can be toggled by the user bad_names = set(info['bads']) # these can't in standard pipelines be enabled (we always take the # union), so pretend they're not in cov at all cov_names = ((set(noise_cov['names']) & set(info['ch_names'])) - set(noise_cov['bads'])) # Actually compute the whitener only using the difference whiten_names = cov_names - bad_names whiten_picks = pick_channels(info['ch_names'], whiten_names) whiten_info = pick_info(info, whiten_picks) rank = _triage_rank_sss(whiten_info, [noise_cov])[1][0] whitener, whitened_ch_names = compute_whitener( noise_cov, whiten_info, rank=rank, verbose=False) whitener *= np.sqrt(nave) # proper scaling for Evoked data assert set(whitened_ch_names) == whiten_names projector[whiten_picks, whiten_picks[:, np.newaxis]] = whitener # Now we need to change the set of "whitened" channels to include # all data channel names so that they are properly italicized. whitened_ch_names = data_names # We would need to set "bad_picks" to identity to show the traces # (but in gray), but here we don't need to because "projector" # starts out as identity. So all that is left to do is take any # *good* data channels that are not in the noise cov to be NaN nan_names = data_names - (bad_names | cov_names) # XXX conditional necessary because of annoying behavior of # pick_channels where an empty list means "all"! if len(nan_names) > 0: nan_picks = pick_channels(info['ch_names'], nan_names) projector[nan_picks] = np.nan elif proj: projector, _ = setup_proj(info, add_eeg_ref=False, verbose=False) return projector, whitened_ch_names def _check_sss(info): """Check SSS history in info.""" ch_used = [ch for ch in _DATA_CH_TYPES_SPLIT if _contains_ch_type(info, ch)] has_meg = 'mag' in ch_used and 'grad' in ch_used has_sss = (has_meg and len(info['proc_history']) > 0 and info['proc_history'][0].get('max_info') is not None) return ch_used, has_meg, has_sss def _triage_rank_sss(info, covs, rank=None, scalings=None): rank = dict() if rank is None else rank scalings = _handle_default('scalings_cov_rank', scalings) # Only look at good channels picks = _pick_data_channels(info, with_ref_meg=False, exclude='bads') info = pick_info(info, picks) ch_used, has_meg, has_sss = _check_sss(info) if has_sss: if 'mag' in rank or 'grad' in rank: raise ValueError('When using SSS, pass "meg" to set the rank ' '(separate rank values for "mag" or "grad" are ' 'meaningless).') elif 'meg' in rank: raise ValueError('When not using SSS, pass separate rank values ' 'for "mag" and "grad" (do not use "meg").') picks_list = _picks_by_type(info, meg_combined=has_sss) if has_sss: # reduce ch_used to combined mag grad ch_used = list(zip(*picks_list))[0] # order pick list by ch_used (required for compat with plot_evoked) picks_list = [x for x, y in sorted(zip(picks_list, ch_used))] n_ch_used = len(ch_used) # make sure we use the same rank estimates for GFP and whitening picks_list2 = [k for k in picks_list] # add meg picks if needed. if has_meg: # append ("meg", picks_meg) picks_list2 += _picks_by_type(info, meg_combined=True) rank_list = [] # rank dict for each cov for cov in covs: # We need to add the covariance projectors, compute the projector, # and apply it, just like we will do in prepare_noise_cov, otherwise # we risk the rank estimates being incorrect (i.e., if the projectors # do not match). info_proj = info.copy() info_proj['projs'] += cov['projs'] this_rank = {} # assemble rank dict for this cov, such that we have meg for ch_type, this_picks in picks_list2: # if we have already estimates / values for mag/grad but not # a value for meg, combine grad and mag. if ('mag' in this_rank and 'grad' in this_rank and 'meg' not in rank): this_rank['meg'] = this_rank['mag'] + this_rank['grad'] # and we're done here break if rank.get(ch_type) is None: ch_names = [info['ch_names'][pick] for pick in this_picks] this_C = pick_channels_cov(cov, ch_names) this_estimated_rank = compute_rank( this_C, scalings=scalings, info=info_proj)[ch_type] this_rank[ch_type] = this_estimated_rank elif rank.get(ch_type) is not None: this_rank[ch_type] = rank[ch_type] rank_list.append(this_rank) return n_ch_used, rank_list, picks_list, has_sss def _check_cov(noise_cov, info): """Check the noise_cov for whitening and issue an SSS warning.""" from ..cov import read_cov, Covariance if noise_cov is None: return None if isinstance(noise_cov, str): noise_cov = read_cov(noise_cov) if not isinstance(noise_cov, Covariance): raise TypeError('noise_cov must be a str or Covariance, got %s' % (type(noise_cov),)) if _check_sss(info)[2]: # has_sss warn('Data have been processed with SSS, which changes the relative ' 'scaling of magnetometers and gradiometers when viewing data ' 'whitened by a noise covariance') return noise_cov def _set_title_multiple_electrodes(title, combine, ch_names, max_chans=6, all=False, ch_type=None): """Prepare a title string for multiple electrodes.""" if title is None: title = ", ".join(ch_names[:max_chans]) ch_type = _channel_type_prettyprint.get(ch_type, ch_type) if ch_type is None: ch_type = "sensor" if len(ch_names) > 1: ch_type += "s" if all is True and isinstance(combine, str): combine = combine.capitalize() title = "{} of {} {}".format( combine, len(ch_names), ch_type) elif len(ch_names) > max_chans and combine != "gfp": logger.info("More than {} channels, truncating title ...".format( max_chans)) title += ", ...\n({} of {} {})".format( combine, len(ch_names), ch_type,) return title def _check_time_unit(time_unit, times): if not isinstance(time_unit, str): raise TypeError('time_unit must be str, got %s' % (type(time_unit),)) if time_unit == 's': pass elif time_unit == 'ms': times = 1e3 * times else: raise ValueError("time_unit must be 's' or 'ms', got %r" % time_unit) return time_unit, times def _plot_masked_image(ax, data, times, mask=None, yvals=None, cmap="RdBu_r", vmin=None, vmax=None, ylim=None, mask_style="both", mask_alpha=.25, mask_cmap="Greys", yscale="linear"): """Plot a potentially masked (evoked, TFR, ...) 2D image.""" from matplotlib import ticker, __version__ as mpl_version if mask_style is None and mask is not None: mask_style = "both" # default draw_mask = mask_style in {"both", "mask"} draw_contour = mask_style in {"both", "contour"} if cmap is None: mask_cmap = cmap # mask param check and preparation if draw_mask is None: if mask is not None: draw_mask = True else: draw_mask = False if draw_contour is None: if mask is not None: draw_contour = True else: draw_contour = False if mask is None: if draw_mask: warn("`mask` is None, not masking the plot ...") draw_mask = False if draw_contour: warn("`mask` is None, not adding contour to the plot ...") draw_contour = False if draw_mask: if mask.shape != data.shape: raise ValueError( "The mask must have the same shape as the data, " "i.e., %s, not %s" % (data.shape, mask.shape)) if draw_contour and yscale == "log": warn("Cannot draw contours with linear yscale yet ...") if yvals is None: # for e.g. Evoked images yvals = np.arange(data.shape[0]) # else, if TFR plot, yvals will be freqs # test yscale if yscale == 'log' and not yvals[0] > 0: raise ValueError('Using log scale for frequency axis requires all your' ' frequencies to be positive (you cannot include' ' the DC component (0 Hz) in the TFR).') if len(yvals) < 2 or yvals[0] == 0: yscale = 'linear' elif yscale != 'linear': ratio = yvals[1:] / yvals[:-1] if yscale == 'auto': if yvals[0] > 0 and np.allclose(ratio, ratio[0]): yscale = 'log' else: yscale = 'linear' # https://github.com/matplotlib/matplotlib/pull/9477 if yscale == "log" and mpl_version == "2.1.0": warn("With matplotlib version 2.1.0, lines may not show up in " "`AverageTFR.plot_joint`. Upgrade to a more recent version.") if yscale == "log": # pcolormesh for log scale # compute bounds between time samples time_lims, = centers_to_edges(times) log_yvals = np.concatenate([[yvals[0] / ratio[0]], yvals, [yvals[-1] * ratio[0]]]) yval_lims = np.sqrt(log_yvals[:-1] * log_yvals[1:]) # construct a time-yvaluency bounds grid time_mesh, yval_mesh = np.meshgrid(time_lims, yval_lims) if mask is not None: ax.pcolormesh(time_mesh, yval_mesh, data, cmap=mask_cmap, vmin=vmin, vmax=vmax, alpha=mask_alpha) im = ax.pcolormesh(time_mesh, yval_mesh, np.ma.masked_where(~mask, data), cmap=cmap, vmin=vmin, vmax=vmax, alpha=1) else: im = ax.pcolormesh(time_mesh, yval_mesh, data, cmap=cmap, vmin=vmin, vmax=vmax) if ylim is None: ylim = yval_lims[[0, -1]] if yscale == 'log': ax.set_yscale('log') ax.get_yaxis().set_major_formatter(ticker.ScalarFormatter()) ax.yaxis.set_minor_formatter(ticker.NullFormatter()) # get rid of minor ticks ax.yaxis.set_minor_locator(ticker.NullLocator()) tick_vals = yvals[np.unique(np.linspace( 0, len(yvals) - 1, 12).round().astype('int'))] ax.set_yticks(tick_vals) else: # imshow for linear because the y ticks are nicer # and the masked areas look better dt = np.median(np.diff(times)) / 2. if len(times) > 1 else 0.1 dy = np.median(np.diff(yvals)) / 2. if len(yvals) > 1 else 0.5 extent = [times[0] - dt, times[-1] + dt, yvals[0] - dy, yvals[-1] + dy] im_args = dict(interpolation='nearest', origin='lower', extent=extent, aspect='auto', vmin=vmin, vmax=vmax) if draw_mask: ax.imshow(data, alpha=mask_alpha, cmap=mask_cmap, **im_args) im = ax.imshow( np.ma.masked_where(~mask, data), cmap=cmap, **im_args) else: ax.imshow(data, cmap=cmap, **im_args) # see #6481 im = ax.imshow(data, cmap=cmap, **im_args) if draw_contour and np.unique(mask).size == 2: big_mask = np.kron(mask, np.ones((10, 10))) ax.contour(big_mask, colors=["k"], extent=extent, linewidths=[.75], corner_mask=False, antialiased=False, levels=[.5]) time_lims = [extent[0], extent[1]] if ylim is None: ylim = [extent[2], extent[3]] ax.set_xlim(time_lims[0], time_lims[-1]) ax.set_ylim(ylim) if (draw_mask or draw_contour) and mask is not None: if mask.all(): t_end = ", all points masked)" else: fraction = 1 - (np.float64(mask.sum()) / np.float64(mask.size)) t_end = ", %0.3g%% of points masked)" % (fraction * 100,) else: t_end = ")" return im, t_end @fill_doc def _make_combine_callable(combine): """Convert None or string values of ``combine`` into callables. Params ------ %(combine)s If callable, the callable must accept one positional input (data of shape ``(n_epochs, n_channels, n_times)`` or ``(n_evokeds, n_channels, n_times)``) and return an :class:`array <numpy.ndarray>` of shape ``(n_epochs, n_times)`` or ``(n_evokeds, n_times)``. """ if combine is None: combine = partial(np.squeeze, axis=1) elif isinstance(combine, str): combine_dict = {key: partial(getattr(np, key), axis=1) for key in ('mean', 'median', 'std')} combine_dict['gfp'] = lambda data: np.sqrt((data ** 2).mean(axis=1)) try: combine = combine_dict[combine] except KeyError: raise ValueError('"combine" must be None, a callable, or one of ' '"mean", "median", "std", or "gfp"; got {}' ''.format(combine)) return combine def center_cmap(cmap, vmin, vmax, name="cmap_centered"): """Center given colormap (ranging from vmin to vmax) at value 0. Parameters ---------- cmap : matplotlib.colors.Colormap The colormap to center around 0. vmin : float Minimum value in the data to map to the lower end of the colormap. vmax : float Maximum value in the data to map to the upper end of the colormap. name : str Name of the new colormap. Defaults to 'cmap_centered'. Returns ------- cmap_centered : matplotlib.colors.Colormap The new colormap centered around 0. Notes ----- This function can be used in situations where vmin and vmax are not symmetric around zero. Normally, this results in the value zero not being mapped to white anymore in many colormaps. Using this function, the value zero will be mapped to white even for asymmetric positive and negative value ranges. Note that this could also be achieved by re-normalizing a given colormap by subclassing matplotlib.colors.Normalize as described here: https://matplotlib.org/users/colormapnorms.html#custom-normalization-two-linear-ranges """ # noqa: E501 from matplotlib.colors import LinearSegmentedColormap vzero = abs(vmin) / float(vmax - vmin) index_old = np.linspace(0, 1, cmap.N) index_new = np.hstack([np.linspace(0, vzero, cmap.N // 2, endpoint=False), np.linspace(vzero, 1, cmap.N // 2)]) colors = "red", "green", "blue", "alpha" cdict = {name: [] for name in colors} for old, new in zip(index_old, index_new): for color, name in zip(cmap(old), colors): cdict[name].append((new, color, color)) return LinearSegmentedColormap(name, cdict) def _convert_psds(psds, dB, estimate, scaling, unit, ch_names=None, first_dim='channel'): """Convert PSDs to dB (if necessary) and appropriate units. The following table summarizes the relationship between the value of parameters ``dB`` and ``estimate``, and the type of plot and corresponding units. | dB | estimate | plot | units | |-------+-------------+------+-------------------| | True | 'power' | PSD | amp**2/Hz (dB) | | True | 'amplitude' | ASD | amp/sqrt(Hz) (dB) | | True | 'auto' | PSD | amp**2/Hz (dB) | | False | 'power' | PSD | amp**2/Hz | | False | 'amplitude' | ASD | amp/sqrt(Hz) | | False | 'auto' | ASD | amp/sqrt(Hz) | where amp are the units corresponding to the variable, as specified by ``unit``. """ _check_option('first_dim', first_dim, ['channel', 'epoch']) where = np.where(psds.min(1) <= 0)[0] if len(where) > 0: # Construct a helpful error message, depending on whether the first # dimension of `psds` are channels or epochs. if dB: bad_value = 'Infinite' else: bad_value = 'Zero' if first_dim == 'channel': bads = ', '.join(ch_names[ii] for ii in where) else: bads = ', '.join(str(ii) for ii in where) msg = f'{bad_value} value in PSD for {first_dim}{_pl(where)} {bads}.' if first_dim == 'channel': msg += '\nThese channels might be dead.' warn(msg, UserWarning) if estimate == 'auto': estimate = 'power' if dB else 'amplitude' if estimate == 'amplitude': np.sqrt(psds, out=psds) psds *= scaling ylabel = r'$\mathrm{%s/\sqrt{Hz}}$' % unit else: psds *= scaling * scaling if '/' in unit: unit = '(%s)' % unit ylabel = r'$\mathrm{%s²/Hz}$' % unit if dB: np.log10(np.maximum(psds, np.finfo(float).tiny), out=psds) psds *= 10 ylabel += r'$\ \mathrm{(dB)}$' return ylabel def _plot_psd(inst, fig, freqs, psd_list, picks_list, titles_list, units_list, scalings_list, ax_list, make_label, color, area_mode, area_alpha, dB, estimate, average, spatial_colors, xscale, line_alpha, sphere, xlabels_list): # helper function for plot_raw_psd and plot_epochs_psd from matplotlib.ticker import ScalarFormatter from .evoked import _plot_lines for key, ls in zip(['lowpass', 'highpass', 'line_freq'], ['--', '--', '-.']): if inst.info[key] is not None: for ax in ax_list: ax.axvline(inst.info[key], color='k', linestyle=ls, alpha=0.25, linewidth=2, zorder=2) if line_alpha is None: line_alpha = 1.0 if average else 0.75 line_alpha = float(line_alpha) ylabels = list() for ii, (psd, picks, title, ax, scalings, units) in enumerate(zip( psd_list, picks_list, titles_list, ax_list, scalings_list, units_list)): ylabel = _convert_psds(psd, dB, estimate, scalings, units, [inst.ch_names[pi] for pi in picks]) ylabels.append(ylabel) del ylabel if average: # mean across channels psd_mean = np.mean(psd, axis=0) if area_mode == 'std': # std across channels psd_std = np.std(psd, axis=0) hyp_limits = (psd_mean - psd_std, psd_mean + psd_std) elif area_mode == 'range': hyp_limits = (np.min(psd, axis=0), np.max(psd, axis=0)) else: # area_mode is None hyp_limits = None ax.plot(freqs, psd_mean, color=color, alpha=line_alpha, linewidth=0.5) if hyp_limits is not None: ax.fill_between(freqs, hyp_limits[0], y2=hyp_limits[1], facecolor=color, alpha=area_alpha) if not average: picks = np.concatenate(picks_list) psd_list = np.concatenate(psd_list) types = np.array(inst.get_channel_types(picks=picks)) # Needed because the data do not match the info anymore. info = create_info([inst.ch_names[p] for p in picks], inst.info['sfreq'], types) info['chs'] = [inst.info['chs'][p] for p in picks] info['dev_head_t'] = inst.info['dev_head_t'] ch_types_used = list() for this_type in _VALID_CHANNEL_TYPES: if this_type in types: ch_types_used.append(this_type) assert len(ch_types_used) == len(ax_list) unit = '' units = {t: yl for t, yl in zip(ch_types_used, ylabels)} titles = {c: t for c, t in zip(ch_types_used, titles_list)} picks = np.arange(len(psd_list)) if not spatial_colors: spatial_colors = color _plot_lines(psd_list, info, picks, fig, ax_list, spatial_colors, unit, units=units, scalings=None, hline=None, gfp=False, types=types, zorder='std', xlim=(freqs[0], freqs[-1]), ylim=None, times=freqs, bad_ch_idx=[], titles=titles, ch_types_used=ch_types_used, selectable=True, psd=True, line_alpha=line_alpha, nave=None, time_unit='ms', sphere=sphere) for ii, (ax, xlabel) in enumerate(zip(ax_list, xlabels_list)): ax.grid(True, linestyle=':') if xscale == 'log': ax.set(xscale='log') ax.set(xlim=[freqs[1] if freqs[0] == 0 else freqs[0], freqs[-1]]) ax.get_xaxis().set_major_formatter(ScalarFormatter()) else: # xscale == 'linear' ax.set(xlim=(freqs[0], freqs[-1])) if make_label: ax.set(ylabel=ylabels[ii], title=titles_list[ii]) if xlabel: ax.set_xlabel('Frequency (Hz)') if make_label: fig.align_ylabels(axs=ax_list) return fig def _trim_ticks(ticks, _min, _max): """Remove ticks that are more extreme than the given limits.""" keep = np.where(np.logical_and(ticks >= _min, ticks <= _max)) return ticks[keep] def _set_window_title(fig, title): if fig.canvas.manager is not None: fig.canvas.manager.set_window_title(title) def _shorten_path_from_middle(fpath, max_len=60, replacement='...'): """Truncate a path from the middle by omitting complete path elements.""" from os.path import sep if len(fpath) > max_len: pathlist = fpath.split(sep) # indices starting from middle, alternating sides, omitting final elem: # range(8) → 3, 4, 2, 5, 1, 6; range(7) → 2, 3, 1, 4, 0, 5 ixs_to_trunc = list(zip(range(len(pathlist) // 2 - 1, -1, -1), range(len(pathlist) // 2, len(pathlist) - 1))) ixs_to_trunc = np.array(ixs_to_trunc).flatten() for ix in ixs_to_trunc: pathlist[ix] = replacement truncs = (np.array(pathlist) == replacement).nonzero()[0] newpath = sep.join(pathlist[:truncs[0]] + pathlist[truncs[-1]:]) if len(newpath) < max_len: break return newpath return fpath def centers_to_edges(*arrays): """Convert center points to edges. Parameters ---------- *arrays : list of ndarray Each input array should be 1D monotonically increasing, and will be cast to float. Returns ------- arrays : list of ndarray Given each input of shape (N,), the output will have shape (N+1,). Examples -------- >>> x = [0., 0.1, 0.2, 0.3] >>> y = [20, 30, 40] >>> centers_to_edges(x, y) # doctest: +SKIP [array([-0.05, 0.05, 0.15, 0.25, 0.35]), array([15., 25., 35., 45.])] """ out = list() for ai, arr in enumerate(arrays): arr = np.asarray(arr, dtype=float) _check_option(f'arrays[{ai}].ndim', arr.ndim, (1,)) if len(arr) > 1: arr_diff = np.diff(arr) / 2. else: arr_diff = [abs(arr[0]) * 0.001] if arr[0] != 0 else [0.001] out.append(np.concatenate([ [arr[0] - arr_diff[0]], arr[:-1] + arr_diff, [arr[-1] + arr_diff[-1]]])) return out
bsd-3-clause
LouisePaulDelvaux/openfisca-france-data
openfisca_france_data/sources/utils.py
4
2153
# -*- coding: utf-8 -*- # OpenFisca -- A versatile microsimulation software # By: OpenFisca Team <contact@openfisca.fr> # # Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team # https://github.com/openfisca # # This file is part of OpenFisca. # # OpenFisca is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # OpenFisca is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from pandas import HDFStore, read_csv def csv2hdf5(csv_name, h5_name, dfname, option='frame'): """ Convert a csv file to a dataframe in a hdf5 Parameters: csv_name: string csv file name h5_name : string hdf5 file name dfname : string dataframe name option : string, 'frame' or 'table', default to 'frame' stoing type in the pytable """ table = read_csv(csv_name) store = HDFStore(h5_name) if option == 'frame': store.put(dfname, table) elif option == 'table': # for frame_table à la pytables object_cols = table.dtypes[ table.dtypes == 'object'] print object_cols.index try: store.append(dfname,table) except: print table.get_dtype_counts() object_cols = table.dtypes[ table.dtypes == 'object'] for col in object_cols.index: print 'removing object column :', col del table[col] store.append(dfname,table) print store store.close() def test_hdf5(h5_name): store = HDFStore(h5_name) for key in store.keys(): print key store.close() if __name__ == '__main__': pass
agpl-3.0
f3r/scikit-learn
sklearn/tests/test_pipeline.py
29
15239
""" Test the pipeline module. """ import numpy as np from scipy import sparse from sklearn.externals.six.moves import zip from sklearn.utils.testing import assert_raises, assert_raises_regex, assert_raise_message from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_warns_message from sklearn.base import clone from sklearn.pipeline import Pipeline, FeatureUnion, make_pipeline, make_union from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LinearRegression from sklearn.cluster import KMeans from sklearn.feature_selection import SelectKBest, f_classif from sklearn.decomposition import PCA, RandomizedPCA, TruncatedSVD from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from sklearn.feature_extraction.text import CountVectorizer JUNK_FOOD_DOCS = ( "the pizza pizza beer copyright", "the pizza burger beer copyright", "the the pizza beer beer copyright", "the burger beer beer copyright", "the coke burger coke copyright", "the coke burger burger", ) class IncorrectT(object): """Small class to test parameter dispatching. """ def __init__(self, a=None, b=None): self.a = a self.b = b class T(IncorrectT): def fit(self, X, y): return self def get_params(self, deep=False): return {'a': self.a, 'b': self.b} def set_params(self, **params): self.a = params['a'] return self class TransfT(T): def transform(self, X, y=None): return X def inverse_transform(self, X): return X class FitParamT(object): """Mock classifier """ def __init__(self): self.successful = False def fit(self, X, y, should_succeed=False): self.successful = should_succeed def predict(self, X): return self.successful def test_pipeline_init(): # Test the various init parameters of the pipeline. assert_raises(TypeError, Pipeline) # Check that we can't instantiate pipelines with objects without fit # method pipe = assert_raises(TypeError, Pipeline, [('svc', IncorrectT)]) # Smoke test with only an estimator clf = T() pipe = Pipeline([('svc', clf)]) assert_equal(pipe.get_params(deep=True), dict(svc__a=None, svc__b=None, svc=clf, **pipe.get_params(deep=False))) # Check that params are set pipe.set_params(svc__a=0.1) assert_equal(clf.a, 0.1) assert_equal(clf.b, None) # Smoke test the repr: repr(pipe) # Test with two objects clf = SVC() filter1 = SelectKBest(f_classif) pipe = Pipeline([('anova', filter1), ('svc', clf)]) # Check that we can't use the same stage name twice assert_raises(ValueError, Pipeline, [('svc', SVC()), ('svc', SVC())]) # Check that params are set pipe.set_params(svc__C=0.1) assert_equal(clf.C, 0.1) # Smoke test the repr: repr(pipe) # Check that params are not set when naming them wrong assert_raises(ValueError, pipe.set_params, anova__C=0.1) # Test clone pipe2 = clone(pipe) assert_false(pipe.named_steps['svc'] is pipe2.named_steps['svc']) # Check that apart from estimators, the parameters are the same params = pipe.get_params(deep=True) params2 = pipe2.get_params(deep=True) for x in pipe.get_params(deep=False): params.pop(x) for x in pipe2.get_params(deep=False): params2.pop(x) # Remove estimators that where copied params.pop('svc') params.pop('anova') params2.pop('svc') params2.pop('anova') assert_equal(params, params2) def test_pipeline_methods_anova(): # Test the various methods of the pipeline (anova). iris = load_iris() X = iris.data y = iris.target # Test with Anova + LogisticRegression clf = LogisticRegression() filter1 = SelectKBest(f_classif, k=2) pipe = Pipeline([('anova', filter1), ('logistic', clf)]) pipe.fit(X, y) pipe.predict(X) pipe.predict_proba(X) pipe.predict_log_proba(X) pipe.score(X, y) def test_pipeline_fit_params(): # Test that the pipeline can take fit parameters pipe = Pipeline([('transf', TransfT()), ('clf', FitParamT())]) pipe.fit(X=None, y=None, clf__should_succeed=True) # classifier should return True assert_true(pipe.predict(None)) # and transformer params should not be changed assert_true(pipe.named_steps['transf'].a is None) assert_true(pipe.named_steps['transf'].b is None) def test_pipeline_raise_set_params_error(): # Test pipeline raises set params error message for nested models. pipe = Pipeline([('cls', LinearRegression())]) # expected error message error_msg = ('Invalid parameter %s for estimator %s. ' 'Check the list of available parameters ' 'with `estimator.get_params().keys()`.') assert_raise_message(ValueError, error_msg % ('fake', 'Pipeline'), pipe.set_params, fake='nope') # nested model check assert_raise_message(ValueError, error_msg % ("fake", pipe), pipe.set_params, fake__estimator='nope') def test_pipeline_methods_pca_svm(): # Test the various methods of the pipeline (pca + svm). iris = load_iris() X = iris.data y = iris.target # Test with PCA + SVC clf = SVC(probability=True, random_state=0) pca = PCA(n_components='mle', whiten=True) pipe = Pipeline([('pca', pca), ('svc', clf)]) pipe.fit(X, y) pipe.predict(X) pipe.predict_proba(X) pipe.predict_log_proba(X) pipe.score(X, y) def test_pipeline_methods_preprocessing_svm(): # Test the various methods of the pipeline (preprocessing + svm). iris = load_iris() X = iris.data y = iris.target n_samples = X.shape[0] n_classes = len(np.unique(y)) scaler = StandardScaler() pca = RandomizedPCA(n_components=2, whiten=True) clf = SVC(probability=True, random_state=0, decision_function_shape='ovr') for preprocessing in [scaler, pca]: pipe = Pipeline([('preprocess', preprocessing), ('svc', clf)]) pipe.fit(X, y) # check shapes of various prediction functions predict = pipe.predict(X) assert_equal(predict.shape, (n_samples,)) proba = pipe.predict_proba(X) assert_equal(proba.shape, (n_samples, n_classes)) log_proba = pipe.predict_log_proba(X) assert_equal(log_proba.shape, (n_samples, n_classes)) decision_function = pipe.decision_function(X) assert_equal(decision_function.shape, (n_samples, n_classes)) pipe.score(X, y) def test_fit_predict_on_pipeline(): # test that the fit_predict method is implemented on a pipeline # test that the fit_predict on pipeline yields same results as applying # transform and clustering steps separately iris = load_iris() scaler = StandardScaler() km = KMeans(random_state=0) # first compute the transform and clustering step separately scaled = scaler.fit_transform(iris.data) separate_pred = km.fit_predict(scaled) # use a pipeline to do the transform and clustering in one step pipe = Pipeline([('scaler', scaler), ('Kmeans', km)]) pipeline_pred = pipe.fit_predict(iris.data) assert_array_almost_equal(pipeline_pred, separate_pred) def test_fit_predict_on_pipeline_without_fit_predict(): # tests that a pipeline does not have fit_predict method when final # step of pipeline does not have fit_predict defined scaler = StandardScaler() pca = PCA() pipe = Pipeline([('scaler', scaler), ('pca', pca)]) assert_raises_regex(AttributeError, "'PCA' object has no attribute 'fit_predict'", getattr, pipe, 'fit_predict') def test_feature_union(): # basic sanity check for feature union iris = load_iris() X = iris.data X -= X.mean(axis=0) y = iris.target svd = TruncatedSVD(n_components=2, random_state=0) select = SelectKBest(k=1) fs = FeatureUnion([("svd", svd), ("select", select)]) fs.fit(X, y) X_transformed = fs.transform(X) assert_equal(X_transformed.shape, (X.shape[0], 3)) # check if it does the expected thing assert_array_almost_equal(X_transformed[:, :-1], svd.fit_transform(X)) assert_array_equal(X_transformed[:, -1], select.fit_transform(X, y).ravel()) # test if it also works for sparse input # We use a different svd object to control the random_state stream fs = FeatureUnion([("svd", svd), ("select", select)]) X_sp = sparse.csr_matrix(X) X_sp_transformed = fs.fit_transform(X_sp, y) assert_array_almost_equal(X_transformed, X_sp_transformed.toarray()) # test setting parameters fs.set_params(select__k=2) assert_equal(fs.fit_transform(X, y).shape, (X.shape[0], 4)) # test it works with transformers missing fit_transform fs = FeatureUnion([("mock", TransfT()), ("svd", svd), ("select", select)]) X_transformed = fs.fit_transform(X, y) assert_equal(X_transformed.shape, (X.shape[0], 8)) def test_make_union(): pca = PCA() mock = TransfT() fu = make_union(pca, mock) names, transformers = zip(*fu.transformer_list) assert_equal(names, ("pca", "transft")) assert_equal(transformers, (pca, mock)) def test_pipeline_transform(): # Test whether pipeline works with a transformer at the end. # Also test pipeline.transform and pipeline.inverse_transform iris = load_iris() X = iris.data pca = PCA(n_components=2) pipeline = Pipeline([('pca', pca)]) # test transform and fit_transform: X_trans = pipeline.fit(X).transform(X) X_trans2 = pipeline.fit_transform(X) X_trans3 = pca.fit_transform(X) assert_array_almost_equal(X_trans, X_trans2) assert_array_almost_equal(X_trans, X_trans3) X_back = pipeline.inverse_transform(X_trans) X_back2 = pca.inverse_transform(X_trans) assert_array_almost_equal(X_back, X_back2) def test_pipeline_fit_transform(): # Test whether pipeline works with a transformer missing fit_transform iris = load_iris() X = iris.data y = iris.target transft = TransfT() pipeline = Pipeline([('mock', transft)]) # test fit_transform: X_trans = pipeline.fit_transform(X, y) X_trans2 = transft.fit(X, y).transform(X) assert_array_almost_equal(X_trans, X_trans2) def test_make_pipeline(): t1 = TransfT() t2 = TransfT() pipe = make_pipeline(t1, t2) assert_true(isinstance(pipe, Pipeline)) assert_equal(pipe.steps[0][0], "transft-1") assert_equal(pipe.steps[1][0], "transft-2") pipe = make_pipeline(t1, t2, FitParamT()) assert_true(isinstance(pipe, Pipeline)) assert_equal(pipe.steps[0][0], "transft-1") assert_equal(pipe.steps[1][0], "transft-2") assert_equal(pipe.steps[2][0], "fitparamt") def test_feature_union_weights(): # test feature union with transformer weights iris = load_iris() X = iris.data y = iris.target pca = RandomizedPCA(n_components=2, random_state=0) select = SelectKBest(k=1) # test using fit followed by transform fs = FeatureUnion([("pca", pca), ("select", select)], transformer_weights={"pca": 10}) fs.fit(X, y) X_transformed = fs.transform(X) # test using fit_transform fs = FeatureUnion([("pca", pca), ("select", select)], transformer_weights={"pca": 10}) X_fit_transformed = fs.fit_transform(X, y) # test it works with transformers missing fit_transform fs = FeatureUnion([("mock", TransfT()), ("pca", pca), ("select", select)], transformer_weights={"mock": 10}) X_fit_transformed_wo_method = fs.fit_transform(X, y) # check against expected result # We use a different pca object to control the random_state stream assert_array_almost_equal(X_transformed[:, :-1], 10 * pca.fit_transform(X)) assert_array_equal(X_transformed[:, -1], select.fit_transform(X, y).ravel()) assert_array_almost_equal(X_fit_transformed[:, :-1], 10 * pca.fit_transform(X)) assert_array_equal(X_fit_transformed[:, -1], select.fit_transform(X, y).ravel()) assert_equal(X_fit_transformed_wo_method.shape, (X.shape[0], 7)) def test_feature_union_parallel(): # test that n_jobs work for FeatureUnion X = JUNK_FOOD_DOCS fs = FeatureUnion([ ("words", CountVectorizer(analyzer='word')), ("chars", CountVectorizer(analyzer='char')), ]) fs_parallel = FeatureUnion([ ("words", CountVectorizer(analyzer='word')), ("chars", CountVectorizer(analyzer='char')), ], n_jobs=2) fs_parallel2 = FeatureUnion([ ("words", CountVectorizer(analyzer='word')), ("chars", CountVectorizer(analyzer='char')), ], n_jobs=2) fs.fit(X) X_transformed = fs.transform(X) assert_equal(X_transformed.shape[0], len(X)) fs_parallel.fit(X) X_transformed_parallel = fs_parallel.transform(X) assert_equal(X_transformed.shape, X_transformed_parallel.shape) assert_array_equal( X_transformed.toarray(), X_transformed_parallel.toarray() ) # fit_transform should behave the same X_transformed_parallel2 = fs_parallel2.fit_transform(X) assert_array_equal( X_transformed.toarray(), X_transformed_parallel2.toarray() ) # transformers should stay fit after fit_transform X_transformed_parallel2 = fs_parallel2.transform(X) assert_array_equal( X_transformed.toarray(), X_transformed_parallel2.toarray() ) def test_feature_union_feature_names(): word_vect = CountVectorizer(analyzer="word") char_vect = CountVectorizer(analyzer="char_wb", ngram_range=(3, 3)) ft = FeatureUnion([("chars", char_vect), ("words", word_vect)]) ft.fit(JUNK_FOOD_DOCS) feature_names = ft.get_feature_names() for feat in feature_names: assert_true("chars__" in feat or "words__" in feat) assert_equal(len(feature_names), 35) def test_classes_property(): iris = load_iris() X = iris.data y = iris.target reg = make_pipeline(SelectKBest(k=1), LinearRegression()) reg.fit(X, y) assert_raises(AttributeError, getattr, reg, "classes_") clf = make_pipeline(SelectKBest(k=1), LogisticRegression(random_state=0)) assert_raises(AttributeError, getattr, clf, "classes_") clf.fit(X, y) assert_array_equal(clf.classes_, np.unique(y)) def test_X1d_inverse_transform(): transformer = TransfT() pipeline = make_pipeline(transformer) X = np.ones(10) msg = "1d X will not be reshaped in pipeline.inverse_transform" assert_warns_message(FutureWarning, msg, pipeline.inverse_transform, X)
bsd-3-clause
kiyoto/statsmodels
statsmodels/datasets/tests/test_utils.py
26
1697
import os import sys from statsmodels.datasets import get_rdataset, webuse, check_internet from numpy.testing import assert_, assert_array_equal, dec cur_dir = os.path.dirname(os.path.abspath(__file__)) def test_get_rdataset(): # smoke test if sys.version_info[0] >= 3: #NOTE: there's no way to test both since the cached files were #created with Python 2.x, they're strings, but Python 3 expects #bytes and the index file path is hard-coded so both can't live #side by side pass #duncan = get_rdataset("Duncan-py3", "car", cache=cur_dir) else: duncan = get_rdataset("Duncan", "car", cache=cur_dir) assert_(duncan.from_cache) #internet_available = check_internet() #@dec.skipif(not internet_available) def t_est_webuse(): # test copied and adjusted from iolib/tests/test_foreign from statsmodels.iolib.tests.results.macrodata import macrodata_result as res2 #base_gh = "http://github.com/statsmodels/statsmodels/raw/master/statsmodels/datasets/macrodata/" base_gh = "http://statsmodels.sourceforge.net/devel/_static/" res1 = webuse('macrodata', baseurl=base_gh, as_df=False) assert_array_equal(res1 == res2, True) #@dec.skipif(not internet_available) def t_est_webuse_pandas(): # test copied and adjusted from iolib/tests/test_foreign from pandas.util.testing import assert_frame_equal from statsmodels.datasets import macrodata dta = macrodata.load_pandas().data base_gh = "http://github.com/statsmodels/statsmodels/raw/master/statsmodels/datasets/macrodata/" res1 = webuse('macrodata', baseurl=base_gh) res1 = res1.astype(float) assert_frame_equal(res1, dta)
bsd-3-clause
kirichoi/tellurium
spyder_mod/Spyder 3.3.0/spyder/app/mainwindow.py
2
133996
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Spyder, the Scientific PYthon Development EnviRonment ===================================================== Developped and maintained by the Spyder Project Contributors Copyright © Spyder Project Contributors Licensed under the terms of the MIT License (see spyder/__init__.py for details) """ # ============================================================================= # Stdlib imports # ============================================================================= from __future__ import print_function import atexit import errno import gc import os import os.path as osp import re import shutil import signal import socket import subprocess import sys import threading import traceback #============================================================================== # Keeping a reference to the original sys.exit before patching it #============================================================================== ORIGINAL_SYS_EXIT = sys.exit #============================================================================== # Check requirements #============================================================================== from spyder import requirements requirements.check_path() requirements.check_qt() requirements.check_spyder_kernels() #============================================================================== # Windows only: support for hiding console window when started with python.exe #============================================================================== set_attached_console_visible = None is_attached_console_visible = None set_windows_appusermodelid = None if os.name == 'nt': from spyder.utils.windows import (set_attached_console_visible, is_attached_console_visible, set_windows_appusermodelid) #============================================================================== # Workaround: importing rope.base.project here, otherwise this module can't # be imported if Spyder was executed from another folder than spyder #============================================================================== try: import rope.base.project # analysis:ignore except ImportError: pass #============================================================================== # Qt imports #============================================================================== from qtpy import API, PYQT5 from qtpy.compat import from_qvariant from qtpy.QtCore import (QByteArray, QCoreApplication, QPoint, QSize, Qt, QThread, QTimer, QUrl, Signal, Slot) from qtpy.QtGui import QColor, QDesktopServices, QIcon, QKeySequence, QPixmap from qtpy.QtWidgets import (QAction, QApplication, QDockWidget, QMainWindow, QMenu, QMessageBox, QShortcut, QSplashScreen, QStyleFactory) # Avoid a "Cannot mix incompatible Qt library" error on Windows platforms from qtpy import QtSvg # analysis:ignore # Avoid a bug in Qt: https://bugreports.qt.io/browse/QTBUG-46720 from qtpy import QtWebEngineWidgets # analysis:ignore # To catch font errors in QtAwesome from qtawesome.iconic_font import FontError #============================================================================== # Proper high DPI scaling is available in Qt >= 5.6.0. This attibute must # be set before creating the application. #============================================================================== from spyder.config.main import CONF if hasattr(Qt, 'AA_EnableHighDpiScaling'): QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, CONF.get('main', 'high_dpi_scaling')) #============================================================================== # Create our QApplication instance here because it's needed to render the # splash screen created below #============================================================================== from spyder.utils.qthelpers import qapplication, MENU_SEPARATOR from spyder.config.base import get_image_path MAIN_APP = qapplication() if PYQT5: APP_ICON = QIcon(get_image_path("spyder.svg")) else: APP_ICON = QIcon(get_image_path("spyder.png")) MAIN_APP.setWindowIcon(APP_ICON) #============================================================================== # Create splash screen out of MainWindow to reduce perceived startup time. #============================================================================== from spyder.config.base import _, get_image_path, DEV, running_under_pytest if not running_under_pytest(): SPLASH = QSplashScreen(QPixmap(get_image_path('Tellurium_splash.png'), 'png')) SPLASH_FONT = SPLASH.font() SPLASH_FONT.setPixelSize(10) SPLASH.setFont(SPLASH_FONT) SPLASH.show() SPLASH.showMessage(_("Initializing..."), Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) QApplication.processEvents() else: SPLASH = None #============================================================================== # Local utility imports #============================================================================== from spyder import (__version__, __project_url__, __forum_url__, __trouble_url__, __trouble_url_short__, get_versions) from spyder.config.base import (get_conf_path, get_module_source_path, STDERR, DEBUG, debug_print, MAC_APP_NAME, get_home_dir, running_in_mac_app, get_module_path, reset_config_files) from spyder.config.main import OPEN_FILES_PORT from spyder.config.utils import IMPORT_EXT, is_gtk_desktop from spyder.app.cli_options import get_options from spyder import dependencies from spyder.py3compat import (is_text_string, to_text_string, PY3, qbytearray_to_str, configparser as cp) from spyder.utils import encoding, programs from spyder.utils import icon_manager as ima from spyder.utils.introspection import module_completion from spyder.utils.programs import is_module_installed from spyder.utils.misc import select_port, getcwd_or_home, get_python_executable from spyder.widgets.fileswitcher import FileSwitcher #============================================================================== # Local gui imports #============================================================================== # NOTE: Move (if possible) import's of widgets and plugins exactly where they # are needed in MainWindow to speed up perceived startup time (i.e. the time # from clicking the Spyder icon to showing the splash screen). try: from spyder.utils.environ import WinUserEnvDialog except ImportError: WinUserEnvDialog = None # analysis:ignore from spyder.utils.qthelpers import (create_action, add_actions, get_icon, add_shortcut_to_tooltip, create_module_bookmark_actions, create_program_action, DialogManager, create_python_script_action, file_uri) from spyder.config.gui import get_shortcut from spyder.otherplugins import get_spyderplugins_mods from spyder.app import tour #============================================================================== # Get the cwd before initializing WorkingDirectory, which sets it to the one # used in the last session #============================================================================== CWD = getcwd_or_home() #============================================================================== # Spyder's main window widgets utilities #============================================================================== def get_python_doc_path(): """ Return Python documentation path (Windows: return the PythonXX.chm path if available) """ if os.name == 'nt': doc_path = osp.join(sys.prefix, "Doc") if not osp.isdir(doc_path): return python_chm = [path for path in os.listdir(doc_path) if re.match(r"(?i)Python[0-9]{3,6}.chm", path)] if python_chm: return file_uri(osp.join(doc_path, python_chm[0])) else: vinf = sys.version_info doc_path = '/usr/share/doc/python%d.%d/html' % (vinf[0], vinf[1]) python_doc = osp.join(doc_path, "index.html") if osp.isfile(python_doc): return file_uri(python_doc) #============================================================================== # Main Window #============================================================================== class MainWindow(QMainWindow): """Spyder main window""" DOCKOPTIONS = QMainWindow.AllowTabbedDocks|QMainWindow.AllowNestedDocks CURSORBLINK_OSDEFAULT = QApplication.cursorFlashTime() SPYDER_PATH = get_conf_path('path') SPYDER_NOT_ACTIVE_PATH = get_conf_path('not_active_path') BOOKMARKS = ( ('Python2', "https://docs.python.org/2/index.html", _("Python2 documentation")), ('Python3', "https://docs.python.org/3/index.html", _("Python3 documentation")), ('numpy', "http://docs.scipy.org/doc/", _("Numpy and Scipy documentation")), ('matplotlib', "http://matplotlib.sourceforge.net/contents.html", _("Matplotlib documentation")), ('PyQt5', "http://pyqt.sourceforge.net/Docs/PyQt5/", _("PyQt5 Reference Guide")), ('PyQt5', "http://pyqt.sourceforge.net/Docs/PyQt5/class_reference.html", _("PyQt5 API Reference")), ('winpython', "https://winpython.github.io/", _("WinPython")) ) DEFAULT_LAYOUTS = 4 # Signals restore_scrollbar_position = Signal() all_actions_defined = Signal() sig_pythonpath_changed = Signal() sig_open_external_file = Signal(str) sig_resized = Signal("QResizeEvent") # related to interactive tour sig_moved = Signal("QMoveEvent") # related to interactive tour def __init__(self, options=None): QMainWindow.__init__(self) qapp = QApplication.instance() if PYQT5: # Enabling scaling for high dpi qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) self.default_style = str(qapp.style().objectName()) self.dialog_manager = DialogManager() self.init_workdir = options.working_directory self.profile = options.profile self.multithreaded = options.multithreaded self.new_instance = options.new_instance self.open_project = options.open_project self.window_title = options.window_title self.debug_print("Start of MainWindow constructor") def signal_handler(signum, frame=None): """Handler for signals.""" sys.stdout.write('Handling signal: %s\n' % signum) sys.stdout.flush() QApplication.quit() if os.name == "nt": try: import win32api win32api.SetConsoleCtrlHandler(signal_handler, True) except ImportError: pass else: signal.signal(signal.SIGTERM, signal_handler) if not DEV: # Make spyder quit when presing ctrl+C in the console # In DEV Ctrl+C doesn't quit, because it helps to # capture the traceback when spyder freezes signal.signal(signal.SIGINT, signal_handler) # Use a custom Qt stylesheet if sys.platform == 'darwin': spy_path = get_module_source_path('spyder') img_path = osp.join(spy_path, 'images') mac_style = open(osp.join(spy_path, 'app', 'mac_stylesheet.qss')).read() mac_style = mac_style.replace('$IMAGE_PATH', img_path) self.setStyleSheet(mac_style) # Create our TEMPDIR if not osp.isdir(programs.TEMPDIR): os.mkdir(programs.TEMPDIR) # Shortcut management data self.shortcut_data = [] # Loading Spyder path self.path = [] self.not_active_path = [] self.project_path = [] if osp.isfile(self.SPYDER_PATH): self.path, _x = encoding.readlines(self.SPYDER_PATH) self.path = [name for name in self.path if osp.isdir(name)] if osp.isfile(self.SPYDER_NOT_ACTIVE_PATH): self.not_active_path, _x = \ encoding.readlines(self.SPYDER_NOT_ACTIVE_PATH) self.not_active_path = \ [name for name in self.not_active_path if osp.isdir(name)] self.remove_path_from_sys_path() self.add_path_to_sys_path() # Plugins self.console = None self.workingdirectory = None self.editor = None self.explorer = None self.help = None self.onlinehelp = None self.projects = None self.outlineexplorer = None self.historylog = None self.extconsole = None self.ipyconsole = None self.variableexplorer = None self.findinfiles = None self.thirdparty_plugins = [] # Tour # TODO: Should I consider it a plugin?? or? self.tour = None self.tours_available = None # File switcher self.fileswitcher = None # Check for updates Thread and Worker, refereces needed to prevent # segfaulting self.check_updates_action = None self.thread_updates = None self.worker_updates = None self.give_updates_feedback = True # Preferences from spyder.plugins.configdialog import (MainConfigPage, ColorSchemeConfigPage) from spyder.plugins.shortcuts import ShortcutsConfigPage from spyder.plugins.runconfig import RunConfigPage from spyder.plugins.maininterpreter import MainInterpreterConfigPage self.general_prefs = [MainConfigPage, ShortcutsConfigPage, ColorSchemeConfigPage, MainInterpreterConfigPage, RunConfigPage] self.prefs_index = None self.prefs_dialog_size = None # Quick Layouts and Dialogs from spyder.plugins.layoutdialog import (LayoutSaveDialog, LayoutSettingsDialog) self.dialog_layout_save = LayoutSaveDialog self.dialog_layout_settings = LayoutSettingsDialog # Actions self.lock_dockwidgets_action = None self.show_toolbars_action = None self.close_dockwidget_action = None self.undo_action = None self.redo_action = None self.copy_action = None self.cut_action = None self.paste_action = None self.selectall_action = None self.maximize_action = None self.fullscreen_action = None # Menu bars self.file_menu = None self.file_menu_actions = [] self.edit_menu = None self.edit_menu_actions = [] self.search_menu = None self.search_menu_actions = [] self.source_menu = None self.source_menu_actions = [] self.run_menu = None self.run_menu_actions = [] self.debug_menu = None self.debug_menu_actions = [] self.consoles_menu = None self.consoles_menu_actions = [] self.projects_menu = None self.projects_menu_actions = [] self.tools_menu = None self.tools_menu_actions = [] self.external_tools_menu = None # We must keep a reference to this, # otherwise the external tools menu is lost after leaving setup method self.external_tools_menu_actions = [] self.view_menu = None self.plugins_menu = None self.plugins_menu_actions = [] self.toolbars_menu = None self.help_menu = None self.help_menu_actions = [] # Status bar widgets self.mem_status = None self.cpu_status = None # Toolbars self.visible_toolbars = [] self.toolbarslist = [] self.main_toolbar = None self.main_toolbar_actions = [] self.file_toolbar = None self.file_toolbar_actions = [] self.edit_toolbar = None self.edit_toolbar_actions = [] self.search_toolbar = None self.search_toolbar_actions = [] self.source_toolbar = None self.source_toolbar_actions = [] self.run_toolbar = None self.run_toolbar_actions = [] self.debug_toolbar = None self.debug_toolbar_actions = [] self.layout_toolbar = None self.layout_toolbar_actions = [] if running_under_pytest(): # Show errors in internal console when testing. CONF.set('main', 'show_internal_errors', False) # Set window title self.set_window_title() if set_windows_appusermodelid != None: res = set_windows_appusermodelid() debug_print("appusermodelid: " + str(res)) # Setting QTimer if running in travis test_travis = os.environ.get('TEST_CI_APP', None) if test_travis is not None: global MAIN_APP timer_shutdown_time = 30000 self.timer_shutdown = QTimer(self) self.timer_shutdown.timeout.connect(MAIN_APP.quit) self.timer_shutdown.start(timer_shutdown_time) # Showing splash screen self.splash = SPLASH if CONF.get('main', 'current_version', '') != __version__: CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day...) # List of satellite widgets (registered in add_dockwidget): self.widgetlist = [] # Flags used if closing() is called by the exit() shell command self.already_closed = False self.is_starting_up = True self.is_setting_up = True self.dockwidgets_locked = CONF.get('main', 'panes_locked') self.floating_dockwidgets = [] self.window_size = None self.window_position = None self.state_before_maximizing = None self.current_quick_layout = None self.previous_layout_settings = None # TODO: related to quick layouts self.last_plugin = None self.fullscreen_flag = None # isFullscreen does not work as expected # The following flag remember the maximized state even when # the window is in fullscreen mode: self.maximized_flag = None # To keep track of the last focused widget self.last_focused_widget = None self.previous_focused_widget = None # Server to open external files on a single instance # This is needed in order to handle socket creation problems. # See issue 4132 if os.name == 'nt': try: self.open_files_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) except OSError as e: self.open_files_server = None QMessageBox.warning(None, "Spyder", _("An error occurred while creating a socket needed " "by Spyder. Please, try to run as an Administrator " "from cmd.exe the following command and then " "restart your computer: <br><br><span " "style=\'color: #555555\'><b>netsh winsock reset" "</b></span><br>")) else: self.open_files_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) self.apply_settings() self.debug_print("End of MainWindow constructor") def debug_print(self, message): """Debug prints""" debug_print(message) #---- Window setup def create_toolbar(self, title, object_name, iconsize=24): """Create and return toolbar with *title* and *object_name*""" toolbar = self.addToolBar(title) toolbar.setObjectName(object_name) toolbar.setIconSize(QSize(iconsize, iconsize)) self.toolbarslist.append(toolbar) return toolbar def setup(self): """Setup main window""" self.debug_print("*** Start of MainWindow setup ***") self.debug_print(" ..core actions") self.close_dockwidget_action = create_action(self, icon=ima.icon('DialogCloseButton'), text=_("Close current pane"), triggered=self.close_current_dockwidget, context=Qt.ApplicationShortcut) self.register_shortcut(self.close_dockwidget_action, "_", "Close pane") self.lock_dockwidgets_action = create_action(self, _("Lock panes"), toggled=self.toggle_lock_dockwidgets, context=Qt.ApplicationShortcut) self.register_shortcut(self.lock_dockwidgets_action, "_", "Lock unlock panes") # custom layouts shortcuts self.toggle_next_layout_action = create_action(self, _("Use next layout"), triggered=self.toggle_next_layout, context=Qt.ApplicationShortcut) self.toggle_previous_layout_action = create_action(self, _("Use previous layout"), triggered=self.toggle_previous_layout, context=Qt.ApplicationShortcut) self.register_shortcut(self.toggle_next_layout_action, "_", "Use next layout") self.register_shortcut(self.toggle_previous_layout_action, "_", "Use previous layout") # File switcher shortcuts self.file_switcher_action = create_action( self, _('File switcher...'), icon=ima.icon('filelist'), tip=_('Fast switch between files'), triggered=self.open_fileswitcher, context=Qt.ApplicationShortcut) self.register_shortcut(self.file_switcher_action, context="_", name="File switcher") self.symbol_finder_action = create_action( self, _('Symbol finder...'), icon=ima.icon('symbol_find'), tip=_('Fast symbol search in file'), triggered=self.open_symbolfinder, context=Qt.ApplicationShortcut) self.register_shortcut(self.symbol_finder_action, context="_", name="symbol finder", add_sc_to_tip=True) self.file_toolbar_actions = [self.file_switcher_action, self.symbol_finder_action] def create_edit_action(text, tr_text, icon): textseq = text.split(' ') method_name = textseq[0].lower()+"".join(textseq[1:]) action = create_action(self, tr_text, icon=icon, triggered=self.global_callback, data=method_name, context=Qt.WidgetShortcut) self.register_shortcut(action, "Editor", text) return action self.undo_action = create_edit_action('Undo', _('Undo'), ima.icon('undo')) self.redo_action = create_edit_action('Redo', _('Redo'), ima.icon('redo')) self.copy_action = create_edit_action('Copy', _('Copy'), ima.icon('editcopy')) self.cut_action = create_edit_action('Cut', _('Cut'), ima.icon('editcut')) self.paste_action = create_edit_action('Paste', _('Paste'), ima.icon('editpaste')) self.selectall_action = create_edit_action("Select All", _("Select All"), ima.icon('selectall')) self.edit_menu_actions = [self.undo_action, self.redo_action, None, self.cut_action, self.copy_action, self.paste_action, self.selectall_action] namespace = None self.debug_print(" ..toolbars") # File menu/toolbar self.file_menu = self.menuBar().addMenu(_("&File")) self.file_toolbar = self.create_toolbar(_("File toolbar"), "file_toolbar") # Edit menu/toolbar self.edit_menu = self.menuBar().addMenu(_("&Edit")) self.edit_toolbar = self.create_toolbar(_("Edit toolbar"), "edit_toolbar") # Search menu/toolbar self.search_menu = self.menuBar().addMenu(_("&Search")) self.search_toolbar = self.create_toolbar(_("Search toolbar"), "search_toolbar") # Source menu/toolbar self.source_menu = self.menuBar().addMenu(_("Sour&ce")) self.source_toolbar = self.create_toolbar(_("Source toolbar"), "source_toolbar") # Run menu/toolbar self.run_menu = self.menuBar().addMenu(_("&Run")) self.run_toolbar = self.create_toolbar(_("Run toolbar"), "run_toolbar") # Debug menu/toolbar self.debug_menu = self.menuBar().addMenu(_("&Debug")) self.debug_toolbar = self.create_toolbar(_("Debug toolbar"), "debug_toolbar") # Consoles menu/toolbar self.consoles_menu = self.menuBar().addMenu(_("C&onsoles")) # Projects menu self.projects_menu = self.menuBar().addMenu(_("&Projects")) self.projects_menu.aboutToShow.connect(self.valid_project) # Tools menu self.tools_menu = self.menuBar().addMenu(_("&Tools")) # View menu self.view_menu = self.menuBar().addMenu(_("&View")) # Help menu self.help_menu = self.menuBar().addMenu(_("&Help")) # Status bar status = self.statusBar() status.setObjectName("StatusBar") status.showMessage(_("Welcome to Spyder!"), 5000) self.debug_print(" ..tools") # Tools + External Tools prefs_action = create_action(self, _("Pre&ferences"), icon=ima.icon('configure'), triggered=self.edit_preferences, context=Qt.ApplicationShortcut) self.register_shortcut(prefs_action, "_", "Preferences", add_sc_to_tip=True) spyder_path_action = create_action(self, _("PYTHONPATH manager"), None, icon=ima.icon('pythonpath'), triggered=self.path_manager_callback, tip=_("Python Path Manager"), menurole=QAction.ApplicationSpecificRole) update_modules_action = create_action(self, _("Update module names list"), triggered=lambda: module_completion.reset(), tip=_("Refresh list of module names " "available in PYTHONPATH")) reset_spyder_action = create_action( self, _("Reset Spyder to factory defaults"), triggered=self.reset_spyder) self.tools_menu_actions = [prefs_action, spyder_path_action] if WinUserEnvDialog is not None: winenv_action = create_action(self, _("Current user environment variables..."), icon='win_env.png', tip=_("Show and edit current user environment " "variables in Windows registry " "(i.e. for all sessions)"), triggered=self.win_env) self.tools_menu_actions.append(winenv_action) self.tools_menu_actions += [reset_spyder_action, MENU_SEPARATOR, update_modules_action] # External Tools submenu self.external_tools_menu = QMenu(_("External Tools")) self.external_tools_menu_actions = [] # WinPython control panel self.wp_action = create_action(self, _("WinPython control panel"), icon=get_icon('winpython.svg'), triggered=lambda: programs.run_python_script('winpython', 'controlpanel')) if os.name == 'nt' and is_module_installed('winpython'): self.external_tools_menu_actions.append(self.wp_action) # Qt-related tools additact = [] for name in ("designer-qt4", "designer"): qtdact = create_program_action(self, _("Qt Designer"), name, 'qtdesigner.png') if qtdact: break for name in ("linguist-qt4", "linguist"): qtlact = create_program_action(self, _("Qt Linguist"), "linguist", 'qtlinguist.png') if qtlact: break args = ['-no-opengl'] if os.name == 'nt' else [] for act in (qtdact, qtlact): if act: additact.append(act) if additact and is_module_installed('winpython'): self.external_tools_menu_actions += [None] + additact # Guidata and Sift self.debug_print(" ..sift?") gdgq_act = [] # Guidata and Guiqwt don't support PyQt5 yet and they fail # with an AssertionError when imported using those bindings # (see issue 2274) try: from guidata import configtools from guidata import config # analysis:ignore guidata_icon = configtools.get_icon('guidata.svg') guidata_act = create_python_script_action(self, _("guidata examples"), guidata_icon, "guidata", osp.join("tests", "__init__")) gdgq_act += [guidata_act] except: pass try: from guidata import configtools from guiqwt import config # analysis:ignore guiqwt_icon = configtools.get_icon('guiqwt.svg') guiqwt_act = create_python_script_action(self, _("guiqwt examples"), guiqwt_icon, "guiqwt", osp.join("tests", "__init__")) if guiqwt_act: gdgq_act += [guiqwt_act] sift_icon = configtools.get_icon('sift.svg') sift_act = create_python_script_action(self, _("Sift"), sift_icon, "guiqwt", osp.join("tests", "sift")) if sift_act: gdgq_act += [sift_act] except: pass if gdgq_act: self.external_tools_menu_actions += [None] + gdgq_act # ViTables vitables_act = create_program_action(self, _("ViTables"), "vitables", 'vitables.png') if vitables_act: self.external_tools_menu_actions += [None, vitables_act] # Maximize current plugin self.maximize_action = create_action(self, '', triggered=self.maximize_dockwidget, context=Qt.ApplicationShortcut) self.register_shortcut(self.maximize_action, "_", "Maximize pane") self.__update_maximize_action() # Fullscreen mode self.fullscreen_action = create_action(self, _("Fullscreen mode"), triggered=self.toggle_fullscreen, context=Qt.ApplicationShortcut) self.register_shortcut(self.fullscreen_action, "_", "Fullscreen mode", add_sc_to_tip=True) # Main toolbar self.main_toolbar_actions = [self.maximize_action, self.fullscreen_action, None, prefs_action, spyder_path_action] self.main_toolbar = self.create_toolbar(_("Main toolbar"), "main_toolbar") # Internal console plugin self.debug_print(" ..plugin: internal console") from spyder.plugins.console import Console self.console = Console(self, namespace, exitfunc=self.closing, profile=self.profile, multithreaded=self.multithreaded, message=_("Spyder Internal Console\n\n" "This console is used to report application\n" "internal errors and to inspect Spyder\n" "internals with the following commands:\n" " spy.app, spy.window, dir(spy)\n\n" "Please don't use it to run your code\n\n")) self.console.register_plugin() # Working directory plugin self.debug_print(" ..plugin: working directory") from spyder.plugins.workingdirectory import WorkingDirectory self.workingdirectory = WorkingDirectory(self, self.init_workdir, main=self) self.workingdirectory.register_plugin() self.toolbarslist.append(self.workingdirectory) # Help plugin if CONF.get('help', 'enable'): self.set_splash(_("Loading help...")) from spyder.plugins.help import Help self.help = Help(self) self.help.register_plugin() # Outline explorer widget if CONF.get('outline_explorer', 'enable'): self.set_splash(_("Loading outline explorer...")) from spyder.plugins.outlineexplorer import OutlineExplorer self.outlineexplorer = OutlineExplorer(self) self.outlineexplorer.register_plugin() # Editor plugin self.set_splash(_("Loading editor...")) from spyder.plugins.editor import Editor self.editor = Editor(self) self.editor.register_plugin() # Populating file menu entries quit_action = create_action(self, _("&Quit"), icon=ima.icon('exit'), tip=_("Quit"), triggered=self.console.quit, context=Qt.ApplicationShortcut) self.register_shortcut(quit_action, "_", "Quit") restart_action = create_action(self, _("&Restart"), icon=ima.icon('restart'), tip=_("Restart"), triggered=self.restart, context=Qt.ApplicationShortcut) self.register_shortcut(restart_action, "_", "Restart") self.file_menu_actions += [self.file_switcher_action, self.symbol_finder_action, None, restart_action, quit_action] self.set_splash("") self.debug_print(" ..widgets") # Explorer if CONF.get('explorer', 'enable'): self.set_splash(_("Loading file explorer...")) from spyder.plugins.explorer import Explorer self.explorer = Explorer(self) self.explorer.register_plugin() # History log widget if CONF.get('historylog', 'enable'): self.set_splash(_("Loading history plugin...")) from spyder.plugins.history import HistoryLog self.historylog = HistoryLog(self) self.historylog.register_plugin() # Online help widget try: # Qt >= v4.4 from spyder.plugins.onlinehelp import OnlineHelp except ImportError: # Qt < v4.4 OnlineHelp = None # analysis:ignore if CONF.get('onlinehelp', 'enable') and OnlineHelp is not None: self.set_splash(_("Loading online help...")) self.onlinehelp = OnlineHelp(self) self.onlinehelp.register_plugin() # Project explorer widget self.set_splash(_("Loading project explorer...")) from spyder.plugins.projects import Projects self.projects = Projects(self) self.projects.register_plugin() self.project_path = self.projects.get_pythonpath(at_start=True) # Find in files if CONF.get('find_in_files', 'enable'): from spyder.plugins.findinfiles import FindInFiles self.findinfiles = FindInFiles(self) self.findinfiles.register_plugin() # Namespace browser self.set_splash(_("Loading namespace browser...")) from spyder.plugins.variableexplorer import VariableExplorer self.variableexplorer = VariableExplorer(self) self.variableexplorer.register_plugin() # IPython console self.set_splash(_("Loading IPython console...")) from spyder.plugins.ipythonconsole import IPythonConsole self.ipyconsole = IPythonConsole(self) self.ipyconsole.register_plugin() self.set_splash(_("Setting up main window...")) # Help menu trouble_action = create_action(self, _("Troubleshooting..."), triggered=self.trouble_guide) dep_action = create_action(self, _("Dependencies..."), triggered=self.show_dependencies, icon=ima.icon('advanced')) report_action = create_action(self, _("Report issue..."), icon=ima.icon('bug'), triggered=self.report_issue) support_action = create_action(self, _("Spyder support..."), triggered=self.google_group) self.check_updates_action = create_action(self, _("Check for updates..."), triggered=self.check_updates) # Spyder documentation spyder_doc = 'https://docs.spyder-ide.org/' doc_action = create_action(self, _("Spyder documentation"), icon=ima.icon('DialogHelpButton'), triggered=lambda: programs.start_file(spyder_doc)) self.register_shortcut(doc_action, "_", "spyder documentation") if self.help is not None: tut_action = create_action(self, _("Spyder tutorial"), triggered=self.help.show_tutorial) else: tut_action = None shortcuts_action = create_action(self, _("Shortcuts Summary"), shortcut="Meta+F1", triggered=self.show_shortcuts_dialog) #----- Tours self.tour = tour.AnimatedTour(self) self.tours_menu = QMenu(_("Interactive tours")) self.tour_menu_actions = [] # TODO: Only show intro tour for now. When we are close to finish # 3.0, we will finish and show the other tour self.tours_available = tour.get_tours(0) for i, tour_available in enumerate(self.tours_available): self.tours_available[i]['last'] = 0 tour_name = tour_available['name'] def trigger(i=i, self=self): # closure needed! return lambda: self.show_tour(i) temp_action = create_action(self, tour_name, tip="", triggered=trigger()) self.tour_menu_actions += [temp_action] self.tours_menu.addActions(self.tour_menu_actions) self.help_menu_actions = [doc_action, tut_action, shortcuts_action, self.tours_menu, MENU_SEPARATOR, trouble_action, report_action, dep_action, self.check_updates_action, support_action, MENU_SEPARATOR] # Python documentation if get_python_doc_path() is not None: pydoc_act = create_action(self, _("Python documentation"), triggered=lambda: programs.start_file(get_python_doc_path())) self.help_menu_actions.append(pydoc_act) # IPython documentation if self.help is not None: ipython_menu = QMenu(_("IPython documentation"), self) intro_action = create_action(self, _("Intro to IPython"), triggered=self.ipyconsole.show_intro) quickref_action = create_action(self, _("Quick reference"), triggered=self.ipyconsole.show_quickref) guiref_action = create_action(self, _("Console help"), triggered=self.ipyconsole.show_guiref) add_actions(ipython_menu, (intro_action, guiref_action, quickref_action)) self.help_menu_actions.append(ipython_menu) # Windows-only: documentation located in sys.prefix/Doc ipm_actions = [] def add_ipm_action(text, path): """Add installed Python module doc action to help submenu""" # QAction.triggered works differently for PySide and PyQt path = file_uri(path) if not API == 'pyside': slot=lambda _checked, path=path: programs.start_file(path) else: slot=lambda path=path: programs.start_file(path) action = create_action(self, text, icon='%s.png' % osp.splitext(path)[1][1:], triggered=slot) ipm_actions.append(action) sysdocpth = osp.join(sys.prefix, 'Doc') if osp.isdir(sysdocpth): # exists on Windows, except frozen dist. for docfn in os.listdir(sysdocpth): pt = r'([a-zA-Z\_]*)(doc)?(-dev)?(-ref)?(-user)?.(chm|pdf)' match = re.match(pt, docfn) if match is not None: pname = match.groups()[0] if pname not in ('Python', ): add_ipm_action(pname, osp.join(sysdocpth, docfn)) # Installed Python modules submenu (Windows only) if ipm_actions: pymods_menu = QMenu(_("Installed Python modules"), self) add_actions(pymods_menu, ipm_actions) self.help_menu_actions.append(pymods_menu) # Online documentation web_resources = QMenu(_("Online documentation")) webres_actions = create_module_bookmark_actions(self, self.BOOKMARKS) webres_actions.insert(2, None) webres_actions.insert(5, None) webres_actions.insert(8, None) add_actions(web_resources, webres_actions) self.help_menu_actions.append(web_resources) # Qt assistant link if sys.platform.startswith('linux') and not PYQT5: qta_exe = "assistant-qt4" else: qta_exe = "assistant" qta_act = create_program_action(self, _("Qt documentation"), qta_exe) if qta_act: self.help_menu_actions += [qta_act, None] # About Spyder about_action = create_action(self, _("About %s...") % "Spyder", icon=ima.icon('MessageBoxInformation'), triggered=self.about) self.help_menu_actions += [MENU_SEPARATOR, about_action] # Status bar widgets from spyder.widgets.status import MemoryStatus, CPUStatus self.mem_status = MemoryStatus(self, status) self.cpu_status = CPUStatus(self, status) self.apply_statusbar_settings() # Third-party plugins for mod in get_spyderplugins_mods(): try: plugin = mod.PLUGIN_CLASS(self) try: # Not all the plugins have the check_compatibility method # i.e Breakpoints, Profiler, Pylint check = plugin.check_compatibility()[0] except AttributeError: check = True if check: self.thirdparty_plugins.append(plugin) plugin.register_plugin() except Exception as error: print("%s: %s" % (mod, str(error)), file=STDERR) traceback.print_exc(file=STDERR) #----- View # View menu self.plugins_menu = QMenu(_("Panes"), self) self.toolbars_menu = QMenu(_("Toolbars"), self) self.quick_layout_menu = QMenu(_("Window layouts"), self) self.quick_layout_set_menu() self.view_menu.addMenu(self.plugins_menu) # Panes add_actions(self.view_menu, (self.lock_dockwidgets_action, self.close_dockwidget_action, self.maximize_action, MENU_SEPARATOR)) self.show_toolbars_action = create_action(self, _("Show toolbars"), triggered=self.show_toolbars, context=Qt.ApplicationShortcut) self.register_shortcut(self.show_toolbars_action, "_", "Show toolbars") self.view_menu.addMenu(self.toolbars_menu) self.view_menu.addAction(self.show_toolbars_action) add_actions(self.view_menu, (MENU_SEPARATOR, self.quick_layout_menu, self.toggle_previous_layout_action, self.toggle_next_layout_action, MENU_SEPARATOR, self.fullscreen_action)) if set_attached_console_visible is not None: cmd_act = create_action(self, _("Attached console window (debugging)"), toggled=set_attached_console_visible) cmd_act.setChecked(is_attached_console_visible()) add_actions(self.view_menu, (MENU_SEPARATOR, cmd_act)) # Adding external tools action to "Tools" menu if self.external_tools_menu_actions: external_tools_act = create_action(self, _("External Tools")) external_tools_act.setMenu(self.external_tools_menu) self.tools_menu_actions += [None, external_tools_act] # Filling out menu/toolbar entries: add_actions(self.file_menu, self.file_menu_actions) add_actions(self.edit_menu, self.edit_menu_actions) add_actions(self.search_menu, self.search_menu_actions) add_actions(self.source_menu, self.source_menu_actions) add_actions(self.run_menu, self.run_menu_actions) add_actions(self.debug_menu, self.debug_menu_actions) add_actions(self.consoles_menu, self.consoles_menu_actions) add_actions(self.projects_menu, self.projects_menu_actions) add_actions(self.tools_menu, self.tools_menu_actions) add_actions(self.external_tools_menu, self.external_tools_menu_actions) add_actions(self.help_menu, self.help_menu_actions) add_actions(self.main_toolbar, self.main_toolbar_actions) add_actions(self.file_toolbar, self.file_toolbar_actions) add_actions(self.edit_toolbar, self.edit_toolbar_actions) add_actions(self.search_toolbar, self.search_toolbar_actions) add_actions(self.source_toolbar, self.source_toolbar_actions) add_actions(self.debug_toolbar, self.debug_toolbar_actions) add_actions(self.run_toolbar, self.run_toolbar_actions) # Apply all defined shortcuts (plugins + 3rd-party plugins) self.apply_shortcuts() # Emitting the signal notifying plugins that main window menu and # toolbar actions are all defined: self.all_actions_defined.emit() # Window set-up self.debug_print("Setting up window...") self.setup_layout(default=False) # Show and hide shortcuts in menus for Mac. # This is a workaround because we can't disable shortcuts # by setting context=Qt.WidgetShortcut there if sys.platform == 'darwin': for name in ['file', 'edit', 'search', 'source', 'run', 'debug', 'projects', 'tools', 'plugins']: menu_object = getattr(self, name + '_menu') menu_object.aboutToShow.connect( lambda name=name: self.show_shortcuts(name)) menu_object.aboutToHide.connect( lambda name=name: self.hide_shortcuts(name)) if self.splash is not None: self.splash.hide() # Enabling tear off for all menus except help menu if CONF.get('main', 'tear_off_menus'): for child in self.menuBar().children(): if isinstance(child, QMenu) and child != self.help_menu: child.setTearOffEnabled(True) # Menu about to show for child in self.menuBar().children(): if isinstance(child, QMenu): try: child.aboutToShow.connect(self.update_edit_menu) except TypeError: pass self.debug_print("*** End of MainWindow setup ***") self.is_starting_up = False def post_visible_setup(self): """Actions to be performed only after the main window's `show` method was triggered""" self.restore_scrollbar_position.emit() # Remove our temporary dir atexit.register(self.remove_tmpdir) # [Workaround for Issue 880] # QDockWidget objects are not painted if restored as floating # windows, so we must dock them before showing the mainwindow, # then set them again as floating windows here. for widget in self.floating_dockwidgets: widget.setFloating(True) # In MacOS X 10.7 our app is not displayed after initialized (I don't # know why because this doesn't happen when started from the terminal), # so we need to resort to this hack to make it appear. if running_in_mac_app(): idx = __file__.index(MAC_APP_NAME) app_path = __file__[:idx] subprocess.call(['open', app_path + MAC_APP_NAME]) # Server to maintain just one Spyder instance and open files in it if # the user tries to start other instances with # $ spyder foo.py if (CONF.get('main', 'single_instance') and not self.new_instance and self.open_files_server): t = threading.Thread(target=self.start_open_files_server) t.setDaemon(True) t.start() # Connect the window to the signal emmited by the previous server # when it gets a client connected to it self.sig_open_external_file.connect(self.open_external_file) # Create Plugins and toolbars submenus self.create_plugins_menu() self.create_toolbars_menu() # Update toolbar visibility status self.toolbars_visible = CONF.get('main', 'toolbars_visible') self.load_last_visible_toolbars() # Update lock status of dockidgets (panes) self.lock_dockwidgets_action.setChecked(self.dockwidgets_locked) self.apply_panes_settings() # Hide Internal Console so that people don't use it instead of # the External or IPython ones if self.console.dockwidget.isVisible() and DEV is None: self.console.toggle_view_action.setChecked(False) self.console.dockwidget.hide() # Show Help and Consoles by default plugins_to_show = [self.ipyconsole] if self.help is not None: plugins_to_show.append(self.help) for plugin in plugins_to_show: if plugin.dockwidget.isVisible(): plugin.dockwidget.raise_() # Show history file if no console is visible if not self.ipyconsole.isvisible: self.historylog.add_history(get_conf_path('history.py')) if self.open_project: self.projects.open_project(self.open_project) else: # Load last project if a project was active when Spyder # was closed self.projects.reopen_last_project() # If no project is active, load last session if self.projects.get_active_project() is None: self.editor.setup_open_files() # Check for spyder updates if DEV is None and CONF.get('main', 'check_updates_on_startup'): self.give_updates_feedback = False self.check_updates(startup=True) # Show dialog with missing dependencies self.report_missing_dependencies() self.is_setting_up = False def set_window_title(self): """Set window title.""" if DEV is not None: title = u"Spyder %s (Python %s.%s)" % (__version__, sys.version_info[0], sys.version_info[1]) else: title = u"Spyder (Python %s.%s)" % (sys.version_info[0], sys.version_info[1]) if DEBUG: title += u" [DEBUG MODE %d]" % DEBUG if self.window_title is not None: title += u' -- ' + to_text_string(self.window_title) if self.projects is not None: path = self.projects.get_active_project_path() if path: path = path.replace(get_home_dir(), u'~') title = u'{0} - {1}'.format(path, title) self.base_title = title self.setWindowTitle(self.base_title) def report_missing_dependencies(self): """Show a QMessageBox with a list of missing hard dependencies""" missing_deps = dependencies.missing_dependencies() if missing_deps: QMessageBox.critical(self, _('Error'), _("<b>You have missing dependencies!</b>" "<br><br><tt>%s</tt><br><br>" "<b>Please install them to avoid this message.</b>" "<br><br>" "<i>Note</i>: Spyder could work without some of these " "dependencies, however to have a smooth experience when " "using Spyder we <i>strongly</i> recommend you to install " "all the listed missing dependencies.<br><br>" "Failing to install these dependencies might result in bugs. " "Please be sure that any found bugs are not the direct " "result of missing dependencies, prior to reporting a new " "issue." ) % missing_deps, QMessageBox.Ok) def load_window_settings(self, prefix, default=False, section='main'): """Load window layout settings from userconfig-based configuration with *prefix*, under *section* default: if True, do not restore inner layout""" get_func = CONF.get_default if default else CONF.get window_size = get_func(section, prefix+'size') prefs_dialog_size = get_func(section, prefix+'prefs_dialog_size') if default: hexstate = None else: hexstate = get_func(section, prefix+'state', None) pos = get_func(section, prefix+'position') # It's necessary to verify if the window/position value is valid # with the current screen. See issue 3748 width = pos[0] height = pos[1] screen_shape = QApplication.desktop().geometry() current_width = screen_shape.width() current_height = screen_shape.height() if current_width < width or current_height < height: pos = CONF.get_default(section, prefix+'position') is_maximized = get_func(section, prefix+'is_maximized') is_fullscreen = get_func(section, prefix+'is_fullscreen') return hexstate, window_size, prefs_dialog_size, pos, is_maximized, \ is_fullscreen def get_window_settings(self): """Return current window settings Symetric to the 'set_window_settings' setter""" window_size = (self.window_size.width(), self.window_size.height()) is_fullscreen = self.isFullScreen() if is_fullscreen: is_maximized = self.maximized_flag else: is_maximized = self.isMaximized() pos = (self.window_position.x(), self.window_position.y()) prefs_dialog_size = (self.prefs_dialog_size.width(), self.prefs_dialog_size.height()) hexstate = qbytearray_to_str(self.saveState()) return (hexstate, window_size, prefs_dialog_size, pos, is_maximized, is_fullscreen) def set_window_settings(self, hexstate, window_size, prefs_dialog_size, pos, is_maximized, is_fullscreen): """Set window settings Symetric to the 'get_window_settings' accessor""" self.setUpdatesEnabled(False) self.window_size = QSize(window_size[0], window_size[1]) # width,height self.prefs_dialog_size = QSize(prefs_dialog_size[0], prefs_dialog_size[1]) # width,height self.window_position = QPoint(pos[0], pos[1]) # x,y self.setWindowState(Qt.WindowNoState) self.resize(self.window_size) self.move(self.window_position) # Window layout if hexstate: self.restoreState( QByteArray().fromHex( str(hexstate).encode('utf-8')) ) # [Workaround for Issue 880] # QDockWidget objects are not painted if restored as floating # windows, so we must dock them before showing the mainwindow. for widget in self.children(): if isinstance(widget, QDockWidget) and widget.isFloating(): self.floating_dockwidgets.append(widget) widget.setFloating(False) # Is fullscreen? if is_fullscreen: self.setWindowState(Qt.WindowFullScreen) self.__update_fullscreen_action() # Is maximized? if is_fullscreen: self.maximized_flag = is_maximized elif is_maximized: self.setWindowState(Qt.WindowMaximized) self.setUpdatesEnabled(True) def save_current_window_settings(self, prefix, section='main', none_state=False): """Save current window settings with *prefix* in the userconfig-based configuration, under *section*""" win_size = self.window_size prefs_size = self.prefs_dialog_size CONF.set(section, prefix+'size', (win_size.width(), win_size.height())) CONF.set(section, prefix+'prefs_dialog_size', (prefs_size.width(), prefs_size.height())) CONF.set(section, prefix+'is_maximized', self.isMaximized()) CONF.set(section, prefix+'is_fullscreen', self.isFullScreen()) pos = self.window_position CONF.set(section, prefix+'position', (pos.x(), pos.y())) self.maximize_dockwidget(restore=True)# Restore non-maximized layout if none_state: CONF.set(section, prefix + 'state', None) else: qba = self.saveState() CONF.set(section, prefix + 'state', qbytearray_to_str(qba)) CONF.set(section, prefix+'statusbar', not self.statusBar().isHidden()) def tabify_plugins(self, first, second): """Tabify plugin dockwigdets""" self.tabifyDockWidget(first.dockwidget, second.dockwidget) # --- Layouts def setup_layout(self, default=False): """Setup window layout""" prefix = 'window' + '/' settings = self.load_window_settings(prefix, default) hexstate = settings[0] self.first_spyder_run = False if hexstate is None: # First Spyder execution: self.setWindowState(Qt.WindowMaximized) self.first_spyder_run = True self.setup_default_layouts('default', settings) # Now that the initial setup is done, copy the window settings, # except for the hexstate in the quick layouts sections for the # default layouts. # Order and name of the default layouts is found in config.py section = 'quick_layouts' get_func = CONF.get_default if default else CONF.get order = get_func(section, 'order') # restore the original defaults if reset layouts is called if default: CONF.set(section, 'active', order) CONF.set(section, 'order', order) CONF.set(section, 'names', order) for index, name, in enumerate(order): prefix = 'layout_{0}/'.format(index) self.save_current_window_settings(prefix, section, none_state=True) # store the initial layout as the default in spyder prefix = 'layout_default/' section = 'quick_layouts' self.save_current_window_settings(prefix, section, none_state=True) self.current_quick_layout = 'default' # Regenerate menu self.quick_layout_set_menu() self.set_window_settings(*settings) for plugin in self.widgetlist: try: plugin.initialize_plugin_in_mainwindow_layout() except Exception as error: print("%s: %s" % (plugin, str(error)), file=STDERR) traceback.print_exc(file=STDERR) def setup_default_layouts(self, index, settings): """Setup default layouts when run for the first time""" self.set_window_settings(*settings) self.setUpdatesEnabled(False) # IMPORTANT: order has to be the same as defined in the config file MATLAB, RSTUDIO, VERTICAL, HORIZONTAL = range(self.DEFAULT_LAYOUTS) # define widgets locally editor = self.editor console_ipy = self.ipyconsole console_int = self.console outline = self.outlineexplorer explorer_project = self.projects explorer_file = self.explorer explorer_variable = self.variableexplorer history = self.historylog finder = self.findinfiles help_plugin = self.help helper = self.onlinehelp plugins = self.thirdparty_plugins global_hidden_widgets = [finder, console_int, explorer_project, helper] + plugins global_hidden_toolbars = [self.source_toolbar, self.edit_toolbar, self.search_toolbar] # Layout definition # layouts are organized by columns, each colum is organized by rows # widths have to add 1.0, height per column have to add 1.0 # Spyder Default Initial Layout s_layout = {'widgets': [ # column 0 [[explorer_project]], # column 1 [[editor]], # column 2 [[outline]], # column 3 [[help_plugin, explorer_variable, helper, explorer_file, finder] + plugins, [console_int, console_ipy, history]] ], 'width fraction': [0.0, # column 0 width 0.55, # column 1 width 0.0, # column 2 width 0.45], # column 3 width 'height fraction': [[1.0], # column 0, row heights [1.0], # column 1, row heights [1.0], # column 2, row heights [0.46, 0.54]], # column 3, row heights 'hidden widgets': [outline], 'hidden toolbars': [], } r_layout = {'widgets': [ # column 0 [[editor], [console_ipy, console_int]], # column 1 [[explorer_variable, history, outline, finder] + plugins, [explorer_file, explorer_project, help_plugin, helper]] ], 'width fraction': [0.55, # column 0 width 0.45], # column 1 width 'height fraction': [[0.55, 0.45], # column 0, row heights [0.55, 0.45]], # column 1, row heights 'hidden widgets': [outline], 'hidden toolbars': [], } # Matlab m_layout = {'widgets': [ # column 0 [[explorer_file, explorer_project], [outline]], # column 1 [[editor], [console_ipy, console_int]], # column 2 [[explorer_variable, finder] + plugins, [history, help_plugin, helper]] ], 'width fraction': [0.20, # column 0 width 0.40, # column 1 width 0.40], # column 2 width 'height fraction': [[0.55, 0.45], # column 0, row heights [0.55, 0.45], # column 1, row heights [0.55, 0.45]], # column 2, row heights 'hidden widgets': [], 'hidden toolbars': [], } # Vertically split v_layout = {'widgets': [ # column 0 [[editor], [console_ipy, console_int, explorer_file, explorer_project, help_plugin, explorer_variable, history, outline, finder, helper] + plugins] ], 'width fraction': [1.0], # column 0 width 'height fraction': [[0.55, 0.45]], # column 0, row heights 'hidden widgets': [outline], 'hidden toolbars': [], } # Horizontally split h_layout = {'widgets': [ # column 0 [[editor]], # column 1 [[console_ipy, console_int, explorer_file, explorer_project, help_plugin, explorer_variable, history, outline, finder, helper] + plugins] ], 'width fraction': [0.55, # column 0 width 0.45], # column 1 width 'height fraction': [[1.0], # column 0, row heights [1.0]], # column 1, row heights 'hidden widgets': [outline], 'hidden toolbars': [] } # Layout selection layouts = {'default': s_layout, RSTUDIO: r_layout, MATLAB: m_layout, VERTICAL: v_layout, HORIZONTAL: h_layout} layout = layouts[index] widgets_layout = layout['widgets'] widgets = [] for column in widgets_layout : for row in column: for widget in row: if widget is not None: widgets.append(widget) # Make every widget visible for widget in widgets: widget.toggle_view(True) action = widget.toggle_view_action try: action.setChecked(widget.dockwidget.isVisible()) except: pass # Set the widgets horizontally for i in range(len(widgets) - 1): first, second = widgets[i], widgets[i+1] if first is not None and second is not None: self.splitDockWidget(first.dockwidget, second.dockwidget, Qt.Horizontal) # Arrange rows vertically for column in widgets_layout : for i in range(len(column) - 1): first_row, second_row = column[i], column[i+1] if first_row is not None and second_row is not None: self.splitDockWidget(first_row[0].dockwidget, second_row[0].dockwidget, Qt.Vertical) # Tabify for column in widgets_layout : for row in column: for i in range(len(row) - 1): first, second = row[i], row[i+1] if first is not None and second is not None: self.tabify_plugins(first, second) # Raise front widget per row row[0].dockwidget.show() row[0].dockwidget.raise_() # Hide toolbars hidden_toolbars = global_hidden_toolbars + layout['hidden toolbars'] for toolbar in hidden_toolbars: if toolbar is not None: toolbar.close() # Hide widgets hidden_widgets = global_hidden_widgets + layout['hidden widgets'] for widget in hidden_widgets: if widget is not None: widget.dockwidget.close() # set the width and height self._layout_widget_info = [] width, height = self.window_size.width(), self.window_size.height() # fix column width # for c in range(len(widgets_layout)): # widget = widgets_layout[c][0][0].dockwidget # min_width, max_width = widget.minimumWidth(), widget.maximumWidth() # info = {'widget': widget, # 'min width': min_width, # 'max width': max_width} # self._layout_widget_info.append(info) # new_width = int(layout['width fraction'][c] * width * 0.95) # widget.setMinimumWidth(new_width) # widget.setMaximumWidth(new_width) # widget.updateGeometry() # fix column height for c, column in enumerate(widgets_layout): for r in range(len(column) - 1): widget = column[r][0] dockwidget = widget.dockwidget dock_min_h = dockwidget.minimumHeight() dock_max_h = dockwidget.maximumHeight() info = {'widget': widget, 'dock min height': dock_min_h, 'dock max height': dock_max_h} self._layout_widget_info.append(info) # The 0.95 factor is to adjust height based on usefull # estimated area in the window new_height = int(layout['height fraction'][c][r]*height*0.95) dockwidget.setMinimumHeight(new_height) dockwidget.setMaximumHeight(new_height) self._custom_layout_timer = QTimer(self) self._custom_layout_timer.timeout.connect(self.layout_fix_timer) self._custom_layout_timer.setSingleShot(True) self._custom_layout_timer.start(5000) def layout_fix_timer(self): """Fixes the height of docks after a new layout is set.""" info = self._layout_widget_info for i in info: dockwidget = i['widget'].dockwidget if 'dock min width' in i: dockwidget.setMinimumWidth(i['dock min width']) dockwidget.setMaximumWidth(i['dock max width']) if 'dock min height' in i: dockwidget.setMinimumHeight(i['dock min height']) dockwidget.setMaximumHeight(i['dock max height']) dockwidget.updateGeometry() self.setUpdatesEnabled(True) @Slot() def toggle_previous_layout(self): """ """ self.toggle_layout('previous') @Slot() def toggle_next_layout(self): """ """ self.toggle_layout('next') def toggle_layout(self, direction='next'): """ """ get = CONF.get names = get('quick_layouts', 'names') order = get('quick_layouts', 'order') active = get('quick_layouts', 'active') if len(active) == 0: return layout_index = ['default'] for name in order: if name in active: layout_index.append(names.index(name)) current_layout = self.current_quick_layout dic = {'next': 1, 'previous': -1} if current_layout is None: # Start from default current_layout = 'default' if current_layout in layout_index: current_index = layout_index.index(current_layout) else: current_index = 0 new_index = (current_index + dic[direction]) % len(layout_index) self.quick_layout_switch(layout_index[new_index]) def quick_layout_set_menu(self): """ """ get = CONF.get names = get('quick_layouts', 'names') order = get('quick_layouts', 'order') active = get('quick_layouts', 'active') ql_actions = [] ql_actions = [create_action(self, _('Spyder Default Layout'), triggered=lambda: self.quick_layout_switch('default'))] for name in order: if name in active: index = names.index(name) # closure required so lambda works with the default parameter def trigger(i=index, self=self): return lambda: self.quick_layout_switch(i) qli_act = create_action(self, name, triggered=trigger()) # closure above replaces the following which stopped working # qli_act = create_action(self, name, triggered=lambda i=index: # self.quick_layout_switch(i) ql_actions += [qli_act] self.ql_save = create_action(self, _("Save current layout"), triggered=lambda: self.quick_layout_save(), context=Qt.ApplicationShortcut) self.ql_preferences = create_action(self, _("Layout preferences"), triggered=lambda: self.quick_layout_settings(), context=Qt.ApplicationShortcut) self.ql_reset = create_action(self, _('Reset to spyder default'), triggered=self.reset_window_layout) self.register_shortcut(self.ql_save, "_", "Save current layout") self.register_shortcut(self.ql_preferences, "_", "Layout preferences") ql_actions += [None] ql_actions += [self.ql_save, self.ql_preferences, self.ql_reset] self.quick_layout_menu.clear() add_actions(self.quick_layout_menu, ql_actions) if len(order) == 0: self.ql_preferences.setEnabled(False) else: self.ql_preferences.setEnabled(True) @Slot() def reset_window_layout(self): """Reset window layout to default""" answer = QMessageBox.warning(self, _("Warning"), _("Window layout will be reset to default settings: " "this affects window position, size and dockwidgets.\n" "Do you want to continue?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.setup_layout(default=True) def quick_layout_save(self): """Save layout dialog""" get = CONF.get set_ = CONF.set names = get('quick_layouts', 'names') order = get('quick_layouts', 'order') active = get('quick_layouts', 'active') dlg = self.dialog_layout_save(self, names) if dlg.exec_(): name = dlg.combo_box.currentText() if name in names: answer = QMessageBox.warning(self, _("Warning"), _("Layout <b>%s</b> will be \ overwritten. Do you want to \ continue?") % name, QMessageBox.Yes | QMessageBox.No) index = order.index(name) else: answer = True if None in names: index = names.index(None) names[index] = name else: index = len(names) names.append(name) order.append(name) # Always make active a new layout even if it overwrites an inactive # layout if name not in active: active.append(name) if answer: self.save_current_window_settings('layout_{}/'.format(index), section='quick_layouts') set_('quick_layouts', 'names', names) set_('quick_layouts', 'order', order) set_('quick_layouts', 'active', active) self.quick_layout_set_menu() def quick_layout_settings(self): """Layout settings dialog""" get = CONF.get set_ = CONF.set section = 'quick_layouts' names = get(section, 'names') order = get(section, 'order') active = get(section, 'active') dlg = self.dialog_layout_settings(self, names, order, active) if dlg.exec_(): set_(section, 'names', dlg.names) set_(section, 'order', dlg.order) set_(section, 'active', dlg.active) self.quick_layout_set_menu() def quick_layout_switch(self, index): """Switch to quick layout number *index*""" section = 'quick_layouts' try: settings = self.load_window_settings('layout_{}/'.format(index), section=section) (hexstate, window_size, prefs_dialog_size, pos, is_maximized, is_fullscreen) = settings # The defaults layouts will always be regenerated unless there was # an overwrite, either by rewriting with same name, or by deleting # and then creating a new one if hexstate is None: # The value for hexstate shouldn't be None for a custom saved # layout (ie, where the index is greater than the number of # defaults). See issue 6202. if index != 'default' and index >= self.DEFAULT_LAYOUTS: QMessageBox.critical( self, _("Warning"), _("Error opening the custom layout. Please close" " Spyder and try again. If the issue persists," " then you must use 'Reset to Spyder default' " "from the layout menu.")) return self.setup_default_layouts(index, settings) except cp.NoOptionError: QMessageBox.critical(self, _("Warning"), _("Quick switch layout #%s has not yet " "been defined.") % str(index)) return # TODO: is there any real use in calling the previous layout # setting? # self.previous_layout_settings = self.get_window_settings() self.set_window_settings(*settings) self.current_quick_layout = index # make sure the flags are correctly set for visible panes for plugin in self.widgetlist: action = plugin.toggle_view_action action.setChecked(plugin.dockwidget.isVisible()) # --- Show/Hide toolbars def _update_show_toolbars_action(self): """Update the text displayed in the menu entry.""" if self.toolbars_visible: text = _("Hide toolbars") tip = _("Hide toolbars") else: text = _("Show toolbars") tip = _("Show toolbars") self.show_toolbars_action.setText(text) self.show_toolbars_action.setToolTip(tip) def save_visible_toolbars(self): """Saves the name of the visible toolbars in the .ini file.""" toolbars = [] for toolbar in self.visible_toolbars: toolbars.append(toolbar.objectName()) CONF.set('main', 'last_visible_toolbars', toolbars) def get_visible_toolbars(self): """Collects the visible toolbars.""" toolbars = [] for toolbar in self.toolbarslist: if toolbar.toggleViewAction().isChecked(): toolbars.append(toolbar) self.visible_toolbars = toolbars def load_last_visible_toolbars(self): """Loads the last visible toolbars from the .ini file.""" toolbars_names = CONF.get('main', 'last_visible_toolbars', default=[]) if toolbars_names: dic = {} for toolbar in self.toolbarslist: dic[toolbar.objectName()] = toolbar toolbars = [] for name in toolbars_names: if name in dic: toolbars.append(dic[name]) self.visible_toolbars = toolbars else: self.get_visible_toolbars() self._update_show_toolbars_action() @Slot() def show_toolbars(self): """Show/Hides toolbars.""" value = not self.toolbars_visible CONF.set('main', 'toolbars_visible', value) if value: self.save_visible_toolbars() else: self.get_visible_toolbars() for toolbar in self.visible_toolbars: toolbar.toggleViewAction().setChecked(value) toolbar.setVisible(value) self.toolbars_visible = value self._update_show_toolbars_action() # --- Other def valid_project(self): """Handle an invalid active project.""" if bool(self.projects.get_active_project_path()): path = self.projects.get_active_project_path() if not self.projects.is_valid_project(path): if path: QMessageBox.critical( self, _('Error'), _("<b>{}</b> is no longer a valid Spyder project! " "Since it is the current active project, it will " "be closed automatically.").format(path)) self.projects.close_project() def free_memory(self): """Free memory after event.""" gc.collect() def plugin_focus_changed(self): """Focus has changed from one plugin to another""" self.update_edit_menu() self.update_search_menu() def show_shortcuts(self, menu): """Show action shortcuts in menu""" for element in getattr(self, menu + '_menu_actions'): if element and isinstance(element, QAction): if element._shown_shortcut is not None: element.setShortcut(element._shown_shortcut) def hide_shortcuts(self, menu): """Hide action shortcuts in menu""" for element in getattr(self, menu + '_menu_actions'): if element and isinstance(element, QAction): if element._shown_shortcut is not None: element.setShortcut(QKeySequence()) def get_focus_widget_properties(self): """Get properties of focus widget Returns tuple (widget, properties) where properties is a tuple of booleans: (is_console, not_readonly, readwrite_editor)""" widget = QApplication.focusWidget() from spyder.widgets.shell import ShellBaseWidget from spyder.widgets.editor import TextEditBaseWidget from spyder.widgets.ipythonconsole import ControlWidget # if focused widget isn't valid try the last focused if not isinstance(widget, (ShellBaseWidget, TextEditBaseWidget, ControlWidget)): widget = self.previous_focused_widget textedit_properties = None if isinstance(widget, (ShellBaseWidget, TextEditBaseWidget, ControlWidget)): console = isinstance(widget, (ShellBaseWidget, ControlWidget)) not_readonly = not widget.isReadOnly() readwrite_editor = not_readonly and not console textedit_properties = (console, not_readonly, readwrite_editor) return widget, textedit_properties def update_edit_menu(self): """Update edit menu""" widget, textedit_properties = self.get_focus_widget_properties() if textedit_properties is None: # widget is not an editor/console return #!!! Below this line, widget is expected to be a QPlainTextEdit instance console, not_readonly, readwrite_editor = textedit_properties # Editor has focus and there is no file opened in it if not console and not_readonly and not self.editor.is_file_opened(): return # Disabling all actions to begin with for child in self.edit_menu.actions(): child.setEnabled(False) self.selectall_action.setEnabled(True) # Undo, redo self.undo_action.setEnabled( readwrite_editor \ and widget.document().isUndoAvailable() ) self.redo_action.setEnabled( readwrite_editor \ and widget.document().isRedoAvailable() ) # Copy, cut, paste, delete has_selection = widget.has_selected_text() self.copy_action.setEnabled(has_selection) self.cut_action.setEnabled(has_selection and not_readonly) self.paste_action.setEnabled(not_readonly) # Comment, uncomment, indent, unindent... if not console and not_readonly: # This is the editor and current file is writable for action in self.editor.edit_menu_actions: action.setEnabled(True) def update_search_menu(self): """Update search menu""" if self.menuBar().hasFocus(): return widget, textedit_properties = self.get_focus_widget_properties() for action in self.editor.search_menu_actions: try: action.setEnabled(self.editor.isAncestorOf(widget)) except RuntimeError: pass if textedit_properties is None: # widget is not an editor/console return #!!! Below this line, widget is expected to be a QPlainTextEdit instance _x, _y, readwrite_editor = textedit_properties # Disable the replace action for read-only files self.search_menu_actions[3].setEnabled(readwrite_editor) def create_plugins_menu(self): order = ['editor', 'console', 'ipython_console', 'variable_explorer', 'help', None, 'explorer', 'outline_explorer', 'project_explorer', 'find_in_files', None, 'historylog', 'profiler', 'breakpoints', 'pylint', None, 'onlinehelp', 'internal_console'] for plugin in self.widgetlist: action = plugin.toggle_view_action action.setChecked(plugin.dockwidget.isVisible()) try: name = plugin.CONF_SECTION pos = order.index(name) except ValueError: pos = None if pos is not None: order[pos] = action else: order.append(action) actions = order[:] for action in order: if type(action) is str: actions.remove(action) self.plugins_menu_actions = actions add_actions(self.plugins_menu, actions) def create_toolbars_menu(self): order = ['file_toolbar', 'run_toolbar', 'debug_toolbar', 'main_toolbar', 'Global working directory', None, 'search_toolbar', 'edit_toolbar', 'source_toolbar'] for toolbar in self.toolbarslist: action = toolbar.toggleViewAction() name = toolbar.objectName() try: pos = order.index(name) except ValueError: pos = None if pos is not None: order[pos] = action else: order.append(action) add_actions(self.toolbars_menu, order) def createPopupMenu(self): menu = QMenu('', self) actions = self.help_menu_actions[:3] + \ [None, self.help_menu_actions[-1]] add_actions(menu, actions) return menu def set_splash(self, message): """Set splash message""" if self.splash is None: return if message: self.debug_print(message) self.splash.show() self.splash.showMessage(message, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) QApplication.processEvents() def remove_tmpdir(self): """Remove Spyder temporary directory""" if CONF.get('main', 'single_instance') and not self.new_instance: shutil.rmtree(programs.TEMPDIR, ignore_errors=True) def closeEvent(self, event): """closeEvent reimplementation""" if self.closing(True): event.accept() else: event.ignore() def resizeEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.fullscreen_flag: self.window_size = self.size() QMainWindow.resizeEvent(self, event) # To be used by the tour to be able to resize self.sig_resized.emit(event) def moveEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.fullscreen_flag: self.window_position = self.pos() QMainWindow.moveEvent(self, event) # To be used by the tour to be able to move self.sig_moved.emit(event) def hideEvent(self, event): """Reimplement Qt method""" try: for plugin in self.widgetlist: if plugin.isAncestorOf(self.last_focused_widget): plugin.visibility_changed(True) QMainWindow.hideEvent(self, event) except RuntimeError: QMainWindow.hideEvent(self, event) def change_last_focused_widget(self, old, now): """To keep track of to the last focused widget""" if (now is None and QApplication.activeWindow() is not None): QApplication.activeWindow().setFocus() self.last_focused_widget = QApplication.focusWidget() elif now is not None: self.last_focused_widget = now self.previous_focused_widget = old def closing(self, cancelable=False): """Exit tasks""" if self.already_closed or self.is_starting_up: return True if cancelable and CONF.get('main', 'prompt_on_exit'): reply = QMessageBox.critical(self, 'Spyder', 'Do you really want to exit?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.No: return False prefix = 'window' + '/' self.save_current_window_settings(prefix) if CONF.get('main', 'single_instance') and self.open_files_server: self.open_files_server.close() for plugin in self.thirdparty_plugins: if not plugin.closing_plugin(cancelable): return False for widget in self.widgetlist: if not widget.closing_plugin(cancelable): return False self.dialog_manager.close_all() if self.toolbars_visible: self.save_visible_toolbars() self.already_closed = True return True def add_dockwidget(self, child): """Add QDockWidget and toggleViewAction""" dockwidget, location = child.create_dockwidget() if CONF.get('main', 'vertical_dockwidget_titlebars'): dockwidget.setFeatures(dockwidget.features()| QDockWidget.DockWidgetVerticalTitleBar) self.addDockWidget(location, dockwidget) self.widgetlist.append(child) @Slot() def close_current_dockwidget(self): widget = QApplication.focusWidget() for plugin in self.widgetlist: if plugin.isAncestorOf(widget): plugin.dockwidget.hide() break def toggle_lock_dockwidgets(self, value): """Lock/Unlock dockwidgets""" self.dockwidgets_locked = value self.apply_panes_settings() CONF.set('main', 'panes_locked', value) def __update_maximize_action(self): if self.state_before_maximizing is None: text = _("Maximize current pane") tip = _("Maximize current pane") icon = ima.icon('maximize') else: text = _("Restore current pane") tip = _("Restore pane to its original size") icon = ima.icon('unmaximize') self.maximize_action.setText(text) self.maximize_action.setIcon(icon) self.maximize_action.setToolTip(tip) @Slot() @Slot(bool) def maximize_dockwidget(self, restore=False): """Shortcut: Ctrl+Alt+Shift+M First call: maximize current dockwidget Second call (or restore=True): restore original window layout""" if self.state_before_maximizing is None: if restore: return # Select plugin to maximize self.state_before_maximizing = self.saveState() focus_widget = QApplication.focusWidget() for plugin in self.widgetlist: plugin.dockwidget.hide() if plugin.isAncestorOf(focus_widget): self.last_plugin = plugin # Only plugins that have a dockwidget are part of widgetlist, # so last_plugin can be None after the above "for" cycle. # For example, this happens if, after Spyder has started, focus # is set to the Working directory toolbar (which doesn't have # a dockwidget) and then you press the Maximize button if self.last_plugin is None: # Using the Editor as default plugin to maximize self.last_plugin = self.editor # Maximize last_plugin self.last_plugin.dockwidget.toggleViewAction().setDisabled(True) self.setCentralWidget(self.last_plugin) self.last_plugin.ismaximized = True # Workaround to solve an issue with editor's outline explorer: # (otherwise the whole plugin is hidden and so is the outline explorer # and the latter won't be refreshed if not visible) self.last_plugin.show() self.last_plugin.visibility_changed(True) if self.last_plugin is self.editor: # Automatically show the outline if the editor was maximized: self.addDockWidget(Qt.RightDockWidgetArea, self.outlineexplorer.dockwidget) self.outlineexplorer.dockwidget.show() else: # Restore original layout (before maximizing current dockwidget) self.last_plugin.dockwidget.setWidget(self.last_plugin) self.last_plugin.dockwidget.toggleViewAction().setEnabled(True) self.setCentralWidget(None) self.last_plugin.ismaximized = False self.restoreState(self.state_before_maximizing) self.state_before_maximizing = None self.last_plugin.get_focus_widget().setFocus() self.__update_maximize_action() def __update_fullscreen_action(self): if self.isFullScreen(): icon = ima.icon('window_nofullscreen') else: icon = ima.icon('window_fullscreen') if is_text_string(icon): icon = get_icon(icon) self.fullscreen_action.setIcon(icon) @Slot() def toggle_fullscreen(self): if self.isFullScreen(): self.fullscreen_flag = False self.showNormal() if self.maximized_flag: self.showMaximized() else: self.maximized_flag = self.isMaximized() self.fullscreen_flag = True self.showFullScreen() self.__update_fullscreen_action() def add_to_toolbar(self, toolbar, widget): """Add widget actions to toolbar""" actions = widget.toolbar_actions if actions is not None: add_actions(toolbar, actions) @Slot() def about(self): """About Spyder""" versions = get_versions() # Show Mercurial revision for development version revlink = '' if versions['revision']: rev = versions['revision'] revlink = " (<a href='https://github.com/spyder-ide/spyder/"\ "commit/%s'>Commit: %s</a>)" % (rev, rev) QMessageBox.about(self, _("About %s") % "Spyder", """<b>Spyder %s</b> %s <br>The Scientific PYthon Development EnviRonment <br>Copyright &copy; The Spyder Project Contributors <br>Licensed under the terms of the MIT License <p>Created by Pierre Raybaut. <br>Developed and maintained by the <a href="%s/blob/master/AUTHORS">Spyder Project Contributors</a>. <br>Many thanks to all the Spyder beta testers and regular users. <p>For help with Spyder errors and crashes, please read our <a href="%s">Troubleshooting page</a>, and for bug reports and feature requests, visit our <a href="%s">Github website</a>. For project discussion, see our <a href="%s">Google Group</a>. <p>This project is part of a larger effort to promote and facilitate the use of Python for scientific and engineering software development. The popular Python distributions <a href="http://continuum.io/downloads">Anaconda</a>, <a href="https://winpython.github.io/">WinPython</a> and <a href="http://python-xy.github.io/">Python(x,y)</a> also contribute to this plan. <p>Python %s %dbits, Qt %s, %s %s on %s <p><small>Most of the icons for the Spyder 2 theme come from the Crystal Project (&copy; 2006-2007 Everaldo Coelho). Other icons for that theme come from <a href="http://p.yusukekamiyamane.com/"> Yusuke Kamiyamane</a> (all rights reserved) and from <a href="http://www.oxygen-icons.org/"> The Oxygen icon theme</a></small>. """ % (versions['spyder'], revlink, __project_url__, __trouble_url__, __project_url__, __forum_url__, versions['python'], versions['bitness'], versions['qt'], versions['qt_api'], versions['qt_api_ver'], versions['system'])) @Slot() def show_dependencies(self): """Show Spyder's Dependencies dialog box""" from spyder.widgets.dependencies import DependenciesDialog dlg = DependenciesDialog(None) dlg.set_data(dependencies.DEPENDENCIES) dlg.exec_() def render_issue(self, description='', traceback=''): """Render issue before sending it to Github""" # Get component versions versions = get_versions() # Get git revision for development version revision = '' if versions['revision']: revision = versions['revision'] # Make a description header in case no description is supplied if not description: description = "### What steps reproduce the problem?" # Make error section from traceback and add appropriate reminder header if traceback: error_section = ("### Traceback\n" "```python-traceback\n" "{}\n" "```".format(traceback)) else: error_section = '' issue_template = """\ ## Description {description} {error_section} ## Versions * Spyder version: {spyder_version} {commit} * Python version: {python_version} * Qt version: {qt_version} * {qt_api_name} version: {qt_api_version} * Operating System: {os_name} {os_version} ### Dependencies ``` {dependencies} ``` """.format(description=description, error_section=error_section, spyder_version=versions['spyder'], commit=revision, python_version=versions['python'], qt_version=versions['qt'], qt_api_name=versions['qt_api'], qt_api_version=versions['qt_api_ver'], os_name=versions['system'], os_version=versions['release'], dependencies=dependencies.status()) return issue_template @Slot() def report_issue(self, body=None, title=None, open_webpage=False): """Report a Spyder issue to github, generating body text if needed.""" if body is None: from spyder.widgets.reporterror import SpyderErrorDialog report_dlg = SpyderErrorDialog(self, is_report=True) report_dlg.show() else: if open_webpage: if PY3: from urllib.parse import quote else: from urllib import quote # analysis:ignore from qtpy.QtCore import QUrlQuery url = QUrl(__project_url__ + '/issues/new') query = QUrlQuery() query.addQueryItem("body", quote(body)) if title: query.addQueryItem("title", quote(title)) url.setQuery(query) QDesktopServices.openUrl(url) @Slot() def trouble_guide(self): """Open Spyder troubleshooting guide in a web browser.""" url = QUrl(__trouble_url__) QDesktopServices.openUrl(url) @Slot() def google_group(self): """Open Spyder Google Group in a web browser.""" url = QUrl(__forum_url__) QDesktopServices.openUrl(url) @Slot() def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = from_qvariant(action.data(), to_text_string) from spyder.widgets.editor import TextEditBaseWidget # If focused widget isn't valid try the last focused if not isinstance(widget, TextEditBaseWidget): widget = self.previous_focused_widget if isinstance(widget, TextEditBaseWidget): getattr(widget, callback)() def redirect_internalshell_stdio(self, state): if state: self.console.shell.interpreter.redirect_stds() else: self.console.shell.interpreter.restore_stds() def open_external_console(self, fname, wdir, args, interact, debug, python, python_args, systerm, post_mortem=False): """Open external console""" if systerm: # Running script in an external system terminal try: if CONF.get('main_interpreter', 'default'): executable = get_python_executable() else: executable = CONF.get('main_interpreter', 'executable') programs.run_python_script_in_terminal( fname, wdir, args, interact, debug, python_args, executable) except NotImplementedError: QMessageBox.critical(self, _("Run"), _("Running an external system terminal " "is not supported on platform %s." ) % os.name) def execute_in_external_console(self, lines, focus_to_editor): """ Execute lines in IPython console and eventually set focus to the Editor. """ console = self.ipyconsole console.visibility_changed(True) console.raise_() console.execute_code(lines) if focus_to_editor: self.editor.visibility_changed(True) def open_file(self, fname, external=False): """ Open filename with the appropriate application Redirect to the right widget (txt -> editor, spydata -> workspace, ...) or open file outside Spyder (if extension is not supported) """ fname = to_text_string(fname) ext = osp.splitext(fname)[1] if encoding.is_text_file(fname): self.editor.load(fname) elif self.variableexplorer is not None and ext in IMPORT_EXT: self.variableexplorer.import_data(fname) elif not external: fname = file_uri(fname) programs.start_file(fname) def open_external_file(self, fname): """ Open external files that can be handled either by the Editor or the variable explorer inside Spyder. """ fname = encoding.to_unicode_from_fs(fname) if osp.isfile(fname): self.open_file(fname, external=True) elif osp.isfile(osp.join(CWD, fname)): self.open_file(osp.join(CWD, fname), external=True) # ---- PYTHONPATH management, etc. def get_spyder_pythonpath(self): """Return Spyder PYTHONPATH""" active_path = [p for p in self.path if p not in self.not_active_path] return active_path + self.project_path def add_path_to_sys_path(self): """Add Spyder path to sys.path""" for path in reversed(self.get_spyder_pythonpath()): sys.path.insert(1, path) def remove_path_from_sys_path(self): """Remove Spyder path from sys.path""" for path in self.path + self.project_path: while path in sys.path: sys.path.remove(path) @Slot() def path_manager_callback(self): """Spyder path manager""" from spyder.widgets.pathmanager import PathManager self.remove_path_from_sys_path() project_path = self.projects.get_pythonpath() dialog = PathManager(self, self.path, project_path, self.not_active_path, sync=True) dialog.redirect_stdio.connect(self.redirect_internalshell_stdio) dialog.exec_() self.add_path_to_sys_path() try: encoding.writelines(self.path, self.SPYDER_PATH) # Saving path encoding.writelines(self.not_active_path, self.SPYDER_NOT_ACTIVE_PATH) except EnvironmentError: pass self.sig_pythonpath_changed.emit() def pythonpath_changed(self): """Projects PYTHONPATH contribution has changed""" self.remove_path_from_sys_path() self.project_path = self.projects.get_pythonpath() self.add_path_to_sys_path() self.sig_pythonpath_changed.emit() @Slot() def win_env(self): """Show Windows current user environment variables""" self.dialog_manager.show(WinUserEnvDialog(self)) #---- Preferences def apply_settings(self): """Apply settings changed in 'Preferences' dialog box""" qapp = QApplication.instance() # Set 'gtk+' as the default theme in Gtk-based desktops # Fixes Issue 2036 if is_gtk_desktop() and ('GTK+' in QStyleFactory.keys()): try: qapp.setStyle('gtk+') except: pass else: style_name = CONF.get('main', 'windows_style', self.default_style) style = QStyleFactory.create(style_name) if style is not None: style.setProperty('name', style_name) qapp.setStyle(style) default = self.DOCKOPTIONS if CONF.get('main', 'vertical_tabs'): default = default|QMainWindow.VerticalTabs if CONF.get('main', 'animated_docks'): default = default|QMainWindow.AnimatedDocks self.setDockOptions(default) self.apply_panes_settings() self.apply_statusbar_settings() if CONF.get('main', 'use_custom_cursor_blinking'): qapp.setCursorFlashTime(CONF.get('main', 'custom_cursor_blinking')) else: qapp.setCursorFlashTime(self.CURSORBLINK_OSDEFAULT) def apply_panes_settings(self): """Update dockwidgets features settings""" # Update toggle action on menu for child in self.widgetlist: features = child.FEATURES if CONF.get('main', 'vertical_dockwidget_titlebars'): features = features | QDockWidget.DockWidgetVerticalTitleBar if not self.dockwidgets_locked: features = features | QDockWidget.DockWidgetMovable child.dockwidget.setFeatures(features) child.update_margins() def apply_statusbar_settings(self): """Update status bar widgets settings""" show_status_bar = CONF.get('main', 'show_status_bar') self.statusBar().setVisible(show_status_bar) if show_status_bar: for widget, name in ((self.mem_status, 'memory_usage'), (self.cpu_status, 'cpu_usage')): if widget is not None: widget.setVisible(CONF.get('main', '%s/enable' % name)) widget.set_interval(CONF.get('main', '%s/timeout' % name)) else: return @Slot() def edit_preferences(self): """Edit Spyder preferences""" from spyder.plugins.configdialog import ConfigDialog dlg = ConfigDialog(self) dlg.size_change.connect(self.set_prefs_size) if self.prefs_dialog_size is not None: dlg.resize(self.prefs_dialog_size) for PrefPageClass in self.general_prefs: widget = PrefPageClass(dlg, main=self) widget.initialize() dlg.add_page(widget) for plugin in [self.workingdirectory, self.editor, self.projects, self.ipyconsole, self.historylog, self.help, self.variableexplorer, self.onlinehelp, self.explorer, self.findinfiles ]+self.thirdparty_plugins: if plugin is not None: try: widget = plugin.create_configwidget(dlg) if widget is not None: dlg.add_page(widget) except Exception: traceback.print_exc(file=sys.stderr) if self.prefs_index is not None: dlg.set_current_index(self.prefs_index) dlg.show() dlg.check_all_settings() dlg.pages_widget.currentChanged.connect(self.__preference_page_changed) dlg.exec_() def __preference_page_changed(self, index): """Preference page index has changed""" self.prefs_index = index def set_prefs_size(self, size): """Save preferences dialog size""" self.prefs_dialog_size = size #---- Shortcuts def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): """ Register QAction or QShortcut to Spyder main application, with shortcut (context, name, default) """ self.shortcut_data.append( (qaction_or_qshortcut, context, name, add_sc_to_tip) ) def apply_shortcuts(self): """Apply shortcuts settings to all widgets/plugins""" toberemoved = [] for index, (qobject, context, name, add_sc_to_tip) in enumerate(self.shortcut_data): keyseq = QKeySequence( get_shortcut(context, name) ) try: if isinstance(qobject, QAction): if sys.platform == 'darwin' and \ qobject._shown_shortcut == 'missing': qobject._shown_shortcut = keyseq else: qobject.setShortcut(keyseq) if add_sc_to_tip: add_shortcut_to_tooltip(qobject, context, name) elif isinstance(qobject, QShortcut): qobject.setKey(keyseq) except RuntimeError: # Object has been deleted toberemoved.append(index) for index in sorted(toberemoved, reverse=True): self.shortcut_data.pop(index) @Slot() def show_shortcuts_dialog(self): from spyder.widgets.shortcutssummary import ShortcutsSummaryDialog dlg = ShortcutsSummaryDialog(None) dlg.exec_() # -- Open files server def start_open_files_server(self): self.open_files_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) port = select_port(default_port=OPEN_FILES_PORT) CONF.set('main', 'open_files_port', port) self.open_files_server.bind(('127.0.0.1', port)) self.open_files_server.listen(20) while 1: # 1 is faster than True try: req, dummy = self.open_files_server.accept() except socket.error as e: # See Issue 1275 for details on why errno EINTR is # silently ignored here. eintr = errno.WSAEINTR if os.name == 'nt' else errno.EINTR # To avoid a traceback after closing on Windows if e.args[0] == eintr: continue # handle a connection abort on close error enotsock = (errno.WSAENOTSOCK if os.name == 'nt' else errno.ENOTSOCK) if e.args[0] in [errno.ECONNABORTED, enotsock]: return raise fname = req.recv(1024) fname = fname.decode('utf-8') self.sig_open_external_file.emit(fname) req.sendall(b' ') # ---- Quit and restart, and reset spyder defaults @Slot() def reset_spyder(self): """ Quit and reset Spyder and then Restart application. """ answer = QMessageBox.warning(self, _("Warning"), _("Spyder will restart and reset to default settings: <br><br>" "Do you want to continue?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.restart(reset=True) @Slot() def restart(self, reset=False): """ Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. """ # Get start path to use in restart script spyder_start_directory = get_module_path('spyder') restart_script = osp.join(spyder_start_directory, 'app', 'restart.py') # Get any initial argument passed when spyder was started # Note: Variables defined in bootstrap.py and spyder/app/start.py env = os.environ.copy() bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None) spyder_args = env.pop('SPYDER_ARGS') # Get current process and python running spyder pid = os.getpid() python = sys.executable # Check if started with bootstrap.py if bootstrap_args is not None: spyder_args = bootstrap_args is_bootstrap = True else: is_bootstrap = False # Pass variables as environment variables (str) to restarter subprocess env['SPYDER_ARGS'] = spyder_args env['SPYDER_PID'] = str(pid) env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap) env['SPYDER_RESET'] = str(reset) if DEV: if os.name == 'nt': env['PYTHONPATH'] = ';'.join(sys.path) else: env['PYTHONPATH'] = ':'.join(sys.path) # Build the command and popen arguments depending on the OS if os.name == 'nt': # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW shell = False else: startupinfo = None shell = True command = '"{0}" "{1}"' command = command.format(python, restart_script) try: if self.closing(True): subprocess.Popen(command, shell=shell, env=env, startupinfo=startupinfo) self.console.quit() except Exception as error: # If there is an error with subprocess, Spyder should not quit and # the error can be inspected in the internal console print(error) # spyder: test-skip print(command) # spyder: test-skip # ---- Interactive Tours def show_tour(self, index): """ """ frames = self.tours_available[index] self.tour.set_tour(index, frames, self) self.tour.start_tour() # ---- Global File Switcher def open_fileswitcher(self, symbol=False): """Open file list management dialog box.""" if self.fileswitcher is not None and \ self.fileswitcher.is_visible: self.fileswitcher.hide() self.fileswitcher.is_visible = False return if symbol: self.fileswitcher.plugin = self.editor self.fileswitcher.set_search_text('@') else: self.fileswitcher.set_search_text('') self.fileswitcher.show() self.fileswitcher.is_visible = True def open_symbolfinder(self): """Open symbol list management dialog box.""" self.open_fileswitcher(symbol=True) def add_to_fileswitcher(self, plugin, tabs, data, icon): """Add a plugin to the File Switcher.""" if self.fileswitcher is None: self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon) else: self.fileswitcher.add_plugin(plugin, tabs, data, icon) self.fileswitcher.sig_goto_file.connect( plugin.get_current_tab_manager().set_stack_index) # ---- Check for Spyder Updates def _check_updates_ready(self): """Called by WorkerUpdates when ready""" from spyder.widgets.helperwidgets import MessageCheckBox # feedback` = False is used on startup, so only positive feedback is # given. `feedback` = True is used when after startup (when using the # menu action, and gives feeback if updates are, or are not found. feedback = self.give_updates_feedback # Get results from worker update_available = self.worker_updates.update_available latest_release = self.worker_updates.latest_release error_msg = self.worker_updates.error url_r = __project_url__ + '/releases' url_i = 'https://docs.spyder-ide.org/installation.html' # Define the custom QMessageBox box = MessageCheckBox(icon=QMessageBox.Information, parent=self) box.setWindowTitle(_("Spyder updates")) box.set_checkbox_text(_("Check for updates on startup")) box.setStandardButtons(QMessageBox.Ok) box.setDefaultButton(QMessageBox.Ok) # Adjust the checkbox depending on the stored configuration section, option = 'main', 'check_updates_on_startup' check_updates = CONF.get(section, option) box.set_checked(check_updates) if error_msg is not None: msg = error_msg box.setText(msg) box.set_check_visible(False) box.exec_() check_updates = box.is_checked() else: if update_available: anaconda_msg = '' if 'Anaconda' in sys.version or 'conda-forge' in sys.version: anaconda_msg = _("<hr><b>IMPORTANT NOTE:</b> It seems " "that you are using Spyder with " "<b>Anaconda/Miniconda</b>. Please " "<b>don't</b> use <code>pip</code> to " "update it as that will probably break " "your installation.<br><br>" "Instead, please wait until new conda " "packages are available and use " "<code>conda</code> to perform the " "update.<hr>") msg = _("<b>Spyder %s is available!</b> <br><br>Please use " "your package manager to update Spyder or go to our " "<a href=\"%s\">Releases</a> page to download this " "new version. <br><br>If you are not sure how to " "proceed to update Spyder please refer to our " " <a href=\"%s\">Installation</a> instructions." "") % (latest_release, url_r, url_i) msg += '<br>' + anaconda_msg box.setText(msg) box.set_check_visible(True) box.exec_() check_updates = box.is_checked() elif feedback: msg = _("Spyder is up to date.") box.setText(msg) box.set_check_visible(False) box.exec_() check_updates = box.is_checked() # Update checkbox based on user interaction CONF.set(section, option, check_updates) # Enable check_updates_action after the thread has finished self.check_updates_action.setDisabled(False) # Provide feeback when clicking menu if check on startup is on self.give_updates_feedback = True @Slot() def check_updates(self, startup=False): """ Check for spyder updates on github releases using a QThread. """ from spyder.workers.updates import WorkerUpdates # Disable check_updates_action while the thread is working self.check_updates_action.setDisabled(True) if self.thread_updates is not None: self.thread_updates.terminate() self.thread_updates = QThread(self) self.worker_updates = WorkerUpdates(self, startup=startup) self.worker_updates.sig_ready.connect(self._check_updates_ready) self.worker_updates.sig_ready.connect(self.thread_updates.quit) self.worker_updates.moveToThread(self.thread_updates) self.thread_updates.started.connect(self.worker_updates.start) self.thread_updates.start() #============================================================================== # Utilities to create the 'main' function #============================================================================== def initialize(): """Initialize Qt, patching sys.exit and eventually setting up ETS""" # This doesn't create our QApplication, just holds a reference to # MAIN_APP, created above to show our splash screen as early as # possible app = qapplication() # --- Set application icon app.setWindowIcon(APP_ICON) #----Monkey patching QApplication class FakeQApplication(QApplication): """Spyder's fake QApplication""" def __init__(self, args): self = app # analysis:ignore @staticmethod def exec_(): """Do nothing because the Qt mainloop is already running""" pass from qtpy import QtWidgets QtWidgets.QApplication = FakeQApplication # ----Monkey patching sys.exit def fake_sys_exit(arg=[]): pass sys.exit = fake_sys_exit # ----Monkey patching sys.excepthook to avoid crashes in PyQt 5.5+ if PYQT5: def spy_excepthook(type_, value, tback): sys.__excepthook__(type_, value, tback) sys.excepthook = spy_excepthook # Removing arguments from sys.argv as in standard Python interpreter sys.argv = [''] # Selecting Qt4 backend for Enthought Tool Suite (if installed) try: from enthought.etsconfig.api import ETSConfig ETSConfig.toolkit = 'qt4' except ImportError: pass return app class Spy(object): """ Inspect Spyder internals Attributes: app Reference to main QApplication object window Reference to spyder.MainWindow widget """ def __init__(self, app, window): self.app = app self.window = window def __dir__(self): return list(self.__dict__.keys()) +\ [x for x in dir(self.__class__) if x[0] != '_'] def versions(self): return get_versions() def run_spyder(app, options, args): """ Create and show Spyder's main window Start QApplication event loop """ #TODO: insert here # Main window main = MainWindow(options) try: main.setup() except BaseException: if main.console is not None: try: main.console.shell.exit_interpreter() except BaseException: pass raise main.show() main.post_visible_setup() if main.console: main.console.shell.interpreter.namespace['spy'] = \ Spy(app=app, window=main) # Open external files passed as args if args: for a in args: main.open_external_file(a) # Don't show icons in menus for Mac if sys.platform == 'darwin': QCoreApplication.setAttribute(Qt.AA_DontShowIconsInMenus, True) # Open external files with our Mac app if running_in_mac_app(): app.sig_open_external_file.connect(main.open_external_file) # To give focus again to the last focused widget after restoring # the window app.focusChanged.connect(main.change_last_focused_widget) if not running_under_pytest(): app.exec_() return main #============================================================================== # Main #============================================================================== def main(): """Main function""" if running_under_pytest(): try: from unittest.mock import Mock except ImportError: from mock import Mock # Python 2 options = Mock() options.working_directory = None options.profile = False options.multithreaded = False options.new_instance = False options.open_project = None options.window_title = None app = initialize() window = run_spyder(app, options, None) return window # **** Collect command line options **** # Note regarding Options: # It's important to collect options before monkey patching sys.exit, # otherwise, optparse won't be able to exit if --help option is passed options, args = get_options() if options.show_console: print("(Deprecated) --show console does nothing, now the default " " behavior is to show the console, use --hide-console if you " "want to hide it") if set_attached_console_visible is not None: set_attached_console_visible(not options.hide_console or options.reset_config_files or options.reset_to_defaults or options.optimize or bool(DEBUG)) app = initialize() if options.reset_config_files: # <!> Remove all configuration files! reset_config_files() return elif options.reset_to_defaults: # Reset Spyder settings to defaults CONF.reset_to_defaults(save=True) return elif options.optimize: # Optimize the whole Spyder's source code directory import spyder programs.run_python_script(module="compileall", args=[spyder.__path__[0]], p_args=['-O']) return # Show crash dialog if CONF.get('main', 'crash', False) and not DEV: CONF.set('main', 'crash', False) if SPLASH is not None: SPLASH.hide() QMessageBox.information( None, "Spyder", "Spyder crashed during last session.<br><br>" "If Spyder does not start at all and <u>before submitting a " "bug report</u>, please try to reset settings to defaults by " "running Spyder with the command line option '--reset':<br>" "<span style=\'color: #555555\'><b>spyder --reset</b></span>" "<br><br>" "<span style=\'color: #ff5555\'><b>Warning:</b></span> " "this command will remove all your Spyder configuration files " "located in '%s').<br><br>" "If Spyder still fails to launch, you should consult our " "comprehensive <b><a href=\"%s\">Troubleshooting Guide</a></b>, " "which when followed carefully solves the vast majority of " "crashes; also, take " "the time to search for <a href=\"%s\">known bugs</a> or " "<a href=\"%s\">discussions</a> matching your situation before " "submitting a report to our <a href=\"%s\">issue tracker</a>. " "Your feedback will always be greatly appreciated." "" % (get_conf_path(), __trouble_url__, __project_url__, __forum_url__, __project_url__)) # Create main window mainwindow = None try: mainwindow = run_spyder(app, options, args) except FontError as fontError: QMessageBox.information(None, "Spyder", "Spyder was unable to load the <i>Spyder 3</i> " "icon theme. That's why it's going to fallback to the " "theme used in Spyder 2.<br><br>" "For that, please close this window and start Spyder again.") CONF.set('main', 'icon_theme', 'spyder 2') except BaseException: CONF.set('main', 'crash', True) import traceback traceback.print_exc(file=STDERR) traceback.print_exc(file=open('spyder_crash.log', 'w')) if mainwindow is None: # An exception occured if SPLASH is not None: SPLASH.hide() return ORIGINAL_SYS_EXIT() if __name__ == "__main__": main()
apache-2.0
likelyzhao/mxnet
example/dec/dec.py
15
7064
# pylint: skip-file from __future__ import print_function import sys import os # code to automatically download dataset curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) sys.path = [os.path.join(curr_path, "../autoencoder")] + sys.path import mxnet as mx import numpy as np import data from scipy.spatial.distance import cdist from sklearn.cluster import KMeans import model from autoencoder import AutoEncoderModel from solver import Solver, Monitor import logging def cluster_acc(Y_pred, Y): from sklearn.utils.linear_assignment_ import linear_assignment assert Y_pred.size == Y.size D = max(Y_pred.max(), Y.max())+1 w = np.zeros((D,D), dtype=np.int64) for i in range(Y_pred.size): w[Y_pred[i], int(Y[i])] += 1 ind = linear_assignment(w.max() - w) return sum([w[i,j] for i,j in ind])*1.0/Y_pred.size, w class DECModel(model.MXModel): class DECLoss(mx.operator.NumpyOp): def __init__(self, num_centers, alpha): super(DECModel.DECLoss, self).__init__(need_top_grad=False) self.num_centers = num_centers self.alpha = alpha def forward(self, in_data, out_data): z = in_data[0] mu = in_data[1] q = out_data[0] self.mask = 1.0/(1.0+cdist(z, mu)**2/self.alpha) q[:] = self.mask**((self.alpha+1.0)/2.0) q[:] = (q.T/q.sum(axis=1)).T def backward(self, out_grad, in_data, out_data, in_grad): q = out_data[0] z = in_data[0] mu = in_data[1] p = in_data[2] dz = in_grad[0] dmu = in_grad[1] self.mask *= (self.alpha+1.0)/self.alpha*(p-q) dz[:] = (z.T*self.mask.sum(axis=1)).T - self.mask.dot(mu) dmu[:] = (mu.T*self.mask.sum(axis=0)).T - self.mask.T.dot(z) def infer_shape(self, in_shape): assert len(in_shape) == 3 assert len(in_shape[0]) == 2 input_shape = in_shape[0] label_shape = (input_shape[0], self.num_centers) mu_shape = (self.num_centers, input_shape[1]) out_shape = (input_shape[0], self.num_centers) return [input_shape, mu_shape, label_shape], [out_shape] def list_arguments(self): return ['data', 'mu', 'label'] def setup(self, X, num_centers, alpha, save_to='dec_model'): sep = X.shape[0]*9/10 X_train = X[:sep] X_val = X[sep:] ae_model = AutoEncoderModel(self.xpu, [X.shape[1],500,500,2000,10], pt_dropout=0.2) if not os.path.exists(save_to+'_pt.arg'): ae_model.layerwise_pretrain(X_train, 256, 50000, 'sgd', l_rate=0.1, decay=0.0, lr_scheduler=mx.misc.FactorScheduler(20000,0.1)) ae_model.finetune(X_train, 256, 100000, 'sgd', l_rate=0.1, decay=0.0, lr_scheduler=mx.misc.FactorScheduler(20000,0.1)) ae_model.save(save_to+'_pt.arg') logging.log(logging.INFO, "Autoencoder Training error: %f"%ae_model.eval(X_train)) logging.log(logging.INFO, "Autoencoder Validation error: %f"%ae_model.eval(X_val)) else: ae_model.load(save_to+'_pt.arg') self.ae_model = ae_model self.dec_op = DECModel.DECLoss(num_centers, alpha) label = mx.sym.Variable('label') self.feature = self.ae_model.encoder self.loss = self.dec_op(data=self.ae_model.encoder, label=label, name='dec') self.args.update({k:v for k,v in self.ae_model.args.items() if k in self.ae_model.encoder.list_arguments()}) self.args['dec_mu'] = mx.nd.empty((num_centers, self.ae_model.dims[-1]), ctx=self.xpu) self.args_grad.update({k: mx.nd.empty(v.shape, ctx=self.xpu) for k,v in self.args.items()}) self.args_mult.update({k: k.endswith('bias') and 2.0 or 1.0 for k in self.args}) self.num_centers = num_centers def cluster(self, X, y=None, update_interval=None): N = X.shape[0] if not update_interval: update_interval = N batch_size = 256 test_iter = mx.io.NDArrayIter({'data': X}, batch_size=batch_size, shuffle=False, last_batch_handle='pad') args = {k: mx.nd.array(v.asnumpy(), ctx=self.xpu) for k, v in self.args.items()} z = list(model.extract_feature(self.feature, args, None, test_iter, N, self.xpu).values())[0] kmeans = KMeans(self.num_centers, n_init=20) kmeans.fit(z) args['dec_mu'][:] = kmeans.cluster_centers_ solver = Solver('sgd', momentum=0.9, wd=0.0, learning_rate=0.01) def ce(label, pred): return np.sum(label*np.log(label/(pred+0.000001)))/label.shape[0] solver.set_metric(mx.metric.CustomMetric(ce)) label_buff = np.zeros((X.shape[0], self.num_centers)) train_iter = mx.io.NDArrayIter({'data': X}, {'label': label_buff}, batch_size=batch_size, shuffle=False, last_batch_handle='roll_over') self.y_pred = np.zeros((X.shape[0])) def refresh(i): if i%update_interval == 0: z = list(model.extract_feature(self.feature, args, None, test_iter, N, self.xpu).values())[0] p = np.zeros((z.shape[0], self.num_centers)) self.dec_op.forward([z, args['dec_mu'].asnumpy()], [p]) y_pred = p.argmax(axis=1) print(np.std(np.bincount(y_pred)), np.bincount(y_pred)) print(np.std(np.bincount(y.astype(np.int))), np.bincount(y.astype(np.int))) if y is not None: print(cluster_acc(y_pred, y)[0]) weight = 1.0/p.sum(axis=0) weight *= self.num_centers/weight.sum() p = (p**2)*weight train_iter.data_list[1][:] = (p.T/p.sum(axis=1)).T print(np.sum(y_pred != self.y_pred), 0.001*y_pred.shape[0]) if np.sum(y_pred != self.y_pred) < 0.001*y_pred.shape[0]: self.y_pred = y_pred return True self.y_pred = y_pred solver.set_iter_start_callback(refresh) solver.set_monitor(Monitor(50)) solver.solve(self.xpu, self.loss, args, self.args_grad, None, train_iter, 0, 1000000000, {}, False) self.end_args = args if y is not None: return cluster_acc(self.y_pred, y)[0] else: return -1 def mnist_exp(xpu): X, Y = data.get_mnist() dec_model = DECModel(xpu, X, 10, 1.0, 'data/mnist') acc = [] for i in [10*(2**j) for j in range(9)]: acc.append(dec_model.cluster(X, Y, i)) logging.log(logging.INFO, 'Clustering Acc: %f at update interval: %d'%(acc[-1], i)) logging.info(str(acc)) logging.info('Best Clustering ACC: %f at update_interval: %d'%(np.max(acc), 10*(2**np.argmax(acc)))) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) mnist_exp(mx.gpu(0))
apache-2.0
kevin-coder/tensorflow-fork
tensorflow/contrib/labeled_tensor/python/ops/ops.py
6
46486
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Non-core ops for LabeledTensor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import types import numpy as np from six import string_types from tensorflow.contrib.labeled_tensor.python.ops import _typecheck as tc from tensorflow.contrib.labeled_tensor.python.ops import core from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import map_fn as map_fn_lib from tensorflow.python.ops import math_ops from tensorflow.python.ops import numerics from tensorflow.python.ops import random_ops from tensorflow.python.training import input # pylint: disable=redefined-builtin @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensor, ops.Tensor, core.Axis, tc.Optional(string_types)) def _gather_1d_on_axis(labeled_tensor, indexer, axis, name=None): with ops.name_scope(name, 'lt_take', [labeled_tensor]) as scope: temp_axes = core.Axes([axis] + list( labeled_tensor.axes.remove(axis.name).values())) transposed = core.transpose(labeled_tensor, temp_axes.keys()) indexed = core.LabeledTensor( array_ops.gather(transposed.tensor, indexer), temp_axes) return core.transpose(indexed, labeled_tensor.axes.keys(), name=scope) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Mapping(string_types, tc.Union(slice, collections.Hashable, list)), tc.Optional(string_types)) def select(labeled_tensor, selection, name=None): """Slice out a subset of the tensor. Args: labeled_tensor: The input tensor. selection: A dictionary mapping an axis name to a scalar, slice or list of values to select. Currently supports two types of selections: (a) Any number of scalar and/or slice selections. (b) Exactly one list selection, without any scalars or slices. name: Optional op name. Returns: The selection as a `LabeledTensor`. Raises: ValueError: If the tensor doesn't have an axis in the selection or if that axis lacks labels. KeyError: If any labels in a selection are not found in the original axis. NotImplementedError: If you attempt to combine a list selection with scalar selection or another list selection. """ with ops.name_scope(name, 'lt_select', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) slices = {} indexers = {} for axis_name, value in selection.items(): if axis_name not in labeled_tensor.axes: raise ValueError( 'The tensor does not have an axis named %s. Its axes are: %r' % (axis_name, labeled_tensor.axes.keys())) axis = labeled_tensor.axes[axis_name] if axis.labels is None: raise ValueError( 'The axis named %s does not have labels. The axis is: %r' % (axis_name, axis)) if isinstance(value, slice): # TODO(shoyer): consider deprecating using slices in favor of lists if value.start is None: start = None else: start = axis.index(value.start) if value.stop is None: stop = None else: # For now, follow the pandas convention of making labeled slices # inclusive of both bounds. stop = axis.index(value.stop) + 1 if value.step is not None: raise NotImplementedError('slicing with a step is not yet supported') slices[axis_name] = slice(start, stop) # Needs to be after checking for slices, since slice objects claim to be # instances of collections.Hashable but hash() on them fails. elif isinstance(value, collections.Hashable): slices[axis_name] = axis.index(value) elif isinstance(value, list): if indexers: raise NotImplementedError( 'select does not yet support more than one list selection at ' 'the same time') indexer = [axis.index(v) for v in value] indexers[axis_name] = ops.convert_to_tensor(indexer, dtype=dtypes.int64) else: # If type checking is working properly, this shouldn't be possible. raise TypeError('cannot handle arbitrary types') if indexers and slices: raise NotImplementedError( 'select does not yet support combined scalar and list selection') # For now, handle array selection separately, because tf.gather_nd does # not support gradients yet. Later, using gather_nd will let us combine # these paths. if indexers: (axis_name, indexer), = indexers.items() axis = core.Axis(axis_name, selection[axis_name]) return _gather_1d_on_axis(labeled_tensor, indexer, axis, name=scope) else: return core.slice_function(labeled_tensor, slices, name=scope) @tc.returns(core.LabeledTensor) @tc.accepts( tc.Collection(core.LabeledTensorLike), string_types, tc.Optional(string_types)) def concat(labeled_tensors, axis_name, name=None): """Concatenate tensors along a dimension. See tf.concat. Args: labeled_tensors: A list of input LabeledTensors. axis_name: The name of the axis along which to concatenate. name: Optional op name. Returns: The concatenated tensor. The coordinate labels for the concatenation dimension are also concatenated, if they are available for every tensor. Raises: ValueError: If fewer than one tensor inputs is provided, if the tensors have incompatible axes, or if `axis_name` isn't the name of an axis. """ with ops.name_scope(name, 'lt_concat', labeled_tensors) as scope: labeled_tensors = [ core.convert_to_labeled_tensor(lt) for lt in labeled_tensors ] if len(labeled_tensors) < 1: raise ValueError('concat expects at least 1 tensor, but received %s' % labeled_tensors) # All tensors must have these axes. axes_0 = labeled_tensors[0].axes axis_names = list(axes_0.keys()) if axis_name not in axis_names: raise ValueError('%s not in %s' % (axis_name, axis_names)) shared_axes = axes_0.remove(axis_name) tensors = [labeled_tensors[0].tensor] concat_axis_list = [axes_0[axis_name]] for labeled_tensor in labeled_tensors[1:]: current_shared_axes = labeled_tensor.axes.remove(axis_name) if current_shared_axes != shared_axes: # TODO(shoyer): add more specific checks about what went wrong, # including raising AxisOrderError when appropriate raise ValueError('Mismatched shared axes: the first tensor ' 'had axes %r but this tensor has axes %r.' % (shared_axes, current_shared_axes)) # Accumulate the axis labels, if they're available. concat_axis_list.append(labeled_tensor.axes[axis_name]) tensors.append(labeled_tensor.tensor) concat_axis = core.concat_axes(concat_axis_list) concat_dimension = axis_names.index(axis_name) concat_tensor = array_ops.concat(tensors, concat_dimension, name=scope) values = list(axes_0.values()) concat_axes = (values[:concat_dimension] + [concat_axis] + values[concat_dimension + 1:]) return core.LabeledTensor(concat_tensor, concat_axes) # TODO(shoyer): rename pack/unpack to stack/unstack @tc.returns(core.LabeledTensor) @tc.accepts( tc.Collection(core.LabeledTensorLike), tc.Union(string_types, core.AxisLike), int, tc.Optional(string_types)) def pack(labeled_tensors, new_axis, axis_position=0, name=None): """Pack tensors along a new axis. See tf.pack. Args: labeled_tensors: The input tensors, which must have identical axes. new_axis: The name of the new axis, or a tuple containing the name and coordinate labels. axis_position: Optional integer position at which to insert the new axis. name: Optional op name. Returns: The packed tensors as a single LabeledTensor, with `new_axis` in the given `axis_position`. Raises: ValueError: If fewer than one input tensors is provided, or if the tensors don't have identical axes. """ with ops.name_scope(name, 'lt_pack', labeled_tensors) as scope: labeled_tensors = [ core.convert_to_labeled_tensor(lt) for lt in labeled_tensors ] if len(labeled_tensors) < 1: raise ValueError('pack expects at least 1 tensors, but received %s' % labeled_tensors) axes_0 = labeled_tensors[0].axes for t in labeled_tensors: if t.axes != axes_0: raise ValueError('Non-identical axes. Expected %s but got %s' % (axes_0, t.axes)) pack_op = array_ops.stack( [t.tensor for t in labeled_tensors], axis=axis_position, name=scope) axes = list(axes_0.values()) axes.insert(axis_position, new_axis) return core.LabeledTensor(pack_op, axes) @tc.returns(tc.List(core.LabeledTensor)) @tc.accepts(core.LabeledTensorLike, tc.Optional(string_types), tc.Optional(string_types)) def unpack(labeled_tensor, axis_name=None, name=None): """Unpack the tensor. See tf.unpack. Args: labeled_tensor: The input tensor. axis_name: Optional name of axis to unpack. By default, the first axis is used. name: Optional op name. Returns: The list of unpacked LabeledTensors. Raises: ValueError: If `axis_name` is not an axis on the input. """ with ops.name_scope(name, 'lt_unpack', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) axis_names = list(labeled_tensor.axes.keys()) if axis_name is None: axis_name = axis_names[0] if axis_name not in axis_names: raise ValueError('%s not in %s' % (axis_name, axis_names)) axis = axis_names.index(axis_name) unpack_ops = array_ops.unstack(labeled_tensor.tensor, axis=axis, name=scope) axes = [a for i, a in enumerate(labeled_tensor.axes.values()) if i != axis] return [core.LabeledTensor(t, axes) for t in unpack_ops] @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Collection(string_types), tc.Collection(tc.Union(string_types, core.AxisLike)), tc.Optional(string_types)) def reshape(labeled_tensor, existing_axes, new_axes, name=None): """Reshape specific axes of a LabeledTensor. Non-indicated axes remain in their original locations. Args: labeled_tensor: The input tensor. existing_axes: List of axis names found on the input tensor. These must appear sequentially in the list of axis names on the input. In other words, they must be a valid slice of `list(labeled_tensor.axes.keys())`. new_axes: List of strings, tuples of (axis_name, axis_value) or Axis objects providing new axes with which to replace `existing_axes` in the reshaped result. At most one element of `new_axes` may be a string, indicating an axis with unknown size. name: Optional op name. Returns: The reshaped LabeledTensor. Raises: ValueError: If `existing_axes` are not all axes on the input, or if more than one of `new_axes` has unknown size. AxisOrderError: If `existing_axes` are not a slice of axis names on the input. """ with ops.name_scope(name, 'lt_reshape', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) original_axis_names = list(labeled_tensor.axes.keys()) existing_axes = list(existing_axes) if not set(existing_axes) <= set(original_axis_names): raise ValueError('existing_axes %r are not contained in the set of axis ' 'names %r on the input labeled tensor' % (existing_axes, original_axis_names)) start = original_axis_names.index(existing_axes[0]) stop = original_axis_names.index(existing_axes[-1]) + 1 if existing_axes != original_axis_names[start:stop]: # We could support existing_axes that aren't a slice by using transpose, # but that could lead to unpredictable performance consequences because # transposes are not free in TensorFlow. If we did transpose # automatically, the user might never realize that their data is being # produced with the wrong order. (The later will occur with some frequency # because of how broadcasting automatically choose axis order.) # So for now we've taken the strict approach. raise core.AxisOrderError( 'existing_axes %r are not a slice of axis names %r on the input ' 'labeled tensor. Use `transpose` or `impose_axis_order` to reorder ' 'axes on the input explicitly.' % (existing_axes, original_axis_names)) if sum(isinstance(axis, string_types) for axis in new_axes) > 1: raise ValueError( 'at most one axis in new_axes can have unknown size. All other ' 'axes must have an indicated integer size or labels: %r' % new_axes) original_values = list(labeled_tensor.axes.values()) axis_size = lambda axis: -1 if axis.size is None else axis.size shape = [axis_size(axis) for axis in original_values[:start]] for axis_ref in new_axes: if isinstance(axis_ref, string_types): shape.append(-1) else: axis = core.as_axis(axis_ref) shape.append(axis_size(axis)) shape.extend(axis_size(axis) for axis in original_values[stop:]) reshaped_tensor = array_ops.reshape( labeled_tensor.tensor, shape, name=scope) axes = original_values[:start] + list(new_axes) + original_values[stop:] return core.LabeledTensor(reshaped_tensor, axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, string_types, string_types, tc.Optional(string_types)) def rename_axis(labeled_tensor, existing_name, new_name, name=None): """Rename an axis of LabeledTensor. Args: labeled_tensor: The input tensor. existing_name: Name for an existing axis on the input. new_name: Desired replacement name. name: Optional op name. Returns: LabeledTensor with renamed axis. Raises: ValueError: If `existing_name` is not an axis on the input. """ with ops.name_scope(name, 'lt_rename_axis', [labeled_tensor]) as scope: if existing_name not in labeled_tensor.axes: raise ValueError('existing_name %r are not contained in the set of axis ' 'names %r on the input labeled tensor' % (existing_name, labeled_tensor.axes.keys())) new_axis = core.Axis(new_name, labeled_tensor.axes[existing_name].value) return reshape(labeled_tensor, [existing_name], [new_axis], name=scope) @tc.returns(tc.List(core.LabeledTensor)) @tc.accepts(string_types, collections.Callable, int, bool, tc.Collection(core.LabeledTensorLike), bool, tc.Optional(string_types)) def _batch_helper(default_name, batch_fn, batch_size, enqueue_many, labeled_tensors, allow_smaller_final_batch, name=None): with ops.name_scope(name, default_name, labeled_tensors) as scope: labeled_tensors = [ core.convert_to_labeled_tensor(lt) for lt in labeled_tensors ] batch_ops = batch_fn([t.tensor for t in labeled_tensors], scope) # TODO(shoyer): Remove this when they sanitize the TF API. if not isinstance(batch_ops, list): assert isinstance(batch_ops, ops.Tensor) batch_ops = [batch_ops] if allow_smaller_final_batch: batch_size = None @tc.returns(core.Axes) @tc.accepts(core.Axes) def output_axes(axes): if enqueue_many: if 'batch' not in axes or list(axes.keys()).index('batch') != 0: raise ValueError( 'When enqueue_many is True, input tensors must have an axis ' 'called "batch" as their first dimension, ' 'but axes were %s' % axes) culled_axes = axes.remove('batch') return core.Axes([('batch', batch_size)] + list(culled_axes.values())) else: return core.Axes([('batch', batch_size)] + list(axes.values())) output_labeled_tensors = [] for i, tensor in enumerate(batch_ops): axes = output_axes(labeled_tensors[i].axes) output_labeled_tensors.append(core.LabeledTensor(tensor, axes)) return output_labeled_tensors @tc.returns(tc.List(core.LabeledTensor)) @tc.accepts( tc.Collection(core.LabeledTensorLike), int, int, int, bool, bool, tc.Optional(string_types)) def batch(labeled_tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, allow_smaller_final_batch=False, name=None): """Rebatch a tensor. See tf.batch. Args: labeled_tensors: The input tensors. batch_size: The output batch size. num_threads: See tf.batch. capacity: See tf.batch. enqueue_many: If true, the input tensors must contain a 'batch' axis as their first axis. If false, the input tensors must not contain a 'batch' axis. See tf.batch. allow_smaller_final_batch: See tf.batch. name: Optional op name. Returns: The rebatched tensors. If enqueue_many is false, the output tensors will have a new 'batch' axis as their first axis. Raises: ValueError: If enqueue_many is True and the first axis of the tensors isn't "batch". """ def fn(tensors, scope): return input.batch( tensors, batch_size=batch_size, num_threads=num_threads, capacity=capacity, enqueue_many=enqueue_many, allow_smaller_final_batch=allow_smaller_final_batch, name=scope) return _batch_helper('lt_batch', fn, batch_size, enqueue_many, labeled_tensors, allow_smaller_final_batch, name) @tc.returns(tc.List(core.LabeledTensor)) @tc.accepts( tc.Collection(core.LabeledTensorLike), int, int, int, bool, int, tc.Optional(int), bool, tc.Optional(string_types)) def shuffle_batch(labeled_tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, min_after_dequeue=0, seed=None, allow_smaller_final_batch=False, name=None): """Rebatch a tensor, with shuffling. See tf.batch. Args: labeled_tensors: The input tensors. batch_size: The output batch size. num_threads: See tf.batch. capacity: See tf.batch. enqueue_many: If true, the input tensors must contain a 'batch' axis as their first axis. If false, the input tensors must not contain a 'batch' axis. See tf.batch. min_after_dequeue: Minimum number of elements in the queue after a dequeue, used to ensure mixing. seed: Optional random seed. allow_smaller_final_batch: See tf.batch. name: Optional op name. Returns: The rebatched tensors. If enqueue_many is false, the output tensors will have a new 'batch' axis as their first axis. Raises: ValueError: If enqueue_many is True and the first axis of the tensors isn't "batch". """ def fn(tensors, scope): return input.shuffle_batch( tensors, batch_size=batch_size, num_threads=num_threads, capacity=capacity, enqueue_many=enqueue_many, min_after_dequeue=min_after_dequeue, seed=seed, allow_smaller_final_batch=allow_smaller_final_batch, name=scope) return _batch_helper('lt_shuffle_batch', fn, batch_size, enqueue_many, labeled_tensors, allow_smaller_final_batch, name) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Mapping(string_types, int), tc.Optional(int), tc.Optional(string_types)) def random_crop(labeled_tensor, shape_map, seed=None, name=None): """Randomly crops a tensor to a given size. See tf.random_crop. Args: labeled_tensor: The input tensor. shape_map: A dictionary mapping axis names to the size of the random crop for that dimension. seed: An optional random seed. name: An optional op name. Returns: A tensor of the same rank as `labeled_tensor`, cropped randomly in the selected dimensions. Raises: ValueError: If the shape map contains an axis name not in the input tensor. """ with ops.name_scope(name, 'lt_random_crop', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) for axis_name in shape_map: if axis_name not in labeled_tensor.axes: raise ValueError('Selection axis %s not in axes %s' % (axis_name, labeled_tensor.axes)) shape = [] axes = [] for axis in labeled_tensor.axes.values(): if axis.name in shape_map: size = shape_map[axis.name] shape.append(size) # We lose labels for the axes we crop, leaving just the size. axes.append((axis.name, size)) else: shape.append(len(axis)) axes.append(axis) crop_op = random_ops.random_crop( labeled_tensor.tensor, shape, seed=seed, name=scope) return core.LabeledTensor(crop_op, axes) # TODO(shoyer): Allow the user to select the axis over which to map. @tc.returns(core.LabeledTensor) @tc.accepts(collections.Callable, core.LabeledTensorLike, tc.Optional(string_types)) def map_fn(fn, labeled_tensor, name=None): """Map on the list of tensors unpacked from labeled_tensor. See tf.map_fn. Args: fn: The function to apply to each unpacked LabeledTensor. It should have type LabeledTensor -> LabeledTensor. labeled_tensor: The input tensor. name: Optional op name. Returns: A tensor that packs the results of applying fn to the list of tensors unpacked from labeled_tensor. """ with ops.name_scope(name, 'lt_map_fn', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) unpack_lts = unpack(labeled_tensor) # TODO(ericmc): Fix this upstream. if labeled_tensor.dtype == dtypes.string: # We must construct the full graph here, because map_fn_lib.map_fn # doesn't work for string-valued tensors. # Constructing the full graph may be slow. map_lts = [fn(t) for t in unpack_lts] return pack(map_lts, list(labeled_tensor.axes.values())[0], name=scope) else: # Figure out what the axis labels should be, but use tf.map_fn to # construct the graph because it's efficient. # It may be slow to construct the full graph, so we infer the labels from # the first element. # TODO(ericmc): This builds a subgraph which then gets thrown away. # Find a more elegant solution. first_map_lt = fn(unpack_lts[0]) final_axes = list(labeled_tensor.axes.values())[:1] + list( first_map_lt.axes.values()) @tc.returns(ops.Tensor) @tc.accepts(ops.Tensor) def tf_fn(tensor): original_axes = list(labeled_tensor.axes.values())[1:] tensor_lt = core.LabeledTensor(tensor, original_axes) return fn(tensor_lt).tensor map_op = map_fn_lib.map_fn( tf_fn, labeled_tensor.tensor, dtype=first_map_lt.dtype) map_lt = core.LabeledTensor(map_op, final_axes) return core.identity(map_lt, name=scope) @tc.returns(core.LabeledTensor) @tc.accepts(collections.Callable, core.LabeledTensorLike, core.LabeledTensorLike, tc.Optional(string_types)) def foldl(fn, labeled_tensor, initial_value, name=None): """Left fold on the list of tensors unpacked from labeled_tensor. See tf.foldl. Args: fn: The function to apply to each unpacked LabeledTensor. It should have type (LabeledTensor, LabeledTensor) -> LabeledTensor. Its arguments are (accumulated_value, next_value). labeled_tensor: The input tensor. initial_value: The initial value of the accumulator. name: Optional op name. Returns: The accumulated value. """ with ops.name_scope(name, 'lt_foldl', [labeled_tensor, initial_value]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) initial_value = core.convert_to_labeled_tensor(initial_value) @tc.returns(ops.Tensor) @tc.accepts(ops.Tensor, ops.Tensor) def tf_fn(accumulator, next_element): accumulator_lt = core.LabeledTensor(accumulator, initial_value.axes) next_element_lt = core.LabeledTensor( next_element, list(labeled_tensor.axes.values())[1:]) return fn(accumulator_lt, next_element_lt).tensor foldl_op = functional_ops.foldl( tf_fn, labeled_tensor.tensor, initializer=initial_value.tensor) foldl_lt = core.LabeledTensor(foldl_op, initial_value.axes) return core.identity(foldl_lt, name=scope) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Optional(tc.Collection(string_types)), tc.Optional(string_types)) def squeeze(labeled_tensor, axis_names=None, name=None): """Remove size-1 dimensions. See tf.squeeze. Args: labeled_tensor: The input tensor. axis_names: The names of the dimensions to remove, or None to remove all size-1 dimensions. name: Optional op name. Returns: A tensor with the specified dimensions removed. Raises: ValueError: If the named axes are not in the tensor, or if they are not size-1. """ with ops.name_scope(name, 'lt_squeeze', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) if axis_names is None: axis_names = [a.name for a in labeled_tensor.axes.values() if len(a) == 1] for axis_name in axis_names: if axis_name not in labeled_tensor.axes: raise ValueError('axis %s is not in tensor axes %s' % (axis_name, labeled_tensor.axes)) elif len(labeled_tensor.axes[axis_name]) != 1: raise ValueError( 'cannot squeeze axis with size greater than 1: (%s, %s)' % (axis_name, labeled_tensor.axes[axis_name])) squeeze_dimensions = [] axes = [] for i, axis in enumerate(labeled_tensor.axes.values()): if axis.name in axis_names: squeeze_dimensions.append(i) else: axes.append(axis) if squeeze_dimensions: squeeze_op = array_ops.squeeze( labeled_tensor.tensor, squeeze_dimensions, name=scope) else: squeeze_op = array_ops.identity(labeled_tensor.tensor, name=scope) return core.LabeledTensor(squeeze_op, axes) # pylint: disable=invalid-name ReduceAxis = tc.Union(string_types, tc.Tuple(string_types, collections.Hashable)) ReduceAxes = tc.Optional(tc.Union(ReduceAxis, tc.Collection(ReduceAxis))) # pylint: enable=invalid-name @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, core.LabeledTensorLike, tc.Optional(string_types)) def matmul(a, b, name=None): """Matrix multiply two tensors with rank 1 or 2. If both tensors have rank 2, a matrix-matrix product is performed. If one tensor has rank 1 and the other has rank 2, then a matrix-vector product is performed. If both tensors have rank 1, then a vector dot-product is performed. (This behavior matches that of `numpy.dot`.) Both tensors must share exactly one dimension in common, which is the dimension the operation is summed along. The inputs will be automatically transposed if necessary as part of the matmul op. We intend to eventually support `matmul` on higher rank input, and also eventually support summing over any number shared dimensions (via an `axis` argument), but neither of these features has been implemented yet. Args: a: First LabeledTensor. b: Second LabeledTensor. name: Optional op name. Returns: LabeledTensor with the result of matrix multiplication. Axes are ordered by the current axis_order_scope, if set, or in or order of appearance on the inputs. Raises: NotImplementedError: If inputs have rank >2 or share multiple axes. ValueError: If the inputs have rank 0 or do not share any axes. """ with ops.name_scope(name, 'lt_matmul', [a, b]) as scope: a = core.convert_to_labeled_tensor(a) b = core.convert_to_labeled_tensor(b) if len(a.axes) > 2 or len(b.axes) > 2: # We could pass batched inputs to tf.matmul to make this work, but we # would also need to use tf.tile and/or tf.transpose. These are more # expensive than doing reshapes, so it's not clear if it's a good idea to # do this automatically. raise NotImplementedError( 'matmul currently requires inputs with rank 2 or less, but ' 'inputs have ranks %r and %r' % (len(a.axes), len(b.axes))) if not a.axes or not b.axes: raise ValueError( 'matmul currently requires inputs with at least rank 1, but ' 'inputs have ranks %r and %r' % (len(a.axes), len(b.axes))) shared_axes = set(a.axes) & set(b.axes) if len(shared_axes) > 1: raise NotImplementedError( 'matmul does not yet support summing over multiple shared axes: %r. ' 'Use transpose and reshape to create a single shared axis to sum ' 'over.' % shared_axes) if not shared_axes: raise ValueError('there must have exactly one axis in common between ' 'input to matmul: %r, %r' % (a.axes.keys(), b.axes.keys())) shared_axis, = shared_axes if a.axes[shared_axis] != b.axes[shared_axis]: raise ValueError('axis %r does not match on input arguments: %r vs %r' % (shared_axis, a.axes[shared_axis].value, b.axes[shared_axis].value)) result_axes = [] for axes in [a.axes, b.axes]: for axis in axes.values(): if axis.name != shared_axis: result_axes.append(axis) axis_scope_order = core.get_axis_order() if axis_scope_order is not None: result_axis_names = [axis.name for axis in result_axes] new_axis_names = [ name for name in axis_scope_order if name in result_axis_names ] if new_axis_names != result_axis_names: # switch a and b b, a = a, b # result_axes is a list of length 1 or 2 result_axes = result_axes[::-1] squeeze_dims = [] if len(a.axes) == 1: a_tensor = array_ops.reshape(a.tensor, (1, -1)) squeeze_dims.append(0) transpose_a = False else: a_tensor = a.tensor transpose_a = list(a.axes.keys()).index(shared_axis) == 0 if len(b.axes) == 1: b_tensor = array_ops.reshape(b.tensor, (-1, 1)) squeeze_dims.append(1) transpose_b = False else: b_tensor = b.tensor transpose_b = list(b.axes.keys()).index(shared_axis) == 1 result_op = math_ops.matmul( a_tensor, b_tensor, transpose_a=transpose_a, transpose_b=transpose_b) if squeeze_dims: result_op = array_ops.squeeze(result_op, squeeze_dims) result_op = array_ops.identity(result_op, name=scope) return core.LabeledTensor(result_op, result_axes) @tc.returns(types.FunctionType) @tc.accepts(string_types, collections.Callable) def define_reduce_op(op_name, reduce_fn): """Define a reduction op for labeled tensors. Args: op_name: string name of the TensorFlow op. reduce_fn: function to call to evaluate the op on a tf.Tensor. Returns: Function defining the given reduction op that acts on a LabeledTensor. """ default_name = 'lt_%s' % op_name @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, ReduceAxes, tc.Optional(string_types)) def op(labeled_tensor, axes=None, name=None): """Computes the given reduction across the given axes of a LabeledTensor. See `tf.{op_name}` for full details. Args: labeled_tensor: The input tensor. axes: A set of axes or None. If None, all axes will be reduced. Axes must all be strings, in which case those dimensions will be removed, or pairs of (name, None) or (name, label), in which case those dimensions will be kept. name: Optional op name. Returns: The reduced LabeledTensor. Raises: ValueError: if any of the axes to reduce over are not found on `labeled_tensor`. """ with ops.name_scope(name, default_name, [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) if axes is None: axes = labeled_tensor.axes.keys() if isinstance(axes, (string_types, tuple)): axes = [axes] reduction_axes = {} axes_to_squeeze = [] for a in axes: if isinstance(a, string_types): # We squeeze out this axis. reduction_axes[a] = a axes_to_squeeze.append(a) else: # We keep this axis, with the user-provided labels. (axis_name, label) = a if label is not None: # The input was a single label, so make it a list so it can be # turned into an Axis. label = [label] reduction_axes[axis_name] = (axis_name, label) for axis_name in reduction_axes: if axis_name not in labeled_tensor.axes: raise ValueError('Axis %s not in axes %s' % (axis_name, labeled_tensor.axes)) intermediate_axes = [] reduction_dimensions = [] for i, axis in enumerate(labeled_tensor.axes.values()): if axis.name in reduction_axes: intermediate_axes.append(reduction_axes[axis.name]) reduction_dimensions.append(i) else: intermediate_axes.append(axis) reduce_op = reduce_fn( labeled_tensor.tensor, reduction_dimensions, keepdims=True) reduce_lt = core.LabeledTensor(reduce_op, intermediate_axes) return squeeze(reduce_lt, axes_to_squeeze, name=scope) op.__doc__ = op.__doc__.format(op_name=op_name) op.__name__ = op_name return op reduce_all = define_reduce_op('reduce_all', math_ops.reduce_all) reduce_any = define_reduce_op('reduce_any', math_ops.reduce_any) reduce_logsumexp = define_reduce_op('reduce_logsumexp', math_ops.reduce_logsumexp) reduce_max = define_reduce_op('reduce_max', math_ops.reduce_max) reduce_mean = define_reduce_op('reduce_mean', math_ops.reduce_mean) reduce_min = define_reduce_op('reduce_min', math_ops.reduce_min) reduce_prod = define_reduce_op('reduce_prod', math_ops.reduce_prod) reduce_sum = define_reduce_op('reduce_sum', math_ops.reduce_sum) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Mapping(str, tc.Union(int, ops.Tensor)), tc.Optional(string_types)) def tile(labeled_tensor, multiples, name=None): """Constructs a tensor by tiling a given tensor. Only axes without tick-labels can be tiled. (Otherwise, axis labels on tiled tensors would no longer be unique.) See lt.tile. Args: labeled_tensor: The input tensor. multiples: A mapping where the keys are axis names and the values are the integer number of times to tile along that axis. Only axes with a multiple different than 1 need be included. name: Optional op name. Returns: A tensor with the indicated axes tiled. Raises: ValueError: If the tiled axes are not axes in the input tensor, or if any axes in multiples have tick labels. """ with ops.name_scope(name, 'lt_tile', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) if not set(multiples.keys()) <= set(labeled_tensor.axes.keys()): raise ValueError('tile axes %r are not contained in the set of axis ' 'names %r on the input labeled tensor' % (multiples.keys(), labeled_tensor.axes)) labeled_axes = [ name for name in multiples if labeled_tensor.axes[name].labels is not None ] if labeled_axes: raise ValueError('cannot tile axes with tick labels: %r' % labeled_axes) multiples_list = [multiples.get(name, 1) for name in labeled_tensor.axes] tile_op = array_ops.tile(labeled_tensor.tensor, multiples_list, name=scope) new_axes = [ axis.name if axis.labels is None else axis for axis in labeled_tensor.axes.values() ] return core.LabeledTensor(tile_op, new_axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Mapping(str, tc.Tuple(core.AxisValue, core.AxisValue)), string_types, tc.Optional(string_types)) def pad(labeled_tensor, paddings, mode='CONSTANT', name=None): """Pads a tensor. See tf.pad. Args: labeled_tensor: The input tensor. paddings: A mapping where the keys are axis names and the values are tuples where the first element is the padding to insert at the beginning of the axis and the second is the padding to insert at the end of the axis. mode: One of "CONSTANT", "REFLECT", or "SYMMETRIC". name: Optional op name. Returns: A tensor with the indicated axes padded, optionally with those axes extended with the provided labels. Raises: ValueError: If the padded axes are not axes in the input tensor. """ with ops.name_scope(name, 'lt_pad', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) if not set(paddings.keys()) <= set(labeled_tensor.axes.keys()): raise ValueError('pad axes %r are not contained in the set of axis ' 'names %r on the input labeled tensor' % (paddings.keys(), labeled_tensor.axes)) new_axes = [] padding_pairs = [] for name, axis in labeled_tensor.axes.items(): if name in paddings: padding_before, padding_after = paddings[name] axis_before = core.Axis(name, padding_before) axis_after = core.Axis(name, padding_after) new_axes.append(core.concat_axes([axis_before, axis, axis_after])) padding_pairs.append((len(axis_before), len(axis_after))) else: new_axes.append(axis) padding_pairs.append((0, 0)) pad_op = array_ops.pad(labeled_tensor.tensor, padding_pairs, mode, name=scope) return core.LabeledTensor(pad_op, new_axes) @tc.returns(core.LabeledTensor) @tc.accepts( tc.Union(np.ndarray, list, tuple, core.Scalar), tc.Optional(dtypes.DType), tc.Optional( tc.Union(core.Axes, tc.Collection( tc.Union(string_types, core.AxisLike)))), tc.Optional(string_types)) def constant(value, dtype=None, axes=None, name=None): """Creates a constant tensor. If `axes` includes any strings, shape is inferred from `value`. Otherwise, the sizes of the given `axes` are used to set `shape` for `tf.constant`. See tf.constant for more details. Args: value: The input tensor. dtype: The type of the returned tensor. axes: Optional Axes, list of strings or list of objects coercible to Axis objects. By default, axes are assumed to be an empty list (i.e., `value` is treated as a scalar). name: Optional op name. Returns: The tensor with elements set to zero. """ with ops.name_scope(name, 'lt_constant', [value]) as scope: if axes is None: axes = [] if isinstance(axes, core.Axes): axes = axes.values() if any(isinstance(ax, string_types) for ax in axes): # need to infer shape shape = None else: # axes already indicate shape axes = [core.as_axis(a) for a in axes] shape = [a.size for a in axes] op = array_ops.constant(value, dtype=dtype, shape=shape, name=scope) return core.LabeledTensor(op, axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Optional(dtypes.DType), tc.Optional(string_types)) def zeros_like(labeled_tensor, dtype=None, name=None): """Creates an identical tensor with all elements set to zero. Args: labeled_tensor: The input tensor. dtype: The type of the returned tensor. name: Optional op name. Returns: The tensor with elements set to zero. """ with ops.name_scope(name, 'lt_zeros_like', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) op = array_ops.zeros_like(labeled_tensor.tensor, dtype=dtype, name=scope) return core.LabeledTensor(op, labeled_tensor.axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Optional(dtypes.DType), tc.Optional(string_types)) def ones_like(labeled_tensor, dtype=None, name=None): """Creates an identical tensor with all elements set to one. Args: labeled_tensor: The input tensor. dtype: The type of the returned tensor. name: Optional op name. Returns: The tensor with elements set to one. """ with ops.name_scope(name, 'lt_ones_like', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) op = array_ops.ones_like(labeled_tensor.tensor, dtype=dtype, name=scope) return core.LabeledTensor(op, labeled_tensor.axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Optional(dtypes.DType), tc.Optional(string_types)) def cast(labeled_tensor, dtype=None, name=None): """Casts a labeled tensor to a new type. Args: labeled_tensor: The input tensor. dtype: The type of the returned tensor. name: Optional op name. Returns: A labeled tensor with the new dtype. """ with ops.name_scope(name, 'lt_cast', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) op = math_ops.cast(labeled_tensor.tensor, dtype=dtype, name=scope) return core.LabeledTensor(op, labeled_tensor.axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, string_types, tc.Optional(string_types)) def verify_tensor_all_finite(labeled_tensor, message, name=None): """Asserts a tensor doesn't contain NaNs or Infs. See tf.verify_tensor_all_finite. Args: labeled_tensor: The input tensor. message: Message to log on failure. name: Optional op name. Returns: The input tensor. """ with ops.name_scope(name, 'lt_verify_tensor_all_finite', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) op = numerics.verify_tensor_all_finite( labeled_tensor.tensor, msg=message, name=scope) return core.LabeledTensor(op, labeled_tensor.axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, core.LabeledTensorLike, tc.Optional(string_types)) def boolean_mask(labeled_tensor, mask, name=None): """Apply a boolean mask to a labeled tensor. Unlike `tf.boolean_mask`, this currently only works on 1-dimensional masks. The mask is applied to the first axis of `labeled_tensor`. Labels on the first axis are removed, because True indices in `mask` may not be known dynamically. Args: labeled_tensor: The input tensor. mask: The type of the returned tensor. name: Optional op name. Returns: The masked labeled tensor. Raises: ValueError: if the first axis of the mask """ with ops.name_scope(name, 'lt_boolean_mask', [labeled_tensor, mask]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) mask = core.convert_to_labeled_tensor(mask) if len(mask.axes) > 1: raise NotImplementedError( "LabeledTensor's boolean_mask currently only supports 1D masks") mask_axis = list(mask.axes.values())[0] lt_axis = list(labeled_tensor.axes.values())[0] if mask_axis != lt_axis: raise ValueError('the first axis of the labeled tensor and the mask ' 'are not equal:\n%r\n%r' % (lt_axis, mask_axis)) op = array_ops.boolean_mask(labeled_tensor.tensor, mask.tensor, name=scope) # TODO(shoyer): attempt to infer labels for the masked values, by calling # tf.contrib.util.constant_value on the mask? axes = [lt_axis.name] + list(labeled_tensor.axes.values())[1:] return core.LabeledTensor(op, axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, core.LabeledTensorLike, core.LabeledTensorLike, tc.Optional(string_types)) def where(condition, x, y, name=None): """Return elements from x or y depending on condition. See `tf.where` for more details. This function currently only implements the three argument version of where. Args: condition: LabeledTensor of type `bool`. x: LabeledTensor for values where condition is true. y: LabeledTensor for values where condition is false. name: Optional op name. Returns: The labeled tensor with values according to condition. Raises: ValueError: if `x` and `y` have different axes, or if the axes of `x` do not start with the axes of `condition`. """ with ops.name_scope(name, 'lt_where', [condition, x, y]) as scope: condition = core.convert_to_labeled_tensor(condition) x = core.convert_to_labeled_tensor(x) y = core.convert_to_labeled_tensor(y) if not condition.axes == x.axes == y.axes: raise ValueError('all inputs to `where` must have equal axes') op = array_ops.where(condition.tensor, x.tensor, y.tensor, name=scope) return core.LabeledTensor(op, x.axes)
apache-2.0
arhik/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/blocking_input.py
69
12119
""" This provides several classes used for blocking interaction with figure windows: :class:`BlockingInput` creates a callable object to retrieve events in a blocking way for interactive sessions :class:`BlockingKeyMouseInput` creates a callable object to retrieve key or mouse clicks in a blocking way for interactive sessions. Note: Subclass of BlockingInput. Used by waitforbuttonpress :class:`BlockingMouseInput` creates a callable object to retrieve mouse clicks in a blocking way for interactive sessions. Note: Subclass of BlockingInput. Used by ginput :class:`BlockingContourLabeler` creates a callable object to retrieve mouse clicks in a blocking way that will then be used to place labels on a ContourSet Note: Subclass of BlockingMouseInput. Used by clabel """ import time import numpy as np from matplotlib import path, verbose from matplotlib.cbook import is_sequence_of_strings class BlockingInput(object): """ Class that creates a callable object to retrieve events in a blocking way. """ def __init__(self, fig, eventslist=()): self.fig = fig assert is_sequence_of_strings(eventslist), "Requires a sequence of event name strings" self.eventslist = eventslist def on_event(self, event): """ Event handler that will be passed to the current figure to retrieve events. """ # Add a new event to list - using a separate function is # overkill for the base class, but this is consistent with # subclasses self.add_event(event) verbose.report("Event %i" % len(self.events)) # This will extract info from events self.post_event() # Check if we have enough events already if len(self.events) >= self.n and self.n > 0: self.fig.canvas.stop_event_loop() def post_event(self): """For baseclass, do nothing but collect events""" pass def cleanup(self): """Disconnect all callbacks""" for cb in self.callbacks: self.fig.canvas.mpl_disconnect(cb) self.callbacks=[] def add_event(self,event): """For base class, this just appends an event to events.""" self.events.append(event) def pop_event(self,index=-1): """ This removes an event from the event list. Defaults to removing last event, but an index can be supplied. Note that this does not check that there are events, much like the normal pop method. If not events exist, this will throw an exception. """ self.events.pop(index) def pop(self,index=-1): self.pop_event(index) pop.__doc__=pop_event.__doc__ def __call__(self, n=1, timeout=30 ): """ Blocking call to retrieve n events """ assert isinstance(n, int), "Requires an integer argument" self.n = n self.events = [] self.callbacks = [] # Ensure that the figure is shown self.fig.show() # connect the events to the on_event function call for n in self.eventslist: self.callbacks.append( self.fig.canvas.mpl_connect(n, self.on_event) ) try: # Start event loop self.fig.canvas.start_event_loop(timeout=timeout) finally: # Run even on exception like ctrl-c # Disconnect the callbacks self.cleanup() # Return the events in this case return self.events class BlockingMouseInput(BlockingInput): """ Class that creates a callable object to retrieve mouse clicks in a blocking way. This class will also retrieve keyboard clicks and treat them like appropriate mouse clicks (delete and backspace are like mouse button 3, enter is like mouse button 2 and all others are like mouse button 1). """ def __init__(self, fig): BlockingInput.__init__(self, fig=fig, eventslist=('button_press_event', 'key_press_event') ) def post_event(self): """ This will be called to process events """ assert len(self.events)>0, "No events yet" if self.events[-1].name == 'key_press_event': self.key_event() else: self.mouse_event() def mouse_event(self): '''Process a mouse click event''' event = self.events[-1] button = event.button if button == 3: self.button3(event) elif button == 2: self.button2(event) else: self.button1(event) def key_event(self): ''' Process a key click event. This maps certain keys to appropriate mouse click events. ''' event = self.events[-1] key = event.key if key == 'backspace' or key == 'delete': self.button3(event) elif key == 'enter': self.button2(event) else: self.button1(event) def button1( self, event ): """ Will be called for any event involving a button other than button 2 or 3. This will add a click if it is inside axes. """ if event.inaxes: self.add_click(event) else: # If not a valid click, remove from event list BlockingInput.pop(self) def button2( self, event ): """ Will be called for any event involving button 2. Button 2 ends blocking input. """ # Remove last event just for cleanliness BlockingInput.pop(self) # This will exit even if not in infinite mode. This is # consistent with matlab and sometimes quite useful, but will # require the user to test how many points were actually # returned before using data. self.fig.canvas.stop_event_loop() def button3( self, event ): """ Will be called for any event involving button 3. Button 3 removes the last click. """ # Remove this last event BlockingInput.pop(self) # Now remove any existing clicks if possible if len(self.events)>0: self.pop() def add_click(self,event): """ This add the coordinates of an event to the list of clicks """ self.clicks.append((event.xdata,event.ydata)) verbose.report("input %i: %f,%f" % (len(self.clicks),event.xdata, event.ydata)) # If desired plot up click if self.show_clicks: self.marks.extend( event.inaxes.plot([event.xdata,], [event.ydata,], 'r+') ) self.fig.canvas.draw() def pop_click(self,index=-1): """ This removes a click from the list of clicks. Defaults to removing the last click. """ self.clicks.pop(index) if self.show_clicks: mark = self.marks.pop(index) mark.remove() self.fig.canvas.draw() def pop(self,index=-1): """ This removes a click and the associated event from the object. Defaults to removing the last click, but any index can be supplied. """ self.pop_click(index) BlockingInput.pop(self,index) def cleanup(self): # clean the figure if self.show_clicks: for mark in self.marks: mark.remove() self.marks = [] self.fig.canvas.draw() # Call base class to remove callbacks BlockingInput.cleanup(self) def __call__(self, n=1, timeout=30, show_clicks=True): """ Blocking call to retrieve n coordinate pairs through mouse clicks. """ self.show_clicks = show_clicks self.clicks = [] self.marks = [] BlockingInput.__call__(self,n=n,timeout=timeout) return self.clicks class BlockingContourLabeler( BlockingMouseInput ): """ Class that creates a callable object that uses mouse clicks or key clicks on a figure window to place contour labels. """ def __init__(self,cs): self.cs = cs BlockingMouseInput.__init__(self, fig=cs.ax.figure ) def button1(self,event): """ This will be called if an event involving a button other than 2 or 3 occcurs. This will add a label to a contour. """ # Shorthand cs = self.cs if event.inaxes == cs.ax: conmin,segmin,imin,xmin,ymin = cs.find_nearest_contour( event.x, event.y, cs.labelIndiceList)[:5] # Get index of nearest level in subset of levels used for labeling lmin = cs.labelIndiceList.index(conmin) # Coordinates of contour paths = cs.collections[conmin].get_paths() lc = paths[segmin].vertices # In pixel/screen space slc = cs.ax.transData.transform(lc) # Get label width for rotating labels and breaking contours lw = cs.get_label_width(cs.labelLevelList[lmin], cs.labelFmt, cs.labelFontSizeList[lmin]) """ # requires python 2.5 # Figure out label rotation. rotation,nlc = cs.calc_label_rot_and_inline( slc, imin, lw, lc if self.inline else [], self.inline_spacing ) """ # Figure out label rotation. if self.inline: lcarg = lc else: lcarg = None rotation,nlc = cs.calc_label_rot_and_inline( slc, imin, lw, lcarg, self.inline_spacing ) cs.add_label(xmin,ymin,rotation,cs.labelLevelList[lmin], cs.labelCValueList[lmin]) if self.inline: # Remove old, not looping over paths so we can do this up front paths.pop(segmin) # Add paths if not empty or single point for n in nlc: if len(n)>1: paths.append( path.Path(n) ) self.fig.canvas.draw() else: # Remove event if not valid BlockingInput.pop(self) def button3(self,event): """ This will be called if button 3 is clicked. This will remove a label if not in inline mode. Unfortunately, if one is doing inline labels, then there is currently no way to fix the broken contour - once humpty-dumpty is broken, he can't be put back together. In inline mode, this does nothing. """ # Remove this last event - not too important for clabel use # since clabel normally doesn't have a maximum number of # events, but best for cleanliness sake. BlockingInput.pop(self) if self.inline: pass else: self.cs.pop_label() self.cs.ax.figure.canvas.draw() def __call__(self,inline,inline_spacing=5,n=-1,timeout=-1): self.inline=inline self.inline_spacing=inline_spacing BlockingMouseInput.__call__(self,n=n,timeout=timeout, show_clicks=False) class BlockingKeyMouseInput(BlockingInput): """ Class that creates a callable object to retrieve a single mouse or keyboard click """ def __init__(self, fig): BlockingInput.__init__(self, fig=fig, eventslist=('button_press_event','key_press_event') ) def post_event(self): """ Determines if it is a key event """ assert len(self.events)>0, "No events yet" self.keyormouse = self.events[-1].name == 'key_press_event' def __call__(self, timeout=30): """ Blocking call to retrieve a single mouse or key click Returns True if key click, False if mouse, or None if timeout """ self.keyormouse = None BlockingInput.__call__(self,n=1,timeout=timeout) return self.keyormouse
agpl-3.0
bzero/statsmodels
statsmodels/tools/grouputils.py
25
22518
# -*- coding: utf-8 -*- """Tools for working with groups This provides several functions to work with groups and a Group class that keeps track of the different representations and has methods to work more easily with groups. Author: Josef Perktold, Author: Nathaniel Smith, recipe for sparse_dummies on scipy user mailing list Created on Tue Nov 29 15:44:53 2011 : sparse_dummies Created on Wed Nov 30 14:28:24 2011 : combine_indices changes: add Group class Notes ~~~~~ This reverses the class I used before, where the class was for the data and the group was auxiliary. Here, it is only the group, no data is kept. sparse_dummies needs checking for corner cases, e.g. what if a category level has zero elements? This can happen with subset selection even if the original groups where defined as arange. Not all methods and options have been tried out yet after refactoring need more efficient loop if groups are sorted -> see GroupSorted.group_iter """ from __future__ import print_function from statsmodels.compat.python import lrange, lzip, range import numpy as np import pandas as pd from statsmodels.compat.numpy import npc_unique import statsmodels.tools.data as data_util from pandas.core.index import Index, MultiIndex def combine_indices(groups, prefix='', sep='.', return_labels=False): """use np.unique to get integer group indices for product, intersection """ if isinstance(groups, tuple): groups = np.column_stack(groups) else: groups = np.asarray(groups) dt = groups.dtype is2d = (groups.ndim == 2) # need to store if is2d: ncols = groups.shape[1] if not groups.flags.c_contiguous: groups = np.array(groups, order='C') groups_ = groups.view([('', groups.dtype)] * groups.shape[1]) else: groups_ = groups uni, uni_idx, uni_inv = npc_unique(groups_, return_index=True, return_inverse=True) if is2d: uni = uni.view(dt).reshape(-1, ncols) # avoiding a view would be # for t in uni.dtype.fields.values(): # assert (t[0] == dt) # # uni.dtype = dt # uni.shape = (uni.size//ncols, ncols) if return_labels: label = [(prefix+sep.join(['%s']*len(uni[0]))) % tuple(ii) for ii in uni] return uni_inv, uni_idx, uni, label else: return uni_inv, uni_idx, uni # written for and used in try_covariance_grouploop.py def group_sums(x, group, use_bincount=True): """simple bincount version, again group : array, integer assumed to be consecutive integers no dtype checking because I want to raise in that case uses loop over columns of x for comparison, simple python loop """ x = np.asarray(x) if x.ndim == 1: x = x[:, None] elif x.ndim > 2 and use_bincount: raise ValueError('not implemented yet') if use_bincount: # re-label groups or bincount takes too much memory if np.max(group) > 2 * x.shape[0]: group = pd.factorize(group)[0] return np.array([np.bincount(group, weights=x[:, col]) for col in range(x.shape[1])]) else: uniques = np.unique(group) result = np.zeros([len(uniques)] + list(x.shape[1:])) for ii, cat in enumerate(uniques): result[ii] = x[g == cat].sum(0) return result def group_sums_dummy(x, group_dummy): """sum by groups given group dummy variable group_dummy can be either ndarray or sparse matrix """ if data_util._is_using_ndarray_type(group_dummy, None): return np.dot(x.T, group_dummy) else: # check for sparse return x.T * group_dummy def dummy_sparse(groups): """create a sparse indicator from a group array with integer labels Parameters ---------- groups: ndarray, int, 1d (nobs,) an array of group indicators for each observation. Group levels are assumed to be defined as consecutive integers, i.e. range(n_groups) where n_groups is the number of group levels. A group level with no observations for it will still produce a column of zeros. Returns ------- indi : ndarray, int8, 2d (nobs, n_groups) an indicator array with one row per observation, that has 1 in the column of the group level for that observation Examples -------- >>> g = np.array([0, 0, 2, 1, 1, 2, 0]) >>> indi = dummy_sparse(g) >>> indi <7x3 sparse matrix of type '<type 'numpy.int8'>' with 7 stored elements in Compressed Sparse Row format> >>> indi.todense() matrix([[1, 0, 0], [1, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]], dtype=int8) current behavior with missing groups >>> g = np.array([0, 0, 2, 0, 2, 0]) >>> indi = dummy_sparse(g) >>> indi.todense() matrix([[1, 0, 0], [1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 0, 1], [1, 0, 0]], dtype=int8) """ from scipy import sparse indptr = np.arange(len(groups)+1) data = np.ones(len(groups), dtype=np.int8) indi = sparse.csr_matrix((data, g, indptr)) return indi class Group(object): def __init__(self, group, name=''): # self.group = np.asarray(group) # TODO: use checks in combine_indices self.name = name uni, uni_idx, uni_inv = combine_indices(group) # TODO: rename these to something easier to remember self.group_int, self.uni_idx, self.uni = uni, uni_idx, uni_inv self.n_groups = len(self.uni) # put this here so they can be overwritten before calling labels self.separator = '.' self.prefix = self.name if self.prefix: self.prefix = self.prefix + '=' # cache decorator def counts(self): return np.bincount(self.group_int) # cache_decorator def labels(self): # is this only needed for product of groups (intersection)? prefix = self.prefix uni = self.uni sep = self.separator if uni.ndim > 1: label = [(prefix+sep.join(['%s']*len(uni[0]))) % tuple(ii) for ii in uni] else: label = [prefix + '%s' % ii for ii in uni] return label def dummy(self, drop_idx=None, sparse=False, dtype=int): """ drop_idx is only available if sparse=False drop_idx is supposed to index into uni """ uni = self.uni if drop_idx is not None: idx = lrange(len(uni)) del idx[drop_idx] uni = uni[idx] group = self.group if not sparse: return (group[:, None] == uni[None, :]).astype(dtype) else: return dummy_sparse(self.group_int) def interaction(self, other): if isinstance(other, self.__class__): other = other.group return self.__class__((self, other)) def group_sums(self, x, use_bincount=True): return group_sums(x, self.group_int, use_bincount=use_bincount) def group_demean(self, x, use_bincount=True): nobs = float(len(x)) means_g = group_sums(x / nobs, self.group_int, use_bincount=use_bincount) x_demeaned = x - means_g[self.group_int] # check reverse_index? return x_demeaned, means_g class GroupSorted(Group): def __init__(self, group, name=''): super(self.__class__, self).__init__(group, name=name) idx = (np.nonzero(np.diff(group))[0]+1).tolist() self.groupidx = lzip([0] + idx, idx + [len(group)]) def group_iter(self): for low, upp in self.groupidx: yield slice(low, upp) def lag_indices(self, lag): """return the index array for lagged values Warning: if k is larger then the number of observations for an individual, then no values for that individual are returned. TODO: for the unbalanced case, I should get the same truncation for the array with lag=0. From the return of lag_idx we wouldn't know which individual is missing. TODO: do I want the full equivalent of lagmat in tsa? maxlag or lag or lags. not tested yet """ lag_idx = np.asarray(self.groupidx)[:, 1] - lag # asarray or already? mask_ok = (lag <= lag_idx) # still an observation that belongs to the same individual return lag_idx[mask_ok] def _is_hierarchical(x): """ Checks if the first item of an array-like object is also array-like If so, we have a MultiIndex and returns True. Else returns False. """ item = x[0] # is there a better way to do this? if isinstance(item, (list, tuple, np.ndarray, pd.Series, pd.DataFrame)): return True else: return False def _make_hierarchical_index(index, names): return MultiIndex.from_tuples(*[index], names=names) def _make_generic_names(index): n_names = len(index.names) pad = str(len(str(n_names))) # number of digits return [("group{0:0"+pad+"}").format(i) for i in range(n_names)] class Grouping(object): def __init__(self, index, names=None): """ index : index-like Can be pandas MultiIndex or Index or array-like. If array-like and is a MultipleIndex (more than one grouping variable), groups are expected to be in each row. E.g., [('red', 1), ('red', 2), ('green', 1), ('green', 2)] names : list or str, optional The names to use for the groups. Should be a str if only one grouping variable is used. Notes ----- If index is already a pandas Index then there is no copy. """ if isinstance(index, (Index, MultiIndex)): if names is not None: if hasattr(index, 'set_names'): # newer pandas index.set_names(names, inplace=True) else: index.names = names self.index = index else: # array-like if _is_hierarchical(index): self.index = _make_hierarchical_index(index, names) else: self.index = Index(index, name=names) if names is None: names = _make_generic_names(self.index) if hasattr(self.index, 'set_names'): self.index.set_names(names, inplace=True) else: self.index.names = names self.nobs = len(self.index) self.nlevels = len(self.index.names) self.slices = None @property def index_shape(self): if hasattr(self.index, 'levshape'): return self.index.levshape else: return self.index.shape @property def levels(self): if hasattr(self.index, 'levels'): return self.index.levels else: return pd.Categorical(self.index).levels @property def labels(self): # this was index_int, but that's not a very good name... if hasattr(self.index, 'labels'): return self.index.labels else: # pandas version issue here # Compat code for the labels -> codes change in pandas 0.15 # FIXME: use .codes directly when we don't want to support # pandas < 0.15 tmp = pd.Categorical(self.index) try: labl = tmp.codes except AttributeError: labl = tmp.labels # Old pandsd return labl[None] @property def group_names(self): return self.index.names def reindex(self, index=None, names=None): """ Resets the index in-place. """ # NOTE: this isn't of much use if the rest of the data doesn't change # This needs to reset cache if names is None: names = self.group_names self = Grouping(index, names) def get_slices(self, level=0): """ Sets the slices attribute to be a list of indices of the sorted groups for the first index level. I.e., self.slices[0] is the index where each observation is in the first (sorted) group. """ # TODO: refactor this groups = self.index.get_level_values(level).unique() groups.sort() if isinstance(self.index, MultiIndex): self.slices = [self.index.get_loc_level(x, level=level)[0] for x in groups] else: self.slices = [self.index.get_loc(x) for x in groups] def count_categories(self, level=0): """ Sets the attribute counts to equal the bincount of the (integer-valued) labels. """ # TODO: refactor this not to set an attribute. Why would we do this? self.counts = np.bincount(self.labels[level]) def check_index(self, is_sorted=True, unique=True, index=None): """Sanity checks""" if not index: index = self.index if is_sorted: test = pd.DataFrame(lrange(len(index)), index=index) test_sorted = test.sort() if not test.index.equals(test_sorted.index): raise Exception('Data is not be sorted') if unique: if len(index) != len(index.unique()): raise Exception('Duplicate index entries') def sort(self, data, index=None): """Applies a (potentially hierarchical) sort operation on a numpy array or pandas series/dataframe based on the grouping index or a user-supplied index. Returns an object of the same type as the original data as well as the matching (sorted) Pandas index. """ if index is None: index = self.index if data_util._is_using_ndarray_type(data, None): if data.ndim == 1: out = pd.Series(data, index=index, copy=True) out = out.sort_index() else: out = pd.DataFrame(data, index=index) out = out.sort(inplace=False) # copies return np.array(out), out.index elif data_util._is_using_pandas(data, None): out = data out = out.reindex(index) # copies? out = out.sort_index() return out, out.index else: msg = 'data must be a Numpy array or a Pandas Series/DataFrame' raise ValueError(msg) def transform_dataframe(self, dataframe, function, level=0, **kwargs): """Apply function to each column, by group Assumes that the dataframe already has a proper index""" if dataframe.shape[0] != self.nobs: raise Exception('dataframe does not have the same shape as index') out = dataframe.groupby(level=level).apply(function, **kwargs) if 1 in out.shape: return np.ravel(out) else: return np.array(out) def transform_array(self, array, function, level=0, **kwargs): """Apply function to each column, by group """ if array.shape[0] != self.nobs: raise Exception('array does not have the same shape as index') dataframe = pd.DataFrame(array, index=self.index) return self.transform_dataframe(dataframe, function, level=level, **kwargs) def transform_slices(self, array, function, level=0, **kwargs): """Apply function to each group. Similar to transform_array but does not coerce array to a DataFrame and back and only works on a 1D or 2D numpy array. function is called function(group, group_idx, **kwargs). """ array = np.asarray(array) if array.shape[0] != self.nobs: raise Exception('array does not have the same shape as index') # always reset because level is given. need to refactor this. self.get_slices(level=level) processed = [] for s in self.slices: if array.ndim == 2: subset = array[s, :] elif array.ndim == 1: subset = array[s] processed.append(function(subset, s, **kwargs)) processed = np.array(processed) return processed.reshape(-1, processed.shape[-1]) # TODO: this isn't general needs to be a PanelGrouping object def dummies_time(self): self.dummy_sparse(level=1) return self._dummies def dummies_groups(self, level=0): self.dummy_sparse(level=level) return self._dummies def dummy_sparse(self, level=0): """create a sparse indicator from a group array with integer labels Parameters ---------- groups: ndarray, int, 1d (nobs,) an array of group indicators for each observation. Group levels are assumed to be defined as consecutive integers, i.e. range(n_groups) where n_groups is the number of group levels. A group level with no observations for it will still produce a column of zeros. Returns ------- indi : ndarray, int8, 2d (nobs, n_groups) an indicator array with one row per observation, that has 1 in the column of the group level for that observation Examples -------- >>> g = np.array([0, 0, 2, 1, 1, 2, 0]) >>> indi = dummy_sparse(g) >>> indi <7x3 sparse matrix of type '<type 'numpy.int8'>' with 7 stored elements in Compressed Sparse Row format> >>> indi.todense() matrix([[1, 0, 0], [1, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]], dtype=int8) current behavior with missing groups >>> g = np.array([0, 0, 2, 0, 2, 0]) >>> indi = dummy_sparse(g) >>> indi.todense() matrix([[1, 0, 0], [1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 0, 1], [1, 0, 0]], dtype=int8) """ from scipy import sparse groups = self.labels[level] indptr = np.arange(len(groups)+1) data = np.ones(len(groups), dtype=np.int8) self._dummies = sparse.csr_matrix((data, groups, indptr)) if __name__ == '__main__': # ---------- examples combine_indices from numpy.testing import assert_equal np.random.seed(985367) groups = np.random.randint(0, 2, size=(10, 2)) uv, ux, u, label = combine_indices(groups, return_labels=True) uv, ux, u, label = combine_indices(groups, prefix='g1,g2=', sep=',', return_labels=True) group0 = np.array(['sector0', 'sector1'])[groups[:, 0]] group1 = np.array(['region0', 'region1'])[groups[:, 1]] uv, ux, u, label = combine_indices((group0, group1), prefix='sector,region=', sep=',', return_labels=True) uv, ux, u, label = combine_indices((group0, group1), prefix='', sep='.', return_labels=True) group_joint = np.array(label)[uv] group_joint_expected = np.array(['sector1.region0', 'sector0.region1', 'sector0.region0', 'sector0.region1', 'sector1.region1', 'sector0.region0', 'sector1.region0', 'sector1.region0', 'sector0.region1', 'sector0.region0'], dtype='|S15') assert_equal(group_joint, group_joint_expected) """ >>> uv array([2, 1, 0, 0, 1, 0, 2, 0, 1, 0]) >>> label ['sector0.region0', 'sector1.region0', 'sector1.region1'] >>> np.array(label)[uv] array(['sector1.region1', 'sector1.region0', 'sector0.region0', 'sector0.region0', 'sector1.region0', 'sector0.region0', 'sector1.region1', 'sector0.region0', 'sector1.region0', 'sector0.region0'], dtype='|S15') >>> np.column_stack((group0, group1)) array([['sector1', 'region1'], ['sector1', 'region0'], ['sector0', 'region0'], ['sector0', 'region0'], ['sector1', 'region0'], ['sector0', 'region0'], ['sector1', 'region1'], ['sector0', 'region0'], ['sector1', 'region0'], ['sector0', 'region0']], dtype='|S7') """ # ------------- examples sparse_dummies from scipy import sparse g = np.array([0, 0, 1, 2, 1, 1, 2, 0]) u = lrange(3) indptr = np.arange(len(g)+1) data = np.ones(len(g), dtype=np.int8) a = sparse.csr_matrix((data, g, indptr)) print(a.todense()) print(np.all(a.todense() == (g[:, None] == np.arange(3)).astype(int))) x = np.arange(len(g)*3).reshape(len(g), 3, order='F') print('group means') print(x.T * a) print(np.dot(x.T, g[:, None] == np.arange(3))) print(np.array([np.bincount(g, weights=x[:, col]) for col in range(3)])) for cat in u: print(x[g == cat].sum(0)) for cat in u: x[g == cat].sum(0) cc = sparse.csr_matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 1, 0]]) # ------------- groupsums print(group_sums(np.arange(len(g)*3*2).reshape(len(g), 3, 2), g, use_bincount=False).T) print(group_sums(np.arange(len(g)*3*2).reshape(len(g), 3, 2)[:, :, 0], g)) print(group_sums(np.arange(len(g)*3*2).reshape(len(g), 3, 2)[:, :, 1], g)) # ------------- examples class x = np.arange(len(g)*3).reshape(len(g), 3, order='F') mygroup = Group(g) print(mygroup.group_int) print(mygroup.group_sums(x)) print(mygroup.labels())
bsd-3-clause
RRShieldsCutler/clusterpluck
clusterpluck/scripts/mpi_collapse.py
1
4106
#!/usr/bin/env Python import argparse import sys import numpy as np import pandas as pd import warnings from clusterpluck.scripts.cluster_dictionary import build_cluster_map from clusterpluck.scripts.orfs_in_common import generate_index_list from clusterpluck.scripts.orfs_in_common import pick_a_cluster from functools import partial from scoop import futures # usage = python -m scoop -vv -n 480 mpi_collapse -i [input.csv] -m [.mpfa key] -o [output.csv] # The arg parser def make_arg_parser(): parser = argparse.ArgumentParser(description='Collapse ORF matrix into a scored cluster matrix. Run with "python -m scoop -vv -n 480 mpi_parallel_collapse [args]"') parser.add_argument('-i', '--input', help='Input is the ORF matrix CSV file.', default='-') parser.add_argument('-m', '--mpfa', help='The multi-protein fasta file (.mpfa) from which to build the dictionary') parser.add_argument('-b', '--bread', help='Where to find the cluster information in the header for the sequence (default="ref|,|")', default='ref|,|') parser.add_argument('-o', '--output', help='Where to save the output csv; default to screen', required=False, default='-') return parser def generate_chunk_list(in_csv2): header = pd.read_csv(in_csv2, header=0, engine='c', index_col=0, nrows=0) header = list(header.columns) print('Extracted headers from input file...\n') return header def parallel_clustermean(mx, c_list): i = len(c_list) mat = np.zeros((i, 1)) c_i = 0 for cluster2 in c_list: mx_dubsub = mx.filter(like=cluster2, axis=0) # subsets the smaller matrix by rows belonging to one cluster # finds the mean of the cells in the cluster x cluster2 matrix with warnings.catch_warnings(): warnings.simplefilter('ignore', category=RuntimeWarning) # np doesn't like taking mean of empty slices cc_mean = np.nanmean(mx_dubsub.values, dtype='float64') mat[c_i, 0] = cc_mean # saves this mean into the pre-existing array at the right location c_i += 1 del mx dfmeans = pd.DataFrame(mat) dfmeans = dfmeans.round(decimals=2) dfmeans.index = c_list return dfmeans def main(): parser = make_arg_parser() args = parser.parse_args() # Parse command line with open(args.mpfa, 'r') as inf: # Generates dictionary with each unique 'refseq_cluster' as keys, ORFs as values cluster_map = build_cluster_map(inf, bread=args.bread) with open(args.input, 'r') as in_csv: print('\nOk, processing input file in pieces...\n') inkey = generate_index_list(in_csv) # print(len(inkey)) with open(args.input, 'r') as in_csv2: headers = generate_chunk_list(in_csv2) # print(len(headers)) c_list = list(cluster_map.keys()) # ct = len(c_list) # print('Found %d clusters...' % ct) data_to_pool = [] grabbed_clusters = [] for cluster in c_list: grab = pick_a_cluster(headers, cluster) # uses the name of the cluster to get a list of all orfs for a particular unique cluster if not grab: pass else: # print(grab) grabbed_clusters.extend([cluster]) with open(args.input, 'r') as inf3: mx = pd.read_csv(inf3, sep=',', header=0, usecols=grab, engine='c') # loads in only the columns from the grab list, i.e. all cols for a unique cluster mx.index = inkey # reindexes the df with the orf labels after importing specific columns with usecols data_to_pool.append(mx) # create the list of dfs to map over for multiprocessing if __name__ == '__main__': print('\nSending data to Workers... work, Workers, work!') results = list(futures.map(partial(parallel_clustermean, c_list=c_list), data_to_pool)) print('\nFile processing complete; writing output file...\n') del data_to_pool with open(args.output, 'w') if args.output != '-' else sys.stdout as outf: outdf = pd.concat(results, axis=1) outdf.columns = grabbed_clusters # names the columns (and index, next line) according to clusters in the order they were processed # outdf.index = c_list outdf.sort_index(axis=0, inplace=True) # ensure that the clusters are in order on cols and rows outdf.sort_index(axis=1, inplace=True) outdf.to_csv(outf) if __name__ == '__main__': main()
mit
batterysim/esctoolbox-python
ocv_model/data.py
1
3900
""" Plot the data from the four A123 battery tests conducted at a range of temperatures. Change the tc variable to view plots from the other test data. For example, change the tc string to N05 to create plots for the CSV files named A123_OCV_N05_S1, A123_OCV_N05_S2, A123_OCV_N05_S3, and A123_OCV_N05_S4. """ import matplotlib.pyplot as plt import pandas as pd # Data # ------------------------------------------------------------------------------ # string that represents temperature of battery test to determine which csv # files to read, values can be N05, N15, N25, P05, P15, P25, P35, or P45 tc = 'N05' df1 = pd.read_csv('../ocv_data/A123_OCV_' + tc + '_S1.csv') test_time1 = df1['Test_Time(s)'] current1 = df1['Current(A)'] voltage1 = df1['Voltage(V)'] df2 = pd.read_csv('../ocv_data/A123_OCV_' + tc + '_S2.csv') test_time2 = df2['Test_Time(s)'] current2 = df2['Current(A)'] voltage2 = df2['Voltage(V)'] df3 = pd.read_csv('../ocv_data/A123_OCV_' + tc + '_S3.csv') test_time3 = df3['Test_Time(s)'] current3 = df3['Current(A)'] voltage3 = df3['Voltage(V)'] df4 = pd.read_csv('../ocv_data/A123_OCV_' + tc + '_S4.csv') test_time4 = df4['Test_Time(s)'] current4 = df4['Current(A)'] voltage4 = df4['Voltage(V)'] # Compare Temperature Data # ------------------------------------------------------------------------------ temps = ['N05', 'N15', 'N25', 'P05', 'P15', 'P25', 'P35', 'P45'] times = [] volts = [] for t in temps: df = pd.read_csv('../ocv_data/A123_OCV_' + t + '_S1.csv') time = df['Test_Time(s)'].values voltage = df['Voltage(V)'].values times.append(time) volts.append(voltage) # Plot # ------------------------------------------------------------------------------ plt.ion() plt.close('all') # Figure 1 plt.figure(1) plt.plot(times[0], volts[0], label='-5$^{\circ}$C') plt.plot(times[1], volts[1], label='-15$^{\circ}$C') plt.plot(times[2], volts[2], label='-25$^{\circ}$C') plt.plot(times[3], volts[3], label='5$^{\circ}$C') plt.plot(times[4], volts[4], label='15$^{\circ}$C') plt.plot(times[5], volts[5], label='25$^{\circ}$C') plt.plot(times[6], volts[6], label='35$^{\circ}$C') plt.plot(times[7], volts[7], label='45$^{\circ}$C') plt.legend(loc='best') plt.xlabel('Time (s)') plt.ylabel('Voltage (V)') plt.title('A123 battery cell') # Figure 2 fig, ax1 = plt.subplots() plt.title('A123_OCV_' + tc + '_S1') ax1.plot(test_time1, current1, color='b', lw=2, label='current') ax1.set_xlabel('Test Time (s)') ax1.set_ylabel('Current (A)', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(test_time1, voltage1, color='r', lw=2, label='voltage') ax2.set_ylabel('Voltage (V)', color='r') ax2.tick_params('y', colors='r') # Figure 3 fig, ax1 = plt.subplots() plt.title('A123_OCV_' + tc + '_S2') ax1.plot(test_time2, current2, color='b', lw=2, label='current') ax1.set_xlabel('Test Time (s)') ax1.set_ylabel('Current (A)', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(test_time2, voltage2, color='r', lw=2, label='voltage') ax2.set_ylabel('Voltage (V)', color='r') ax2.tick_params('y', colors='r') # Figure 4 fig, ax1 = plt.subplots() plt.title('A123_OCV_' + tc + '_S3') ax1.plot(test_time3, current3, color='b', lw=2, label='current') ax1.set_xlabel('Test Time (s)') ax1.set_ylabel('Current (A)', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(test_time3, voltage3, color='r', lw=2, label='voltage') ax2.set_ylabel('Voltage (V)', color='r') ax2.tick_params('y', colors='r') # Figure 5 fig, ax1 = plt.subplots() plt.title('A123_OCV_' + tc + '_S4') ax1.plot(test_time4, current4, color='b', lw=2, label='current') ax1.set_xlabel('Test Time (s)') ax1.set_ylabel('Current (A)', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(test_time4, voltage4, color='r', lw=2, label='voltage') ax2.set_ylabel('Voltage (V)', color='r') ax2.tick_params('y', colors='r')
mit
huguesv/PTVS
Python/Product/Miniconda/Miniconda3-x64/Lib/site-packages/conda/_vendor/tqdm/_tqdm.py
6
46609
""" Customisable progressbar decorator for iterators. Includes a default (x)range iterator printing to stderr. Usage: >>> from tqdm import trange[, tqdm] >>> for i in trange(10): #same as: for i in tqdm(xrange(10)) ... ... """ from __future__ import absolute_import # integer division / : float, // : int from __future__ import division # compatibility functions and utilities from ._utils import _supports_unicode, _environ_cols_wrapper, _range, _unich, \ _term_move_up, _unicode, WeakSet, _basestring, _OrderedDict from ._monitor import TMonitor # native libraries import sys from numbers import Number from time import time from contextlib import contextmanager # For parallelism safety import multiprocessing as mp import threading as th from warnings import warn __author__ = {"github.com/": ["noamraph", "obiwanus", "kmike", "hadim", "casperdcl", "lrq3000"]} __all__ = ['tqdm', 'trange', 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning', 'TqdmExperimentalWarning', 'TqdmDeprecationWarning', 'TqdmMonitorWarning'] class TqdmTypeError(TypeError): pass class TqdmKeyError(KeyError): pass class TqdmWarning(Warning): """base class for all tqdm warnings. Used for non-external-code-breaking errors, such as garbled printing. """ def __init__(self, msg, fp_write=None, *a, **k): if fp_write is not None: fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n') else: super(TqdmWarning, self).__init__(msg, *a, **k) class TqdmExperimentalWarning(TqdmWarning, FutureWarning): """beta feature, unstable API and behaviour""" pass class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning): # not suppressed if raised pass class TqdmMonitorWarning(TqdmWarning, RuntimeWarning): """tqdm monitor errors which do not affect external functionality""" pass # Create global parallelism locks to avoid racing issues with parallel bars # works only if fork available (Linux, MacOSX, but not on Windows) try: mp_lock = mp.RLock() # multiprocessing lock except ImportError: # pragma: no cover mp_lock = None except OSError: # pragma: no cover mp_lock = None try: th_lock = th.RLock() # thread lock except OSError: # pragma: no cover th_lock = None class TqdmDefaultWriteLock(object): """ Provide a default write lock for thread and multiprocessing safety. Works only on platforms supporting `fork` (so Windows is excluded). On Windows, you need to supply the lock from the parent to the children as an argument to joblib or the parallelism lib you use. """ def __init__(self): global mp_lock, th_lock self.locks = [lk for lk in [mp_lock, th_lock] if lk is not None] def acquire(self): for lock in self.locks: lock.acquire() def release(self): for lock in self.locks[::-1]: # Release in inverse order of acquisition lock.release() def __enter__(self): self.acquire() def __exit__(self, *exc): self.release() class tqdm(object): """ Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested. """ monitor_interval = 10 # set to 0 to disable the thread monitor = None _lock = TqdmDefaultWriteLock() @staticmethod def format_sizeof(num, suffix='', divisor=1000): """ Formats a number (greater than unity) with SI Order of Magnitude prefixes. Parameters ---------- num : float Number ( >= 1) to format. suffix : str, optional Post-postfix [default: '']. divisor : float, optionl Divisor between prefixes [default: 1000]. Returns ------- out : str Number with Order of Magnitude SI unit postfix. """ for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 999.95: if abs(num) < 99.95: if abs(num) < 9.995: return '{0:1.2f}'.format(num) + unit + suffix return '{0:2.1f}'.format(num) + unit + suffix return '{0:3.0f}'.format(num) + unit + suffix num /= divisor return '{0:3.1f}Y'.format(num) + suffix @staticmethod def format_interval(t): """ Formats a number of seconds as a clock time, [H:]MM:SS Parameters ---------- t : int Number of seconds. Returns ------- out : str [H:]MM:SS """ mins, s = divmod(int(t), 60) h, m = divmod(mins, 60) if h: return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s) else: return '{0:02d}:{1:02d}'.format(m, s) @staticmethod def status_printer(file): """ Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh). """ fp = file fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover def fp_write(s): fp.write(_unicode(s)) fp_flush() last_len = [0] def print_status(s): len_s = len(s) fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0))) last_len[0] = len_s return print_status @staticmethod def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000): """ Return a string-based progress bar given some parameters Parameters ---------- n : int Number of finished iterations. total : int The expected total number of iterations. If meaningless (), only basic progress statistics are displayed (no ETA). elapsed : float Number of seconds passed since start. ncols : int, optional The width of the entire output message. If specified, dynamically resizes the progress meter to stay within this bound [default: None]. The fallback meter width is 10 for the progress bar + no limit for the iterations counter and statistics. If 0, will not print any meter (only stats). prefix : str, optional Prefix message (included in total width) [default: '']. Use as {desc} in bar_format string. ascii : bool, optional If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters (1-9 #). unit : str, optional The iteration unit [default: 'it']. unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale `total` and `n`. rate : float, optional Manual override for iteration rate. If [default: None], uses n/elapsed. bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, elapsed, remaining, desc, postfix. Note that a trailing ": " is automatically removed after {desc} if the latter is empty. postfix : *, optional Similar to `prefix`, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ', ' + postfix. However other types are supported (#382). unit_divisor : float, optional [default: 1000], ignored unless `unit_scale` is True. Returns ------- out : Formatted meter and stats, ready to display. """ # sanity check: total if total and n > total: total = None # apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): total *= unit_scale n *= unit_scale unit_scale = False format_interval = tqdm.format_interval elapsed_str = format_interval(elapsed) # if unspecified, attempt to use rate = average speed # (we allow manual override since predicting time is an arcane art) if rate is None and elapsed: rate = n / elapsed inv_rate = 1 / rate if rate else None format_sizeof = tqdm.format_sizeof rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else '{0:5.2f}'.format(rate)) if rate else '?') + unit + '/s' rate_inv_fmt = ((format_sizeof(inv_rate) if unit_scale else '{0:5.2f}'.format(inv_rate)) if inv_rate else '?') + 's/' + unit rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt if unit_scale: n_fmt = format_sizeof(n, divisor=unit_divisor) total_fmt = format_sizeof(total, divisor=unit_divisor) \ if total else None else: n_fmt = str(n) total_fmt = str(total) try: postfix = ', ' + postfix if postfix else '' except TypeError: pass # total is known: we can predict some stats if total: # fractional and percentage progress frac = n / total percentage = frac * 100 remaining_str = format_interval((total - n) / rate) \ if rate else '?' # format the stats displayed to the left and right sides of the bar if prefix: # old prefix setup work around bool_prefix_colon_already = (prefix[-2:] == ": ") l_bar = prefix if bool_prefix_colon_already else prefix + ": " else: l_bar = '' l_bar += '{0:3.0f}%|'.format(percentage) r_bar = '| {0}/{1} [{2}<{3}, {4}{5}]'.format( n_fmt, total_fmt, elapsed_str, remaining_str, rate_fmt, postfix) if ncols == 0: return l_bar[:-1] + r_bar[1:] if bar_format: # Custom bar formatting # Populate a dict with all available progress indicators bar_args = {'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt, 'percentage': percentage, 'rate': inv_rate if inv_rate and inv_rate > 1 else rate, 'rate_fmt': rate_fmt, 'rate_noinv': rate, 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate, 'rate_inv_fmt': rate_inv_fmt, 'elapsed': elapsed_str, 'remaining': remaining_str, 'l_bar': l_bar, 'r_bar': r_bar, 'desc': prefix or '', 'postfix': postfix, # 'bar': full_bar # replaced by procedure below } # auto-remove colon for empty `desc` if not prefix: bar_format = bar_format.replace("{desc}: ", '') # Interpolate supplied bar format with the dict if '{bar}' in bar_format: # Format left/right sides of the bar, and format the bar # later in the remaining space (avoid breaking display) l_bar_user, r_bar_user = bar_format.split('{bar}') l_bar = l_bar_user.format(**bar_args) r_bar = r_bar_user.format(**bar_args) else: # Else no progress bar, we can just format and return return bar_format.format(**bar_args) # Formatting progress bar # space available for bar's display N_BARS = max(1, ncols - len(l_bar) - len(r_bar)) if ncols \ else 10 # format bar depending on availability of unicode/ascii chars if ascii: bar_length, frac_bar_length = divmod( int(frac * N_BARS * 10), 10) bar = '#' * bar_length frac_bar = chr(48 + frac_bar_length) if frac_bar_length \ else ' ' else: bar_length, frac_bar_length = divmod(int(frac * N_BARS * 8), 8) bar = _unich(0x2588) * bar_length frac_bar = _unich(0x2590 - frac_bar_length) \ if frac_bar_length else ' ' # whitespace padding if bar_length < N_BARS: full_bar = bar + frac_bar + \ ' ' * max(N_BARS - bar_length - 1, 0) else: full_bar = bar + \ ' ' * max(N_BARS - bar_length, 0) # Piece together the bar parts return l_bar + full_bar + r_bar # no total: no progressbar, ETA, just progress stats else: return ((prefix + ": ") if prefix else '') + \ '{0}{1} [{2}, {3}{4}]'.format( n_fmt, unit, elapsed_str, rate_fmt, postfix) def __new__(cls, *args, **kwargs): # Create a new instance instance = object.__new__(cls) # Add to the list of instances if "_instances" not in cls.__dict__: cls._instances = WeakSet() if "_lock" not in cls.__dict__: cls._lock = TqdmDefaultWriteLock() with cls._lock: cls._instances.add(instance) # Create the monitoring thread if cls.monitor_interval and (cls.monitor is None or not cls.monitor.report()): try: cls.monitor = TMonitor(cls, cls.monitor_interval) except Exception as e: # pragma: nocover warn("tqdm:disabling monitor support" " (monitor_interval = 0) due to:\n" + str(e), TqdmMonitorWarning) cls.monitor_interval = 0 # Return the instance return instance @classmethod def _get_free_pos(cls, instance=None): """Skips specified instance""" positions = set(abs(inst.pos) for inst in cls._instances if inst is not instance) return min(set(range(len(positions) + 1)).difference(positions)) @classmethod def _decr_instances(cls, instance): """ Remove from list and reposition other bars so that newer bars won't overlap previous bars """ with cls._lock: try: cls._instances.remove(instance) except KeyError: if not instance.gui: # pragma: no cover raise else: for inst in cls._instances: # negative `pos` means fixed if inst.pos > abs(instance.pos): inst.pos -= 1 # TODO: check this doesn't overwrite another fixed bar # Kill monitor if no instances are left if not cls._instances and cls.monitor: try: cls.monitor.exit() del cls.monitor except AttributeError: # pragma: nocover pass else: cls.monitor = None @classmethod def write(cls, s, file=None, end="\n", nolock=False): """ Print a message via tqdm (without overlap with bars) """ fp = file if file is not None else sys.stdout with cls.external_write_mode(file=file, nolock=nolock): # Write the message fp.write(s) fp.write(end) @classmethod @contextmanager def external_write_mode(cls, file=None, nolock=False): """ Disable tqdm within context and refresh tqdm when exits. Useful when writing to standard output stream """ fp = file if file is not None else sys.stdout if not nolock: cls._lock.acquire() # Clear all bars inst_cleared = [] for inst in getattr(cls, '_instances', []): # Clear instance if in the target output file # or if write output + tqdm output are both either # sys.stdout or sys.stderr (because both are mixed in terminal) if inst.fp == fp or all( f in (sys.stdout, sys.stderr) for f in (fp, inst.fp)): inst.clear(nolock=True) inst_cleared.append(inst) yield # Force refresh display of bars we cleared for inst in inst_cleared: # Avoid race conditions by checking that the instance started if hasattr(inst, 'start_t'): # pragma: nocover inst.refresh(nolock=True) if not nolock: cls._lock.release() @classmethod def set_lock(cls, lock): cls._lock = lock @classmethod def get_lock(cls): return cls._lock @classmethod def pandas(tclass, *targs, **tkwargs): """ Registers the given `tqdm` class with pandas.core. ( frame.DataFrame | series.Series | groupby.DataFrameGroupBy | groupby.SeriesGroupBy ).progress_apply A new instance will be create every time `progress_apply` is called, and each instance will automatically close() upon completion. Parameters ---------- targs, tkwargs : arguments for the tqdm instance Examples -------- >>> import pandas as pd >>> import numpy as np >>> from tqdm import tqdm, tqdm_gui >>> >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6))) >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc >>> # Now you can use `progress_apply` instead of `apply` >>> df.groupby(0).progress_apply(lambda x: x**2) References ---------- https://stackoverflow.com/questions/18603270/ progress-indicator-during-pandas-operations-python """ from pandas.core.frame import DataFrame from pandas.core.series import Series from pandas.core.groupby import DataFrameGroupBy from pandas.core.groupby import SeriesGroupBy from pandas.core.groupby import GroupBy from pandas.core.groupby import PanelGroupBy from pandas import Panel deprecated_t = [tkwargs.pop('deprecated_t', None)] def inner_generator(df_function='apply'): def inner(df, func, *args, **kwargs): """ Parameters ---------- df : (DataFrame|Series)[GroupBy] Data (may be grouped). func : function To be applied on the (grouped) data. **kwargs : optional Transmitted to `df.apply()`. """ # Precompute total iterations total = getattr(df, 'ngroups', None) if total is None: # not grouped if df_function == 'applymap': total = df.size elif isinstance(df, Series): total = len(df) else: # DataFrame or Panel axis = kwargs.get('axis', 0) # when axis=0, total is shape[axis1] total = df.size // df.shape[axis] # Init bar if deprecated_t[0] is not None: t = deprecated_t[0] deprecated_t[0] = None else: t = tclass(*targs, total=total, **tkwargs) if len(args) > 0: # *args intentionally not supported (see #244, #299) TqdmDeprecationWarning( "Except func, normal arguments are intentionally" + " not supported by" + " `(DataFrame|Series|GroupBy).progress_apply`." + " Use keyword arguments instead.", fp_write=getattr(t.fp, 'write', sys.stderr.write)) # Define bar updating wrapper def wrapper(*args, **kwargs): # update tbar correctly # it seems `pandas apply` calls `func` twice # on the first column/row to decide whether it can # take a fast or slow code path; so stop when t.total==t.n t.update(n=1 if t.total and t.n < t.total else 0) return func(*args, **kwargs) # Apply the provided function (in **kwargs) # on the df using our wrapper (which provides bar updating) result = getattr(df, df_function)(wrapper, **kwargs) # Close bar and return pandas calculation result t.close() return result return inner # Monkeypatch pandas to provide easy methods # Enable custom tqdm progress in pandas! Series.progress_apply = inner_generator() SeriesGroupBy.progress_apply = inner_generator() Series.progress_map = inner_generator('map') SeriesGroupBy.progress_map = inner_generator('map') DataFrame.progress_apply = inner_generator() DataFrameGroupBy.progress_apply = inner_generator() DataFrame.progress_applymap = inner_generator('applymap') Panel.progress_apply = inner_generator() PanelGroupBy.progress_apply = inner_generator() GroupBy.progress_apply = inner_generator() GroupBy.progress_aggregate = inner_generator('aggregate') GroupBy.progress_transform = inner_generator('transform') def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, gui=False, **kwargs): """ Parameters ---------- iterable : iterable, optional Iterable to decorate with a progressbar. Leave blank to manually manage the updates. desc : str, optional Prefix for the progressbar. total : int, optional The number of expected iterations. If unspecified, len(iterable) is used if possible. As a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If `gui` is True and this parameter needs subsequent updating, specify an initial arbitrary large positive integer, e.g. int(9e9). leave : bool, optional If [default: True], keeps all traces of the progressbar upon termination of iteration. file : `io.TextIOWrapper` or `io.StringIO`, optional Specifies where to output the progress messages (default: sys.stderr). Uses `file.write(str)` and `file.flush()` methods. ncols : int, optional The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats). mininterval : float, optional Minimum progress display update interval, in seconds [default: 0.1]. maxinterval : float, optional Maximum progress display update interval, in seconds [default: 10]. Automatically adjusts `miniters` to correspond to `mininterval` after long display update lag. Only works if `dynamic_miniters` or monitor thread is enabled. miniters : int, optional Minimum progress display update interval, in iterations. If 0 and `dynamic_miniters`, will automatically adjust to equal `mininterval` (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and `mininterval` to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1. ascii : bool, optional If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters `1-9 #`. disable : bool, optional Whether to disable the entire progressbar wrapper [default: False]. If set to None, disable on non-TTY. unit : str, optional String that will be used to define the unit of each iteration [default: it]. unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale `total` and `n`. dynamic_ncols : bool, optional If set, constantly alters `ncols` to the environment (allowing for window resizes) [default: False]. smoothing : float, optional Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3]. bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, elapsed, remaining, desc, postfix. Note that a trailing ": " is automatically removed after {desc} if the latter is empty. initial : int, optional The initial counter value. Useful when restarting a progress bar [default: 0]. position : int, optional Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads). postfix : dict or *, optional Specify additional stats to display at the end of the bar. Calls `set_postfix(**postfix)` if possible (dict). unit_divisor : float, optional [default: 1000], ignored unless `unit_scale` is True. gui : bool, optional WARNING: internal parameter - do not use. Use tqdm_gui(...) instead. If set, will attempt to use matplotlib animations for a graphical output [default: False]. Returns ------- out : decorated iterator. """ if file is None: file = sys.stderr if disable is None and hasattr(file, "isatty") and not file.isatty(): disable = True if disable: self.iterable = iterable self.disable = disable self.pos = self._get_free_pos(self) self._instances.remove(self) self.n = initial return if kwargs: self.disable = True self.pos = self._get_free_pos(self) self._instances.remove(self) raise (TqdmDeprecationWarning("""\ `nested` is deprecated and automated. Use position instead for manual control. """, fp_write=getattr(file, 'write', sys.stderr.write)) if "nested" in kwargs else TqdmKeyError("Unknown argument(s): " + str(kwargs))) # Preprocess the arguments if total is None and iterable is not None: try: total = len(iterable) except (TypeError, AttributeError): total = None if ((ncols is None) and (file in (sys.stderr, sys.stdout))) or \ dynamic_ncols: # pragma: no cover if dynamic_ncols: dynamic_ncols = _environ_cols_wrapper() if dynamic_ncols: ncols = dynamic_ncols(file) # elif ncols is not None: # ncols = 79 else: _dynamic_ncols = _environ_cols_wrapper() if _dynamic_ncols: ncols = _dynamic_ncols(file) # else: # ncols = 79 if miniters is None: miniters = 0 dynamic_miniters = True else: dynamic_miniters = False if mininterval is None: mininterval = 0 if maxinterval is None: maxinterval = 0 if ascii is None: ascii = not _supports_unicode(file) if bar_format and not ascii: # Convert bar format into unicode since terminal uses unicode bar_format = _unicode(bar_format) if smoothing is None: smoothing = 0 # Store the arguments self.iterable = iterable self.desc = desc or '' self.total = total self.leave = leave self.fp = file self.ncols = ncols self.mininterval = mininterval self.maxinterval = maxinterval self.miniters = miniters self.dynamic_miniters = dynamic_miniters self.ascii = ascii self.disable = disable self.unit = unit self.unit_scale = unit_scale self.unit_divisor = unit_divisor self.gui = gui self.dynamic_ncols = dynamic_ncols self.smoothing = smoothing self.avg_time = None self._time = time self.bar_format = bar_format self.postfix = None if postfix: try: self.set_postfix(refresh=False, **postfix) except TypeError: self.postfix = postfix # Init the iterations counters self.last_print_n = initial self.n = initial # if nested, at initial sp() call we replace '\r' by '\n' to # not overwrite the outer progress bar if position is None: self.pos = self._get_free_pos(self) else: # mark fixed positions as negative self.pos = -position if not gui: # Initialize the screen printer self.sp = self.status_printer(self.fp) with self._lock: if self.pos: self.moveto(abs(self.pos)) self.sp(self.__repr__(elapsed=0)) if self.pos: self.moveto(-abs(self.pos)) # Init the time counter self.last_print_t = self._time() # NB: Avoid race conditions by setting start_t at the very end of init self.start_t = self.last_print_t def __len__(self): return self.total if self.iterable is None else \ (self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else self.total) def __enter__(self): return self def __exit__(self, *exc): self.close() return False def __del__(self): self.close() def __repr__(self, elapsed=None): return self.format_meter( self.n, self.total, elapsed if elapsed is not None else self._time() - self.start_t, self.dynamic_ncols(self.fp) if self.dynamic_ncols else self.ncols, self.desc, self.ascii, self.unit, self.unit_scale, 1 / self.avg_time if self.avg_time else None, self.bar_format, self.postfix, self.unit_divisor) def __lt__(self, other): return abs(self.pos) < abs(other.pos) def __le__(self, other): return (self < other) or (self == other) def __eq__(self, other): return abs(self.pos) == abs(other.pos) def __ne__(self, other): return not (self == other) def __gt__(self, other): return not (self <= other) def __ge__(self, other): return not (self < other) def __hash__(self): return id(self) def __iter__(self): """Backward-compatibility to use: for x in tqdm(iterable)""" # Inlining instance variables as locals (speed optimisation) iterable = self.iterable # If the bar is disabled, then just walk the iterable # (note: keep this check outside the loop for performance) if self.disable: for obj in iterable: yield obj else: mininterval = self.mininterval maxinterval = self.maxinterval miniters = self.miniters dynamic_miniters = self.dynamic_miniters last_print_t = self.last_print_t last_print_n = self.last_print_n n = self.n smoothing = self.smoothing avg_time = self.avg_time _time = self._time try: sp = self.sp except AttributeError: raise TqdmDeprecationWarning("""\ Please use `tqdm_gui(...)` instead of `tqdm(..., gui=True)` """, fp_write=getattr(self.fp, 'write', sys.stderr.write)) for obj in iterable: yield obj # Update and possibly print the progressbar. # Note: does not call self.update(1) for speed optimisation. n += 1 # check counter first to avoid calls to time() if n - last_print_n >= self.miniters: miniters = self.miniters # watch monitoring thread changes delta_t = _time() - last_print_t if delta_t >= mininterval: cur_t = _time() delta_it = n - last_print_n # EMA (not just overall average) if smoothing and delta_t and delta_it: avg_time = delta_t / delta_it \ if avg_time is None \ else smoothing * delta_t / delta_it + \ (1 - smoothing) * avg_time self.n = n with self._lock: if self.pos: self.moveto(abs(self.pos)) # Print bar update sp(self.__repr__()) if self.pos: self.moveto(-abs(self.pos)) # If no `miniters` was specified, adjust automatically # to the max iteration rate seen so far between 2 prints if dynamic_miniters: if maxinterval and delta_t >= maxinterval: # Adjust miniters to time interval by rule of 3 if mininterval: # Set miniters to correspond to mininterval miniters = delta_it * mininterval / delta_t else: # Set miniters to correspond to maxinterval miniters = delta_it * maxinterval / delta_t elif smoothing: # EMA-weight miniters to converge # towards the timeframe of mininterval miniters = smoothing * delta_it * \ (mininterval / delta_t if mininterval and delta_t else 1) + \ (1 - smoothing) * miniters else: # Maximum nb of iterations between 2 prints miniters = max(miniters, delta_it) # Store old values for next call self.n = self.last_print_n = last_print_n = n self.last_print_t = last_print_t = cur_t self.miniters = miniters # Closing the progress bar. # Update some internal variables for close(). self.last_print_n = last_print_n self.n = n self.miniters = miniters self.close() def update(self, n=1): """ Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: ... ... ... t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if `t.update()` will be called in such a way that `filesize` will be exactly reached and printed. Parameters ---------- n : int, optional Increment to add to the internal counter of iterations [default: 1]. """ # N.B.: see __iter__() for more comments. if self.disable: return if n < 0: raise ValueError("n ({0}) cannot be negative".format(n)) self.n += n # check counter first to reduce calls to time() if self.n - self.last_print_n >= self.miniters: delta_t = self._time() - self.last_print_t if delta_t >= self.mininterval: cur_t = self._time() delta_it = self.n - self.last_print_n # >= n # elapsed = cur_t - self.start_t # EMA (not just overall average) if self.smoothing and delta_t and delta_it: self.avg_time = delta_t / delta_it \ if self.avg_time is None \ else self.smoothing * delta_t / delta_it + \ (1 - self.smoothing) * self.avg_time if not hasattr(self, "sp"): raise TqdmDeprecationWarning("""\ Please use `tqdm_gui(...)` instead of `tqdm(..., gui=True)` """, fp_write=getattr(self.fp, 'write', sys.stderr.write)) with self._lock: if self.pos: self.moveto(abs(self.pos)) # Print bar update self.sp(self.__repr__()) if self.pos: self.moveto(-abs(self.pos)) # If no `miniters` was specified, adjust automatically to the # maximum iteration rate seen so far between two prints. # e.g.: After running `tqdm.update(5)`, subsequent # calls to `tqdm.update()` will only cause an update after # at least 5 more iterations. if self.dynamic_miniters: if self.maxinterval and delta_t >= self.maxinterval: if self.mininterval: self.miniters = delta_it * self.mininterval \ / delta_t else: self.miniters = delta_it * self.maxinterval \ / delta_t elif self.smoothing: self.miniters = self.smoothing * delta_it * \ (self.mininterval / delta_t if self.mininterval and delta_t else 1) + \ (1 - self.smoothing) * self.miniters else: self.miniters = max(self.miniters, delta_it) # Store old values for next call self.last_print_n = self.n self.last_print_t = cur_t def close(self): """ Cleanup and (if leave=False) close the progressbar. """ if self.disable: return # Prevent multiple closures self.disable = True # decrement instance pos and remove from internal set pos = abs(self.pos) self._decr_instances(self) # GUI mode if not hasattr(self, "sp"): return # annoyingly, _supports_unicode isn't good enough def fp_write(s): self.fp.write(_unicode(s)) try: fp_write('') except ValueError as e: if 'closed' in str(e): return raise # pragma: no cover with self._lock: if pos: self.moveto(pos) if self.leave: if self.last_print_n < self.n: # stats for overall rate (no weighted average) self.avg_time = None self.sp(self.__repr__()) if pos: self.moveto(-pos) else: fp_write('\n') else: self.sp('') # clear up last bar if pos: self.moveto(-pos) else: fp_write('\r') def unpause(self): """ Restart tqdm timer from last print time. """ cur_t = self._time() self.start_t += cur_t - self.last_print_t self.last_print_t = cur_t def set_description(self, desc=None, refresh=True): """ Set/modify description of the progress bar. Parameters ---------- desc : str, optional refresh : bool, optional Forces refresh [default: True]. """ self.desc = desc + ': ' if desc else '' if refresh: self.refresh() def set_description_str(self, desc=None, refresh=True): """ Set/modify description without ': ' appended. """ self.desc = desc or '' if refresh: self.refresh() def set_postfix(self, ordered_dict=None, refresh=True, **kwargs): """ Set/modify postfix (additional stats) with automatic formatting based on datatype. Parameters ---------- ordered_dict : dict or OrderedDict, optional refresh : bool, optional Forces refresh [default: True]. kwargs : dict, optional """ # Sort in alphabetical order to be more deterministic postfix = _OrderedDict([] if ordered_dict is None else ordered_dict) for key in sorted(kwargs.keys()): postfix[key] = kwargs[key] # Preprocess stats according to datatype for key in postfix.keys(): # Number: limit the length of the string if isinstance(postfix[key], Number): postfix[key] = '{0:2.3g}'.format(postfix[key]) # Else for any other type, try to get the string conversion elif not isinstance(postfix[key], _basestring): postfix[key] = str(postfix[key]) # Else if it's a string, don't need to preprocess anything # Stitch together to get the final postfix self.postfix = ', '.join(key + '=' + postfix[key].strip() for key in postfix.keys()) if refresh: self.refresh() def set_postfix_str(self, s='', refresh=True): """ Postfix without dictionary expansion, similar to prefix handling. """ self.postfix = str(s) if refresh: self.refresh() def moveto(self, n): self.fp.write(_unicode('\n' * n + _term_move_up() * -n)) self.fp.flush() def clear(self, nolock=False): """ Clear current bar display """ if self.disable: return if not nolock: self._lock.acquire() self.moveto(abs(self.pos)) self.sp('') self.fp.write('\r') # place cursor back at the beginning of line self.moveto(-abs(self.pos)) if not nolock: self._lock.release() def refresh(self, nolock=False): """ Force refresh the display of this bar """ if self.disable: return if not nolock: self._lock.acquire() self.moveto(abs(self.pos)) self.sp(self.__repr__()) self.moveto(-abs(self.pos)) if not nolock: self._lock.release() def trange(*args, **kwargs): """ A shortcut for tqdm(xrange(*args), **kwargs). On Python3+ range is used instead of xrange. """ return tqdm(_range(*args), **kwargs)
apache-2.0
HolgerPeters/scikit-learn
sklearn/utils/fixes.py
14
13240
"""Compatibility fixes for older version of python, numpy and scipy If you add content to this file, please give the version of the package at which the fixe is no longer needed. """ # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # Fabian Pedregosa <fpedregosa@acm.org> # Lars Buitinck # # License: BSD 3 clause import warnings import sys import functools import os import errno import numpy as np import scipy.sparse as sp import scipy try: from inspect import signature except ImportError: from ..externals.funcsigs import signature def _parse_version(version_string): version = [] for x in version_string.split('.'): try: version.append(int(x)) except ValueError: # x may be of the form dev-1ea1592 version.append(x) return tuple(version) np_version = _parse_version(np.__version__) sp_version = _parse_version(scipy.__version__) try: from scipy.special import expit # SciPy >= 0.10 with np.errstate(invalid='ignore', over='ignore'): if np.isnan(expit(1000)): # SciPy < 0.14 raise ImportError("no stable expit in scipy.special") except ImportError: def expit(x, out=None): """Logistic sigmoid function, ``1 / (1 + exp(-x))``. See sklearn.utils.extmath.log_logistic for the log of this function. """ if out is None: out = np.empty(np.atleast_1d(x).shape, dtype=np.float64) out[:] = x # 1 / (1 + exp(-x)) = (1 + tanh(x / 2)) / 2 # This way of computing the logistic is both fast and stable. out *= .5 np.tanh(out, out) out += 1 out *= .5 return out.reshape(np.shape(x)) # little danse to see if np.copy has an 'order' keyword argument # Supported since numpy 1.7.0 if 'order' in signature(np.copy).parameters: def safe_copy(X): # Copy, but keep the order return np.copy(X, order='K') else: # Before an 'order' argument was introduced, numpy wouldn't muck with # the ordering safe_copy = np.copy try: if (not np.allclose(np.divide(.4, 1, casting="unsafe"), np.divide(.4, 1, casting="unsafe", dtype=np.float64)) or not np.allclose(np.divide(.4, 1), .4)): raise TypeError('Divide not working with dtype: ' 'https://github.com/numpy/numpy/issues/3484') divide = np.divide except TypeError: # Compat for old versions of np.divide that do not provide support for # the dtype args def divide(x1, x2, out=None, dtype=None): out_orig = out if out is None: out = np.asarray(x1, dtype=dtype) if out is x1: out = x1.copy() else: if out is not x1: out[:] = x1 if dtype is not None and out.dtype != dtype: out = out.astype(dtype) out /= x2 if out_orig is None and np.isscalar(x1): out = np.asscalar(out) return out try: np.array(5).astype(float, copy=False) except TypeError: # Compat where astype accepted no copy argument (numpy < 1.7.0) def astype(array, dtype, copy=True): if not copy and array.dtype == dtype: return array return array.astype(dtype) else: astype = np.ndarray.astype try: with warnings.catch_warnings(record=True): # Don't raise the numpy deprecation warnings that appear in # 1.9, but avoid Python bug due to simplefilter('ignore') warnings.simplefilter('always') sp.csr_matrix([1.0, 2.0, 3.0]).max(axis=0) except (TypeError, AttributeError): # in scipy < 14.0, sparse matrix min/max doesn't accept an `axis` argument # the following code is taken from the scipy 0.14 codebase def _minor_reduce(X, ufunc): major_index = np.flatnonzero(np.diff(X.indptr)) if X.data.size == 0 and major_index.size == 0: # Numpy < 1.8.0 don't handle empty arrays in reduceat value = np.zeros_like(X.data) else: value = ufunc.reduceat(X.data, X.indptr[major_index]) return major_index, value def _min_or_max_axis(X, axis, min_or_max): N = X.shape[axis] if N == 0: raise ValueError("zero-size array to reduction operation") M = X.shape[1 - axis] mat = X.tocsc() if axis == 0 else X.tocsr() mat.sum_duplicates() major_index, value = _minor_reduce(mat, min_or_max) not_full = np.diff(mat.indptr)[major_index] < N value[not_full] = min_or_max(value[not_full], 0) mask = value != 0 major_index = np.compress(mask, major_index) value = np.compress(mask, value) from scipy.sparse import coo_matrix if axis == 0: res = coo_matrix((value, (np.zeros(len(value)), major_index)), dtype=X.dtype, shape=(1, M)) else: res = coo_matrix((value, (major_index, np.zeros(len(value)))), dtype=X.dtype, shape=(M, 1)) return res.A.ravel() def _sparse_min_or_max(X, axis, min_or_max): if axis is None: if 0 in X.shape: raise ValueError("zero-size array to reduction operation") zero = X.dtype.type(0) if X.nnz == 0: return zero m = min_or_max.reduce(X.data.ravel()) if X.nnz != np.product(X.shape): m = min_or_max(zero, m) return m if axis < 0: axis += 2 if (axis == 0) or (axis == 1): return _min_or_max_axis(X, axis, min_or_max) else: raise ValueError("invalid axis, use 0 for rows, or 1 for columns") def sparse_min_max(X, axis): return (_sparse_min_or_max(X, axis, np.minimum), _sparse_min_or_max(X, axis, np.maximum)) else: def sparse_min_max(X, axis): return (X.min(axis=axis).toarray().ravel(), X.max(axis=axis).toarray().ravel()) try: from numpy import argpartition except ImportError: # numpy.argpartition was introduced in v 1.8.0 def argpartition(a, kth, axis=-1, kind='introselect', order=None): return np.argsort(a, axis=axis, order=order) try: from numpy import partition except ImportError: warnings.warn('Using `sort` instead of partition.' 'Upgrade numpy to 1.8 for better performace on large number' 'of clusters') def partition(a, kth, axis=-1, kind='introselect', order=None): return np.sort(a, axis=axis, order=order) if np_version < (1, 7): # Prior to 1.7.0, np.frombuffer wouldn't work for empty first arg. def frombuffer_empty(buf, dtype): if len(buf) == 0: return np.empty(0, dtype=dtype) else: return np.frombuffer(buf, dtype=dtype) else: frombuffer_empty = np.frombuffer if np_version < (1, 8): def in1d(ar1, ar2, assume_unique=False, invert=False): # Backport of numpy function in1d 1.8.1 to support numpy 1.6.2 # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() # This code is significantly faster when the condition is satisfied. if len(ar2) < 10 * len(ar1) ** 0.145: if invert: mask = np.ones(len(ar1), dtype=np.bool) for a in ar2: mask &= (ar1 != a) else: mask = np.zeros(len(ar1), dtype=np.bool) for a in ar2: mask |= (ar1 == a) return mask # Otherwise use sorting if not assume_unique: ar1, rev_idx = np.unique(ar1, return_inverse=True) ar2 = np.unique(ar2) ar = np.concatenate((ar1, ar2)) # We need this to be a stable sort, so always use 'mergesort' # here. The values from the first array should always come before # the values from the second array. order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = (sar[1:] != sar[:-1]) else: bool_ar = (sar[1:] == sar[:-1]) flag = np.concatenate((bool_ar, [invert])) indx = order.argsort(kind='mergesort')[:len(ar1)] if assume_unique: return flag[indx] else: return flag[indx][rev_idx] else: from numpy import in1d if sp_version < (0, 15): # Backport fix for scikit-learn/scikit-learn#2986 / scipy/scipy#4142 from ._scipy_sparse_lsqr_backport import lsqr as sparse_lsqr else: from scipy.sparse.linalg import lsqr as sparse_lsqr def parallel_helper(obj, methodname, *args, **kwargs): """Helper to workaround Python 2 limitations of pickling instance methods""" return getattr(obj, methodname)(*args, **kwargs) if np_version < (1, 6, 2): # Allow bincount to accept empty arrays # https://github.com/numpy/numpy/commit/40f0844846a9d7665616b142407a3d74cb65a040 def bincount(x, weights=None, minlength=None): if len(x) > 0: return np.bincount(x, weights, minlength) else: if minlength is None: minlength = 0 minlength = np.asscalar(np.asarray(minlength, dtype=np.intp)) return np.zeros(minlength, dtype=np.intp) else: from numpy import bincount if 'exist_ok' in signature(os.makedirs).parameters: makedirs = os.makedirs else: def makedirs(name, mode=0o777, exist_ok=False): """makedirs(name [, mode=0o777][, exist_ok=False]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target directory already exists, raise an OSError if exist_ok is False. Otherwise no exception is raised. This is recursive. """ try: os.makedirs(name, mode=mode) except OSError as e: if (not exist_ok or e.errno != errno.EEXIST or not os.path.isdir(name)): raise if np_version < (1, 8, 1): def array_equal(a1, a2): # copy-paste from numpy 1.8.1 try: a1, a2 = np.asarray(a1), np.asarray(a2) except: return False if a1.shape != a2.shape: return False return bool(np.asarray(a1 == a2).all()) else: from numpy import array_equal if sp_version < (0, 13, 0): def rankdata(a, method='average'): if method not in ('average', 'min', 'max', 'dense', 'ordinal'): raise ValueError('unknown method "{0}"'.format(method)) arr = np.ravel(np.asarray(a)) algo = 'mergesort' if method == 'ordinal' else 'quicksort' sorter = np.argsort(arr, kind=algo) inv = np.empty(sorter.size, dtype=np.intp) inv[sorter] = np.arange(sorter.size, dtype=np.intp) if method == 'ordinal': return inv + 1 arr = arr[sorter] obs = np.r_[True, arr[1:] != arr[:-1]] dense = obs.cumsum()[inv] if method == 'dense': return dense # cumulative counts of each unique value count = np.r_[np.nonzero(obs)[0], len(obs)] if method == 'max': return count[dense] if method == 'min': return count[dense - 1] + 1 # average method return .5 * (count[dense] + count[dense - 1] + 1) else: from scipy.stats import rankdata if np_version < (1, 12): class MaskedArray(np.ma.MaskedArray): # Before numpy 1.12, np.ma.MaskedArray object is not picklable # This fix is needed to make our model_selection.GridSearchCV # picklable as the ``cv_results_`` param uses MaskedArray def __getstate__(self): """Return the internal state of the masked array, for pickling purposes. """ cf = 'CF'[self.flags.fnc] data_state = super(np.ma.MaskedArray, self).__reduce__()[2] return data_state + (np.ma.getmaskarray(self).tostring(cf), self._fill_value) else: from numpy.ma import MaskedArray # noqa if 'axis' not in signature(np.linalg.norm).parameters: def norm(X, ord=None, axis=None): """ Handles the axis parameter for the norm function in old versions of numpy (useless for numpy >= 1.8). """ if axis is None or X.ndim == 1: result = np.linalg.norm(X, ord=ord) return result if axis not in (0, 1): raise NotImplementedError(""" The fix that adds axis parameter to the old numpy norm only works for 1D or 2D arrays. """) if axis == 0: X = X.T result = np.zeros(X.shape[0]) for i in range(len(result)): result[i] = np.linalg.norm(X[i], ord=ord) return result else: norm = np.linalg.norm
bsd-3-clause
mugizico/scikit-learn
examples/text/document_clustering.py
230
8356
""" ======================================= Clustering text documents using k-means ======================================= This is an example showing how the scikit-learn can be used to cluster documents by topics using a bag-of-words approach. This example uses a scipy.sparse matrix to store the features instead of standard numpy arrays. Two feature extraction methods can be used in this example: - TfidfVectorizer uses a in-memory vocabulary (a python dict) to map the most frequent words to features indices and hence compute a word occurrence frequency (sparse) matrix. The word frequencies are then reweighted using the Inverse Document Frequency (IDF) vector collected feature-wise over the corpus. - HashingVectorizer hashes word occurrences to a fixed dimensional space, possibly with collisions. The word count vectors are then normalized to each have l2-norm equal to one (projected to the euclidean unit-ball) which seems to be important for k-means to work in high dimensional space. HashingVectorizer does not provide IDF weighting as this is a stateless model (the fit method does nothing). When IDF weighting is needed it can be added by pipelining its output to a TfidfTransformer instance. Two algorithms are demoed: ordinary k-means and its more scalable cousin minibatch k-means. Additionally, latent sematic analysis can also be used to reduce dimensionality and discover latent patterns in the data. It can be noted that k-means (and minibatch k-means) are very sensitive to feature scaling and that in this case the IDF weighting helps improve the quality of the clustering by quite a lot as measured against the "ground truth" provided by the class label assignments of the 20 newsgroups dataset. This improvement is not visible in the Silhouette Coefficient which is small for both as this measure seem to suffer from the phenomenon called "Concentration of Measure" or "Curse of Dimensionality" for high dimensional datasets such as text data. Other measures such as V-measure and Adjusted Rand Index are information theoretic based evaluation scores: as they are only based on cluster assignments rather than distances, hence not affected by the curse of dimensionality. Note: as k-means is optimizing a non-convex objective function, it will likely end up in a local optimum. Several runs with independent random init might be necessary to get a good convergence. """ # Author: Peter Prettenhofer <peter.prettenhofer@gmail.com> # Lars Buitinck <L.J.Buitinck@uva.nl> # License: BSD 3 clause from __future__ import print_function from sklearn.datasets import fetch_20newsgroups from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Normalizer from sklearn import metrics from sklearn.cluster import KMeans, MiniBatchKMeans import logging from optparse import OptionParser import sys from time import time import numpy as np # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') # parse commandline arguments op = OptionParser() op.add_option("--lsa", dest="n_components", type="int", help="Preprocess documents with latent semantic analysis.") op.add_option("--no-minibatch", action="store_false", dest="minibatch", default=True, help="Use ordinary k-means algorithm (in batch mode).") op.add_option("--no-idf", action="store_false", dest="use_idf", default=True, help="Disable Inverse Document Frequency feature weighting.") op.add_option("--use-hashing", action="store_true", default=False, help="Use a hashing feature vectorizer") op.add_option("--n-features", type=int, default=10000, help="Maximum number of features (dimensions)" " to extract from text.") op.add_option("--verbose", action="store_true", dest="verbose", default=False, help="Print progress reports inside k-means algorithm.") print(__doc__) op.print_help() (opts, args) = op.parse_args() if len(args) > 0: op.error("this script takes no arguments.") sys.exit(1) ############################################################################### # Load some categories from the training set categories = [ 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space', ] # Uncomment the following to do the analysis on all the categories #categories = None print("Loading 20 newsgroups dataset for categories:") print(categories) dataset = fetch_20newsgroups(subset='all', categories=categories, shuffle=True, random_state=42) print("%d documents" % len(dataset.data)) print("%d categories" % len(dataset.target_names)) print() labels = dataset.target true_k = np.unique(labels).shape[0] print("Extracting features from the training dataset using a sparse vectorizer") t0 = time() if opts.use_hashing: if opts.use_idf: # Perform an IDF normalization on the output of HashingVectorizer hasher = HashingVectorizer(n_features=opts.n_features, stop_words='english', non_negative=True, norm=None, binary=False) vectorizer = make_pipeline(hasher, TfidfTransformer()) else: vectorizer = HashingVectorizer(n_features=opts.n_features, stop_words='english', non_negative=False, norm='l2', binary=False) else: vectorizer = TfidfVectorizer(max_df=0.5, max_features=opts.n_features, min_df=2, stop_words='english', use_idf=opts.use_idf) X = vectorizer.fit_transform(dataset.data) print("done in %fs" % (time() - t0)) print("n_samples: %d, n_features: %d" % X.shape) print() if opts.n_components: print("Performing dimensionality reduction using LSA") t0 = time() # Vectorizer results are normalized, which makes KMeans behave as # spherical k-means for better results. Since LSA/SVD results are # not normalized, we have to redo the normalization. svd = TruncatedSVD(opts.n_components) normalizer = Normalizer(copy=False) lsa = make_pipeline(svd, normalizer) X = lsa.fit_transform(X) print("done in %fs" % (time() - t0)) explained_variance = svd.explained_variance_ratio_.sum() print("Explained variance of the SVD step: {}%".format( int(explained_variance * 100))) print() ############################################################################### # Do the actual clustering if opts.minibatch: km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, init_size=1000, batch_size=1000, verbose=opts.verbose) else: km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1, verbose=opts.verbose) print("Clustering sparse data with %s" % km) t0 = time() km.fit(X) print("done in %0.3fs" % (time() - t0)) print() print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels, km.labels_)) print("Completeness: %0.3f" % metrics.completeness_score(labels, km.labels_)) print("V-measure: %0.3f" % metrics.v_measure_score(labels, km.labels_)) print("Adjusted Rand-Index: %.3f" % metrics.adjusted_rand_score(labels, km.labels_)) print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, km.labels_, sample_size=1000)) print() if not opts.use_hashing: print("Top terms per cluster:") if opts.n_components: original_space_centroids = svd.inverse_transform(km.cluster_centers_) order_centroids = original_space_centroids.argsort()[:, ::-1] else: order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = vectorizer.get_feature_names() for i in range(true_k): print("Cluster %d:" % i, end='') for ind in order_centroids[i, :10]: print(' %s' % terms[ind], end='') print()
bsd-3-clause
WesleyyC/Restaurant-Revenue-Prediction
Ari/testing_grounds/GradientBoost.py
2
1338
import numpy as np import pandas as pd from math import sqrt from sklearn import ensemble from sklearn.metrics import mean_squared_error ############################################################################### # Load data df_train = pd.read_csv("train_numerical_head.csv") df_train.head() feats = df_train.drop(str(42), axis=1) X_train = feats.values #features y_train = df_train[str(42)].values #target df_test = pd.read_csv("test_numerical_head.csv") df_train.head() X_test = feats.values #features ############################################################################### # Preprocess for i in range(0, len(y_train)-1): if y_train[i]>10000000: print "works" y_train[i]=10000000 ############################################################################### # Fit regression model params = {'n_estimators': 500, 'max_depth': 3, 'min_samples_split': 1, 'learning_rate': 0.001, 'loss': 'lad'} clf = ensemble.GradientBoostingRegressor(**params) clf.fit(X_train, y_train) ############################################################################### # Prediction result = clf.predict(X_test) result = np.asarray(result) np.savetxt("result.csv", result, delimiter=",") rmse = sqrt(mean_squared_error(y_train, clf.predict(X_train))) print "GradientBoostingRegressor RMSE: " , rmse
mit
jluttine/bayespy
bayespy/inference/vmp/nodes/beta.py
3
5230
################################################################################ # Copyright (C) 2014 Jaakko Luttinen # # This file is licensed under the MIT License. ################################################################################ """ A module for the beta distribution node """ import numpy as np import scipy.special as special from .deterministic import Deterministic from .dirichlet import (DirichletMoments, DirichletDistribution, Dirichlet) from .node import Moments, ensureparents class BetaMoments(DirichletMoments): """ Class for the moments of beta variables. """ def __init__(self): super().__init__(2) def compute_fixed_moments(self, p): """ Compute the moments for a fixed value """ p = np.asanyarray(p)[...,None] * [1,-1] + [0,1] self.dims = ( (2,), ) return super().compute_fixed_moments(p) @classmethod def from_values(cls, p): """ Return the shape of the moments for a fixed value. """ return cls() class BetaDistribution(DirichletDistribution): """ Class for the VMP formulas of beta variables. Although the realizations are scalars (probability p), the moments is a two-dimensional vector: [log(p), log(1-p)]. """ def compute_message_to_parent(self, parent, index, u_self, u_alpha): """ Compute the message to a parent node. """ return super().compute_message_to_parent(parent, index, u_self, u_alpha) def compute_phi_from_parents(self, u_alpha, mask=True): """ Compute the natural parameter vector given parent moments. """ return super().compute_phi_from_parents(u_alpha, mask=mask) def compute_moments_and_cgf(self, phi, mask=True): """ Compute the moments and :math:`g(\phi)`. """ return super().compute_moments_and_cgf(phi, mask) def compute_cgf_from_parents(self, u_alpha): """ Compute :math:`\mathrm{E}_{q(p)}[g(p)]` """ return super().compute_cgf_from_parents(u_alpha) def compute_fixed_moments_and_f(self, p, mask=True): """ Compute the moments and :math:`f(x)` for a fixed value. """ p = np.asanyarray(p)[...,None] * [1,-1] + [0,1] return super().compute_fixed_moments_and_f(p, mask=mask) def random(self, *phi, plates=None): """ Draw a random sample from the distribution. """ p = super().random(*phi, plates=plates) return p[...,0] class Beta(Dirichlet): r""" Node for beta random variables. The node models a probability variable :math:`p \in [0,1]` as .. math:: p \sim \mathrm{Beta}(a, b) where :math:`a` and :math:`b` are prior counts for success and failure, respectively. Parameters ---------- alpha : (...,2)-shaped array Two-element vector containing :math:`a` and :math:`b` Examples -------- >>> import warnings >>> warnings.filterwarnings('ignore', category=RuntimeWarning) >>> from bayespy.nodes import Bernoulli, Beta >>> p = Beta([1e-3, 1e-3]) >>> z = Bernoulli(p, plates=(10,)) >>> z.observe([0, 1, 1, 1, 0, 1, 1, 1, 0, 1]) >>> p.update() >>> import bayespy.plot as bpplt >>> import numpy as np >>> bpplt.pdf(p, np.linspace(0, 1, num=100)) [<matplotlib.lines.Line2D object at 0x...>] """ _moments = BetaMoments() _distribution = BetaDistribution() def __init__(self, alpha, **kwargs): """ Create beta node """ super().__init__(alpha, **kwargs) @classmethod def _constructor(cls, alpha, **kwargs): """ Constructs distribution and moments objects. """ retval = super()._constructor(alpha, **kwargs) if retval[2] != cls._moments.dims: raise ValueError("Parent has wrong dimensionality. Must be a " "two-dimensional vector.") return ( retval[0], retval[1], retval[2], retval[3], cls._distribution, cls._moments, retval[6] ) def complement(self): return Complement(self) def __str__(self): """ Print the distribution using standard parameterization. """ a = self.phi[0][...,0] b = self.phi[0][...,1] return ("%s ~ Beta(a, b)\n" " a = \n" "%s\n" " b = \n" "%s\n" % (self.name, a, b)) class Complement(Deterministic): """ Perform 1-p where p is a Beta node. """ _moments = BetaMoments() _parent_moments = (BetaMoments(),) def __init__(self, p, **kwargs): super().__init__(p, dims=p.dims, **kwargs) def _compute_message_to_parent(self, index, m, u_p): if index != 0: raise IndexError() m0 = m[0][...,-1::-1] return [m0] def _compute_moments(self, u_p): u0 = u_p[0][...,-1::-1] return [u0]
mit
datapythonista/pandas
pandas/tests/indexes/datetimes/methods/test_shift.py
4
5476
from datetime import datetime import pytest import pytz from pandas.errors import NullFrequencyError import pandas as pd from pandas import ( DatetimeIndex, Series, date_range, ) import pandas._testing as tm START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) class TestDatetimeIndexShift: # ------------------------------------------------------------- # DatetimeIndex.shift is used in integer addition def test_dti_shift_tzaware(self, tz_naive_fixture): # GH#9903 tz = tz_naive_fixture idx = DatetimeIndex([], name="xxx", tz=tz) tm.assert_index_equal(idx.shift(0, freq="H"), idx) tm.assert_index_equal(idx.shift(3, freq="H"), idx) idx = DatetimeIndex( ["2011-01-01 10:00", "2011-01-01 11:00", "2011-01-01 12:00"], name="xxx", tz=tz, freq="H", ) tm.assert_index_equal(idx.shift(0, freq="H"), idx) exp = DatetimeIndex( ["2011-01-01 13:00", "2011-01-01 14:00", "2011-01-01 15:00"], name="xxx", tz=tz, freq="H", ) tm.assert_index_equal(idx.shift(3, freq="H"), exp) exp = DatetimeIndex( ["2011-01-01 07:00", "2011-01-01 08:00", "2011-01-01 09:00"], name="xxx", tz=tz, freq="H", ) tm.assert_index_equal(idx.shift(-3, freq="H"), exp) def test_dti_shift_freqs(self): # test shift for DatetimeIndex and non DatetimeIndex # GH#8083 drange = date_range("20130101", periods=5) result = drange.shift(1) expected = DatetimeIndex( ["2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05", "2013-01-06"], freq="D", ) tm.assert_index_equal(result, expected) result = drange.shift(-1) expected = DatetimeIndex( ["2012-12-31", "2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04"], freq="D", ) tm.assert_index_equal(result, expected) result = drange.shift(3, freq="2D") expected = DatetimeIndex( ["2013-01-07", "2013-01-08", "2013-01-09", "2013-01-10", "2013-01-11"], freq="D", ) tm.assert_index_equal(result, expected) def test_dti_shift_int(self): rng = date_range("1/1/2000", periods=20) result = rng + 5 * rng.freq expected = rng.shift(5) tm.assert_index_equal(result, expected) result = rng - 5 * rng.freq expected = rng.shift(-5) tm.assert_index_equal(result, expected) def test_dti_shift_no_freq(self): # GH#19147 dti = DatetimeIndex(["2011-01-01 10:00", "2011-01-01"], freq=None) with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"): dti.shift(2) @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_dti_shift_localized(self, tzstr): dr = date_range("2011/1/1", "2012/1/1", freq="W-FRI") dr_tz = dr.tz_localize(tzstr) result = dr_tz.shift(1, "10T") assert result.tz == dr_tz.tz def test_dti_shift_across_dst(self): # GH 8616 idx = date_range("2013-11-03", tz="America/Chicago", periods=7, freq="H") s = Series(index=idx[:-1], dtype=object) result = s.shift(freq="H") expected = Series(index=idx[1:], dtype=object) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "shift, result_time", [ [0, "2014-11-14 00:00:00"], [-1, "2014-11-13 23:00:00"], [1, "2014-11-14 01:00:00"], ], ) def test_dti_shift_near_midnight(self, shift, result_time): # GH 8616 dt = datetime(2014, 11, 14, 0) dt_est = pytz.timezone("EST").localize(dt) s = Series(data=[1], index=[dt_est]) result = s.shift(shift, freq="H") expected = Series(1, index=DatetimeIndex([result_time], tz="EST")) tm.assert_series_equal(result, expected) def test_shift_periods(self): # GH#22458 : argument 'n' was deprecated in favor of 'periods' idx = date_range(start=START, end=END, periods=3) tm.assert_index_equal(idx.shift(periods=0), idx) tm.assert_index_equal(idx.shift(0), idx) @pytest.mark.parametrize("freq", ["B", "C"]) def test_shift_bday(self, freq): rng = date_range(START, END, freq=freq) shifted = rng.shift(5) assert shifted[0] == rng[5] assert shifted.freq == rng.freq shifted = rng.shift(-5) assert shifted[5] == rng[0] assert shifted.freq == rng.freq shifted = rng.shift(0) assert shifted[0] == rng[0] assert shifted.freq == rng.freq def test_shift_bmonth(self): rng = date_range(START, END, freq=pd.offsets.BMonthEnd()) shifted = rng.shift(1, freq=pd.offsets.BDay()) assert shifted[0] == rng[0] + pd.offsets.BDay() rng = date_range(START, END, freq=pd.offsets.BMonthEnd()) with tm.assert_produces_warning(pd.errors.PerformanceWarning): shifted = rng.shift(1, freq=pd.offsets.CDay()) assert shifted[0] == rng[0] + pd.offsets.CDay() def test_shift_empty(self): # GH#14811 dti = date_range(start="2016-10-21", end="2016-10-21", freq="BM") result = dti.shift(1) tm.assert_index_equal(result, dti)
bsd-3-clause
krez13/scikit-learn
examples/svm/plot_svm_kernels.py
329
1971
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= SVM-Kernels ========================================================= Three different types of SVM-Kernels are displayed below. The polynomial and RBF are especially useful when the data-points are not linearly separable. """ print(__doc__) # Code source: Gaël Varoquaux # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import svm # Our dataset and targets X = np.c_[(.4, -.7), (-1.5, -1), (-1.4, -.9), (-1.3, -1.2), (-1.1, -.2), (-1.2, -.4), (-.5, 1.2), (-1.5, 2.1), (1, 1), # -- (1.3, .8), (1.2, .5), (.2, -2), (.5, -2.4), (.2, -2.3), (0, -2.7), (1.3, 2.1)].T Y = [0] * 8 + [1] * 8 # figure number fignum = 1 # fit the model for kernel in ('linear', 'poly', 'rbf'): clf = svm.SVC(kernel=kernel, gamma=2) clf.fit(X, Y) # plot the line, the points, and the nearest vectors to the plane plt.figure(fignum, figsize=(4, 3)) plt.clf() plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors='none', zorder=10) plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired) plt.axis('tight') x_min = -3 x_max = 3 y_min = -3 y_max = 3 XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) # Put the result into a color plot Z = Z.reshape(XX.shape) plt.figure(fignum, figsize=(4, 3)) plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired) plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'], levels=[-.5, 0, .5]) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xticks(()) plt.yticks(()) fignum = fignum + 1 plt.show()
bsd-3-clause
imaculate/scikit-learn
examples/gaussian_process/plot_gpr_prior_posterior.py
104
2878
""" ========================================================================== Illustration of prior and posterior Gaussian process for different kernels ========================================================================== This example illustrates the prior and posterior of a GPR with different kernels. Mean, standard deviation, and 10 samples are shown for both prior and posterior. """ print(__doc__) # Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # # License: BSD 3 clause import numpy as np from matplotlib import pyplot as plt from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import (RBF, Matern, RationalQuadratic, ExpSineSquared, DotProduct, ConstantKernel) kernels = [1.0 * RBF(length_scale=1.0, length_scale_bounds=(1e-1, 10.0)), 1.0 * RationalQuadratic(length_scale=1.0, alpha=0.1), 1.0 * ExpSineSquared(length_scale=1.0, periodicity=3.0, length_scale_bounds=(0.1, 10.0), periodicity_bounds=(1.0, 10.0)), ConstantKernel(0.1, (0.01, 10.0)) * (DotProduct(sigma_0=1.0, sigma_0_bounds=(0.0, 10.0)) ** 2), 1.0 * Matern(length_scale=1.0, length_scale_bounds=(1e-1, 10.0), nu=1.5)] for fig_index, kernel in enumerate(kernels): # Specify Gaussian Process gp = GaussianProcessRegressor(kernel=kernel) # Plot prior plt.figure(fig_index, figsize=(8, 8)) plt.subplot(2, 1, 1) X_ = np.linspace(0, 5, 100) y_mean, y_std = gp.predict(X_[:, np.newaxis], return_std=True) plt.plot(X_, y_mean, 'k', lw=3, zorder=9) plt.fill_between(X_, y_mean - y_std, y_mean + y_std, alpha=0.5, color='k') y_samples = gp.sample_y(X_[:, np.newaxis], 10) plt.plot(X_, y_samples, lw=1) plt.xlim(0, 5) plt.ylim(-3, 3) plt.title("Prior (kernel: %s)" % kernel, fontsize=12) # Generate data and fit GP rng = np.random.RandomState(4) X = rng.uniform(0, 5, 10)[:, np.newaxis] y = np.sin((X[:, 0] - 2.5) ** 2) gp.fit(X, y) # Plot posterior plt.subplot(2, 1, 2) X_ = np.linspace(0, 5, 100) y_mean, y_std = gp.predict(X_[:, np.newaxis], return_std=True) plt.plot(X_, y_mean, 'k', lw=3, zorder=9) plt.fill_between(X_, y_mean - y_std, y_mean + y_std, alpha=0.5, color='k') y_samples = gp.sample_y(X_[:, np.newaxis], 10) plt.plot(X_, y_samples, lw=1) plt.scatter(X[:, 0], y, c='r', s=50, zorder=10) plt.xlim(0, 5) plt.ylim(-3, 3) plt.title("Posterior (kernel: %s)\n Log-Likelihood: %.3f" % (gp.kernel_, gp.log_marginal_likelihood(gp.kernel_.theta)), fontsize=12) plt.tight_layout() plt.show()
bsd-3-clause
marcocaccin/scikit-learn
sklearn/neighbors/nearest_centroid.py
38
7356
# -*- coding: utf-8 -*- """ Nearest Centroid Classification """ # Author: Robert Layton <robertlayton@gmail.com> # Olivier Grisel <olivier.grisel@ensta.org> # # License: BSD 3 clause import warnings import numpy as np from scipy import sparse as sp from ..base import BaseEstimator, ClassifierMixin from ..metrics.pairwise import pairwise_distances from ..preprocessing import LabelEncoder from ..utils.validation import check_array, check_X_y, check_is_fitted from ..utils.sparsefuncs import csc_median_axis_0 from ..utils.multiclass import check_classification_targets class NearestCentroid(BaseEstimator, ClassifierMixin): """Nearest centroid classifier. Each class is represented by its centroid, with test samples classified to the class with the nearest centroid. Read more in the :ref:`User Guide <nearest_centroid_classifier>`. Parameters ---------- metric: string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by metrics.pairwise.pairwise_distances for its metric parameter. The centroids for the samples corresponding to each class is the point from which the sum of the distances (according to the metric) of all samples that belong to that particular class are minimized. If the "manhattan" metric is provided, this centroid is the median and for all other metrics, the centroid is now set to be the mean. shrink_threshold : float, optional (default = None) Threshold for shrinking centroids to remove features. Attributes ---------- centroids_ : array-like, shape = [n_classes, n_features] Centroid of each class Examples -------- >>> from sklearn.neighbors.nearest_centroid import NearestCentroid >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> clf = NearestCentroid() >>> clf.fit(X, y) NearestCentroid(metric='euclidean', shrink_threshold=None) >>> print(clf.predict([[-0.8, -1]])) [1] See also -------- sklearn.neighbors.KNeighborsClassifier: nearest neighbors classifier Notes ----- When used for text classification with tf-idf vectors, this classifier is also known as the Rocchio classifier. References ---------- Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of multiple cancer types by shrunken centroids of gene expression. Proceedings of the National Academy of Sciences of the United States of America, 99(10), 6567-6572. The National Academy of Sciences. """ def __init__(self, metric='euclidean', shrink_threshold=None): self.metric = metric self.shrink_threshold = shrink_threshold def fit(self, X, y): """ Fit the NearestCentroid model according to the given training data. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. Note that centroid shrinking cannot be used with sparse matrices. y : array, shape = [n_samples] Target values (integers) """ # If X is sparse and the metric is "manhattan", store it in a csc # format is easier to calculate the median. if self.metric == 'manhattan': X, y = check_X_y(X, y, ['csc']) else: X, y = check_X_y(X, y, ['csr', 'csc']) is_X_sparse = sp.issparse(X) if is_X_sparse and self.shrink_threshold: raise ValueError("threshold shrinking not supported" " for sparse input") check_classification_targets(y) n_samples, n_features = X.shape le = LabelEncoder() y_ind = le.fit_transform(y) self.classes_ = classes = le.classes_ n_classes = classes.size if n_classes < 2: raise ValueError('y has less than 2 classes') # Mask mapping each class to it's members. self.centroids_ = np.empty((n_classes, n_features), dtype=np.float64) # Number of clusters in each class. nk = np.zeros(n_classes) for cur_class in range(n_classes): center_mask = y_ind == cur_class nk[cur_class] = np.sum(center_mask) if is_X_sparse: center_mask = np.where(center_mask)[0] # XXX: Update other averaging methods according to the metrics. if self.metric == "manhattan": # NumPy does not calculate median of sparse matrices. if not is_X_sparse: self.centroids_[cur_class] = np.median(X[center_mask], axis=0) else: self.centroids_[cur_class] = csc_median_axis_0(X[center_mask]) else: if self.metric != 'euclidean': warnings.warn("Averaging for metrics other than " "euclidean and manhattan not supported. " "The average is set to be the mean." ) self.centroids_[cur_class] = X[center_mask].mean(axis=0) if self.shrink_threshold: dataset_centroid_ = np.mean(X, axis=0) # m parameter for determining deviation m = np.sqrt((1. / nk) + (1. / n_samples)) # Calculate deviation using the standard deviation of centroids. variance = (X - self.centroids_[y_ind]) ** 2 variance = variance.sum(axis=0) s = np.sqrt(variance / (n_samples - n_classes)) s += np.median(s) # To deter outliers from affecting the results. mm = m.reshape(len(m), 1) # Reshape to allow broadcasting. ms = mm * s deviation = ((self.centroids_ - dataset_centroid_) / ms) # Soft thresholding: if the deviation crosses 0 during shrinking, # it becomes zero. signs = np.sign(deviation) deviation = (np.abs(deviation) - self.shrink_threshold) deviation[deviation < 0] = 0 deviation *= signs # Now adjust the centroids using the deviation msd = ms * deviation self.centroids_ = dataset_centroid_[np.newaxis, :] + msd return self def predict(self, X): """Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = [n_samples] Notes ----- If the metric constructor parameter is "precomputed", X is assumed to be the distance matrix between the data to be predicted and ``self.centroids_``. """ check_is_fitted(self, 'centroids_') X = check_array(X, accept_sparse='csr') return self.classes_[pairwise_distances( X, self.centroids_, metric=self.metric).argmin(axis=1)]
bsd-3-clause
reedessick/nmodelte
lib/nmode_plotting.py
1
32700
usage=""" written to provide basic plotting functions that are common to many investigations """ import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt #plt.rcParams.update({"text.usetex":True}) import numpy as np pi = np.pi infty = np.infty from numpy import linalg #from scipy import linalg import nmode_utils as nm_u #################################################################################################### # # # standard plotting functions # labels should be set by caller # #################################################################################################### def plot(x, y, n_l_m=False, mode_nums=False): fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range(len(y)) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, y[m], label=label) return fig, ax ################################################## def amp_plot(x, y, n_l_m=False, mode_nums=False): fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range(len(y) ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [nm_u.amp(l1,l2) for l1,l2 in y[m]], label=label) return fig, ax ################################################## def phs_plot(x, y, n_l_m=False, mode_nums=False): fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range(len(y) ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [nm_u.phs(l1,l2)/(2*pi) for l1,l2 in y[m]], label=label) return fig, ax ################################################## def amp_phs_plot(x, y, n_l_m=False, mode_nums=False): fig = plt.figure() ax1 = plt.subplot(2,1,1) ax2 = plt.subplot(2,1,2) plt.subplots_adjust(hspace=0.05, wspace=0.05) if not mode_nums: mode_nums = range(len(y) ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax1.plot(x, [nm_u.amp(l1,l2) for l1,l2 in y[m]], label=label) ax2.plot(x, [nm_u.phs(l1,l2)/(2*pi) for l1,l2 in y[m]], label=label) return fig, ax1, ax2 ################################################## def real_plot(x, y, n_l_m=False, mode_nums=False): fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range(len(y) ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [l[0] for l in y[m]], label=label) return fig, ax ################################################## def imag_plot(x, y, n_l_m=False, mode_nums=False): fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range(len(y) ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [l[1] for l in y[m]], label=label) return fig, ax ################################################## def real_imag_plot(x, y, n_l_m=False, mode_nums=False): fig = plt.figure() ax1 = plt.subplot(2,1,1) ax2 = plt.subplot(2,1,2) plt.subplots_adjust(hspace=0.05, wspace=0.05) if not mode_nums: mode_nums = range(len(y) ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax1.plot(x, [l[0] for l in y[m]], label=label) ax2.plot(x, [l[1] for l in y[m]], label=label) return fig, ax1, ax2 ################################################## def multi_gen_plot(x, y, gens, n_l_m=False, mode_nums=False): fig = plt.figure() num_gen = len(gens) ax_height = 0.8/num_gen buff = 0.01*ax_height axs = [] for genNo, gen in enumerate(gens): ax = fig.add_axes( [0.15, 0.95-(1+genNo)*ax_height, 0.8, ax_height-buff] ) for m in gen: if mode_nums and (m not in mode_nums): continue label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, y[m], label=label) plt.setp(ax.get_xticklabels(), visible=False) axs.append( ax ) plt.setp(ax.get_xticklabels(), visible=True) return fig, axs ################################################## def multi_gen_amp_plot(x, y, gens, n_l_m=False, mode_nums=False): """ returns a stacked plot with one panel for each generation expects gens to have the form: [ [modeNo00, modeNo01, modeNo02,...], [modeNo10, modeNo11, modeNo12,...], ...] """ fig = plt.figure() num_gen = len(gens) ax_height = 0.8/num_gen buff = 0.01*ax_height axs = [] for genNo, gen in enumerate(gens): ax = fig.add_axes( [0.15, 0.95 - (1+genNo)*ax_height, 0.8, ax_height-buff] ) for m in gen: if mode_nums and (m not in mode_nums): continue label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [nm_u.amp(l1,l2) for l1,l2 in y[m]], label=label) plt.setp(ax.get_xticklabels(), visible=False) axs.append(ax) plt.setp(ax.get_xticklabels(), visible=True) return fig, axs ################################################## def multi_gen_phs_plot(x, y, gens, n_l_m=False, mode_nums=False): """ returns a stacked plot with one panel for each generation expects gens to have the form: [ [modeNo00, modeNo01, modeNo02,...], [modeNo10, modeNo11, modeNo12,...], ...] """ fig = plt.figure() num_gen = len(gens) ax_height = 0.8/num_gen buff = 0.01*ax_height axs = [] for genNo, gen in enumerate(gens): ax = fig.add_axes( [0.15, 0.95 - (1+genNo)*ax_height, 0.8, ax_height-buff] ) for m in gen: if mode_nums and (m not in mode_nums): continue label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [nm_u.phs(l1,l2)/(2*pi) for l1,l2 in y[m]], label=label) plt.setp(ax.get_xticklabels(), visible=False) axs.append(ax) plt.setp(ax.get_xticklabels(), visible=True) return fig, axs ################################################## def multi_gen_real_plot(x, y, gens, n_l_m=False, mode_nums=False): """ returns a stacked plot with one panel for each generation expects gens to have the form: [ [modeNo00, modeNo01, modeNo02,...], [modeNo10, modeNo11, modeNo12,...], ...] """ fig = plt.figure() num_gen = len(gens) ax_height = 0.8/num_gen buff = 0.01*ax_height axs = [] for genNo, gen in enumerate(gens): ax = fig.add_axes( [0.15, 0.95 - (1+genNo)*ax_height, 0.8, ax_height-buff] ) for m in gen: if mode_nums and (m not in mode_nums): continue label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [l[0] for l in y[m]], label=label) plt.setp(ax.get_xticklabels(), visible=False) axs.append(ax) plt.setp(ax.get_xticklabels(), visible=True) return fig, axs ################################################## def multi_gen_imag_plot(x, y, gens, n_l_m=False, mode_nums=False): """ returns a stacked plot with one panel for each generation expects gens to have the form: [ [modeNo00, modeNo01, modeNo02,...], [modeNo10, modeNo11, modeNo12,...], ...] """ fig = plt.figure() num_gen = len(gens) ax_height = 0.8/num_gen buff = 0.01*ax_height axs = [] for genNo, gen in enumerate(gens): ax = fig.add_axes( [0.15, 0.95 - (1+genNo)*ax_height, 0.8, ax_height-buff] ) for m in gen: if mode_nums and (m not in mode_nums): continue label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot(x, [l[1] for l in y[m]], label=label) plt.setp(ax.get_xticklabels(), visible=False) axs.append(ax) plt.setp(ax.get_xticklabels(), visible=True) return fig, axs #################################################################################################### # # phase portraits # #################################################################################################### def _compute_time_derivatives(t,q,system,current): import network_flow as nf Porb = system.Porb N_m = len(q) N_p = len(q[0]) dqdt_P = [ [] for n in range(N_m) ] if current == "x": for ind in range(N_p): # all points in data this_q = [] for m in range(N_m): this_q += q[m][ind] # add real and imagninary part for each mode to single list this_dqdt_P = nf.dxdt_no_NLT(t[ind], this_q, (N_m*2, system)) # compute derivatives for m in range(N_m): dqdt_P[m].append( [this_dqdt_P[2*m]*Porb, this_dqdt_P[2*m+1]*Porb] ) # re-format list into familiar form elif current == "q": for ind in range(N_p): # all points in data this_q = [] for m in range(N_m): this_q += q[m][ind] # add real and imagninary part for each mode to single list this_dqdt_P = nf.dqdt_no_NLT(t[ind], this_q, (N_m*2, system)) # compute derivatives for m in range(N_m): dqdt_P[m].append( [this_dqdt_P[2*m]*Porb, this_dqdt_P[2*m+1]*Porb] ) # re-format list into familiar form else: sys.exit("unknown variable type: %s in nmode_plotting.phase_portrait" % current) return dqdt_P, N_m, N_p ################################################## def amp_phase_portrait(t, q, system, current, n_l_m=False, mode_nums=False, verbose=False): """ computes and overlays phase portraits for each mode. These are phase portraits for the amplitude of the mode """ if verbose: print "\tcomputing time derivatives" dqdt_P, N_m, N_p = _compute_time_derivatives(t,q,system,current) if verbose: print "\tcomputing A, \dot{A} and plotting" fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range( N_m ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) this_q = q[m] this_dqdt_P = dqdt_P[m] ax.plot([nm_u.amp(l1,l2) for l1,l2 in this_q], [(this_q[ind][0]*this_dqdt_P[ind][0] + this_q[ind][1]*this_dqdt_P[ind][1]) / (nm_u.amp(this_q[ind][0], this_q[ind][1])) for ind in range(N_p)], label=label) return fig, ax ################################################## def real_phase_portrait(t, q, system, current, n_l_m=False, mode_nums=False, verbose=False): """ computes and overlays phase portraits for each mode. These are phase portraits for the real part of the mode """ if verbose: print "\tcomputing time derivatives" dqdt_P, N_m, N_p = _compute_time_derivatives(t,q,system,current) if verbose: print "\tcomputing A, \dot{A} and plotting" fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range( N_m ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot([l for l,_ in q[m]], [l for l,_ in dqdt_P[m]], label=label) return fig, ax ################################################## def imag_phase_portrait(t, q, system, current, n_l_m=False, mode_nums=False, verbose=False): """ computes and overlays phase portraits for each mode. These are phase portraits for the imaginary part of the mode """ if verbose: print "\tcomputing time derivatives" dqdt_P, N_m, N_p = _compute_time_derivatives(t,q,system,current) if verbose: print "\tcomputing A, \dot{A} and plotting" fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range( N_m ) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot([l for _,l in q[m]], [l for _,l in dqdt_P[m]], label=label) return fig, ax ################################################## def real_imag_phase_portrait(q, n_l_m=False, mode_nums=False): """ plots the Real part of each mode agains the Imaginary part of the same mode In polar coordinates, this corresponds to amplitude and phase """ fig = plt.figure() ax = plt.subplot(1,1,1) if not mode_nums: mode_nums = range(len(q)) for m in mode_nums: label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot([l for l,_ in q[m]], [l for _,l in q[m]], label=label) return fig, ax ################################################## # # multi-gen phase portraits # ################################################## def multi_gen_amp_phase_portrait(t, q, system, current, gens, n_l_m=False, mode_nums=False, verbose=False): """ computes and overlays phase portraits for each mode. These are phase portraits for the amplitude of the mode automatically separates modes by generation (specified by gens) """ if verbose: print "\tcomputing time derivatives" dqdt_P, N_m, N_p = _compute_time_derivatives(t,q,system,current) if verbose: print "\tcomputing A, \dot{A} and plotting" fig = plt.figure() num_gen = len(gens) ax_height = 0.8/num_gen buff = 0.01*ax_height g_min = infty g_max = -infty axs = [] for genNo, gen in enumerate(gens): ax = fig.add_axes( [0.15, 0.95 - (1+genNo)*ax_height, 0.8, ax_height-buff] ) for m in gen: if mode_nums and (m not in mode_nums): continue label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) this_q = q[m] this_dqdt_P = dqdt_P[m] ax.plot([nm_u.amp(l1,l2) for l1,l2 in this_q], [(this_q[ind][0]*this_dqdt_P[ind][0] + this_q[ind][1]*this_dqdt_P[ind][1]) / (nm_u.amp(this_q[ind][0], this_q[ind][1])) for ind in range(N_p)], label=label) # figure out minimum/maximum this_min, this_max = ax.get_xlim() if this_min < g_min: g_min = this_min if this_max > g_max: g_max = this_max plt.setp(ax.get_xticklabels(), visible=False) axs.append(ax) plt.setp(ax.get_xticklabels(), visible=True) for ax in axs: ax.set_xlim(xmin=g_min, xmax=g_max) return fig, axs ################################################## def multi_gen_real_imag_phase_portrait(q, gens, n_l_m=False, mode_nums=False): """ computes and overlays phase portraits for each mode. These are phase portraits for the amplitude of the mode automatically separates modes by generation (specified by gens) """ fig = plt.figure() num_gen = len(gens) ax_height = 0.8/num_gen buff = 0.01*ax_height g_min = infty g_max = -infty axs = [] for genNo, gen in enumerate(gens): ax = fig.add_axes( [0.15, 0.95 - (1+genNo)*ax_height, 0.8, ax_height-buff] ) for m in gen: if mode_nums and (m not in mode_nums): continue label = "mode %d" % m if n_l_m: label += ":%s" % str(n_l_m[m]) ax.plot([l for l,_ in q[m]], [l for _,l in q[m]], label=label) # figure out minimum/maximum this_min, this_max = ax.get_xlim() if this_min < g_min: g_min = this_min if this_max > g_max: g_max = this_max plt.setp(ax.get_xticklabels(), visible=False) axs.append(ax) plt.setp(ax.get_xticklabels(), visible=True) for ax in axs: ax.set_xlim(xmin=g_min, xmax=g_max) return fig, axs #################################################################################################### # # Instantaneous linearization # stability of perturbations about current flow #################################################################################################### def eig_q(q, network, just_eigval=False): """ computes the eigenvalues of system for the single sample in q. q must have the form [R0, I0, R1, I1, R2, I2, R3, I3, ...] returns a list of eigenvalues and eigenvectors this is a linearization of the evolution of two infinitesimally close neighboring trajectories, one of which is currently at the point {q} """ Nm = len(network) M = np.zeros((2*Nm, 2*Nm)) # holder for matrix we diagonalize ### build matrix for modeNo in range(Nm): wo, yo, _ = network.wyU[modeNo] ro_ind = 2*modeNo io_ind = ro_ind+1 # diagonal 2x2 matrix M[ro_ind][ro_ind] = -yo M[ro_ind][io_ind] = wo M[io_ind][ro_ind] = -wo M[io_ind][io_ind] = -yo # off-diagonal elements for i,j,k in network.K[modeNo]: if i == j: ri_ind = 2*i ii_ind = ri_ind+1 ri = q[ri_ind] ii = q[ii_ind] M[ro_ind][ri_ind] = 2*wo*k*ii M[ro_ind][ii_ind] = 2*wo*k*ri M[io_ind][ri_ind] = 2*wo*k*ri M[io_ind][ii_ind] = -2*wo*k*ii else: # i != j ri_ind = 2*i ii_ind = ri_ind+1 ri = q[ri_ind] ii = q[ii_ind] rj_ind = 2*j ij_ind = rj_ind+1 rj = q[rj_ind] ij = q[ij_ind] M[ro_ind][ri_ind] = 2*wo*k*ij M[ro_ind][ii_ind] = 2*wo*k*rj M[io_ind][ri_ind] = 2*wo*k*rj M[io_ind][ii_ind] = -2*wo*k*ij M[ro_ind][rj_ind] = 2*wo*k*ii M[ro_ind][ij_ind] = 2*wo*k*ri M[io_ind][rj_ind] = 2*wo*k*ri M[io_ind][ij_ind] = -2*wo*k*ij ### diagonalize matrix. get eigenvalues, vectors if just_eigvals: return linalg.eigvals(M, overwrite_a=True) eigenvalues, eigenvectors = linalg.eig(M, overwrite_a=True) # overwrite_a=True may help performance, and I don't care about "a" at this point (a=M within the function) ### now, the eigenvectors may be complex, and we really want to return the corresponding real and imaginary parts of each mode (which are mixed into two complex numbers). We convert this by hand converted_eigenvectors = np.zeros((2*Nm, 2*Nm)) for vecNo in range(2*Nm): eigenvect = eigenvectors[:,vecNo] for modeNo in range(Nm): r = eigenvect[2*modeNo] i = eigenvect[2*modeNo+1] converted_eigenvectors[2*modeNo][vecNo] = np.real(r) - np.imag(i) converted_eigenvectors[2*modeNo+1][vecNo] = np.imag(r) + np.real(i) ### correct normalization converted_eigenvectors[:,vecNo] = converted_eigenvectors[:,vecNo]/sum(converted_eigenvectors[:,vecNo]**2)**0.5 return eigenvalues, converted_eigenvectors ################################################## def eig_x(t_P, x, system, just_eigvals=False): """ computes the eigenvalues of system for the single sample in q. x must have the form [R0, I0, R1, I1, R2, I2, R3, I3, ...] returns a list of eigenvalues and eigenvectors this is a linearization of the evolution of two infinitesimally close neighboring trajectories, one of which is currently at the point {q} """ network = system.network Nm = len(network) M = np.zeros((2*Nm, 2*Nm)) # holder for matrix we diagonalize t = t_P*system.Porb ### build matrix for modeNo in range(Nm): wo, yo, _ = network.wyU[modeNo] ro_ind = 2*modeNo io_ind = ro_ind+1 # diagonal 2x2 matrix M[ro_ind][ro_ind] = -yo M[ro_ind][io_ind] = wo M[io_ind][ro_ind] = -wo M[io_ind][io_ind] = -yo # off-diagonal elements for i,j,k in network.K[modeNo]: if i == j: wi = network.modes[i].w phs = (wo + 2*wi)*t cosW = np.cos(phs) sinW = np.sin(phs) ri_ind = 2*i ii_ind = ri_ind+1 ri = x[ri_ind] ii = x[ii_ind] M[ro_ind][ri_ind] = 2*wo*k*(cosW*ii - sinW*ri) M[ro_ind][ii_ind] = 2*wo*k*(cosW*ri + sinW*ii) M[io_ind][ri_ind] = 2*wo*k*(cosW*ri + sinW*ii) M[io_ind][ii_ind] = 2*wo*k*(cosW*ii + sinW*ri) else: # i != j wi = network.modes[i].w wj = network.modes[j].w phs = (wo+wi+wj)*t cosW = np.cos(phs) sinW = np.sin(phs) ri_ind = 2*i ii_ind = ri_ind+1 ri = x[ri_ind] ii = x[ii_ind] rj_ind = 2*j ij_ind = rj_ind+1 rj = x[rj_ind] ij = x[ij_ind] M[ro_ind][ri_ind] = 2*wo*k*(cosW*ij - sinW*rj) M[ro_ind][ii_ind] = 2*wo*k*(cosW*rj + sinW*ij) M[io_ind][ri_ind] = 2*wo*k*(cosW*rj + sinW*ij) M[io_ind][ii_ind] = 2*wo*k*(cosW*ij + sinW*rj) M[ro_ind][rj_ind] = 2*wo*k*(cosW*ii - sinW*ri) M[ro_ind][ij_ind] = 2*wo*k*(cosW*ri + sinW*ii) M[io_ind][rj_ind] = 2*wo*k*(cosW*ri + sinW*ii) M[io_ind][ij_ind] = 2*wo*k*(cosW*ii + sinW*ri) ### diagonalize matrix. get eigenvalues, vectors if just_eigvals: return linalg.eigvals(M, overwrite_a=True) eigenvalues, eigenvectors = linalg.eig(M, overwrite_a=True) # overwrite_a=True may help performance, and I don't care about "a" at this point (a=M within the function) ### now, the eigenvectors may be complex, and we really want to return the corresponding real and imaginary parts of each mode (which are mixed into two complex numbers). We convert this by hand converted_eigenvectors = np.zeros((2*Nm, 2*Nm)) for vecNo in range(2*Nm): eigenvect = eigenvectors[:,vecNo] for modeNo in range(Nm): r = eigenvect[2*modeNo] i = eigenvect[2*modeNo+1] converted_eigenvectors[2*modeNo][vecNo] = np.real(r) - np.imag(i) converted_eigenvectors[2*modeNo+1][vecNo] = np.imag(r) + np.real(i) ### correct normalization converted_eigenvectors[:,vecNo] = converted_eigenvectors[:,vecNo]/sum(converted_eigenvectors[:,vecNo]**2)**0.5 return eigenvalues, converted_eigenvectors ################################################## def nmode_eig_q(q, system, max_eig=False, verbose=False): """ computes the eigenvalues of the sytem for each sample in q. assumes "q" is the integration variable Returns a list of eigenvalues and eigenvectors if max_eig: returns ONLY the eigenvalue/vector with max{Re{eigenvalue}} at each sample """ if verbose: import time eigvals = [] eigvecs = [] L = len(q[0]) for ind in range(L): if verbose: to = time.time() this_q = [] for Q in q: this_q += Q[ind] # add real and imagninary part for each mode to single list eigenvalues, eigenvectors = eig_q(this_q, system.network) if max_eig: ev = [(np.real(e), ev_ind) for ev_ind, e in enumerate(eigenvalues)] ev.sort(key=lambda l: l[0], reverse=True) max_ev_ind = ev[0][1] eigenvalues = eigenvalues[max_ev_ind] eigenvectors = eigenvectors[:,max_ev_ind] eigvals.append(eigenvalues) eigvecs.append(eigenvectors) if verbose: print "\t%d / %d\t%f" % (ind+1, L, time.time()-to) return eigvals, eigvecs ################################################## def nmode_eig_x(t_P, x, system, max_eig=False, verbose=False): """ computes the eigenvalues of the sytem for each sample in x. assumes "x" is the integration variable Returns a list of eigenvalues and eigenvectors if max_eig: returns ONLY the eigenvalue/vector with max{Re{eigenvalue}} at each sample """ if verbose: import time Porb = system.Porb network = system.network Nm = len(system.network) eigvals = [] eigvecs = [] L = len(t_P) for ind in range(L): if verbose: to = time.time() t = t_P[ind]*Porb this_x = [] for modeNo in range(Nm): this_x += x[modeNo][ind] eigenvalues, eigenvectors = eig_x(t_P[ind], this_x, system) if max_eig: ev = [(np.real(e), ev) for ev, e in enumerate(eigenvalues)] ev.sort(key=lambda l: l[0], reverse=True) max_ev_ind = ev[0][1] eigenvalues = eigenvalues[max_ev_ind] eigenvectors = eigenvectors[:,max_ev_ind] eigvals.append(eigenvalues) eigvecs.append(eigenvectors) if verbose: print "\t%d / %d\t%f" % (ind+1, L, time.time()-to) return eigvals, eigvecs ################################################## def nmode_eigval_q(q, system, max_eig=False, verbose=False): """ computes the eigenvalues of the sytem for each sample in q. assumes "q" is the integration variable Returns a list of eigenvalues if max_eig: returns ONLY the eigenvalue/vector with max{Re{eigenvalue}} at each sample """ if verbose: import time eigvals = [] L = len(q[0]) for ind in range(L): if verbose: to = time.time() this_q = [] for Q in q: this_q += Q[ind] eigenvalues = eig_q(this_q, system.network, just_eigvals=True) if max_eig: ev = [(np.real(e), ev_ind) for ev_ind, e in enumerate(eigenvalues)] ev.sort(key=lambda l: l[0], reverse=True) max_ev_ind = ev[0][1] eigenvalues = eigenvalues[max_ev_ind] eigvals.append(eigenvalues) if verbose: print "\t%d / %d\t%f" % (ind+1, L, time.time()-to) return eigvals ################################################## def nmode_eigval_x(t_P, x, system, max_eig=False, verbose=False): """ computes the eigenvalues of the sytem for each sample in x. assumes "x" is the integration variable Returns a list of eigenvalues if max_eig: returns ONLY the eigenvalue/vector with max{Re{eigenvalue}} at each sample """ if verbose: import time eigvals = [] L = len(t_P) for ind in range(L): if verbose: to = time.time() this_x = [] for X in x: this_x += X[ind] eigenvalues = eig_x(t_P[ind], this_x, system, just_eigvals=True) if max_eig: ev = [(np.real(e), ev_ind) for ev_ind, e in enumerate(eigenvalues)] ev.sort(key=lambda l: l[0], reverse=True) max_ev_ind = ev[0][1] eigenvalues = eigenvalues[max_ev_ind] eigvals.append(eigenvalues) if verbose: print "\t%d / %d\t%f" % (ind+1, L, time.time()-to) return eigvals ################################################## def eig_plot(t_P, vals, vecs1, vecs2, system, cmap=plt.cm.jet): """ generates a plot showing the evolution of a single eigenvalue and corresponding eigenvector over time (given as inputs) plots the amplitude and phase of each mode vals must be an array: size (len(t_P)) vecs1 must be an array: size (len(t_P), N_m) vecs2 must be an array: size (len(t_P), N_m) """ Nm = len(vecs1[0]) fig = plt.figure() ax1 = fig.add_axes([0.15, 0.75, 0.70, 0.2]) ax1p = ax1.twinx() ax2 = fig.add_axes([0.15, 0.45, 0.70, 0.275]) ax2_cb = fig.add_axes([0.855, 0.45, 0.020, 0.275]) ax3 = fig.add_axes([0.15, 0.15, 0.70, 0.275]) ax3_cb = fig.add_axes([0.855, 0.15, 0.020, 0.275]) # plot eigenvalue time series ax1.plot(t_P, np.real(vals)*system.Porb, color='b') ax1p.plot(t_P, np.imag(vals)/system.Oorb, color='g') plt.setp(ax1.get_xticklabels(), visible=False) # plot eigenvector surface plot ### vecs1 cmap_min = np.floor(round(np.amin(vecs1[vecs1>-np.infty]),5)) cmap_max = np.ceil(round(np.amax(vecs1[vecs1<np.infty]),5)) cmap_norm=matplotlib.colors.Normalize(vmin=cmap_min, vmax=cmap_max) vec_plot(ax2, vecs1, t_P, cmap=cmap, cmap_norm=cmap_norm) cb2 = matplotlib.colorbar.ColorbarBase(ax2_cb, cmap=cmap, norm=cmap_norm, orientation='vertical') plt.setp(ax2.get_xticklabels(), visible=False) ### vecs2 cmap_min = np.floor(round(np.amin(vecs2[vecs2>-np.infty]),5)) cmap_max = np.ceil(round(np.amax(vecs2[vecs2<np.infty]),5)) cmap_norm = matplotlib.colors.Normalize(vmin=cmap_min, vmax=cmap_max) vec_plot(ax3, vecs2, t_P, cmap=cmap, cmap_norm=cmap_norm) cb3 = matplotlib.colorbar.ColorbarBase(ax3_cb, cmap=cmap, norm=cmap_norm, orientation='vertical') ax1.set_ylabel(r"$\mathbb{R}\{s\} \cdot P_{\mathrm{orb}}$", color='b') ax1p.set_ylabel(r"$\mathbb{I}\{s\} / \Omega_{\mathrm{orb}}$", color='g') ax2.set_ylabel(r"mode No.") ax3.set_ylabel(r"mode No.") ax3.set_xlabel(r'$t/P_{\mathrm{orb}}$') return fig, [ax1,ax1p,ax2,ax3], [cb2, cb3] ######################### def vec_plot(ax, vecs, t_P, cmap=plt.cm.jet, cmap_norm=None): """ helper function for eig_plot that generates the proper checkerboard for vectors over time """ if not cmap_norm: cmap_norm = matplotlib.colors.Normalize(vmin=np.amin(vecs), vmax=np.amax(vecs)) return ax.imshow(np.transpose(vecs), cmap=cmap, norm=cmap_norm, interpolation='nearest', origin='lower', aspect='auto', extent=(t_P[0], t_P[-1],-0.5,len(vecs[0])-0.5) ) ################################################## def eigval_plot(t_P, eigvals, system): """ plots the trajectories of the eigenvalues in eigvals in the complex plane eigvals must be an array: size (len(t_P), N_m) eigvals will be sorted within this method """ fig = plt.figure() ax1 = plt.subplot(2,1,1) ax2 = plt.subplot(2,1,2) plt.subplots_adjust(hspace=0.05, wspace=0.05) eigenvalues = [[] for i in range(len(eigvals[0]))] # place holder # sort list of eigenvalues and form plotting arrays for evals in eigvals: e = list(evals[:]) e.sort(key=lambda l: np.imag(l), reverse=True) e.sort(key=lambda l: np.real(l), reverse=True) for ind, ee in enumerate(e): eigenvalues[ind].append(ee) for evals in eigenvalues: ax1.plot(t_P, np.real(evals)*system.Porb, alpha=0.5) ax2.plot(t_P, np.imag(evals)/system.Oorb, alpha=0.5) ax1.set_ylabel(r'$\mathbb{R}\{s\}\cdot P_{\mathrm{orb}}$') plt.setp(ax1.get_xticklabels(), visible=False) ax2.set_ylabel(r'$\mathbb{I}\{s\} / \Omega_{\mathrm{orb}}$') ax2.set_xlabel(r'$t/P_{\mathrm{orb}}$') return fig, ax1, ax2 ################################################## def growth_rates(t,q,system,current, verbose=False): """ computes the growth rates of the system at all times in sample. Does this by computing (dx/dt)/(x) or (dq/dt)/(q) as appropriate. Returns a list of complex numbers with len(list) = N_m for plotting, this is used in conjunction with real_imag_plot() """ if verbose: print "\tcomputing time derivatives" dqdt_P, N_m, N_p = _compute_time_derivatives(t,q,system,current) if verbose: print "\tcomputing growth rates" s = [] for modeNo in range(N_m): _q = q[modeNo] _dqdt_P = dqdt_P[modeNo] _s = [] for ind in range(N_p): r, i = _q[ind] dr, di = _dqdt_P[ind] A2 = r**2 + i**2 if A2 > 0: _s.append( [(r*dr + i*di)/A2, (r*di - i*dr)/(2*np.pi*A2)] ) # WARNING: different normalizations for real and imag parts else: # special case of zero divisor l = [] if (r*dr + i*di) > 0: l.append( abs(r*dr + i*di)/(r*dr + i*di)*np.infty ) else: l.append( 0 ) if (r*di - i*dr) > 0: l.append( abs(r*di - i*dr)/(r*di - i*dr)*np.inty ) else: l.append( 0 ) _s.append( l ) s.append( _s ) return s ################################################## def amp_growth_rates(t, q, system, current, verbose=False): """ computes the growth rates of the system at all times in sample. |dx/dt|/|x| , etc. """ if verbose: print "\tcomputing time derivatives" dqdt_P, N_m, N_p = _compute_time_derivatives(t,q,system,current) if verbose: print "\tcomputing growth rates" s = [] for modeNo in xrange(N_m): ### iterate through modes _q = q[modeNo] _dqdt_P = dqdt_P[modeNo] _s = [] for ind in xrange(N_p): ### iterate through time steps r, i = _q[ind] dr, di = _dqdt_P[ind] A2 = r**2 + i**2 AdA = r*dr + i*di if A2 > 0: _s.append( AdA/A2 ) elif AdA > 0: _s.append( abs(dA)/dA * np.infty ) else: _s.append( 0 ) s.append( _s ) return s ################################################## def analytic_amp_growth_rates(t, q, system, current, verbose=False): """ computes the expected growth rates assuming a single three-mode triple selecting the correct triple is not necessarily obvious... compute growth rate over all triples and then choose the maximum thereof (for each mode?) """ if verbose: print "\tcomputing coupling structure" gens, coups = system.network.gens() if verbose: print "\tcomputing 3mode frequencies" freqs = system.compute_3mode_freqs() q = np.array(q) N_m = len(q) N_p = len(t) s = np.empty((N_m, N_p)) for p in gens[0]: ### zero the parents s[p,:] = 0 if verbose: print "\tcomputing analytic growth rates (with assumptions...)" for ind in xrange(N_p): ### compute the children for gen, coup in zip(gens[1:], coups): ss = [(threemode_growth_rate( np.sum(q[p][ind]**2), system, freqs, p, d1, d2, k ), (p, d1, d2, k)) for p, d1, d2, k in coup] ss.sort(key=lambda l: l[0]) ### small to large for S, (p, d1, d2, k) in ss: ### iterate through, overwritting with larger S as needed s[d1][ind] = S s[d2][ind] = S return s*system.Porb ### def threemode_growth_rate( Eparent, system, freqs, p, d1, d2, k): """ computes expected growth rate for 3mode system """ O = freqs[p] wp, yp, Up = system.network.wyU[p] w1, y1, U1 = system.network.wyU[d1] w2, y2, U2 = system.network.wyU[d2] y1Py2 = y1+y2 y1My2 = y1-y2 d1Pd2 = O + w1 + w2 amp = ( ((y1My2)**2 - (d1Pd2)**2 + 16*w1*w2*k**2*Eparent)**2 + 4*(y1My2)**2 * (d1Pd2)**2 )**0.25 phs = 0.5*np.arctan( 2*(y1My2)*(d1Pd2) / ( y1Py2**2 - d1Pd2**2 + 16*w1*w2*k**2*Eparent ) ) ### NEED TO WORRY ABOUT THE QUADRANTS? return 0.5*(-y1Py2 + amp*np.cos(phs))
gpl-2.0
pv/scikit-learn
sklearn/metrics/pairwise.py
104
42995
# -*- coding: utf-8 -*- # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Robert Layton <robertlayton@gmail.com> # Andreas Mueller <amueller@ais.uni-bonn.de> # Philippe Gervais <philippe.gervais@inria.fr> # Lars Buitinck <larsmans@gmail.com> # Joel Nothman <joel.nothman@gmail.com> # License: BSD 3 clause import itertools import numpy as np from scipy.spatial import distance from scipy.sparse import csr_matrix from scipy.sparse import issparse from ..utils import check_array from ..utils import gen_even_slices from ..utils import gen_batches from ..utils.fixes import partial from ..utils.extmath import row_norms, safe_sparse_dot from ..preprocessing import normalize from ..externals.joblib import Parallel from ..externals.joblib import delayed from ..externals.joblib.parallel import cpu_count from .pairwise_fast import _chi2_kernel_fast, _sparse_manhattan # Utility Functions def _return_float_dtype(X, Y): """ 1. If dtype of X and Y is float32, then dtype float32 is returned. 2. Else dtype float is returned. """ if not issparse(X) and not isinstance(X, np.ndarray): X = np.asarray(X) if Y is None: Y_dtype = X.dtype elif not issparse(Y) and not isinstance(Y, np.ndarray): Y = np.asarray(Y) Y_dtype = Y.dtype else: Y_dtype = Y.dtype if X.dtype == Y_dtype == np.float32: dtype = np.float32 else: dtype = np.float return X, Y, dtype def check_pairwise_arrays(X, Y): """ Set X and Y appropriately and checks inputs If Y is None, it is set as a pointer to X (i.e. not a copy). If Y is given, this does not happen. All distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the second dimension of the two arrays is equal. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples_a, n_features) Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) Returns ------- safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ X, Y, dtype = _return_float_dtype(X, Y) if Y is X or Y is None: X = Y = check_array(X, accept_sparse='csr', dtype=dtype) else: X = check_array(X, accept_sparse='csr', dtype=dtype) Y = check_array(Y, accept_sparse='csr', dtype=dtype) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices: " "X.shape[1] == %d while Y.shape[1] == %d" % ( X.shape[1], Y.shape[1])) return X, Y def check_paired_arrays(X, Y): """ Set X and Y appropriately and checks inputs for paired distances All paired distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the dimensions of the two arrays are equal. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples_a, n_features) Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) Returns ------- safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ X, Y = check_pairwise_arrays(X, Y) if X.shape != Y.shape: raise ValueError("X and Y should be of same shape. They were " "respectively %r and %r long." % (X.shape, Y.shape)) return X, Y # Pairwise distances def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. For efficiency reasons, the euclidean distance between a pair of row vector x and y is computed as:: dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) This formulation has two advantages over other ways of computing distances. First, it is computationally efficient when dealing with sparse data. Second, if x varies but y remains unchanged, then the right-most dot product `dot(y, y)` can be pre-computed. However, this is not the most precise way of doing this computation, and the distance matrix returned by this function may not be exactly symmetric as required by, e.g., ``scipy.spatial.distance`` functions. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples_1, n_features) Y : {array-like, sparse matrix}, shape (n_samples_2, n_features) Y_norm_squared : array-like, shape (n_samples_2, ), optional Pre-computed dot-products of vectors in Y (e.g., ``(Y**2).sum(axis=1)``) squared : boolean, optional Return squared Euclidean distances. Returns ------- distances : {array, sparse matrix}, shape (n_samples_1, n_samples_2) Examples -------- >>> from sklearn.metrics.pairwise import euclidean_distances >>> X = [[0, 1], [1, 1]] >>> # distance between rows of X >>> euclidean_distances(X, X) array([[ 0., 1.], [ 1., 0.]]) >>> # get distance to origin >>> euclidean_distances(X, [[0, 0]]) array([[ 1. ], [ 1.41421356]]) See also -------- paired_distances : distances betweens pairs of elements of X and Y. """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. X, Y = check_pairwise_arrays(X, Y) if Y_norm_squared is not None: YY = check_array(Y_norm_squared) if YY.shape != (1, Y.shape[0]): raise ValueError( "Incompatible dimensions for Y and Y_norm_squared") else: YY = row_norms(Y, squared=True)[np.newaxis, :] if X is Y: # shortcut in the common case euclidean_distances(X, X) XX = YY.T else: XX = row_norms(X, squared=True)[:, np.newaxis] distances = safe_sparse_dot(X, Y.T, dense_output=True) distances *= -2 distances += XX distances += YY np.maximum(distances, 0, out=distances) if X is Y: # Ensure that distances between vectors and themselves are set to 0.0. # This may not be the case due to floating point rounding errors. distances.flat[::distances.shape[0] + 1] = 0.0 return distances if squared else np.sqrt(distances, out=distances) def pairwise_distances_argmin_min(X, Y, axis=1, metric="euclidean", batch_size=500, metric_kwargs=None): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). The minimal distances are also returned. This is mostly equivalent to calling: (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis), pairwise_distances(X, Y=Y, metric=metric).min(axis=axis)) but uses much less memory, and is faster for large arrays. Parameters ---------- X, Y : {array-like, sparse matrix} Arrays containing points. Respective shapes (n_samples1, n_features) and (n_samples2, n_features) batch_size : integer To reduce memory consumption over the naive solution, data are processed in batches, comprising batch_size rows of X and batch_size rows of Y. The default value is quite conservative, but can be changed for fine-tuning. The larger the number, the larger the memory usage. metric : string or callable, default 'euclidean' metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. metric_kwargs : dict, optional Keyword arguments to pass to specified metric function. axis : int, optional, default 1 Axis along which the argmin and distances are to be computed. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. distances : numpy.ndarray distances[i] is the distance between the i-th row in X and the argmin[i]-th row in Y. See also -------- sklearn.metrics.pairwise_distances sklearn.metrics.pairwise_distances_argmin """ dist_func = None if metric in PAIRWISE_DISTANCE_FUNCTIONS: dist_func = PAIRWISE_DISTANCE_FUNCTIONS[metric] elif not callable(metric) and not isinstance(metric, str): raise ValueError("'metric' must be a string or a callable") X, Y = check_pairwise_arrays(X, Y) if metric_kwargs is None: metric_kwargs = {} if axis == 0: X, Y = Y, X # Allocate output arrays indices = np.empty(X.shape[0], dtype=np.intp) values = np.empty(X.shape[0]) values.fill(np.infty) for chunk_x in gen_batches(X.shape[0], batch_size): X_chunk = X[chunk_x, :] for chunk_y in gen_batches(Y.shape[0], batch_size): Y_chunk = Y[chunk_y, :] if dist_func is not None: if metric == 'euclidean': # special case, for speed d_chunk = safe_sparse_dot(X_chunk, Y_chunk.T, dense_output=True) d_chunk *= -2 d_chunk += row_norms(X_chunk, squared=True)[:, np.newaxis] d_chunk += row_norms(Y_chunk, squared=True)[np.newaxis, :] np.maximum(d_chunk, 0, d_chunk) else: d_chunk = dist_func(X_chunk, Y_chunk, **metric_kwargs) else: d_chunk = pairwise_distances(X_chunk, Y_chunk, metric=metric, **metric_kwargs) # Update indices and minimum values using chunk min_indices = d_chunk.argmin(axis=1) min_values = d_chunk[np.arange(chunk_x.stop - chunk_x.start), min_indices] flags = values[chunk_x] > min_values indices[chunk_x][flags] = min_indices[flags] + chunk_y.start values[chunk_x][flags] = min_values[flags] if metric == "euclidean" and not metric_kwargs.get("squared", False): np.sqrt(values, values) return indices, values def pairwise_distances_argmin(X, Y, axis=1, metric="euclidean", batch_size=500, metric_kwargs=None): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). This is mostly equivalent to calling: pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) but uses much less memory, and is faster for large arrays. This function works with dense 2D arrays only. Parameters ---------- X : array-like Arrays containing points. Respective shapes (n_samples1, n_features) and (n_samples2, n_features) Y : array-like Arrays containing points. Respective shapes (n_samples1, n_features) and (n_samples2, n_features) batch_size : integer To reduce memory consumption over the naive solution, data are processed in batches, comprising batch_size rows of X and batch_size rows of Y. The default value is quite conservative, but can be changed for fine-tuning. The larger the number, the larger the memory usage. metric : string or callable metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. metric_kwargs : dict keyword arguments to pass to specified metric function. axis : int, optional, default 1 Axis along which the argmin and distances are to be computed. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. See also -------- sklearn.metrics.pairwise_distances sklearn.metrics.pairwise_distances_argmin_min """ if metric_kwargs is None: metric_kwargs = {} return pairwise_distances_argmin_min(X, Y, axis, metric, batch_size, metric_kwargs)[0] def manhattan_distances(X, Y=None, sum_over_features=True, size_threshold=5e8): """ Compute the L1 distances between the vectors in X and Y. With sum_over_features equal to False it returns the componentwise distances. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array_like An array with shape (n_samples_X, n_features). Y : array_like, optional An array with shape (n_samples_Y, n_features). sum_over_features : bool, default=True If True the function returns the pairwise distance matrix else it returns the componentwise L1 pairwise-distances. Not supported for sparse matrix inputs. size_threshold : int, default=5e8 Unused parameter. Returns ------- D : array If sum_over_features is False shape is (n_samples_X * n_samples_Y, n_features) and D contains the componentwise L1 pairwise-distances (ie. absolute difference), else shape is (n_samples_X, n_samples_Y) and D contains the pairwise L1 distances. Examples -------- >>> from sklearn.metrics.pairwise import manhattan_distances >>> manhattan_distances(3, 3)#doctest:+ELLIPSIS array([[ 0.]]) >>> manhattan_distances(3, 2)#doctest:+ELLIPSIS array([[ 1.]]) >>> manhattan_distances(2, 3)#doctest:+ELLIPSIS array([[ 1.]]) >>> manhattan_distances([[1, 2], [3, 4]],\ [[1, 2], [0, 3]])#doctest:+ELLIPSIS array([[ 0., 2.], [ 4., 4.]]) >>> import numpy as np >>> X = np.ones((1, 2)) >>> y = 2 * np.ones((2, 2)) >>> manhattan_distances(X, y, sum_over_features=False)#doctest:+ELLIPSIS array([[ 1., 1.], [ 1., 1.]]...) """ X, Y = check_pairwise_arrays(X, Y) if issparse(X) or issparse(Y): if not sum_over_features: raise TypeError("sum_over_features=%r not supported" " for sparse matrices" % sum_over_features) X = csr_matrix(X, copy=False) Y = csr_matrix(Y, copy=False) D = np.zeros((X.shape[0], Y.shape[0])) _sparse_manhattan(X.data, X.indices, X.indptr, Y.data, Y.indices, Y.indptr, X.shape[1], D) return D if sum_over_features: return distance.cdist(X, Y, 'cityblock') D = X[:, np.newaxis, :] - Y[np.newaxis, :, :] D = np.abs(D, D) return D.reshape((-1, X.shape[1])) def cosine_distances(X, Y=None): """ Compute cosine distance between samples in X and Y. Cosine distance is defined as 1.0 minus the cosine similarity. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array_like, sparse matrix with shape (n_samples_X, n_features). Y : array_like, sparse matrix (optional) with shape (n_samples_Y, n_features). Returns ------- distance matrix : array An array with shape (n_samples_X, n_samples_Y). See also -------- sklearn.metrics.pairwise.cosine_similarity scipy.spatial.distance.cosine (dense matrices only) """ # 1.0 - cosine_similarity(X, Y) without copy S = cosine_similarity(X, Y) S *= -1 S += 1 return S # Paired distances def paired_euclidean_distances(X, Y): """ Computes the paired euclidean distances between X and Y Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array-like, shape (n_samples, n_features) Y : array-like, shape (n_samples, n_features) Returns ------- distances : ndarray (n_samples, ) """ X, Y = check_paired_arrays(X, Y) return row_norms(X - Y) def paired_manhattan_distances(X, Y): """Compute the L1 distances between the vectors in X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array-like, shape (n_samples, n_features) Y : array-like, shape (n_samples, n_features) Returns ------- distances : ndarray (n_samples, ) """ X, Y = check_paired_arrays(X, Y) diff = X - Y if issparse(diff): diff.data = np.abs(diff.data) return np.squeeze(np.array(diff.sum(axis=1))) else: return np.abs(diff).sum(axis=-1) def paired_cosine_distances(X, Y): """ Computes the paired cosine distances between X and Y Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array-like, shape (n_samples, n_features) Y : array-like, shape (n_samples, n_features) Returns ------- distances : ndarray, shape (n_samples, ) Notes ------ The cosine distance is equivalent to the half the squared euclidean distance if each sample is normalized to unit norm """ X, Y = check_paired_arrays(X, Y) return .5 * row_norms(normalize(X) - normalize(Y), squared=True) PAIRED_DISTANCES = { 'cosine': paired_cosine_distances, 'euclidean': paired_euclidean_distances, 'l2': paired_euclidean_distances, 'l1': paired_manhattan_distances, 'manhattan': paired_manhattan_distances, 'cityblock': paired_manhattan_distances} def paired_distances(X, Y, metric="euclidean", **kwds): """ Computes the paired distances between X and Y. Computes the distances between (X[0], Y[0]), (X[1], Y[1]), etc... Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : ndarray (n_samples, n_features) Array 1 for distance computation. Y : ndarray (n_samples, n_features) Array 2 for distance computation. metric : string or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options specified in PAIRED_DISTANCES, including "euclidean", "manhattan", or "cosine". Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. Returns ------- distances : ndarray (n_samples, ) Examples -------- >>> from sklearn.metrics.pairwise import paired_distances >>> X = [[0, 1], [1, 1]] >>> Y = [[0, 1], [2, 1]] >>> paired_distances(X, Y) array([ 0., 1.]) See also -------- pairwise_distances : pairwise distances. """ if metric in PAIRED_DISTANCES: func = PAIRED_DISTANCES[metric] return func(X, Y) elif callable(metric): # Check the matrix first (it is usually done by the metric) X, Y = check_paired_arrays(X, Y) distances = np.zeros(len(X)) for i in range(len(X)): distances[i] = metric(X[i], Y[i]) return distances else: raise ValueError('Unknown distance %s' % metric) # Kernels def linear_kernel(X, Y=None): """ Compute the linear kernel between X and Y. Read more in the :ref:`User Guide <linear_kernel>`. Parameters ---------- X : array of shape (n_samples_1, n_features) Y : array of shape (n_samples_2, n_features) Returns ------- Gram matrix : array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) return safe_sparse_dot(X, Y.T, dense_output=True) def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1): """ Compute the polynomial kernel between X and Y:: K(X, Y) = (gamma <X, Y> + coef0)^degree Read more in the :ref:`User Guide <polynomial_kernel>`. Parameters ---------- X : ndarray of shape (n_samples_1, n_features) Y : ndarray of shape (n_samples_2, n_features) coef0 : int, default 1 degree : int, default 3 Returns ------- Gram matrix : array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = safe_sparse_dot(X, Y.T, dense_output=True) K *= gamma K += coef0 K **= degree return K def sigmoid_kernel(X, Y=None, gamma=None, coef0=1): """ Compute the sigmoid kernel between X and Y:: K(X, Y) = tanh(gamma <X, Y> + coef0) Read more in the :ref:`User Guide <sigmoid_kernel>`. Parameters ---------- X : ndarray of shape (n_samples_1, n_features) Y : ndarray of shape (n_samples_2, n_features) coef0 : int, default 1 Returns ------- Gram matrix: array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = safe_sparse_dot(X, Y.T, dense_output=True) K *= gamma K += coef0 np.tanh(K, K) # compute tanh in-place return K def rbf_kernel(X, Y=None, gamma=None): """ Compute the rbf (gaussian) kernel between X and Y:: K(x, y) = exp(-gamma ||x-y||^2) for each pair of rows x in X and y in Y. Read more in the :ref:`User Guide <rbf_kernel>`. Parameters ---------- X : array of shape (n_samples_X, n_features) Y : array of shape (n_samples_Y, n_features) gamma : float Returns ------- kernel_matrix : array of shape (n_samples_X, n_samples_Y) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = euclidean_distances(X, Y, squared=True) K *= -gamma np.exp(K, K) # exponentiate K in-place return K def cosine_similarity(X, Y=None, dense_output=True): """Compute cosine similarity between samples in X and Y. Cosine similarity, or the cosine kernel, computes similarity as the normalized dot product of X and Y: K(X, Y) = <X, Y> / (||X||*||Y||) On L2-normalized data, this function is equivalent to linear_kernel. Read more in the :ref:`User Guide <cosine_similarity>`. Parameters ---------- X : ndarray or sparse array, shape: (n_samples_X, n_features) Input data. Y : ndarray or sparse array, shape: (n_samples_Y, n_features) Input data. If ``None``, the output will be the pairwise similarities between all samples in ``X``. dense_output : boolean (optional), default True Whether to return dense output even when the input is sparse. If ``False``, the output is sparse if both input arrays are sparse. Returns ------- kernel matrix : array An array with shape (n_samples_X, n_samples_Y). """ # to avoid recursive import X, Y = check_pairwise_arrays(X, Y) X_normalized = normalize(X, copy=True) if X is Y: Y_normalized = X_normalized else: Y_normalized = normalize(Y, copy=True) K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output) return K def additive_chi2_kernel(X, Y=None): """Computes the additive chi-squared kernel between observations in X and Y The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by:: k(x, y) = -Sum [(x - y)^2 / (x + y)] It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Notes ----- As the negative of a distance, this kernel is only conditionally positive definite. Parameters ---------- X : array-like of shape (n_samples_X, n_features) Y : array of shape (n_samples_Y, n_features) Returns ------- kernel_matrix : array of shape (n_samples_X, n_samples_Y) References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf See also -------- chi2_kernel : The exponentiated version of the kernel, which is usually preferable. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to this kernel. """ if issparse(X) or issparse(Y): raise ValueError("additive_chi2 does not support sparse matrices.") X, Y = check_pairwise_arrays(X, Y) if (X < 0).any(): raise ValueError("X contains negative values.") if Y is not X and (Y < 0).any(): raise ValueError("Y contains negative values.") result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype) _chi2_kernel_fast(X, Y, result) return result def chi2_kernel(X, Y=None, gamma=1.): """Computes the exponential chi-squared kernel X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by:: k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)]) It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Parameters ---------- X : array-like of shape (n_samples_X, n_features) Y : array of shape (n_samples_Y, n_features) gamma : float, default=1. Scaling parameter of the chi2 kernel. Returns ------- kernel_matrix : array of shape (n_samples_X, n_samples_Y) References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf See also -------- additive_chi2_kernel : The additive version of this kernel sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to the additive version of this kernel. """ K = additive_chi2_kernel(X, Y) K *= gamma return np.exp(K, K) # Helper functions - distance PAIRWISE_DISTANCE_FUNCTIONS = { # If updating this dictionary, update the doc in both distance_metrics() # and also in pairwise_distances()! 'cityblock': manhattan_distances, 'cosine': cosine_distances, 'euclidean': euclidean_distances, 'l2': euclidean_distances, 'l1': manhattan_distances, 'manhattan': manhattan_distances, } def distance_metrics(): """Valid metrics for pairwise_distances. This function simply returns the valid pairwise distance metrics. It exists to allow for a description of the mapping for each of the valid strings. The valid distance metrics, and the function they map to, are: ============ ==================================== metric Function ============ ==================================== 'cityblock' metrics.pairwise.manhattan_distances 'cosine' metrics.pairwise.cosine_distances 'euclidean' metrics.pairwise.euclidean_distances 'l1' metrics.pairwise.manhattan_distances 'l2' metrics.pairwise.euclidean_distances 'manhattan' metrics.pairwise.manhattan_distances ============ ==================================== Read more in the :ref:`User Guide <metrics>`. """ return PAIRWISE_DISTANCE_FUNCTIONS def _parallel_pairwise(X, Y, func, n_jobs, **kwds): """Break the pairwise matrix in n_jobs even slices and compute them in parallel""" if n_jobs < 0: n_jobs = max(cpu_count() + 1 + n_jobs, 1) if Y is None: Y = X if n_jobs == 1: # Special case to avoid picklability checks in delayed return func(X, Y, **kwds) # TODO: in some cases, backend='threading' may be appropriate fd = delayed(func) ret = Parallel(n_jobs=n_jobs, verbose=0)( fd(X, Y[s], **kwds) for s in gen_even_slices(Y.shape[0], n_jobs)) return np.hstack(ret) def _pairwise_callable(X, Y, metric, **kwds): """Handle the callable case for pairwise_{distances,kernels} """ X, Y = check_pairwise_arrays(X, Y) if X is Y: # Only calculate metric for upper triangle out = np.zeros((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.combinations(range(X.shape[0]), 2) for i, j in iterator: out[i, j] = metric(X[i], Y[j], **kwds) # Make symmetric # NB: out += out.T will produce incorrect results out = out + out.T # Calculate diagonal # NB: nonzero diagonals are allowed for both metrics and kernels for i in range(X.shape[0]): x = X[i] out[i, i] = metric(x, x, **kwds) else: # Calculate all cells out = np.empty((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) for i, j in iterator: out[i, j] = metric(X[i], Y[j], **kwds) return out _VALID_METRICS = ['euclidean', 'l2', 'l1', 'manhattan', 'cityblock', 'braycurtis', 'canberra', 'chebyshev', 'correlation', 'cosine', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule', "wminkowski"] def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds): """ Compute the distance matrix from a vector array X and optional Y. This method takes either a vector array or a distance matrix, and returns a distance matrix. If the input is a vector array, the distances are computed. If the input is a distances matrix, it is returned instead. This method provides a safe way to take a distance matrix as input, while preserving compatibility with many other algorithms that take a vector array. If Y is given (default is None), then the returned matrix is the pairwise distance between the arrays from both X and Y. Valid values for metric are: - From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan']. These metrics support sparse matrix inputs. - From scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. These metrics do not support sparse matrix inputs. Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are valid scipy.spatial.distance metrics), the scikit-learn implementation will be used, which is faster and has support for sparse matrices (except for 'cityblock'). For a verbose description of the metrics from scikit-learn, see the __doc__ of the sklearn.pairwise.distance_metrics function. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. Y : array [n_samples_b, n_features], optional An optional second feature array. Only allowed if metric != "precomputed". metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by scipy.spatial.distance.pdist for its metric parameter, or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. If metric is "precomputed", X is assumed to be a distance matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. n_jobs : int The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- D : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b] A distance matrix D such that D_{i, j} is the distance between the ith and jth vectors of the given matrix X, if Y is None. If Y is not None, then D_{i, j} is the distance between the ith array from X and the jth array from Y. """ if (metric not in _VALID_METRICS and not callable(metric) and metric != "precomputed"): raise ValueError("Unknown metric %s. " "Valid metrics are %s, or 'precomputed', or a " "callable" % (metric, _VALID_METRICS)) if metric == "precomputed": return X elif metric in PAIRWISE_DISTANCE_FUNCTIONS: func = PAIRWISE_DISTANCE_FUNCTIONS[metric] elif callable(metric): func = partial(_pairwise_callable, metric=metric, **kwds) else: if issparse(X) or issparse(Y): raise TypeError("scipy distance metrics do not" " support sparse matrices.") X, Y = check_pairwise_arrays(X, Y) if n_jobs == 1 and X is Y: return distance.squareform(distance.pdist(X, metric=metric, **kwds)) func = partial(distance.cdist, metric=metric, **kwds) return _parallel_pairwise(X, Y, func, n_jobs, **kwds) # Helper functions - distance PAIRWISE_KERNEL_FUNCTIONS = { # If updating this dictionary, update the doc in both distance_metrics() # and also in pairwise_distances()! 'additive_chi2': additive_chi2_kernel, 'chi2': chi2_kernel, 'linear': linear_kernel, 'polynomial': polynomial_kernel, 'poly': polynomial_kernel, 'rbf': rbf_kernel, 'sigmoid': sigmoid_kernel, 'cosine': cosine_similarity, } def kernel_metrics(): """ Valid metrics for pairwise_kernels This function simply returns the valid pairwise distance metrics. It exists, however, to allow for a verbose description of the mapping for each of the valid strings. The valid distance metrics, and the function they map to, are: =============== ======================================== metric Function =============== ======================================== 'additive_chi2' sklearn.pairwise.additive_chi2_kernel 'chi2' sklearn.pairwise.chi2_kernel 'linear' sklearn.pairwise.linear_kernel 'poly' sklearn.pairwise.polynomial_kernel 'polynomial' sklearn.pairwise.polynomial_kernel 'rbf' sklearn.pairwise.rbf_kernel 'sigmoid' sklearn.pairwise.sigmoid_kernel 'cosine' sklearn.pairwise.cosine_similarity =============== ======================================== Read more in the :ref:`User Guide <metrics>`. """ return PAIRWISE_KERNEL_FUNCTIONS KERNEL_PARAMS = { "additive_chi2": (), "chi2": (), "cosine": (), "exp_chi2": frozenset(["gamma"]), "linear": (), "poly": frozenset(["gamma", "degree", "coef0"]), "polynomial": frozenset(["gamma", "degree", "coef0"]), "rbf": frozenset(["gamma"]), "sigmoid": frozenset(["gamma", "coef0"]), } def pairwise_kernels(X, Y=None, metric="linear", filter_params=False, n_jobs=1, **kwds): """Compute the kernel between arrays X and optional array Y. This method takes either a vector array or a kernel matrix, and returns a kernel matrix. If the input is a vector array, the kernels are computed. If the input is a kernel matrix, it is returned instead. This method provides a safe way to take a kernel matrix as input, while preserving compatibility with many other algorithms that take a vector array. If Y is given (default is None), then the returned matrix is the pairwise kernel between the arrays from both X and Y. Valid values for metric are:: ['rbf', 'sigmoid', 'polynomial', 'poly', 'linear', 'cosine'] Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise kernels between samples, or a feature array. Y : array [n_samples_b, n_features] A second feature array only if X has shape [n_samples_a, n_features]. metric : string, or callable The metric to use when calculating kernel between instances in a feature array. If metric is a string, it must be one of the metrics in pairwise.PAIRWISE_KERNEL_FUNCTIONS. If metric is "precomputed", X is assumed to be a kernel matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. n_jobs : int The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. filter_params: boolean Whether to filter invalid parameters or not. `**kwds` : optional keyword parameters Any further parameters are passed directly to the kernel function. Returns ------- K : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b] A kernel matrix K such that K_{i, j} is the kernel between the ith and jth vectors of the given matrix X, if Y is None. If Y is not None, then K_{i, j} is the kernel between the ith array from X and the jth array from Y. Notes ----- If metric is 'precomputed', Y is ignored and X is returned. """ if metric == "precomputed": return X elif metric in PAIRWISE_KERNEL_FUNCTIONS: if filter_params: kwds = dict((k, kwds[k]) for k in kwds if k in KERNEL_PARAMS[metric]) func = PAIRWISE_KERNEL_FUNCTIONS[metric] elif callable(metric): func = partial(_pairwise_callable, metric=metric, **kwds) else: raise ValueError("Unknown kernel %r" % metric) return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
bsd-3-clause
nashmit/GMolModel
tests_inputs/lin_bead.py
2
6158
import sys, os, glob import numpy as np import scipy import scipy.stats import argparse import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter parser = argparse.ArgumentParser() parser.add_argument('--dir', default=None, help='Directory with input data files') parser.add_argument('--inFNRoots', default=None, nargs='+', help='Name root for first input data files') parser.add_argument('--skiprows', default=300, type=int, help='# of lines to be skipped by numpy.loadtxt') parser.add_argument('--nbins', default=50, type=int, help='Number of bins for histograms. Default for 7.2 spacing') parser.add_argument('--xmin', default=-180, type=float, help='Minimum x value for histograms') parser.add_argument('--xmax', default=180, type=float, help='Maximum x value for histograms') parser.add_argument('--makehist', action='store_true', default=False, help='Make histogram') parser.add_argument('--printhist', action='store_true', default=False, help='Make histogram') parser.add_argument('--makeplot', action='store_true', default=False, help='Make histogram plot') parser.add_argument('--minmax', action='store_true', default=False, help='Print min and max') parser.add_argument('--moments', action='store_true', default=False, help='Print average and standard deviation') args = parser.parse_args() import genfuncs # Additional data flex_expect_rho = np.array([(1.0/360.0) for i in range(args.nbins)]) # General plot parameters if args.makeplot: matplotlib.rc('font',**{\ 'family':'serif',\ 'serif':['Computer Modern Roman'], \ 'size':8}) # EU mod matplotlib.rc('text', usetex=True) fig_width = 3.36 # One-column figure fig_width2 = 6.68 # Two-column figure fig_height = 3.0 fignum = 1 plt.figure(num=fignum, figsize=(fig_width, fig_height), linewidth=3.0) #plt.subplots_adjust(left=0.15, right=0.95, bottom=0.2, top=0.95) plt.subplots_adjust(left=0.20, right=0.95, bottom=0.2, top=0.95) subtitle = 3 * [None] subtitle[0] = 'NO FIXMAN' subtitle[1] = 'CDHMC' subtitle[2] = 'MIXED' for ri in range(len(args.inFNRoots)): # Iterate through roots FNlist = glob.glob(os.path.join(args.dir, args.inFNRoots[ri] + '*')) nrounds = len(FNlist) num_lines = sum(1 for line in open(FNlist[0])) #hists = [] hists = np.zeros((nrounds, 2, args.nbins)) relHists = np.zeros((nrounds, 2, args.nbins)) print FNlist for li in range(nrounds): with open(FNlist[li], 'r') as in_FN1: alldata = np.loadtxt(in_FN1, skiprows=args.skiprows) print "alldata", alldata #col_size = int(np.ceil(alldata.shape[0]/2)) col_size = alldata.shape[0] col_size_1 = col_size - 1 col_size_2 = col_size - 2 # Get col col = np.zeros((col_size)) for ci in range(col_size): col[ci] = alldata[ci] #if alldata[ci] == 1: # Move accepted # col[ci] = alldata[ci] #else: # Move not accepted # col[ci] = alldata[ci] if args.minmax: print col.min(), col.max() if args.moments: mean = np.mean(col) var = np.var(col) print mean, var, scipy.stats.skew(col) , scipy.stats.kurtosis(col) # Histogram if args.makehist: h = np.histogram(col, bins=args.nbins, range=(args.xmin, args.xmax), density=True) hists[li][0] = h[0] hists[li][1] = h[1][:-1] #hists.append(np.histogram(col, bins=args.nbins, range=(args.xmin, args.xmax), density=True)) #print hists[li][1][i] + ((hists[li][1][i+1] - hists[li][1][i])/2), hists[li][0][i] #print "0", np.sum(hists[li][0]) #print "X Cnt" print 'hists', hists dx = (hists[0][1][1] - hists[0][1][0]) dx2 = (hists[0][1][1] - hists[0][1][0])/2 if args.makehist: # Get probabilties meanHist = np.zeros((args.nbins)) stdHist = np.zeros((args.nbins)) # Get mean of probabilities #if args.printhist: # print "X <P(X)>" #xticks = np.zeros((args.nbins)) #for li in range(nrounds): # for i in range(args.nbins): # meanHist[i] += hists[li][0][i] #for i in range(args.nbins): # meanHist[i] /= nrounds # #xticks[i] = hists[0][1][i] + ((hists[0][1][i+1] - hists[0][1][i])/2) # xticks[i] = hists[0][1][i] + dx2 # if args.printhist: # print xticks[i], meanHist[i] xticks = np.zeros((args.nbins)) for i in range(args.nbins): print 'hists[:, [0], [%d]]' % (i) , np.ravel(hists[:, [0], [i]]) meanHist[i] = np.mean(np.ravel(hists[:, [0], [i]])) stdHist[i] = np.std(np.ravel(hists[:, [0], [i]])) xticks[i] = hists[0][1][i] + dx2 print 'xticks', xticks print 'meanHist', meanHist print 'stdHist', stdHist # Plot if args.makeplot: ax = plt.subplot(len(args.inFNRoots), 1, ri+1) meanL = ax.errorbar(xticks, meanHist, color='#000000', yerr=stdHist, linewidth=1.0, \ capthick=0.5, capsize=1.0, elinewidth=0.5) flexL, = ax.plot(xticks, flex_expect_rho, 'r--', linewidth=1.0, color='#009900') #ax.legend([meanL, flexL], [args.inFNRoots[ri][0:5], 'Expected'], \ # loc=0, fontsize=6) plt.ylabel(r'$\mathrm{\rho(\phi)}$', fontsize=8) plt.xlim((-180, 180)) plt.ylim((0.0020, 0.0035)) if ri != 2: plt.xticks([]) else: plt.xticks(np.arange(-180, 181, 90)) ax.get_xaxis().set_ticklabels(np.arange(-180, 181, 90)) plt.setp(ax.get_xticklabels(), rotation='horizontal', fontsize=8) plt.xlabel(r'$\mathrm{\phi(degrees)}$', fontsize=8) plt.yticks(np.arange(0.0020, 0.0040, 0.0005)) yticklabels = ["%.4f"%(i) for i in np.arange(0.0020, 0.0040, 0.0005)] ax.get_yaxis().set_ticklabels(yticklabels) plt.setp(ax.get_yticklabels(), rotation='horizontal', fontsize=8) textrelhpos = 0.5 textrelvpos = 0.9 ax.text(textrelhpos, textrelvpos, subtitle[ri], transform=ax.transAxes, \ horizontalalignment='center', verticalalignment='top', \ fontsize=8) if args.makeplot: figFN = 'temp.pdf' plt.savefig(figFN, dpi=600, format='pdf')
gpl-3.0
kylerbrown/scikit-learn
sklearn/metrics/tests/test_score_objects.py
138
14048
import pickle import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_not_equal from sklearn.base import BaseEstimator from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score, log_loss, precision_score, recall_score) from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.scorer import (check_scoring, _PredictScorer, _passthrough_scorer) from sklearn.metrics import make_scorer, get_scorer, SCORERS from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from sklearn.cluster import KMeans from sklearn.dummy import DummyRegressor from sklearn.linear_model import Ridge, LogisticRegression from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.datasets import make_blobs from sklearn.datasets import make_classification from sklearn.datasets import make_multilabel_classification from sklearn.datasets import load_diabetes from sklearn.cross_validation import train_test_split, cross_val_score from sklearn.grid_search import GridSearchCV from sklearn.multiclass import OneVsRestClassifier REGRESSION_SCORERS = ['r2', 'mean_absolute_error', 'mean_squared_error', 'median_absolute_error'] CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro', 'roc_auc', 'average_precision', 'precision', 'precision_weighted', 'precision_macro', 'precision_micro', 'recall', 'recall_weighted', 'recall_macro', 'recall_micro', 'log_loss', 'adjusted_rand_score' # not really, but works ] MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples'] class EstimatorWithoutFit(object): """Dummy estimator to test check_scoring""" pass class EstimatorWithFit(BaseEstimator): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self class EstimatorWithFitAndScore(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self def score(self, X, y): return 1.0 class EstimatorWithFitAndPredict(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): self.y = y return self def predict(self, X): return self.y class DummyScorer(object): """Dummy scorer that always returns 1.""" def __call__(self, est, X, y): return 1 def test_check_scoring(): # Test all branches of check_scoring estimator = EstimatorWithoutFit() pattern = (r"estimator should a be an estimator implementing 'fit' method," r" .* was passed") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = check_scoring(estimator) assert_true(scorer is _passthrough_scorer) assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = (r"If no scoring is specified, the estimator passed should have" r" a 'score' method\. The estimator .* does not\.") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) scorer = check_scoring(estimator, "accuracy") assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFit() scorer = check_scoring(estimator, "accuracy") assert_true(isinstance(scorer, _PredictScorer)) estimator = EstimatorWithFit() scorer = check_scoring(estimator, allow_none=True) assert_true(scorer is None) def test_check_scoring_gridsearchcv(): # test that check_scoring works on GridSearchCV and pipeline. # slightly redundant non-regression test. grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]}) scorer = check_scoring(grid, "f1") assert_true(isinstance(scorer, _PredictScorer)) pipe = make_pipeline(LinearSVC()) scorer = check_scoring(pipe, "f1") assert_true(isinstance(scorer, _PredictScorer)) # check that cross_val_score definitely calls the scorer # and doesn't make any assumptions about the estimator apart from having a # fit. scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer()) assert_array_equal(scores, 1) def test_make_scorer(): # Sanity check on the make_scorer factory function. f = lambda *args: 0 assert_raises(ValueError, make_scorer, f, needs_threshold=True, needs_proba=True) def test_classification_scores(): # Test classification scorers. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train) for prefix, metric in [('f1', f1_score), ('precision', precision_score), ('recall', recall_score)]: score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='weighted') assert_almost_equal(score1, score2) score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='macro') assert_almost_equal(score1, score2) score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='micro') assert_almost_equal(score1, score2) score1 = get_scorer('%s' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=1) assert_almost_equal(score1, score2) # test fbeta score that takes an argument scorer = make_scorer(fbeta_score, beta=2) score1 = scorer(clf, X_test, y_test) score2 = fbeta_score(y_test, clf.predict(X_test), beta=2) assert_almost_equal(score1, score2) # test that custom scorer can be pickled unpickled_scorer = pickle.loads(pickle.dumps(scorer)) score3 = unpickled_scorer(clf, X_test, y_test) assert_almost_equal(score1, score3) # smoke test the repr: repr(fbeta_score) def test_regression_scorers(): # Test regression scorers. diabetes = load_diabetes() X, y = diabetes.data, diabetes.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = Ridge() clf.fit(X_train, y_train) score1 = get_scorer('r2')(clf, X_test, y_test) score2 = r2_score(y_test, clf.predict(X_test)) assert_almost_equal(score1, score2) def test_thresholded_scorers(): # Test scorers that take thresholds. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) assert_almost_equal(score1, score3) logscore = get_scorer('log_loss')(clf, X_test, y_test) logloss = log_loss(y_test, clf.predict_proba(X_test)) assert_almost_equal(-logscore, logloss) # same for an estimator without decision_function clf = DecisionTreeClassifier() clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) # test with a regressor (no decision_function) reg = DecisionTreeRegressor() reg.fit(X_train, y_train) score1 = get_scorer('roc_auc')(reg, X_test, y_test) score2 = roc_auc_score(y_test, reg.predict(X_test)) assert_almost_equal(score1, score2) # Test that an exception is raised on more than two classes X, y = make_blobs(random_state=0, centers=3) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf.fit(X_train, y_train) assert_raises(ValueError, get_scorer('roc_auc'), clf, X_test, y_test) def test_thresholded_scorers_multilabel_indicator_data(): # Test that the scorer work with multilabel-indicator format # for multilabel and multi-output multi-class classifier X, y = make_multilabel_classification(allow_unlabeled=False, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Multi-output multi-class predict_proba clf = DecisionTreeClassifier() clf.fit(X_train, y_train) y_proba = clf.predict_proba(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p[:, -1] for p in y_proba).T) assert_almost_equal(score1, score2) # Multi-output multi-class decision_function # TODO Is there any yet? clf = DecisionTreeClassifier() clf.fit(X_train, y_train) clf._predict_proba = clf.predict_proba clf.predict_proba = None clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)] y_proba = clf.decision_function(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p for p in y_proba).T) assert_almost_equal(score1, score2) # Multilabel predict_proba clf = OneVsRestClassifier(DecisionTreeClassifier()) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) assert_almost_equal(score1, score2) # Multilabel decision function clf = OneVsRestClassifier(LinearSVC(random_state=0)) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) assert_almost_equal(score1, score2) def test_unsupervised_scorers(): # Test clustering scorers against gold standard labeling. # We don't have any real unsupervised Scorers yet. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) km = KMeans(n_clusters=3) km.fit(X_train) score1 = get_scorer('adjusted_rand_score')(km, X_test, y_test) score2 = adjusted_rand_score(y_test, km.predict(X_test)) assert_almost_equal(score1, score2) @ignore_warnings def test_raises_on_score_list(): # Test that when a list of scores is returned, we raise proper errors. X, y = make_blobs(random_state=0) f1_scorer_no_average = make_scorer(f1_score, average=None) clf = DecisionTreeClassifier() assert_raises(ValueError, cross_val_score, clf, X, y, scoring=f1_scorer_no_average) grid_search = GridSearchCV(clf, scoring=f1_scorer_no_average, param_grid={'max_depth': [1, 2]}) assert_raises(ValueError, grid_search.fit, X, y) @ignore_warnings def test_scorer_sample_weight(): # Test that scorers support sample_weight or raise sensible errors # Unlike the metrics invariance test, in the scorer case it's harder # to ensure that, on the classifier output, weighted and unweighted # scores really should be unequal. X, y = make_classification(random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) split = train_test_split(X, y, y_ml, random_state=0) X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split sample_weight = np.ones_like(y_test) sample_weight[:10] = 0 # get sensible estimators for each metric sensible_regr = DummyRegressor(strategy='median') sensible_regr.fit(X_train, y_train) sensible_clf = DecisionTreeClassifier(random_state=0) sensible_clf.fit(X_train, y_train) sensible_ml_clf = DecisionTreeClassifier(random_state=0) sensible_ml_clf.fit(X_train, y_ml_train) estimator = dict([(name, sensible_regr) for name in REGRESSION_SCORERS] + [(name, sensible_clf) for name in CLF_SCORERS] + [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS]) for name, scorer in SCORERS.items(): if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else: target = y_test try: weighted = scorer(estimator[name], X_test, target, sample_weight=sample_weight) ignored = scorer(estimator[name], X_test[10:], target[10:]) unweighted = scorer(estimator[name], X_test, target) assert_not_equal(weighted, unweighted, msg="scorer {0} behaves identically when " "called with sample weights: {1} vs " "{2}".format(name, weighted, unweighted)) assert_almost_equal(weighted, ignored, err_msg="scorer {0} behaves differently when " "ignoring samples and setting sample_weight to" " 0: {1} vs {2}".format(name, weighted, ignored)) except TypeError as e: assert_true("sample_weight" in str(e), "scorer {0} raises unhelpful exception when called " "with sample weights: {1}".format(name, str(e)))
bsd-3-clause
rabernat/xray
xarray/tests/test_formatting.py
1
6103
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from xarray.core import formatting from xarray.core.pycompat import PY3 from . import TestCase, raises_regex class TestFormatting(TestCase): def test_get_indexer_at_least_n_items(self): cases = [ ((20,), (slice(10),)), ((3, 20,), (0, slice(10))), ((2, 10,), (0, slice(10))), ((2, 5,), (slice(2), slice(None))), ((1, 2, 5,), (0, slice(2), slice(None))), ((2, 3, 5,), (0, slice(2), slice(None))), ((1, 10, 1,), (0, slice(10), slice(None))), ((2, 5, 1,), (slice(2), slice(None), slice(None))), ((2, 5, 3,), (0, slice(4), slice(None))), ((2, 3, 3,), (slice(2), slice(None), slice(None))), ] for shape, expected in cases: actual = formatting._get_indexer_at_least_n_items(shape, 10) self.assertEqual(expected, actual) def test_first_n_items(self): array = np.arange(100).reshape(10, 5, 2) for n in [3, 10, 13, 100, 200]: actual = formatting.first_n_items(array, n) expected = array.flat[:n] self.assertItemsEqual(expected, actual) with raises_regex(ValueError, 'at least one item'): formatting.first_n_items(array, 0) def test_last_item(self): array = np.arange(100) reshape = ((10, 10), (1, 100), (2, 2, 5, 5)) expected = np.array([99]) for r in reshape: result = formatting.last_item(array.reshape(r)) self.assertEqual(result, expected) def test_format_item(self): cases = [ (pd.Timestamp('2000-01-01T12'), '2000-01-01T12:00:00'), (pd.Timestamp('2000-01-01'), '2000-01-01'), (pd.Timestamp('NaT'), 'NaT'), (pd.Timedelta('10 days 1 hour'), '10 days 01:00:00'), (pd.Timedelta('-3 days'), '-3 days +00:00:00'), (pd.Timedelta('3 hours'), '0 days 03:00:00'), (pd.Timedelta('NaT'), 'NaT'), ('foo', "'foo'"), (u'foo', "'foo'" if PY3 else "u'foo'"), (b'foo', "b'foo'" if PY3 else "'foo'"), (1, '1'), (1.0, '1.0'), ] for item, expected in cases: actual = formatting.format_item(item) self.assertEqual(expected, actual) def test_format_items(self): cases = [ (np.arange(4) * np.timedelta64(1, 'D'), '0 days 1 days 2 days 3 days'), (np.arange(4) * np.timedelta64(3, 'h'), '00:00:00 03:00:00 06:00:00 09:00:00'), (np.arange(4) * np.timedelta64(500, 'ms'), '00:00:00 00:00:00.500000 00:00:01 00:00:01.500000'), (pd.to_timedelta(['NaT', '0s', '1s', 'NaT']), 'NaT 00:00:00 00:00:01 NaT'), (pd.to_timedelta(['1 day 1 hour', '1 day', '0 hours']), '1 days 01:00:00 1 days 00:00:00 0 days 00:00:00'), ([1, 2, 3], '1 2 3'), ] for item, expected in cases: actual = ' '.join(formatting.format_items(item)) self.assertEqual(expected, actual) def test_format_array_flat(self): actual = formatting.format_array_flat(np.arange(100), 13) expected = '0 1 2 3 4 ...' self.assertEqual(expected, actual) actual = formatting.format_array_flat(np.arange(100.0), 11) expected = '0.0 1.0 ...' self.assertEqual(expected, actual) actual = formatting.format_array_flat(np.arange(100.0), 1) expected = '0.0 ...' self.assertEqual(expected, actual) actual = formatting.format_array_flat(np.arange(3), 5) expected = '0 1 2' self.assertEqual(expected, actual) actual = formatting.format_array_flat(np.arange(4.0), 11) expected = '0.0 1.0 ...' self.assertEqual(expected, actual) actual = formatting.format_array_flat(np.arange(4), 0) expected = '0 ...' self.assertEqual(expected, actual) def test_pretty_print(self): self.assertEqual(formatting.pretty_print('abcdefghij', 8), 'abcde...') self.assertEqual(formatting.pretty_print(u'ß', 1), u'ß') def test_maybe_truncate(self): self.assertEqual(formatting.maybe_truncate(u'ß', 10), u'ß') def test_format_timestamp_out_of_bounds(self): from datetime import datetime date = datetime(1300, 12, 1) expected = '1300-12-01' result = formatting.format_timestamp(date) self.assertEqual(result, expected) date = datetime(2300, 12, 1) expected = '2300-12-01' result = formatting.format_timestamp(date) self.assertEqual(result, expected) def test_attribute_repr(self): short = formatting.summarize_attr(u'key', u'Short string') long = formatting.summarize_attr(u'key', 100 * u'Very long string ') newlines = formatting.summarize_attr(u'key', u'\n\n\n') tabs = formatting.summarize_attr(u'key', u'\t\t\t') self.assertEqual(short, ' key: Short string') self.assertLessEqual(len(long), 80) self.assertTrue(long.endswith(u'...')) self.assertNotIn(u'\n', newlines) self.assertNotIn(u'\t', tabs) def test_set_numpy_options(): original_options = np.get_printoptions() with formatting.set_numpy_options(threshold=10): assert len(repr(np.arange(500))) < 200 # original options are restored assert np.get_printoptions() == original_options def test_short_array_repr(): cases = [ np.random.randn(500), np.random.randn(20, 20), np.random.randn(5, 10, 15), np.random.randn(5, 10, 15, 3), ] # number of lines: # for default numpy repr: 167, 140, 254, 248 # for short_array_repr: 1, 7, 24, 19 for array in cases: num_lines = formatting.short_array_repr(array).count('\n') + 1 assert num_lines < 30
apache-2.0
astroML/astroML
examples/datasets/plot_sdss_filters.py
5
1366
""" SDSS Filters ------------ Download and plot the five SDSS filter bands along with a Vega spectrum. This data is available on the SDSS website (filters) and on the STSci website (Vega). """ # Author: Jake VanderPlas <vanderplas@astro.washington.edu> # License: BSD # The figure is an example from astroML: see http://astroML.github.com from matplotlib import pyplot as plt from astroML.datasets import fetch_sdss_filter, fetch_vega_spectrum #------------------------------------------------------------ # Set up figure and axes fig = plt.figure() ax = fig.add_subplot(111) #---------------------------------------------------------------------- # Fetch and plot the Vega spectrum spec = fetch_vega_spectrum() lam = spec[0] spectrum = spec[1] / 2.1 / spec[1].max() ax.plot(lam, spectrum, '-k', lw=2) #------------------------------------------------------------ # Fetch and plot the five filters text_kwargs = dict(fontsize=20, ha='center', va='center', alpha=0.5) for f, c, loc in zip('ugriz', 'bgrmk', [3500, 4600, 6100, 7500, 8800]): data = fetch_sdss_filter(f) ax.fill(data[0], data[1], ec=c, fc=c, alpha=0.4) ax.text(loc, 0.02, f, color=c, **text_kwargs) ax.set_xlim(3000, 11000) ax.set_title('SDSS Filters and Reference Spectrum') ax.set_xlabel('Wavelength (Angstroms)') ax.set_ylabel('normalized flux / filter transmission') plt.show()
bsd-2-clause
hackthemarket/pystrat
sim_ml.py
1
11376
# driver for playing with sim & ml # simple trading strategy simulator import pandas as pd from pandas.tools.plotting import autocorrelation_plot from pandas.tools.plotting import scatter_matrix import numpy as np from scipy import stats import sklearn from sklearn import preprocessing as pp import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import interactive interactive(True) import sys import time import logging as log log.basicConfig(level=log.DEBUG) import glob import os.path import pickle import logging as log log.basicConfig(level=log.DEBUG) import random import pdb pd.set_option('display.width',500) import tensorflow as tf import pyfolio as pf import pyfolio import collections import sim Dataset = collections.namedtuple('Dataset', ['data', 'target']) def get_univ(f = 'U.pkl', from_dt='2005-01-01'): # dev driver P = pickle.load(open(f)) log.info('loaded <%s>',f) P.describe() U = P[P.index >= '2005-01-01'] return U # U.describe() # _,B = sim.sim(U) # #plot NAV # B.NAV.plot(title='Equal Weight Everyone') # return B def _fitntestRandomForest( train, vlad, max_nodes=1024, steps=100, model_dir='/tmp/rf') : # build fit & test random forest for input fsize = len(train.data.columns) nclasses = len(train.target.unique()) hparams = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams( num_trees=nclasses, max_nodes=max_nodes, num_classes=nclasses, num_features=fsize) classifier = tf.contrib.learn.TensorForestEstimator(hparams) tdata = train.data.as_matrix().astype(np.float32) ttgt = train.target.as_matrix().astype(np.float32) vdata = vlad.data.as_matrix().astype(np.float32) vtgt = vlad.target.as_matrix().astype(np.float32) monitors = [tf.contrib.learn.TensorForestLossMonitor(10, 10)] classifier.fit(x=tdata, y=ttgt, steps=steps, monitors=monitors) result = classifier.evaluate(x=vdata, y=vtgt)#, steps=np.round(steps/10) print('Accuracy: {0:f}'.format(result["accuracy"])) return result,classifier def bestworst( U, cfg, kvargs ) : """ Buy the prior period's losers and sell the prior period's winners in proportion to their over- or under-performance of the equal-weighted market. """ N = len(U.index) mktR = U.Return.mean() Weight = np.add( U.Return, -mktR ) / (-N) # now let's ensure that we spend 100% on each side U.Weight = 2 * np.sign(Weight) * (abs(Weight) / sum(abs(Weight))) return U def just_ML(U,cfg,kvargs): """ strategy that just uses ML signal and buys those expected to go up and sells those expected to go down """ nlongs = len(U[U.MLPrediction==2].index) nshorts = len(U[U.MLPrediction==0].index) #pdb.set_trace() U.Weight = np.where(U.MLPrediction==2, 1/float(nlongs), U.Weight) U.Weight = np.where(U.MLPrediction==0, -1/float(nshorts), U.Weight) return U def pyfolio_tf ( Balances ): Balances.index=Balances.index.tz_localize('UTC') pf.create_full_tear_sheet(Balances.NET_Return) def bestworst_ML( U, cfg, kvargs ) : """ Buy the prior period's losers and sell the prior period's winners in proportion to their over- or under-performance of the equal-weighted market. Then, cross-reference ML's views with this. The possibilities are: - Good: We're buying something predicted to go up - Good: We're selling something predicted to go down - OK : We're buying something predicted to stay flat - OK : We're selling something predicted to stay flat - Bad : We're buying something predicted to go down - Bad : We're selling something predicted to go up We leave the *OK*s alone and deallocate from the *Bad*s according to value in kvargs 'realloc' and reallocate to the *Goods*. """ realloc = kvargs.get('realloc', 0.5) N = len(U.index) mktR = U.Return.mean() Weight = np.add( U.Return, -mktR ) / (-N) # now let's ensure that we spend 100% on each side U.Weight = 2 * np.sign(Weight) * (abs(Weight) / sum(abs(Weight))) # now, let's add-in our ML insights # we're going to deallocate from these guys bad1 = np.logical_and(U.MLPrediction==0, U.Weight > 0) bad2 = np.logical_and(U.MLPrediction==2, U.Weight < 0) bads = np.logical_or(bad1, bad2) lbads = np.logical_and(bads, U.Weight>0) sbads = np.logical_and(bads, U.Weight<0) # and reallocate to these good1 = np.logical_and(U.MLPrediction==0, U.Weight < 0) good2 = np.logical_and(U.MLPrediction==2, U.Weight > 0) goods = np.logical_or( good1, good2 ) lgoods = np.logical_and(goods, U.Weight>0) sgoods = np.logical_and(goods, U.Weight<0) numlgoods = len(U[lgoods].index) numsgoods = len(U[sgoods].index) # how much weight to add to longs & shorts? lwt = U[lbads].Weight.sum() * realloc swt = U[sbads].Weight.sum() * realloc # let's deallocate from bads U.Weight = np.where( bads, U.Weight * (1-realloc),U.Weight) # and allocate to goods long & short if numlgoods > 0: U.Weight = np.where( lgoods, U.Weight + (lwt/numlgoods), U.Weight ) if numsgoods > 0: U.Weight = np.where( sgoods, U.Weight + (swt/numsgoods), U.Weight ) # pdb.set_trace() return U def bestworst_ML( U, cfg, kvargs ) : """ Buy the prior period's losers and sell the prior period's winners in proportion to their over- or under-performance of the equal-weighted market. Then, cross-reference ML's views with this. The possibilities are: - Good: We're buying something predicted to go up - Good: We're selling something predicted to go down - OK : We're buying something predicted to stay flat - OK : We're selling something predicted to stay flat - Bad : We're buying something predicted to go down - Bad : We're selling something predicted to go up We leave the *OK*s alone and deallocate from the *Bad*s according to value in kvargs 'realloc' and reallocate to the *Goods*. """ realloc = kvargs.get('realloc', 0.5) N = len(U.index) mktR = U.Return.mean() Weight = np.add( U.Return, -mktR ) / (-N) # now let's ensure that we spend 100% on each side U.Weight = 2 * np.sign(Weight) * (abs(Weight) / sum(abs(Weight))) # now, let's add-in our ML insights # we're going to deallocate from these guys bad1 = np.logical_and(U.MLPrediction==0, U.Weight > 0) bad2 = np.logical_and(U.MLPrediction==2, U.Weight < 0) bads = np.logical_or(bad1, bad2) lbads = np.logical_and(bads, U.Weight>0) sbads = np.logical_and(bads, U.Weight<0) # and reallocate to these good1 = np.logical_and(U.MLPrediction==0, U.Weight < 0) good2 = np.logical_and(U.MLPrediction==2, U.Weight > 0) goods = np.logical_or( good1, good2 ) lgoods = np.logical_and(goods, U.Weight>0) sgoods = np.logical_and(goods, U.Weight<0) numlgoods = len(U[lgoods].index) numsgoods = len(U[sgoods].index) # how much weight to add to longs & shorts? lwt = U[lbads].Weight.sum() * realloc swt = U[sbads].Weight.sum() * realloc # let's deallocate from bads U.Weight = np.where( bads, U.Weight * (1-realloc),U.Weight) # and allocate to goods long & short if numlgoods > 0: U.Weight = np.where( lgoods, U.Weight + (lwt/numlgoods), U.Weight ) if numsgoods > 0: U.Weight = np.where( sgoods, U.Weight + (swt/numsgoods), U.Weight ) # pdb.set_trace() return U def _fitntestSVM( train, vlad, steps=30, model_dir='/tmp/svm') : # build fit & test SVM for input fsize = len(train.data.columns) nclasses = len(train.target.unique()) feature_columns = [tf.contrib.layers.real_valued_column("features", dimension=fsize)] tdata = train.data.as_matrix().astype(np.float32) ttgt = train.target.as_matrix().astype(np.float32) vdata = vlad.data.as_matrix().astype(np.float32) vtgt = vlad.target.as_matrix().astype(np.float32) def input_fn_t(): return { 'example_id' : tf.constant(train.data.columns.values), # 'example_id' : tf.constant(ttgt), 'multi_dim_feature' : tf.constant(tdata), }, tf.constant(ttgt) def input_fn_v(): return { 'example_id' : tf.constant(vlad.data.columns.values), # 'example_id' : tf.constant(vtgt), 'multi_dim_feature' : tf.constant(vdata), }, tf.constant(vtgt) # pdb.set_trace() multi_dim_feature = tf.contrib.layers.real_valued_column( 'multi_dim_feature', dimension=fsize) classifier = tf.contrib.learn.SVM(feature_columns=[multi_dim_feature], example_id_column='example_id', l1_regularization=0.001, l2_regularization=0.001) classifier.fit(input_fn=input_fn_t, steps=steps) result = svm_classifier.evaluate(input_fn=input_fn_v, steps=steps) print('Accuracy: {0:f}'.format(result["accuracy"])) return result,classifier ##################################################################### log.info('getting univ...') U = get_univ() # load ml data fname = 'forsims.pkl' forsims = pickle.load(open(fname)) log.info('read %s', fname) src_train = forsims['src_train'] src_vlad = forsims['src_vlad'] Kvlad = forsims['Kvlad'] forsims = None Kvlad.head() print Kvlad.shape print src_vlad.data.shape print src_train.data.shape # let's train our model log.info('training RF model') src_rf = _fitntestRandomForest(train=src_train, vlad=src_vlad, model_dir='/tmp/src_rf',steps=100) # now let's use our trained model to fit the validation set vdata = src_vlad.data.as_matrix().astype(np.float32) vtgt = src_vlad.target.as_matrix().astype(np.float32) log.info('predicting...') p=src_rf[1].predict( x=vdata) log.info('results...') # how'd it do? R = pd.DataFrame( {'predicted':p,'actual':vtgt}) R['dist'] = np.abs(R.actual-R.predicted) # avg distance is meaningful. a null predictor should get about .88, # so anything below provides some edge print R.dist.mean() twos=R.dist[R.dist==2] len(twos.index)/float(len(R.index)) # ok, let's create a df with date,symbol and prediction which we'll then join onto the simulation dataset V = pd.DataFrame( {'Date': Kvlad.Date, 'Sym': Kvlad.Sym, 'MLPrediction': R.predicted }) #Kvlad.head() print U.shape print V.shape V.head() Uv = U[U.index >= V.Date.min()] print Uv.shape Uv.reset_index(inplace=True) Uv.head() #V.set_index('Date',inplace=True) Uml = Uv.merge( V, how='left', on=['Date','Sym'] ) Uml.sort_values(['Date','Sym'],inplace=True) log.info('built annotated universe.') Uml.set_index('Date',inplace=True) Uml.head() #kvargs = {'realloc':1} #S,B = sim.sim(Uml,sim_FUN=bestworst_ML,kvargs=kvargs) #Sbw,Bbw = sim.sim(U, sim_FUN=bestworst) #Bbw.NAV.plot(title="LoMacKinlay") #Sbw,Bbw = sim.sim(U, sim_FUN=bestworst) #Bbw.NAV.plot(title="LoMacKinlay") #src_svm = _fitntestSVM(train=src_train, vlad=src_vlad, model_dir='/tmp/src_svm', steps=10)
gpl-3.0
RPGOne/scikit-learn
sklearn/manifold/isomap.py
50
7515
"""Isomap for manifold learning""" # Author: Jake Vanderplas -- <vanderplas@astro.washington.edu> # License: BSD 3 clause (C) 2011 import numpy as np from ..base import BaseEstimator, TransformerMixin from ..neighbors import NearestNeighbors, kneighbors_graph from ..utils import check_array from ..utils.graph import graph_shortest_path from ..decomposition import KernelPCA from ..preprocessing import KernelCenterer class Isomap(BaseEstimator, TransformerMixin): """Isomap Embedding Non-linear dimensionality reduction through Isometric Mapping Read more in the :ref:`User Guide <isomap>`. Parameters ---------- n_neighbors : integer number of neighbors to consider for each point. n_components : integer number of coordinates for the manifold eigen_solver : ['auto'|'arpack'|'dense'] 'auto' : Attempt to choose the most efficient solver for the given problem. 'arpack' : Use Arnoldi decomposition to find the eigenvalues and eigenvectors. 'dense' : Use a direct solver (i.e. LAPACK) for the eigenvalue decomposition. tol : float Convergence tolerance passed to arpack or lobpcg. not used if eigen_solver == 'dense'. max_iter : integer Maximum number of iterations for the arpack solver. not used if eigen_solver == 'dense'. path_method : string ['auto'|'FW'|'D'] Method to use in finding shortest path. 'auto' : attempt to choose the best algorithm automatically. 'FW' : Floyd-Warshall algorithm. 'D' : Dijkstra's algorithm. neighbors_algorithm : string ['auto'|'brute'|'kd_tree'|'ball_tree'] Algorithm to use for nearest neighbors search, passed to neighbors.NearestNeighbors instance. n_jobs : int, optional (default = 1) The number of parallel jobs to run. If ``-1``, then the number of jobs is set to the number of CPU cores. Attributes ---------- embedding_ : array-like, shape (n_samples, n_components) Stores the embedding vectors. kernel_pca_ : object `KernelPCA` object used to implement the embedding. training_data_ : array-like, shape (n_samples, n_features) Stores the training data. nbrs_ : sklearn.neighbors.NearestNeighbors instance Stores nearest neighbors instance, including BallTree or KDtree if applicable. dist_matrix_ : array-like, shape (n_samples, n_samples) Stores the geodesic distance matrix of training data. References ---------- .. [1] Tenenbaum, J.B.; De Silva, V.; & Langford, J.C. A global geometric framework for nonlinear dimensionality reduction. Science 290 (5500) """ def __init__(self, n_neighbors=5, n_components=2, eigen_solver='auto', tol=0, max_iter=None, path_method='auto', neighbors_algorithm='auto', n_jobs=1): self.n_neighbors = n_neighbors self.n_components = n_components self.eigen_solver = eigen_solver self.tol = tol self.max_iter = max_iter self.path_method = path_method self.neighbors_algorithm = neighbors_algorithm self.n_jobs = n_jobs def _fit_transform(self, X): X = check_array(X) self.nbrs_ = NearestNeighbors(n_neighbors=self.n_neighbors, algorithm=self.neighbors_algorithm, n_jobs=self.n_jobs) self.nbrs_.fit(X) self.training_data_ = self.nbrs_._fit_X self.kernel_pca_ = KernelPCA(n_components=self.n_components, kernel="precomputed", eigen_solver=self.eigen_solver, tol=self.tol, max_iter=self.max_iter, n_jobs=self.n_jobs) kng = kneighbors_graph(self.nbrs_, self.n_neighbors, mode='distance', n_jobs=self.n_jobs) self.dist_matrix_ = graph_shortest_path(kng, method=self.path_method, directed=False) G = self.dist_matrix_ ** 2 G *= -0.5 self.embedding_ = self.kernel_pca_.fit_transform(G) def reconstruction_error(self): """Compute the reconstruction error for the embedding. Returns ------- reconstruction_error : float Notes ------- The cost function of an isomap embedding is ``E = frobenius_norm[K(D) - K(D_fit)] / n_samples`` Where D is the matrix of distances for the input data X, D_fit is the matrix of distances for the output embedding X_fit, and K is the isomap kernel: ``K(D) = -0.5 * (I - 1/n_samples) * D^2 * (I - 1/n_samples)`` """ G = -0.5 * self.dist_matrix_ ** 2 G_center = KernelCenterer().fit_transform(G) evals = self.kernel_pca_.lambdas_ return np.sqrt(np.sum(G_center ** 2) - np.sum(evals ** 2)) / G.shape[0] def fit(self, X, y=None): """Compute the embedding vectors for data X Parameters ---------- X : {array-like, sparse matrix, BallTree, KDTree, NearestNeighbors} Sample data, shape = (n_samples, n_features), in the form of a numpy array, precomputed tree, or NearestNeighbors object. Returns ------- self : returns an instance of self. """ self._fit_transform(X) return self def fit_transform(self, X, y=None): """Fit the model from data in X and transform X. Parameters ---------- X: {array-like, sparse matrix, BallTree, KDTree} Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- X_new: array-like, shape (n_samples, n_components) """ self._fit_transform(X) return self.embedding_ def transform(self, X): """Transform X. This is implemented by linking the points X into the graph of geodesic distances of the training data. First the `n_neighbors` nearest neighbors of X are found in the training data, and from these the shortest geodesic distances from each point in X to each point in the training data are computed in order to construct the kernel. The embedding of X is the projection of this kernel onto the embedding vectors of the training set. Parameters ---------- X: array-like, shape (n_samples, n_features) Returns ------- X_new: array-like, shape (n_samples, n_components) """ X = check_array(X) distances, indices = self.nbrs_.kneighbors(X, return_distance=True) # Create the graph of shortest distances from X to self.training_data_ # via the nearest neighbors of X. # This can be done as a single array operation, but it potentially # takes a lot of memory. To avoid that, use a loop: G_X = np.zeros((X.shape[0], self.training_data_.shape[0])) for i in range(X.shape[0]): G_X[i] = np.min(self.dist_matrix_[indices[i]] + distances[i][:, None], 0) G_X **= 2 G_X *= -0.5 return self.kernel_pca_.transform(G_X)
bsd-3-clause
mjafin/bcbio-nextgen
bcbio/rnaseq/sailfish.py
1
9327
import os import bcbio.pipeline.datadict as dd from bcbio.distributed.transaction import file_transaction from bcbio.provenance import do from bcbio.utils import (file_exists, safe_makedir, is_gzipped, rbind, partition, R_package_path, Rscript_cmd) from bcbio.pipeline import config_utils, disambiguate from bcbio.rnaseq import gtf from bcbio.bam import fastq from bcbio.log import logger import pandas as pd import numpy as np def run_sailfish(data): samplename = dd.get_sample_name(data) files = dd.get_input_sequence_files(data) work_dir = dd.get_work_dir(data) if len(files) == 2: fq1, fq2 = files else: fq1, fq2 = files[0], None sailfish_dir = os.path.join(work_dir, "sailfish", samplename) gtf_file = dd.get_gtf_file(data) assert file_exists(gtf_file), "%s was not found, exiting." % gtf_file fasta_file = dd.get_ref_file(data) assert file_exists(fasta_file), "%s was not found, exiting." % fasta_file stranded = dd.get_strandedness(data).lower() out_file = sailfish(fq1, fq2, sailfish_dir, gtf_file, fasta_file, stranded, data) data = dd.set_sailfish(data, out_file) data = dd.set_sailfish_dir(data, sailfish_dir) return [[data]] def sailfish(fq1, fq2, sailfish_dir, gtf_file, ref_file, strandedness, data): safe_makedir(sailfish_dir) samplename = dd.get_sample_name(data) quant_dir = os.path.join(sailfish_dir, "quant") out_file = os.path.join(quant_dir, "quant.sf") if file_exists(out_file): return out_file kmer_size = int(fastq.estimate_read_length(fq1)) if kmer_size < 30: # kmer size must be odd kmer_size = kmer_size - 5 kmer_size = kmer_size if kmer_size % 2 else kmer_size - 1 else: kmer_size = 25 sailfish_idx = sailfish_index(gtf_file, ref_file, data, sailfish_dir, kmer_size) num_cores = dd.get_num_cores(data) sailfish = config_utils.get_program("sailfish", data["config"]) cmd = "{sailfish} quant -i {sailfish_idx} -p {num_cores} " cmd += _libtype_string(fq1, fq2, strandedness) fq1_cmd = "{fq1}" if not is_gzipped(fq1) else "<(gzip -cd {fq1})" fq1_cmd = fq1_cmd.format(fq1=fq1) if not fq2: cmd += " -r {fq1_cmd} " else: fq2_cmd = "{fq2}" if not is_gzipped(fq2) else "<(gzip -cd {fq2})" fq2_cmd = fq2_cmd.format(fq2=fq2) cmd += " -1 {fq1_cmd} -2 {fq2_cmd} " cmd += "--useVBOpt --numBootstraps 30 " cmd += "-o {tx_out_dir}" message = "Quantifying transcripts in {fq1} and {fq2}." with file_transaction(data, quant_dir) as tx_out_dir: do.run(cmd.format(**locals()), message.format(**locals()), None) _sleuthify_sailfish(quant_dir) return out_file def _sleuthify_sailfish(sailfish_dir): """ if installed, use wasabi to create abundance.h5 output for use with sleuth """ if not R_package_path("wasabi"): return None else: rscript = Rscript_cmd() cmd = """{rscript} -e 'library("wasabi"); prepare_fish_for_sleuth(c("{sailfish_dir}"))'""" do.run(cmd.format(**locals()), "Converting Sailfish to Sleuth format.") return os.path.join(sailfish_dir, "abundance.h5") def create_combined_fasta(data, out_dir): """ if there are genomes to be disambiguated, create a FASTA file of all of the transcripts for all genomes """ items = disambiguate.split([data]) fasta_files = [] for i in items: odata = i[0] gtf_file = dd.get_gtf_file(odata) ref_file = dd.get_ref_file(odata) out_file = os.path.join(out_dir, dd.get_genome_build(odata) + ".fa") if file_exists(out_file): fasta_files.append(out_file) else: out_file = _gtf_to_fasta(gtf_file, ref_file, out_file) out_file = _clean_gtf_fa(out_file, out_file) fasta_files.append(out_file) out_stem = os.path.join(out_dir, dd.get_genome_build(data)) if dd.get_disambiguate(data): out_stem = "-".join([out_stem] + (dd.get_disambiguate(data) or [])) combined_file = out_stem + ".fa" if file_exists(combined_file): return combined_file fasta_file_string = " ".join(fasta_files) cmd = "cat {fasta_file_string} > {tx_out_file}" with file_transaction(combined_file) as tx_out_file: do.run(cmd.format(**locals()), "Combining transcriptome FASTA files.") return combined_file def sailfish_index(gtf_file, ref_file, data, out_dir, kmer_size): out_dir = os.path.join(out_dir, "index", dd.get_genome_build(data)) if dd.get_disambiguate(data): out_dir = "-".join([out_dir] + (dd.get_disambiguate(data) or [])) sailfish = config_utils.get_program("sailfish", data["config"]) num_cores = dd.get_num_cores(data) gtf_fa = create_combined_fasta(data, out_dir) if file_exists(out_dir + "versionInfo.json"): return out_dir with file_transaction(out_dir) as tx_out_dir: cmd = ("{sailfish} index -p {num_cores} -t {gtf_fa} -o {tx_out_dir} " "-k {kmer_size}") message = "Creating sailfish index for {gtf_fa}." do.run(cmd.format(**locals()), message.format(**locals()), None) return out_dir def _libtype_string(fq1, fq2, strandedness): """ supports just the Tophat unstranded/firstrand/secondstrand """ libtype = "-l I" if fq2 else "-l " strand = _sailfish_strand_string(strandedness) return libtype + strand def _sailfish_strand_string(strandedness): return {'unstranded': "U", 'firststrand': "SR", 'secondstrand': "SF"}.get(strandedness, "U") def _gtf_to_fasta(gtf_file, ref_file, out_file): with file_transaction(out_file) as tx_gtf_fa: cmd = "gtf_to_fasta {gtf_file} {ref_file} {tx_gtf_fa}" message = "Extracting genomic sequences of {gtf_file}." do.run(cmd.format(**locals()), message.format(**locals()), None) return out_file def _clean_gtf_fa(gtf_fa, out_file): """ convert the gtf_to_fasta sequence names to just the transcript ID >1 ENST00000389680 chrM+ 648-1601 -> >ENST00000389680 """ with file_transaction(out_file) as tx_out_file: with open(gtf_fa) as in_handle, open(tx_out_file, "w") as out_handle: for line in in_handle: if line.startswith(">"): line = ">" + line.split()[1] + "\n" out_handle.write(line) return out_file def combine_sailfish(samples): work_dir = dd.get_in_samples(samples, dd.get_work_dir) sailfish_dir = os.path.join(work_dir, "sailfish") gtf_file = dd.get_in_samples(samples, dd.get_gtf_file) dont_combine, to_combine = partition(dd.get_sailfish, dd.sample_data_iterator(samples), True) if not to_combine: return samples tidy_file = os.path.join(sailfish_dir, "combined.sf") transcript_tpm_file = os.path.join(sailfish_dir, "combined.isoform.sf.tpm") gene_tpm_file = os.path.join(sailfish_dir, "combined.gene.sf.tpm") tx2gene = os.path.join(sailfish_dir, "tx2gene.csv") if not all([file_exists(x) for x in [gene_tpm_file, tidy_file, transcript_tpm_file, tx2gene]]): logger.info("Combining count files into %s." % tidy_file) df = pd.DataFrame() for data in to_combine: sailfish_file = dd.get_sailfish(data) samplename = dd.get_sample_name(data) new_df = _sailfish_expression_parser(sailfish_file, samplename) if df.empty: df = new_df else: df = rbind([df, new_df]) df["id"] = df.index # some versions of the transcript annotations can have duplicated entries df = df.drop_duplicates(["id", "sample"]) with file_transaction(tidy_file) as tx_out_file: df.to_csv(tx_out_file, sep="\t", index_label="name") with file_transaction(transcript_tpm_file) as tx_out_file: df.pivot("id", "sample", "tpm").to_csv(tx_out_file, sep="\t") with file_transaction(gene_tpm_file) as tx_out_file: pivot = df.pivot("id", "sample", "tpm") tdf = pd.DataFrame.from_dict(gtf.transcript_to_gene(gtf_file), orient="index") tdf.columns = ["gene_id"] pivot = pivot.join(tdf) pivot = pivot.groupby("gene_id").agg(np.sum) pivot.to_csv(tx_out_file, sep="\t") tx2gene = gtf.tx2genefile(gtf_file, tx2gene) logger.info("Finished combining count files into %s." % tidy_file) updated_samples = [] for data in dd.sample_data_iterator(samples): data = dd.set_sailfish_tidy(data, tidy_file) data = dd.set_sailfish_transcript_tpm(data, transcript_tpm_file) data = dd.set_sailfish_gene_tpm(data, gene_tpm_file) data = dd.set_tx2gene(data, tx2gene) updated_samples.append([data]) return updated_samples def _sailfish_expression_parser(sailfish_file, samplename): col_names = ["name", "length", "effectiveLength", "tpm", "numreads"] df = pd.read_csv(sailfish_file, comment="#", header=None, skiprows=1, index_col=0, names=col_names, sep="\t") df["sample"] = samplename return df
mit
gfyoung/pandas
pandas/tests/extension/test_numpy.py
1
16802
""" This file contains a minimal set of tests for compliance with the extension array interface test suite, and should contain no other tests. The test suite for the full functionality of the array is located in `pandas/tests/arrays/`. The tests in this file are inherited from the BaseExtensionTests, and only minimal tweaks should be applied to get the tests passing (by overwriting a parent method). Additional tests should either be added to one of the BaseExtensionTests classes (if they are relevant for the extension interface for all dtypes), or be added to the array-specific tests in `pandas/tests/arrays/`. """ import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.core.arrays.numpy_ import PandasArray, PandasDtype from . import base @pytest.fixture(params=["float", "object"]) def dtype(request): return PandasDtype(np.dtype(request.param)) @pytest.fixture def allow_in_pandas(monkeypatch): """ A monkeypatch to tells pandas to let us in. By default, passing a PandasArray to an index / series / frame constructor will unbox that PandasArray to an ndarray, and treat it as a non-EA column. We don't want people using EAs without reason. The mechanism for this is a check against ABCPandasArray in each constructor. But, for testing, we need to allow them in pandas. So we patch the _typ of PandasArray, so that we evade the ABCPandasArray check. """ with monkeypatch.context() as m: m.setattr(PandasArray, "_typ", "extension") yield @pytest.fixture def data(allow_in_pandas, dtype): if dtype.numpy_dtype == "object": return pd.Series([(i,) for i in range(100)]).array return PandasArray(np.arange(1, 101, dtype=dtype._dtype)) @pytest.fixture def data_missing(allow_in_pandas, dtype): if dtype.numpy_dtype == "object": return PandasArray(np.array([np.nan, (1,)], dtype=object)) return PandasArray(np.array([np.nan, 1.0])) @pytest.fixture def na_value(): return np.nan @pytest.fixture def na_cmp(): def cmp(a, b): return np.isnan(a) and np.isnan(b) return cmp @pytest.fixture def data_for_sorting(allow_in_pandas, dtype): """Length-3 array with a known sort order. This should be three items [B, C, A] with A < B < C """ if dtype.numpy_dtype == "object": # Use an empty tuple for first element, then remove, # to disable np.array's shape inference. return PandasArray(np.array([(), (2,), (3,), (1,)], dtype=object)[1:]) return PandasArray(np.array([1, 2, 0])) @pytest.fixture def data_missing_for_sorting(allow_in_pandas, dtype): """Length-3 array with a known sort order. This should be three items [B, NA, A] with A < B and NA missing. """ if dtype.numpy_dtype == "object": return PandasArray(np.array([(1,), np.nan, (0,)], dtype=object)) return PandasArray(np.array([1, np.nan, 0])) @pytest.fixture def data_for_grouping(allow_in_pandas, dtype): """Data for factorization, grouping, and unique tests. Expected to be like [B, B, NA, NA, A, A, B, C] Where A < B < C and NA is missing """ if dtype.numpy_dtype == "object": a, b, c = (1,), (2,), (3,) else: a, b, c = np.arange(3) return PandasArray( np.array([b, b, np.nan, np.nan, a, a, b, c], dtype=dtype.numpy_dtype) ) @pytest.fixture def skip_numpy_object(dtype): """ Tests for PandasArray with nested data. Users typically won't create these objects via `pd.array`, but they can show up through `.array` on a Series with nested data. Many of the base tests fail, as they aren't appropriate for nested data. This fixture allows these tests to be skipped when used as a usefixtures marker to either an individual test or a test class. """ if dtype == "object": raise pytest.skip("Skipping for object dtype.") skip_nested = pytest.mark.usefixtures("skip_numpy_object") class BaseNumPyTests: pass class TestCasting(BaseNumPyTests, base.BaseCastingTests): @skip_nested def test_astype_str(self, data): # ValueError: setting an array element with a sequence super().test_astype_str(data) @skip_nested def test_astype_string(self, data): # GH-33465 # ValueError: setting an array element with a sequence super().test_astype_string(data) class TestConstructors(BaseNumPyTests, base.BaseConstructorsTests): @pytest.mark.skip(reason="We don't register our dtype") # We don't want to register. This test should probably be split in two. def test_from_dtype(self, data): pass @skip_nested def test_array_from_scalars(self, data): # ValueError: PandasArray must be 1-dimensional. super().test_array_from_scalars(data) @skip_nested def test_series_constructor_scalar_with_index(self, data, dtype): # ValueError: Length of passed values is 1, index implies 3. super().test_series_constructor_scalar_with_index(data, dtype) class TestDtype(BaseNumPyTests, base.BaseDtypeTests): @pytest.mark.skip(reason="Incorrect expected.") # we unsurprisingly clash with a NumPy name. def test_check_dtype(self, data): pass class TestGetitem(BaseNumPyTests, base.BaseGetitemTests): @skip_nested def test_getitem_scalar(self, data): # AssertionError super().test_getitem_scalar(data) @skip_nested def test_take_series(self, data): # ValueError: PandasArray must be 1-dimensional. super().test_take_series(data) def test_loc_iloc_frame_single_dtype(self, data, request): npdtype = data.dtype.numpy_dtype if npdtype == object: # GH#33125 mark = pytest.mark.xfail( reason="GH#33125 astype doesn't recognize data.dtype" ) request.node.add_marker(mark) super().test_loc_iloc_frame_single_dtype(data) class TestGroupby(BaseNumPyTests, base.BaseGroupbyTests): @skip_nested def test_groupby_extension_apply( self, data_for_grouping, groupby_apply_op, request ): super().test_groupby_extension_apply(data_for_grouping, groupby_apply_op) class TestInterface(BaseNumPyTests, base.BaseInterfaceTests): @skip_nested def test_array_interface(self, data): # NumPy array shape inference super().test_array_interface(data) class TestMethods(BaseNumPyTests, base.BaseMethodsTests): @pytest.mark.skip(reason="TODO: remove?") def test_value_counts(self, all_data, dropna): pass @pytest.mark.xfail(reason="not working. will be covered by #32028") def test_value_counts_with_normalize(self, data): return super().test_value_counts_with_normalize(data) @pytest.mark.skip(reason="Incorrect expected") # We have a bool dtype, so the result is an ExtensionArray # but expected is not def test_combine_le(self, data_repeated): super().test_combine_le(data_repeated) @skip_nested def test_combine_add(self, data_repeated): # Not numeric super().test_combine_add(data_repeated) @skip_nested def test_shift_fill_value(self, data): # np.array shape inference. Shift implementation fails. super().test_shift_fill_value(data) @skip_nested @pytest.mark.parametrize("box", [pd.Series, lambda x: x]) @pytest.mark.parametrize("method", [lambda x: x.unique(), pd.unique]) def test_unique(self, data, box, method): # Fails creating expected super().test_unique(data, box, method) @skip_nested def test_fillna_copy_frame(self, data_missing): # The "scalar" for this array isn't a scalar. super().test_fillna_copy_frame(data_missing) @skip_nested def test_fillna_copy_series(self, data_missing): # The "scalar" for this array isn't a scalar. super().test_fillna_copy_series(data_missing) @skip_nested def test_hash_pandas_object_works(self, data, as_frame): # ndarray of tuples not hashable super().test_hash_pandas_object_works(data, as_frame) @skip_nested def test_searchsorted(self, data_for_sorting, as_series): # Test setup fails. super().test_searchsorted(data_for_sorting, as_series) @skip_nested def test_where_series(self, data, na_value, as_frame): # Test setup fails. super().test_where_series(data, na_value, as_frame) @skip_nested @pytest.mark.parametrize("repeats", [0, 1, 2, [1, 2, 3]]) def test_repeat(self, data, repeats, as_series, use_numpy): # Fails creating expected super().test_repeat(data, repeats, as_series, use_numpy) @pytest.mark.xfail(reason="PandasArray.diff may fail on dtype") def test_diff(self, data, periods): return super().test_diff(data, periods) @skip_nested @pytest.mark.parametrize("box", [pd.array, pd.Series, pd.DataFrame]) def test_equals(self, data, na_value, as_series, box): # Fails creating with _from_sequence super().test_equals(data, na_value, as_series, box) @skip_nested class TestArithmetics(BaseNumPyTests, base.BaseArithmeticOpsTests): divmod_exc = None series_scalar_exc = None frame_scalar_exc = None series_array_exc = None def test_divmod_series_array(self, data): s = pd.Series(data) self._check_divmod_op(s, divmod, data, exc=None) @pytest.mark.skip("We implement ops") def test_error(self, data, all_arithmetic_operators): pass def test_arith_series_with_scalar(self, data, all_arithmetic_operators): super().test_arith_series_with_scalar(data, all_arithmetic_operators) def test_arith_series_with_array(self, data, all_arithmetic_operators): super().test_arith_series_with_array(data, all_arithmetic_operators) class TestPrinting(BaseNumPyTests, base.BasePrintingTests): pass @skip_nested class TestNumericReduce(BaseNumPyTests, base.BaseNumericReduceTests): def check_reduce(self, s, op_name, skipna): result = getattr(s, op_name)(skipna=skipna) # avoid coercing int -> float. Just cast to the actual numpy type. expected = getattr(s.astype(s.dtype._dtype), op_name)(skipna=skipna) tm.assert_almost_equal(result, expected) @skip_nested class TestBooleanReduce(BaseNumPyTests, base.BaseBooleanReduceTests): pass class TestMissing(BaseNumPyTests, base.BaseMissingTests): @skip_nested def test_fillna_scalar(self, data_missing): # Non-scalar "scalar" values. super().test_fillna_scalar(data_missing) @skip_nested def test_fillna_series_method(self, data_missing, fillna_method): # Non-scalar "scalar" values. super().test_fillna_series_method(data_missing, fillna_method) @skip_nested def test_fillna_series(self, data_missing): # Non-scalar "scalar" values. super().test_fillna_series(data_missing) @skip_nested def test_fillna_frame(self, data_missing): # Non-scalar "scalar" values. super().test_fillna_frame(data_missing) @pytest.mark.skip("Invalid test") def test_fillna_fill_other(self, data): # inplace update doesn't work correctly with patched extension arrays # extract_array returns PandasArray, while dtype is a numpy dtype super().test_fillna_fill_other(data_missing) class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): @pytest.mark.skip("Incorrect parent test") # not actually a mixed concat, since we concat int and int. def test_concat_mixed_dtypes(self, data): super().test_concat_mixed_dtypes(data) @pytest.mark.xfail( reason="GH#33125 PandasArray.astype does not recognize PandasDtype" ) def test_concat(self, data, in_frame): super().test_concat(data, in_frame) @pytest.mark.xfail( reason="GH#33125 PandasArray.astype does not recognize PandasDtype" ) def test_concat_all_na_block(self, data_missing, in_frame): super().test_concat_all_na_block(data_missing, in_frame) @skip_nested def test_merge(self, data, na_value): # Fails creating expected super().test_merge(data, na_value) @skip_nested def test_merge_on_extension_array(self, data): # Fails creating expected super().test_merge_on_extension_array(data) @skip_nested def test_merge_on_extension_array_duplicates(self, data): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) @skip_nested def test_transpose_frame(self, data): super().test_transpose_frame(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_nested def test_setitem_scalar_series(self, data, box_in_series): # AssertionError super().test_setitem_scalar_series(data, box_in_series) @skip_nested def test_setitem_sequence(self, data, box_in_series): # ValueError: shape mismatch: value array of shape (2,1) could not # be broadcast to indexing result of shape (2,) super().test_setitem_sequence(data, box_in_series) @skip_nested def test_setitem_sequence_mismatched_length_raises(self, data, as_array): # ValueError: PandasArray must be 1-dimensional. super().test_setitem_sequence_mismatched_length_raises(data, as_array) @skip_nested def test_setitem_sequence_broadcasts(self, data, box_in_series): # ValueError: cannot set using a list-like indexer with a different # length than the value super().test_setitem_sequence_broadcasts(data, box_in_series) @skip_nested def test_setitem_loc_scalar_mixed(self, data): # AssertionError super().test_setitem_loc_scalar_mixed(data) @skip_nested def test_setitem_loc_scalar_multiple_homogoneous(self, data): # AssertionError super().test_setitem_loc_scalar_multiple_homogoneous(data) @skip_nested def test_setitem_iloc_scalar_mixed(self, data): # AssertionError super().test_setitem_iloc_scalar_mixed(data) @skip_nested def test_setitem_iloc_scalar_multiple_homogoneous(self, data): # AssertionError super().test_setitem_iloc_scalar_multiple_homogoneous(data) @skip_nested @pytest.mark.parametrize("setter", ["loc", None]) def test_setitem_mask_broadcast(self, data, setter): # ValueError: cannot set using a list-like indexer with a different # length than the value super().test_setitem_mask_broadcast(data, setter) @skip_nested def test_setitem_scalar_key_sequence_raise(self, data): # Failed: DID NOT RAISE <class 'ValueError'> super().test_setitem_scalar_key_sequence_raise(data) # TODO: there is some issue with PandasArray, therefore, # skip the setitem test for now, and fix it later (GH 31446) @skip_nested @pytest.mark.parametrize( "mask", [ np.array([True, True, True, False, False]), pd.array([True, True, True, False, False], dtype="boolean"), ], ids=["numpy-array", "boolean-array"], ) def test_setitem_mask(self, data, mask, box_in_series): super().test_setitem_mask(data, mask, box_in_series) @skip_nested def test_setitem_mask_raises(self, data, box_in_series): super().test_setitem_mask_raises(data, box_in_series) @skip_nested @pytest.mark.parametrize( "idx", [[0, 1, 2], pd.array([0, 1, 2], dtype="Int64"), np.array([0, 1, 2])], ids=["list", "integer-array", "numpy-array"], ) def test_setitem_integer_array(self, data, idx, box_in_series): super().test_setitem_integer_array(data, idx, box_in_series) @skip_nested @pytest.mark.parametrize( "idx, box_in_series", [ ([0, 1, 2, pd.NA], False), pytest.param([0, 1, 2, pd.NA], True, marks=pytest.mark.xfail), (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False), (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False), ], ids=["list-False", "list-True", "integer-array-False", "integer-array-True"], ) def test_setitem_integer_with_missing_raises(self, data, idx, box_in_series): super().test_setitem_integer_with_missing_raises(data, idx, box_in_series) @skip_nested def test_setitem_slice(self, data, box_in_series): super().test_setitem_slice(data, box_in_series) @skip_nested def test_setitem_loc_iloc_slice(self, data): super().test_setitem_loc_iloc_slice(data) @skip_nested class TestParsing(BaseNumPyTests, base.BaseParsingTests): pass
bsd-3-clause
jpautom/scikit-learn
sklearn/decomposition/dict_learning.py
20
46133
""" Dictionary learning """ from __future__ import print_function # Author: Vlad Niculae, Gael Varoquaux, Alexandre Gramfort # License: BSD 3 clause import time import sys import itertools from math import sqrt, ceil import numpy as np from scipy import linalg from numpy.lib.stride_tricks import as_strided from ..base import BaseEstimator, TransformerMixin from ..externals.joblib import Parallel, delayed, cpu_count from ..externals.six.moves import zip from ..utils import (check_array, check_random_state, gen_even_slices, gen_batches, _get_n_jobs) from ..utils.extmath import randomized_svd, row_norms from ..utils.validation import check_is_fitted from ..linear_model import Lasso, orthogonal_mp_gram, LassoLars, Lars def _sparse_encode(X, dictionary, gram, cov=None, algorithm='lasso_lars', regularization=None, copy_cov=True, init=None, max_iter=1000, check_input=True, verbose=0): """Generic sparse coding Each column of the result is the solution to a Lasso problem. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix. dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows. gram: None | array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' gram can be None if method is 'threshold'. cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary * X' algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than regularization from the projection dictionary * data' regularization : int | float The regularization parameter. It corresponds to alpha when algorithm is 'lasso_lars', 'lasso_cd' or 'threshold'. Otherwise it corresponds to n_nonzero_coefs. init: array of shape (n_samples, n_components) Initialization value of the sparse code. Only used if `algorithm='lasso_cd'`. max_iter: int, 1000 by default Maximum number of iterations to perform if `algorithm='lasso_cd'`. copy_cov: boolean, optional Whether to copy the precomputed covariance matrix; if False, it may be overwritten. check_input: boolean, optional If False, the input arrays X and dictionary will not be checked. verbose: int Controls the verbosity; the higher, the more messages. Defaults to 0. Returns ------- code: array of shape (n_components, n_features) The sparse codes See also -------- sklearn.linear_model.lars_path sklearn.linear_model.orthogonal_mp sklearn.linear_model.Lasso SparseCoder """ if X.ndim == 1: X = X[:, np.newaxis] n_samples, n_features = X.shape if cov is None and algorithm != 'lasso_cd': # overwriting cov is safe copy_cov = False cov = np.dot(dictionary, X.T) if algorithm == 'lasso_lars': alpha = float(regularization) / n_features # account for scaling try: err_mgt = np.seterr(all='ignore') # Not passing in verbose=max(0, verbose-1) because Lars.fit already # corrects the verbosity level. lasso_lars = LassoLars(alpha=alpha, fit_intercept=False, verbose=verbose, normalize=False, precompute=gram, fit_path=False) lasso_lars.fit(dictionary.T, X.T, Xy=cov) new_code = lasso_lars.coef_ finally: np.seterr(**err_mgt) elif algorithm == 'lasso_cd': alpha = float(regularization) / n_features # account for scaling # TODO: Make verbosity argument for Lasso? # sklearn.linear_model.coordinate_descent.enet_path has a verbosity # argument that we could pass in from Lasso. clf = Lasso(alpha=alpha, fit_intercept=False, normalize=False, precompute=gram, max_iter=max_iter, warm_start=True) clf.coef_ = init clf.fit(dictionary.T, X.T, check_input=check_input) new_code = clf.coef_ elif algorithm == 'lars': try: err_mgt = np.seterr(all='ignore') # Not passing in verbose=max(0, verbose-1) because Lars.fit already # corrects the verbosity level. lars = Lars(fit_intercept=False, verbose=verbose, normalize=False, precompute=gram, n_nonzero_coefs=int(regularization), fit_path=False) lars.fit(dictionary.T, X.T, Xy=cov) new_code = lars.coef_ finally: np.seterr(**err_mgt) elif algorithm == 'threshold': new_code = ((np.sign(cov) * np.maximum(np.abs(cov) - regularization, 0)).T) elif algorithm == 'omp': # TODO: Should verbose argument be passed to this? new_code = orthogonal_mp_gram( Gram=gram, Xy=cov, n_nonzero_coefs=int(regularization), tol=None, norms_squared=row_norms(X, squared=True), copy_Xy=copy_cov).T else: raise ValueError('Sparse coding method must be "lasso_lars" ' '"lasso_cd", "lasso", "threshold" or "omp", got %s.' % algorithm) return new_code # XXX : could be moved to the linear_model module def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, max_iter=1000, n_jobs=1, check_input=True, verbose=0): """Sparse coding Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array `code` such that:: X ~= code * dictionary Read more in the :ref:`User Guide <SparseCoder>`. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output. gram: array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary' * X algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection dictionary * X' n_nonzero_coefs: int, 0.1 * n_features by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. alpha: float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threhold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. init: array of shape (n_samples, n_components) Initialization value of the sparse codes. Only used if `algorithm='lasso_cd'`. max_iter: int, 1000 by default Maximum number of iterations to perform if `algorithm='lasso_cd'`. copy_cov: boolean, optional Whether to copy the precomputed covariance matrix; if False, it may be overwritten. n_jobs: int, optional Number of parallel jobs to run. check_input: boolean, optional If False, the input arrays X and dictionary will not be checked. verbose : int, optional Controls the verbosity; the higher, the more messages. Defaults to 0. Returns ------- code: array of shape (n_samples, n_components) The sparse codes See also -------- sklearn.linear_model.lars_path sklearn.linear_model.orthogonal_mp sklearn.linear_model.Lasso SparseCoder """ if check_input: if algorithm == 'lasso_cd': dictionary = check_array(dictionary, order='C', dtype='float64') X = check_array(X, order='C', dtype='float64') else: dictionary = check_array(dictionary) X = check_array(X) n_samples, n_features = X.shape n_components = dictionary.shape[0] if gram is None and algorithm != 'threshold': gram = np.dot(dictionary, dictionary.T) if cov is None and algorithm != 'lasso_cd': copy_cov = False cov = np.dot(dictionary, X.T) if algorithm in ('lars', 'omp'): regularization = n_nonzero_coefs if regularization is None: regularization = min(max(n_features / 10, 1), n_components) else: regularization = alpha if regularization is None: regularization = 1. if n_jobs == 1 or algorithm == 'threshold': code = _sparse_encode(X, dictionary, gram, cov=cov, algorithm=algorithm, regularization=regularization, copy_cov=copy_cov, init=init, max_iter=max_iter, check_input=False, verbose=verbose) # This ensure that dimensionality of code is always 2, # consistant with the case n_jobs > 1 if code.ndim == 1: code = code[np.newaxis, :] return code # Enter parallel code block code = np.empty((n_samples, n_components)) slices = list(gen_even_slices(n_samples, _get_n_jobs(n_jobs))) code_views = Parallel(n_jobs=n_jobs, verbose=verbose)( delayed(_sparse_encode)( X[this_slice], dictionary, gram, cov[:, this_slice] if cov is not None else None, algorithm, regularization=regularization, copy_cov=copy_cov, init=init[this_slice] if init is not None else None, max_iter=max_iter, check_input=False) for this_slice in slices) for this_slice, this_view in zip(slices, code_views): code[this_slice] = this_view return code def _update_dict(dictionary, Y, code, verbose=False, return_r2=False, random_state=None): """Update the dense dictionary factor in place. Parameters ---------- dictionary: array of shape (n_features, n_components) Value of the dictionary at the previous iteration. Y: array of shape (n_features, n_samples) Data matrix. code: array of shape (n_components, n_samples) Sparse coding of the data against which to optimize the dictionary. verbose: Degree of output the procedure will print. return_r2: bool Whether to compute and return the residual sum of squares corresponding to the computed solution. random_state: int or RandomState Pseudo number generator state used for random sampling. Returns ------- dictionary: array of shape (n_features, n_components) Updated dictionary. """ n_components = len(code) n_samples = Y.shape[0] random_state = check_random_state(random_state) # Residuals, computed 'in-place' for efficiency R = -np.dot(dictionary, code) R += Y R = np.asfortranarray(R) ger, = linalg.get_blas_funcs(('ger',), (dictionary, code)) for k in range(n_components): # R <- 1.0 * U_k * V_k^T + R R = ger(1.0, dictionary[:, k], code[k, :], a=R, overwrite_a=True) dictionary[:, k] = np.dot(R, code[k, :].T) # Scale k'th atom atom_norm_square = np.dot(dictionary[:, k], dictionary[:, k]) if atom_norm_square < 1e-20: if verbose == 1: sys.stdout.write("+") sys.stdout.flush() elif verbose: print("Adding new random atom") dictionary[:, k] = random_state.randn(n_samples) # Setting corresponding coefs to 0 code[k, :] = 0.0 dictionary[:, k] /= sqrt(np.dot(dictionary[:, k], dictionary[:, k])) else: dictionary[:, k] /= sqrt(atom_norm_square) # R <- -1.0 * U_k * V_k^T + R R = ger(-1.0, dictionary[:, k], code[k, :], a=R, overwrite_a=True) if return_r2: R **= 2 # R is fortran-ordered. For numpy version < 1.6, sum does not # follow the quick striding first, and is thus inefficient on # fortran ordered data. We take a flat view of the data with no # striding R = as_strided(R, shape=(R.size, ), strides=(R.dtype.itemsize,)) R = np.sum(R) return dictionary, R return dictionary def dict_learning(X, n_components, alpha, max_iter=100, tol=1e-8, method='lars', n_jobs=1, dict_init=None, code_init=None, callback=None, verbose=False, random_state=None, return_n_iter=False): """Solves a dictionary learning matrix factorization problem. Finds the best dictionary and the corresponding sparse code for approximating the data matrix X by solving:: (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components where V is the dictionary and U is the sparse code. Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix. n_components: int, Number of dictionary atoms to extract. alpha: int, Sparsity controlling parameter. max_iter: int, Maximum number of iterations to perform. tol: float, Tolerance for the stopping condition. method: {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. n_jobs: int, Number of parallel jobs to run, or -1 to autodetect. dict_init: array of shape (n_components, n_features), Initial value for the dictionary for warm restart scenarios. code_init: array of shape (n_samples, n_components), Initial value for the sparse code for warm restart scenarios. callback: Callable that gets invoked every five iterations. verbose: Degree of output the procedure will print. random_state: int or RandomState Pseudo number generator state used for random sampling. return_n_iter : bool Whether or not to return the number of iterations. Returns ------- code: array of shape (n_samples, n_components) The sparse code factor in the matrix factorization. dictionary: array of shape (n_components, n_features), The dictionary factor in the matrix factorization. errors: array Vector of errors at each iteration. n_iter : int Number of iterations run. Returned only if `return_n_iter` is set to True. See also -------- dict_learning_online DictionaryLearning MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA """ if method not in ('lars', 'cd'): raise ValueError('Coding method %r not supported as a fit algorithm.' % method) method = 'lasso_' + method t0 = time.time() # Avoid integer division problems alpha = float(alpha) random_state = check_random_state(random_state) if n_jobs == -1: n_jobs = cpu_count() # Init the code and the dictionary with SVD of Y if code_init is not None and dict_init is not None: code = np.array(code_init, order='F') # Don't copy V, it will happen below dictionary = dict_init else: code, S, dictionary = linalg.svd(X, full_matrices=False) dictionary = S[:, np.newaxis] * dictionary r = len(dictionary) if n_components <= r: # True even if n_components=None code = code[:, :n_components] dictionary = dictionary[:n_components, :] else: code = np.c_[code, np.zeros((len(code), n_components - r))] dictionary = np.r_[dictionary, np.zeros((n_components - r, dictionary.shape[1]))] # Fortran-order dict, as we are going to access its row vectors dictionary = np.array(dictionary, order='F') residuals = 0 errors = [] current_cost = np.nan if verbose == 1: print('[dict_learning]', end=' ') # If max_iter is 0, number of iterations returned should be zero ii = -1 for ii in range(max_iter): dt = (time.time() - t0) if verbose == 1: sys.stdout.write(".") sys.stdout.flush() elif verbose: print("Iteration % 3i " "(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)" % (ii, dt, dt / 60, current_cost)) # Update code code = sparse_encode(X, dictionary, algorithm=method, alpha=alpha, init=code, n_jobs=n_jobs) # Update dictionary dictionary, residuals = _update_dict(dictionary.T, X.T, code.T, verbose=verbose, return_r2=True, random_state=random_state) dictionary = dictionary.T # Cost function current_cost = 0.5 * residuals + alpha * np.sum(np.abs(code)) errors.append(current_cost) if ii > 0: dE = errors[-2] - errors[-1] # assert(dE >= -tol * errors[-1]) if dE < tol * errors[-1]: if verbose == 1: # A line return print("") elif verbose: print("--- Convergence reached after %d iterations" % ii) break if ii % 5 == 0 and callback is not None: callback(locals()) if return_n_iter: return code, dictionary, errors, ii + 1 else: return code, dictionary, errors def dict_learning_online(X, n_components=2, alpha=1, n_iter=100, return_code=True, dict_init=None, callback=None, batch_size=3, verbose=False, shuffle=True, n_jobs=1, method='lars', iter_offset=0, random_state=None, return_inner_stats=False, inner_stats=None, return_n_iter=False): """Solves a dictionary learning matrix factorization problem online. Finds the best dictionary and the corresponding sparse code for approximating the data matrix X by solving:: (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components where V is the dictionary and U is the sparse code. This is accomplished by repeatedly iterating over mini-batches by slicing the input data. Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix. n_components : int, Number of dictionary atoms to extract. alpha : float, Sparsity controlling parameter. n_iter : int, Number of iterations to perform. return_code : boolean, Whether to also return the code U or just the dictionary V. dict_init : array of shape (n_components, n_features), Initial value for the dictionary for warm restart scenarios. callback : Callable that gets invoked every five iterations. batch_size : int, The number of samples to take in each batch. verbose : Degree of output the procedure will print. shuffle : boolean, Whether to shuffle the data before splitting it in batches. n_jobs : int, Number of parallel jobs to run, or -1 to autodetect. method : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. iter_offset : int, default 0 Number of previous iterations completed on the dictionary used for initialization. random_state : int or RandomState Pseudo number generator state used for random sampling. return_inner_stats : boolean, optional Return the inner statistics A (dictionary covariance) and B (data approximation). Useful to restart the algorithm in an online setting. If return_inner_stats is True, return_code is ignored inner_stats : tuple of (A, B) ndarrays Inner sufficient statistics that are kept by the algorithm. Passing them at initialization is useful in online settings, to avoid loosing the history of the evolution. A (n_components, n_components) is the dictionary covariance matrix. B (n_features, n_components) is the data approximation matrix return_n_iter : bool Whether or not to return the number of iterations. Returns ------- code : array of shape (n_samples, n_components), the sparse code (only returned if `return_code=True`) dictionary : array of shape (n_components, n_features), the solutions to the dictionary learning problem n_iter : int Number of iterations run. Returned only if `return_n_iter` is set to `True`. See also -------- dict_learning DictionaryLearning MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA """ if n_components is None: n_components = X.shape[1] if method not in ('lars', 'cd'): raise ValueError('Coding method not supported as a fit algorithm.') method = 'lasso_' + method t0 = time.time() n_samples, n_features = X.shape # Avoid integer division problems alpha = float(alpha) random_state = check_random_state(random_state) if n_jobs == -1: n_jobs = cpu_count() # Init V with SVD of X if dict_init is not None: dictionary = dict_init else: _, S, dictionary = randomized_svd(X, n_components, random_state=random_state) dictionary = S[:, np.newaxis] * dictionary r = len(dictionary) if n_components <= r: dictionary = dictionary[:n_components, :] else: dictionary = np.r_[dictionary, np.zeros((n_components - r, dictionary.shape[1]))] if verbose == 1: print('[dict_learning]', end=' ') if shuffle: X_train = X.copy() random_state.shuffle(X_train) else: X_train = X dictionary = check_array(dictionary.T, order='F', dtype=np.float64, copy=False) X_train = check_array(X_train, order='C', dtype=np.float64, copy=False) batches = gen_batches(n_samples, batch_size) batches = itertools.cycle(batches) # The covariance of the dictionary if inner_stats is None: A = np.zeros((n_components, n_components)) # The data approximation B = np.zeros((n_features, n_components)) else: A = inner_stats[0].copy() B = inner_stats[1].copy() # If n_iter is zero, we need to return zero. ii = iter_offset - 1 for ii, batch in zip(range(iter_offset, iter_offset + n_iter), batches): this_X = X_train[batch] dt = (time.time() - t0) if verbose == 1: sys.stdout.write(".") sys.stdout.flush() elif verbose: if verbose > 10 or ii % ceil(100. / verbose) == 0: print ("Iteration % 3i (elapsed time: % 3is, % 4.1fmn)" % (ii, dt, dt / 60)) this_code = sparse_encode(this_X, dictionary.T, algorithm=method, alpha=alpha, n_jobs=n_jobs).T # Update the auxiliary variables if ii < batch_size - 1: theta = float((ii + 1) * batch_size) else: theta = float(batch_size ** 2 + ii + 1 - batch_size) beta = (theta + 1 - batch_size) / (theta + 1) A *= beta A += np.dot(this_code, this_code.T) B *= beta B += np.dot(this_X.T, this_code.T) # Update dictionary dictionary = _update_dict(dictionary, B, A, verbose=verbose, random_state=random_state) # XXX: Can the residuals be of any use? # Maybe we need a stopping criteria based on the amount of # modification in the dictionary if callback is not None: callback(locals()) if return_inner_stats: if return_n_iter: return dictionary.T, (A, B), ii - iter_offset + 1 else: return dictionary.T, (A, B) if return_code: if verbose > 1: print('Learning code...', end=' ') elif verbose == 1: print('|', end=' ') code = sparse_encode(X, dictionary.T, algorithm=method, alpha=alpha, n_jobs=n_jobs, check_input=False) if verbose > 1: dt = (time.time() - t0) print('done (total time: % 3is, % 4.1fmn)' % (dt, dt / 60)) if return_n_iter: return code, dictionary.T, ii - iter_offset + 1 else: return code, dictionary.T if return_n_iter: return dictionary.T, ii - iter_offset + 1 else: return dictionary.T class SparseCodingMixin(TransformerMixin): """Sparse coding mixin""" def _set_sparse_coding_params(self, n_components, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, split_sign=False, n_jobs=1): self.n_components = n_components self.transform_algorithm = transform_algorithm self.transform_n_nonzero_coefs = transform_n_nonzero_coefs self.transform_alpha = transform_alpha self.split_sign = split_sign self.n_jobs = n_jobs def transform(self, X, y=None): """Encode the data as a sparse combination of the dictionary atoms. Coding method is determined by the object parameter `transform_algorithm`. Parameters ---------- X : array of shape (n_samples, n_features) Test data to be transformed, must have the same number of features as the data used to train the model. Returns ------- X_new : array, shape (n_samples, n_components) Transformed data """ check_is_fitted(self, 'components_') # XXX : kwargs is not documented X = check_array(X) n_samples, n_features = X.shape code = sparse_encode( X, self.components_, algorithm=self.transform_algorithm, n_nonzero_coefs=self.transform_n_nonzero_coefs, alpha=self.transform_alpha, n_jobs=self.n_jobs) if self.split_sign: # feature vector is split into a positive and negative side n_samples, n_features = code.shape split_code = np.empty((n_samples, 2 * n_features)) split_code[:, :n_features] = np.maximum(code, 0) split_code[:, n_features:] = -np.minimum(code, 0) code = split_code return code class SparseCoder(BaseEstimator, SparseCodingMixin): """Sparse coding Finds a sparse representation of data against a fixed, precomputed dictionary. Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array `code` such that:: X ~= code * dictionary Read more in the :ref:`User Guide <SparseCoder>`. Parameters ---------- dictionary : array, [n_components, n_features] The dictionary atoms used for sparse coding. Lines are assumed to be normalized to unit norm. transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \ 'threshold'} Algorithm used to transform the data: lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection ``dictionary * X'`` transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. transform_alpha : float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. split_sign : bool, False by default Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers. n_jobs : int, number of parallel jobs to run Attributes ---------- components_ : array, [n_components, n_features] The unchanged dictionary atoms See also -------- DictionaryLearning MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA sparse_encode """ def __init__(self, dictionary, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, split_sign=False, n_jobs=1): self._set_sparse_coding_params(dictionary.shape[0], transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.components_ = dictionary def fit(self, X, y=None): """Do nothing and return the estimator unchanged This method is just there to implement the usual API and hence work in pipelines. """ return self class DictionaryLearning(BaseEstimator, SparseCodingMixin): """Dictionary learning Finds a dictionary (a set of atoms) that can best be used to represent data using a sparse code. Solves the optimization problem:: (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- n_components : int, number of dictionary elements to extract alpha : float, sparsity controlling parameter max_iter : int, maximum number of iterations to perform tol : float, tolerance for numerical error fit_algorithm : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. .. versionadded:: 0.17 *cd* coordinate descent method to improve speed. transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \ 'threshold'} Algorithm used to transform the data lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection ``dictionary * X'`` .. versionadded:: 0.17 *lasso_cd* coordinate descent method to improve speed. transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. transform_alpha : float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. split_sign : bool, False by default Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers. n_jobs : int, number of parallel jobs to run code_init : array of shape (n_samples, n_components), initial value for the code, for warm restart dict_init : array of shape (n_components, n_features), initial values for the dictionary, for warm restart verbose : degree of verbosity of the printed output random_state : int or RandomState Pseudo number generator state used for random sampling. Attributes ---------- components_ : array, [n_components, n_features] dictionary atoms extracted from the data error_ : array vector of errors at each iteration n_iter_ : int Number of iterations run. Notes ----- **References:** J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning for sparse coding (http://www.di.ens.fr/sierra/pdfs/icml09.pdf) See also -------- SparseCoder MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA """ def __init__(self, n_components=None, alpha=1, max_iter=1000, tol=1e-8, fit_algorithm='lars', transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, n_jobs=1, code_init=None, dict_init=None, verbose=False, split_sign=False, random_state=None): self._set_sparse_coding_params(n_components, transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.alpha = alpha self.max_iter = max_iter self.tol = tol self.fit_algorithm = fit_algorithm self.code_init = code_init self.dict_init = dict_init self.verbose = verbose self.random_state = random_state def fit(self, X, y=None): """Fit the model from data in X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- self: object Returns the object itself """ random_state = check_random_state(self.random_state) X = check_array(X) if self.n_components is None: n_components = X.shape[1] else: n_components = self.n_components V, U, E, self.n_iter_ = dict_learning( X, n_components, self.alpha, tol=self.tol, max_iter=self.max_iter, method=self.fit_algorithm, n_jobs=self.n_jobs, code_init=self.code_init, dict_init=self.dict_init, verbose=self.verbose, random_state=random_state, return_n_iter=True) self.components_ = U self.error_ = E return self class MiniBatchDictionaryLearning(BaseEstimator, SparseCodingMixin): """Mini-batch dictionary learning Finds a dictionary (a set of atoms) that can best be used to represent data using a sparse code. Solves the optimization problem:: (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- n_components : int, number of dictionary elements to extract alpha : float, sparsity controlling parameter n_iter : int, total number of iterations to perform fit_algorithm : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \ 'threshold'} Algorithm used to transform the data. lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection dictionary * X' transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. transform_alpha : float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. split_sign : bool, False by default Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers. n_jobs : int, number of parallel jobs to run dict_init : array of shape (n_components, n_features), initial value of the dictionary for warm restart scenarios verbose : degree of verbosity of the printed output batch_size : int, number of samples in each mini-batch shuffle : bool, whether to shuffle the samples before forming batches random_state : int or RandomState Pseudo number generator state used for random sampling. Attributes ---------- components_ : array, [n_components, n_features] components extracted from the data inner_stats_ : tuple of (A, B) ndarrays Internal sufficient statistics that are kept by the algorithm. Keeping them is useful in online settings, to avoid loosing the history of the evolution, but they shouldn't have any use for the end user. A (n_components, n_components) is the dictionary covariance matrix. B (n_features, n_components) is the data approximation matrix n_iter_ : int Number of iterations run. Notes ----- **References:** J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning for sparse coding (http://www.di.ens.fr/sierra/pdfs/icml09.pdf) See also -------- SparseCoder DictionaryLearning SparsePCA MiniBatchSparsePCA """ def __init__(self, n_components=None, alpha=1, n_iter=1000, fit_algorithm='lars', n_jobs=1, batch_size=3, shuffle=True, dict_init=None, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, verbose=False, split_sign=False, random_state=None): self._set_sparse_coding_params(n_components, transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.alpha = alpha self.n_iter = n_iter self.fit_algorithm = fit_algorithm self.dict_init = dict_init self.verbose = verbose self.shuffle = shuffle self.batch_size = batch_size self.split_sign = split_sign self.random_state = random_state def fit(self, X, y=None): """Fit the model from data in X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- self : object Returns the instance itself. """ random_state = check_random_state(self.random_state) X = check_array(X) U, (A, B), self.n_iter_ = dict_learning_online( X, self.n_components, self.alpha, n_iter=self.n_iter, return_code=False, method=self.fit_algorithm, n_jobs=self.n_jobs, dict_init=self.dict_init, batch_size=self.batch_size, shuffle=self.shuffle, verbose=self.verbose, random_state=random_state, return_inner_stats=True, return_n_iter=True) self.components_ = U # Keep track of the state of the algorithm to be able to do # some online fitting (partial_fit) self.inner_stats_ = (A, B) self.iter_offset_ = self.n_iter return self def partial_fit(self, X, y=None, iter_offset=None): """Updates the model using the data in X as a mini-batch. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. iter_offset: integer, optional The number of iteration on data batches that has been performed before this call to partial_fit. This is optional: if no number is passed, the memory of the object is used. Returns ------- self : object Returns the instance itself. """ if not hasattr(self, 'random_state_'): self.random_state_ = check_random_state(self.random_state) X = check_array(X) if hasattr(self, 'components_'): dict_init = self.components_ else: dict_init = self.dict_init inner_stats = getattr(self, 'inner_stats_', None) if iter_offset is None: iter_offset = getattr(self, 'iter_offset_', 0) U, (A, B) = dict_learning_online( X, self.n_components, self.alpha, n_iter=self.n_iter, method=self.fit_algorithm, n_jobs=self.n_jobs, dict_init=dict_init, batch_size=len(X), shuffle=False, verbose=self.verbose, return_code=False, iter_offset=iter_offset, random_state=self.random_state_, return_inner_stats=True, inner_stats=inner_stats) self.components_ = U # Keep track of the state of the algorithm to be able to do # some online fitting (partial_fit) self.inner_stats_ = (A, B) self.iter_offset_ = iter_offset + self.n_iter return self
bsd-3-clause
xuanyuanking/spark
python/pyspark/pandas/base.py
3
55960
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Base and utility classes for pandas-on-Spark objects. """ from abc import ABCMeta, abstractmethod from functools import wraps, partial from itertools import chain from typing import Any, Callable, Optional, Sequence, Tuple, Union, cast, TYPE_CHECKING import numpy as np import pandas as pd # noqa: F401 from pandas.api.types import is_list_like, CategoricalDtype from pyspark.sql import functions as F, Column, Window from pyspark.sql.types import ( DoubleType, FloatType, LongType, ) from pyspark import pandas as ps # For running doctests and reference resolution in PyCharm. from pyspark.pandas._typing import Axis, Dtype, IndexOpsLike, Label, SeriesOrIndex from pyspark.pandas.config import get_option, option_context from pyspark.pandas.internal import ( InternalField, InternalFrame, NATURAL_ORDER_COLUMN_NAME, SPARK_DEFAULT_INDEX_NAME, ) from pyspark.pandas.spark import functions as SF from pyspark.pandas.spark.accessors import SparkIndexOpsMethods from pyspark.pandas.typedef import extension_dtypes from pyspark.pandas.utils import ( combine_frames, same_anchor, scol_for, validate_axis, ERROR_MESSAGE_CANNOT_COMBINE, ) from pyspark.pandas.frame import DataFrame if TYPE_CHECKING: from pyspark.sql._typing import ColumnOrName # noqa: F401 (SPARK-34943) from pyspark.pandas.data_type_ops.base import DataTypeOps # noqa: F401 (SPARK-34943) from pyspark.pandas.series import Series # noqa: F401 (SPARK-34943) def should_alignment_for_column_op(self: SeriesOrIndex, other: SeriesOrIndex) -> bool: from pyspark.pandas.series import Series if isinstance(self, Series) and isinstance(other, Series): return not same_anchor(self, other) else: return self._internal.spark_frame is not other._internal.spark_frame def align_diff_index_ops( func: Callable[..., Column], this_index_ops: SeriesOrIndex, *args: Any ) -> SeriesOrIndex: """ Align the `IndexOpsMixin` objects and apply the function. Parameters ---------- func : The function to apply this_index_ops : IndexOpsMixin A base `IndexOpsMixin` object args : list of other arguments including other `IndexOpsMixin` objects Returns ------- `Index` if all `this_index_ops` and arguments are `Index`; otherwise `Series` """ from pyspark.pandas.indexes import Index from pyspark.pandas.series import Series, first_series cols = [arg for arg in args if isinstance(arg, IndexOpsMixin)] if isinstance(this_index_ops, Series) and all(isinstance(col, Series) for col in cols): combined = combine_frames( this_index_ops.to_frame(), *[cast(Series, col).rename(i) for i, col in enumerate(cols)], how="full" ) return column_op(func)( combined["this"]._psser_for(combined["this"]._internal.column_labels[0]), *[ combined["that"]._psser_for(label) for label in combined["that"]._internal.column_labels ] ).rename(this_index_ops.name) else: # This could cause as many counts, reset_index calls, joins for combining # as the number of `Index`s in `args`. So far it's fine since we can assume the ops # only work between at most two `Index`s. We might need to fix it in the future. self_len = len(this_index_ops) if any(len(col) != self_len for col in args if isinstance(col, IndexOpsMixin)): raise ValueError("operands could not be broadcast together with shapes") with option_context("compute.default_index_type", "distributed-sequence"): if isinstance(this_index_ops, Index) and all(isinstance(col, Index) for col in cols): return Index( column_op(func)( this_index_ops.to_series().reset_index(drop=True), *[ arg.to_series().reset_index(drop=True) if isinstance(arg, Index) else arg for arg in args ] ).sort_index(), name=this_index_ops.name, ) elif isinstance(this_index_ops, Series): this = cast(DataFrame, this_index_ops.reset_index()) that = [ cast(Series, col.to_series() if isinstance(col, Index) else col) .rename(i) .reset_index(drop=True) for i, col in enumerate(cols) ] combined = combine_frames(this, *that, how="full").sort_index() combined = combined.set_index( combined._internal.column_labels[: this_index_ops._internal.index_level] ) combined.index.names = this_index_ops._internal.index_names return column_op(func)( first_series(combined["this"]), *[ combined["that"]._psser_for(label) for label in combined["that"]._internal.column_labels ] ).rename(this_index_ops.name) else: this = cast(Index, this_index_ops).to_frame().reset_index(drop=True) that_series = next(col for col in cols if isinstance(col, Series)) that_frame = that_series._psdf[ [ cast(Series, col.to_series() if isinstance(col, Index) else col).rename(i) for i, col in enumerate(cols) ] ] combined = combine_frames(this, that_frame.reset_index()).sort_index() self_index = ( combined["this"].set_index(combined["this"]._internal.column_labels).index ) other = combined["that"].set_index( combined["that"]._internal.column_labels[: that_series._internal.index_level] ) other.index.names = that_series._internal.index_names return column_op(func)( self_index, *[ other._psser_for(label) for label, col in zip(other._internal.column_labels, cols) ] ).rename(that_series.name) def booleanize_null(scol: Column, f: Callable[..., Column]) -> Column: """ Booleanize Null in Spark Column """ comp_ops = [ getattr(Column, "__{}__".format(comp_op)) for comp_op in ["eq", "ne", "lt", "le", "ge", "gt"] ] if f in comp_ops: # if `f` is "!=", fill null with True otherwise False filler = f == Column.__ne__ scol = F.when(scol.isNull(), filler).otherwise(scol) return scol def column_op(f: Callable[..., Column]) -> Callable[..., SeriesOrIndex]: """ A decorator that wraps APIs taking/returning Spark Column so that pandas-on-Spark Series can be supported too. If this decorator is used for the `f` function that takes Spark Column and returns Spark Column, decorated `f` takes pandas-on-Spark Series as well and returns pandas-on-Spark Series. :param f: a function that takes Spark Column and returns Spark Column. :param self: pandas-on-Spark Series :param args: arguments that the function `f` takes. """ @wraps(f) def wrapper(self: SeriesOrIndex, *args: Any) -> SeriesOrIndex: from pyspark.pandas.indexes.base import Index from pyspark.pandas.series import Series # It is possible for the function `f` takes other arguments than Spark Column. # To cover this case, explicitly check if the argument is pandas-on-Spark Series and # extract Spark Column. For other arguments, they are used as are. cols = [arg for arg in args if isinstance(arg, (Series, Index))] if all(not should_alignment_for_column_op(self, col) for col in cols): # Same DataFrame anchors scol = f( self.spark.column, *[arg.spark.column if isinstance(arg, IndexOpsMixin) else arg for arg in args] ) field = InternalField.from_struct_field( self._internal.spark_frame.select(scol).schema[0], use_extension_dtypes=any( isinstance(col.dtype, extension_dtypes) for col in [self] + cols ), ) if not field.is_extension_dtype: scol = booleanize_null(scol, f).alias(field.name) if isinstance(self, Series) or not any(isinstance(col, Series) for col in cols): index_ops = self._with_new_scol(scol, field=field) else: psser = next(col for col in cols if isinstance(col, Series)) index_ops = psser._with_new_scol(scol, field=field) elif get_option("compute.ops_on_diff_frames"): index_ops = align_diff_index_ops(f, self, *args) else: raise ValueError(ERROR_MESSAGE_CANNOT_COMBINE) if not all(self.name == col.name for col in cols): index_ops = index_ops.rename(None) return index_ops return wrapper def numpy_column_op(f: Callable[..., Column]) -> Callable[..., SeriesOrIndex]: @wraps(f) def wrapper(self: SeriesOrIndex, *args: Any) -> SeriesOrIndex: # PySpark does not support NumPy type out of the box. For now, we convert NumPy types # into some primitive types understandable in PySpark. new_args = [] for arg in args: # TODO: This is a quick hack to support NumPy type. We should revisit this. if isinstance(self.spark.data_type, LongType) and isinstance(arg, np.timedelta64): new_args.append(float(arg / np.timedelta64(1, "s"))) else: new_args.append(arg) return column_op(f)(self, *new_args) return wrapper class IndexOpsMixin(object, metaclass=ABCMeta): """common ops mixin to support a unified interface / docs for Series / Index Assuming there are following attributes or properties and function. """ @property @abstractmethod def _internal(self) -> InternalFrame: pass @property @abstractmethod def _psdf(self) -> DataFrame: pass @abstractmethod def _with_new_scol( self: IndexOpsLike, scol: Column, *, field: Optional[InternalField] = None ) -> IndexOpsLike: pass @property @abstractmethod def _column_label(self) -> Optional[Label]: pass @property @abstractmethod def spark(self: IndexOpsLike) -> SparkIndexOpsMethods[IndexOpsLike]: pass @property def _dtype_op(self) -> "DataTypeOps": from pyspark.pandas.data_type_ops.base import DataTypeOps return DataTypeOps(self.dtype, self.spark.data_type) @abstractmethod def copy(self: IndexOpsLike) -> IndexOpsLike: pass # arithmetic operators def __neg__(self: IndexOpsLike) -> IndexOpsLike: return cast(IndexOpsLike, column_op(Column.__neg__)(self)) def __add__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.add(self, other) def __sub__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.sub(self, other) def __mul__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.mul(self, other) def __truediv__(self, other: Any) -> SeriesOrIndex: """ __truediv__ has different behaviour between pandas and PySpark for several cases. 1. When divide np.inf by zero, PySpark returns null whereas pandas returns np.inf 2. When divide positive number by zero, PySpark returns null whereas pandas returns np.inf 3. When divide -np.inf by zero, PySpark returns null whereas pandas returns -np.inf 4. When divide negative number by zero, PySpark returns null whereas pandas returns -np.inf +-------------------------------------------+ | dividend (divisor: 0) | PySpark | pandas | |-----------------------|---------|---------| | np.inf | null | np.inf | | -np.inf | null | -np.inf | | 10 | null | np.inf | | -10 | null | -np.inf | +-----------------------|---------|---------+ """ return self._dtype_op.truediv(self, other) def __mod__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.mod(self, other) def __radd__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.radd(self, other) def __rsub__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.rsub(self, other) def __rmul__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.rmul(self, other) def __rtruediv__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.rtruediv(self, other) def __floordiv__(self, other: Any) -> SeriesOrIndex: """ __floordiv__ has different behaviour between pandas and PySpark for several cases. 1. When divide np.inf by zero, PySpark returns null whereas pandas returns np.inf 2. When divide positive number by zero, PySpark returns null whereas pandas returns np.inf 3. When divide -np.inf by zero, PySpark returns null whereas pandas returns -np.inf 4. When divide negative number by zero, PySpark returns null whereas pandas returns -np.inf +-------------------------------------------+ | dividend (divisor: 0) | PySpark | pandas | |-----------------------|---------|---------| | np.inf | null | np.inf | | -np.inf | null | -np.inf | | 10 | null | np.inf | | -10 | null | -np.inf | +-----------------------|---------|---------+ """ return self._dtype_op.floordiv(self, other) def __rfloordiv__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.rfloordiv(self, other) def __rmod__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.rmod(self, other) def __pow__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.pow(self, other) def __rpow__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.rpow(self, other) def __abs__(self: IndexOpsLike) -> IndexOpsLike: return cast(IndexOpsLike, column_op(F.abs)(self)) # comparison operators def __eq__(self, other: Any) -> SeriesOrIndex: # type: ignore[override] return column_op(Column.__eq__)(self, other) def __ne__(self, other: Any) -> SeriesOrIndex: # type: ignore[override] return column_op(Column.__ne__)(self, other) __lt__ = column_op(Column.__lt__) __le__ = column_op(Column.__le__) __ge__ = column_op(Column.__ge__) __gt__ = column_op(Column.__gt__) def __invert__(self: IndexOpsLike) -> IndexOpsLike: return cast(IndexOpsLike, column_op(Column.__invert__)(self)) # `and`, `or`, `not` cannot be overloaded in Python, # so use bitwise operators as boolean operators def __and__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.__and__(self, other) def __or__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.__or__(self, other) def __rand__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.rand(self, other) def __ror__(self, other: Any) -> SeriesOrIndex: return self._dtype_op.ror(self, other) def __len__(self) -> int: return len(self._psdf) # NDArray Compat def __array_ufunc__( self, ufunc: Callable, method: str, *inputs: Any, **kwargs: Any ) -> SeriesOrIndex: from pyspark.pandas import numpy_compat # Try dunder methods first. result = numpy_compat.maybe_dispatch_ufunc_to_dunder_op( self, ufunc, method, *inputs, **kwargs ) # After that, we try with PySpark APIs. if result is NotImplemented: result = numpy_compat.maybe_dispatch_ufunc_to_spark_func( self, ufunc, method, *inputs, **kwargs ) if result is not NotImplemented: return cast(SeriesOrIndex, result) else: # TODO: support more APIs? raise NotImplementedError( "pandas-on-Spark objects currently do not support %s." % ufunc ) @property def dtype(self) -> Dtype: """Return the dtype object of the underlying data. Examples -------- >>> s = ps.Series([1, 2, 3]) >>> s.dtype dtype('int64') >>> s = ps.Series(list('abc')) >>> s.dtype dtype('O') >>> s = ps.Series(pd.date_range('20130101', periods=3)) >>> s.dtype dtype('<M8[ns]') >>> s.rename("a").to_frame().set_index("a").index.dtype dtype('<M8[ns]') """ return self._internal.data_fields[0].dtype @property def empty(self) -> bool: """ Returns true if the current object is empty. Otherwise, returns false. >>> ps.range(10).id.empty False >>> ps.range(0).id.empty True >>> ps.DataFrame({}, index=list('abc')).index.empty False """ return self._internal.resolved_copy.spark_frame.rdd.isEmpty() @property def hasnans(self) -> bool: """ Return True if it has any missing values. Otherwise, it returns False. >>> ps.DataFrame({}, index=list('abc')).index.hasnans False >>> ps.Series(['a', None]).hasnans True >>> ps.Series([1.0, 2.0, np.nan]).hasnans True >>> ps.Series([1, 2, 3]).hasnans False >>> (ps.Series([1.0, 2.0, np.nan]) + 1).hasnans True >>> ps.Series([1, 2, 3]).rename("a").to_frame().set_index("a").index.hasnans False """ sdf = self._internal.spark_frame scol = self.spark.column if isinstance(self.spark.data_type, (DoubleType, FloatType)): return sdf.select(F.max(scol.isNull() | F.isnan(scol))).collect()[0][0] else: return sdf.select(F.max(scol.isNull())).collect()[0][0] @property def is_monotonic(self) -> bool: """ Return boolean if values in the object are monotonically increasing. .. note:: the current implementation of is_monotonic requires to shuffle and aggregate multiple times to check the order locally and globally, which is potentially expensive. In case of multi-index, all data are transferred to single node which can easily cause out-of-memory error currently. .. note:: Disable the Spark config `spark.sql.optimizer.nestedSchemaPruning.enabled` for multi-index if you're using pandas-on-Spark < 1.7.0 with PySpark 3.1.1. Returns ------- is_monotonic : bool Examples -------- >>> ser = ps.Series(['1/1/2018', '3/1/2018', '4/1/2018']) >>> ser.is_monotonic True >>> df = ps.DataFrame({'dates': [None, '1/1/2018', '2/1/2018', '3/1/2018']}) >>> df.dates.is_monotonic False >>> df.index.is_monotonic True >>> ser = ps.Series([1]) >>> ser.is_monotonic True >>> ser = ps.Series([]) >>> ser.is_monotonic True >>> ser.rename("a").to_frame().set_index("a").index.is_monotonic True >>> ser = ps.Series([5, 4, 3, 2, 1], index=[1, 2, 3, 4, 5]) >>> ser.is_monotonic False >>> ser.index.is_monotonic True Support for MultiIndex >>> midx = ps.MultiIndex.from_tuples( ... [('x', 'a'), ('x', 'b'), ('y', 'c'), ('y', 'd'), ('z', 'e')]) >>> midx # doctest: +SKIP MultiIndex([('x', 'a'), ('x', 'b'), ('y', 'c'), ('y', 'd'), ('z', 'e')], ) >>> midx.is_monotonic True >>> midx = ps.MultiIndex.from_tuples( ... [('z', 'a'), ('z', 'b'), ('y', 'c'), ('y', 'd'), ('x', 'e')]) >>> midx # doctest: +SKIP MultiIndex([('z', 'a'), ('z', 'b'), ('y', 'c'), ('y', 'd'), ('x', 'e')], ) >>> midx.is_monotonic False """ return self._is_monotonic("increasing") is_monotonic_increasing = is_monotonic @property def is_monotonic_decreasing(self) -> bool: """ Return boolean if values in the object are monotonically decreasing. .. note:: the current implementation of is_monotonic_decreasing requires to shuffle and aggregate multiple times to check the order locally and globally, which is potentially expensive. In case of multi-index, all data are transferred to single node which can easily cause out-of-memory error currently. .. note:: Disable the Spark config `spark.sql.optimizer.nestedSchemaPruning.enabled` for multi-index if you're using pandas-on-Spark < 1.7.0 with PySpark 3.1.1. Returns ------- is_monotonic : bool Examples -------- >>> ser = ps.Series(['4/1/2018', '3/1/2018', '1/1/2018']) >>> ser.is_monotonic_decreasing True >>> df = ps.DataFrame({'dates': [None, '3/1/2018', '2/1/2018', '1/1/2018']}) >>> df.dates.is_monotonic_decreasing False >>> df.index.is_monotonic_decreasing False >>> ser = ps.Series([1]) >>> ser.is_monotonic_decreasing True >>> ser = ps.Series([]) >>> ser.is_monotonic_decreasing True >>> ser.rename("a").to_frame().set_index("a").index.is_monotonic_decreasing True >>> ser = ps.Series([5, 4, 3, 2, 1], index=[1, 2, 3, 4, 5]) >>> ser.is_monotonic_decreasing True >>> ser.index.is_monotonic_decreasing False Support for MultiIndex >>> midx = ps.MultiIndex.from_tuples( ... [('x', 'a'), ('x', 'b'), ('y', 'c'), ('y', 'd'), ('z', 'e')]) >>> midx # doctest: +SKIP MultiIndex([('x', 'a'), ('x', 'b'), ('y', 'c'), ('y', 'd'), ('z', 'e')], ) >>> midx.is_monotonic_decreasing False >>> midx = ps.MultiIndex.from_tuples( ... [('z', 'e'), ('z', 'd'), ('y', 'c'), ('y', 'b'), ('x', 'a')]) >>> midx # doctest: +SKIP MultiIndex([('z', 'a'), ('z', 'b'), ('y', 'c'), ('y', 'd'), ('x', 'e')], ) >>> midx.is_monotonic_decreasing True """ return self._is_monotonic("decreasing") def _is_locally_monotonic_spark_column(self, order: str) -> Column: window = ( Window.partitionBy(F.col("__partition_id")) .orderBy(NATURAL_ORDER_COLUMN_NAME) .rowsBetween(-1, -1) ) if order == "increasing": return (F.col("__origin") >= F.lag(F.col("__origin"), 1).over(window)) & F.col( "__origin" ).isNotNull() else: return (F.col("__origin") <= F.lag(F.col("__origin"), 1).over(window)) & F.col( "__origin" ).isNotNull() def _is_monotonic(self, order: str) -> bool: assert order in ("increasing", "decreasing") sdf = self._internal.spark_frame sdf = ( sdf.select( F.spark_partition_id().alias( "__partition_id" ), # Make sure we use the same partition id in the whole job. F.col(NATURAL_ORDER_COLUMN_NAME), self.spark.column.alias("__origin"), ) .select( F.col("__partition_id"), F.col("__origin"), self._is_locally_monotonic_spark_column(order).alias( "__comparison_within_partition" ), ) .groupby(F.col("__partition_id")) .agg( F.min(F.col("__origin")).alias("__partition_min"), F.max(F.col("__origin")).alias("__partition_max"), F.min(F.coalesce(F.col("__comparison_within_partition"), SF.lit(True))).alias( "__comparison_within_partition" ), ) ) # Now we're windowing the aggregation results without partition specification. # The number of rows here will be as the same of partitions, which is expected # to be small. window = Window.orderBy(F.col("__partition_id")).rowsBetween(-1, -1) if order == "increasing": comparison_col = F.col("__partition_min") >= F.lag(F.col("__partition_max"), 1).over( window ) else: comparison_col = F.col("__partition_min") <= F.lag(F.col("__partition_max"), 1).over( window ) sdf = sdf.select( comparison_col.alias("__comparison_between_partitions"), F.col("__comparison_within_partition"), ) ret = sdf.select( F.min(F.coalesce(F.col("__comparison_between_partitions"), SF.lit(True))) & F.min(F.coalesce(F.col("__comparison_within_partition"), SF.lit(True))) ).collect()[0][0] if ret is None: return True else: return ret @property def ndim(self) -> int: """ Return an int representing the number of array dimensions. Return 1 for Series / Index / MultiIndex. Examples -------- For Series >>> s = ps.Series([None, 1, 2, 3, 4], index=[4, 5, 2, 1, 8]) >>> s.ndim 1 For Index >>> s.index.ndim 1 For MultiIndex >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [1, 1, 1, 1, 1, 2, 1, 2, 2]]) >>> s = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx) >>> s.index.ndim 1 """ return 1 def astype(self: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike: """ Cast a pandas-on-Spark object to a specified dtype ``dtype``. Parameters ---------- dtype : data type Use a numpy.dtype or Python type to cast entire pandas object to the same type. Returns ------- casted : same type as caller See Also -------- to_datetime : Convert argument to datetime. Examples -------- >>> ser = ps.Series([1, 2], dtype='int32') >>> ser 0 1 1 2 dtype: int32 >>> ser.astype('int64') 0 1 1 2 dtype: int64 >>> ser.rename("a").to_frame().set_index("a").index.astype('int64') Int64Index([1, 2], dtype='int64', name='a') """ return self._dtype_op.astype(self, dtype) def isin(self: IndexOpsLike, values: Sequence[Any]) -> IndexOpsLike: """ Check whether `values` are contained in Series or Index. Return a boolean Series or Index showing whether each element in the Series matches an element in the passed sequence of `values` exactly. Parameters ---------- values : set or list-like The sequence of values to test. Returns ------- isin : Series (bool dtype) or Index (bool dtype) Examples -------- >>> s = ps.Series(['lama', 'cow', 'lama', 'beetle', 'lama', ... 'hippo'], name='animal') >>> s.isin(['cow', 'lama']) 0 True 1 True 2 True 3 False 4 True 5 False Name: animal, dtype: bool Passing a single string as ``s.isin('lama')`` will raise an error. Use a list of one element instead: >>> s.isin(['lama']) 0 True 1 False 2 True 3 False 4 True 5 False Name: animal, dtype: bool >>> s.rename("a").to_frame().set_index("a").index.isin(['lama']) Index([True, False, True, False, True, False], dtype='object', name='a') """ if not is_list_like(values): raise TypeError( "only list-like objects are allowed to be passed" " to isin(), you passed a [{values_type}]".format(values_type=type(values).__name__) ) values = values.tolist() if isinstance(values, np.ndarray) else list(values) return self._with_new_scol(self.spark.column.isin([SF.lit(v) for v in values])) def isnull(self: IndexOpsLike) -> IndexOpsLike: """ Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Returns ------- Series or Index : Mask of bool values for each element in Series that indicates whether an element is not an NA value. Examples -------- >>> ser = ps.Series([5, 6, np.NaN]) >>> ser.isna() # doctest: +NORMALIZE_WHITESPACE 0 False 1 False 2 True dtype: bool >>> ser.rename("a").to_frame().set_index("a").index.isna() Index([False, False, True], dtype='object', name='a') """ from pyspark.pandas.indexes import MultiIndex if isinstance(self, MultiIndex): raise NotImplementedError("isna is not defined for MultiIndex") return self._dtype_op.isnull(self) isna = isnull def notnull(self: IndexOpsLike) -> IndexOpsLike: """ Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values. Returns ------- Series or Index : Mask of bool values for each element in Series that indicates whether an element is not an NA value. Examples -------- Show which entries in a Series are not NA. >>> ser = ps.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.notna() 0 True 1 True 2 False dtype: bool >>> ser.rename("a").to_frame().set_index("a").index.notna() Index([True, True, False], dtype='object', name='a') """ from pyspark.pandas.indexes import MultiIndex if isinstance(self, MultiIndex): raise NotImplementedError("notna is not defined for MultiIndex") return (~self.isnull()).rename(self.name) # type: ignore notna = notnull # TODO: axis, skipna, and many arguments should be implemented. def all(self, axis: Axis = 0) -> bool: """ Return whether all elements are True. Returns True unless there at least one element within a series that is False or equivalent (e.g. zero or empty) Parameters ---------- axis : {0 or 'index'}, default 0 Indicate which axis or axes should be reduced. * 0 / 'index' : reduce the index, return a Series whose index is the original column labels. Examples -------- >>> ps.Series([True, True]).all() True >>> ps.Series([True, False]).all() False >>> ps.Series([0, 1]).all() False >>> ps.Series([1, 2, 3]).all() True >>> ps.Series([True, True, None]).all() True >>> ps.Series([True, False, None]).all() False >>> ps.Series([]).all() True >>> ps.Series([np.nan]).all() True >>> df = ps.Series([True, False, None]).rename("a").to_frame() >>> df.set_index("a").index.all() False """ axis = validate_axis(axis) if axis != 0: raise NotImplementedError('axis should be either 0 or "index" currently.') sdf = self._internal.spark_frame.select(self.spark.column) col = scol_for(sdf, sdf.columns[0]) # Note that we're ignoring `None`s here for now. # any and every was added as of Spark 3.0 # ret = sdf.select(F.expr("every(CAST(`%s` AS BOOLEAN))" % sdf.columns[0])).collect()[0][0] # Here we use min as its alternative: ret = sdf.select(F.min(F.coalesce(col.cast("boolean"), SF.lit(True)))).collect()[0][0] if ret is None: return True else: return ret # TODO: axis, skipna, and many arguments should be implemented. def any(self, axis: Axis = 0) -> bool: """ Return whether any element is True. Returns False unless there at least one element within a series that is True or equivalent (e.g. non-zero or non-empty). Parameters ---------- axis : {0 or 'index'}, default 0 Indicate which axis or axes should be reduced. * 0 / 'index' : reduce the index, return a Series whose index is the original column labels. Examples -------- >>> ps.Series([False, False]).any() False >>> ps.Series([True, False]).any() True >>> ps.Series([0, 0]).any() False >>> ps.Series([0, 1, 2]).any() True >>> ps.Series([False, False, None]).any() False >>> ps.Series([True, False, None]).any() True >>> ps.Series([]).any() False >>> ps.Series([np.nan]).any() False >>> df = ps.Series([True, False, None]).rename("a").to_frame() >>> df.set_index("a").index.any() True """ axis = validate_axis(axis) if axis != 0: raise NotImplementedError('axis should be either 0 or "index" currently.') sdf = self._internal.spark_frame.select(self.spark.column) col = scol_for(sdf, sdf.columns[0]) # Note that we're ignoring `None`s here for now. # any and every was added as of Spark 3.0 # ret = sdf.select(F.expr("any(CAST(`%s` AS BOOLEAN))" % sdf.columns[0])).collect()[0][0] # Here we use max as its alternative: ret = sdf.select(F.max(F.coalesce(col.cast("boolean"), SF.lit(False)))).collect()[0][0] if ret is None: return False else: return ret # TODO: add frep and axis parameter def shift( self: IndexOpsLike, periods: int = 1, fill_value: Optional[Any] = None ) -> IndexOpsLike: """ Shift Series/Index by desired number of periods. .. note:: the current implementation of shift uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- periods : int Number of periods to shift. Can be positive or negative. fill_value : object, optional The scalar value to use for newly introduced missing values. The default depends on the dtype of self. For numeric data, np.nan is used. Returns ------- Copy of input Series/Index, shifted. Examples -------- >>> df = ps.DataFrame({'Col1': [10, 20, 15, 30, 45], ... 'Col2': [13, 23, 18, 33, 48], ... 'Col3': [17, 27, 22, 37, 52]}, ... columns=['Col1', 'Col2', 'Col3']) >>> df.Col1.shift(periods=3) 0 NaN 1 NaN 2 NaN 3 10.0 4 20.0 Name: Col1, dtype: float64 >>> df.Col2.shift(periods=3, fill_value=0) 0 0 1 0 2 0 3 13 4 23 Name: Col2, dtype: int64 >>> df.index.shift(periods=3, fill_value=0) Int64Index([0, 0, 0, 0, 1], dtype='int64') """ return self._shift(periods, fill_value).spark.analyzed def _shift( self: IndexOpsLike, periods: int, fill_value: Any, *, part_cols: Sequence["ColumnOrName"] = () ) -> IndexOpsLike: if not isinstance(periods, int): raise TypeError("periods should be an int; however, got [%s]" % type(periods).__name__) col = self.spark.column window = ( Window.partitionBy(*part_cols) .orderBy(NATURAL_ORDER_COLUMN_NAME) .rowsBetween(-periods, -periods) ) lag_col = F.lag(col, periods).over(window) col = F.when(lag_col.isNull() | F.isnan(lag_col), fill_value).otherwise(lag_col) return self._with_new_scol(col, field=self._internal.data_fields[0].copy(nullable=True)) # TODO: Update Documentation for Bins Parameter when its supported def value_counts( self, normalize: bool = False, sort: bool = True, ascending: bool = False, bins: None = None, dropna: bool = True, ) -> "Series": """ Return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default. Parameters ---------- normalize : boolean, default False If True then the object returned will contain the relative frequencies of the unique values. sort : boolean, default True Sort by values. ascending : boolean, default False Sort in ascending order. bins : Not Yet Supported dropna : boolean, default True Don't include counts of NaN. Returns ------- counts : Series See Also -------- Series.count: Number of non-NA elements in a Series. Examples -------- For Series >>> df = ps.DataFrame({'x':[0, 0, 1, 1, 1, np.nan]}) >>> df.x.value_counts() # doctest: +NORMALIZE_WHITESPACE 1.0 3 0.0 2 Name: x, dtype: int64 With `normalize` set to `True`, returns the relative frequency by dividing all values by the sum of values. >>> df.x.value_counts(normalize=True) # doctest: +NORMALIZE_WHITESPACE 1.0 0.6 0.0 0.4 Name: x, dtype: float64 **dropna** With `dropna` set to `False` we can also see NaN index values. >>> df.x.value_counts(dropna=False) # doctest: +NORMALIZE_WHITESPACE 1.0 3 0.0 2 NaN 1 Name: x, dtype: int64 For Index >>> idx = ps.Index([3, 1, 2, 3, 4, np.nan]) >>> idx Float64Index([3.0, 1.0, 2.0, 3.0, 4.0, nan], dtype='float64') >>> idx.value_counts().sort_index() 1.0 1 2.0 1 3.0 2 4.0 1 dtype: int64 **sort** With `sort` set to `False`, the result wouldn't be sorted by number of count. >>> idx.value_counts(sort=True).sort_index() 1.0 1 2.0 1 3.0 2 4.0 1 dtype: int64 **normalize** With `normalize` set to `True`, returns the relative frequency by dividing all values by the sum of values. >>> idx.value_counts(normalize=True).sort_index() 1.0 0.2 2.0 0.2 3.0 0.4 4.0 0.2 dtype: float64 **dropna** With `dropna` set to `False` we can also see NaN index values. >>> idx.value_counts(dropna=False).sort_index() # doctest: +SKIP 1.0 1 2.0 1 3.0 2 4.0 1 NaN 1 dtype: int64 For MultiIndex. >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [1, 1, 1, 1, 1, 2, 1, 2, 2]]) >>> s = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx) >>> s.index # doctest: +SKIP MultiIndex([( 'lama', 'weight'), ( 'lama', 'weight'), ( 'lama', 'weight'), ( 'cow', 'weight'), ( 'cow', 'weight'), ( 'cow', 'length'), ('falcon', 'weight'), ('falcon', 'length'), ('falcon', 'length')], ) >>> s.index.value_counts().sort_index() (cow, length) 1 (cow, weight) 2 (falcon, length) 2 (falcon, weight) 1 (lama, weight) 3 dtype: int64 >>> s.index.value_counts(normalize=True).sort_index() (cow, length) 0.111111 (cow, weight) 0.222222 (falcon, length) 0.222222 (falcon, weight) 0.111111 (lama, weight) 0.333333 dtype: float64 If Index has name, keep the name up. >>> idx = ps.Index([0, 0, 0, 1, 1, 2, 3], name='pandas-on-Spark') >>> idx.value_counts().sort_index() 0 3 1 2 2 1 3 1 Name: pandas-on-Spark, dtype: int64 """ from pyspark.pandas.series import first_series if bins is not None: raise NotImplementedError("value_counts currently does not support bins") if dropna: sdf_dropna = self._internal.spark_frame.select(self.spark.column).dropna() else: sdf_dropna = self._internal.spark_frame.select(self.spark.column) index_name = SPARK_DEFAULT_INDEX_NAME column_name = self._internal.data_spark_column_names[0] sdf = sdf_dropna.groupby(scol_for(sdf_dropna, column_name).alias(index_name)).count() if sort: if ascending: sdf = sdf.orderBy(F.col("count")) else: sdf = sdf.orderBy(F.col("count").desc()) if normalize: sum = sdf_dropna.count() sdf = sdf.withColumn("count", F.col("count") / SF.lit(sum)) internal = InternalFrame( spark_frame=sdf, index_spark_columns=[scol_for(sdf, index_name)], column_labels=self._internal.column_labels, data_spark_columns=[scol_for(sdf, "count")], column_label_names=self._internal.column_label_names, ) return first_series(DataFrame(internal)) def nunique(self, dropna: bool = True, approx: bool = False, rsd: float = 0.05) -> int: """ Return number of unique elements in the object. Excludes NA values by default. Parameters ---------- dropna : bool, default True Don’t include NaN in the count. approx: bool, default False If False, will use the exact algorithm and return the exact number of unique. If True, it uses the HyperLogLog approximate algorithm, which is significantly faster for large amount of data. Note: This parameter is specific to pandas-on-Spark and is not found in pandas. rsd: float, default 0.05 Maximum estimation error allowed in the HyperLogLog algorithm. Note: Just like ``approx`` this parameter is specific to pandas-on-Spark. Returns ------- int See Also -------- DataFrame.nunique: Method nunique for DataFrame. Series.count: Count non-NA/null observations in the Series. Examples -------- >>> ps.Series([1, 2, 3, np.nan]).nunique() 3 >>> ps.Series([1, 2, 3, np.nan]).nunique(dropna=False) 4 On big data, we recommend using the approximate algorithm to speed up this function. The result will be very close to the exact unique count. >>> ps.Series([1, 2, 3, np.nan]).nunique(approx=True) 3 >>> idx = ps.Index([1, 1, 2, None]) >>> idx Float64Index([1.0, 1.0, 2.0, nan], dtype='float64') >>> idx.nunique() 2 >>> idx.nunique(dropna=False) 3 """ res = self._internal.spark_frame.select([self._nunique(dropna, approx, rsd)]) return res.collect()[0][0] def _nunique(self, dropna: bool = True, approx: bool = False, rsd: float = 0.05) -> Column: colname = self._internal.data_spark_column_names[0] count_fn = cast( Callable[[Column], Column], partial(F.approx_count_distinct, rsd=rsd) if approx else F.countDistinct, ) if dropna: return count_fn(self.spark.column).alias(colname) else: return ( count_fn(self.spark.column) + F.when( F.count(F.when(self.spark.column.isNull(), 1).otherwise(None)) >= 1, 1 ).otherwise(0) ).alias(colname) def take(self: IndexOpsLike, indices: Sequence[int]) -> IndexOpsLike: """ Return the elements in the given *positional* indices along an axis. This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object. Parameters ---------- indices : array-like An array of ints indicating which positions to take. Returns ------- taken : same type as caller An array-like containing the elements taken from the object. See Also -------- DataFrame.loc : Select a subset of a DataFrame by labels. DataFrame.iloc : Select a subset of a DataFrame by positions. numpy.take : Take elements from an array along an axis. Examples -------- Series >>> psser = ps.Series([100, 200, 300, 400, 500]) >>> psser 0 100 1 200 2 300 3 400 4 500 dtype: int64 >>> psser.take([0, 2, 4]).sort_index() 0 100 2 300 4 500 dtype: int64 Index >>> psidx = ps.Index([100, 200, 300, 400, 500]) >>> psidx Int64Index([100, 200, 300, 400, 500], dtype='int64') >>> psidx.take([0, 2, 4]).sort_values() Int64Index([100, 300, 500], dtype='int64') MultiIndex >>> psmidx = ps.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("x", "c")]) >>> psmidx # doctest: +SKIP MultiIndex([('x', 'a'), ('x', 'b'), ('x', 'c')], ) >>> psmidx.take([0, 2]) # doctest: +SKIP MultiIndex([('x', 'a'), ('x', 'c')], ) """ if not is_list_like(indices) or isinstance(indices, (dict, set)): raise TypeError("`indices` must be a list-like except dict or set") if isinstance(self, ps.Series): return cast(IndexOpsLike, self.iloc[indices]) else: return cast(IndexOpsLike, self._psdf.iloc[indices].index) def factorize( self: IndexOpsLike, sort: bool = True, na_sentinel: Optional[int] = -1 ) -> Tuple[IndexOpsLike, pd.Index]: """ Encode the object as an enumerated type or categorical variable. This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. Parameters ---------- sort : bool, default True na_sentinel : int or None, default -1 Value to mark "not found". If None, will not drop the NaN from the uniques of the values. Returns ------- codes : Series or Index A Series or Index that's an indexer into `uniques`. ``uniques.take(codes)`` will have the same values as `values`. uniques : pd.Index The unique valid values. .. note :: Even if there's a missing value in `values`, `uniques` will *not* contain an entry for it. Examples -------- >>> psser = ps.Series(['b', None, 'a', 'c', 'b']) >>> codes, uniques = psser.factorize() >>> codes 0 1 1 -1 2 0 3 2 4 1 dtype: int32 >>> uniques Index(['a', 'b', 'c'], dtype='object') >>> codes, uniques = psser.factorize(na_sentinel=None) >>> codes 0 1 1 3 2 0 3 2 4 1 dtype: int32 >>> uniques Index(['a', 'b', 'c', None], dtype='object') >>> codes, uniques = psser.factorize(na_sentinel=-2) >>> codes 0 1 1 -2 2 0 3 2 4 1 dtype: int32 >>> uniques Index(['a', 'b', 'c'], dtype='object') For Index: >>> psidx = ps.Index(['b', None, 'a', 'c', 'b']) >>> codes, uniques = psidx.factorize() >>> codes Int64Index([1, -1, 0, 2, 1], dtype='int64') >>> uniques Index(['a', 'b', 'c'], dtype='object') """ from pyspark.pandas.series import first_series assert (na_sentinel is None) or isinstance(na_sentinel, int) assert sort is True if isinstance(self.dtype, CategoricalDtype): categories = self.dtype.categories if len(categories) == 0: scol = SF.lit(None) else: kvs = list( chain( *[ (SF.lit(code), SF.lit(category)) for code, category in enumerate(categories) ] ) ) map_scol = F.create_map(*kvs) scol = map_scol.getItem(self.spark.column) codes, uniques = self._with_new_scol( scol.alias(self._internal.data_spark_column_names[0]) ).factorize(na_sentinel=na_sentinel) return codes, uniques.astype(self.dtype) uniq_sdf = self._internal.spark_frame.select(self.spark.column).distinct() # Check number of uniques and constructs sorted `uniques_list` max_compute_count = get_option("compute.max_rows") if max_compute_count is not None: uniq_pdf = uniq_sdf.limit(max_compute_count + 1).toPandas() if len(uniq_pdf) > max_compute_count: raise ValueError( "Current Series has more then {0} unique values. " "Please set 'compute.max_rows' by using 'pyspark.pandas.config.set_option' " "to more than {0} rows. Note that, before changing the " "'compute.max_rows', this operation is considerably expensive.".format( max_compute_count ) ) else: uniq_pdf = uniq_sdf.toPandas() # pandas takes both NaN and null in Spark to np.nan, so de-duplication is required uniq_series = first_series(uniq_pdf).drop_duplicates() uniques_list = uniq_series.tolist() uniques_list = sorted(uniques_list, key=lambda x: (pd.isna(x), x)) # Constructs `unique_to_code` mapping non-na unique to code unique_to_code = {} if na_sentinel is not None: na_sentinel_code = na_sentinel code = 0 for unique in uniques_list: if pd.isna(unique): if na_sentinel is None: na_sentinel_code = code else: unique_to_code[unique] = code code += 1 kvs = list( chain(*([(SF.lit(unique), SF.lit(code)) for unique, code in unique_to_code.items()])) ) if len(kvs) == 0: # uniques are all missing values new_scol = SF.lit(na_sentinel_code) else: scol = self.spark.column if isinstance(self.spark.data_type, (FloatType, DoubleType)): cond = scol.isNull() | F.isnan(scol) else: cond = scol.isNull() map_scol = F.create_map(*kvs) null_scol = F.when(cond, SF.lit(na_sentinel_code)) new_scol = null_scol.otherwise(map_scol.getItem(scol)) codes = self._with_new_scol(new_scol.alias(self._internal.data_spark_column_names[0])) if na_sentinel is not None: # Drops the NaN from the uniques of the values uniques_list = [x for x in uniques_list if not pd.isna(x)] uniques = pd.Index(uniques_list) return codes, uniques def _test() -> None: import os import doctest import sys from pyspark.sql import SparkSession import pyspark.pandas.base os.chdir(os.environ["SPARK_HOME"]) globs = pyspark.pandas.base.__dict__.copy() globs["ps"] = pyspark.pandas spark = ( SparkSession.builder.master("local[4]").appName("pyspark.pandas.base tests").getOrCreate() ) (failure_count, test_count) = doctest.testmod( pyspark.pandas.base, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE, ) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
apache-2.0
phobson/statsmodels
statsmodels/sandbox/distributions/genpareto.py
33
10406
# -*- coding: utf-8 -*- """ Created on Thu Aug 12 14:59:03 2010 Warning: not tried out or tested yet, Done Author: josef-pktd """ from __future__ import print_function import numpy as np from scipy import stats from scipy.misc import comb from scipy.stats.distributions import rv_continuous from numpy import where, inf from numpy import abs as np_abs ## Generalized Pareto with reversed sign of c as in literature class genpareto2_gen(rv_continuous): def _argcheck(self, c): c = np.asarray(c) self.b = where(c > 0, 1.0/np_abs(c), inf) return where(c==0, 0, 1) def _pdf(self, x, c): Px = np.power(1-c*x,-1.0+1.0/c) return Px def _logpdf(self, x, c): return (-1.0+1.0/c) * np.log1p(-c*x) def _cdf(self, x, c): return 1.0 - np.power(1-c*x,1.0/c) def _ppf(self, q, c): vals = -1.0/c * (np.power(1-q, c)-1) return vals def _munp(self, n, c): k = np.arange(0,n+1) val = (1.0/c)**n * np.sum(comb(n,k)*(-1)**k / (1.0+c*k),axis=0) return where(c*n > -1, val, inf) def _entropy(self, c): if (c < 0): return 1-c else: self.b = 1.0 / c return rv_continuous._entropy(self, c) genpareto2 = genpareto2_gen(a=0.0,name='genpareto', longname="A generalized Pareto", shapes='c',extradoc=""" Generalized Pareto distribution genpareto2.pdf(x,c) = (1+c*x)**(-1-1/c) for c != 0, and for x >= 0 for all c, and x < 1/abs(c) for c < 0. """ ) shape, loc, scale = 0.5, 0, 1 rv = np.arange(5) quant = [0.01, 0.1, 0.5, 0.9, 0.99] for method, x in [('pdf', rv), ('cdf', rv), ('sf', rv), ('ppf', quant), ('isf', quant)]: print(getattr(genpareto2, method)(x, shape, loc, scale)) print(getattr(stats.genpareto, method)(x, -shape, loc, scale)) print(genpareto2.stats(shape, loc, scale, moments='mvsk')) print(stats.genpareto.stats(-shape, loc, scale, moments='mvsk')) print(genpareto2.entropy(shape, loc, scale)) print(stats.genpareto.entropy(-shape, loc, scale)) def paramstopot(thresh, shape, scale): '''transform shape scale for peak over threshold y = x-u|x>u ~ GPD(k, sigma-k*u) if x ~ GPD(k, sigma) notation of de Zea Bermudez, Kotz k, sigma is shape, scale ''' return shape, scale - shape*thresh def paramsfrompot(thresh, shape, scalepot): return shape, scalepot + shape*thresh def warnif(cond, msg): if not cond: print(msg, 'does not hold') def meanexcess(thresh, shape, scale): '''mean excess function of genpareto assert are inequality conditions in de Zea Bermudez, Kotz ''' warnif(shape > -1, 'shape > -1') warnif(thresh >= 0, 'thresh >= 0') #make it weak inequality warnif((scale - shape*thresh) > 0, '(scale - shape*thresh) > 0') return (scale - shape*thresh) / (1 + shape) def meanexcess_plot(data, params=None, lidx=100, uidx=10, method='emp', plot=0): if method == 'est': #doesn't make much sense yet, #estimate the parameters and use theoretical meanexcess if params is None: raise NotImplementedError else: pass #estimate parames elif method == 'emp': #calculate meanexcess from data datasorted = np.sort(data) meanexcess = (datasorted[::-1].cumsum())/np.arange(1,len(data)+1) - datasorted[::-1] meanexcess = meanexcess[::-1] if plot: plt.plot(datasorted[:-uidx], meanexcess[:-uidx]) if not params is None: shape, scale = params plt.plot(datasorted[:-uidx], (scale - datasorted[:-uidx] * shape) / (1. + shape)) return datasorted, meanexcess print(meanexcess(5, -0.5, 10)) print(meanexcess(5, -2, 10)) import matplotlib.pyplot as plt data = genpareto2.rvs(-0.75, scale=5, size=1000) #data = np.random.uniform(50, size=1000) #data = stats.norm.rvs(0, np.sqrt(50), size=1000) #data = stats.pareto.rvs(1.5, np.sqrt(50), size=1000) tmp = meanexcess_plot(data, params=(-0.75, 5), plot=1) print(tmp[1][-20:]) print(tmp[0][-20:]) #plt.show() def meanexcess_emp(data): datasorted = np.sort(data).astype(float) meanexcess = (datasorted[::-1].cumsum())/np.arange(1,len(data)+1) - datasorted[::-1] meancont = (datasorted[::-1].cumsum())/np.arange(1,len(data)+1) meanexcess = meanexcess[::-1] return datasorted, meanexcess, meancont[::-1] def meanexcess_dist(self, lb, *args, **kwds): #default function in expect is identity # need args in call if np.ndim(lb) == 0: return self.expect(lb=lb, conditional=True) else: return np.array([self.expect(lb=lbb, conditional=True) for lbb in lb]) ds, me, mc = meanexcess_emp(1.*np.arange(1,10)) print(ds) print(me) print(mc) print(meanexcess_dist(stats.norm, lb=0.5)) print(meanexcess_dist(stats.norm, lb=[-np.inf, -0.5, 0, 0.5])) rvs = stats.norm.rvs(size=100000) rvs = rvs - rvs.mean() print(rvs.mean(), rvs[rvs>-0.5].mean(), rvs[rvs>0].mean(), rvs[rvs>0.5].mean()) ''' C:\Programs\Python25\lib\site-packages\matplotlib-0.99.1-py2.5-win32.egg\matplotlib\rcsetup.py:117: UserWarning: rcParams key "numerix" is obsolete and has no effect; please delete it from your matplotlibrc file warnings.warn('rcParams key "numerix" is obsolete and has no effect;\n' [ 1. 0.5 0. 0. 0. ] [ 1. 0.5 0. 0. 0. ] [ 0. 0.75 1. 1. 1. ] [ 0. 0.75 1. 1. 1. ] [ 1. 0.25 0. 0. 0. ] [ 1. 0.25 0. 0. 0. ] [ 0.01002513 0.1026334 0.58578644 1.36754447 1.8 ] [ 0.01002513 0.1026334 0.58578644 1.36754447 1.8 ] [ 1.8 1.36754447 0.58578644 0.1026334 0.01002513] [ 1.8 1.36754447 0.58578644 0.1026334 0.01002513] (array(0.66666666666666674), array(0.22222222222222243), array(0.56568542494923058), array(-0.60000000000032916)) (array(0.66666666666666674), array(0.22222222222222243), array(0.56568542494923058), array(-0.60000000000032916)) 0.5 0.5 25.0 shape > -1 does not hold -20 [ 41.4980671 42.83145298 44.24197578 45.81622844 47.57145212 49.52692287 51.70553275 54.0830766 56.61358997 59.53409167 62.8970042 66.73494156 71.04227973 76.24015612 82.71835988 89.79611663 99.4252195 106.2372462 94.83432424 0. ] [ 15.79736355 16.16373531 17.44204268 17.47968055 17.73264951 18.23939099 19.02638455 20.79746264 23.7169161 24.48807136 25.90496638 28.35556795 32.27623618 34.65714495 37.37093362 47.32957609 51.27970515 78.98913941 129.04309012 189.66864848] >>> np.arange(10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> meanexcess_emp(np.arange(10)) (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([4, 4, 5, 5, 5, 6, 6, 5, 4, 0]), array([9, 8, 8, 7, 7, 6, 6, 5, 5, 4])) >>> meanexcess_emp(1*np.arange(10)) (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([4, 4, 5, 5, 5, 6, 6, 5, 4, 0]), array([9, 8, 8, 7, 7, 6, 6, 5, 5, 4])) >>> meanexcess_emp(1.*np.arange(10)) (array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]), array([ 4.5 , 4.88888889, 5.25 , 5.57142857, 5.83333333, 6. , 6. , 5.66666667, 4.5 , 0. ]), array([ 9. , 8.5, 8. , 7.5, 7. , 6.5, 6. , 5.5, 5. , 4.5])) >>> meanexcess_emp(0.5**np.arange(10)) (array([ 0.00195313, 0.00390625, 0.0078125 , 0.015625 , 0.03125 , 0.0625 , 0.125 , 0.25 , 0.5 , 1. ]), array([ 0.19960938, 0.22135417, 0.24804688, 0.28125 , 0.32291667, 0.375 , 0.4375 , 0.5 , 0.5 , 0. ]), array([ 1. , 0.75 , 0.58333333, 0.46875 , 0.3875 , 0.328125 , 0.28348214, 0.24902344, 0.22178819, 0.19980469])) >>> meanexcess_emp(np.arange(10)**0.5) (array([ 0. , 1. , 1.41421356, 1.73205081, 2. , 2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ]), array([ 1.93060005, 2.03400006, 2.11147337, 2.16567659, 2.19328936, 2.18473364, 2.11854461, 1.94280904, 1.5 , 0. ]), array([ 3. , 2.91421356, 2.82472615, 2.73091704, 2.63194723, 2.52662269, 2.41311242, 2.28825007, 2.14511117, 1.93060005])) >>> meanexcess_emp(np.arange(10)**-2) (array([-2147483648, 0, 0, 0, 0, 0, 0, 0, 0, 1]), array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), array([ 1, 0, 0, 0, 0, 0, 0, 0, 0, -214748365])) >>> meanexcess_emp(np.arange(10)**(-0.5)) (array([ 0.33333333, 0.35355339, 0.37796447, 0.40824829, 0.4472136 , 0.5 , 0.57735027, 0.70710678, 1. , Inf]), array([ Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, NaN]), array([ Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf])) >>> np.arange(10)**(-0.5) array([ Inf, 1. , 0.70710678, 0.57735027, 0.5 , 0.4472136 , 0.40824829, 0.37796447, 0.35355339, 0.33333333]) >>> meanexcess_emp(np.arange(1,10)**(-0.5)) (array([ 0.33333333, 0.35355339, 0.37796447, 0.40824829, 0.4472136 , 0.5 , 0.57735027, 0.70710678, 1. ]), array([ 0.4857152 , 0.50223543, 0.51998842, 0.53861177, 0.55689141, 0.57111426, 0.56903559, 0.5 , 0. ]), array([ 1. , 0.85355339, 0.76148568, 0.69611426, 0.64633413, 0.60665316, 0.57398334, 0.5464296 , 0.52275224])) >>> meanexcess_emp(np.arange(1,10)) (array([1, 2, 3, 4, 5, 6, 7, 8, 9]), array([4, 5, 5, 5, 6, 6, 5, 4, 0]), array([9, 8, 8, 7, 7, 6, 6, 5, 5])) >>> meanexcess_emp(1.*np.arange(1,10)) (array([ 1., 2., 3., 4., 5., 6., 7., 8., 9.]), array([ 4.88888889, 5.25 , 5.57142857, 5.83333333, 6. , 6. , 5.66666667, 4.5 , 0. ]), array([ 9. , 8.5, 8. , 7.5, 7. , 6.5, 6. , 5.5, 5. ])) >>> datasorted = np.sort(1.*np.arange(1,10)) >>> (datasorted[::-1].cumsum()-datasorted[::-1]) array([ 0., 9., 17., 24., 30., 35., 39., 42., 44.]) >>> datasorted[::-1].cumsum() array([ 9., 17., 24., 30., 35., 39., 42., 44., 45.]) >>> datasorted[::-1] array([ 9., 8., 7., 6., 5., 4., 3., 2., 1.]) >>> '''
bsd-3-clause