repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_template.py
""" This is a fully functional do nothing backend to provide a template to backend writers. It is fully functional in that you can select it as a backend with import matplotlib matplotlib.use('Template') and your matplotlib scripts will (should!) run without error, though no output is produced. This provides a nice starting point for backend writers because you can selectively implement methods (draw_rectangle, draw_lines, etc...) and slowly see your figure come to life w/o having to have a full blown implementation before getting any results. Copy this to backend_xxx.py and replace all instances of 'template' with 'xxx'. Then implement the class methods and functions below, and add 'xxx' to the switchyard in matplotlib/backends/__init__.py and 'xxx' to the backends list in the validate_backend methon in matplotlib/__init__.py and you're off. You can use your backend with:: import matplotlib matplotlib.use('xxx') from pylab import * plot([1,2,3]) show() matplotlib also supports external backends, so you can place you can use any module in your PYTHONPATH with the syntax:: import matplotlib matplotlib.use('module://my_backend') where my_backend.py is your module name. This syntax is also recognized in the rc file and in the -d argument in pylab, e.g.,:: python simple_plot.py -dmodule://my_backend If your backend implements support for saving figures (i.e. has a print_xyz() method) you can register it as the default handler for a given file type from matplotlib.backend_bases import register_backend register_backend('xyz', 'my_backend', 'XYZ File Format') ... plt.savefig("figure.xyz") The files that are most relevant to backend_writers are matplotlib/backends/backend_your_backend.py matplotlib/backend_bases.py matplotlib/backends/__init__.py matplotlib/__init__.py matplotlib/_pylab_helpers.py Naming Conventions * classes Upper or MixedUpperCase * variables lower or lowerUpper * functions lower or underscore_separated """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) from matplotlib.figure import Figure class RendererTemplate(RendererBase): """ The renderer handles drawing/rendering operations. This is a minimal do-nothing class that can be used to get started when writing a new backend. Refer to backend_bases.RendererBase for documentation of the classes methods. """ def __init__(self, dpi): self.dpi = dpi def draw_path(self, gc, path, transform, rgbFace=None): pass # draw_markers is optional, and we get more correct relative # timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_markers(self, gc, marker_path, marker_trans, path, trans, # rgbFace=None): # pass # draw_path_collection is optional, and we get more correct # relative timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_path_collection(self, gc, master_transform, paths, # all_transforms, offsets, offsetTrans, # facecolors, edgecolors, linewidths, linestyles, # antialiaseds): # pass # draw_quad_mesh is optional, and we get more correct # relative timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight, # coordinates, offsets, offsetTrans, facecolors, # antialiased, edgecolors): # pass def draw_image(self, gc, x, y, im): pass def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): pass def flipy(self): return True def get_canvas_width_height(self): return 100, 100 def get_text_width_height_descent(self, s, prop, ismath): return 1, 1, 1 def new_gc(self): return GraphicsContextTemplate() def points_to_pixels(self, points): # if backend doesn't have dpi, e.g., postscript or svg return points # elif backend assumes a value for pixels_per_inch #return points/72.0 * self.dpi.get() * pixels_per_inch/72.0 # else #return points/72.0 * self.dpi.get() class GraphicsContextTemplate(GraphicsContextBase): """ The graphics context provides the color, line styles, etc... See the gtk and postscript backends for examples of mapping the graphics context attributes (cap styles, join styles, line widths, colors) to a particular backend. In GTK this is done by wrapping a gtk.gdk.GC object and forwarding the appropriate calls to it using a dictionary mapping styles to gdk constants. In Postscript, all the work is done by the renderer, mapping line styles to postscript calls. If it's more appropriate to do the mapping at the renderer level (as in the postscript backend), you don't need to override any of the GC methods. If it's more appropriate to wrap an instance (as in the GTK backend) and do the mapping here, you'll need to override several of the setter methods. The base GraphicsContext stores colors as a RGB tuple on the unit interval, e.g., (0.5, 0.0, 1.0). You may need to map this to colors appropriate for your backend. """ pass ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## def draw_if_interactive(): """ For image backends - is not required For GUI backends - this should be overridden if drawing should be done in interactive python mode """ def show(block=None): """ For image backends - is not required For GUI backends - show() is usually the last line of a pylab script and tells the backend that it is time to draw. In interactive mode, this may be a do nothing func. See the GTK backend for an example of how to handle interactive versus batch mode """ for manager in Gcf.get_all_fig_managers(): # do something to display the GUI pass def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # May be implemented via the `_new_figure_manager_template` helper. # If a main-level app must be created, this (and # new_figure_manager_given_figure) is the usual place to do it -- see # backend_wx, backend_wxagg and backend_tkagg for examples. Not all GUIs # require explicit instantiation of a main-level app (egg backend_gtk, # backend_gtkagg) for pylab. FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig) def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ # May be implemented via the `_new_figure_manager_template` helper. canvas = FigureCanvasTemplate(figure) manager = FigureManagerTemplate(canvas, num) return manager class FigureCanvasTemplate(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Note GUI templates will want to connect events for button presses, mouse movements and key presses to functions that call the base class methods button_press_event, button_release_event, motion_notify_event, key_press_event, and key_release_event. See, e.g., backend_gtk.py, backend_wx.py and backend_tkagg.py Attributes ---------- figure : `matplotlib.figure.Figure` A high-level Figure instance """ def draw(self): """ Draw the figure using the renderer """ renderer = RendererTemplate(self.figure.dpi) self.figure.draw(renderer) # You should provide a print_xxx function for every file format # you can write. # If the file type is not in the base set of filetypes, # you should add it to the class-scope filetypes dictionary as follows: filetypes = FigureCanvasBase.filetypes.copy() filetypes['foo'] = 'My magic Foo format' def print_foo(self, filename, *args, **kwargs): """ Write out format foo. The dpi, facecolor and edgecolor are restored to their original values after this call, so you don't need to save and restore them. """ pass def get_default_filetype(self): return 'foo' class FigureManagerTemplate(FigureManagerBase): """ Wrap everything up into a window for the pylab interface For non interactive backends, the base class does all the work """ pass ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################################################## FigureCanvas = FigureCanvasTemplate FigureManager = FigureManagerTemplate
9,529
33.157706
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_mixed.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import six from matplotlib.backends.backend_agg import RendererAgg from matplotlib.tight_bbox import process_figure_for_rasterizing class MixedModeRenderer(object): """ A helper class to implement a renderer that switches between vector and raster drawing. An example may be a PDF writer, where most things are drawn with PDF vector commands, but some very complex objects, such as quad meshes, are rasterised and then output as images. """ def __init__(self, figure, width, height, dpi, vector_renderer, raster_renderer_class=None, bbox_inches_restore=None): """ Parameters ---------- figure : `matplotlib.figure.Figure` The figure instance. width : scalar The width of the canvas in logical units height : scalar The height of the canvas in logical units dpi : scalar The dpi of the canvas vector_renderer : `matplotlib.backend_bases.RendererBase` An instance of a subclass of `~matplotlib.backend_bases.RendererBase` that will be used for the vector drawing. raster_renderer_class : `matplotlib.backend_bases.RendererBase` The renderer class to use for the raster drawing. If not provided, this will use the Agg backend (which is currently the only viable option anyway.) """ if raster_renderer_class is None: raster_renderer_class = RendererAgg self._raster_renderer_class = raster_renderer_class self._width = width self._height = height self.dpi = dpi self._vector_renderer = vector_renderer self._raster_renderer = None self._rasterizing = 0 # A reference to the figure is needed as we need to change # the figure dpi before and after the rasterization. Although # this looks ugly, I couldn't find a better solution. -JJL self.figure = figure self._figdpi = figure.get_dpi() self._bbox_inches_restore = bbox_inches_restore self._set_current_renderer(vector_renderer) _methods = """ close_group draw_image draw_markers draw_path draw_path_collection draw_quad_mesh draw_tex draw_text finalize flipy get_canvas_width_height get_image_magnification get_texmanager get_text_width_height_descent new_gc open_group option_image_nocomposite points_to_pixels strip_math start_filter stop_filter draw_gouraud_triangle draw_gouraud_triangles option_scale_image _text2path _get_text_path_transform height width """.split() def _set_current_renderer(self, renderer): self._renderer = renderer for method in self._methods: if hasattr(renderer, method): setattr(self, method, getattr(renderer, method)) renderer.start_rasterizing = self.start_rasterizing renderer.stop_rasterizing = self.stop_rasterizing def start_rasterizing(self): """ Enter "raster" mode. All subsequent drawing commands (until stop_rasterizing is called) will be drawn with the raster backend. If start_rasterizing is called multiple times before stop_rasterizing is called, this method has no effect. """ # change the dpi of the figure temporarily. self.figure.set_dpi(self.dpi) if self._bbox_inches_restore: # when tight bbox is used r = process_figure_for_rasterizing(self.figure, self._bbox_inches_restore) self._bbox_inches_restore = r if self._rasterizing == 0: self._raster_renderer = self._raster_renderer_class( self._width*self.dpi, self._height*self.dpi, self.dpi) self._set_current_renderer(self._raster_renderer) self._rasterizing += 1 def stop_rasterizing(self): """ Exit "raster" mode. All of the drawing that was done since the last start_rasterizing command will be copied to the vector backend by calling draw_image. If stop_rasterizing is called multiple times before start_rasterizing is called, this method has no effect. """ self._rasterizing -= 1 if self._rasterizing == 0: self._set_current_renderer(self._vector_renderer) height = self._height * self.dpi buffer, bounds = self._raster_renderer.tostring_rgba_minimized() l, b, w, h = bounds if w > 0 and h > 0: image = np.frombuffer(buffer, dtype=np.uint8) image = image.reshape((h, w, 4)) image = image[::-1] gc = self._renderer.new_gc() # TODO: If the mixedmode resolution differs from the figure's # dpi, the image must be scaled (dpi->_figdpi). Not all # backends support this. self._renderer.draw_image( gc, l * self._figdpi / self.dpi, (height-b-h) * self._figdpi / self.dpi, image) self._raster_renderer = None self._rasterizing = False # restore the figure dpi. self.figure.set_dpi(self._figdpi) if self._bbox_inches_restore: # when tight bbox is used r = process_figure_for_rasterizing(self.figure, self._bbox_inches_restore, self._figdpi) self._bbox_inches_restore = r
5,860
36.570513
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/windowing.py
""" MS Windows-specific helper for the TkAgg backend. With rcParams['tk.window_focus'] default of False, it is effectively disabled. It uses a tiny C++ extension module to access MS Win functions. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from matplotlib import rcParams try: if not rcParams['tk.window_focus']: raise ImportError from matplotlib._windowing import GetForegroundWindow, SetForegroundWindow except ImportError: def GetForegroundWindow(): return 0 def SetForegroundWindow(hwnd): pass class FocusManager(object): def __init__(self): self._shellWindow = GetForegroundWindow() def __del__(self): SetForegroundWindow(self._shellWindow)
798
23.96875
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_pdf.py
# -*- coding: utf-8 -*- """ A PDF matplotlib backend Author: Jouni K Seppänen <[email protected]> """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six import unichr import codecs import collections from datetime import datetime from functools import total_ordering from io import BytesIO import logging from math import ceil, cos, floor, pi, sin import os import re import struct import sys import time import warnings import zlib import numpy as np from matplotlib import cbook, __version__, rcParams from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.cbook import (Bunch, get_realpath_and_stat, is_writable_file_like, maxdict) from matplotlib.figure import Figure from matplotlib.font_manager import findfont, is_opentype_cff_font, get_font from matplotlib.afm import AFM import matplotlib.type1font as type1font import matplotlib.dviread as dviread from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE, LOAD_NO_HINTING, KERNING_UNFITTED) from matplotlib.mathtext import MathTextParser from matplotlib.transforms import Affine2D, BboxBase from matplotlib.path import Path from matplotlib.dates import UTC from matplotlib import _path from matplotlib import _png from matplotlib import ttconv _log = logging.getLogger(__name__) # Overview # # The low-level knowledge about pdf syntax lies mainly in the pdfRepr # function and the classes Reference, Name, Operator, and Stream. The # PdfFile class knows about the overall structure of pdf documents. # It provides a "write" method for writing arbitrary strings in the # file, and an "output" method that passes objects through the pdfRepr # function before writing them in the file. The output method is # called by the RendererPdf class, which contains the various draw_foo # methods. RendererPdf contains a GraphicsContextPdf instance, and # each draw_foo calls self.check_gc before outputting commands. This # method checks whether the pdf graphics state needs to be modified # and outputs the necessary commands. GraphicsContextPdf represents # the graphics state, and its "delta" method returns the commands that # modify the state. # Add "pdf.use14corefonts: True" in your configuration file to use only # the 14 PDF core fonts. These fonts do not need to be embedded; every # PDF viewing application is required to have them. This results in very # light PDF files you can use directly in LaTeX or ConTeXt documents # generated with pdfTeX, without any conversion. # These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique, # Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique, # Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic, # Times-BoldItalic, Symbol, ZapfDingbats. # # Some tricky points: # # 1. The clip path can only be widened by popping from the state # stack. Thus the state must be pushed onto the stack before narrowing # the clip path. This is taken care of by GraphicsContextPdf. # # 2. Sometimes it is necessary to refer to something (e.g., font, # image, or extended graphics state, which contains the alpha value) # in the page stream by a name that needs to be defined outside the # stream. PdfFile provides the methods fontName, imageObject, and # alphaState for this purpose. The implementations of these methods # should perhaps be generalized. # TODOs: # # * encoding of fonts, including mathtext fonts and unicode support # * TTF support has lots of small TODOs, e.g., how do you know if a font # is serif/sans-serif, or symbolic/non-symbolic? # * draw_markers, draw_line_collection, etc. def fill(strings, linelen=75): """Make one string from sequence of strings, with whitespace in between. The whitespace is chosen to form lines of at most linelen characters, if possible.""" currpos = 0 lasti = 0 result = [] for i, s in enumerate(strings): length = len(s) if currpos + length < linelen: currpos += length + 1 else: result.append(b' '.join(strings[lasti:i])) lasti = i currpos = length result.append(b' '.join(strings[lasti:])) return b'\n'.join(result) # PDF strings are supposed to be able to include any eight-bit data, # except that unbalanced parens and backslashes must be escaped by a # backslash. However, sf bug #2708559 shows that the carriage return # character may get read as a newline; these characters correspond to # \gamma and \Omega in TeX's math font encoding. Escaping them fixes # the bug. _string_escape_regex = re.compile(br'([\\()\r\n])') def _string_escape(match): m = match.group(0) if m in br'\()': return b'\\' + m elif m == b'\n': return br'\n' elif m == b'\r': return br'\r' assert False def pdfRepr(obj): """Map Python objects to PDF syntax.""" # Some objects defined later have their own pdfRepr method. if hasattr(obj, 'pdfRepr'): return obj.pdfRepr() # Floats. PDF does not have exponential notation (1.0e-10) so we # need to use %f with some precision. Perhaps the precision # should adapt to the magnitude of the number? elif isinstance(obj, (float, np.floating)): if not np.isfinite(obj): raise ValueError("Can only output finite numbers in PDF") r = ("%.10f" % obj).encode('ascii') return r.rstrip(b'0').rstrip(b'.') # Booleans. Needs to be tested before integers since # isinstance(True, int) is true. elif isinstance(obj, bool): return [b'false', b'true'][obj] # Integers are written as such. elif isinstance(obj, (six.integer_types, np.integer)): return ("%d" % obj).encode('ascii') # Unicode strings are encoded in UTF-16BE with byte-order mark. elif isinstance(obj, six.text_type): try: # But maybe it's really ASCII? s = obj.encode('ASCII') return pdfRepr(s) except UnicodeEncodeError: s = codecs.BOM_UTF16_BE + obj.encode('UTF-16BE') return pdfRepr(s) # Strings are written in parentheses, with backslashes and parens # escaped. Actually balanced parens are allowed, but it is # simpler to escape them all. TODO: cut long strings into lines; # I believe there is some maximum line length in PDF. elif isinstance(obj, bytes): return b'(' + _string_escape_regex.sub(_string_escape, obj) + b')' # Dictionaries. The keys must be PDF names, so if we find strings # there, we make Name objects from them. The values may be # anything, so the caller must ensure that PDF names are # represented as Name objects. elif isinstance(obj, dict): r = [b"<<"] r.extend([Name(key).pdfRepr() + b" " + pdfRepr(obj[key]) for key in sorted(obj)]) r.append(b">>") return fill(r) # Lists. elif isinstance(obj, (list, tuple)): r = [b"["] r.extend([pdfRepr(val) for val in obj]) r.append(b"]") return fill(r) # The null keyword. elif obj is None: return b'null' # A date. elif isinstance(obj, datetime): r = obj.strftime('D:%Y%m%d%H%M%S') z = obj.utcoffset() if z is not None: z = z.seconds else: if time.daylight: z = time.altzone else: z = time.timezone if z == 0: r += 'Z' elif z < 0: r += "+%02d'%02d'" % ((-z) // 3600, (-z) % 3600) else: r += "-%02d'%02d'" % (z // 3600, z % 3600) return pdfRepr(r) # A bounding box elif isinstance(obj, BboxBase): return fill([pdfRepr(val) for val in obj.bounds]) else: raise TypeError("Don't know a PDF representation for {} objects" .format(type(obj))) class Reference(object): """PDF reference object. Use PdfFile.reserveObject() to create References. """ def __init__(self, id): self.id = id def __repr__(self): return "<Reference %d>" % self.id def pdfRepr(self): return ("%d 0 R" % self.id).encode('ascii') def write(self, contents, file): write = file.write write(("%d 0 obj\n" % self.id).encode('ascii')) write(pdfRepr(contents)) write(b"\nendobj\n") @total_ordering class Name(object): """PDF name object.""" __slots__ = ('name',) _regex = re.compile(r'[^!-~]') def __init__(self, name): if isinstance(name, Name): self.name = name.name else: if isinstance(name, bytes): name = name.decode('ascii') self.name = self._regex.sub(Name.hexify, name).encode('ascii') def __repr__(self): return "<Name %s>" % self.name def __str__(self): return '/' + six.text_type(self.name) def __eq__(self, other): return isinstance(other, Name) and self.name == other.name def __lt__(self, other): return isinstance(other, Name) and self.name < other.name def __hash__(self): return hash(self.name) @staticmethod def hexify(match): return '#%02x' % ord(match.group()) def pdfRepr(self): return b'/' + self.name class Operator(object): """PDF operator object.""" __slots__ = ('op',) def __init__(self, op): self.op = op def __repr__(self): return '<Operator %s>' % self.op def pdfRepr(self): return self.op class Verbatim(object): """Store verbatim PDF command content for later inclusion in the stream.""" def __init__(self, x): self._x = x def pdfRepr(self): return self._x # PDF operators (not an exhaustive list) _pdfops = dict( close_fill_stroke=b'b', fill_stroke=b'B', fill=b'f', closepath=b'h', close_stroke=b's', stroke=b'S', endpath=b'n', begin_text=b'BT', end_text=b'ET', curveto=b'c', rectangle=b're', lineto=b'l', moveto=b'm', concat_matrix=b'cm', use_xobject=b'Do', setgray_stroke=b'G', setgray_nonstroke=b'g', setrgb_stroke=b'RG', setrgb_nonstroke=b'rg', setcolorspace_stroke=b'CS', setcolorspace_nonstroke=b'cs', setcolor_stroke=b'SCN', setcolor_nonstroke=b'scn', setdash=b'd', setlinejoin=b'j', setlinecap=b'J', setgstate=b'gs', gsave=b'q', grestore=b'Q', textpos=b'Td', selectfont=b'Tf', textmatrix=b'Tm', show=b'Tj', showkern=b'TJ', setlinewidth=b'w', clip=b'W', shading=b'sh') Op = Bunch(**{name: Operator(value) for name, value in six.iteritems(_pdfops)}) def _paint_path(fill, stroke): """Return the PDF operator to paint a path in the following way: fill: fill the path with the fill color stroke: stroke the outline of the path with the line color""" if stroke: if fill: return Op.fill_stroke else: return Op.stroke else: if fill: return Op.fill else: return Op.endpath Op.paint_path = _paint_path class Stream(object): """PDF stream object. This has no pdfRepr method. Instead, call begin(), then output the contents of the stream by calling write(), and finally call end(). """ __slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos') def __init__(self, id, len, file, extra=None, png=None): """id: object id of stream; len: an unused Reference object for the length of the stream, or None (to use a memory buffer); file: a PdfFile; extra: a dictionary of extra key-value pairs to include in the stream header; png: if the data is already png compressed, the decode parameters""" self.id = id # object id self.len = len # id of length object self.pdfFile = file self.file = file.fh # file to which the stream is written self.compressobj = None # compression object if extra is None: self.extra = dict() else: self.extra = extra.copy() if png is not None: self.extra.update({'Filter': Name('FlateDecode'), 'DecodeParms': png}) self.pdfFile.recordXref(self.id) if rcParams['pdf.compression'] and not png: self.compressobj = zlib.compressobj(rcParams['pdf.compression']) if self.len is None: self.file = BytesIO() else: self._writeHeader() self.pos = self.file.tell() def _writeHeader(self): write = self.file.write write(("%d 0 obj\n" % self.id).encode('ascii')) dict = self.extra dict['Length'] = self.len if rcParams['pdf.compression']: dict['Filter'] = Name('FlateDecode') write(pdfRepr(dict)) write(b"\nstream\n") def end(self): """Finalize stream.""" self._flush() if self.len is None: contents = self.file.getvalue() self.len = len(contents) self.file = self.pdfFile.fh self._writeHeader() self.file.write(contents) self.file.write(b"\nendstream\nendobj\n") else: length = self.file.tell() - self.pos self.file.write(b"\nendstream\nendobj\n") self.pdfFile.writeObject(self.len, length) def write(self, data): """Write some data on the stream.""" if self.compressobj is None: self.file.write(data) else: compressed = self.compressobj.compress(data) self.file.write(compressed) def _flush(self): """Flush the compression object.""" if self.compressobj is not None: compressed = self.compressobj.flush() self.file.write(compressed) self.compressobj = None class PdfFile(object): """PDF file object.""" def __init__(self, filename, metadata=None): self.nextObject = 1 # next free object id self.xrefTable = [[0, 65535, 'the zero object']] self.passed_in_file_object = False self.original_file_like = None self.tell_base = 0 fh, opened = cbook.to_filehandle(filename, "wb", return_opened=True) if not opened: try: self.tell_base = filename.tell() except IOError: fh = BytesIO() self.original_file_like = filename else: fh = filename self.passed_in_file_object = True self._core14fontdir = os.path.join( rcParams['datapath'], 'fonts', 'pdfcorefonts') self.fh = fh self.currentstream = None # stream object to write to, if any fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha # Output some eight-bit chars as a comment so various utilities # recognize the file as binary by looking at the first few # lines (see note in section 3.4.1 of the PDF reference). fh.write(b"%\254\334 \253\272\n") self.rootObject = self.reserveObject('root') self.pagesObject = self.reserveObject('pages') self.pageList = [] self.fontObject = self.reserveObject('fonts') self.alphaStateObject = self.reserveObject('extended graphics states') self.hatchObject = self.reserveObject('tiling patterns') self.gouraudObject = self.reserveObject('Gouraud triangles') self.XObjectObject = self.reserveObject('external objects') self.resourceObject = self.reserveObject('resources') root = {'Type': Name('Catalog'), 'Pages': self.pagesObject} self.writeObject(self.rootObject, root) # get source date from SOURCE_DATE_EPOCH, if set # See https://reproducible-builds.org/specs/source-date-epoch/ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") if source_date_epoch: source_date = datetime.utcfromtimestamp(int(source_date_epoch)) source_date = source_date.replace(tzinfo=UTC) else: source_date = datetime.today() self.infoDict = { 'Creator': 'matplotlib %s, http://matplotlib.org' % __version__, 'Producer': 'matplotlib pdf backend %s' % __version__, 'CreationDate': source_date } if metadata is not None: self.infoDict.update(metadata) self.infoDict = {k: v for (k, v) in self.infoDict.items() if v is not None} self.fontNames = {} # maps filenames to internal font names self.nextFont = 1 # next free internal font name self.dviFontInfo = {} # maps dvi font names to embedding information self._texFontMap = None # maps TeX font names to PostScript fonts # differently encoded Type-1 fonts may share the same descriptor self.type1Descriptors = {} self.used_characters = {} self.alphaStates = {} # maps alpha values to graphics state objects self.nextAlphaState = 1 # reproducible writeHatches needs an ordered dict: self.hatchPatterns = collections.OrderedDict() self.nextHatch = 1 self.gouraudTriangles = [] self._images = collections.OrderedDict() # reproducible writeImages self.nextImage = 1 self.markers = collections.OrderedDict() # reproducible writeMarkers self.multi_byte_charprocs = {} self.paths = [] self.pageAnnotations = [] # A list of annotations for the # current page # The PDF spec recommends to include every procset procsets = [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()] # Write resource dictionary. # Possibly TODO: more general ExtGState (graphics state dictionaries) # ColorSpace Pattern Shading Properties resources = {'Font': self.fontObject, 'XObject': self.XObjectObject, 'ExtGState': self.alphaStateObject, 'Pattern': self.hatchObject, 'Shading': self.gouraudObject, 'ProcSet': procsets} self.writeObject(self.resourceObject, resources) def newPage(self, width, height): self.endStream() self.width, self.height = width, height contentObject = self.reserveObject('page contents') thePage = {'Type': Name('Page'), 'Parent': self.pagesObject, 'Resources': self.resourceObject, 'MediaBox': [0, 0, 72 * width, 72 * height], 'Contents': contentObject, 'Group': {'Type': Name('Group'), 'S': Name('Transparency'), 'CS': Name('DeviceRGB')}, 'Annots': self.pageAnnotations, } pageObject = self.reserveObject('page') self.writeObject(pageObject, thePage) self.pageList.append(pageObject) self.beginStream(contentObject.id, self.reserveObject('length of content stream')) # Initialize the pdf graphics state to match the default mpl # graphics context: currently only the join style needs to be set self.output(GraphicsContextPdf.joinstyles['round'], Op.setlinejoin) # Clear the list of annotations for the next page self.pageAnnotations = [] def newTextnote(self, text, positionRect=[-100, -100, 0, 0]): # Create a new annotation of type text theNote = {'Type': Name('Annot'), 'Subtype': Name('Text'), 'Contents': text, 'Rect': positionRect, } annotObject = self.reserveObject('annotation') self.writeObject(annotObject, theNote) self.pageAnnotations.append(annotObject) def finalize(self): "Write out the various deferred objects and the pdf end matter." self.endStream() self.writeFonts() self.writeObject( self.alphaStateObject, {val[0]: val[1] for val in six.itervalues(self.alphaStates)}) self.writeHatches() self.writeGouraudTriangles() xobjects = { name: ob for image, name, ob in six.itervalues(self._images)} for tup in six.itervalues(self.markers): xobjects[tup[0]] = tup[1] for name, value in six.iteritems(self.multi_byte_charprocs): xobjects[name] = value for name, path, trans, ob, join, cap, padding, filled, stroked \ in self.paths: xobjects[name] = ob self.writeObject(self.XObjectObject, xobjects) self.writeImages() self.writeMarkers() self.writePathCollectionTemplates() self.writeObject(self.pagesObject, {'Type': Name('Pages'), 'Kids': self.pageList, 'Count': len(self.pageList)}) self.writeInfoDict() # Finalize the file self.writeXref() self.writeTrailer() def close(self): "Flush all buffers and free all resources." self.endStream() if self.passed_in_file_object: self.fh.flush() else: if self.original_file_like is not None: self.original_file_like.write(self.fh.getvalue()) self.fh.close() def write(self, data): if self.currentstream is None: self.fh.write(data) else: self.currentstream.write(data) def output(self, *data): self.write(fill([pdfRepr(x) for x in data])) self.write(b'\n') def beginStream(self, id, len, extra=None, png=None): assert self.currentstream is None self.currentstream = Stream(id, len, self, extra, png) def endStream(self): if self.currentstream is not None: self.currentstream.end() self.currentstream = None def fontName(self, fontprop): """ Select a font based on fontprop and return a name suitable for Op.selectfont. If fontprop is a string, it will be interpreted as the filename of the font. """ if isinstance(fontprop, six.string_types): filename = fontprop elif rcParams['pdf.use14corefonts']: filename = findfont( fontprop, fontext='afm', directory=self._core14fontdir) if filename is None: filename = findfont( "Helvetica", fontext='afm', directory=self._core14fontdir) else: filename = findfont(fontprop) Fx = self.fontNames.get(filename) if Fx is None: Fx = Name('F%d' % self.nextFont) self.fontNames[filename] = Fx self.nextFont += 1 _log.debug('Assigning font %s = %r', Fx, filename) return Fx @property def texFontMap(self): # lazy-load texFontMap, it takes a while to parse # and usetex is a relatively rare use case if self._texFontMap is None: self._texFontMap = dviread.PsfontsMap( dviread.find_tex_file('pdftex.map')) return self._texFontMap def dviFontName(self, dvifont): """ Given a dvi font object, return a name suitable for Op.selectfont. This registers the font information in self.dviFontInfo if not yet registered. """ dvi_info = self.dviFontInfo.get(dvifont.texname) if dvi_info is not None: return dvi_info.pdfname psfont = self.texFontMap[dvifont.texname] if psfont.filename is None: raise ValueError( "No usable font file found for {} (TeX: {}); " "the font may lack a Type-1 version" .format(psfont.psname, dvifont.texname)) pdfname = Name('F%d' % self.nextFont) self.nextFont += 1 _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname) self.dviFontInfo[dvifont.texname] = Bunch( dvifont=dvifont, pdfname=pdfname, fontfile=psfont.filename, basefont=psfont.psname, encodingfile=psfont.encoding, effects=psfont.effects) return pdfname def writeFonts(self): fonts = {} for dviname, info in sorted(self.dviFontInfo.items()): Fx = info.pdfname _log.debug('Embedding Type-1 font %s from dvi.', dviname) fonts[Fx] = self._embedTeXFont(info) for filename in sorted(self.fontNames): Fx = self.fontNames[filename] _log.debug('Embedding font %s.', filename) if filename.endswith('.afm'): # from pdf.use14corefonts _log.debug('Writing AFM font.') fonts[Fx] = self._write_afm_font(filename) else: # a normal TrueType font _log.debug('Writing TrueType font.') realpath, stat_key = get_realpath_and_stat(filename) chars = self.used_characters.get(stat_key) if chars is not None and len(chars[1]): fonts[Fx] = self.embedTTF(realpath, chars[1]) self.writeObject(self.fontObject, fonts) def _write_afm_font(self, filename): with open(filename, 'rb') as fh: font = AFM(fh) fontname = font.get_fontname() fontdict = {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(fontname), 'Encoding': Name('WinAnsiEncoding')} fontdictObject = self.reserveObject('font dictionary') self.writeObject(fontdictObject, fontdict) return fontdictObject def _embedTeXFont(self, fontinfo): _log.debug('Embedding TeX font %s - fontinfo=%s', fontinfo.dvifont.texname, fontinfo.__dict__) # Widths widthsObject = self.reserveObject('font widths') self.writeObject(widthsObject, fontinfo.dvifont.widths) # Font dictionary fontdictObject = self.reserveObject('font dictionary') fontdict = { 'Type': Name('Font'), 'Subtype': Name('Type1'), 'FirstChar': 0, 'LastChar': len(fontinfo.dvifont.widths) - 1, 'Widths': widthsObject, } # Encoding (if needed) if fontinfo.encodingfile is not None: enc = dviread.Encoding(fontinfo.encodingfile) differencesArray = [Name(ch) for ch in enc] differencesArray = [0] + differencesArray fontdict['Encoding'] = \ {'Type': Name('Encoding'), 'Differences': differencesArray} # If no file is specified, stop short if fontinfo.fontfile is None: _log.warning( "Because of TeX configuration (pdftex.map, see updmap option " "pdftexDownloadBase14) the font %s is not embedded. This is " "deprecated as of PDF 1.5 and it may cause the consumer " "application to show something that was not intended.", fontinfo.basefont) fontdict['BaseFont'] = Name(fontinfo.basefont) self.writeObject(fontdictObject, fontdict) return fontdictObject # We have a font file to embed - read it in and apply any effects t1font = type1font.Type1Font(fontinfo.fontfile) if fontinfo.effects: t1font = t1font.transform(fontinfo.effects) fontdict['BaseFont'] = Name(t1font.prop['FontName']) # Font descriptors may be shared between differently encoded # Type-1 fonts, so only create a new descriptor if there is no # existing descriptor for this font. effects = (fontinfo.effects.get('slant', 0.0), fontinfo.effects.get('extend', 1.0)) fontdesc = self.type1Descriptors.get((fontinfo.fontfile, effects)) if fontdesc is None: fontdesc = self.createType1Descriptor(t1font, fontinfo.fontfile) self.type1Descriptors[(fontinfo.fontfile, effects)] = fontdesc fontdict['FontDescriptor'] = fontdesc self.writeObject(fontdictObject, fontdict) return fontdictObject def createType1Descriptor(self, t1font, fontfile): # Create and write the font descriptor and the font file # of a Type-1 font fontdescObject = self.reserveObject('font descriptor') fontfileObject = self.reserveObject('font file') italic_angle = t1font.prop['ItalicAngle'] fixed_pitch = t1font.prop['isFixedPitch'] flags = 0 # fixed width if fixed_pitch: flags |= 1 << 0 # TODO: serif if 0: flags |= 1 << 1 # TODO: symbolic (most TeX fonts are) if 1: flags |= 1 << 2 # non-symbolic else: flags |= 1 << 5 # italic if italic_angle: flags |= 1 << 6 # TODO: all caps if 0: flags |= 1 << 16 # TODO: small caps if 0: flags |= 1 << 17 # TODO: force bold if 0: flags |= 1 << 18 ft2font = get_font(fontfile) descriptor = { 'Type': Name('FontDescriptor'), 'FontName': Name(t1font.prop['FontName']), 'Flags': flags, 'FontBBox': ft2font.bbox, 'ItalicAngle': italic_angle, 'Ascent': ft2font.ascender, 'Descent': ft2font.descender, 'CapHeight': 1000, # TODO: find this out 'XHeight': 500, # TODO: this one too 'FontFile': fontfileObject, 'FontFamily': t1font.prop['FamilyName'], 'StemV': 50, # TODO # (see also revision 3874; but not all TeX distros have AFM files!) # 'FontWeight': a number where 400 = Regular, 700 = Bold } self.writeObject(fontdescObject, descriptor) self.beginStream(fontfileObject.id, None, {'Length1': len(t1font.parts[0]), 'Length2': len(t1font.parts[1]), 'Length3': 0}) self.currentstream.write(t1font.parts[0]) self.currentstream.write(t1font.parts[1]) self.endStream() return fontdescObject def _get_xobject_symbol_name(self, filename, symbol_name): return "%s-%s" % ( os.path.splitext(os.path.basename(filename))[0], symbol_name) _identityToUnicodeCMap = """/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> <ffff> endcodespacerange %d beginbfrange %s endbfrange endcmap CMapName currentdict /CMap defineresource pop end end""" def embedTTF(self, filename, characters): """Embed the TTF font from the named file into the document.""" font = get_font(filename) fonttype = rcParams['pdf.fonttype'] def cvt(length, upe=font.units_per_EM, nearest=True): "Convert font coordinates to PDF glyph coordinates" value = length / upe * 1000 if nearest: return np.round(value) # Perhaps best to round away from zero for bounding # boxes and the like if value < 0: return floor(value) else: return ceil(value) def embedTTFType3(font, characters, descriptor): """The Type 3-specific part of embedding a Truetype font""" widthsObject = self.reserveObject('font widths') fontdescObject = self.reserveObject('font descriptor') fontdictObject = self.reserveObject('font dictionary') charprocsObject = self.reserveObject('character procs') differencesArray = [] firstchar, lastchar = 0, 255 bbox = [cvt(x, nearest=False) for x in font.bbox] fontdict = { 'Type': Name('Font'), 'BaseFont': ps_name, 'FirstChar': firstchar, 'LastChar': lastchar, 'FontDescriptor': fontdescObject, 'Subtype': Name('Type3'), 'Name': descriptor['FontName'], 'FontBBox': bbox, 'FontMatrix': [.001, 0, 0, .001, 0, 0], 'CharProcs': charprocsObject, 'Encoding': { 'Type': Name('Encoding'), 'Differences': differencesArray}, 'Widths': widthsObject } # Make the "Widths" array from encodings import cp1252 # The "decoding_map" was changed # to a "decoding_table" as of Python 2.5. if hasattr(cp1252, 'decoding_map'): def decode_char(charcode): return cp1252.decoding_map[charcode] or 0 else: def decode_char(charcode): return ord(cp1252.decoding_table[charcode]) def get_char_width(charcode): s = decode_char(charcode) width = font.load_char( s, flags=LOAD_NO_SCALE | LOAD_NO_HINTING).horiAdvance return cvt(width) widths = [get_char_width(charcode) for charcode in range(firstchar, lastchar+1)] descriptor['MaxWidth'] = max(widths) # Make the "Differences" array, sort the ccodes < 255 from # the multi-byte ccodes, and build the whole set of glyph ids # that we need from this font. glyph_ids = [] differences = [] multi_byte_chars = set() for c in characters: ccode = c gind = font.get_char_index(ccode) glyph_ids.append(gind) glyph_name = font.get_glyph_name(gind) if ccode <= 255: differences.append((ccode, glyph_name)) else: multi_byte_chars.add(glyph_name) differences.sort() last_c = -2 for c, name in differences: if c != last_c + 1: differencesArray.append(c) differencesArray.append(Name(name)) last_c = c # Make the charprocs array (using ttconv to generate the # actual outlines) rawcharprocs = ttconv.get_pdf_charprocs( filename.encode(sys.getfilesystemencoding()), glyph_ids) charprocs = {} for charname in sorted(rawcharprocs): stream = rawcharprocs[charname] charprocDict = {'Length': len(stream)} # The 2-byte characters are used as XObjects, so they # need extra info in their dictionary if charname in multi_byte_chars: charprocDict['Type'] = Name('XObject') charprocDict['Subtype'] = Name('Form') charprocDict['BBox'] = bbox # Each glyph includes bounding box information, # but xpdf and ghostscript can't handle it in a # Form XObject (they segfault!!!), so we remove it # from the stream here. It's not needed anyway, # since the Form XObject includes it in its BBox # value. stream = stream[stream.find(b"d1") + 2:] charprocObject = self.reserveObject('charProc') self.beginStream(charprocObject.id, None, charprocDict) self.currentstream.write(stream) self.endStream() # Send the glyphs with ccode > 255 to the XObject dictionary, # and the others to the font itself if charname in multi_byte_chars: name = self._get_xobject_symbol_name(filename, charname) self.multi_byte_charprocs[name] = charprocObject else: charprocs[charname] = charprocObject # Write everything out self.writeObject(fontdictObject, fontdict) self.writeObject(fontdescObject, descriptor) self.writeObject(widthsObject, widths) self.writeObject(charprocsObject, charprocs) return fontdictObject def embedTTFType42(font, characters, descriptor): """The Type 42-specific part of embedding a Truetype font""" fontdescObject = self.reserveObject('font descriptor') cidFontDictObject = self.reserveObject('CID font dictionary') type0FontDictObject = self.reserveObject('Type 0 font dictionary') cidToGidMapObject = self.reserveObject('CIDToGIDMap stream') fontfileObject = self.reserveObject('font file stream') wObject = self.reserveObject('Type 0 widths') toUnicodeMapObject = self.reserveObject('ToUnicode map') cidFontDict = { 'Type': Name('Font'), 'Subtype': Name('CIDFontType2'), 'BaseFont': ps_name, 'CIDSystemInfo': { 'Registry': 'Adobe', 'Ordering': 'Identity', 'Supplement': 0}, 'FontDescriptor': fontdescObject, 'W': wObject, 'CIDToGIDMap': cidToGidMapObject } type0FontDict = { 'Type': Name('Font'), 'Subtype': Name('Type0'), 'BaseFont': ps_name, 'Encoding': Name('Identity-H'), 'DescendantFonts': [cidFontDictObject], 'ToUnicode': toUnicodeMapObject } # Make fontfile stream descriptor['FontFile2'] = fontfileObject length1Object = self.reserveObject('decoded length of a font') self.beginStream( fontfileObject.id, self.reserveObject('length of font stream'), {'Length1': length1Object}) with open(filename, 'rb') as fontfile: length1 = 0 while True: data = fontfile.read(4096) if not data: break length1 += len(data) self.currentstream.write(data) self.endStream() self.writeObject(length1Object, length1) # Make the 'W' (Widths) array, CidToGidMap and ToUnicode CMap # at the same time cid_to_gid_map = ['\0'] * 65536 widths = [] max_ccode = 0 for c in characters: ccode = c gind = font.get_char_index(ccode) glyph = font.load_char(ccode, flags=LOAD_NO_SCALE | LOAD_NO_HINTING) widths.append((ccode, cvt(glyph.horiAdvance))) if ccode < 65536: cid_to_gid_map[ccode] = unichr(gind) max_ccode = max(ccode, max_ccode) widths.sort() cid_to_gid_map = cid_to_gid_map[:max_ccode + 1] last_ccode = -2 w = [] max_width = 0 unicode_groups = [] for ccode, width in widths: if ccode != last_ccode + 1: w.append(ccode) w.append([width]) unicode_groups.append([ccode, ccode]) else: w[-1].append(width) unicode_groups[-1][1] = ccode max_width = max(max_width, width) last_ccode = ccode unicode_bfrange = [] for start, end in unicode_groups: unicode_bfrange.append( "<%04x> <%04x> [%s]" % (start, end, " ".join(["<%04x>" % x for x in range(start, end+1)]))) unicode_cmap = (self._identityToUnicodeCMap % (len(unicode_groups), "\n".join(unicode_bfrange))).encode('ascii') # CIDToGIDMap stream cid_to_gid_map = "".join(cid_to_gid_map).encode("utf-16be") self.beginStream(cidToGidMapObject.id, None, {'Length': len(cid_to_gid_map)}) self.currentstream.write(cid_to_gid_map) self.endStream() # ToUnicode CMap self.beginStream(toUnicodeMapObject.id, None, {'Length': unicode_cmap}) self.currentstream.write(unicode_cmap) self.endStream() descriptor['MaxWidth'] = max_width # Write everything out self.writeObject(cidFontDictObject, cidFontDict) self.writeObject(type0FontDictObject, type0FontDict) self.writeObject(fontdescObject, descriptor) self.writeObject(wObject, w) return type0FontDictObject # Beginning of main embedTTF function... # You are lost in a maze of TrueType tables, all different... sfnt = font.get_sfnt() try: ps_name = sfnt[1, 0, 0, 6].decode('mac_roman') # Macintosh scheme except KeyError: # Microsoft scheme: ps_name = sfnt[3, 1, 0x0409, 6].decode('utf-16be') # (see freetype/ttnameid.h) ps_name = ps_name.encode('ascii', 'replace') ps_name = Name(ps_name) pclt = font.get_sfnt_table('pclt') or {'capHeight': 0, 'xHeight': 0} post = font.get_sfnt_table('post') or {'italicAngle': (0, 0)} ff = font.face_flags sf = font.style_flags flags = 0 symbolic = False # ps_name.name in ('Cmsy10', 'Cmmi10', 'Cmex10') if ff & FIXED_WIDTH: flags |= 1 << 0 if 0: # TODO: serif flags |= 1 << 1 if symbolic: flags |= 1 << 2 else: flags |= 1 << 5 if sf & ITALIC: flags |= 1 << 6 if 0: # TODO: all caps flags |= 1 << 16 if 0: # TODO: small caps flags |= 1 << 17 if 0: # TODO: force bold flags |= 1 << 18 descriptor = { 'Type': Name('FontDescriptor'), 'FontName': ps_name, 'Flags': flags, 'FontBBox': [cvt(x, nearest=False) for x in font.bbox], 'Ascent': cvt(font.ascender, nearest=False), 'Descent': cvt(font.descender, nearest=False), 'CapHeight': cvt(pclt['capHeight'], nearest=False), 'XHeight': cvt(pclt['xHeight']), 'ItalicAngle': post['italicAngle'][1], # ??? 'StemV': 0 # ??? } # The font subsetting to a Type 3 font does not work for # OpenType (.otf) that embed a Postscript CFF font, so avoid that -- # save as a (non-subsetted) Type 42 font instead. if is_opentype_cff_font(filename): fonttype = 42 _log.warning("%r can not be subsetted into a Type 3 font. The " "entire font will be embedded in the output.", os.path.basename(filename)) if fonttype == 3: return embedTTFType3(font, characters, descriptor) elif fonttype == 42: return embedTTFType42(font, characters, descriptor) def alphaState(self, alpha): """Return name of an ExtGState that sets alpha to the given value.""" state = self.alphaStates.get(alpha, None) if state is not None: return state[0] name = Name('A%d' % self.nextAlphaState) self.nextAlphaState += 1 self.alphaStates[alpha] = \ (name, {'Type': Name('ExtGState'), 'CA': alpha[0], 'ca': alpha[1]}) return name def hatchPattern(self, hatch_style): # The colors may come in as numpy arrays, which aren't hashable if hatch_style is not None: edge, face, hatch = hatch_style if edge is not None: edge = tuple(edge) if face is not None: face = tuple(face) hatch_style = (edge, face, hatch) pattern = self.hatchPatterns.get(hatch_style, None) if pattern is not None: return pattern name = Name('H%d' % self.nextHatch) self.nextHatch += 1 self.hatchPatterns[hatch_style] = name return name def writeHatches(self): hatchDict = dict() sidelen = 72.0 for hatch_style, name in six.iteritems(self.hatchPatterns): ob = self.reserveObject('hatch pattern') hatchDict[name] = ob res = {'Procsets': [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]} self.beginStream( ob.id, None, {'Type': Name('Pattern'), 'PatternType': 1, 'PaintType': 1, 'TilingType': 1, 'BBox': [0, 0, sidelen, sidelen], 'XStep': sidelen, 'YStep': sidelen, 'Resources': res, # Change origin to match Agg at top-left. 'Matrix': [1, 0, 0, 1, 0, self.height * 72]}) stroke_rgb, fill_rgb, path = hatch_style self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2], Op.setrgb_stroke) if fill_rgb is not None: self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2], Op.setrgb_nonstroke, 0, 0, sidelen, sidelen, Op.rectangle, Op.fill) self.output(rcParams['hatch.linewidth'], Op.setlinewidth) self.output(*self.pathOperations( Path.hatch(path), Affine2D().scale(sidelen), simplify=False)) self.output(Op.fill_stroke) self.endStream() self.writeObject(self.hatchObject, hatchDict) def addGouraudTriangles(self, points, colors): name = Name('GT%d' % len(self.gouraudTriangles)) self.gouraudTriangles.append((name, points, colors)) return name def writeGouraudTriangles(self): gouraudDict = dict() for name, points, colors in self.gouraudTriangles: ob = self.reserveObject('Gouraud triangle') gouraudDict[name] = ob shape = points.shape flat_points = points.reshape((shape[0] * shape[1], 2)) flat_colors = colors.reshape((shape[0] * shape[1], 4)) points_min = np.min(flat_points, axis=0) - (1 << 8) points_max = np.max(flat_points, axis=0) + (1 << 8) factor = 0xffffffff / (points_max - points_min) self.beginStream( ob.id, None, {'ShadingType': 4, 'BitsPerCoordinate': 32, 'BitsPerComponent': 8, 'BitsPerFlag': 8, 'ColorSpace': Name('DeviceRGB'), 'AntiAlias': True, 'Decode': [points_min[0], points_max[0], points_min[1], points_max[1], 0, 1, 0, 1, 0, 1] }) streamarr = np.empty( (shape[0] * shape[1],), dtype=[(str('flags'), str('u1')), (str('points'), str('>u4'), (2,)), (str('colors'), str('u1'), (3,))]) streamarr['flags'] = 0 streamarr['points'] = (flat_points - points_min) * factor streamarr['colors'] = flat_colors[:, :3] * 255.0 self.write(streamarr.tostring()) self.endStream() self.writeObject(self.gouraudObject, gouraudDict) def imageObject(self, image): """Return name of an image XObject representing the given image.""" entry = self._images.get(id(image), None) if entry is not None: return entry[1] name = Name('I%d' % self.nextImage) ob = self.reserveObject('image %d' % self.nextImage) self.nextImage += 1 self._images[id(image)] = (image, name, ob) return name def _unpack(self, im): """ Unpack the image object im into height, width, data, alpha, where data and alpha are HxWx3 (RGB) or HxWx1 (grayscale or alpha) arrays, except alpha is None if the image is fully opaque. """ h, w = im.shape[:2] im = im[::-1] if im.ndim == 2: return h, w, im, None else: rgb = im[:, :, :3] rgb = np.array(rgb, order='C') # PDF needs a separate alpha image if im.shape[2] == 4: alpha = im[:, :, 3][..., None] if np.all(alpha == 255): alpha = None else: alpha = np.array(alpha, order='C') else: alpha = None return h, w, rgb, alpha def _writePng(self, data): """ Write the image *data* into the pdf file using png predictors with Flate compression. """ buffer = BytesIO() _png.write_png(data, buffer) buffer.seek(8) written = 0 header = bytearray(8) while True: n = buffer.readinto(header) assert n == 8 length, type = struct.unpack(b'!L4s', bytes(header)) if type == b'IDAT': data = bytearray(length) n = buffer.readinto(data) assert n == length self.currentstream.write(bytes(data)) written += n elif type == b'IEND': break else: buffer.seek(length, 1) buffer.seek(4, 1) # skip CRC def _writeImg(self, data, height, width, grayscale, id, smask=None): """ Write the image *data* of size *height* x *width*, as grayscale if *grayscale* is true and RGB otherwise, as pdf object *id* and with the soft mask (alpha channel) *smask*, which should be either None or a *height* x *width* x 1 array. """ obj = {'Type': Name('XObject'), 'Subtype': Name('Image'), 'Width': width, 'Height': height, 'ColorSpace': Name('DeviceGray' if grayscale else 'DeviceRGB'), 'BitsPerComponent': 8} if smask: obj['SMask'] = smask if rcParams['pdf.compression']: png = {'Predictor': 10, 'Colors': 1 if grayscale else 3, 'Columns': width} else: png = None self.beginStream( id, self.reserveObject('length of image stream'), obj, png=png ) if png: self._writePng(data) else: self.currentstream.write(data.tostring()) self.endStream() def writeImages(self): for img, name, ob in six.itervalues(self._images): height, width, data, adata = self._unpack(img) if adata is not None: smaskObject = self.reserveObject("smask") self._writeImg(adata, height, width, True, smaskObject.id) else: smaskObject = None self._writeImg(data, height, width, False, ob.id, smaskObject) def markerObject(self, path, trans, fill, stroke, lw, joinstyle, capstyle): """Return name of a marker XObject representing the given path.""" # self.markers used by markerObject, writeMarkers, close: # mapping from (path operations, fill?, stroke?) to # [name, object reference, bounding box, linewidth] # This enables different draw_markers calls to share the XObject # if the gc is sufficiently similar: colors etc can vary, but # the choices of whether to fill and whether to stroke cannot. # We need a bounding box enclosing all of the XObject path, # but since line width may vary, we store the maximum of all # occurring line widths in self.markers. # close() is somewhat tightly coupled in that it expects the # first two components of each value in self.markers to be the # name and object reference. pathops = self.pathOperations(path, trans, simplify=False) key = (tuple(pathops), bool(fill), bool(stroke), joinstyle, capstyle) result = self.markers.get(key) if result is None: name = Name('M%d' % len(self.markers)) ob = self.reserveObject('marker %d' % len(self.markers)) bbox = path.get_extents(trans) self.markers[key] = [name, ob, bbox, lw] else: if result[-1] < lw: result[-1] = lw name = result[0] return name def writeMarkers(self): for ((pathops, fill, stroke, joinstyle, capstyle), (name, ob, bbox, lw)) in six.iteritems(self.markers): bbox = bbox.padded(lw * 0.5) self.beginStream( ob.id, None, {'Type': Name('XObject'), 'Subtype': Name('Form'), 'BBox': list(bbox.extents)}) self.output(GraphicsContextPdf.joinstyles[joinstyle], Op.setlinejoin) self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) self.output(*pathops) self.output(Op.paint_path(fill, stroke)) self.endStream() def pathCollectionObject(self, gc, path, trans, padding, filled, stroked): name = Name('P%d' % len(self.paths)) ob = self.reserveObject('path %d' % len(self.paths)) self.paths.append( (name, path, trans, ob, gc.get_joinstyle(), gc.get_capstyle(), padding, filled, stroked)) return name def writePathCollectionTemplates(self): for (name, path, trans, ob, joinstyle, capstyle, padding, filled, stroked) in self.paths: pathops = self.pathOperations(path, trans, simplify=False) bbox = path.get_extents(trans) if not np.all(np.isfinite(bbox.extents)): extents = [0, 0, 0, 0] else: bbox = bbox.padded(padding) extents = list(bbox.extents) self.beginStream( ob.id, None, {'Type': Name('XObject'), 'Subtype': Name('Form'), 'BBox': extents}) self.output(GraphicsContextPdf.joinstyles[joinstyle], Op.setlinejoin) self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) self.output(*pathops) self.output(Op.paint_path(filled, stroked)) self.endStream() @staticmethod def pathOperations(path, transform, clip=None, simplify=None, sketch=None): return [Verbatim(_path.convert_to_string( path, transform, clip, simplify, sketch, 6, [Op.moveto.op, Op.lineto.op, b'', Op.curveto.op, Op.closepath.op], True))] def writePath(self, path, transform, clip=False, sketch=None): if clip: clip = (0.0, 0.0, self.width * 72, self.height * 72) simplify = path.should_simplify else: clip = None simplify = False cmds = self.pathOperations(path, transform, clip, simplify=simplify, sketch=sketch) self.output(*cmds) def reserveObject(self, name=''): """Reserve an ID for an indirect object. The name is used for debugging in case we forget to print out the object with writeObject. """ id = self.nextObject self.nextObject += 1 self.xrefTable.append([None, 0, name]) return Reference(id) def recordXref(self, id): self.xrefTable[id][0] = self.fh.tell() - self.tell_base def writeObject(self, object, contents): self.recordXref(object.id) object.write(contents, self) def writeXref(self): """Write out the xref table.""" self.startxref = self.fh.tell() - self.tell_base self.write(("xref\n0 %d\n" % self.nextObject).encode('ascii')) i = 0 borken = False for offset, generation, name in self.xrefTable: if offset is None: print('No offset for object %d (%s)' % (i, name), file=sys.stderr) borken = True else: if name == 'the zero object': key = "f" else: key = "n" text = "%010d %05d %s \n" % (offset, generation, key) self.write(text.encode('ascii')) i += 1 if borken: raise AssertionError('Indirect object does not exist') def writeInfoDict(self): """Write out the info dictionary, checking it for good form""" def is_string_like(x): return isinstance(x, six.string_types) def is_date(x): return isinstance(x, datetime) check_trapped = (lambda x: isinstance(x, Name) and x.name in ('True', 'False', 'Unknown')) keywords = {'Title': is_string_like, 'Author': is_string_like, 'Subject': is_string_like, 'Keywords': is_string_like, 'Creator': is_string_like, 'Producer': is_string_like, 'CreationDate': is_date, 'ModDate': is_date, 'Trapped': check_trapped} for k in self.infoDict: if k not in keywords: warnings.warn('Unknown infodict keyword: %s' % k) else: if not keywords[k](self.infoDict[k]): warnings.warn('Bad value for infodict keyword %s' % k) self.infoObject = self.reserveObject('info') self.writeObject(self.infoObject, self.infoDict) def writeTrailer(self): """Write out the PDF trailer.""" self.write(b"trailer\n") self.write(pdfRepr( {'Size': self.nextObject, 'Root': self.rootObject, 'Info': self.infoObject})) # Could add 'ID' self.write(("\nstartxref\n%d\n%%%%EOF\n" % self.startxref).encode('ascii')) class RendererPdf(RendererBase): afm_font_cache = maxdict(50) def __init__(self, file, image_dpi, height, width): RendererBase.__init__(self) self.height = height self.width = width self.file = file self.gc = self.new_gc() self.mathtext_parser = MathTextParser("Pdf") self.image_dpi = image_dpi def finalize(self): self.file.output(*self.gc.finalize()) def check_gc(self, gc, fillcolor=None): orig_fill = getattr(gc, '_fillcolor', (0., 0., 0.)) gc._fillcolor = fillcolor orig_alphas = getattr(gc, '_effective_alphas', (1.0, 1.0)) if gc.get_rgb() is None: # it should not matter what color here # since linewidth should be 0 # unless affected by global settings in rcParams # hence setting zero alpha just incase gc.set_foreground((0, 0, 0, 0), isRGBA=True) if gc._forced_alpha: gc._effective_alphas = (gc._alpha, gc._alpha) elif fillcolor is None or len(fillcolor) < 4: gc._effective_alphas = (gc._rgb[3], 1.0) else: gc._effective_alphas = (gc._rgb[3], fillcolor[3]) delta = self.gc.delta(gc) if delta: self.file.output(*delta) # Restore gc to avoid unwanted side effects gc._fillcolor = orig_fill gc._effective_alphas = orig_alphas def track_characters(self, font, s): """Keeps track of which characters are required from each font.""" if isinstance(font, six.string_types): fname = font else: fname = font.fname realpath, stat_key = get_realpath_and_stat(fname) used_characters = self.file.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update([ord(x) for x in s]) def merge_used_characters(self, other): for stat_key, (realpath, charset) in six.iteritems(other): used_characters = self.file.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update(charset) def get_image_magnification(self): return self.image_dpi/72.0 def option_scale_image(self): """ pdf backend support arbitrary scaling of image. """ return True def option_image_nocomposite(self): """ return whether to generate a composite image from multiple images on a set of axes """ return not rcParams['image.composite_image'] def draw_image(self, gc, x, y, im, transform=None): h, w = im.shape[:2] if w == 0 or h == 0: return if transform is None: # If there's no transform, alpha has already been applied gc.set_alpha(1.0) self.check_gc(gc) w = 72.0 * w / self.image_dpi h = 72.0 * h / self.image_dpi imob = self.file.imageObject(im) if transform is None: self.file.output(Op.gsave, w, 0, 0, h, x, y, Op.concat_matrix, imob, Op.use_xobject, Op.grestore) else: tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() self.file.output(Op.gsave, 1, 0, 0, 1, x, y, Op.concat_matrix, tr1, tr2, tr3, tr4, tr5, tr6, Op.concat_matrix, imob, Op.use_xobject, Op.grestore) def draw_path(self, gc, path, transform, rgbFace=None): self.check_gc(gc, rgbFace) self.file.writePath( path, transform, rgbFace is None and gc.get_hatch_path() is None, gc.get_sketch_params()) self.file.output(self.gc.paint()) def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): # We can only reuse the objects if the presence of fill and # stroke (and the amount of alpha for each) is the same for # all of them can_do_optimization = True facecolors = np.asarray(facecolors) edgecolors = np.asarray(edgecolors) if not len(facecolors): filled = False can_do_optimization = not gc.get_hatch() else: if np.all(facecolors[:, 3] == facecolors[0, 3]): filled = facecolors[0, 3] != 0.0 else: can_do_optimization = False if not len(edgecolors): stroked = False else: if np.all(np.asarray(linewidths) == 0.0): stroked = False elif np.all(edgecolors[:, 3] == edgecolors[0, 3]): stroked = edgecolors[0, 3] != 0.0 else: can_do_optimization = False # Is the optimization worth it? Rough calculation: # cost of emitting a path in-line is len_path * uses_per_path # cost of XObject is len_path + 5 for the definition, # uses_per_path for the uses len_path = len(paths[0].vertices) if len(paths) > 0 else 0 uses_per_path = self._iter_collection_uses_per_path( paths, all_transforms, offsets, facecolors, edgecolors) should_do_optimization = \ len_path + uses_per_path + 5 < len_path * uses_per_path if (not can_do_optimization) or (not should_do_optimization): return RendererBase.draw_path_collection( self, gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position) padding = np.max(linewidths) path_codes = [] for i, (path, transform) in enumerate(self._iter_collection_raw_paths( master_transform, paths, all_transforms)): name = self.file.pathCollectionObject( gc, path, transform, padding, filled, stroked) path_codes.append(name) output = self.file.output output(*self.gc.push()) lastx, lasty = 0, 0 for xo, yo, path_id, gc0, rgbFace in self._iter_collection( gc, master_transform, all_transforms, path_codes, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): self.check_gc(gc0, rgbFace) dx, dy = xo - lastx, yo - lasty output(1, 0, 0, 1, dx, dy, Op.concat_matrix, path_id, Op.use_xobject) lastx, lasty = xo, yo output(*self.gc.pop()) def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): # Same logic as in draw_path_collection len_marker_path = len(marker_path) uses = len(path) if len_marker_path * uses < len_marker_path + uses + 5: RendererBase.draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace) return self.check_gc(gc, rgbFace) fill = gc.fill(rgbFace) stroke = gc.stroke() output = self.file.output marker = self.file.markerObject( marker_path, marker_trans, fill, stroke, self.gc._linewidth, gc.get_joinstyle(), gc.get_capstyle()) output(Op.gsave) lastx, lasty = 0, 0 for vertices, code in path.iter_segments( trans, clip=(0, 0, self.file.width*72, self.file.height*72), simplify=False): if len(vertices): x, y = vertices[-2:] if (x < 0 or y < 0 or x > self.file.width * 72 or y > self.file.height * 72): continue dx, dy = x - lastx, y - lasty output(1, 0, 0, 1, dx, dy, Op.concat_matrix, marker, Op.use_xobject) lastx, lasty = x, y output(Op.grestore) def draw_gouraud_triangle(self, gc, points, colors, trans): self.draw_gouraud_triangles(gc, points.reshape((1, 3, 2)), colors.reshape((1, 3, 4)), trans) def draw_gouraud_triangles(self, gc, points, colors, trans): assert len(points) == len(colors) assert points.ndim == 3 assert points.shape[1] == 3 assert points.shape[2] == 2 assert colors.ndim == 3 assert colors.shape[1] == 3 assert colors.shape[2] == 4 shape = points.shape points = points.reshape((shape[0] * shape[1], 2)) tpoints = trans.transform(points) tpoints = tpoints.reshape(shape) name = self.file.addGouraudTriangles(tpoints, colors) self.check_gc(gc) self.file.output(name, Op.shading) def _setup_textpos(self, x, y, angle, oldx=0, oldy=0, oldangle=0): if angle == oldangle == 0: self.file.output(x - oldx, y - oldy, Op.textpos) else: angle = angle / 180.0 * pi self.file.output(cos(angle), sin(angle), -sin(angle), cos(angle), x, y, Op.textmatrix) self.file.output(0, 0, Op.textpos) def draw_mathtext(self, gc, x, y, s, prop, angle): # TODO: fix positioning and encoding width, height, descent, glyphs, rects, used_characters = \ self.mathtext_parser.parse(s, 72, prop) self.merge_used_characters(used_characters) # When using Type 3 fonts, we can't use character codes higher # than 255, so we use the "Do" command to render those # instead. global_fonttype = rcParams['pdf.fonttype'] # Set up a global transformation matrix for the whole math expression a = angle / 180.0 * pi self.file.output(Op.gsave) self.file.output(cos(a), sin(a), -sin(a), cos(a), x, y, Op.concat_matrix) self.check_gc(gc, gc._rgb) self.file.output(Op.begin_text) prev_font = None, None oldx, oldy = 0, 0 for ox, oy, fontname, fontsize, num, symbol_name in glyphs: if is_opentype_cff_font(fontname): fonttype = 42 else: fonttype = global_fonttype if fonttype == 42 or num <= 255: self._setup_textpos(ox, oy, 0, oldx, oldy) oldx, oldy = ox, oy if (fontname, fontsize) != prev_font: self.file.output(self.file.fontName(fontname), fontsize, Op.selectfont) prev_font = fontname, fontsize self.file.output(self.encode_string(unichr(num), fonttype), Op.show) self.file.output(Op.end_text) # If using Type 3 fonts, render all of the multi-byte characters # as XObjects using the 'Do' command. if global_fonttype == 3: for ox, oy, fontname, fontsize, num, symbol_name in glyphs: if is_opentype_cff_font(fontname): fonttype = 42 else: fonttype = global_fonttype if fonttype == 3 and num > 255: self.file.fontName(fontname) self.file.output(Op.gsave, 0.001 * fontsize, 0, 0, 0.001 * fontsize, ox, oy, Op.concat_matrix) name = self.file._get_xobject_symbol_name( fontname, symbol_name) self.file.output(Name(name), Op.use_xobject) self.file.output(Op.grestore) # Draw any horizontal lines in the math layout for ox, oy, width, height in rects: self.file.output(Op.gsave, ox, oy, width, height, Op.rectangle, Op.fill, Op.grestore) # Pop off the global transformation self.file.output(Op.grestore) def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None): texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() dvifile = texmanager.make_dvi(s, fontsize) with dviread.Dvi(dvifile, 72) as dvi: page = next(iter(dvi)) # Gather font information and do some setup for combining # characters into strings. The variable seq will contain a # sequence of font and text entries. A font entry is a list # ['font', name, size] where name is a Name object for the # font. A text entry is ['text', x, y, glyphs, x+w] where x # and y are the starting coordinates, w is the width, and # glyphs is a list; in this phase it will always contain just # one one-character string, but later it may have longer # strings interspersed with kern amounts. oldfont, seq = None, [] for x1, y1, dvifont, glyph, width in page.text: if dvifont != oldfont: pdfname = self.file.dviFontName(dvifont) seq += [['font', pdfname, dvifont.size]] oldfont = dvifont # We need to convert the glyph numbers to bytes, and the easiest # way to do this on both Python 2 and 3 is .encode('latin-1') seq += [['text', x1, y1, [six.unichr(glyph).encode('latin-1')], x1+width]] # Find consecutive text strings with constant y coordinate and # combine into a sequence of strings and kerns, or just one # string (if any kerns would be less than 0.1 points). i, curx, fontsize = 0, 0, None while i < len(seq)-1: elt, nxt = seq[i:i+2] if elt[0] == 'font': fontsize = elt[2] elif elt[0] == nxt[0] == 'text' and elt[2] == nxt[2]: offset = elt[4] - nxt[1] if abs(offset) < 0.1: elt[3][-1] += nxt[3][0] elt[4] += nxt[4]-nxt[1] else: elt[3] += [offset*1000.0/fontsize, nxt[3][0]] elt[4] = nxt[4] del seq[i+1] continue i += 1 # Create a transform to map the dvi contents to the canvas. mytrans = Affine2D().rotate_deg(angle).translate(x, y) # Output the text. self.check_gc(gc, gc._rgb) self.file.output(Op.begin_text) curx, cury, oldx, oldy = 0, 0, 0, 0 for elt in seq: if elt[0] == 'font': self.file.output(elt[1], elt[2], Op.selectfont) elif elt[0] == 'text': curx, cury = mytrans.transform_point((elt[1], elt[2])) self._setup_textpos(curx, cury, angle, oldx, oldy) oldx, oldy = curx, cury if len(elt[3]) == 1: self.file.output(elt[3][0], Op.show) else: self.file.output(elt[3], Op.showkern) else: assert False self.file.output(Op.end_text) # Then output the boxes (e.g., variable-length lines of square # roots). boxgc = self.new_gc() boxgc.copy_properties(gc) boxgc.set_linewidth(0) pathops = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] for x1, y1, h, w in page.boxes: path = Path([[x1, y1], [x1+w, y1], [x1+w, y1+h], [x1, y1+h], [0, 0]], pathops) self.draw_path(boxgc, path, mytrans, gc._rgb) def encode_string(self, s, fonttype): if fonttype in (1, 3): return s.encode('cp1252', 'replace') return s.encode('utf-16be', 'replace') def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): # TODO: combine consecutive texts into one BT/ET delimited section # This function is rather complex, since there is no way to # access characters of a Type 3 font with codes > 255. (Type # 3 fonts can not have a CIDMap). Therefore, we break the # string into chunks, where each chunk contains exclusively # 1-byte or exclusively 2-byte characters, and output each # chunk a separate command. 1-byte characters use the regular # text show command (Tj), whereas 2-byte characters use the # use XObject command (Do). If using Type 42 fonts, all of # this complication is avoided, but of course, those fonts can # not be subsetted. self.check_gc(gc, gc._rgb) if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) fontsize = prop.get_size_in_points() if rcParams['pdf.use14corefonts']: font = self._get_font_afm(prop) l, b, w, h = font.get_str_bbox(s) fonttype = 1 else: font = self._get_font_ttf(prop) self.track_characters(font, s) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) fonttype = rcParams['pdf.fonttype'] # We can't subset all OpenType fonts, so switch to Type 42 # in that case. if is_opentype_cff_font(font.fname): fonttype = 42 def check_simple_method(s): """Determine if we should use the simple or woven method to output this text, and chunks the string into 1-byte and 2-byte sections if necessary.""" use_simple_method = True chunks = [] if not rcParams['pdf.use14corefonts']: if fonttype == 3 and not isinstance(s, bytes) and len(s) != 0: # Break the string into chunks where each chunk is either # a string of chars <= 255, or a single character > 255. s = six.text_type(s) for c in s: if ord(c) <= 255: char_type = 1 else: char_type = 2 if len(chunks) and chunks[-1][0] == char_type: chunks[-1][1].append(c) else: chunks.append((char_type, [c])) use_simple_method = (len(chunks) == 1 and chunks[-1][0] == 1) return use_simple_method, chunks def draw_text_simple(): """Outputs text using the simple method.""" self.file.output(Op.begin_text, self.file.fontName(prop), fontsize, Op.selectfont) self._setup_textpos(x, y, angle) self.file.output(self.encode_string(s, fonttype), Op.show, Op.end_text) def draw_text_woven(chunks): """Outputs text using the woven method, alternating between chunks of 1-byte characters and 2-byte characters. Only used for Type 3 fonts.""" chunks = [(a, ''.join(b)) for a, b in chunks] # Do the rotation and global translation as a single matrix # concatenation up front self.file.output(Op.gsave) a = angle / 180.0 * pi self.file.output(cos(a), sin(a), -sin(a), cos(a), x, y, Op.concat_matrix) # Output all the 1-byte characters in a BT/ET group, then # output all the 2-byte characters. for mode in (1, 2): newx = oldx = 0 # Output a 1-byte character chunk if mode == 1: self.file.output(Op.begin_text, self.file.fontName(prop), fontsize, Op.selectfont) for chunk_type, chunk in chunks: if mode == 1 and chunk_type == 1: self._setup_textpos(newx, 0, 0, oldx, 0, 0) self.file.output(self.encode_string(chunk, fonttype), Op.show) oldx = newx lastgind = None for c in chunk: ccode = ord(c) gind = font.get_char_index(ccode) if gind is not None: if mode == 2 and chunk_type == 2: glyph_name = font.get_glyph_name(gind) self.file.output(Op.gsave) self.file.output(0.001 * fontsize, 0, 0, 0.001 * fontsize, newx, 0, Op.concat_matrix) name = self.file._get_xobject_symbol_name( font.fname, glyph_name) self.file.output(Name(name), Op.use_xobject) self.file.output(Op.grestore) # Move the pointer based on the character width # and kerning glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) if lastgind is not None: kern = font.get_kerning( lastgind, gind, KERNING_UNFITTED) else: kern = 0 lastgind = gind newx += kern/64.0 + glyph.linearHoriAdvance/65536.0 if mode == 1: self.file.output(Op.end_text) self.file.output(Op.grestore) use_simple_method, chunks = check_simple_method(s) if use_simple_method: return draw_text_simple() else: return draw_text_woven(chunks) def get_text_width_height_descent(self, s, prop, ismath): if rcParams['text.usetex']: texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() w, h, d = texmanager.get_text_width_height_descent(s, fontsize, renderer=self) return w, h, d if ismath: w, h, d, glyphs, rects, used_characters = \ self.mathtext_parser.parse(s, 72, prop) elif rcParams['pdf.use14corefonts']: font = self._get_font_afm(prop) l, b, w, h, d = font.get_str_bbox_and_descent(s) scale = prop.get_size_in_points() w *= scale / 1000 h *= scale / 1000 d *= scale / 1000 else: font = self._get_font_ttf(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) w, h = font.get_width_height() scale = (1.0 / 64.0) w *= scale h *= scale d = font.get_descent() d *= scale return w, h, d def _get_font_afm(self, prop): key = hash(prop) font = self.afm_font_cache.get(key) if font is None: filename = findfont( prop, fontext='afm', directory=self.file._core14fontdir) if filename is None: filename = findfont( "Helvetica", fontext='afm', directory=self.file._core14fontdir) font = self.afm_font_cache.get(filename) if font is None: with open(filename, 'rb') as fh: font = AFM(fh) self.afm_font_cache[filename] = font self.afm_font_cache[key] = font return font def _get_font_ttf(self, prop): filename = findfont(prop) font = get_font(filename) font.clear() font.set_size(prop.get_size_in_points(), 72) return font def flipy(self): return False def get_canvas_width_height(self): return self.file.width * 72.0, self.file.height * 72.0 def new_gc(self): return GraphicsContextPdf(self.file) class GraphicsContextPdf(GraphicsContextBase): def __init__(self, file): GraphicsContextBase.__init__(self) self._fillcolor = (0.0, 0.0, 0.0) self._effective_alphas = (1.0, 1.0) self.file = file self.parent = None def __repr__(self): d = dict(self.__dict__) del d['file'] del d['parent'] return repr(d) def stroke(self): """ Predicate: does the path need to be stroked (its outline drawn)? This tests for the various conditions that disable stroking the path, in which case it would presumably be filled. """ # _linewidth > 0: in pdf a line of width 0 is drawn at minimum # possible device width, but e.g., agg doesn't draw at all return (self._linewidth > 0 and self._alpha > 0 and (len(self._rgb) <= 3 or self._rgb[3] != 0.0)) def fill(self, *args): """ Predicate: does the path need to be filled? An optional argument can be used to specify an alternative _fillcolor, as needed by RendererPdf.draw_markers. """ if len(args): _fillcolor = args[0] else: _fillcolor = self._fillcolor return (self._hatch or (_fillcolor is not None and (len(_fillcolor) <= 3 or _fillcolor[3] != 0.0))) def paint(self): """ Return the appropriate pdf operator to cause the path to be stroked, filled, or both. """ return Op.paint_path(self.fill(), self.stroke()) capstyles = {'butt': 0, 'round': 1, 'projecting': 2} joinstyles = {'miter': 0, 'round': 1, 'bevel': 2} def capstyle_cmd(self, style): return [self.capstyles[style], Op.setlinecap] def joinstyle_cmd(self, style): return [self.joinstyles[style], Op.setlinejoin] def linewidth_cmd(self, width): return [width, Op.setlinewidth] def dash_cmd(self, dashes): offset, dash = dashes if dash is None: dash = [] offset = 0 return [list(dash), offset, Op.setdash] def alpha_cmd(self, alpha, forced, effective_alphas): name = self.file.alphaState(effective_alphas) return [name, Op.setgstate] def hatch_cmd(self, hatch, hatch_color): if not hatch: if self._fillcolor is not None: return self.fillcolor_cmd(self._fillcolor) else: return [Name('DeviceRGB'), Op.setcolorspace_nonstroke] else: hatch_style = (hatch_color, self._fillcolor, hatch) name = self.file.hatchPattern(hatch_style) return [Name('Pattern'), Op.setcolorspace_nonstroke, name, Op.setcolor_nonstroke] def rgb_cmd(self, rgb): if rcParams['pdf.inheritcolor']: return [] if rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_stroke] else: return list(rgb[:3]) + [Op.setrgb_stroke] def fillcolor_cmd(self, rgb): if rgb is None or rcParams['pdf.inheritcolor']: return [] elif rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_nonstroke] else: return list(rgb[:3]) + [Op.setrgb_nonstroke] def push(self): parent = GraphicsContextPdf(self.file) parent.copy_properties(self) parent.parent = self.parent self.parent = parent return [Op.gsave] def pop(self): assert self.parent is not None self.copy_properties(self.parent) self.parent = self.parent.parent return [Op.grestore] def clip_cmd(self, cliprect, clippath): """Set clip rectangle. Calls self.pop() and self.push().""" cmds = [] # Pop graphics state until we hit the right one or the stack is empty while ((self._cliprect, self._clippath) != (cliprect, clippath) and self.parent is not None): cmds.extend(self.pop()) # Unless we hit the right one, set the clip polygon if ((self._cliprect, self._clippath) != (cliprect, clippath) or self.parent is None): cmds.extend(self.push()) if self._cliprect != cliprect: cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath]) if self._clippath != clippath: path, affine = clippath.get_transformed_path_and_affine() cmds.extend( PdfFile.pathOperations(path, affine, simplify=False) + [Op.clip, Op.endpath]) return cmds commands = ( # must come first since may pop (('_cliprect', '_clippath'), clip_cmd), (('_alpha', '_forced_alpha', '_effective_alphas'), alpha_cmd), (('_capstyle',), capstyle_cmd), (('_fillcolor',), fillcolor_cmd), (('_joinstyle',), joinstyle_cmd), (('_linewidth',), linewidth_cmd), (('_dashes',), dash_cmd), (('_rgb',), rgb_cmd), # must come after fillcolor and rgb (('_hatch', '_hatch_color'), hatch_cmd), ) def delta(self, other): """ Copy properties of other into self and return PDF commands needed to transform self into other. """ cmds = [] fill_performed = False for params, cmd in self.commands: different = False for p in params: ours = getattr(self, p) theirs = getattr(other, p) try: if ours is None or theirs is None: different = ours is not theirs else: different = bool(ours != theirs) except ValueError: ours = np.asarray(ours) theirs = np.asarray(theirs) different = (ours.shape != theirs.shape or np.any(ours != theirs)) if different: break # Need to update hatching if we also updated fillcolor if params == ('_hatch', '_hatch_color') and fill_performed: different = True if different: if params == ('_fillcolor',): fill_performed = True theirs = [getattr(other, p) for p in params] cmds.extend(cmd(self, *theirs)) for p in params: setattr(self, p, getattr(other, p)) return cmds def copy_properties(self, other): """ Copy properties of other into self. """ GraphicsContextBase.copy_properties(self, other) fillcolor = getattr(other, '_fillcolor', self._fillcolor) effective_alphas = getattr(other, '_effective_alphas', self._effective_alphas) self._fillcolor = fillcolor self._effective_alphas = effective_alphas def finalize(self): """ Make sure every pushed graphics state is popped. """ cmds = [] while self.parent is not None: cmds.extend(self.pop()) return cmds ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## class PdfPages(object): """ A multi-page PDF file. Examples -------- >>> import matplotlib.pyplot as plt >>> # Initialize: >>> with PdfPages('foo.pdf') as pdf: ... # As many times as you like, create a figure fig and save it: ... fig = plt.figure() ... pdf.savefig(fig) ... # When no figure is specified the current figure is saved ... pdf.savefig() Notes ----- In reality :class:`PdfPages` is a thin wrapper around :class:`PdfFile`, in order to avoid confusion when using :func:`~matplotlib.pyplot.savefig` and forgetting the format argument. """ __slots__ = ('_file', 'keep_empty') def __init__(self, filename, keep_empty=True, metadata=None): """ Create a new PdfPages object. Parameters ---------- filename : str Plots using :meth:`PdfPages.savefig` will be written to a file at this location. The file is opened at once and any older file with the same name is overwritten. keep_empty : bool, optional If set to False, then empty pdf files will be deleted automatically when closed. metadata : dictionary, optional Information dictionary object (see PDF reference section 10.2.1 'Document Information Dictionary'), e.g.: `{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome fig'}` The standard keys are `'Title'`, `'Author'`, `'Subject'`, `'Keywords'`, `'Creator'`, `'Producer'`, `'CreationDate'`, `'ModDate'`, and `'Trapped'`. Values have been predefined for `'Creator'`, `'Producer'` and `'CreationDate'`. They can be removed by setting them to `None`. """ self._file = PdfFile(filename, metadata=metadata) self.keep_empty = keep_empty def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): """ Finalize this object, making the underlying file a complete PDF file. """ self._file.finalize() self._file.close() if (self.get_pagecount() == 0 and not self.keep_empty and not self._file.passed_in_file_object): os.remove(self._file.fh.name) self._file = None def infodict(self): """ Return a modifiable information dictionary object (see PDF reference section 10.2.1 'Document Information Dictionary'). """ return self._file.infoDict def savefig(self, figure=None, **kwargs): """ Saves a :class:`~matplotlib.figure.Figure` to this file as a new page. Any other keyword arguments are passed to :meth:`~matplotlib.figure.Figure.savefig`. Parameters ---------- figure : :class:`~matplotlib.figure.Figure` or int, optional Specifies what figure is saved to file. If not specified, the active figure is saved. If a :class:`~matplotlib.figure.Figure` instance is provided, this figure is saved. If an int is specified, the figure instance to save is looked up by number. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure # Force use of pdf backend, as PdfPages is tightly coupled with it. try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPdf(figure) figure.savefig(self, format="pdf", **kwargs) finally: figure.canvas = orig_canvas def get_pagecount(self): """ Returns the current number of pages in the multipage pdf file. """ return len(self._file.pageList) def attach_note(self, text, positionRect=[-100, -100, 0, 0]): """ Add a new text note to the page to be saved next. The optional positionRect specifies the position of the new note on the page. It is outside the page per default to make sure it is invisible on printouts. """ self._file.newTextnote(text, positionRect) class FigureCanvasPdf(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Attributes ---------- figure : `matplotlib.figure.Figure` A high-level Figure instance """ fixed_dpi = 72 def draw(self): pass filetypes = {'pdf': 'Portable Document Format'} def get_default_filetype(self): return 'pdf' def print_pdf(self, filename, **kwargs): image_dpi = kwargs.get('dpi', 72) # dpi to use for images self.figure.set_dpi(72) # there are 72 pdf points to an inch width, height = self.figure.get_size_inches() if isinstance(filename, PdfPages): file = filename._file else: file = PdfFile(filename, metadata=kwargs.pop("metadata", None)) try: file.newPage(width, height) _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None) renderer = MixedModeRenderer( self.figure, width, height, image_dpi, RendererPdf(file, image_dpi, height, width), bbox_inches_restore=_bbox_inches_restore) self.figure.draw(renderer) renderer.finalize() if not isinstance(filename, PdfPages): file.finalize() finally: if isinstance(filename, PdfPages): # finish off this page file.endStream() else: # we opened the file above; now finish it off file.close() class FigureManagerPdf(FigureManagerBase): pass @_Backend.export class _BackendPdf(_Backend): FigureCanvas = FigureCanvasPdf FigureManager = FigureManagerPdf
98,115
36.664491
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3cairo.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from . import backend_cairo, backend_gtk3 from .backend_cairo import cairo, HAS_CAIRO_CFFI from .backend_gtk3 import _BackendGTK3 from matplotlib.backend_bases import cursors class RendererGTK3Cairo(backend_cairo.RendererCairo): def set_context(self, ctx): if HAS_CAIRO_CFFI and not isinstance(ctx, cairo.Context): ctx = cairo.Context._from_pointer( cairo.ffi.cast( 'cairo_t **', id(ctx) + object.__basicsize__)[0], incref=True) self.gc.ctx = ctx class FigureCanvasGTK3Cairo(backend_gtk3.FigureCanvasGTK3, backend_cairo.FigureCanvasCairo): def _renderer_init(self): """Use cairo renderer.""" self._renderer = RendererGTK3Cairo(self.figure.dpi) def _render_figure(self, width, height): self._renderer.set_width_height(width, height) self.figure.draw(self._renderer) def on_draw_event(self, widget, ctx): """GtkDrawable draw event.""" toolbar = self.toolbar # if toolbar: # toolbar.set_cursor(cursors.WAIT) self._renderer.set_context(ctx) allocation = self.get_allocation() self._render_figure(allocation.width, allocation.height) # if toolbar: # toolbar.set_cursor(toolbar._lastCursor) return False # finish event propagation? class FigureManagerGTK3Cairo(backend_gtk3.FigureManagerGTK3): pass @_BackendGTK3.export class _BackendGTK3Cairo(_BackendGTK3): FigureCanvas = FigureCanvasGTK3Cairo FigureManager = FigureManagerGTK3Cairo
1,740
30.089286
66
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_qt4.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from .backend_qt5 import ( backend_version, SPECIAL_KEYS, SUPER, ALT, CTRL, SHIFT, MODIFIER_KEYS, cursord, _create_qApp, _BackendQT5, TimerQT, MainWindow, FigureManagerQT, NavigationToolbar2QT, SubplotToolQt, error_msg_qt, exception_handler) from .backend_qt5 import FigureCanvasQT as FigureCanvasQT5 @_BackendQT5.export class _BackendQT4(_BackendQT5): pass
498
30.1875
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3agg.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as np import warnings from . import backend_agg, backend_gtk3 from .backend_cairo import cairo, HAS_CAIRO_CFFI from .backend_gtk3 import _BackendGTK3 from matplotlib import transforms if six.PY3 and not HAS_CAIRO_CFFI: warnings.warn( "The Gtk3Agg backend is known to not work on Python 3.x with pycairo. " "Try installing cairocffi.") class FigureCanvasGTK3Agg(backend_gtk3.FigureCanvasGTK3, backend_agg.FigureCanvasAgg): def __init__(self, figure): backend_gtk3.FigureCanvasGTK3.__init__(self, figure) self._bbox_queue = [] def _renderer_init(self): pass def _render_figure(self, width, height): backend_agg.FigureCanvasAgg.draw(self) def on_draw_event(self, widget, ctx): """ GtkDrawable draw event, like expose_event in GTK 2.X """ allocation = self.get_allocation() w, h = allocation.width, allocation.height if not len(self._bbox_queue): self._render_figure(w, h) bbox_queue = [transforms.Bbox([[0, 0], [w, h]])] else: bbox_queue = self._bbox_queue if HAS_CAIRO_CFFI and not isinstance(ctx, cairo.Context): ctx = cairo.Context._from_pointer( cairo.ffi.cast('cairo_t **', id(ctx) + object.__basicsize__)[0], incref=True) for bbox in bbox_queue: area = self.copy_from_bbox(bbox) buf = np.fromstring(area.to_string_argb(), dtype='uint8') x = int(bbox.x0) y = h - int(bbox.y1) width = int(bbox.x1) - int(bbox.x0) height = int(bbox.y1) - int(bbox.y0) if HAS_CAIRO_CFFI: image = cairo.ImageSurface.create_for_data( buf.data, cairo.FORMAT_ARGB32, width, height) else: image = cairo.ImageSurface.create_for_data( buf, cairo.FORMAT_ARGB32, width, height) ctx.set_source_surface(image, x, y) ctx.paint() if len(self._bbox_queue): self._bbox_queue = [] return False def blit(self, bbox=None): # If bbox is None, blit the entire canvas to gtk. Otherwise # blit only the area defined by the bbox. if bbox is None: bbox = self.figure.bbox allocation = self.get_allocation() w, h = allocation.width, allocation.height x = int(bbox.x0) y = h - int(bbox.y1) width = int(bbox.x1) - int(bbox.x0) height = int(bbox.y1) - int(bbox.y0) self._bbox_queue.append(bbox) self.queue_draw_area(x, y, width, height) def print_png(self, filename, *args, **kwargs): # Do this so we can save the resolution of figure in the PNG file agg = self.switch_backends(backend_agg.FigureCanvasAgg) return agg.print_png(filename, *args, **kwargs) class FigureManagerGTK3Agg(backend_gtk3.FigureManagerGTK3): pass @_BackendGTK3.export class _BackendGTK3Cairo(_BackendGTK3): FigureCanvas = FigureCanvasGTK3Agg FigureManager = FigureManagerGTK3Agg
3,296
31.009709
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_macosx.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import os from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase) from matplotlib.figure import Figure from matplotlib import rcParams from matplotlib.widgets import SubplotTool import matplotlib from matplotlib.backends import _macosx from .backend_agg import FigureCanvasAgg ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## class TimerMac(_macosx.Timer, TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses CoreFoundation run loops for timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' # completely implemented at the C-level (in _macosx.Timer) class FigureCanvasMac(_macosx.FigureCanvas, FigureCanvasAgg): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Events such as button presses, mouse movements, and key presses are handled in the C code and the base class methods button_press_event, button_release_event, motion_notify_event, key_press_event, and key_release_event are called from there. Attributes ---------- figure : `matplotlib.figure.Figure` A high-level Figure instance """ def __init__(self, figure): FigureCanvasBase.__init__(self, figure) width, height = self.get_width_height() _macosx.FigureCanvas.__init__(self, width, height) self._device_scale = 1.0 def _set_device_scale(self, value): if self._device_scale != value: self.figure.dpi = self.figure.dpi / self._device_scale * value self._device_scale = value def _draw(self): renderer = self.get_renderer(cleared=self.figure.stale) if self.figure.stale: self.figure.draw(renderer) return renderer def draw(self): self.invalidate() self.flush_events() def draw_idle(self, *args, **kwargs): self.invalidate() def blit(self, bbox): self.invalidate() def resize(self, width, height): dpi = self.figure.dpi width /= dpi height /= dpi self.figure.set_size_inches(width * self._device_scale, height * self._device_scale, forward=False) FigureCanvasBase.resize_event(self) self.draw_idle() def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of `backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Other Parameters ---------------- interval : scalar Timer interval in milliseconds callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerMac(*args, **kwargs) class FigureManagerMac(_macosx.FigureManager, FigureManagerBase): """ Wrap everything up into a window for the pylab interface """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) title = "Figure %d" % num _macosx.FigureManager.__init__(self, canvas, title) if rcParams['toolbar']=='toolbar2': self.toolbar = NavigationToolbar2Mac(canvas) else: self.toolbar = None if self.toolbar is not None: self.toolbar.update() def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) if matplotlib.is_interactive(): self.show() self.canvas.draw_idle() def close(self): Gcf.destroy(self.num) class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2): def __init__(self, canvas): NavigationToolbar2.__init__(self, canvas) def _init_toolbar(self): basedir = os.path.join(rcParams['datapath'], "images") _macosx.NavigationToolbar2.__init__(self, basedir) def draw_rubberband(self, event, x0, y0, x1, y1): self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1)) def release(self, event): self.canvas.remove_rubberband() def set_cursor(self, cursor): _macosx.set_cursor(cursor) def save_figure(self, *args): filename = _macosx.choose_save_file('Save the figure', self.canvas.get_default_filename()) if filename is None: # Cancel return self.canvas.figure.savefig(filename) def prepare_configure_subplots(self): toolfig = Figure(figsize=(6,3)) canvas = FigureCanvasMac(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) return canvas def set_message(self, message): _macosx.NavigationToolbar2.set_message(self, message.encode('utf-8')) ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################################################## @_Backend.export class _BackendMac(_Backend): FigureCanvas = FigureCanvasMac FigureManager = FigureManagerMac @staticmethod def trigger_manager_draw(manager): # For performance reasons, we don't want to redraw the figure after # each draw command. Instead, we mark the figure as invalid, so that it # will be redrawn as soon as the event loop resumes via PyOS_InputHook. # This function should be called after each draw event, even if # matplotlib is not running interactively. manager.canvas.invalidate() @staticmethod def mainloop(): _macosx.show()
6,821
31.331754
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_qt5cairo.py
import six from .backend_cairo import cairo, FigureCanvasCairo, RendererCairo from .backend_qt5 import QtCore, QtGui, _BackendQT5, FigureCanvasQT from .qt_compat import QT_API class FigureCanvasQTCairo(FigureCanvasQT, FigureCanvasCairo): def __init__(self, figure): super(FigureCanvasQTCairo, self).__init__(figure=figure) self._renderer = RendererCairo(self.figure.dpi) self._renderer.set_width_height(-1, -1) # Invalid values. def draw(self): if hasattr(self._renderer.gc, "ctx"): self.figure.draw(self._renderer) super(FigureCanvasQTCairo, self).draw() def paintEvent(self, event): self._update_dpi() dpi_ratio = self._dpi_ratio width = dpi_ratio * self.width() height = dpi_ratio * self.height() if (width, height) != self._renderer.get_canvas_width_height(): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) self._renderer.set_ctx_from_surface(surface) self._renderer.set_width_height(width, height) self.figure.draw(self._renderer) buf = self._renderer.gc.ctx.get_target().get_data() qimage = QtGui.QImage(buf, width, height, QtGui.QImage.Format_ARGB32_Premultiplied) # Adjust the buf reference count to work around a memory leak bug in # QImage under PySide on Python 3. if QT_API == 'PySide' and six.PY3: import ctypes ctypes.c_long.from_address(id(buf)).value = 1 if hasattr(qimage, 'setDevicePixelRatio'): # Not available on Qt4 or some older Qt5. qimage.setDevicePixelRatio(dpi_ratio) painter = QtGui.QPainter(self) painter.drawImage(0, 0, qimage) self._draw_rect_callback(painter) painter.end() @_BackendQT5.export class _BackendQT5Cairo(_BackendQT5): FigureCanvas = FigureCanvasQTCairo
1,938
37.78
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/tkagg.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import tkinter as Tk import numpy as np from matplotlib.backends import _tkagg def blit(photoimage, aggimage, bbox=None, colormode=1): tk = photoimage.tk if bbox is not None: bbox_array = bbox.__array__() # x1, x2, y1, y2 bboxptr = (bbox_array[0, 0], bbox_array[1, 0], bbox_array[0, 1], bbox_array[1, 1]) else: bboxptr = 0 data = np.asarray(aggimage) dataptr = (data.shape[0], data.shape[1], data.ctypes.data) try: tk.call( "PyAggImagePhoto", photoimage, dataptr, colormode, bboxptr) except Tk.TclError: if hasattr(tk, 'interpaddr'): _tkagg.tkinit(tk.interpaddr(), 1) else: # very old python? _tkagg.tkinit(tk, 0) tk.call("PyAggImagePhoto", photoimage, dataptr, colormode, bboxptr) def test(aggimage): r = Tk.Tk() c = Tk.Canvas(r, width=aggimage.width, height=aggimage.height) c.pack() p = Tk.PhotoImage(width=aggimage.width, height=aggimage.height) blit(p, aggimage) c.create_image(aggimage.width,aggimage.height,image=p) blit(p, aggimage) while True: r.update_idletasks()
1,334
28.666667
67
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_gdk.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings import gobject import gtk; gdk = gtk.gdk import pango pygtk_version_required = (2,2,0) if gtk.pygtk_version < pygtk_version_required: raise ImportError ("PyGTK %d.%d.%d is installed\n" "PyGTK %d.%d.%d or later is required" % (gtk.pygtk_version + pygtk_version_required)) del pygtk_version_required import numpy as np import matplotlib from matplotlib import rcParams from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) from matplotlib.cbook import warn_deprecated from matplotlib.mathtext import MathTextParser from matplotlib.transforms import Affine2D from matplotlib.backends._backend_gdk import pixbuf_get_pixels_array backend_version = "%d.%d.%d" % gtk.pygtk_version # Image formats that this backend supports - for FileChooser and print_figure() IMAGE_FORMAT = sorted(['bmp', 'eps', 'jpg', 'png', 'ps', 'svg']) # 'raw', 'rgb' IMAGE_FORMAT_DEFAULT = 'png' class RendererGDK(RendererBase): fontweights = { 100 : pango.WEIGHT_ULTRALIGHT, 200 : pango.WEIGHT_LIGHT, 300 : pango.WEIGHT_LIGHT, 400 : pango.WEIGHT_NORMAL, 500 : pango.WEIGHT_NORMAL, 600 : pango.WEIGHT_BOLD, 700 : pango.WEIGHT_BOLD, 800 : pango.WEIGHT_HEAVY, 900 : pango.WEIGHT_ULTRABOLD, 'ultralight' : pango.WEIGHT_ULTRALIGHT, 'light' : pango.WEIGHT_LIGHT, 'normal' : pango.WEIGHT_NORMAL, 'medium' : pango.WEIGHT_NORMAL, 'semibold' : pango.WEIGHT_BOLD, 'bold' : pango.WEIGHT_BOLD, 'heavy' : pango.WEIGHT_HEAVY, 'ultrabold' : pango.WEIGHT_ULTRABOLD, 'black' : pango.WEIGHT_ULTRABOLD, } # cache for efficiency, these must be at class, not instance level layoutd = {} # a map from text prop tups to pango layouts rotated = {} # a map from text prop tups to rotated text pixbufs def __init__(self, gtkDA, dpi): # widget gtkDA is used for: # '<widget>.create_pango_layout(s)' # cmap line below) self.gtkDA = gtkDA self.dpi = dpi self._cmap = gtkDA.get_colormap() self.mathtext_parser = MathTextParser("Agg") def set_pixmap (self, pixmap): self.gdkDrawable = pixmap def set_width_height (self, width, height): """w,h is the figure w,h not the pixmap w,h """ self.width, self.height = width, height def draw_path(self, gc, path, transform, rgbFace=None): transform = transform + Affine2D(). \ scale(1.0, -1.0).translate(0, self.height) polygons = path.to_polygons(transform, self.width, self.height) for polygon in polygons: # draw_polygon won't take an arbitrary sequence -- it must be a list # of tuples polygon = [(int(np.round(x)), int(np.round(y))) for x, y in polygon] if rgbFace is not None: saveColor = gc.gdkGC.foreground gc.gdkGC.foreground = gc.rgb_to_gdk_color(rgbFace) self.gdkDrawable.draw_polygon(gc.gdkGC, True, polygon) gc.gdkGC.foreground = saveColor if gc.gdkGC.line_width > 0: self.gdkDrawable.draw_lines(gc.gdkGC, polygon) def draw_image(self, gc, x, y, im): bbox = gc.get_clip_rectangle() if bbox != None: l,b,w,h = bbox.bounds #rectangle = (int(l), self.height-int(b+h), # int(w), int(h)) # set clip rect? rows, cols = im.shape[:2] pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=True, bits_per_sample=8, width=cols, height=rows) array = pixbuf_get_pixels_array(pixbuf) array[:, :, :] = im[::-1] gc = self.new_gc() y = self.height-y-rows try: # new in 2.2 # can use None instead of gc.gdkGC, if don't need clipping self.gdkDrawable.draw_pixbuf (gc.gdkGC, pixbuf, 0, 0, int(x), int(y), cols, rows, gdk.RGB_DITHER_NONE, 0, 0) except AttributeError: # deprecated in 2.2 pixbuf.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0, int(x), int(y), cols, rows, gdk.RGB_DITHER_NONE, 0, 0) def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): x, y = int(x), int(y) if x < 0 or y < 0: # window has shrunk and text is off the edge return if angle not in (0,90): warnings.warn('backend_gdk: unable to draw text at angles ' + 'other than 0 or 90') elif ismath: self._draw_mathtext(gc, x, y, s, prop, angle) elif angle==90: self._draw_rotated_text(gc, x, y, s, prop, angle) else: layout, inkRect, logicalRect = self._get_pango_layout(s, prop) l, b, w, h = inkRect if (x + w > self.width or y + h > self.height): return self.gdkDrawable.draw_layout(gc.gdkGC, x, y-h-b, layout) def _draw_mathtext(self, gc, x, y, s, prop, angle): ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) if angle == 90: width, height = height, width x -= width y -= height imw = font_image.get_width() imh = font_image.get_height() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=True, bits_per_sample=8, width=imw, height=imh) array = pixbuf_get_pixels_array(pixbuf) rgb = gc.get_rgb() array[:,:,0] = int(rgb[0]*255) array[:,:,1] = int(rgb[1]*255) array[:,:,2] = int(rgb[2]*255) array[:,:,3] = ( np.fromstring(font_image.as_str(), np.uint8).reshape((imh, imw))) # can use None instead of gc.gdkGC, if don't need clipping self.gdkDrawable.draw_pixbuf(gc.gdkGC, pixbuf, 0, 0, int(x), int(y), imw, imh, gdk.RGB_DITHER_NONE, 0, 0) def _draw_rotated_text(self, gc, x, y, s, prop, angle): """ Draw the text rotated 90 degrees, other angles are not supported """ # this function (and its called functions) is a bottleneck # Pango 1.6 supports rotated text, but pygtk 2.4.0 does not yet have # wrapper functions # GTK+ 2.6 pixbufs support rotation gdrawable = self.gdkDrawable ggc = gc.gdkGC layout, inkRect, logicalRect = self._get_pango_layout(s, prop) l, b, w, h = inkRect x = int(x-h) y = int(y-w) if (x < 0 or y < 0 or # window has shrunk and text is off the edge x + w > self.width or y + h > self.height): return key = (x,y,s,angle,hash(prop)) imageVert = self.rotated.get(key) if imageVert != None: gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w) return imageBack = gdrawable.get_image(x, y, w, h) imageVert = gdrawable.get_image(x, y, h, w) imageFlip = gtk.gdk.Image(type=gdk.IMAGE_FASTEST, visual=gdrawable.get_visual(), width=w, height=h) if imageFlip == None or imageBack == None or imageVert == None: warnings.warn("Could not renderer vertical text") return imageFlip.set_colormap(self._cmap) for i in range(w): for j in range(h): imageFlip.put_pixel(i, j, imageVert.get_pixel(j,w-i-1) ) gdrawable.draw_image(ggc, imageFlip, 0, 0, x, y, w, h) gdrawable.draw_layout(ggc, x, y-b, layout) imageIn = gdrawable.get_image(x, y, w, h) for i in range(w): for j in range(h): imageVert.put_pixel(j, i, imageIn.get_pixel(w-i-1,j) ) gdrawable.draw_image(ggc, imageBack, 0, 0, x, y, w, h) gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w) self.rotated[key] = imageVert def _get_pango_layout(self, s, prop): """ Create a pango layout instance for Text 's' with properties 'prop'. Return - pango layout (from cache if already exists) Note that pango assumes a logical DPI of 96 Ref: pango/fonts.c/pango_font_description_set_size() manual page """ # problem? - cache gets bigger and bigger, is never cleared out # two (not one) layouts are created for every text item s (then they # are cached) - why? key = self.dpi, s, hash(prop) value = self.layoutd.get(key) if value != None: return value size = prop.get_size_in_points() * self.dpi / 96.0 size = np.round(size) font_str = '%s, %s %i' % (prop.get_name(), prop.get_style(), size,) font = pango.FontDescription(font_str) # later - add fontweight to font_str font.set_weight(self.fontweights[prop.get_weight()]) layout = self.gtkDA.create_pango_layout(s) layout.set_font_description(font) inkRect, logicalRect = layout.get_pixel_extents() self.layoutd[key] = layout, inkRect, logicalRect return layout, inkRect, logicalRect def flipy(self): return True def get_canvas_width_height(self): return self.width, self.height def get_text_width_height_descent(self, s, prop, ismath): if ismath: ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) return width, height, descent layout, inkRect, logicalRect = self._get_pango_layout(s, prop) l, b, w, h = inkRect ll, lb, lw, lh = logicalRect return w, h + 1, h - lh def new_gc(self): return GraphicsContextGDK(renderer=self) def points_to_pixels(self, points): return points/72.0 * self.dpi class GraphicsContextGDK(GraphicsContextBase): # a cache shared by all class instances _cached = {} # map: rgb color -> gdk.Color _joind = { 'bevel' : gdk.JOIN_BEVEL, 'miter' : gdk.JOIN_MITER, 'round' : gdk.JOIN_ROUND, } _capd = { 'butt' : gdk.CAP_BUTT, 'projecting' : gdk.CAP_PROJECTING, 'round' : gdk.CAP_ROUND, } def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer self.gdkGC = gtk.gdk.GC(renderer.gdkDrawable) self._cmap = renderer._cmap def rgb_to_gdk_color(self, rgb): """ rgb - an RGB tuple (three 0.0-1.0 values) return an allocated gtk.gdk.Color """ try: return self._cached[tuple(rgb)] except KeyError: color = self._cached[tuple(rgb)] = \ self._cmap.alloc_color( int(rgb[0]*65535),int(rgb[1]*65535),int(rgb[2]*65535)) return color #def set_antialiased(self, b): # anti-aliasing is not supported by GDK def set_capstyle(self, cs): GraphicsContextBase.set_capstyle(self, cs) self.gdkGC.cap_style = self._capd[self._capstyle] def set_clip_rectangle(self, rectangle): GraphicsContextBase.set_clip_rectangle(self, rectangle) if rectangle is None: return l,b,w,h = rectangle.bounds rectangle = (int(l), self.renderer.height-int(b+h)+1, int(w), int(h)) #rectangle = (int(l), self.renderer.height-int(b+h), # int(w+1), int(h+2)) self.gdkGC.set_clip_rectangle(rectangle) def set_dashes(self, dash_offset, dash_list): GraphicsContextBase.set_dashes(self, dash_offset, dash_list) if dash_list == None: self.gdkGC.line_style = gdk.LINE_SOLID else: pixels = self.renderer.points_to_pixels(np.asarray(dash_list)) dl = [max(1, int(np.round(val))) for val in pixels] self.gdkGC.set_dashes(dash_offset, dl) self.gdkGC.line_style = gdk.LINE_ON_OFF_DASH def set_foreground(self, fg, isRGBA=False): GraphicsContextBase.set_foreground(self, fg, isRGBA) self.gdkGC.foreground = self.rgb_to_gdk_color(self.get_rgb()) def set_joinstyle(self, js): GraphicsContextBase.set_joinstyle(self, js) self.gdkGC.join_style = self._joind[self._joinstyle] def set_linewidth(self, w): GraphicsContextBase.set_linewidth(self, w) if w == 0: self.gdkGC.line_width = 0 else: pixels = self.renderer.points_to_pixels(w) self.gdkGC.line_width = max(1, int(np.round(pixels))) class FigureCanvasGDK (FigureCanvasBase): def __init__(self, figure): FigureCanvasBase.__init__(self, figure) if self.__class__ == matplotlib.backends.backend_gdk.FigureCanvasGDK: warn_deprecated('2.0', message="The GDK backend is " "deprecated. It is untested, known to be " "broken and will be removed in Matplotlib 3.0. " "Use the Agg backend instead. " "See Matplotlib usage FAQ for" " more info on backends.", alternative="Agg") self._renderer_init() def _renderer_init(self): self._renderer = RendererGDK (gtk.DrawingArea(), self.figure.dpi) def _render_figure(self, pixmap, width, height): self._renderer.set_pixmap (pixmap) self._renderer.set_width_height (width, height) self.figure.draw (self._renderer) filetypes = FigureCanvasBase.filetypes.copy() filetypes['jpg'] = 'JPEG' filetypes['jpeg'] = 'JPEG' def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, 'jpeg') print_jpg = print_jpeg def print_png(self, filename, *args, **kwargs): return self._print_image(filename, 'png') def _print_image(self, filename, format, *args, **kwargs): width, height = self.get_width_height() pixmap = gtk.gdk.Pixmap (None, width, height, depth=24) self._render_figure(pixmap, width, height) # jpg colors don't match the display very well, png colors match # better pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) # set the default quality, if we are writing a JPEG. # http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html#method-gdkpixbuf--save options = {k: kwargs[k] for k in ['quality'] if k in kwargs} if format in ['jpg', 'jpeg']: options.setdefault('quality', rcParams['savefig.jpeg_quality']) options['quality'] = str(options['quality']) pixbuf.save(filename, format, options=options) @_Backend.export class _BackendGDK(_Backend): FigureCanvas = FigureCanvasGDK FigureManager = FigureManagerBase
15,793
34.977221
85
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_webagg_core.py
""" Displays Agg images in the browser, with interactivity """ # The WebAgg backend is divided into two modules: # # - `backend_webagg_core.py` contains code necessary to embed a WebAgg # plot inside of a web application, and communicate in an abstract # way over a web socket. # # - `backend_webagg.py` contains a concrete implementation of a basic # application, implemented with tornado. from __future__ import (absolute_import, division, print_function, unicode_literals) import six import datetime import io import json import os import warnings import numpy as np import tornado from matplotlib.backends import backend_agg from matplotlib.backend_bases import _Backend from matplotlib import backend_bases from matplotlib import _png # http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes _SHIFT_LUT = {59: ':', 61: '+', 173: '_', 186: ':', 187: '+', 188: '<', 189: '_', 190: '>', 191: '?', 192: '~', 219: '{', 220: '|', 221: '}', 222: '"'} _LUT = {8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'control', 18: 'alt', 19: 'pause', 20: 'caps', 27: 'escape', 32: ' ', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'insert', 46: 'delete', 91: 'super', 92: 'super', 93: 'select', 106: '*', 107: '+', 109: '-', 110: '.', 111: '/', 144: 'num_lock', 145: 'scroll_lock', 186: ':', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: "'"} def _handle_key(key): """Handle key codes""" code = int(key[key.index('k') + 1:]) value = chr(code) # letter keys if code >= 65 and code <= 90: if 'shift+' in key: key = key.replace('shift+', '') else: value = value.lower() # number keys elif code >= 48 and code <= 57: if 'shift+' in key: value = ')!@#$%^&*('[int(value)] key = key.replace('shift+', '') # function keys elif code >= 112 and code <= 123: value = 'f%s' % (code - 111) # number pad keys elif code >= 96 and code <= 105: value = '%s' % (code - 96) # keys with shift alternatives elif code in _SHIFT_LUT and 'shift+' in key: key = key.replace('shift+', '') value = _SHIFT_LUT[code] elif code in _LUT: value = _LUT[code] key = key[:key.index('k')] + value return key class FigureCanvasWebAggCore(backend_agg.FigureCanvasAgg): supports_blit = False def __init__(self, *args, **kwargs): backend_agg.FigureCanvasAgg.__init__(self, *args, **kwargs) # Set to True when the renderer contains data that is newer # than the PNG buffer. self._png_is_old = True # Set to True by the `refresh` message so that the next frame # sent to the clients will be a full frame. self._force_full = True # Store the current image mode so that at any point, clients can # request the information. This should be changed by calling # self.set_image_mode(mode) so that the notification can be given # to the connected clients. self._current_image_mode = 'full' # Store the DPI ratio of the browser. This is the scaling that # occurs automatically for all images on a HiDPI display. self._dpi_ratio = 1 def show(self): # show the figure window from matplotlib.pyplot import show show() def draw(self): renderer = self.get_renderer(cleared=True) self._png_is_old = True backend_agg.RendererAgg.lock.acquire() try: self.figure.draw(renderer) finally: backend_agg.RendererAgg.lock.release() # Swap the frames self.manager.refresh_all() def draw_idle(self): self.send_event("draw") def set_image_mode(self, mode): """ Set the image mode for any subsequent images which will be sent to the clients. The modes may currently be either 'full' or 'diff'. Note: diff images may not contain transparency, therefore upon draw this mode may be changed if the resulting image has any transparent component. """ if mode not in ['full', 'diff']: raise ValueError('image mode must be either full or diff.') if self._current_image_mode != mode: self._current_image_mode = mode self.handle_send_image_mode(None) def get_diff_image(self): if self._png_is_old: renderer = self.get_renderer() # The buffer is created as type uint32 so that entire # pixels can be compared in one numpy call, rather than # needing to compare each plane separately. buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32) .reshape((renderer.height, renderer.width))) # If any pixels have transparency, we need to force a full # draw as we cannot overlay new on top of old. pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,)) if self._force_full or np.any(pixels[:, :, 3] != 255): self.set_image_mode('full') output = buff else: self.set_image_mode('diff') last_buffer = (np.frombuffer(self._last_renderer.buffer_rgba(), dtype=np.uint32) .reshape((renderer.height, renderer.width))) diff = buff != last_buffer output = np.where(diff, buff, 0) # TODO: We should write a new version of write_png that # handles the differencing inline buff = _png.write_png( output.view(dtype=np.uint8).reshape(output.shape + (4,)), None, compression=6, filter=_png.PNG_FILTER_NONE) # Swap the renderer frames self._renderer, self._last_renderer = ( self._last_renderer, renderer) self._force_full = False self._png_is_old = False return buff def get_renderer(self, cleared=None): # Mirrors super.get_renderer, but caches the old one # so that we can do things such as produce a diff image # in get_diff_image _, _, w, h = self.figure.bbox.bounds w, h = int(w), int(h) key = w, h, self.figure.dpi try: self._lastKey, self._renderer except AttributeError: need_new_renderer = True else: need_new_renderer = (self._lastKey != key) if need_new_renderer: self._renderer = backend_agg.RendererAgg( w, h, self.figure.dpi) self._last_renderer = backend_agg.RendererAgg( w, h, self.figure.dpi) self._lastKey = key elif cleared: self._renderer.clear() return self._renderer def handle_event(self, event): e_type = event['type'] handler = getattr(self, 'handle_{0}'.format(e_type), self.handle_unknown_event) return handler(event) def handle_unknown_event(self, event): warnings.warn('Unhandled message type {0}. {1}'.format( event['type'], event)) def handle_ack(self, event): # Network latency tends to decrease if traffic is flowing # in both directions. Therefore, the browser sends back # an "ack" message after each image frame is received. # This could also be used as a simple sanity check in the # future, but for now the performance increase is enough # to justify it, even if the server does nothing with it. pass def handle_draw(self, event): self.draw() def _handle_mouse(self, event): x = event['x'] y = event['y'] y = self.get_renderer().height - y # Javascript button numbers and matplotlib button numbers are # off by 1 button = event['button'] + 1 # The right mouse button pops up a context menu, which # doesn't work very well, so use the middle mouse button # instead. It doesn't seem that it's possible to disable # the context menu in recent versions of Chrome. If this # is resolved, please also adjust the docstring in MouseEvent. if button == 2: button = 3 e_type = event['type'] guiEvent = event.get('guiEvent', None) if e_type == 'button_press': self.button_press_event(x, y, button, guiEvent=guiEvent) elif e_type == 'button_release': self.button_release_event(x, y, button, guiEvent=guiEvent) elif e_type == 'motion_notify': self.motion_notify_event(x, y, guiEvent=guiEvent) elif e_type == 'figure_enter': self.enter_notify_event(xy=(x, y), guiEvent=guiEvent) elif e_type == 'figure_leave': self.leave_notify_event() elif e_type == 'scroll': self.scroll_event(x, y, event['step'], guiEvent=guiEvent) handle_button_press = handle_button_release = handle_motion_notify = \ handle_figure_enter = handle_figure_leave = handle_scroll = \ _handle_mouse def _handle_key(self, event): key = _handle_key(event['key']) e_type = event['type'] guiEvent = event.get('guiEvent', None) if e_type == 'key_press': self.key_press_event(key, guiEvent=guiEvent) elif e_type == 'key_release': self.key_release_event(key, guiEvent=guiEvent) handle_key_press = handle_key_release = _handle_key def handle_toolbar_button(self, event): # TODO: Be more suspicious of the input getattr(self.toolbar, event['name'])() def handle_refresh(self, event): figure_label = self.figure.get_label() if not figure_label: figure_label = "Figure {0}".format(self.manager.num) self.send_event('figure_label', label=figure_label) self._force_full = True self.draw_idle() def handle_resize(self, event): x, y = event.get('width', 800), event.get('height', 800) x, y = int(x) * self._dpi_ratio, int(y) * self._dpi_ratio fig = self.figure # An attempt at approximating the figure size in pixels. fig.set_size_inches(x / fig.dpi, y / fig.dpi, forward=False) _, _, w, h = self.figure.bbox.bounds # Acknowledge the resize, and force the viewer to update the # canvas size to the figure's new size (which is hopefully # identical or within a pixel or so). self._png_is_old = True self.manager.resize(w, h) self.resize_event() def handle_send_image_mode(self, event): # The client requests notification of what the current image mode is. self.send_event('image_mode', mode=self._current_image_mode) def handle_set_dpi_ratio(self, event): dpi_ratio = event.get('dpi_ratio', 1) if dpi_ratio != self._dpi_ratio: # We don't want to scale up the figure dpi more than once. if not hasattr(self.figure, '_original_dpi'): self.figure._original_dpi = self.figure.dpi self.figure.dpi = dpi_ratio * self.figure._original_dpi self._dpi_ratio = dpi_ratio self._force_full = True self.draw_idle() def send_event(self, event_type, **kwargs): self.manager._send_event(event_type, **kwargs) _JQUERY_ICON_CLASSES = { 'home': 'ui-icon ui-icon-home', 'back': 'ui-icon ui-icon-circle-arrow-w', 'forward': 'ui-icon ui-icon-circle-arrow-e', 'zoom_to_rect': 'ui-icon ui-icon-search', 'move': 'ui-icon ui-icon-arrow-4', 'download': 'ui-icon ui-icon-disk', None: None, } class NavigationToolbar2WebAgg(backend_bases.NavigationToolbar2): # Use the standard toolbar items + download button toolitems = [(text, tooltip_text, _JQUERY_ICON_CLASSES[image_file], name_of_method) for text, tooltip_text, image_file, name_of_method in (backend_bases.NavigationToolbar2.toolitems + (('Download', 'Download plot', 'download', 'download'),)) if image_file in _JQUERY_ICON_CLASSES] def _init_toolbar(self): self.message = '' self.cursor = 0 def set_message(self, message): if message != self.message: self.canvas.send_event("message", message=message) self.message = message def set_cursor(self, cursor): if cursor != self.cursor: self.canvas.send_event("cursor", cursor=cursor) self.cursor = cursor def draw_rubberband(self, event, x0, y0, x1, y1): self.canvas.send_event( "rubberband", x0=x0, y0=y0, x1=x1, y1=y1) def release_zoom(self, event): backend_bases.NavigationToolbar2.release_zoom(self, event) self.canvas.send_event( "rubberband", x0=-1, y0=-1, x1=-1, y1=-1) def save_figure(self, *args): """Save the current figure""" self.canvas.send_event('save') class FigureManagerWebAgg(backend_bases.FigureManagerBase): ToolbarCls = NavigationToolbar2WebAgg def __init__(self, canvas, num): backend_bases.FigureManagerBase.__init__(self, canvas, num) self.web_sockets = set() self.toolbar = self._get_toolbar(canvas) def show(self): pass def _get_toolbar(self, canvas): toolbar = self.ToolbarCls(canvas) return toolbar def resize(self, w, h): self._send_event( 'resize', size=(w / self.canvas._dpi_ratio, h / self.canvas._dpi_ratio)) def set_window_title(self, title): self._send_event('figure_label', label=title) # The following methods are specific to FigureManagerWebAgg def add_web_socket(self, web_socket): assert hasattr(web_socket, 'send_binary') assert hasattr(web_socket, 'send_json') self.web_sockets.add(web_socket) _, _, w, h = self.canvas.figure.bbox.bounds self.resize(w, h) self._send_event('refresh') def remove_web_socket(self, web_socket): self.web_sockets.remove(web_socket) def handle_json(self, content): self.canvas.handle_event(content) def refresh_all(self): if self.web_sockets: diff = self.canvas.get_diff_image() if diff is not None: for s in self.web_sockets: s.send_binary(diff) @classmethod def get_javascript(cls, stream=None): if stream is None: output = io.StringIO() else: output = stream with io.open(os.path.join( os.path.dirname(__file__), "web_backend", "js", "mpl.js"), encoding='utf8') as fd: output.write(fd.read()) toolitems = [] for name, tooltip, image, method in cls.ToolbarCls.toolitems: if name is None: toolitems.append(['', '', '', '']) else: toolitems.append([name, tooltip, image, method]) output.write("mpl.toolbar_items = {0};\n\n".format( json.dumps(toolitems))) extensions = [] for filetype, ext in sorted(FigureCanvasWebAggCore. get_supported_filetypes_grouped(). items()): if not ext[0] == 'pgf': # pgf does not support BytesIO extensions.append(ext[0]) output.write("mpl.extensions = {0};\n\n".format( json.dumps(extensions))) output.write("mpl.default_extension = {0};".format( json.dumps(FigureCanvasWebAggCore.get_default_filetype()))) if stream is None: return output.getvalue() @classmethod def get_static_file_path(cls): return os.path.join(os.path.dirname(__file__), 'web_backend') def _send_event(self, event_type, **kwargs): payload = {'type': event_type} payload.update(kwargs) for s in self.web_sockets: s.send_json(payload) class TimerTornado(backend_bases.TimerBase): def _timer_start(self): self._timer_stop() if self._single: ioloop = tornado.ioloop.IOLoop.instance() self._timer = ioloop.add_timeout( datetime.timedelta(milliseconds=self.interval), self._on_timer) else: self._timer = tornado.ioloop.PeriodicCallback( self._on_timer, self.interval) self._timer.start() def _timer_stop(self): if self._timer is None: return elif self._single: ioloop = tornado.ioloop.IOLoop.instance() ioloop.remove_timeout(self._timer) else: self._timer.stop() self._timer = None def _timer_set_interval(self): # Only stop and restart it if the timer has already been started if self._timer is not None: self._timer_stop() self._timer_start() @_Backend.export class _BackendWebAggCoreAgg(_Backend): FigureCanvas = FigureCanvasWebAggCore FigureManager = FigureManagerWebAgg
17,958
32.012868
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/_backend_tk.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import tkinter as Tk import logging import os.path import sys # Paint image to Tk photo blitter extension import matplotlib.backends.tkagg as tkagg from matplotlib.backends.backend_agg import FigureCanvasAgg import matplotlib.backends.windowing as windowing import matplotlib from matplotlib import backend_tools, cbook, rcParams from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, StatusbarBase, TimerBase, ToolContainerBase, cursors) from matplotlib.backend_managers import ToolManager from matplotlib._pylab_helpers import Gcf from matplotlib.figure import Figure from matplotlib.widgets import SubplotTool _log = logging.getLogger(__name__) backend_version = Tk.TkVersion # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 75 cursord = { cursors.MOVE: "fleur", cursors.HAND: "hand2", cursors.POINTER: "arrow", cursors.SELECT_REGION: "tcross", cursors.WAIT: "watch", } def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines""" if not isinstance(msg, six.string_types): msg = '\n'.join(map(str, msg)) return msg def error_msg_tkpaint(msg, parent=None): from six.moves import tkinter_messagebox as tkMessageBox tkMessageBox.showerror("matplotlib", msg) class TimerTk(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses Tk's timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def __init__(self, parent, *args, **kwargs): TimerBase.__init__(self, *args, **kwargs) self.parent = parent self._timer = None def _timer_start(self): self._timer_stop() self._timer = self.parent.after(self._interval, self._on_timer) def _timer_stop(self): if self._timer is not None: self.parent.after_cancel(self._timer) self._timer = None def _on_timer(self): TimerBase._on_timer(self) # Tk after() is only a single shot, so we need to add code here to # reset the timer if we're not operating in single shot mode. However, # if _timer is None, this means that _timer_stop has been called; so # don't recreate the timer in that case. if not self._single and self._timer: self._timer = self.parent.after(self._interval, self._on_timer) else: self._timer = None class FigureCanvasTk(FigureCanvasBase): keyvald = {65507 : 'control', 65505 : 'shift', 65513 : 'alt', 65515 : 'super', 65508 : 'control', 65506 : 'shift', 65514 : 'alt', 65361 : 'left', 65362 : 'up', 65363 : 'right', 65364 : 'down', 65307 : 'escape', 65470 : 'f1', 65471 : 'f2', 65472 : 'f3', 65473 : 'f4', 65474 : 'f5', 65475 : 'f6', 65476 : 'f7', 65477 : 'f8', 65478 : 'f9', 65479 : 'f10', 65480 : 'f11', 65481 : 'f12', 65300 : 'scroll_lock', 65299 : 'break', 65288 : 'backspace', 65293 : 'enter', 65379 : 'insert', 65535 : 'delete', 65360 : 'home', 65367 : 'end', 65365 : 'pageup', 65366 : 'pagedown', 65438 : '0', 65436 : '1', 65433 : '2', 65435 : '3', 65430 : '4', 65437 : '5', 65432 : '6', 65429 : '7', 65431 : '8', 65434 : '9', 65451 : '+', 65453 : '-', 65450 : '*', 65455 : '/', 65439 : 'dec', 65421 : 'enter', } _keycode_lookup = { 262145: 'control', 524320: 'alt', 524352: 'alt', 1048584: 'super', 1048592: 'super', 131074: 'shift', 131076: 'shift', } """_keycode_lookup is used for badly mapped (i.e. no event.key_sym set) keys on apple keyboards.""" def __init__(self, figure, master=None, resize_callback=None): super(FigureCanvasTk, self).__init__(figure) self._idle = True self._idle_callback = None t1,t2,w,h = self.figure.bbox.bounds w, h = int(w), int(h) self._tkcanvas = Tk.Canvas( master=master, background="white", width=w, height=h, borderwidth=0, highlightthickness=0) self._tkphoto = Tk.PhotoImage( master=self._tkcanvas, width=w, height=h) self._tkcanvas.create_image(w//2, h//2, image=self._tkphoto) self._resize_callback = resize_callback self._tkcanvas.bind("<Configure>", self.resize) self._tkcanvas.bind("<Key>", self.key_press) self._tkcanvas.bind("<Motion>", self.motion_notify_event) self._tkcanvas.bind("<KeyRelease>", self.key_release) for name in "<Button-1>", "<Button-2>", "<Button-3>": self._tkcanvas.bind(name, self.button_press_event) for name in "<Double-Button-1>", "<Double-Button-2>", "<Double-Button-3>": self._tkcanvas.bind(name, self.button_dblclick_event) for name in "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>": self._tkcanvas.bind(name, self.button_release_event) # Mouse wheel on Linux generates button 4/5 events for name in "<Button-4>", "<Button-5>": self._tkcanvas.bind(name, self.scroll_event) # Mouse wheel for windows goes to the window with the focus. # Since the canvas won't usually have the focus, bind the # event to the window containing the canvas instead. # See http://wiki.tcl.tk/3893 (mousewheel) for details root = self._tkcanvas.winfo_toplevel() root.bind("<MouseWheel>", self.scroll_event_windows, "+") # Can't get destroy events by binding to _tkcanvas. Therefore, bind # to the window and filter. def filter_destroy(evt): if evt.widget is self._tkcanvas: self._master.update_idletasks() self.close_event() root.bind("<Destroy>", filter_destroy, "+") self._master = master self._tkcanvas.focus_set() def resize(self, event): width, height = event.width, event.height if self._resize_callback is not None: self._resize_callback(event) # compute desired figure size in inches dpival = self.figure.dpi winch = width/dpival hinch = height/dpival self.figure.set_size_inches(winch, hinch, forward=False) self._tkcanvas.delete(self._tkphoto) self._tkphoto = Tk.PhotoImage( master=self._tkcanvas, width=int(width), height=int(height)) self._tkcanvas.create_image(int(width/2),int(height/2),image=self._tkphoto) self.resize_event() self.draw() # a resizing will in general move the pointer position # relative to the canvas, so process it as a motion notify # event. An intended side effect of this call is to allow # window raises (which trigger a resize) to get the cursor # position to the mpl event framework so key presses which are # over the axes will work w/o clicks or explicit motion self._update_pointer_position(event) def _update_pointer_position(self, guiEvent=None): """ Figure out if we are inside the canvas or not and update the canvas enter/leave events """ # if the pointer if over the canvas, set the lastx and lasty # attrs of the canvas so it can process event w/o mouse click # or move # the window's upper, left coords in screen coords xw = self._tkcanvas.winfo_rootx() yw = self._tkcanvas.winfo_rooty() # the pointer's location in screen coords xp, yp = self._tkcanvas.winfo_pointerxy() # not figure out the canvas coordinates of the pointer xc = xp - xw yc = yp - yw # flip top/bottom yc = self.figure.bbox.height - yc # JDH: this method was written originally to get the pointer # location to the backend lastx and lasty attrs so that events # like KeyEvent can be handled without mouse events. e.g., if # the cursor is already above the axes, then key presses like # 'g' should toggle the grid. In order for this to work in # backend_bases, the canvas needs to know _lastx and _lasty. # There are three ways to get this info the canvas: # # 1) set it explicitly # # 2) call enter/leave events explicitly. The downside of this # in the impl below is that enter could be repeatedly # triggered if the mouse is over the axes and one is # resizing with the keyboard. This is not entirely bad, # because the mouse position relative to the canvas is # changing, but it may be surprising to get repeated entries # without leaves # # 3) process it as a motion notify event. This also has pros # and cons. The mouse is moving relative to the window, but # this may surpise an event handler writer who is getting # motion_notify_events even if the mouse has not moved # here are the three scenarios if 1: # just manually set it self._lastx, self._lasty = xc, yc elif 0: # alternate implementation: process it as a motion FigureCanvasBase.motion_notify_event(self, xc, yc, guiEvent) elif 0: # alternate implementation -- process enter/leave events # instead of motion/notify if self.figure.bbox.contains(xc, yc): self.enter_notify_event(guiEvent, xy=(xc,yc)) else: self.leave_notify_event(guiEvent) show = cbook.deprecated("2.2", name="FigureCanvasTk.show", alternative="FigureCanvasTk.draw")( lambda self: self.draw()) def draw_idle(self): 'update drawing area only if idle' if self._idle is False: return self._idle = False def idle_draw(*args): try: self.draw() finally: self._idle = True self._idle_callback = self._tkcanvas.after_idle(idle_draw) def get_tk_widget(self): """returns the Tk widget used to implement FigureCanvasTkAgg. Although the initial implementation uses a Tk canvas, this routine is intended to hide that fact. """ return self._tkcanvas def motion_notify_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) def button_press_event(self, event, dblclick=False): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if sys.platform=='darwin': # 2 and 3 were reversed on the OSX platform I # tested under tkagg if num==2: num=3 elif num==3: num=2 FigureCanvasBase.button_press_event(self, x, y, num, dblclick=dblclick, guiEvent=event) def button_dblclick_event(self,event): self.button_press_event(event,dblclick=True) def button_release_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if sys.platform=='darwin': # 2 and 3 were reversed on the OSX platform I # tested under tkagg if num==2: num=3 elif num==3: num=2 FigureCanvasBase.button_release_event(self, x, y, num, guiEvent=event) def scroll_event(self, event): x = event.x y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if num==4: step = +1 elif num==5: step = -1 else: step = 0 FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) def scroll_event_windows(self, event): """MouseWheel event processor""" # need to find the window that contains the mouse w = event.widget.winfo_containing(event.x_root, event.y_root) if w == self._tkcanvas: x = event.x_root - w.winfo_rootx() y = event.y_root - w.winfo_rooty() y = self.figure.bbox.height - y step = event.delta/120. FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) def _get_key(self, event): val = event.keysym_num if val in self.keyvald: key = self.keyvald[val] elif val == 0 and sys.platform == 'darwin' and \ event.keycode in self._keycode_lookup: key = self._keycode_lookup[event.keycode] elif val < 256: key = chr(val) else: key = None # add modifier keys to the key string. Bit details originate from # http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm # BIT_SHIFT = 0x001; BIT_CAPSLOCK = 0x002; BIT_CONTROL = 0x004; # BIT_LEFT_ALT = 0x008; BIT_NUMLOCK = 0x010; BIT_RIGHT_ALT = 0x080; # BIT_MB_1 = 0x100; BIT_MB_2 = 0x200; BIT_MB_3 = 0x400; # In general, the modifier key is excluded from the modifier flag, # however this is not the case on "darwin", so double check that # we aren't adding repeat modifier flags to a modifier key. if sys.platform == 'win32': modifiers = [(17, 'alt', 'alt'), (2, 'ctrl', 'control'), ] elif sys.platform == 'darwin': modifiers = [(3, 'super', 'super'), (4, 'alt', 'alt'), (2, 'ctrl', 'control'), ] else: modifiers = [(6, 'super', 'super'), (3, 'alt', 'alt'), (2, 'ctrl', 'control'), ] if key is not None: # note, shift is not added to the keys as this is already accounted for for bitmask, prefix, key_name in modifiers: if event.state & (1 << bitmask) and key_name not in key: key = '{0}+{1}'.format(prefix, key) return key def key_press(self, event): key = self._get_key(event) FigureCanvasBase.key_press_event(self, key, guiEvent=event) def key_release(self, event): key = self._get_key(event) FigureCanvasBase.key_release_event(self, key, guiEvent=event) def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Other Parameters ---------------- interval : scalar Timer interval in milliseconds callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerTk(self._tkcanvas, *args, **kwargs) def flush_events(self): self._master.update() class FigureManagerTk(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : tk.Toolbar The tk.Toolbar window : tk.Window The tk.Window """ def __init__(self, canvas, num, window): FigureManagerBase.__init__(self, canvas, num) self.window = window self.window.withdraw() self.set_window_title("Figure %d" % num) self.canvas = canvas self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self._num = num self.toolmanager = self._get_toolmanager() self.toolbar = self._get_toolbar() self.statusbar = None if self.toolmanager: backend_tools.add_tools_to_manager(self.toolmanager) if self.toolbar: backend_tools.add_tools_to_container(self.toolbar) self.statusbar = StatusbarTk(self.window, self.toolmanager) self._shown = False def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolmanager is not None: pass elif self.toolbar is not None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) def _get_toolbar(self): if matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2Tk(self.canvas, self.window) elif matplotlib.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarTk(self.toolmanager, self.window) else: toolbar = None return toolbar def _get_toolmanager(self): if rcParams['toolbar'] == 'toolmanager': toolmanager = ToolManager(self.canvas.figure) else: toolmanager = None return toolmanager def resize(self, width, height=None): # before 09-12-22, the resize method takes a single *event* # parameter. On the other hand, the resize method of other # FigureManager class takes *width* and *height* parameter, # which is used to change the size of the window. For the # Figure.set_size_inches with forward=True work with Tk # backend, I changed the function signature but tried to keep # it backward compatible. -JJL # when a single parameter is given, consider it as a event if height is None: cbook.warn_deprecated("2.2", "FigureManagerTkAgg.resize now takes " "width and height as separate arguments") width = width.width else: self.canvas._tkcanvas.master.geometry("%dx%d" % (width, height)) if self.toolbar is not None: self.toolbar.configure(width=width) def show(self): """ this function doesn't segfault but causes the PyEval_RestoreThread: NULL state bug on win32 """ _focus = windowing.FocusManager() if not self._shown: def destroy(*args): self.window = None Gcf.destroy(self._num) self.canvas._tkcanvas.bind("<Destroy>", destroy) self.window.deiconify() else: self.canvas.draw_idle() # Raise the new window. self.canvas.manager.window.attributes('-topmost', 1) self.canvas.manager.window.attributes('-topmost', 0) self._shown = True def destroy(self, *args): if self.window is not None: #self.toolbar.destroy() if self.canvas._idle_callback: self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback) self.window.destroy() if Gcf.get_num_fig_managers()==0: if self.window is not None: self.window.quit() self.window = None def get_window_title(self): return self.window.wm_title() def set_window_title(self, title): self.window.wm_title(title) def full_screen_toggle(self): is_fullscreen = bool(self.window.attributes('-fullscreen')) self.window.attributes('-fullscreen', not is_fullscreen) @cbook.deprecated("2.2") class AxisMenu(object): def __init__(self, master, naxes): self._master = master self._naxes = naxes self._mbar = Tk.Frame(master=master, relief=Tk.RAISED, borderwidth=2) self._mbar.pack(side=Tk.LEFT) self._mbutton = Tk.Menubutton( master=self._mbar, text="Axes", underline=0) self._mbutton.pack(side=Tk.LEFT, padx="2m") self._mbutton.menu = Tk.Menu(self._mbutton) self._mbutton.menu.add_command( label="Select All", command=self.select_all) self._mbutton.menu.add_command( label="Invert All", command=self.invert_all) self._axis_var = [] self._checkbutton = [] for i in range(naxes): self._axis_var.append(Tk.IntVar()) self._axis_var[i].set(1) self._checkbutton.append(self._mbutton.menu.add_checkbutton( label = "Axis %d" % (i+1), variable=self._axis_var[i], command=self.set_active)) self._mbutton.menu.invoke(self._mbutton.menu.index("Select All")) self._mbutton['menu'] = self._mbutton.menu self._mbar.tk_menuBar(self._mbutton) self.set_active() def adjust(self, naxes): if self._naxes < naxes: for i in range(self._naxes, naxes): self._axis_var.append(Tk.IntVar()) self._axis_var[i].set(1) self._checkbutton.append( self._mbutton.menu.add_checkbutton( label = "Axis %d" % (i+1), variable=self._axis_var[i], command=self.set_active)) elif self._naxes > naxes: for i in range(self._naxes-1, naxes-1, -1): del self._axis_var[i] self._mbutton.menu.forget(self._checkbutton[i]) del self._checkbutton[i] self._naxes = naxes self.set_active() def get_indices(self): a = [i for i in range(len(self._axis_var)) if self._axis_var[i].get()] return a def set_active(self): self._master.set_active(self.get_indices()) def invert_all(self): for a in self._axis_var: a.set(not a.get()) self.set_active() def select_all(self): for a in self._axis_var: a.set(1) self.set_active() class NavigationToolbar2Tk(NavigationToolbar2, Tk.Frame): """ Attributes ---------- canvas : `FigureCanvas` the figure canvas on which to operate win : tk.Window the tk.Window which owns this toolbar """ def __init__(self, canvas, window): self.canvas = canvas self.window = window NavigationToolbar2.__init__(self, canvas) def destroy(self, *args): del self.message Tk.Frame.destroy(self, *args) def set_message(self, s): self.message.set(s) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y0 = height - y0 y1 = height - y1 if hasattr(self, "lastrect"): self.canvas._tkcanvas.delete(self.lastrect) self.lastrect = self.canvas._tkcanvas.create_rectangle(x0, y0, x1, y1) #self.canvas.draw() def release(self, event): try: self.lastrect except AttributeError: pass else: self.canvas._tkcanvas.delete(self.lastrect) del self.lastrect def set_cursor(self, cursor): self.window.configure(cursor=cursord[cursor]) self.window.update_idletasks() def _Button(self, text, file, command, extension='.gif'): img_file = os.path.join( rcParams['datapath'], 'images', file + extension) im = Tk.PhotoImage(master=self, file=img_file) b = Tk.Button( master=self, text=text, padx=2, pady=2, image=im, command=command) b._ntimage = im b.pack(side=Tk.LEFT) return b def _Spacer(self): # Buttons are 30px high, so make this 26px tall with padding to center it s = Tk.Frame( master=self, height=26, relief=Tk.RIDGE, pady=2, bg="DarkGray") s.pack(side=Tk.LEFT, padx=5) return s def _init_toolbar(self): xmin, xmax = self.canvas.figure.bbox.intervalx height, width = 50, xmax-xmin Tk.Frame.__init__(self, master=self.window, width=int(width), height=int(height), borderwidth=2) self.update() # Make axes menu for text, tooltip_text, image_file, callback in self.toolitems: if text is None: # Add a spacer; return value is unused. self._Spacer() else: button = self._Button(text=text, file=image_file, command=getattr(self, callback)) if tooltip_text is not None: ToolTip.createToolTip(button, tooltip_text) self.message = Tk.StringVar(master=self) self._message_label = Tk.Label(master=self, textvariable=self.message) self._message_label.pack(side=Tk.RIGHT) self.pack(side=Tk.BOTTOM, fill=Tk.X) def configure_subplots(self): toolfig = Figure(figsize=(6,3)) window = Tk.Toplevel() canvas = type(self.canvas)(toolfig, master=window) toolfig.subplots_adjust(top=0.9) canvas.tool = SubplotTool(self.canvas.figure, toolfig) canvas.draw() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) window.grab_set() def save_figure(self, *args): from six.moves import tkinter_tkfiledialog, tkinter_messagebox filetypes = self.canvas.get_supported_filetypes().copy() default_filetype = self.canvas.get_default_filetype() # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first default_filetype_name = filetypes.pop(default_filetype) sorted_filetypes = ([(default_filetype, default_filetype_name)] + sorted(six.iteritems(filetypes))) tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes] # adding a default extension seems to break the # asksaveasfilename dialog when you choose various save types # from the dropdown. Passing in the empty string seems to # work - JDH! #defaultextension = self.canvas.get_default_filetype() defaultextension = '' initialdir = os.path.expanduser(rcParams['savefig.directory']) initialfile = self.canvas.get_default_filename() fname = tkinter_tkfiledialog.asksaveasfilename( master=self.window, title='Save the figure', filetypes=tk_filetypes, defaultextension=defaultextension, initialdir=initialdir, initialfile=initialfile, ) if fname in ["", ()]: return # Save dir for next time, unless empty str (i.e., use cwd). if initialdir != "": rcParams['savefig.directory'] = ( os.path.dirname(six.text_type(fname))) try: # This method will handle the delegation to the correct type self.canvas.figure.savefig(fname) except Exception as e: tkinter_messagebox.showerror("Error saving file", str(e)) def set_active(self, ind): self._ind = ind self._active = [self._axes[i] for i in self._ind] def update(self): _focus = windowing.FocusManager() self._axes = self.canvas.figure.axes NavigationToolbar2.update(self) class ToolTip(object): """ Tooltip recipe from http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_01.shtml#e387 """ @staticmethod def createToolTip(widget, text): toolTip = ToolTip(widget) def enter(event): toolTip.showtip(text) def leave(event): toolTip.hidetip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 def showtip(self, text): "Display text in tooltip window" self.text = text if self.tipwindow or not self.text: return x, y, _, _ = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + self.widget.winfo_rooty() self.tipwindow = tw = Tk.Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except Tk.TclError: pass label = Tk.Label(tw, text=self.text, justify=Tk.LEFT, background="#ffffe0", relief=Tk.SOLID, borderwidth=1) label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() class RubberbandTk(backend_tools.RubberbandBase): def __init__(self, *args, **kwargs): backend_tools.RubberbandBase.__init__(self, *args, **kwargs) def draw_rubberband(self, x0, y0, x1, y1): height = self.figure.canvas.figure.bbox.height y0 = height - y0 y1 = height - y1 if hasattr(self, "lastrect"): self.figure.canvas._tkcanvas.delete(self.lastrect) self.lastrect = self.figure.canvas._tkcanvas.create_rectangle( x0, y0, x1, y1) def remove_rubberband(self): if hasattr(self, "lastrect"): self.figure.canvas._tkcanvas.delete(self.lastrect) del self.lastrect class SetCursorTk(backend_tools.SetCursorBase): def set_cursor(self, cursor): self.figure.canvas.manager.window.configure(cursor=cursord[cursor]) class ToolbarTk(ToolContainerBase, Tk.Frame): _icon_extension = '.gif' def __init__(self, toolmanager, window): ToolContainerBase.__init__(self, toolmanager) xmin, xmax = self.toolmanager.canvas.figure.bbox.intervalx height, width = 50, xmax - xmin Tk.Frame.__init__(self, master=window, width=int(width), height=int(height), borderwidth=2) self._toolitems = {} self.pack(side=Tk.TOP, fill=Tk.X) self._groups = {} def add_toolitem( self, name, group, position, image_file, description, toggle): frame = self._get_groupframe(group) button = self._Button(name, image_file, toggle, frame) if description is not None: ToolTip.createToolTip(button, description) self._toolitems.setdefault(name, []) self._toolitems[name].append(button) def _get_groupframe(self, group): if group not in self._groups: if self._groups: self._add_separator() frame = Tk.Frame(master=self, borderwidth=0) frame.pack(side=Tk.LEFT, fill=Tk.Y) self._groups[group] = frame return self._groups[group] def _add_separator(self): separator = Tk.Frame(master=self, bd=5, width=1, bg='black') separator.pack(side=Tk.LEFT, fill=Tk.Y, padx=2) def _Button(self, text, image_file, toggle, frame): if image_file is not None: im = Tk.PhotoImage(master=self, file=image_file) else: im = None if not toggle: b = Tk.Button(master=frame, text=text, padx=2, pady=2, image=im, command=lambda: self._button_click(text)) else: # There is a bug in tkinter included in some python 3.6 versions # that without this variable, produces a "visual" toggling of # other near checkbuttons # https://bugs.python.org/issue29402 # https://bugs.python.org/issue25684 var = Tk.IntVar() b = Tk.Checkbutton(master=frame, text=text, padx=2, pady=2, image=im, indicatoron=False, command=lambda: self._button_click(text), variable=var) b._ntimage = im b.pack(side=Tk.LEFT) return b def _button_click(self, name): self.trigger_tool(name) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for toolitem in self._toolitems[name]: if toggled: toolitem.select() else: toolitem.deselect() def remove_toolitem(self, name): for toolitem in self._toolitems[name]: toolitem.pack_forget() del self._toolitems[name] class StatusbarTk(StatusbarBase, Tk.Frame): def __init__(self, window, *args, **kwargs): StatusbarBase.__init__(self, *args, **kwargs) xmin, xmax = self.toolmanager.canvas.figure.bbox.intervalx height, width = 50, xmax - xmin Tk.Frame.__init__(self, master=window, width=int(width), height=int(height), borderwidth=2) self._message = Tk.StringVar(master=self) self._message_label = Tk.Label(master=self, textvariable=self._message) self._message_label.pack(side=Tk.RIGHT) self.pack(side=Tk.TOP, fill=Tk.X) def set_message(self, s): self._message.set(s) class SaveFigureTk(backend_tools.SaveFigureBase): def trigger(self, *args): from six.moves import tkinter_tkfiledialog, tkinter_messagebox filetypes = self.figure.canvas.get_supported_filetypes().copy() default_filetype = self.figure.canvas.get_default_filetype() # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first default_filetype_name = filetypes.pop(default_filetype) sorted_filetypes = ([(default_filetype, default_filetype_name)] + sorted(six.iteritems(filetypes))) tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes] # adding a default extension seems to break the # asksaveasfilename dialog when you choose various save types # from the dropdown. Passing in the empty string seems to # work - JDH! # defaultextension = self.figure.canvas.get_default_filetype() defaultextension = '' initialdir = os.path.expanduser(rcParams['savefig.directory']) initialfile = self.figure.canvas.get_default_filename() fname = tkinter_tkfiledialog.asksaveasfilename( master=self.figure.canvas.manager.window, title='Save the figure', filetypes=tk_filetypes, defaultextension=defaultextension, initialdir=initialdir, initialfile=initialfile, ) if fname == "" or fname == (): return else: if initialdir == '': # explicitly missing key or empty str signals to use cwd rcParams['savefig.directory'] = initialdir else: # save dir for next time rcParams['savefig.directory'] = os.path.dirname( six.text_type(fname)) try: # This method will handle the delegation to the correct type self.figure.savefig(fname) except Exception as e: tkinter_messagebox.showerror("Error saving file", str(e)) class ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase): def __init__(self, *args, **kwargs): backend_tools.ConfigureSubplotsBase.__init__(self, *args, **kwargs) self.window = None def trigger(self, *args): self.init_window() self.window.lift() def init_window(self): if self.window: return toolfig = Figure(figsize=(6, 3)) self.window = Tk.Tk() canvas = type(self.canvas)(toolfig, master=self.window) toolfig.subplots_adjust(top=0.9) _tool = SubplotTool(self.figure, toolfig) canvas.draw() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.window.protocol("WM_DELETE_WINDOW", self.destroy) def destroy(self, *args, **kwargs): self.window.destroy() self.window = None backend_tools.ToolSaveFigure = SaveFigureTk backend_tools.ToolConfigureSubplots = ConfigureSubplotsTk backend_tools.ToolSetCursor = SetCursorTk backend_tools.ToolRubberband = RubberbandTk Toolbar = ToolbarTk @_Backend.export class _BackendTk(_Backend): FigureManager = FigureManagerTk @classmethod def new_figure_manager_given_figure(cls, num, figure): """ Create a new figure manager instance for the given figure. """ _focus = windowing.FocusManager() window = Tk.Tk(className="matplotlib") window.withdraw() # Put a mpl icon on the window rather than the default tk icon. # Tkinter doesn't allow colour icons on linux systems, but tk>=8.5 has # a iconphoto command which we call directly. Source: # http://mail.python.org/pipermail/tkinter-discuss/2006-November/000954.html icon_fname = os.path.join( rcParams['datapath'], 'images', 'matplotlib.ppm') icon_img = Tk.PhotoImage(file=icon_fname) try: window.tk.call('wm', 'iconphoto', window._w, icon_img) except Exception as exc: # log the failure (due e.g. to Tk version), but carry on _log.info('Could not load matplotlib icon: %s', exc) canvas = cls.FigureCanvas(figure, master=window) manager = cls.FigureManager(canvas, num, window) if matplotlib.is_interactive(): manager.show() canvas.draw_idle() return manager @staticmethod def trigger_manager_draw(manager): manager.show() @staticmethod def mainloop(): Tk.mainloop()
39,322
35.613594
166
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_qt4cairo.py
from .backend_qt5cairo import _BackendQT5Cairo @_BackendQT5Cairo.export class _BackendQT4Cairo(_BackendQT5Cairo): pass
125
17
46
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py
""" A PostScript backend, which can produce both PostScript .ps and .eps """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import StringIO import glob, os, shutil, sys, time, datetime import io import logging from tempfile import mkstemp from matplotlib import cbook, __version__, rcParams, checkdep_ghostscript from matplotlib.afm import AFM from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) from matplotlib.cbook import (get_realpath_and_stat, is_writable_file_like, maxdict, file_requires_unicode) from matplotlib.compat.subprocess import subprocess from matplotlib.font_manager import findfont, is_opentype_cff_font, get_font from matplotlib.ft2font import KERNING_DEFAULT, LOAD_NO_HINTING from matplotlib.ttconv import convert_ttf_to_ps from matplotlib.mathtext import MathTextParser from matplotlib._mathtext_data import uni2type1 from matplotlib.path import Path from matplotlib import _path from matplotlib.transforms import Affine2D from matplotlib.backends.backend_mixed import MixedModeRenderer import numpy as np import binascii import re _log = logging.getLogger(__name__) backend_version = 'Level II' debugPS = 0 class PsBackendHelper(object): def __init__(self): self._cached = {} @property def gs_exe(self): """ executable name of ghostscript. """ try: return self._cached["gs_exe"] except KeyError: pass gs_exe, gs_version = checkdep_ghostscript() if gs_exe is None: gs_exe = 'gs' self._cached["gs_exe"] = str(gs_exe) return str(gs_exe) @property def gs_version(self): """ version of ghostscript. """ try: return self._cached["gs_version"] except KeyError: pass from matplotlib.compat.subprocess import Popen, PIPE s = Popen([self.gs_exe, "--version"], stdout=PIPE) pipe, stderr = s.communicate() if six.PY3: ver = pipe.decode('ascii') else: ver = pipe try: gs_version = tuple(map(int, ver.strip().split("."))) except ValueError: # if something went wrong parsing return null version number gs_version = (0, 0) self._cached["gs_version"] = gs_version return gs_version @property def supports_ps2write(self): """ True if the installed ghostscript supports ps2write device. """ return self.gs_version[0] >= 9 ps_backend_helper = PsBackendHelper() papersize = {'letter': (8.5,11), 'legal': (8.5,14), 'ledger': (11,17), 'a0': (33.11,46.81), 'a1': (23.39,33.11), 'a2': (16.54,23.39), 'a3': (11.69,16.54), 'a4': (8.27,11.69), 'a5': (5.83,8.27), 'a6': (4.13,5.83), 'a7': (2.91,4.13), 'a8': (2.07,2.91), 'a9': (1.457,2.05), 'a10': (1.02,1.457), 'b0': (40.55,57.32), 'b1': (28.66,40.55), 'b2': (20.27,28.66), 'b3': (14.33,20.27), 'b4': (10.11,14.33), 'b5': (7.16,10.11), 'b6': (5.04,7.16), 'b7': (3.58,5.04), 'b8': (2.51,3.58), 'b9': (1.76,2.51), 'b10': (1.26,1.76)} def _get_papertype(w, h): keys = list(six.iterkeys(papersize)) keys.sort() keys.reverse() for key in keys: if key.startswith('l'): continue pw, ph = papersize[key] if (w < pw) and (h < ph): return key return 'a0' def _num_to_str(val): if isinstance(val, six.string_types): return val ival = int(val) if val == ival: return str(ival) s = "%1.3f"%val s = s.rstrip("0") s = s.rstrip(".") return s def _nums_to_str(*args): return ' '.join(map(_num_to_str,args)) def quote_ps_string(s): "Quote dangerous characters of S for use in a PostScript string constant." s = s.replace(b"\\", b"\\\\") s = s.replace(b"(", b"\\(") s = s.replace(b")", b"\\)") s = s.replace(b"'", b"\\251") s = s.replace(b"`", b"\\301") s = re.sub(br"[^ -~\n]", lambda x: br"\%03o" % ord(x.group()), s) return s.decode('ascii') def _move_path_to_path_or_stream(src, dst): """Move the contents of file at *src* to path-or-filelike *dst*. If *dst* is a path, the metadata of *src* are *not* copied. """ if is_writable_file_like(dst): fh = (io.open(src, 'r', encoding='latin-1') if file_requires_unicode(dst) else io.open(src, 'rb')) with fh: shutil.copyfileobj(fh, dst) else: # Py3: shutil.move(src, dst, copy_function=shutil.copyfile) open(dst, 'w').close() mode = os.stat(dst).st_mode shutil.move(src, dst) os.chmod(dst, mode) class RendererPS(RendererBase): """ The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles. """ afmfontd = maxdict(50) def __init__(self, width, height, pswriter, imagedpi=72): """ Although postscript itself is dpi independent, we need to imform the image code about a requested dpi to generate high res images and them scale them before embeddin them """ RendererBase.__init__(self) self.width = width self.height = height self._pswriter = pswriter if rcParams['text.usetex']: self.textcnt = 0 self.psfrag = [] self.imagedpi = imagedpi # current renderer state (None=uninitialised) self.color = None self.linewidth = None self.linejoin = None self.linecap = None self.linedash = None self.fontname = None self.fontsize = None self._hatches = {} self.image_magnification = imagedpi/72.0 self._clip_paths = {} self._path_collection_id = 0 self.used_characters = {} self.mathtext_parser = MathTextParser("PS") self._afm_font_dir = os.path.join( rcParams['datapath'], 'fonts', 'afm') def track_characters(self, font, s): """Keeps track of which characters are required from each font.""" realpath, stat_key = get_realpath_and_stat(font.fname) used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update([ord(x) for x in s]) def merge_used_characters(self, other): for stat_key, (realpath, charset) in six.iteritems(other): used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update(charset) def set_color(self, r, g, b, store=1): if (r,g,b) != self.color: if r==g and r==b: self._pswriter.write("%1.3f setgray\n"%r) else: self._pswriter.write("%1.3f %1.3f %1.3f setrgbcolor\n"%(r,g,b)) if store: self.color = (r,g,b) def set_linewidth(self, linewidth, store=1): linewidth = float(linewidth) if linewidth != self.linewidth: self._pswriter.write("%1.3f setlinewidth\n"%linewidth) if store: self.linewidth = linewidth def set_linejoin(self, linejoin, store=1): if linejoin != self.linejoin: self._pswriter.write("%d setlinejoin\n"%linejoin) if store: self.linejoin = linejoin def set_linecap(self, linecap, store=1): if linecap != self.linecap: self._pswriter.write("%d setlinecap\n"%linecap) if store: self.linecap = linecap def set_linedash(self, offset, seq, store=1): if self.linedash is not None: oldo, oldseq = self.linedash if np.array_equal(seq, oldseq) and oldo == offset: return if seq is not None and len(seq): s="[%s] %d setdash\n"%(_nums_to_str(*seq), offset) self._pswriter.write(s) else: self._pswriter.write("[] 0 setdash\n") if store: self.linedash = (offset, seq) def set_font(self, fontname, fontsize, store=1): if rcParams['ps.useafm']: return if (fontname,fontsize) != (self.fontname,self.fontsize): out = ("/%s findfont\n" "%1.3f scalefont\n" "setfont\n" % (fontname, fontsize)) self._pswriter.write(out) if store: self.fontname = fontname if store: self.fontsize = fontsize def create_hatch(self, hatch): sidelen = 72 if hatch in self._hatches: return self._hatches[hatch] name = 'H%d' % len(self._hatches) linewidth = rcParams['hatch.linewidth'] pageheight = self.height * 72 self._pswriter.write("""\ << /PatternType 1 /PaintType 2 /TilingType 2 /BBox[0 0 %(sidelen)d %(sidelen)d] /XStep %(sidelen)d /YStep %(sidelen)d /PaintProc { pop %(linewidth)f setlinewidth """ % locals()) self._pswriter.write( self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)) self._pswriter.write("""\ fill stroke } bind >> matrix 0.0 %(pageheight)f translate makepattern /%(name)s exch def """ % locals()) self._hatches[hatch] = name return name def get_canvas_width_height(self): 'return the canvas width and height in display coords' return self.width * 72.0, self.height * 72.0 def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop """ if rcParams['text.usetex']: texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() w, h, d = texmanager.get_text_width_height_descent(s, fontsize, renderer=self) return w, h, d if ismath: width, height, descent, pswriter, used_characters = \ self.mathtext_parser.parse(s, 72, prop) return width, height, descent if rcParams['ps.useafm']: if ismath: s = s[1:-1] font = self._get_font_afm(prop) l,b,w,h,d = font.get_str_bbox_and_descent(s) fontsize = prop.get_size_in_points() scale = 0.001*fontsize w *= scale h *= scale d *= scale return w, h, d font = self._get_font_ttf(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) w, h = font.get_width_height() w /= 64.0 # convert from subpixels h /= 64.0 d = font.get_descent() d /= 64.0 return w, h, d def flipy(self): 'return true if small y numbers are top for renderer' return False def _get_font_afm(self, prop): key = hash(prop) font = self.afmfontd.get(key) if font is None: fname = findfont(prop, fontext='afm', directory=self._afm_font_dir) if fname is None: fname = findfont( "Helvetica", fontext='afm', directory=self._afm_font_dir) font = self.afmfontd.get(fname) if font is None: with io.open(fname, 'rb') as fh: font = AFM(fh) self.afmfontd[fname] = font self.afmfontd[key] = font return font def _get_font_ttf(self, prop): fname = findfont(prop) font = get_font(fname) font.clear() size = prop.get_size_in_points() font.set_size(size, 72.0) return font def _rgb(self, rgba): h, w = rgba.shape[:2] rgb = rgba[::-1, :, :3] return h, w, rgb.tostring() def _hex_lines(self, s, chars_per_line=128): s = binascii.b2a_hex(s) nhex = len(s) lines = [] for i in range(0,nhex,chars_per_line): limit = min(i+chars_per_line, nhex) lines.append(s[i:limit]) return lines def get_image_magnification(self): """ Get the factor by which to magnify images passed to draw_image. Allows a backend to have images at a different resolution to other artists. """ return self.image_magnification def option_scale_image(self): """ ps backend support arbitrary scaling of image. """ return True def option_image_nocomposite(self): """ return whether to generate a composite image from multiple images on a set of axes """ return not rcParams['image.composite_image'] def _get_image_h_w_bits_command(self, im): h, w, bits = self._rgb(im) imagecmd = "false 3 colorimage" return h, w, bits, imagecmd def draw_image(self, gc, x, y, im, transform=None): """ Draw the Image instance into the current axes; x is the distance in pixels from the left hand side of the canvas and y is the distance from bottom """ h, w, bits, imagecmd = self._get_image_h_w_bits_command(im) hexlines = b'\n'.join(self._hex_lines(bits)).decode('ascii') if transform is None: matrix = "1 0 0 1 0 0" xscale = w / self.image_magnification yscale = h / self.image_magnification else: matrix = " ".join(map(str, transform.frozen().to_values())) xscale = 1.0 yscale = 1.0 figh = self.height * 72 bbox = gc.get_clip_rectangle() clippath, clippath_trans = gc.get_clip_path() clip = [] if bbox is not None: clipx,clipy,clipw,cliph = bbox.bounds clip.append('%s clipbox' % _nums_to_str(clipw, cliph, clipx, clipy)) if clippath is not None: id = self._get_clip_path(clippath, clippath_trans) clip.append('%s' % id) clip = '\n'.join(clip) ps = """gsave %(clip)s %(x)s %(y)s translate [%(matrix)s] concat %(xscale)s %(yscale)s scale /DataString %(w)s string def %(w)s %(h)s 8 [ %(w)s 0 0 -%(h)s 0 %(h)s ] { currentfile DataString readhexstring pop } bind %(imagecmd)s %(hexlines)s grestore """ % locals() self._pswriter.write(ps) def _convert_path(self, path, transform, clip=False, simplify=None): if clip: clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0) else: clip = None return _path.convert_to_string( path, transform, clip, simplify, None, 6, [b'm', b'l', b'', b'c', b'cl'], True).decode('ascii') def _get_clip_path(self, clippath, clippath_transform): key = (clippath, id(clippath_transform)) pid = self._clip_paths.get(key) if pid is None: pid = 'c%x' % len(self._clip_paths) ps_cmd = ['/%s {' % pid] ps_cmd.append(self._convert_path(clippath, clippath_transform, simplify=False)) ps_cmd.extend(['clip', 'newpath', '} bind def\n']) self._pswriter.write('\n'.join(ps_cmd)) self._clip_paths[key] = pid return pid def draw_path(self, gc, path, transform, rgbFace=None): """ Draws a Path instance using the given affine transform. """ clip = rgbFace is None and gc.get_hatch_path() is None simplify = path.should_simplify and clip ps = self._convert_path(path, transform, clip=clip, simplify=simplify) self._draw_ps(ps, gc, rgbFace) def draw_markers( self, gc, marker_path, marker_trans, path, trans, rgbFace=None): """ Draw the markers defined by path at each of the positions in x and y. path coordinates are points, x and y coords will be transformed by the transform """ if debugPS: self._pswriter.write('% draw_markers \n') if rgbFace: if len(rgbFace) == 4 and rgbFace[3] == 0: return if rgbFace[0] == rgbFace[1] == rgbFace[2]: ps_color = '%1.3f setgray' % rgbFace[0] else: ps_color = '%1.3f %1.3f %1.3f setrgbcolor' % rgbFace[:3] # construct the generic marker command: ps_cmd = ['/o {', 'gsave', 'newpath', 'translate'] # don't want the translate to be global lw = gc.get_linewidth() stroke = lw != 0.0 if stroke: ps_cmd.append('%.1f setlinewidth' % lw) jint = gc.get_joinstyle() ps_cmd.append('%d setlinejoin' % jint) cint = gc.get_capstyle() ps_cmd.append('%d setlinecap' % cint) ps_cmd.append(self._convert_path(marker_path, marker_trans, simplify=False)) if rgbFace: if stroke: ps_cmd.append('gsave') ps_cmd.extend([ps_color, 'fill']) if stroke: ps_cmd.append('grestore') if stroke: ps_cmd.append('stroke') ps_cmd.extend(['grestore', '} bind def']) for vertices, code in path.iter_segments( trans, clip=(0, 0, self.width*72, self.height*72), simplify=False): if len(vertices): x, y = vertices[-2:] ps_cmd.append("%g %g o" % (x, y)) ps = '\n'.join(ps_cmd) self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False) def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): # Is the optimization worth it? Rough calculation: # cost of emitting a path in-line is # (len_path + 2) * uses_per_path # cost of definition+use is # (len_path + 3) + 3 * uses_per_path len_path = len(paths[0].vertices) if len(paths) > 0 else 0 uses_per_path = self._iter_collection_uses_per_path( paths, all_transforms, offsets, facecolors, edgecolors) should_do_optimization = \ len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path if not should_do_optimization: return RendererBase.draw_path_collection( self, gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position) write = self._pswriter.write path_codes = [] for i, (path, transform) in enumerate(self._iter_collection_raw_paths( master_transform, paths, all_transforms)): name = 'p%x_%x' % (self._path_collection_id, i) ps_cmd = ['/%s {' % name, 'newpath', 'translate'] ps_cmd.append(self._convert_path(path, transform, simplify=False)) ps_cmd.extend(['} bind def\n']) write('\n'.join(ps_cmd)) path_codes.append(name) for xo, yo, path_id, gc0, rgbFace in self._iter_collection( gc, master_transform, all_transforms, path_codes, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): ps = "%g %g %s" % (xo, yo, path_id) self._draw_ps(ps, gc0, rgbFace) self._path_collection_id += 1 def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None): """ draw a Text instance """ w, h, bl = self.get_text_width_height_descent(s, prop, ismath) fontsize = prop.get_size_in_points() thetext = 'psmarker%d' % self.textcnt color = '%1.3f,%1.3f,%1.3f'% gc.get_rgb()[:3] fontcmd = {'sans-serif' : r'{\sffamily %s}', 'monospace' : r'{\ttfamily %s}'}.get( rcParams['font.family'][0], r'{\rmfamily %s}') s = fontcmd % s tex = r'\color[rgb]{%s} %s' % (color, s) corr = 0#w/2*(fontsize-10)/10 if rcParams['text.latex.preview']: # use baseline alignment! pos = _nums_to_str(x-corr, y) self.psfrag.append(r'\psfrag{%s}[Bl][Bl][1][%f]{\fontsize{%f}{%f}%s}'%(thetext, angle, fontsize, fontsize*1.25, tex)) else: # stick to the bottom alignment, but this may give incorrect baseline some times. pos = _nums_to_str(x-corr, y-bl) self.psfrag.append(r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}'%(thetext, angle, fontsize, fontsize*1.25, tex)) ps = """\ gsave %(pos)s moveto (%(thetext)s) show grestore """ % locals() self._pswriter.write(ps) self.textcnt += 1 def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): """ Draw a Text instance. """ # local to avoid repeated attribute lookups write = self._pswriter.write if debugPS: write("% text\n") if len(gc.get_rgb()) == 4 and gc.get_rgb()[3] == 0: return # Special handling for fully transparent. if ismath=='TeX': return self.draw_tex(gc, x, y, s, prop, angle) elif ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) elif rcParams['ps.useafm']: self.set_color(*gc.get_rgb()) font = self._get_font_afm(prop) fontname = font.get_fontname() fontsize = prop.get_size_in_points() scale = 0.001*fontsize thisx = 0 thisy = font.get_str_bbox_and_descent(s)[4] * scale last_name = None lines = [] for c in s: name = uni2type1.get(ord(c), 'question') try: width = font.get_width_from_char_name(name) except KeyError: name = 'question' width = font.get_width_char('?') if last_name is not None: kern = font.get_kern_dist_from_name(last_name, name) else: kern = 0 last_name = name thisx += kern * scale lines.append('%f %f m /%s glyphshow'%(thisx, thisy, name)) thisx += width * scale thetext = "\n".join(lines) ps = """\ gsave /%(fontname)s findfont %(fontsize)s scalefont setfont %(x)f %(y)f translate %(angle)f rotate %(thetext)s grestore """ % locals() self._pswriter.write(ps) else: font = self._get_font_ttf(prop) font.set_text(s, 0, flags=LOAD_NO_HINTING) self.track_characters(font, s) self.set_color(*gc.get_rgb()) sfnt = font.get_sfnt() try: ps_name = sfnt[1, 0, 0, 6].decode('mac_roman') except KeyError: ps_name = sfnt[3, 1, 0x0409, 6].decode('utf-16be') ps_name = ps_name.encode('ascii', 'replace').decode('ascii') self.set_font(ps_name, prop.get_size_in_points()) lastgind = None lines = [] thisx = 0 thisy = 0 for c in s: ccode = ord(c) gind = font.get_char_index(ccode) if gind is None: ccode = ord('?') name = '.notdef' gind = 0 else: name = font.get_glyph_name(gind) glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) if lastgind is not None: kern = font.get_kerning(lastgind, gind, KERNING_DEFAULT) else: kern = 0 lastgind = gind thisx += kern/64.0 lines.append('%f %f m /%s glyphshow'%(thisx, thisy, name)) thisx += glyph.linearHoriAdvance/65536.0 thetext = '\n'.join(lines) ps = """gsave %(x)f %(y)f translate %(angle)f rotate %(thetext)s grestore """ % locals() self._pswriter.write(ps) def new_gc(self): return GraphicsContextPS() def draw_mathtext(self, gc, x, y, s, prop, angle): """ Draw the math text using matplotlib.mathtext """ if debugPS: self._pswriter.write("% mathtext\n") width, height, descent, pswriter, used_characters = \ self.mathtext_parser.parse(s, 72, prop) self.merge_used_characters(used_characters) self.set_color(*gc.get_rgb()) thetext = pswriter.getvalue() ps = """gsave %(x)f %(y)f translate %(angle)f rotate %(thetext)s grestore """ % locals() self._pswriter.write(ps) def draw_gouraud_triangle(self, gc, points, colors, trans): self.draw_gouraud_triangles(gc, points.reshape((1, 3, 2)), colors.reshape((1, 3, 4)), trans) def draw_gouraud_triangles(self, gc, points, colors, trans): assert len(points) == len(colors) assert points.ndim == 3 assert points.shape[1] == 3 assert points.shape[2] == 2 assert colors.ndim == 3 assert colors.shape[1] == 3 assert colors.shape[2] == 4 shape = points.shape flat_points = points.reshape((shape[0] * shape[1], 2)) flat_points = trans.transform(flat_points) flat_colors = colors.reshape((shape[0] * shape[1], 4)) points_min = np.min(flat_points, axis=0) - (1 << 12) points_max = np.max(flat_points, axis=0) + (1 << 12) factor = np.ceil((2 ** 32 - 1) / (points_max - points_min)) xmin, ymin = points_min xmax, ymax = points_max streamarr = np.empty( (shape[0] * shape[1],), dtype=[('flags', 'u1'), ('points', '>u4', (2,)), ('colors', 'u1', (3,))]) streamarr['flags'] = 0 streamarr['points'] = (flat_points - points_min) * factor streamarr['colors'] = flat_colors[:, :3] * 255.0 stream = quote_ps_string(streamarr.tostring()) self._pswriter.write(""" gsave << /ShadingType 4 /ColorSpace [/DeviceRGB] /BitsPerCoordinate 32 /BitsPerComponent 8 /BitsPerFlag 8 /AntiAlias true /Decode [ %(xmin)f %(xmax)f %(ymin)f %(ymax)f 0 1 0 1 0 1 ] /DataSource (%(stream)s) >> shfill grestore """ % locals()) def _draw_ps(self, ps, gc, rgbFace, fill=True, stroke=True, command=None): """ Emit the PostScript sniplet 'ps' with all the attributes from 'gc' applied. 'ps' must consist of PostScript commands to construct a path. The fill and/or stroke kwargs can be set to False if the 'ps' string already includes filling and/or stroking, in which case _draw_ps is just supplying properties and clipping. """ # local variable eliminates all repeated attribute lookups write = self._pswriter.write if debugPS and command: write("% "+command+"\n") mightstroke = gc.shouldstroke() stroke = stroke and mightstroke fill = (fill and rgbFace is not None and (len(rgbFace) <= 3 or rgbFace[3] != 0.0)) hatch = gc.get_hatch() if mightstroke: self.set_linewidth(gc.get_linewidth()) jint = gc.get_joinstyle() self.set_linejoin(jint) cint = gc.get_capstyle() self.set_linecap(cint) self.set_linedash(*gc.get_dashes()) self.set_color(*gc.get_rgb()[:3]) write('gsave\n') cliprect = gc.get_clip_rectangle() if cliprect: x,y,w,h=cliprect.bounds write('%1.4g %1.4g %1.4g %1.4g clipbox\n' % (w,h,x,y)) clippath, clippath_trans = gc.get_clip_path() if clippath: id = self._get_clip_path(clippath, clippath_trans) write('%s\n' % id) # Jochen, is the strip necessary? - this could be a honking big string write(ps.strip()) write("\n") if fill: if stroke or hatch: write("gsave\n") self.set_color(store=0, *rgbFace[:3]) write("fill\n") if stroke or hatch: write("grestore\n") if hatch: hatch_name = self.create_hatch(hatch) write("gsave\n") write("%f %f %f " % gc.get_hatch_color()[:3]) write("%s setpattern fill grestore\n" % hatch_name) if stroke: write("stroke\n") write("grestore\n") class GraphicsContextPS(GraphicsContextBase): def get_capstyle(self): return {'butt':0, 'round':1, 'projecting':2}[GraphicsContextBase.get_capstyle(self)] def get_joinstyle(self): return {'miter':0, 'round':1, 'bevel':2}[GraphicsContextBase.get_joinstyle(self)] def shouldstroke(self): return (self.get_linewidth() > 0.0 and (len(self.get_rgb()) <= 3 or self.get_rgb()[3] != 0.0)) class FigureCanvasPS(FigureCanvasBase): _renderer_class = RendererPS fixed_dpi = 72 def draw(self): pass filetypes = {'ps' : 'Postscript', 'eps' : 'Encapsulated Postscript'} def get_default_filetype(self): return 'ps' def print_ps(self, outfile, *args, **kwargs): return self._print_ps(outfile, 'ps', *args, **kwargs) def print_eps(self, outfile, *args, **kwargs): return self._print_ps(outfile, 'eps', *args, **kwargs) def _print_ps(self, outfile, format, *args, **kwargs): papertype = kwargs.pop("papertype", rcParams['ps.papersize']) papertype = papertype.lower() if papertype == 'auto': pass elif papertype not in papersize: raise RuntimeError('%s is not a valid papertype. Use one of %s' % (papertype, ', '.join(papersize))) orientation = kwargs.pop("orientation", "portrait").lower() if orientation == 'landscape': isLandscape = True elif orientation == 'portrait': isLandscape = False else: raise RuntimeError('Orientation must be "portrait" or "landscape"') self.figure.set_dpi(72) # Override the dpi kwarg imagedpi = kwargs.pop("dpi", 72) facecolor = kwargs.pop("facecolor", "w") edgecolor = kwargs.pop("edgecolor", "w") if rcParams['text.usetex']: self._print_figure_tex(outfile, format, imagedpi, facecolor, edgecolor, orientation, isLandscape, papertype, **kwargs) else: self._print_figure(outfile, format, imagedpi, facecolor, edgecolor, orientation, isLandscape, papertype, **kwargs) def _print_figure(self, outfile, format, dpi=72, facecolor='w', edgecolor='w', orientation='portrait', isLandscape=False, papertype=None, metadata=None, **kwargs): """ Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you'll probably want to override this on hardcopy If outfile is a string, it is interpreted as a file name. If the extension matches .ep* write encapsulated postscript, otherwise write a stand-alone PostScript file. If outfile is a file object, a stand-alone PostScript file is written into this file object. metadata must be a dictionary. Currently, only the value for the key 'Creator' is used. """ isEPSF = format == 'eps' if isinstance(outfile, (six.string_types, getattr(os, "PathLike", ()),)): outfile = title = getattr(os, "fspath", lambda obj: obj)(outfile) passed_in_file_object = False elif is_writable_file_like(outfile): title = None passed_in_file_object = True else: raise ValueError("outfile must be a path or a file-like object") # find the appropriate papertype width, height = self.figure.get_size_inches() if papertype == 'auto': if isLandscape: papertype = _get_papertype(height, width) else: papertype = _get_papertype(width, height) if isLandscape: paperHeight, paperWidth = papersize[papertype] else: paperWidth, paperHeight = papersize[papertype] if rcParams['ps.usedistiller'] and not papertype == 'auto': # distillers will improperly clip eps files if the pagesize is # too small if width>paperWidth or height>paperHeight: if isLandscape: papertype = _get_papertype(height, width) paperHeight, paperWidth = papersize[papertype] else: papertype = _get_papertype(width, height) paperWidth, paperHeight = papersize[papertype] # center the figure on the paper xo = 72*0.5*(paperWidth - width) yo = 72*0.5*(paperHeight - height) l, b, w, h = self.figure.bbox.bounds llx = xo lly = yo urx = llx + w ury = lly + h rotation = 0 if isLandscape: llx, lly, urx, ury = lly, llx, ury, urx xo, yo = 72*paperHeight - yo, xo rotation = 90 bbox = (llx, lly, urx, ury) # generate PostScript code for the figure and store it in a string origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) dryrun = kwargs.get("dryrun", False) if dryrun: class NullWriter(object): def write(self, *kl, **kwargs): pass self._pswriter = NullWriter() else: self._pswriter = io.StringIO() # mixed mode rendering _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None) ps_renderer = self._renderer_class(width, height, self._pswriter, imagedpi=dpi) renderer = MixedModeRenderer(self.figure, width, height, dpi, ps_renderer, bbox_inches_restore=_bbox_inches_restore) self.figure.draw(renderer) if dryrun: # return immediately if dryrun (tightbbox=True) return self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) # check for custom metadata if metadata is not None and 'Creator' in metadata: creator_str = metadata['Creator'] else: creator_str = "matplotlib version " + __version__ + \ ", http://matplotlib.org/" def print_figure_impl(fh): # write the PostScript headers if isEPSF: print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) else: print("%!PS-Adobe-3.0", file=fh) if title: print("%%Title: "+title, file=fh) print("%%Creator: " + creator_str, file=fh) # get source date from SOURCE_DATE_EPOCH, if set # See https://reproducible-builds.org/specs/source-date-epoch/ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") if source_date_epoch: source_date = datetime.datetime.utcfromtimestamp( int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y") else: source_date = time.ctime() print("%%CreationDate: "+source_date, file=fh) print("%%Orientation: " + orientation, file=fh) if not isEPSF: print("%%DocumentPaperSizes: "+papertype, file=fh) print("%%%%BoundingBox: %d %d %d %d" % bbox, file=fh) if not isEPSF: print("%%Pages: 1", file=fh) print("%%EndComments", file=fh) Ndict = len(psDefs) print("%%BeginProlog", file=fh) if not rcParams['ps.useafm']: Ndict += len(ps_renderer.used_characters) print("/mpldict %d dict def" % Ndict, file=fh) print("mpldict begin", file=fh) for d in psDefs: d = d.strip() for l in d.split('\n'): print(l.strip(), file=fh) if not rcParams['ps.useafm']: for font_filename, chars in six.itervalues( ps_renderer.used_characters): if len(chars): font = get_font(font_filename) glyph_ids = [] for c in chars: gind = font.get_char_index(c) glyph_ids.append(gind) fonttype = rcParams['ps.fonttype'] # Can not use more than 255 characters from a # single font for Type 3 if len(glyph_ids) > 255: fonttype = 42 # The ttf to ps (subsetting) support doesn't work for # OpenType fonts that are Postscript inside (like the # STIX fonts). This will simply turn that off to avoid # errors. if is_opentype_cff_font(font_filename): raise RuntimeError( "OpenType CFF fonts can not be saved using " "the internal Postscript backend at this " "time; consider using the Cairo backend") else: fh.flush() convert_ttf_to_ps( font_filename.encode( sys.getfilesystemencoding()), fh, fonttype, glyph_ids) print("end", file=fh) print("%%EndProlog", file=fh) if not isEPSF: print("%%Page: 1 1", file=fh) print("mpldict begin", file=fh) print("%s translate" % _nums_to_str(xo, yo), file=fh) if rotation: print("%d rotate" % rotation, file=fh) print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0), file=fh) # write the figure content = self._pswriter.getvalue() if not isinstance(content, six.text_type): content = content.decode('ascii') print(content, file=fh) # write the trailer print("end", file=fh) print("showpage", file=fh) if not isEPSF: print("%%EOF", file=fh) fh.flush() if rcParams['ps.usedistiller']: # We are going to use an external program to process the output. # Write to a temporary file. fd, tmpfile = mkstemp() try: with io.open(fd, 'w', encoding='latin-1') as fh: print_figure_impl(fh) if rcParams['ps.usedistiller'] == 'ghostscript': gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) elif rcParams['ps.usedistiller'] == 'xpdf': xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) _move_path_to_path_or_stream(tmpfile, outfile) finally: if os.path.isfile(tmpfile): os.unlink(tmpfile) else: # Write directly to outfile. if passed_in_file_object: requires_unicode = file_requires_unicode(outfile) if (not requires_unicode and (six.PY3 or not isinstance(outfile, StringIO))): fh = io.TextIOWrapper(outfile, encoding="latin-1") # Prevent the io.TextIOWrapper from closing the # underlying file def do_nothing(): pass fh.close = do_nothing else: fh = outfile print_figure_impl(fh) else: with io.open(outfile, 'w', encoding='latin-1') as fh: print_figure_impl(fh) def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor, orientation, isLandscape, papertype, metadata=None, **kwargs): """ If text.usetex is True in rc, a temporary pair of tex/eps files are created to allow tex to manage the text layout via the PSFrags package. These files are processed to yield the final ps or eps file. metadata must be a dictionary. Currently, only the value for the key 'Creator' is used. """ isEPSF = format == 'eps' if isinstance(outfile, six.string_types): title = outfile elif is_writable_file_like(outfile): title = None else: raise ValueError("outfile must be a path or a file-like object") self.figure.dpi = 72 # ignore the dpi kwarg width, height = self.figure.get_size_inches() xo = 0 yo = 0 l, b, w, h = self.figure.bbox.bounds llx = xo lly = yo urx = llx + w ury = lly + h bbox = (llx, lly, urx, ury) # generate PostScript code for the figure and store it in a string origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) dryrun = kwargs.get("dryrun", False) if dryrun: class NullWriter(object): def write(self, *kl, **kwargs): pass self._pswriter = NullWriter() else: self._pswriter = io.StringIO() # mixed mode rendering _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None) ps_renderer = self._renderer_class(width, height, self._pswriter, imagedpi=dpi) renderer = MixedModeRenderer(self.figure, width, height, dpi, ps_renderer, bbox_inches_restore=_bbox_inches_restore) self.figure.draw(renderer) if dryrun: # return immediately if dryrun (tightbbox=True) return self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) # check for custom metadata if metadata is not None and 'Creator' in metadata: creator_str = metadata['Creator'] else: creator_str = "matplotlib version " + __version__ + \ ", http://matplotlib.org/" # write to a temp file, we'll move it to outfile when done fd, tmpfile = mkstemp() try: with io.open(fd, 'w', encoding='latin-1') as fh: # write the Encapsulated PostScript headers print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) if title: print("%%Title: "+title, file=fh) print("%%Creator: " + creator_str, file=fh) # get source date from SOURCE_DATE_EPOCH, if set # See https://reproducible-builds.org/specs/source-date-epoch/ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") if source_date_epoch: source_date = datetime.datetime.utcfromtimestamp( int(source_date_epoch)).strftime( "%a %b %d %H:%M:%S %Y") else: source_date = time.ctime() print("%%CreationDate: "+source_date, file=fh) print("%%%%BoundingBox: %d %d %d %d" % bbox, file=fh) print("%%EndComments", file=fh) Ndict = len(psDefs) print("%%BeginProlog", file=fh) print("/mpldict %d dict def" % Ndict, file=fh) print("mpldict begin", file=fh) for d in psDefs: d = d.strip() for l in d.split('\n'): print(l.strip(), file=fh) print("end", file=fh) print("%%EndProlog", file=fh) print("mpldict begin", file=fh) print("%s translate" % _nums_to_str(xo, yo), file=fh) print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0), file=fh) # write the figure print(self._pswriter.getvalue(), file=fh) # write the trailer print("end", file=fh) print("showpage", file=fh) fh.flush() if isLandscape: # now we are ready to rotate isLandscape = True width, height = height, width bbox = (lly, llx, ury, urx) # set the paper size to the figure size if isEPSF. The # resulting ps file has the given size with correct bounding # box so that there is no need to call 'pstoeps' if isEPSF: paperWidth, paperHeight = self.figure.get_size_inches() if isLandscape: paperWidth, paperHeight = paperHeight, paperWidth else: temp_papertype = _get_papertype(width, height) if papertype == 'auto': papertype = temp_papertype paperWidth, paperHeight = papersize[temp_papertype] else: paperWidth, paperHeight = papersize[papertype] if (width > paperWidth or height > paperHeight) and isEPSF: paperWidth, paperHeight = papersize[temp_papertype] _log.info('Your figure is too big to fit on %s paper. ' '%s paper will be used to prevent clipping.', papertype, temp_papertype) texmanager = ps_renderer.get_texmanager() font_preamble = texmanager.get_font_preamble() custom_preamble = texmanager.get_custom_preamble() psfrag_rotated = convert_psfrags(tmpfile, ps_renderer.psfrag, font_preamble, custom_preamble, paperWidth, paperHeight, orientation) if (rcParams['ps.usedistiller'] == 'ghostscript' or rcParams['text.usetex']): gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) elif rcParams['ps.usedistiller'] == 'xpdf': xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) _move_path_to_path_or_stream(tmpfile, outfile) finally: if os.path.isfile(tmpfile): os.unlink(tmpfile) def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble, paperWidth, paperHeight, orientation): """ When we want to use the LaTeX backend with postscript, we write PSFrag tags to a temporary postscript file, each one marking a position for LaTeX to render some text. convert_psfrags generates a LaTeX document containing the commands to convert those tags to text. LaTeX/dvips produces the postscript file that includes the actual text. """ tmpdir = os.path.split(tmpfile)[0] epsfile = tmpfile+'.eps' shutil.move(tmpfile, epsfile) latexfile = tmpfile+'.tex' dvifile = tmpfile+'.dvi' psfile = tmpfile+'.ps' if orientation == 'landscape': angle = 90 else: angle = 0 if rcParams['text.latex.unicode']: unicode_preamble = """\\usepackage{ucs} \\usepackage[utf8x]{inputenc}""" else: unicode_preamble = '' s = """\\documentclass{article} %s %s %s \\usepackage[dvips, papersize={%sin,%sin}, body={%sin,%sin}, margin={0in,0in}]{geometry} \\usepackage{psfrag} \\usepackage[dvips]{graphicx} \\usepackage{color} \\pagestyle{empty} \\begin{document} \\begin{figure} \\centering \\leavevmode %s \\includegraphics*[angle=%s]{%s} \\end{figure} \\end{document} """% (font_preamble, unicode_preamble, custom_preamble, paperWidth, paperHeight, paperWidth, paperHeight, '\n'.join(psfrags), angle, os.path.split(epsfile)[-1]) with io.open(latexfile, 'wb') as latexh: if rcParams['text.latex.unicode']: latexh.write(s.encode('utf8')) else: try: latexh.write(s.encode('ascii')) except UnicodeEncodeError: _log.info("You are using unicode and latex, but have " "not enabled the matplotlib 'text.latex.unicode' " "rcParam.") raise # Replace \\ for / so latex does not think there is a function call latexfile = latexfile.replace("\\", "/") # Replace ~ so Latex does not think it is line break latexfile = latexfile.replace("~", "\\string~") command = [str("latex"), "-interaction=nonstopmode", '"%s"' % latexfile] _log.debug('%s', command) try: report = subprocess.check_output(command, cwd=tmpdir, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('LaTeX was not able to process the following ' 'file:\n%s\n\n' 'Here is the full report generated by LaTeX:\n%s ' '\n\n' % (latexfile, exc.output.decode("utf-8")))) _log.debug(report) command = [str('dvips'), '-q', '-R0', '-o', os.path.basename(psfile), os.path.basename(dvifile)] _log.debug(command) try: report = subprocess.check_output(command, cwd=tmpdir, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('dvips was not able to process the following ' 'file:\n%s\n\n' 'Here is the full report generated by dvips:\n%s ' '\n\n' % (dvifile, exc.output.decode("utf-8")))) _log.debug(report) os.remove(epsfile) shutil.move(psfile, tmpfile) # check if the dvips created a ps in landscape paper. Somehow, # above latex+dvips results in a ps file in a landscape mode for a # certain figure sizes (e.g., 8.3in,5.8in which is a5). And the # bounding box of the final output got messed up. We check see if # the generated ps file is in landscape and return this # information. The return value is used in pstoeps step to recover # the correct bounding box. 2010-06-05 JJL with io.open(tmpfile) as fh: if "Landscape" in fh.read(1000): psfrag_rotated = True else: psfrag_rotated = False if not debugPS: for fname in glob.glob(tmpfile+'.*'): os.remove(fname) return psfrag_rotated def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): """ Use ghostscript's pswrite or epswrite device to distill a file. This yields smaller files without illegal encapsulated postscript operators. The output is low-level, converting text to outlines. """ if eps: paper_option = "-dEPSCrop" else: paper_option = "-sPAPERSIZE=%s" % ptype psfile = tmpfile + '.ps' dpi = rcParams['ps.distiller.res'] gs_exe = ps_backend_helper.gs_exe if ps_backend_helper.supports_ps2write: # gs version >= 9 device_name = "ps2write" else: device_name = "pswrite" command = [str(gs_exe), "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=%s" % device_name, paper_option, "-sOutputFile=%s" % psfile, tmpfile] _log.debug(command) try: report = subprocess.check_output(command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('ghostscript was not able to process your image.\n' 'Here is the full report generated by ghostscript:\n%s ' '\n\n' % exc.output.decode("utf-8"))) _log.debug(report) os.remove(tmpfile) shutil.move(psfile, tmpfile) # While it is best if above steps preserve the original bounding # box, there seem to be cases when it is not. For those cases, # the original bbox can be restored during the pstoeps step. if eps: # For some versions of gs, above steps result in an ps file # where the original bbox is no more correct. Do not adjust # bbox for now. if ps_backend_helper.supports_ps2write: # fo gs version >= 9 w/ ps2write device pstoeps(tmpfile, bbox, rotated=rotated) else: pstoeps(tmpfile) def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): """ Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file. This yields smaller files without illegal encapsulated postscript operators. This distiller is preferred, generating high-level postscript output that treats text as text. """ pdffile = tmpfile + '.pdf' psfile = tmpfile + '.ps' # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows happy # (https://www.ghostscript.com/doc/9.22/Use.htm#MS_Windows). command = [str("ps2pdf"), "-dAutoFilterColorImages#false", "-dAutoFilterGrayImages#false", "-dAutoRotatePages#false", "-sGrayImageFilter#FlateEncode", "-sColorImageFilter#FlateEncode", "-dEPSCrop" if eps else "-sPAPERSIZE#%s" % ptype, tmpfile, pdffile] _log.debug(command) try: report = subprocess.check_output(command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('ps2pdf was not able to process your image.\n' 'Here is the full report generated by ps2pdf:\n%s ' '\n\n' % exc.output.decode("utf-8"))) _log.debug(report) command = [str("pdftops"), "-paper", "match", "-level2", pdffile, psfile] _log.debug(command) try: report = subprocess.check_output(command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError( ('pdftops was not able to process your image.\n' 'Here is the full report generated by pdftops:\n%s ' '\n\n' % exc.output.decode("utf-8"))) _log.debug(report) os.remove(tmpfile) shutil.move(psfile, tmpfile) if eps: pstoeps(tmpfile) for fname in glob.glob(tmpfile+'.*'): os.remove(fname) def get_bbox_header(lbrt, rotated=False): """ return a postscript header stringfor the given bbox lbrt=(l, b, r, t). Optionally, return rotate command. """ l, b, r, t = lbrt if rotated: rotate = "%.2f %.2f translate\n90 rotate" % (l+r, 0) else: rotate = "" bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t)) hires_bbox_info = '%%%%HiResBoundingBox: %.6f %.6f %.6f %.6f' % (l, b, r, t) return '\n'.join([bbox_info, hires_bbox_info]), rotate # get_bbox is deprecated. I don't see any reason to use ghostscript to # find the bounding box, as the required bounding box is alread known. def get_bbox(tmpfile, bbox): """ Use ghostscript's bbox device to find the center of the bounding box. Return an appropriately sized bbox centered around that point. A bit of a hack. """ gs_exe = ps_backend_helper.gs_exe command = [gs_exe, "-dBATCH", "-dNOPAUSE", "-sDEVICE=bbox", "%s" % tmpfile] _log.debug(command) p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (stdout, stderr) = (p.stdout, p.stderr) _log.debug(stdout.read()) bbox_info = stderr.read() _log.info(bbox_info) bbox_found = re.search('%%HiResBoundingBox: .*', bbox_info) if bbox_found: bbox_info = bbox_found.group() else: raise RuntimeError('Ghostscript was not able to extract a bounding box.\ Here is the Ghostscript output:\n\n%s' % bbox_info) l, b, r, t = [float(i) for i in bbox_info.split()[-4:]] # this is a hack to deal with the fact that ghostscript does not return the # intended bbox, but a tight bbox. For now, we just center the ink in the # intended bbox. This is not ideal, users may intend the ink to not be # centered. if bbox is None: l, b, r, t = (l-1, b-1, r+1, t+1) else: x = (l+r)/2 y = (b+t)/2 dx = (bbox[2]-bbox[0])/2 dy = (bbox[3]-bbox[1])/2 l,b,r,t = (x-dx, y-dy, x+dx, y+dy) bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t)) hires_bbox_info = '%%%%HiResBoundingBox: %.6f %.6f %.6f %.6f' % (l, b, r, t) return '\n'.join([bbox_info, hires_bbox_info]) def pstoeps(tmpfile, bbox=None, rotated=False): """ Convert the postscript to encapsulated postscript. The bbox of the eps file will be replaced with the given *bbox* argument. If None, original bbox will be used. """ # if rotated==True, the output eps file need to be rotated if bbox: bbox_info, rotate = get_bbox_header(bbox, rotated=rotated) else: bbox_info, rotate = None, None epsfile = tmpfile + '.eps' with io.open(epsfile, 'wb') as epsh, io.open(tmpfile, 'rb') as tmph: write = epsh.write # Modify the header: for line in tmph: if line.startswith(b'%!PS'): write(b"%!PS-Adobe-3.0 EPSF-3.0\n") if bbox: write(bbox_info.encode('ascii') + b'\n') elif line.startswith(b'%%EndComments'): write(line) write(b'%%BeginProlog\n' b'save\n' b'countdictstack\n' b'mark\n' b'newpath\n' b'/showpage {} def\n' b'/setpagedevice {pop} def\n' b'%%EndProlog\n' b'%%Page 1 1\n') if rotate: write(rotate.encode('ascii') + b'\n') break elif bbox and line.startswith((b'%%Bound', b'%%HiResBound', b'%%DocumentMedia', b'%%Pages')): pass else: write(line) # Now rewrite the rest of the file, and modify the trailer. # This is done in a second loop such that the header of the embedded # eps file is not modified. for line in tmph: if line.startswith(b'%%EOF'): write(b'cleartomark\n' b'countdictstack\n' b'exch sub { end } repeat\n' b'restore\n' b'showpage\n' b'%%EOF\n') elif line.startswith(b'%%PageBoundingBox'): pass else: write(line) os.remove(tmpfile) shutil.move(epsfile, tmpfile) class FigureManagerPS(FigureManagerBase): pass # The following Python dictionary psDefs contains the entries for the # PostScript dictionary mpldict. This dictionary implements most of # the matplotlib primitives and some abbreviations. # # References: # http://www.adobe.com/products/postscript/pdfs/PLRM.pdf # http://www.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial/ # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/ # # The usage comments use the notation of the operator summary # in the PostScript Language reference manual. psDefs = [ # x y *m* - "/m { moveto } bind def", # x y *l* - "/l { lineto } bind def", # x y *r* - "/r { rlineto } bind def", # x1 y1 x2 y2 x y *c* - "/c { curveto } bind def", # *closepath* - "/cl { closepath } bind def", # w h x y *box* - """/box { m 1 index 0 r 0 exch r neg 0 r cl } bind def""", # w h x y *clipbox* - """/clipbox { box clip newpath } bind def""", ] @_Backend.export class _BackendPS(_Backend): FigureCanvas = FigureCanvasPS FigureManager = FigureManagerPS
62,098
34.323663
129
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_cairo.py
""" A Cairo backend for matplotlib ============================== :Author: Steve Chaplin and others This backend depends on `cairo <http://cairographics.org>`_, and either on cairocffi, or (Python 2 only) on pycairo. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import gzip import sys import warnings import numpy as np # cairocffi is more widely compatible than pycairo (in particular pgi only # works with cairocffi) so try it first. try: import cairocffi as cairo except ImportError: try: import cairo except ImportError: raise ImportError("cairo backend requires that cairocffi or pycairo " "is installed") else: HAS_CAIRO_CFFI = False else: HAS_CAIRO_CFFI = True if cairo.version_info < (1, 4, 0): raise ImportError("cairo {} is installed; " "cairo>=1.4.0 is required".format(cairo.version)) backend_version = cairo.version from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) from matplotlib.mathtext import MathTextParser from matplotlib.path import Path from matplotlib.transforms import Affine2D from matplotlib.font_manager import ttfFontProperty class ArrayWrapper: """Thin wrapper around numpy ndarray to expose the interface expected by cairocffi. Basically replicates the array.array interface. """ def __init__(self, myarray): self.__array = myarray self.__data = myarray.ctypes.data self.__size = len(myarray.flatten()) self.itemsize = myarray.itemsize def buffer_info(self): return (self.__data, self.__size) class RendererCairo(RendererBase): fontweights = { 100 : cairo.FONT_WEIGHT_NORMAL, 200 : cairo.FONT_WEIGHT_NORMAL, 300 : cairo.FONT_WEIGHT_NORMAL, 400 : cairo.FONT_WEIGHT_NORMAL, 500 : cairo.FONT_WEIGHT_NORMAL, 600 : cairo.FONT_WEIGHT_BOLD, 700 : cairo.FONT_WEIGHT_BOLD, 800 : cairo.FONT_WEIGHT_BOLD, 900 : cairo.FONT_WEIGHT_BOLD, 'ultralight' : cairo.FONT_WEIGHT_NORMAL, 'light' : cairo.FONT_WEIGHT_NORMAL, 'normal' : cairo.FONT_WEIGHT_NORMAL, 'medium' : cairo.FONT_WEIGHT_NORMAL, 'regular' : cairo.FONT_WEIGHT_NORMAL, 'semibold' : cairo.FONT_WEIGHT_BOLD, 'bold' : cairo.FONT_WEIGHT_BOLD, 'heavy' : cairo.FONT_WEIGHT_BOLD, 'ultrabold' : cairo.FONT_WEIGHT_BOLD, 'black' : cairo.FONT_WEIGHT_BOLD, } fontangles = { 'italic' : cairo.FONT_SLANT_ITALIC, 'normal' : cairo.FONT_SLANT_NORMAL, 'oblique' : cairo.FONT_SLANT_OBLIQUE, } def __init__(self, dpi): self.dpi = dpi self.gc = GraphicsContextCairo(renderer=self) self.text_ctx = cairo.Context( cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)) self.mathtext_parser = MathTextParser('Cairo') RendererBase.__init__(self) def set_ctx_from_surface(self, surface): self.gc.ctx = cairo.Context(surface) # Although it may appear natural to automatically call # `self.set_width_height(surface.get_width(), surface.get_height())` # here (instead of having the caller do so separately), this would fail # for PDF/PS/SVG surfaces, which have no way to report their extents. def set_width_height(self, width, height): self.width = width self.height = height def _fill_and_stroke(self, ctx, fill_c, alpha, alpha_overrides): if fill_c is not None: ctx.save() if len(fill_c) == 3 or alpha_overrides: ctx.set_source_rgba(fill_c[0], fill_c[1], fill_c[2], alpha) else: ctx.set_source_rgba(fill_c[0], fill_c[1], fill_c[2], fill_c[3]) ctx.fill_preserve() ctx.restore() ctx.stroke() @staticmethod def convert_path(ctx, path, transform, clip=None): for points, code in path.iter_segments(transform, clip=clip): if code == Path.MOVETO: ctx.move_to(*points) elif code == Path.CLOSEPOLY: ctx.close_path() elif code == Path.LINETO: ctx.line_to(*points) elif code == Path.CURVE3: ctx.curve_to(points[0], points[1], points[0], points[1], points[2], points[3]) elif code == Path.CURVE4: ctx.curve_to(*points) def draw_path(self, gc, path, transform, rgbFace=None): ctx = gc.ctx # We'll clip the path to the actual rendering extents # if the path isn't filled. if rgbFace is None and gc.get_hatch() is None: clip = ctx.clip_extents() else: clip = None transform = (transform + Affine2D().scale(1.0, -1.0).translate(0, self.height)) ctx.new_path() self.convert_path(ctx, path, transform, clip) self._fill_and_stroke( ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) def draw_markers(self, gc, marker_path, marker_trans, path, transform, rgbFace=None): ctx = gc.ctx ctx.new_path() # Create the path for the marker; it needs to be flipped here already! self.convert_path( ctx, marker_path, marker_trans + Affine2D().scale(1.0, -1.0)) marker_path = ctx.copy_path_flat() # Figure out whether the path has a fill x1, y1, x2, y2 = ctx.fill_extents() if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0: filled = False # No fill, just unset this (so we don't try to fill it later on) rgbFace = None else: filled = True transform = (transform + Affine2D().scale(1.0, -1.0).translate(0, self.height)) ctx.new_path() for i, (vertices, codes) in enumerate( path.iter_segments(transform, simplify=False)): if len(vertices): x, y = vertices[-2:] ctx.save() # Translate and apply path ctx.translate(x, y) ctx.append_path(marker_path) ctx.restore() # Slower code path if there is a fill; we need to draw # the fill and stroke for each marker at the same time. # Also flush out the drawing every once in a while to # prevent the paths from getting way too long. if filled or i % 1000 == 0: self._fill_and_stroke( ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) # Fast path, if there is no fill, draw everything in one step if not filled: self._fill_and_stroke( ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) def draw_image(self, gc, x, y, im): # bbox - not currently used if sys.byteorder == 'little': im = im[:, :, (2, 1, 0, 3)] else: im = im[:, :, (3, 0, 1, 2)] if HAS_CAIRO_CFFI: # cairocffi tries to use the buffer_info from array.array # that we replicate in ArrayWrapper and alternatively falls back # on ctypes to get a pointer to the numpy array. This works # correctly on a numpy array in python3 but not 2.7. We replicate # the array.array functionality here to get cross version support. imbuffer = ArrayWrapper(im.flatten()) else: # pycairo uses PyObject_AsWriteBuffer to get a pointer to the # numpy array; this works correctly on a regular numpy array but # not on a py2 memoryview. imbuffer = im.flatten() surface = cairo.ImageSurface.create_for_data( imbuffer, cairo.FORMAT_ARGB32, im.shape[1], im.shape[0], im.shape[1]*4) ctx = gc.ctx y = self.height - y - im.shape[0] ctx.save() ctx.set_source_surface(surface, float(x), float(y)) if gc.get_alpha() != 1.0: ctx.paint_with_alpha(gc.get_alpha()) else: ctx.paint() ctx.restore() def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): # Note: x,y are device/display coords, not user-coords, unlike other # draw_* methods if ismath: self._draw_mathtext(gc, x, y, s, prop, angle) else: ctx = gc.ctx ctx.new_path() ctx.move_to(x, y) ctx.select_font_face(prop.get_name(), self.fontangles[prop.get_style()], self.fontweights[prop.get_weight()]) size = prop.get_size_in_points() * self.dpi / 72.0 ctx.save() if angle: ctx.rotate(np.deg2rad(-angle)) ctx.set_font_size(size) if HAS_CAIRO_CFFI: if not isinstance(s, six.text_type): s = six.text_type(s) else: if six.PY2 and isinstance(s, six.text_type): s = s.encode("utf-8") ctx.show_text(s) ctx.restore() def _draw_mathtext(self, gc, x, y, s, prop, angle): ctx = gc.ctx width, height, descent, glyphs, rects = self.mathtext_parser.parse( s, self.dpi, prop) ctx.save() ctx.translate(x, y) if angle: ctx.rotate(np.deg2rad(-angle)) for font, fontsize, s, ox, oy in glyphs: ctx.new_path() ctx.move_to(ox, oy) fontProp = ttfFontProperty(font) ctx.save() ctx.select_font_face(fontProp.name, self.fontangles[fontProp.style], self.fontweights[fontProp.weight]) size = fontsize * self.dpi / 72.0 ctx.set_font_size(size) if not six.PY3 and isinstance(s, six.text_type): s = s.encode("utf-8") ctx.show_text(s) ctx.restore() for ox, oy, w, h in rects: ctx.new_path() ctx.rectangle(ox, oy, w, h) ctx.set_source_rgb(0, 0, 0) ctx.fill_preserve() ctx.restore() def get_canvas_width_height(self): return self.width, self.height def get_text_width_height_descent(self, s, prop, ismath): if ismath: width, height, descent, fonts, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) return width, height, descent ctx = self.text_ctx ctx.save() ctx.select_font_face(prop.get_name(), self.fontangles[prop.get_style()], self.fontweights[prop.get_weight()]) # Cairo (says it) uses 1/96 inch user space units, ref: cairo_gstate.c # but if /96.0 is used the font is too small size = prop.get_size_in_points() * self.dpi / 72 # problem - scale remembers last setting and font can become # enormous causing program to crash # save/restore prevents the problem ctx.set_font_size(size) y_bearing, w, h = ctx.text_extents(s)[1:4] ctx.restore() return w, h, h + y_bearing def new_gc(self): self.gc.ctx.save() self.gc._alpha = 1 self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA return self.gc def points_to_pixels(self, points): return points / 72 * self.dpi class GraphicsContextCairo(GraphicsContextBase): _joind = { 'bevel' : cairo.LINE_JOIN_BEVEL, 'miter' : cairo.LINE_JOIN_MITER, 'round' : cairo.LINE_JOIN_ROUND, } _capd = { 'butt' : cairo.LINE_CAP_BUTT, 'projecting' : cairo.LINE_CAP_SQUARE, 'round' : cairo.LINE_CAP_ROUND, } def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer def restore(self): self.ctx.restore() def set_alpha(self, alpha): GraphicsContextBase.set_alpha(self, alpha) _alpha = self.get_alpha() rgb = self._rgb if self.get_forced_alpha(): self.ctx.set_source_rgba(rgb[0], rgb[1], rgb[2], _alpha) else: self.ctx.set_source_rgba(rgb[0], rgb[1], rgb[2], rgb[3]) # def set_antialiased(self, b): # cairo has many antialiasing modes, we need to pick one for True and # one for False. def set_capstyle(self, cs): if cs in ('butt', 'round', 'projecting'): self._capstyle = cs self.ctx.set_line_cap(self._capd[cs]) else: raise ValueError('Unrecognized cap style. Found %s' % cs) def set_clip_rectangle(self, rectangle): if not rectangle: return x, y, w, h = np.round(rectangle.bounds) ctx = self.ctx ctx.new_path() ctx.rectangle(x, self.renderer.height - h - y, w, h) ctx.clip() def set_clip_path(self, path): if not path: return tpath, affine = path.get_transformed_path_and_affine() ctx = self.ctx ctx.new_path() affine = (affine + Affine2D().scale(1, -1).translate(0, self.renderer.height)) RendererCairo.convert_path(ctx, tpath, affine) ctx.clip() def set_dashes(self, offset, dashes): self._dashes = offset, dashes if dashes == None: self.ctx.set_dash([], 0) # switch dashes off else: self.ctx.set_dash( list(self.renderer.points_to_pixels(np.asarray(dashes))), offset) def set_foreground(self, fg, isRGBA=None): GraphicsContextBase.set_foreground(self, fg, isRGBA) if len(self._rgb) == 3: self.ctx.set_source_rgb(*self._rgb) else: self.ctx.set_source_rgba(*self._rgb) def get_rgb(self): return self.ctx.get_source().get_rgba()[:3] def set_joinstyle(self, js): if js in ('miter', 'round', 'bevel'): self._joinstyle = js self.ctx.set_line_join(self._joind[js]) else: raise ValueError('Unrecognized join style. Found %s' % js) def set_linewidth(self, w): self._linewidth = float(w) self.ctx.set_line_width(self.renderer.points_to_pixels(w)) class FigureCanvasCairo(FigureCanvasBase): supports_blit = False def print_png(self, fobj, *args, **kwargs): width, height = self.get_width_height() renderer = RendererCairo(self.figure.dpi) renderer.set_width_height(width, height) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) renderer.set_ctx_from_surface(surface) self.figure.draw(renderer) surface.write_to_png(fobj) def print_pdf(self, fobj, *args, **kwargs): return self._save(fobj, 'pdf', *args, **kwargs) def print_ps(self, fobj, *args, **kwargs): return self._save(fobj, 'ps', *args, **kwargs) def print_svg(self, fobj, *args, **kwargs): return self._save(fobj, 'svg', *args, **kwargs) def print_svgz(self, fobj, *args, **kwargs): return self._save(fobj, 'svgz', *args, **kwargs) def _save(self, fo, fmt, **kwargs): # save PDF/PS/SVG orientation = kwargs.get('orientation', 'portrait') dpi = 72 self.figure.dpi = dpi w_in, h_in = self.figure.get_size_inches() width_in_points, height_in_points = w_in * dpi, h_in * dpi if orientation == 'landscape': width_in_points, height_in_points = ( height_in_points, width_in_points) if fmt == 'ps': if not hasattr(cairo, 'PSSurface'): raise RuntimeError('cairo has not been compiled with PS ' 'support enabled') surface = cairo.PSSurface(fo, width_in_points, height_in_points) elif fmt == 'pdf': if not hasattr(cairo, 'PDFSurface'): raise RuntimeError('cairo has not been compiled with PDF ' 'support enabled') surface = cairo.PDFSurface(fo, width_in_points, height_in_points) elif fmt in ('svg', 'svgz'): if not hasattr(cairo, 'SVGSurface'): raise RuntimeError('cairo has not been compiled with SVG ' 'support enabled') if fmt == 'svgz': if isinstance(fo, six.string_types): fo = gzip.GzipFile(fo, 'wb') else: fo = gzip.GzipFile(None, 'wb', fileobj=fo) surface = cairo.SVGSurface(fo, width_in_points, height_in_points) else: warnings.warn("unknown format: %s" % fmt) return # surface.set_dpi() can be used renderer = RendererCairo(self.figure.dpi) renderer.set_width_height(width_in_points, height_in_points) renderer.set_ctx_from_surface(surface) ctx = renderer.gc.ctx if orientation == 'landscape': ctx.rotate(np.pi / 2) ctx.translate(0, -height_in_points) # Perhaps add an '%%Orientation: Landscape' comment? self.figure.draw(renderer) ctx.show_page() surface.finish() if fmt == 'svgz': fo.close() @_Backend.export class _BackendCairo(_Backend): FigureCanvas = FigureCanvasCairo FigureManager = FigureManagerBase
18,010
33.570058
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_gtkagg.py
""" Render to gtk from agg """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import matplotlib from matplotlib.cbook import warn_deprecated from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.backends.backend_gtk import ( gtk, _BackendGTK, FigureCanvasGTK, FigureManagerGTK, NavigationToolbar2GTK, backend_version, error_msg_gtk, PIXELS_PER_INCH) from matplotlib.backends._gtkagg import agg_to_gtk_drawable class NavigationToolbar2GTKAgg(NavigationToolbar2GTK): def _get_canvas(self, fig): return FigureCanvasGTKAgg(fig) class FigureManagerGTKAgg(FigureManagerGTK): def _get_toolbar(self, canvas): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2GTKAgg (canvas, self.window) else: toolbar = None return toolbar class FigureCanvasGTKAgg(FigureCanvasGTK, FigureCanvasAgg): filetypes = FigureCanvasGTK.filetypes.copy() filetypes.update(FigureCanvasAgg.filetypes) def __init__(self, *args, **kwargs): warn_deprecated('2.2', message=('The GTKAgg backend is deprecated. It is ' 'untested and will be removed in Matplotlib ' '3.0. Use the GTK3Agg backend instead. See ' 'Matplotlib usage FAQ for more info on ' 'backends.'), alternative='GTK3Agg') super(FigureCanvasGTKAgg, self).__init__(*args, **kwargs) def configure_event(self, widget, event=None): if widget.window is None: return try: del self.renderer except AttributeError: pass w,h = widget.window.get_size() if w==1 or h==1: return # empty fig # compute desired figure size in inches dpival = self.figure.dpi winch = w/dpival hinch = h/dpival self.figure.set_size_inches(winch, hinch, forward=False) self._need_redraw = True self.resize_event() return True def _render_figure(self, pixmap, width, height): FigureCanvasAgg.draw(self) buf = self.buffer_rgba() ren = self.get_renderer() w = int(ren.width) h = int(ren.height) pixbuf = gtk.gdk.pixbuf_new_from_data( buf, gtk.gdk.COLORSPACE_RGB, True, 8, w, h, w*4) pixmap.draw_pixbuf(pixmap.new_gc(), pixbuf, 0, 0, 0, 0, w, h, gtk.gdk.RGB_DITHER_NONE, 0, 0) def blit(self, bbox=None): agg_to_gtk_drawable(self._pixmap, self.renderer._renderer, bbox) x, y, w, h = self.allocation self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, 0, 0, 0, 0, w, h) def print_png(self, filename, *args, **kwargs): # Do this so we can save the resolution of figure in the PNG file agg = self.switch_backends(FigureCanvasAgg) return agg.print_png(filename, *args, **kwargs) @_BackendGTK.export class _BackendGTKAgg(_BackendGTK): FigureCanvas = FigureCanvasGTKAgg FigureManager = FigureManagerGTKAgg
3,353
33.57732
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/wx_compat.py
#!/usr/bin/env python """ A wx API adapter to hide differences between wxPython classic and phoenix. It is assumed that the user code is selecting what version it wants to use, here we just ensure that it meets the minimum required by matplotlib. For an example see embedding_in_wx2.py """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from distutils.version import StrictVersion, LooseVersion missingwx = "Matplotlib backend_wx and backend_wxagg require wxPython>=2.9" try: import wx backend_version = wx.VERSION_STRING is_phoenix = 'phoenix' in wx.PlatformInfo except ImportError: raise ImportError(missingwx) try: wx_version = StrictVersion(wx.VERSION_STRING) except ValueError: wx_version = LooseVersion(wx.VERSION_STRING) # Ensure we have the correct version imported if wx_version < str("2.9"): raise ImportError(missingwx) if is_phoenix: # define all the wxPython phoenix stuff # font styles, families and weight fontweights = { 100: wx.FONTWEIGHT_LIGHT, 200: wx.FONTWEIGHT_LIGHT, 300: wx.FONTWEIGHT_LIGHT, 400: wx.FONTWEIGHT_NORMAL, 500: wx.FONTWEIGHT_NORMAL, 600: wx.FONTWEIGHT_NORMAL, 700: wx.FONTWEIGHT_BOLD, 800: wx.FONTWEIGHT_BOLD, 900: wx.FONTWEIGHT_BOLD, 'ultralight': wx.FONTWEIGHT_LIGHT, 'light': wx.FONTWEIGHT_LIGHT, 'normal': wx.FONTWEIGHT_NORMAL, 'medium': wx.FONTWEIGHT_NORMAL, 'semibold': wx.FONTWEIGHT_NORMAL, 'bold': wx.FONTWEIGHT_BOLD, 'heavy': wx.FONTWEIGHT_BOLD, 'ultrabold': wx.FONTWEIGHT_BOLD, 'black': wx.FONTWEIGHT_BOLD } fontangles = { 'italic': wx.FONTSTYLE_ITALIC, 'normal': wx.FONTSTYLE_NORMAL, 'oblique': wx.FONTSTYLE_SLANT} # wxPython allows for portable font styles, choosing them appropriately # for the target platform. Map some standard font names to the portable # styles # QUESTION: Is it be wise to agree standard fontnames across all backends? fontnames = {'Sans': wx.FONTFAMILY_SWISS, 'Roman': wx.FONTFAMILY_ROMAN, 'Script': wx.FONTFAMILY_SCRIPT, 'Decorative': wx.FONTFAMILY_DECORATIVE, 'Modern': wx.FONTFAMILY_MODERN, 'Courier': wx.FONTFAMILY_MODERN, 'courier': wx.FONTFAMILY_MODERN} dashd_wx = {'solid': wx.PENSTYLE_SOLID, 'dashed': wx.PENSTYLE_SHORT_DASH, 'dashdot': wx.PENSTYLE_DOT_DASH, 'dotted': wx.PENSTYLE_DOT} # functions changes BitmapFromBuffer = wx.Bitmap.FromBufferRGBA EmptyBitmap = wx.Bitmap EmptyImage = wx.Image Cursor = wx.Cursor EventLoop = wx.GUIEventLoop NamedColour = wx.Colour StockCursor = wx.Cursor else: # define all the wxPython classic stuff # font styles, families and weight fontweights = { 100: wx.LIGHT, 200: wx.LIGHT, 300: wx.LIGHT, 400: wx.NORMAL, 500: wx.NORMAL, 600: wx.NORMAL, 700: wx.BOLD, 800: wx.BOLD, 900: wx.BOLD, 'ultralight': wx.LIGHT, 'light': wx.LIGHT, 'normal': wx.NORMAL, 'medium': wx.NORMAL, 'semibold': wx.NORMAL, 'bold': wx.BOLD, 'heavy': wx.BOLD, 'ultrabold': wx.BOLD, 'black': wx.BOLD } fontangles = { 'italic': wx.ITALIC, 'normal': wx.NORMAL, 'oblique': wx.SLANT} # wxPython allows for portable font styles, choosing them appropriately # for the target platform. Map some standard font names to the portable # styles # QUESTION: Is it be wise to agree standard fontnames across all backends? fontnames = {'Sans': wx.SWISS, 'Roman': wx.ROMAN, 'Script': wx.SCRIPT, 'Decorative': wx.DECORATIVE, 'Modern': wx.MODERN, 'Courier': wx.MODERN, 'courier': wx.MODERN} dashd_wx = {'solid': wx.SOLID, 'dashed': wx.SHORT_DASH, 'dashdot': wx.DOT_DASH, 'dotted': wx.DOT} # functions changes BitmapFromBuffer = wx.BitmapFromBufferRGBA EmptyBitmap = wx.EmptyBitmap EmptyImage = wx.EmptyImage Cursor = wx.StockCursor EventLoop = wx.EventLoop NamedColour = wx.NamedColour StockCursor = wx.StockCursor # wxPython Classic's DoAddTool has become AddTool in Phoenix. Otherwise # they are the same, except for early betas and prerelease builds of # Phoenix. This function provides a shim that does the RightThing based on # which wxPython is in use. def _AddTool(parent, wx_ids, text, bmp, tooltip_text): if text in ['Pan', 'Zoom']: kind = wx.ITEM_CHECK else: kind = wx.ITEM_NORMAL if is_phoenix: add_tool = parent.AddTool else: add_tool = parent.DoAddTool if not is_phoenix or wx_version >= str("4.0.0b2"): # NOTE: when support for Phoenix prior to 4.0.0b2 is dropped then # all that is needed is this clause, and the if and else clause can # be removed. kwargs = dict(label=text, bitmap=bmp, bmpDisabled=wx.NullBitmap, shortHelp=text, longHelp=tooltip_text, kind=kind) else: kwargs = dict(label=text, bitmap=bmp, bmpDisabled=wx.NullBitmap, shortHelpString=text, longHelpString=tooltip_text, kind=kind) return add_tool(wx_ids[text], **kwargs)
5,751
31.134078
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_qt5agg.py
""" Render to qt from agg """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import ctypes from matplotlib import cbook from matplotlib.transforms import Bbox from .backend_agg import FigureCanvasAgg from .backend_qt5 import ( QtCore, QtGui, QtWidgets, _BackendQT5, FigureCanvasQT, FigureManagerQT, NavigationToolbar2QT, backend_version) from .qt_compat import QT_API class FigureCanvasQTAgg(FigureCanvasAgg, FigureCanvasQT): def __init__(self, figure): super(FigureCanvasQTAgg, self).__init__(figure=figure) self._bbox_queue = [] @property @cbook.deprecated("2.1") def blitbox(self): return self._bbox_queue def paintEvent(self, e): """Copy the image from the Agg canvas to the qt.drawable. In Qt, all drawing should be done inside of here when a widget is shown onscreen. """ if self._update_dpi(): # The dpi update triggered its own paintEvent. return self._draw_idle() # Only does something if a draw is pending. # if the canvas does not have a renderer, then give up and wait for # FigureCanvasAgg.draw(self) to be called if not hasattr(self, 'renderer'): return painter = QtGui.QPainter(self) if self._bbox_queue: bbox_queue = self._bbox_queue else: painter.eraseRect(self.rect()) bbox_queue = [ Bbox([[0, 0], [self.renderer.width, self.renderer.height]])] self._bbox_queue = [] for bbox in bbox_queue: l, b, r, t = map(int, bbox.extents) w = r - l h = t - b reg = self.copy_from_bbox(bbox) buf = reg.to_string_argb() qimage = QtGui.QImage(buf, w, h, QtGui.QImage.Format_ARGB32) # Adjust the buf reference count to work around a memory leak bug # in QImage under PySide on Python 3. if QT_API == 'PySide' and six.PY3: ctypes.c_long.from_address(id(buf)).value = 1 if hasattr(qimage, 'setDevicePixelRatio'): # Not available on Qt4 or some older Qt5. qimage.setDevicePixelRatio(self._dpi_ratio) origin = QtCore.QPoint(l, self.renderer.height - t) painter.drawImage(origin / self._dpi_ratio, qimage) self._draw_rect_callback(painter) painter.end() def blit(self, bbox=None): """Blit the region in bbox. """ # If bbox is None, blit the entire canvas. Otherwise # blit only the area defined by the bbox. if bbox is None and self.figure: bbox = self.figure.bbox self._bbox_queue.append(bbox) # repaint uses logical pixels, not physical pixels like the renderer. l, b, w, h = [pt / self._dpi_ratio for pt in bbox.bounds] t = b + h self.repaint(l, self.renderer.height / self._dpi_ratio - t, w, h) def print_figure(self, *args, **kwargs): super(FigureCanvasQTAgg, self).print_figure(*args, **kwargs) self.draw() @cbook.deprecated("2.2") class FigureCanvasQTAggBase(FigureCanvasQTAgg): pass @_BackendQT5.export class _BackendQT5Agg(_BackendQT5): FigureCanvas = FigureCanvasQTAgg
3,357
30.679245
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_wx.py
""" A wxPython backend for matplotlib, based (very heavily) on backend_template.py and backend_gtk.py Author: Jeremy O'Donoghue ([email protected]) Derived from original copyright work by John Hunter ([email protected]) Copyright (C) Jeremy O'Donoghue & John Hunter, 2003-4 License: This work is licensed under a PSF compatible license. A copy should be included with this source code. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import xrange import six import sys import os import os.path import math import weakref import warnings import matplotlib from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, NavigationToolbar2, RendererBase, TimerBase, cursors) from matplotlib.backend_bases import _has_pil from matplotlib._pylab_helpers import Gcf from matplotlib.cbook import is_writable_file_like, warn_deprecated from matplotlib.figure import Figure from matplotlib.path import Path from matplotlib.transforms import Affine2D from matplotlib.widgets import SubplotTool from matplotlib import cbook, rcParams, backend_tools from . import wx_compat as wxc import wx # Debugging settings here... # Debug level set here. If the debug level is less than 5, information # messages (progressively more info for lower value) are printed. In addition, # traceback is performed, and pdb activated, for all uncaught exceptions in # this case _DEBUG = 5 if _DEBUG < 5: import traceback import pdb _DEBUG_lvls = {1: 'Low ', 2: 'Med ', 3: 'High', 4: 'Error'} def DEBUG_MSG(string, lvl=3, o=None): if lvl >= _DEBUG: cls = o.__class__ # Jeremy, often times the commented line won't print but the # one below does. I think WX is redefining stderr, damned # beast # print("%s- %s in %s" % (_DEBUG_lvls[lvl], string, cls), # file=sys.stderr) print("%s- %s in %s" % (_DEBUG_lvls[lvl], string, cls)) def debug_on_error(type, value, tb): """Code due to Thomas Heller - published in Python Cookbook (O'Reilley)""" traceback.print_exception(type, value, tb) print() pdb.pm() # jdh uncomment class fake_stderr(object): """ Wx does strange things with stderr, as it makes the assumption that there is probably no console. This redirects stderr to the console, since we know that there is one! """ def write(self, msg): print("Stderr: %s\n\r" % msg) # the True dots per inch on the screen; should be display dependent # see # http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 # for some info about screen dpi PIXELS_PER_INCH = 75 # Delay time for idle checks IDLE_DELAY = 5 def error_msg_wx(msg, parent=None): """ Signal an error condition -- in a GUI, popup a error dialog """ dialog = wx.MessageDialog(parent=parent, message=msg, caption='Matplotlib backend_wx error', style=wx.OK | wx.CENTRE) dialog.ShowModal() dialog.Destroy() return None def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines.""" if not isinstance(msg, six.string_types): msg = '\n'.join(map(str, msg)) return msg class TimerWx(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses WxTimer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def __init__(self, parent, *args, **kwargs): TimerBase.__init__(self, *args, **kwargs) # Create a new timer and connect the timer event to our handler. # For WX, the events have to use a widget for binding. self.parent = parent self._timer = wx.Timer(self.parent, wx.NewId()) self.parent.Bind(wx.EVT_TIMER, self._on_timer, self._timer) # Unbinding causes Wx to stop for some reason. Disabling for now. # def __del__(self): # TimerBase.__del__(self) # self.parent.Bind(wx.EVT_TIMER, None, self._timer) def _timer_start(self): self._timer.Start(self._interval, self._single) def _timer_stop(self): self._timer.Stop() def _timer_set_interval(self): self._timer_start() def _timer_set_single_shot(self): self._timer.Start() def _on_timer(self, *args): TimerBase._on_timer(self) class RendererWx(RendererBase): """ The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles. It acts as the 'renderer' instance used by many classes in the hierarchy. """ # In wxPython, drawing is performed on a wxDC instance, which will # generally be mapped to the client aread of the window displaying # the plot. Under wxPython, the wxDC instance has a wx.Pen which # describes the colour and weight of any lines drawn, and a wxBrush # which describes the fill colour of any closed polygon. fontweights = wxc.fontweights fontangles = wxc.fontangles # wxPython allows for portable font styles, choosing them appropriately # for the target platform. Map some standard font names to the portable # styles # QUESTION: Is it be wise to agree standard fontnames across all backends? fontnames = wxc.fontnames def __init__(self, bitmap, dpi): """ Initialise a wxWindows renderer instance. """ warn_deprecated('2.0', message="The WX backend is " "deprecated. It's untested " "and will be removed in Matplotlib 3.0. " "Use the WXAgg backend instead. " "See Matplotlib usage FAQ for more info on backends.", alternative='WXAgg') RendererBase.__init__(self) DEBUG_MSG("__init__()", 1, self) self.width = bitmap.GetWidth() self.height = bitmap.GetHeight() self.bitmap = bitmap self.fontd = {} self.dpi = dpi self.gc = None def flipy(self): return True def offset_text_height(self): return True def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop """ # return 1, 1 if ismath: s = self.strip_math(s) if self.gc is None: gc = self.new_gc() else: gc = self.gc gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) gfx_ctx.SetFont(font, wx.BLACK) w, h, descent, leading = gfx_ctx.GetFullTextExtent(s) return w, h, descent def get_canvas_width_height(self): 'return the canvas width and height in display coords' return self.width, self.height def handle_clip_rectangle(self, gc): new_bounds = gc.get_clip_rectangle() if new_bounds is not None: new_bounds = new_bounds.bounds gfx_ctx = gc.gfx_ctx if gfx_ctx._lastcliprect != new_bounds: gfx_ctx._lastcliprect = new_bounds if new_bounds is None: gfx_ctx.ResetClip() else: gfx_ctx.Clip(new_bounds[0], self.height - new_bounds[1] - new_bounds[3], new_bounds[2], new_bounds[3]) @staticmethod def convert_path(gfx_ctx, path, transform): wxpath = gfx_ctx.CreatePath() for points, code in path.iter_segments(transform): if code == Path.MOVETO: wxpath.MoveToPoint(*points) elif code == Path.LINETO: wxpath.AddLineToPoint(*points) elif code == Path.CURVE3: wxpath.AddQuadCurveToPoint(*points) elif code == Path.CURVE4: wxpath.AddCurveToPoint(*points) elif code == Path.CLOSEPOLY: wxpath.CloseSubpath() return wxpath def draw_path(self, gc, path, transform, rgbFace=None): gc.select() self.handle_clip_rectangle(gc) gfx_ctx = gc.gfx_ctx transform = transform + \ Affine2D().scale(1.0, -1.0).translate(0.0, self.height) wxpath = self.convert_path(gfx_ctx, path, transform) if rgbFace is not None: gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace))) gfx_ctx.DrawPath(wxpath) else: gfx_ctx.StrokePath(wxpath) gc.unselect() def draw_image(self, gc, x, y, im): bbox = gc.get_clip_rectangle() if bbox is not None: l, b, w, h = bbox.bounds else: l = 0 b = 0 w = self.width h = self.height rows, cols = im.shape[:2] bitmap = wxc.BitmapFromBuffer(cols, rows, im.tostring()) gc = self.get_gc() gc.select() gc.gfx_ctx.DrawBitmap(bitmap, int(l), int(self.height - b), int(w), int(-h)) gc.unselect() def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): if ismath: s = self.strip_math(s) DEBUG_MSG("draw_text()", 1, self) gc.select() self.handle_clip_rectangle(gc) gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) color = gc.get_wxcolour(gc.get_rgb()) gfx_ctx.SetFont(font, color) w, h, d = self.get_text_width_height_descent(s, prop, ismath) x = int(x) y = int(y - h) if angle == 0.0: gfx_ctx.DrawText(s, x, y) else: rads = math.radians(angle) xo = h * math.sin(rads) yo = h * math.cos(rads) gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads) gc.unselect() def new_gc(self): """ Return an instance of a GraphicsContextWx, and sets the current gc copy """ DEBUG_MSG('new_gc()', 2, self) self.gc = GraphicsContextWx(self.bitmap, self) self.gc.select() self.gc.unselect() return self.gc def get_gc(self): """ Fetch the locally cached gc. """ # This is a dirty hack to allow anything with access to a renderer to # access the current graphics context assert self.gc is not None, "gc must be defined" return self.gc def get_wx_font(self, s, prop): """ Return a wx font. Cache instances in a font dictionary for efficiency """ DEBUG_MSG("get_wx_font()", 1, self) key = hash(prop) fontprop = prop fontname = fontprop.get_name() font = self.fontd.get(key) if font is not None: return font # Allow use of platform independent and dependent font names wxFontname = self.fontnames.get(fontname, wx.ROMAN) wxFacename = '' # Empty => wxPython chooses based on wx_fontname # Font colour is determined by the active wx.Pen # TODO: It may be wise to cache font information size = self.points_to_pixels(fontprop.get_size_in_points()) font = wx.Font(int(size + 0.5), # Size wxFontname, # 'Generic' name self.fontangles[fontprop.get_style()], # Angle self.fontweights[fontprop.get_weight()], # Weight False, # Underline wxFacename) # Platform font name # cache the font and gc and return it self.fontd[key] = font return font def points_to_pixels(self, points): """ convert point measures to pixes using dpi and the pixels per inch of the display """ return points * (PIXELS_PER_INCH / 72.0 * self.dpi / 72.0) class GraphicsContextWx(GraphicsContextBase): """ The graphics context provides the color, line styles, etc... This class stores a reference to a wxMemoryDC, and a wxGraphicsContext that draws to it. Creating a wxGraphicsContext seems to be fairly heavy, so these objects are cached based on the bitmap object that is passed in. The base GraphicsContext stores colors as a RGB tuple on the unit interval, e.g., (0.5, 0.0, 1.0). wxPython uses an int interval, but since wxPython colour management is rather simple, I have not chosen to implement a separate colour manager class. """ _capd = {'butt': wx.CAP_BUTT, 'projecting': wx.CAP_PROJECTING, 'round': wx.CAP_ROUND} _joind = {'bevel': wx.JOIN_BEVEL, 'miter': wx.JOIN_MITER, 'round': wx.JOIN_ROUND} _cache = weakref.WeakKeyDictionary() def __init__(self, bitmap, renderer): GraphicsContextBase.__init__(self) # assert self.Ok(), "wxMemoryDC not OK to use" DEBUG_MSG("__init__()", 1, self) DEBUG_MSG("__init__() 2: %s" % bitmap, 1, self) dc, gfx_ctx = self._cache.get(bitmap, (None, None)) if dc is None: dc = wx.MemoryDC() dc.SelectObject(bitmap) gfx_ctx = wx.GraphicsContext.Create(dc) gfx_ctx._lastcliprect = None self._cache[bitmap] = dc, gfx_ctx self.bitmap = bitmap self.dc = dc self.gfx_ctx = gfx_ctx self._pen = wx.Pen('BLACK', 1, wx.SOLID) gfx_ctx.SetPen(self._pen) self._style = wx.SOLID self.renderer = renderer def select(self): """ Select the current bitmap into this wxDC instance """ if sys.platform == 'win32': self.dc.SelectObject(self.bitmap) self.IsSelected = True def unselect(self): """ Select a Null bitmasp into this wxDC instance """ if sys.platform == 'win32': self.dc.SelectObject(wx.NullBitmap) self.IsSelected = False def set_foreground(self, fg, isRGBA=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ # Implementation note: wxPython has a separate concept of pen and # brush - the brush fills any outline trace left by the pen. # Here we set both to the same colour - if a figure is not to be # filled, the renderer will set the brush to be transparent # Same goes for text foreground... DEBUG_MSG("set_foreground()", 1, self) self.select() GraphicsContextBase.set_foreground(self, fg, isRGBA) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_linewidth(self, w): """ Set the line width. """ w = float(w) DEBUG_MSG("set_linewidth()", 1, self) self.select() if w > 0 and w < 1: w = 1 GraphicsContextBase.set_linewidth(self, w) lw = int(self.renderer.points_to_pixels(self._linewidth)) if lw == 0: lw = 1 self._pen.SetWidth(lw) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ DEBUG_MSG("set_capstyle()", 1, self) self.select() GraphicsContextBase.set_capstyle(self, cs) self._pen.SetCap(GraphicsContextWx._capd[self._capstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ DEBUG_MSG("set_joinstyle()", 1, self) self.select() GraphicsContextBase.set_joinstyle(self, js) self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() @cbook.deprecated("2.1") def set_linestyle(self, ls): """ Set the line style to be one of """ DEBUG_MSG("set_linestyle()", 1, self) self.select() GraphicsContextBase.set_linestyle(self, ls) try: self._style = wxc.dashd_wx[ls] except KeyError: self._style = wx.LONG_DASH # Style not used elsewhere... # On MS Windows platform, only line width of 1 allowed for dash lines if wx.Platform == '__WXMSW__': self.set_linewidth(1) self._pen.SetStyle(self._style) self.gfx_ctx.SetPen(self._pen) self.unselect() def get_wxcolour(self, color): """return a wx.Colour from RGB format""" DEBUG_MSG("get_wx_color()", 1, self) if len(color) == 3: r, g, b = color r *= 255 g *= 255 b *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b)) else: r, g, b, a = color r *= 255 g *= 255 b *= 255 a *= 255 return wx.Colour( red=int(r), green=int(g), blue=int(b), alpha=int(a)) class _FigureCanvasWxBase(FigureCanvasBase, wx.Panel): """ The FigureCanvas contains the figure and does event handling. In the wxPython backend, it is derived from wxPanel, and (usually) lives inside a frame instantiated by a FigureManagerWx. The parent window probably implements a wx.Sizer to control the displayed control size - but we give a hint as to our preferred minimum size. """ keyvald = { wx.WXK_CONTROL: 'control', wx.WXK_SHIFT: 'shift', wx.WXK_ALT: 'alt', wx.WXK_LEFT: 'left', wx.WXK_UP: 'up', wx.WXK_RIGHT: 'right', wx.WXK_DOWN: 'down', wx.WXK_ESCAPE: 'escape', wx.WXK_F1: 'f1', wx.WXK_F2: 'f2', wx.WXK_F3: 'f3', wx.WXK_F4: 'f4', wx.WXK_F5: 'f5', wx.WXK_F6: 'f6', wx.WXK_F7: 'f7', wx.WXK_F8: 'f8', wx.WXK_F9: 'f9', wx.WXK_F10: 'f10', wx.WXK_F11: 'f11', wx.WXK_F12: 'f12', wx.WXK_SCROLL: 'scroll_lock', wx.WXK_PAUSE: 'break', wx.WXK_BACK: 'backspace', wx.WXK_RETURN: 'enter', wx.WXK_INSERT: 'insert', wx.WXK_DELETE: 'delete', wx.WXK_HOME: 'home', wx.WXK_END: 'end', wx.WXK_PAGEUP: 'pageup', wx.WXK_PAGEDOWN: 'pagedown', wx.WXK_NUMPAD0: '0', wx.WXK_NUMPAD1: '1', wx.WXK_NUMPAD2: '2', wx.WXK_NUMPAD3: '3', wx.WXK_NUMPAD4: '4', wx.WXK_NUMPAD5: '5', wx.WXK_NUMPAD6: '6', wx.WXK_NUMPAD7: '7', wx.WXK_NUMPAD8: '8', wx.WXK_NUMPAD9: '9', wx.WXK_NUMPAD_ADD: '+', wx.WXK_NUMPAD_SUBTRACT: '-', wx.WXK_NUMPAD_MULTIPLY: '*', wx.WXK_NUMPAD_DIVIDE: '/', wx.WXK_NUMPAD_DECIMAL: 'dec', wx.WXK_NUMPAD_ENTER: 'enter', wx.WXK_NUMPAD_UP: 'up', wx.WXK_NUMPAD_RIGHT: 'right', wx.WXK_NUMPAD_DOWN: 'down', wx.WXK_NUMPAD_LEFT: 'left', wx.WXK_NUMPAD_PAGEUP: 'pageup', wx.WXK_NUMPAD_PAGEDOWN: 'pagedown', wx.WXK_NUMPAD_HOME: 'home', wx.WXK_NUMPAD_END: 'end', wx.WXK_NUMPAD_INSERT: 'insert', wx.WXK_NUMPAD_DELETE: 'delete', } def __init__(self, parent, id, figure): """ Initialise a FigureWx instance. - Initialise the FigureCanvasBase and wxPanel parents. - Set event handlers for: EVT_SIZE (Resize event) EVT_PAINT (Paint event) """ FigureCanvasBase.__init__(self, figure) # Set preferred window size hint - helps the sizer (if one is # connected) l, b, w, h = figure.bbox.bounds w = int(math.ceil(w)) h = int(math.ceil(h)) wx.Panel.__init__(self, parent, id, size=wx.Size(w, h)) def do_nothing(*args, **kwargs): warnings.warn( "could not find a setinitialsize function for backend_wx; " "please report your wxpython version=%s " "to the matplotlib developers list" % wxc.backend_version) pass # try to find the set size func across wx versions try: getattr(self, 'SetInitialSize') except AttributeError: self.SetInitialSize = getattr(self, 'SetBestFittingSize', do_nothing) if not hasattr(self, 'IsShownOnScreen'): self.IsShownOnScreen = getattr(self, 'IsVisible', lambda *args: True) # Create the drawing bitmap self.bitmap = wxc.EmptyBitmap(w, h) DEBUG_MSG("__init__() - bitmap w:%d h:%d" % (w, h), 2, self) # TODO: Add support for 'point' inspection and plot navigation. self._isDrawn = False self.Bind(wx.EVT_SIZE, self._onSize) self.Bind(wx.EVT_PAINT, self._onPaint) self.Bind(wx.EVT_KEY_DOWN, self._onKeyDown) self.Bind(wx.EVT_KEY_UP, self._onKeyUp) self.Bind(wx.EVT_RIGHT_DOWN, self._onRightButtonDown) self.Bind(wx.EVT_RIGHT_DCLICK, self._onRightButtonDClick) self.Bind(wx.EVT_RIGHT_UP, self._onRightButtonUp) self.Bind(wx.EVT_MOUSEWHEEL, self._onMouseWheel) self.Bind(wx.EVT_LEFT_DOWN, self._onLeftButtonDown) self.Bind(wx.EVT_LEFT_DCLICK, self._onLeftButtonDClick) self.Bind(wx.EVT_LEFT_UP, self._onLeftButtonUp) self.Bind(wx.EVT_MOTION, self._onMotion) self.Bind(wx.EVT_LEAVE_WINDOW, self._onLeave) self.Bind(wx.EVT_ENTER_WINDOW, self._onEnter) # Add middle button events self.Bind(wx.EVT_MIDDLE_DOWN, self._onMiddleButtonDown) self.Bind(wx.EVT_MIDDLE_DCLICK, self._onMiddleButtonDClick) self.Bind(wx.EVT_MIDDLE_UP, self._onMiddleButtonUp) self.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self._onCaptureLost) self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self._onCaptureLost) self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Reduce flicker. self.SetBackgroundColour(wx.WHITE) self.macros = {} # dict from wx id to seq of macros def Destroy(self, *args, **kwargs): wx.Panel.Destroy(self, *args, **kwargs) def Copy_to_Clipboard(self, event=None): "copy bitmap of canvas to system clipboard" bmp_obj = wx.BitmapDataObject() bmp_obj.SetBitmap(self.bitmap) if not wx.TheClipboard.IsOpened(): open_success = wx.TheClipboard.Open() if open_success: wx.TheClipboard.SetData(bmp_obj) wx.TheClipboard.Close() wx.TheClipboard.Flush() def draw_idle(self): """ Delay rendering until the GUI is idle. """ DEBUG_MSG("draw_idle()", 1, self) self._isDrawn = False # Force redraw # Triggering a paint event is all that is needed to defer drawing # until later. The platform will send the event when it thinks it is # a good time (usually as soon as there are no other events pending). self.Refresh(eraseBackground=False) def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Other Parameters ---------------- interval : scalar Timer interval in milliseconds callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerWx(self, *args, **kwargs) def flush_events(self): wx.Yield() def start_event_loop(self, timeout=0): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout. Raises RuntimeError if event loop is already running. """ if hasattr(self, '_event_loop'): raise RuntimeError("Event loop already running") id = wx.NewId() timer = wx.Timer(self, id=id) if timeout > 0: timer.Start(timeout * 1000, oneShot=True) self.Bind(wx.EVT_TIMER, self.stop_event_loop, id=id) # Event loop handler for start/stop event loop self._event_loop = wxc.EventLoop() self._event_loop.Run() timer.Stop() def stop_event_loop(self, event=None): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. """ if hasattr(self, '_event_loop'): if self._event_loop.IsRunning(): self._event_loop.Exit() del self._event_loop def _get_imagesave_wildcards(self): 'return the wildcard string for the filesave dialog' default_filetype = self.get_default_filetype() filetypes = self.get_supported_filetypes_grouped() sorted_filetypes = sorted(filetypes.items()) wildcards = [] extensions = [] filter_index = 0 for i, (name, exts) in enumerate(sorted_filetypes): ext_list = ';'.join(['*.%s' % ext for ext in exts]) extensions.append(exts[0]) wildcard = '%s (%s)|%s' % (name, ext_list, ext_list) if default_filetype in exts: filter_index = i wildcards.append(wildcard) wildcards = '|'.join(wildcards) return wildcards, extensions, filter_index def gui_repaint(self, drawDC=None, origin='WX'): """ Performs update of the displayed image on the GUI canvas, using the supplied wx.PaintDC device context. The 'WXAgg' backend sets origin accordingly. """ DEBUG_MSG("gui_repaint()", 1, self) if self.IsShownOnScreen(): if not drawDC: # not called from OnPaint use a ClientDC drawDC = wx.ClientDC(self) # following is for 'WX' backend on Windows # the bitmap can not be in use by another DC, # see GraphicsContextWx._cache if wx.Platform == '__WXMSW__' and origin == 'WX': img = self.bitmap.ConvertToImage() bmp = img.ConvertToBitmap() drawDC.DrawBitmap(bmp, 0, 0) else: drawDC.DrawBitmap(self.bitmap, 0, 0) filetypes = FigureCanvasBase.filetypes.copy() filetypes['bmp'] = 'Windows bitmap' filetypes['jpeg'] = 'JPEG' filetypes['jpg'] = 'JPEG' filetypes['pcx'] = 'PCX' filetypes['png'] = 'Portable Network Graphics' filetypes['tif'] = 'Tagged Image Format File' filetypes['tiff'] = 'Tagged Image Format File' filetypes['xpm'] = 'X pixmap' def print_figure(self, filename, *args, **kwargs): super(_FigureCanvasWxBase, self).print_figure( filename, *args, **kwargs) # Restore the current view; this is needed because the artist contains # methods rely on particular attributes of the rendered figure for # determining things like bounding boxes. if self._isDrawn: self.draw() def _onPaint(self, evt): """ Called when wxPaintEvt is generated """ DEBUG_MSG("_onPaint()", 1, self) drawDC = wx.PaintDC(self) if not self._isDrawn: self.draw(drawDC=drawDC) else: self.gui_repaint(drawDC=drawDC) drawDC.Destroy() def _onSize(self, evt): """ Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window. """ DEBUG_MSG("_onSize()", 2, self) sz = self.GetParent().GetSizer() if sz: si = sz.GetItem(self) if sz and si and not si.Proportion and not si.Flag & wx.EXPAND: # managed by a sizer, but with a fixed size size = self.GetMinSize() else: # variable size size = self.GetClientSize() if getattr(self, "_width", None): if size == (self._width, self._height): # no change in size return self._width, self._height = size # Create a new, correctly sized bitmap self.bitmap = wxc.EmptyBitmap(self._width, self._height) self._isDrawn = False if self._width <= 1 or self._height <= 1: return # Empty figure dpival = self.figure.dpi winch = self._width / dpival hinch = self._height / dpival self.figure.set_size_inches(winch, hinch, forward=False) # Rendering will happen on the associated paint event # so no need to do anything here except to make sure # the whole background is repainted. self.Refresh(eraseBackground=False) FigureCanvasBase.resize_event(self) def _get_key(self, evt): keyval = evt.KeyCode if keyval in self.keyvald: key = self.keyvald[keyval] elif keyval < 256: key = chr(keyval) # wx always returns an uppercase, so make it lowercase if the shift # key is not depressed (NOTE: this will not handle Caps Lock) if not evt.ShiftDown(): key = key.lower() else: key = None for meth, prefix in ( [evt.AltDown, 'alt'], [evt.ControlDown, 'ctrl'], ): if meth(): key = '{0}+{1}'.format(prefix, key) return key def _onKeyDown(self, evt): """Capture key press.""" key = self._get_key(evt) FigureCanvasBase.key_press_event(self, key, guiEvent=evt) if self: evt.Skip() def _onKeyUp(self, evt): """Release key.""" key = self._get_key(evt) FigureCanvasBase.key_release_event(self, key, guiEvent=evt) if self: evt.Skip() def _set_capture(self, capture=True): """control wx mouse capture """ if self.HasCapture(): self.ReleaseMouse() if capture: self.CaptureMouse() def _onCaptureLost(self, evt): """Capture changed or lost""" self._set_capture(False) def _onRightButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(True) FigureCanvasBase.button_press_event(self, x, y, 3, guiEvent=evt) def _onRightButtonDClick(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(True) FigureCanvasBase.button_press_event(self, x, y, 3, dblclick=True, guiEvent=evt) def _onRightButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(False) FigureCanvasBase.button_release_event(self, x, y, 3, guiEvent=evt) def _onLeftButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(True) FigureCanvasBase.button_press_event(self, x, y, 1, guiEvent=evt) def _onLeftButtonDClick(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(True) FigureCanvasBase.button_press_event(self, x, y, 1, dblclick=True, guiEvent=evt) def _onLeftButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(False) FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt) # Add middle button events def _onMiddleButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(True) FigureCanvasBase.button_press_event(self, x, y, 2, guiEvent=evt) def _onMiddleButtonDClick(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(True) FigureCanvasBase.button_press_event(self, x, y, 2, dblclick=True, guiEvent=evt) def _onMiddleButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self._set_capture(False) FigureCanvasBase.button_release_event(self, x, y, 2, guiEvent=evt) def _onMouseWheel(self, evt): """Translate mouse wheel events into matplotlib events""" # Determine mouse location x = evt.GetX() y = self.figure.bbox.height - evt.GetY() # Convert delta/rotation/rate into a floating point step size delta = evt.GetWheelDelta() rotation = evt.GetWheelRotation() rate = evt.GetLinesPerAction() step = rate * rotation / delta # Done handling event evt.Skip() # Mac is giving two events for every wheel event # Need to skip every second one if wx.Platform == '__WXMAC__': if not hasattr(self, '_skipwheelevent'): self._skipwheelevent = True elif self._skipwheelevent: self._skipwheelevent = False return # Return without processing event else: self._skipwheelevent = True # Convert to mpl event FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=evt) def _onMotion(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt) def _onLeave(self, evt): """Mouse has left the window.""" evt.Skip() FigureCanvasBase.leave_notify_event(self, guiEvent=evt) def _onEnter(self, evt): """Mouse has entered the window.""" FigureCanvasBase.enter_notify_event(self, guiEvent=evt) class FigureCanvasWx(_FigureCanvasWxBase): # Rendering to a Wx canvas using the deprecated Wx renderer. def draw(self, drawDC=None): """ Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified. """ DEBUG_MSG("draw()", 1, self) self.renderer = RendererWx(self.bitmap, self.figure.dpi) self.figure.draw(self.renderer) self._isDrawn = True self.gui_repaint(drawDC=drawDC) def print_bmp(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_BMP, *args, **kwargs) if not _has_pil: def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_JPEG, *args, **kwargs) print_jpg = print_jpeg def print_pcx(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_PCX, *args, **kwargs) def print_png(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_PNG, *args, **kwargs) if not _has_pil: def print_tiff(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_TIF, *args, **kwargs) print_tif = print_tiff def print_xpm(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_XPM, *args, **kwargs) def _print_image(self, filename, filetype, *args, **kwargs): origBitmap = self.bitmap l, b, width, height = self.figure.bbox.bounds width = int(math.ceil(width)) height = int(math.ceil(height)) self.bitmap = wxc.EmptyBitmap(width, height) renderer = RendererWx(self.bitmap, self.figure.dpi) gc = renderer.new_gc() self.figure.draw(renderer) # image is the object that we call SaveFile on. image = self.bitmap # set the JPEG quality appropriately. Unfortunately, it is only # possible to set the quality on a wx.Image object. So if we # are saving a JPEG, convert the wx.Bitmap to a wx.Image, # and set the quality. if filetype == wx.BITMAP_TYPE_JPEG: jpeg_quality = kwargs.get('quality', rcParams['savefig.jpeg_quality']) image = self.bitmap.ConvertToImage() image.SetOption(wx.IMAGE_OPTION_QUALITY, str(jpeg_quality)) # Now that we have rendered into the bitmap, save it # to the appropriate file type and clean up if isinstance(filename, six.string_types): if not image.SaveFile(filename, filetype): DEBUG_MSG('print_figure() file save error', 4, self) raise RuntimeError( 'Could not save figure to %s\n' % (filename)) elif is_writable_file_like(filename): if not isinstance(image, wx.Image): image = image.ConvertToImage() if not image.SaveStream(filename, filetype): DEBUG_MSG('print_figure() file save error', 4, self) raise RuntimeError( 'Could not save figure to %s\n' % (filename)) # Restore everything to normal self.bitmap = origBitmap # Note: draw is required here since bits of state about the # last renderer are strewn about the artist draw methods. Do # not remove the draw without first verifying that these have # been cleaned up. The artist contains() methods will fail # otherwise. if self._isDrawn: self.draw() self.Refresh() ######################################################################## # # The following functions and classes are for pylab compatibility # mode (matplotlib.pylab) and implement figure managers, etc... # ######################################################################## class FigureFrameWx(wx.Frame): def __init__(self, num, fig): # On non-Windows platform, explicitly set the position - fix # positioning bug on some Linux platforms if wx.Platform == '__WXMSW__': pos = wx.DefaultPosition else: pos = wx.Point(20, 20) l, b, w, h = fig.bbox.bounds wx.Frame.__init__(self, parent=None, id=-1, pos=pos, title="Figure %d" % num) # Frame will be sized later by the Fit method DEBUG_MSG("__init__()", 1, self) self.num = num statbar = StatusBarWx(self) self.SetStatusBar(statbar) self.canvas = self.get_canvas(fig) self.canvas.SetInitialSize(wx.Size(fig.bbox.width, fig.bbox.height)) self.canvas.SetFocus() self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version self.toolbar = self._get_toolbar(statbar) if self.toolbar is not None: self.toolbar.Realize() # On Windows platform, default window size is incorrect, so set # toolbar width to figure width. if wxc.is_phoenix: tw, th = self.toolbar.GetSize() fw, fh = self.canvas.GetSize() else: tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version. self.toolbar.SetSize(wx.Size(fw, th)) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(self.sizer) self.Fit() self.canvas.SetMinSize((2, 2)) # give the window a matplotlib icon rather than the stock one. # This is not currently working on Linux and is untested elsewhere. # icon_path = os.path.join(matplotlib.rcParams['datapath'], # 'images', 'matplotlib.png') # icon = wx.IconFromBitmap(wx.Bitmap(icon_path)) # for xpm type icons try: # icon = wx.Icon(icon_path, wx.BITMAP_TYPE_XPM) # self.SetIcon(icon) self.figmgr = FigureManagerWx(self.canvas, num, self) self.Bind(wx.EVT_CLOSE, self._onClose) def _get_toolbar(self, statbar): if rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2Wx(self.canvas) toolbar.set_status_bar(statbar) else: toolbar = None return toolbar def get_canvas(self, fig): return FigureCanvasWx(self, -1, fig) def get_figure_manager(self): DEBUG_MSG("get_figure_manager()", 1, self) return self.figmgr def _onClose(self, evt): DEBUG_MSG("onClose()", 1, self) self.canvas.close_event() self.canvas.stop_event_loop() Gcf.destroy(self.num) # self.Destroy() def GetToolBar(self): """Override wxFrame::GetToolBar as we don't have managed toolbar""" return self.toolbar def Destroy(self, *args, **kwargs): try: self.canvas.mpl_disconnect(self.toolbar._idDrag) # Rationale for line above: see issue 2941338. except AttributeError: pass # classic toolbar lacks the attribute if not self.IsBeingDeleted(): wx.Frame.Destroy(self, *args, **kwargs) if self.toolbar is not None: self.toolbar.Destroy() wxapp = wx.GetApp() if wxapp: wxapp.Yield() return True class FigureManagerWx(FigureManagerBase): """ This class contains the FigureCanvas and GUI frame It is instantiated by GcfWx whenever a new figure is created. GcfWx is responsible for managing multiple instances of FigureManagerWx. Attributes ---------- canvas : `FigureCanvas` a FigureCanvasWx(wx.Panel) instance window : wxFrame a wxFrame instance - wxpython.org/Phoenix/docs/html/Frame.html """ def __init__(self, canvas, num, frame): DEBUG_MSG("__init__()", 1, self) FigureManagerBase.__init__(self, canvas, num) self.frame = frame self.window = frame self.tb = frame.GetToolBar() self.toolbar = self.tb # consistent with other backends def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.tb is not None: self.tb.update() self.canvas.figure.add_axobserver(notify_axes_change) def show(self): self.frame.Show() self.canvas.draw() def destroy(self, *args): DEBUG_MSG("destroy()", 1, self) self.frame.Destroy() wxapp = wx.GetApp() if wxapp: wxapp.Yield() def get_window_title(self): return self.window.GetTitle() def set_window_title(self, title): self.window.SetTitle(title) def resize(self, width, height): 'Set the canvas size in pixels' self.canvas.SetInitialSize(wx.Size(width, height)) self.window.GetSizer().Fit(self.window) # Identifiers for toolbar controls - images_wx contains bitmaps for the images # used in the controls. wxWindows does not provide any stock images, so I've # 'stolen' those from GTK2, and transformed them into the appropriate format. # import images_wx _NTB_AXISMENU = wx.NewId() _NTB_AXISMENU_BUTTON = wx.NewId() _NTB_X_PAN_LEFT = wx.NewId() _NTB_X_PAN_RIGHT = wx.NewId() _NTB_X_ZOOMIN = wx.NewId() _NTB_X_ZOOMOUT = wx.NewId() _NTB_Y_PAN_UP = wx.NewId() _NTB_Y_PAN_DOWN = wx.NewId() _NTB_Y_ZOOMIN = wx.NewId() _NTB_Y_ZOOMOUT = wx.NewId() # _NTB_SUBPLOT =wx.NewId() _NTB_SAVE = wx.NewId() _NTB_CLOSE = wx.NewId() def _load_bitmap(filename): """ Load a bitmap file from the backends/images subdirectory in which the matplotlib library is installed. The filename parameter should not contain any path information as this is determined automatically. Returns a wx.Bitmap object """ basedir = os.path.join(rcParams['datapath'], 'images') bmpFilename = os.path.normpath(os.path.join(basedir, filename)) if not os.path.exists(bmpFilename): raise IOError('Could not find bitmap file "%s"; dying' % bmpFilename) bmp = wx.Bitmap(bmpFilename) return bmp class MenuButtonWx(wx.Button): """ wxPython does not permit a menu to be incorporated directly into a toolbar. This class simulates the effect by associating a pop-up menu with a button in the toolbar, and managing this as though it were a menu. """ def __init__(self, parent): wx.Button.__init__(self, parent, _NTB_AXISMENU_BUTTON, "Axes: ", style=wx.BU_EXACTFIT) self._toolbar = parent self._menu = wx.Menu() self._axisId = [] # First two menu items never change... self._allId = wx.NewId() self._invertId = wx.NewId() self._menu.Append(self._allId, "All", "Select all axes", False) self._menu.Append(self._invertId, "Invert", "Invert axes selected", False) self._menu.AppendSeparator() self.Bind(wx.EVT_BUTTON, self._onMenuButton, id=_NTB_AXISMENU_BUTTON) self.Bind(wx.EVT_MENU, self._handleSelectAllAxes, id=self._allId) self.Bind(wx.EVT_MENU, self._handleInvertAxesSelected, id=self._invertId) def Destroy(self): self._menu.Destroy() self.Destroy() def _onMenuButton(self, evt): """Handle menu button pressed.""" if wxc.is_phoenix: x, y = self.GetPosition() w, h = self.GetSize() else: x, y = self.GetPositionTuple() w, h = self.GetSizeTuple() self.PopupMenuXY(self._menu, x, y + h - 4) # When menu returned, indicate selection in button evt.Skip() def _handleSelectAllAxes(self, evt): """Called when the 'select all axes' menu item is selected.""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def _handleInvertAxesSelected(self, evt): """Called when the invert all menu item is selected""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): self._menu.Check(self._axisId[i], False) else: self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def _onMenuItemSelected(self, evt): """Called whenever one of the specific axis menu items is selected""" current = self._menu.IsChecked(evt.GetId()) if current: new = False else: new = True self._menu.Check(evt.GetId(), new) # Lines above would be deleted based on svn tracker ID 2841525; # not clear whether this matters or not. self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def updateAxes(self, maxAxis): """Ensures that there are entries for max_axis axes in the menu (selected by default).""" if maxAxis > len(self._axisId): for i in range(len(self._axisId) + 1, maxAxis + 1, 1): menuId = wx.NewId() self._axisId.append(menuId) self._menu.Append(menuId, "Axis %d" % i, "Select axis %d" % i, True) self._menu.Check(menuId, True) self.Bind(wx.EVT_MENU, self._onMenuItemSelected, id=menuId) elif maxAxis < len(self._axisId): for menuId in self._axisId[maxAxis:]: self._menu.Delete(menuId) self._axisId = self._axisId[:maxAxis] self._toolbar.set_active(list(xrange(maxAxis))) def getActiveAxes(self): """Return a list of the selected axes.""" active = [] for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): active.append(i) return active def updateButtonText(self, lst): """Update the list of selected axes in the menu button.""" self.SetLabel( 'Axes: ' + ','.join('%d' % (e + 1) for e in lst)) cursord = { cursors.MOVE: wx.CURSOR_HAND, cursors.HAND: wx.CURSOR_HAND, cursors.POINTER: wx.CURSOR_ARROW, cursors.SELECT_REGION: wx.CURSOR_CROSS, cursors.WAIT: wx.CURSOR_WAIT, } @cbook.deprecated("2.2") class SubplotToolWX(wx.Frame): def __init__(self, targetfig): wx.Frame.__init__(self, None, -1, "Configure subplots") toolfig = Figure((6, 3)) canvas = FigureCanvasWx(self, -1, toolfig) # Create a figure manager to manage things figmgr = FigureManager(canvas, 1, self) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(sizer) self.Fit() tool = SubplotTool(targetfig, toolfig) class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar): def __init__(self, canvas): wx.ToolBar.__init__(self, canvas.GetParent(), -1) NavigationToolbar2.__init__(self, canvas) self.canvas = canvas self._idle = True self.statbar = None self.prevZoomRect = None # for now, use alternate zoom-rectangle drawing on all # Macs. N.B. In future versions of wx it may be possible to # detect Retina displays with window.GetContentScaleFactor() # and/or dc.GetContentScaleFactor() self.retinaFix = 'wxMac' in wx.PlatformInfo def get_canvas(self, frame, fig): return type(self.canvas)(frame, -1, fig) def _init_toolbar(self): DEBUG_MSG("_init_toolbar", 1, self) self._parent = self.canvas.GetParent() self.wx_ids = {} for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.AddSeparator() continue self.wx_ids[text] = wx.NewId() wxc._AddTool(self, self.wx_ids, text, _load_bitmap(image_file + '.png'), tooltip_text) self.Bind(wx.EVT_TOOL, getattr(self, callback), id=self.wx_ids[text]) self.Realize() def zoom(self, *args): self.ToggleTool(self.wx_ids['Pan'], False) NavigationToolbar2.zoom(self, *args) def pan(self, *args): self.ToggleTool(self.wx_ids['Zoom'], False) NavigationToolbar2.pan(self, *args) def configure_subplots(self, evt): frame = wx.Frame(None, -1, "Configure subplots") toolfig = Figure((6, 3)) canvas = self.get_canvas(frame, toolfig) # Create a figure manager to manage things figmgr = FigureManager(canvas, 1, frame) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(canvas, 1, wx.LEFT | wx.TOP | wx.GROW) frame.SetSizer(sizer) frame.Fit() tool = SubplotTool(self.canvas.figure, toolfig) frame.Show() def save_figure(self, *args): # Fetch the required filename and file type. filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards() default_file = self.canvas.get_default_filename() dlg = wx.FileDialog(self._parent, "Save to file", "", default_file, filetypes, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) dlg.SetFilterIndex(filter_index) if dlg.ShowModal() == wx.ID_OK: dirname = dlg.GetDirectory() filename = dlg.GetFilename() DEBUG_MSG( 'Save file dir:%s name:%s' % (dirname, filename), 3, self) format = exts[dlg.GetFilterIndex()] basename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format != ext: # looks like they forgot to set the image type drop # down, going with the extension. warnings.warn( 'extension %s did not match the selected ' 'image type %s; going with %s' % (ext, format, ext), stacklevel=0) format = ext try: self.canvas.figure.savefig( os.path.join(dirname, filename), format=format) except Exception as e: error_msg_wx(str(e)) def set_cursor(self, cursor): cursor = wxc.Cursor(cursord[cursor]) self.canvas.SetCursor(cursor) self.canvas.Update() @cbook.deprecated("2.1", alternative="canvas.draw_idle") def dynamic_update(self): d = self._idle self._idle = False if d: self.canvas.draw() self._idle = True def press(self, event): if self._active == 'ZOOM': if not self.retinaFix: self.wxoverlay = wx.Overlay() else: if event.inaxes is not None: self.savedRetinaImage = self.canvas.copy_from_bbox( event.inaxes.bbox) self.zoomStartX = event.xdata self.zoomStartY = event.ydata self.zoomAxes = event.inaxes def release(self, event): if self._active == 'ZOOM': # When the mouse is released we reset the overlay and it # restores the former content to the window. if not self.retinaFix: self.wxoverlay.Reset() del self.wxoverlay else: del self.savedRetinaImage if self.prevZoomRect: self.prevZoomRect.pop(0).remove() self.prevZoomRect = None if self.zoomAxes: self.zoomAxes = None def draw_rubberband(self, event, x0, y0, x1, y1): if self.retinaFix: # On Macs, use the following code # wx.DCOverlay does not work properly on Retina displays. rubberBandColor = '#C0C0FF' if self.prevZoomRect: self.prevZoomRect.pop(0).remove() self.canvas.restore_region(self.savedRetinaImage) X0, X1 = self.zoomStartX, event.xdata Y0, Y1 = self.zoomStartY, event.ydata lineX = (X0, X0, X1, X1, X0) lineY = (Y0, Y1, Y1, Y0, Y0) self.prevZoomRect = self.zoomAxes.plot( lineX, lineY, '-', color=rubberBandColor) self.zoomAxes.draw_artist(self.prevZoomRect[0]) self.canvas.blit(self.zoomAxes.bbox) return # Use an Overlay to draw a rubberband-like bounding box. dc = wx.ClientDC(self.canvas) odc = wx.DCOverlay(self.wxoverlay, dc) odc.Clear() # Mac's DC is already the same as a GCDC, and it causes # problems with the overlay if we try to use an actual # wx.GCDC so don't try it. if 'wxMac' not in wx.PlatformInfo: dc = wx.GCDC(dc) height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 if y1 < y0: y0, y1 = y1, y0 if x1 < y0: x0, x1 = x1, x0 w = x1 - x0 h = y1 - y0 rect = wx.Rect(x0, y0, w, h) rubberBandColor = '#C0C0FF' # or load from config? # Set a pen for the border color = wxc.NamedColour(rubberBandColor) dc.SetPen(wx.Pen(color, 1)) # use the same color, plus alpha for the brush r, g, b, a = color.Get(True) color.Set(r, g, b, 0x60) dc.SetBrush(wx.Brush(color)) if wxc.is_phoenix: dc.DrawRectangle(rect) else: dc.DrawRectangleRect(rect) def set_status_bar(self, statbar): self.statbar = statbar def set_message(self, s): if self.statbar is not None: self.statbar.set_function(s) def set_history_buttons(self): can_backward = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack._elements) - 1 self.EnableTool(self.wx_ids['Back'], can_backward) self.EnableTool(self.wx_ids['Forward'], can_forward) @cbook.deprecated("2.2", alternative="NavigationToolbar2Wx") class Toolbar(NavigationToolbar2Wx): pass class StatusBarWx(wx.StatusBar): """ A status bar is added to _FigureFrame to allow measurements and the previously selected scroll function to be displayed as a user convenience. """ def __init__(self, parent): wx.StatusBar.__init__(self, parent, -1) self.SetFieldsCount(2) self.SetStatusText("None", 1) # self.SetStatusText("Measurement: None", 2) # self.Reposition() def set_function(self, string): self.SetStatusText("%s" % string, 1) # def set_measurement(self, string): # self.SetStatusText("Measurement: %s" % string, 2) # tools for matplotlib.backend_managers.ToolManager: # for now only SaveFigure, SetCursor and Rubberband are implemented # once a ToolbarWx is implemented, also FigureManagerWx needs to be # modified, similar to pull request #9934 class SaveFigureWx(backend_tools.SaveFigureBase): def trigger(self, *args): # Fetch the required filename and file type. filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards() default_dir = os.path.expanduser( matplotlib.rcParams['savefig.directory']) default_file = self.canvas.get_default_filename() dlg = wx.FileDialog(self.canvas.GetTopLevelParent(), "Save to file", default_dir, default_file, filetypes, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) dlg.SetFilterIndex(filter_index) if dlg.ShowModal() != wx.ID_OK: return dirname = dlg.GetDirectory() filename = dlg.GetFilename() DEBUG_MSG('Save file dir:%s name:%s' % (dirname, filename), 3, self) format = exts[dlg.GetFilterIndex()] basename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format != ext: # looks like they forgot to set the image type drop # down, going with the extension. warnings.warn( 'extension %s did not match the selected ' 'image type %s; going with %s' % (ext, format, ext), stacklevel=0) format = ext if default_dir != "": matplotlib.rcParams['savefig.directory'] = dirname try: self.canvas.figure.savefig( os.path.join(dirname, filename), format=format) except Exception as e: error_msg_wx(str(e)) class SetCursorWx(backend_tools.SetCursorBase): def set_cursor(self, cursor): cursor = wxc.Cursor(cursord[cursor]) self.canvas.SetCursor(cursor) self.canvas.Update() if 'wxMac' not in wx.PlatformInfo: # on most platforms, use overlay class RubberbandWx(backend_tools.RubberbandBase): def __init__(self, *args, **kwargs): backend_tools.RubberbandBase.__init__(self, *args, **kwargs) self.wxoverlay = None def draw_rubberband(self, x0, y0, x1, y1): # Use an Overlay to draw a rubberband-like bounding box. if self.wxoverlay is None: self.wxoverlay = wx.Overlay() dc = wx.ClientDC(self.canvas) odc = wx.DCOverlay(self.wxoverlay, dc) odc.Clear() dc = wx.GCDC(dc) height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 if y1 < y0: y0, y1 = y1, y0 if x1 < y0: x0, x1 = x1, x0 w = x1 - x0 h = y1 - y0 rect = wx.Rect(x0, y0, w, h) rubberBandColor = '#C0C0FF' # or load from config? # Set a pen for the border color = wxc.NamedColour(rubberBandColor) dc.SetPen(wx.Pen(color, 1)) # use the same color, plus alpha for the brush r, g, b, a = color.Get(True) color.Set(r, g, b, 0x60) dc.SetBrush(wx.Brush(color)) if wxc.is_phoenix: dc.DrawRectangle(rect) else: dc.DrawRectangleRect(rect) def remove_rubberband(self): if self.wxoverlay is None: return self.wxoverlay.Reset() self.wxoverlay = None else: # on Mac OS retina displays DCOverlay does not work # and dc.SetLogicalFunction does not have an effect on any display # the workaround is to blit the full image for remove_rubberband class RubberbandWx(backend_tools.RubberbandBase): def __init__(self, *args, **kwargs): backend_tools.RubberbandBase.__init__(self, *args, **kwargs) self._rect = None def draw_rubberband(self, x0, y0, x1, y1): dc = wx.ClientDC(self.canvas) # this would be required if the Canvas is a ScrolledWindow, # which is not the case for now # self.PrepareDC(dc) # delete old rubberband if self._rect: self.remove_rubberband(dc) # draw new rubberband dc.SetPen(wx.Pen(wx.BLACK, 1, wx.SOLID)) dc.SetBrush(wx.TRANSPARENT_BRUSH) self._rect = (x0, self.canvas._height-y0, x1-x0, -y1+y0) if wxc.is_phoenix: dc.DrawRectangle(self._rect) else: dc.DrawRectangleRect(self._rect) def remove_rubberband(self, dc=None): if not self._rect: return if self.canvas.bitmap: if dc is None: dc = wx.ClientDC(self.canvas) dc.DrawBitmap(self.canvas.bitmap, 0, 0) # for testing the method on Windows, use this code instead: # img = self.canvas.bitmap.ConvertToImage() # bmp = img.ConvertToBitmap() # dc.DrawBitmap(bmp, 0, 0) self._rect = None backend_tools.ToolSaveFigure = SaveFigureWx backend_tools.ToolSetCursor = SetCursorWx backend_tools.ToolRubberband = RubberbandWx # < Additions for printing support: Matt Newville class PrintoutWx(wx.Printout): """ Simple wrapper around wx Printout class -- all the real work here is scaling the matplotlib canvas bitmap to the current printer's definition. """ def __init__(self, canvas, width=5.5, margin=0.5, title='matplotlib'): wx.Printout.__init__(self, title=title) self.canvas = canvas # width, in inches of output figure (approximate) self.width = width self.margin = margin def HasPage(self, page): # current only supports 1 page print return page == 1 def GetPageInfo(self): return (1, 1, 1, 1) def OnPrintPage(self, page): self.canvas.draw() dc = self.GetDC() (ppw, pph) = self.GetPPIPrinter() # printer's pixels per in (pgw, pgh) = self.GetPageSizePixels() # page size in pixels (dcw, dch) = dc.GetSize() if wxc.is_phoenix: (grw, grh) = self.canvas.GetSize() else: (grw, grh) = self.canvas.GetSizeTuple() # save current figure dpi resolution and bg color, # so that we can temporarily set them to the dpi of # the printer, and the bg color to white bgcolor = self.canvas.figure.get_facecolor() fig_dpi = self.canvas.figure.dpi # draw the bitmap, scaled appropriately vscale = float(ppw) / fig_dpi # set figure resolution,bg color for printer self.canvas.figure.dpi = ppw self.canvas.figure.set_facecolor('#FFFFFF') renderer = RendererWx(self.canvas.bitmap, self.canvas.figure.dpi) self.canvas.figure.draw(renderer) self.canvas.bitmap.SetWidth( int(self.canvas.bitmap.GetWidth() * vscale)) self.canvas.bitmap.SetHeight( int(self.canvas.bitmap.GetHeight() * vscale)) self.canvas.draw() # page may need additional scaling on preview page_scale = 1.0 if self.IsPreview(): page_scale = float(dcw) / pgw # get margin in pixels = (margin in in) * (pixels/in) top_margin = int(self.margin * pph * page_scale) left_margin = int(self.margin * ppw * page_scale) # set scale so that width of output is self.width inches # (assuming grw is size of graph in inches....) user_scale = (self.width * fig_dpi * page_scale) / float(grw) dc.SetDeviceOrigin(left_margin, top_margin) dc.SetUserScale(user_scale, user_scale) # this cute little number avoid API inconsistencies in wx try: dc.DrawBitmap(self.canvas.bitmap, 0, 0) except Exception: try: dc.DrawBitmap(self.canvas.bitmap, (0, 0)) except Exception: pass # restore original figure resolution self.canvas.figure.set_facecolor(bgcolor) self.canvas.figure.dpi = fig_dpi self.canvas.draw() return True # > @_Backend.export class _BackendWx(_Backend): FigureCanvas = FigureCanvasWx FigureManager = FigureManagerWx _frame_class = FigureFrameWx @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @classmethod def new_figure_manager(cls, num, *args, **kwargs): # Create a wx.App instance if it has not been created sofar. wxapp = wx.GetApp() if wxapp is None: wxapp = wx.App(False) wxapp.SetExitOnFrameDelete(True) # Retain a reference to the app object so that it does not get # garbage collected. _BackendWx._theWxApp = wxapp return super(_BackendWx, cls).new_figure_manager(num, *args, **kwargs) @classmethod def new_figure_manager_given_figure(cls, num, figure): frame = cls._frame_class(num, figure) figmgr = frame.get_figure_manager() if matplotlib.is_interactive(): figmgr.frame.Show() figure.canvas.draw_idle() return figmgr @staticmethod def mainloop(): if not wx.App.IsMainLoopRunning(): wxapp = wx.GetApp() if wxapp is not None: wxapp.MainLoop()
69,524
33.710434
131
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_gtk.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import logging import os import sys import warnings if six.PY3: warnings.warn( "The gtk* backends have not been tested with Python 3.x", ImportWarning) try: import gobject import gtk; gdk = gtk.gdk import pango except ImportError: raise ImportError("Gtk* backend requires pygtk to be installed.") pygtk_version_required = (2,4,0) if gtk.pygtk_version < pygtk_version_required: raise ImportError ("PyGTK %d.%d.%d is installed\n" "PyGTK %d.%d.%d or later is required" % (gtk.pygtk_version + pygtk_version_required)) del pygtk_version_required _new_tooltip_api = (gtk.pygtk_version[1] >= 12) import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors) from matplotlib.backends.backend_gdk import RendererGDK, FigureCanvasGDK from matplotlib.cbook import is_writable_file_like, warn_deprecated from matplotlib.figure import Figure from matplotlib.widgets import SubplotTool from matplotlib import ( cbook, colors as mcolors, lines, markers, rcParams) _log = logging.getLogger(__name__) backend_version = "%d.%d.%d" % gtk.pygtk_version # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 96 # Hide the benign warning that it can't stat a file that doesn't warnings.filterwarnings('ignore', '.*Unable to retrieve the file info for.*', gtk.Warning) cursord = { cursors.MOVE : gdk.Cursor(gdk.FLEUR), cursors.HAND : gdk.Cursor(gdk.HAND2), cursors.POINTER : gdk.Cursor(gdk.LEFT_PTR), cursors.SELECT_REGION : gdk.Cursor(gdk.TCROSS), cursors.WAIT : gdk.Cursor(gdk.WATCH), } # ref gtk+/gtk/gtkwidget.h def GTK_WIDGET_DRAWABLE(w): flags = w.flags(); return flags & gtk.VISIBLE != 0 and flags & gtk.MAPPED != 0 class TimerGTK(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` using GTK for timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def _timer_start(self): # Need to stop it, otherwise we potentially leak a timer id that will # never be stopped. self._timer_stop() self._timer = gobject.timeout_add(self._interval, self._on_timer) def _timer_stop(self): if self._timer is not None: gobject.source_remove(self._timer) self._timer = None def _timer_set_interval(self): # Only stop and restart it if the timer has already been started if self._timer is not None: self._timer_stop() self._timer_start() def _on_timer(self): TimerBase._on_timer(self) # Gtk timeout_add() requires that the callback returns True if it # is to be called again. if len(self.callbacks) > 0 and not self._single: return True else: self._timer = None return False class FigureCanvasGTK (gtk.DrawingArea, FigureCanvasBase): keyvald = {65507 : 'control', 65505 : 'shift', 65513 : 'alt', 65508 : 'control', 65506 : 'shift', 65514 : 'alt', 65361 : 'left', 65362 : 'up', 65363 : 'right', 65364 : 'down', 65307 : 'escape', 65470 : 'f1', 65471 : 'f2', 65472 : 'f3', 65473 : 'f4', 65474 : 'f5', 65475 : 'f6', 65476 : 'f7', 65477 : 'f8', 65478 : 'f9', 65479 : 'f10', 65480 : 'f11', 65481 : 'f12', 65300 : 'scroll_lock', 65299 : 'break', 65288 : 'backspace', 65293 : 'enter', 65379 : 'insert', 65535 : 'delete', 65360 : 'home', 65367 : 'end', 65365 : 'pageup', 65366 : 'pagedown', 65438 : '0', 65436 : '1', 65433 : '2', 65435 : '3', 65430 : '4', 65437 : '5', 65432 : '6', 65429 : '7', 65431 : '8', 65434 : '9', 65451 : '+', 65453 : '-', 65450 : '*', 65455 : '/', 65439 : 'dec', 65421 : 'enter', 65511 : 'super', 65512 : 'super', 65406 : 'alt', 65289 : 'tab', } # Setting this as a static constant prevents # this resulting expression from leaking event_mask = (gdk.BUTTON_PRESS_MASK | gdk.BUTTON_RELEASE_MASK | gdk.EXPOSURE_MASK | gdk.KEY_PRESS_MASK | gdk.KEY_RELEASE_MASK | gdk.ENTER_NOTIFY_MASK | gdk.LEAVE_NOTIFY_MASK | gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK) def __init__(self, figure): if self.__class__ == matplotlib.backends.backend_gtk.FigureCanvasGTK: warn_deprecated('2.0', message="The GTK backend is " "deprecated. It is untested, known to be " "broken and will be removed in Matplotlib 3.0. " "Use the GTKAgg backend instead. " "See Matplotlib usage FAQ for" " more info on backends.", alternative="GTKAgg") FigureCanvasBase.__init__(self, figure) gtk.DrawingArea.__init__(self) self._idle_draw_id = 0 self._need_redraw = True self._pixmap_width = -1 self._pixmap_height = -1 self._lastCursor = None self.connect('scroll_event', self.scroll_event) self.connect('button_press_event', self.button_press_event) self.connect('button_release_event', self.button_release_event) self.connect('configure_event', self.configure_event) self.connect('expose_event', self.expose_event) self.connect('key_press_event', self.key_press_event) self.connect('key_release_event', self.key_release_event) self.connect('motion_notify_event', self.motion_notify_event) self.connect('leave_notify_event', self.leave_notify_event) self.connect('enter_notify_event', self.enter_notify_event) self.set_events(self.__class__.event_mask) self.set_double_buffered(False) self.set_flags(gtk.CAN_FOCUS) self._renderer_init() self.last_downclick = {} def destroy(self): #gtk.DrawingArea.destroy(self) self.close_event() if self._idle_draw_id != 0: gobject.source_remove(self._idle_draw_id) def scroll_event(self, widget, event): x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y if event.direction==gdk.SCROLL_UP: step = 1 else: step = -1 FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) return False # finish event propagation? def button_press_event(self, widget, event): x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y dblclick = (event.type == gdk._2BUTTON_PRESS) if not dblclick: # GTK is the only backend that generates a DOWN-UP-DOWN-DBLCLICK-UP event # sequence for a double click. All other backends have a DOWN-UP-DBLCLICK-UP # sequence. In order to provide consistency to matplotlib users, we will # eat the extra DOWN event in the case that we detect it is part of a double # click. # first, get the double click time in milliseconds. current_time = event.get_time() last_time = self.last_downclick.get(event.button,0) dblclick_time = gtk.settings_get_for_screen(gdk.screen_get_default()).get_property('gtk-double-click-time') delta_time = current_time-last_time if delta_time < dblclick_time: del self.last_downclick[event.button] # we do not want to eat more than one event. return False # eat. self.last_downclick[event.button] = current_time FigureCanvasBase.button_press_event(self, x, y, event.button, dblclick=dblclick, guiEvent=event) return False # finish event propagation? def button_release_event(self, widget, event): x = event.x # flipy so y=0 is bottom of canvas y = self.allocation.height - event.y FigureCanvasBase.button_release_event(self, x, y, event.button, guiEvent=event) return False # finish event propagation? def key_press_event(self, widget, event): key = self._get_key(event) FigureCanvasBase.key_press_event(self, key, guiEvent=event) return True # stop event propagation def key_release_event(self, widget, event): key = self._get_key(event) FigureCanvasBase.key_release_event(self, key, guiEvent=event) return True # stop event propagation def motion_notify_event(self, widget, event): if event.is_hint: x, y, state = event.window.get_pointer() else: x, y, state = event.x, event.y, event.state # flipy so y=0 is bottom of canvas y = self.allocation.height - y FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) return False # finish event propagation? def leave_notify_event(self, widget, event): FigureCanvasBase.leave_notify_event(self, event) def enter_notify_event(self, widget, event): x, y, state = event.window.get_pointer() FigureCanvasBase.enter_notify_event(self, event, xy=(x, y)) def _get_key(self, event): if event.keyval in self.keyvald: key = self.keyvald[event.keyval] elif event.keyval < 256: key = chr(event.keyval) else: key = None for key_mask, prefix in ( [gdk.MOD4_MASK, 'super'], [gdk.MOD1_MASK, 'alt'], [gdk.CONTROL_MASK, 'ctrl'], ): if event.state & key_mask: key = '{0}+{1}'.format(prefix, key) return key def configure_event(self, widget, event): if widget.window is None: return w, h = event.width, event.height if w < 3 or h < 3: return # empty fig # resize the figure (in inches) dpi = self.figure.dpi self.figure.set_size_inches(w/dpi, h/dpi, forward=False) self._need_redraw = True return False # finish event propagation? def draw(self): # Note: FigureCanvasBase.draw() is inconveniently named as it clashes # with the deprecated gtk.Widget.draw() self._need_redraw = True if GTK_WIDGET_DRAWABLE(self): self.queue_draw() # do a synchronous draw (its less efficient than an async draw, # but is required if/when animation is used) self.window.process_updates (False) def draw_idle(self): if self._idle_draw_id != 0: return def idle_draw(*args): try: self.draw() finally: self._idle_draw_id = 0 return False self._idle_draw_id = gobject.idle_add(idle_draw) def _renderer_init(self): """Override by GTK backends to select a different renderer Renderer should provide the methods: set_pixmap () set_width_height () that are used by _render_figure() / _pixmap_prepare() """ self._renderer = RendererGDK (self, self.figure.dpi) def _pixmap_prepare(self, width, height): """ Make sure _._pixmap is at least width, height, create new pixmap if necessary """ create_pixmap = False if width > self._pixmap_width: # increase the pixmap in 10%+ (rather than 1 pixel) steps self._pixmap_width = max (int (self._pixmap_width * 1.1), width) create_pixmap = True if height > self._pixmap_height: self._pixmap_height = max (int (self._pixmap_height * 1.1), height) create_pixmap = True if create_pixmap: self._pixmap = gdk.Pixmap (self.window, self._pixmap_width, self._pixmap_height) self._renderer.set_pixmap (self._pixmap) def _render_figure(self, pixmap, width, height): """used by GTK and GTKcairo. GTKAgg overrides """ self._renderer.set_width_height (width, height) self.figure.draw (self._renderer) def expose_event(self, widget, event): """Expose_event for all GTK backends. Should not be overridden. """ toolbar = self.toolbar # if toolbar: # toolbar.set_cursor(cursors.WAIT) if GTK_WIDGET_DRAWABLE(self): if self._need_redraw: x, y, w, h = self.allocation self._pixmap_prepare (w, h) self._render_figure(self._pixmap, w, h) self._need_redraw = False x, y, w, h = event.area self.window.draw_drawable (self.style.fg_gc[self.state], self._pixmap, x, y, x, y, w, h) # if toolbar: # toolbar.set_cursor(toolbar._lastCursor) return False # finish event propagation? filetypes = FigureCanvasBase.filetypes.copy() filetypes['jpg'] = 'JPEG' filetypes['jpeg'] = 'JPEG' filetypes['png'] = 'Portable Network Graphics' def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, 'jpeg') print_jpg = print_jpeg def print_png(self, filename, *args, **kwargs): return self._print_image(filename, 'png') def _print_image(self, filename, format, *args, **kwargs): if self.flags() & gtk.REALIZED == 0: # for self.window(for pixmap) and has a side effect of altering # figure width,height (via configure-event?) gtk.DrawingArea.realize(self) width, height = self.get_width_height() pixmap = gdk.Pixmap (self.window, width, height) self._renderer.set_pixmap (pixmap) self._render_figure(pixmap, width, height) # jpg colors don't match the display very well, png colors match # better pixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, 0, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) # set the default quality, if we are writing a JPEG. # http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html#method-gdkpixbuf--save options = {k: kwargs[k] for k in ['quality'] if k in kwargs} if format in ['jpg', 'jpeg']: options.setdefault('quality', rcParams['savefig.jpeg_quality']) options['quality'] = str(options['quality']) if isinstance(filename, six.string_types): try: pixbuf.save(filename, format, options=options) except gobject.GError as exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) elif is_writable_file_like(filename): if hasattr(pixbuf, 'save_to_callback'): def save_callback(buf, data=None): data.write(buf) try: pixbuf.save_to_callback(save_callback, format, user_data=filename, options=options) except gobject.GError as exc: error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self) else: raise ValueError("Saving to a Python file-like object is only supported by PyGTK >= 2.8") else: raise ValueError("filename must be a path or a file-like object") def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Other Parameters ---------------- interval : scalar Timer interval in milliseconds callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerGTK(*args, **kwargs) def flush_events(self): gtk.gdk.threads_enter() while gtk.events_pending(): gtk.main_iteration(True) gtk.gdk.flush() gtk.gdk.threads_leave() class FigureManagerGTK(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : gtk.Toolbar The gtk.Toolbar (gtk only) vbox : gtk.VBox The gtk.VBox containing the canvas and toolbar (gtk only) window : gtk.Window The gtk.Window (gtk only) """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) self.window = gtk.Window() self.window.set_wmclass("matplotlib", "Matplotlib") self.set_window_title("Figure %d" % num) if window_icon: try: self.window.set_icon_from_file(window_icon) except: # some versions of gtk throw a glib.GError but not # all, so I am not sure how to catch it. I am unhappy # diong a blanket catch here, but an not sure what a # better way is - JDH _log.info('Could not load matplotlib ' 'icon: %s', sys.exc_info()[1]) self.vbox = gtk.VBox() self.window.add(self.vbox) self.vbox.show() self.canvas.show() self.vbox.pack_start(self.canvas, True, True) self.toolbar = self._get_toolbar(canvas) # calculate size for window w = int (self.canvas.figure.bbox.width) h = int (self.canvas.figure.bbox.height) if self.toolbar is not None: self.toolbar.show() self.vbox.pack_end(self.toolbar, False, False) tb_w, tb_h = self.toolbar.size_request() h += tb_h self.window.set_default_size (w, h) def destroy(*args): Gcf.destroy(num) self.window.connect("destroy", destroy) self.window.connect("delete_event", destroy) if matplotlib.is_interactive(): self.window.show() self.canvas.draw_idle() def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar is not None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) self.canvas.grab_focus() def destroy(self, *args): if hasattr(self, 'toolbar') and self.toolbar is not None: self.toolbar.destroy() if hasattr(self, 'vbox'): self.vbox.destroy() if hasattr(self, 'window'): self.window.destroy() if hasattr(self, 'canvas'): self.canvas.destroy() self.__dict__.clear() #Is this needed? Other backends don't have it. if Gcf.get_num_fig_managers()==0 and \ not matplotlib.is_interactive() and \ gtk.main_level() >= 1: gtk.main_quit() def show(self): # show the figure window self.window.show() # raise the window above others and release the "above lock" self.window.set_keep_above(True) self.window.set_keep_above(False) def full_screen_toggle(self): self._full_screen_flag = not self._full_screen_flag if self._full_screen_flag: self.window.fullscreen() else: self.window.unfullscreen() _full_screen_flag = False def _get_toolbar(self, canvas): # must be inited after the window, drawingArea and figure # attrs are set if rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2GTK (canvas, self.window) else: toolbar = None return toolbar def get_window_title(self): return self.window.get_title() def set_window_title(self, title): self.window.set_title(title) def resize(self, width, height): 'set the canvas size in pixels' #_, _, cw, ch = self.canvas.allocation #_, _, ww, wh = self.window.allocation #self.window.resize (width-cw+ww, height-ch+wh) self.window.resize(width, height) class NavigationToolbar2GTK(NavigationToolbar2, gtk.Toolbar): def __init__(self, canvas, window): self.win = window gtk.Toolbar.__init__(self) NavigationToolbar2.__init__(self, canvas) def set_message(self, s): self.message.set_label(s) def set_cursor(self, cursor): self.canvas.window.set_cursor(cursord[cursor]) gtk.main_iteration() def release(self, event): try: del self._pixmapBack except AttributeError: pass def draw_rubberband(self, event, x0, y0, x1, y1): 'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744' drawable = self.canvas.window if drawable is None: return gc = drawable.new_gc() height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 w = abs(x1 - x0) h = abs(y1 - y0) rect = [int(val)for val in (min(x0,x1), min(y0, y1), w, h)] try: lastrect, pixmapBack = self._pixmapBack except AttributeError: #snap image back if event.inaxes is None: return ax = event.inaxes l,b,w,h = [int(val) for val in ax.bbox.bounds] b = int(height)-(b+h) axrect = l,b,w,h self._pixmapBack = axrect, gtk.gdk.Pixmap(drawable, w, h) self._pixmapBack[1].draw_drawable(gc, drawable, l, b, 0, 0, w, h) else: drawable.draw_drawable(gc, pixmapBack, 0, 0, *lastrect) drawable.draw_rectangle(gc, False, *rect) def _init_toolbar(self): self.set_style(gtk.TOOLBAR_ICONS) self._init_toolbar2_4() def _init_toolbar2_4(self): basedir = os.path.join(rcParams['datapath'],'images') if not _new_tooltip_api: self.tooltips = gtk.Tooltips() for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.insert( gtk.SeparatorToolItem(), -1 ) continue fname = os.path.join(basedir, image_file + '.png') image = gtk.Image() image.set_from_file(fname) tbutton = gtk.ToolButton(image, text) self.insert(tbutton, -1) tbutton.connect('clicked', getattr(self, callback)) if _new_tooltip_api: tbutton.set_tooltip_text(tooltip_text) else: tbutton.set_tooltip(self.tooltips, tooltip_text, 'Private') toolitem = gtk.SeparatorToolItem() self.insert(toolitem, -1) # set_draw() not making separator invisible, # bug #143692 fixed Jun 06 2004, will be in GTK+ 2.6 toolitem.set_draw(False) toolitem.set_expand(True) toolitem = gtk.ToolItem() self.insert(toolitem, -1) self.message = gtk.Label() toolitem.add(self.message) self.show_all() def get_filechooser(self): fc = FileChooserDialog( title='Save the figure', parent=self.win, path=os.path.expanduser(rcParams['savefig.directory']), filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) fc.set_current_name(self.canvas.get_default_filename()) return fc def save_figure(self, *args): chooser = self.get_filechooser() fname, format = chooser.get_filename_from_user() chooser.destroy() if fname: startpath = os.path.expanduser(rcParams['savefig.directory']) # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": rcParams['savefig.directory'] = ( os.path.dirname(six.text_type(fname))) try: self.canvas.figure.savefig(fname, format=format) except Exception as e: error_msg_gtk(str(e), parent=self) def configure_subplots(self, button): toolfig = Figure(figsize=(6,3)) canvas = self._get_canvas(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) w = int(toolfig.bbox.width) h = int(toolfig.bbox.height) window = gtk.Window() if window_icon: try: window.set_icon_from_file(window_icon) except: # we presumably already logged a message on the # failure of the main plot, don't keep reporting pass window.set_title("Subplot Configuration Tool") window.set_default_size(w, h) vbox = gtk.VBox() window.add(vbox) vbox.show() canvas.show() vbox.pack_start(canvas, True, True) window.show() def _get_canvas(self, fig): return FigureCanvasGTK(fig) class FileChooserDialog(gtk.FileChooserDialog): """GTK+ 2.4 file selector which presents the user with a menu of supported image formats """ def __init__ (self, title = 'Save file', parent = None, action = gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK), path = None, filetypes = [], default_filetype = None ): super(FileChooserDialog, self).__init__(title, parent, action, buttons) super(FileChooserDialog, self).set_do_overwrite_confirmation(True) self.set_default_response(gtk.RESPONSE_OK) if not path: path = os.getcwd() + os.sep # create an extra widget to list supported image formats self.set_current_folder (path) self.set_current_name ('image.' + default_filetype) hbox = gtk.HBox(spacing=10) hbox.pack_start(gtk.Label ("File Format:"), expand=False) liststore = gtk.ListStore(gobject.TYPE_STRING) cbox = gtk.ComboBox(liststore) cell = gtk.CellRendererText() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) hbox.pack_start(cbox) self.filetypes = filetypes self.sorted_filetypes = sorted(six.iteritems(filetypes)) default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): cbox.append_text("%s (*.%s)" % (name, ext)) if ext == default_filetype: default = i cbox.set_active(default) self.ext = default_filetype def cb_cbox_changed (cbox, data=None): """File extension changed""" head, filename = os.path.split(self.get_filename()) root, ext = os.path.splitext(filename) ext = ext[1:] new_ext = self.sorted_filetypes[cbox.get_active()][0] self.ext = new_ext if ext in self.filetypes: filename = root + '.' + new_ext elif ext == '': filename = filename.rstrip('.') + '.' + new_ext self.set_current_name(filename) cbox.connect("changed", cb_cbox_changed) hbox.show_all() self.set_extra_widget(hbox) def get_filename_from_user (self): while True: filename = None if self.run() != int(gtk.RESPONSE_OK): break filename = self.get_filename() break return filename, self.ext class DialogLineprops(object): """ A GUI dialog for controlling lineprops """ signals = ( 'on_combobox_lineprops_changed', 'on_combobox_linestyle_changed', 'on_combobox_marker_changed', 'on_colorbutton_linestyle_color_set', 'on_colorbutton_markerface_color_set', 'on_dialog_lineprops_okbutton_clicked', 'on_dialog_lineprops_cancelbutton_clicked', ) linestyles = [ls for ls in lines.Line2D.lineStyles if ls.strip()] linestyled = {s: i for i, s in enumerate(linestyles)} markers = [m for m in markers.MarkerStyle.markers if isinstance(m, six.string_types)] markerd = {s: i for i, s in enumerate(markers)} def __init__(self, lines): import gtk.glade datadir = matplotlib.get_data_path() gladefile = os.path.join(datadir, 'lineprops.glade') if not os.path.exists(gladefile): raise IOError( 'Could not find gladefile lineprops.glade in %s' % datadir) self._inited = False self._updateson = True # suppress updates when setting widgets manually self.wtree = gtk.glade.XML(gladefile, 'dialog_lineprops') self.wtree.signal_autoconnect( {s: getattr(self, s) for s in self.signals}) self.dlg = self.wtree.get_widget('dialog_lineprops') self.lines = lines cbox = self.wtree.get_widget('combobox_lineprops') cbox.set_active(0) self.cbox_lineprops = cbox cbox = self.wtree.get_widget('combobox_linestyles') for ls in self.linestyles: cbox.append_text(ls) cbox.set_active(0) self.cbox_linestyles = cbox cbox = self.wtree.get_widget('combobox_markers') for m in self.markers: cbox.append_text(m) cbox.set_active(0) self.cbox_markers = cbox self._lastcnt = 0 self._inited = True def show(self): 'populate the combo box' self._updateson = False # flush the old cbox = self.cbox_lineprops for i in range(self._lastcnt-1,-1,-1): cbox.remove_text(i) # add the new for line in self.lines: cbox.append_text(line.get_label()) cbox.set_active(0) self._updateson = True self._lastcnt = len(self.lines) self.dlg.show() def get_active_line(self): 'get the active line' ind = self.cbox_lineprops.get_active() line = self.lines[ind] return line def get_active_linestyle(self): 'get the active lineinestyle' ind = self.cbox_linestyles.get_active() ls = self.linestyles[ind] return ls def get_active_marker(self): 'get the active lineinestyle' ind = self.cbox_markers.get_active() m = self.markers[ind] return m def _update(self): 'update the active line props from the widgets' if not self._inited or not self._updateson: return line = self.get_active_line() ls = self.get_active_linestyle() marker = self.get_active_marker() line.set_linestyle(ls) line.set_marker(marker) button = self.wtree.get_widget('colorbutton_linestyle') color = button.get_color() r, g, b = [val/65535. for val in (color.red, color.green, color.blue)] line.set_color((r,g,b)) button = self.wtree.get_widget('colorbutton_markerface') color = button.get_color() r, g, b = [val/65535. for val in (color.red, color.green, color.blue)] line.set_markerfacecolor((r,g,b)) line.figure.canvas.draw() def on_combobox_lineprops_changed(self, item): 'update the widgets from the active line' if not self._inited: return self._updateson = False line = self.get_active_line() ls = line.get_linestyle() if ls is None: ls = 'None' self.cbox_linestyles.set_active(self.linestyled[ls]) marker = line.get_marker() if marker is None: marker = 'None' self.cbox_markers.set_active(self.markerd[marker]) rgba = mcolors.to_rgba(line.get_color()) color = gtk.gdk.Color(*[int(val*65535) for val in rgba[:3]]) button = self.wtree.get_widget('colorbutton_linestyle') button.set_color(color) rgba = mcolors.to_rgba(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int(val*65535) for val in rgba[:3]]) button = self.wtree.get_widget('colorbutton_markerface') button.set_color(color) self._updateson = True def on_combobox_linestyle_changed(self, item): self._update() def on_combobox_marker_changed(self, item): self._update() def on_colorbutton_linestyle_color_set(self, button): self._update() def on_colorbutton_markerface_color_set(self, button): 'called colorbutton marker clicked' self._update() def on_dialog_lineprops_okbutton_clicked(self, button): self._update() self.dlg.hide() def on_dialog_lineprops_cancelbutton_clicked(self, button): self.dlg.hide() # set icon used when windows are minimized # Unfortunately, the SVG renderer (rsvg) leaks memory under earlier # versions of pygtk, so we have to use a PNG file instead. try: if gtk.pygtk_version < (2, 8, 0) or sys.platform == 'win32': icon_filename = 'matplotlib.png' else: icon_filename = 'matplotlib.svg' window_icon = os.path.join(rcParams['datapath'], 'images', icon_filename) except: window_icon = None _log.info('Could not load matplotlib icon: %s', sys.exc_info()[1]) def error_msg_gtk(msg, parent=None): if parent is not None: # find the toplevel gtk.Window parent = parent.get_toplevel() if parent.flags() & gtk.TOPLEVEL == 0: parent = None if not isinstance(msg, six.string_types): msg = ','.join(map(str, msg)) dialog = gtk.MessageDialog( parent = parent, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, message_format = msg) dialog.run() dialog.destroy() @_Backend.export class _BackendGTK(_Backend): FigureCanvas = FigureCanvasGTK FigureManager = FigureManagerGTK @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @staticmethod def mainloop(): if gtk.main_level() == 0: gtk.main()
36,244
33.918112
166
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/__init__.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import matplotlib import inspect import traceback import warnings import logging _log = logging.getLogger(__name__) backend = matplotlib.get_backend() _backend_loading_tb = "".join( line for line in traceback.format_stack() # Filter out line noise from importlib line. if not line.startswith(' File "<frozen importlib._bootstrap')) def pylab_setup(name=None): '''return new_figure_manager, draw_if_interactive and show for pyplot This provides the backend-specific functions that are used by pyplot to abstract away the difference between interactive backends. Parameters ---------- name : str, optional The name of the backend to use. If `None`, falls back to ``matplotlib.get_backend()`` (which return :rc:`backend`). Returns ------- backend_mod : module The module which contains the backend of choice new_figure_manager : function Create a new figure manager (roughly maps to GUI window) draw_if_interactive : function Redraw the current figure if pyplot is interactive show : function Show (and possibly block) any unshown figures. ''' # Import the requested backend into a generic module object if name is None: # validates, to match all_backends name = matplotlib.get_backend() if name.startswith('module://'): backend_name = name[9:] else: backend_name = 'backend_' + name backend_name = backend_name.lower() # until we banish mixed case backend_name = 'matplotlib.backends.%s' % backend_name.lower() # the last argument is specifies whether to use absolute or relative # imports. 0 means only perform absolute imports. backend_mod = __import__(backend_name, globals(), locals(), [backend_name], 0) # Things we pull in from all backends new_figure_manager = backend_mod.new_figure_manager # image backends like pdf, agg or svg do not need to do anything # for "show" or "draw_if_interactive", so if they are not defined # by the backend, just do nothing def do_nothing_show(*args, **kwargs): frame = inspect.currentframe() fname = frame.f_back.f_code.co_filename if fname in ('<stdin>', '<ipython console>'): warnings.warn(""" Your currently selected backend, '%s' does not support show(). Please select a GUI backend in your matplotlibrc file ('%s') or with matplotlib.use()""" % (name, matplotlib.matplotlib_fname())) def do_nothing(*args, **kwargs): pass backend_version = getattr(backend_mod, 'backend_version', 'unknown') show = getattr(backend_mod, 'show', do_nothing_show) draw_if_interactive = getattr(backend_mod, 'draw_if_interactive', do_nothing) _log.debug('backend %s version %s', name, backend_version) # need to keep a global reference to the backend for compatibility # reasons. See https://github.com/matplotlib/matplotlib/issues/6092 global backend backend = name return backend_mod, new_figure_manager, draw_if_interactive, show
3,286
32.886598
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/_gtk3_compat.py
""" GObject compatibility loader; supports ``gi`` and ``pgi``. The binding selection rules are as follows: - if ``gi`` has already been imported, use it; else - if ``pgi`` has already been imported, use it; else - if ``gi`` can be imported, use it; else - if ``pgi`` can be imported, use it; else - error out. Thus, to force usage of PGI when both bindings are installed, import it first. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import importlib import sys if "gi" in sys.modules: import gi elif "pgi" in sys.modules: import pgi as gi else: try: import gi except ImportError: try: import pgi as gi except ImportError: raise ImportError("The Gtk3 backend requires PyGObject or pgi") gi.require_version("Gtk", "3.0") globals().update( {name: importlib.import_module("{}.repository.{}".format(gi.__name__, name)) for name in ["GLib", "GObject", "Gtk", "Gdk"]})
1,029
23.52381
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_nbagg.py
"""Interactive figures in the IPython notebook""" # Note: There is a notebook in # lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify # that changes made maintain expected behaviour. import six from base64 import b64encode import io import json import os import uuid from IPython.display import display, Javascript, HTML try: # Jupyter/IPython 4.x or later from ipykernel.comm import Comm except ImportError: # Jupyter/IPython 3.x or earlier from IPython.kernel.comm import Comm from matplotlib import rcParams, is_interactive from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, NavigationToolbar2) from matplotlib.backends.backend_webagg_core import ( FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg, TimerTornado) def connection_info(): """ Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use. """ result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure result.append('{0} - {0}'.format((fig.get_label() or "Figure {0}".format(manager.num)), manager.web_sockets)) if not is_interactive(): result.append('Figures pending show: {0}'.format(len(Gcf._activeQue))) return '\n'.join(result) # Note: Version 3.2 and 4.x icons # http://fontawesome.io/3.2.1/icons/ # http://fontawesome.io/ # the `fa fa-xxx` part targets font-awesome 4, (IPython 3.x) # the icon-xxx targets font awesome 3.21 (IPython 2.x) _FONT_AWESOME_CLASSES = { 'home': 'fa fa-home icon-home', 'back': 'fa fa-arrow-left icon-arrow-left', 'forward': 'fa fa-arrow-right icon-arrow-right', 'zoom_to_rect': 'fa fa-square-o icon-check-empty', 'move': 'fa fa-arrows icon-move', 'download': 'fa fa-floppy-o icon-save', None: None } class NavigationIPy(NavigationToolbar2WebAgg): # Use the standard toolbar items + download button toolitems = [(text, tooltip_text, _FONT_AWESOME_CLASSES[image_file], name_of_method) for text, tooltip_text, image_file, name_of_method in (NavigationToolbar2.toolitems + (('Download', 'Download plot', 'download', 'download'),)) if image_file in _FONT_AWESOME_CLASSES] class FigureManagerNbAgg(FigureManagerWebAgg): ToolbarCls = NavigationIPy def __init__(self, canvas, num): self._shown = False FigureManagerWebAgg.__init__(self, canvas, num) def display_js(self): # XXX How to do this just once? It has to deal with multiple # browser instances using the same kernel (require.js - but the # file isn't static?). display(Javascript(FigureManagerNbAgg.get_javascript())) def show(self): if not self._shown: self.display_js() self._create_comm() else: self.canvas.draw_idle() self._shown = True def reshow(self): """ A special method to re-show the figure in the notebook. """ self._shown = False self.show() @property def connected(self): return bool(self.web_sockets) @classmethod def get_javascript(cls, stream=None): if stream is None: output = io.StringIO() else: output = stream super(FigureManagerNbAgg, cls).get_javascript(stream=output) with io.open(os.path.join( os.path.dirname(__file__), "web_backend", 'js', "nbagg_mpl.js"), encoding='utf8') as fd: output.write(fd.read()) if stream is None: return output.getvalue() def _create_comm(self): comm = CommSocket(self) self.add_web_socket(comm) return comm def destroy(self): self._send_event('close') # need to copy comms as callbacks will modify this list for comm in list(self.web_sockets): comm.on_close() self.clearup_closed() def clearup_closed(self): """Clear up any closed Comms.""" self.web_sockets = set([socket for socket in self.web_sockets if socket.is_open()]) if len(self.web_sockets) == 0: self.canvas.close_event() def remove_comm(self, comm_id): self.web_sockets = set([socket for socket in self.web_sockets if not socket.comm.comm_id == comm_id]) class FigureCanvasNbAgg(FigureCanvasWebAggCore): def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) class CommSocket(object): """ Manages the Comm connection between IPython and the browser (client). Comms are 2 way, with the CommSocket being able to publish a message via the send_json method, and handle a message with on_message. On the JS side figure.send_message and figure.ws.onmessage do the sending and receiving respectively. """ def __init__(self, manager): self.supports_binary = None self.manager = manager self.uuid = str(uuid.uuid4()) # Publish an output area with a unique ID. The javascript can then # hook into this area. display(HTML("<div id=%r></div>" % self.uuid)) try: self.comm = Comm('matplotlib', data={'id': self.uuid}) except AttributeError: raise RuntimeError('Unable to create an IPython notebook Comm ' 'instance. Are you in the IPython notebook?') self.comm.on_msg(self.on_message) manager = self.manager self._ext_close = False def _on_close(close_message): self._ext_close = True manager.remove_comm(close_message['content']['comm_id']) manager.clearup_closed() self.comm.on_close(_on_close) def is_open(self): return not (self._ext_close or self.comm._closed) def on_close(self): # When the socket is closed, deregister the websocket with # the FigureManager. if self.is_open(): try: self.comm.close() except KeyError: # apparently already cleaned it up? pass def send_json(self, content): self.comm.send({'data': json.dumps(content)}) def send_binary(self, blob): # The comm is ascii, so we always send the image in base64 # encoded data URL form. data = b64encode(blob) if six.PY3: data = data.decode('ascii') data_uri = "data:image/png;base64,{0}".format(data) self.comm.send({'data': data_uri}) def on_message(self, message): # The 'supports_binary' message is relevant to the # websocket itself. The other messages get passed along # to matplotlib as-is. # Every message has a "type" and a "figure_id". message = json.loads(message['content']['data']) if message['type'] == 'closing': self.on_close() self.manager.clearup_closed() elif message['type'] == 'supports_binary': self.supports_binary = message['value'] else: self.manager.handle_json(message) @_Backend.export class _BackendNbAgg(_Backend): FigureCanvas = FigureCanvasNbAgg FigureManager = FigureManagerNbAgg @staticmethod def new_figure_manager_given_figure(num, figure): canvas = FigureCanvasNbAgg(figure) manager = FigureManagerNbAgg(canvas, num) if is_interactive(): manager.show() figure.canvas.draw_idle() canvas.mpl_connect('close_event', lambda event: Gcf.destroy(num)) return manager @staticmethod def trigger_manager_draw(manager): manager.show() @staticmethod def show(*args, **kwargs): ## TODO: something to do when keyword block==False ? from matplotlib._pylab_helpers import Gcf managers = Gcf.get_all_fig_managers() if not managers: return interactive = is_interactive() for manager in managers: manager.show() # plt.figure adds an event which puts the figure in focus # in the activeQue. Disable this behaviour, as it results in # figures being put as the active figure after they have been # shown, even in non-interactive mode. if hasattr(manager, '_cidgcf'): manager.canvas.mpl_disconnect(manager._cidgcf) if not interactive and manager in Gcf._activeQue: Gcf._activeQue.remove(manager)
8,839
31.619926
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_qt5.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import functools import os import re import signal import sys from six import unichr import traceback import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors, ToolContainerBase, StatusbarBase) import matplotlib.backends.qt_editor.figureoptions as figureoptions from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool from matplotlib.figure import Figure from matplotlib.backend_managers import ToolManager from matplotlib import backend_tools from .qt_compat import ( QtCore, QtGui, QtWidgets, _getSaveFileName, is_pyqt5, __version__, QT_API) backend_version = __version__ # SPECIAL_KEYS are keys that do *not* return their unicode name # instead they have manually specified names SPECIAL_KEYS = {QtCore.Qt.Key_Control: 'control', QtCore.Qt.Key_Shift: 'shift', QtCore.Qt.Key_Alt: 'alt', QtCore.Qt.Key_Meta: 'super', QtCore.Qt.Key_Return: 'enter', QtCore.Qt.Key_Left: 'left', QtCore.Qt.Key_Up: 'up', QtCore.Qt.Key_Right: 'right', QtCore.Qt.Key_Down: 'down', QtCore.Qt.Key_Escape: 'escape', QtCore.Qt.Key_F1: 'f1', QtCore.Qt.Key_F2: 'f2', QtCore.Qt.Key_F3: 'f3', QtCore.Qt.Key_F4: 'f4', QtCore.Qt.Key_F5: 'f5', QtCore.Qt.Key_F6: 'f6', QtCore.Qt.Key_F7: 'f7', QtCore.Qt.Key_F8: 'f8', QtCore.Qt.Key_F9: 'f9', QtCore.Qt.Key_F10: 'f10', QtCore.Qt.Key_F11: 'f11', QtCore.Qt.Key_F12: 'f12', QtCore.Qt.Key_Home: 'home', QtCore.Qt.Key_End: 'end', QtCore.Qt.Key_PageUp: 'pageup', QtCore.Qt.Key_PageDown: 'pagedown', QtCore.Qt.Key_Tab: 'tab', QtCore.Qt.Key_Backspace: 'backspace', QtCore.Qt.Key_Enter: 'enter', QtCore.Qt.Key_Insert: 'insert', QtCore.Qt.Key_Delete: 'delete', QtCore.Qt.Key_Pause: 'pause', QtCore.Qt.Key_SysReq: 'sysreq', QtCore.Qt.Key_Clear: 'clear', } # define which modifier keys are collected on keyboard events. # elements are (mpl names, Modifier Flag, Qt Key) tuples SUPER = 0 ALT = 1 CTRL = 2 SHIFT = 3 MODIFIER_KEYS = [('super', QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta), ('alt', QtCore.Qt.AltModifier, QtCore.Qt.Key_Alt), ('ctrl', QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control), ('shift', QtCore.Qt.ShiftModifier, QtCore.Qt.Key_Shift), ] if sys.platform == 'darwin': # in OSX, the control and super (aka cmd/apple) keys are switched, so # switch them back. SPECIAL_KEYS.update({QtCore.Qt.Key_Control: 'cmd', # cmd/apple key QtCore.Qt.Key_Meta: 'control', }) MODIFIER_KEYS[0] = ('cmd', QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control) MODIFIER_KEYS[2] = ('ctrl', QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta) cursord = { cursors.MOVE: QtCore.Qt.SizeAllCursor, cursors.HAND: QtCore.Qt.PointingHandCursor, cursors.POINTER: QtCore.Qt.ArrowCursor, cursors.SELECT_REGION: QtCore.Qt.CrossCursor, cursors.WAIT: QtCore.Qt.WaitCursor, } # make place holder qApp = None def _create_qApp(): """ Only one qApp can exist at a time, so check before creating one. """ global qApp if qApp is None: app = QtWidgets.QApplication.instance() if app is None: # check for DISPLAY env variable on X11 build of Qt if is_pyqt5(): try: from PyQt5 import QtX11Extras is_x11_build = True except ImportError: is_x11_build = False else: is_x11_build = hasattr(QtGui, "QX11Info") if is_x11_build: display = os.environ.get('DISPLAY') if display is None or not re.search(r':\d', display): raise RuntimeError('Invalid DISPLAY variable') qApp = QtWidgets.QApplication([b"matplotlib"]) qApp.lastWindowClosed.connect(qApp.quit) else: qApp = app if is_pyqt5(): try: qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) qApp.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) except AttributeError: pass def _allow_super_init(__init__): """ Decorator for ``__init__`` to allow ``super().__init__`` on PyQt4/PySide2. """ if QT_API == "PyQt5": return __init__ else: # To work around lack of cooperative inheritance in PyQt4, PySide, # and PySide2, when calling FigureCanvasQT.__init__, we temporarily # patch QWidget.__init__ by a cooperative version, that first calls # QWidget.__init__ with no additional arguments, and then finds the # next class in the MRO with an __init__ that does support cooperative # inheritance (i.e., not defined by the PyQt4, PySide, PySide2, sip # or Shiboken packages), and manually call its `__init__`, once again # passing the additional arguments. qwidget_init = QtWidgets.QWidget.__init__ def cooperative_qwidget_init(self, *args, **kwargs): qwidget_init(self) mro = type(self).__mro__ next_coop_init = next( cls for cls in mro[mro.index(QtWidgets.QWidget) + 1:] if cls.__module__.split(".")[0] not in [ "PyQt4", "sip", "PySide", "PySide2", "Shiboken"]) next_coop_init.__init__(self, *args, **kwargs) @functools.wraps(__init__) def wrapper(self, **kwargs): try: QtWidgets.QWidget.__init__ = cooperative_qwidget_init __init__(self, **kwargs) finally: # Restore __init__ QtWidgets.QWidget.__init__ = qwidget_init return wrapper class TimerQT(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses Qt timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def __init__(self, *args, **kwargs): TimerBase.__init__(self, *args, **kwargs) # Create a new timer and connect the timeout() signal to the # _on_timer method. self._timer = QtCore.QTimer() self._timer.timeout.connect(self._on_timer) self._timer_set_interval() def _timer_set_single_shot(self): self._timer.setSingleShot(self._single) def _timer_set_interval(self): self._timer.setInterval(self._interval) def _timer_start(self): self._timer.start() def _timer_stop(self): self._timer.stop() class FigureCanvasQT(QtWidgets.QWidget, FigureCanvasBase): # map Qt button codes to MouseEvent's ones: buttond = {QtCore.Qt.LeftButton: 1, QtCore.Qt.MidButton: 2, QtCore.Qt.RightButton: 3, # QtCore.Qt.XButton1: None, # QtCore.Qt.XButton2: None, } @_allow_super_init def __init__(self, figure): _create_qApp() super(FigureCanvasQT, self).__init__(figure=figure) self.figure = figure # We don't want to scale up the figure DPI more than once. # Note, we don't handle a signal for changing DPI yet. figure._original_dpi = figure.dpi self._update_figure_dpi() # In cases with mixed resolution displays, we need to be careful if the # dpi_ratio changes - in this case we need to resize the canvas # accordingly. We could watch for screenChanged events from Qt, but # the issue is that we can't guarantee this will be emitted *before* # the first paintEvent for the canvas, so instead we keep track of the # dpi_ratio value here and in paintEvent we resize the canvas if # needed. self._dpi_ratio_prev = None self._draw_pending = False self._is_drawing = False self._draw_rect_callback = lambda painter: None self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent) self.setMouseTracking(True) self.resize(*self.get_width_height()) # Key auto-repeat enabled by default self._keyautorepeat = True palette = QtGui.QPalette(QtCore.Qt.white) self.setPalette(palette) def _update_figure_dpi(self): dpi = self._dpi_ratio * self.figure._original_dpi self.figure._set_dpi(dpi, forward=False) @property def _dpi_ratio(self): # Not available on Qt4 or some older Qt5. try: # self.devicePixelRatio() returns 0 in rare cases return self.devicePixelRatio() or 1 except AttributeError: return 1 def _update_dpi(self): # As described in __init__ above, we need to be careful in cases with # mixed resolution displays if dpi_ratio is changing between painting # events. # Return whether we triggered a resizeEvent (and thus a paintEvent) # from within this function. if self._dpi_ratio != self._dpi_ratio_prev: # We need to update the figure DPI. self._update_figure_dpi() self._dpi_ratio_prev = self._dpi_ratio # The easiest way to resize the canvas is to emit a resizeEvent # since we implement all the logic for resizing the canvas for # that event. event = QtGui.QResizeEvent(self.size(), self.size()) self.resizeEvent(event) # resizeEvent triggers a paintEvent itself, so we exit this one # (after making sure that the event is immediately handled). return True return False def get_width_height(self): w, h = FigureCanvasBase.get_width_height(self) return int(w / self._dpi_ratio), int(h / self._dpi_ratio) def enterEvent(self, event): FigureCanvasBase.enter_notify_event(self, guiEvent=event) def leaveEvent(self, event): QtWidgets.QApplication.restoreOverrideCursor() FigureCanvasBase.leave_notify_event(self, guiEvent=event) def mouseEventCoords(self, pos): """Calculate mouse coordinates in physical pixels Qt5 use logical pixels, but the figure is scaled to physical pixels for rendering. Transform to physical pixels so that all of the down-stream transforms work as expected. Also, the origin is different and needs to be corrected. """ dpi_ratio = self._dpi_ratio x = pos.x() # flip y so y=0 is bottom of canvas y = self.figure.bbox.height / dpi_ratio - pos.y() return x * dpi_ratio, y * dpi_ratio def mousePressEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, guiEvent=event) def mouseDoubleClickEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, dblclick=True, guiEvent=event) def mouseMoveEvent(self, event): x, y = self.mouseEventCoords(event) FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) def mouseReleaseEvent(self, event): x, y = self.mouseEventCoords(event) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_release_event(self, x, y, button, guiEvent=event) if is_pyqt5(): def wheelEvent(self, event): x, y = self.mouseEventCoords(event) # from QWheelEvent::delta doc if event.pixelDelta().x() == 0 and event.pixelDelta().y() == 0: steps = event.angleDelta().y() / 120 else: steps = event.pixelDelta().y() if steps: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) else: def wheelEvent(self, event): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() # from QWheelEvent::delta doc steps = event.delta() / 120 if event.orientation() == QtCore.Qt.Vertical: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) def keyPressEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_press_event(self, key, guiEvent=event) def keyReleaseEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_release_event(self, key, guiEvent=event) @property def keyAutoRepeat(self): """ If True, enable auto-repeat for key events. """ return self._keyautorepeat @keyAutoRepeat.setter def keyAutoRepeat(self, val): self._keyautorepeat = bool(val) def resizeEvent(self, event): # _dpi_ratio_prev will be set the first time the canvas is painted, and # the rendered buffer is useless before anyways. if self._dpi_ratio_prev is None: return w = event.size().width() * self._dpi_ratio h = event.size().height() * self._dpi_ratio dpival = self.figure.dpi winch = w / dpival hinch = h / dpival self.figure.set_size_inches(winch, hinch, forward=False) # pass back into Qt to let it finish QtWidgets.QWidget.resizeEvent(self, event) # emit our resize events FigureCanvasBase.resize_event(self) def sizeHint(self): w, h = self.get_width_height() return QtCore.QSize(w, h) def minumumSizeHint(self): return QtCore.QSize(10, 10) def _get_key(self, event): if not self._keyautorepeat and event.isAutoRepeat(): return None event_key = event.key() event_mods = int(event.modifiers()) # actually a bitmask # get names of the pressed modifier keys # bit twiddling to pick out modifier keys from event_mods bitmask, # if event_key is a MODIFIER, it should not be duplicated in mods mods = [name for name, mod_key, qt_key in MODIFIER_KEYS if event_key != qt_key and (event_mods & mod_key) == mod_key] try: # for certain keys (enter, left, backspace, etc) use a word for the # key, rather than unicode key = SPECIAL_KEYS[event_key] except KeyError: # unicode defines code points up to 0x0010ffff # QT will use Key_Codes larger than that for keyboard keys that are # are not unicode characters (like multimedia keys) # skip these # if you really want them, you should add them to SPECIAL_KEYS MAX_UNICODE = 0x10ffff if event_key > MAX_UNICODE: return None key = unichr(event_key) # qt delivers capitalized letters. fix capitalization # note that capslock is ignored if 'shift' in mods: mods.remove('shift') else: key = key.lower() mods.reverse() return '+'.join(mods + [key]) def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Other Parameters ---------------- interval : scalar Timer interval in milliseconds callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerQT(*args, **kwargs) def flush_events(self): qApp.processEvents() def start_event_loop(self, timeout=0): if hasattr(self, "_event_loop") and self._event_loop.isRunning(): raise RuntimeError("Event loop already running") self._event_loop = event_loop = QtCore.QEventLoop() if timeout: timer = QtCore.QTimer.singleShot(timeout * 1000, event_loop.quit) event_loop.exec_() def stop_event_loop(self, event=None): if hasattr(self, "_event_loop"): self._event_loop.quit() def draw(self): """Render the figure, and queue a request for a Qt draw. """ # The renderer draw is done here; delaying causes problems with code # that uses the result of the draw() to update plot elements. if self._is_drawing: return self._is_drawing = True try: super(FigureCanvasQT, self).draw() finally: self._is_drawing = False self.update() def draw_idle(self): """Queue redraw of the Agg buffer and request Qt paintEvent. """ # The Agg draw needs to be handled by the same thread matplotlib # modifies the scene graph from. Post Agg draw request to the # current event loop in order to ensure thread affinity and to # accumulate multiple draw requests from event handling. # TODO: queued signal connection might be safer than singleShot if not (self._draw_pending or self._is_drawing): self._draw_pending = True QtCore.QTimer.singleShot(0, self._draw_idle) def _draw_idle(self): if self.height() < 0 or self.width() < 0: self._draw_pending = False if not self._draw_pending: return try: self.draw() except Exception: # Uncaught exceptions are fatal for PyQt5, so catch them instead. traceback.print_exc() finally: self._draw_pending = False def drawRectangle(self, rect): # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs # to be called at the end of paintEvent. if rect is not None: def _draw_rect_callback(painter): pen = QtGui.QPen(QtCore.Qt.black, 1 / self._dpi_ratio, QtCore.Qt.DotLine) painter.setPen(pen) painter.drawRect(*(pt / self._dpi_ratio for pt in rect)) else: def _draw_rect_callback(painter): return self._draw_rect_callback = _draw_rect_callback self.update() class MainWindow(QtWidgets.QMainWindow): closing = QtCore.Signal() def closeEvent(self, event): self.closing.emit() QtWidgets.QMainWindow.closeEvent(self, event) class FigureManagerQT(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : qt.QToolBar The qt.QToolBar window : qt.QMainWindow The qt.QMainWindow """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) self.canvas = canvas self.window = MainWindow() self.window.closing.connect(canvas.close_event) self.window.closing.connect(self._widgetclosed) self.window.setWindowTitle("Figure %d" % num) image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.svg') self.window.setWindowIcon(QtGui.QIcon(image)) # Give the keyboard focus to the figure instead of the # manager; StrongFocus accepts both tab and click to focus and # will enable the canvas to process event w/o clicking. # ClickFocus only takes the focus is the window has been # clicked # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus) self.canvas.setFocus() self.window._destroying = False self.toolmanager = self._get_toolmanager() self.toolbar = self._get_toolbar(self.canvas, self.window) self.statusbar = None if self.toolmanager: backend_tools.add_tools_to_manager(self.toolmanager) if self.toolbar: backend_tools.add_tools_to_container(self.toolbar) self.statusbar = StatusbarQt(self.window, self.toolmanager) if self.toolbar is not None: self.window.addToolBar(self.toolbar) if not self.toolmanager: # add text label to status bar statusbar_label = QtWidgets.QLabel() self.window.statusBar().addWidget(statusbar_label) self.toolbar.message.connect(statusbar_label.setText) tbs_height = self.toolbar.sizeHint().height() else: tbs_height = 0 # resize the main window so it will display the canvas with the # requested size: cs = canvas.sizeHint() sbs = self.window.statusBar().sizeHint() self._status_and_tool_height = tbs_height + sbs.height() height = cs.height() + self._status_and_tool_height self.window.resize(cs.width(), height) self.window.setCentralWidget(self.canvas) if matplotlib.is_interactive(): self.window.show() self.canvas.draw_idle() def notify_axes_change(fig): # This will be called whenever the current axes is changed if self.toolbar is not None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) self.window.raise_() def full_screen_toggle(self): if self.window.isFullScreen(): self.window.showNormal() else: self.window.showFullScreen() def _widgetclosed(self): if self.window._destroying: return self.window._destroying = True try: Gcf.destroy(self.num) except AttributeError: pass # It seems that when the python session is killed, # Gcf can get destroyed before the Gcf.destroy # line is run, leading to a useless AttributeError. def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2QT(canvas, parent, False) elif matplotlib.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarQt(self.toolmanager, self.window) else: toolbar = None return toolbar def _get_toolmanager(self): if matplotlib.rcParams['toolbar'] == 'toolmanager': toolmanager = ToolManager(self.canvas.figure) else: toolmanager = None return toolmanager def resize(self, width, height): 'set the canvas size in pixels' self.window.resize(width, height + self._status_and_tool_height) def show(self): self.window.show() self.window.activateWindow() self.window.raise_() def destroy(self, *args): # check for qApp first, as PySide deletes it in its atexit handler if QtWidgets.QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True self.window.destroyed.connect(self._widgetclosed) if self.toolbar: self.toolbar.destroy() self.window.close() def get_window_title(self): return six.text_type(self.window.windowTitle()) def set_window_title(self, title): self.window.setWindowTitle(title) class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): message = QtCore.Signal(str) def __init__(self, canvas, parent, coordinates=True): """ coordinates: should we show the coordinates on the right? """ self.canvas = canvas self.parent = parent self.coordinates = coordinates self._actions = {} """A mapping of toolitem method names to their QActions""" QtWidgets.QToolBar.__init__(self, parent) NavigationToolbar2.__init__(self, canvas) def _icon(self, name): if is_pyqt5(): name = name.replace('.png', '_large.png') pm = QtGui.QPixmap(os.path.join(self.basedir, name)) if hasattr(pm, 'setDevicePixelRatio'): pm.setDevicePixelRatio(self.canvas._dpi_ratio) return QtGui.QIcon(pm) def _init_toolbar(self): self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images') for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.addSeparator() else: a = self.addAction(self._icon(image_file + '.png'), text, getattr(self, callback)) self._actions[callback] = a if callback in ['zoom', 'pan']: a.setCheckable(True) if tooltip_text is not None: a.setToolTip(tooltip_text) if text == 'Subplots': a = self.addAction(self._icon("qt4_editor_options.png"), 'Customize', self.edit_parameters) a.setToolTip('Edit axis, curve and image parameters') self.buttons = {} # Add the x,y location widget at the right side of the toolbar # The stretch factor is 1 which means any resizing of the toolbar # will resize this label instead of the buttons. if self.coordinates: self.locLabel = QtWidgets.QLabel("", self) self.locLabel.setAlignment( QtCore.Qt.AlignRight | QtCore.Qt.AlignTop) self.locLabel.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored)) labelAction = self.addWidget(self.locLabel) labelAction.setVisible(True) # reference holder for subplots_adjust window self.adj_window = None # Esthetic adjustments - we need to set these explicitly in PyQt5 # otherwise the layout looks different - but we don't want to set it if # not using HiDPI icons otherwise they look worse than before. if is_pyqt5(): self.setIconSize(QtCore.QSize(24, 24)) self.layout().setSpacing(12) if is_pyqt5(): # For some reason, self.setMinimumHeight doesn't seem to carry over to # the actual sizeHint, so override it instead in order to make the # aesthetic adjustments noted above. def sizeHint(self): size = super(NavigationToolbar2QT, self).sizeHint() size.setHeight(max(48, size.height())) return size def edit_parameters(self): allaxes = self.canvas.figure.get_axes() if not allaxes: QtWidgets.QMessageBox.warning( self.parent, "Error", "There are no axes to edit.") return elif len(allaxes) == 1: axes, = allaxes else: titles = [] for axes in allaxes: name = (axes.get_title() or " - ".join(filter(None, [axes.get_xlabel(), axes.get_ylabel()])) or "<anonymous {} (id: {:#x})>".format( type(axes).__name__, id(axes))) titles.append(name) item, ok = QtWidgets.QInputDialog.getItem( self.parent, 'Customize', 'Select axes:', titles, 0, False) if ok: axes = allaxes[titles.index(six.text_type(item))] else: return figureoptions.figure_edit(axes, self) def _update_buttons_checked(self): # sync button checkstates to match active mode self._actions['pan'].setChecked(self._active == 'PAN') self._actions['zoom'].setChecked(self._active == 'ZOOM') def pan(self, *args): super(NavigationToolbar2QT, self).pan(*args) self._update_buttons_checked() def zoom(self, *args): super(NavigationToolbar2QT, self).zoom(*args) self._update_buttons_checked() def set_message(self, s): self.message.emit(s) if self.coordinates: self.locLabel.setText(s) def set_cursor(self, cursor): self.canvas.setCursor(cursord[cursor]) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas.drawRectangle(rect) def remove_rubberband(self): self.canvas.drawRectangle(None) def configure_subplots(self): image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.png') dia = SubplotToolQt(self.canvas.figure, self.parent) dia.setWindowIcon(QtGui.QIcon(image)) dia.exec_() def save_figure(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = sorted(six.iteritems(filetypes)) default_filetype = self.canvas.get_default_filetype() startpath = os.path.expanduser( matplotlib.rcParams['savefig.directory']) start = os.path.join(startpath, self.canvas.get_default_filename()) filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) fname, filter = _getSaveFileName(self.parent, "Choose a filename to save to", start, filters, selectedFilter) if fname: # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": matplotlib.rcParams['savefig.directory'] = ( os.path.dirname(six.text_type(fname))) try: self.canvas.figure.savefig(six.text_type(fname)) except Exception as e: QtWidgets.QMessageBox.critical( self, "Error saving file", six.text_type(e), QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton) class SubplotToolQt(UiSubplotTool): def __init__(self, targetfig, parent): UiSubplotTool.__init__(self, None) self._figure = targetfig for lower, higher in [("bottom", "top"), ("left", "right")]: self._widgets[lower].valueChanged.connect( lambda val: self._widgets[higher].setMinimum(val + .001)) self._widgets[higher].valueChanged.connect( lambda val: self._widgets[lower].setMaximum(val - .001)) self._attrs = ["top", "bottom", "left", "right", "hspace", "wspace"] self._defaults = {attr: vars(self._figure.subplotpars)[attr] for attr in self._attrs} # Set values after setting the range callbacks, but before setting up # the redraw callbacks. self._reset() for attr in self._attrs: self._widgets[attr].valueChanged.connect(self._on_value_changed) for action, method in [("Export values", self._export_values), ("Tight layout", self._tight_layout), ("Reset", self._reset), ("Close", self.close)]: self._widgets[action].clicked.connect(method) def _export_values(self): # Explicitly round to 3 decimals (which is also the spinbox precision) # to avoid numbers of the form 0.100...001. dialog = QtWidgets.QDialog() layout = QtWidgets.QVBoxLayout() dialog.setLayout(layout) text = QtWidgets.QPlainTextEdit() text.setReadOnly(True) layout.addWidget(text) text.setPlainText( ",\n".join("{}={:.3}".format(attr, self._widgets[attr].value()) for attr in self._attrs)) # Adjust the height of the text widget to fit the whole text, plus # some padding. size = text.maximumSize() size.setHeight( QtGui.QFontMetrics(text.document().defaultFont()) .size(0, text.toPlainText()).height() + 20) text.setMaximumSize(size) dialog.exec_() def _on_value_changed(self): self._figure.subplots_adjust(**{attr: self._widgets[attr].value() for attr in self._attrs}) self._figure.canvas.draw_idle() def _tight_layout(self): self._figure.tight_layout() for attr in self._attrs: widget = self._widgets[attr] widget.blockSignals(True) widget.setValue(vars(self._figure.subplotpars)[attr]) widget.blockSignals(False) self._figure.canvas.draw_idle() def _reset(self): for attr, value in self._defaults.items(): self._widgets[attr].setValue(value) class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): def __init__(self, toolmanager, parent): ToolContainerBase.__init__(self, toolmanager) QtWidgets.QToolBar.__init__(self, parent) self._toolitems = {} self._groups = {} self._last = None @property def _icon_extension(self): if is_pyqt5(): return '_large.png' return '.png' def add_toolitem( self, name, group, position, image_file, description, toggle): button = QtWidgets.QToolButton(self) button.setIcon(self._icon(image_file)) button.setText(name) if description: button.setToolTip(description) def handler(): self.trigger_tool(name) if toggle: button.setCheckable(True) button.toggled.connect(handler) else: button.clicked.connect(handler) self._last = button self._toolitems.setdefault(name, []) self._add_to_group(group, name, button, position) self._toolitems[name].append((button, handler)) def _add_to_group(self, group, name, button, position): gr = self._groups.get(group, []) if not gr: sep = self.addSeparator() gr.append(sep) before = gr[position] widget = self.insertWidget(before, button) gr.insert(position, widget) self._groups[group] = gr def _icon(self, name): pm = QtGui.QPixmap(name) if hasattr(pm, 'setDevicePixelRatio'): pm.setDevicePixelRatio(self.toolmanager.canvas._dpi_ratio) return QtGui.QIcon(pm) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for button, handler in self._toolitems[name]: button.toggled.disconnect(handler) button.setChecked(toggled) button.toggled.connect(handler) def remove_toolitem(self, name): for button, handler in self._toolitems[name]: button.setParent(None) del self._toolitems[name] class StatusbarQt(StatusbarBase, QtWidgets.QLabel): def __init__(self, window, *args, **kwargs): StatusbarBase.__init__(self, *args, **kwargs) QtWidgets.QLabel.__init__(self) window.statusBar().addWidget(self) def set_message(self, s): self.setText(s) class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.png') parent = self.canvas.manager.window dia = SubplotToolQt(self.figure, parent) dia.setWindowIcon(QtGui.QIcon(image)) dia.exec_() class SaveFigureQt(backend_tools.SaveFigureBase): def trigger(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = sorted(six.iteritems(filetypes)) default_filetype = self.canvas.get_default_filetype() startpath = os.path.expanduser( matplotlib.rcParams['savefig.directory']) start = os.path.join(startpath, self.canvas.get_default_filename()) filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) parent = self.canvas.manager.window fname, filter = _getSaveFileName(parent, "Choose a filename to save to", start, filters, selectedFilter) if fname: # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": matplotlib.rcParams['savefig.directory'] = ( os.path.dirname(six.text_type(fname))) try: self.canvas.figure.savefig(six.text_type(fname)) except Exception as e: QtWidgets.QMessageBox.critical( self, "Error saving file", six.text_type(e), QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton) class SetCursorQt(backend_tools.SetCursorBase): def set_cursor(self, cursor): self.canvas.setCursor(cursord[cursor]) class RubberbandQt(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas.drawRectangle(rect) def remove_rubberband(self): self.canvas.drawRectangle(None) backend_tools.ToolSaveFigure = SaveFigureQt backend_tools.ToolConfigureSubplots = ConfigureSubplotsQt backend_tools.ToolSetCursor = SetCursorQt backend_tools.ToolRubberband = RubberbandQt def error_msg_qt(msg, parent=None): if not isinstance(msg, six.string_types): msg = ','.join(map(str, msg)) QtWidgets.QMessageBox.warning(None, "Matplotlib", msg, QtGui.QMessageBox.Ok) def exception_handler(type, value, tb): """Handle uncaught exceptions It does not catch SystemExit """ msg = '' # get the filename attribute if available (for IOError) if hasattr(value, 'filename') and value.filename is not None: msg = value.filename + ': ' if hasattr(value, 'strerror') and value.strerror is not None: msg += value.strerror else: msg += six.text_type(value) if len(msg): error_msg_qt(msg) @_Backend.export class _BackendQT5(_Backend): FigureCanvas = FigureCanvasQT FigureManager = FigureManagerQT @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @staticmethod def mainloop(): # allow KeyboardInterrupt exceptions to close the plot window. signal.signal(signal.SIGINT, signal.SIG_DFL) qApp.exec_()
41,139
35.732143
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_wxcairo.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import wx from .backend_cairo import cairo, FigureCanvasCairo, RendererCairo from .backend_wx import ( _BackendWx, _FigureCanvasWxBase, FigureFrameWx, NavigationToolbar2Wx as NavigationToolbar2WxCairo) import wx.lib.wxcairo as wxcairo class FigureFrameWxCairo(FigureFrameWx): def get_canvas(self, fig): return FigureCanvasWxCairo(self, -1, fig) class FigureCanvasWxCairo(_FigureCanvasWxBase, FigureCanvasCairo): """ The FigureCanvas contains the figure and does event handling. In the wxPython backend, it is derived from wxPanel, and (usually) lives inside a frame instantiated by a FigureManagerWx. The parent window probably implements a wxSizer to control the displayed control size - but we give a hint as to our preferred minimum size. """ def __init__(self, parent, id, figure): # _FigureCanvasWxBase should be fixed to have the same signature as # every other FigureCanvas and use cooperative inheritance, but in the # meantime the following will make do. _FigureCanvasWxBase.__init__(self, parent, id, figure) FigureCanvasCairo.__init__(self, figure) self._renderer = RendererCairo(self.figure.dpi) def draw(self, drawDC=None): width = int(self.figure.bbox.width) height = int(self.figure.bbox.height) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) self._renderer.set_ctx_from_surface(surface) self._renderer.set_width_height(width, height) self.figure.draw(self._renderer) self.bitmap = wxcairo.BitmapFromImageSurface(surface) self._isDrawn = True self.gui_repaint(drawDC=drawDC, origin='WXCairo') @_BackendWx.export class _BackendWxCairo(_BackendWx): FigureCanvas = FigureCanvasWxCairo _frame_class = FigureFrameWxCairo
1,965
35.407407
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_webagg.py
""" Displays Agg images in the browser, with interactivity """ from __future__ import (absolute_import, division, print_function, unicode_literals) # The WebAgg backend is divided into two modules: # # - `backend_webagg_core.py` contains code necessary to embed a WebAgg # plot inside of a web application, and communicate in an abstract # way over a web socket. # # - `backend_webagg.py` contains a concrete implementation of a basic # application, implemented with tornado. import six from contextlib import contextmanager import errno import json import os import random import sys import signal import socket import threading try: import tornado except ImportError: raise RuntimeError("The WebAgg backend requires Tornado.") import tornado.web import tornado.ioloop import tornado.websocket from matplotlib import rcParams from matplotlib.backend_bases import _Backend from matplotlib._pylab_helpers import Gcf from . import backend_webagg_core as core from .backend_webagg_core import TimerTornado class ServerThread(threading.Thread): def run(self): tornado.ioloop.IOLoop.instance().start() webagg_server_thread = ServerThread() class FigureCanvasWebAgg(core.FigureCanvasWebAggCore): def show(self): # show the figure window show() def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) class WebAggApplication(tornado.web.Application): initialized = False started = False class FavIcon(tornado.web.RequestHandler): def get(self): image_path = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'mpl-data', 'images') self.set_header('Content-Type', 'image/png') with open(os.path.join(image_path, 'matplotlib.png'), 'rb') as fd: self.write(fd.read()) class SingleFigurePage(tornado.web.RequestHandler): def __init__(self, application, request, **kwargs): self.url_prefix = kwargs.pop('url_prefix', '') tornado.web.RequestHandler.__init__(self, application, request, **kwargs) def get(self, fignum): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request, prefix=self.url_prefix) self.render( "single_figure.html", prefix=self.url_prefix, ws_uri=ws_uri, fig_id=fignum, toolitems=core.NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas) class AllFiguresPage(tornado.web.RequestHandler): def __init__(self, application, request, **kwargs): self.url_prefix = kwargs.pop('url_prefix', '') tornado.web.RequestHandler.__init__(self, application, request, **kwargs) def get(self): ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request, prefix=self.url_prefix) self.render( "all_figures.html", prefix=self.url_prefix, ws_uri=ws_uri, figures=sorted(Gcf.figs.items()), toolitems=core.NavigationToolbar2WebAgg.toolitems) class MplJs(tornado.web.RequestHandler): def get(self): self.set_header('Content-Type', 'application/javascript') js_content = core.FigureManagerWebAgg.get_javascript() self.write(js_content) class Download(tornado.web.RequestHandler): def get(self, fignum, fmt): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) # TODO: Move this to a central location mimetypes = { 'ps': 'application/postscript', 'eps': 'application/postscript', 'pdf': 'application/pdf', 'svg': 'image/svg+xml', 'png': 'image/png', 'jpeg': 'image/jpeg', 'tif': 'image/tiff', 'emf': 'application/emf' } self.set_header('Content-Type', mimetypes.get(fmt, 'binary')) buff = six.BytesIO() manager.canvas.figure.savefig(buff, format=fmt) self.write(buff.getvalue()) class WebSocket(tornado.websocket.WebSocketHandler): supports_binary = True def open(self, fignum): self.fignum = int(fignum) self.manager = Gcf.get_fig_manager(self.fignum) self.manager.add_web_socket(self) if hasattr(self, 'set_nodelay'): self.set_nodelay(True) def on_close(self): self.manager.remove_web_socket(self) def on_message(self, message): message = json.loads(message) # The 'supports_binary' message is on a client-by-client # basis. The others affect the (shared) canvas as a # whole. if message['type'] == 'supports_binary': self.supports_binary = message['value'] else: manager = Gcf.get_fig_manager(self.fignum) # It is possible for a figure to be closed, # but a stale figure UI is still sending messages # from the browser. if manager is not None: manager.handle_json(message) def send_json(self, content): self.write_message(json.dumps(content)) def send_binary(self, blob): if self.supports_binary: self.write_message(blob, binary=True) else: data_uri = "data:image/png;base64,{0}".format( blob.encode('base64').replace('\n', '')) self.write_message(data_uri) def __init__(self, url_prefix=''): if url_prefix: assert url_prefix[0] == '/' and url_prefix[-1] != '/', \ 'url_prefix must start with a "/" and not end with one.' super(WebAggApplication, self).__init__( [ # Static files for the CSS and JS (url_prefix + r'/_static/(.*)', tornado.web.StaticFileHandler, {'path': core.FigureManagerWebAgg.get_static_file_path()}), # An MPL favicon (url_prefix + r'/favicon.ico', self.FavIcon), # The page that contains all of the pieces (url_prefix + r'/([0-9]+)', self.SingleFigurePage, {'url_prefix': url_prefix}), # The page that contains all of the figures (url_prefix + r'/?', self.AllFiguresPage, {'url_prefix': url_prefix}), (url_prefix + r'/js/mpl.js', self.MplJs), # Sends images and events to the browser, and receives # events from the browser (url_prefix + r'/([0-9]+)/ws', self.WebSocket), # Handles the downloading (i.e., saving) of static images (url_prefix + r'/([0-9]+)/download.([a-z0-9.]+)', self.Download), ], template_path=core.FigureManagerWebAgg.get_static_file_path()) @classmethod def initialize(cls, url_prefix='', port=None, address=None): if cls.initialized: return # Create the class instance app = cls(url_prefix=url_prefix) cls.url_prefix = url_prefix # This port selection algorithm is borrowed, more or less # verbatim, from IPython. def random_ports(port, n): """ Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n]. """ for i in range(min(5, n)): yield port + i for i in range(n - 5): yield port + random.randint(-2 * n, 2 * n) success = None if address is None: cls.address = rcParams['webagg.address'] else: cls.address = address cls.port = rcParams['webagg.port'] for port in random_ports(cls.port, rcParams['webagg.port_retries']): try: app.listen(port, cls.address) except socket.error as e: if e.errno != errno.EADDRINUSE: raise else: cls.port = port success = True break if not success: raise SystemExit( "The webagg server could not be started because an available " "port could not be found") cls.initialized = True @classmethod def start(cls): if cls.started: return """ IOLoop.running() was removed as of Tornado 2.4; see for example https://groups.google.com/forum/#!topic/python-tornado/QLMzkpQBGOY Thus there is no correct way to check if the loop has already been launched. We may end up with two concurrently running loops in that unlucky case with all the expected consequences. """ ioloop = tornado.ioloop.IOLoop.instance() def shutdown(): ioloop.stop() print("Server is stopped") sys.stdout.flush() cls.started = False @contextmanager def catch_sigint(): old_handler = signal.signal( signal.SIGINT, lambda sig, frame: ioloop.add_callback_from_signal(shutdown)) try: yield finally: signal.signal(signal.SIGINT, old_handler) # Set the flag to True *before* blocking on ioloop.start() cls.started = True print("Press Ctrl+C to stop WebAgg server") sys.stdout.flush() with catch_sigint(): ioloop.start() def ipython_inline_display(figure): import tornado.template WebAggApplication.initialize() if not webagg_server_thread.is_alive(): webagg_server_thread.start() with open(os.path.join( core.FigureManagerWebAgg.get_static_file_path(), 'ipython_inline_figure.html')) as fd: tpl = fd.read() fignum = figure.number t = tornado.template.Template(tpl) return t.generate( prefix=WebAggApplication.url_prefix, fig_id=fignum, toolitems=core.NavigationToolbar2WebAgg.toolitems, canvas=figure.canvas, port=WebAggApplication.port).decode('utf-8') @_Backend.export class _BackendWebAgg(_Backend): FigureCanvas = FigureCanvasWebAgg FigureManager = core.FigureManagerWebAgg @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @staticmethod def show(): WebAggApplication.initialize() url = "http://127.0.0.1:{port}{prefix}".format( port=WebAggApplication.port, prefix=WebAggApplication.url_prefix) if rcParams['webagg.open_in_browser']: import webbrowser webbrowser.open(url) else: print("To view figure, visit {0}".format(url)) WebAggApplication.start()
11,565
31.951567
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py
from __future__ import absolute_import, division, print_function from .. import cbook from . import tkagg # Paint image to Tk photo blitter extension. from .backend_agg import FigureCanvasAgg from ._backend_tk import ( _BackendTk, FigureCanvasTk, FigureManagerTk, NavigationToolbar2Tk) class FigureCanvasTkAgg(FigureCanvasAgg, FigureCanvasTk): def draw(self): super(FigureCanvasTkAgg, self).draw() tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2) self._master.update_idletasks() def blit(self, bbox=None): tkagg.blit( self._tkphoto, self.renderer._renderer, bbox=bbox, colormode=2) self._master.update_idletasks() @cbook.deprecated("2.2") class FigureManagerTkAgg(FigureManagerTk): pass @cbook.deprecated("2.2") class NavigationToolbar2TkAgg(NavigationToolbar2Tk): pass @_BackendTk.export class _BackendTkAgg(_BackendTk): FigureCanvas = FigureCanvasTkAgg
957
26.371429
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_wxagg.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import wx import matplotlib from matplotlib import cbook from . import wx_compat as wxc from .backend_agg import FigureCanvasAgg from .backend_wx import ( _BackendWx, _FigureCanvasWxBase, FigureFrameWx, NavigationToolbar2Wx as NavigationToolbar2WxAgg) class FigureFrameWxAgg(FigureFrameWx): def get_canvas(self, fig): return FigureCanvasWxAgg(self, -1, fig) class FigureCanvasWxAgg(FigureCanvasAgg, _FigureCanvasWxBase): """ The FigureCanvas contains the figure and does event handling. In the wxPython backend, it is derived from wxPanel, and (usually) lives inside a frame instantiated by a FigureManagerWx. The parent window probably implements a wxSizer to control the displayed control size - but we give a hint as to our preferred minimum size. """ def draw(self, drawDC=None): """ Render the figure using agg. """ FigureCanvasAgg.draw(self) self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self._isDrawn = True self.gui_repaint(drawDC=drawDC, origin='WXAgg') def blit(self, bbox=None): """ Transfer the region of the agg buffer defined by bbox to the display. If bbox is None, the entire buffer is transferred. """ if bbox is None: self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self.gui_repaint() return l, b, w, h = bbox.bounds r = l + w t = b + h x = int(l) y = int(self.bitmap.GetHeight() - t) srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destDC = wx.MemoryDC() destDC.SelectObject(self.bitmap) destDC.Blit(x, y, int(w), int(h), srcDC, x, y) destDC.SelectObject(wx.NullBitmap) srcDC.SelectObject(wx.NullBitmap) self.gui_repaint() filetypes = FigureCanvasAgg.filetypes @cbook.deprecated("2.2", alternative="NavigationToolbar2WxAgg") class Toolbar(NavigationToolbar2WxAgg): pass # agg/wxPython image conversion functions (wxPython >= 2.8) def _convert_agg_to_wx_image(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Image. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgb -> image image = wxc.EmptyImage(int(agg.width), int(agg.height)) image.SetData(agg.tostring_rgb()) return image else: # agg => rgba buffer -> bitmap => clipped bitmap => image return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox)) def _convert_agg_to_wx_bitmap(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgba buffer -> bitmap return wxc.BitmapFromBuffer(int(agg.width), int(agg.height), agg.buffer_rgba()) else: # agg => rgba buffer -> bitmap => clipped bitmap return _WX28_clipped_agg_as_bitmap(agg, bbox) def _WX28_clipped_agg_as_bitmap(agg, bbox): """ Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap. Note: agg must be a backend_agg.RendererAgg instance. """ l, b, width, height = bbox.bounds r = l + width t = b + height srcBmp = wxc.BitmapFromBuffer(int(agg.width), int(agg.height), agg.buffer_rgba()) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destBmp = wxc.EmptyBitmap(int(width), int(height)) destDC = wx.MemoryDC() destDC.SelectObject(destBmp) x = int(l) y = int(int(agg.height) - t) destDC.Blit(0, 0, int(width), int(height), srcDC, x, y) srcDC.SelectObject(wx.NullBitmap) destDC.SelectObject(wx.NullBitmap) return destBmp @_BackendWx.export class _BackendWxAgg(_BackendWx): FigureCanvas = FigureCanvasWxAgg _frame_class = FigureFrameWxAgg
4,326
28.236486
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/backend_pgf.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import atexit import codecs import errno import math import os import re import shutil import sys import tempfile import warnings import weakref import matplotlib as mpl from matplotlib import _png, rcParams from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.cbook import is_writable_file_like from matplotlib.compat import subprocess from matplotlib.compat.subprocess import check_output from matplotlib.path import Path ############################################################################### # create a list of system fonts, all of these should work with xe/lua-latex system_fonts = [] if sys.platform.startswith('win'): from matplotlib import font_manager for f in font_manager.win32InstalledFonts(): try: system_fonts.append(font_manager.get_font(str(f)).family_name) except: pass # unknown error, skip this font else: # assuming fontconfig is installed and the command 'fc-list' exists try: # list scalable (non-bitmap) fonts fc_list = check_output([str('fc-list'), ':outline,scalable', 'family']) fc_list = fc_list.decode('utf8') system_fonts = [f.split(',')[0] for f in fc_list.splitlines()] system_fonts = list(set(system_fonts)) except: warnings.warn('error getting fonts from fc-list', UserWarning) def get_texcommand(): """Get chosen TeX system from rc.""" texsystem_options = ["xelatex", "lualatex", "pdflatex"] texsystem = rcParams["pgf.texsystem"] return texsystem if texsystem in texsystem_options else "xelatex" def get_fontspec(): """Build fontspec preamble from rc.""" latex_fontspec = [] texcommand = get_texcommand() if texcommand != "pdflatex": latex_fontspec.append("\\usepackage{fontspec}") if texcommand != "pdflatex" and rcParams["pgf.rcfonts"]: # try to find fonts from rc parameters families = ["serif", "sans-serif", "monospace"] fontspecs = [r"\setmainfont{%s}", r"\setsansfont{%s}", r"\setmonofont{%s}"] for family, fontspec in zip(families, fontspecs): matches = [f for f in rcParams["font." + family] if f in system_fonts] if matches: latex_fontspec.append(fontspec % matches[0]) else: pass # no fonts found, fallback to LaTeX defaule return "\n".join(latex_fontspec) def get_preamble(): """Get LaTeX preamble from rc.""" return "\n".join(rcParams["pgf.preamble"]) ############################################################################### # This almost made me cry!!! # In the end, it's better to use only one unit for all coordinates, since the # arithmetic in latex seems to produce inaccurate conversions. latex_pt_to_in = 1. / 72.27 latex_in_to_pt = 1. / latex_pt_to_in mpl_pt_to_in = 1. / 72. mpl_in_to_pt = 1. / mpl_pt_to_in ############################################################################### # helper functions NO_ESCAPE = r"(?<!\\)(?:\\\\)*" re_mathsep = re.compile(NO_ESCAPE + r"\$") re_escapetext = re.compile(NO_ESCAPE + "([_^$%])") repl_escapetext = lambda m: "\\" + m.group(1) re_mathdefault = re.compile(NO_ESCAPE + r"(\\mathdefault)") repl_mathdefault = lambda m: m.group(0)[:-len(m.group(1))] def common_texification(text): """ Do some necessary and/or useful substitutions for texts to be included in LaTeX documents. """ # Sometimes, matplotlib adds the unknown command \mathdefault. # Not using \mathnormal instead since this looks odd for the latex cm font. text = re_mathdefault.sub(repl_mathdefault, text) # split text into normaltext and inline math parts parts = re_mathsep.split(text) for i, s in enumerate(parts): if not i % 2: # textmode replacements s = re_escapetext.sub(repl_escapetext, s) else: # mathmode replacements s = r"\(\displaystyle %s\)" % s parts[i] = s return "".join(parts) def writeln(fh, line): # every line of a file included with \\input must be terminated with % # if not, latex will create additional vertical spaces for some reason fh.write(line) fh.write("%\n") def _font_properties_str(prop): # translate font properties to latex commands, return as string commands = [] families = {"serif": r"\rmfamily", "sans": r"\sffamily", "sans-serif": r"\sffamily", "monospace": r"\ttfamily"} family = prop.get_family()[0] if family in families: commands.append(families[family]) elif family in system_fonts and get_texcommand() != "pdflatex": commands.append(r"\setmainfont{%s}\rmfamily" % family) else: pass # print warning? size = prop.get_size_in_points() commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2)) styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"} commands.append(styles[prop.get_style()]) boldstyles = ["semibold", "demibold", "demi", "bold", "heavy", "extra bold", "black"] if prop.get_weight() in boldstyles: commands.append(r"\bfseries") commands.append(r"\selectfont") return "".join(commands) def make_pdf_to_png_converter(): """ Returns a function that converts a pdf file to a png file. """ tools_available = [] # check for pdftocairo try: check_output([str("pdftocairo"), "-v"], stderr=subprocess.STDOUT) tools_available.append("pdftocairo") except: pass # check for ghostscript gs, ver = mpl.checkdep_ghostscript() if gs: tools_available.append("gs") # pick converter if "pdftocairo" in tools_available: def cairo_convert(pdffile, pngfile, dpi): cmd = [str("pdftocairo"), "-singlefile", "-png", "-r", "%d" % dpi, pdffile, os.path.splitext(pngfile)[0]] check_output(cmd, stderr=subprocess.STDOUT) return cairo_convert elif "gs" in tools_available: def gs_convert(pdffile, pngfile, dpi): cmd = [str(gs), '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT', '-dUseCIEColor', '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE', '-sDEVICE=png16m', '-sOutputFile=%s' % pngfile, '-r%d' % dpi, pdffile] check_output(cmd, stderr=subprocess.STDOUT) return gs_convert else: raise RuntimeError("No suitable pdf to png renderer found.") class LatexError(Exception): def __init__(self, message, latex_output=""): Exception.__init__(self, message) self.latex_output = latex_output class LatexManagerFactory(object): previous_instance = None @staticmethod def get_latex_manager(): texcommand = get_texcommand() latex_header = LatexManager._build_latex_header() prev = LatexManagerFactory.previous_instance # Check if the previous instance of LatexManager can be reused. if (prev and prev.latex_header == latex_header and prev.texcommand == texcommand): if rcParams["pgf.debug"]: print("reusing LatexManager") return prev else: if rcParams["pgf.debug"]: print("creating LatexManager") new_inst = LatexManager() LatexManagerFactory.previous_instance = new_inst return new_inst class LatexManager(object): """ The LatexManager opens an instance of the LaTeX application for determining the metrics of text elements. The LaTeX environment can be modified by setting fonts and/or a custem preamble in the rc parameters. """ _unclean_instances = weakref.WeakSet() @staticmethod def _build_latex_header(): latex_preamble = get_preamble() latex_fontspec = get_fontspec() # Create LaTeX header with some content, else LaTeX will load some math # fonts later when we don't expect the additional output on stdout. # TODO: is this sufficient? latex_header = [r"\documentclass{minimal}", latex_preamble, latex_fontspec, r"\begin{document}", r"text $math \mu$", # force latex to load fonts now r"\typeout{pgf_backend_query_start}"] return "\n".join(latex_header) @staticmethod def _cleanup_remaining_instances(): unclean_instances = list(LatexManager._unclean_instances) for latex_manager in unclean_instances: latex_manager._cleanup() def _stdin_writeln(self, s): self.latex_stdin_utf8.write(s) self.latex_stdin_utf8.write("\n") self.latex_stdin_utf8.flush() def _expect(self, s): exp = s.encode("utf8") buf = bytearray() while True: b = self.latex.stdout.read(1) buf += b if buf[-len(exp):] == exp: break if not len(b): raise LatexError("LaTeX process halted", buf.decode("utf8")) return buf.decode("utf8") def _expect_prompt(self): return self._expect("\n*") def __init__(self): # store references for __del__ self._os_path = os.path self._shutil = shutil self._debug = rcParams["pgf.debug"] # create a tmp directory for running latex, remember to cleanup self.tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_lm_") LatexManager._unclean_instances.add(self) # test the LaTeX setup to ensure a clean startup of the subprocess self.texcommand = get_texcommand() self.latex_header = LatexManager._build_latex_header() latex_end = "\n\\makeatletter\n\\@@end\n" try: latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=self.tmpdir) except OSError as e: if e.errno == errno.ENOENT: raise RuntimeError( "Latex command not found. Install %r or change " "pgf.texsystem to the desired command." % self.texcommand) else: raise RuntimeError( "Error starting process %r" % self.texcommand) test_input = self.latex_header + latex_end stdout, stderr = latex.communicate(test_input.encode("utf-8")) if latex.returncode != 0: raise LatexError("LaTeX returned an error, probably missing font " "or error in preamble:\n%s" % stdout) # open LaTeX process for real work latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=self.tmpdir) self.latex = latex self.latex_stdin_utf8 = codecs.getwriter("utf8")(self.latex.stdin) # write header with 'pgf_backend_query_start' token self._stdin_writeln(self._build_latex_header()) # read all lines until our 'pgf_backend_query_start' token appears self._expect("*pgf_backend_query_start") self._expect_prompt() # cache for strings already processed self.str_cache = {} def _cleanup(self): if not self._os_path.isdir(self.tmpdir): return try: self.latex.communicate() self.latex_stdin_utf8.close() self.latex.stdout.close() except: pass try: self._shutil.rmtree(self.tmpdir) LatexManager._unclean_instances.discard(self) except: sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir) def __del__(self): if self._debug: print("deleting LatexManager") self._cleanup() def get_width_height_descent(self, text, prop): """ Get the width, total height and descent for a text typesetted by the current LaTeX environment. """ # apply font properties and define textbox prop_cmds = _font_properties_str(prop) textbox = "\\sbox0{%s %s}" % (prop_cmds, text) # check cache if textbox in self.str_cache: return self.str_cache[textbox] # send textbox to LaTeX and wait for prompt self._stdin_writeln(textbox) try: self._expect_prompt() except LatexError as e: raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" .format(text, e.latex_output)) # typeout width, height and text offset of the last textbox self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}") # read answer from latex and advance to the next prompt try: answer = self._expect_prompt() except LatexError as e: raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" .format(text, e.latex_output)) # parse metrics from the answer string try: width, height, offset = answer.splitlines()[0].split(",") except: raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" .format(text, answer)) w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2]) # the height returned from LaTeX goes from base to top. # the height matplotlib expects goes from bottom to top. self.str_cache[textbox] = (w, h + o, o) return w, h + o, o class RendererPgf(RendererBase): def __init__(self, figure, fh, dummy=False): """ Creates a new PGF renderer that translates any drawing instruction into text commands to be interpreted in a latex pgfpicture environment. Attributes ---------- figure : `matplotlib.figure.Figure` Matplotlib figure to initialize height, width and dpi from. fh : file-like File handle for the output of the drawing commands. """ RendererBase.__init__(self) self.dpi = figure.dpi self.fh = fh self.figure = figure self.image_counter = 0 # get LatexManager instance self.latexManager = LatexManagerFactory.get_latex_manager() if dummy: # dummy==True deactivate all methods nop = lambda *args, **kwargs: None for m in RendererPgf.__dict__: if m.startswith("draw_"): self.__dict__[m] = nop else: # if fh does not belong to a filename, deactivate draw_image if not hasattr(fh, 'name') or not os.path.exists(fh.name): warnings.warn("streamed pgf-code does not support raster " "graphics, consider using the pgf-to-pdf option", UserWarning) self.__dict__["draw_image"] = lambda *args, **kwargs: None def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): writeln(self.fh, r"\begin{pgfscope}") # convert from display units to in f = 1. / self.dpi # set style and clip self._print_pgf_clip(gc) self._print_pgf_path_styles(gc, rgbFace) # build marker definition bl, tr = marker_path.get_extents(marker_trans).get_points() coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f writeln(self.fh, r"\pgfsys@defobject{currentmarker}" r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords) self._print_pgf_path(None, marker_path, marker_trans) self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0, fill=rgbFace is not None) writeln(self.fh, r"}") # draw marker for each vertex for point, code in path.iter_segments(trans, simplify=False): x, y = point[0] * f, point[1] * f writeln(self.fh, r"\begin{pgfscope}") writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y)) writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}") writeln(self.fh, r"\end{pgfscope}") writeln(self.fh, r"\end{pgfscope}") def draw_path(self, gc, path, transform, rgbFace=None): writeln(self.fh, r"\begin{pgfscope}") # draw the path self._print_pgf_clip(gc) self._print_pgf_path_styles(gc, rgbFace) self._print_pgf_path(gc, path, transform, rgbFace) self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0, fill=rgbFace is not None) writeln(self.fh, r"\end{pgfscope}") # if present, draw pattern on top if gc.get_hatch(): writeln(self.fh, r"\begin{pgfscope}") self._print_pgf_path_styles(gc, rgbFace) # combine clip and path for clipping self._print_pgf_clip(gc) self._print_pgf_path(gc, path, transform, rgbFace) writeln(self.fh, r"\pgfusepath{clip}") # build pattern definition writeln(self.fh, r"\pgfsys@defobject{currentpattern}" r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{") writeln(self.fh, r"\begin{pgfscope}") writeln(self.fh, r"\pgfpathrectangle" r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}") writeln(self.fh, r"\pgfusepath{clip}") scale = mpl.transforms.Affine2D().scale(self.dpi) self._print_pgf_path(None, gc.get_hatch_path(), scale) self._pgf_path_draw(stroke=True) writeln(self.fh, r"\end{pgfscope}") writeln(self.fh, r"}") # repeat pattern, filling the bounding rect of the path f = 1. / self.dpi (xmin, ymin), (xmax, ymax) = \ path.get_extents(transform).get_points() xmin, xmax = f * xmin, f * xmax ymin, ymax = f * ymin, f * ymax repx, repy = int(math.ceil(xmax-xmin)), int(math.ceil(ymax-ymin)) writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin)) for iy in range(repy): for ix in range(repx): writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}") writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}") writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx) writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}") writeln(self.fh, r"\end{pgfscope}") def _print_pgf_clip(self, gc): f = 1. / self.dpi # check for clip box bbox = gc.get_clip_rectangle() if bbox: p1, p2 = bbox.get_points() w, h = p2 - p1 coords = p1[0] * f, p1[1] * f, w * f, h * f writeln(self.fh, r"\pgfpathrectangle" r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}" % coords) writeln(self.fh, r"\pgfusepath{clip}") # check for clip path clippath, clippath_trans = gc.get_clip_path() if clippath is not None: self._print_pgf_path(gc, clippath, clippath_trans) writeln(self.fh, r"\pgfusepath{clip}") def _print_pgf_path_styles(self, gc, rgbFace): # cap style capstyles = {"butt": r"\pgfsetbuttcap", "round": r"\pgfsetroundcap", "projecting": r"\pgfsetrectcap"} writeln(self.fh, capstyles[gc.get_capstyle()]) # join style joinstyles = {"miter": r"\pgfsetmiterjoin", "round": r"\pgfsetroundjoin", "bevel": r"\pgfsetbeveljoin"} writeln(self.fh, joinstyles[gc.get_joinstyle()]) # filling has_fill = rgbFace is not None if gc.get_forced_alpha(): fillopacity = strokeopacity = gc.get_alpha() else: strokeopacity = gc.get_rgb()[3] fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0 if has_fill: writeln(self.fh, r"\definecolor{currentfill}{rgb}{%f,%f,%f}" % tuple(rgbFace[:3])) writeln(self.fh, r"\pgfsetfillcolor{currentfill}") if has_fill and fillopacity != 1.0: writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity) # linewidth and color lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt stroke_rgba = gc.get_rgb() writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw) writeln(self.fh, r"\definecolor{currentstroke}{rgb}{%f,%f,%f}" % stroke_rgba[:3]) writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}") if strokeopacity != 1.0: writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity) # line style dash_offset, dash_list = gc.get_dashes() if dash_list is None: writeln(self.fh, r"\pgfsetdash{}{0pt}") else: writeln(self.fh, r"\pgfsetdash{%s}{%fpt}" % ("".join(r"{%fpt}" % dash for dash in dash_list), dash_offset)) def _print_pgf_path(self, gc, path, transform, rgbFace=None): f = 1. / self.dpi # check for clip box / ignore clip for filled paths bbox = gc.get_clip_rectangle() if gc else None if bbox and (rgbFace is None): p1, p2 = bbox.get_points() clip = (p1[0], p1[1], p2[0], p2[1]) else: clip = None # build path for points, code in path.iter_segments(transform, clip=clip): if code == Path.MOVETO: x, y = tuple(points) writeln(self.fh, r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" % (f * x, f * y)) elif code == Path.CLOSEPOLY: writeln(self.fh, r"\pgfpathclose") elif code == Path.LINETO: x, y = tuple(points) writeln(self.fh, r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" % (f * x, f * y)) elif code == Path.CURVE3: cx, cy, px, py = tuple(points) coords = cx * f, cy * f, px * f, py * f writeln(self.fh, r"\pgfpathquadraticcurveto" r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}" % coords) elif code == Path.CURVE4: c1x, c1y, c2x, c2y, px, py = tuple(points) coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f writeln(self.fh, r"\pgfpathcurveto" r"{\pgfqpoint{%fin}{%fin}}" r"{\pgfqpoint{%fin}{%fin}}" r"{\pgfqpoint{%fin}{%fin}}" % coords) def _pgf_path_draw(self, stroke=True, fill=False): actions = [] if stroke: actions.append("stroke") if fill: actions.append("fill") writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions)) def option_scale_image(self): """ pgf backend supports affine transform of image. """ return True def option_image_nocomposite(self): """ return whether to generate a composite image from multiple images on a set of axes """ return not rcParams['image.composite_image'] def draw_image(self, gc, x, y, im, transform=None): h, w = im.shape[:2] if w == 0 or h == 0: return # save the images to png files path = os.path.dirname(self.fh.name) fname = os.path.splitext(os.path.basename(self.fh.name))[0] fname_img = "%s-img%d.png" % (fname, self.image_counter) self.image_counter += 1 _png.write_png(im[::-1], os.path.join(path, fname_img)) # reference the image in the pgf picture writeln(self.fh, r"\begin{pgfscope}") self._print_pgf_clip(gc) f = 1. / self.dpi # from display coords to inch if transform is None: writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f)) w, h = w * f, h * f else: tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() writeln(self.fh, r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" % (tr1 * f, tr2 * f, tr3 * f, tr4 * f, (tr5 + x) * f, (tr6 + y) * f)) w = h = 1 # scale is already included in the transform interp = str(transform is None).lower() # interpolation in PDF reader writeln(self.fh, r"\pgftext[left,bottom]" r"{\pgfimage[interpolate=%s,width=%fin,height=%fin]{%s}}" % (interp, w, h, fname_img)) writeln(self.fh, r"\end{pgfscope}") def draw_tex(self, gc, x, y, s, prop, angle, ismath="TeX!", mtext=None): self.draw_text(gc, x, y, s, prop, angle, ismath, mtext) def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): # prepare string for tex s = common_texification(s) prop_cmds = _font_properties_str(prop) s = r"%s %s" % (prop_cmds, s) writeln(self.fh, r"\begin{pgfscope}") alpha = gc.get_alpha() if alpha != 1.0: writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha) writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha) rgb = tuple(gc.get_rgb())[:3] if rgb != (0, 0, 0): writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb) writeln(self.fh, r"\pgfsetstrokecolor{textcolor}") writeln(self.fh, r"\pgfsetfillcolor{textcolor}") s = r"\color{textcolor}" + s f = 1.0 / self.figure.dpi text_args = [] if mtext and ( (angle == 0 or mtext.get_rotation_mode() == "anchor") and mtext.get_va() != "center_baseline"): # if text anchoring can be supported, get the original coordinates # and add alignment information x, y = mtext.get_transform().transform_point(mtext.get_position()) text_args.append("x=%fin" % (x * f)) text_args.append("y=%fin" % (y * f)) halign = {"left": "left", "right": "right", "center": ""} valign = {"top": "top", "bottom": "bottom", "baseline": "base", "center": ""} text_args.append(halign[mtext.get_ha()]) text_args.append(valign[mtext.get_va()]) else: # if not, use the text layout provided by matplotlib text_args.append("x=%fin" % (x * f)) text_args.append("y=%fin" % (y * f)) text_args.append("left") text_args.append("base") if angle != 0: text_args.append("rotate=%f" % angle) writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s)) writeln(self.fh, r"\end{pgfscope}") def get_text_width_height_descent(self, s, prop, ismath): # check if the math is supposed to be displaystyled s = common_texification(s) # get text metrics in units of latex pt, convert to display units w, h, d = self.latexManager.get_width_height_descent(s, prop) # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in # but having a little bit more space around the text looks better, # plus the bounding box reported by LaTeX is VERY narrow f = mpl_pt_to_in * self.dpi return w * f, h * f, d * f def flipy(self): return False def get_canvas_width_height(self): return self.figure.get_figwidth(), self.figure.get_figheight() def points_to_pixels(self, points): return points * mpl_pt_to_in * self.dpi def new_gc(self): return GraphicsContextPgf() class GraphicsContextPgf(GraphicsContextBase): pass ######################################################################## class TmpDirCleaner(object): remaining_tmpdirs = set() @staticmethod def add(tmpdir): TmpDirCleaner.remaining_tmpdirs.add(tmpdir) @staticmethod def cleanup_remaining_tmpdirs(): for tmpdir in TmpDirCleaner.remaining_tmpdirs: try: shutil.rmtree(tmpdir) except: sys.stderr.write("error deleting tmp directory %s\n" % tmpdir) class FigureCanvasPgf(FigureCanvasBase): filetypes = {"pgf": "LaTeX PGF picture", "pdf": "LaTeX compiled PGF picture", "png": "Portable Network Graphics", } def get_default_filetype(self): return 'pdf' def _print_pgf_to_fh(self, fh, *args, **kwargs): if kwargs.get("dryrun", False): renderer = RendererPgf(self.figure, None, dummy=True) self.figure.draw(renderer) return header_text = """%% Creator: Matplotlib, PGF backend %% %% To include the figure in your LaTeX document, write %% \\input{<filename>.pgf} %% %% Make sure the required packages are loaded in your preamble %% \\usepackage{pgf} %% %% Figures using additional raster images can only be included by \\input if %% they are in the same directory as the main LaTeX file. For loading figures %% from other directories you can use the `import` package %% \\usepackage{import} %% and then include the figures with %% \\import{<path to file>}{<filename>.pgf} %% """ # append the preamble used by the backend as a comment for debugging header_info_preamble = ["%% Matplotlib used the following preamble"] for line in get_preamble().splitlines(): header_info_preamble.append("%% " + line) for line in get_fontspec().splitlines(): header_info_preamble.append("%% " + line) header_info_preamble.append("%%") header_info_preamble = "\n".join(header_info_preamble) # get figure size in inch w, h = self.figure.get_figwidth(), self.figure.get_figheight() dpi = self.figure.get_dpi() # create pgfpicture environment and write the pgf code fh.write(header_text) fh.write(header_info_preamble) fh.write("\n") writeln(fh, r"\begingroup") writeln(fh, r"\makeatletter") writeln(fh, r"\begin{pgfpicture}") writeln(fh, r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}" % (w, h)) writeln(fh, r"\pgfusepath{use as bounding box, clip}") _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None) renderer = MixedModeRenderer(self.figure, w, h, dpi, RendererPgf(self.figure, fh), bbox_inches_restore=_bbox_inches_restore) self.figure.draw(renderer) # end the pgfpicture environment writeln(fh, r"\end{pgfpicture}") writeln(fh, r"\makeatother") writeln(fh, r"\endgroup") def print_pgf(self, fname_or_fh, *args, **kwargs): """ Output pgf commands for drawing the figure so it can be included and rendered in latex documents. """ if kwargs.get("dryrun", False): self._print_pgf_to_fh(None, *args, **kwargs) return # figure out where the pgf is to be written to if isinstance(fname_or_fh, six.string_types): with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh: self._print_pgf_to_fh(fh, *args, **kwargs) elif is_writable_file_like(fname_or_fh): fh = codecs.getwriter("utf-8")(fname_or_fh) self._print_pgf_to_fh(fh, *args, **kwargs) else: raise ValueError("filename must be a path") def _print_pdf_to_fh(self, fh, *args, **kwargs): w, h = self.figure.get_figwidth(), self.figure.get_figheight() try: # create temporary directory for compiling the figure tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_") fname_pgf = os.path.join(tmpdir, "figure.pgf") fname_tex = os.path.join(tmpdir, "figure.tex") fname_pdf = os.path.join(tmpdir, "figure.pdf") # print figure to pgf and compile it with latex self.print_pgf(fname_pgf, *args, **kwargs) latex_preamble = get_preamble() latex_fontspec = get_fontspec() latexcode = """ \\documentclass[12pt]{minimal} \\usepackage[paperwidth=%fin, paperheight=%fin, margin=0in]{geometry} %s %s \\usepackage{pgf} \\begin{document} \\centering \\input{figure.pgf} \\end{document}""" % (w, h, latex_preamble, latex_fontspec) with codecs.open(fname_tex, "w", "utf-8") as fh_tex: fh_tex.write(latexcode) texcommand = get_texcommand() cmdargs = [str(texcommand), "-interaction=nonstopmode", "-halt-on-error", "figure.tex"] try: check_output(cmdargs, stderr=subprocess.STDOUT, cwd=tmpdir) except subprocess.CalledProcessError as e: raise RuntimeError( "%s was not able to process your file.\n\nFull log:\n%s" % (texcommand, e.output)) # copy file contents to target with open(fname_pdf, "rb") as fh_src: shutil.copyfileobj(fh_src, fh) finally: try: shutil.rmtree(tmpdir) except: TmpDirCleaner.add(tmpdir) def print_pdf(self, fname_or_fh, *args, **kwargs): """ Use LaTeX to compile a Pgf generated figure to PDF. """ if kwargs.get("dryrun", False): self._print_pgf_to_fh(None, *args, **kwargs) return # figure out where the pdf is to be written to if isinstance(fname_or_fh, six.string_types): with open(fname_or_fh, "wb") as fh: self._print_pdf_to_fh(fh, *args, **kwargs) elif is_writable_file_like(fname_or_fh): self._print_pdf_to_fh(fname_or_fh, *args, **kwargs) else: raise ValueError("filename must be a path or a file-like object") def _print_png_to_fh(self, fh, *args, **kwargs): converter = make_pdf_to_png_converter() try: # create temporary directory for pdf creation and png conversion tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_") fname_pdf = os.path.join(tmpdir, "figure.pdf") fname_png = os.path.join(tmpdir, "figure.png") # create pdf and try to convert it to png self.print_pdf(fname_pdf, *args, **kwargs) converter(fname_pdf, fname_png, dpi=self.figure.dpi) # copy file contents to target with open(fname_png, "rb") as fh_src: shutil.copyfileobj(fh_src, fh) finally: try: shutil.rmtree(tmpdir) except: TmpDirCleaner.add(tmpdir) def print_png(self, fname_or_fh, *args, **kwargs): """ Use LaTeX to compile a pgf figure to pdf and convert it to png. """ if kwargs.get("dryrun", False): self._print_pgf_to_fh(None, *args, **kwargs) return if isinstance(fname_or_fh, six.string_types): with open(fname_or_fh, "wb") as fh: self._print_png_to_fh(fh, *args, **kwargs) elif is_writable_file_like(fname_or_fh): self._print_png_to_fh(fname_or_fh, *args, **kwargs) else: raise ValueError("filename must be a path or a file-like object") def get_renderer(self): return RendererPgf(self.figure, None, dummy=True) class FigureManagerPgf(FigureManagerBase): def __init__(self, *args): FigureManagerBase.__init__(self, *args) @_Backend.export class _BackendPgf(_Backend): FigureCanvas = FigureCanvasPgf FigureManager = FigureManagerPgf def _cleanup_all(): LatexManager._cleanup_remaining_instances() TmpDirCleaner.cleanup_remaining_tmpdirs() atexit.register(_cleanup_all)
37,119
36.457114
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/qt_editor/figureoptions.py
# -*- coding: utf-8 -*- # # Copyright © 2009 Pierre Raybaut # Licensed under the terms of the MIT License # see the mpl licenses directory for a copy of the license """Module that provides a GUI-based editor for matplotlib's figure options""" from __future__ import (absolute_import, division, print_function, unicode_literals) import six import os.path as osp import re import matplotlib from matplotlib import cm, colors as mcolors, markers, image as mimage import matplotlib.backends.qt_editor.formlayout as formlayout from matplotlib.backends.qt_compat import QtGui def get_icon(name): basedir = osp.join(matplotlib.rcParams['datapath'], 'images') return QtGui.QIcon(osp.join(basedir, name)) LINESTYLES = {'-': 'Solid', '--': 'Dashed', '-.': 'DashDot', ':': 'Dotted', 'None': 'None', } DRAWSTYLES = { 'default': 'Default', 'steps-pre': 'Steps (Pre)', 'steps': 'Steps (Pre)', 'steps-mid': 'Steps (Mid)', 'steps-post': 'Steps (Post)'} MARKERS = markers.MarkerStyle.markers def figure_edit(axes, parent=None): """Edit matplotlib figure options""" sep = (None, None) # separator # Get / General # Cast to builtin floats as they have nicer reprs. xmin, xmax = map(float, axes.get_xlim()) ymin, ymax = map(float, axes.get_ylim()) general = [('Title', axes.get_title()), sep, (None, "<b>X-Axis</b>"), ('Left', xmin), ('Right', xmax), ('Label', axes.get_xlabel()), ('Scale', [axes.get_xscale(), 'linear', 'log', 'logit']), sep, (None, "<b>Y-Axis</b>"), ('Bottom', ymin), ('Top', ymax), ('Label', axes.get_ylabel()), ('Scale', [axes.get_yscale(), 'linear', 'log', 'logit']), sep, ('(Re-)Generate automatic legend', False), ] # Save the unit data xconverter = axes.xaxis.converter yconverter = axes.yaxis.converter xunits = axes.xaxis.get_units() yunits = axes.yaxis.get_units() # Sorting for default labels (_lineXXX, _imageXXX). def cmp_key(label): match = re.match(r"(_line|_image)(\d+)", label) if match: return match.group(1), int(match.group(2)) else: return label, 0 # Get / Curves linedict = {} for line in axes.get_lines(): label = line.get_label() if label == '_nolegend_': continue linedict[label] = line curves = [] def prepare_data(d, init): """Prepare entry for FormLayout. `d` is a mapping of shorthands to style names (a single style may have multiple shorthands, in particular the shorthands `None`, `"None"`, `"none"` and `""` are synonyms); `init` is one shorthand of the initial style. This function returns an list suitable for initializing a FormLayout combobox, namely `[initial_name, (shorthand, style_name), (shorthand, style_name), ...]`. """ # Drop duplicate shorthands from dict (by overwriting them during # the dict comprehension). name2short = {name: short for short, name in d.items()} # Convert back to {shorthand: name}. short2name = {short: name for name, short in name2short.items()} # Find the kept shorthand for the style specified by init. canonical_init = name2short[d[init]] # Sort by representation and prepend the initial value. return ([canonical_init] + sorted(short2name.items(), key=lambda short_and_name: short_and_name[1])) curvelabels = sorted(linedict, key=cmp_key) for label in curvelabels: line = linedict[label] color = mcolors.to_hex( mcolors.to_rgba(line.get_color(), line.get_alpha()), keep_alpha=True) ec = mcolors.to_hex( mcolors.to_rgba(line.get_markeredgecolor(), line.get_alpha()), keep_alpha=True) fc = mcolors.to_hex( mcolors.to_rgba(line.get_markerfacecolor(), line.get_alpha()), keep_alpha=True) curvedata = [ ('Label', label), sep, (None, '<b>Line</b>'), ('Line style', prepare_data(LINESTYLES, line.get_linestyle())), ('Draw style', prepare_data(DRAWSTYLES, line.get_drawstyle())), ('Width', line.get_linewidth()), ('Color (RGBA)', color), sep, (None, '<b>Marker</b>'), ('Style', prepare_data(MARKERS, line.get_marker())), ('Size', line.get_markersize()), ('Face color (RGBA)', fc), ('Edge color (RGBA)', ec)] curves.append([curvedata, label, ""]) # Is there a curve displayed? has_curve = bool(curves) # Get / Images imagedict = {} for image in axes.get_images(): label = image.get_label() if label == '_nolegend_': continue imagedict[label] = image imagelabels = sorted(imagedict, key=cmp_key) images = [] cmaps = [(cmap, name) for name, cmap in sorted(cm.cmap_d.items())] for label in imagelabels: image = imagedict[label] cmap = image.get_cmap() if cmap not in cm.cmap_d.values(): cmaps = [(cmap, cmap.name)] + cmaps low, high = image.get_clim() imagedata = [ ('Label', label), ('Colormap', [cmap.name] + cmaps), ('Min. value', low), ('Max. value', high), ('Interpolation', [image.get_interpolation()] + [(name, name) for name in sorted(mimage.interpolations_names)])] images.append([imagedata, label, ""]) # Is there an image displayed? has_image = bool(images) datalist = [(general, "Axes", "")] if curves: datalist.append((curves, "Curves", "")) if images: datalist.append((images, "Images", "")) def apply_callback(data): """This function will be called to apply changes""" orig_xlim = axes.get_xlim() orig_ylim = axes.get_ylim() general = data.pop(0) curves = data.pop(0) if has_curve else [] images = data.pop(0) if has_image else [] if data: raise ValueError("Unexpected field") # Set / General (title, xmin, xmax, xlabel, xscale, ymin, ymax, ylabel, yscale, generate_legend) = general if axes.get_xscale() != xscale: axes.set_xscale(xscale) if axes.get_yscale() != yscale: axes.set_yscale(yscale) axes.set_title(title) axes.set_xlim(xmin, xmax) axes.set_xlabel(xlabel) axes.set_ylim(ymin, ymax) axes.set_ylabel(ylabel) # Restore the unit data axes.xaxis.converter = xconverter axes.yaxis.converter = yconverter axes.xaxis.set_units(xunits) axes.yaxis.set_units(yunits) axes.xaxis._update_axisinfo() axes.yaxis._update_axisinfo() # Set / Curves for index, curve in enumerate(curves): line = linedict[curvelabels[index]] (label, linestyle, drawstyle, linewidth, color, marker, markersize, markerfacecolor, markeredgecolor) = curve line.set_label(label) line.set_linestyle(linestyle) line.set_drawstyle(drawstyle) line.set_linewidth(linewidth) rgba = mcolors.to_rgba(color) line.set_alpha(None) line.set_color(rgba) if marker is not 'none': line.set_marker(marker) line.set_markersize(markersize) line.set_markerfacecolor(markerfacecolor) line.set_markeredgecolor(markeredgecolor) # Set / Images for index, image_settings in enumerate(images): image = imagedict[imagelabels[index]] label, cmap, low, high, interpolation = image_settings image.set_label(label) image.set_cmap(cm.get_cmap(cmap)) image.set_clim(*sorted([low, high])) image.set_interpolation(interpolation) # re-generate legend, if checkbox is checked if generate_legend: draggable = None ncol = 1 if axes.legend_ is not None: old_legend = axes.get_legend() draggable = old_legend._draggable is not None ncol = old_legend._ncol new_legend = axes.legend(ncol=ncol) if new_legend: new_legend.draggable(draggable) # Redraw figure = axes.get_figure() figure.canvas.draw() if not (axes.get_xlim() == orig_xlim and axes.get_ylim() == orig_ylim): figure.canvas.toolbar.push_current() data = formlayout.fedit(datalist, title="Figure options", parent=parent, icon=get_icon('qt4_editor_options.svg'), apply=apply_callback) if data is not None: apply_callback(data)
9,209
34.019011
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/qt_editor/formsubplottool.py
from matplotlib.backends.qt_compat import QtWidgets class UiSubplotTool(QtWidgets.QDialog): def __init__(self, *args, **kwargs): super(UiSubplotTool, self).__init__(*args, **kwargs) self.setObjectName("SubplotTool") self._widgets = {} layout = QtWidgets.QHBoxLayout() self.setLayout(layout) left = QtWidgets.QVBoxLayout() layout.addLayout(left) right = QtWidgets.QVBoxLayout() layout.addLayout(right) box = QtWidgets.QGroupBox("Borders") left.addWidget(box) inner = QtWidgets.QFormLayout(box) for side in ["top", "bottom", "left", "right"]: self._widgets[side] = widget = QtWidgets.QDoubleSpinBox() widget.setMinimum(0) widget.setMaximum(1) widget.setDecimals(3) widget.setSingleStep(.005) widget.setKeyboardTracking(False) inner.addRow(side, widget) left.addStretch(1) box = QtWidgets.QGroupBox("Spacings") right.addWidget(box) inner = QtWidgets.QFormLayout(box) for side in ["hspace", "wspace"]: self._widgets[side] = widget = QtWidgets.QDoubleSpinBox() widget.setMinimum(0) widget.setMaximum(1) widget.setDecimals(3) widget.setSingleStep(.005) widget.setKeyboardTracking(False) inner.addRow(side, widget) right.addStretch(1) widget = QtWidgets.QPushButton("Export values") self._widgets["Export values"] = widget # Don't trigger on <enter>, which is used to input values. widget.setAutoDefault(False) left.addWidget(widget) for action in ["Tight layout", "Reset", "Close"]: self._widgets[action] = widget = QtWidgets.QPushButton(action) widget.setAutoDefault(False) right.addWidget(widget) self._widgets["Close"].setFocus()
1,953
33.280702
74
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/qt_editor/__init__.py
from __future__ import (absolute_import, division, print_function, unicode_literals)
109
35.666667
66
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/qt_editor/formlayout.py
# -*- 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. """ # 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 from __future__ import (absolute_import, division, print_function, unicode_literals) __version__ = '1.0.10' __license__ = __doc__ import copy import datetime import warnings import six from matplotlib import colors as mcolors from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore BLACKLIST = {"title", "label"} class ColorButton(QtWidgets.QPushButton): """ Color choosing push button """ colorChanged = QtCore.Signal(QtGui.QColor) def __init__(self, parent=None): QtWidgets.QPushButton.__init__(self, parent) self.setFixedSize(20, 20) self.setIconSize(QtCore.QSize(12, 12)) self.clicked.connect(self.choose_color) self._color = QtGui.QColor() def choose_color(self): color = QtWidgets.QColorDialog.getColor( self._color, self.parentWidget(), "", QtWidgets.QColorDialog.ShowAlphaChannel) if color.isValid(): self.set_color(color) def get_color(self): return self._color @QtCore.Slot(QtGui.QColor) def set_color(self, color): if color != self._color: self._color = color self.colorChanged.emit(self._color) pixmap = QtGui.QPixmap(self.iconSize()) pixmap.fill(color) self.setIcon(QtGui.QIcon(pixmap)) color = QtCore.Property(QtGui.QColor, get_color, set_color) def to_qcolor(color): """Create a QColor from a matplotlib color""" qcolor = QtGui.QColor() try: rgba = mcolors.to_rgba(color) except ValueError: warnings.warn('Ignoring invalid color %r' % color) return qcolor # return invalid QColor qcolor.setRgbF(*rgba) return qcolor class ColorLayout(QtWidgets.QHBoxLayout): """Color-specialized QLineEdit layout""" def __init__(self, color, parent=None): QtWidgets.QHBoxLayout.__init__(self) assert isinstance(color, QtGui.QColor) self.lineedit = QtWidgets.QLineEdit( mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent) self.lineedit.editingFinished.connect(self.update_color) self.addWidget(self.lineedit) self.colorbtn = ColorButton(parent) self.colorbtn.color = color self.colorbtn.colorChanged.connect(self.update_text) self.addWidget(self.colorbtn) def update_color(self): color = self.text() qcolor = to_qcolor(color) self.colorbtn.color = qcolor # defaults to black if not qcolor.isValid() def update_text(self, color): self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) def text(self): return self.lineedit.text() def font_is_installed(font): """Check if font is installed""" return [fam for fam in QtGui.QFontDatabase().families() if six.text_type(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) and len(tup) == 4 and font_is_installed(tup[0]) and isinstance(tup[1], int) and isinstance(tup[2], bool) and isinstance(tup[3], bool)): return None font = QtGui.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 (six.text_type(font.family()), int(font.pointSize()), font.italic(), font.bold()) class FontLayout(QtWidgets.QGridLayout): """Font selection""" def __init__(self, value, parent=None): QtWidgets.QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QtWidgets.QFontComboBox(parent) self.family.setCurrentFont(font) self.addWidget(self.family, 0, 0, 1, -1) # Font size self.size = QtWidgets.QComboBox(parent) self.size.setEditable(True) sizelist = list(range(6, 12)) + list(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 = QtWidgets.QCheckBox(self.tr("Italic"), parent) self.italic.setChecked(font.italic()) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QtWidgets.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 == QtGui.QDoubleValidator.Acceptable class FormWidget(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, data, comment="", parent=None): QtWidgets.QWidget.__init__(self, parent) self.data = copy.deepcopy(data) self.widgets = [] self.formlayout = QtWidgets.QFormLayout(self) if comment: self.formlayout.addRow(QtWidgets.QLabel(comment)) self.formlayout.addRow(QtWidgets.QLabel(" ")) def get_dialog(self): """Return FormDialog instance""" dialog = self.parent() while not isinstance(dialog, QtWidgets.QDialog): dialog = dialog.parent() return dialog def setup(self): for label, value in self.data: if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QtWidgets.QLabel(" "), QtWidgets.QLabel(" ")) self.widgets.append(None) continue elif label is None: # Comment self.formlayout.addRow(QtWidgets.QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif (label.lower() not in BLACKLIST and mcolors.is_color_like(value)): field = ColorLayout(to_qcolor(value), self) elif isinstance(value, six.string_types): field = QtWidgets.QLineEdit(value, self) elif isinstance(value, (list, tuple)): if isinstance(value, tuple): value = list(value) selindex = value.pop(0) field = QtWidgets.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): warnings.warn( "index '%s' is invalid (label: %s, value: %s)" % (selindex, label, value)) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QtWidgets.QCheckBox(self) if value: field.setCheckState(QtCore.Qt.Checked) else: field.setCheckState(QtCore.Qt.Unchecked) elif isinstance(value, float): field = QtWidgets.QLineEdit(repr(value), self) field.setCursorPosition(0) field.setValidator(QtGui.QDoubleValidator(field)) field.validator().setLocale(QtCore.QLocale("C")) dialog = self.get_dialog() dialog.register_float_field(field) field.textChanged.connect(lambda text: dialog.update_buttons()) elif isinstance(value, int): field = QtWidgets.QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QtWidgets.QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QtWidgets.QDateEdit(self) field.setDate(value) else: field = QtWidgets.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, six.string_types) or mcolors.is_color_like(value)): value = six.text_type(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() == QtCore.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(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, datalist, comment="", parent=None): QtWidgets.QWidget.__init__(self, parent) layout = QtWidgets.QVBoxLayout() self.setLayout(layout) self.combobox = QtWidgets.QComboBox() layout.addWidget(self.combobox) self.stackwidget = QtWidgets.QStackedWidget(self) layout.addWidget(self.stackwidget) self.combobox.currentIndexChanged.connect(self.stackwidget.setCurrentIndex) 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(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, datalist, comment="", parent=None): QtWidgets.QWidget.__init__(self, parent) layout = QtWidgets.QVBoxLayout() self.tabwidget = QtWidgets.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(QtWidgets.QDialog): """Form Dialog""" def __init__(self, data, title="", comment="", icon=None, parent=None, apply=None): QtWidgets.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 = QtWidgets.QVBoxLayout() layout.addWidget(self.formwidget) self.float_fields = [] self.formwidget.setup() # Button box self.bbox = bbox = QtWidgets.QDialogButtonBox( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) self.formwidget.update_buttons.connect(self.update_buttons) if self.apply_callback is not None: apply_btn = bbox.addButton(QtWidgets.QDialogButtonBox.Apply) apply_btn.clicked.connect(self.apply) bbox.accepted.connect(self.accept) bbox.rejected.connect(self.reject) layout.addWidget(bbox) self.setLayout(layout) self.setWindowTitle(title) if not isinstance(icon, QtGui.QIcon): icon = QtWidgets.QWidget().style().standardIcon(QtWidgets.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 (QtWidgets.QDialogButtonBox.Ok, QtWidgets.QDialogButtonBox.Apply): btn = self.bbox.button(btn_type) if btn is not None: btn.setEnabled(valid) def accept(self): self.data = self.formwidget.get() QtWidgets.QDialog.accept(self) def reject(self): self.data = None QtWidgets.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 QtWidgets.QApplication.startingUp(): _app = QtWidgets.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"))
19,420
34.634862
99
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/web_backend/ipython_inline_figure.html
<!-- Within the kernel, we don't know the address of the matplotlib websocket server, so we have to get in client-side and fetch our resources that way. --> <script> // We can't proceed until these Javascript files are fetched, so // we fetch them synchronously $.ajaxSetup({async: false}); $.getScript("http://" + window.location.hostname + ":{{ port }}{{prefix}}/_static/js/mpl_tornado.js"); $.getScript("http://" + window.location.hostname + ":{{ port }}{{prefix}}/js/mpl.js"); $.ajaxSetup({async: true}); function init_figure{{ fig_id }}(e) { $('div.output').off('resize'); var output_div = $(e.target).find('div.output_subarea'); var websocket_type = mpl.get_websocket_type(); var websocket = new websocket_type( "ws://" + window.location.hostname + ":{{ port }}{{ prefix}}/" + {{ repr(str(fig_id)) }} + "/ws"); var fig = new mpl.figure( {{repr(str(fig_id))}}, websocket, mpl_ondownload, output_div); // Fetch the first image fig.context.drawImage(fig.imageObj, 0, 0); fig.focus_on_mouseover = true; } // We can't initialize the figure contents until our content // has been added to the DOM. This is a bit of hack to get an // event for that. $('div.output').resize(init_figure{{ fig_id }}); </script>
1,305
36.314286
104
html
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/web_backend/single_figure.html
<html> <head> <link rel="stylesheet" href="{{ prefix }}/_static/css/page.css" type="text/css"> <link rel="stylesheet" href="{{ prefix }}/_static/css/boilerplate.css" type="text/css" /> <link rel="stylesheet" href="{{ prefix }}/_static/css/fbm.css" type="text/css" /> <link rel="stylesheet" href="{{ prefix }}/_static/jquery/css/themes/base/jquery-ui.min.css" > <script src="{{ prefix }}/_static/jquery/js/jquery-1.11.3.min.js"></script> <script src="{{ prefix }}/_static/jquery/js/jquery-ui.min.js"></script> <script src="{{ prefix }}/_static/js/mpl_tornado.js"></script> <script src="{{ prefix }}/js/mpl.js"></script> <script> $(document).ready( function() { var websocket_type = mpl.get_websocket_type(); var websocket = new websocket_type( "{{ ws_uri }}" + {{ repr(str(fig_id)) }} + "/ws"); var fig = new mpl.figure( {{repr(str(fig_id))}}, websocket, mpl_ondownload, $('div#figure')); } ); </script> <title>matplotlib</title> </head> <body> <div id="mpl-warnings" class="mpl-warnings"></div> <div id="figure" style="margin: 10px 10px;"></div> </body> </html>
1,203
37.83871
97
html
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/web_backend/all_figures.html
<html> <head> <link rel="stylesheet" href="{{ prefix }}/_static/css/page.css" type="text/css"> <link rel="stylesheet" href="{{ prefix }}/_static/css/boilerplate.css" type="text/css" /> <link rel="stylesheet" href="{{ prefix }}/_static/css/fbm.css" type="text/css" /> <link rel="stylesheet" href="{{ prefix }}/_static/jquery/css/themes/base/jquery-ui.min.css" > <script src="{{ prefix }}/_static/jquery/js/jquery-1.11.3.min.js"></script> <script src="{{ prefix }}/_static/jquery/js/jquery-ui.min.js"></script> <script src="{{ prefix }}/_static/js/mpl_tornado.js"></script> <script src="{{ prefix }}/js/mpl.js"></script> <script> {% for (fig_id, fig_manager) in figures %} $(document).ready( function() { var main_div = $('div#figures'); var figure_div = $('<div id="figure-div"/>') main_div.append(figure_div); var websocket_type = mpl.get_websocket_type(); var websocket = new websocket_type( "{{ ws_uri }}" + "{{ fig_id }}" + "/ws"); var fig = new mpl.figure( "{{ fig_id }}", websocket, mpl_ondownload, figure_div); fig.focus_on_mouseover = true; $(fig.canvas).attr('tabindex', {{ fig_id }}); } ); {% end %} </script> <title>MPL | WebAgg current figures</title> </head> <body> <div id="mpl-warnings" class="mpl-warnings"></div> <div id="figures" style="margin: 10px 10px;"></div> </body> </html>
1,512
33.386364
97
html
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/web_backend/jquery/css/themes/base/jquery-ui.min.css
/*! jQuery UI - v1.11.4 - 2015-03-11 * http://jqueryui.com * Includes: core.css, accordion.css, autocomplete.css, button.css, datepicker.css, dialog.css, draggable.css, menu.css, progressbar.css, resizable.css, selectable.css, selectmenu.css, slider.css, sortable.css, spinner.css, tabs.css, tooltip.css, theme.css * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Trebuchet%20MS%2CTahoma%2CVerdana%2CArial%2Csans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=f6a828&bgTextureHeader=gloss_wave&bgImgOpacityHeader=35&borderColorHeader=e78f08&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=eeeeee&bgTextureContent=highlight_soft&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=333333&iconColorContent=222222&bgColorDefault=f6f6f6&bgTextureDefault=glass&bgImgOpacityDefault=100&borderColorDefault=cccccc&fcDefault=1c94c4&iconColorDefault=ef8c08&bgColorHover=fdf5ce&bgTextureHover=glass&bgImgOpacityHover=100&borderColorHover=fbcb09&fcHover=c77405&iconColorHover=ef8c08&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=fbd850&fcActive=eb8f00&iconColorActive=ef8c08&bgColorHighlight=ffe45c&bgTextureHighlight=highlight_soft&bgImgOpacityHighlight=75&borderColorHighlight=fed22f&fcHighlight=363636&iconColorHighlight=228ef1&bgColorError=b81900&bgTextureError=diagonals_thick&bgImgOpacityError=18&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffd27a&bgColorOverlay=666666&bgTextureOverlay=diagonals_thick&bgImgOpacityOverlay=20&opacityOverlay=50&bgColorShadow=000000&bgTextureShadow=flat&bgImgOpacityShadow=10&opacityShadow=20&thicknessShadow=5px&offsetTopShadow=-5px&offsetLeftShadow=-5px&cornerRadiusShadow=5px * Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */ .ui-helper-hidden{display:none}.ui-helper-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table;border-collapse:collapse}.ui-helper-clearfix:after{clear:both}.ui-helper-clearfix{min-height:0}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-front{z-index:100}.ui-state-disabled{cursor:default!important}.ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-overlay{position:fixed;top:0;left:0;width:100%;height:100%}.ui-accordion .ui-accordion-header{display:block;cursor:pointer;position:relative;margin:2px 0 0 0;padding:.5em .5em .5em .7em;min-height:0;font-size:100%}.ui-accordion .ui-accordion-icons{padding-left:2.2em}.ui-accordion .ui-accordion-icons .ui-accordion-icons{padding-left:2.2em}.ui-accordion .ui-accordion-header .ui-accordion-header-icon{position:absolute;left:.5em;top:50%;margin-top:-8px}.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;overflow:auto}.ui-autocomplete{position:absolute;top:0;left:0;cursor:default}.ui-button{display:inline-block;position:relative;padding:0;line-height:normal;margin-right:.1em;cursor:pointer;vertical-align:middle;text-align:center;overflow:visible}.ui-button,.ui-button:link,.ui-button:visited,.ui-button:hover,.ui-button:active{text-decoration:none}.ui-button-icon-only{width:2.2em}button.ui-button-icon-only{width:2.4em}.ui-button-icons-only{width:3.4em}button.ui-button-icons-only{width:3.7em}.ui-button .ui-button-text{display:block;line-height:normal}.ui-button-text-only .ui-button-text{padding:.4em 1em}.ui-button-icon-only .ui-button-text,.ui-button-icons-only .ui-button-text{padding:.4em;text-indent:-9999999px}.ui-button-text-icon-primary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 1em .4em 2.1em}.ui-button-text-icon-secondary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 2.1em .4em 1em}.ui-button-text-icons .ui-button-text{padding-left:2.1em;padding-right:2.1em}input.ui-button{padding:.4em 1em}.ui-button-icon-only .ui-icon,.ui-button-text-icon-primary .ui-icon,.ui-button-text-icon-secondary .ui-icon,.ui-button-text-icons .ui-icon,.ui-button-icons-only .ui-icon{position:absolute;top:50%;margin-top:-8px}.ui-button-icon-only .ui-icon{left:50%;margin-left:-8px}.ui-button-text-icon-primary .ui-button-icon-primary,.ui-button-text-icons .ui-button-icon-primary,.ui-button-icons-only .ui-button-icon-primary{left:.5em}.ui-button-text-icon-secondary .ui-button-icon-secondary,.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-buttonset{margin-right:7px}.ui-buttonset .ui-button{margin-left:0;margin-right:-.3em}input.ui-button::-moz-focus-inner,button.ui-button::-moz-focus-inner{border:0;padding:0}.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepicker-year{width:45%}.ui-datepicker table{width:100%;font-size:.9em;border-collapse:collapse;margin:0 0 .4em}.ui-datepicker th{padding:.7em .3em;text-align:center;font-weight:bold;border:0}.ui-datepicker td{border:0;padding:1px}.ui-datepicker td span,.ui-datepicker td a{display:block;padding:.2em;text-align:right;text-decoration:none}.ui-datepicker .ui-datepicker-buttonpane{background-image:none;margin:.7em 0 0 0;padding:0 .2em;border-left:0;border-right:0;border-bottom:0}.ui-datepicker .ui-datepicker-buttonpane button{float:right;margin:.5em .2em .4em;cursor:pointer;padding:.2em .6em .3em .6em;width:auto;overflow:visible}.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current{float:left}.ui-datepicker.ui-datepicker-multi{width:auto}.ui-datepicker-multi .ui-datepicker-group{float:left}.ui-datepicker-multi .ui-datepicker-group table{width:95%;margin:0 auto .4em}.ui-datepicker-multi-2 .ui-datepicker-group{width:50%}.ui-datepicker-multi-3 .ui-datepicker-group{width:33.3%}.ui-datepicker-multi-4 .ui-datepicker-group{width:25%}.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-buttonpane{clear:left}.ui-datepicker-row-break{clear:both;width:100%;font-size:0}.ui-datepicker-rtl{direction:rtl}.ui-datepicker-rtl .ui-datepicker-prev{right:2px;left:auto}.ui-datepicker-rtl .ui-datepicker-next{left:2px;right:auto}.ui-datepicker-rtl .ui-datepicker-prev:hover{right:1px;left:auto}.ui-datepicker-rtl .ui-datepicker-next:hover{left:1px;right:auto}.ui-datepicker-rtl .ui-datepicker-buttonpane{clear:right}.ui-datepicker-rtl .ui-datepicker-buttonpane button{float:left}.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current,.ui-datepicker-rtl .ui-datepicker-group{float:right}.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-dialog{overflow:hidden;position:absolute;top:0;left:0;padding:.2em;outline:0}.ui-dialog .ui-dialog-titlebar{padding:.4em 1em;position:relative}.ui-dialog .ui-dialog-title{float:left;margin:.1em 0;white-space:nowrap;width:90%;overflow:hidden;text-overflow:ellipsis}.ui-dialog .ui-dialog-titlebar-close{position:absolute;right:.3em;top:50%;width:20px;margin:-10px 0 0 0;padding:1px;height:20px}.ui-dialog .ui-dialog-content{position:relative;border:0;padding:.5em 1em;background:none;overflow:auto}.ui-dialog .ui-dialog-buttonpane{text-align:left;border-width:1px 0 0 0;background-image:none;margin-top:.5em;padding:.3em 1em .5em .4em}.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset{float:right}.ui-dialog .ui-dialog-buttonpane button{margin:.5em .4em .5em 0;cursor:pointer}.ui-dialog .ui-resizable-se{width:12px;height:12px;right:-5px;bottom:-5px;background-position:16px 16px}.ui-draggable .ui-dialog-titlebar{cursor:move}.ui-draggable-handle{-ms-touch-action:none;touch-action:none}.ui-menu{list-style:none;padding:0;margin:0;display:block;outline:none}.ui-menu .ui-menu{position:absolute}.ui-menu .ui-menu-item{position:relative;margin:0;padding:3px 1em 3px .4em;cursor:pointer;min-height:0;list-style-image:url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")}.ui-menu .ui-menu-divider{margin:5px 0;height:0;font-size:0;line-height:0;border-width:1px 0 0 0}.ui-menu .ui-state-focus,.ui-menu .ui-state-active{margin:-1px}.ui-menu-icons{position:relative}.ui-menu-icons .ui-menu-item{padding-left:2em}.ui-menu .ui-icon{position:absolute;top:0;bottom:0;left:.2em;margin:auto 0}.ui-menu .ui-menu-icon{left:auto;right:0}.ui-progressbar{height:2em;text-align:left;overflow:hidden}.ui-progressbar .ui-progressbar-value{margin:-1px;height:100%}.ui-progressbar .ui-progressbar-overlay{background:url("data:image/gif;base64,R0lGODlhKAAoAIABAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAQABACwAAAAAKAAoAAACkYwNqXrdC52DS06a7MFZI+4FHBCKoDeWKXqymPqGqxvJrXZbMx7Ttc+w9XgU2FB3lOyQRWET2IFGiU9m1frDVpxZZc6bfHwv4c1YXP6k1Vdy292Fb6UkuvFtXpvWSzA+HycXJHUXiGYIiMg2R6W459gnWGfHNdjIqDWVqemH2ekpObkpOlppWUqZiqr6edqqWQAAIfkECQEAAQAsAAAAACgAKAAAApSMgZnGfaqcg1E2uuzDmmHUBR8Qil95hiPKqWn3aqtLsS18y7G1SzNeowWBENtQd+T1JktP05nzPTdJZlR6vUxNWWjV+vUWhWNkWFwxl9VpZRedYcflIOLafaa28XdsH/ynlcc1uPVDZxQIR0K25+cICCmoqCe5mGhZOfeYSUh5yJcJyrkZWWpaR8doJ2o4NYq62lAAACH5BAkBAAEALAAAAAAoACgAAAKVDI4Yy22ZnINRNqosw0Bv7i1gyHUkFj7oSaWlu3ovC8GxNso5fluz3qLVhBVeT/Lz7ZTHyxL5dDalQWPVOsQWtRnuwXaFTj9jVVh8pma9JjZ4zYSj5ZOyma7uuolffh+IR5aW97cHuBUXKGKXlKjn+DiHWMcYJah4N0lYCMlJOXipGRr5qdgoSTrqWSq6WFl2ypoaUAAAIfkECQEAAQAsAAAAACgAKAAAApaEb6HLgd/iO7FNWtcFWe+ufODGjRfoiJ2akShbueb0wtI50zm02pbvwfWEMWBQ1zKGlLIhskiEPm9R6vRXxV4ZzWT2yHOGpWMyorblKlNp8HmHEb/lCXjcW7bmtXP8Xt229OVWR1fod2eWqNfHuMjXCPkIGNileOiImVmCOEmoSfn3yXlJWmoHGhqp6ilYuWYpmTqKUgAAIfkECQEAAQAsAAAAACgAKAAAApiEH6kb58biQ3FNWtMFWW3eNVcojuFGfqnZqSebuS06w5V80/X02pKe8zFwP6EFWOT1lDFk8rGERh1TTNOocQ61Hm4Xm2VexUHpzjymViHrFbiELsefVrn6XKfnt2Q9G/+Xdie499XHd2g4h7ioOGhXGJboGAnXSBnoBwKYyfioubZJ2Hn0RuRZaflZOil56Zp6iioKSXpUAAAh+QQJAQABACwAAAAAKAAoAAACkoQRqRvnxuI7kU1a1UU5bd5tnSeOZXhmn5lWK3qNTWvRdQxP8qvaC+/yaYQzXO7BMvaUEmJRd3TsiMAgswmNYrSgZdYrTX6tSHGZO73ezuAw2uxuQ+BbeZfMxsexY35+/Qe4J1inV0g4x3WHuMhIl2jXOKT2Q+VU5fgoSUI52VfZyfkJGkha6jmY+aaYdirq+lQAACH5BAkBAAEALAAAAAAoACgAAAKWBIKpYe0L3YNKToqswUlvznigd4wiR4KhZrKt9Upqip61i9E3vMvxRdHlbEFiEXfk9YARYxOZZD6VQ2pUunBmtRXo1Lf8hMVVcNl8JafV38aM2/Fu5V16Bn63r6xt97j09+MXSFi4BniGFae3hzbH9+hYBzkpuUh5aZmHuanZOZgIuvbGiNeomCnaxxap2upaCZsq+1kAACH5BAkBAAEALAAAAAAoACgAAAKXjI8By5zf4kOxTVrXNVlv1X0d8IGZGKLnNpYtm8Lr9cqVeuOSvfOW79D9aDHizNhDJidFZhNydEahOaDH6nomtJjp1tutKoNWkvA6JqfRVLHU/QUfau9l2x7G54d1fl995xcIGAdXqMfBNadoYrhH+Mg2KBlpVpbluCiXmMnZ2Sh4GBqJ+ckIOqqJ6LmKSllZmsoq6wpQAAAh+QQJAQABACwAAAAAKAAoAAAClYx/oLvoxuJDkU1a1YUZbJ59nSd2ZXhWqbRa2/gF8Gu2DY3iqs7yrq+xBYEkYvFSM8aSSObE+ZgRl1BHFZNr7pRCavZ5BW2142hY3AN/zWtsmf12p9XxxFl2lpLn1rseztfXZjdIWIf2s5dItwjYKBgo9yg5pHgzJXTEeGlZuenpyPmpGQoKOWkYmSpaSnqKileI2FAAACH5BAkBAAEALAAAAAAoACgAAAKVjB+gu+jG4kORTVrVhRlsnn2dJ3ZleFaptFrb+CXmO9OozeL5VfP99HvAWhpiUdcwkpBH3825AwYdU8xTqlLGhtCosArKMpvfa1mMRae9VvWZfeB2XfPkeLmm18lUcBj+p5dnN8jXZ3YIGEhYuOUn45aoCDkp16hl5IjYJvjWKcnoGQpqyPlpOhr3aElaqrq56Bq7VAAAOw==");height:100%;filter:alpha(opacity=25);opacity:0.25}.ui-progressbar-indeterminate .ui-progressbar-value{background-image:none}.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block;-ms-touch-action:none;touch-action:none}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}.ui-selectable{-ms-touch-action:none;touch-action:none}.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}.ui-selectmenu-menu{padding:0;margin:0;position:absolute;top:0;left:0;display:none}.ui-selectmenu-menu .ui-menu{overflow:auto;overflow-x:hidden;padding-bottom:1px}.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup{font-size:1em;font-weight:bold;line-height:1.5;padding:2px 0.4em;margin:0.5em 0 0 0;height:auto;border:0}.ui-selectmenu-open{display:block}.ui-selectmenu-button{display:inline-block;overflow:hidden;position:relative;text-decoration:none;cursor:pointer}.ui-selectmenu-button span.ui-icon{right:0.5em;left:auto;margin-top:-8px;position:absolute;top:50%}.ui-selectmenu-button span.ui-selectmenu-text{text-align:left;padding:0.4em 2.1em 0.4em 1em;display:block;line-height:1.4;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ui-slider{position:relative;text-align:left}.ui-slider .ui-slider-handle{position:absolute;z-index:2;width:1.2em;height:1.2em;cursor:default;-ms-touch-action:none;touch-action:none}.ui-slider .ui-slider-range{position:absolute;z-index:1;font-size:.7em;display:block;border:0;background-position:0 0}.ui-slider.ui-state-disabled .ui-slider-handle,.ui-slider.ui-state-disabled .ui-slider-range{filter:inherit}.ui-slider-horizontal{height:.8em}.ui-slider-horizontal .ui-slider-handle{top:-.3em;margin-left:-.6em}.ui-slider-horizontal .ui-slider-range{top:0;height:100%}.ui-slider-horizontal .ui-slider-range-min{left:0}.ui-slider-horizontal .ui-slider-range-max{right:0}.ui-slider-vertical{width:.8em;height:100px}.ui-slider-vertical .ui-slider-handle{left:-.3em;margin-left:0;margin-bottom:-.6em}.ui-slider-vertical .ui-slider-range{left:0;width:100%}.ui-slider-vertical .ui-slider-range-min{bottom:0}.ui-slider-vertical .ui-slider-range-max{top:0}.ui-sortable-handle{-ms-touch-action:none;touch-action:none}.ui-spinner{position:relative;display:inline-block;overflow:hidden;padding:0;vertical-align:middle}.ui-spinner-input{border:none;background:none;color:inherit;padding:0;margin:.2em 0;vertical-align:middle;margin-left:.4em;margin-right:22px}.ui-spinner-button{width:16px;height:50%;font-size:.5em;padding:0;margin:0;text-align:center;position:absolute;cursor:default;display:block;overflow:hidden;right:0}.ui-spinner a.ui-spinner-button{border-top:none;border-bottom:none;border-right:none}.ui-spinner .ui-icon{position:absolute;margin-top:-8px;top:50%;left:0}.ui-spinner-up{top:0}.ui-spinner-down{bottom:0}.ui-spinner .ui-icon-triangle-1-s{background-position:-65px -16px}.ui-tabs{position:relative;padding:.2em}.ui-tabs .ui-tabs-nav{margin:0;padding:.2em .2em 0}.ui-tabs .ui-tabs-nav li{list-style:none;float:left;position:relative;top:0;margin:1px .2em 0 0;border-bottom-width:0;padding:0;white-space:nowrap}.ui-tabs .ui-tabs-nav .ui-tabs-anchor{float:left;padding:.5em 1em;text-decoration:none}.ui-tabs .ui-tabs-nav li.ui-tabs-active{margin-bottom:-1px;padding-bottom:1px}.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor{cursor:text}.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor{cursor:pointer}.ui-tabs .ui-tabs-panel{display:block;border-width:0;padding:1em 1.4em;background:none}.ui-tooltip{padding:8px;position:absolute;z-index:9999;max-width:300px;-webkit-box-shadow:0 0 5px #aaa;box-shadow:0 0 5px #aaa}body .ui-tooltip{border-width:2px}.ui-widget{font-family:Trebuchet MS,Tahoma,Verdana,Arial,sans-serif;font-size:1.1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Trebuchet MS,Tahoma,Verdana,Arial,sans-serif;font-size:1em}.ui-widget-content{border:1px solid #ddd;background:#eee url("images/ui-bg_highlight-soft_100_eeeeee_1x100.png") 50% top repeat-x;color:#333}.ui-widget-content a{color:#333}.ui-widget-header{border:1px solid #e78f08;background:#f6a828 url("images/ui-bg_gloss-wave_35_f6a828_500x100.png") 50% 50% repeat-x;color:#fff;font-weight:bold}.ui-widget-header a{color:#fff}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default{border:1px solid #ccc;background:#f6f6f6 url("images/ui-bg_glass_100_f6f6f6_1x400.png") 50% 50% repeat-x;font-weight:bold;color:#1c94c4}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited{color:#1c94c4;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus{border:1px solid #fbcb09;background:#fdf5ce url("images/ui-bg_glass_100_fdf5ce_1x400.png") 50% 50% repeat-x;font-weight:bold;color:#c77405}.ui-state-hover a,.ui-state-hover a:hover,.ui-state-hover a:link,.ui-state-hover a:visited,.ui-state-focus a,.ui-state-focus a:hover,.ui-state-focus a:link,.ui-state-focus a:visited{color:#c77405;text-decoration:none}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active{border:1px solid #fbd850;background:#fff url("images/ui-bg_glass_65_ffffff_1x400.png") 50% 50% repeat-x;font-weight:bold;color:#eb8f00}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#eb8f00;text-decoration:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #fed22f;background:#ffe45c url("images/ui-bg_highlight-soft_75_ffe45c_1x100.png") 50% top repeat-x;color:#363636}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#363636}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #cd0a0a;background:#b81900 url("images/ui-bg_diagonals-thick_18_b81900_40x40.png") 50% 50% repeat;color:#fff}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#fff}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#fff}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-state-disabled .ui-icon{filter:Alpha(Opacity=35)}.ui-icon{width:16px;height:16px}.ui-icon,.ui-widget-content .ui-icon{background-image:url("images/ui-icons_222222_256x240.png")}.ui-widget-header .ui-icon{background-image:url("images/ui-icons_ffffff_256x240.png")}.ui-state-default .ui-icon{background-image:url("images/ui-icons_ef8c08_256x240.png")}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon{background-image:url("images/ui-icons_ef8c08_256x240.png")}.ui-state-active .ui-icon{background-image:url("images/ui-icons_ef8c08_256x240.png")}.ui-state-highlight .ui-icon{background-image:url("images/ui-icons_228ef1_256x240.png")}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url("images/ui-icons_ffd27a_256x240.png")}.ui-icon-blank{background-position:16px 16px}.ui-icon-carat-1-n{background-position:0 0}.ui-icon-carat-1-ne{background-position:-16px 0}.ui-icon-carat-1-e{background-position:-32px 0}.ui-icon-carat-1-se{background-position:-48px 0}.ui-icon-carat-1-s{background-position:-64px 0}.ui-icon-carat-1-sw{background-position:-80px 0}.ui-icon-carat-1-w{background-position:-96px 0}.ui-icon-carat-1-nw{background-position:-112px 0}.ui-icon-carat-2-n-s{background-position:-128px 0}.ui-icon-carat-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-64px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-64px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:0 -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-on{background-position:-96px -144px}.ui-icon-radio-off{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{border-top-left-radius:4px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{border-top-right-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{border-bottom-left-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{border-bottom-right-radius:4px}.ui-widget-overlay{background:#666 url("images/ui-bg_diagonals-thick_20_666666_40x40.png") 50% 50% repeat;opacity:.5;filter:Alpha(Opacity=50)}.ui-widget-shadow{margin:-5px 0 0 -5px;padding:5px;background:#000 url("images/ui-bg_flat_10_000000_40x100.png") 50% 50% repeat-x;opacity:.2;filter:Alpha(Opacity=20);border-radius:5px}
30,163
4,308.142857
28,367
css
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/web_backend/css/page.css
/** * Primary styles * * Author: IPython Development Team */ body { background-color: white; /* This makes sure that the body covers the entire window and needs to be in a different element than the display: box in wrapper below */ position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; overflow: visible; } div#header { /* Initially hidden to prevent FLOUC */ display: none; position: relative; height: 40px; padding: 5px; margin: 0px; width: 100%; } span#ipython_notebook { position: absolute; padding: 2px 2px 2px 5px; } span#ipython_notebook img { font-family: Verdana, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif; height: 24px; text-decoration:none; display: inline; color: black; } #site { width: 100%; display: none; } /* We set the fonts by hand here to override the values in the theme */ .ui-widget { font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif; } /* Smaller buttons */ .ui-button .ui-button-text { padding: 0.2em 0.8em; font-size: 77%; } input.ui-button { padding: 0.3em 0.9em; } span#login_widget { float: right; } .border-box-sizing { box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; } #figure-div { display: inline-block; margin: 10px; }
1,599
18.277108
97
css
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/web_backend/css/fbm.css
/* Flexible box model classes */ /* Taken from Alex Russell http://infrequently.org/2009/08/css-3-progress/ */ .hbox { display: -webkit-box; -webkit-box-orient: horizontal; -webkit-box-align: stretch; display: -moz-box; -moz-box-orient: horizontal; -moz-box-align: stretch; display: box; box-orient: horizontal; box-align: stretch; } .hbox > * { -webkit-box-flex: 0; -moz-box-flex: 0; box-flex: 0; } .vbox { display: -webkit-box; -webkit-box-orient: vertical; -webkit-box-align: stretch; display: -moz-box; -moz-box-orient: vertical; -moz-box-align: stretch; display: box; box-orient: vertical; box-align: stretch; } .vbox > * { -webkit-box-flex: 0; -moz-box-flex: 0; box-flex: 0; } .reverse { -webkit-box-direction: reverse; -moz-box-direction: reverse; box-direction: reverse; } .box-flex0 { -webkit-box-flex: 0; -moz-box-flex: 0; box-flex: 0; } .box-flex1, .box-flex { -webkit-box-flex: 1; -moz-box-flex: 1; box-flex: 1; } .box-flex2 { -webkit-box-flex: 2; -moz-box-flex: 2; box-flex: 2; } .box-group1 { -webkit-box-flex-group: 1; -moz-box-flex-group: 1; box-flex-group: 1; } .box-group2 { -webkit-box-flex-group: 2; -moz-box-flex-group: 2; box-flex-group: 2; } .start { -webkit-box-pack: start; -moz-box-pack: start; box-pack: start; } .end { -webkit-box-pack: end; -moz-box-pack: end; box-pack: end; } .center { -webkit-box-pack: center; -moz-box-pack: center; box-pack: center; }
1,473
14.040816
77
css
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/backends/web_backend/css/boilerplate.css
/** * HTML5 ✰ Boilerplate * * style.css contains a reset, font normalization and some base styles. * * Credit is left where credit is due. * Much inspiration was taken from these projects: * - yui.yahooapis.com/2.8.1/build/base/base.css * - camendesign.com/design/ * - praegnanz.de/weblog/htmlcssjs-kickstart */ /** * html5doctor.com Reset Stylesheet (Eric Meyer's Reset Reloaded + HTML5 baseline) * v1.6.1 2010-09-17 | Authors: Eric Meyer & Richard Clark * html5doctor.com/html-5-reset-stylesheet/ */ html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } sup { vertical-align: super; } sub { vertical-align: sub; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ""; content: none; } ins { background-color: #ff9; color: #000; text-decoration: none; } mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; } del { text-decoration: line-through; } abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; } table { border-collapse: collapse; border-spacing: 0; } hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } input, select { vertical-align: middle; } /** * Font normalization inspired by YUI Library's fonts.css: developer.yahoo.com/yui/ */ body { font:13px/1.231 sans-serif; *font-size:small; } /* Hack retained to preserve specificity */ select, input, textarea, button { font:99% sans-serif; } /* Normalize monospace sizing: en.wikipedia.org/wiki/MediaWiki_talk:Common.css/Archive_11#Teletype_style_fix_for_Chrome */ pre, code, kbd, samp { font-family: monospace, sans-serif; } em,i { font-style: italic; } b,strong { font-weight: bold; }
2,308
28.602564
101
css
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/projections/polar.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from collections import OrderedDict import numpy as np from matplotlib.axes import Axes import matplotlib.axis as maxis from matplotlib import cbook from matplotlib import docstring import matplotlib.markers as mmarkers import matplotlib.patches as mpatches import matplotlib.path as mpath from matplotlib import rcParams import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.spines as mspines class PolarTransform(mtransforms.Transform): """ The base polar transform. This handles projection *theta* and *r* into Cartesian coordinate space *x* and *y*, but does not perform the ultimate affine transformation into the correct position. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, axis=None, use_rmin=True, _apply_theta_transforms=True): mtransforms.Transform.__init__(self) self._axis = axis self._use_rmin = use_rmin self._apply_theta_transforms = _apply_theta_transforms def __str__(self): return ("{}(\n" "{},\n" " use_rmin={},\n" " _apply_theta_transforms={})" .format(type(self).__name__, mtransforms._indent_str(self._axis), self._use_rmin, self._apply_theta_transforms)) def transform_non_affine(self, tr): xy = np.empty(tr.shape, float) t = tr[:, 0:1] r = tr[:, 1:2] x = xy[:, 0:1] y = xy[:, 1:2] # PolarAxes does not use the theta transforms here, but apply them for # backwards-compatibility if not being used by it. if self._apply_theta_transforms and self._axis is not None: t *= self._axis.get_theta_direction() t += self._axis.get_theta_offset() if self._use_rmin and self._axis is not None: r = r - self._axis.get_rorigin() mask = r < 0 x[:] = np.where(mask, np.nan, r * np.cos(t)) y[:] = np.where(mask, np.nan, r * np.sin(t)) return xy transform_non_affine.__doc__ = \ mtransforms.Transform.transform_non_affine.__doc__ def transform_path_non_affine(self, path): vertices = path.vertices if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]: return mpath.Path(self.transform(vertices), path.codes) ipath = path.interpolated(path._interpolation_steps) return mpath.Path(self.transform(ipath.vertices), ipath.codes) transform_path_non_affine.__doc__ = \ mtransforms.Transform.transform_path_non_affine.__doc__ def inverted(self): return PolarAxes.InvertedPolarTransform(self._axis, self._use_rmin, self._apply_theta_transforms) inverted.__doc__ = mtransforms.Transform.inverted.__doc__ class PolarAffine(mtransforms.Affine2DBase): """ The affine part of the polar projection. Scales the output so that maximum radius rests on the edge of the axes circle. """ def __init__(self, scale_transform, limits): """ *limits* is the view limit of the data. The only part of its bounds that is used is the y limits (for the radius limits). The theta range is handled by the non-affine transform. """ mtransforms.Affine2DBase.__init__(self) self._scale_transform = scale_transform self._limits = limits self.set_children(scale_transform, limits) self._mtx = None def __str__(self): return ("{}(\n" "{},\n" "{})" .format(type(self).__name__, mtransforms._indent_str(self._scale_transform), mtransforms._indent_str(self._limits))) def get_matrix(self): if self._invalid: limits_scaled = self._limits.transformed(self._scale_transform) yscale = limits_scaled.ymax - limits_scaled.ymin affine = mtransforms.Affine2D() \ .scale(0.5 / yscale) \ .translate(0.5, 0.5) self._mtx = affine.get_matrix() self._inverted = None self._invalid = 0 return self._mtx get_matrix.__doc__ = mtransforms.Affine2DBase.get_matrix.__doc__ class InvertedPolarTransform(mtransforms.Transform): """ The inverse of the polar transform, mapping Cartesian coordinate space *x* and *y* back to *theta* and *r*. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, axis=None, use_rmin=True, _apply_theta_transforms=True): mtransforms.Transform.__init__(self) self._axis = axis self._use_rmin = use_rmin self._apply_theta_transforms = _apply_theta_transforms def __str__(self): return ("{}(\n" "{},\n" " use_rmin={},\n" " _apply_theta_transforms={})" .format(type(self).__name__, mtransforms._indent_str(self._axis), self._use_rmin, self._apply_theta_transforms)) def transform_non_affine(self, xy): x = xy[:, 0:1] y = xy[:, 1:] r = np.sqrt(x*x + y*y) with np.errstate(invalid='ignore'): # At x=y=r=0 this will raise an # invalid value warning when doing 0/0 # Divide by zero warnings are only raised when # the numerator is different from 0. That # should not happen here. theta = np.arccos(x / r) theta = np.where(y < 0, 2 * np.pi - theta, theta) # PolarAxes does not use the theta transforms here, but apply them for # backwards-compatibility if not being used by it. if self._apply_theta_transforms and self._axis is not None: theta -= self._axis.get_theta_offset() theta *= self._axis.get_theta_direction() theta %= 2 * np.pi if self._use_rmin and self._axis is not None: r += self._axis.get_rorigin() return np.concatenate((theta, r), 1) transform_non_affine.__doc__ = \ mtransforms.Transform.transform_non_affine.__doc__ def inverted(self): return PolarAxes.PolarTransform(self._axis, self._use_rmin, self._apply_theta_transforms) inverted.__doc__ = mtransforms.Transform.inverted.__doc__ class ThetaFormatter(mticker.Formatter): """ Used to format the *theta* tick labels. Converts the native unit of radians into degrees and adds a degree symbol. """ def __call__(self, x, pos=None): vmin, vmax = self.axis.get_view_interval() d = np.rad2deg(abs(vmax - vmin)) digits = max(-int(np.log10(d) - 1.5), 0) if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: format_str = r"${value:0.{digits:d}f}^\circ$" return format_str.format(value=np.rad2deg(x), digits=digits) else: # we use unicode, rather than mathtext with \circ, so # that it will work correctly with any arbitrary font # (assuming it has a degree sign), whereas $5\circ$ # will only work correctly with one of the supported # math fonts (Computer Modern and STIX) format_str = "{value:0.{digits:d}f}\N{DEGREE SIGN}" return format_str.format(value=np.rad2deg(x), digits=digits) class _AxisWrapper(object): def __init__(self, axis): self._axis = axis def get_view_interval(self): return np.rad2deg(self._axis.get_view_interval()) def set_view_interval(self, vmin, vmax): self._axis.set_view_interval(*np.deg2rad((vmin, vmax))) def get_minpos(self): return np.rad2deg(self._axis.get_minpos()) def get_data_interval(self): return np.rad2deg(self._axis.get_data_interval()) def set_data_interval(self, vmin, vmax): self._axis.set_data_interval(*np.deg2rad((vmin, vmax))) def get_tick_space(self): return self._axis.get_tick_space() class ThetaLocator(mticker.Locator): """ Used to locate theta ticks. This will work the same as the base locator except in the case that the view spans the entire circle. In such cases, the previously used default locations of every 45 degrees are returned. """ def __init__(self, base): self.base = base self.axis = self.base.axis = _AxisWrapper(self.base.axis) def set_axis(self, axis): self.axis = _AxisWrapper(axis) self.base.set_axis(self.axis) def __call__(self): lim = self.axis.get_view_interval() if _is_full_circle_deg(lim[0], lim[1]): return np.arange(8) * 2 * np.pi / 8 else: return np.deg2rad(self.base()) def autoscale(self): return self.base.autoscale() def pan(self, numsteps): return self.base.pan(numsteps) def refresh(self): return self.base.refresh() def view_limits(self, vmin, vmax): vmin, vmax = np.rad2deg((vmin, vmax)) return np.deg2rad(self.base.view_limits(vmin, vmax)) def zoom(self, direction): return self.base.zoom(direction) class ThetaTick(maxis.XTick): """ A theta-axis tick. This subclass of `XTick` provides angular ticks with some small modification to their re-positioning such that ticks are rotated based on tick location. This results in ticks that are correctly perpendicular to the arc spine. When 'auto' rotation is enabled, labels are also rotated to be parallel to the spine. The label padding is also applied here since it's not possible to use a generic axes transform to produce tick-specific padding. """ def __init__(self, axes, *args, **kwargs): self._text1_translate = mtransforms.ScaledTranslation( 0, 0, axes.figure.dpi_scale_trans) self._text2_translate = mtransforms.ScaledTranslation( 0, 0, axes.figure.dpi_scale_trans) super(ThetaTick, self).__init__(axes, *args, **kwargs) def _get_text1(self): t = super(ThetaTick, self)._get_text1() t.set_rotation_mode('anchor') t.set_transform(t.get_transform() + self._text1_translate) return t def _get_text2(self): t = super(ThetaTick, self)._get_text2() t.set_rotation_mode('anchor') t.set_transform(t.get_transform() + self._text2_translate) return t def _apply_params(self, **kw): super(ThetaTick, self)._apply_params(**kw) # Ensure transform is correct; sometimes this gets reset. trans = self.label1.get_transform() if not trans.contains_branch(self._text1_translate): self.label1.set_transform(trans + self._text1_translate) trans = self.label2.get_transform() if not trans.contains_branch(self._text2_translate): self.label2.set_transform(trans + self._text2_translate) def _update_padding(self, pad, angle): padx = pad * np.cos(angle) / 72 pady = pad * np.sin(angle) / 72 self._text1_translate._t = (padx, pady) self._text1_translate.invalidate() self._text2_translate._t = (-padx, -pady) self._text2_translate.invalidate() def update_position(self, loc): super(ThetaTick, self).update_position(loc) axes = self.axes angle = loc * axes.get_theta_direction() + axes.get_theta_offset() text_angle = np.rad2deg(angle) % 360 - 90 angle -= np.pi / 2 if self.tick1On: marker = self.tick1line.get_marker() if marker in (mmarkers.TICKUP, '|'): trans = mtransforms.Affine2D().scale(1.0, 1.0).rotate(angle) elif marker == mmarkers.TICKDOWN: trans = mtransforms.Affine2D().scale(1.0, -1.0).rotate(angle) else: # Don't modify custom tick line markers. trans = self.tick1line._marker._transform self.tick1line._marker._transform = trans if self.tick2On: marker = self.tick2line.get_marker() if marker in (mmarkers.TICKUP, '|'): trans = mtransforms.Affine2D().scale(1.0, 1.0).rotate(angle) elif marker == mmarkers.TICKDOWN: trans = mtransforms.Affine2D().scale(1.0, -1.0).rotate(angle) else: # Don't modify custom tick line markers. trans = self.tick2line._marker._transform self.tick2line._marker._transform = trans mode, user_angle = self._labelrotation if mode == 'default': text_angle = user_angle else: if text_angle > 90: text_angle -= 180 elif text_angle < -90: text_angle += 180 text_angle += user_angle if self.label1On: self.label1.set_rotation(text_angle) if self.label2On: self.label2.set_rotation(text_angle) # This extra padding helps preserve the look from previous releases but # is also needed because labels are anchored to their center. pad = self._pad + 7 self._update_padding(pad, self._loc * axes.get_theta_direction() + axes.get_theta_offset()) class ThetaAxis(maxis.XAxis): """ A theta Axis. This overrides certain properties of an `XAxis` to provide special-casing for an angular axis. """ __name__ = 'thetaaxis' axis_name = 'theta' def _get_tick(self, major): if major: tick_kw = self._major_tick_kw else: tick_kw = self._minor_tick_kw return ThetaTick(self.axes, 0, '', major=major, **tick_kw) def _wrap_locator_formatter(self): self.set_major_locator(ThetaLocator(self.get_major_locator())) self.set_major_formatter(ThetaFormatter()) self.isDefault_majloc = True self.isDefault_majfmt = True def cla(self): super(ThetaAxis, self).cla() self.set_ticks_position('none') self._wrap_locator_formatter() def _set_scale(self, value, **kwargs): super(ThetaAxis, self)._set_scale(value, **kwargs) self._wrap_locator_formatter() def _copy_tick_props(self, src, dest): 'Copy the props from src tick to dest tick' if src is None or dest is None: return super(ThetaAxis, self)._copy_tick_props(src, dest) # Ensure that tick transforms are independent so that padding works. trans = dest._get_text1_transform()[0] dest.label1.set_transform(trans + dest._text1_translate) trans = dest._get_text2_transform()[0] dest.label2.set_transform(trans + dest._text2_translate) class RadialLocator(mticker.Locator): """ Used to locate radius ticks. Ensures that all ticks are strictly positive. For all other tasks, it delegates to the base :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base, axes=None): self.base = base self._axes = axes def __call__(self): show_all = True # Ensure previous behaviour with full circle non-annular views. if self._axes: if _is_full_circle_rad(*self._axes.viewLim.intervalx): rorigin = self._axes.get_rorigin() if self._axes.get_rmin() <= rorigin: show_all = False if show_all: return self.base() else: return [tick for tick in self.base() if tick > rorigin] def autoscale(self): return self.base.autoscale() def pan(self, numsteps): return self.base.pan(numsteps) def zoom(self, direction): return self.base.zoom(direction) def refresh(self): return self.base.refresh() def view_limits(self, vmin, vmax): vmin, vmax = self.base.view_limits(vmin, vmax) return mtransforms.nonsingular(min(0, vmin), vmax) class _ThetaShift(mtransforms.ScaledTranslation): """ Apply a padding shift based on axes theta limits. This is used to create padding for radial ticks. Parameters ---------- axes : matplotlib.axes.Axes The owning axes; used to determine limits. pad : float The padding to apply, in points. start : str, {'min', 'max', 'rlabel'} Whether to shift away from the start (``'min'``) or the end (``'max'``) of the axes, or using the rlabel position (``'rlabel'``). """ def __init__(self, axes, pad, mode): mtransforms.ScaledTranslation.__init__(self, pad, pad, axes.figure.dpi_scale_trans) self.set_children(axes._realViewLim) self.axes = axes self.mode = mode self.pad = pad def __str__(self): return ("{}(\n" "{},\n" "{},\n" "{})" .format(type(self).__name__, mtransforms._indent_str(self.axes), mtransforms._indent_str(self.pad), mtransforms._indent_str(repr(self.mode)))) def get_matrix(self): if self._invalid: if self.mode == 'rlabel': angle = ( np.deg2rad(self.axes.get_rlabel_position()) * self.axes.get_theta_direction() + self.axes.get_theta_offset() ) else: if self.mode == 'min': angle = self.axes._realViewLim.xmin elif self.mode == 'max': angle = self.axes._realViewLim.xmax if self.mode in ('rlabel', 'min'): padx = np.cos(angle - np.pi / 2) pady = np.sin(angle - np.pi / 2) else: padx = np.cos(angle + np.pi / 2) pady = np.sin(angle + np.pi / 2) self._t = (self.pad * padx / 72, self.pad * pady / 72) return mtransforms.ScaledTranslation.get_matrix(self) class RadialTick(maxis.YTick): """ A radial-axis tick. This subclass of `YTick` provides radial ticks with some small modification to their re-positioning such that ticks are rotated based on axes limits. This results in ticks that are correctly perpendicular to the spine. Labels are also rotated to be perpendicular to the spine, when 'auto' rotation is enabled. """ def _get_text1(self): t = super(RadialTick, self)._get_text1() t.set_rotation_mode('anchor') return t def _get_text2(self): t = super(RadialTick, self)._get_text2() t.set_rotation_mode('anchor') return t def _determine_anchor(self, mode, angle, start): # Note: angle is the (spine angle - 90) because it's used for the tick # & text setup, so all numbers below are -90 from (normed) spine angle. if mode == 'auto': if start: if -90 <= angle <= 90: return 'left', 'center' else: return 'right', 'center' else: if -90 <= angle <= 90: return 'right', 'center' else: return 'left', 'center' else: if start: if angle < -68.5: return 'center', 'top' elif angle < -23.5: return 'left', 'top' elif angle < 22.5: return 'left', 'center' elif angle < 67.5: return 'left', 'bottom' elif angle < 112.5: return 'center', 'bottom' elif angle < 157.5: return 'right', 'bottom' elif angle < 202.5: return 'right', 'center' elif angle < 247.5: return 'right', 'top' else: return 'center', 'top' else: if angle < -68.5: return 'center', 'bottom' elif angle < -23.5: return 'right', 'bottom' elif angle < 22.5: return 'right', 'center' elif angle < 67.5: return 'right', 'top' elif angle < 112.5: return 'center', 'top' elif angle < 157.5: return 'left', 'top' elif angle < 202.5: return 'left', 'center' elif angle < 247.5: return 'left', 'bottom' else: return 'center', 'bottom' def update_position(self, loc): super(RadialTick, self).update_position(loc) axes = self.axes thetamin = axes.get_thetamin() thetamax = axes.get_thetamax() direction = axes.get_theta_direction() offset_rad = axes.get_theta_offset() offset = np.rad2deg(offset_rad) full = _is_full_circle_deg(thetamin, thetamax) if full: angle = (axes.get_rlabel_position() * direction + offset) % 360 - 90 tick_angle = 0 if angle > 90: text_angle = angle - 180 elif angle < -90: text_angle = angle + 180 else: text_angle = angle else: angle = (thetamin * direction + offset) % 360 - 90 if direction > 0: tick_angle = np.deg2rad(angle) else: tick_angle = np.deg2rad(angle + 180) if angle > 90: text_angle = angle - 180 elif angle < -90: text_angle = angle + 180 else: text_angle = angle mode, user_angle = self._labelrotation if mode == 'auto': text_angle += user_angle else: text_angle = user_angle if self.label1On: if full: ha = 'left' va = 'bottom' else: ha, va = self._determine_anchor(mode, angle, direction > 0) self.label1.set_ha(ha) self.label1.set_va(va) self.label1.set_rotation(text_angle) if self.tick1On: marker = self.tick1line.get_marker() if marker == mmarkers.TICKLEFT: trans = (mtransforms.Affine2D() .scale(1.0, 1.0) .rotate(tick_angle)) elif marker == '_': trans = (mtransforms.Affine2D() .scale(1.0, 1.0) .rotate(tick_angle + np.pi / 2)) elif marker == mmarkers.TICKRIGHT: trans = (mtransforms.Affine2D() .scale(-1.0, 1.0) .rotate(tick_angle)) else: # Don't modify custom tick line markers. trans = self.tick1line._marker._transform self.tick1line._marker._transform = trans if full: self.label2On = False self.tick2On = False else: angle = (thetamax * direction + offset) % 360 - 90 if direction > 0: tick_angle = np.deg2rad(angle) else: tick_angle = np.deg2rad(angle + 180) if angle > 90: text_angle = angle - 180 elif angle < -90: text_angle = angle + 180 else: text_angle = angle mode, user_angle = self._labelrotation if mode == 'auto': text_angle += user_angle else: text_angle = user_angle if self.label2On: ha, va = self._determine_anchor(mode, angle, direction < 0) self.label2.set_ha(ha) self.label2.set_va(va) self.label2.set_rotation(text_angle) if self.tick2On: marker = self.tick2line.get_marker() if marker == mmarkers.TICKLEFT: trans = (mtransforms.Affine2D() .scale(1.0, 1.0) .rotate(tick_angle)) elif marker == '_': trans = (mtransforms.Affine2D() .scale(1.0, 1.0) .rotate(tick_angle + np.pi / 2)) elif marker == mmarkers.TICKRIGHT: trans = (mtransforms.Affine2D() .scale(-1.0, 1.0) .rotate(tick_angle)) else: # Don't modify custom tick line markers. trans = self.tick2line._marker._transform self.tick2line._marker._transform = trans class RadialAxis(maxis.YAxis): """ A radial Axis. This overrides certain properties of a `YAxis` to provide special-casing for a radial axis. """ __name__ = 'radialaxis' axis_name = 'radius' def __init__(self, *args, **kwargs): super(RadialAxis, self).__init__(*args, **kwargs) self.sticky_edges.y.append(0) def _get_tick(self, major): if major: tick_kw = self._major_tick_kw else: tick_kw = self._minor_tick_kw return RadialTick(self.axes, 0, '', major=major, **tick_kw) def _wrap_locator_formatter(self): self.set_major_locator(RadialLocator(self.get_major_locator(), self.axes)) self.isDefault_majloc = True def cla(self): super(RadialAxis, self).cla() self.set_ticks_position('none') self._wrap_locator_formatter() def _set_scale(self, value, **kwargs): super(RadialAxis, self)._set_scale(value, **kwargs) self._wrap_locator_formatter() def _is_full_circle_deg(thetamin, thetamax): """ Determine if a wedge (in degrees) spans the full circle. The condition is derived from :class:`~matplotlib.patches.Wedge`. """ return abs(abs(thetamax - thetamin) - 360.0) < 1e-12 def _is_full_circle_rad(thetamin, thetamax): """ Determine if a wedge (in radians) spans the full circle. The condition is derived from :class:`~matplotlib.patches.Wedge`. """ return abs(abs(thetamax - thetamin) - 2 * np.pi) < 1.74e-14 class _WedgeBbox(mtransforms.Bbox): """ Transform (theta,r) wedge Bbox into axes bounding box. Parameters ---------- center : tuple of float Center of the wedge viewLim : `~matplotlib.transforms.Bbox` Bbox determining the boundaries of the wedge originLim : `~matplotlib.transforms.Bbox` Bbox determining the origin for the wedge, if different from *viewLim* """ def __init__(self, center, viewLim, originLim, **kwargs): mtransforms.Bbox.__init__(self, np.array([[0.0, 0.0], [1.0, 1.0]], np.float), **kwargs) self._center = center self._viewLim = viewLim self._originLim = originLim self.set_children(viewLim, originLim) def __str__(self): return ("{}(\n" "{},\n" "{},\n" "{})" .format(type(self).__name__, mtransforms._indent_str(self._center), mtransforms._indent_str(self._viewLim), mtransforms._indent_str(self._originLim))) def get_points(self): if self._invalid: points = self._viewLim.get_points().copy() # Scale angular limits to work with Wedge. points[:, 0] *= 180 / np.pi if points[0, 0] > points[1, 0]: points[:, 0] = points[::-1, 0] # Scale radial limits based on origin radius. points[:, 1] -= self._originLim.y0 # Scale radial limits to match axes limits. rscale = 0.5 / points[1, 1] points[:, 1] *= rscale width = min(points[1, 1] - points[0, 1], 0.5) # Generate bounding box for wedge. wedge = mpatches.Wedge(self._center, points[1, 1], points[0, 0], points[1, 0], width=width) self.update_from_path(wedge.get_path()) # Ensure equal aspect ratio. w, h = self._points[1] - self._points[0] if h < w: deltah = (w - h) / 2.0 deltaw = 0.0 elif w < h: deltah = 0.0 deltaw = (h - w) / 2.0 else: deltah = 0.0 deltaw = 0.0 self._points += np.array([[-deltaw, -deltah], [deltaw, deltah]]) self._invalid = 0 return self._points get_points.__doc__ = mtransforms.Bbox.get_points.__doc__ class PolarAxes(Axes): """ A polar graph projection, where the input dimensions are *theta*, *r*. Theta starts pointing east and goes anti-clockwise. """ name = 'polar' def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. """ self._default_theta_offset = kwargs.pop('theta_offset', 0) self._default_theta_direction = kwargs.pop('theta_direction', 1) self._default_rlabel_position = np.deg2rad( kwargs.pop('rlabel_position', 22.5)) Axes.__init__(self, *args, **kwargs) self.use_sticky_edges = True self.set_aspect('equal', adjustable='box', anchor='C') self.cla() __init__.__doc__ = Axes.__init__.__doc__ def cla(self): Axes.cla(self) self.title.set_y(1.05) start = self.spines.get('start', None) if start: start.set_visible(False) end = self.spines.get('end', None) if end: end.set_visible(False) self.set_xlim(0.0, 2 * np.pi) self.grid(rcParams['polaraxes.grid']) inner = self.spines.get('inner', None) if inner: inner.set_visible(False) self.set_rorigin(None) self.set_theta_offset(self._default_theta_offset) self.set_theta_direction(self._default_theta_direction) def _init_axis(self): "move this out of __init__ because non-separable axes don't use it" self.xaxis = ThetaAxis(self) self.yaxis = RadialAxis(self) # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla() # results in weird artifacts. Therefore we disable this for # now. # self.spines['polar'].register_axis(self.yaxis) self._update_transScale() def _set_lim_and_transforms(self): # A view limit where the minimum radius can be locked if the user # specifies an alternate origin. self._originViewLim = mtransforms.LockableBbox(self.viewLim) # Handle angular offset and direction. self._direction = mtransforms.Affine2D() \ .scale(self._default_theta_direction, 1.0) self._theta_offset = mtransforms.Affine2D() \ .translate(self._default_theta_offset, 0.0) self.transShift = mtransforms.composite_transform_factory( self._direction, self._theta_offset) # A view limit shifted to the correct location after accounting for # orientation and offset. self._realViewLim = mtransforms.TransformedBbox(self.viewLim, self.transShift) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = mtransforms.TransformWrapper( mtransforms.IdentityTransform()) # Scale view limit into a bbox around the selected wedge. This may be # smaller than the usual unit axes rectangle if not plotting the full # circle. self.axesLim = _WedgeBbox((0.5, 0.5), self._realViewLim, self._originViewLim) # Scale the wedge to fill the axes. self.transWedge = mtransforms.BboxTransformFrom(self.axesLim) # Scale the axes to fill the figure. self.transAxes = mtransforms.BboxTransformTo(self.bbox) # A (possibly non-linear) projection on the (already scaled) # data. This one is aware of rmin self.transProjection = self.PolarTransform( self, _apply_theta_transforms=False) # Add dependency on rorigin. self.transProjection.set_children(self._originViewLim) # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self._originViewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = ( self.transScale + self.transShift + self.transProjection + (self.transProjectionAffine + self.transWedge + self.transAxes)) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 0.0 and r == 1.0 # at the edge of the axis circles. self._xaxis_transform = ( mtransforms.blended_transform_factory( mtransforms.IdentityTransform(), mtransforms.BboxTransformTo(self.viewLim)) + self.transData) # The theta labels are flipped along the radius, so that text 1 is on # the outside by default. This should work the same as before. flipr_transform = mtransforms.Affine2D() \ .translate(0.0, -0.5) \ .scale(1.0, -1.0) \ .translate(0.0, 0.5) self._xaxis_text_transform = flipr_transform + self._xaxis_transform # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from thetamin to # thetamax. self._yaxis_transform = ( mtransforms.blended_transform_factory( mtransforms.BboxTransformTo(self.viewLim), mtransforms.IdentityTransform()) + self.transData) # The r-axis labels are put at an angle and padded in the r-direction self._r_label_position = mtransforms.Affine2D() \ .translate(self._default_rlabel_position, 0.0) self._yaxis_text_transform = mtransforms.TransformWrapper( self._r_label_position + self.transData) def get_xaxis_transform(self, which='grid'): if which not in ['tick1', 'tick2', 'grid']: raise ValueError( "'which' must be one of 'tick1', 'tick2', or 'grid'") return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return self._xaxis_text_transform, 'center', 'center' def get_xaxis_text2_transform(self, pad): return self._xaxis_text_transform, 'center', 'center' def get_yaxis_transform(self, which='grid'): if which in ('tick1', 'tick2'): return self._yaxis_text_transform elif which == 'grid': return self._yaxis_transform else: raise ValueError( "'which' must be one of 'tick1', 'tick2', or 'grid'") def get_yaxis_text1_transform(self, pad): thetamin, thetamax = self._realViewLim.intervalx if _is_full_circle_rad(thetamin, thetamax): return self._yaxis_text_transform, 'bottom', 'left' elif self.get_theta_direction() > 0: halign = 'left' pad_shift = _ThetaShift(self, pad, 'min') else: halign = 'right' pad_shift = _ThetaShift(self, pad, 'max') return self._yaxis_text_transform + pad_shift, 'center', halign def get_yaxis_text2_transform(self, pad): if self.get_theta_direction() > 0: halign = 'right' pad_shift = _ThetaShift(self, pad, 'max') else: halign = 'left' pad_shift = _ThetaShift(self, pad, 'min') return self._yaxis_text_transform + pad_shift, 'center', halign def draw(self, *args, **kwargs): thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx) if thetamin > thetamax: thetamin, thetamax = thetamax, thetamin rmin, rmax = self._realViewLim.intervaly - self.get_rorigin() if isinstance(self.patch, mpatches.Wedge): # Backwards-compatibility: Any subclassed Axes might override the # patch to not be the Wedge that PolarAxes uses. center = self.transWedge.transform_point((0.5, 0.5)) self.patch.set_center(center) self.patch.set_theta1(thetamin) self.patch.set_theta2(thetamax) edge, _ = self.transWedge.transform_point((1, 0)) radius = edge - center[0] width = min(radius * (rmax - rmin) / rmax, radius) self.patch.set_radius(radius) self.patch.set_width(width) inner_width = radius - width inner = self.spines.get('inner', None) if inner: inner.set_visible(inner_width != 0.0) visible = not _is_full_circle_deg(thetamin, thetamax) # For backwards compatibility, any subclassed Axes might override the # spines to not include start/end that PolarAxes uses. start = self.spines.get('start', None) end = self.spines.get('end', None) if start: start.set_visible(visible) if end: end.set_visible(visible) if visible: yaxis_text_transform = self._yaxis_transform else: yaxis_text_transform = self._r_label_position + self.transData if self._yaxis_text_transform != yaxis_text_transform: self._yaxis_text_transform.set(yaxis_text_transform) self.yaxis.reset_ticks() self.yaxis.set_clip_path(self.patch) Axes.draw(self, *args, **kwargs) def _gen_axes_patch(self): return mpatches.Wedge((0.5, 0.5), 0.5, 0.0, 360.0) def _gen_axes_spines(self): spines = OrderedDict([ ('polar', mspines.Spine.arc_spine(self, 'top', (0.5, 0.5), 0.5, 0.0, 360.0)), ('start', mspines.Spine.linear_spine(self, 'left')), ('end', mspines.Spine.linear_spine(self, 'right')), ('inner', mspines.Spine.arc_spine(self, 'bottom', (0.5, 0.5), 0.0, 0.0, 360.0)) ]) spines['polar'].set_transform(self.transWedge + self.transAxes) spines['inner'].set_transform(self.transWedge + self.transAxes) spines['start'].set_transform(self._yaxis_transform) spines['end'].set_transform(self._yaxis_transform) return spines def set_thetamax(self, thetamax): self.viewLim.x1 = np.deg2rad(thetamax) def get_thetamax(self): return np.rad2deg(self.viewLim.xmax) def set_thetamin(self, thetamin): self.viewLim.x0 = np.deg2rad(thetamin) def get_thetamin(self): return np.rad2deg(self.viewLim.xmin) def set_thetalim(self, *args, **kwargs): if 'thetamin' in kwargs: kwargs['xmin'] = np.deg2rad(kwargs.pop('thetamin')) if 'thetamax' in kwargs: kwargs['xmax'] = np.deg2rad(kwargs.pop('thetamax')) return tuple(np.rad2deg(self.set_xlim(*args, **kwargs))) def set_theta_offset(self, offset): """ Set the offset for the location of 0 in radians. """ mtx = self._theta_offset.get_matrix() mtx[0, 2] = offset self._theta_offset.invalidate() def get_theta_offset(self): """ Get the offset for the location of 0 in radians. """ return self._theta_offset.get_matrix()[0, 2] def set_theta_zero_location(self, loc, offset=0.0): """ Sets the location of theta's zero. (Calls set_theta_offset with the correct value in radians under the hood.) loc : str May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE". offset : float, optional An offset in degrees to apply from the specified `loc`. **Note:** this offset is *always* applied counter-clockwise regardless of the direction setting. """ mapping = { 'N': np.pi * 0.5, 'NW': np.pi * 0.75, 'W': np.pi, 'SW': np.pi * 1.25, 'S': np.pi * 1.5, 'SE': np.pi * 1.75, 'E': 0, 'NE': np.pi * 0.25} return self.set_theta_offset(mapping[loc] + np.deg2rad(offset)) def set_theta_direction(self, direction): """ Set the direction in which theta increases. clockwise, -1: Theta increases in the clockwise direction counterclockwise, anticlockwise, 1: Theta increases in the counterclockwise direction """ mtx = self._direction.get_matrix() if direction in ('clockwise',): mtx[0, 0] = -1 elif direction in ('counterclockwise', 'anticlockwise'): mtx[0, 0] = 1 elif direction in (1, -1): mtx[0, 0] = direction else: raise ValueError( "direction must be 1, -1, clockwise or counterclockwise") self._direction.invalidate() def get_theta_direction(self): """ Get the direction in which theta increases. -1: Theta increases in the clockwise direction 1: Theta increases in the counterclockwise direction """ return self._direction.get_matrix()[0, 0] def set_rmax(self, rmax): self.viewLim.y1 = rmax def get_rmax(self): return self.viewLim.ymax def set_rmin(self, rmin): self.viewLim.y0 = rmin def get_rmin(self): return self.viewLim.ymin def set_rorigin(self, rorigin): self._originViewLim.locked_y0 = rorigin def get_rorigin(self): return self._originViewLim.y0 def set_rlim(self, *args, **kwargs): if 'rmin' in kwargs: kwargs['ymin'] = kwargs.pop('rmin') if 'rmax' in kwargs: kwargs['ymax'] = kwargs.pop('rmax') return self.set_ylim(*args, **kwargs) def get_rlabel_position(self): """ Returns ------- float The theta position of the radius labels in degrees. """ return np.rad2deg(self._r_label_position.get_matrix()[0, 2]) def set_rlabel_position(self, value): """Updates the theta position of the radius labels. Parameters ---------- value : number The angular position of the radius labels in degrees. """ self._r_label_position.clear().translate(np.deg2rad(value), 0.0) def set_yscale(self, *args, **kwargs): Axes.set_yscale(self, *args, **kwargs) self.yaxis.set_major_locator( self.RadialLocator(self.yaxis.get_major_locator(), self)) def set_rscale(self, *args, **kwargs): return Axes.set_yscale(self, *args, **kwargs) def set_rticks(self, *args, **kwargs): return Axes.set_yticks(self, *args, **kwargs) @docstring.dedent_interpd def set_thetagrids(self, angles, labels=None, frac=None, fmt=None, **kwargs): """ Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not None, is a ``len(angles)`` list of strings of the labels to use at each angle. If *labels* is None, the labels will be ``fmt %% angle`` *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). e.g., 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ if frac is not None: cbook.warn_deprecated('2.1', name='frac', obj_type='parameter', alternative='tick padding via ' 'Axes.tick_params') # Make sure we take into account unitized data angles = self.convert_yunits(angles) angles = np.deg2rad(angles) self.set_xticks(angles) if labels is not None: self.set_xticklabels(labels) elif fmt is not None: self.xaxis.set_major_formatter(mticker.FormatStrFormatter(fmt)) for t in self.xaxis.get_ticklabels(): t.update(kwargs) return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels() @docstring.dedent_interpd def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs): """ Set the radial locations and labels of the *r* grids. The labels will appear at radial distances *radii* at the given *angle* in degrees. *labels*, if not None, is a ``len(radii)`` list of strings of the labels to use at each radius. If *labels* is None, the built-in formatter will be used. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data radii = self.convert_xunits(radii) radii = np.asarray(radii) self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) elif fmt is not None: self.yaxis.set_major_formatter(mticker.FormatStrFormatter(fmt)) if angle is None: angle = self.get_rlabel_position() self.set_rlabel_position(angle) for t in self.yaxis.get_ticklabels(): t.update(kwargs) return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels() def set_xscale(self, scale, *args, **kwargs): if scale != 'linear': raise NotImplementedError( "You can not set the xscale on a polar plot.") def format_coord(self, theta, r): """ Return a format string formatting the coordinate using Unicode characters. """ if theta < 0: theta += 2 * np.pi theta /= np.pi return ('\N{GREEK SMALL LETTER THETA}=%0.3f\N{GREEK SMALL LETTER PI} ' '(%0.3f\N{DEGREE SIGN}), r=%0.3f') % (theta, theta * 180.0, r) def get_data_ratio(self): ''' Return the aspect ratio of the data itself. For a polar plot, this should always be 1.0 ''' return 1.0 # # # Interactive panning def can_zoom(self): """ Return *True* if this axes supports the zoom box button functionality. Polar axes do not support zoom boxes. """ return False def can_pan(self): """ Return *True* if this axes supports the pan/zoom button functionality. For polar axes, this is slightly misleading. Both panning and zooming are performed by the same button. Panning is performed in azimuth while zooming is done along the radial. """ return True def start_pan(self, x, y, button): angle = np.deg2rad(self.get_rlabel_position()) mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if t >= angle - epsilon and t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = cbook.Bunch( rmax=self.get_rmax(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), r_label_angle=self.get_rlabel_position(), x=x, y=y, mode=mode) def end_pan(self): del self._pan_start def drag_pan(self, button, key, x, y): p = self._pan_start if p.mode == 'drag_r_labels': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) # Deal with theta dt0 = t - startt dt1 = startt - t if abs(dt1) < abs(dt0): dt = abs(dt1) * np.sign(dt0) * -1.0 else: dt = dt0 * -1.0 dt = (dt / np.pi) * 180.0 self.set_rlabel_position(p.r_label_angle - dt) trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0) trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0) for t in self.yaxis.majorTicks + self.yaxis.minorTicks: t.label1.set_va(vert1) t.label1.set_ha(horiz1) t.label2.set_va(vert2) t.label2.set_ha(horiz2) elif p.mode == 'zoom': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) # Deal with r scale = r / startr self.set_rmax(p.rmax / scale) # to keep things all self contained, we can put aliases to the Polar classes # defined above. This isn't strictly necessary, but it makes some of the # code more readable (and provides a backwards compatible Polar API) PolarAxes.PolarTransform = PolarTransform PolarAxes.PolarAffine = PolarAffine PolarAxes.InvertedPolarTransform = InvertedPolarTransform PolarAxes.ThetaFormatter = ThetaFormatter PolarAxes.RadialLocator = RadialLocator PolarAxes.ThetaLocator = ThetaLocator # These are a couple of aborted attempts to project a polar plot using # cubic bezier curves. # def transform_path(self, path): # twopi = 2.0 * np.pi # halfpi = 0.5 * np.pi # vertices = path.vertices # t0 = vertices[0:-1, 0] # t1 = vertices[1: , 0] # td = np.where(t1 > t0, t1 - t0, twopi - (t0 - t1)) # maxtd = td.max() # interpolate = np.ceil(maxtd / halfpi) # if interpolate > 1.0: # vertices = self.interpolate(vertices, interpolate) # vertices = self.transform(vertices) # result = np.zeros((len(vertices) * 3 - 2, 2), float) # codes = mpath.Path.CURVE4 * np.ones((len(vertices) * 3 - 2, ), # mpath.Path.code_type) # result[0] = vertices[0] # codes[0] = mpath.Path.MOVETO # kappa = 4.0 * ((np.sqrt(2.0) - 1.0) / 3.0) # kappa = 0.5 # p0 = vertices[0:-1] # p1 = vertices[1: ] # x0 = p0[:, 0:1] # y0 = p0[:, 1: ] # b0 = ((y0 - x0) - y0) / ((x0 + y0) - x0) # a0 = y0 - b0*x0 # x1 = p1[:, 0:1] # y1 = p1[:, 1: ] # b1 = ((y1 - x1) - y1) / ((x1 + y1) - x1) # a1 = y1 - b1*x1 # x = -(a0-a1) / (b0-b1) # y = a0 + b0*x # xk = (x - x0) * kappa + x0 # yk = (y - y0) * kappa + y0 # result[1::3, 0:1] = xk # result[1::3, 1: ] = yk # xk = (x - x1) * kappa + x1 # yk = (y - y1) * kappa + y1 # result[2::3, 0:1] = xk # result[2::3, 1: ] = yk # result[3::3] = p1 # print(vertices[-2:]) # print(result[-2:]) # return mpath.Path(result, codes) # twopi = 2.0 * np.pi # halfpi = 0.5 * np.pi # vertices = path.vertices # t0 = vertices[0:-1, 0] # t1 = vertices[1: , 0] # td = np.where(t1 > t0, t1 - t0, twopi - (t0 - t1)) # maxtd = td.max() # interpolate = np.ceil(maxtd / halfpi) # print("interpolate", interpolate) # if interpolate > 1.0: # vertices = self.interpolate(vertices, interpolate) # result = np.zeros((len(vertices) * 3 - 2, 2), float) # codes = mpath.Path.CURVE4 * np.ones((len(vertices) * 3 - 2, ), # mpath.Path.code_type) # result[0] = vertices[0] # codes[0] = mpath.Path.MOVETO # kappa = 4.0 * ((np.sqrt(2.0) - 1.0) / 3.0) # tkappa = np.arctan(kappa) # hyp_kappa = np.sqrt(kappa*kappa + 1.0) # t0 = vertices[0:-1, 0] # t1 = vertices[1: , 0] # r0 = vertices[0:-1, 1] # r1 = vertices[1: , 1] # td = np.where(t1 > t0, t1 - t0, twopi - (t0 - t1)) # td_scaled = td / (np.pi * 0.5) # rd = r1 - r0 # r0kappa = r0 * kappa * td_scaled # r1kappa = r1 * kappa * td_scaled # ravg_kappa = ((r1 + r0) / 2.0) * kappa * td_scaled # result[1::3, 0] = t0 + (tkappa * td_scaled) # result[1::3, 1] = r0*hyp_kappa # # result[1::3, 1] = r0 / np.cos(tkappa * td_scaled) # # np.sqrt(r0*r0 + ravg_kappa*ravg_kappa) # result[2::3, 0] = t1 - (tkappa * td_scaled) # result[2::3, 1] = r1*hyp_kappa # # result[2::3, 1] = r1 / np.cos(tkappa * td_scaled) # # np.sqrt(r1*r1 + ravg_kappa*ravg_kappa) # result[3::3, 0] = t1 # result[3::3, 1] = r1 # print(vertices[:6], result[:6], t0[:6], t1[:6], td[:6], # td_scaled[:6], tkappa) # result = self.transform(result) # return mpath.Path(result, codes) # transform_path_non_affine = transform_path
55,098
34.825098
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/projections/geo.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as np import matplotlib from matplotlib import rcParams from matplotlib.axes import Axes import matplotlib.axis as maxis from matplotlib.patches import Circle from matplotlib.path import Path import matplotlib.spines as mspines from matplotlib.ticker import ( Formatter, NullLocator, FixedLocator, NullFormatter) from matplotlib.transforms import Affine2D, BboxTransformTo, Transform class GeoAxes(Axes): """An abstract base class for geographic projections.""" class ThetaFormatter(Formatter): """ Used to format the theta tick labels. Converts the native unit of radians into degrees and adds a degree symbol. """ def __init__(self, round_to=1.0): self._round_to = round_to def __call__(self, x, pos=None): degrees = (x / np.pi) * 180.0 degrees = np.round(degrees / self._round_to) * self._round_to if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: return r"$%0.0f^\circ$" % degrees else: return "%0.0f\N{DEGREE SIGN}" % degrees RESOLUTION = 75 def _init_axis(self): self.xaxis = maxis.XAxis(self) self.yaxis = maxis.YAxis(self) # Do not register xaxis or yaxis with spines -- as done in # Axes._init_axis() -- until GeoAxes.xaxis.cla() works. # self.spines['geo'].register_axis(self.yaxis) self._update_transScale() def cla(self): Axes.cla(self) self.set_longitude_grid(30) self.set_latitude_grid(15) self.set_longitude_grid_ends(75) self.xaxis.set_minor_locator(NullLocator()) self.yaxis.set_minor_locator(NullLocator()) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? self.grid(rcParams['axes.grid']) Axes.set_xlim(self, -np.pi, np.pi) Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0) def _set_lim_and_transforms(self): # A (possibly non-linear) projection on the (already scaled) data self.transProjection = self._get_core_transform(self.RESOLUTION) self.transAffine = self._get_affine_transform() self.transAxes = BboxTransformTo(self.bbox) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = \ self.transProjection + \ self.transAffine + \ self.transAxes # This is the transform for longitude ticks. self._xaxis_pretransform = \ Affine2D() \ .scale(1, self._longitude_cap * 2) \ .translate(0, -self._longitude_cap) self._xaxis_transform = \ self._xaxis_pretransform + \ self.transData self._xaxis_text1_transform = \ Affine2D().scale(1, 0) + \ self.transData + \ Affine2D().translate(0, 4) self._xaxis_text2_transform = \ Affine2D().scale(1, 0) + \ self.transData + \ Affine2D().translate(0, -4) # This is the transform for latitude ticks. yaxis_stretch = Affine2D().scale(np.pi * 2, 1).translate(-np.pi, 0) yaxis_space = Affine2D().scale(1, 1.1) self._yaxis_transform = \ yaxis_stretch + \ self.transData yaxis_text_base = \ yaxis_stretch + \ self.transProjection + \ (yaxis_space + \ self.transAffine + \ self.transAxes) self._yaxis_text1_transform = \ yaxis_text_base + \ Affine2D().translate(-8, 0) self._yaxis_text2_transform = \ yaxis_text_base + \ Affine2D().translate(8, 0) def _get_affine_transform(self): transform = self._get_core_transform(1) xscale, _ = transform.transform_point((np.pi, 0)) _, yscale = transform.transform_point((0, np.pi / 2)) return Affine2D() \ .scale(0.5 / xscale, 0.5 / yscale) \ .translate(0.5, 0.5) def get_xaxis_transform(self,which='grid'): if which not in ['tick1', 'tick2', 'grid']: raise ValueError( "'which' must be one of 'tick1', 'tick2', or 'grid'") return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return self._xaxis_text1_transform, 'bottom', 'center' def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'top', 'center' def get_yaxis_transform(self,which='grid'): if which not in ['tick1', 'tick2', 'grid']: raise ValueError( "'which' must be one of 'tick1', 'tick2', or 'grid'") return self._yaxis_transform def get_yaxis_text1_transform(self, pad): return self._yaxis_text1_transform, 'center', 'right' def get_yaxis_text2_transform(self, pad): return self._yaxis_text2_transform, 'center', 'left' def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): return {'geo':mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)} def set_yscale(self, *args, **kwargs): if args[0] != 'linear': raise NotImplementedError set_xscale = set_yscale def set_xlim(self, *args, **kwargs): raise TypeError("It is not possible to change axes limits " "for geographic projections. Please consider " "using Basemap or Cartopy.") set_ylim = set_xlim def format_coord(self, lon, lat): 'return a format string formatting the coordinate' lon, lat = np.rad2deg([lon, lat]) if lat >= 0.0: ns = 'N' else: ns = 'S' if lon >= 0.0: ew = 'E' else: ew = 'W' return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s' % (abs(lat), ns, abs(lon), ew)) def set_longitude_grid(self, degrees): """ Set the number of degrees between each longitude grid. """ # Skip -180 and 180, which are the fixed limits. grid = np.arange(-180 + degrees, 180, degrees) self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) self.xaxis.set_major_formatter(self.ThetaFormatter(degrees)) def set_latitude_grid(self, degrees): """ Set the number of degrees between each latitude grid. """ # Skip -90 and 90, which are the fixed limits. grid = np.arange(-90 + degrees, 90, degrees) self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) self.yaxis.set_major_formatter(self.ThetaFormatter(degrees)) def set_longitude_grid_ends(self, degrees): """ Set the latitude(s) at which to stop drawing the longitude grids. """ self._longitude_cap = np.deg2rad(degrees) self._xaxis_pretransform \ .clear() \ .scale(1.0, self._longitude_cap * 2.0) \ .translate(0.0, -self._longitude_cap) def get_data_ratio(self): ''' Return the aspect ratio of the data itself. ''' return 1.0 ### Interactive panning def can_zoom(self): """ Return *True* if this axes supports the zoom box button functionality. This axes object does not support interactive zoom box. """ return False def can_pan(self) : """ Return *True* if this axes supports the pan/zoom button functionality. This axes object does not support interactive pan/zoom. """ return False def start_pan(self, x, y, button): pass def end_pan(self): pass def drag_pan(self, button, key, x, y): pass class _GeoTransform(Transform): # Factoring out some common functionality. input_dims = 2 output_dims = 2 is_separable = False def __init__(self, resolution): """ Create a new geographical transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved space. """ Transform.__init__(self) self._resolution = resolution def __str__(self): return "{}({})".format(type(self).__name__, self._resolution) def transform_path_non_affine(self, path): vertices = path.vertices ipath = path.interpolated(self._resolution) return Path(self.transform(ipath.vertices), ipath.codes) transform_path_non_affine.__doc__ = \ Transform.transform_path_non_affine.__doc__ class AitoffAxes(GeoAxes): name = 'aitoff' class AitoffTransform(_GeoTransform): """The base Aitoff transform.""" def transform_non_affine(self, ll): longitude = ll[:, 0] latitude = ll[:, 1] # Pre-compute some values half_long = longitude / 2.0 cos_latitude = np.cos(latitude) alpha = np.arccos(cos_latitude * np.cos(half_long)) # Avoid divide-by-zero errors using same method as NumPy. alpha[alpha == 0.0] = 1e-20 # We want unnormalized sinc. numpy.sinc gives us normalized sinc_alpha = np.sin(alpha) / alpha xy = np.empty_like(ll, float) xy[:, 0] = (cos_latitude * np.sin(half_long)) / sinc_alpha xy[:, 1] = np.sin(latitude) / sinc_alpha return xy transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return AitoffAxes.InvertedAitoffTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ class InvertedAitoffTransform(_GeoTransform): def transform_non_affine(self, xy): # MGDTODO: Math is hard ;( return xy transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return AitoffAxes.AitoffTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 GeoAxes.__init__(self, *args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.cla() def _get_core_transform(self, resolution): return self.AitoffTransform(resolution) class HammerAxes(GeoAxes): name = 'hammer' class HammerTransform(_GeoTransform): """The base Hammer transform.""" def transform_non_affine(self, ll): longitude = ll[:, 0:1] latitude = ll[:, 1:2] # Pre-compute some values half_long = longitude / 2.0 cos_latitude = np.cos(latitude) sqrt2 = np.sqrt(2.0) alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long)) x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha y = (sqrt2 * np.sin(latitude)) / alpha return np.concatenate((x, y), 1) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return HammerAxes.InvertedHammerTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ class InvertedHammerTransform(_GeoTransform): def transform_non_affine(self, xy): x, y = xy.T z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2) longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1))) latitude = np.arcsin(y*z) return np.column_stack([longitude, latitude]) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return HammerAxes.HammerTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 GeoAxes.__init__(self, *args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.cla() def _get_core_transform(self, resolution): return self.HammerTransform(resolution) class MollweideAxes(GeoAxes): name = 'mollweide' class MollweideTransform(_GeoTransform): """The base Mollweide transform.""" def transform_non_affine(self, ll): def d(theta): delta = (-(theta + np.sin(theta) - pi_sin_l) / (1 + np.cos(theta))) return delta, np.abs(delta) > 0.001 longitude = ll[:, 0] latitude = ll[:, 1] clat = np.pi/2 - np.abs(latitude) ihigh = clat < 0.087 # within 5 degrees of the poles ilow = ~ihigh aux = np.empty(latitude.shape, dtype=float) if ilow.any(): # Newton-Raphson iteration pi_sin_l = np.pi * np.sin(latitude[ilow]) theta = 2.0 * latitude[ilow] delta, large_delta = d(theta) while np.any(large_delta): theta[large_delta] += delta[large_delta] delta, large_delta = d(theta) aux[ilow] = theta / 2 if ihigh.any(): # Taylor series-based approx. solution e = clat[ihigh] d = 0.5 * (3 * np.pi * e**2) ** (1.0/3) aux[ihigh] = (np.pi/2 - d) * np.sign(latitude[ihigh]) xy = np.empty(ll.shape, dtype=float) xy[:,0] = (2.0 * np.sqrt(2.0) / np.pi) * longitude * np.cos(aux) xy[:,1] = np.sqrt(2.0) * np.sin(aux) return xy transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return MollweideAxes.InvertedMollweideTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ class InvertedMollweideTransform(_GeoTransform): def transform_non_affine(self, xy): x = xy[:, 0:1] y = xy[:, 1:2] # from Equations (7, 8) of # http://mathworld.wolfram.com/MollweideProjection.html theta = np.arcsin(y / np.sqrt(2)) lon = (np.pi / (2 * np.sqrt(2))) * x / np.cos(theta) lat = np.arcsin((2 * theta + np.sin(2 * theta)) / np.pi) return np.concatenate((lon, lat), 1) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return MollweideAxes.MollweideTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 GeoAxes.__init__(self, *args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.cla() def _get_core_transform(self, resolution): return self.MollweideTransform(resolution) class LambertAxes(GeoAxes): name = 'lambert' class LambertTransform(_GeoTransform): """The base Lambert transform.""" def __init__(self, center_longitude, center_latitude, resolution): """ Create a new Lambert transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved Lambert space. """ _GeoTransform.__init__(self, resolution) self._center_longitude = center_longitude self._center_latitude = center_latitude def transform_non_affine(self, ll): longitude = ll[:, 0:1] latitude = ll[:, 1:2] clong = self._center_longitude clat = self._center_latitude cos_lat = np.cos(latitude) sin_lat = np.sin(latitude) diff_long = longitude - clong cos_diff_long = np.cos(diff_long) inner_k = (1.0 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long) # Prevent divide-by-zero problems inner_k = np.where(inner_k == 0.0, 1e-15, inner_k) k = np.sqrt(2.0 / inner_k) x = k*cos_lat*np.sin(diff_long) y = k*(np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long) return np.concatenate((x, y), 1) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return LambertAxes.InvertedLambertTransform( self._center_longitude, self._center_latitude, self._resolution) inverted.__doc__ = Transform.inverted.__doc__ class InvertedLambertTransform(_GeoTransform): def __init__(self, center_longitude, center_latitude, resolution): _GeoTransform.__init__(self, resolution) self._center_longitude = center_longitude self._center_latitude = center_latitude def transform_non_affine(self, xy): x = xy[:, 0:1] y = xy[:, 1:2] clong = self._center_longitude clat = self._center_latitude p = np.sqrt(x*x + y*y) p = np.where(p == 0.0, 1e-9, p) c = 2.0 * np.arcsin(0.5 * p) sin_c = np.sin(c) cos_c = np.cos(c) lat = np.arcsin(cos_c*np.sin(clat) + ((y*sin_c*np.cos(clat)) / p)) lon = clong + np.arctan( (x*sin_c) / (p*np.cos(clat)*cos_c - y*np.sin(clat)*sin_c)) return np.concatenate((lon, lat), 1) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return LambertAxes.LambertTransform( self._center_longitude, self._center_latitude, self._resolution) inverted.__doc__ = Transform.inverted.__doc__ def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 self._center_longitude = kwargs.pop("center_longitude", 0.0) self._center_latitude = kwargs.pop("center_latitude", 0.0) GeoAxes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() def cla(self): GeoAxes.cla(self) self.yaxis.set_major_formatter(NullFormatter()) def _get_core_transform(self, resolution): return self.LambertTransform( self._center_longitude, self._center_latitude, resolution) def _get_affine_transform(self): return Affine2D() \ .scale(0.25) \ .translate(0.5, 0.5)
19,032
33.731752
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/projections/__init__.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from .geo import AitoffAxes, HammerAxes, LambertAxes, MollweideAxes from .polar import PolarAxes from matplotlib import axes class ProjectionRegistry(object): """ Manages the set of projections available to the system. """ def __init__(self): self._all_projection_types = {} def register(self, *projections): """ Register a new set of projection(s). """ for projection in projections: name = projection.name self._all_projection_types[name] = projection def get_projection_class(self, name): """ Get a projection class from its *name*. """ return self._all_projection_types[name] def get_projection_names(self): """ Get a list of the names of all projections currently registered. """ return sorted(self._all_projection_types) projection_registry = ProjectionRegistry() projection_registry.register( axes.Axes, PolarAxes, AitoffAxes, HammerAxes, LambertAxes, MollweideAxes) def register_projection(cls): projection_registry.register(cls) def get_projection_class(projection=None): """ Get a projection class from its name. If *projection* is None, a standard rectilinear projection is returned. """ if projection is None: projection = 'rectilinear' try: return projection_registry.get_projection_class(projection) except KeyError: raise ValueError("Unknown projection '%s'" % projection) def process_projection_requirements(figure, *args, **kwargs): """ Handle the args/kwargs to for add_axes/add_subplot/gca, returning:: (axes_proj_class, proj_class_kwargs, proj_stack_key) Which can be used for new axes initialization/identification. .. note:: **kwargs** is modified in place. """ ispolar = kwargs.pop('polar', False) projection = kwargs.pop('projection', None) if ispolar: if projection is not None and projection != 'polar': raise ValueError( "polar=True, yet projection=%r. " "Only one of these arguments should be supplied." % projection) projection = 'polar' if isinstance(projection, six.string_types) or projection is None: projection_class = get_projection_class(projection) elif hasattr(projection, '_as_mpl_axes'): projection_class, extra_kwargs = projection._as_mpl_axes() kwargs.update(**extra_kwargs) else: raise TypeError('projection must be a string, None or implement a ' '_as_mpl_axes method. Got %r' % projection) # Make the key without projection kwargs, this is used as a unique # lookup for axes instances key = figure._make_key(*args, **kwargs) return projection_class, kwargs, key def get_projection_names(): """ Get a list of acceptable projection names. """ return projection_registry.get_projection_names()
3,152
27.405405
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_ticker.py
from __future__ import absolute_import, division, print_function from numpy.testing import assert_almost_equal import numpy as np import pytest import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker import warnings class TestMaxNLocator(object): basic_data = [ (20, 100, np.array([20., 40., 60., 80., 100.])), (0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])), (-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])), ] integer_data = [ (-0.1, 1.1, None, np.array([-1, 0, 1, 2])), (-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])), (1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])), ] @pytest.mark.parametrize('vmin, vmax, expected', basic_data) def test_basic(self, vmin, vmax, expected): loc = mticker.MaxNLocator(nbins=5) assert_almost_equal(loc.tick_values(vmin, vmax), expected) @pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data) def test_integer(self, vmin, vmax, steps, expected): loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps) assert_almost_equal(loc.tick_values(vmin, vmax), expected) class TestLinearLocator(object): def test_basic(self): loc = mticker.LinearLocator(numticks=3) test_value = np.array([-0.8, -0.3, 0.2]) assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) def test_set_params(self): """ Create linear locator with presets={}, numticks=2 and change it to something else. See if change was successful. Should not exception. """ loc = mticker.LinearLocator(numticks=2) loc.set_params(numticks=8, presets={(0, 1): []}) assert loc.numticks == 8 assert loc.presets == {(0, 1): []} class TestMultipleLocator(object): def test_basic(self): loc = mticker.MultipleLocator(base=3.147) test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294, 9.441, 12.588]) assert_almost_equal(loc.tick_values(-7, 10), test_value) def test_set_params(self): """ Create multiple locator with 0.7 base, and change it to something else. See if change was successful. """ mult = mticker.MultipleLocator(base=0.7) mult.set_params(base=1.7) assert mult._base == 1.7 class TestAutoMinorLocator(object): def test_basic(self): fig, ax = plt.subplots() ax.set_xlim(0, 1.39) ax.minorticks_on() test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9, 0.95, 1, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]) assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) # NB: the following values are assuming that *xlim* is [0, 5] params = [ (0, 0), # no major tick => no minor tick either (1, 0), # a single major tick => no minor tick (2, 4), # 1 "nice" major step => 1*5 minor **divisions** (3, 6) # 2 "not nice" major steps => 2*4 minor **divisions** ] @pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params) def test_low_number_of_majorticks( self, nb_majorticks, expected_nb_minorticks): # This test is related to issue #8804 fig, ax = plt.subplots() xlims = (0, 5) # easier to test the different code paths ax.set_xlim(*xlims) ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks)) ax.minorticks_on() ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks class TestLogLocator(object): def test_basic(self): loc = mticker.LogLocator(numticks=5) with pytest.raises(ValueError): loc.tick_values(0, 1000) test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, 1.00000000e+07, 1.000000000e+09]) assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value) loc = mticker.LogLocator(base=2) test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.]) assert_almost_equal(loc.tick_values(1, 100), test_value) def test_set_params(self): """ Create log locator with default value, base=10.0, subs=[1.0], numdecs=4, numticks=15 and change it to something else. See if change was successful. Should not raise exception. """ loc = mticker.LogLocator() loc.set_params(numticks=7, numdecs=8, subs=[2.0], base=4) assert loc.numticks == 7 assert loc.numdecs == 8 assert loc._base == 4 assert list(loc._subs) == [2.0] class TestNullLocator(object): def test_set_params(self): """ Create null locator, and attempt to call set_params() on it. Should not exception, and should raise a warning. """ loc = mticker.NullLocator() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") loc.set_params() assert len(w) == 1 class TestLogitLocator(object): def test_set_params(self): """ Create logit locator with default minor=False, and change it to something else. See if change was successful. Should not exception. """ loc = mticker.LogitLocator() # Defaults to false. loc.set_params(minor=True) assert loc.minor class TestFixedLocator(object): def test_set_params(self): """ Create fixed locator with 5 nbins, and change it to something else. See if change was successful. Should not exception. """ fixed = mticker.FixedLocator(range(0, 24), nbins=5) fixed.set_params(nbins=7) assert fixed.nbins == 7 class TestIndexLocator(object): def test_set_params(self): """ Create index locator with 3 base, 4 offset. and change it to something else. See if change was successful. Should not exception. """ index = mticker.IndexLocator(base=3, offset=4) index.set_params(base=7, offset=7) assert index._base == 7 assert index.offset == 7 class TestSymmetricalLogLocator(object): def test_set_params(self): """ Create symmetrical log locator with default subs =[1.0] numticks = 15, and change it to something else. See if change was successful. Should not exception. """ sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) sym.set_params(subs=[2.0], numticks=8) assert sym._subs == [2.0] assert sym.numticks == 8 class TestScalarFormatter(object): offset_data = [ (123, 189, 0), (-189, -123, 0), (12341, 12349, 12340), (-12349, -12341, -12340), (99999.5, 100010.5, 100000), (-100010.5, -99999.5, -100000), (99990.5, 100000.5, 100000), (-100000.5, -99990.5, -100000), (1233999, 1234001, 1234000), (-1234001, -1233999, -1234000), (1, 1, 1), (123, 123, 120), # Test cases courtesy of @WeatherGod (.4538, .4578, .45), (3789.12, 3783.1, 3780), (45124.3, 45831.75, 45000), (0.000721, 0.0007243, 0.00072), (12592.82, 12591.43, 12590), (9., 12., 0), (900., 1200., 0), (1900., 1200., 0), (0.99, 1.01, 1), (9.99, 10.01, 10), (99.99, 100.01, 100), (5.99, 6.01, 6), (15.99, 16.01, 16), (-0.452, 0.492, 0), (-0.492, 0.492, 0), (12331.4, 12350.5, 12300), (-12335.3, 12335.3, 0), ] use_offset_data = [True, False] @pytest.mark.parametrize('left, right, offset', offset_data) def test_offset_value(self, left, right, offset): fig, ax = plt.subplots() formatter = ax.get_xaxis().get_major_formatter() with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', 'Attempting to set identical', UserWarning) ax.set_xlim(left, right) assert len(w) == (1 if left == right else 0) # Update ticks. next(ax.get_xaxis().iter_ticks()) assert formatter.offset == offset with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', 'Attempting to set identical', UserWarning) ax.set_xlim(right, left) assert len(w) == (1 if left == right else 0) # Update ticks. next(ax.get_xaxis().iter_ticks()) assert formatter.offset == offset @pytest.mark.parametrize('use_offset', use_offset_data) def test_use_offset(self, use_offset): with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}): tmp_form = mticker.ScalarFormatter() assert use_offset == tmp_form.get_useOffset() class FakeAxis(object): """Allow Formatter to be called without having a "full" plot set up.""" def __init__(self, vmin=1, vmax=10): self.vmin = vmin self.vmax = vmax def get_view_interval(self): return self.vmin, self.vmax class TestLogFormatterExponent(object): param_data = [ (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0), ['-3', '-2', '-1', '0', '1', '2', '3']), # With labelOnlyBase=False, non-integer powers should be nicely # formatted. (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]), range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']), (False, 50, np.array([3, 5, 12, 42], dtype='float'), range(6), ['3', '5', '12', '42']), ] base_data = [2.0, 5.0, 10.0, np.pi, np.e] @pytest.mark.parametrize( 'labelOnlyBase, exponent, locs, positions, expected', param_data) @pytest.mark.parametrize('base', base_data) def test_basic(self, labelOnlyBase, base, exponent, locs, positions, expected): formatter = mticker.LogFormatterExponent(base=base, labelOnlyBase=labelOnlyBase) formatter.axis = FakeAxis(1, base**exponent) vals = base**locs labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)] assert labels == expected def test_blank(self): # Should be a blank string for non-integer powers if labelOnlyBase=True formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True) formatter.axis = FakeAxis() assert formatter(10**0.1) == '' class TestLogFormatterMathtext(): fmt = mticker.LogFormatterMathtext() test_data = [ (0, 1, '$\\mathdefault{10^{0}}$'), (0, 1e-2, '$\\mathdefault{10^{-2}}$'), (0, 1e2, '$\\mathdefault{10^{2}}$'), (3, 1, '$\\mathdefault{1}$'), (3, 1e-2, '$\\mathdefault{0.01}$'), (3, 1e2, '$\\mathdefault{100}$'), (3, 1e-3, '$\\mathdefault{10^{-3}}$'), (3, 1e3, '$\\mathdefault{10^{3}}$'), ] @pytest.mark.parametrize('min_exponent, value, expected', test_data) def test_min_exponent(self, min_exponent, value, expected): with matplotlib.rc_context({'axes.formatter.min_exponent': min_exponent}): assert self.fmt(value) == expected class TestLogFormatterSciNotation(object): test_data = [ (2, 0.03125, '$\\mathdefault{2^{-5}}$'), (2, 1, '$\\mathdefault{2^{0}}$'), (2, 32, '$\\mathdefault{2^{5}}$'), (2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'), (2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'), (2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'), (10, -1, '$\\mathdefault{-10^{0}}$'), (10, 1e-05, '$\\mathdefault{10^{-5}}$'), (10, 1, '$\\mathdefault{10^{0}}$'), (10, 100000, '$\\mathdefault{10^{5}}$'), (10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'), (10, 2, '$\\mathdefault{2\\times10^{0}}$'), (10, 200000, '$\\mathdefault{2\\times10^{5}}$'), (10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'), (10, 5, '$\\mathdefault{5\\times10^{0}}$'), (10, 500000, '$\\mathdefault{5\\times10^{5}}$'), ] @pytest.mark.style('default') @pytest.mark.parametrize('base, value, expected', test_data) def test_basic(self, base, value, expected): formatter = mticker.LogFormatterSciNotation(base=base) formatter.sublabel = {1, 2, 5, 1.2} with matplotlib.rc_context({'text.usetex': False}): assert formatter(value) == expected class TestLogFormatter(object): pprint_data = [ (3.141592654e-05, 0.001, '3.142e-5'), (0.0003141592654, 0.001, '3.142e-4'), (0.003141592654, 0.001, '3.142e-3'), (0.03141592654, 0.001, '3.142e-2'), (0.3141592654, 0.001, '3.142e-1'), (3.141592654, 0.001, '3.142'), (31.41592654, 0.001, '3.142e1'), (314.1592654, 0.001, '3.142e2'), (3141.592654, 0.001, '3.142e3'), (31415.92654, 0.001, '3.142e4'), (314159.2654, 0.001, '3.142e5'), (1e-05, 0.001, '1e-5'), (0.0001, 0.001, '1e-4'), (0.001, 0.001, '1e-3'), (0.01, 0.001, '1e-2'), (0.1, 0.001, '1e-1'), (1, 0.001, '1'), (10, 0.001, '10'), (100, 0.001, '100'), (1000, 0.001, '1000'), (10000, 0.001, '1e4'), (100000, 0.001, '1e5'), (3.141592654e-05, 0.015, '0'), (0.0003141592654, 0.015, '0'), (0.003141592654, 0.015, '0.003'), (0.03141592654, 0.015, '0.031'), (0.3141592654, 0.015, '0.314'), (3.141592654, 0.015, '3.142'), (31.41592654, 0.015, '31.416'), (314.1592654, 0.015, '314.159'), (3141.592654, 0.015, '3141.593'), (31415.92654, 0.015, '31415.927'), (314159.2654, 0.015, '314159.265'), (1e-05, 0.015, '0'), (0.0001, 0.015, '0'), (0.001, 0.015, '0.001'), (0.01, 0.015, '0.01'), (0.1, 0.015, '0.1'), (1, 0.015, '1'), (10, 0.015, '10'), (100, 0.015, '100'), (1000, 0.015, '1000'), (10000, 0.015, '10000'), (100000, 0.015, '100000'), (3.141592654e-05, 0.5, '0'), (0.0003141592654, 0.5, '0'), (0.003141592654, 0.5, '0.003'), (0.03141592654, 0.5, '0.031'), (0.3141592654, 0.5, '0.314'), (3.141592654, 0.5, '3.142'), (31.41592654, 0.5, '31.416'), (314.1592654, 0.5, '314.159'), (3141.592654, 0.5, '3141.593'), (31415.92654, 0.5, '31415.927'), (314159.2654, 0.5, '314159.265'), (1e-05, 0.5, '0'), (0.0001, 0.5, '0'), (0.001, 0.5, '0.001'), (0.01, 0.5, '0.01'), (0.1, 0.5, '0.1'), (1, 0.5, '1'), (10, 0.5, '10'), (100, 0.5, '100'), (1000, 0.5, '1000'), (10000, 0.5, '10000'), (100000, 0.5, '100000'), (3.141592654e-05, 5, '0'), (0.0003141592654, 5, '0'), (0.003141592654, 5, '0'), (0.03141592654, 5, '0.03'), (0.3141592654, 5, '0.31'), (3.141592654, 5, '3.14'), (31.41592654, 5, '31.42'), (314.1592654, 5, '314.16'), (3141.592654, 5, '3141.59'), (31415.92654, 5, '31415.93'), (314159.2654, 5, '314159.27'), (1e-05, 5, '0'), (0.0001, 5, '0'), (0.001, 5, '0'), (0.01, 5, '0.01'), (0.1, 5, '0.1'), (1, 5, '1'), (10, 5, '10'), (100, 5, '100'), (1000, 5, '1000'), (10000, 5, '10000'), (100000, 5, '100000'), (3.141592654e-05, 100, '0'), (0.0003141592654, 100, '0'), (0.003141592654, 100, '0'), (0.03141592654, 100, '0'), (0.3141592654, 100, '0.3'), (3.141592654, 100, '3.1'), (31.41592654, 100, '31.4'), (314.1592654, 100, '314.2'), (3141.592654, 100, '3141.6'), (31415.92654, 100, '31415.9'), (314159.2654, 100, '314159.3'), (1e-05, 100, '0'), (0.0001, 100, '0'), (0.001, 100, '0'), (0.01, 100, '0'), (0.1, 100, '0.1'), (1, 100, '1'), (10, 100, '10'), (100, 100, '100'), (1000, 100, '1000'), (10000, 100, '10000'), (100000, 100, '100000'), (3.141592654e-05, 1000000.0, '3.1e-5'), (0.0003141592654, 1000000.0, '3.1e-4'), (0.003141592654, 1000000.0, '3.1e-3'), (0.03141592654, 1000000.0, '3.1e-2'), (0.3141592654, 1000000.0, '3.1e-1'), (3.141592654, 1000000.0, '3.1'), (31.41592654, 1000000.0, '3.1e1'), (314.1592654, 1000000.0, '3.1e2'), (3141.592654, 1000000.0, '3.1e3'), (31415.92654, 1000000.0, '3.1e4'), (314159.2654, 1000000.0, '3.1e5'), (1e-05, 1000000.0, '1e-5'), (0.0001, 1000000.0, '1e-4'), (0.001, 1000000.0, '1e-3'), (0.01, 1000000.0, '1e-2'), (0.1, 1000000.0, '1e-1'), (1, 1000000.0, '1'), (10, 1000000.0, '10'), (100, 1000000.0, '100'), (1000, 1000000.0, '1000'), (10000, 1000000.0, '1e4'), (100000, 1000000.0, '1e5'), ] @pytest.mark.parametrize('value, domain, expected', pprint_data) def test_pprint(self, value, domain, expected): fmt = mticker.LogFormatter() label = fmt.pprint_val(value, domain) assert label == expected def _sub_labels(self, axis, subs=()): "Test whether locator marks subs to be labeled" fmt = axis.get_minor_formatter() minor_tlocs = axis.get_minorticklocs() fmt.set_locs(minor_tlocs) coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs))) label_expected = [np.round(c) in subs for c in coefs] label_test = [fmt(x) != '' for x in minor_tlocs] assert label_test == label_expected @pytest.mark.style('default') def test_sublabel(self): # test label locator fig, ax = plt.subplots() ax.set_xscale('log') ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[])) ax.xaxis.set_minor_locator(mticker.LogLocator(base=10, subs=np.arange(2, 10))) ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True)) ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False)) # axis range above 3 decades, only bases are labeled ax.set_xlim(1, 1e4) fmt = ax.xaxis.get_major_formatter() fmt.set_locs(ax.xaxis.get_majorticklocs()) show_major_labels = [fmt(x) != '' for x in ax.xaxis.get_majorticklocs()] assert np.all(show_major_labels) self._sub_labels(ax.xaxis, subs=[]) # For the next two, if the numdec threshold in LogFormatter.set_locs # were 3, then the label sub would be 3 for 2-3 decades and (2,5) # for 1-2 decades. With a threshold of 1, subs are not labeled. # axis range at 2 to 3 decades ax.set_xlim(1, 800) self._sub_labels(ax.xaxis, subs=[]) # axis range at 1 to 2 decades ax.set_xlim(1, 80) self._sub_labels(ax.xaxis, subs=[]) # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6 ax.set_xlim(1, 8) self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6]) # axis range at 0 to 0.4 decades, label all ax.set_xlim(0.5, 0.9) self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int)) @pytest.mark.parametrize('val', [1, 10, 100, 1000]) def test_LogFormatter_call(self, val): # test _num_to_string method used in __call__ temp_lf = mticker.LogFormatter() temp_lf.axis = FakeAxis() assert temp_lf(val) == str(val) class TestFormatStrFormatter(object): def test_basic(self): # test % style formatter tmp_form = mticker.FormatStrFormatter('%05d') assert '00002' == tmp_form(2) class TestStrMethodFormatter(object): test_data = [ ('{x:05d}', (2,), '00002'), ('{x:03d}-{pos:02d}', (2, 1), '002-01'), ] @pytest.mark.parametrize('format, input, expected', test_data) def test_basic(self, format, input, expected): fmt = mticker.StrMethodFormatter(format) assert fmt(*input) == expected class TestEngFormatter(object): # (input, expected) where ''expected'' corresponds to the outputs # respectively returned when (places=None, places=0, places=2) raw_format_data = [ (-1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')), (-1.23456789, ('-1.23457', '-1', '-1.23')), (-0.123456789, ('-123.457 m', '-123 m', '-123.46 m')), (-0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')), (-0.0, ('0', '0', '0.00')), (-0, ('0', '0', '0.00')), (0, ('0', '0', '0.00')), (1.23456789e-6, (u'1.23457 \u03bc', u'1 \u03bc', u'1.23 \u03bc')), (0.123456789, ('123.457 m', '123 m', '123.46 m')), (0.1, ('100 m', '100 m', '100.00 m')), (1, ('1', '1', '1.00')), (1.23456789, ('1.23457', '1', '1.23')), (999.9, ('999.9', '1 k', '999.90')), # places=0: corner-case rounding (999.9999, ('1 k', '1 k', '1.00 k')), # corner-case roudning for all (1000, ('1 k', '1 k', '1.00 k')), (1001, ('1.001 k', '1 k', '1.00 k')), (100001, ('100.001 k', '100 k', '100.00 k')), (987654.321, ('987.654 k', '988 k', '987.65 k')), (1.23e27, ('1230 Y', '1230 Y', '1230.00 Y')) # OoR value (> 1000 Y) ] @pytest.mark.parametrize('input, expected', raw_format_data) def test_params(self, input, expected): """ Test the formatting of EngFormatter for various values of the 'places' argument, in several cases: 0. without a unit symbol but with a (default) space separator; 1. with both a unit symbol and a (default) space separator; 2. with both a unit symbol and some non default separators; 3. without a unit symbol but with some non default separators. Note that cases 2. and 3. are looped over several separator strings. """ UNIT = 's' # seconds DIGITS = '0123456789' # %timeit showed 10-20% faster search than set # Case 0: unit='' (default) and sep=' ' (default). # 'expected' already corresponds to this reference case. exp_outputs = expected formatters = ( mticker.EngFormatter(), # places=None (default) mticker.EngFormatter(places=0), mticker.EngFormatter(places=2) ) for _formatter, _exp_output in zip(formatters, exp_outputs): assert _formatter(input) == _exp_output # Case 1: unit=UNIT and sep=' ' (default). # Append a unit symbol to the reference case. # Beware of the values in [1, 1000), where there is no prefix! exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix else _s + UNIT for _s in expected) formatters = ( mticker.EngFormatter(unit=UNIT), # places=None (default) mticker.EngFormatter(unit=UNIT, places=0), mticker.EngFormatter(unit=UNIT, places=2) ) for _formatter, _exp_output in zip(formatters, exp_outputs): assert _formatter(input) == _exp_output # Test several non default separators: no separator, a narrow # no-break space (unicode character) and an extravagant string. for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"): # Case 2: unit=UNIT and sep=_sep. # Replace the default space separator from the reference case # with the tested one `_sep` and append a unit symbol to it. exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix else _s.replace(" ", _sep) + UNIT for _s in expected) formatters = ( mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None mticker.EngFormatter(unit=UNIT, places=0, sep=_sep), mticker.EngFormatter(unit=UNIT, places=2, sep=_sep) ) for _formatter, _exp_output in zip(formatters, exp_outputs): assert _formatter(input) == _exp_output # Case 3: unit='' (default) and sep=_sep. # Replace the default space separator from the reference case # with the tested one `_sep`. Reference case is already unitless. exp_outputs = (_s.replace(" ", _sep) for _s in expected) formatters = ( mticker.EngFormatter(sep=_sep), # places=None (default) mticker.EngFormatter(places=0, sep=_sep), mticker.EngFormatter(places=2, sep=_sep) ) for _formatter, _exp_output in zip(formatters, exp_outputs): assert _formatter(input) == _exp_output class TestPercentFormatter(object): percent_data = [ # Check explicitly set decimals over different intervals and values (100, 0, '%', 120, 100, '120%'), (100, 0, '%', 100, 90, '100%'), (100, 0, '%', 90, 50, '90%'), (100, 0, '%', -1.7, 40, '-2%'), (100, 1, '%', 90.0, 100, '90.0%'), (100, 1, '%', 80.1, 90, '80.1%'), (100, 1, '%', 70.23, 50, '70.2%'), # 60.554 instead of 60.55: see https://bugs.python.org/issue5118 (100, 1, '%', -60.554, 40, '-60.6%'), # Check auto decimals over different intervals and values (100, None, '%', 95, 1, '95.00%'), (1.0, None, '%', 3, 6, '300%'), (17.0, None, '%', 1, 8.5, '6%'), (17.0, None, '%', 1, 8.4, '5.9%'), (5, None, '%', -100, 0.000001, '-2000.00000%'), # Check percent symbol (1.0, 2, None, 1.2, 100, '120.00'), (75, 3, '', 50, 100, '66.667'), (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'), ] percent_ids = [ # Check explicitly set decimals over different intervals and values 'decimals=0, x>100%', 'decimals=0, x=100%', 'decimals=0, x<100%', 'decimals=0, x<0%', 'decimals=1, x>100%', 'decimals=1, x=100%', 'decimals=1, x<100%', 'decimals=1, x<0%', # Check auto decimals over different intervals and values 'autodecimal, x<100%, display_range=1', 'autodecimal, x>100%, display_range=6 (custom xmax test)', 'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)', 'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)', 'autodecimal, x<-100%, display_range=1e-6 (tiny display range)', # Check percent symbol 'None as percent symbol', 'Empty percent symbol', 'Custom percent symbol', ] latex_data = [ (False, False, r'50\{t}%'), (False, True, r'50\\\{t\}\%'), (True, False, r'50\{t}%'), (True, True, r'50\{t}%'), ] @pytest.mark.parametrize( 'xmax, decimals, symbol, x, display_range, expected', percent_data, ids=percent_ids) def test_basic(self, xmax, decimals, symbol, x, display_range, expected): formatter = mticker.PercentFormatter(xmax, decimals, symbol) with matplotlib.rc_context(rc={'text.usetex': False}): assert formatter.format_pct(x, display_range) == expected @pytest.mark.parametrize('is_latex, usetex, expected', latex_data) def test_latex(self, is_latex, usetex, expected): fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex) with matplotlib.rc_context(rc={'text.usetex': usetex}): assert fmt.format_pct(50, 100) == expected
28,203
37.582763
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_category.py
# -*- coding: utf-8 -*- """Catch all for categorical functions""" from __future__ import absolute_import, division, print_function import pytest import numpy as np from matplotlib.axes import Axes import matplotlib.pyplot as plt import matplotlib.category as cat # Python2/3 text handling _to_str = cat.StrCategoryFormatter._text class TestUnitData(object): test_cases = [('single', (["hello world"], [0])), ('unicode', (["Здравствуйте мир"], [0])), ('mixed', (['A', "np.nan", 'B', "3.14", "мир"], [0, 1, 2, 3, 4]))] ids, data = zip(*test_cases) @pytest.mark.parametrize("data, locs", data, ids=ids) def test_unit(self, data, locs): unit = cat.UnitData(data) assert list(unit._mapping.keys()) == data assert list(unit._mapping.values()) == locs def test_update(self): data = ['a', 'd'] locs = [0, 1] data_update = ['b', 'd', 'e'] unique_data = ['a', 'd', 'b', 'e'] updated_locs = [0, 1, 2, 3] unit = cat.UnitData(data) assert list(unit._mapping.keys()) == data assert list(unit._mapping.values()) == locs unit.update(data_update) assert list(unit._mapping.keys()) == unique_data assert list(unit._mapping.values()) == updated_locs failing_test_cases = [("number", 3.14), ("nan", np.nan), ("list", [3.14, 12]), ("mixed type", ["A", 2])] fids, fdata = zip(*test_cases) @pytest.mark.parametrize("fdata", fdata, ids=fids) def test_non_string_fails(self, fdata): with pytest.raises(TypeError): cat.UnitData(fdata) @pytest.mark.parametrize("fdata", fdata, ids=fids) def test_non_string_update_fails(self, fdata): unitdata = cat.UnitData() with pytest.raises(TypeError): unitdata.update(fdata) class FakeAxis(object): def __init__(self, units): self.units = units class TestStrCategoryConverter(object): """Based on the pandas conversion and factorization tests: ref: /pandas/tseries/tests/test_converter.py /pandas/tests/test_algos.py:TestFactorize """ test_cases = [("unicode", ["Здравствуйте мир"]), ("ascii", ["hello world"]), ("single", ['a', 'b', 'c']), ("integer string", ["1", "2"]), ("single + values>10", ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"])] ids, values = zip(*test_cases) failing_test_cases = [("mixed", [3.14, 'A', np.inf]), ("string integer", ['42', 42])] fids, fvalues = zip(*failing_test_cases) @pytest.fixture(autouse=True) def mock_axis(self, request): self.cc = cat.StrCategoryConverter() # self.unit should be probably be replaced with real mock unit self.unit = cat.UnitData() self.ax = FakeAxis(self.unit) @pytest.mark.parametrize("vals", values, ids=ids) def test_convert(self, vals): np.testing.assert_allclose(self.cc.convert(vals, self.ax.units, self.ax), range(len(vals))) @pytest.mark.parametrize("value", ["hi", "мир"], ids=["ascii", "unicode"]) def test_convert_one_string(self, value): assert self.cc.convert(value, self.unit, self.ax) == 0 def test_convert_one_number(self): actual = self.cc.convert(0.0, self.unit, self.ax) np.testing.assert_allclose(actual, np.array([0.])) def test_convert_float_array(self): data = np.array([1, 2, 3], dtype=float) actual = self.cc.convert(data, self.unit, self.ax) np.testing.assert_allclose(actual, np.array([1., 2., 3.])) @pytest.mark.parametrize("fvals", fvalues, ids=fids) def test_convert_fail(self, fvals): with pytest.raises(TypeError): self.cc.convert(fvals, self.unit, self.ax) def test_axisinfo(self): axis = self.cc.axisinfo(self.unit, self.ax) assert isinstance(axis.majloc, cat.StrCategoryLocator) assert isinstance(axis.majfmt, cat.StrCategoryFormatter) def test_default_units(self): assert isinstance(self.cc.default_units(["a"], self.ax), cat.UnitData) @pytest.fixture def ax(): return plt.figure().subplots() PLOT_LIST = [Axes.scatter, Axes.plot, Axes.bar] PLOT_IDS = ["scatter", "plot", "bar"] class TestStrCategoryLocator(object): def test_StrCategoryLocator(self): locs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] unit = cat.UnitData([str(j) for j in locs]) ticks = cat.StrCategoryLocator(unit._mapping) np.testing.assert_array_equal(ticks.tick_values(None, None), locs) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_StrCategoryLocatorPlot(self, ax, plotter): ax.plot(["a", "b", "c"]) np.testing.assert_array_equal(ax.yaxis.major.locator(), range(3)) class TestStrCategoryFormatter(object): test_cases = [("ascii", ["hello", "world", "hi"]), ("unicode", ["Здравствуйте", "привет"])] ids, cases = zip(*test_cases) @pytest.mark.parametrize("ydata", cases, ids=ids) def test_StrCategoryFormatter(self, ax, ydata): unit = cat.UnitData(ydata) labels = cat.StrCategoryFormatter(unit._mapping) for i, d in enumerate(ydata): assert labels(i, i) == _to_str(d) @pytest.mark.parametrize("ydata", cases, ids=ids) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_StrCategoryFormatterPlot(self, ax, ydata, plotter): plotter(ax, range(len(ydata)), ydata) for i, d in enumerate(ydata): assert ax.yaxis.major.formatter(i, i) == _to_str(d) assert ax.yaxis.major.formatter(i+1, i+1) == "" assert ax.yaxis.major.formatter(0, None) == "" def axis_test(axis, labels): ticks = list(range(len(labels))) np.testing.assert_array_equal(axis.get_majorticklocs(), ticks) graph_labels = [axis.major.formatter(i, i) for i in ticks] assert graph_labels == [_to_str(l) for l in labels] assert list(axis.units._mapping.keys()) == [l for l in labels] assert list(axis.units._mapping.values()) == ticks class TestPlotBytes(object): bytes_cases = [('string list', ['a', 'b', 'c']), ('bytes list', [b'a', b'b', b'c']), ('bytes ndarray', np.array([b'a', b'b', b'c']))] bytes_ids, bytes_data = zip(*bytes_cases) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) @pytest.mark.parametrize("bdata", bytes_data, ids=bytes_ids) def test_plot_bytes(self, ax, plotter, bdata): counts = np.array([4, 6, 5]) plotter(ax, bdata, counts) axis_test(ax.xaxis, bdata) class TestPlotNumlike(object): numlike_cases = [('string list', ['1', '11', '3']), ('string ndarray', np.array(['1', '11', '3'])), ('bytes list', [b'1', b'11', b'3']), ('bytes ndarray', np.array([b'1', b'11', b'3']))] numlike_ids, numlike_data = zip(*numlike_cases) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) @pytest.mark.parametrize("ndata", numlike_data, ids=numlike_ids) def test_plot_numlike(self, ax, plotter, ndata): counts = np.array([4, 6, 5]) plotter(ax, ndata, counts) axis_test(ax.xaxis, ndata) class TestPlotTypes(object): @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_unicode(self, ax, plotter): words = ['Здравствуйте', 'привет'] plotter(ax, words, [0, 1]) axis_test(ax.xaxis, words) @pytest.fixture def test_data(self): self.x = ["hello", "happy", "world"] self.xy = [2, 6, 3] self.y = ["Python", "is", "fun"] self.yx = [3, 4, 5] @pytest.mark.usefixtures("test_data") @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_xaxis(self, ax, test_data, plotter): plotter(ax, self.x, self.xy) axis_test(ax.xaxis, self.x) @pytest.mark.usefixtures("test_data") @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_yaxis(self, ax, test_data, plotter): plotter(ax, self.yx, self.y) axis_test(ax.yaxis, self.y) @pytest.mark.usefixtures("test_data") @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_xyaxis(self, ax, test_data, plotter): plotter(ax, self.x, self.y) axis_test(ax.xaxis, self.x) axis_test(ax.yaxis, self.y) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_update_plot(self, ax, plotter): plotter(ax, ['a', 'b'], ['e', 'g']) plotter(ax, ['a', 'b', 'd'], ['f', 'a', 'b']) plotter(ax, ['b', 'c', 'd'], ['g', 'e', 'd']) axis_test(ax.xaxis, ['a', 'b', 'd', 'c']) axis_test(ax.yaxis, ['e', 'g', 'f', 'a', 'b', 'd']) failing_test_cases = [("mixed", ['A', 3.14]), ("number integer", ['1', 1]), ("string integer", ['42', 42]), ("missing", ['12', np.nan])] fids, fvalues = zip(*failing_test_cases) PLOT_BROKEN_LIST = [Axes.scatter, pytest.param(Axes.plot, marks=pytest.mark.xfail), pytest.param(Axes.bar, marks=pytest.mark.xfail)] PLOT_BROKEN_IDS = ["scatter", "plot", "bar"] @pytest.mark.parametrize("plotter", PLOT_BROKEN_LIST, ids=PLOT_BROKEN_IDS) @pytest.mark.parametrize("xdata", fvalues, ids=fids) def test_mixed_type_exception(self, ax, plotter, xdata): with pytest.raises(TypeError): plotter(ax, xdata, [1, 2]) @pytest.mark.parametrize("plotter", PLOT_BROKEN_LIST, ids=PLOT_BROKEN_IDS) @pytest.mark.parametrize("xdata", fvalues, ids=fids) def test_mixed_type_update_exception(self, ax, plotter, xdata): with pytest.raises(TypeError): plotter(ax, [0, 3], [1, 3]) plotter(ax, xdata, [1, 2])
10,321
35.996416
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_quiver.py
from __future__ import print_function import warnings import numpy as np import pytest import sys from matplotlib import pyplot as plt from matplotlib.testing.decorators import image_comparison def draw_quiver(ax, **kw): X, Y = np.meshgrid(np.arange(0, 2 * np.pi, 1), np.arange(0, 2 * np.pi, 1)) U = np.cos(X) V = np.sin(Y) Q = ax.quiver(U, V, **kw) return Q def test_quiver_memory_leak(): fig, ax = plt.subplots() Q = draw_quiver(ax) ttX = Q.X Q.remove() del Q assert sys.getrefcount(ttX) == 2 def test_quiver_key_memory_leak(): fig, ax = plt.subplots() Q = draw_quiver(ax) qk = ax.quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) assert sys.getrefcount(qk) == 3 qk.remove() assert sys.getrefcount(qk) == 2 def test_no_warnings(): fig, ax = plt.subplots() X, Y = np.meshgrid(np.arange(15), np.arange(10)) U = V = np.ones_like(X) phi = (np.random.rand(15, 10) - .5) * 150 with warnings.catch_warnings(record=True) as w: ax.quiver(X, Y, U, V, angles=phi) fig.canvas.draw() assert len(w) == 0 def test_zero_headlength(): # Based on report by Doug McNeil: # http://matplotlib.1069221.n5.nabble.com/quiver-warnings-td28107.html fig, ax = plt.subplots() X, Y = np.meshgrid(np.arange(10), np.arange(10)) U, V = np.cos(X), np.sin(Y) with warnings.catch_warnings(record=True) as w: ax.quiver(U, V, headlength=0, headaxislength=0) fig.canvas.draw() assert len(w) == 0 @image_comparison(baseline_images=['quiver_animated_test_image'], extensions=['png']) def test_quiver_animate(): # Tests fix for #2616 fig, ax = plt.subplots() Q = draw_quiver(ax, animated=True) qk = ax.quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) @image_comparison(baseline_images=['quiver_with_key_test_image'], extensions=['png']) def test_quiver_with_key(): fig, ax = plt.subplots() ax.margins(0.1) Q = draw_quiver(ax) qk = ax.quiverkey(Q, 0.5, 0.95, 2, r'$2\, \mathrm{m}\, \mathrm{s}^{-1}$', angle=-10, coordinates='figure', labelpos='W', fontproperties={'weight': 'bold', 'size': 'large'}) @image_comparison(baseline_images=['quiver_single_test_image'], extensions=['png'], remove_text=True) def test_quiver_single(): fig, ax = plt.subplots() ax.margins(0.1) ax.quiver([1], [1], [2], [2]) def test_quiver_copy(): fig, ax = plt.subplots() uv = dict(u=np.array([1.1]), v=np.array([2.0])) q0 = ax.quiver([1], [1], uv['u'], uv['v']) uv['v'][0] = 0 assert q0.V[0] == 2.0 @image_comparison(baseline_images=['quiver_key_pivot'], extensions=['png'], remove_text=True) def test_quiver_key_pivot(): fig, ax = plt.subplots() u, v = np.mgrid[0:2*np.pi:10j, 0:2*np.pi:10j] q = ax.quiver(np.sin(u), np.cos(v)) ax.set_xlim(-2, 11) ax.set_ylim(-2, 11) ax.quiverkey(q, 0.5, 1, 1, 'N', labelpos='N') ax.quiverkey(q, 1, 0.5, 1, 'E', labelpos='E') ax.quiverkey(q, 0.5, 0, 1, 'S', labelpos='S') ax.quiverkey(q, 0, 0.5, 1, 'W', labelpos='W') @image_comparison(baseline_images=['barbs_test_image'], extensions=['png'], remove_text=True) def test_barbs(): x = np.linspace(-5, 5, 5) X, Y = np.meshgrid(x, x) U, V = 12*X, 12*Y fig, ax = plt.subplots() ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False, sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3), cmap='viridis') @image_comparison(baseline_images=['barbs_pivot_test_image'], extensions=['png'], remove_text=True) def test_barbs_pivot(): x = np.linspace(-5, 5, 5) X, Y = np.meshgrid(x, x) U, V = 12*X, 12*Y fig, ax = plt.subplots() ax.barbs(X, Y, U, V, fill_empty=True, rounding=False, pivot=1.7, sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3)) ax.scatter(X, Y, s=49, c='black') def test_bad_masked_sizes(): 'Test error handling when given differing sized masked arrays' x = np.arange(3) y = np.arange(3) u = np.ma.array(15. * np.ones((4,))) v = np.ma.array(15. * np.ones_like(u)) u[1] = np.ma.masked v[1] = np.ma.masked fig, ax = plt.subplots() with pytest.raises(ValueError): ax.barbs(x, y, u, v) def test_angles_and_scale(): # angles array + scale_units kwarg fig, ax = plt.subplots() X, Y = np.meshgrid(np.arange(15), np.arange(10)) U = V = np.ones_like(X) phi = (np.random.rand(15, 10) - .5) * 150 ax.quiver(X, Y, U, V, angles=phi, scale_units='xy') @image_comparison(baseline_images=['quiver_xy'], extensions=['png'], remove_text=True) def test_quiver_xy(): # simple arrow pointing from SW to NE fig, ax = plt.subplots(subplot_kw=dict(aspect='equal')) ax.quiver(0, 0, 1, 1, angles='xy', scale_units='xy', scale=1) ax.set_xlim(0, 1.1) ax.set_ylim(0, 1.1) ax.grid() def test_quiverkey_angles(): # Check that only a single arrow is plotted for a quiverkey when an array # of angles is given to the original quiver plot fig, ax = plt.subplots() X, Y = np.meshgrid(np.arange(2), np.arange(2)) U = V = angles = np.ones_like(X) q = ax.quiver(X, Y, U, V, angles=angles) qk = ax.quiverkey(q, 1, 1, 2, 'Label') # The arrows are only created when the key is drawn fig.canvas.draw() assert len(qk.verts) == 1
5,827
27.70936
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_spines.py
from __future__ import absolute_import, division, print_function import numpy as np import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison @image_comparison(baseline_images=['spines_axes_positions']) def test_spines_axes_positions(): # SF bug 2852168 fig = plt.figure() x = np.linspace(0, 2*np.pi, 100) y = 2*np.sin(x) ax = fig.add_subplot(1, 1, 1) ax.set_title('centered spines') ax.plot(x, y) ax.spines['right'].set_position(('axes', 0.1)) ax.yaxis.set_ticks_position('right') ax.spines['top'].set_position(('axes', 0.25)) ax.xaxis.set_ticks_position('top') ax.spines['left'].set_color('none') ax.spines['bottom'].set_color('none') @image_comparison(baseline_images=['spines_data_positions']) def test_spines_data_positions(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.spines['left'].set_position(('data', -1.5)) ax.spines['top'].set_position(('data', 0.5)) ax.spines['right'].set_position(('data', -0.5)) ax.spines['bottom'].set_position('zero') ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) @image_comparison(baseline_images=['spines_capstyle']) def test_spines_capstyle(): # issue 2542 plt.rc('axes', linewidth=20) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xticks([]) ax.set_yticks([]) def test_label_without_ticks(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.subplots_adjust(left=0.3, bottom=0.3) ax.plot(np.arange(10)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('outward', 30)) ax.spines['right'].set_visible(False) ax.set_ylabel('y label') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('outward', 30)) ax.spines['top'].set_visible(False) ax.set_xlabel('x label') ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) plt.draw() spine = ax.spines['left'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() assert ax.yaxis.label.get_position()[0] < spinebbox.xmin, \ "Y-Axis label not left of the spine" spine = ax.spines['bottom'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() assert ax.xaxis.label.get_position()[1] < spinebbox.ymin, \ "X-Axis label not below the spine"
2,392
30.486842
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_image.py
from __future__ import absolute_import, division, print_function import six from copy import copy import io import os import sys import warnings import numpy as np from numpy import ma from numpy.testing import assert_array_equal from matplotlib import ( colors, image as mimage, patches, pyplot as plt, rc_context, rcParams) from matplotlib.image import (AxesImage, BboxImage, FigureImage, NonUniformImage, PcolorImage) from matplotlib.testing.decorators import image_comparison from matplotlib.transforms import Bbox, Affine2D, TransformedBbox import pytest try: from PIL import Image HAS_PIL = True except ImportError: HAS_PIL = False needs_pillow = pytest.mark.xfail(not HAS_PIL, reason='Test requires Pillow') @image_comparison(baseline_images=['image_interps'], style='mpl20') def test_image_interps(): 'make the basic nearest, bilinear and bicubic interps' X = np.arange(100) X = X.reshape(5, 20) fig = plt.figure() ax1 = fig.add_subplot(311) ax1.imshow(X, interpolation='nearest') ax1.set_title('three interpolations') ax1.set_ylabel('nearest') ax2 = fig.add_subplot(312) ax2.imshow(X, interpolation='bilinear') ax2.set_ylabel('bilinear') ax3 = fig.add_subplot(313) ax3.imshow(X, interpolation='bicubic') ax3.set_ylabel('bicubic') @image_comparison(baseline_images=['interp_nearest_vs_none'], extensions=['pdf', 'svg'], remove_text=True) def test_interp_nearest_vs_none(): 'Test the effect of "nearest" and "none" interpolation' # Setting dpi to something really small makes the difference very # visible. This works fine with pdf, since the dpi setting doesn't # affect anything but images, but the agg output becomes unusably # small. rcParams['savefig.dpi'] = 3 X = np.array([[[218, 165, 32], [122, 103, 238]], [[127, 255, 0], [255, 99, 71]]], dtype=np.uint8) fig = plt.figure() ax1 = fig.add_subplot(121) ax1.imshow(X, interpolation='none') ax1.set_title('interpolation none') ax2 = fig.add_subplot(122) ax2.imshow(X, interpolation='nearest') ax2.set_title('interpolation nearest') def do_figimage(suppressComposite): """ Helper for the next two tests """ fig = plt.figure(figsize=(2,2), dpi=100) fig.suppressComposite = suppressComposite x,y = np.ix_(np.arange(100.0)/100.0, np.arange(100.0)/100.0) z = np.sin(x**2 + y**2 - x*y) c = np.sin(20*x**2 + 50*y**2) img = z + c/5 fig.figimage(img, xo=0, yo=0, origin='lower') fig.figimage(img[::-1,:], xo=0, yo=100, origin='lower') fig.figimage(img[:,::-1], xo=100, yo=0, origin='lower') fig.figimage(img[::-1,::-1], xo=100, yo=100, origin='lower') @image_comparison(baseline_images=['figimage-0'], extensions=['png','pdf']) def test_figimage0(): 'test the figimage method' suppressComposite = False do_figimage(suppressComposite) @image_comparison(baseline_images=['figimage-1'], extensions=['png','pdf']) def test_figimage1(): 'test the figimage method' suppressComposite = True do_figimage(suppressComposite) def test_image_python_io(): fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3]) buffer = io.BytesIO() fig.savefig(buffer) buffer.seek(0) plt.imread(buffer) @needs_pillow def test_imread_pil_uint16(): img = plt.imread(os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_image', 'uint16.tif')) assert (img.dtype == np.uint16) assert np.sum(img) == 134184960 @pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python 3.6+") @needs_pillow def test_imread_fspath(): from pathlib import Path img = plt.imread( Path(__file__).parent / 'baseline_images/test_image/uint16.tif') assert img.dtype == np.uint16 assert np.sum(img) == 134184960 def test_imsave(): # The goal here is that the user can specify an output logical DPI # for the image, but this will not actually add any extra pixels # to the image, it will merely be used for metadata purposes. # So we do the traditional case (dpi == 1), and the new case (dpi # == 100) and read the resulting PNG files back in and make sure # the data is 100% identical. np.random.seed(1) data = np.random.rand(256, 128) buff_dpi1 = io.BytesIO() plt.imsave(buff_dpi1, data, dpi=1) buff_dpi100 = io.BytesIO() plt.imsave(buff_dpi100, data, dpi=100) buff_dpi1.seek(0) arr_dpi1 = plt.imread(buff_dpi1) buff_dpi100.seek(0) arr_dpi100 = plt.imread(buff_dpi100) assert arr_dpi1.shape == (256, 128, 4) assert arr_dpi100.shape == (256, 128, 4) assert_array_equal(arr_dpi1, arr_dpi100) @pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python 3.6+") @pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"]) def test_imsave_fspath(fmt): Path = pytest.importorskip("pathlib").Path plt.imsave(Path(os.devnull), np.array([[0, 1]]), format=fmt) def test_imsave_color_alpha(): # Test that imsave accept arrays with ndim=3 where the third dimension is # color and alpha without raising any exceptions, and that the data is # acceptably preserved through a save/read roundtrip. np.random.seed(1) for origin in ['lower', 'upper']: data = np.random.rand(16, 16, 4) buff = io.BytesIO() plt.imsave(buff, data, origin=origin, format="png") buff.seek(0) arr_buf = plt.imread(buff) # Recreate the float -> uint8 conversion of the data # We can only expect to be the same with 8 bits of precision, # since that's what the PNG file used. data = (255*data).astype('uint8') if origin == 'lower': data = data[::-1] arr_buf = (255*arr_buf).astype('uint8') assert_array_equal(data, arr_buf) @image_comparison(baseline_images=['image_alpha'], remove_text=True) def test_image_alpha(): plt.figure() np.random.seed(0) Z = np.random.rand(6, 6) plt.subplot(131) plt.imshow(Z, alpha=1.0, interpolation='none') plt.subplot(132) plt.imshow(Z, alpha=0.5, interpolation='none') plt.subplot(133) plt.imshow(Z, alpha=0.5, interpolation='nearest') def test_cursor_data(): from matplotlib.backend_bases import MouseEvent fig, ax = plt.subplots() im = ax.imshow(np.arange(100).reshape(10, 10), origin='upper') x, y = 4, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 44 # Now try for a point outside the image # Tests issue #4957 x, y = 10.1, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) is None # Hmm, something is wrong here... I get 0, not None... # But, this works further down in the tests with extents flipped #x, y = 0.1, -0.1 #xdisp, ydisp = ax.transData.transform_point([x, y]) #event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) #z = im.get_cursor_data(event) #assert z is None, "Did not get None, got %d" % z ax.clear() # Now try with the extents flipped. im = ax.imshow(np.arange(100).reshape(10, 10), origin='lower') x, y = 4, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 44 fig, ax = plt.subplots() im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5]) x, y = 0.25, 0.25 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 55 # Now try for a point outside the image # Tests issue #4957 x, y = 0.75, 0.25 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) is None x, y = 0.01, -0.01 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) is None @image_comparison(baseline_images=['image_clip'], style='mpl20') def test_image_clip(): d = [[1, 2], [3, 4]] fig, ax = plt.subplots() im = ax.imshow(d) patch = patches.Circle((0, 0), radius=1, transform=ax.transData) im.set_clip_path(patch) @image_comparison(baseline_images=['image_cliprect'], style='mpl20') def test_image_cliprect(): import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111) d = [[1,2],[3,4]] im = ax.imshow(d, extent=(0,5,0,5)) rect = patches.Rectangle(xy=(1,1), width=2, height=2, transform=im.axes.transData) im.set_clip_path(rect) @image_comparison(baseline_images=['imshow'], remove_text=True, style='mpl20') def test_imshow(): import numpy as np import matplotlib.pyplot as plt fig = plt.figure() arr = np.arange(100).reshape((10, 10)) ax = fig.add_subplot(111) ax.imshow(arr, interpolation="bilinear", extent=(1,2,1,2)) ax.set_xlim(0,3) ax.set_ylim(0,3) @image_comparison(baseline_images=['no_interpolation_origin'], remove_text=True) def test_no_interpolation_origin(): fig = plt.figure() ax = fig.add_subplot(211) ax.imshow(np.arange(100).reshape((2, 50)), origin="lower", interpolation='none') ax = fig.add_subplot(212) ax.imshow(np.arange(100).reshape((2, 50)), interpolation='none') @image_comparison(baseline_images=['image_shift'], remove_text=True, extensions=['pdf', 'svg']) def test_image_shift(): from matplotlib.colors import LogNorm imgData = [[1.0/(x) + 1.0/(y) for x in range(1,100)] for y in range(1,100)] tMin=734717.945208 tMax=734717.946366 fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(imgData, norm=LogNorm(), interpolation='none', extent=(tMin, tMax, 1, 100)) ax.set_aspect('auto') def test_image_edges(): f = plt.figure(figsize=[1, 1]) ax = f.add_axes([0, 0, 1, 1], frameon=False) data = np.tile(np.arange(12), 15).reshape(20, 9) im = ax.imshow(data, origin='upper', extent=[-10, 10, -10, 10], interpolation='none', cmap='gray') x = y = 2 ax.set_xlim([-x, x]) ax.set_ylim([-y, y]) ax.set_xticks([]) ax.set_yticks([]) buf = io.BytesIO() f.savefig(buf, facecolor=(0, 1, 0)) buf.seek(0) im = plt.imread(buf) r, g, b, a = sum(im[:, 0]) r, g, b, a = sum(im[:, -1]) assert g != 100, 'Expected a non-green edge - but sadly, it was.' @image_comparison(baseline_images=['image_composite_background'], remove_text=True, style='mpl20') def test_image_composite_background(): fig = plt.figure() ax = fig.add_subplot(111) arr = np.arange(12).reshape(4, 3) ax.imshow(arr, extent=[0, 2, 15, 0]) ax.imshow(arr, extent=[4, 6, 15, 0]) ax.set_facecolor((1, 0, 0, 0.5)) ax.set_xlim([0, 12]) @image_comparison(baseline_images=['image_composite_alpha'], remove_text=True) def test_image_composite_alpha(): """ Tests that the alpha value is recognized and correctly applied in the process of compositing images together. """ fig = plt.figure() ax = fig.add_subplot(111) arr = np.zeros((11, 21, 4)) arr[:, :, 0] = 1 arr[:, :, 3] = np.concatenate((np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1])) arr2 = np.zeros((21, 11, 4)) arr2[:, :, 0] = 1 arr2[:, :, 1] = 1 arr2[:, :, 3] = np.concatenate((np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1]))[:, np.newaxis] ax.imshow(arr, extent=[1, 2, 5, 0], alpha=0.3) ax.imshow(arr, extent=[2, 3, 5, 0], alpha=0.6) ax.imshow(arr, extent=[3, 4, 5, 0]) ax.imshow(arr2, extent=[0, 5, 1, 2]) ax.imshow(arr2, extent=[0, 5, 2, 3], alpha=0.6) ax.imshow(arr2, extent=[0, 5, 3, 4], alpha=0.3) ax.set_facecolor((0, 0.5, 0, 1)) ax.set_xlim([0, 5]) ax.set_ylim([5, 0]) @image_comparison(baseline_images=['rasterize_10dpi'], extensions=['pdf', 'svg'], remove_text=True, style='mpl20') def test_rasterize_dpi(): # This test should check rasterized rendering with high output resolution. # It plots a rasterized line and a normal image with implot. So it will catch # when images end up in the wrong place in case of non-standard dpi setting. # Instead of high-res rasterization i use low-res. Therefore the fact that the # resolution is non-standard is easily checked by image_comparison. import numpy as np import matplotlib.pyplot as plt img = np.asarray([[1, 2], [3, 4]]) fig, axes = plt.subplots(1, 3, figsize = (3, 1)) axes[0].imshow(img) axes[1].plot([0,1],[0,1], linewidth=20., rasterized=True) axes[1].set(xlim = (0,1), ylim = (-1, 2)) axes[2].plot([0,1],[0,1], linewidth=20.) axes[2].set(xlim = (0,1), ylim = (-1, 2)) # Low-dpi PDF rasterization errors prevent proper image comparison tests. # Hide detailed structures like the axes spines. for ax in axes: ax.set_xticks([]) ax.set_yticks([]) for spine in ax.spines.values(): spine.set_visible(False) rcParams['savefig.dpi'] = 10 @image_comparison(baseline_images=['bbox_image_inverted'], remove_text=True, style='mpl20') def test_bbox_image_inverted(): # This is just used to produce an image to feed to BboxImage image = np.arange(100).reshape((10, 10)) ax = plt.subplot(111) bbox_im = BboxImage( TransformedBbox(Bbox([[100, 100], [0, 0]]), ax.transData)) bbox_im.set_data(image) bbox_im.set_clip_on(False) ax.set_xlim(0, 100) ax.set_ylim(0, 100) ax.add_artist(bbox_im) image = np.identity(10) bbox_im = BboxImage( TransformedBbox(Bbox([[0.1, 0.2], [0.3, 0.25]]), ax.figure.transFigure)) bbox_im.set_data(image) bbox_im.set_clip_on(False) ax.add_artist(bbox_im) def test_get_window_extent_for_AxisImage(): # Create a figure of known size (1000x1000 pixels), place an image # object at a given location and check that get_window_extent() # returns the correct bounding box values (in pixels). im = np.array([[0.25, 0.75, 1.0, 0.75], [0.1, 0.65, 0.5, 0.4], [0.6, 0.3, 0.0, 0.2], [0.7, 0.9, 0.4, 0.6]]) fig = plt.figure(figsize=(10, 10), dpi=100) ax = plt.subplot() ax.set_position([0, 0, 1, 1]) ax.set_xlim(0, 1) ax.set_ylim(0, 1) im_obj = ax.imshow(im, extent=[0.4, 0.7, 0.2, 0.9], interpolation='nearest') fig.canvas.draw() renderer = fig.canvas.renderer im_bbox = im_obj.get_window_extent(renderer) assert_array_equal(im_bbox.get_points(), [[400, 200], [700, 900]]) @image_comparison(baseline_images=['zoom_and_clip_upper_origin'], remove_text=True, extensions=['png'], style='mpl20') def test_zoom_and_clip_upper_origin(): image = np.arange(100) image = image.reshape((10, 10)) fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(image) ax.set_ylim(2.0, -0.5) ax.set_xlim(-0.5, 2.0) def test_nonuniformimage_setcmap(): ax = plt.gca() im = NonUniformImage(ax) im.set_cmap('Blues') def test_nonuniformimage_setnorm(): ax = plt.gca() im = NonUniformImage(ax) im.set_norm(plt.Normalize()) @needs_pillow def test_jpeg_2d(): # smoke test that mode-L pillow images work. imd = np.ones((10, 10), dtype='uint8') for i in range(10): imd[i, :] = np.linspace(0.0, 1.0, 10) * 255 im = Image.new('L', (10, 10)) im.putdata(imd.flatten()) fig, ax = plt.subplots() ax.imshow(im) @needs_pillow def test_jpeg_alpha(): plt.figure(figsize=(1, 1), dpi=300) # Create an image that is all black, with a gradient from 0-1 in # the alpha channel from left to right. im = np.zeros((300, 300, 4), dtype=float) im[..., 3] = np.linspace(0.0, 1.0, 300) plt.figimage(im) buff = io.BytesIO() with rc_context({'savefig.facecolor': 'red'}): plt.savefig(buff, transparent=True, format='jpg', dpi=300) buff.seek(0) image = Image.open(buff) # If this fails, there will be only one color (all black). If this # is working, we should have all 256 shades of grey represented. num_colors = len(image.getcolors(256)) assert 175 <= num_colors <= 185 # The fully transparent part should be red. corner_pixel = image.getpixel((0, 0)) assert corner_pixel == (254, 0, 0) def test_nonuniformimage_setdata(): ax = plt.gca() im = NonUniformImage(ax) x = np.arange(3, dtype=float) y = np.arange(4, dtype=float) z = np.arange(12, dtype=float).reshape((4, 3)) im.set_data(x, y, z) x[0] = y[0] = z[0, 0] = 9.9 assert im._A[0, 0] == im._Ax[0] == im._Ay[0] == 0, 'value changed' def test_axesimage_setdata(): ax = plt.gca() im = AxesImage(ax) z = np.arange(12, dtype=float).reshape((4, 3)) im.set_data(z) z[0, 0] = 9.9 assert im._A[0, 0] == 0, 'value changed' def test_figureimage_setdata(): fig = plt.gcf() im = FigureImage(fig) z = np.arange(12, dtype=float).reshape((4, 3)) im.set_data(z) z[0, 0] = 9.9 assert im._A[0, 0] == 0, 'value changed' def test_pcolorimage_setdata(): ax = plt.gca() im = PcolorImage(ax) x = np.arange(3, dtype=float) y = np.arange(4, dtype=float) z = np.arange(6, dtype=float).reshape((3, 2)) im.set_data(x, y, z) x[0] = y[0] = z[0, 0] = 9.9 assert im._A[0, 0] == im._Ax[0] == im._Ay[0] == 0, 'value changed' def test_pcolorimage_extent(): im = plt.hist2d([1, 2, 3], [3, 5, 6], bins=[[0, 3, 7], [1, 2, 3]])[-1] assert im.get_extent() == (0, 7, 1, 3) def test_minimized_rasterized(): # This ensures that the rasterized content in the colorbars is # only as thick as the colorbar, and doesn't extend to other parts # of the image. See #5814. While the original bug exists only # in Postscript, the best way to detect it is to generate SVG # and then parse the output to make sure the two colorbar images # are the same size. from xml.etree import ElementTree np.random.seed(0) data = np.random.rand(10, 10) fig, ax = plt.subplots(1, 2) p1 = ax[0].pcolormesh(data) p2 = ax[1].pcolormesh(data) plt.colorbar(p1, ax=ax[0]) plt.colorbar(p2, ax=ax[1]) buff = io.BytesIO() plt.savefig(buff, format='svg') buff = io.BytesIO(buff.getvalue()) tree = ElementTree.parse(buff) width = None for image in tree.iter('image'): if width is None: width = image['width'] else: if image['width'] != width: assert False @pytest.mark.network def test_load_from_url(): req = six.moves.urllib.request.urlopen( "http://matplotlib.org/_static/logo_sidebar_horiz.png") plt.imread(req) @image_comparison(baseline_images=['log_scale_image'], remove_text=True) # The recwarn fixture captures a warning in image_comparison. def test_log_scale_image(recwarn): Z = np.zeros((10, 10)) Z[::2] = 1 fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(Z, extent=[1, 100, 1, 100], cmap='viridis', vmax=1, vmin=-1) ax.set_yscale('log') @image_comparison(baseline_images=['rotate_image'], remove_text=True) def test_rotate_image(): delta = 0.25 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / (2 * np.pi * 0.5 * 1.5)) Z = Z2 - Z1 # difference of Gaussians fig, ax1 = plt.subplots(1, 1) im1 = ax1.imshow(Z, interpolation='none', cmap='viridis', origin='lower', extent=[-2, 4, -3, 2], clip_on=True) trans_data2 = Affine2D().rotate_deg(30) + ax1.transData im1.set_transform(trans_data2) # display intended extent of the image x1, x2, y1, y2 = im1.get_extent() ax1.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "r--", lw=3, transform=trans_data2) ax1.set_xlim(2, 5) ax1.set_ylim(0, 4) def test_image_preserve_size(): buff = io.BytesIO() im = np.zeros((481, 321)) plt.imsave(buff, im, format="png") buff.seek(0) img = plt.imread(buff) assert img.shape[:2] == im.shape def test_image_preserve_size2(): n = 7 data = np.identity(n, float) fig = plt.figure(figsize=(n, n), frameon=False) ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(data, interpolation='nearest', origin='lower',aspect='auto') buff = io.BytesIO() fig.savefig(buff, dpi=1) buff.seek(0) img = plt.imread(buff) assert img.shape == (7, 7, 4) assert_array_equal(np.asarray(img[:, :, 0], bool), np.identity(n, bool)[::-1]) @image_comparison(baseline_images=['mask_image_over_under'], remove_text=True, extensions=['png']) def test_mask_image_over_under(): delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / (2 * np.pi * 0.5 * 1.5)) Z = 10*(Z2 - Z1) # difference of Gaussians palette = copy(plt.cm.gray) palette.set_over('r', 1.0) palette.set_under('g', 1.0) palette.set_bad('b', 1.0) Zm = ma.masked_where(Z > 1.2, Z) fig, (ax1, ax2) = plt.subplots(1, 2) im = ax1.imshow(Zm, interpolation='bilinear', cmap=palette, norm=colors.Normalize(vmin=-1.0, vmax=1.0, clip=False), origin='lower', extent=[-3, 3, -3, 3]) ax1.set_title('Green=low, Red=high, Blue=bad') fig.colorbar(im, extend='both', orientation='horizontal', ax=ax1, aspect=10) im = ax2.imshow(Zm, interpolation='nearest', cmap=palette, norm=colors.BoundaryNorm([-1, -0.5, -0.2, 0, 0.2, 0.5, 1], ncolors=256, clip=False), origin='lower', extent=[-3, 3, -3, 3]) ax2.set_title('With BoundaryNorm') fig.colorbar(im, extend='both', spacing='proportional', orientation='horizontal', ax=ax2, aspect=10) @image_comparison(baseline_images=['mask_image'], remove_text=True) def test_mask_image(): # Test mask image two ways: Using nans and using a masked array. fig, (ax1, ax2) = plt.subplots(1, 2) A = np.ones((5, 5)) A[1:2, 1:2] = np.nan ax1.imshow(A, interpolation='nearest') A = np.zeros((5, 5), dtype=bool) A[1:2, 1:2] = True A = np.ma.masked_array(np.ones((5, 5), dtype=np.uint16), A) ax2.imshow(A, interpolation='nearest') @image_comparison(baseline_images=['imshow_endianess'], remove_text=True, extensions=['png']) def test_imshow_endianess(): x = np.arange(10) X, Y = np.meshgrid(x, x) Z = ((X-5)**2 + (Y-5)**2)**0.5 fig, (ax1, ax2) = plt.subplots(1, 2) kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis') ax1.imshow(Z.astype('<f8'), **kwargs) ax2.imshow(Z.astype('>f8'), **kwargs) @image_comparison(baseline_images=['imshow_masked_interpolation'], remove_text=True, style='mpl20') def test_imshow_masked_interpolation(): cm = copy(plt.get_cmap('viridis')) cm.set_over('r') cm.set_under('b') cm.set_bad('k') N = 20 n = colors.Normalize(vmin=0, vmax=N*N-1) # data = np.random.random((N, N))*N*N data = np.arange(N*N, dtype='float').reshape(N, N) data[5, 5] = -1 # This will cause crazy ringing for the higher-order # interpolations data[15, 5] = 1e5 # data[3, 3] = np.nan data[15, 15] = np.inf mask = np.zeros_like(data).astype('bool') mask[5, 15] = True data = np.ma.masked_array(data, mask) fig, ax_grid = plt.subplots(3, 6) for interp, ax in zip(sorted(mimage._interpd_), ax_grid.ravel()): ax.set_title(interp) ax.imshow(data, norm=n, cmap=cm, interpolation=interp) ax.axis('off') def test_imshow_no_warn_invalid(): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter("always") plt.imshow([[1, 2], [3, np.nan]]) assert len(warns) == 0 @pytest.mark.parametrize( 'dtype', [np.dtype(s) for s in 'u2 u4 i2 i4 i8 f4 f8'.split()]) def test_imshow_clips_rgb_to_valid_range(dtype): arr = np.arange(300, dtype=dtype).reshape((10, 10, 3)) if dtype.kind != 'u': arr -= 10 too_low = arr < 0 too_high = arr > 255 if dtype.kind == 'f': arr = arr / 255 _, ax = plt.subplots() out = ax.imshow(arr).get_array() assert (out[too_low] == 0).all() if dtype.kind == 'f': assert (out[too_high] == 1).all() assert out.dtype.kind == 'f' else: assert (out[too_high] == 255).all() assert out.dtype == np.uint8 @image_comparison(baseline_images=['imshow_flatfield'], remove_text=True, style='mpl20', extensions=['png']) def test_imshow_flatfield(): fig, ax = plt.subplots() im = ax.imshow(np.ones((5, 5))) im.set_clim(.5, 1.5) @image_comparison(baseline_images=['imshow_bignumbers'], remove_text=True, style='mpl20', extensions=['png']) def test_imshow_bignumbers(): # putting a big number in an array of integers shouldn't # ruin the dynamic range of the resolved bits. fig, ax = plt.subplots() img = np.array([[1, 2, 1e12],[3, 1, 4]], dtype=np.uint64) pc = ax.imshow(img) pc.set_clim(0, 5) @image_comparison(baseline_images=['imshow_bignumbers_real'], remove_text=True, style='mpl20', extensions=['png']) def test_imshow_bignumbers_real(): # putting a big number in an array of integers shouldn't # ruin the dynamic range of the resolved bits. fig, ax = plt.subplots() img = np.array([[2., 1., 1.e22],[4., 1., 3.]]) pc = ax.imshow(img) pc.set_clim(0, 5) @pytest.mark.parametrize( "make_norm", [colors.Normalize, colors.LogNorm, lambda: colors.SymLogNorm(1), lambda: colors.PowerNorm(1)]) def test_empty_imshow(make_norm): fig, ax = plt.subplots() with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "Attempting to set identical left==right") im = ax.imshow([[]], norm=make_norm()) im.set_extent([-5, 5, -5, 5]) fig.canvas.draw() with pytest.raises(RuntimeError): im.make_image(fig._cachedRenderer) def test_imshow_float128(): fig, ax = plt.subplots() ax.imshow(np.zeros((3, 3), dtype=np.longdouble)) def test_imshow_bool(): fig, ax = plt.subplots() ax.imshow(np.array([[True, False], [False, True]], dtype=bool)) def test_imshow_deprecated_interd_warn(): im = plt.imshow([[1, 2], [3, np.nan]]) for k in ('_interpd', '_interpdr', 'iterpnames'): with warnings.catch_warnings(record=True) as warns: getattr(im, k) assert len(warns) == 1 def test_full_invalid(): x = np.ones((10, 10)) x[:] = np.nan f, ax = plt.subplots() ax.imshow(x) f.canvas.draw() @pytest.mark.parametrize("fmt,counted", [("ps", b" colorimage"), ("svg", b"<image")]) @pytest.mark.parametrize("composite_image,count", [(True, 1), (False, 2)]) def test_composite(fmt, counted, composite_image, count): # Test that figures can be saved with and without combining multiple images # (on a single set of axes) into a single composite image. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(0, 3) ax.imshow(Z, extent=[0, 1, 0, 1]) ax.imshow(Z[::-1], extent=[2, 3, 0, 1]) plt.rcParams['image.composite_image'] = composite_image buf = io.BytesIO() fig.savefig(buf, format=fmt) assert buf.getvalue().count(counted) == count def test_relim(): fig, ax = plt.subplots() ax.imshow([[0]], extent=(0, 1, 0, 1)) ax.relim() ax.autoscale() assert ax.get_xlim() == ax.get_ylim() == (0, 1)
28,875
29.205021
103
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_pickle.py
from __future__ import absolute_import, division, print_function from six.moves import cPickle as pickle from six.moves import range from io import BytesIO import numpy as np from matplotlib.testing.decorators import image_comparison from matplotlib.dates import rrulewrapper import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms def test_simple(): fig = plt.figure() pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) ax = plt.subplot(121) pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL) ax = plt.axes(projection='polar') plt.plot(np.arange(10), label='foobar') plt.legend() pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL) # ax = plt.subplot(121, projection='hammer') # pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL) plt.figure() plt.bar(x=np.arange(10), height=np.arange(10)) pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL) fig = plt.figure() ax = plt.axes() plt.plot(np.arange(10)) ax.set_yscale('log') pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) @image_comparison(baseline_images=['multi_pickle'], extensions=['png'], remove_text=True, style='mpl20') def test_complete(): fig = plt.figure('Figure with a label?', figsize=(10, 6)) plt.suptitle('Can you fit any more in a figure?') # make some arbitrary data x, y = np.arange(8), np.arange(10) data = u = v = np.linspace(0, 10, 80).reshape(10, 8) v = np.sin(v * -0.6) # Ensure lists also pickle correctly. plt.subplot(3, 3, 1) plt.plot(list(range(10))) plt.subplot(3, 3, 2) plt.contourf(data, hatches=['//', 'ooo']) plt.colorbar() plt.subplot(3, 3, 3) plt.pcolormesh(data) plt.subplot(3, 3, 4) plt.imshow(data) plt.subplot(3, 3, 5) plt.pcolor(data) ax = plt.subplot(3, 3, 6) ax.set_xlim(0, 7) ax.set_ylim(0, 9) plt.streamplot(x, y, u, v) ax = plt.subplot(3, 3, 7) ax.set_xlim(0, 7) ax.set_ylim(0, 9) plt.quiver(x, y, u, v) plt.subplot(3, 3, 8) plt.scatter(x, x**2, label='$x^2$') plt.legend(loc='upper left') plt.subplot(3, 3, 9) plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4) # # plotting is done, now test its pickle-ability # result_fh = BytesIO() pickle.dump(fig, result_fh, pickle.HIGHEST_PROTOCOL) plt.close('all') # make doubly sure that there are no figures left assert plt._pylab_helpers.Gcf.figs == {} # wind back the fh and load in the figure result_fh.seek(0) fig = pickle.load(result_fh) # make sure there is now a figure manager assert plt._pylab_helpers.Gcf.figs != {} assert fig.get_label() == 'Figure with a label?' def test_no_pyplot(): # tests pickle-ability of a figure not created with pyplot from matplotlib.backends.backend_pdf import FigureCanvasPdf as fc from matplotlib.figure import Figure fig = Figure() _ = fc(fig) ax = fig.add_subplot(1, 1, 1) ax.plot([1, 2, 3], [1, 2, 3]) pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) def test_renderer(): from matplotlib.backends.backend_agg import RendererAgg renderer = RendererAgg(10, 20, 30) pickle.dump(renderer, BytesIO()) def test_image(): # Prior to v1.4.0 the Image would cache data which was not picklable # once it had been drawn. from matplotlib.backends.backend_agg import new_figure_manager manager = new_figure_manager(1000) fig = manager.canvas.figure ax = fig.add_subplot(1, 1, 1) ax.imshow(np.arange(12).reshape(3, 4)) manager.canvas.draw() pickle.dump(fig, BytesIO()) def test_polar(): ax = plt.subplot(111, polar=True) fig = plt.gcf() pf = pickle.dumps(fig) pickle.loads(pf) plt.draw() class TransformBlob(object): def __init__(self): self.identity = mtransforms.IdentityTransform() self.identity2 = mtransforms.IdentityTransform() # Force use of the more complex composition. self.composite = mtransforms.CompositeGenericTransform( self.identity, self.identity2) # Check parent -> child links of TransformWrapper. self.wrapper = mtransforms.TransformWrapper(self.composite) # Check child -> parent links of TransformWrapper. self.composite2 = mtransforms.CompositeGenericTransform( self.wrapper, self.identity) def test_transform(): obj = TransformBlob() pf = pickle.dumps(obj) del obj obj = pickle.loads(pf) # Check parent -> child links of TransformWrapper. assert obj.wrapper._child == obj.composite # Check child -> parent links of TransformWrapper. assert [v() for v in obj.wrapper._parents.values()] == [obj.composite2] # Check input and output dimensions are set as expected. assert obj.wrapper.input_dims == obj.composite.input_dims assert obj.wrapper.output_dims == obj.composite.output_dims def test_rrulewrapper(): r = rrulewrapper(2) try: pickle.loads(pickle.dumps(r)) except RecursionError: print('rrulewrapper pickling test failed') raise
5,184
26.727273
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/conftest.py
from __future__ import absolute_import, division, print_function from matplotlib.testing.conftest import (mpl_test_settings, mpl_image_comparison_parameters, pytest_configure, pytest_unconfigure, pd)
324
45.428571
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backend_ps.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import io import re import numpy as np import pytest import six import matplotlib import matplotlib.pyplot as plt from matplotlib import patheffects from matplotlib.testing.decorators import image_comparison from matplotlib.testing.determinism import (_determinism_source_date_epoch, _determinism_check) needs_ghostscript = pytest.mark.xfail( matplotlib.checkdep_ghostscript()[0] is None, reason="This test needs a ghostscript installation") needs_usetex = pytest.mark.xfail( not matplotlib.checkdep_usetex(True), reason="This test needs a TeX installation") # This tests tends to hit a TeX cache lock on AppVeyor. @pytest.mark.flaky(reruns=3) @pytest.mark.parametrize('format, use_log, rcParams', [ ('ps', False, {}), needs_ghostscript(('ps', False, {'ps.usedistiller': 'ghostscript'})), needs_usetex(needs_ghostscript(('ps', False, {'text.latex.unicode': True, 'text.usetex': True}))), ('eps', False, {}), ('eps', True, {'ps.useafm': True}), needs_usetex(needs_ghostscript(('eps', False, {'text.latex.unicode': True, 'text.usetex': True}))), ], ids=[ 'ps', 'ps with distiller', 'ps with usetex', 'eps', 'eps afm', 'eps with usetex' ]) def test_savefig_to_stringio(format, use_log, rcParams): matplotlib.rcParams.update(rcParams) fig, ax = plt.subplots() buffers = [ six.moves.StringIO(), io.StringIO(), io.BytesIO()] if use_log: ax.set_yscale('log') ax.plot([1, 2], [1, 2]) ax.set_title(u"Déjà vu") for buffer in buffers: fig.savefig(buffer, format=format) values = [x.getvalue() for x in buffers] if six.PY3: values = [ values[0].encode('ascii'), values[1].encode('ascii'), values[2]] # Remove comments from the output. This includes things that # could change from run to run, such as the time. values = [re.sub(b'%%.*?\n', b'', x) for x in values] assert values[0] == values[1] assert values[1] == values[2].replace(b'\r\n', b'\n') for buffer in buffers: buffer.close() def test_patheffects(): with matplotlib.rc_context(): matplotlib.rcParams['path.effects'] = [ patheffects.withStroke(linewidth=4, foreground='w')] fig, ax = plt.subplots() ax.plot([1, 2, 3]) with io.BytesIO() as ps: fig.savefig(ps, format='ps') @needs_usetex @needs_ghostscript def test_tilde_in_tempfilename(): # Tilde ~ in the tempdir path (e.g. TMPDIR, TMP or TEMP on windows # when the username is very long and windows uses a short name) breaks # latex before https://github.com/matplotlib/matplotlib/pull/5928 import tempfile import shutil import os import os.path tempdir = None old_tempdir = tempfile.tempdir try: # change the path for new tempdirs, which is used # internally by the ps backend to write a file tempdir = tempfile.mkdtemp() base_tempdir = os.path.join(tempdir, "short~1") os.makedirs(base_tempdir) tempfile.tempdir = base_tempdir # usetex results in the latex call, which does not like the ~ plt.rc('text', usetex=True) plt.plot([1, 2, 3, 4]) plt.xlabel(r'\textbf{time} (s)') output_eps = os.path.join(base_tempdir, 'tex_demo.eps') # use the PS backend to write the file... plt.savefig(output_eps, format="ps") finally: tempfile.tempdir = old_tempdir if tempdir: try: shutil.rmtree(tempdir) except Exception as e: # do not break if this is not removable... print(e) def test_source_date_epoch(): """Test SOURCE_DATE_EPOCH support for PS output""" # SOURCE_DATE_EPOCH support is not tested with text.usetex, # because the produced timestamp comes from ghostscript: # %%CreationDate: D:20000101000000Z00\'00\', and this could change # with another ghostscript version. _determinism_source_date_epoch( "ps", b"%%CreationDate: Sat Jan 01 00:00:00 2000") def test_determinism_all(): """Test for reproducible PS output""" _determinism_check(format="ps") @needs_usetex @needs_ghostscript def test_determinism_all_tex(): """Test for reproducible PS/tex output""" _determinism_check(format="ps", usetex=True) @image_comparison(baseline_images=["empty"], extensions=["eps"]) def test_transparency(): fig, ax = plt.subplots() ax.set_axis_off() ax.plot([0, 1], color="r", alpha=0) ax.text(.5, .5, "foo", color="r", alpha=0) @needs_usetex def test_failing_latex(tmpdir): """Test failing latex subprocess call""" path = str(tmpdir.join("tmpoutput.ps")) matplotlib.rcParams['text.usetex'] = True # This fails with "Double subscript" plt.xlabel("$22_2_2$") with pytest.raises(RuntimeError): plt.savefig(path)
5,170
28.890173
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_offsetbox.py
from __future__ import absolute_import, division, print_function import pytest from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines from matplotlib.offsetbox import ( AnchoredOffsetbox, DrawingArea, _get_packed_offsets) @image_comparison(baseline_images=['offsetbox_clipping'], remove_text=True) def test_offsetbox_clipping(): # - create a plot # - put an AnchoredOffsetbox with a child DrawingArea # at the center of the axes # - give the DrawingArea a gray background # - put a black line across the bounds of the DrawingArea # - see that the black line is clipped to the edges of # the DrawingArea. fig, ax = plt.subplots() size = 100 da = DrawingArea(size, size, clip=True) bg = mpatches.Rectangle((0, 0), size, size, facecolor='#CCCCCC', edgecolor='None', linewidth=0) line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2], color='black', linewidth=10) anchored_box = AnchoredOffsetbox( loc=10, child=da, pad=0., frameon=False, bbox_to_anchor=(.5, .5), bbox_transform=ax.transAxes, borderpad=0.) da.add_artist(bg) da.add_artist(line) ax.add_artist(anchored_box) ax.set_xlim((0, 1)) ax.set_ylim((0, 1)) def test_offsetbox_clip_children(): # - create a plot # - put an AnchoredOffsetbox with a child DrawingArea # at the center of the axes # - give the DrawingArea a gray background # - put a black line across the bounds of the DrawingArea # - see that the black line is clipped to the edges of # the DrawingArea. fig, ax = plt.subplots() size = 100 da = DrawingArea(size, size, clip=True) bg = mpatches.Rectangle((0, 0), size, size, facecolor='#CCCCCC', edgecolor='None', linewidth=0) line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2], color='black', linewidth=10) anchored_box = AnchoredOffsetbox( loc=10, child=da, pad=0., frameon=False, bbox_to_anchor=(.5, .5), bbox_transform=ax.transAxes, borderpad=0.) da.add_artist(bg) da.add_artist(line) ax.add_artist(anchored_box) fig.canvas.draw() assert not fig.stale da.clip_children = True assert fig.stale def test_offsetbox_loc_codes(): # Check that valid string location codes all work with an AnchoredOffsetbox codes = {'upper right': 1, 'upper left': 2, 'lower left': 3, 'lower right': 4, 'right': 5, 'center left': 6, 'center right': 7, 'lower center': 8, 'upper center': 9, 'center': 10, } fig, ax = plt.subplots() da = DrawingArea(100, 100) for code in codes: anchored_box = AnchoredOffsetbox(loc=code, child=da) ax.add_artist(anchored_box) fig.canvas.draw() def test_expand_with_tight_layout(): # Check issue reported in #10476, and updated due to #10784 fig, ax = plt.subplots() d1 = [1, 2] d2 = [2, 1] ax.plot(d1, label='series 1') ax.plot(d2, label='series 2') ax.legend(ncol=2, mode='expand') fig.tight_layout() # where the crash used to happen @pytest.mark.parametrize('wd_list', ([(150, 1)], [(150, 1)]*3, [(0.1, 1)], [(0.1, 1)]*2)) @pytest.mark.parametrize('total', (250, 100, 0, -1, None)) @pytest.mark.parametrize('sep', (250, 1, 0, -1)) @pytest.mark.parametrize('mode', ("expand", "fixed", "equal")) def test_get_packed_offsets(wd_list, total, sep, mode): # Check a (rather arbitrary) set of parameters due to successive similar # issue tickets (at least #10476 and #10784) related to corner cases # triggered inside this function when calling higher-level functions # (e.g. `Axes.legend`). _get_packed_offsets(wd_list, total, sep, mode=mode)
4,252
31.968992
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_ttconv.py
from __future__ import absolute_import, division, print_function import six import matplotlib from matplotlib.font_manager import FontProperties from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import os.path @image_comparison(baseline_images=["truetype-conversion"], extensions=["pdf"]) def test_truetype_conversion(): fontname = os.path.join(os.path.dirname(__file__), 'mpltest.ttf') fontname = os.path.abspath(fontname) fontprop = FontProperties(fname=fontname, size=80) matplotlib.rcParams['pdf.fonttype'] = 3 fig = plt.figure() ax = fig.add_subplot(111) ax.text(0, 0, "ABCDE", fontproperties=fontprop) ax.set_xticks([]) ax.set_yticks([])
743
30
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_animation.py
from __future__ import absolute_import, division, print_function import six import sys import tempfile import numpy as np import pytest import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib import animation class NullMovieWriter(animation.AbstractMovieWriter): """ A minimal MovieWriter. It doesn't actually write anything. It just saves the arguments that were given to the setup() and grab_frame() methods as attributes, and counts how many times grab_frame() is called. This class doesn't have an __init__ method with the appropriate signature, and it doesn't define an isAvailable() method, so it cannot be added to the 'writers' registry. """ frame_size_can_vary = True def setup(self, fig, outfile, dpi, *args): self.fig = fig self.outfile = outfile self.dpi = dpi self.args = args self._count = 0 def grab_frame(self, **savefig_kwargs): self.savefig_kwargs = savefig_kwargs self._count += 1 def finish(self): pass def test_null_movie_writer(): # Test running an animation with NullMovieWriter. fig = plt.figure() def init(): pass def animate(i): pass num_frames = 5 filename = "unused.null" dpi = 50 savefig_kwargs = dict(foo=0) anim = animation.FuncAnimation(fig, animate, init_func=init, frames=num_frames) writer = NullMovieWriter() anim.save(filename, dpi=dpi, writer=writer, savefig_kwargs=savefig_kwargs) assert writer.fig == fig assert writer.outfile == filename assert writer.dpi == dpi assert writer.args == () assert writer.savefig_kwargs == savefig_kwargs assert writer._count == num_frames def test_movie_writer_dpi_default(): # Test setting up movie writer with figure.dpi default. fig = plt.figure() filename = "unused.null" fps = 5 codec = "unused" bitrate = 1 extra_args = ["unused"] def run(): pass writer = animation.MovieWriter(fps, codec, bitrate, extra_args) writer._run = run writer.setup(fig, filename) assert writer.dpi == fig.dpi @animation.writers.register('null') class RegisteredNullMovieWriter(NullMovieWriter): # To be able to add NullMovieWriter to the 'writers' registry, # we must define an __init__ method with a specific signature, # and we must define the class method isAvailable(). # (These methods are not actually required to use an instance # of this class as the 'writer' argument of Animation.save().) def __init__(self, fps=None, codec=None, bitrate=None, extra_args=None, metadata=None): pass @classmethod def isAvailable(self): return True WRITER_OUTPUT = [ ('ffmpeg', 'movie.mp4'), ('ffmpeg_file', 'movie.mp4'), ('avconv', 'movie.mp4'), ('avconv_file', 'movie.mp4'), ('imagemagick', 'movie.gif'), ('imagemagick_file', 'movie.gif'), ('pillow', 'movie.gif'), ('html', 'movie.html'), ('null', 'movie.null') ] if sys.version_info >= (3, 6): from pathlib import Path WRITER_OUTPUT += [ (writer, Path(output)) for writer, output in WRITER_OUTPUT] # Smoke test for saving animations. In the future, we should probably # design more sophisticated tests which compare resulting frames a-la # matplotlib.testing.image_comparison @pytest.mark.parametrize('writer, output', WRITER_OUTPUT) def test_save_animation_smoketest(tmpdir, writer, output): try: # for ImageMagick the rcparams must be patched to account for # 'convert' being a built in MS tool, not the imagemagick # tool. writer._init_from_registry() except AttributeError: pass if not animation.writers.is_available(writer): pytest.skip("writer '%s' not available on this system" % writer) fig, ax = plt.subplots() line, = ax.plot([], []) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) dpi = None codec = None if writer == 'ffmpeg': # Issue #8253 fig.set_size_inches((10.85, 9.21)) dpi = 100. codec = 'h264' def init(): line.set_data([], []) return line, def animate(i): x = np.linspace(0, 10, 100) y = np.sin(x + i) line.set_data(x, y) return line, # Use temporary directory for the file-based writers, which produce a file # per frame with known names. with tmpdir.as_cwd(): anim = animation.FuncAnimation(fig, animate, init_func=init, frames=5) try: anim.save(output, fps=30, writer=writer, bitrate=500, dpi=dpi, codec=codec) except UnicodeDecodeError: pytest.xfail("There can be errors in the numpy import stack, " "see issues #1891 and #2679") def test_no_length_frames(): fig, ax = plt.subplots() line, = ax.plot([], []) def init(): line.set_data([], []) return line, def animate(i): x = np.linspace(0, 10, 100) y = np.sin(x + i) line.set_data(x, y) return line, anim = animation.FuncAnimation(fig, animate, init_func=init, frames=iter(range(5))) writer = NullMovieWriter() anim.save('unused.null', writer=writer) def test_movie_writer_registry(): ffmpeg_path = mpl.rcParams['animation.ffmpeg_path'] # Not sure about the first state as there could be some writer # which set rcparams # assert not animation.writers._dirty assert len(animation.writers._registered) > 0 animation.writers.list() # resets dirty state assert not animation.writers._dirty mpl.rcParams['animation.ffmpeg_path'] = u"not_available_ever_xxxx" assert animation.writers._dirty animation.writers.list() # resets assert not animation.writers._dirty assert not animation.writers.is_available("ffmpeg") # something which is guaranteed to be available in path # and exits immediately bin = u"true" if sys.platform != 'win32' else u"where" mpl.rcParams['animation.ffmpeg_path'] = bin assert animation.writers._dirty animation.writers.list() # resets assert not animation.writers._dirty assert animation.writers.is_available("ffmpeg") mpl.rcParams['animation.ffmpeg_path'] = ffmpeg_path
6,426
27.95045
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_font_manager.py
from __future__ import absolute_import, division, print_function import six import os import tempfile import warnings import numpy as np import pytest from matplotlib.font_manager import ( findfont, FontProperties, fontManager, json_dump, json_load, get_font, get_fontconfig_fonts, is_opentype_cff_font, fontManager as fm) from matplotlib import rc_context if six.PY2: from distutils.spawn import find_executable has_fclist = find_executable('fc-list') is not None else: # py >= 3.3 from shutil import which has_fclist = which('fc-list') is not None def test_font_priority(): with rc_context(rc={ 'font.sans-serif': ['cmmi10', 'Bitstream Vera Sans']}): font = findfont( FontProperties(family=["sans-serif"])) assert os.path.basename(font) == 'cmmi10.ttf' # Smoketest get_charmap, which isn't used internally anymore font = get_font(font) cmap = font.get_charmap() assert len(cmap) == 131 assert cmap[8729] == 30 def test_score_weight(): assert 0 == fontManager.score_weight("regular", "regular") assert 0 == fontManager.score_weight("bold", "bold") assert (0 < fontManager.score_weight(400, 400) < fontManager.score_weight("normal", "bold")) assert (0 < fontManager.score_weight("normal", "regular") < fontManager.score_weight("normal", "bold")) assert (fontManager.score_weight("normal", "regular") == fontManager.score_weight(400, 400)) def test_json_serialization(): # on windows, we can't open a file twice, so save the name and unlink # manually... try: name = None with tempfile.NamedTemporaryFile(delete=False) as temp: name = temp.name json_dump(fontManager, name) copy = json_load(name) finally: if name and os.path.exists(name): os.remove(name) with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'findfont: Font family.*not found') for prop in ({'family': 'STIXGeneral'}, {'family': 'Bitstream Vera Sans', 'weight': 700}, {'family': 'no such font family'}): fp = FontProperties(**prop) assert (fontManager.findfont(fp, rebuild_if_missing=False) == copy.findfont(fp, rebuild_if_missing=False)) def test_otf(): fname = '/usr/share/fonts/opentype/freefont/FreeMono.otf' if os.path.exists(fname): assert is_opentype_cff_font(fname) otf_files = [f for f in fm.ttffiles if 'otf' in f] for f in otf_files: with open(f, 'rb') as fd: res = fd.read(4) == b'OTTO' assert res == is_opentype_cff_font(f) @pytest.mark.skipif(not has_fclist, reason='no fontconfig installed') def test_get_fontconfig_fonts(): assert len(get_fontconfig_fonts()) > 1 @pytest.mark.parametrize('factor', [2, 4, 6, 8]) def test_hinting_factor(factor): font = findfont(FontProperties(family=["sans-serif"])) font1 = get_font(font, hinting_factor=1) font1.clear() font1.set_size(12, 100) font1.set_text('abc') expected = font1.get_width_height() hinted_font = get_font(font, hinting_factor=factor) hinted_font.clear() hinted_font.set_size(12, 100) hinted_font.set_text('abc') # Check that hinting only changes text layout by a small (10%) amount. np.testing.assert_allclose(hinted_font.get_width_height(), expected, rtol=0.1)
3,510
31.509259
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_artist.py
from __future__ import absolute_import, division, print_function import io import warnings from itertools import chain import numpy as np import pytest import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines import matplotlib.path as mpath import matplotlib.transforms as mtransforms import matplotlib.collections as mcollections import matplotlib.artist as martist from matplotlib.testing.decorators import image_comparison def test_patch_transform_of_none(): # tests the behaviour of patches added to an Axes with various transform # specifications ax = plt.axes() ax.set_xlim([1, 3]) ax.set_ylim([1, 3]) # Draw an ellipse over data coord (2,2) by specifying device coords. xy_data = (2, 2) xy_pix = ax.transData.transform_point(xy_data) # Not providing a transform of None puts the ellipse in data coordinates . e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5) ax.add_patch(e) assert e._transform == ax.transData # Providing a transform of None puts the ellipse in device coordinates. e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral', transform=None, alpha=0.5) assert e.is_transform_set() is True ax.add_patch(e) assert isinstance(e._transform, mtransforms.IdentityTransform) # Providing an IdentityTransform puts the ellipse in device coordinates. e = mpatches.Ellipse(xy_pix, width=100, height=100, transform=mtransforms.IdentityTransform(), alpha=0.5) ax.add_patch(e) assert isinstance(e._transform, mtransforms.IdentityTransform) # Not providing a transform, and then subsequently "get_transform" should # not mean that "is_transform_set". e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral', alpha=0.5) intermediate_transform = e.get_transform() assert e.is_transform_set() is False ax.add_patch(e) assert e.get_transform() != intermediate_transform assert e.is_transform_set() is True assert e._transform == ax.transData def test_collection_transform_of_none(): # tests the behaviour of collections added to an Axes with various # transform specifications ax = plt.axes() ax.set_xlim([1, 3]) ax.set_ylim([1, 3]) # draw an ellipse over data coord (2,2) by specifying device coords xy_data = (2, 2) xy_pix = ax.transData.transform_point(xy_data) # not providing a transform of None puts the ellipse in data coordinates e = mpatches.Ellipse(xy_data, width=1, height=1) c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5) ax.add_collection(c) # the collection should be in data coordinates assert c.get_offset_transform() + c.get_transform() == ax.transData # providing a transform of None puts the ellipse in device coordinates e = mpatches.Ellipse(xy_pix, width=120, height=120) c = mcollections.PatchCollection([e], facecolor='coral', alpha=0.5) c.set_transform(None) ax.add_collection(c) assert isinstance(c.get_transform(), mtransforms.IdentityTransform) # providing an IdentityTransform puts the ellipse in device coordinates e = mpatches.Ellipse(xy_pix, width=100, height=100) c = mcollections.PatchCollection([e], transform=mtransforms.IdentityTransform(), alpha=0.5) ax.add_collection(c) assert isinstance(c._transOffset, mtransforms.IdentityTransform) @image_comparison(baseline_images=["clip_path_clipping"], remove_text=True) def test_clipping(): exterior = mpath.Path.unit_rectangle().deepcopy() exterior.vertices *= 4 exterior.vertices -= 2 interior = mpath.Path.unit_circle().deepcopy() interior.vertices = interior.vertices[::-1] clip_path = mpath.Path(vertices=np.concatenate([exterior.vertices, interior.vertices]), codes=np.concatenate([exterior.codes, interior.codes])) star = mpath.Path.unit_regular_star(6).deepcopy() star.vertices *= 2.6 ax1 = plt.subplot(121) col = mcollections.PathCollection([star], lw=5, edgecolor='blue', facecolor='red', alpha=0.7, hatch='*') col.set_clip_path(clip_path, ax1.transData) ax1.add_collection(col) ax2 = plt.subplot(122, sharex=ax1, sharey=ax1) patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red', alpha=0.7, hatch='*') patch.set_clip_path(clip_path, ax2.transData) ax2.add_patch(patch) ax1.set_xlim([-3, 3]) ax1.set_ylim([-3, 3]) def test_cull_markers(): x = np.random.random(20000) y = np.random.random(20000) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y, 'k.') ax.set_xlim(2, 3) pdf = io.BytesIO() fig.savefig(pdf, format="pdf") assert len(pdf.getvalue()) < 8000 svg = io.BytesIO() fig.savefig(svg, format="svg") assert len(svg.getvalue()) < 20000 @image_comparison(baseline_images=['hatching'], remove_text=True, style='default') def test_hatching(): fig, ax = plt.subplots(1, 1) # Default hatch color. rect1 = mpatches.Rectangle((0, 0), 3, 4, hatch='/') ax.add_patch(rect1) rect2 = mcollections.RegularPolyCollection(4, sizes=[16000], offsets=[(1.5, 6.5)], transOffset=ax.transData, hatch='/') ax.add_collection(rect2) # Ensure edge color is not applied to hatching. rect3 = mpatches.Rectangle((4, 0), 3, 4, hatch='/', edgecolor='C1') ax.add_patch(rect3) rect4 = mcollections.RegularPolyCollection(4, sizes=[16000], offsets=[(5.5, 6.5)], transOffset=ax.transData, hatch='/', edgecolor='C1') ax.add_collection(rect4) ax.set_xlim(0, 7) ax.set_ylim(0, 9) def test_remove(): fig, ax = plt.subplots() im = ax.imshow(np.arange(36).reshape(6, 6)) ln, = ax.plot(range(5)) assert fig.stale assert ax.stale fig.canvas.draw() assert not fig.stale assert not ax.stale assert not ln.stale assert im in ax.mouseover_set assert ln not in ax.mouseover_set assert im.axes is ax im.remove() ln.remove() for art in [im, ln]: assert art.axes is None assert art.figure is None assert im not in ax.mouseover_set assert fig.stale assert ax.stale @image_comparison(baseline_images=["default_edges"], remove_text=True, extensions=['png'], style='default') def test_default_edges(): fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2) ax1.plot(np.arange(10), np.arange(10), 'x', np.arange(10) + 1, np.arange(10), 'o') ax2.bar(np.arange(10), np.arange(10), align='edge') ax3.text(0, 0, "BOX", size=24, bbox=dict(boxstyle='sawtooth')) ax3.set_xlim((-1, 1)) ax3.set_ylim((-1, 1)) pp1 = mpatches.PathPatch( mpath.Path([(0, 0), (1, 0), (1, 1), (0, 0)], [mpath.Path.MOVETO, mpath.Path.CURVE3, mpath.Path.CURVE3, mpath.Path.CLOSEPOLY]), fc="none", transform=ax4.transData) ax4.add_patch(pp1) def test_properties(): ln = mlines.Line2D([], []) with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") ln.properties() assert len(w) == 0 def test_setp(): # Check empty list plt.setp([]) plt.setp([[]]) # Check arbitrary iterables fig, axes = plt.subplots() lines1 = axes.plot(range(3)) lines2 = axes.plot(range(3)) martist.setp(chain(lines1, lines2), 'lw', 5) plt.setp(axes.spines.values(), color='green') # Check `file` argument sio = io.StringIO() plt.setp(lines1, 'zorder', file=sio) assert sio.getvalue() == ' zorder: float \n' def test_None_zorder(): fig, ax = plt.subplots() ln, = ax.plot(range(5), zorder=None) assert ln.get_zorder() == mlines.Line2D.zorder ln.set_zorder(123456) assert ln.get_zorder() == 123456 ln.set_zorder(None) assert ln.get_zorder() == mlines.Line2D.zorder @pytest.mark.parametrize('accept_clause, expected', [ ('', 'unknown'), ("ACCEPTS: [ '-' | '--' | '-.' ]", "[ '-' | '--' | '-.' ] "), ('ACCEPTS: Some description.', 'Some description. '), ('.. ACCEPTS: Some description.', 'Some description. '), ]) def test_artist_inspector_get_valid_values(accept_clause, expected): class TestArtist(martist.Artist): def set_f(self): pass func = TestArtist.set_f if hasattr(func, '__func__'): func = func.__func__ # python 2 must write via __func__.__doc__ func.__doc__ = """ Some text. %s """ % accept_clause valid_values = martist.ArtistInspector(TestArtist).get_valid_values('f') assert valid_values == expected
9,318
31.929329
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_rcparams.py
from __future__ import absolute_import, division, print_function import six import os import warnings from collections import OrderedDict from cycler import cycler, Cycler import pytest try: from unittest import mock except ImportError: import mock import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as mcolors from itertools import chain import numpy as np from matplotlib.rcsetup import (validate_bool_maybe_none, validate_stringlist, validate_colorlist, validate_color, validate_bool, validate_nseq_int, validate_nseq_float, validate_cycler, validate_hatch, validate_hist_bins, _validate_linestyle) mpl.rc('text', usetex=False) mpl.rc('lines', linewidth=22) fname = os.path.join(os.path.dirname(__file__), 'test_rcparams.rc') def test_rcparams(): usetex = mpl.rcParams['text.usetex'] linewidth = mpl.rcParams['lines.linewidth'] # test context given dictionary with mpl.rc_context(rc={'text.usetex': not usetex}): assert mpl.rcParams['text.usetex'] == (not usetex) assert mpl.rcParams['text.usetex'] == usetex # test context given filename (mpl.rc sets linewdith to 33) with mpl.rc_context(fname=fname): assert mpl.rcParams['lines.linewidth'] == 33 assert mpl.rcParams['lines.linewidth'] == linewidth # test context given filename and dictionary with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}): assert mpl.rcParams['lines.linewidth'] == 44 assert mpl.rcParams['lines.linewidth'] == linewidth # test rc_file try: mpl.rc_file(fname) assert mpl.rcParams['lines.linewidth'] == 33 finally: mpl.rcParams['lines.linewidth'] = linewidth def test_RcParams_class(): rc = mpl.RcParams({'font.cursive': ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive'], 'font.family': 'sans-serif', 'font.weight': 'normal', 'font.size': 12}) expected_repr = """ RcParams({'font.cursive': ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive'], 'font.family': ['sans-serif'], 'font.size': 12.0, 'font.weight': 'normal'})""".lstrip() assert expected_repr == repr(rc) expected_str = """ font.cursive: ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive'] font.family: ['sans-serif'] font.size: 12.0 font.weight: normal""".lstrip() assert expected_str == str(rc) # test the find_all functionality assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]')) assert ['font.family'] == list(rc.find_all('family')) def test_rcparams_update(): rc = mpl.RcParams({'figure.figsize': (3.5, 42)}) bad_dict = {'figure.figsize': (3.5, 42, 1)} # make sure validation happens on input with pytest.raises(ValueError): with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(validate)', category=UserWarning) rc.update(bad_dict) def test_rcparams_init(): with pytest.raises(ValueError): with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(validate)', category=UserWarning) mpl.RcParams({'figure.figsize': (3.5, 42, 1)}) def test_Bug_2543(): # Test that it possible to add all values to itself / deepcopy # This was not possible because validate_bool_maybe_none did not # accept None as an argument. # https://github.com/matplotlib/matplotlib/issues/2543 # We filter warnings at this stage since a number of them are raised # for deprecated rcparams as they should. We don't want these in the # printed in the test suite. with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(deprecated|obsolete)', category=UserWarning) with mpl.rc_context(): _copy = mpl.rcParams.copy() for key in _copy: mpl.rcParams[key] = _copy[key] mpl.rcParams['text.dvipnghack'] = None with mpl.rc_context(): from copy import deepcopy _deep_copy = deepcopy(mpl.rcParams) # real test is that this does not raise assert validate_bool_maybe_none(None) is None assert validate_bool_maybe_none("none") is None with pytest.raises(ValueError): validate_bool_maybe_none("blah") with pytest.raises(ValueError): validate_bool(None) with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True legend_color_tests = [ ('face', {'color': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'inherit', 'axes.facecolor': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')), ('edge', {'color': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'inherit', 'axes.edgecolor': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')) ] legend_color_test_ids = [ 'same facecolor', 'inherited facecolor', 'different facecolor', 'same edgecolor', 'inherited edgecolor', 'different facecolor', ] @pytest.mark.parametrize('color_type, param_dict, target', legend_color_tests, ids=legend_color_test_ids) def test_legend_colors(color_type, param_dict, target): param_dict['legend.%scolor' % (color_type, )] = param_dict.pop('color') get_func = 'get_%scolor' % (color_type, ) with mpl.rc_context(param_dict): _, ax = plt.subplots() ax.plot(range(3), label='test') leg = ax.legend() assert getattr(leg.legendPatch, get_func)() == target def test_Issue_1713(): utf32_be = os.path.join(os.path.dirname(__file__), 'test_utf32_be_rcparams.rc') import locale with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'): rc = mpl.rc_params_from_file(utf32_be, True, False) assert rc.get('timezone') == 'UTC' def generate_validator_testcases(valid): validation_tests = ( {'validator': validate_bool, 'success': chain(((_, True) for _ in ('t', 'y', 'yes', 'on', 'true', '1', 1, True)), ((_, False) for _ in ('f', 'n', 'no', 'off', 'false', '0', 0, False))), 'fail': ((_, ValueError) for _ in ('aardvark', 2, -1, [], ))}, {'validator': validate_stringlist, 'success': (('', []), ('a,b', ['a', 'b']), ('aardvark', ['aardvark']), ('aardvark, ', ['aardvark']), ('aardvark, ,', ['aardvark']), (['a', 'b'], ['a', 'b']), (('a', 'b'), ['a', 'b']), (iter(['a', 'b']), ['a', 'b']), (np.array(['a', 'b']), ['a', 'b']), ((1, 2), ['1', '2']), (np.array([1, 2]), ['1', '2']), ), 'fail': ((dict(), ValueError), (1, ValueError), ) }, {'validator': validate_nseq_int(2), 'success': ((_, [1, 2]) for _ in ('1, 2', [1.5, 2.5], [1, 2], (1, 2), np.array((1, 2)))), 'fail': ((_, ValueError) for _ in ('aardvark', ('a', 1), (1, 2, 3) )) }, {'validator': validate_nseq_float(2), 'success': ((_, [1.5, 2.5]) for _ in ('1.5, 2.5', [1.5, 2.5], [1.5, 2.5], (1.5, 2.5), np.array((1.5, 2.5)))), 'fail': ((_, ValueError) for _ in ('aardvark', ('a', 1), (1, 2, 3) )) }, {'validator': validate_cycler, 'success': (('cycler("color", "rgb")', cycler("color", 'rgb')), (cycler('linestyle', ['-', '--']), cycler('linestyle', ['-', '--'])), ("""(cycler("color", ["r", "g", "b"]) + cycler("mew", [2, 3, 5]))""", (cycler("color", 'rgb') + cycler("markeredgewidth", [2, 3, 5]))), ("cycler(c='rgb', lw=[1, 2, 3])", cycler('color', 'rgb') + cycler('linewidth', [1, 2, 3])), ("cycler('c', 'rgb') * cycler('linestyle', ['-', '--'])", (cycler('color', 'rgb') * cycler('linestyle', ['-', '--']))), (cycler('ls', ['-', '--']), cycler('linestyle', ['-', '--'])), (cycler(mew=[2, 5]), cycler('markeredgewidth', [2, 5])), ), # This is *so* incredibly important: validate_cycler() eval's # an arbitrary string! I think I have it locked down enough, # and that is what this is testing. # TODO: Note that these tests are actually insufficient, as it may # be that they raised errors, but still did an action prior to # raising the exception. We should devise some additional tests # for that... 'fail': ((4, ValueError), # Gotta be a string or Cycler object ('cycler("bleh, [])', ValueError), # syntax error ('Cycler("linewidth", [1, 2, 3])', ValueError), # only 'cycler()' function is allowed ('1 + 2', ValueError), # doesn't produce a Cycler object ('os.system("echo Gotcha")', ValueError), # os not available ('import os', ValueError), # should not be able to import ('def badjuju(a): return a; badjuju(cycler("color", "rgb"))', ValueError), # Should not be able to define anything # even if it does return a cycler ('cycler("waka", [1, 2, 3])', ValueError), # not a property ('cycler(c=[1, 2, 3])', ValueError), # invalid values ("cycler(lw=['a', 'b', 'c'])", ValueError), # invalid values (cycler('waka', [1, 3, 5]), ValueError), # not a property (cycler('color', ['C1', 'r', 'g']), ValueError) # no CN ) }, {'validator': validate_hatch, 'success': (('--|', '--|'), ('\\oO', '\\oO'), ('/+*/.x', '/+*/.x'), ('', '')), 'fail': (('--_', ValueError), (8, ValueError), ('X', ValueError)), }, {'validator': validate_colorlist, 'success': (('r,g,b', ['r', 'g', 'b']), (['r', 'g', 'b'], ['r', 'g', 'b']), ('r, ,', ['r']), (['', 'g', 'blue'], ['g', 'blue']), ([np.array([1, 0, 0]), np.array([0, 1, 0])], np.array([[1, 0, 0], [0, 1, 0]])), (np.array([[1, 0, 0], [0, 1, 0]]), np.array([[1, 0, 0], [0, 1, 0]])), ), 'fail': (('fish', ValueError), ), }, {'validator': validate_color, 'success': (('None', 'none'), ('none', 'none'), ('AABBCC', '#AABBCC'), # RGB hex code ('AABBCC00', '#AABBCC00'), # RGBA hex code ('tab:blue', 'tab:blue'), # named color ('C0', 'C0'), # color from cycle ('(0, 1, 0)', [0.0, 1.0, 0.0]), # RGB tuple ((0, 1, 0), (0, 1, 0)), # non-string version ('(0, 1, 0, 1)', [0.0, 1.0, 0.0, 1.0]), # RGBA tuple ((0, 1, 0, 1), (0, 1, 0, 1)), # non-string version ('(0, 1, "0.5")', [0.0, 1.0, 0.5]), # unusual but valid ), 'fail': (('tab:veryblue', ValueError), # invalid name ('C123', ValueError), # invalid RGB(A) code and cycle index ('(0, 1)', ValueError), # tuple with length < 3 ('(0, 1, 0, 1, 0)', ValueError), # tuple with length > 4 ('(0, 1, none)', ValueError), # cannot cast none to float ), }, {'validator': validate_hist_bins, 'success': (('auto', 'auto'), ('10', 10), ('1, 2, 3', [1, 2, 3]), ([1, 2, 3], [1, 2, 3]), (np.arange(15), np.arange(15)) ), 'fail': (('aardvark', ValueError), ) } ) # The behavior of _validate_linestyle depends on the version of Python. # ASCII-compliant bytes arguments should pass on Python 2 because of the # automatic conversion between bytes and strings. Python 3 does not # perform such a conversion, so the same cases should raise an exception. # # Common cases: ls_test = {'validator': _validate_linestyle, 'success': (('-', '-'), ('solid', 'solid'), ('--', '--'), ('dashed', 'dashed'), ('-.', '-.'), ('dashdot', 'dashdot'), (':', ':'), ('dotted', 'dotted'), ('', ''), (' ', ' '), ('None', 'none'), ('none', 'none'), ('DoTtEd', 'dotted'), # case-insensitive (['1.23', '4.56'], (None, [1.23, 4.56])), ([1.23, 456], (None, [1.23, 456.0])), ([1, 2, 3, 4], (None, [1.0, 2.0, 3.0, 4.0])), ), 'fail': (('aardvark', ValueError), # not a valid string ('dotted'.encode('utf-16'), ValueError), # even on PY2 ((None, [1, 2]), ValueError), # (offset, dashes) != OK ((0, [1, 2]), ValueError), # idem ((-1, [1, 2]), ValueError), # idem ([1, 2, 3], ValueError), # sequence with odd length (1.23, ValueError), # not a sequence ) } # Add some cases of bytes arguments that Python 2 can convert silently: ls_bytes_args = (b'dotted', 'dotted'.encode('ascii')) if six.PY3: ls_test['fail'] += tuple((arg, ValueError) for arg in ls_bytes_args) else: ls_test['success'] += tuple((arg, 'dotted') for arg in ls_bytes_args) # Update the validation test sequence. validation_tests += (ls_test,) for validator_dict in validation_tests: validator = validator_dict['validator'] if valid: for arg, target in validator_dict['success']: yield validator, arg, target else: for arg, error_type in validator_dict['fail']: yield validator, arg, error_type @pytest.mark.parametrize('validator, arg, target', generate_validator_testcases(True)) def test_validator_valid(validator, arg, target): res = validator(arg) if isinstance(target, np.ndarray): assert np.all(res == target) elif not isinstance(target, Cycler): assert res == target else: # Cyclers can't simply be asserted equal. They don't implement __eq__ assert list(res) == list(target) @pytest.mark.parametrize('validator, arg, exception_type', generate_validator_testcases(False)) def test_validator_invalid(validator, arg, exception_type): with pytest.raises(exception_type): validator(arg) def test_keymaps(): key_list = [k for k in mpl.rcParams if 'keymap' in k] for k in key_list: assert isinstance(mpl.rcParams[k], list) def test_rcparams_reset_after_fail(): # There was previously a bug that meant that if rc_context failed and # raised an exception due to issues in the supplied rc parameters, the # global rc parameters were left in a modified state. with mpl.rc_context(rc={'text.usetex': False}): assert mpl.rcParams['text.usetex'] is False with pytest.raises(KeyError): with mpl.rc_context(rc=OrderedDict([('text.usetex', True), ('test.blah', True)])): pass assert mpl.rcParams['text.usetex'] is False def test_if_rctemplate_is_up_to_date(): # This tests if the matplotlibrc.template file # contains all valid rcParams. dep1 = mpl._all_deprecated dep2 = mpl._deprecated_set deprecated = list(dep1.union(dep2)) #print(deprecated) path_to_rc = mpl.matplotlib_fname() with open(path_to_rc, "r") as f: rclines = f.readlines() missing = {} for k,v in mpl.defaultParams.items(): if k[0] == "_": continue if k in deprecated: continue if "verbose" in k: continue found = False for line in rclines: if k in line: found = True if not found: missing.update({k:v}) if missing: raise ValueError("The following params are missing " + "in the matplotlibrc.template file: {}" .format(missing.items())) def test_if_rctemplate_would_be_valid(tmpdir): # This tests if the matplotlibrc.template file would result in a valid # rc file if all lines are uncommented. path_to_rc = mpl.matplotlib_fname() with open(path_to_rc, "r") as f: rclines = f.readlines() newlines = [] for line in rclines: if line[0] == "#": newline = line[1:] else: newline = line if "$TEMPLATE_BACKEND" in newline: newline = "backend : Agg" if "datapath" in newline: newline = "" newlines.append(newline) d = tmpdir.mkdir('test1') fname = str(d.join('testrcvalid.temp')) with open(fname, "w") as f: f.writelines(newlines) with pytest.warns(None) as record: dic = mpl.rc_params_from_file(fname, fail_on_error=True, use_default_template=False) assert len(record) == 0 #d1 = set(dic.keys()) #d2 = set(matplotlib.defaultParams.keys()) #print(d2-d1)
19,307
38.728395
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_basic.py
from __future__ import absolute_import, division, print_function import six import sys import matplotlib def test_simple(): assert 1 + 1 == 2 def test_override_builtins(): import pylab ok_to_override = { '__name__', '__doc__', '__package__', '__loader__', '__spec__', 'any', 'all', 'sum', 'divmod' } # We could use six.moves.builtins here, but that seems # to do a little more than just this. if six.PY3: builtins = sys.modules['builtins'] else: builtins = sys.modules['__builtin__'] overridden = False for key in dir(pylab): if key in dir(builtins): if (getattr(pylab, key) != getattr(builtins, key) and key not in ok_to_override): print("'%s' was overridden in globals()." % key) overridden = True assert not overridden def test_verbose(): assert isinstance(matplotlib.verbose, matplotlib.Verbose)
1,020
20.270833
65
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_constrainedlayout.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings import numpy as np import pytest from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea from matplotlib.patches import Rectangle import matplotlib.gridspec as gridspec from matplotlib import ticker, rcParams def example_plot(ax, fontsize=12, nodec=False): ax.plot([1, 2]) ax.locator_params(nbins=3) if not nodec: ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) else: ax.set_xticklabels('') ax.set_yticklabels('') def example_pcolor(ax, fontsize=12): dx, dy = 0.6, 0.6 y, x = np.mgrid[slice(-3, 3 + dy, dy), slice(-3, 3 + dx, dx)] z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) pcm = ax.pcolormesh(x, y, z, cmap='RdBu_r', vmin=-1., vmax=1., rasterized=True) # ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) return pcm @image_comparison(baseline_images=['constrained_layout1'], extensions=['png']) def test_constrained_layout1(): 'Test constrained_layout for a single subplot' fig = plt.figure(constrained_layout=True) ax = fig.add_subplot(111) example_plot(ax, fontsize=24) @image_comparison(baseline_images=['constrained_layout2'], extensions=['png']) def test_constrained_layout2(): 'Test constrained_layout for 2x2 subplots' fig, axs = plt.subplots(2, 2, constrained_layout=True) for ax in axs.flatten(): example_plot(ax, fontsize=24) @image_comparison(baseline_images=['constrained_layout3'], extensions=['png']) def test_constrained_layout3(): 'Test constrained_layout for colorbars with subplots' fig, axs = plt.subplots(2, 2, constrained_layout=True) for nn, ax in enumerate(axs.flatten()): pcm = example_pcolor(ax, fontsize=24) if nn == 3: pad = 0.08 else: pad = 0.02 # default fig.colorbar(pcm, ax=ax, pad=pad) @image_comparison(baseline_images=['constrained_layout4']) def test_constrained_layout4(): 'Test constrained_layout for a single colorbar with subplots' fig, axs = plt.subplots(2, 2, constrained_layout=True) for ax in axs.flatten(): pcm = example_pcolor(ax, fontsize=24) fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6) @image_comparison(baseline_images=['constrained_layout5'], tol=5.e-2, extensions=['png']) def test_constrained_layout5(): ''' Test constrained_layout for a single colorbar with subplots, colorbar bottom ''' fig, axs = plt.subplots(2, 2, constrained_layout=True) for ax in axs.flatten(): pcm = example_pcolor(ax, fontsize=24) fig.colorbar(pcm, ax=axs, use_gridspec=False, pad=0.01, shrink=0.6, location='bottom') @image_comparison(baseline_images=['constrained_layout6'], extensions=['png']) def test_constrained_layout6(): 'Test constrained_layout for nested gridspecs' fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(1, 2, figure=fig) gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0]) gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1]) axsl = [] for gs in gsl: ax = fig.add_subplot(gs) axsl += [ax] example_plot(ax, fontsize=12) ax.set_xlabel('x-label\nMultiLine') axsr = [] for gs in gsr: ax = fig.add_subplot(gs) axsr += [ax] pcm = example_pcolor(ax, fontsize=12) fig.colorbar(pcm, ax=axsr, pad=0.01, shrink=0.99, location='bottom', ticks=ticker.MaxNLocator(nbins=5)) @image_comparison(baseline_images=['constrained_layout8'], extensions=['png']) def test_constrained_layout8(): 'Test for gridspecs that are not completely full' fig = plt.figure(figsize=(7, 4), constrained_layout=True) gs = gridspec.GridSpec(3, 5, figure=fig) axs = [] j = 1 for i in [0, 1]: ax = fig.add_subplot(gs[j, i]) axs += [ax] pcm = example_pcolor(ax, fontsize=10) if i > 0: ax.set_ylabel('') if j < 1: ax.set_xlabel('') ax.set_title('') j = 0 for i in [2, 4]: ax = fig.add_subplot(gs[j, i]) axs += [ax] pcm = example_pcolor(ax, fontsize=10) if i > 0: ax.set_ylabel('') if j < 1: ax.set_xlabel('') ax.set_title('') ax = fig.add_subplot(gs[2, :]) axs += [ax] pcm = example_pcolor(ax, fontsize=10) fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6) def test_constrained_layout7(): 'Test for proper warning if fig not set in GridSpec' with pytest.warns(UserWarning, match='Calling figure.constrained_layout, ' 'but figure not setup to do constrained layout'): fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(1, 2) gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0]) gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1]) axsl = [] for gs in gsl: ax = fig.add_subplot(gs) # need to trigger a draw to get warning fig.draw(fig.canvas.get_renderer()) @image_comparison(baseline_images=['constrained_layout8'], extensions=['png']) def test_constrained_layout8(): 'Test for gridspecs that are not completely full' fig = plt.figure(figsize=(10, 5), constrained_layout=True) gs = gridspec.GridSpec(3, 5, figure=fig) axs = [] j = 1 for i in [0, 4]: ax = fig.add_subplot(gs[j, i]) axs += [ax] pcm = example_pcolor(ax, fontsize=9) if i > 0: ax.set_ylabel('') if j < 1: ax.set_xlabel('') ax.set_title('') j = 0 for i in [1]: ax = fig.add_subplot(gs[j, i]) axs += [ax] pcm = example_pcolor(ax, fontsize=9) if i > 0: ax.set_ylabel('') if j < 1: ax.set_xlabel('') ax.set_title('') ax = fig.add_subplot(gs[2, :]) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6) @image_comparison(baseline_images=['constrained_layout9'], extensions=['png']) def test_constrained_layout9(): 'Test for handling suptitle and for sharex and sharey' fig, axs = plt.subplots(2, 2, constrained_layout=True, sharex=False, sharey=False) # ax = fig.add_subplot(111) for ax in axs.flatten(): pcm = example_pcolor(ax, fontsize=24) ax.set_xlabel('') ax.set_ylabel('') ax.set_aspect(2.) fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6) fig.suptitle('Test Suptitle', fontsize=28) @image_comparison(baseline_images=['constrained_layout10'], extensions=['png']) def test_constrained_layout10(): 'Test for handling legend outside axis' fig, axs = plt.subplots(2, 2, constrained_layout=True) for ax in axs.flatten(): ax.plot(np.arange(12), label='This is a label') ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) @image_comparison(baseline_images=['constrained_layout11'], extensions=['png']) def test_constrained_layout11(): 'Test for multiple nested gridspecs ' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9) @image_comparison(baseline_images=['constrained_layout11rat'], extensions=['png']) def test_constrained_layout11rat(): 'Test for multiple nested gridspecs with width_ratios' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig, width_ratios=[6., 1.]) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1], height_ratios=[2., 1.]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9) @image_comparison(baseline_images=['constrained_layout12'], extensions=['png']) def test_constrained_layout12(): 'Test that very unbalanced labeling still works.' fig = plt.figure(constrained_layout=True) gs0 = gridspec.GridSpec(6, 2, figure=fig) ax1 = fig.add_subplot(gs0[:3, 1]) ax2 = fig.add_subplot(gs0[3:, 1]) example_plot(ax1, fontsize=24) example_plot(ax2, fontsize=24) ax = fig.add_subplot(gs0[0:2, 0]) example_plot(ax, nodec=True) ax = fig.add_subplot(gs0[2:4, 0]) example_plot(ax, nodec=True) ax = fig.add_subplot(gs0[4:, 0]) example_plot(ax, nodec=True) ax.set_xlabel('x-label') @image_comparison(baseline_images=['constrained_layout13'], tol=2.e-2, extensions=['png']) def test_constrained_layout13(): 'Test that padding works.' fig, axs = plt.subplots(2, 2, constrained_layout=True) for ax in axs.flatten(): pcm = example_pcolor(ax, fontsize=12) fig.colorbar(pcm, ax=ax, shrink=0.6, aspect=20., pad=0.02) fig.set_constrained_layout_pads(w_pad=24./72., h_pad=24./72.) @image_comparison(baseline_images=['constrained_layout14'], extensions=['png']) def test_constrained_layout14(): 'Test that padding works.' fig, axs = plt.subplots(2, 2, constrained_layout=True) for ax in axs.flatten(): pcm = example_pcolor(ax, fontsize=12) fig.colorbar(pcm, ax=ax, shrink=0.6, aspect=20., pad=0.02) fig.set_constrained_layout_pads( w_pad=3./72., h_pad=3./72., hspace=0.2, wspace=0.2) @image_comparison(baseline_images=['constrained_layout15'], extensions=['png']) def test_constrained_layout15(): 'Test that rcparams work.' rcParams['figure.constrained_layout.use'] = True fig, axs = plt.subplots(2, 2) for ax in axs.flatten(): example_plot(ax, fontsize=12) @image_comparison(baseline_images=['constrained_layout16'], extensions=['png']) def test_constrained_layout16(): 'Test ax.set_position.' fig, ax = plt.subplots(constrained_layout=True) example_plot(ax, fontsize=12) ax2 = fig.add_axes([0.2, 0.2, 0.4, 0.4]) @image_comparison(baseline_images=['constrained_layout17'], extensions=['png']) def test_constrained_layout17(): 'Test uneven gridspecs' fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(3, 3, figure=fig) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[0, 1:]) ax3 = fig.add_subplot(gs[1:, 0:2]) ax4 = fig.add_subplot(gs[1:, -1]) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) def test_constrained_layout18(): 'Test twinx' fig, ax = plt.subplots(constrained_layout=True) ax2 = ax.twinx() example_plot(ax) example_plot(ax2, fontsize=24) fig.canvas.draw() assert all(ax.get_position().extents == ax2.get_position().extents) def test_constrained_layout19(): 'Test twiny' fig, ax = plt.subplots(constrained_layout=True) ax2 = ax.twiny() example_plot(ax) example_plot(ax2, fontsize=24) ax2.set_title('') ax.set_title('') fig.canvas.draw() assert all(ax.get_position().extents == ax2.get_position().extents) def test_constrained_layout20(): 'Smoke test cl does not mess up added axes' gx = np.linspace(-5, 5, 4) img = np.hypot(gx, gx[:, None]) fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) mesh = ax.pcolormesh(gx, gx, img) fig.colorbar(mesh)
12,468
30.890026
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_axes.py
from __future__ import absolute_import, division, print_function import six from six.moves import xrange from itertools import chain, product from distutils.version import LooseVersion import io import datetime import pytz import numpy as np from numpy import ma from cycler import cycler import pytest import warnings import matplotlib from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib.markers as mmarkers import matplotlib.patches as mpatches import matplotlib.colors as mcolors from numpy.testing import assert_allclose, assert_array_equal from matplotlib.cbook import ( IgnoredKeywordWarning, MatplotlibDeprecationWarning) from matplotlib.cbook._backports import broadcast_to # Note: Some test cases are run twice: once normally and once with labeled data # These two must be defined in the same test function or need to have # different baseline images to prevent race conditions when pytest runs # the tests with multiple threads. def test_get_labels(): fig, ax = plt.subplots() ax.set_xlabel('x label') ax.set_ylabel('y label') assert ax.get_xlabel() == 'x label' assert ax.get_ylabel() == 'y label' @image_comparison(baseline_images=['acorr'], extensions=['png'], style='mpl20') def test_acorr(): np.random.seed(19680801) n = 512 x = np.random.normal(0, 1, n).cumsum() fig, ax = plt.subplots() ax.acorr(x, maxlags=n - 1, label='acorr') ax.legend() @image_comparison(baseline_images=['spy'], extensions=['png'], style='mpl20') def test_spy(): np.random.seed(19680801) a = np.ones(32 * 32) a[:16 * 32] = 0 np.random.shuffle(a) a = np.reshape(a, (32, 32)) fig, ax = plt.subplots() ax.spy(a) @image_comparison(baseline_images=['matshow'], extensions=['png'], style='mpl20') def test_matshow(): np.random.seed(19680801) a = np.random.rand(32, 32) fig, ax = plt.subplots() ax.matshow(a) @image_comparison(baseline_images=['formatter_ticker_001', 'formatter_ticker_002', 'formatter_ticker_003', 'formatter_ticker_004', 'formatter_ticker_005', ]) def test_formatter_ticker(): import matplotlib.testing.jpl_units as units units.register() # This should affect the tick size. (Tests issue #543) matplotlib.rcParams['lines.markeredgewidth'] = 30 # This essentially test to see if user specified labels get overwritten # by the auto labeler functionality of the axes. xdata = [x*units.sec for x in range(10)] ydata1 = [(1.5*y - 0.5)*units.km for y in range(10)] ydata2 = [(1.75*y - 1.0)*units.km for y in range(10)] fig = plt.figure() ax = plt.subplot(111) ax.set_xlabel("x-label 001") fig = plt.figure() ax = plt.subplot(111) ax.set_xlabel("x-label 001") ax.plot(xdata, ydata1, color='blue', xunits="sec") fig = plt.figure() ax = plt.subplot(111) ax.set_xlabel("x-label 001") ax.plot(xdata, ydata1, color='blue', xunits="sec") ax.set_xlabel("x-label 003") fig = plt.figure() ax = plt.subplot(111) ax.plot(xdata, ydata1, color='blue', xunits="sec") ax.plot(xdata, ydata2, color='green', xunits="hour") ax.set_xlabel("x-label 004") # See SF bug 2846058 # https://sourceforge.net/tracker/?func=detail&aid=2846058&group_id=80706&atid=560720 fig = plt.figure() ax = plt.subplot(111) ax.plot(xdata, ydata1, color='blue', xunits="sec") ax.plot(xdata, ydata2, color='green', xunits="hour") ax.set_xlabel("x-label 005") ax.autoscale_view() @image_comparison(baseline_images=["formatter_large_small"]) def test_formatter_large_small(): # github issue #617, pull #619 if LooseVersion(np.__version__) >= LooseVersion('1.11.0'): pytest.skip("Fall out from a fixed numpy bug") fig, ax = plt.subplots(1) x = [0.500000001, 0.500000002] y = [1e64, 1.1e64] ax.plot(x, y) @image_comparison(baseline_images=["twin_axis_locaters_formatters"]) def test_twin_axis_locaters_formatters(): vals = np.linspace(0, 1, num=5, endpoint=True) locs = np.sin(np.pi * vals / 2.0) majl = plt.FixedLocator(locs) minl = plt.FixedLocator([0.1, 0.2, 0.3]) fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) ax1.plot([0.1, 100], [0, 1]) ax1.yaxis.set_major_locator(majl) ax1.yaxis.set_minor_locator(minl) ax1.yaxis.set_major_formatter(plt.FormatStrFormatter('%08.2lf')) ax1.yaxis.set_minor_formatter(plt.FixedFormatter(['tricks', 'mind', 'jedi'])) ax1.xaxis.set_major_locator(plt.LinearLocator()) ax1.xaxis.set_minor_locator(plt.FixedLocator([15, 35, 55, 75])) ax1.xaxis.set_major_formatter(plt.FormatStrFormatter('%05.2lf')) ax1.xaxis.set_minor_formatter(plt.FixedFormatter(['c', '3', 'p', 'o'])) ax2 = ax1.twiny() ax3 = ax1.twinx() def test_twinx_cla(): fig, ax = plt.subplots() ax2 = ax.twinx() ax3 = ax2.twiny() plt.draw() assert not ax2.xaxis.get_visible() assert not ax2.patch.get_visible() ax2.cla() ax3.cla() assert not ax2.xaxis.get_visible() assert not ax2.patch.get_visible() assert ax2.yaxis.get_visible() assert ax3.xaxis.get_visible() assert not ax3.patch.get_visible() assert not ax3.yaxis.get_visible() assert ax.xaxis.get_visible() assert ax.patch.get_visible() assert ax.yaxis.get_visible() @image_comparison(baseline_images=['twin_autoscale'], extensions=['png']) def test_twinx_axis_scales(): x = np.array([0, 0.5, 1]) y = 0.5 * x x2 = np.array([0, 1, 2]) y2 = 2 * x2 fig = plt.figure() ax = fig.add_axes((0, 0, 1, 1), autoscalex_on=False, autoscaley_on=False) ax.plot(x, y, color='blue', lw=10) ax2 = plt.twinx(ax) ax2.plot(x2, y2, 'r--', lw=5) ax.margins(0, 0) ax2.margins(0, 0) def test_twin_inherit_autoscale_setting(): fig, ax = plt.subplots() ax_x_on = ax.twinx() ax.set_autoscalex_on(False) ax_x_off = ax.twinx() assert ax_x_on.get_autoscalex_on() assert not ax_x_off.get_autoscalex_on() ax_y_on = ax.twiny() ax.set_autoscaley_on(False) ax_y_off = ax.twiny() assert ax_y_on.get_autoscaley_on() assert not ax_y_off.get_autoscaley_on() def test_inverted_cla(): # Github PR #5450. Setting autoscale should reset # axes to be non-inverted. # plotting an image, then 1d graph, axis is now down fig = plt.figure(0) ax = fig.gca() # 1. test that a new axis is not inverted per default assert not ax.xaxis_inverted() assert not ax.yaxis_inverted() img = np.random.random((100, 100)) ax.imshow(img) # 2. test that a image axis is inverted assert not ax.xaxis_inverted() assert ax.yaxis_inverted() # 3. test that clearing and plotting a line, axes are # not inverted ax.cla() x = np.linspace(0, 2*np.pi, 100) ax.plot(x, np.cos(x)) assert not ax.xaxis_inverted() assert not ax.yaxis_inverted() # 4. autoscaling should not bring back axes to normal ax.cla() ax.imshow(img) plt.autoscale() assert not(ax.xaxis_inverted()) assert ax.yaxis_inverted() # 5. two shared axes. Clearing the master axis should bring axes in shared # axes back to normal ax0 = plt.subplot(211) ax1 = plt.subplot(212, sharey=ax0) ax0.imshow(img) ax1.plot(x, np.cos(x)) ax0.cla() assert not(ax1.yaxis_inverted()) ax1.cla() # 6. clearing the nonmaster should not touch limits ax0.imshow(img) ax1.plot(x, np.cos(x)) ax1.cla() assert ax.yaxis_inverted() # clean up plt.close(fig) @image_comparison(baseline_images=["minorticks_on_rcParams_both"], extensions=['png']) def test_minorticks_on_rcParams_both(): fig = plt.figure() matplotlib.rcParams['xtick.minor.visible'] = True matplotlib.rcParams['ytick.minor.visible'] = True plt.plot([0, 1], [0, 1]) plt.axis([0, 1, 0, 1]) @image_comparison(baseline_images=["autoscale_tiny_range"], remove_text=True) def test_autoscale_tiny_range(): # github pull #904 fig, ax = plt.subplots(2, 2) ax = ax.flatten() for i in xrange(4): y1 = 10**(-11 - i) ax[i].plot([0, 1], [1, 1 + y1]) @pytest.mark.style('default') def test_autoscale_tight(): fig, ax = plt.subplots(1, 1) ax.plot([1, 2, 3, 4]) ax.autoscale(enable=True, axis='x', tight=False) ax.autoscale(enable=True, axis='y', tight=True) assert_allclose(ax.get_xlim(), (-0.15, 3.15)) assert_allclose(ax.get_ylim(), (1.0, 4.0)) @pytest.mark.style('default') def test_autoscale_log_shared(): # related to github #7587 # array starts at zero to trigger _minpos handling x = np.arange(100, dtype=float) fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) ax1.loglog(x, x) ax2.semilogx(x, x) ax1.autoscale(tight=True) ax2.autoscale(tight=True) plt.draw() lims = (x[1], x[-1]) assert_allclose(ax1.get_xlim(), lims) assert_allclose(ax1.get_ylim(), lims) assert_allclose(ax2.get_xlim(), lims) assert_allclose(ax2.get_ylim(), (x[0], x[-1])) @pytest.mark.style('default') def test_use_sticky_edges(): fig, ax = plt.subplots() ax.imshow([[0, 1], [2, 3]], origin='lower') assert_allclose(ax.get_xlim(), (-0.5, 1.5)) assert_allclose(ax.get_ylim(), (-0.5, 1.5)) ax.use_sticky_edges = False ax.autoscale() xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin) ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin) assert_allclose(ax.get_xlim(), xlim) assert_allclose(ax.get_ylim(), ylim) # Make sure it is reversible: ax.use_sticky_edges = True ax.autoscale() assert_allclose(ax.get_xlim(), (-0.5, 1.5)) assert_allclose(ax.get_ylim(), (-0.5, 1.5)) @image_comparison(baseline_images=['offset_points'], remove_text=True) def test_basic_annotate(): # Setup some data t = np.arange(0.0, 5.0, 0.01) s = np.cos(2.0*np.pi * t) # Offset Points fig = plt.figure() ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-3, 5)) line, = ax.plot(t, s, lw=3, color='purple') ax.annotate('local max', xy=(3, 1), xycoords='data', xytext=(3, 3), textcoords='offset points') @image_comparison(baseline_images=['arrow_simple'], extensions=['png'], remove_text=True) def test_arrow_simple(): # Simple image test for ax.arrow # kwargs that take discrete values length_includes_head = (True, False) shape = ('full', 'left', 'right') head_starts_at_zero = (True, False) # Create outer product of values kwargs = list(product(length_includes_head, shape, head_starts_at_zero)) fig, axs = plt.subplots(3, 4) for i, (ax, kwarg) in enumerate(zip(axs.flatten(), kwargs)): ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) # Unpack kwargs (length_includes_head, shape, head_starts_at_zero) = kwarg theta = 2 * np.pi * i / 12 # Draw arrow ax.arrow(0, 0, np.sin(theta), np.cos(theta), width=theta/100, length_includes_head=length_includes_head, shape=shape, head_starts_at_zero=head_starts_at_zero, head_width=theta / 10, head_length=theta / 10) def test_annotate_default_arrow(): # Check that we can make an annotation arrow with only default properties. fig, ax = plt.subplots() ann = ax.annotate("foo", (0, 1), xytext=(2, 3)) assert ann.arrow_patch is None ann = ax.annotate("foo", (0, 1), xytext=(2, 3), arrowprops={}) assert ann.arrow_patch is not None @image_comparison(baseline_images=['polar_axes'], style='default') def test_polar_annotations(): # you can specify the xypoint and the xytext in different # positions and coordinate systems, and optionally turn on a # connecting line and mark the point with a marker. Annotations # work on polar axes too. In the example below, the xy point is # in native coordinates (xycoords defaults to 'data'). For a # polar axes, this is in (theta, radius) space. The text in this # example is placed in the fractional figure coordinate system. # Text keyword args like horizontal and vertical alignment are # respected # Setup some data r = np.arange(0.0, 1.0, 0.001) theta = 2.0 * 2.0 * np.pi * r fig = plt.figure() ax = fig.add_subplot(111, polar=True) line, = ax.plot(theta, r, color='#ee8d18', lw=3) line, = ax.plot((0, 0), (0, 1), color="#0000ff", lw=1) ind = 800 thisr, thistheta = r[ind], theta[ind] ax.plot([thistheta], [thisr], 'o') ax.annotate('a polar annotation', xy=(thistheta, thisr), # theta, radius xytext=(0.05, 0.05), # fraction, fraction textcoords='figure fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='left', verticalalignment='baseline', ) ax.tick_params(axis='x', tick1On=True, tick2On=True, direction='out') @image_comparison(baseline_images=['polar_coords'], style='default', remove_text=True) def test_polar_coord_annotations(): # You can also use polar notation on a catesian axes. Here the # native coordinate system ('data') is cartesian, so you need to # specify the xycoords and textcoords as 'polar' if you want to # use (theta, radius) from matplotlib.patches import Ellipse el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5) fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') ax.add_artist(el) el.set_clip_box(ax.bbox) ax.annotate('the top', xy=(np.pi/2., 10.), # theta, radius xytext=(np.pi/3, 20.), # theta, radius xycoords='polar', textcoords='polar', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='left', verticalalignment='baseline', clip_on=True, # clip to the axes bounding box ) ax.set_xlim(-20, 20) ax.set_ylim(-20, 20) @image_comparison(baseline_images=['fill_units'], extensions=['png'], savefig_kwarg={'dpi': 60}) def test_fill_units(): from datetime import datetime import matplotlib.testing.jpl_units as units units.register() # generate some data t = units.Epoch("ET", dt=datetime(2009, 4, 27)) value = 10.0 * units.deg day = units.Duration("ET", 24.0 * 60.0 * 60.0) fig = plt.figure() # Top-Left ax1 = fig.add_subplot(221) ax1.plot([t], [value], yunits='deg', color='red') ax1.fill([733525.0, 733525.0, 733526.0, 733526.0], [0.0, 0.0, 90.0, 0.0], 'b') # Top-Right ax2 = fig.add_subplot(222) ax2.plot([t], [value], yunits='deg', color='red') ax2.fill([t, t, t + day, t + day], [0.0, 0.0, 90.0, 0.0], 'b') # Bottom-Left ax3 = fig.add_subplot(223) ax3.plot([t], [value], yunits='deg', color='red') ax3.fill([733525.0, 733525.0, 733526.0, 733526.0], [0 * units.deg, 0 * units.deg, 90 * units.deg, 0 * units.deg], 'b') # Bottom-Right ax4 = fig.add_subplot(224) ax4.plot([t], [value], yunits='deg', color='red') ax4.fill([t, t, t + day, t + day], [0 * units.deg, 0 * units.deg, 90 * units.deg, 0 * units.deg], facecolor="blue") fig.autofmt_xdate() @image_comparison(baseline_images=['single_point', 'single_point']) def test_single_point(): # Issue #1796: don't let lines.marker affect the grid matplotlib.rcParams['lines.marker'] = 'o' matplotlib.rcParams['axes.grid'] = True fig = plt.figure() plt.subplot(211) plt.plot([0], [0], 'o') plt.subplot(212) plt.plot([1], [1], 'o') # Reuse testcase from above for a labeled data test data = {'a': [0], 'b': [1]} fig = plt.figure() plt.subplot(211) plt.plot('a', 'a', 'o', data=data) plt.subplot(212) plt.plot('b', 'b', 'o', data=data) @image_comparison(baseline_images=['single_date']) def test_single_date(): time1 = [721964.0] data1 = [-65.54] fig = plt.figure() plt.subplot(211) plt.plot_date(time1, data1, 'o', color='r') plt.subplot(212) plt.plot(time1, data1, 'o', color='r') @image_comparison(baseline_images=['shaped_data']) def test_shaped_data(): xdata = np.array([[0.53295185, 0.23052951, 0.19057629, 0.66724975, 0.96577916, 0.73136095, 0.60823287, 0.01792100, 0.29744742, 0.27164665], [0.27980120, 0.25814229, 0.02818193, 0.12966456, 0.57446277, 0.58167607, 0.71028245, 0.69112737, 0.89923072, 0.99072476], [0.81218578, 0.80464528, 0.76071809, 0.85616314, 0.12757994, 0.94324936, 0.73078663, 0.09658102, 0.60703967, 0.77664978], [0.28332265, 0.81479711, 0.86985333, 0.43797066, 0.32540082, 0.43819229, 0.92230363, 0.49414252, 0.68168256, 0.05922372], [0.10721335, 0.93904142, 0.79163075, 0.73232848, 0.90283839, 0.68408046, 0.25502302, 0.95976614, 0.59214115, 0.13663711], [0.28087456, 0.33127607, 0.15530412, 0.76558121, 0.83389773, 0.03735974, 0.98717738, 0.71432229, 0.54881366, 0.86893953], [0.77995937, 0.99555600, 0.29688434, 0.15646162, 0.05184800, 0.37161935, 0.12998491, 0.09377296, 0.36882507, 0.36583435], [0.37851836, 0.05315792, 0.63144617, 0.25003433, 0.69586032, 0.11393988, 0.92362096, 0.88045438, 0.93530252, 0.68275072], [0.86486596, 0.83236675, 0.82960664, 0.57796630, 0.25724233, 0.84841095, 0.90862812, 0.64414887, 0.35652720, 0.71026066], [0.01383268, 0.34060930, 0.76084285, 0.70800694, 0.87634056, 0.08213693, 0.54655021, 0.98123181, 0.44080053, 0.86815815]]) y1 = np.arange(10).reshape((1, -1)) y2 = np.arange(10).reshape((-1, 1)) fig = plt.figure() plt.subplot(411) plt.plot(y1) plt.subplot(412) plt.plot(y2) plt.subplot(413) with pytest.raises(ValueError): plt.plot((y1, y2)) plt.subplot(414) plt.plot(xdata[:, 1], xdata[1, :], 'o') @image_comparison(baseline_images=['const_xy']) def test_const_xy(): fig = plt.figure() plt.subplot(311) plt.plot(np.arange(10), np.ones((10,))) plt.subplot(312) plt.plot(np.ones((10,)), np.arange(10)) plt.subplot(313) plt.plot(np.ones((10,)), np.ones((10,)), 'o') @image_comparison(baseline_images=['polar_wrap_180', 'polar_wrap_360'], style='default') def test_polar_wrap(): fig = plt.figure() plt.subplot(111, polar=True) plt.polar(np.deg2rad([179, -179]), [0.2, 0.1], "b.-") plt.polar(np.deg2rad([179, 181]), [0.2, 0.1], "g.-") plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3]) assert len(fig.axes) == 1, 'More than one polar axes created.' fig = plt.figure() plt.subplot(111, polar=True) plt.polar(np.deg2rad([2, -2]), [0.2, 0.1], "b.-") plt.polar(np.deg2rad([2, 358]), [0.2, 0.1], "g.-") plt.polar(np.deg2rad([358, 2]), [0.2, 0.1], "r.-") plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3]) @image_comparison(baseline_images=['polar_units', 'polar_units_2'], style='default') def test_polar_units(): import matplotlib.testing.jpl_units as units units.register() pi = np.pi deg = units.deg km = units.km x1 = [pi/6.0, pi/4.0, pi/3.0, pi/2.0] x2 = [30.0*deg, 45.0*deg, 60.0*deg, 90.0*deg] y1 = [1.0, 2.0, 3.0, 4.0] y2 = [4.0, 3.0, 2.0, 1.0] fig = plt.figure() plt.polar(x2, y1, color="blue") # polar(x2, y1, color = "red", xunits="rad") # polar(x2, y2, color = "green") fig = plt.figure() # make sure runits and theta units work y1 = [y*km for y in y1] plt.polar(x2, y1, color="blue", thetaunits="rad", runits="km") assert isinstance(plt.gca().get_xaxis().get_major_formatter(), units.UnitDblFormatter) @image_comparison(baseline_images=['polar_rmin'], style='default') def test_polar_rmin(): r = np.arange(0, 3.0, 0.01) theta = 2*np.pi*r fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) ax.plot(theta, r) ax.set_rmax(2.0) ax.set_rmin(0.5) @image_comparison(baseline_images=['polar_negative_rmin'], style='default') def test_polar_negative_rmin(): r = np.arange(-3.0, 0.0, 0.01) theta = 2*np.pi*r fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) ax.plot(theta, r) ax.set_rmax(0.0) ax.set_rmin(-3.0) @image_comparison(baseline_images=['polar_rorigin'], style='default') def test_polar_rorigin(): r = np.arange(0, 3.0, 0.01) theta = 2*np.pi*r fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) ax.plot(theta, r) ax.set_rmax(2.0) ax.set_rmin(0.5) ax.set_rorigin(0.0) @image_comparison(baseline_images=['polar_theta_position'], style='default') def test_polar_theta_position(): r = np.arange(0, 3.0, 0.01) theta = 2*np.pi*r fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) ax.plot(theta, r) ax.set_theta_zero_location("NW", 30) ax.set_theta_direction('clockwise') @image_comparison(baseline_images=['polar_rlabel_position'], style='default') def test_polar_rlabel_position(): fig = plt.figure() ax = fig.add_subplot(111, projection='polar') ax.set_rlabel_position(315) ax.tick_params(rotation='auto') @image_comparison(baseline_images=['polar_theta_wedge'], style='default', tol=0.01 if six.PY2 else 0) def test_polar_theta_limits(): r = np.arange(0, 3.0, 0.01) theta = 2*np.pi*r theta_mins = np.arange(15.0, 361.0, 90.0) theta_maxs = np.arange(50.0, 361.0, 90.0) DIRECTIONS = ('out', 'in', 'inout') fig, axes = plt.subplots(len(theta_mins), len(theta_maxs), subplot_kw={'polar': True}, figsize=(8, 6)) for i, start in enumerate(theta_mins): for j, end in enumerate(theta_maxs): ax = axes[i, j] ax.plot(theta, r) if start < end: ax.set_thetamin(start) ax.set_thetamax(end) else: # Plot with clockwise orientation instead. ax.set_thetamin(end) ax.set_thetamax(start) ax.set_theta_direction('clockwise') ax.tick_params(tick1On=True, tick2On=True, direction=DIRECTIONS[i % len(DIRECTIONS)], rotation='auto') ax.yaxis.set_tick_params(label2On=True, rotation='auto') @image_comparison(baseline_images=['axvspan_epoch']) def test_axvspan_epoch(): from datetime import datetime import matplotlib.testing.jpl_units as units units.register() # generate some data t0 = units.Epoch("ET", dt=datetime(2009, 1, 20)) tf = units.Epoch("ET", dt=datetime(2009, 1, 21)) dt = units.Duration("ET", units.day.convert("sec")) fig = plt.figure() plt.axvspan(t0, tf, facecolor="blue", alpha=0.25) ax = plt.gca() ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) @image_comparison(baseline_images=['axhspan_epoch']) def test_axhspan_epoch(): from datetime import datetime import matplotlib.testing.jpl_units as units units.register() # generate some data t0 = units.Epoch("ET", dt=datetime(2009, 1, 20)) tf = units.Epoch("ET", dt=datetime(2009, 1, 21)) dt = units.Duration("ET", units.day.convert("sec")) fig = plt.figure() plt.axhspan(t0, tf, facecolor="blue", alpha=0.25) ax = plt.gca() ax.set_ylim(t0 - 5.0*dt, tf + 5.0*dt) @image_comparison(baseline_images=['hexbin_extent', 'hexbin_extent'], remove_text=True, extensions=['png']) def test_hexbin_extent(): # this test exposes sf bug 2856228 fig = plt.figure() ax = fig.add_subplot(111) data = (np.arange(2000) / 2000).reshape((2, 1000)) x, y = data ax.hexbin(x, y, extent=[.1, .3, .6, .7]) # Reuse testcase from above for a labeled data test data = {"x": x, "y": y} fig = plt.figure() ax = fig.add_subplot(111) ax.hexbin("x", "y", extent=[.1, .3, .6, .7], data=data) @image_comparison(baseline_images=['hexbin_empty'], remove_text=True, extensions=['png']) def test_hexbin_empty(): # From #3886: creating hexbin from empty dataset raises ValueError ax = plt.gca() ax.hexbin([], []) def test_hexbin_pickable(): # From #1973: Test that picking a hexbin collection works class FauxMouseEvent: def __init__(self, x, y): self.x = x self.y = y fig = plt.figure() ax = fig.add_subplot(111) data = (np.arange(200) / 200).reshape((2, 100)) x, y = data hb = ax.hexbin(x, y, extent=[.1, .3, .6, .7], picker=-1) assert hb.contains(FauxMouseEvent(400, 300))[0] @image_comparison(baseline_images=['hexbin_log'], remove_text=True, extensions=['png']) def test_hexbin_log(): # Issue #1636 fig = plt.figure() np.random.seed(0) n = 100000 x = np.random.standard_normal(n) y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n) y = np.power(2, y * 0.5) ax = fig.add_subplot(111) ax.hexbin(x, y, yscale='log') def test_inverted_limits(): # Test gh:1553 # Calling invert_xaxis prior to plotting should not disable autoscaling # while still maintaining the inverted direction fig = plt.figure() ax = fig.gca() ax.invert_xaxis() ax.plot([-5, -3, 2, 4], [1, 2, -3, 5]) assert ax.get_xlim() == (4, -5) assert ax.get_ylim() == (-3, 5) plt.close() fig = plt.figure() ax = fig.gca() ax.invert_yaxis() ax.plot([-5, -3, 2, 4], [1, 2, -3, 5]) assert ax.get_xlim() == (-5, 4) assert ax.get_ylim() == (5, -3) plt.close() @image_comparison(baseline_images=['nonfinite_limits']) def test_nonfinite_limits(): x = np.arange(0., np.e, 0.01) # silence divide by zero warning from log(0) olderr = np.seterr(divide='ignore') try: y = np.log(x) finally: np.seterr(**olderr) x[len(x)//2] = np.nan fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) @image_comparison(baseline_images=['imshow', 'imshow'], remove_text=True, style='mpl20') def test_imshow(): # Create a NxN image N = 100 (x, y) = np.indices((N, N)) x -= N//2 y -= N//2 r = np.sqrt(x**2+y**2-x*y) # Create a contour plot at N/4 and extract both the clip path and transform fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(r) # Reuse testcase from above for a labeled data test data = {"r": r} fig = plt.figure() ax = fig.add_subplot(111) ax.imshow("r", data=data) @image_comparison(baseline_images=['imshow_clip'], style='mpl20') def test_imshow_clip(): # As originally reported by Gellule Xg <[email protected]> # Create a NxN image N = 100 (x, y) = np.indices((N, N)) x -= N//2 y -= N//2 r = np.sqrt(x**2+y**2-x*y) # Create a contour plot at N/4 and extract both the clip path and transform fig = plt.figure() ax = fig.add_subplot(111) c = ax.contour(r, [N/4]) x = c.collections[0] clipPath = x.get_paths()[0] clipTransform = x.get_transform() from matplotlib.transforms import TransformedPath clip_path = TransformedPath(clipPath, clipTransform) # Plot the image clipped by the contour ax.imshow(r, clip_path=clip_path) @image_comparison(baseline_images=['polycollection_joinstyle'], remove_text=True) def test_polycollection_joinstyle(): # Bug #2890979 reported by Matthew West from matplotlib import collections as mcoll fig = plt.figure() ax = fig.add_subplot(111) verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]]) c = mcoll.PolyCollection([verts], linewidths=40) ax.add_collection(c) ax.set_xbound(0, 3) ax.set_ybound(0, 3) @pytest.mark.parametrize( 'x, y1, y2', [ (np.zeros((2, 2)), 3, 3), (np.arange(0.0, 2, 0.02), np.zeros((2, 2)), 3), (np.arange(0.0, 2, 0.02), 3, np.zeros((2, 2))) ], ids=[ '2d_x_input', '2d_y1_input', '2d_y2_input' ] ) def test_fill_between_input(x, y1, y2): fig = plt.figure() ax = fig.add_subplot(211) with pytest.raises(ValueError): ax.fill_between(x, y1, y2) @pytest.mark.parametrize( 'y, x1, x2', [ (np.zeros((2, 2)), 3, 3), (np.arange(0.0, 2, 0.02), np.zeros((2, 2)), 3), (np.arange(0.0, 2, 0.02), 3, np.zeros((2, 2))) ], ids=[ '2d_y_input', '2d_x1_input', '2d_x2_input' ] ) def test_fill_betweenx_input(y, x1, x2): fig = plt.figure() ax = fig.add_subplot(211) with pytest.raises(ValueError): ax.fill_betweenx(y, x1, x2) @image_comparison(baseline_images=['fill_between_interpolate'], remove_text=True) def test_fill_between_interpolate(): x = np.arange(0.0, 2, 0.02) y1 = np.sin(2*np.pi*x) y2 = 1.2*np.sin(4*np.pi*x) fig = plt.figure() ax = fig.add_subplot(211) ax.plot(x, y1, x, y2, color='black') ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='white', hatch='/', interpolate=True) ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True) # Test support for masked arrays. y2 = np.ma.masked_greater(y2, 1.0) # Test that plotting works for masked arrays with the first element masked y2[0] = np.ma.masked ax1 = fig.add_subplot(212, sharex=ax) ax1.plot(x, y1, x, y2, color='black') ax1.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', interpolate=True) ax1.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True) @image_comparison(baseline_images=['fill_between_interpolate_decreasing'], style='mpl20', remove_text=True) def test_fill_between_interpolate_decreasing(): p = np.array([724.3, 700, 655]) t = np.array([9.4, 7, 2.2]) prof = np.array([7.9, 6.6, 3.8]) fig = plt.figure(figsize=(9, 9)) ax = fig.add_subplot(1, 1, 1) ax.plot(t, p, 'tab:red') ax.plot(prof, p, 'k') ax.fill_betweenx(p, t, prof, where=prof < t, facecolor='blue', interpolate=True, alpha=0.4) ax.fill_betweenx(p, t, prof, where=prof > t, facecolor='red', interpolate=True, alpha=0.4) ax.set_xlim(0, 30) ax.set_ylim(800, 600) @image_comparison(baseline_images=['symlog']) def test_symlog(): x = np.array([0, 1, 2, 4, 6, 9, 12, 24]) y = np.array([1000000, 500000, 100000, 100, 5, 0, 0, 0]) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) ax.set_yscale('symlog') ax.set_xscale('linear') ax.set_ylim(-1, 10000000) @image_comparison(baseline_images=['symlog2'], remove_text=True) def test_symlog2(): # Numbers from -50 to 50, with 0.1 as step x = np.arange(-50, 50, 0.001) fig = plt.figure() ax = fig.add_subplot(511) # Plots a simple linear function 'f(x) = x' ax.plot(x, x) ax.set_xscale('symlog', linthreshx=20.0) ax.grid(True) ax = fig.add_subplot(512) # Plots a simple linear function 'f(x) = x' ax.plot(x, x) ax.set_xscale('symlog', linthreshx=2.0) ax.grid(True) ax = fig.add_subplot(513) # Plots a simple linear function 'f(x) = x' ax.plot(x, x) ax.set_xscale('symlog', linthreshx=1.0) ax.grid(True) ax = fig.add_subplot(514) # Plots a simple linear function 'f(x) = x' ax.plot(x, x) ax.set_xscale('symlog', linthreshx=0.1) ax.grid(True) ax = fig.add_subplot(515) # Plots a simple linear function 'f(x) = x' ax.plot(x, x) ax.set_xscale('symlog', linthreshx=0.01) ax.grid(True) ax.set_ylim(-0.1, 0.1) def test_pcolorargs_5205(): # Smoketest to catch issue found in gh:5205 x = [-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5] y = [-1.5, -1.25, -1.0, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5] X, Y = np.meshgrid(x, y) Z = np.hypot(X, Y) plt.pcolor(Z) plt.pcolor(list(Z)) plt.pcolor(x, y, Z) plt.pcolor(X, Y, list(Z)) @image_comparison(baseline_images=['pcolormesh'], remove_text=True) def test_pcolormesh(): n = 12 x = np.linspace(-1.5, 1.5, n) y = np.linspace(-1.5, 1.5, n*2) X, Y = np.meshgrid(x, y) Qx = np.cos(Y) - np.cos(X) Qz = np.sin(Y) + np.sin(X) Qx = (Qx + 1.1) Z = np.hypot(X, Y) / 5 Z = (Z - Z.min()) / Z.ptp() # The color array can include masked values: Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z) fig = plt.figure() ax = fig.add_subplot(131) ax.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k') ax = fig.add_subplot(132) ax.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w']) ax = fig.add_subplot(133) ax.pcolormesh(Qx, Qz, Z, shading="gouraud") @image_comparison(baseline_images=['pcolormesh_datetime_axis'], extensions=['png'], remove_text=False) def test_pcolormesh_datetime_axis(): fig = plt.figure() fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15) base = datetime.datetime(2013, 1, 1) x = np.array([base + datetime.timedelta(days=d) for d in range(21)]) y = np.arange(21) z1, z2 = np.meshgrid(np.arange(20), np.arange(20)) z = z1 * z2 plt.subplot(221) plt.pcolormesh(x[:-1], y[:-1], z) plt.subplot(222) plt.pcolormesh(x, y, z) x = np.repeat(x[np.newaxis], 21, axis=0) y = np.repeat(y[:, np.newaxis], 21, axis=1) plt.subplot(223) plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z) plt.subplot(224) plt.pcolormesh(x, y, z) for ax in fig.get_axes(): for label in ax.get_xticklabels(): label.set_ha('right') label.set_rotation(30) @image_comparison(baseline_images=['pcolor_datetime_axis'], extensions=['png'], remove_text=False) def test_pcolor_datetime_axis(): fig = plt.figure() fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15) base = datetime.datetime(2013, 1, 1) x = np.array([base + datetime.timedelta(days=d) for d in range(21)]) y = np.arange(21) z1, z2 = np.meshgrid(np.arange(20), np.arange(20)) z = z1 * z2 plt.subplot(221) plt.pcolor(x[:-1], y[:-1], z) plt.subplot(222) plt.pcolor(x, y, z) x = np.repeat(x[np.newaxis], 21, axis=0) y = np.repeat(y[:, np.newaxis], 21, axis=1) plt.subplot(223) plt.pcolor(x[:-1, :-1], y[:-1, :-1], z) plt.subplot(224) plt.pcolor(x, y, z) for ax in fig.get_axes(): for label in ax.get_xticklabels(): label.set_ha('right') label.set_rotation(30) def test_pcolorargs(): n = 12 x = np.linspace(-1.5, 1.5, n) y = np.linspace(-1.5, 1.5, n*2) X, Y = np.meshgrid(x, y) Z = np.sqrt(X**2 + Y**2)/5 _, ax = plt.subplots() with pytest.raises(TypeError): ax.pcolormesh(y, x, Z) with pytest.raises(TypeError): ax.pcolormesh(X, Y, Z.T) with pytest.raises(TypeError): ax.pcolormesh(x, y, Z[:-1, :-1], shading="gouraud") with pytest.raises(TypeError): ax.pcolormesh(X, Y, Z[:-1, :-1], shading="gouraud") x[0] = np.NaN with pytest.raises(ValueError): ax.pcolormesh(x, y, Z[:-1, :-1]) with np.errstate(invalid='ignore'): x = np.ma.array(x, mask=(x < 0)) with pytest.raises(ValueError): ax.pcolormesh(x, y, Z[:-1, :-1]) @image_comparison(baseline_images=['canonical']) def test_canonical(): fig, ax = plt.subplots() ax.plot([1, 2, 3]) @image_comparison(baseline_images=['arc_angles'], remove_text=True, style='default', extensions=['png']) def test_arc_angles(): from matplotlib import patches # Ellipse parameters w = 2 h = 1 centre = (0.2, 0.5) scale = 2 fig, axs = plt.subplots(3, 3) for i, ax in enumerate(axs.flat): theta2 = i * 360 / 9 theta1 = theta2 - 45 ax.add_patch(patches.Ellipse(centre, w, h, alpha=0.3)) ax.add_patch(patches.Arc(centre, w, h, theta1=theta1, theta2=theta2)) # Straight lines intersecting start and end of arc ax.plot([scale * np.cos(np.deg2rad(theta1)) + centre[0], centre[0], scale * np.cos(np.deg2rad(theta2)) + centre[0]], [scale * np.sin(np.deg2rad(theta1)) + centre[1], centre[1], scale * np.sin(np.deg2rad(theta2)) + centre[1]]) ax.set_xlim(-scale, scale) ax.set_ylim(-scale, scale) # This looks the same, but it triggers a different code path when it # gets large enough. w *= 10 h *= 10 centre = (centre[0] * 10, centre[1] * 10) scale *= 10 @image_comparison(baseline_images=['arc_ellipse'], remove_text=True) def test_arc_ellipse(): from matplotlib import patches xcenter, ycenter = 0.38, 0.52 width, height = 1e-1, 3e-1 angle = -30 theta = np.deg2rad(np.arange(360)) x = width / 2. * np.cos(theta) y = height / 2. * np.sin(theta) rtheta = np.deg2rad(angle) R = np.array([ [np.cos(rtheta), -np.sin(rtheta)], [np.sin(rtheta), np.cos(rtheta)]]) x, y = np.dot(R, np.array([x, y])) x += xcenter y += ycenter fig = plt.figure() ax = fig.add_subplot(211, aspect='auto') ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1) e1 = patches.Arc((xcenter, ycenter), width, height, angle=angle, linewidth=2, fill=False, zorder=2) ax.add_patch(e1) ax = fig.add_subplot(212, aspect='equal') ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1) e2 = patches.Arc((xcenter, ycenter), width, height, angle=angle, linewidth=2, fill=False, zorder=2) ax.add_patch(e2) @image_comparison(baseline_images=['markevery'], remove_text=True) def test_markevery(): x = np.linspace(0, 10, 100) y = np.sin(x) * np.sqrt(x/10 + 0.5) # check marker only plot fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y, 'o', label='default') ax.plot(x, y, 'd', markevery=None, label='mark all') ax.plot(x, y, 's', markevery=10, label='mark every 10') ax.plot(x, y, '+', markevery=(5, 20), label='mark every 5 starting at 10') ax.legend() @image_comparison(baseline_images=['markevery_line'], remove_text=True) def test_markevery_line(): x = np.linspace(0, 10, 100) y = np.sin(x) * np.sqrt(x/10 + 0.5) # check line/marker combos fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y, '-o', label='default') ax.plot(x, y, '-d', markevery=None, label='mark all') ax.plot(x, y, '-s', markevery=10, label='mark every 10') ax.plot(x, y, '-+', markevery=(5, 20), label='mark every 5 starting at 10') ax.legend() @image_comparison(baseline_images=['markevery_linear_scales'], remove_text=True) def test_markevery_linear_scales(): cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cols = 3 gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols) delta = 0.11 x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta for i, case in enumerate(cases): row = (i // cols) col = i % cols plt.subplot(gs[row, col]) plt.title('markevery=%s' % str(case)) plt.plot(x, y, 'o', ls='-', ms=4, markevery=case) @image_comparison(baseline_images=['markevery_linear_scales_zoomed'], remove_text=True) def test_markevery_linear_scales_zoomed(): cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cols = 3 gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols) delta = 0.11 x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta for i, case in enumerate(cases): row = (i // cols) col = i % cols plt.subplot(gs[row, col]) plt.title('markevery=%s' % str(case)) plt.plot(x, y, 'o', ls='-', ms=4, markevery=case) plt.xlim((6, 6.7)) plt.ylim((1.1, 1.7)) @image_comparison(baseline_images=['markevery_log_scales'], remove_text=True) def test_markevery_log_scales(): cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cols = 3 gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols) delta = 0.11 x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta for i, case in enumerate(cases): row = (i // cols) col = i % cols plt.subplot(gs[row, col]) plt.title('markevery=%s' % str(case)) plt.xscale('log') plt.yscale('log') plt.plot(x, y, 'o', ls='-', ms=4, markevery=case) @image_comparison(baseline_images=['markevery_polar'], style='default', remove_text=True) def test_markevery_polar(): cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cols = 3 gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols) r = np.linspace(0, 3.0, 200) theta = 2 * np.pi * r for i, case in enumerate(cases): row = (i // cols) col = i % cols plt.subplot(gs[row, col], polar=True) plt.title('markevery=%s' % str(case)) plt.plot(theta, r, 'o', ls='-', ms=4, markevery=case) @image_comparison(baseline_images=['marker_edges'], remove_text=True) def test_marker_edges(): x = np.linspace(0, 1, 10) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, np.sin(x), 'y.', ms=30.0, mew=0, mec='r') ax.plot(x+0.1, np.sin(x), 'y.', ms=30.0, mew=1, mec='r') ax.plot(x+0.2, np.sin(x), 'y.', ms=30.0, mew=2, mec='b') @image_comparison(baseline_images=['bar_tick_label_single', 'bar_tick_label_single'], extensions=['png']) def test_bar_tick_label_single(): # From 2516: plot bar with array of string labels for x axis ax = plt.gca() ax.bar(0, 1, tick_label='0') # Reuse testcase from above for a labeled data test data = {"a": 0, "b": 1} fig = plt.figure() ax = fig.add_subplot(111) ax = plt.gca() ax.bar("a", "b", tick_label='0', data=data) def test_bar_ticklabel_fail(): fig, ax = plt.subplots() ax.bar([], []) @image_comparison(baseline_images=['bar_tick_label_multiple'], extensions=['png']) def test_bar_tick_label_multiple(): # From 2516: plot bar with array of string labels for x axis ax = plt.gca() ax.bar([1, 2.5], [1, 2], width=[0.2, 0.5], tick_label=['a', 'b'], align='center') @image_comparison( baseline_images=['bar_tick_label_multiple_old_label_alignment'], extensions=['png']) def test_bar_tick_label_multiple_old_alignment(): # Test that the algnment for class is backward compatible matplotlib.rcParams["ytick.alignment"] = "center" ax = plt.gca() ax.bar([1, 2.5], [1, 2], width=[0.2, 0.5], tick_label=['a', 'b'], align='center') @image_comparison(baseline_images=['barh_tick_label'], extensions=['png']) def test_barh_tick_label(): # From 2516: plot barh with array of string labels for y axis ax = plt.gca() ax.barh([1, 2.5], [1, 2], height=[0.2, 0.5], tick_label=['a', 'b'], align='center') @image_comparison(baseline_images=['hist_log'], remove_text=True) def test_hist_log(): data0 = np.linspace(0, 1, 200)**3 data = np.r_[1-data0, 1+data0] fig = plt.figure() ax = fig.add_subplot(111) ax.hist(data, fill=False, log=True) @image_comparison(baseline_images=['hist_bar_empty'], remove_text=True, extensions=['png']) def test_hist_bar_empty(): # From #3886: creating hist from empty dataset raises ValueError ax = plt.gca() ax.hist([], histtype='bar') @image_comparison(baseline_images=['hist_step_empty'], remove_text=True, extensions=['png']) def test_hist_step_empty(): # From #3886: creating hist from empty dataset raises ValueError ax = plt.gca() ax.hist([], histtype='step') @image_comparison(baseline_images=['hist_steplog'], remove_text=True, tol=0.1) def test_hist_steplog(): np.random.seed(0) data = np.random.standard_normal(2000) data += -2.0 - np.min(data) data_pos = data + 2.1 data_big = data_pos + 30 weights = np.ones_like(data) * 1.e-5 ax = plt.subplot(4, 1, 1) plt.hist(data, 100, histtype='stepfilled', log=True) ax = plt.subplot(4, 1, 2) plt.hist(data_pos, 100, histtype='stepfilled', log=True) ax = plt.subplot(4, 1, 3) plt.hist(data, 100, weights=weights, histtype='stepfilled', log=True) ax = plt.subplot(4, 1, 4) plt.hist(data_big, 100, histtype='stepfilled', log=True, orientation='horizontal') @image_comparison(baseline_images=['hist_step_filled'], remove_text=True, extensions=['png']) def test_hist_step_filled(): np.random.seed(0) x = np.random.randn(1000, 3) n_bins = 10 kwargs = [{'fill': True}, {'fill': False}, {'fill': None}, {}]*2 types = ['step']*4+['stepfilled']*4 fig, axes = plt.subplots(nrows=2, ncols=4) axes = axes.flatten() for kg, _type, ax in zip(kwargs, types, axes): ax.hist(x, n_bins, histtype=_type, stacked=True, **kg) ax.set_title('%s/%s' % (kg, _type)) ax.set_ylim(ymin=-50) patches = axes[0].patches assert all([p.get_facecolor() == p.get_edgecolor() for p in patches]) @image_comparison(baseline_images=['hist_density'], extensions=['png']) def test_hist_density(): np.random.seed(19680801) data = np.random.standard_normal(2000) fig, ax = plt.subplots() ax.hist(data, density=True) @image_comparison(baseline_images=['hist_step_log_bottom'], remove_text=True, extensions=['png']) def test_hist_step_log_bottom(): # check that bottom doesn't get overwritten by the 'minimum' on a # log scale histogram (https://github.com/matplotlib/matplotlib/pull/4608) np.random.seed(0) data = np.random.standard_normal(2000) fig = plt.figure() ax = fig.add_subplot(111) # normal hist (should clip minimum to 1/base) ax.hist(data, bins=10, log=True, histtype='stepfilled', alpha=0.5, color='b') # manual bottom < 1/base (previously buggy, see #4608) ax.hist(data, bins=10, log=True, histtype='stepfilled', alpha=0.5, color='g', bottom=1e-2) # manual bottom > 1/base ax.hist(data, bins=10, log=True, histtype='stepfilled', alpha=0.5, color='r', bottom=0.5) # array bottom with some less than 1/base (should clip to 1/base) ax.hist(data, bins=10, log=True, histtype='stepfilled', alpha=0.5, color='y', bottom=np.arange(10)) ax.set_ylim(9e-3, 1e3) def test_hist_unequal_bins_density(): # Test correct behavior of normalized histogram with unequal bins # https://github.com/matplotlib/matplotlib/issues/9557 rng = np.random.RandomState(57483) t = rng.randn(100) bins = [-3, -1, -0.5, 0, 1, 5] mpl_heights, _, _ = plt.hist(t, bins=bins, density=True) np_heights, _ = np.histogram(t, bins=bins, density=True) assert_allclose(mpl_heights, np_heights) def test_hist_datetime_datasets(): data = [[datetime.datetime(2017, 1, 1), datetime.datetime(2017, 1, 1)], [datetime.datetime(2017, 1, 1), datetime.datetime(2017, 1, 2)]] fig, ax = plt.subplots() ax.hist(data, stacked=True) ax.hist(data, stacked=False) def contour_dat(): x = np.linspace(-3, 5, 150) y = np.linspace(-3, 5, 120) z = np.cos(x) + np.sin(y[:, np.newaxis]) return x, y, z @image_comparison(baseline_images=['contour_hatching']) def test_contour_hatching(): x, y, z = contour_dat() fig = plt.figure() ax = fig.add_subplot(111) cs = ax.contourf(x, y, z, hatches=['-', '/', '\\', '//'], cmap=plt.get_cmap('gray'), extend='both', alpha=0.5) @image_comparison(baseline_images=['contour_colorbar']) def test_contour_colorbar(): x, y, z = contour_dat() fig = plt.figure() ax = fig.add_subplot(111) cs = ax.contourf(x, y, z, levels=np.arange(-1.8, 1.801, 0.2), cmap=plt.get_cmap('RdBu'), vmin=-0.6, vmax=0.6, extend='both') cs1 = ax.contour(x, y, z, levels=np.arange(-2.2, -0.599, 0.2), colors=['y'], linestyles='solid', linewidths=2) cs2 = ax.contour(x, y, z, levels=np.arange(0.6, 2.2, 0.2), colors=['c'], linewidths=2) cbar = fig.colorbar(cs, ax=ax) cbar.add_lines(cs1) cbar.add_lines(cs2, erase=False) @image_comparison(baseline_images=['hist2d', 'hist2d']) def test_hist2d(): np.random.seed(0) # make it not symmetric in case we switch x and y axis x = np.random.randn(100)*2+5 y = np.random.randn(100)-2 fig = plt.figure() ax = fig.add_subplot(111) ax.hist2d(x, y, bins=10) # Reuse testcase from above for a labeled data test data = {"x": x, "y": y} fig = plt.figure() ax = fig.add_subplot(111) ax.hist2d("x", "y", bins=10, data=data) @image_comparison(baseline_images=['hist2d_transpose']) def test_hist2d_transpose(): np.random.seed(0) # make sure the output from np.histogram is transposed before # passing to pcolorfast x = np.array([5]*100) y = np.random.randn(100)-2 fig = plt.figure() ax = fig.add_subplot(111) ax.hist2d(x, y, bins=10) @image_comparison(baseline_images=['scatter', 'scatter']) def test_scatter_plot(): fig, ax = plt.subplots() data = {"x": [3, 4, 2, 6], "y": [2, 5, 2, 3], "c": ['r', 'y', 'b', 'lime'], "s": [24, 15, 19, 29]} ax.scatter(data["x"], data["y"], c=data["c"], s=data["s"]) # Reuse testcase from above for a labeled data test fig, ax = plt.subplots() ax.scatter("x", "y", c="c", s="s", data=data) @image_comparison(baseline_images=['scatter_marker'], remove_text=True, extensions=['png']) def test_scatter_marker(): fig, (ax0, ax1, ax2) = plt.subplots(ncols=3) ax0.scatter([3, 4, 2, 6], [2, 5, 2, 3], c=[(1, 0, 0), 'y', 'b', 'lime'], s=[60, 50, 40, 30], edgecolors=['k', 'r', 'g', 'b'], marker='s') ax1.scatter([3, 4, 2, 6], [2, 5, 2, 3], c=[(1, 0, 0), 'y', 'b', 'lime'], s=[60, 50, 40, 30], edgecolors=['k', 'r', 'g', 'b'], marker=mmarkers.MarkerStyle('o', fillstyle='top')) # unit area ellipse rx, ry = 3, 1 area = rx * ry * np.pi theta = np.linspace(0, 2 * np.pi, 21) verts = np.column_stack([np.cos(theta) * rx / area, np.sin(theta) * ry / area]) ax2.scatter([3, 4, 2, 6], [2, 5, 2, 3], c=[(1, 0, 0), 'y', 'b', 'lime'], s=[60, 50, 40, 30], edgecolors=['k', 'r', 'g', 'b'], verts=verts) @image_comparison(baseline_images=['scatter_2D'], remove_text=True, extensions=['png']) def test_scatter_2D(): x = np.arange(3) y = np.arange(2) x, y = np.meshgrid(x, y) z = x + y fig, ax = plt.subplots() ax.scatter(x, y, c=z, s=200, edgecolors='face') def test_scatter_color(): # Try to catch cases where 'c' kwarg should have been used. with pytest.raises(ValueError): plt.scatter([1, 2], [1, 2], color=[0.1, 0.2]) with pytest.raises(ValueError): plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3]) def test_as_mpl_axes_api(): # tests the _as_mpl_axes api from matplotlib.projections.polar import PolarAxes import matplotlib.axes as maxes class Polar(object): def __init__(self): self.theta_offset = 0 def _as_mpl_axes(self): # implement the matplotlib axes interface return PolarAxes, {'theta_offset': self.theta_offset} prj = Polar() prj2 = Polar() prj2.theta_offset = np.pi prj3 = Polar() # testing axes creation with plt.axes ax = plt.axes([0, 0, 1, 1], projection=prj) assert type(ax) == PolarAxes ax_via_gca = plt.gca(projection=prj) assert ax_via_gca is ax plt.close() # testing axes creation with gca ax = plt.gca(projection=prj) assert type(ax) == maxes._subplots._subplot_classes[PolarAxes] ax_via_gca = plt.gca(projection=prj) assert ax_via_gca is ax # try getting the axes given a different polar projection with pytest.warns(UserWarning) as rec: ax_via_gca = plt.gca(projection=prj2) assert len(rec) == 1 assert 'Requested projection is different' in str(rec[0].message) assert ax_via_gca is not ax assert ax.get_theta_offset() == 0 assert ax_via_gca.get_theta_offset() == np.pi # try getting the axes given an == (not is) polar projection with pytest.warns(UserWarning): ax_via_gca = plt.gca(projection=prj3) assert len(rec) == 1 assert 'Requested projection is different' in str(rec[0].message) assert ax_via_gca is ax plt.close() # testing axes creation with subplot ax = plt.subplot(121, projection=prj) assert type(ax) == maxes._subplots._subplot_classes[PolarAxes] plt.close() def test_pyplot_axes(): # test focusing of Axes in other Figure fig1, ax1 = plt.subplots() fig2, ax2 = plt.subplots() assert ax1 is plt.axes(ax1) assert ax1 is plt.gca() assert fig1 is plt.gcf() plt.close(fig1) plt.close(fig2) @image_comparison(baseline_images=['log_scales']) def test_log_scales(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.log(np.linspace(0.1, 100))) ax.set_yscale('log', basey=5.5) ax.invert_yaxis() ax.set_xscale('log', basex=9.0) @image_comparison(baseline_images=['stackplot_test_image', 'stackplot_test_image']) def test_stackplot(): fig = plt.figure() x = np.linspace(0, 10, 10) y1 = 1.0 * x y2 = 2.0 * x + 1 y3 = 3.0 * x + 2 ax = fig.add_subplot(1, 1, 1) ax.stackplot(x, y1, y2, y3) ax.set_xlim((0, 10)) ax.set_ylim((0, 70)) # Reuse testcase from above for a labeled data test data = {"x": x, "y1": y1, "y2": y2, "y3": y3} fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.stackplot("x", "y1", "y2", "y3", data=data) ax.set_xlim((0, 10)) ax.set_ylim((0, 70)) @image_comparison(baseline_images=['stackplot_test_baseline'], remove_text=True) def test_stackplot_baseline(): np.random.seed(0) def layers(n, m): a = np.zeros((m, n)) for i in range(n): for j in range(5): x = 1 / (.1 + np.random.random()) y = 2 * np.random.random() - .5 z = 10 / (.1 + np.random.random()) a[:, i] += x * np.exp(-((np.arange(m) / m - y) * z) ** 2) return a d = layers(3, 100) d[50, :] = 0 # test for fixed weighted wiggle (issue #6313) fig, axs = plt.subplots(2, 2) axs[0, 0].stackplot(range(100), d.T, baseline='zero') axs[0, 1].stackplot(range(100), d.T, baseline='sym') axs[1, 0].stackplot(range(100), d.T, baseline='wiggle') axs[1, 1].stackplot(range(100), d.T, baseline='weighted_wiggle') @image_comparison(baseline_images=['bxp_baseline'], extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_baseline(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats) @image_comparison(baseline_images=['bxp_rangewhis'], extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_rangewhis(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)), whis='range' ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats) @image_comparison(baseline_images=['bxp_precentilewhis'], extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_precentilewhis(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)), whis=[5, 95] ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats) @image_comparison(baseline_images=['bxp_with_xlabels'], extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_with_xlabels(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) for stats, label in zip(logstats, list('ABCD')): stats['label'] = label fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats) @image_comparison(baseline_images=['bxp_horizontal'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default', tol=0.1) def test_bxp_horizontal(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_xscale('log') ax.bxp(logstats, vert=False) @image_comparison(baseline_images=['bxp_with_ylabels'], extensions=['png'], savefig_kwarg={'dpi': 40}, style='default', tol=0.1,) def test_bxp_with_ylabels(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) for stats, label in zip(logstats, list('ABCD')): stats['label'] = label fig, ax = plt.subplots() ax.set_xscale('log') ax.bxp(logstats, vert=False) @image_comparison(baseline_images=['bxp_patchartist'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_patchartist(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, patch_artist=True) @image_comparison(baseline_images=['bxp_custompatchartist'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 100}, style='default') def test_bxp_custompatchartist(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') boxprops = dict(facecolor='yellow', edgecolor='green', linestyle='dotted') ax.bxp(logstats, patch_artist=True, boxprops=boxprops) @image_comparison(baseline_images=['bxp_customoutlier'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_customoutlier(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') flierprops = dict(linestyle='none', marker='d', markerfacecolor='g') ax.bxp(logstats, flierprops=flierprops) @image_comparison(baseline_images=['bxp_withmean_custompoint'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_showcustommean(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') meanprops = dict(linestyle='none', marker='d', markerfacecolor='green') ax.bxp(logstats, showmeans=True, meanprops=meanprops) @image_comparison(baseline_images=['bxp_custombox'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_custombox(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') boxprops = dict(linestyle='--', color='b', linewidth=3) ax.bxp(logstats, boxprops=boxprops) @image_comparison(baseline_images=['bxp_custommedian'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_custommedian(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') medianprops = dict(linestyle='--', color='b', linewidth=3) ax.bxp(logstats, medianprops=medianprops) @image_comparison(baseline_images=['bxp_customcap'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_customcap(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') capprops = dict(linestyle='--', color='g', linewidth=3) ax.bxp(logstats, capprops=capprops) @image_comparison(baseline_images=['bxp_customwhisker'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_customwhisker(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') whiskerprops = dict(linestyle='-', color='m', linewidth=3) ax.bxp(logstats, whiskerprops=whiskerprops) @image_comparison(baseline_images=['bxp_withnotch'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_shownotches(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, shownotches=True) @image_comparison(baseline_images=['bxp_nocaps'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_nocaps(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, showcaps=False) @image_comparison(baseline_images=['bxp_nobox'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_nobox(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, showbox=False) @image_comparison(baseline_images=['bxp_no_flier_stats'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_no_flier_stats(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) for ls in logstats: ls.pop('fliers', None) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, showfliers=False) @image_comparison(baseline_images=['bxp_withmean_point'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_showmean(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, showmeans=True, meanline=False) @image_comparison(baseline_images=['bxp_withmean_line'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_showmeanasline(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, showmeans=True, meanline=True) @image_comparison(baseline_images=['bxp_scalarwidth'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_scalarwidth(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, widths=0.25) @image_comparison(baseline_images=['bxp_customwidths'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_customwidths(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, widths=[0.10, 0.25, 0.65, 0.85]) @image_comparison(baseline_images=['bxp_custompositions'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_bxp_custompositions(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') ax.bxp(logstats, positions=[1, 5, 6, 7]) def test_bxp_bad_widths(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') with pytest.raises(ValueError): ax.bxp(logstats, widths=[1]) def test_bxp_bad_positions(): np.random.seed(937) logstats = matplotlib.cbook.boxplot_stats( np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)) ) fig, ax = plt.subplots() ax.set_yscale('log') with pytest.raises(ValueError): ax.bxp(logstats, positions=[2, 3]) @image_comparison(baseline_images=['boxplot', 'boxplot'], tol=1, style='default') def test_boxplot(): # Randomness used for bootstrapping. np.random.seed(937) x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() ax.boxplot([x, x], bootstrap=10000, notch=1) ax.set_ylim((-30, 30)) # Reuse testcase from above for a labeled data test data = {"x": [x, x]} fig, ax = plt.subplots() ax.boxplot("x", bootstrap=10000, notch=1, data=data) ax.set_ylim((-30, 30)) @image_comparison(baseline_images=['boxplot_sym2'], remove_text=True, extensions=['png'], style='default') def test_boxplot_sym2(): # Randomness used for bootstrapping. np.random.seed(937) x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, [ax1, ax2] = plt.subplots(1, 2) ax1.boxplot([x, x], bootstrap=10000, sym='^') ax1.set_ylim((-30, 30)) ax2.boxplot([x, x], bootstrap=10000, sym='g') ax2.set_ylim((-30, 30)) @image_comparison(baseline_images=['boxplot_sym'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_boxplot_sym(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() ax.boxplot([x, x], sym='gs') ax.set_ylim((-30, 30)) @image_comparison( baseline_images=['boxplot_autorange_false_whiskers', 'boxplot_autorange_true_whiskers'], extensions=['png'], style='default' ) def test_boxplot_autorange_whiskers(): # Randomness used for bootstrapping. np.random.seed(937) x = np.ones(140) x = np.hstack([0, x, 2]) fig1, ax1 = plt.subplots() ax1.boxplot([x, x], bootstrap=10000, notch=1) ax1.set_ylim((-5, 5)) fig2, ax2 = plt.subplots() ax2.boxplot([x, x], bootstrap=10000, notch=1, autorange=True) ax2.set_ylim((-5, 5)) def _rc_test_bxp_helper(ax, rc_dict): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) with matplotlib.rc_context(rc_dict): ax.boxplot([x, x]) return ax @image_comparison(baseline_images=['boxplot_rc_parameters'], savefig_kwarg={'dpi': 100}, remove_text=True, tol=1, style='default') def test_boxplot_rc_parameters(): # Randomness used for bootstrapping. np.random.seed(937) fig, ax = plt.subplots(3) rc_axis0 = { 'boxplot.notch': True, 'boxplot.whiskers': [5, 95], 'boxplot.bootstrap': 10000, 'boxplot.flierprops.color': 'b', 'boxplot.flierprops.marker': 'o', 'boxplot.flierprops.markerfacecolor': 'g', 'boxplot.flierprops.markeredgecolor': 'b', 'boxplot.flierprops.markersize': 5, 'boxplot.flierprops.linestyle': '--', 'boxplot.flierprops.linewidth': 2.0, 'boxplot.boxprops.color': 'r', 'boxplot.boxprops.linewidth': 2.0, 'boxplot.boxprops.linestyle': '--', 'boxplot.capprops.color': 'c', 'boxplot.capprops.linewidth': 2.0, 'boxplot.capprops.linestyle': '--', 'boxplot.medianprops.color': 'k', 'boxplot.medianprops.linewidth': 2.0, 'boxplot.medianprops.linestyle': '--', } rc_axis1 = { 'boxplot.vertical': False, 'boxplot.whiskers': 'range', 'boxplot.patchartist': True, } rc_axis2 = { 'boxplot.whiskers': 2.0, 'boxplot.showcaps': False, 'boxplot.showbox': False, 'boxplot.showfliers': False, 'boxplot.showmeans': True, 'boxplot.meanline': True, 'boxplot.meanprops.color': 'c', 'boxplot.meanprops.linewidth': 2.0, 'boxplot.meanprops.linestyle': '--', 'boxplot.whiskerprops.color': 'r', 'boxplot.whiskerprops.linewidth': 2.0, 'boxplot.whiskerprops.linestyle': '-.', } dict_list = [rc_axis0, rc_axis1, rc_axis2] for axis, rc_axis in zip(ax, dict_list): _rc_test_bxp_helper(axis, rc_axis) assert (matplotlib.patches.PathPatch in [type(t) for t in ax[1].get_children()]) @image_comparison(baseline_images=['boxplot_with_CIarray'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_boxplot_with_CIarray(): # Randomness used for bootstrapping. np.random.seed(937) x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig = plt.figure() ax = fig.add_subplot(111) CIs = np.array([[-1.5, 3.], [-1., 3.5]]) # show 1 boxplot with mpl medians/conf. interfals, 1 with manual values ax.boxplot([x, x], bootstrap=10000, usermedians=[None, 1.0], conf_intervals=CIs, notch=1) ax.set_ylim((-30, 30)) @image_comparison(baseline_images=['boxplot_no_inverted_whisker'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_boxplot_no_weird_whisker(): x = np.array([3, 9000, 150, 88, 350, 200000, 1400, 960], dtype=np.float64) ax1 = plt.axes() ax1.boxplot(x) ax1.set_yscale('log') ax1.yaxis.grid(False, which='minor') ax1.xaxis.grid(False) def test_boxplot_bad_medians_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() with pytest.raises(ValueError): ax.boxplot(x, usermedians=[1, 2]) def test_boxplot_bad_medians_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() with pytest.raises(ValueError): ax.boxplot([x, x], usermedians=[[1, 2], [1, 2]]) def test_boxplot_bad_ci_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() with pytest.raises(ValueError): ax.boxplot([x, x], conf_intervals=[[1, 2]]) def test_boxplot_zorder(): x = np.arange(10) fix, ax = plt.subplots() assert ax.boxplot(x)['boxes'][0].get_zorder() == 2 assert ax.boxplot(x, zorder=10)['boxes'][0].get_zorder() == 10 def test_boxplot_bad_ci_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() with pytest.raises(ValueError): ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) @image_comparison(baseline_images=['boxplot_mod_artists_after_plotting'], remove_text=True, extensions=['png'], savefig_kwarg={'dpi': 40}, style='default') def test_boxplot_mod_artist_after_plotting(): x = [0.15, 0.11, 0.06, 0.06, 0.12, 0.56, -0.56] fig, ax = plt.subplots() bp = ax.boxplot(x, sym="o") for key in bp: for obj in bp[key]: obj.set_color('green') @image_comparison(baseline_images=['violinplot_vert_baseline', 'violinplot_vert_baseline'], extensions=['png']) def test_vert_violinplot_baseline(): # First 9 digits of frac(sqrt(2)) np.random.seed(414213562) data = [np.random.normal(size=100) for i in range(4)] ax = plt.axes() ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=0) # Reuse testcase from above for a labeled data test data = {"d": data} fig, ax = plt.subplots() ax = plt.axes() ax.violinplot("d", positions=range(4), showmeans=0, showextrema=0, showmedians=0, data=data) @image_comparison(baseline_images=['violinplot_vert_showmeans'], extensions=['png']) def test_vert_violinplot_showmeans(): ax = plt.axes() # First 9 digits of frac(sqrt(3)) np.random.seed(732050807) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), showmeans=1, showextrema=0, showmedians=0) @image_comparison(baseline_images=['violinplot_vert_showextrema'], extensions=['png']) def test_vert_violinplot_showextrema(): ax = plt.axes() # First 9 digits of frac(sqrt(5)) np.random.seed(236067977) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=1, showmedians=0) @image_comparison(baseline_images=['violinplot_vert_showmedians'], extensions=['png']) def test_vert_violinplot_showmedians(): ax = plt.axes() # First 9 digits of frac(sqrt(7)) np.random.seed(645751311) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=1) @image_comparison(baseline_images=['violinplot_vert_showall'], extensions=['png']) def test_vert_violinplot_showall(): ax = plt.axes() # First 9 digits of frac(sqrt(11)) np.random.seed(316624790) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), showmeans=1, showextrema=1, showmedians=1) @image_comparison(baseline_images=['violinplot_vert_custompoints_10'], extensions=['png']) def test_vert_violinplot_custompoints_10(): ax = plt.axes() # First 9 digits of frac(sqrt(13)) np.random.seed(605551275) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=0, points=10) @image_comparison(baseline_images=['violinplot_vert_custompoints_200'], extensions=['png']) def test_vert_violinplot_custompoints_200(): ax = plt.axes() # First 9 digits of frac(sqrt(17)) np.random.seed(123105625) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=0, points=200) @image_comparison(baseline_images=['violinplot_horiz_baseline'], extensions=['png']) def test_horiz_violinplot_baseline(): ax = plt.axes() # First 9 digits of frac(sqrt(19)) np.random.seed(358898943) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=0) @image_comparison(baseline_images=['violinplot_horiz_showmedians'], extensions=['png']) def test_horiz_violinplot_showmedians(): ax = plt.axes() # First 9 digits of frac(sqrt(23)) np.random.seed(795831523) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=1) @image_comparison(baseline_images=['violinplot_horiz_showmeans'], extensions=['png']) def test_horiz_violinplot_showmeans(): ax = plt.axes() # First 9 digits of frac(sqrt(29)) np.random.seed(385164807) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=1, showextrema=0, showmedians=0) @image_comparison(baseline_images=['violinplot_horiz_showextrema'], extensions=['png']) def test_horiz_violinplot_showextrema(): ax = plt.axes() # First 9 digits of frac(sqrt(31)) np.random.seed(567764362) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=1, showmedians=0) @image_comparison(baseline_images=['violinplot_horiz_showall'], extensions=['png']) def test_horiz_violinplot_showall(): ax = plt.axes() # First 9 digits of frac(sqrt(37)) np.random.seed(82762530) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=1, showextrema=1, showmedians=1) @image_comparison(baseline_images=['violinplot_horiz_custompoints_10'], extensions=['png']) def test_horiz_violinplot_custompoints_10(): ax = plt.axes() # First 9 digits of frac(sqrt(41)) np.random.seed(403124237) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=0, points=10) @image_comparison(baseline_images=['violinplot_horiz_custompoints_200'], extensions=['png']) def test_horiz_violinplot_custompoints_200(): ax = plt.axes() # First 9 digits of frac(sqrt(43)) np.random.seed(557438524) data = [np.random.normal(size=100) for i in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=0, points=200) def test_violinplot_bad_positions(): ax = plt.axes() # First 9 digits of frac(sqrt(47)) np.random.seed(855654600) data = [np.random.normal(size=100) for i in range(4)] with pytest.raises(ValueError): ax.violinplot(data, positions=range(5)) def test_violinplot_bad_widths(): ax = plt.axes() # First 9 digits of frac(sqrt(53)) np.random.seed(280109889) data = [np.random.normal(size=100) for i in range(4)] with pytest.raises(ValueError): ax.violinplot(data, positions=range(4), widths=[1, 2, 3]) def test_manage_xticks(): _, ax = plt.subplots() ax.set_xlim(0, 4) old_xlim = ax.get_xlim() np.random.seed(0) y1 = np.random.normal(10, 3, 20) y2 = np.random.normal(3, 1, 20) ax.boxplot([y1, y2], positions=[1, 2], manage_xticks=False) new_xlim = ax.get_xlim() assert_array_equal(old_xlim, new_xlim) def test_tick_space_size_0(): # allow font size to be zero, which affects ticks when there is # no other text in the figure. plt.plot([0, 1], [0, 1]) matplotlib.rcParams.update({'font.size': 0}) b = io.BytesIO() plt.savefig(b, dpi=80, format='raw') @image_comparison(baseline_images=['errorbar_basic', 'errorbar_mixed', 'errorbar_basic']) def test_errorbar(): x = np.arange(0.1, 4, 0.5) y = np.exp(-x) yerr = 0.1 + 0.2*np.sqrt(x) xerr = 0.1 + yerr # First illustrate basic pyplot interface, using defaults where possible. fig = plt.figure() ax = fig.gca() ax.errorbar(x, y, xerr=0.2, yerr=0.4) ax.set_title("Simplest errorbars, 0.2 in x, 0.4 in y") # Now switch to a more OO interface to exercise more features. fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True) ax = axs[0, 0] # Try a Nx1 shaped error just to check ax.errorbar(x, y, yerr=np.reshape(yerr, (len(y), 1)), fmt='o') ax.set_title('Vert. symmetric') # With 4 subplots, reduce the number of axis ticks to avoid crowding. ax.locator_params(nbins=4) ax = axs[0, 1] ax.errorbar(x, y, xerr=xerr, fmt='o', alpha=0.4) ax.set_title('Hor. symmetric w/ alpha') ax = axs[1, 0] ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o') ax.set_title('H, V asymmetric') ax = axs[1, 1] ax.set_yscale('log') # Here we have to be careful to keep all y values positive: ylower = np.maximum(1e-2, y - yerr) yerr_lower = y - ylower ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr, fmt='o', ecolor='g', capthick=2) ax.set_title('Mixed sym., log y') fig.suptitle('Variable errorbars') # Reuse the first testcase from above for a labeled data test data = {"x": x, "y": y} fig = plt.figure() ax = fig.gca() ax.errorbar("x", "y", xerr=0.2, yerr=0.4, data=data) ax.set_title("Simplest errorbars, 0.2 in x, 0.4 in y") def test_errorbar_colorcycle(): f, ax = plt.subplots() x = np.arange(10) y = 2*x e1, _, _ = ax.errorbar(x, y, c=None) e2, _, _ = ax.errorbar(x, 2*y, c=None) ln1, = ax.plot(x, 4*y) assert mcolors.to_rgba(e1.get_color()) == mcolors.to_rgba('C0') assert mcolors.to_rgba(e2.get_color()) == mcolors.to_rgba('C1') assert mcolors.to_rgba(ln1.get_color()) == mcolors.to_rgba('C2') def test_errorbar_shape(): fig = plt.figure() ax = fig.gca() x = np.arange(0.1, 4, 0.5) y = np.exp(-x) yerr1 = 0.1 + 0.2*np.sqrt(x) yerr = np.vstack((yerr1, 2*yerr1)).T xerr = 0.1 + yerr with pytest.raises(ValueError): ax.errorbar(x, y, yerr=yerr, fmt='o') with pytest.raises(ValueError): ax.errorbar(x, y, xerr=xerr, fmt='o') with pytest.raises(ValueError): ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt='o') @image_comparison(baseline_images=['errorbar_limits']) def test_errorbar_limits(): x = np.arange(0.5, 5.5, 0.5) y = np.exp(-x) xerr = 0.1 yerr = 0.2 ls = 'dotted' fig = plt.figure() ax = fig.add_subplot(1, 1, 1) # standard error bars plt.errorbar(x, y, xerr=xerr, yerr=yerr, ls=ls, color='blue') # including upper limits uplims = np.zeros_like(x) uplims[[1, 5, 9]] = True plt.errorbar(x, y+0.5, xerr=xerr, yerr=yerr, uplims=uplims, ls=ls, color='green') # including lower limits lolims = np.zeros_like(x) lolims[[2, 4, 8]] = True plt.errorbar(x, y+1.0, xerr=xerr, yerr=yerr, lolims=lolims, ls=ls, color='red') # including upper and lower limits plt.errorbar(x, y+1.5, marker='o', ms=8, xerr=xerr, yerr=yerr, lolims=lolims, uplims=uplims, ls=ls, color='magenta') # including xlower and xupper limits xerr = 0.2 yerr = np.zeros_like(x) + 0.2 yerr[[3, 6]] = 0.3 xlolims = lolims xuplims = uplims lolims = np.zeros_like(x) uplims = np.zeros_like(x) lolims[[6]] = True uplims[[3]] = True plt.errorbar(x, y+2.1, marker='o', ms=8, xerr=xerr, yerr=yerr, xlolims=xlolims, xuplims=xuplims, uplims=uplims, lolims=lolims, ls='none', mec='blue', capsize=0, color='cyan') ax.set_xlim((0, 5.5)) ax.set_title('Errorbar upper and lower limits') def test_errobar_nonefmt(): # Check that passing 'none' as a format still plots errorbars x = np.arange(5) y = np.arange(5) plotline, _, barlines = plt.errorbar(x, y, xerr=1, yerr=1, fmt='none') assert plotline is None for errbar in barlines: assert np.all(errbar.get_color() == mcolors.to_rgba('C0')) @image_comparison(baseline_images=['errorbar_with_prop_cycle'], extensions=['png'], style='mpl20', remove_text=True) def test_errorbar_with_prop_cycle(): _cycle = cycler(ls=['--', ':'], marker=['s', 's'], mfc=['k', 'w']) plt.rc("axes", prop_cycle=_cycle) fig, ax = plt.subplots() ax.errorbar(x=[2, 4, 10], y=[3, 2, 4], yerr=0.5) ax.errorbar(x=[2, 4, 10], y=[6, 4, 2], yerr=0.5) @image_comparison(baseline_images=['hist_stacked_stepfilled', 'hist_stacked_stepfilled']) def test_hist_stacked_stepfilled(): # make some data d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) fig = plt.figure() ax = fig.add_subplot(111) ax.hist((d1, d2), histtype="stepfilled", stacked=True) # Reuse testcase from above for a labeled data test data = {"x": (d1, d2)} fig = plt.figure() ax = fig.add_subplot(111) ax.hist("x", histtype="stepfilled", stacked=True, data=data) @image_comparison(baseline_images=['hist_offset']) def test_hist_offset(): # make some data d1 = np.linspace(0, 10, 50) d2 = np.linspace(1, 3, 20) fig = plt.figure() ax = fig.add_subplot(111) ax.hist(d1, bottom=5) ax.hist(d2, bottom=15) @image_comparison(baseline_images=['hist_step'], extensions=['png'], remove_text=True) def test_hist_step(): # make some data d1 = np.linspace(1, 3, 20) fig = plt.figure() ax = fig.add_subplot(111) ax.hist(d1, histtype="step") ax.set_ylim(0, 10) ax.set_xlim(-1, 5) @image_comparison(baseline_images=['hist_step_horiz'], extensions=['png']) def test_hist_step_horiz(): # make some data d1 = np.linspace(0, 10, 50) d2 = np.linspace(1, 3, 20) fig = plt.figure() ax = fig.add_subplot(111) ax.hist((d1, d2), histtype="step", orientation="horizontal") @image_comparison(baseline_images=['hist_stacked_weights']) def test_hist_stacked_weighted(): # make some data d1 = np.linspace(0, 10, 50) d2 = np.linspace(1, 3, 20) w1 = np.linspace(0.01, 3.5, 50) w2 = np.linspace(0.05, 2., 20) fig = plt.figure() ax = fig.add_subplot(111) ax.hist((d1, d2), weights=(w1, w2), histtype="stepfilled", stacked=True) def test_stem_args(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) x = list(xrange(10)) y = list(xrange(10)) # Test the call signatures ax.stem(y) ax.stem(x, y) ax.stem(x, y, 'r--') ax.stem(x, y, 'r--', basefmt='b--') def test_stem_dates(): fig, ax = plt.subplots(1, 1) from dateutil import parser x = parser.parse("2013-9-28 11:00:00") y = 100 x1 = parser.parse("2013-9-28 12:00:00") y1 = 200 ax.stem([x, x1], [y, y1], "*-") @image_comparison(baseline_images=['hist_stacked_stepfilled_alpha']) def test_hist_stacked_stepfilled_alpha(): # make some data d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) fig = plt.figure() ax = fig.add_subplot(111) ax.hist((d1, d2), histtype="stepfilled", stacked=True, alpha=0.5) @image_comparison(baseline_images=['hist_stacked_step']) def test_hist_stacked_step(): # make some data d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) fig = plt.figure() ax = fig.add_subplot(111) ax.hist((d1, d2), histtype="step", stacked=True) @image_comparison(baseline_images=['hist_stacked_normed']) def test_hist_stacked_normed(): # make some data d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) fig, ax = plt.subplots() with pytest.warns(UserWarning): ax.hist((d1, d2), stacked=True, normed=True) @image_comparison(baseline_images=['hist_stacked_normed'], extensions=['png']) def test_hist_stacked_density(): # make some data d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) fig, ax = plt.subplots() ax.hist((d1, d2), stacked=True, density=True) @pytest.mark.parametrize('normed', [False, True]) @pytest.mark.parametrize('density', [False, True]) def test_hist_normed_density(normed, density): # Normed and density should not be used simultaneously d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) fig, ax = plt.subplots() # test that kwargs normed and density cannot be set both. with pytest.raises(Exception): ax.hist((d1, d2), stacked=True, normed=normed, density=density) @image_comparison(baseline_images=['hist_step_bottom'], extensions=['png'], remove_text=True) def test_hist_step_bottom(): # make some data d1 = np.linspace(1, 3, 20) fig = plt.figure() ax = fig.add_subplot(111) ax.hist(d1, bottom=np.arange(10), histtype="stepfilled") @image_comparison(baseline_images=['hist_stacked_bar']) def test_hist_stacked_bar(): # make some data d = [[100, 100, 100, 100, 200, 320, 450, 80, 20, 600, 310, 800], [20, 23, 50, 11, 100, 420], [120, 120, 120, 140, 140, 150, 180], [60, 60, 60, 60, 300, 300, 5, 5, 5, 5, 10, 300], [555, 555, 555, 30, 30, 30, 30, 30, 100, 100, 100, 100, 30, 30], [30, 30, 30, 30, 400, 400, 400, 400, 400, 400, 400, 400]] colors = [(0.5759849696758961, 1.0, 0.0), (0.0, 1.0, 0.350624650815206), (0.0, 1.0, 0.6549834156005998), (0.0, 0.6569064625276622, 1.0), (0.28302699607823545, 0.0, 1.0), (0.6849123462299822, 0.0, 1.0)] labels = ['green', 'orange', ' yellow', 'magenta', 'black'] fig = plt.figure() ax = fig.add_subplot(111) ax.hist(d, bins=10, histtype='barstacked', align='mid', color=colors, label=labels) ax.legend(loc='upper right', bbox_to_anchor=(1.0, 1.0), ncol=1) def test_hist_emptydata(): fig = plt.figure() ax = fig.add_subplot(111) ax.hist([[], range(10), range(10)], histtype="step") @image_comparison(baseline_images=['transparent_markers'], remove_text=True) def test_transparent_markers(): np.random.seed(0) data = np.random.random(50) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(data, 'D', mfc='none', markersize=100) @image_comparison(baseline_images=['rgba_markers'], remove_text=True) def test_rgba_markers(): fig, axs = plt.subplots(ncols=2) rcolors = [(1, 0, 0, 1), (1, 0, 0, 0.5)] bcolors = [(0, 0, 1, 1), (0, 0, 1, 0.5)] alphas = [None, 0.2] kw = dict(ms=100, mew=20) for i, alpha in enumerate(alphas): for j, rcolor in enumerate(rcolors): for k, bcolor in enumerate(bcolors): axs[i].plot(j+1, k+1, 'o', mfc=bcolor, mec=rcolor, alpha=alpha, **kw) axs[i].plot(j+1, k+3, 'x', mec=rcolor, alpha=alpha, **kw) for ax in axs: ax.axis([-1, 4, 0, 5]) @image_comparison(baseline_images=['mollweide_grid'], remove_text=True) def test_mollweide_grid(): # test that both horizontal and vertical gridlines appear on the Mollweide # projection fig = plt.figure() ax = fig.add_subplot(111, projection='mollweide') ax.grid() def test_mollweide_forward_inverse_closure(): # test that the round-trip Mollweide forward->inverse transformation is an # approximate identity fig = plt.figure() ax = fig.add_subplot(111, projection='mollweide') # set up 1-degree grid in longitude, latitude lon = np.linspace(-np.pi, np.pi, 360) lat = np.linspace(-np.pi / 2.0, np.pi / 2.0, 180) lon, lat = np.meshgrid(lon, lat) ll = np.vstack((lon.flatten(), lat.flatten())).T # perform forward transform xy = ax.transProjection.transform(ll) # perform inverse transform ll2 = ax.transProjection.inverted().transform(xy) # compare np.testing.assert_array_almost_equal(ll, ll2, 3) def test_mollweide_inverse_forward_closure(): # test that the round-trip Mollweide inverse->forward transformation is an # approximate identity fig = plt.figure() ax = fig.add_subplot(111, projection='mollweide') # set up grid in x, y x = np.linspace(0, 1, 500) x, y = np.meshgrid(x, x) xy = np.vstack((x.flatten(), y.flatten())).T # perform inverse transform ll = ax.transProjection.inverted().transform(xy) # perform forward transform xy2 = ax.transProjection.transform(ll) # compare np.testing.assert_array_almost_equal(xy, xy2, 3) @image_comparison(baseline_images=['test_alpha'], remove_text=True) def test_alpha(): np.random.seed(0) data = np.random.random(50) fig = plt.figure() ax = fig.add_subplot(111) # alpha=.5 markers, solid line ax.plot(data, '-D', color=[1, 0, 0], mfc=[1, 0, 0, .5], markersize=20, lw=10) # everything solid by kwarg ax.plot(data + 2, '-D', color=[1, 0, 0, .5], mfc=[1, 0, 0, .5], markersize=20, lw=10, alpha=1) # everything alpha=.5 by kwarg ax.plot(data + 4, '-D', color=[1, 0, 0], mfc=[1, 0, 0], markersize=20, lw=10, alpha=.5) # everything alpha=.5 by colors ax.plot(data + 6, '-D', color=[1, 0, 0, .5], mfc=[1, 0, 0, .5], markersize=20, lw=10) # alpha=.5 line, solid markers ax.plot(data + 8, '-D', color=[1, 0, 0, .5], mfc=[1, 0, 0], markersize=20, lw=10) @image_comparison(baseline_images=['eventplot', 'eventplot'], remove_text=True) def test_eventplot(): ''' test that eventplot produces the correct output ''' np.random.seed(0) data1 = np.random.random([32, 20]).tolist() data2 = np.random.random([6, 20]).tolist() data = data1 + data2 num_datasets = len(data) colors1 = [[0, 1, .7]] * len(data1) colors2 = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, .75, 0], [1, 0, 1], [0, 1, 1]] colors = colors1 + colors2 lineoffsets1 = 12 + np.arange(0, len(data1)) * .33 lineoffsets2 = [-15, -3, 1, 1.5, 6, 10] lineoffsets = lineoffsets1.tolist() + lineoffsets2 linelengths1 = [.33] * len(data1) linelengths2 = [5, 2, 1, 1, 3, 1.5] linelengths = linelengths1 + linelengths2 fig = plt.figure() axobj = fig.add_subplot(111) colls = axobj.eventplot(data, colors=colors, lineoffsets=lineoffsets, linelengths=linelengths) num_collections = len(colls) assert num_collections == num_datasets # Reuse testcase from above for a labeled data test data = {"pos": data, "c": colors, "lo": lineoffsets, "ll": linelengths} fig = plt.figure() axobj = fig.add_subplot(111) colls = axobj.eventplot("pos", colors="c", lineoffsets="lo", linelengths="ll", data=data) num_collections = len(colls) assert num_collections == num_datasets @image_comparison(baseline_images=['test_eventplot_defaults'], extensions=['png'], remove_text=True) def test_eventplot_defaults(): ''' test that eventplot produces the correct output given the default params (see bug #3728) ''' np.random.seed(0) data1 = np.random.random([32, 20]).tolist() data2 = np.random.random([6, 20]).tolist() data = data1 + data2 fig = plt.figure() axobj = fig.add_subplot(111) colls = axobj.eventplot(data) @pytest.mark.parametrize(('colors'), [ ('0.5',), # string color with multiple characters: not OK before #8193 fix ('tab:orange', 'tab:pink', 'tab:cyan', 'bLacK'), # case-insensitive ('red', (0, 1, 0), None, (1, 0, 1, 0.5)), # a tricky case mixing types ('rgbk',) # len('rgbk') == len(data) and each character is a valid color ]) def test_eventplot_colors(colors): '''Test the *colors* parameter of eventplot. Inspired by the issue #8193. ''' data = [[i] for i in range(4)] # 4 successive events of different nature # Build the list of the expected colors expected = [c if c is not None else 'C0' for c in colors] # Convert the list into an array of RGBA values # NB: ['rgbk'] is not a valid argument for to_rgba_array, while 'rgbk' is. if len(expected) == 1: expected = expected[0] expected = broadcast_to(mcolors.to_rgba_array(expected), (len(data), 4)) fig, ax = plt.subplots() if len(colors) == 1: # tuple with a single string (like '0.5' or 'rgbk') colors = colors[0] collections = ax.eventplot(data, colors=colors) for coll, color in zip(collections, expected): assert_allclose(coll.get_color(), color) @image_comparison(baseline_images=['test_eventplot_problem_kwargs'], extensions=['png'], remove_text=True) def test_eventplot_problem_kwargs(): ''' test that 'singular' versions of LineCollection props raise an IgnoredKeywordWarning rather than overriding the 'plural' versions (e.g. to prevent 'color' from overriding 'colors', see issue #4297) ''' np.random.seed(0) data1 = np.random.random([20]).tolist() data2 = np.random.random([10]).tolist() data = [data1, data2] fig = plt.figure() axobj = fig.add_subplot(111) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") colls = axobj.eventplot(data, colors=['r', 'b'], color=['c', 'm'], linewidths=[2, 1], linewidth=[1, 2], linestyles=['solid', 'dashed'], linestyle=['dashdot', 'dotted']) # check that three IgnoredKeywordWarnings were raised assert len(w) == 3 assert all(issubclass(wi.category, IgnoredKeywordWarning) for wi in w) def test_empty_eventplot(): fig, ax = plt.subplots(1, 1) ax.eventplot([[]], colors=[(0.0, 0.0, 0.0, 0.0)]) plt.draw() @pytest.mark.parametrize('data, orientation', product( ([[]], [[], [0, 1]], [[0, 1], []]), ('_empty', 'vertical', 'horizontal', None, 'none'))) def test_eventplot_orientation(data, orientation): """Introduced when fixing issue #6412. """ opts = {} if orientation == "_empty" else {'orientation': orientation} fig, ax = plt.subplots(1, 1) ax.eventplot(data, **opts) plt.draw() @image_comparison(baseline_images=['marker_styles'], extensions=['png'], remove_text=True) def test_marker_styles(): fig = plt.figure() ax = fig.add_subplot(111) for y, marker in enumerate(sorted(matplotlib.markers.MarkerStyle.markers, key=lambda x: str(type(x))+str(x))): ax.plot((y % 2)*5 + np.arange(10)*10, np.ones(10)*10*y, linestyle='', marker=marker, markersize=10+y/5, label=marker) @image_comparison(baseline_images=['rc_markerfill'], extensions=['png']) def test_markers_fillstyle_rcparams(): fig, ax = plt.subplots() x = np.arange(7) for idx, (style, marker) in enumerate( [('top', 's'), ('bottom', 'o'), ('none', '^')]): matplotlib.rcParams['markers.fillstyle'] = style ax.plot(x+idx, marker=marker) @image_comparison(baseline_images=['vertex_markers'], extensions=['png'], remove_text=True) def test_vertex_markers(): data = list(xrange(10)) marker_as_tuple = ((-1, -1), (1, -1), (1, 1), (-1, 1)) marker_as_list = [(-1, -1), (1, -1), (1, 1), (-1, 1)] fig = plt.figure() ax = fig.add_subplot(111) ax.plot(data, linestyle='', marker=marker_as_tuple, mfc='k') ax.plot(data[::-1], linestyle='', marker=marker_as_list, mfc='b') ax.set_xlim([-1, 10]) ax.set_ylim([-1, 10]) @image_comparison(baseline_images=['vline_hline_zorder', 'errorbar_zorder']) def test_eb_line_zorder(): x = list(xrange(10)) # First illustrate basic pyplot interface, using defaults where possible. fig = plt.figure() ax = fig.gca() ax.plot(x, lw=10, zorder=5) ax.axhline(1, color='red', lw=10, zorder=1) ax.axhline(5, color='green', lw=10, zorder=10) ax.axvline(7, color='m', lw=10, zorder=7) ax.axvline(2, color='k', lw=10, zorder=3) ax.set_title("axvline and axhline zorder test") # Now switch to a more OO interface to exercise more features. fig = plt.figure() ax = fig.gca() x = list(xrange(10)) y = np.zeros(10) yerr = list(xrange(10)) ax.errorbar(x, y, yerr=yerr, zorder=5, lw=5, color='r') for j in range(10): ax.axhline(j, lw=5, color='k', zorder=j) ax.axhline(-j, lw=5, color='k', zorder=j) ax.set_title("errorbar zorder test") @image_comparison( baseline_images=['vlines_basic', 'vlines_with_nan', 'vlines_masked'], extensions=['png'] ) def test_vlines(): # normal x1 = [2, 3, 4, 5, 7] y1 = [2, -6, 3, 8, 2] fig1, ax1 = plt.subplots() ax1.vlines(x1, 0, y1, colors='g', linewidth=5) # GH #7406 x2 = [2, 3, 4, 5, 6, 7] y2 = [2, -6, 3, 8, np.nan, 2] fig2, (ax2, ax3, ax4) = plt.subplots(nrows=3, figsize=(4, 8)) ax2.vlines(x2, 0, y2, colors='g', linewidth=5) x3 = [2, 3, 4, 5, 6, 7] y3 = [np.nan, 2, -6, 3, 8, 2] ax3.vlines(x3, 0, y3, colors='r', linewidth=3, linestyle='--') x4 = [2, 3, 4, 5, 6, 7] y4 = [np.nan, 2, -6, 3, 8, np.nan] ax4.vlines(x4, 0, y4, colors='k', linewidth=2) # tweak the x-axis so we can see the lines better for ax in [ax1, ax2, ax3, ax4]: ax.set_xlim(0, 10) # check that the y-lims are all automatically the same assert ax1.get_ylim() == ax2.get_ylim() assert ax1.get_ylim() == ax3.get_ylim() assert ax1.get_ylim() == ax4.get_ylim() fig3, ax5 = plt.subplots() x5 = np.ma.masked_equal([2, 4, 6, 8, 10, 12], 8) ymin5 = np.ma.masked_equal([0, 1, -1, 0, 2, 1], 2) ymax5 = np.ma.masked_equal([13, 14, 15, 16, 17, 18], 18) ax5.vlines(x5, ymin5, ymax5, colors='k', linewidth=2) ax5.set_xlim(0, 15) @image_comparison( baseline_images=['hlines_basic', 'hlines_with_nan', 'hlines_masked'], extensions=['png'] ) def test_hlines(): # normal y1 = [2, 3, 4, 5, 7] x1 = [2, -6, 3, 8, 2] fig1, ax1 = plt.subplots() ax1.hlines(y1, 0, x1, colors='g', linewidth=5) # GH #7406 y2 = [2, 3, 4, 5, 6, 7] x2 = [2, -6, 3, 8, np.nan, 2] fig2, (ax2, ax3, ax4) = plt.subplots(nrows=3, figsize=(4, 8)) ax2.hlines(y2, 0, x2, colors='g', linewidth=5) y3 = [2, 3, 4, 5, 6, 7] x3 = [np.nan, 2, -6, 3, 8, 2] ax3.hlines(y3, 0, x3, colors='r', linewidth=3, linestyle='--') y4 = [2, 3, 4, 5, 6, 7] x4 = [np.nan, 2, -6, 3, 8, np.nan] ax4.hlines(y4, 0, x4, colors='k', linewidth=2) # tweak the y-axis so we can see the lines better for ax in [ax1, ax2, ax3, ax4]: ax.set_ylim(0, 10) # check that the x-lims are all automatically the same assert ax1.get_xlim() == ax2.get_xlim() assert ax1.get_xlim() == ax3.get_xlim() assert ax1.get_xlim() == ax4.get_xlim() fig3, ax5 = plt.subplots() y5 = np.ma.masked_equal([2, 4, 6, 8, 10, 12], 8) xmin5 = np.ma.masked_equal([0, 1, -1, 0, 2, 1], 2) xmax5 = np.ma.masked_equal([13, 14, 15, 16, 17, 18], 18) ax5.hlines(y5, xmin5, xmax5, colors='k', linewidth=2) ax5.set_ylim(0, 15) @image_comparison(baseline_images=['step_linestyle', 'step_linestyle'], remove_text=True) def test_step_linestyle(): x = y = np.arange(10) # First illustrate basic pyplot interface, using defaults where possible. fig, ax_lst = plt.subplots(2, 2) ax_lst = ax_lst.flatten() ln_styles = ['-', '--', '-.', ':'] for ax, ls in zip(ax_lst, ln_styles): ax.step(x, y, lw=5, linestyle=ls, where='pre') ax.step(x, y + 1, lw=5, linestyle=ls, where='mid') ax.step(x, y + 2, lw=5, linestyle=ls, where='post') ax.set_xlim([-1, 5]) ax.set_ylim([-1, 7]) # Reuse testcase from above for a labeled data test data = {"x": x, "y": y, "y1": y+1, "y2": y+2} fig, ax_lst = plt.subplots(2, 2) ax_lst = ax_lst.flatten() ln_styles = ['-', '--', '-.', ':'] for ax, ls in zip(ax_lst, ln_styles): ax.step("x", "y", lw=5, linestyle=ls, where='pre', data=data) ax.step("x", "y1", lw=5, linestyle=ls, where='mid', data=data) ax.step("x", "y2", lw=5, linestyle=ls, where='post', data=data) ax.set_xlim([-1, 5]) ax.set_ylim([-1, 7]) @image_comparison(baseline_images=['mixed_collection'], remove_text=True) def test_mixed_collection(): from matplotlib import patches from matplotlib import collections x = list(xrange(10)) # First illustrate basic pyplot interface, using defaults where possible. fig = plt.figure() ax = fig.add_subplot(1, 1, 1) c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green') # PDF can optimize this one p1 = collections.PatchCollection([c], match_original=True) p1.set_offsets([[0, 0], [24, 24]]) p1.set_linewidths([1, 5]) # PDF can't optimize this one, because the alpha of the edge changes p2 = collections.PatchCollection([c], match_original=True) p2.set_offsets([[48, 0], [-32, -16]]) p2.set_linewidths([1, 5]) p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]]) ax.patch.set_color('0.5') ax.add_collection(p1) ax.add_collection(p2) ax.set_xlim(0, 16) ax.set_ylim(0, 16) def test_subplot_key_hash(): ax = plt.subplot(np.float64(5.5), np.int64(1), np.float64(1.2)) ax.twinx() assert ax.get_subplotspec().get_geometry() == (5, 1, 0, 0) @image_comparison(baseline_images=['specgram_freqs', 'specgram_freqs_linear'], remove_text=True, extensions=['png'], tol=0.07, style='default') def test_specgram_freqs(): '''test axes.specgram in default (psd) mode with sinusoidal stimuli''' n = 1000 Fs = 10. fstims1 = [Fs/4, Fs/5, Fs/11] fstims2 = [Fs/4.7, Fs/5.6, Fs/11.9] NFFT = int(10 * Fs / min(fstims1 + fstims2)) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y1 = np.zeros(x.size) y2 = np.zeros(x.size) for fstim1, fstim2 in zip(fstims1, fstims2): y1 += np.sin(fstim1 * x * np.pi * 2) y2 += np.sin(fstim2 * x * np.pi * 2) y = np.hstack([y1, y2]) fig1 = plt.figure() fig2 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) ax21 = fig2.add_subplot(3, 1, 1) ax22 = fig2.add_subplot(3, 1, 2) ax23 = fig2.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default') spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided') spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided') spec21 = ax21.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', scale='linear', norm=matplotlib.colors.LogNorm()) spec22 = ax22.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', scale='linear', norm=matplotlib.colors.LogNorm()) spec23 = ax23.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', scale='linear', norm=matplotlib.colors.LogNorm()) @image_comparison(baseline_images=['specgram_noise', 'specgram_noise_linear'], remove_text=True, extensions=['png'], tol=0.01, style='default') def test_specgram_noise(): '''test axes.specgram in default (psd) mode with noise stimuli''' np.random.seed(0) n = 1000 Fs = 10. NFFT = int(10 * Fs / 11) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) fig1 = plt.figure() fig2 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) ax21 = fig2.add_subplot(3, 1, 1) ax22 = fig2.add_subplot(3, 1, 2) ax23 = fig2.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default') spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided') spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided') spec21 = ax21.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', scale='linear', norm=matplotlib.colors.LogNorm()) spec22 = ax22.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', scale='linear', norm=matplotlib.colors.LogNorm()) spec23 = ax23.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', scale='linear', norm=matplotlib.colors.LogNorm()) @image_comparison(baseline_images=['specgram_magnitude_freqs', 'specgram_magnitude_freqs_linear'], remove_text=True, extensions=['png'], tol=0.07, style='default') def test_specgram_magnitude_freqs(): '''test axes.specgram in magnitude mode with sinusoidal stimuli''' n = 1000 Fs = 10. fstims1 = [Fs/4, Fs/5, Fs/11] fstims2 = [Fs/4.7, Fs/5.6, Fs/11.9] NFFT = int(100 * Fs / min(fstims1 + fstims2)) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y1 = np.zeros(x.size) y2 = np.zeros(x.size) for i, (fstim1, fstim2) in enumerate(zip(fstims1, fstims2)): y1 += np.sin(fstim1 * x * np.pi * 2) y2 += np.sin(fstim2 * x * np.pi * 2) y1[-1] = y1[-1]/y1[-1] y2[-1] = y2[-1]/y2[-1] y = np.hstack([y1, y2]) fig1 = plt.figure() fig2 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) ax21 = fig2.add_subplot(3, 1, 1) ax22 = fig2.add_subplot(3, 1, 2) ax23 = fig2.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='magnitude') spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='magnitude') spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='magnitude') spec21 = ax21.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='magnitude', scale='linear', norm=matplotlib.colors.LogNorm()) spec22 = ax22.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='magnitude', scale='linear', norm=matplotlib.colors.LogNorm()) spec23 = ax23.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='magnitude', scale='linear', norm=matplotlib.colors.LogNorm()) @image_comparison(baseline_images=['specgram_magnitude_noise', 'specgram_magnitude_noise_linear'], remove_text=True, extensions=['png'], style='default') def test_specgram_magnitude_noise(): '''test axes.specgram in magnitude mode with noise stimuli''' np.random.seed(0) n = 1000 Fs = 10. NFFT = int(10 * Fs / 11) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) fig1 = plt.figure() fig2 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) ax21 = fig2.add_subplot(3, 1, 1) ax22 = fig2.add_subplot(3, 1, 2) ax23 = fig2.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='magnitude') spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='magnitude') spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='magnitude') spec21 = ax21.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='magnitude', scale='linear', norm=matplotlib.colors.LogNorm()) spec22 = ax22.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='magnitude', scale='linear', norm=matplotlib.colors.LogNorm()) spec23 = ax23.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='magnitude', scale='linear', norm=matplotlib.colors.LogNorm()) @image_comparison(baseline_images=['specgram_angle_freqs'], remove_text=True, extensions=['png'], tol=0.007, style='default') def test_specgram_angle_freqs(): '''test axes.specgram in angle mode with sinusoidal stimuli''' n = 1000 Fs = 10. fstims1 = [Fs/4, Fs/5, Fs/11] fstims2 = [Fs/4.7, Fs/5.6, Fs/11.9] NFFT = int(10 * Fs / min(fstims1 + fstims2)) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y1 = np.zeros(x.size) y2 = np.zeros(x.size) for i, (fstim1, fstim2) in enumerate(zip(fstims1, fstims2)): y1 += np.sin(fstim1 * x * np.pi * 2) y2 += np.sin(fstim2 * x * np.pi * 2) y1[-1] = y1[-1]/y1[-1] y2[-1] = y2[-1]/y2[-1] y = np.hstack([y1, y2]) fig1 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='angle') spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='angle') spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') with pytest.raises(ValueError): ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') with pytest.raises(ValueError): ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') with pytest.raises(ValueError): ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_angle_noise'], remove_text=True, extensions=['png'], style='default') def test_specgram_noise_angle(): '''test axes.specgram in angle mode with noise stimuli''' np.random.seed(0) n = 1000 Fs = 10. NFFT = int(10 * Fs / 11) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) fig1 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='angle') spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='angle') spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') with pytest.raises(ValueError): ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') with pytest.raises(ValueError): ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') with pytest.raises(ValueError): ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_phase_freqs'], remove_text=True, extensions=['png'], style='default') def test_specgram_freqs_phase(): '''test axes.specgram in phase mode with sinusoidal stimuli''' n = 1000 Fs = 10. fstims1 = [Fs/4, Fs/5, Fs/11] fstims2 = [Fs/4.7, Fs/5.6, Fs/11.9] NFFT = int(10 * Fs / min(fstims1 + fstims2)) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y1 = np.zeros(x.size) y2 = np.zeros(x.size) for i, (fstim1, fstim2) in enumerate(zip(fstims1, fstims2)): y1 += np.sin(fstim1 * x * np.pi * 2) y2 += np.sin(fstim2 * x * np.pi * 2) y1[-1] = y1[-1]/y1[-1] y2[-1] = y2[-1]/y2[-1] y = np.hstack([y1, y2]) fig1 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase') spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase') spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase') with pytest.raises(ValueError): ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') with pytest.raises(ValueError): ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') with pytest.raises(ValueError): ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_phase_noise'], remove_text=True, extensions=['png'], style='default') def test_specgram_noise_phase(): '''test axes.specgram in phase mode with noise stimuli''' np.random.seed(0) n = 1000 Fs = 10. NFFT = int(10 * Fs / 11) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) fig1 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) spec11 = ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', ) spec12 = ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', ) spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', ) with pytest.raises(ValueError): ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') with pytest.raises(ValueError): ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') with pytest.raises(ValueError): ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @image_comparison(baseline_images=['psd_freqs'], remove_text=True, extensions=['png']) def test_psd_freqs(): '''test axes.psd with sinusoidal stimuli''' n = 10000 Fs = 100. fstims1 = [Fs/4, Fs/5, Fs/11] fstims2 = [Fs/4.7, Fs/5.6, Fs/11.9] NFFT = int(1000 * Fs / min(fstims1 + fstims2)) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y1 = np.zeros(x.size) y2 = np.zeros(x.size) for fstim1, fstim2 in zip(fstims1, fstims2): y1 += np.sin(fstim1 * x * np.pi * 2) y2 += np.sin(fstim2 * x * np.pi * 2) y = np.hstack([y1, y2]) fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) psd1, freqs1 = ax1.psd(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default') psd2, freqs2 = ax2.psd(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', return_line=False) psd3, freqs3, line3 = ax3.psd(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', return_line=True) ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['psd_noise'], remove_text=True, extensions=['png']) def test_psd_noise(): '''test axes.psd with noise stimuli''' np.random.seed(0) n = 10000 Fs = 100. NFFT = int(1000 * Fs / 11) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) psd1, freqs1 = ax1.psd(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default') psd2, freqs2 = ax2.psd(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', return_line=False) psd3, freqs3, line3 = ax3.psd(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', return_line=True) ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['csd_freqs'], remove_text=True, extensions=['png']) def test_csd_freqs(): '''test axes.csd with sinusoidal stimuli''' n = 10000 Fs = 100. fstims1 = [Fs/4, Fs/5, Fs/11] fstims2 = [Fs/4.7, Fs/5.6, Fs/11.9] NFFT = int(1000 * Fs / min(fstims1 + fstims2)) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y1 = np.zeros(x.size) y2 = np.zeros(x.size) for fstim1, fstim2 in zip(fstims1, fstims2): y1 += np.sin(fstim1 * x * np.pi * 2) y2 += np.sin(fstim2 * x * np.pi * 2) fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) csd1, freqs1 = ax1.csd(y1, y2, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default') csd2, freqs2 = ax2.csd(y1, y2, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', return_line=False) csd3, freqs3, line3 = ax3.csd(y1, y2, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', return_line=True) ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['csd_noise'], remove_text=True, extensions=['png']) def test_csd_noise(): '''test axes.csd with noise stimuli''' np.random.seed(0) n = 10000 Fs = 100. NFFT = int(1000 * Fs / 11) noverlap = int(NFFT / 2) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) csd1, freqs1 = ax1.csd(y1, y2, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default') csd2, freqs2 = ax2.csd(y1, y2, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', return_line=False) csd3, freqs3, line3 = ax3.csd(y1, y2, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', return_line=True) ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['magnitude_spectrum_freqs_linear', 'magnitude_spectrum_freqs_dB'], remove_text=True, extensions=['png']) def test_magnitude_spectrum_freqs(): '''test axes.magnitude_spectrum with sinusoidal stimuli''' n = 10000 Fs = 100. fstims1 = [Fs/4, Fs/5, Fs/11] NFFT = int(1000 * Fs / min(fstims1)) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y = np.zeros(x.size) for i, fstim1 in enumerate(fstims1): y += np.sin(fstim1 * x * np.pi * 2) * 10**i y = y fig1 = plt.figure() fig2 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) ax21 = fig2.add_subplot(3, 1, 1) ax22 = fig2.add_subplot(3, 1, 2) ax23 = fig2.add_subplot(3, 1, 3) spec11, freqs11, line11 = ax11.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default') spec12, freqs12, line12 = ax12.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided') spec13, freqs13, line13 = ax13.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided') spec21, freqs21, line21 = ax21.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default', scale='dB') spec22, freqs22, line22 = ax22.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided', scale='dB') spec23, freqs23, line23 = ax23.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided', scale='dB') ax11.set_xlabel('') ax12.set_xlabel('') ax13.set_xlabel('') ax11.set_ylabel('') ax12.set_ylabel('') ax13.set_ylabel('') ax21.set_xlabel('') ax22.set_xlabel('') ax23.set_xlabel('') ax21.set_ylabel('') ax22.set_ylabel('') ax23.set_ylabel('') @image_comparison(baseline_images=['magnitude_spectrum_noise_linear', 'magnitude_spectrum_noise_dB'], remove_text=True, extensions=['png']) def test_magnitude_spectrum_noise(): '''test axes.magnitude_spectrum with noise stimuli''' np.random.seed(0) n = 10000 Fs = 100. NFFT = int(1000 * Fs / 11) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) - .5 fig1 = plt.figure() fig2 = plt.figure() ax11 = fig1.add_subplot(3, 1, 1) ax12 = fig1.add_subplot(3, 1, 2) ax13 = fig1.add_subplot(3, 1, 3) ax21 = fig2.add_subplot(3, 1, 1) ax22 = fig2.add_subplot(3, 1, 2) ax23 = fig2.add_subplot(3, 1, 3) spec11, freqs11, line11 = ax11.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default') spec12, freqs12, line12 = ax12.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided') spec13, freqs13, line13 = ax13.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided') spec21, freqs21, line21 = ax21.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default', scale='dB') spec22, freqs22, line22 = ax22.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided', scale='dB') spec23, freqs23, line23 = ax23.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided', scale='dB') ax11.set_xlabel('') ax12.set_xlabel('') ax13.set_xlabel('') ax11.set_ylabel('') ax12.set_ylabel('') ax13.set_ylabel('') ax21.set_xlabel('') ax22.set_xlabel('') ax23.set_xlabel('') ax21.set_ylabel('') ax22.set_ylabel('') ax23.set_ylabel('') @image_comparison(baseline_images=['angle_spectrum_freqs'], remove_text=True, extensions=['png']) def test_angle_spectrum_freqs(): '''test axes.angle_spectrum with sinusoidal stimuli''' n = 10000 Fs = 100. fstims1 = [Fs/4, Fs/5, Fs/11] NFFT = int(1000 * Fs / min(fstims1)) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y = np.zeros(x.size) for i, fstim1 in enumerate(fstims1): y += np.sin(fstim1 * x * np.pi * 2) * 10**i y = y fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) spec1, freqs1, line1 = ax1.angle_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default') spec2, freqs2, line2 = ax2.angle_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided') spec3, freqs3, line3 = ax3.angle_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided') ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['angle_spectrum_noise'], remove_text=True, extensions=['png']) def test_angle_spectrum_noise(): '''test axes.angle_spectrum with noise stimuli''' np.random.seed(0) n = 10000 Fs = 100. NFFT = int(1000 * Fs / 11) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) - .5 fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) spec1, freqs1, line1 = ax1.angle_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default') spec2, freqs2, line2 = ax2.angle_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided') spec3, freqs3, line3 = ax3.angle_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided') ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['phase_spectrum_freqs'], remove_text=True, extensions=['png']) def test_phase_spectrum_freqs(): '''test axes.phase_spectrum with sinusoidal stimuli''' n = 10000 Fs = 100. fstims1 = [Fs/4, Fs/5, Fs/11] NFFT = int(1000 * Fs / min(fstims1)) pad_to = int(2 ** np.ceil(np.log2(NFFT))) x = np.arange(0, n, 1/Fs) y = np.zeros(x.size) for i, fstim1 in enumerate(fstims1): y += np.sin(fstim1 * x * np.pi * 2) * 10**i y = y fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) spec1, freqs1, line1 = ax1.phase_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default') spec2, freqs2, line2 = ax2.phase_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided') spec3, freqs3, line3 = ax3.phase_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided') ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['phase_spectrum_noise'], remove_text=True, extensions=['png']) def test_phase_spectrum_noise(): '''test axes.phase_spectrum with noise stimuli''' np.random.seed(0) n = 10000 Fs = 100. NFFT = int(1000 * Fs / 11) pad_to = int(2 ** np.ceil(np.log2(NFFT))) y1 = np.random.standard_normal(n) y2 = np.random.rand(n) y = np.hstack([y1, y2]) - .5 fig = plt.figure() ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) spec1, freqs1, line1 = ax1.phase_spectrum(y, Fs=Fs, pad_to=pad_to, sides='default') spec2, freqs2, line2 = ax2.phase_spectrum(y, Fs=Fs, pad_to=pad_to, sides='onesided') spec3, freqs3, line3 = ax3.phase_spectrum(y, Fs=Fs, pad_to=pad_to, sides='twosided') ax1.set_xlabel('') ax2.set_xlabel('') ax3.set_xlabel('') ax1.set_ylabel('') ax2.set_ylabel('') ax3.set_ylabel('') @image_comparison(baseline_images=['twin_spines'], remove_text=True, extensions=['png']) def test_twin_spines(): def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in six.itervalues(ax.spines): sp.set_visible(False) fig = plt.figure(figsize=(4, 3)) fig.subplots_adjust(right=0.75) host = fig.add_subplot(111) par1 = host.twinx() par2 = host.twinx() # Offset the right spine of par2. The ticks and label have already been # placed on the right by twinx above. par2.spines["right"].set_position(("axes", 1.2)) # Having been created by twinx, par2 has its frame off, so the line of # its detached spine is invisible. First, activate the frame but make # the patch and spines invisible. make_patch_spines_invisible(par2) # Second, show the right spine. par2.spines["right"].set_visible(True) p1, = host.plot([0, 1, 2], [0, 1, 2], "b-") p2, = par1.plot([0, 1, 2], [0, 3, 2], "r-") p3, = par2.plot([0, 1, 2], [50, 30, 15], "g-") host.set_xlim(0, 2) host.set_ylim(0, 2) par1.set_ylim(0, 4) par2.set_ylim(1, 65) host.yaxis.label.set_color(p1.get_color()) par1.yaxis.label.set_color(p2.get_color()) par2.yaxis.label.set_color(p3.get_color()) tkw = dict(size=4, width=1.5) host.tick_params(axis='y', colors=p1.get_color(), **tkw) par1.tick_params(axis='y', colors=p2.get_color(), **tkw) par2.tick_params(axis='y', colors=p3.get_color(), **tkw) host.tick_params(axis='x', **tkw) @image_comparison(baseline_images=['twin_spines_on_top', 'twin_spines_on_top'], extensions=['png'], remove_text=True) def test_twin_spines_on_top(): matplotlib.rcParams['axes.linewidth'] = 48.0 matplotlib.rcParams['lines.linewidth'] = 48.0 fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) data = np.array([[1000, 1100, 1200, 1250], [310, 301, 360, 400]]) ax2 = ax1.twinx() ax1.plot(data[0], data[1]/1E3, color='#BEAED4') ax1.fill_between(data[0], data[1]/1E3, color='#BEAED4', alpha=.8) ax2.plot(data[0], data[1]/1E3, color='#7FC97F') ax2.fill_between(data[0], data[1]/1E3, color='#7FC97F', alpha=.5) # Reuse testcase from above for a labeled data test data = {"i": data[0], "j": data[1]/1E3} fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) ax2 = ax1.twinx() ax1.plot("i", "j", color='#BEAED4', data=data) ax1.fill_between("i", "j", color='#BEAED4', alpha=.8, data=data) ax2.plot("i", "j", color='#7FC97F', data=data) ax2.fill_between("i", "j", color='#7FC97F', alpha=.5, data=data) def test_rcparam_grid_minor(): orig_grid = matplotlib.rcParams['axes.grid'] orig_locator = matplotlib.rcParams['axes.grid.which'] matplotlib.rcParams['axes.grid'] = True values = ( (('both'), (True, True)), (('major'), (True, False)), (('minor'), (False, True)) ) for locator, result in values: matplotlib.rcParams['axes.grid.which'] = locator fig = plt.figure() ax = fig.add_subplot(1, 1, 1) assert (ax.xaxis._gridOnMajor, ax.xaxis._gridOnMinor) == result matplotlib.rcParams['axes.grid'] = orig_grid matplotlib.rcParams['axes.grid.which'] = orig_locator def test_vline_limit(): fig = plt.figure() ax = fig.gca() ax.axvline(0.5) ax.plot([-0.1, 0, 0.2, 0.1]) (ymin, ymax) = ax.get_ylim() assert_allclose(ax.get_ylim(), (-.1, .2)) def test_empty_shared_subplots(): # empty plots with shared axes inherit limits from populated plots fig, axes = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True) axes[0].plot([1, 2, 3], [2, 4, 6]) x0, x1 = axes[1].get_xlim() y0, y1 = axes[1].get_ylim() assert x0 <= 1 assert x1 >= 3 assert y0 <= 2 assert y1 >= 6 def test_shared_with_aspect_1(): # allow sharing one axis for adjustable in ['box', 'datalim']: fig, axes = plt.subplots(nrows=2, sharex=True) axes[0].set_aspect(2, adjustable=adjustable, share=True) assert axes[1].get_aspect() == 2 assert axes[1].get_adjustable() == adjustable fig, axes = plt.subplots(nrows=2, sharex=True) axes[0].set_aspect(2, adjustable=adjustable) assert axes[1].get_aspect() == 'auto' def test_shared_with_aspect_2(): # Share 2 axes only with 'box': fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True) axes[0].set_aspect(2, share=True) axes[0].plot([1, 2], [3, 4]) axes[1].plot([3, 4], [1, 2]) plt.draw() # Trigger apply_aspect(). assert axes[0].get_xlim() == axes[1].get_xlim() assert axes[0].get_ylim() == axes[1].get_ylim() def test_shared_with_aspect_3(): # Different aspect ratios: for adjustable in ['box', 'datalim']: fig, axes = plt.subplots(nrows=2, sharey=True) axes[0].set_aspect(2, adjustable=adjustable) axes[1].set_aspect(0.5, adjustable=adjustable) axes[0].plot([1, 2], [3, 4]) axes[1].plot([3, 4], [1, 2]) plt.draw() # Trigger apply_aspect(). assert axes[0].get_xlim() != axes[1].get_xlim() assert axes[0].get_ylim() == axes[1].get_ylim() fig_aspect = fig.bbox_inches.height / fig.bbox_inches.width for ax in axes: p = ax.get_position() box_aspect = p.height / p.width lim_aspect = ax.viewLim.height / ax.viewLim.width expected = fig_aspect * box_aspect / lim_aspect assert round(expected, 4) == round(ax.get_aspect(), 4) @pytest.mark.parametrize('twin', ('x', 'y')) def test_twin_with_aspect(twin): fig, ax = plt.subplots() # test twinx or twiny ax_twin = getattr(ax, 'twin{}'.format(twin))() ax.set_aspect(5) ax_twin.set_aspect(2) assert_array_equal(ax.bbox.extents, ax_twin.bbox.extents) def test_relim_visible_only(): x1 = (0., 10.) y1 = (0., 10.) x2 = (-10., 20.) y2 = (-10., 30.) fig = matplotlib.figure.Figure() ax = fig.add_subplot(111) ax.plot(x1, y1) assert ax.get_xlim() == x1 assert ax.get_ylim() == y1 l = ax.plot(x2, y2) assert ax.get_xlim() == x2 assert ax.get_ylim() == y2 l[0].set_visible(False) assert ax.get_xlim() == x2 assert ax.get_ylim() == y2 ax.relim(visible_only=True) ax.autoscale_view() assert ax.get_xlim() == x1 assert ax.get_ylim() == y1 def test_text_labelsize(): """ tests for issue #1172 """ fig = plt.figure() ax = fig.gca() ax.tick_params(labelsize='large') ax.tick_params(direction='out') @image_comparison(baseline_images=['pie_linewidth_0', 'pie_linewidth_0', 'pie_linewidth_0'], extensions=['png']) def test_pie_linewidth_0(): # The slices will be ordered and plotted counter-clockwise. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 0}) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') # Reuse testcase from above for a labeled data test data = {"l": labels, "s": sizes, "c": colors, "ex": explode} fig = plt.figure() ax = fig.gca() ax.pie("s", explode="ex", labels="l", colors="c", autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 0}, data=data) ax.axis('equal') # And again to test the pyplot functions which should also be able to be # called with a data kwarg plt.figure() plt.pie("s", explode="ex", labels="l", colors="c", autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 0}, data=data) plt.axis('equal') @image_comparison(baseline_images=['pie_center_radius'], extensions=['png']) def test_pie_center_radius(): # The slices will be ordered and plotted counter-clockwise. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 0}, center=(1, 2), radius=1.5) plt.annotate("Center point", xy=(1, 2), xytext=(1, 1.5), arrowprops=dict(arrowstyle="->", connectionstyle="arc3")) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') @image_comparison(baseline_images=['pie_linewidth_2'], extensions=['png']) def test_pie_linewidth_2(): # The slices will be ordered and plotted counter-clockwise. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 2}) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') @image_comparison(baseline_images=['pie_ccw_true'], extensions=['png']) def test_pie_ccw_true(): # The slices will be ordered and plotted counter-clockwise. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, counterclock=True) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') @image_comparison(baseline_images=['pie_frame_grid'], extensions=['png']) def test_pie_frame_grid(): # The slices will be ordered and plotted counter-clockwise. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] # only "explode" the 2nd slice (i.e. 'Hogs') explode = (0, 0.1, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 0}, frame=True, center=(2, 2)) plt.pie(sizes[::-1], explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 0}, frame=True, center=(5, 2)) plt.pie(sizes, explode=explode[::-1], labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, wedgeprops={'linewidth': 0}, frame=True, center=(3, 5)) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') @image_comparison(baseline_images=['pie_rotatelabels_true'], extensions=['png']) def test_pie_rotatelabels_true(): # The slices will be ordered and plotted counter-clockwise. labels = 'Hogwarts', 'Frogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, rotatelabels=True) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') @image_comparison(baseline_images=['set_get_ticklabels'], extensions=['png']) def test_set_get_ticklabels(): # test issue 2246 fig, ax = plt.subplots(2) ha = ['normal', 'set_x/yticklabels'] ax[0].plot(np.arange(10)) ax[0].set_title(ha[0]) ax[1].plot(np.arange(10)) ax[1].set_title(ha[1]) # set ticklabel to 1 plot in normal way ax[0].set_xticklabels(('a', 'b', 'c', 'd')) ax[0].set_yticklabels(('11', '12', '13', '14')) # set ticklabel to the other plot, expect the 2 plots have same label # setting pass get_ticklabels return value as ticklabels argument ax[1].set_xticklabels(ax[0].get_xticklabels()) ax[1].set_yticklabels(ax[0].get_yticklabels()) def test_tick_label_update(): # test issue 9397 fig, ax = plt.subplots() # Set up a dummy formatter def formatter_func(x, pos): return "unit value" if x == 1 else "" ax.xaxis.set_major_formatter(plt.FuncFormatter(formatter_func)) # Force some of the x-axis ticks to be outside of the drawn range ax.set_xticks([-1, 0, 1, 2, 3]) ax.set_xlim(-0.5, 2.5) ax.figure.canvas.draw() tick_texts = [tick.get_text() for tick in ax.xaxis.get_ticklabels()] assert tick_texts == ["", "", "unit value", "", ""] @image_comparison(baseline_images=['o_marker_path_snap'], extensions=['png'], savefig_kwarg={'dpi': 72}) def test_o_marker_path_snap(): fig, ax = plt.subplots() ax.margins(.1) for ms in range(1, 15): ax.plot([1, 2, ], np.ones(2) + ms, 'o', ms=ms) for ms in np.linspace(1, 10, 25): ax.plot([3, 4, ], np.ones(2) + ms, 'o', ms=ms) def test_margins(): # test all ways margins can be called data = [1, 10] xmin = 0.0 xmax = len(data) - 1.0 ymin = min(data) ymax = max(data) fig1, ax1 = plt.subplots(1, 1) ax1.plot(data) ax1.margins(1) assert ax1.margins() == (1, 1) assert ax1.get_xlim() == (xmin - (xmax - xmin) * 1, xmax + (xmax - xmin) * 1) assert ax1.get_ylim() == (ymin - (ymax - ymin) * 1, ymax + (ymax - ymin) * 1) fig2, ax2 = plt.subplots(1, 1) ax2.plot(data) ax2.margins(0.5, 2) assert ax2.margins() == (0.5, 2) assert ax2.get_xlim() == (xmin - (xmax - xmin) * 0.5, xmax + (xmax - xmin) * 0.5) assert ax2.get_ylim() == (ymin - (ymax - ymin) * 2, ymax + (ymax - ymin) * 2) fig3, ax3 = plt.subplots(1, 1) ax3.plot(data) ax3.margins(x=-0.2, y=0.5) assert ax3.margins() == (-0.2, 0.5) assert ax3.get_xlim() == (xmin - (xmax - xmin) * -0.2, xmax + (xmax - xmin) * -0.2) assert ax3.get_ylim() == (ymin - (ymax - ymin) * 0.5, ymax + (ymax - ymin) * 0.5) def test_length_one_hist(): fig, ax = plt.subplots() ax.hist(1) ax.hist([1]) def test_pathological_hexbin(): # issue #2863 out = io.BytesIO() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") mylist = [10] * 100 fig, ax = plt.subplots(1, 1) ax.hexbin(mylist, mylist) fig.savefig(out) assert len(w) == 0 def test_color_None(): # issue 3855 fig, ax = plt.subplots() ax.plot([1, 2], [1, 2], color=None) def test_color_alias(): # issues 4157 and 4162 fig, ax = plt.subplots() line = ax.plot([0, 1], c='lime')[0] assert 'lime' == line.get_color() def test_numerical_hist_label(): fig, ax = plt.subplots() ax.hist([range(15)] * 5, label=range(5)) ax.legend() def test_unicode_hist_label(): fig, ax = plt.subplots() a = (b'\xe5\xbe\x88\xe6\xbc\x82\xe4\xba\xae, ' + b'r\xc3\xb6m\xc3\xa4n ch\xc3\xa4r\xc3\xa1ct\xc3\xa8rs') b = b'\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d' labels = [a.decode('utf-8'), 'hi aardvark', b.decode('utf-8'), ] ax.hist([range(15)] * 3, label=labels) ax.legend() def test_move_offsetlabel(): data = np.random.random(10) * 1e-22 fig, ax = plt.subplots() ax.plot(data) ax.yaxis.tick_right() assert (1, 0.5) == ax.yaxis.offsetText.get_position() @image_comparison(baseline_images=['rc_spines'], extensions=['png'], savefig_kwarg={'dpi': 40}) def test_rc_spines(): rc_dict = { 'axes.spines.left': False, 'axes.spines.right': False, 'axes.spines.top': False, 'axes.spines.bottom': False} with matplotlib.rc_context(rc_dict): fig, ax = plt.subplots() @image_comparison(baseline_images=['rc_grid'], extensions=['png'], savefig_kwarg={'dpi': 40}) def test_rc_grid(): fig = plt.figure() rc_dict0 = { 'axes.grid': True, 'axes.grid.axis': 'both' } rc_dict1 = { 'axes.grid': True, 'axes.grid.axis': 'x' } rc_dict2 = { 'axes.grid': True, 'axes.grid.axis': 'y' } dict_list = [rc_dict0, rc_dict1, rc_dict2] i = 1 for rc_dict in dict_list: with matplotlib.rc_context(rc_dict): fig.add_subplot(3, 1, i) i += 1 def test_rc_tick(): d = {'xtick.bottom': False, 'xtick.top': True, 'ytick.left': True, 'ytick.right': False} with plt.rc_context(rc=d): fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) xax = ax1.xaxis yax = ax1.yaxis # tick1On bottom/left assert not xax._major_tick_kw['tick1On'] assert xax._major_tick_kw['tick2On'] assert not xax._minor_tick_kw['tick1On'] assert xax._minor_tick_kw['tick2On'] assert yax._major_tick_kw['tick1On'] assert not yax._major_tick_kw['tick2On'] assert yax._minor_tick_kw['tick1On'] assert not yax._minor_tick_kw['tick2On'] def test_rc_major_minor_tick(): d = {'xtick.top': True, 'ytick.right': True, # Enable all ticks 'xtick.bottom': True, 'ytick.left': True, # Selectively disable 'xtick.minor.bottom': False, 'xtick.major.bottom': False, 'ytick.major.left': False, 'ytick.minor.left': False} with plt.rc_context(rc=d): fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) xax = ax1.xaxis yax = ax1.yaxis # tick1On bottom/left assert not xax._major_tick_kw['tick1On'] assert xax._major_tick_kw['tick2On'] assert not xax._minor_tick_kw['tick1On'] assert xax._minor_tick_kw['tick2On'] assert not yax._major_tick_kw['tick1On'] assert yax._major_tick_kw['tick2On'] assert not yax._minor_tick_kw['tick1On'] assert yax._minor_tick_kw['tick2On'] def test_square_plot(): x = np.arange(4) y = np.array([1., 3., 5., 7.]) fig, ax = plt.subplots() ax.plot(x, y, 'mo') ax.axis('square') xlim, ylim = ax.get_xlim(), ax.get_ylim() assert np.diff(xlim) == np.diff(ylim) assert ax.get_aspect() == 'equal' def test_no_None(): fig, ax = plt.subplots() with pytest.raises(ValueError): plt.plot(None) with pytest.raises(ValueError): plt.plot(None, None) def test_pcolor_fast_non_uniform(): Z = np.arange(6).reshape((3, 2)) X = np.array([0, 1, 2, 10]) Y = np.array([0, 1, 2]) plt.figure() ax = plt.subplot(111) ax.pcolorfast(X, Y, Z.T) def test_shared_scale(): fig, axs = plt.subplots(2, 2, sharex=True, sharey=True) axs[0, 0].set_xscale("log") axs[0, 0].set_yscale("log") for ax in axs.flat: assert ax.get_yscale() == 'log' assert ax.get_xscale() == 'log' axs[1, 1].set_xscale("linear") axs[1, 1].set_yscale("linear") for ax in axs.flat: assert ax.get_yscale() == 'linear' assert ax.get_xscale() == 'linear' def test_violin_point_mass(): """Violin plot should handle point mass pdf gracefully.""" plt.violinplot(np.array([0, 0])) def generate_errorbar_inputs(): base_xy = cycler('x', [np.arange(5)]) + cycler('y', [np.ones((5, ))]) err_cycler = cycler('err', [1, [1, 1, 1, 1, 1], [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], [[1]] * 5, np.ones(5), np.ones((2, 5)), np.ones((5, 1)), None ]) xerr_cy = cycler('xerr', err_cycler) yerr_cy = cycler('yerr', err_cycler) empty = ((cycler('x', [[]]) + cycler('y', [[]])) * cycler('xerr', [[], None]) * cycler('yerr', [[], None])) xerr_only = base_xy * xerr_cy yerr_only = base_xy * yerr_cy both_err = base_xy * yerr_cy * xerr_cy test_cyclers = chain(xerr_only, yerr_only, both_err, empty) return test_cyclers @pytest.mark.parametrize('kwargs', generate_errorbar_inputs()) def test_errorbar_inputs_shotgun(kwargs): ax = plt.gca() eb = ax.errorbar(**kwargs) eb.remove() @image_comparison(baseline_images=["dash_offset"], remove_text=True) def test_dash_offset(): fig, ax = plt.subplots() x = np.linspace(0, 10) y = np.ones_like(x) for j in range(0, 100, 2): ax.plot(x, j*y, ls=(j, (10, 10)), lw=5, color='k') def test_title_pad(): # check that title padding puts the title in the right # place... fig, ax = plt.subplots() ax.set_title('aardvark', pad=30.) m = ax.titleOffsetTrans.get_matrix() assert m[1, -1] == (30. / 72. * fig.dpi) ax.set_title('aardvark', pad=0.) m = ax.titleOffsetTrans.get_matrix() assert m[1, -1] == 0. # check that it is reverted... ax.set_title('aardvark', pad=None) m = ax.titleOffsetTrans.get_matrix() assert m[1, -1] == (matplotlib.rcParams['axes.titlepad'] / 72. * fig.dpi) def test_title_location_roundtrip(): fig, ax = plt.subplots() ax.set_title('aardvark') ax.set_title('left', loc='left') ax.set_title('right', loc='right') assert 'left' == ax.get_title(loc='left') assert 'right' == ax.get_title(loc='right') assert 'aardvark' == ax.get_title() with pytest.raises(ValueError): ax.get_title(loc='foo') with pytest.raises(ValueError): ax.set_title('fail', loc='foo') @image_comparison(baseline_images=["loglog"], remove_text=True, extensions=['png']) def test_loglog(): fig, ax = plt.subplots() x = np.arange(1, 11) ax.loglog(x, x**3, lw=5) ax.tick_params(length=25, width=2) ax.tick_params(length=15, width=2, which='minor') @image_comparison(baseline_images=["test_loglog_nonpos"], remove_text=True, extensions=['png'], style='mpl20') def test_loglog_nonpos(): fig, ax = plt.subplots(3, 3) x = np.arange(1, 11) y = x**3 y[7] = -3. x[4] = -10 for nn, mcx in enumerate(['mask', 'clip', '']): for mm, mcy in enumerate(['mask', 'clip', '']): kws = {} if mcx: kws['nonposx'] = mcx if mcy: kws['nonposy'] = mcy ax[mm, nn].loglog(x, y**3, lw=2, **kws) @pytest.mark.style('default') def test_axes_margins(): fig, ax = plt.subplots() ax.plot([0, 1, 2, 3]) assert ax.get_ybound()[0] != 0 fig, ax = plt.subplots() ax.bar([0, 1, 2, 3], [1, 1, 1, 1]) assert ax.get_ybound()[0] == 0 fig, ax = plt.subplots() ax.barh([0, 1, 2, 3], [1, 1, 1, 1]) assert ax.get_xbound()[0] == 0 fig, ax = plt.subplots() ax.pcolor(np.zeros((10, 10))) assert ax.get_xbound() == (0, 10) assert ax.get_ybound() == (0, 10) fig, ax = plt.subplots() ax.pcolorfast(np.zeros((10, 10))) assert ax.get_xbound() == (0, 10) assert ax.get_ybound() == (0, 10) fig, ax = plt.subplots() ax.hist(np.arange(10)) assert ax.get_ybound()[0] == 0 fig, ax = plt.subplots() ax.imshow(np.zeros((10, 10))) assert ax.get_xbound() == (-0.5, 9.5) assert ax.get_ybound() == (-0.5, 9.5) @pytest.fixture(params=['x', 'y']) def shared_axis_remover(request): def _helper_x(ax): ax2 = ax.twinx() ax2.remove() ax.set_xlim(0, 15) r = ax.xaxis.get_major_locator()() assert r[-1] > 14 def _helper_y(ax): ax2 = ax.twiny() ax2.remove() ax.set_ylim(0, 15) r = ax.yaxis.get_major_locator()() assert r[-1] > 14 return {"x": _helper_x, "y": _helper_y}[request.param] @pytest.fixture(params=['gca', 'subplots', 'subplots_shared', 'add_axes']) def shared_axes_generator(request): # test all of the ways to get fig/ax sets if request.param == 'gca': fig = plt.figure() ax = fig.gca() elif request.param == 'subplots': fig, ax = plt.subplots() elif request.param == 'subplots_shared': fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all') ax = ax_lst[0][0] elif request.param == 'add_axes': fig = plt.figure() ax = fig.add_axes([.1, .1, .8, .8]) return fig, ax def test_remove_shared_axes(shared_axes_generator, shared_axis_remover): # test all of the ways to get fig/ax sets fig, ax = shared_axes_generator shared_axis_remover(ax) def test_remove_shared_axes_relim(): fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all') ax = ax_lst[0][0] orig_xlim = ax_lst[0][1].get_xlim() ax.remove() ax.set_xlim(0, 5) assert_array_equal(ax_lst[0][1].get_xlim(), orig_xlim) def test_adjust_numtick_aspect(): fig, ax = plt.subplots() ax.yaxis.get_major_locator().set_params(nbins='auto') ax.set_xlim(0, 1000) ax.set_aspect('equal') fig.canvas.draw() assert len(ax.yaxis.get_major_locator()()) == 2 ax.set_ylim(0, 1000) fig.canvas.draw() assert len(ax.yaxis.get_major_locator()()) > 2 @image_comparison(baseline_images=["auto_numticks"], style='default', extensions=['png']) def test_auto_numticks(): # Make tiny, empty subplots, verify that there are only 3 ticks. fig, axes = plt.subplots(4, 4) @image_comparison(baseline_images=["auto_numticks_log"], style='default', extensions=['png']) def test_auto_numticks_log(): # Verify that there are not too many ticks with a large log range. fig, ax = plt.subplots() matplotlib.rcParams['axes.autolimit_mode'] = 'round_numbers' ax.loglog([1e-20, 1e5], [1e-16, 10]) def test_broken_barh_empty(): fig, ax = plt.subplots() ax.broken_barh([], (.1, .5)) def test_pandas_pcolormesh(pd): time = pd.date_range('2000-01-01', periods=10) depth = np.arange(20) data = np.random.rand(20, 10) fig, ax = plt.subplots() ax.pcolormesh(time, depth, data) def test_pandas_indexing_dates(pd): dates = np.arange('2005-02', '2005-03', dtype='datetime64[D]') values = np.sin(np.array(range(len(dates)))) df = pd.DataFrame({'dates': dates, 'values': values}) ax = plt.gca() without_zero_index = df[np.array(df.index) % 2 == 1].copy() ax.plot('dates', 'values', data=without_zero_index) def test_pandas_errorbar_indexing(pd): df = pd.DataFrame(np.random.uniform(size=(5, 4)), columns=['x', 'y', 'xe', 'ye'], index=[1, 2, 3, 4, 5]) fig, ax = plt.subplots() ax.errorbar('x', 'y', xerr='xe', yerr='ye', data=df) def test_pandas_indexing_hist(pd): ser_1 = pd.Series(data=[1, 2, 2, 3, 3, 4, 4, 4, 4, 5]) ser_2 = ser_1.iloc[1:] fig, axes = plt.subplots() axes.hist(ser_2) def test_pandas_bar_align_center(pd): # Tests fix for issue 8767 df = pd.DataFrame({'a': range(2), 'b': range(2)}) fig, ax = plt.subplots(1) ax.bar(df.loc[df['a'] == 1, 'b'], df.loc[df['a'] == 1, 'b'], align='center') fig.canvas.draw() def test_axis_set_tick_params_labelsize_labelcolor(): # Tests fix for issue 4346 axis_1 = plt.subplot() axis_1.yaxis.set_tick_params(labelsize=30, labelcolor='red', direction='out') # Expected values after setting the ticks assert axis_1.yaxis.majorTicks[0]._size == 4.0 assert axis_1.yaxis.majorTicks[0]._color == 'k' assert axis_1.yaxis.majorTicks[0]._labelsize == 30.0 assert axis_1.yaxis.majorTicks[0]._labelcolor == 'red' def test_axes_tick_params_gridlines(): # Now treating grid params like other Tick params ax = plt.subplot() ax.tick_params(grid_color='b', grid_linewidth=5, grid_alpha=0.5, grid_linestyle='dashdot') for axis in ax.xaxis, ax.yaxis: assert axis.majorTicks[0]._grid_color == 'b' assert axis.majorTicks[0]._grid_linewidth == 5 assert axis.majorTicks[0]._grid_alpha == 0.5 assert axis.majorTicks[0]._grid_linestyle == 'dashdot' def test_axes_tick_params_ylabelside(): # Tests fix for issue 10267 ax = plt.subplot() ax.tick_params(labelleft=False, labelright=True, which='major') ax.tick_params(labelleft=False, labelright=True, which='minor') # expects left false, right true assert ax.yaxis.majorTicks[0].label1On is False assert ax.yaxis.majorTicks[0].label2On is True assert ax.yaxis.minorTicks[0].label1On is False assert ax.yaxis.minorTicks[0].label2On is True def test_axes_tick_params_xlabelside(): # Tests fix for issue 10267 ax = plt.subplot() ax.tick_params(labeltop=True, labelbottom=False, which='major') ax.tick_params(labeltop=True, labelbottom=False, which='minor') # expects top True, bottom False # label1On mapped to labelbottom # label2On mapped to labeltop assert ax.xaxis.majorTicks[0].label1On is False assert ax.xaxis.majorTicks[0].label2On is True assert ax.xaxis.minorTicks[0].label1On is False assert ax.xaxis.minorTicks[0].label2On is True def test_none_kwargs(): fig, ax = plt.subplots() ln, = ax.plot(range(32), linestyle=None) assert ln.get_linestyle() == '-' def test_ls_ds_conflict(): with pytest.raises(ValueError): plt.plot(range(32), linestyle='steps-pre:', drawstyle='steps-post') def test_bar_uint8(): xs = [0, 1, 2, 3] b = plt.bar(np.array(xs, dtype=np.uint8), [2, 3, 4, 5]) for (patch, x) in zip(b.patches, xs): assert patch.xy[0] == x @image_comparison(baseline_images=['date_timezone_x'], extensions=['png']) def test_date_timezone_x(): # Tests issue 5575 time_index = [pytz.timezone('Canada/Eastern').localize(datetime.datetime( year=2016, month=2, day=22, hour=x)) for x in range(3)] # Same Timezone fig = plt.figure(figsize=(20, 12)) plt.subplot(2, 1, 1) plt.plot_date(time_index, [3] * 3, tz='Canada/Eastern') # Different Timezone plt.subplot(2, 1, 2) plt.plot_date(time_index, [3] * 3, tz='UTC') @image_comparison(baseline_images=['date_timezone_y'], extensions=['png']) def test_date_timezone_y(): # Tests issue 5575 time_index = [pytz.timezone('Canada/Eastern').localize(datetime.datetime( year=2016, month=2, day=22, hour=x)) for x in range(3)] # Same Timezone fig = plt.figure(figsize=(20, 12)) plt.subplot(2, 1, 1) plt.plot_date([3] * 3, time_index, tz='Canada/Eastern', xdate=False, ydate=True) # Different Timezone plt.subplot(2, 1, 2) plt.plot_date([3] * 3, time_index, tz='UTC', xdate=False, ydate=True) @image_comparison(baseline_images=['date_timezone_x_and_y'], extensions=['png']) def test_date_timezone_x_and_y(): # Tests issue 5575 time_index = [pytz.timezone('UTC').localize(datetime.datetime( year=2016, month=2, day=22, hour=x)) for x in range(3)] # Same Timezone fig = plt.figure(figsize=(20, 12)) plt.subplot(2, 1, 1) plt.plot_date(time_index, time_index, tz='UTC', ydate=True) # Different Timezone plt.subplot(2, 1, 2) plt.plot_date(time_index, time_index, tz='US/Eastern', ydate=True) @image_comparison(baseline_images=['axisbelow'], extensions=['png'], remove_text=True) def test_axisbelow(): # Test 'line' setting added in 6287. # Show only grids, not frame or ticks, to make this test # independent of future change to drawing order of those elements. fig, axs = plt.subplots(ncols=3, sharex=True, sharey=True) settings = (False, 'line', True) for ax, setting in zip(axs, settings): ax.plot((0, 10), (0, 10), lw=10, color='m') circ = mpatches.Circle((3, 3), color='r') ax.add_patch(circ) ax.grid(color='c', linestyle='-', linewidth=3) ax.tick_params(top=False, bottom=False, left=False, right=False) for spine in ax.spines.values(): spine.set_visible(False) ax.set_axisbelow(setting) def test_offset_label_color(): # Tests issue 6440 fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot([1.01e9, 1.02e9, 1.03e9]) ax.yaxis.set_tick_params(labelcolor='red') assert ax.yaxis.get_offset_text().get_color() == 'red' def test_large_offset(): fig, ax = plt.subplots() ax.plot((1 + np.array([0, 1.e-12])) * 1.e27) fig.canvas.draw() def test_barb_units(): fig, ax = plt.subplots() dates = [datetime.datetime(2017, 7, 15, 18, i) for i in range(0, 60, 10)] y = np.linspace(0, 5, len(dates)) u = v = np.linspace(0, 50, len(dates)) ax.barbs(dates, y, u, v) def test_quiver_units(): fig, ax = plt.subplots() dates = [datetime.datetime(2017, 7, 15, 18, i) for i in range(0, 60, 10)] y = np.linspace(0, 5, len(dates)) u = v = np.linspace(0, 50, len(dates)) ax.quiver(dates, y, u, v) def test_bar_color_cycle(): ccov = mcolors.colorConverter.to_rgb fig, ax = plt.subplots() for j in range(5): ln, = ax.plot(range(3)) brs = ax.bar(range(3), range(3)) for br in brs: assert ccov(ln.get_color()) == ccov(br.get_facecolor()) def test_tick_param_label_rotation(): fix, (ax, ax2) = plt.subplots(1, 2) ax.plot([0, 1], [0, 1]) ax2.plot([0, 1], [0, 1]) ax.xaxis.set_tick_params(which='both', rotation=75) ax.yaxis.set_tick_params(which='both', rotation=90) for text in ax.get_xticklabels(which='both'): assert text.get_rotation() == 75 for text in ax.get_yticklabels(which='both'): assert text.get_rotation() == 90 ax2.tick_params(axis='x', labelrotation=53) ax2.tick_params(axis='y', rotation=35) for text in ax2.get_xticklabels(which='major'): assert text.get_rotation() == 53 for text in ax2.get_yticklabels(which='major'): assert text.get_rotation() == 35 @pytest.mark.style('default') def test_fillbetween_cycle(): fig, ax = plt.subplots() for j in range(3): cc = ax.fill_between(range(3), range(3)) target = mcolors.to_rgba('C{}'.format(j)) assert tuple(cc.get_facecolors().squeeze()) == tuple(target) for j in range(3, 6): cc = ax.fill_betweenx(range(3), range(3)) target = mcolors.to_rgba('C{}'.format(j)) assert tuple(cc.get_facecolors().squeeze()) == tuple(target) target = mcolors.to_rgba('k') for al in ['facecolor', 'facecolors', 'color']: cc = ax.fill_between(range(3), range(3), **{al: 'k'}) assert tuple(cc.get_facecolors().squeeze()) == tuple(target) edge_target = mcolors.to_rgba('k') for j, el in enumerate(['edgecolor', 'edgecolors'], start=6): cc = ax.fill_between(range(3), range(3), **{el: 'k'}) face_target = mcolors.to_rgba('C{}'.format(j)) assert tuple(cc.get_facecolors().squeeze()) == tuple(face_target) assert tuple(cc.get_edgecolors().squeeze()) == tuple(edge_target) def test_log_margins(): plt.rcParams['axes.autolimit_mode'] = 'data' fig, ax = plt.subplots() margin = 0.05 ax.set_xmargin(margin) ax.semilogx([10, 100], [10, 100]) xlim0, xlim1 = ax.get_xlim() transform = ax.xaxis.get_transform() xlim0t, xlim1t = transform.transform([xlim0, xlim1]) x0t, x1t = transform.transform([10, 100]) delta = (x1t - x0t) * margin assert_allclose([xlim0t + delta, xlim1t - delta], [x0t, x1t]) def test_color_length_mismatch(): N = 5 x, y = np.arange(N), np.arange(N) colors = np.arange(N+1) fig, ax = plt.subplots() with pytest.raises(ValueError): ax.scatter(x, y, c=colors) c_rgb = (0.5, 0.5, 0.5) ax.scatter(x, y, c=c_rgb) ax.scatter(x, y, c=[c_rgb] * N) def test_scatter_color_masking(): x = np.array([1, 2, 3]) y = np.array([1, np.nan, 3]) colors = np.array(['k', 'w', 'k']) linewidths = np.array([1, 2, 3]) s = plt.scatter(x, y, color=colors, linewidths=linewidths) facecolors = s.get_facecolors() linecolors = s.get_edgecolors() linewidths = s.get_linewidths() assert_array_equal(facecolors[1], np.array([0, 0, 0, 1])) assert_array_equal(linecolors[1], np.array([0, 0, 0, 1])) assert linewidths[1] == 3 def test_eventplot_legend(): plt.eventplot([1.0], label='Label') plt.legend() def test_bar_broadcast_args(): fig, ax = plt.subplots() # Check that a bar chart with a single height for all bars works. ax.bar(range(4), 1) # Check that a horizontal chart with one width works. ax.bar(0, 1, bottom=range(4), width=1, orientation='horizontal') # Check that edgecolor gets broadcasted. rect1, rect2 = ax.bar([0, 1], [0, 1], edgecolor=(.1, .2, .3, .4)) assert rect1.get_edgecolor() == rect2.get_edgecolor() == (.1, .2, .3, .4) def test_invalid_axis_limits(): plt.plot([0, 1], [0, 1]) with pytest.raises(ValueError): plt.xlim(np.nan) with pytest.raises(ValueError): plt.xlim(np.inf) with pytest.raises(ValueError): plt.ylim(np.nan) with pytest.raises(ValueError): plt.ylim(np.inf) # Test all 4 combinations of logs/symlogs for minorticks_on() @pytest.mark.parametrize('xscale', ['symlog', 'log']) @pytest.mark.parametrize('yscale', ['symlog', 'log']) def test_minorticks_on(xscale, yscale): ax = plt.subplot(111) ax.plot([1, 2, 3, 4]) ax.set_xscale(xscale) ax.set_yscale(yscale) ax.minorticks_on() def test_twinx_knows_limits(): fig, ax = plt.subplots() ax.axvspan(1, 2) xtwin = ax.twinx() xtwin.plot([0, 0.5], [1, 2]) # control axis fig2, ax2 = plt.subplots() ax2.axvspan(1, 2) ax2.plot([0, 0.5], [1, 2]) assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx) @pytest.mark.style('mpl20') @pytest.mark.parametrize('args, kwargs, warning_count', [((1, 1), {'width': 1, 'bottom': 1}, 0), ((1, ), {'height': 1, 'bottom': 1}, 0), ((), {'x': 1, 'height': 1}, 0), ((), {'left': 1, 'height': 1}, 1)]) def test_bar_signature(args, kwargs, warning_count): fig, ax = plt.subplots() with warnings.catch_warnings(record=True) as w: r, = ax.bar(*args, **kwargs) assert r.get_width() == kwargs.get('width', 0.8) assert r.get_y() == kwargs.get('bottom', 0) assert len(w) == warning_count @pytest.mark.style('mpl20') @pytest.mark.parametrize('args, kwargs, warning_count', [((1, 1), {'height': 1, 'left': 1}, 0), ((1, ), {'width': 1, 'left': 1}, 0), ((), {'y': 1, 'width': 1}, 0), ((), {'bottom': 1, 'width': 1}, 1)]) def test_barh_signature(args, kwargs, warning_count): fig, ax = plt.subplots() with warnings.catch_warnings(record=True) as w: r, = ax.barh(*args, **kwargs) assert r.get_height() == kwargs.get('height', 0.8) assert r.get_x() == kwargs.get('left', 0) assert len(w) == warning_count def test_zero_linewidth(): # Check that setting a zero linewidth doesn't error plt.plot([0, 1], [0, 1], ls='--', lw=0) def test_patch_deprecations(): fig, ax = plt.subplots() with warnings.catch_warnings(record=True) as w: assert ax.patch == ax.axesPatch assert fig.patch == fig.figurePatch assert len(w) == 2 def test_polar_gridlines(): fig = plt.figure() ax = fig.add_subplot(111, polar=True) # make all major grid lines lighter, only x grid lines set in 2.1.0 ax.grid(alpha=0.2) # hide y tick labels, no effect in 2.1.0 plt.setp(ax.yaxis.get_ticklabels(), visible=False) fig.canvas.draw() assert ax.xaxis.majorTicks[0].gridline.get_alpha() == .2 assert ax.yaxis.majorTicks[0].gridline.get_alpha() == .2 def test_empty_errorbar_legend(): fig, ax = plt.subplots() ax.errorbar([], [], xerr=[], label='empty y') ax.errorbar([], [], yerr=[], label='empty x') ax.legend() def test_plot_columns_cycle_deprecation(): with pytest.warns(MatplotlibDeprecationWarning): plt.plot(np.zeros((2, 2)), np.zeros((2, 3)))
180,002
31.068947
89
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_scale.py
from __future__ import print_function, unicode_literals from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib.scale import Log10Transform, InvertedLog10Transform import numpy as np import io import pytest @image_comparison(baseline_images=['log_scales'], remove_text=True) def test_log_scales(): ax = plt.figure().add_subplot(122, yscale='log', xscale='symlog') ax.axvline(24.1) ax.axhline(24.1) @image_comparison(baseline_images=['logit_scales'], remove_text=True, extensions=['png']) def test_logit_scales(): ax = plt.figure().add_subplot(111, xscale='logit') # Typical extinction curve for logit x = np.array([0.001, 0.003, 0.01, 0.03, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.97, 0.99, 0.997, 0.999]) y = 1.0 / x ax.plot(x, y) ax.grid(True) def test_log_scatter(): """Issue #1799""" fig, ax = plt.subplots(1) x = np.arange(10) y = np.arange(10) - 1 ax.scatter(x, y) buf = io.BytesIO() fig.savefig(buf, format='pdf') buf = io.BytesIO() fig.savefig(buf, format='eps') buf = io.BytesIO() fig.savefig(buf, format='svg') def test_logscale_subs(): fig, ax = plt.subplots() ax.set_yscale('log', subsy=np.array([2, 3, 4])) # force draw fig.canvas.draw() @image_comparison(baseline_images=['logscale_mask'], remove_text=True, extensions=['png']) def test_logscale_mask(): # Check that zero values are masked correctly on log scales. # See github issue 8045 xs = np.linspace(0, 50, 1001) fig, ax = plt.subplots() ax.plot(np.exp(-xs**2)) fig.canvas.draw() ax.set(yscale="log") def test_extra_kwargs_raise(): fig, ax = plt.subplots() with pytest.raises(ValueError): ax.set_yscale('log', nonpos='mask') def test_logscale_invert_transform(): fig, ax = plt.subplots() ax.set_yscale('log') # get transformation from data to axes tform = (ax.transAxes + ax.transData.inverted()).inverted() # direct test of log transform inversion assert isinstance(Log10Transform().inverted(), InvertedLog10Transform) def test_logscale_transform_repr(): # check that repr of log transform succeeds fig, ax = plt.subplots() ax.set_yscale('log') s = repr(ax.transData) # check that repr of log transform returns correct string s = repr(Log10Transform(nonpos='clip')) assert s == "Log10Transform({!r})".format('clip') @image_comparison(baseline_images=['logscale_nonpos_values'], remove_text=True, extensions=['png'], style='mpl20') def test_logscale_nonpos_values(): np.random.seed(19680801) xs = np.random.normal(size=int(1e3)) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.hist(xs, range=(-5, 5), bins=10) ax1.set_yscale('log') ax2.hist(xs, range=(-5, 5), bins=10) ax2.set_yscale('log', nonposy='mask') xdata = np.arange(0, 10, 0.01) ydata = np.exp(-xdata) edata = 0.2*(10-xdata)*np.cos(5*xdata)*np.exp(-xdata) ax3.fill_between(xdata, ydata - edata, ydata + edata) ax3.set_yscale('log') x = np.logspace(-1, 1) y = x ** 3 yerr = x**2 ax4.errorbar(x, y, yerr=yerr) ax4.set_yscale('log') ax4.set_xscale('log')
3,316
25.75
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_dviread.py
from __future__ import absolute_import, division, print_function import six from matplotlib.testing.decorators import skip_if_command_unavailable import matplotlib.dviread as dr import os.path import json import pytest def test_PsfontsMap(monkeypatch): monkeypatch.setattr(dr, 'find_tex_file', lambda x: x) filename = os.path.join( os.path.dirname(__file__), 'baseline_images', 'dviread', 'test.map') fontmap = dr.PsfontsMap(filename) # Check all properties of a few fonts for n in [1, 2, 3, 4, 5]: key = ('TeXfont%d' % n).encode('ascii') entry = fontmap[key] assert entry.texname == key assert entry.psname == ('PSfont%d' % n).encode('ascii') if n not in [3, 5]: assert entry.encoding == ('font%d.enc' % n).encode('ascii') elif n == 3: assert entry.encoding == b'enc3.foo' # We don't care about the encoding of TeXfont5, which specifies # multiple encodings. if n not in [1, 5]: assert entry.filename == ('font%d.pfa' % n).encode('ascii') else: assert entry.filename == ('font%d.pfb' % n).encode('ascii') if n == 4: assert entry.effects == {'slant': -0.1, 'extend': 2.2} else: assert entry.effects == {} # Some special cases entry = fontmap[b'TeXfont6'] assert entry.filename is None assert entry.encoding is None entry = fontmap[b'TeXfont7'] assert entry.filename is None assert entry.encoding == b'font7.enc' entry = fontmap[b'TeXfont8'] assert entry.filename == b'font8.pfb' assert entry.encoding is None entry = fontmap[b'TeXfont9'] assert entry.filename == b'/absolute/font9.pfb' # Missing font with pytest.raises(KeyError) as exc: fontmap[b'no-such-font'] assert 'no-such-font' in str(exc.value) @skip_if_command_unavailable(["kpsewhich", "-version"]) def test_dviread(): dir = os.path.join(os.path.dirname(__file__), 'baseline_images', 'dviread') with open(os.path.join(dir, 'test.json')) as f: correct = json.load(f) for entry in correct: entry['text'] = [[a, b, c, d.encode('ascii'), e] for [a, b, c, d, e] in entry['text']] with dr.Dvi(os.path.join(dir, 'test.dvi'), None) as dvi: data = [{'text': [[t.x, t.y, six.unichr(t.glyph), t.font.texname, round(t.font.size, 2)] for t in page.text], 'boxes': [[b.x, b.y, b.height, b.width] for b in page.boxes]} for page in dvi] assert data == correct
2,704
35.554054
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_table.py
from __future__ import absolute_import, division, print_function import six import matplotlib.pyplot as plt import numpy as np from matplotlib.testing.decorators import image_comparison from matplotlib.table import CustomCell, Table from matplotlib.path import Path def test_non_square(): # Check that creating a non-square table works cellcolors = ['b', 'r'] plt.table(cellColours=cellcolors) @image_comparison(baseline_images=['table_zorder'], extensions=['png'], remove_text=True) def test_zorder(): data = [[66386, 174296], [58230, 381139]] colLabels = ('Freeze', 'Wind') rowLabels = ['%d year' % x for x in (100, 50)] cellText = [] yoff = np.zeros(len(colLabels)) for row in reversed(data): yoff += row cellText.append(['%1.1f' % (x/1000.0) for x in yoff]) t = np.linspace(0, 2*np.pi, 100) plt.plot(t, np.cos(t), lw=4, zorder=2) plt.table(cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, loc='center', zorder=-2, ) plt.table(cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, loc='upper center', zorder=4, ) plt.yticks([]) @image_comparison(baseline_images=['table_labels'], extensions=['png']) def test_label_colours(): dim = 3 c = np.linspace(0, 1, dim) colours = plt.cm.RdYlGn(c) cellText = [['1'] * dim] * dim fig = plt.figure() ax1 = fig.add_subplot(4, 1, 1) ax1.axis('off') ax1.table(cellText=cellText, rowColours=colours, loc='best') ax2 = fig.add_subplot(4, 1, 2) ax2.axis('off') ax2.table(cellText=cellText, rowColours=colours, rowLabels=['Header'] * dim, loc='best') ax3 = fig.add_subplot(4, 1, 3) ax3.axis('off') ax3.table(cellText=cellText, colColours=colours, loc='best') ax4 = fig.add_subplot(4, 1, 4) ax4.axis('off') ax4.table(cellText=cellText, colColours=colours, colLabels=['Header'] * dim, loc='best') @image_comparison(baseline_images=['table_cell_manipulation'], extensions=['png'], remove_text=True) def test_diff_cell_table(): cells = ('horizontal', 'vertical', 'open', 'closed', 'T', 'R', 'B', 'L') cellText = [['1'] * len(cells)] * 2 colWidths = [0.1] * len(cells) _, axes = plt.subplots(nrows=len(cells), figsize=(4, len(cells)+1)) for ax, cell in zip(axes, cells): ax.table( colWidths=colWidths, cellText=cellText, loc='center', edges=cell, ) ax.axis('off') plt.tight_layout() def test_customcell(): types = ('horizontal', 'vertical', 'open', 'closed', 'T', 'R', 'B', 'L') codes = ( (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO), (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO), (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO), (Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY), (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO), (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO), (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO, Path.MOVETO), (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO), ) for t, c in zip(types, codes): cell = CustomCell((0, 0), visible_edges=t, width=1, height=1) code = tuple(s for _, s in cell.get_path().iter_segments()) assert c == code @image_comparison(baseline_images=['table_auto_column'], extensions=['png']) def test_auto_column(): fig = plt.figure() # iterable list input ax1 = fig.add_subplot(4, 1, 1) ax1.axis('off') tb1 = ax1.table(cellText=[['Fit Text', 2], ['very long long text, Longer text than default', 1]], rowLabels=["A", "B"], colLabels=["Col1", "Col2"], loc="center") tb1.auto_set_font_size(False) tb1.set_fontsize(12) tb1.auto_set_column_width([-1, 0, 1]) # iterable tuple input ax2 = fig.add_subplot(4, 1, 2) ax2.axis('off') tb2 = ax2.table(cellText=[['Fit Text', 2], ['very long long text, Longer text than default', 1]], rowLabels=["A", "B"], colLabels=["Col1", "Col2"], loc="center") tb2.auto_set_font_size(False) tb2.set_fontsize(12) tb2.auto_set_column_width((-1, 0, 1)) #3 single inputs ax3 = fig.add_subplot(4, 1, 3) ax3.axis('off') tb3 = ax3.table(cellText=[['Fit Text', 2], ['very long long text, Longer text than default', 1]], rowLabels=["A", "B"], colLabels=["Col1", "Col2"], loc="center") tb3.auto_set_font_size(False) tb3.set_fontsize(12) tb3.auto_set_column_width(-1) tb3.auto_set_column_width(0) tb3.auto_set_column_width(1) #4 non integer interable input ax4 = fig.add_subplot(4, 1, 4) ax4.axis('off') tb4 = ax4.table(cellText=[['Fit Text', 2], ['very long long text, Longer text than default', 1]], rowLabels=["A", "B"], colLabels=["Col1", "Col2"], loc="center") tb4.auto_set_font_size(False) tb4.set_fontsize(12) tb4.auto_set_column_width("-101") def test_table_cells(): fig, ax = plt.subplots() table = Table(ax) cell = table.add_cell(1, 2, 1, 1) assert isinstance(cell, CustomCell) assert cell is table[1, 2] cell2 = CustomCell((0, 0), 1, 2, visible_edges=None) table[2, 1] = cell2 assert table[2, 1] is cell2 # make sure gettitem support has not broken # properties and setp table.properties() plt.setp(table)
5,984
28.628713
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_compare_images.py
from __future__ import absolute_import, division, print_function import six import io import os import shutil import warnings from numpy.testing import assert_almost_equal import pytest from pytest import approx from matplotlib.testing.compare import compare_images from matplotlib.testing.decorators import _image_directories, image_comparison from matplotlib.testing.exceptions import ImageComparisonFailure baseline_dir, result_dir = _image_directories(lambda: 'dummy func') # Tests of the image comparison algorithm. @pytest.mark.parametrize( 'im1, im2, tol, expect_rms', [ # Comparison of an image and the same image with minor differences. # This expects the images to compare equal under normal tolerance, and # have a small RMS. ('basn3p02.png', 'basn3p02-minorchange.png', 10, None), # Now test with no tolerance. ('basn3p02.png', 'basn3p02-minorchange.png', 0, 6.50646), # Comparison with an image that is shifted by 1px in the X axis. ('basn3p02.png', 'basn3p02-1px-offset.png', 0, 90.15611), # Comparison with an image with half the pixels shifted by 1px in the X # axis. ('basn3p02.png', 'basn3p02-half-1px-offset.png', 0, 63.75), # Comparison of an image and the same image scrambled. # This expects the images to compare completely different, with a very # large RMS. # Note: The image has been scrambled in a specific way, by having # each color component of each pixel randomly placed somewhere in the # image. It contains exactly the same number of pixels of each color # value of R, G and B, but in a totally different position. # Test with no tolerance to make sure that we pick up even a very small # RMS error. ('basn3p02.png', 'basn3p02-scrambled.png', 0, 172.63582), # Comparison of an image and a slightly brighter image. # The two images are solid color, with the second image being exactly 1 # color value brighter. # This expects the images to compare equal under normal tolerance, and # have an RMS of exactly 1. ('all127.png', 'all128.png', 0, 1), # Now test the reverse comparison. ('all128.png', 'all127.png', 0, 1), ]) def test_image_comparison_expect_rms(im1, im2, tol, expect_rms): """Compare two images, expecting a particular RMS error. im1 and im2 are filenames relative to the baseline_dir directory. tol is the tolerance to pass to compare_images. expect_rms is the expected RMS value, or None. If None, the test will succeed if compare_images succeeds. Otherwise, the test will succeed if compare_images fails and returns an RMS error almost equal to this value. """ im1 = os.path.join(baseline_dir, im1) im2_src = os.path.join(baseline_dir, im2) im2 = os.path.join(result_dir, im2) # Move im2 from baseline_dir to result_dir. This will ensure that # compare_images writes the diff file to result_dir, instead of trying to # write to the (possibly read-only) baseline_dir. shutil.copyfile(im2_src, im2) results = compare_images(im1, im2, tol=tol, in_decorator=True) if expect_rms is None: assert results is None else: assert results is not None assert results['rms'] == approx(expect_rms, abs=1e-4) # The following tests are used by test_nose_image_comparison to ensure that the # image_comparison decorator continues to work with nose. They should not be # prefixed by test_ so they don't run with pytest. def nosetest_empty(): pass def nosetest_simple_figure(): import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(6.4, 4), dpi=100) ax.plot([1, 2, 3], [3, 4, 5]) return fig def nosetest_manual_text_removal(): from matplotlib.testing.decorators import ImageComparisonTest fig = nosetest_simple_figure() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # Make sure this removes text like it should. ImageComparisonTest.remove_text(fig) assert len(w) == 1 assert 'remove_text function was deprecated in version 2.1.' in str(w[0]) @pytest.mark.parametrize( 'func, kwargs, errors, failures, dots', [ (nosetest_empty, {'baseline_images': []}, [], [], ''), (nosetest_empty, {'baseline_images': ['foo']}, [(AssertionError, 'Test generated 0 images but there are 1 baseline images')], [], 'E'), (nosetest_simple_figure, {'baseline_images': ['basn3p02'], 'extensions': ['png'], 'remove_text': True}, [], [(ImageComparisonFailure, 'Image sizes do not match expected size:')], 'F'), (nosetest_simple_figure, {'baseline_images': ['simple']}, [], [(ImageComparisonFailure, 'images not close')] * 3, 'FFF'), (nosetest_simple_figure, {'baseline_images': ['simple'], 'remove_text': True}, [], [], '...'), (nosetest_manual_text_removal, {'baseline_images': ['simple']}, [], [], '...'), ], ids=[ 'empty', 'extra baselines', 'incorrect shape', 'failing figure', 'passing figure', 'manual text removal', ]) def test_nose_image_comparison(func, kwargs, errors, failures, dots, monkeypatch): nose = pytest.importorskip('nose') monkeypatch.setattr('matplotlib._called_from_pytest', False) class TestResultVerifier(nose.result.TextTestResult): def __init__(self, *args, **kwargs): super(TestResultVerifier, self).__init__(*args, **kwargs) self.error_count = 0 self.failure_count = 0 def addError(self, test, err): super(TestResultVerifier, self).addError(test, err) if self.error_count < len(errors): assert err[0] is errors[self.error_count][0] assert errors[self.error_count][1] in str(err[1]) else: raise err[1] self.error_count += 1 def addFailure(self, test, err): super(TestResultVerifier, self).addFailure(test, err) assert self.failure_count < len(failures), err[1] assert err[0] is failures[self.failure_count][0] assert failures[self.failure_count][1] in str(err[1]) self.failure_count += 1 # Make sure that multiple extensions work, but don't require LaTeX or # Inkscape to do so. kwargs.setdefault('extensions', ['png', 'png', 'png']) func = image_comparison(**kwargs)(func) loader = nose.loader.TestLoader() suite = loader.loadTestsFromGenerator( func, 'matplotlib.tests.test_compare_images') if six.PY2: output = io.BytesIO() else: output = io.StringIO() result = TestResultVerifier(stream=output, descriptions=True, verbosity=1) with warnings.catch_warnings(): # Nose uses deprecated stuff; we don't care about it. warnings.simplefilter('ignore', DeprecationWarning) suite.run(result=result) assert output.getvalue() == dots assert result.error_count == len(errors) assert result.failure_count == len(failures)
7,394
35.608911
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_simplification.py
from __future__ import absolute_import, division, print_function import io import numpy as np from numpy.testing import assert_array_almost_equal, assert_array_equal import pytest from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib import patches, transforms from matplotlib.path import Path # NOTE: All of these tests assume that path.simplify is set to True # (the default) @image_comparison(baseline_images=['clipping'], remove_text=True) def test_clipping(): t = np.arange(0.0, 2.0, 0.01) s = np.sin(2*np.pi*t) fig, ax = plt.subplots() ax.plot(t, s, linewidth=1.0) ax.set_ylim((-0.20, -0.28)) @image_comparison(baseline_images=['overflow'], remove_text=True) def test_overflow(): x = np.array([1.0, 2.0, 3.0, 2.0e5]) y = np.arange(len(x)) fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(xmin=2, xmax=6) @image_comparison(baseline_images=['clipping_diamond'], remove_text=True) def test_diamond(): x = np.array([0.0, 1.0, 0.0, -1.0, 0.0]) y = np.array([1.0, 0.0, -1.0, 0.0, 1.0]) fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(xmin=-0.6, xmax=0.6) ax.set_ylim(ymin=-0.6, ymax=0.6) def test_noise(): np.random.seed(0) x = np.random.uniform(size=(50000,)) * 50 fig, ax = plt.subplots() p1 = ax.plot(x, solid_joinstyle='round', linewidth=2.0) path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) simplified = path.cleaned(simplify=True) assert simplified.vertices.size == 25512 def test_antiparallel_simplification(): def _get_simplified(x, y): fig, ax = plt.subplots() p1 = ax.plot(x, y) path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) simplified = path.cleaned(simplify=True) simplified = transform.inverted().transform_path(simplified) return simplified # test ending on a maximum x = [0, 0, 0, 0, 0, 1] y = [.5, 1, -1, 1, 2, .5] simplified = _get_simplified(x, y) assert_array_almost_equal([[0., 0.5], [0., -1.], [0., 2.], [1., 0.5]], simplified.vertices[:-2, :]) # test ending on a minimum x = [0, 0, 0, 0, 0, 1] y = [.5, 1, -1, 1, -2, .5] simplified = _get_simplified(x, y) assert_array_almost_equal([[0., 0.5], [0., 1.], [0., -2.], [1., 0.5]], simplified.vertices[:-2, :]) # test ending in between x = [0, 0, 0, 0, 0, 1] y = [.5, 1, -1, 1, 0, .5] simplified = _get_simplified(x, y) assert_array_almost_equal([[0., 0.5], [0., 1.], [0., -1.], [0., 0.], [1., 0.5]], simplified.vertices[:-2, :]) # test no anti-parallel ending at max x = [0, 0, 0, 0, 0, 1] y = [.5, 1, 2, 1, 3, .5] simplified = _get_simplified(x, y) assert_array_almost_equal([[0., 0.5], [0., 3.], [1., 0.5]], simplified.vertices[:-2, :]) # test no anti-parallel ending in middle x = [0, 0, 0, 0, 0, 1] y = [.5, 1, 2, 1, 1, .5] simplified = _get_simplified(x, y) assert_array_almost_equal([[0., 0.5], [0., 2.], [0., 1.], [1., 0.5]], simplified.vertices[:-2, :]) # Only consider angles in 0 <= angle <= pi/2, otherwise # using min/max will get the expected results out of order: # min/max for simplification code depends on original vector, # and if angle is outside above range then simplification # min/max will be opposite from actual min/max. @pytest.mark.parametrize('angle', [0, np.pi/4, np.pi/3, np.pi/2]) @pytest.mark.parametrize('offset', [0, .5]) def test_angled_antiparallel(angle, offset): scale = 5 np.random.seed(19680801) # get 15 random offsets # TODO: guarantee offset > 0 results in some offsets < 0 vert_offsets = (np.random.rand(15) - offset) * scale # always start at 0 so rotation makes sense vert_offsets[0] = 0 # always take the first step the same direction vert_offsets[1] = 1 # compute points along a diagonal line x = np.sin(angle) * vert_offsets y = np.cos(angle) * vert_offsets # will check these later x_max = x[1:].max() x_min = x[1:].min() y_max = y[1:].max() y_min = y[1:].min() if offset > 0: p_expected = Path([[0, 0], [x_max, y_max], [x_min, y_min], [x[-1], y[-1]], [0, 0]], codes=[1, 2, 2, 2, 0]) else: p_expected = Path([[0, 0], [x_max, y_max], [x[-1], y[-1]], [0, 0]], codes=[1, 2, 2, 0]) p = Path(np.vstack([x, y]).T) p2 = p.cleaned(simplify=True) assert_array_almost_equal(p_expected.vertices, p2.vertices) assert_array_equal(p_expected.codes, p2.codes) def test_sine_plus_noise(): np.random.seed(0) x = (np.sin(np.linspace(0, np.pi * 2.0, 50000)) + np.random.uniform(size=(50000,)) * 0.01) fig, ax = plt.subplots() p1 = ax.plot(x, solid_joinstyle='round', linewidth=2.0) path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) simplified = path.cleaned(simplify=True) assert simplified.vertices.size == 25240 @image_comparison(baseline_images=['simplify_curve'], remove_text=True) def test_simplify_curve(): pp1 = patches.PathPatch( Path([(0, 0), (1, 0), (1, 1), (np.nan, 1), (0, 0), (2, 0), (2, 2), (0, 0)], [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), fc="none") fig, ax = plt.subplots() ax.add_patch(pp1) ax.set_xlim((0, 2)) ax.set_ylim((0, 2)) @image_comparison(baseline_images=['hatch_simplify'], remove_text=True) def test_hatch(): fig, ax = plt.subplots() ax.add_patch(plt.Rectangle((0, 0), 1, 1, fill=False, hatch="/")) ax.set_xlim((0.45, 0.55)) ax.set_ylim((0.45, 0.55)) @image_comparison(baseline_images=['fft_peaks'], remove_text=True) def test_fft_peaks(): fig, ax = plt.subplots() t = np.arange(65536) p1 = ax.plot(abs(np.fft.fft(np.sin(2*np.pi*.01*t)*np.blackman(len(t))))) path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) simplified = path.cleaned(simplify=True) assert simplified.vertices.size == 36 def test_start_with_moveto(): # Should be entirely clipped away to a single MOVETO data = b""" ZwAAAAku+v9UAQAA+Tj6/z8CAADpQ/r/KAMAANlO+v8QBAAAyVn6//UEAAC6ZPr/2gUAAKpv+v+8 BgAAm3r6/50HAACLhfr/ewgAAHyQ+v9ZCQAAbZv6/zQKAABepvr/DgsAAE+x+v/lCwAAQLz6/7wM AAAxx/r/kA0AACPS+v9jDgAAFN36/zQPAAAF6Pr/AxAAAPfy+v/QEAAA6f36/5wRAADbCPv/ZhIA AMwT+/8uEwAAvh77//UTAACwKfv/uRQAAKM0+/98FQAAlT/7/z0WAACHSvv//RYAAHlV+/+7FwAA bGD7/3cYAABea/v/MRkAAFF2+//pGQAARIH7/6AaAAA3jPv/VRsAACmX+/8JHAAAHKL7/7ocAAAP rfv/ah0AAAO4+/8YHgAA9sL7/8QeAADpzfv/bx8AANzY+/8YIAAA0OP7/78gAADD7vv/ZCEAALf5 +/8IIgAAqwT8/6kiAACeD/z/SiMAAJIa/P/oIwAAhiX8/4QkAAB6MPz/HyUAAG47/P+4JQAAYkb8 /1AmAABWUfz/5SYAAEpc/P95JwAAPmf8/wsoAAAzcvz/nCgAACd9/P8qKQAAHIj8/7cpAAAQk/z/ QyoAAAWe/P/MKgAA+aj8/1QrAADus/z/2isAAOO+/P9eLAAA2Mn8/+AsAADM1Pz/YS0AAMHf/P/g LQAAtur8/10uAACr9fz/2C4AAKEA/f9SLwAAlgv9/8ovAACLFv3/QDAAAIAh/f+1MAAAdSz9/ycx AABrN/3/mDEAAGBC/f8IMgAAVk39/3UyAABLWP3/4TIAAEFj/f9LMwAANm79/7MzAAAsef3/GjQA ACKE/f9+NAAAF4/9/+E0AAANmv3/QzUAAAOl/f+iNQAA+a/9/wA2AADvuv3/XDYAAOXF/f+2NgAA 29D9/w83AADR2/3/ZjcAAMfm/f+7NwAAvfH9/w44AACz/P3/XzgAAKkH/v+vOAAAnxL+//04AACW Hf7/SjkAAIwo/v+UOQAAgjP+/905AAB5Pv7/JDoAAG9J/v9pOgAAZVT+/606AABcX/7/7zoAAFJq /v8vOwAASXX+/207AAA/gP7/qjsAADaL/v/lOwAALZb+/x48AAAjof7/VTwAABqs/v+LPAAAELf+ /788AAAHwv7/8TwAAP7M/v8hPQAA9df+/1A9AADr4v7/fT0AAOLt/v+oPQAA2fj+/9E9AADQA/// +T0AAMYO//8fPgAAvRn//0M+AAC0JP//ZT4AAKsv//+GPgAAojr//6U+AACZRf//wj4AAJBQ///d PgAAh1v///c+AAB+Zv//Dz8AAHRx//8lPwAAa3z//zk/AABih///TD8AAFmS//9dPwAAUJ3//2w/ AABHqP//ej8AAD6z//+FPwAANb7//48/AAAsyf//lz8AACPU//+ePwAAGt///6M/AAAR6v//pj8A AAj1//+nPwAA/////w==""" import base64 if hasattr(base64, 'encodebytes'): # Python 3 case decodebytes = base64.decodebytes else: # Python 2 case decodebytes = base64.decodestring verts = np.fromstring(decodebytes(data), dtype='<i4') verts = verts.reshape((len(verts) // 2, 2)) path = Path(verts) segs = path.iter_segments(transforms.IdentityTransform(), clip=(0.0, 0.0, 100.0, 100.0)) segs = list(segs) assert len(segs) == 1 assert segs[0][1] == Path.MOVETO def test_throw_rendering_complexity_exceeded(): plt.rcParams['path.simplify'] = False xx = np.arange(200000) yy = np.random.rand(200000) yy[1000] = np.nan fig, ax = plt.subplots() ax.plot(xx, yy) with pytest.raises(OverflowError): fig.savefig(io.BytesIO()) @image_comparison(baseline_images=['clipper_edge'], remove_text=True) def test_clipper(): dat = (0, 1, 0, 2, 0, 3, 0, 4, 0, 5) fig = plt.figure(figsize=(2, 1)) fig.subplots_adjust(left=0, bottom=0, wspace=0, hspace=0) ax = fig.add_axes((0, 0, 1.0, 1.0), ylim=(0, 5), autoscale_on=False) ax.plot(dat) ax.xaxis.set_major_locator(plt.MultipleLocator(1)) ax.yaxis.set_major_locator(plt.MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlim(5, 9) @image_comparison(baseline_images=['para_equal_perp'], remove_text=True) def test_para_equal_perp(): x = np.array([0, 1, 2, 1, 0, -1, 0, 1] + [1] * 128) y = np.array([1, 1, 2, 1, 0, -1, 0, 0] + [0] * 128) fig, ax = plt.subplots() ax.plot(x + 1, y + 1) ax.plot(x + 1, y + 1, 'ro') @image_comparison(baseline_images=['clipping_with_nans']) def test_clipping_with_nans(): x = np.linspace(0, 3.14 * 2, 3000) y = np.sin(x) x[::100] = np.nan fig, ax = plt.subplots() ax.plot(x, y) ax.set_ylim(-0.25, 0.25) def test_clipping_full(): p = Path([[1e30, 1e30]] * 5) simplified = list(p.iter_segments(clip=[0, 0, 100, 100])) assert simplified == [] p = Path([[50, 40], [75, 65]], [1, 2]) simplified = list(p.iter_segments(clip=[0, 0, 100, 100])) assert ([(list(x), y) for x, y in simplified] == [([50, 40], 1), ([75, 65], 2)]) p = Path([[50, 40]], [1]) simplified = list(p.iter_segments(clip=[0, 0, 100, 100])) assert ([(list(x), y) for x, y in simplified] == [([50, 40], 1)])
11,169
31.005731
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backends_interactive.py
import importlib import os import sys from matplotlib.compat.subprocess import Popen import pytest # Minimal smoke-testing of the backends for which the dependencies are # PyPI-installable on Travis. They are not available for all tested Python # versions so we don't fail on missing backends. # # We also don't test on Py2 because its subprocess module doesn't support # timeouts, and it would require a separate code path to check for module # existence without actually trying to import the module (which may install # an undesirable input hook). def _get_testable_interactive_backends(): backends = [] for deps, backend in [(["cairocffi", "pgi"], "gtk3agg"), (["cairocffi", "pgi"], "gtk3cairo"), (["PyQt5"], "qt5agg"), (["cairocffi", "PyQt5"], "qt5cairo"), (["tkinter"], "tkagg"), (["wx"], "wxagg")]: reason = None if sys.version_info < (3,): reason = "Py3-only test" elif not os.environ.get("DISPLAY"): reason = "No $DISPLAY" elif any(importlib.util.find_spec(dep) is None for dep in deps): reason = "Missing dependency" backends.append(pytest.mark.skip(reason=reason)(backend) if reason else backend) return backends _test_script = """\ import sys from matplotlib import pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3], [1,3,1]) fig.canvas.mpl_connect("draw_event", lambda event: sys.exit()) plt.show() """ @pytest.mark.parametrize("backend", _get_testable_interactive_backends()) @pytest.mark.flaky(reruns=3) def test_backend(backend): environ = os.environ.copy() environ["MPLBACKEND"] = backend proc = Popen([sys.executable, "-c", _test_script], env=environ) # Empirically, 1s is not enough on Travis. assert proc.wait(timeout=10) == 0
1,944
31.966102
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_contour.py
from __future__ import absolute_import, division, print_function import datetime import numpy as np from matplotlib.testing.decorators import image_comparison from matplotlib import pyplot as plt from numpy.testing import assert_array_almost_equal import pytest import warnings def test_contour_shape_1d_valid(): x = np.arange(10) y = np.arange(9) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) ax.contour(x, y, z) def test_contour_shape_2d_valid(): x = np.arange(10) y = np.arange(9) xg, yg = np.meshgrid(x, y) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) ax.contour(xg, yg, z) def test_contour_shape_mismatch_1(): x = np.arange(9) y = np.arange(9) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) excinfo.match(r'Length of x must be number of columns in z.') def test_contour_shape_mismatch_2(): x = np.arange(10) y = np.arange(10) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) excinfo.match(r'Length of y must be number of rows in z.') def test_contour_shape_mismatch_3(): x = np.arange(10) y = np.arange(10) xg, yg = np.meshgrid(x, y) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) with pytest.raises(TypeError) as excinfo: ax.contour(xg, y, z) excinfo.match(r'Number of dimensions of x and y should match.') with pytest.raises(TypeError) as excinfo: ax.contour(x, yg, z) excinfo.match(r'Number of dimensions of x and y should match.') def test_contour_shape_mismatch_4(): g = np.random.random((9, 10)) b = np.random.random((9, 9)) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) with pytest.raises(TypeError) as excinfo: ax.contour(b, g, z) excinfo.match(r'Shape of x does not match that of z: found \(9L?, 9L?\) ' + r'instead of \(9L?, 10L?\)') with pytest.raises(TypeError) as excinfo: ax.contour(g, b, z) excinfo.match(r'Shape of y does not match that of z: found \(9L?, 9L?\) ' + r'instead of \(9L?, 10L?\)') def test_contour_shape_invalid_1(): x = np.random.random((3, 3, 3)) y = np.random.random((3, 3, 3)) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) excinfo.match(r'Inputs x and y must be 1D or 2D.') def test_contour_shape_invalid_2(): x = np.random.random((3, 3, 3)) y = np.random.random((3, 3, 3)) z = np.random.random((3, 3, 3)) fig = plt.figure() ax = fig.add_subplot(111) with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) excinfo.match(r'Input z must be a 2D array.') def test_contour_empty_levels(): x = np.arange(9) z = np.random.random((9, 9)) fig, ax = plt.subplots() with pytest.warns(UserWarning) as record: ax.contour(x, x, z, levels=[]) assert len(record) == 1 def test_contour_badlevel_fmt(): # test funny edge case from # https://github.com/matplotlib/matplotlib/issues/9742 # User supplied fmt for each level as a dictionary, but # MPL changed the level to the minimum data value because # no contours possible. # This would error out pre # https://github.com/matplotlib/matplotlib/pull/9743 x = np.arange(9) z = np.zeros((9, 9)) fig, ax = plt.subplots() fmt = {1.: '%1.2f'} with pytest.warns(UserWarning) as record: cs = ax.contour(x, x, z, levels=[1.]) ax.clabel(cs, fmt=fmt) assert len(record) == 1 def test_contour_uniform_z(): x = np.arange(9) z = np.ones((9, 9)) fig, ax = plt.subplots() with pytest.warns(UserWarning) as record: ax.contour(x, x, z) assert len(record) == 1 @image_comparison(baseline_images=['contour_manual_labels'], savefig_kwarg={'dpi': 200}, remove_text=True, style='mpl20') def test_contour_manual_labels(): x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10)) z = np.max(np.dstack([abs(x), abs(y)]), 2) plt.figure(figsize=(6, 2), dpi=200) cs = plt.contour(x, y, z) pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)]) plt.clabel(cs, manual=pts) @image_comparison(baseline_images=['contour_labels_size_color'], extensions=['png'], remove_text=True, style='mpl20') def test_contour_labels_size_color(): x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10)) z = np.max(np.dstack([abs(x), abs(y)]), 2) plt.figure(figsize=(6, 2)) cs = plt.contour(x, y, z) pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)]) plt.clabel(cs, manual=pts, fontsize='small', colors=('r', 'g')) @image_comparison(baseline_images=['contour_manual_colors_and_levels'], extensions=['png'], remove_text=True) def test_given_colors_levels_and_extends(): _, axes = plt.subplots(2, 4) data = np.arange(12).reshape(3, 4) colors = ['red', 'yellow', 'pink', 'blue', 'black'] levels = [2, 4, 8, 10] for i, ax in enumerate(axes.flatten()): filled = i % 2 == 0. extend = ['neither', 'min', 'max', 'both'][i // 2] if filled: # If filled, we have 3 colors with no extension, # 4 colors with one extension, and 5 colors with both extensions first_color = 1 if extend in ['max', 'neither'] else None last_color = -1 if extend in ['min', 'neither'] else None c = ax.contourf(data, colors=colors[first_color:last_color], levels=levels, extend=extend) else: # If not filled, we have 4 levels and 4 colors c = ax.contour(data, colors=colors[:-1], levels=levels, extend=extend) plt.colorbar(c, ax=ax) @image_comparison(baseline_images=['contour_datetime_axis'], extensions=['png'], remove_text=False) def test_contour_datetime_axis(): fig = plt.figure() fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15) base = datetime.datetime(2013, 1, 1) x = np.array([base + datetime.timedelta(days=d) for d in range(20)]) y = np.arange(20) z1, z2 = np.meshgrid(np.arange(20), np.arange(20)) z = z1 * z2 plt.subplot(221) plt.contour(x, y, z) plt.subplot(222) plt.contourf(x, y, z) x = np.repeat(x[np.newaxis], 20, axis=0) y = np.repeat(y[:, np.newaxis], 20, axis=1) plt.subplot(223) plt.contour(x, y, z) plt.subplot(224) plt.contourf(x, y, z) for ax in fig.get_axes(): for label in ax.get_xticklabels(): label.set_ha('right') label.set_rotation(30) @image_comparison(baseline_images=['contour_test_label_transforms'], extensions=['png'], remove_text=True) def test_labels(): # Adapted from pylab_examples example code: contour_demo.py # see issues #2475, #2843, and #2818 for explanation delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / (2 * np.pi * 0.5 * 1.5)) # difference of Gaussians Z = 10.0 * (Z2 - Z1) fig, ax = plt.subplots(1, 1) CS = ax.contour(X, Y, Z) disp_units = [(216, 177), (359, 290), (521, 406)] data_units = [(-2, .5), (0, -1.5), (2.8, 1)] CS.clabel() for x, y in data_units: CS.add_label_near(x, y, inline=True, transform=None) for x, y in disp_units: CS.add_label_near(x, y, inline=True, transform=False) @image_comparison(baseline_images=['contour_corner_mask_False', 'contour_corner_mask_True'], extensions=['png'], remove_text=True) def test_corner_mask(): n = 60 mask_level = 0.95 noise_amp = 1.0 np.random.seed([1]) x, y = np.meshgrid(np.linspace(0, 2.0, n), np.linspace(0, 2.0, n)) z = np.cos(7*x)*np.sin(8*y) + noise_amp*np.random.rand(n, n) mask = np.where(np.random.rand(n, n) >= mask_level, True, False) z = np.ma.array(z, mask=mask) for corner_mask in [False, True]: fig = plt.figure() plt.contourf(z, corner_mask=corner_mask) def test_contourf_decreasing_levels(): # github issue 5477. z = [[0.1, 0.3], [0.5, 0.7]] plt.figure() with pytest.raises(ValueError): plt.contourf(z, [1.0, 0.0]) def test_contourf_symmetric_locator(): # github issue 7271 z = np.arange(12).reshape((3, 4)) locator = plt.MaxNLocator(nbins=4, symmetric=True) cs = plt.contourf(z, locator=locator) assert_array_almost_equal(cs.levels, np.linspace(-12, 12, 5)) def test_contour_1x1_array(): # github issue 8197 with pytest.raises(TypeError) as excinfo: plt.contour([[0]]) excinfo.match(r'Input z must be at least a 2x2 array.') with pytest.raises(TypeError) as excinfo: plt.contour([0], [0], [[0]]) excinfo.match(r'Input z must be at least a 2x2 array.') def test_internal_cpp_api(): # Following github issue 8197. import matplotlib._contour as _contour with pytest.raises(TypeError) as excinfo: qcg = _contour.QuadContourGenerator() excinfo.match(r'function takes exactly 6 arguments \(0 given\)') with pytest.raises(ValueError) as excinfo: qcg = _contour.QuadContourGenerator(1, 2, 3, 4, 5, 6) excinfo.match(r'Expected 2-dimensional array, got 0') with pytest.raises(ValueError) as excinfo: qcg = _contour.QuadContourGenerator([[0]], [[0]], [[]], None, True, 0) excinfo.match(r'x, y and z must all be 2D arrays with the same dimensions') with pytest.raises(ValueError) as excinfo: qcg = _contour.QuadContourGenerator([[0]], [[0]], [[0]], None, True, 0) excinfo.match(r'x, y and z must all be at least 2x2 arrays') arr = [[0, 1], [2, 3]] with pytest.raises(ValueError) as excinfo: qcg = _contour.QuadContourGenerator(arr, arr, arr, [[0]], True, 0) excinfo.match(r'If mask is set it must be a 2D array with the same ' + r'dimensions as x.') qcg = _contour.QuadContourGenerator(arr, arr, arr, None, True, 0) with pytest.raises(ValueError) as excinfo: qcg.create_filled_contour(1, 0) excinfo.match(r'filled contour levels must be increasing') def test_circular_contour_warning(): # Check that almost circular contours don't throw a warning with pytest.warns(None) as record: x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4)) r = np.sqrt(x ** 2 + y ** 2) plt.figure() cs = plt.contour(x, y, r) plt.clabel(cs) assert len(record) == 0
11,061
28.897297
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_bbox_tight.py
from __future__ import absolute_import, division, print_function import numpy as np from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib.path as mpath import matplotlib.patches as mpatches from matplotlib.ticker import FuncFormatter @image_comparison(baseline_images=['bbox_inches_tight'], remove_text=True, savefig_kwarg=dict(bbox_inches='tight')) def test_bbox_inches_tight(): #: Test that a figure saved using bbox_inches='tight' is clipped correctly data = [[66386, 174296, 75131, 577908, 32015], [58230, 381139, 78045, 99308, 160454], [89135, 80552, 152558, 497981, 603535], [78415, 81858, 150656, 193263, 69638], [139361, 331509, 343164, 781380, 52269]] colLabels = rowLabels = [''] * 5 rows = len(data) ind = np.arange(len(colLabels)) + 0.3 # the x locations for the groups cellText = [] width = 0.4 # the width of the bars yoff = np.zeros(len(colLabels)) # the bottom values for stacked bar chart fig, ax = plt.subplots(1, 1) for row in range(rows): ax.bar(ind, data[row], width, bottom=yoff, color='b') yoff = yoff + data[row] cellText.append(['']) plt.xticks([]) plt.legend([''] * 5, loc=(1.2, 0.2)) # Add a table at the bottom of the axes cellText.reverse() the_table = plt.table(cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, loc='bottom') @image_comparison(baseline_images=['bbox_inches_tight_suptile_legend'], remove_text=False, savefig_kwarg={'bbox_inches': 'tight'}) def test_bbox_inches_tight_suptile_legend(): plt.plot(np.arange(10), label='a straight line') plt.legend(bbox_to_anchor=(0.9, 1), loc=2, ) plt.title('Axis title') plt.suptitle('Figure title') # put an extra long y tick on to see that the bbox is accounted for def y_formatter(y, pos): if int(y) == 4: return 'The number 4' else: return str(y) plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter)) plt.xlabel('X axis') @image_comparison(baseline_images=['bbox_inches_tight_clipping'], remove_text=True, savefig_kwarg={'bbox_inches': 'tight'}) def test_bbox_inches_tight_clipping(): # tests bbox clipping on scatter points, and path clipping on a patch # to generate an appropriately tight bbox plt.scatter(np.arange(10), np.arange(10)) ax = plt.gca() ax.set_xlim([0, 5]) ax.set_ylim([0, 5]) # make a massive rectangle and clip it with a path patch = mpatches.Rectangle([-50, -50], 100, 100, transform=ax.transData, facecolor='blue', alpha=0.5) path = mpath.Path.unit_regular_star(5).deepcopy() path.vertices *= 0.25 patch.set_clip_path(path, transform=ax.transAxes) plt.gcf().artists.append(patch) @image_comparison(baseline_images=['bbox_inches_tight_raster'], remove_text=True, savefig_kwarg={'bbox_inches': 'tight'}) def test_bbox_inches_tight_raster(): """Test rasterization with tight_layout""" fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1.0, 2.0], rasterized=True)
3,323
35.527473
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backend_pgf.py
# -*- encoding: utf-8 -*- from __future__ import absolute_import, division, print_function import os import shutil import numpy as np import pytest import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.compat import subprocess from matplotlib.testing.compare import compare_images, ImageComparisonFailure from matplotlib.testing.decorators import image_comparison, _image_directories baseline_dir, result_dir = _image_directories(lambda: 'dummy func') def check_for(texsystem): header = """ \\documentclass{minimal} \\usepackage{pgf} \\begin{document} \\typeout{pgfversion=\\pgfversion} \\makeatletter \\@@end """ try: latex = subprocess.Popen([str(texsystem), "-halt-on-error"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = latex.communicate(header.encode("utf8")) except OSError: return False return latex.returncode == 0 needs_xelatex = pytest.mark.skipif(not check_for('xelatex'), reason='xelatex + pgf is required') needs_pdflatex = pytest.mark.skipif(not check_for('pdflatex'), reason='pdflatex + pgf is required') def compare_figure(fname, savefig_kwargs={}, tol=0): actual = os.path.join(result_dir, fname) plt.savefig(actual, **savefig_kwargs) expected = os.path.join(result_dir, "expected_%s" % fname) shutil.copyfile(os.path.join(baseline_dir, fname), expected) err = compare_images(expected, actual, tol=tol) if err: raise ImageComparisonFailure(err) def create_figure(): plt.figure() x = np.linspace(0, 1, 15) # line plot plt.plot(x, x ** 2, "b-") # marker plt.plot(x, 1 - x**2, "g>") # filled paths and patterns plt.fill_between([0., .4], [.4, 0.], hatch='//', facecolor="lightgray", edgecolor="red") plt.fill([3, 3, .8, .8, 3], [2, -2, -2, 0, 2], "b") # text and typesetting plt.plot([0.9], [0.5], "ro", markersize=3) plt.text(0.9, 0.5, u'unicode (ü, °, µ) and math ($\\mu_i = x_i^2$)', ha='right', fontsize=20) plt.ylabel('sans-serif, blue, $\\frac{\\sqrt{x}}{y^2}$..', family='sans-serif', color='blue') plt.xlim(0, 1) plt.ylim(0, 1) # test compiling a figure to pdf with xelatex @needs_xelatex @pytest.mark.backend('pgf') @image_comparison(baseline_images=['pgf_xelatex'], extensions=['pdf'], style='default') def test_xelatex(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} mpl.rcParams.update(rc_xelatex) create_figure() # test compiling a figure to pdf with pdflatex @needs_pdflatex @pytest.mark.backend('pgf') @image_comparison(baseline_images=['pgf_pdflatex'], extensions=['pdf'], style='default') def test_pdflatex(): import os if os.environ.get('APPVEYOR', False): pytest.xfail("pdflatex test does not work on appveyor due to missing " "LaTeX fonts") rc_pdflatex = {'font.family': 'serif', 'pgf.rcfonts': False, 'pgf.texsystem': 'pdflatex', 'pgf.preamble': ['\\usepackage[utf8x]{inputenc}', '\\usepackage[T1]{fontenc}']} mpl.rcParams.update(rc_pdflatex) create_figure() # test updating the rc parameters for each figure @needs_xelatex @needs_pdflatex @pytest.mark.style('default') @pytest.mark.backend('pgf') def test_rcupdate(): rc_sets = [] rc_sets.append({'font.family': 'sans-serif', 'font.size': 30, 'figure.subplot.left': .2, 'lines.markersize': 10, 'pgf.rcfonts': False, 'pgf.texsystem': 'xelatex'}) rc_sets.append({'font.family': 'monospace', 'font.size': 10, 'figure.subplot.left': .1, 'lines.markersize': 20, 'pgf.rcfonts': False, 'pgf.texsystem': 'pdflatex', 'pgf.preamble': ['\\usepackage[utf8x]{inputenc}', '\\usepackage[T1]{fontenc}', '\\usepackage{sfmath}']}) tol = (6, 0) original_params = mpl.rcParams.copy() for i, rc_set in enumerate(rc_sets): mpl.rcParams.clear() mpl.rcParams.update(original_params) mpl.rcParams.update(rc_set) create_figure() compare_figure('pgf_rcupdate%d.pdf' % (i + 1), tol=tol[i]) # test backend-side clipping, since large numbers are not supported by TeX @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') def test_pathclip(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} mpl.rcParams.update(rc_xelatex) plt.figure() plt.plot([0., 1e100], [0., 1e100]) plt.xlim(0, 1) plt.ylim(0, 1) # this test passes if compiling/saving to pdf works (no image comparison) plt.savefig(os.path.join(result_dir, "pgf_pathclip.pdf")) # test mixed mode rendering @needs_xelatex @pytest.mark.backend('pgf') @image_comparison(baseline_images=['pgf_mixedmode'], extensions=['pdf'], style='default') def test_mixedmode(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} mpl.rcParams.update(rc_xelatex) Y, X = np.ogrid[-1:1:40j, -1:1:40j] plt.figure() plt.pcolor(X**2 + Y**2).set_rasterized(True) # test bbox_inches clipping @needs_xelatex @pytest.mark.style('default') @pytest.mark.backend('pgf') def test_bbox_inches(): rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} mpl.rcParams.update(rc_xelatex) Y, X = np.ogrid[-1:1:40j, -1:1:40j] fig = plt.figure() ax1 = fig.add_subplot(121) ax1.plot(range(5)) ax2 = fig.add_subplot(122) ax2.plot(range(5)) plt.tight_layout() bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox}, tol=0)
6,218
30.409091
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_afm.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from six import BytesIO import matplotlib.afm as afm AFM_TEST_DATA = b"""StartFontMetrics 2.0 Comment Comments are ignored. Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 FontName MyFont-Bold EncodingScheme FontSpecific FullName My Font Bold FamilyName Test Fonts Weight Bold ItalicAngle 0.0 IsFixedPitch false UnderlinePosition -100 UnderlineThickness 50 Version 001.000 Notice Copyright (c) 2017 No one. FontBBox 0 -321 1234 369 StartCharMetrics 3 C 0 ; WX 250 ; N space ; B 0 0 0 0 ; C 42 ; WX 1141 ; N foo ; B 40 60 800 360 ; C 99 ; WX 583 ; N bar ; B 40 -10 543 210 ; EndCharMetrics EndFontMetrics """ def test_nonascii_str(): # This tests that we also decode bytes as utf-8 properly. # Else, font files with non ascii characters fail to load. inp_str = u"привет" byte_str = inp_str.encode("utf8") ret = afm._to_str(byte_str) assert ret == inp_str def test_parse_header(): fh = BytesIO(AFM_TEST_DATA) header = afm._parse_header(fh) assert header == { b'StartFontMetrics': 2.0, b'FontName': 'MyFont-Bold', b'EncodingScheme': 'FontSpecific', b'FullName': 'My Font Bold', b'FamilyName': 'Test Fonts', b'Weight': 'Bold', b'ItalicAngle': 0.0, b'IsFixedPitch': False, b'UnderlinePosition': -100, b'UnderlineThickness': 50, b'Version': '001.000', b'Notice': 'Copyright (c) 2017 No one.', b'FontBBox': [0, -321, 1234, 369], b'StartCharMetrics': 3, } def test_parse_char_metrics(): fh = BytesIO(AFM_TEST_DATA) afm._parse_header(fh) # position metrics = afm._parse_char_metrics(fh) assert metrics == ( {0: (250.0, 'space', [0, 0, 0, 0]), 42: (1141.0, 'foo', [40, 60, 800, 360]), 99: (583.0, 'bar', [40, -10, 543, 210]), }, {'space': (250.0, [0, 0, 0, 0]), 'foo': (1141.0, [40, 60, 800, 360]), 'bar': (583.0, [40, -10, 543, 210]), }) def test_get_familyname_guessed(): fh = BytesIO(AFM_TEST_DATA) fm = afm.AFM(fh) del fm._header[b'FamilyName'] # remove FamilyName, so we have to guess assert fm.get_familyname() == 'My Font'
2,281
26.166667
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_type1font.py
from __future__ import absolute_import, division, print_function import six import matplotlib.type1font as t1f import os.path import difflib def test_Type1Font(): filename = os.path.join(os.path.dirname(__file__), 'cmr10.pfb') font = t1f.Type1Font(filename) slanted = font.transform({'slant': 1}) condensed = font.transform({'extend': 0.5}) with open(filename, 'rb') as fd: rawdata = fd.read() assert font.parts[0] == rawdata[0x0006:0x10c5] assert font.parts[1] == rawdata[0x10cb:0x897f] assert font.parts[2] == rawdata[0x8985:0x8ba6] assert font.parts[1:] == slanted.parts[1:] assert font.parts[1:] == condensed.parts[1:] differ = difflib.Differ() diff = list(differ.compare( font.parts[0].decode('latin-1').splitlines(), slanted.parts[0].decode('latin-1').splitlines())) for line in ( # Removes UniqueID '- FontDirectory/CMR10 known{/CMR10 findfont dup/UniqueID known{dup', '+ FontDirectory/CMR10 known{/CMR10 findfont dup', # Changes the font name '- /FontName /CMR10 def', '+ /FontName /CMR10_Slant_1000 def', # Alters FontMatrix '- /FontMatrix [0.001 0 0 0.001 0 0 ]readonly def', '+ /FontMatrix [0.001 0.0 0.001 0.001 0.0 0.0]readonly def', # Alters ItalicAngle '- /ItalicAngle 0 def', '+ /ItalicAngle -45.0 def'): assert line in diff, 'diff to slanted font must contain %s' % line diff = list(differ.compare(font.parts[0].decode('latin-1').splitlines(), condensed.parts[0].decode('latin-1').splitlines())) for line in ( # Removes UniqueID '- FontDirectory/CMR10 known{/CMR10 findfont dup/UniqueID known{dup', '+ FontDirectory/CMR10 known{/CMR10 findfont dup', # Changes the font name '- /FontName /CMR10 def', '+ /FontName /CMR10_Extend_500 def', # Alters FontMatrix '- /FontMatrix [0.001 0 0 0.001 0 0 ]readonly def', '+ /FontMatrix [0.0005 0.0 0.0 0.001 0.0 0.0]readonly def'): assert line in diff, 'diff to condensed font must contain %s' % line
2,175
38.563636
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_agg.py
from __future__ import absolute_import, division, print_function import io import numpy as np from numpy.testing import assert_array_almost_equal import pytest from matplotlib import ( collections, path, pyplot as plt, transforms as mtransforms, rcParams) from matplotlib.image import imread from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.testing.decorators import image_comparison def test_repeated_save_with_alpha(): # We want an image which has a background color of bluish green, with an # alpha of 0.25. fig = Figure([1, 0.4]) canvas = FigureCanvas(fig) fig.set_facecolor((0, 1, 0.4)) fig.patch.set_alpha(0.25) # The target color is fig.patch.get_facecolor() buf = io.BytesIO() fig.savefig(buf, facecolor=fig.get_facecolor(), edgecolor='none') # Save the figure again to check that the # colors don't bleed from the previous renderer. buf.seek(0) fig.savefig(buf, facecolor=fig.get_facecolor(), edgecolor='none') # Check the first pixel has the desired color & alpha # (approx: 0, 1.0, 0.4, 0.25) buf.seek(0) assert_array_almost_equal(tuple(imread(buf)[0, 0]), (0.0, 1.0, 0.4, 0.250), decimal=3) def test_large_single_path_collection(): buff = io.BytesIO() # Generates a too-large single path in a path collection that # would cause a segfault if the draw_markers optimization is # applied. f, ax = plt.subplots() collection = collections.PathCollection( [path.Path([[-10, 5], [10, 5], [10, -5], [-10, -5], [-10, 5]])]) ax.add_artist(collection) ax.set_xlim(10**-3, 1) plt.savefig(buff) def test_marker_with_nan(): # This creates a marker with nans in it, which was segfaulting the # Agg backend (see #3722) fig, ax = plt.subplots(1) steps = 1000 data = np.arange(steps) ax.semilogx(data) ax.fill_between(data, data*0.8, data*1.2) buf = io.BytesIO() fig.savefig(buf, format='png') def test_long_path(): buff = io.BytesIO() fig, ax = plt.subplots() np.random.seed(0) points = np.random.rand(70000) ax.plot(points) fig.savefig(buff, format='png') @image_comparison(baseline_images=['agg_filter'], extensions=['png'], remove_text=True) def test_agg_filter(): def smooth1d(x, window_len): s = np.r_[2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]] w = np.hanning(window_len) y = np.convolve(w/w.sum(), s, mode='same') return y[window_len-1:-window_len+1] def smooth2d(A, sigma=3): window_len = max(int(sigma), 3)*2 + 1 A1 = np.array([smooth1d(x, window_len) for x in np.asarray(A)]) A2 = np.transpose(A1) A3 = np.array([smooth1d(x, window_len) for x in A2]) A4 = np.transpose(A3) return A4 class BaseFilter(object): def prepare_image(self, src_image, dpi, pad): ny, nx, depth = src_image.shape padded_src = np.zeros([pad*2 + ny, pad*2 + nx, depth], dtype="d") padded_src[pad:-pad, pad:-pad, :] = src_image[:, :, :] return padded_src # , tgt_image def get_pad(self, dpi): return 0 def __call__(self, im, dpi): pad = self.get_pad(dpi) padded_src = self.prepare_image(im, dpi, pad) tgt_image = self.process_image(padded_src, dpi) return tgt_image, -pad, -pad class OffsetFilter(BaseFilter): def __init__(self, offsets=None): if offsets is None: self.offsets = (0, 0) else: self.offsets = offsets def get_pad(self, dpi): return int(max(*self.offsets)/72.*dpi) def process_image(self, padded_src, dpi): ox, oy = self.offsets a1 = np.roll(padded_src, int(ox/72.*dpi), axis=1) a2 = np.roll(a1, -int(oy/72.*dpi), axis=0) return a2 class GaussianFilter(BaseFilter): "simple gauss filter" def __init__(self, sigma, alpha=0.5, color=None): self.sigma = sigma self.alpha = alpha if color is None: self.color = (0, 0, 0) else: self.color = color def get_pad(self, dpi): return int(self.sigma*3/72.*dpi) def process_image(self, padded_src, dpi): tgt_image = np.zeros_like(padded_src) aa = smooth2d(padded_src[:, :, -1]*self.alpha, self.sigma/72.*dpi) tgt_image[:, :, -1] = aa tgt_image[:, :, :-1] = self.color return tgt_image class DropShadowFilter(BaseFilter): def __init__(self, sigma, alpha=0.3, color=None, offsets=None): self.gauss_filter = GaussianFilter(sigma, alpha, color) self.offset_filter = OffsetFilter(offsets) def get_pad(self, dpi): return max(self.gauss_filter.get_pad(dpi), self.offset_filter.get_pad(dpi)) def process_image(self, padded_src, dpi): t1 = self.gauss_filter.process_image(padded_src, dpi) t2 = self.offset_filter.process_image(t1, dpi) return t2 fig = plt.figure() ax = fig.add_subplot(111) # draw lines l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-", mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1") l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-", mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1") gauss = DropShadowFilter(4) for l in [l1, l2]: # draw shadows with same lines with slight offset. xx = l.get_xdata() yy = l.get_ydata() shadow, = ax.plot(xx, yy) shadow.update_from(l) # offset transform ot = mtransforms.offset_copy(l.get_transform(), ax.figure, x=4.0, y=-6.0, units='points') shadow.set_transform(ot) # adjust zorder of the shadow lines so that it is drawn below the # original lines shadow.set_zorder(l.get_zorder() - 0.5) shadow.set_agg_filter(gauss) shadow.set_rasterized(True) # to support mixed-mode renderers ax.set_xlim(0., 1.) ax.set_ylim(0., 1.) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) def test_too_large_image(): fig = plt.figure(figsize=(300, 1000)) buff = io.BytesIO() with pytest.raises(ValueError): fig.savefig(buff) def test_chunksize(): x = range(200) # Test without chunksize fig, ax = plt.subplots() ax.plot(x, np.sin(x)) fig.canvas.draw() # Test with chunksize fig, ax = plt.subplots() rcParams['agg.path.chunksize'] = 105 ax.plot(x, np.sin(x)) fig.canvas.draw() @pytest.mark.backend('Agg') def test_jpeg_dpi(): Image = pytest.importorskip("PIL.Image") # Check that dpi is set correctly in jpg files. plt.plot([0, 1, 2], [0, 1, 0]) buf = io.BytesIO() plt.savefig(buf, format="jpg", dpi=200) im = Image.open(buf) assert im.info['dpi'] == (200, 200)
7,365
29.188525
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_colorbar.py
from __future__ import absolute_import, division, print_function import numpy as np import pytest from matplotlib import rc_context from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib.colors import BoundaryNorm, LogNorm from matplotlib.cm import get_cmap from matplotlib.colorbar import ColorbarBase def _get_cmap_norms(): """ Define a colormap and appropriate norms for each of the four possible settings of the extend keyword. Helper function for _colorbar_extension_shape and colorbar_extension_length. """ # Create a color map and specify the levels it represents. cmap = get_cmap("RdBu", lut=5) clevs = [-5., -2.5, -.5, .5, 1.5, 3.5] # Define norms for the color maps. norms = dict() norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1) norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1) norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1) norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1) return cmap, norms def _colorbar_extension_shape(spacing): ''' Produce 4 colorbars with rectangular extensions for either uniform or proportional spacing. Helper function for test_colorbar_extension_shape. ''' # Get a colormap and appropriate norms for each extension type. cmap, norms = _get_cmap_norms() # Create a figure and adjust whitespace for subplots. fig = plt.figure() fig.subplots_adjust(hspace=4) for i, extension_type in enumerate(('neither', 'min', 'max', 'both')): # Get the appropriate norm and use it to get colorbar boundaries. norm = norms[extension_type] boundaries = values = norm.boundaries # Create a subplot. cax = fig.add_subplot(4, 1, i + 1) # Generate the colorbar. cb = ColorbarBase(cax, cmap=cmap, norm=norm, boundaries=boundaries, values=values, extend=extension_type, extendrect=True, orientation='horizontal', spacing=spacing) # Turn off text and ticks. cax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False) # Return the figure to the caller. return fig def _colorbar_extension_length(spacing): ''' Produce 12 colorbars with variable length extensions for either uniform or proportional spacing. Helper function for test_colorbar_extension_length. ''' # Get a colormap and appropriate norms for each extension type. cmap, norms = _get_cmap_norms() # Create a figure and adjust whitespace for subplots. fig = plt.figure() fig.subplots_adjust(hspace=.6) for i, extension_type in enumerate(('neither', 'min', 'max', 'both')): # Get the appropriate norm and use it to get colorbar boundaries. norm = norms[extension_type] boundaries = values = norm.boundaries for j, extendfrac in enumerate((None, 'auto', 0.1)): # Create a subplot. cax = fig.add_subplot(12, 1, i*3 + j + 1) # Generate the colorbar. ColorbarBase(cax, cmap=cmap, norm=norm, boundaries=boundaries, values=values, extend=extension_type, extendfrac=extendfrac, orientation='horizontal', spacing=spacing) # Turn off text and ticks. cax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False) # Return the figure to the caller. return fig @image_comparison( baseline_images=['colorbar_extensions_shape_uniform', 'colorbar_extensions_shape_proportional'], extensions=['png']) def test_colorbar_extension_shape(): '''Test rectangular colorbar extensions.''' # Create figures for uniform and proportionally spaced colorbars. _colorbar_extension_shape('uniform') _colorbar_extension_shape('proportional') @image_comparison(baseline_images=['colorbar_extensions_uniform', 'colorbar_extensions_proportional'], extensions=['png']) def test_colorbar_extension_length(): '''Test variable length colorbar extensions.''' # Create figures for uniform and proportionally spaced colorbars. _colorbar_extension_length('uniform') _colorbar_extension_length('proportional') @image_comparison(baseline_images=['cbar_with_orientation', 'cbar_locationing', 'double_cbar', 'cbar_sharing', ], extensions=['png'], remove_text=True, savefig_kwarg={'dpi': 40}) def test_colorbar_positioning(): data = np.arange(1200).reshape(30, 40) levels = [0, 200, 400, 600, 800, 1000, 1200] # ------------------- plt.figure() plt.contourf(data, levels=levels) plt.colorbar(orientation='horizontal', use_gridspec=False) locations = ['left', 'right', 'top', 'bottom'] plt.figure() for i, location in enumerate(locations): plt.subplot(2, 2, i + 1) plt.contourf(data, levels=levels) plt.colorbar(location=location, use_gridspec=False) # ------------------- plt.figure() # make some other data (random integers) data_2nd = np.array([[2, 3, 2, 3], [1.5, 2, 2, 3], [2, 3, 3, 4]]) # make the random data expand to the shape of the main data data_2nd = np.repeat(np.repeat(data_2nd, 10, axis=1), 10, axis=0) color_mappable = plt.contourf(data, levels=levels, extend='both') # test extend frac here hatch_mappable = plt.contourf(data_2nd, levels=[1, 2, 3], colors='none', hatches=['/', 'o', '+'], extend='max') plt.contour(hatch_mappable, colors='black') plt.colorbar(color_mappable, location='left', label='variable 1', use_gridspec=False) plt.colorbar(hatch_mappable, location='right', label='variable 2', use_gridspec=False) # ------------------- plt.figure() ax1 = plt.subplot(211, anchor='NE', aspect='equal') plt.contourf(data, levels=levels) ax2 = plt.subplot(223) plt.contourf(data, levels=levels) ax3 = plt.subplot(224) plt.contourf(data, levels=levels) plt.colorbar(ax=[ax2, ax3, ax1], location='right', pad=0.0, shrink=0.5, panchor=False, use_gridspec=False) plt.colorbar(ax=[ax2, ax3, ax1], location='left', shrink=0.5, panchor=False, use_gridspec=False) plt.colorbar(ax=[ax1], location='bottom', panchor=False, anchor=(0.8, 0.5), shrink=0.6, use_gridspec=False) @image_comparison(baseline_images=['cbar_with_subplots_adjust'], extensions=['png'], remove_text=True, savefig_kwarg={'dpi': 40}) def test_gridspec_make_colorbar(): plt.figure() data = np.arange(1200).reshape(30, 40) levels = [0, 200, 400, 600, 800, 1000, 1200] plt.subplot(121) plt.contourf(data, levels=levels) plt.colorbar(use_gridspec=True, orientation='vertical') plt.subplot(122) plt.contourf(data, levels=levels) plt.colorbar(use_gridspec=True, orientation='horizontal') plt.subplots_adjust(top=0.95, right=0.95, bottom=0.2, hspace=0.25) @image_comparison(baseline_images=['colorbar_single_scatter'], extensions=['png'], remove_text=True, savefig_kwarg={'dpi': 40}) def test_colorbar_single_scatter(): # Issue #2642: if a path collection has only one entry, # the norm scaling within the colorbar must ensure a # finite range, otherwise a zero denominator will occur in _locate. plt.figure() x = np.arange(4) y = x.copy() z = np.ma.masked_greater(np.arange(50, 54), 50) cmap = plt.get_cmap('jet', 16) cs = plt.scatter(x, y, z, c=z, cmap=cmap) plt.colorbar(cs) @pytest.mark.parametrize('use_gridspec', [False, True], ids=['no gridspec', 'with gridspec']) def test_remove_from_figure(use_gridspec): """ Test `remove_from_figure` with the specified ``use_gridspec`` setting """ fig = plt.figure() ax = fig.add_subplot(111) sc = ax.scatter([1, 2], [3, 4], cmap="spring") sc.set_array(np.array([5, 6])) pre_figbox = np.array(ax.figbox) cb = fig.colorbar(sc, use_gridspec=use_gridspec) fig.subplots_adjust() cb.remove() fig.subplots_adjust() post_figbox = np.array(ax.figbox) assert (pre_figbox == post_figbox).all() def test_colorbarbase(): # smoke test from #3805 ax = plt.gca() ColorbarBase(ax, plt.cm.bone) @image_comparison( baseline_images=['colorbar_closed_patch'], remove_text=True) def test_colorbar_closed_patch(): fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_axes([0.05, 0.85, 0.9, 0.1]) ax2 = fig.add_axes([0.1, 0.65, 0.75, 0.1]) ax3 = fig.add_axes([0.05, 0.45, 0.9, 0.1]) ax4 = fig.add_axes([0.05, 0.25, 0.9, 0.1]) ax5 = fig.add_axes([0.05, 0.05, 0.9, 0.1]) cmap = get_cmap("RdBu", lut=5) im = ax1.pcolormesh(np.linspace(0, 10, 16).reshape((4, 4)), cmap=cmap) values = np.linspace(0, 10, 5) with rc_context({'axes.linewidth': 16}): plt.colorbar(im, cax=ax2, cmap=cmap, orientation='horizontal', extend='both', extendfrac=0.5, values=values) plt.colorbar(im, cax=ax3, cmap=cmap, orientation='horizontal', extend='both', values=values) plt.colorbar(im, cax=ax4, cmap=cmap, orientation='horizontal', extend='both', extendrect=True, values=values) plt.colorbar(im, cax=ax5, cmap=cmap, orientation='horizontal', extend='neither', values=values) def test_colorbar_ticks(): # test fix for #5673 fig, ax = plt.subplots() x = np.arange(-3.0, 4.001) y = np.arange(-4.0, 3.001) X, Y = np.meshgrid(x, y) Z = X * Y clevs = np.array([-12, -5, 0, 5, 12], dtype=float) colors = ['r', 'g', 'b', 'c'] cs = ax.contourf(X, Y, Z, clevs, colors=colors) cbar = fig.colorbar(cs, ax=ax, extend='neither', orientation='horizontal', ticks=clevs) assert len(cbar.ax.xaxis.get_ticklocs()) == len(clevs) def test_colorbar_get_ticks(): # test feature for #5792 plt.figure() data = np.arange(1200).reshape(30, 40) levels = [0, 200, 400, 600, 800, 1000, 1200] plt.subplot() plt.contourf(data, levels=levels) # testing getter for user set ticks userTicks = plt.colorbar(ticks=[0, 600, 1200]) assert userTicks.get_ticks().tolist() == [0, 600, 1200] # testing for getter after calling set_ticks userTicks.set_ticks([600, 700, 800]) assert userTicks.get_ticks().tolist() == [600, 700, 800] # testing for getter after calling set_ticks with some ticks out of bounds userTicks.set_ticks([600, 1300, 1400, 1500]) assert userTicks.get_ticks().tolist() == [600] # testing getter when no ticks are assigned defTicks = plt.colorbar(orientation='horizontal') assert defTicks.get_ticks().tolist() == levels def test_colorbar_lognorm_extension(): # Test that colorbar with lognorm is extended correctly f, ax = plt.subplots() cb = ColorbarBase(ax, norm=LogNorm(vmin=0.1, vmax=1000.0), orientation='vertical', extend='both') assert cb._values[0] >= 0.0 def test_colorbar_axes_kw(): # test fix for #8493: This does only test, that axes-related keywords pass # and do not raise an exception. plt.figure() plt.imshow(([[1, 2], [3, 4]])) plt.colorbar(orientation='horizontal', fraction=0.2, pad=0.2, shrink=0.5, aspect=10, anchor=(0., 0.), panchor=(0., 1.))
11,847
36.375394
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_subplots.py
from __future__ import absolute_import, division, print_function import warnings import numpy import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison import pytest def check_shared(axs, x_shared, y_shared): """ x_shared and y_shared are n x n boolean matrices; entry (i, j) indicates whether the x (or y) axes of subplots i and j should be shared. """ shared = [axs[0]._shared_x_axes, axs[0]._shared_y_axes] for (i1, ax1), (i2, ax2), (i3, (name, shared)) in zip( enumerate(axs), enumerate(axs), enumerate(zip("xy", [x_shared, y_shared]))): if i2 <= i1: continue assert shared[i3].joined(ax1, ax2) == shared[i1, i2], \ "axes %i and %i incorrectly %ssharing %s axis" % ( i1, i2, "not " if shared[i1, i2] else "", name) def check_visible(axs, x_visible, y_visible): def tostr(v): return "invisible" if v else "visible" for (ax, vx, vy) in zip(axs, x_visible, y_visible): for l in ax.get_xticklabels() + [ax.get_xaxis().offsetText]: assert l.get_visible() == vx, \ "X axis was incorrectly %s" % (tostr(vx)) for l in ax.get_yticklabels() + [ax.get_yaxis().offsetText]: assert l.get_visible() == vy, \ "Y axis was incorrectly %s" % (tostr(vy)) def test_shared(): rdim = (4, 4, 2) share = { 'all': numpy.ones(rdim[:2], dtype=bool), 'none': numpy.zeros(rdim[:2], dtype=bool), 'row': numpy.array([ [False, True, False, False], [True, False, False, False], [False, False, False, True], [False, False, True, False]]), 'col': numpy.array([ [False, False, True, False], [False, False, False, True], [True, False, False, False], [False, True, False, False]]), } visible = { 'x': { 'all': [False, False, True, True], 'col': [False, False, True, True], 'row': [True] * 4, 'none': [True] * 4, False: [True] * 4, True: [False, False, True, True], }, 'y': { 'all': [True, False, True, False], 'col': [True] * 4, 'row': [True, False, True, False], 'none': [True] * 4, False: [True] * 4, True: [True, False, True, False], }, } share[False] = share['none'] share[True] = share['all'] # test default f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2) axs = [a1, a2, a3, a4] check_shared(axs, share['none'], share['none']) plt.close(f) # test all option combinations ops = [False, True, 'all', 'none', 'row', 'col'] for xo in ops: for yo in ops: f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=xo, sharey=yo) axs = [a1, a2, a3, a4] check_shared(axs, share[xo], share[yo]) check_visible(axs, visible['x'][xo], visible['y'][yo]) plt.close(f) # test label_outer f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=True, sharey=True) axs = [a1, a2, a3, a4] for ax in axs: ax.label_outer() check_visible(axs, [False, False, True, True], [True, False, True, False]) def test_shared_and_moved(): # test if sharey is on, but then tick_left is called that labels don't # re-appear. Seaborn does this just to be sure yaxis is on left... f, (a1, a2) = plt.subplots(1, 2, sharey=True) check_visible([a2], [True], [False]) a2.yaxis.tick_left() check_visible([a2], [True], [False]) f, (a1, a2) = plt.subplots(2, 1, sharex=True) check_visible([a1], [False], [True]) a2.xaxis.tick_bottom() check_visible([a1], [False], [True]) def test_exceptions(): # TODO should this test more options? with pytest.raises(ValueError): plt.subplots(2, 2, sharex='blah') with pytest.raises(ValueError): plt.subplots(2, 2, sharey='blah') # We filter warnings in this test which are genuine since # the point of this test is to ensure that this raises. with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*sharex argument to subplots', category=UserWarning) with pytest.raises(ValueError): plt.subplots(2, 2, -1) with pytest.raises(ValueError): plt.subplots(2, 2, 0) with pytest.raises(ValueError): plt.subplots(2, 2, 5) @image_comparison(baseline_images=['subplots_offset_text'], remove_text=False) def test_subplots_offsettext(): x = numpy.arange(0, 1e10, 1e9) y = numpy.arange(0, 100, 10)+1e4 fig, axes = plt.subplots(2, 2, sharex='col', sharey='all') axes[0, 0].plot(x, x) axes[1, 0].plot(x, x) axes[0, 1].plot(y, x) axes[1, 1].plot(y, x)
5,110
34.006849
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_streamplot.py
from __future__ import absolute_import, division, print_function import sys import numpy as np from numpy.testing import assert_array_almost_equal import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison import matplotlib.transforms as mtransforms on_win = (sys.platform == 'win32') def velocity_field(): Y, X = np.mgrid[-3:3:100j, -3:3:100j] U = -1 - X**2 + Y V = 1 + X - Y**2 return X, Y, U, V def swirl_velocity_field(): x = np.linspace(-3., 3., 100) y = np.linspace(-3., 3., 100) X, Y = np.meshgrid(x, y) a = 0.1 U = np.cos(a) * (-Y) - np.sin(a) * X V = np.sin(a) * (-Y) + np.cos(a) * X return x, y, U, V @image_comparison(baseline_images=['streamplot_startpoints']) def test_startpoints(): X, Y, U, V = velocity_field() start_x = np.linspace(X.min(), X.max(), 10) start_y = np.linspace(Y.min(), Y.max(), 10) start_points = np.column_stack([start_x, start_y]) plt.streamplot(X, Y, U, V, start_points=start_points) plt.plot(start_x, start_y, 'ok') @image_comparison(baseline_images=['streamplot_colormap'], tol=.02) def test_colormap(): X, Y, U, V = velocity_field() plt.streamplot(X, Y, U, V, color=U, density=0.6, linewidth=2, cmap=plt.cm.autumn) plt.colorbar() @image_comparison(baseline_images=['streamplot_linewidth']) def test_linewidth(): X, Y, U, V = velocity_field() speed = np.sqrt(U*U + V*V) lw = 5*speed/speed.max() df = 25. / 30. # Compatibility factor for old test image plt.streamplot(X, Y, U, V, density=[0.5 * df, 1. * df], color='k', linewidth=lw) @image_comparison(baseline_images=['streamplot_masks_and_nans'], tol=0.04 if on_win else 0) def test_masks_and_nans(): X, Y, U, V = velocity_field() mask = np.zeros(U.shape, dtype=bool) mask[40:60, 40:60] = 1 U[:20, :20] = np.nan U = np.ma.array(U, mask=mask) with np.errstate(invalid='ignore'): plt.streamplot(X, Y, U, V, color=U, cmap=plt.cm.Blues) @image_comparison(baseline_images=['streamplot_maxlength'], extensions=['png']) def test_maxlength(): x, y, U, V = swirl_velocity_field() plt.streamplot(x, y, U, V, maxlength=10., start_points=[[0., 1.5]], linewidth=2, density=2) @image_comparison(baseline_images=['streamplot_direction'], extensions=['png']) def test_direction(): x, y, U, V = swirl_velocity_field() plt.streamplot(x, y, U, V, integration_direction='backward', maxlength=1.5, start_points=[[1.5, 0.]], linewidth=2, density=2) def test_streamplot_limits(): ax = plt.axes() x = np.linspace(-5, 10, 20) y = np.linspace(-2, 4, 10) y, x = np.meshgrid(y, x) trans = mtransforms.Affine2D().translate(25, 32) + ax.transData plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans) # The calculated bounds are approximately the bounds of the original data, # this is because the entire path is taken into account when updating the # datalim. assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6), decimal=1)
3,235
30.72549
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_cycles.py
import warnings from matplotlib.testing.decorators import image_comparison from matplotlib.cbook import MatplotlibDeprecationWarning import matplotlib.pyplot as plt import numpy as np import pytest from cycler import cycler @image_comparison(baseline_images=['color_cycle_basic'], remove_text=True, extensions=['png']) def test_colorcycle_basic(): fig = plt.figure() ax = fig.add_subplot(111) ax.set_prop_cycle(cycler('color', ['r', 'g', 'y'])) xs = np.arange(10) ys = 0.25 * xs + 2 ax.plot(xs, ys, label='red', lw=4) ys = 0.45 * xs + 3 ax.plot(xs, ys, label='green', lw=4) ys = 0.65 * xs + 4 ax.plot(xs, ys, label='yellow', lw=4) ys = 0.85 * xs + 5 ax.plot(xs, ys, label='red2', lw=4) ax.legend(loc='upper left') @image_comparison(baseline_images=['marker_cycle', 'marker_cycle'], remove_text=True, extensions=['png']) def test_marker_cycle(): fig = plt.figure() ax = fig.add_subplot(111) ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + cycler('marker', ['.', '*', 'x'])) xs = np.arange(10) ys = 0.25 * xs + 2 ax.plot(xs, ys, label='red dot', lw=4, ms=16) ys = 0.45 * xs + 3 ax.plot(xs, ys, label='green star', lw=4, ms=16) ys = 0.65 * xs + 4 ax.plot(xs, ys, label='yellow x', lw=4, ms=16) ys = 0.85 * xs + 5 ax.plot(xs, ys, label='red2 dot', lw=4, ms=16) ax.legend(loc='upper left') fig = plt.figure() ax = fig.add_subplot(111) # Test keyword arguments, numpy arrays, and generic iterators ax.set_prop_cycle(c=np.array(['r', 'g', 'y']), marker=iter(['.', '*', 'x'])) xs = np.arange(10) ys = 0.25 * xs + 2 ax.plot(xs, ys, label='red dot', lw=4, ms=16) ys = 0.45 * xs + 3 ax.plot(xs, ys, label='green star', lw=4, ms=16) ys = 0.65 * xs + 4 ax.plot(xs, ys, label='yellow x', lw=4, ms=16) ys = 0.85 * xs + 5 ax.plot(xs, ys, label='red2 dot', lw=4, ms=16) ax.legend(loc='upper left') @image_comparison(baseline_images=['lineprop_cycle_basic'], remove_text=True, extensions=['png']) def test_linestylecycle_basic(): fig = plt.figure() ax = fig.add_subplot(111) ax.set_prop_cycle(cycler('ls', ['-', '--', ':'])) xs = np.arange(10) ys = 0.25 * xs + 2 ax.plot(xs, ys, label='solid', lw=4, color='k') ys = 0.45 * xs + 3 ax.plot(xs, ys, label='dashed', lw=4, color='k') ys = 0.65 * xs + 4 ax.plot(xs, ys, label='dotted', lw=4, color='k') ys = 0.85 * xs + 5 ax.plot(xs, ys, label='solid2', lw=4, color='k') ax.legend(loc='upper left') @image_comparison(baseline_images=['fill_cycle_basic'], remove_text=True, extensions=['png']) def test_fillcycle_basic(): fig = plt.figure() ax = fig.add_subplot(111) ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + cycler('hatch', ['xx', 'O', '|-']) + cycler('linestyle', ['-', '--', ':'])) xs = np.arange(10) ys = 0.25 * xs**.5 + 2 ax.fill(xs, ys, label='red, xx', linewidth=3) ys = 0.45 * xs**.5 + 3 ax.fill(xs, ys, label='green, circle', linewidth=3) ys = 0.65 * xs**.5 + 4 ax.fill(xs, ys, label='yellow, cross', linewidth=3) ys = 0.85 * xs**.5 + 5 ax.fill(xs, ys, label='red2, xx', linewidth=3) ax.legend(loc='upper left') @image_comparison(baseline_images=['fill_cycle_ignore'], remove_text=True, extensions=['png']) def test_fillcycle_ignore(): fig = plt.figure() ax = fig.add_subplot(111) ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']) + cycler('hatch', ['xx', 'O', '|-']) + cycler('marker', ['.', '*', 'D'])) xs = np.arange(10) ys = 0.25 * xs**.5 + 2 # Should not advance the cycler, even though there is an # unspecified property in the cycler "marker". # "marker" is not a Polygon property, and should be ignored. ax.fill(xs, ys, 'r', hatch='xx', label='red, xx') ys = 0.45 * xs**.5 + 3 # Allow the cycler to advance, but specify some properties ax.fill(xs, ys, hatch='O', label='red, circle') ys = 0.65 * xs**.5 + 4 ax.fill(xs, ys, label='green, circle') ys = 0.85 * xs**.5 + 5 ax.fill(xs, ys, label='yellow, cross') ax.legend(loc='upper left') @image_comparison(baseline_images=['property_collision_plot'], remove_text=True, extensions=['png']) def test_property_collision_plot(): fig, ax = plt.subplots() ax.set_prop_cycle('linewidth', [2, 4]) for c in range(1, 4): ax.plot(np.arange(10), c * np.arange(10), lw=0.1, color='k') ax.plot(np.arange(10), 4 * np.arange(10), color='k') ax.plot(np.arange(10), 5 * np.arange(10), color='k') @image_comparison(baseline_images=['property_collision_fill'], remove_text=True, extensions=['png']) def test_property_collision_fill(): fig, ax = plt.subplots() xs = np.arange(10) ys = 0.25 * xs**.5 + 2 ax.set_prop_cycle(linewidth=[2, 3, 4, 5, 6], facecolor='bgcmy') for c in range(1, 4): ax.fill(xs, c * ys, lw=0.1) ax.fill(xs, 4 * ys) ax.fill(xs, 5 * ys) def test_valid_input_forms(): fig, ax = plt.subplots() # These should not raise an error. ax.set_prop_cycle(None) ax.set_prop_cycle(cycler('linewidth', [1, 2])) ax.set_prop_cycle('color', 'rgywkbcm') ax.set_prop_cycle('lw', (1, 2)) ax.set_prop_cycle('linewidth', [1, 2]) ax.set_prop_cycle('linewidth', iter([1, 2])) ax.set_prop_cycle('linewidth', np.array([1, 2])) ax.set_prop_cycle('color', np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])) ax.set_prop_cycle('dashes', [[], [13, 2], [8, 3, 1, 3], [None, None]]) ax.set_prop_cycle(lw=[1, 2], color=['k', 'w'], ls=['-', '--']) ax.set_prop_cycle(lw=np.array([1, 2]), color=np.array(['k', 'w']), ls=np.array(['-', '--'])) assert True def test_cycle_reset(): fig, ax = plt.subplots() # Can't really test a reset because only a cycle object is stored # but we can test the first item of the cycle. prop = next(ax._get_lines.prop_cycler) ax.set_prop_cycle(linewidth=[10, 9, 4]) assert prop != next(ax._get_lines.prop_cycler) ax.set_prop_cycle(None) got = next(ax._get_lines.prop_cycler) assert prop == got fig, ax = plt.subplots() # Need to double-check the old set/get_color_cycle(), too with warnings.catch_warnings(): warnings.simplefilter("ignore", MatplotlibDeprecationWarning) prop = next(ax._get_lines.prop_cycler) ax.set_color_cycle(['c', 'm', 'y', 'k']) assert prop != next(ax._get_lines.prop_cycler) ax.set_color_cycle(None) got = next(ax._get_lines.prop_cycler) assert prop == got def test_invalid_input_forms(): fig, ax = plt.subplots() with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(1) with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle([1, 2]) with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('color', 'fish') with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('linewidth', 1) with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('linewidth', {'1': 1, '2': 2}) with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(linewidth=1, color='r') with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('foobar', [1, 2]) with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(foobar=[1, 2]) with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(cycler(foobar=[1, 2])) with pytest.raises(ValueError): ax.set_prop_cycle(cycler(color='rgb', c='cmy'))
7,921
34.524664
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_tightlayout.py
from __future__ import absolute_import, division, print_function import six import warnings import numpy as np from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea from matplotlib.patches import Rectangle def example_plot(ax, fontsize=12): ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) @image_comparison(baseline_images=['tight_layout1']) def test_tight_layout1(): 'Test tight_layout for a single subplot' fig = plt.figure() ax = fig.add_subplot(111) example_plot(ax, fontsize=24) plt.tight_layout() @image_comparison(baseline_images=['tight_layout2']) def test_tight_layout2(): 'Test tight_layout for multiple subplots' fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout() @image_comparison(baseline_images=['tight_layout3']) def test_tight_layout3(): 'Test tight_layout for multiple subplots' fig = plt.figure() ax1 = plt.subplot(221) ax2 = plt.subplot(223) ax3 = plt.subplot(122) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.tight_layout() @image_comparison(baseline_images=['tight_layout4'], freetype_version=('2.5.5', '2.6.1')) def test_tight_layout4(): 'Test tight_layout for subplot2grid' fig = plt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0)) ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout() @image_comparison(baseline_images=['tight_layout5']) def test_tight_layout5(): 'Test tight_layout for image' fig = plt.figure() ax = plt.subplot(111) arr = np.arange(100).reshape((10, 10)) ax.imshow(arr, interpolation="none") plt.tight_layout() @image_comparison(baseline_images=['tight_layout6']) def test_tight_layout6(): 'Test tight_layout for gridspec' # This raises warnings since tight layout cannot # do this fully automatically. But the test is # correct since the layout is manually edited with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) fig = plt.figure() import matplotlib.gridspec as gridspec gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) gs2 = gridspec.GridSpec(3, 1) for ss in gs2: ax = fig.add_subplot(ss) example_plot(ax) ax.set_title("") ax.set_xlabel("") ax.set_xlabel("x-label", fontsize=12) gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.45) top = min(gs1.top, gs2.top) bottom = max(gs1.bottom, gs2.bottom) gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom), 0.5, 1 - (gs1.top-top)]) gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom), None, 1 - (gs2.top-top)], h_pad=0.45) @image_comparison(baseline_images=['tight_layout7']) def test_tight_layout7(): # tight layout with left and right titles fig = plt.figure() fontsize = 24 ax = fig.add_subplot(111) ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Left Title', loc='left', fontsize=fontsize) ax.set_title('Right Title', loc='right', fontsize=fontsize) plt.tight_layout() @image_comparison(baseline_images=['tight_layout8']) def test_tight_layout8(): 'Test automatic use of tight_layout' fig = plt.figure() fig.set_tight_layout({'pad': .1}) ax = fig.add_subplot(111) example_plot(ax, fontsize=24) @image_comparison(baseline_images=['tight_layout9']) def test_tight_layout9(): # Test tight_layout for non-visible suplots # GH 8244 f, axarr = plt.subplots(2, 2) axarr[1][1].set_visible(False) plt.tight_layout() # The following test is misleading when the text is removed. @image_comparison(baseline_images=['outward_ticks'], remove_text=False) def test_outward_ticks(): 'Test automatic use of tight_layout' fig = plt.figure() ax = fig.add_subplot(221) ax.xaxis.set_tick_params(tickdir='out', length=16, width=3) ax.yaxis.set_tick_params(tickdir='out', length=16, width=3) ax.xaxis.set_tick_params( tickdir='out', length=32, width=3, tick1On=True, which='minor') ax.yaxis.set_tick_params( tickdir='out', length=32, width=3, tick1On=True, which='minor') # The following minor ticks are not labelled, and they # are drawn over the major ticks and labels--ugly! ax.xaxis.set_ticks([0], minor=True) ax.yaxis.set_ticks([0], minor=True) ax = fig.add_subplot(222) ax.xaxis.set_tick_params(tickdir='in', length=32, width=3) ax.yaxis.set_tick_params(tickdir='in', length=32, width=3) ax = fig.add_subplot(223) ax.xaxis.set_tick_params(tickdir='inout', length=32, width=3) ax.yaxis.set_tick_params(tickdir='inout', length=32, width=3) ax = fig.add_subplot(224) ax.xaxis.set_tick_params(tickdir='out', length=32, width=3) ax.yaxis.set_tick_params(tickdir='out', length=32, width=3) plt.tight_layout() def add_offsetboxes(ax, size=10, margin=.1, color='black'): """ Surround ax with OffsetBoxes """ m, mp = margin, 1+margin anchor_points = [(-m, -m), (-m, .5), (-m, mp), (mp, .5), (.5, mp), (mp, mp), (.5, -m), (mp, -m), (.5, -m)] for point in anchor_points: da = DrawingArea(size, size) background = Rectangle((0, 0), width=size, height=size, facecolor=color, edgecolor='None', linewidth=0, antialiased=False) da.add_artist(background) anchored_box = AnchoredOffsetbox( loc=10, child=da, pad=0., frameon=False, bbox_to_anchor=point, bbox_transform=ax.transAxes, borderpad=0.) ax.add_artist(anchored_box) return anchored_box @image_comparison(baseline_images=['tight_layout_offsetboxes1', 'tight_layout_offsetboxes2']) def test_tight_layout_offsetboxes(): # 1. # - Create 4 subplots # - Plot a diagonal line on them # - Surround each plot with 7 boxes # - Use tight_layout # - See that the squares are included in the tight_layout # and that the squares in the middle do not overlap # # 2. # - Make the squares around the right side axes invisible # - See that the invisible squares do not affect the # tight_layout rows = cols = 2 colors = ['red', 'blue', 'green', 'yellow'] x = y = [0, 1] def _subplots(): _, axs = plt.subplots(rows, cols) axs = axs.flat for ax, color in zip(axs, colors): ax.plot(x, y, color=color) add_offsetboxes(ax, 20, color=color) return axs # 1. axs = _subplots() plt.tight_layout() # 2. axs = _subplots() for ax in (axs[cols-1::rows]): for child in ax.get_children(): if isinstance(child, AnchoredOffsetbox): child.set_visible(False) plt.tight_layout() def test_empty_layout(): """Tests that tight layout doesn't cause an error when there are no axes. """ fig = plt.gcf() fig.tight_layout()
8,117
28.52
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_patches.py
""" Tests specific to the patches module. """ from __future__ import absolute_import, division, print_function import six import numpy as np from numpy.testing import assert_almost_equal, assert_array_equal import pytest from matplotlib.patches import Polygon from matplotlib.patches import Rectangle from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.collections as mcollections from matplotlib import path as mpath from matplotlib import transforms as mtransforms import matplotlib.style as mstyle import sys on_win = (sys.platform == 'win32') def test_Polygon_close(): #: Github issue #1018 identified a bug in the Polygon handling #: of the closed attribute; the path was not getting closed #: when set_xy was used to set the vertices. # open set of vertices: xy = [[0, 0], [0, 1], [1, 1]] # closed set: xyclosed = xy + [[0, 0]] # start with open path and close it: p = Polygon(xy, closed=True) assert_array_equal(p.get_xy(), xyclosed) p.set_xy(xy) assert_array_equal(p.get_xy(), xyclosed) # start with closed path and open it: p = Polygon(xyclosed, closed=False) assert_array_equal(p.get_xy(), xy) p.set_xy(xyclosed) assert_array_equal(p.get_xy(), xy) # start with open path and leave it open: p = Polygon(xy, closed=False) assert_array_equal(p.get_xy(), xy) p.set_xy(xy) assert_array_equal(p.get_xy(), xy) # start with closed path and leave it closed: p = Polygon(xyclosed, closed=True) assert_array_equal(p.get_xy(), xyclosed) p.set_xy(xyclosed) assert_array_equal(p.get_xy(), xyclosed) def test_rotate_rect(): loc = np.asarray([1.0, 2.0]) width = 2 height = 3 angle = 30.0 # A rotated rectangle rect1 = Rectangle(loc, width, height, angle=angle) # A non-rotated rectangle rect2 = Rectangle(loc, width, height) # Set up an explicit rotation matrix (in radians) angle_rad = np.pi * angle / 180.0 rotation_matrix = np.array([[np.cos(angle_rad), -np.sin(angle_rad)], [np.sin(angle_rad), np.cos(angle_rad)]]) # Translate to origin, rotate each vertex, and then translate back new_verts = np.inner(rotation_matrix, rect2.get_verts() - loc).T + loc # They should be the same assert_almost_equal(rect1.get_verts(), new_verts) def test_negative_rect(): # These two rectangles have the same vertices, but starting from a # different point. (We also drop the last vertex, which is a duplicate.) pos_vertices = Rectangle((-3, -2), 3, 2).get_verts()[:-1] neg_vertices = Rectangle((0, 0), -3, -2).get_verts()[:-1] assert_array_equal(np.roll(neg_vertices, 2, 0), pos_vertices) @image_comparison(baseline_images=['clip_to_bbox']) def test_clip_to_bbox(): fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlim([-18, 20]) ax.set_ylim([-150, 100]) path = mpath.Path.unit_regular_star(8).deepcopy() path.vertices *= [10, 100] path.vertices -= [5, 25] path2 = mpath.Path.unit_circle().deepcopy() path2.vertices *= [10, 100] path2.vertices += [10, -25] combined = mpath.Path.make_compound_path(path, path2) patch = mpatches.PathPatch( combined, alpha=0.5, facecolor='coral', edgecolor='none') ax.add_patch(patch) bbox = mtransforms.Bbox([[-12, -77.5], [50, -110]]) result_path = combined.clip_to_bbox(bbox) result_patch = mpatches.PathPatch( result_path, alpha=0.5, facecolor='green', lw=4, edgecolor='black') ax.add_patch(result_patch) @image_comparison(baseline_images=['patch_alpha_coloring'], remove_text=True) def test_patch_alpha_coloring(): """ Test checks that the patch and collection are rendered with the specified alpha values in their facecolor and edgecolor. """ star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the star with an internal cutout of the circle verts = np.concatenate([circle.vertices, star.vertices[::-1]]) codes = np.concatenate([circle.codes, star.codes]) cut_star1 = mpath.Path(verts, codes) cut_star2 = mpath.Path(verts + 1, codes) ax = plt.axes() patch = mpatches.PathPatch(cut_star1, linewidth=5, linestyle='dashdot', facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_patch(patch) col = mcollections.PathCollection([cut_star2], linewidth=5, linestyles='dashdot', facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_collection(col) ax.set_xlim([-1, 2]) ax.set_ylim([-1, 2]) @image_comparison(baseline_images=['patch_alpha_override'], remove_text=True) def test_patch_alpha_override(): #: Test checks that specifying an alpha attribute for a patch or #: collection will override any alpha component of the facecolor #: or edgecolor. star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the star with an internal cutout of the circle verts = np.concatenate([circle.vertices, star.vertices[::-1]]) codes = np.concatenate([circle.codes, star.codes]) cut_star1 = mpath.Path(verts, codes) cut_star2 = mpath.Path(verts + 1, codes) ax = plt.axes() patch = mpatches.PathPatch(cut_star1, linewidth=5, linestyle='dashdot', alpha=0.25, facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_patch(patch) col = mcollections.PathCollection([cut_star2], linewidth=5, linestyles='dashdot', alpha=0.25, facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_collection(col) ax.set_xlim([-1, 2]) ax.set_ylim([-1, 2]) @pytest.mark.style('default') def test_patch_color_none(): # Make sure the alpha kwarg does not override 'none' facecolor. # Addresses issue #7478. c = plt.Circle((0, 0), 1, facecolor='none', alpha=1) assert c.get_facecolor()[0] == 0 @image_comparison(baseline_images=['patch_custom_linestyle'], remove_text=True) def test_patch_custom_linestyle(): #: A test to check that patches and collections accept custom dash #: patterns as linestyle and that they display correctly. star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the star with an internal cutout of the circle verts = np.concatenate([circle.vertices, star.vertices[::-1]]) codes = np.concatenate([circle.codes, star.codes]) cut_star1 = mpath.Path(verts, codes) cut_star2 = mpath.Path(verts + 1, codes) ax = plt.axes() patch = mpatches.PathPatch(cut_star1, linewidth=5, linestyle=(0.0, (5.0, 7.0, 10.0, 7.0)), facecolor=(1, 0, 0), edgecolor=(0, 0, 1)) ax.add_patch(patch) col = mcollections.PathCollection([cut_star2], linewidth=5, linestyles=[(0.0, (5.0, 7.0, 10.0, 7.0))], facecolor=(1, 0, 0), edgecolor=(0, 0, 1)) ax.add_collection(col) ax.set_xlim([-1, 2]) ax.set_ylim([-1, 2]) def test_patch_linestyle_accents(): #: Test if linestyle can also be specified with short menoics #: like "--" #: c.f. Gihub issue #2136 star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the star with an internal cutout of the circle verts = np.concatenate([circle.vertices, star.vertices[::-1]]) codes = np.concatenate([circle.codes, star.codes]) linestyles = ["-", "--", "-.", ":", "solid", "dashed", "dashdot", "dotted"] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for i, ls in enumerate(linestyles): star = mpath.Path(verts + i, codes) patch = mpatches.PathPatch(star, linewidth=3, linestyle=ls, facecolor=(1, 0, 0), edgecolor=(0, 0, 1)) ax.add_patch(patch) ax.set_xlim([-1, i + 1]) ax.set_ylim([-1, i + 1]) fig.canvas.draw() assert True def test_wedge_movement(): param_dict = {'center': ((0, 0), (1, 1), 'set_center'), 'r': (5, 8, 'set_radius'), 'width': (2, 3, 'set_width'), 'theta1': (0, 30, 'set_theta1'), 'theta2': (45, 50, 'set_theta2')} init_args = dict((k, v[0]) for (k, v) in six.iteritems(param_dict)) w = mpatches.Wedge(**init_args) for attr, (old_v, new_v, func) in six.iteritems(param_dict): assert getattr(w, attr) == old_v getattr(w, func)(new_v) assert getattr(w, attr) == new_v # png needs tol>=0.06, pdf tol>=1.617 @image_comparison(baseline_images=['wedge_range'], remove_text=True, tol=1.65 if on_win else 0) def test_wedge_range(): ax = plt.axes() t1 = 2.313869244286224 args = [[52.31386924, 232.31386924], [52.313869244286224, 232.31386924428622], [t1, t1 + 180.0], [0, 360], [90, 90 + 360], [-180, 180], [0, 380], [45, 46], [46, 45]] for i, (theta1, theta2) in enumerate(args): x = i % 3 y = i // 3 wedge = mpatches.Wedge((x * 3, y * 3), 1, theta1, theta2, facecolor='none', edgecolor='k', lw=3) ax.add_artist(wedge) ax.set_xlim([-2, 8]) ax.set_ylim([-2, 9]) def test_patch_str(): """ Check that patches have nice and working `str` representation. Note that the logic is that `__str__` is defined such that: str(eval(str(p))) == str(p) """ p = mpatches.Circle(xy=(1, 2), radius=3) assert str(p) == 'Circle(xy=(1, 2), radius=3)' p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5) assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)' p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5) assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)' p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6) assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)' p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7) expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)' assert str(p) == expected @image_comparison(baseline_images=['multi_color_hatch'], remove_text=True, style='default') def test_multi_color_hatch(): fig, ax = plt.subplots() rects = ax.bar(range(5), range(1, 6)) for i, rect in enumerate(rects): rect.set_facecolor('none') rect.set_edgecolor('C{}'.format(i)) rect.set_hatch('/') for i in range(5): with mstyle.context({'hatch.color': 'C{}'.format(i)}): r = Rectangle((i - .8 / 2, 5), .8, 1, hatch='//', fc='none') ax.add_patch(r) @image_comparison(baseline_images=['units_rectangle'], extensions=['png']) def test_units_rectangle(): import matplotlib.testing.jpl_units as U U.register() p = mpatches.Rectangle((5*U.km, 6*U.km), 1*U.km, 2*U.km) fig, ax = plt.subplots() ax.add_patch(p) ax.set_xlim([4*U.km, 7*U.km]) ax.set_ylim([5*U.km, 9*U.km]) @image_comparison(baseline_images=['connection_patch'], extensions=['png'], style='mpl20', remove_text=True) def test_connection_patch(): fig, (ax1, ax2) = plt.subplots(1, 2) con = mpatches.ConnectionPatch(xyA=(0.1, 0.1), xyB=(0.9, 0.9), coordsA='data', coordsB='data', axesA=ax2, axesB=ax1, arrowstyle="->") ax2.add_artist(con) def test_datetime_rectangle(): # Check that creating a rectangle with timedeltas doesn't fail from datetime import datetime, timedelta start = datetime(2017, 1, 1, 0, 0, 0) delta = timedelta(seconds=16) patch = mpatches.Rectangle((start, 0), delta, 1) fig, ax = plt.subplots() ax.add_patch(patch) def test_datetime_datetime_fails(): from datetime import datetime start = datetime(2017, 1, 1, 0, 0, 0) dt_delta = datetime(1970, 1, 5) # Will be 5 days if units are done wrong with pytest.raises(TypeError): mpatches.Rectangle((start, 0), dt_delta, 1) with pytest.raises(TypeError): mpatches.Rectangle((0, start), 1, dt_delta) def test_contains_point(): ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0, 0) points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)] path = ell.get_path() transform = ell.get_transform() radius = ell._process_radius(None) expected = np.array([path.contains_point(point, transform, radius) for point in points]) result = np.array([ell.contains_point(point) for point in points]) assert np.all(result == expected) def test_contains_points(): ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0, 0) points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)] path = ell.get_path() transform = ell.get_transform() radius = ell._process_radius(None) expected = path.contains_points(points, transform, radius) result = ell.contains_points(points) assert np.all(result == expected)
13,849
32.535109
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_usetex.py
from __future__ import absolute_import, division, print_function import pytest import matplotlib from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt @pytest.mark.skipif(not matplotlib.checkdep_usetex(True), reason='Missing TeX or Ghostscript or dvipng') @image_comparison(baseline_images=['test_usetex'], extensions=['pdf', 'png'], tol=0.3) def test_usetex(): matplotlib.rcParams['text.usetex'] = True fig = plt.figure() ax = fig.add_subplot(111) ax.text(0.1, 0.2, # the \LaTeX macro exercises character sizing and placement, # \left[ ... \right\} draw some variable-height characters, # \sqrt and \frac draw horizontal rules, \mathrm changes the font r'\LaTeX\ $\left[\int\limits_e^{2e}' r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$', fontsize=24) ax.set_xticks([]) ax.set_yticks([])
984
34.178571
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_mathtext.py
from __future__ import absolute_import, division, print_function import six import io import re import numpy as np import pytest import matplotlib from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib import mathtext math_tests = [ r'$a+b+\dot s+\dot{s}+\ldots$', r'$x \doteq y$', r'\$100.00 $\alpha \_$', r'$\frac{\$100.00}{y}$', r'$x y$', r'$x+y\ x=y\ x<y\ x:y\ x,y\ x@y$', r'$100\%y\ x*y\ x/y x\$y$', r'$x\leftarrow y\ x\forall y\ x-y$', r'$x \sf x \bf x {\cal X} \rm x$', r'$x\ x\,x\;x\quad x\qquad x\!x\hspace{ 0.5 }y$', r'$\{ \rm braces \}$', r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$', r'$\left(x\right)$', r'$\sin(x)$', r'$x_2$', r'$x^2$', r'$x^2_y$', r'$x_y^2$', r'$\prod_{i=\alpha_{i+1}}^\infty$', r'$x = \frac{x+\frac{5}{2}}{\frac{y+3}{8}}$', r'$dz/dt = \gamma x^2 + {\rm sin}(2\pi y+\phi)$', r'Foo: $\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau}$', r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i \sin(2 \pi f x_i)$', r'Variable $i$ is good', r'$\Delta_i^j$', r'$\Delta^j_{i+1}$', r'$\ddot{o}\acute{e}\grave{e}\hat{O}\breve{\imath}\tilde{n}\vec{q}$', r"$\arccos((x^i))$", r"$\gamma = \frac{x=\frac{6}{8}}{y} \delta$", r'$\limsup_{x\to\infty}$', r'$\oint^\infty_0$', r"$f'\quad f'''(x)\quad ''/\mathrm{yr}$", r'$\frac{x_2888}{y}$', r"$\sqrt[3]{\frac{X_2}{Y}}=5$", r"$\sqrt[5]{\prod^\frac{x}{2\pi^2}_\infty}$", r"$\sqrt[3]{x}=5$", r'$\frac{X}{\frac{X}{Y}}$', r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$", r'$\mathcal{H} = \int d \tau \left(\epsilon E^2 + \mu H^2\right)$', r'$\widehat{abc}\widetilde{def}$', '$\\Gamma \\Delta \\Theta \\Lambda \\Xi \\Pi \\Sigma \\Upsilon \\Phi \\Psi \\Omega$', '$\\alpha \\beta \\gamma \\delta \\epsilon \\zeta \\eta \\theta \\iota \\lambda \\mu \\nu \\xi \\pi \\kappa \\rho \\sigma \\tau \\upsilon \\phi \\chi \\psi$', # The examples prefixed by 'mmltt' are from the MathML torture test here: # http://www.mozilla.org/projects/mathml/demo/texvsmml.xhtml r'${x}^{2}{y}^{2}$', r'${}_{2}F_{3}$', r'$\frac{x+{y}^{2}}{k+1}$', r'$x+{y}^{\frac{2}{k+1}}$', r'$\frac{a}{b/2}$', r'${a}_{0}+\frac{1}{{a}_{1}+\frac{1}{{a}_{2}+\frac{1}{{a}_{3}+\frac{1}{{a}_{4}}}}}$', r'${a}_{0}+\frac{1}{{a}_{1}+\frac{1}{{a}_{2}+\frac{1}{{a}_{3}+\frac{1}{{a}_{4}}}}}$', r'$\binom{n}{k/2}$', r'$\binom{p}{2}{x}^{2}{y}^{p-2}-\frac{1}{1-x}\frac{1}{1-{x}^{2}}$', r'${x}^{2y}$', r'$\sum _{i=1}^{p}\sum _{j=1}^{q}\sum _{k=1}^{r}{a}_{ij}{b}_{jk}{c}_{ki}$', r'$\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+x}}}}}}}$', r'$\left(\frac{{\partial }^{2}}{\partial {x}^{2}}+\frac{{\partial }^{2}}{\partial {y}^{2}}\right){|\varphi \left(x+iy\right)|}^{2}=0$', r'${2}^{{2}^{{2}^{x}}}$', r'${\int }_{1}^{x}\frac{\mathrm{dt}}{t}$', r'$\int {\int }_{D}\mathrm{dx} \mathrm{dy}$', # mathtex doesn't support array # 'mmltt18' : r'$f\left(x\right)=\left\{\begin{array}{cc}\hfill 1/3\hfill & \text{if_}0\le x\le 1;\hfill \\ \hfill 2/3\hfill & \hfill \text{if_}3\le x\le 4;\hfill \\ \hfill 0\hfill & \text{elsewhere.}\hfill \end{array}$', # mathtex doesn't support stackrel # 'mmltt19' : ur'$\stackrel{\stackrel{k\text{times}}{\ufe37}}{x+...+x}$', r'${y}_{{x}^{2}}$', # mathtex doesn't support the "\text" command # 'mmltt21' : r'$\sum _{p\text{\prime}}f\left(p\right)={\int }_{t>1}f\left(t\right) d\pi \left(t\right)$', # mathtex doesn't support array # 'mmltt23' : r'$\left(\begin{array}{cc}\hfill \left(\begin{array}{cc}\hfill a\hfill & \hfill b\hfill \\ \hfill c\hfill & \hfill d\hfill \end{array}\right)\hfill & \hfill \left(\begin{array}{cc}\hfill e\hfill & \hfill f\hfill \\ \hfill g\hfill & \hfill h\hfill \end{array}\right)\hfill \\ \hfill 0\hfill & \hfill \left(\begin{array}{cc}\hfill i\hfill & \hfill j\hfill \\ \hfill k\hfill & \hfill l\hfill \end{array}\right)\hfill \end{array}\right)$', # mathtex doesn't support array # 'mmltt24' : u'$det|\\begin{array}{ccccc}\\hfill {c}_{0}\\hfill & \\hfill {c}_{1}\\hfill & \\hfill {c}_{2}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{n}\\hfill \\\\ \\hfill {c}_{1}\\hfill & \\hfill {c}_{2}\\hfill & \\hfill {c}_{3}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{n+1}\\hfill \\\\ \\hfill {c}_{2}\\hfill & \\hfill {c}_{3}\\hfill & \\hfill {c}_{4}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{n+2}\\hfill \\\\ \\hfill \\u22ee\\hfill & \\hfill \\u22ee\\hfill & \\hfill \\u22ee\\hfill & \\hfill \\hfill & \\hfill \\u22ee\\hfill \\\\ \\hfill {c}_{n}\\hfill & \\hfill {c}_{n+1}\\hfill & \\hfill {c}_{n+2}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{2n}\\hfill \\end{array}|>0$', r'${y}_{{x}_{2}}$', r'${x}_{92}^{31415}+\pi $', r'${x}_{{y}_{b}^{a}}^{{z}_{c}^{d}}$', r'${y}_{3}^{\prime \prime \prime }$', r"$\left( \xi \left( 1 - \xi \right) \right)$", # Bug 2969451 r"$\left(2 \, a=b\right)$", # Sage bug #8125 r"$? ! &$", # github issue #466 r'$\operatorname{cos} x$', # github issue #553 r'$\sum _{\genfrac{}{}{0}{}{0\leq i\leq m}{0<j<n}}P\left(i,j\right)$', r"$\left\Vert a \right\Vert \left\vert b \right\vert \left| a \right| \left\| b\right\| \Vert a \Vert \vert b \vert$", r'$\mathring{A} \stackrel{\circ}{A} \AA$', r'$M \, M \thinspace M \/ M \> M \: M \; M \ M \enspace M \quad M \qquad M \! M$', r'$\Cup$ $\Cap$ $\leftharpoonup$ $\barwedge$ $\rightharpoonup$', r'$\dotplus$ $\doteq$ $\doteqdot$ $\ddots$', r'$xyz^kx_kx^py^{p-2} d_i^jb_jc_kd x^j_i E^0 E^0_u$', # github issue #4873 r'${xyz}^k{x}_{k}{x}^{p}{y}^{p-2} {d}_{i}^{j}{b}_{j}{c}_{k}{d} {x}^{j}_{i}{E}^{0}{E}^0_u$', r'${\int}_x^x x\oint_x^x x\int_{X}^{X}x\int_x x \int^x x \int_{x} x\int^{x}{\int}_{x} x{\int}^{x}_{x}x$', r'testing$^{123}$', ' '.join('$\\' + p + '$' for p in sorted(mathtext.Parser._snowflake)), r'$6-2$; $-2$; $ -2$; ${-2}$; ${ -2}$; $20^{+3}_{-2}$', r'$\overline{\omega}^x \frac{1}{2}_0^x$', # github issue #5444 r'$,$ $.$ $1{,}234{, }567{ , }890$ and $1,234,567,890$', # github issue 5799 r'$\left(X\right)_{a}^{b}$', # github issue 7615 r'$\dfrac{\$100.00}{y}$', # github issue #1888 ] digits = "0123456789" uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercase = "abcdefghijklmnopqrstuvwxyz" uppergreek = ("\\Gamma \\Delta \\Theta \\Lambda \\Xi \\Pi \\Sigma \\Upsilon \\Phi \\Psi " "\\Omega") lowergreek = ("\\alpha \\beta \\gamma \\delta \\epsilon \\zeta \\eta \\theta \\iota " "\\lambda \\mu \\nu \\xi \\pi \\kappa \\rho \\sigma \\tau \\upsilon " "\\phi \\chi \\psi") all = [digits, uppercase, lowercase, uppergreek, lowergreek] font_test_specs = [ ([], all), (['mathrm'], all), (['mathbf'], all), (['mathit'], all), (['mathtt'], [digits, uppercase, lowercase]), (['mathcircled'], [digits, uppercase, lowercase]), (['mathrm', 'mathcircled'], [digits, uppercase, lowercase]), (['mathbf', 'mathcircled'], [digits, uppercase, lowercase]), (['mathbb'], [digits, uppercase, lowercase, r'\Gamma \Pi \Sigma \gamma \pi']), (['mathrm', 'mathbb'], [digits, uppercase, lowercase, r'\Gamma \Pi \Sigma \gamma \pi']), (['mathbf', 'mathbb'], [digits, uppercase, lowercase, r'\Gamma \Pi \Sigma \gamma \pi']), (['mathcal'], [uppercase]), (['mathfrak'], [uppercase, lowercase]), (['mathbf', 'mathfrak'], [uppercase, lowercase]), (['mathscr'], [uppercase, lowercase]), (['mathsf'], [digits, uppercase, lowercase]), (['mathrm', 'mathsf'], [digits, uppercase, lowercase]), (['mathbf', 'mathsf'], [digits, uppercase, lowercase]) ] font_tests = [] for fonts, chars in font_test_specs: wrapper = [' '.join(fonts), ' $'] for font in fonts: wrapper.append(r'\%s{' % font) wrapper.append('%s') for font in fonts: wrapper.append('}') wrapper.append('$') wrapper = ''.join(wrapper) for set in chars: font_tests.append(wrapper % set) @pytest.fixture def baseline_images(request, fontset, index): return ['%s_%s_%02d' % (request.param, fontset, index)] @pytest.mark.parametrize('index, test', enumerate(math_tests), ids=[str(index) for index in range(len(math_tests))]) @pytest.mark.parametrize('fontset', ['cm', 'stix', 'stixsans', 'dejavusans', 'dejavuserif']) @pytest.mark.parametrize('baseline_images', ['mathtext'], indirect=True) @image_comparison(baseline_images=None) def test_mathtext_rendering(baseline_images, fontset, index, test): matplotlib.rcParams['mathtext.fontset'] = fontset fig = plt.figure(figsize=(5.25, 0.75)) fig.text(0.5, 0.5, test, horizontalalignment='center', verticalalignment='center') @pytest.mark.parametrize('index, test', enumerate(font_tests), ids=[str(index) for index in range(len(font_tests))]) @pytest.mark.parametrize('fontset', ['cm', 'stix', 'stixsans', 'dejavusans', 'dejavuserif']) @pytest.mark.parametrize('baseline_images', ['mathfont'], indirect=True) @image_comparison(baseline_images=None, extensions=['png']) def test_mathfont_rendering(baseline_images, fontset, index, test): matplotlib.rcParams['mathtext.fontset'] = fontset fig = plt.figure(figsize=(5.25, 0.75)) fig.text(0.5, 0.5, test, horizontalalignment='center', verticalalignment='center') def test_fontinfo(): import matplotlib.font_manager as font_manager import matplotlib.ft2font as ft2font fontpath = font_manager.findfont("DejaVu Sans") font = ft2font.FT2Font(fontpath) table = font.get_sfnt_table("head") assert table['version'] == (1, 0) @pytest.mark.parametrize( 'math, msg', [ (r'$\hspace{}$', r'Expected \hspace{n}'), (r'$\hspace{foo}$', r'Expected \hspace{n}'), (r'$\frac$', r'Expected \frac{num}{den}'), (r'$\frac{}{}$', r'Expected \frac{num}{den}'), (r'$\stackrel$', r'Expected \stackrel{num}{den}'), (r'$\stackrel{}{}$', r'Expected \stackrel{num}{den}'), (r'$\binom$', r'Expected \binom{num}{den}'), (r'$\binom{}{}$', r'Expected \binom{num}{den}'), (r'$\genfrac$', r'Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'), (r'$\genfrac{}{}{}{}{}{}$', r'Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'), (r'$\sqrt$', r'Expected \sqrt{value}'), (r'$\sqrt f$', r'Expected \sqrt{value}'), (r'$\overline$', r'Expected \overline{value}'), (r'$\overline{}$', r'Expected \overline{value}'), (r'$\leftF$', r'Expected a delimiter'), (r'$\rightF$', r'Unknown symbol: \rightF'), (r'$\left(\right$', r'Expected a delimiter'), (r'$\left($', r'Expected "\right"'), (r'$\dfrac$', r'Expected \dfrac{num}{den}'), (r'$\dfrac{}{}$', r'Expected \dfrac{num}{den}'), ], ids=[ 'hspace without value', 'hspace with invalid value', 'frac without parameters', 'frac with empty parameters', 'stackrel without parameters', 'stackrel with empty parameters', 'binom without parameters', 'binom with empty parameters', 'genfrac without parameters', 'genfrac with empty parameters', 'sqrt without parameters', 'sqrt with invalid value', 'overline without parameters', 'overline with empty parameter', 'left with invalid delimiter', 'right with invalid delimiter', 'unclosed parentheses with sizing', 'unclosed parentheses without sizing', 'dfrac without parameters', 'dfrac with empty parameters', ] ) def test_mathtext_exceptions(math, msg): parser = mathtext.MathTextParser('agg') with pytest.raises(ValueError) as excinfo: parser.parse(math) excinfo.match(re.escape(msg)) def test_single_minus_sign(): plt.figure(figsize=(0.3, 0.3)) plt.text(0.5, 0.5, '$-$') for spine in plt.gca().spines.values(): spine.set_visible(False) plt.gca().set_xticks([]) plt.gca().set_yticks([]) buff = io.BytesIO() plt.savefig(buff, format="rgba", dpi=1000) array = np.fromstring(buff.getvalue(), dtype=np.uint8) # If this fails, it would be all white assert not np.all(array == 0xff)
12,837
45.179856
703
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backend_pdf.py
# -*- encoding: utf-8 -*- from __future__ import absolute_import, division, print_function import six import io import os import sys import tempfile import numpy as np import pytest from matplotlib import dviread, pyplot as plt, checkdep_usetex, rcParams from matplotlib.backends.backend_pdf import PdfPages from matplotlib.testing.compare import compare_images from matplotlib.testing.decorators import image_comparison from matplotlib.testing.determinism import (_determinism_source_date_epoch, _determinism_check) needs_usetex = pytest.mark.xfail( not checkdep_usetex(True), reason="This test needs a TeX installation") @image_comparison(baseline_images=['pdf_use14corefonts'], extensions=['pdf']) def test_use14corefonts(): rcParams['pdf.use14corefonts'] = True rcParams['font.family'] = 'sans-serif' rcParams['font.size'] = 8 rcParams['font.sans-serif'] = ['Helvetica'] rcParams['pdf.compression'] = 0 text = u'''A three-line text positioned just above a blue line and containing some French characters and the euro symbol: "Merci pépé pour les 10 €"''' fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title('Test PDF backend with option use14corefonts=True') ax.text(0.5, 0.5, text, horizontalalignment='center', verticalalignment='bottom', fontsize=14) ax.axhline(0.5, linewidth=0.5) def test_type42(): rcParams['pdf.fonttype'] = 42 fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1, 2, 3]) fig.savefig(io.BytesIO()) def test_multipage_pagecount(): with PdfPages(io.BytesIO()) as pdf: assert pdf.get_pagecount() == 0 fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1, 2, 3]) fig.savefig(pdf, format="pdf") assert pdf.get_pagecount() == 1 pdf.savefig() assert pdf.get_pagecount() == 2 def test_multipage_properfinalize(): pdfio = io.BytesIO() with PdfPages(pdfio) as pdf: for i in range(10): fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('This is a long title') fig.savefig(pdf, format="pdf") pdfio.seek(0) assert sum(b'startxref' in line for line in pdfio) == 1 assert sys.getsizeof(pdfio) < 40000 def test_multipage_keep_empty(): from matplotlib.backends.backend_pdf import PdfPages from tempfile import NamedTemporaryFile # test empty pdf files # test that an empty pdf is left behind with keep_empty=True (default) with NamedTemporaryFile(delete=False) as tmp: with PdfPages(tmp) as pdf: filename = pdf._file.fh.name assert os.path.exists(filename) os.remove(filename) # test if an empty pdf is deleting itself afterwards with keep_empty=False with PdfPages(filename, keep_empty=False) as pdf: pass assert not os.path.exists(filename) # test pdf files with content, they should never be deleted fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1, 2, 3]) # test that a non-empty pdf is left behind with keep_empty=True (default) with NamedTemporaryFile(delete=False) as tmp: with PdfPages(tmp) as pdf: filename = pdf._file.fh.name pdf.savefig() assert os.path.exists(filename) os.remove(filename) # test that a non-empty pdf is left behind with keep_empty=False with NamedTemporaryFile(delete=False) as tmp: with PdfPages(tmp, keep_empty=False) as pdf: filename = pdf._file.fh.name pdf.savefig() assert os.path.exists(filename) os.remove(filename) def test_composite_image(): # Test that figures can be saved with and without combining multiple images # (on a single set of axes) into a single composite image. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(0, 3) ax.imshow(Z, extent=[0, 1, 0, 1]) ax.imshow(Z[::-1], extent=[2, 3, 0, 1]) plt.rcParams['image.composite_image'] = True with PdfPages(io.BytesIO()) as pdf: fig.savefig(pdf, format="pdf") assert len(pdf._file._images) == 1 plt.rcParams['image.composite_image'] = False with PdfPages(io.BytesIO()) as pdf: fig.savefig(pdf, format="pdf") assert len(pdf._file._images) == 2 @pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python 3.6+") def test_pdfpages_fspath(): from pathlib import Path with PdfPages(Path(os.devnull)) as pdf: pdf.savefig(plt.figure()) def test_source_date_epoch(): """Test SOURCE_DATE_EPOCH support for PDF output""" _determinism_source_date_epoch("pdf", b"/CreationDate (D:20000101000000Z)") def test_determinism_plain(): """Test for reproducible PDF output: simple figure""" _determinism_check('', format="pdf") def test_determinism_images(): """Test for reproducible PDF output: figure with different images""" _determinism_check('i', format="pdf") def test_determinism_hatches(): """Test for reproducible PDF output: figure with different hatches""" _determinism_check('h', format="pdf") def test_determinism_markers(): """Test for reproducible PDF output: figure with different markers""" _determinism_check('m', format="pdf") def test_determinism_all(): """Test for reproducible PDF output""" _determinism_check(format="pdf") @image_comparison(baseline_images=['hatching_legend'], extensions=['pdf']) def test_hatching_legend(): """Test for correct hatching on patches in legend""" fig = plt.figure(figsize=(1, 2)) a = plt.Rectangle([0, 0], 0, 0, facecolor="green", hatch="XXXX") b = plt.Rectangle([0, 0], 0, 0, facecolor="blue", hatch="XXXX") fig.legend([a, b, a, b], ["", "", "", ""]) @image_comparison(baseline_images=['grayscale_alpha'], extensions=['pdf']) def test_grayscale_alpha(): """Masking images with NaN did not work for grayscale images""" x, y = np.ogrid[-2:2:.1, -2:2:.1] dd = np.exp(-(x**2 + y**2)) dd[dd < .1] = np.nan fig, ax = plt.subplots() ax.imshow(dd, interpolation='none', cmap='gray_r') ax.set_xticks([]) ax.set_yticks([]) # This tests tends to hit a TeX cache lock on AppVeyor. @pytest.mark.flaky(reruns=3) @needs_usetex def test_missing_psfont(monkeypatch): """An error is raised if a TeX font lacks a Type-1 equivalent""" def psfont(*args, **kwargs): return dviread.PsFont(texname='texfont', psname='Some Font', effects=None, encoding=None, filename=None) monkeypatch.setattr(dviread.PsfontsMap, '__getitem__', psfont) rcParams['text.usetex'] = True fig, ax = plt.subplots() ax.text(0.5, 0.5, 'hello') with tempfile.TemporaryFile() as tmpfile, pytest.raises(ValueError): fig.savefig(tmpfile, format='pdf') @pytest.mark.style('default') def test_pdf_savefig_when_color_is_none(tmpdir): fig, ax = plt.subplots() plt.axis('off') ax.plot(np.sin(np.linspace(-5, 5, 100)), 'v', c='none') actual_image = tmpdir.join('figure.pdf') expected_image = tmpdir.join('figure.eps') fig.savefig(str(actual_image), format='pdf') fig.savefig(str(expected_image), format='eps') result = compare_images(str(actual_image), str(expected_image), 0) assert result is None @needs_usetex def test_failing_latex(tmpdir): """Test failing latex subprocess call""" path = str(tmpdir.join("tmpoutput.pdf")) rcParams['text.usetex'] = True # This fails with "Double subscript" plt.xlabel("$22_2_2$") with pytest.raises(RuntimeError): plt.savefig(path)
7,811
31.414938
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backend_bases.py
from matplotlib.backend_bases import FigureCanvasBase from matplotlib.backend_bases import RendererBase import matplotlib.pyplot as plt import matplotlib.transforms as transforms import matplotlib.path as path import numpy as np import os import shutil import tempfile def test_uses_per_path(): id = transforms.Affine2D() paths = [path.Path.unit_regular_polygon(i) for i in range(3, 7)] tforms = [id.rotate(i) for i in range(1, 5)] offsets = np.arange(20).reshape((10, 2)) facecolors = ['red', 'green'] edgecolors = ['red', 'green'] def check(master_transform, paths, all_transforms, offsets, facecolors, edgecolors): rb = RendererBase() raw_paths = list(rb._iter_collection_raw_paths( master_transform, paths, all_transforms)) gc = rb.new_gc() ids = [path_id for xo, yo, path_id, gc0, rgbFace in rb._iter_collection(gc, master_transform, all_transforms, range(len(raw_paths)), offsets, transforms.IdentityTransform(), facecolors, edgecolors, [], [], [False], [], 'data')] uses = rb._iter_collection_uses_per_path( paths, all_transforms, offsets, facecolors, edgecolors) if raw_paths: seen = np.bincount(ids, minlength=len(raw_paths)) assert set(seen).issubset([uses - 1, uses]) check(id, paths, tforms, offsets, facecolors, edgecolors) check(id, paths[0:1], tforms, offsets, facecolors, edgecolors) check(id, [], tforms, offsets, facecolors, edgecolors) check(id, paths, tforms[0:1], offsets, facecolors, edgecolors) check(id, paths, [], offsets, facecolors, edgecolors) for n in range(0, offsets.shape[0]): check(id, paths, tforms, offsets[0:n, :], facecolors, edgecolors) check(id, paths, tforms, offsets, [], edgecolors) check(id, paths, tforms, offsets, facecolors, []) check(id, paths, tforms, offsets, [], []) check(id, paths, tforms, offsets, facecolors[0:1], edgecolors) def test_get_default_filename(): try: test_dir = tempfile.mkdtemp() plt.rcParams['savefig.directory'] = test_dir fig = plt.figure() canvas = FigureCanvasBase(fig) filename = canvas.get_default_filename() assert filename == 'image.png' finally: shutil.rmtree(test_dir) def test_get_default_filename_already_exists(): # From #3068: Suggest non-existing default filename try: test_dir = tempfile.mkdtemp() plt.rcParams['savefig.directory'] = test_dir fig = plt.figure() canvas = FigureCanvasBase(fig) # create 'image.png' in figure's save dir open(os.path.join(test_dir, 'image.png'), 'w').close() filename = canvas.get_default_filename() assert filename == 'image-1.png' finally: shutil.rmtree(test_dir)
2,983
36.3
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_triangulation.py
from __future__ import absolute_import, division, print_function import numpy as np import matplotlib.pyplot as plt import matplotlib.tri as mtri import pytest from numpy.testing import assert_array_equal, assert_array_almost_equal,\ assert_array_less import numpy.ma.testutils as matest from matplotlib.testing.decorators import image_comparison import matplotlib.cm as cm from matplotlib.path import Path import sys on_win = (sys.platform == 'win32') def test_delaunay(): # No duplicate points, regular grid. nx = 5 ny = 4 x, y = np.meshgrid(np.linspace(0.0, 1.0, nx), np.linspace(0.0, 1.0, ny)) x = x.ravel() y = y.ravel() npoints = nx*ny ntriangles = 2 * (nx-1) * (ny-1) nedges = 3*nx*ny - 2*nx - 2*ny + 1 # Create delaunay triangulation. triang = mtri.Triangulation(x, y) # The tests in the remainder of this function should be passed by any # triangulation that does not contain duplicate points. # Points - floating point. assert_array_almost_equal(triang.x, x) assert_array_almost_equal(triang.y, y) # Triangles - integers. assert len(triang.triangles) == ntriangles assert np.min(triang.triangles) == 0 assert np.max(triang.triangles) == npoints-1 # Edges - integers. assert len(triang.edges) == nedges assert np.min(triang.edges) == 0 assert np.max(triang.edges) == npoints-1 # Neighbors - integers. # Check that neighbors calculated by C++ triangulation class are the same # as those returned from delaunay routine. neighbors = triang.neighbors triang._neighbors = None assert_array_equal(triang.neighbors, neighbors) # Is each point used in at least one triangle? assert_array_equal(np.unique(triang.triangles), np.arange(npoints)) def test_delaunay_duplicate_points(): # x[duplicate] == x[duplicate_of] # y[duplicate] == y[duplicate_of] npoints = 10 duplicate = 7 duplicate_of = 3 np.random.seed(23) x = np.random.random((npoints)) y = np.random.random((npoints)) x[duplicate] = x[duplicate_of] y[duplicate] = y[duplicate_of] # Create delaunay triangulation. triang = mtri.Triangulation(x, y) # Duplicate points should be ignored, so the index of the duplicate points # should not appear in any triangle. assert_array_equal(np.unique(triang.triangles), np.delete(np.arange(npoints), duplicate)) def test_delaunay_points_in_line(): # Cannot triangulate points that are all in a straight line, but check # that delaunay code fails gracefully. x = np.linspace(0.0, 10.0, 11) y = np.linspace(0.0, 10.0, 11) with pytest.raises(RuntimeError): mtri.Triangulation(x, y) # Add an extra point not on the line and the triangulation is OK. x = np.append(x, 2.0) y = np.append(y, 8.0) triang = mtri.Triangulation(x, y) @pytest.mark.parametrize('x, y', [ # Triangulation should raise a ValueError if passed less than 3 points. ([], []), ([1], [5]), ([1, 2], [5, 6]), # Triangulation should also raise a ValueError if passed duplicate points # such that there are less than 3 unique points. ([1, 2, 1], [5, 6, 5]), ([1, 2, 2], [5, 6, 6]), ([1, 1, 1, 2, 1, 2], [5, 5, 5, 6, 5, 6]), ]) def test_delaunay_insufficient_points(x, y): with pytest.raises(ValueError): mtri.Triangulation(x, y) def test_delaunay_robust(): # Fails when mtri.Triangulation uses matplotlib.delaunay, works when using # qhull. tri_points = np.array([ [0.8660254037844384, -0.5000000000000004], [0.7577722283113836, -0.5000000000000004], [0.6495190528383288, -0.5000000000000003], [0.5412658773652739, -0.5000000000000003], [0.811898816047911, -0.40625000000000044], [0.7036456405748561, -0.4062500000000004], [0.5953924651018013, -0.40625000000000033]]) test_points = np.asarray([ [0.58, -0.46], [0.65, -0.46], [0.65, -0.42], [0.7, -0.48], [0.7, -0.44], [0.75, -0.44], [0.8, -0.48]]) # Utility function that indicates if a triangle defined by 3 points # (xtri, ytri) contains the test point xy. Avoid calling with a point that # lies on or very near to an edge of the triangle. def tri_contains_point(xtri, ytri, xy): tri_points = np.vstack((xtri, ytri)).T return Path(tri_points).contains_point(xy) # Utility function that returns how many triangles of the specified # triangulation contain the test point xy. Avoid calling with a point that # lies on or very near to an edge of any triangle in the triangulation. def tris_contain_point(triang, xy): count = 0 for tri in triang.triangles: if tri_contains_point(triang.x[tri], triang.y[tri], xy): count += 1 return count # Using matplotlib.delaunay, an invalid triangulation is created with # overlapping triangles; qhull is OK. triang = mtri.Triangulation(tri_points[:, 0], tri_points[:, 1]) for test_point in test_points: assert tris_contain_point(triang, test_point) == 1 # If ignore the first point of tri_points, matplotlib.delaunay throws a # KeyError when calculating the convex hull; qhull is OK. triang = mtri.Triangulation(tri_points[1:, 0], tri_points[1:, 1]) @image_comparison(baseline_images=['tripcolor1'], extensions=['png']) def test_tripcolor(): x = np.asarray([0, 0.5, 1, 0, 0.5, 1, 0, 0.5, 1, 0.75]) y = np.asarray([0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1, 0.75]) triangles = np.asarray([ [0, 1, 3], [1, 4, 3], [1, 2, 4], [2, 5, 4], [3, 4, 6], [4, 7, 6], [4, 5, 9], [7, 4, 9], [8, 7, 9], [5, 8, 9]]) # Triangulation with same number of points and triangles. triang = mtri.Triangulation(x, y, triangles) Cpoints = x + 0.5*y xmid = x[triang.triangles].mean(axis=1) ymid = y[triang.triangles].mean(axis=1) Cfaces = 0.5*xmid + ymid plt.subplot(121) plt.tripcolor(triang, Cpoints, edgecolors='k') plt.title('point colors') plt.subplot(122) plt.tripcolor(triang, facecolors=Cfaces, edgecolors='k') plt.title('facecolors') def test_no_modify(): # Test that Triangulation does not modify triangles array passed to it. triangles = np.array([[3, 2, 0], [3, 1, 0]], dtype=np.int32) points = np.array([(0, 0), (0, 1.1), (1, 0), (1, 1)]) old_triangles = triangles.copy() tri = mtri.Triangulation(points[:, 0], points[:, 1], triangles) edges = tri.edges assert_array_equal(old_triangles, triangles) def test_trifinder(): # Test points within triangles of masked triangulation. x, y = np.meshgrid(np.arange(4), np.arange(4)) x = x.ravel() y = y.ravel() triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6], [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9], [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13], [10, 14, 13], [10, 11, 14], [11, 15, 14]] mask = np.zeros(len(triangles)) mask[8:10] = 1 triang = mtri.Triangulation(x, y, triangles, mask) trifinder = triang.get_trifinder() xs = [0.25, 1.25, 2.25, 3.25] ys = [0.25, 1.25, 2.25, 3.25] xs, ys = np.meshgrid(xs, ys) xs = xs.ravel() ys = ys.ravel() tris = trifinder(xs, ys) assert_array_equal(tris, [0, 2, 4, -1, 6, -1, 10, -1, 12, 14, 16, -1, -1, -1, -1, -1]) tris = trifinder(xs-0.5, ys-0.5) assert_array_equal(tris, [-1, -1, -1, -1, -1, 1, 3, 5, -1, 7, -1, 11, -1, 13, 15, 17]) # Test points exactly on boundary edges of masked triangulation. xs = [0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 1.5, 1.5, 0.0, 1.0, 2.0, 3.0] ys = [0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 1.0, 2.0, 1.5, 1.5, 1.5, 1.5] tris = trifinder(xs, ys) assert_array_equal(tris, [0, 2, 4, 13, 15, 17, 3, 14, 6, 7, 10, 11]) # Test points exactly on boundary corners of masked triangulation. xs = [0.0, 3.0] ys = [0.0, 3.0] tris = trifinder(xs, ys) assert_array_equal(tris, [0, 17]) # # Test triangles with horizontal colinear points. These are not valid # triangulations, but we try to deal with the simplest violations. # # If +ve, triangulation is OK, if -ve triangulation invalid, # if zero have colinear points but should pass tests anyway. delta = 0.0 x = [1.5, 0, 1, 2, 3, 1.5, 1.5] y = [-1, 0, 0, 0, 0, delta, 1] triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5], [3, 4, 5], [1, 5, 6], [4, 6, 5]] triang = mtri.Triangulation(x, y, triangles) trifinder = triang.get_trifinder() xs = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9] ys = [-0.1, 0.1] xs, ys = np.meshgrid(xs, ys) tris = trifinder(xs, ys) assert_array_equal(tris, [[-1, 0, 0, 1, 1, 2, -1], [-1, 6, 6, 6, 7, 7, -1]]) # # Test triangles with vertical colinear points. These are not valid # triangulations, but we try to deal with the simplest violations. # # If +ve, triangulation is OK, if -ve triangulation invalid, # if zero have colinear points but should pass tests anyway. delta = 0.0 x = [-1, -delta, 0, 0, 0, 0, 1] y = [1.5, 1.5, 0, 1, 2, 3, 1.5] triangles = [[0, 1, 2], [0, 1, 5], [1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 6, 3], [3, 6, 4], [4, 6, 5]] triang = mtri.Triangulation(x, y, triangles) trifinder = triang.get_trifinder() xs = [-0.1, 0.1] ys = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9] xs, ys = np.meshgrid(xs, ys) tris = trifinder(xs, ys) assert_array_equal(tris, [[-1, -1], [0, 5], [0, 5], [0, 6], [1, 6], [1, 7], [-1, -1]]) # Test that changing triangulation by setting a mask causes the trifinder # to be reinitialised. x = [0, 1, 0, 1] y = [0, 0, 1, 1] triangles = [[0, 1, 2], [1, 3, 2]] triang = mtri.Triangulation(x, y, triangles) trifinder = triang.get_trifinder() xs = [-0.2, 0.2, 0.8, 1.2] ys = [0.5, 0.5, 0.5, 0.5] tris = trifinder(xs, ys) assert_array_equal(tris, [-1, 0, 1, -1]) triang.set_mask([1, 0]) assert trifinder == triang.get_trifinder() tris = trifinder(xs, ys) assert_array_equal(tris, [-1, -1, 1, -1]) def test_triinterp(): # Test points within triangles of masked triangulation. x, y = np.meshgrid(np.arange(4), np.arange(4)) x = x.ravel() y = y.ravel() z = 1.23*x - 4.79*y triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6], [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9], [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13], [10, 14, 13], [10, 11, 14], [11, 15, 14]] mask = np.zeros(len(triangles)) mask[8:10] = 1 triang = mtri.Triangulation(x, y, triangles, mask) linear_interp = mtri.LinearTriInterpolator(triang, z) cubic_min_E = mtri.CubicTriInterpolator(triang, z) cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom') xs = np.linspace(0.25, 2.75, 6) ys = [0.25, 0.75, 2.25, 2.75] xs, ys = np.meshgrid(xs, ys) # Testing arrays with array.ndim = 2 for interp in (linear_interp, cubic_min_E, cubic_geom): zs = interp(xs, ys) assert_array_almost_equal(zs, (1.23*xs - 4.79*ys)) # Test points outside triangulation. xs = [-0.25, 1.25, 1.75, 3.25] ys = xs xs, ys = np.meshgrid(xs, ys) for interp in (linear_interp, cubic_min_E, cubic_geom): zs = linear_interp(xs, ys) assert_array_equal(zs.mask, [[True]*4]*4) # Test mixed configuration (outside / inside). xs = np.linspace(0.25, 1.75, 6) ys = [0.25, 0.75, 1.25, 1.75] xs, ys = np.meshgrid(xs, ys) for interp in (linear_interp, cubic_min_E, cubic_geom): zs = interp(xs, ys) matest.assert_array_almost_equal(zs, (1.23*xs - 4.79*ys)) mask = (xs >= 1) * (xs <= 2) * (ys >= 1) * (ys <= 2) assert_array_equal(zs.mask, mask) # 2nd order patch test: on a grid with an 'arbitrary shaped' triangle, # patch test shall be exact for quadratic functions and cubic # interpolator if *kind* = user (a, b, c) = (1.23, -4.79, 0.6) def quad(x, y): return a*(x-0.5)**2 + b*(y-0.5)**2 + c*x*y def gradient_quad(x, y): return (2*a*(x-0.5) + c*y, 2*b*(y-0.5) + c*x) x = np.array([0.2, 0.33367, 0.669, 0., 1., 1., 0.]) y = np.array([0.3, 0.80755, 0.4335, 0., 0., 1., 1.]) triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5], [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]]) triang = mtri.Triangulation(x, y, triangles) z = quad(x, y) dz = gradient_quad(x, y) # test points for 2nd order patch test xs = np.linspace(0., 1., 5) ys = np.linspace(0., 1., 5) xs, ys = np.meshgrid(xs, ys) cubic_user = mtri.CubicTriInterpolator(triang, z, kind='user', dz=dz) interp_zs = cubic_user(xs, ys) assert_array_almost_equal(interp_zs, quad(xs, ys)) (interp_dzsdx, interp_dzsdy) = cubic_user.gradient(x, y) (dzsdx, dzsdy) = gradient_quad(x, y) assert_array_almost_equal(interp_dzsdx, dzsdx) assert_array_almost_equal(interp_dzsdy, dzsdy) # Cubic improvement: cubic interpolation shall perform better than linear # on a sufficiently dense mesh for a quadratic function. n = 11 x, y = np.meshgrid(np.linspace(0., 1., n+1), np.linspace(0., 1., n+1)) x = x.ravel() y = y.ravel() z = quad(x, y) triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1)) xs, ys = np.meshgrid(np.linspace(0.1, 0.9, 5), np.linspace(0.1, 0.9, 5)) xs = xs.ravel() ys = ys.ravel() linear_interp = mtri.LinearTriInterpolator(triang, z) cubic_min_E = mtri.CubicTriInterpolator(triang, z) cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom') zs = quad(xs, ys) diff_lin = np.abs(linear_interp(xs, ys) - zs) for interp in (cubic_min_E, cubic_geom): diff_cubic = np.abs(interp(xs, ys) - zs) assert np.max(diff_lin) >= 10 * np.max(diff_cubic) assert (np.dot(diff_lin, diff_lin) >= 100 * np.dot(diff_cubic, diff_cubic)) def test_triinterpcubic_C1_continuity(): # Below the 4 tests which demonstrate C1 continuity of the # TriCubicInterpolator (testing the cubic shape functions on arbitrary # triangle): # # 1) Testing continuity of function & derivatives at corner for all 9 # shape functions. Testing also function values at same location. # 2) Testing C1 continuity along each edge (as gradient is polynomial of # 2nd order, it is sufficient to test at the middle). # 3) Testing C1 continuity at triangle barycenter (where the 3 subtriangles # meet) # 4) Testing C1 continuity at median 1/3 points (midside between 2 # subtriangles) # Utility test function check_continuity def check_continuity(interpolator, loc, values=None): """ Checks the continuity of interpolator (and its derivatives) near location loc. Can check the value at loc itself if *values* is provided. *interpolator* TriInterpolator *loc* location to test (x0, y0) *values* (optional) array [z0, dzx0, dzy0] to check the value at *loc* """ n_star = 24 # Number of continuity points in a boundary of loc epsilon = 1.e-10 # Distance for loc boundary k = 100. # Continuity coefficient (loc_x, loc_y) = loc star_x = loc_x + epsilon*np.cos(np.linspace(0., 2*np.pi, n_star)) star_y = loc_y + epsilon*np.sin(np.linspace(0., 2*np.pi, n_star)) z = interpolator([loc_x], [loc_y])[0] (dzx, dzy) = interpolator.gradient([loc_x], [loc_y]) if values is not None: assert_array_almost_equal(z, values[0]) assert_array_almost_equal(dzx[0], values[1]) assert_array_almost_equal(dzy[0], values[2]) diff_z = interpolator(star_x, star_y) - z (tab_dzx, tab_dzy) = interpolator.gradient(star_x, star_y) diff_dzx = tab_dzx - dzx diff_dzy = tab_dzy - dzy assert_array_less(diff_z, epsilon*k) assert_array_less(diff_dzx, epsilon*k) assert_array_less(diff_dzy, epsilon*k) # Drawing arbitrary triangle (a, b, c) inside a unit square. (ax, ay) = (0.2, 0.3) (bx, by) = (0.33367, 0.80755) (cx, cy) = (0.669, 0.4335) x = np.array([ax, bx, cx, 0., 1., 1., 0.]) y = np.array([ay, by, cy, 0., 0., 1., 1.]) triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5], [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]]) triang = mtri.Triangulation(x, y, triangles) for idof in range(9): z = np.zeros(7, dtype=np.float64) dzx = np.zeros(7, dtype=np.float64) dzy = np.zeros(7, dtype=np.float64) values = np.zeros([3, 3], dtype=np.float64) case = idof//3 values[case, idof % 3] = 1.0 if case == 0: z[idof] = 1.0 elif case == 1: dzx[idof % 3] = 1.0 elif case == 2: dzy[idof % 3] = 1.0 interp = mtri.CubicTriInterpolator(triang, z, kind='user', dz=(dzx, dzy)) # Test 1) Checking values and continuity at nodes check_continuity(interp, (ax, ay), values[:, 0]) check_continuity(interp, (bx, by), values[:, 1]) check_continuity(interp, (cx, cy), values[:, 2]) # Test 2) Checking continuity at midside nodes check_continuity(interp, ((ax+bx)*0.5, (ay+by)*0.5)) check_continuity(interp, ((ax+cx)*0.5, (ay+cy)*0.5)) check_continuity(interp, ((cx+bx)*0.5, (cy+by)*0.5)) # Test 3) Checking continuity at barycenter check_continuity(interp, ((ax+bx+cx)/3., (ay+by+cy)/3.)) # Test 4) Checking continuity at median 1/3-point check_continuity(interp, ((4.*ax+bx+cx)/6., (4.*ay+by+cy)/6.)) check_continuity(interp, ((ax+4.*bx+cx)/6., (ay+4.*by+cy)/6.)) check_continuity(interp, ((ax+bx+4.*cx)/6., (ay+by+4.*cy)/6.)) def test_triinterpcubic_cg_solver(): # Now 3 basic tests of the Sparse CG solver, used for # TriCubicInterpolator with *kind* = 'min_E' # 1) A commonly used test involves a 2d Poisson matrix. def poisson_sparse_matrix(n, m): """ Sparse Poisson matrix. Returns the sparse matrix in coo format resulting from the discretisation of the 2-dimensional Poisson equation according to a finite difference numerical scheme on a uniform (n, m) grid. Size of the matrix: (n*m, n*m) """ l = m*n rows = np.concatenate([ np.arange(l, dtype=np.int32), np.arange(l-1, dtype=np.int32), np.arange(1, l, dtype=np.int32), np.arange(l-n, dtype=np.int32), np.arange(n, l, dtype=np.int32)]) cols = np.concatenate([ np.arange(l, dtype=np.int32), np.arange(1, l, dtype=np.int32), np.arange(l-1, dtype=np.int32), np.arange(n, l, dtype=np.int32), np.arange(l-n, dtype=np.int32)]) vals = np.concatenate([ 4*np.ones(l, dtype=np.float64), -np.ones(l-1, dtype=np.float64), -np.ones(l-1, dtype=np.float64), -np.ones(l-n, dtype=np.float64), -np.ones(l-n, dtype=np.float64)]) # In fact +1 and -1 diags have some zeros vals[l:2*l-1][m-1::m] = 0. vals[2*l-1:3*l-2][m-1::m] = 0. return vals, rows, cols, (n*m, n*m) # Instantiating a sparse Poisson matrix of size 48 x 48: (n, m) = (12, 4) mat = mtri.triinterpolate._Sparse_Matrix_coo(*poisson_sparse_matrix(n, m)) mat.compress_csc() mat_dense = mat.to_dense() # Testing a sparse solve for all 48 basis vector for itest in range(n*m): b = np.zeros(n*m, dtype=np.float64) b[itest] = 1. x, _ = mtri.triinterpolate._cg(A=mat, b=b, x0=np.zeros(n*m), tol=1.e-10) assert_array_almost_equal(np.dot(mat_dense, x), b) # 2) Same matrix with inserting 2 rows - cols with null diag terms # (but still linked with the rest of the matrix by extra-diag terms) (i_zero, j_zero) = (12, 49) vals, rows, cols, _ = poisson_sparse_matrix(n, m) rows = rows + 1*(rows >= i_zero) + 1*(rows >= j_zero) cols = cols + 1*(cols >= i_zero) + 1*(cols >= j_zero) # adding extra-diag terms rows = np.concatenate([rows, [i_zero, i_zero-1, j_zero, j_zero-1]]) cols = np.concatenate([cols, [i_zero-1, i_zero, j_zero-1, j_zero]]) vals = np.concatenate([vals, [1., 1., 1., 1.]]) mat = mtri.triinterpolate._Sparse_Matrix_coo(vals, rows, cols, (n*m + 2, n*m + 2)) mat.compress_csc() mat_dense = mat.to_dense() # Testing a sparse solve for all 50 basis vec for itest in range(n*m + 2): b = np.zeros(n*m + 2, dtype=np.float64) b[itest] = 1. x, _ = mtri.triinterpolate._cg(A=mat, b=b, x0=np.ones(n*m + 2), tol=1.e-10) assert_array_almost_equal(np.dot(mat_dense, x), b) # 3) Now a simple test that summation of duplicate (i.e. with same rows, # same cols) entries occurs when compressed. vals = np.ones(17, dtype=np.float64) rows = np.array([0, 1, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1], dtype=np.int32) cols = np.array([0, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2], dtype=np.int32) dim = (3, 3) mat = mtri.triinterpolate._Sparse_Matrix_coo(vals, rows, cols, dim) mat.compress_csc() mat_dense = mat.to_dense() assert_array_almost_equal(mat_dense, np.array([ [1., 2., 0.], [2., 1., 5.], [0., 5., 1.]], dtype=np.float64)) def test_triinterpcubic_geom_weights(): # Tests to check computation of weights for _DOF_estimator_geom: # The weight sum per triangle can be 1. (in case all angles < 90 degrees) # or (2*w_i) where w_i = 1-alpha_i/np.pi is the weight of apex i ; alpha_i # is the apex angle > 90 degrees. (ax, ay) = (0., 1.687) x = np.array([ax, 0.5*ax, 0., 1.]) y = np.array([ay, -ay, 0., 0.]) z = np.zeros(4, dtype=np.float64) triangles = [[0, 2, 3], [1, 3, 2]] sum_w = np.zeros([4, 2]) # 4 possibilities ; 2 triangles for theta in np.linspace(0., 2*np.pi, 14): # rotating the figure... x_rot = np.cos(theta)*x + np.sin(theta)*y y_rot = -np.sin(theta)*x + np.cos(theta)*y triang = mtri.Triangulation(x_rot, y_rot, triangles) cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom') dof_estimator = mtri.triinterpolate._DOF_estimator_geom(cubic_geom) weights = dof_estimator.compute_geom_weights() # Testing for the 4 possibilities... sum_w[0, :] = np.sum(weights, 1) - 1 for itri in range(3): sum_w[itri+1, :] = np.sum(weights, 1) - 2*weights[:, itri] assert_array_almost_equal(np.min(np.abs(sum_w), axis=0), np.array([0., 0.], dtype=np.float64)) def test_triinterp_colinear(): # Tests interpolating inside a triangulation with horizontal colinear # points (refer also to the tests :func:`test_trifinder` ). # # These are not valid triangulations, but we try to deal with the # simplest violations (i. e. those handled by default TriFinder). # # Note that the LinearTriInterpolator and the CubicTriInterpolator with # kind='min_E' or 'geom' still pass a linear patch test. # We also test interpolation inside a flat triangle, by forcing # *tri_index* in a call to :meth:`_interpolate_multikeys`. # If +ve, triangulation is OK, if -ve triangulation invalid, # if zero have colinear points but should pass tests anyway. delta = 0. x0 = np.array([1.5, 0, 1, 2, 3, 1.5, 1.5]) y0 = np.array([-1, 0, 0, 0, 0, delta, 1]) # We test different affine transformations of the initial figure ; to # avoid issues related to round-off errors we only use integer # coefficients (otherwise the Triangulation might become invalid even with # delta == 0). transformations = [[1, 0], [0, 1], [1, 1], [1, 2], [-2, -1], [-2, 1]] for transformation in transformations: x_rot = transformation[0]*x0 + transformation[1]*y0 y_rot = -transformation[1]*x0 + transformation[0]*y0 (x, y) = (x_rot, y_rot) z = 1.23*x - 4.79*y triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5], [3, 4, 5], [1, 5, 6], [4, 6, 5]] triang = mtri.Triangulation(x, y, triangles) xs = np.linspace(np.min(triang.x), np.max(triang.x), 20) ys = np.linspace(np.min(triang.y), np.max(triang.y), 20) xs, ys = np.meshgrid(xs, ys) xs = xs.ravel() ys = ys.ravel() mask_out = (triang.get_trifinder()(xs, ys) == -1) zs_target = np.ma.array(1.23*xs - 4.79*ys, mask=mask_out) linear_interp = mtri.LinearTriInterpolator(triang, z) cubic_min_E = mtri.CubicTriInterpolator(triang, z) cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom') for interp in (linear_interp, cubic_min_E, cubic_geom): zs = interp(xs, ys) assert_array_almost_equal(zs_target, zs) # Testing interpolation inside the flat triangle number 4: [2, 3, 5] # by imposing *tri_index* in a call to :meth:`_interpolate_multikeys` itri = 4 pt1 = triang.triangles[itri, 0] pt2 = triang.triangles[itri, 1] xs = np.linspace(triang.x[pt1], triang.x[pt2], 10) ys = np.linspace(triang.y[pt1], triang.y[pt2], 10) zs_target = 1.23*xs - 4.79*ys for interp in (linear_interp, cubic_min_E, cubic_geom): zs, = interp._interpolate_multikeys( xs, ys, tri_index=itri*np.ones(10, dtype=np.int32)) assert_array_almost_equal(zs_target, zs) def test_triinterp_transformations(): # 1) Testing that the interpolation scheme is invariant by rotation of the # whole figure. # Note: This test is non-trivial for a CubicTriInterpolator with # kind='min_E'. It does fail for a non-isotropic stiffness matrix E of # :class:`_ReducedHCT_Element` (tested with E=np.diag([1., 1., 1.])), and # provides a good test for :meth:`get_Kff_and_Ff`of the same class. # # 2) Also testing that the interpolation scheme is invariant by expansion # of the whole figure along one axis. n_angles = 20 n_radii = 10 min_radius = 0.15 def z(x, y): r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2) theta1 = np.arctan2(0.5-x, 0.5-y) r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2) theta2 = np.arctan2(-x-0.2, -y-0.2) z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) + (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) + 0.7*(x**2 + y**2)) return (np.max(z)-z)/(np.max(z)-np.min(z)) # First create the x and y coordinates of the points. radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0 + n_angles, 2*np.pi + n_angles, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi/n_angles x0 = (radii*np.cos(angles)).flatten() y0 = (radii*np.sin(angles)).flatten() triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation z0 = z(x0, y0) # Then create the test points xs0 = np.linspace(-1., 1., 23) ys0 = np.linspace(-1., 1., 23) xs0, ys0 = np.meshgrid(xs0, ys0) xs0 = xs0.ravel() ys0 = ys0.ravel() interp_z0 = {} for i_angle in range(2): # Rotating everything theta = 2*np.pi / n_angles * i_angle x = np.cos(theta)*x0 + np.sin(theta)*y0 y = -np.sin(theta)*x0 + np.cos(theta)*y0 xs = np.cos(theta)*xs0 + np.sin(theta)*ys0 ys = -np.sin(theta)*xs0 + np.cos(theta)*ys0 triang = mtri.Triangulation(x, y, triang0.triangles) linear_interp = mtri.LinearTriInterpolator(triang, z0) cubic_min_E = mtri.CubicTriInterpolator(triang, z0) cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom') dic_interp = {'lin': linear_interp, 'min_E': cubic_min_E, 'geom': cubic_geom} # Testing that the interpolation is invariant by rotation... for interp_key in ['lin', 'min_E', 'geom']: interp = dic_interp[interp_key] if i_angle == 0: interp_z0[interp_key] = interp(xs0, ys0) # storage else: interpz = interp(xs, ys) matest.assert_array_almost_equal(interpz, interp_z0[interp_key]) scale_factor = 987654.3210 for scaled_axis in ('x', 'y'): # Scaling everything (expansion along scaled_axis) if scaled_axis == 'x': x = scale_factor * x0 y = y0 xs = scale_factor * xs0 ys = ys0 else: x = x0 y = scale_factor * y0 xs = xs0 ys = scale_factor * ys0 triang = mtri.Triangulation(x, y, triang0.triangles) linear_interp = mtri.LinearTriInterpolator(triang, z0) cubic_min_E = mtri.CubicTriInterpolator(triang, z0) cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom') dic_interp = {'lin': linear_interp, 'min_E': cubic_min_E, 'geom': cubic_geom} # Testing that the interpolation is invariant by expansion along # 1 axis... for interp_key in ['lin', 'min_E', 'geom']: interpz = dic_interp[interp_key](xs, ys) matest.assert_array_almost_equal(interpz, interp_z0[interp_key]) @image_comparison(baseline_images=['tri_smooth_contouring'], extensions=['png'], remove_text=True, tol=0.07) def test_tri_smooth_contouring(): # Image comparison based on example tricontour_smooth_user. n_angles = 20 n_radii = 10 min_radius = 0.15 def z(x, y): r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2) theta1 = np.arctan2(0.5-x, 0.5-y) r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2) theta2 = np.arctan2(-x-0.2, -y-0.2) z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) + (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) + 0.7*(x**2 + y**2)) return (np.max(z)-z)/(np.max(z)-np.min(z)) # First create the x and y coordinates of the points. radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0 + n_angles, 2*np.pi + n_angles, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi/n_angles x0 = (radii*np.cos(angles)).flatten() y0 = (radii*np.sin(angles)).flatten() triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation z0 = z(x0, y0) triang0.set_mask(np.hypot(x0[triang0.triangles].mean(axis=1), y0[triang0.triangles].mean(axis=1)) < min_radius) # Then the plot refiner = mtri.UniformTriRefiner(triang0) tri_refi, z_test_refi = refiner.refine_field(z0, subdiv=4) levels = np.arange(0., 1., 0.025) plt.triplot(triang0, lw=0.5, color='0.5') plt.tricontour(tri_refi, z_test_refi, levels=levels, colors="black") @image_comparison(baseline_images=['tri_smooth_gradient'], extensions=['png'], remove_text=True, tol=0.092) def test_tri_smooth_gradient(): # Image comparison based on example trigradient_demo. def dipole_potential(x, y): """ An electric dipole potential V """ r_sq = x**2 + y**2 theta = np.arctan2(y, x) z = np.cos(theta)/r_sq return (np.max(z)-z) / (np.max(z)-np.min(z)) # Creating a Triangulation n_angles = 30 n_radii = 10 min_radius = 0.2 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi/n_angles x = (radii*np.cos(angles)).flatten() y = (radii*np.sin(angles)).flatten() V = dipole_potential(x, y) triang = mtri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) # Refine data - interpolates the electrical potential V refiner = mtri.UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) # Computes the electrical field (Ex, Ey) as gradient of -V tci = mtri.CubicTriInterpolator(triang, -V) (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2) # Plot the triangulation, the potential iso-contours and the vector field plt.figure() plt.gca().set_aspect('equal') plt.triplot(triang, color='0.8') levels = np.arange(0., 1., 0.01) cmap = cm.get_cmap(name='hot', lut=None) plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 1.0, 1.0, 1.0]) # Plots direction of the electrical vector field plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm, units='xy', scale=10., zorder=3, color='blue', width=0.007, headwidth=3., headlength=4.) # We are leaving ax.use_sticky_margins as True, so the # view limits are the contour data limits. def test_tritools(): # Tests TriAnalyzer.scale_factors on masked triangulation # Tests circle_ratios on equilateral and right-angled triangle. x = np.array([0., 1., 0.5, 0., 2.]) y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.]) triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32) mask = np.array([False, False, True], dtype=bool) triang = mtri.Triangulation(x, y, triangles, mask=mask) analyser = mtri.TriAnalyzer(triang) assert_array_almost_equal(analyser.scale_factors, np.array([1., 1./(1.+0.5*np.sqrt(3.))])) assert_array_almost_equal( analyser.circle_ratios(rescale=False), np.ma.masked_array([0.5, 1./(1.+np.sqrt(2.)), np.nan], mask)) # Tests circle ratio of a flat triangle x = np.array([0., 1., 2.]) y = np.array([1., 1.+3., 1.+6.]) triangles = np.array([[0, 1, 2]], dtype=np.int32) triang = mtri.Triangulation(x, y, triangles) analyser = mtri.TriAnalyzer(triang) assert_array_almost_equal(analyser.circle_ratios(), np.array([0.])) # Tests TriAnalyzer.get_flat_tri_mask # Creates a triangulation of [-1, 1] x [-1, 1] with contiguous groups of # 'flat' triangles at the 4 corners and at the center. Checks that only # those at the borders are eliminated by TriAnalyzer.get_flat_tri_mask n = 9 def power(x, a): return np.abs(x)**a*np.sign(x) x = np.linspace(-1., 1., n+1) x, y = np.meshgrid(power(x, 2.), power(x, 0.25)) x = x.ravel() y = y.ravel() triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1)) analyser = mtri.TriAnalyzer(triang) mask_flat = analyser.get_flat_tri_mask(0.2) verif_mask = np.zeros(162, dtype=bool) corners_index = [0, 1, 2, 3, 14, 15, 16, 17, 18, 19, 34, 35, 126, 127, 142, 143, 144, 145, 146, 147, 158, 159, 160, 161] verif_mask[corners_index] = True assert_array_equal(mask_flat, verif_mask) # Now including a hole (masked triangle) at the center. The center also # shall be eliminated by get_flat_tri_mask. mask = np.zeros(162, dtype=bool) mask[80] = True triang.set_mask(mask) mask_flat = analyser.get_flat_tri_mask(0.2) center_index = [44, 45, 62, 63, 78, 79, 80, 81, 82, 83, 98, 99, 116, 117] verif_mask[center_index] = True assert_array_equal(mask_flat, verif_mask) def test_trirefine(): # Testing subdiv=2 refinement n = 3 subdiv = 2 x = np.linspace(-1., 1., n+1) x, y = np.meshgrid(x, x) x = x.ravel() y = y.ravel() mask = np.zeros(2*n**2, dtype=bool) mask[n**2:] = True triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1), mask=mask) refiner = mtri.UniformTriRefiner(triang) refi_triang = refiner.refine_triangulation(subdiv=subdiv) x_refi = refi_triang.x y_refi = refi_triang.y n_refi = n * subdiv**2 x_verif = np.linspace(-1., 1., n_refi+1) x_verif, y_verif = np.meshgrid(x_verif, x_verif) x_verif = x_verif.ravel() y_verif = y_verif.ravel() ind1d = np.in1d(np.around(x_verif*(2.5+y_verif), 8), np.around(x_refi*(2.5+y_refi), 8)) assert_array_equal(ind1d, True) # Testing the mask of the refined triangulation refi_mask = refi_triang.mask refi_tri_barycenter_x = np.sum(refi_triang.x[refi_triang.triangles], axis=1) / 3. refi_tri_barycenter_y = np.sum(refi_triang.y[refi_triang.triangles], axis=1) / 3. tri_finder = triang.get_trifinder() refi_tri_indices = tri_finder(refi_tri_barycenter_x, refi_tri_barycenter_y) refi_tri_mask = triang.mask[refi_tri_indices] assert_array_equal(refi_mask, refi_tri_mask) # Testing that the numbering of triangles does not change the # interpolation result. x = np.asarray([0.0, 1.0, 0.0, 1.0]) y = np.asarray([0.0, 0.0, 1.0, 1.0]) triang = [mtri.Triangulation(x, y, [[0, 1, 3], [3, 2, 0]]), mtri.Triangulation(x, y, [[0, 1, 3], [2, 0, 3]])] z = np.sqrt((x-0.3)*(x-0.3) + (y-0.4)*(y-0.4)) # Refining the 2 triangulations and reordering the points xyz_data = [] for i in range(2): refiner = mtri.UniformTriRefiner(triang[i]) refined_triang, refined_z = refiner.refine_field(z, subdiv=1) xyz = np.dstack((refined_triang.x, refined_triang.y, refined_z))[0] xyz = xyz[np.lexsort((xyz[:, 1], xyz[:, 0]))] xyz_data += [xyz] assert_array_almost_equal(xyz_data[0], xyz_data[1]) def meshgrid_triangles(n): """ Utility function. Returns triangles to mesh a np.meshgrid of n x n points """ tri = [] for i in range(n-1): for j in range(n-1): a = i + j*(n) b = (i+1) + j*n c = i + (j+1)*n d = (i+1) + (j+1)*n tri += [[a, b, d], [a, d, c]] return np.array(tri, dtype=np.int32) def test_triplot_return(): # Check that triplot returns the artists it adds from matplotlib.figure import Figure ax = Figure().add_axes([0.1, 0.1, 0.7, 0.7]) triang = mtri.Triangulation( [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], triangles=[[0, 1, 3], [3, 2, 0]]) assert ax.triplot(triang, "b-") is not None, \ 'triplot should return the artist it adds' def test_trirefiner_fortran_contiguous_triangles(): # github issue 4180. Test requires two arrays of triangles that are # identical except that one is C-contiguous and one is fortran-contiguous. triangles1 = np.array([[2, 0, 3], [2, 1, 0]]) assert not np.isfortran(triangles1) triangles2 = np.array(triangles1, copy=True, order='F') assert np.isfortran(triangles2) x = np.array([0.39, 0.59, 0.43, 0.32]) y = np.array([33.99, 34.01, 34.19, 34.18]) triang1 = mtri.Triangulation(x, y, triangles1) triang2 = mtri.Triangulation(x, y, triangles2) refiner1 = mtri.UniformTriRefiner(triang1) refiner2 = mtri.UniformTriRefiner(triang2) fine_triang1 = refiner1.refine_triangulation(subdiv=1) fine_triang2 = refiner2.refine_triangulation(subdiv=1) assert_array_equal(fine_triang1.triangles, fine_triang2.triangles) def test_qhull_triangle_orientation(): # github issue 4437. xi = np.linspace(-2, 2, 100) x, y = map(np.ravel, np.meshgrid(xi, xi)) w = np.logical_and(x > y - 1, np.logical_and(x < -1.95, y > -1.2)) x, y = x[w], y[w] theta = np.radians(25) x1 = x*np.cos(theta) - y*np.sin(theta) y1 = x*np.sin(theta) + y*np.cos(theta) # Calculate Delaunay triangulation using Qhull. triang = mtri.Triangulation(x1, y1) # Neighbors returned by Qhull. qhull_neighbors = triang.neighbors # Obtain neighbors using own C++ calculation. triang._neighbors = None own_neighbors = triang.neighbors assert_array_equal(qhull_neighbors, own_neighbors) def test_trianalyzer_mismatched_indices(): # github issue 4999. x = np.array([0., 1., 0.5, 0., 2.]) y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.]) triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32) mask = np.array([False, False, True], dtype=bool) triang = mtri.Triangulation(x, y, triangles, mask=mask) analyser = mtri.TriAnalyzer(triang) # numpy >= 1.10 raises a VisibleDeprecationWarning in the following line # prior to the fix. triang2 = analyser._get_compressed_triangulation() def test_tricontourf_decreasing_levels(): # github issue 5477. x = [0.0, 1.0, 1.0] y = [0.0, 0.0, 1.0] z = [0.2, 0.4, 0.6] plt.figure() with pytest.raises(ValueError): plt.tricontourf(x, y, z, [1.0, 0.0]) def test_internal_cpp_api(): # Following github issue 8197. import matplotlib._tri as _tri # C++ Triangulation. with pytest.raises(TypeError) as excinfo: triang = _tri.Triangulation() excinfo.match(r'function takes exactly 7 arguments \(0 given\)') with pytest.raises(ValueError) as excinfo: triang = _tri.Triangulation([], [1], [[]], None, None, None, False) excinfo.match(r'x and y must be 1D arrays of the same length') x = [0, 1, 1] y = [0, 0, 1] with pytest.raises(ValueError) as excinfo: triang = _tri.Triangulation(x, y, [[0, 1]], None, None, None, False) excinfo.match(r'triangles must be a 2D array of shape \(\?,3\)') tris = [[0, 1, 2]] with pytest.raises(ValueError) as excinfo: triang = _tri.Triangulation(x, y, tris, [0, 1], None, None, False) excinfo.match(r'mask must be a 1D array with the same length as the ' + r'triangles array') with pytest.raises(ValueError) as excinfo: triang = _tri.Triangulation(x, y, tris, None, [[1]], None, False) excinfo.match(r'edges must be a 2D array with shape \(\?,2\)') with pytest.raises(ValueError) as excinfo: triang = _tri.Triangulation(x, y, tris, None, None, [[-1]], False) excinfo.match(r'neighbors must be a 2D array with the same shape as the ' + r'triangles array') triang = _tri.Triangulation(x, y, tris, None, None, None, False) with pytest.raises(ValueError) as excinfo: triang.calculate_plane_coefficients([]) excinfo.match(r'z array must have same length as triangulation x and y ' + r'arrays') with pytest.raises(ValueError) as excinfo: triang.set_mask([0, 1]) excinfo.match(r'mask must be a 1D array with the same length as the ' + r'triangles array') # C++ TriContourGenerator. with pytest.raises(TypeError) as excinfo: tcg = _tri.TriContourGenerator() excinfo.match(r'function takes exactly 2 arguments \(0 given\)') with pytest.raises(ValueError) as excinfo: tcg = _tri.TriContourGenerator(triang, [1]) excinfo.match(r'z must be a 1D array with the same length as the x and ' + r'y arrays') z = [0, 1, 2] tcg = _tri.TriContourGenerator(triang, z) with pytest.raises(ValueError) as excinfo: tcg.create_filled_contour(1, 0) excinfo.match(r'filled contour levels must be increasing') # C++ TrapezoidMapTriFinder. with pytest.raises(TypeError) as excinfo: trifinder = _tri.TrapezoidMapTriFinder() excinfo.match(r'function takes exactly 1 argument \(0 given\)') trifinder = _tri.TrapezoidMapTriFinder(triang) with pytest.raises(ValueError) as excinfo: trifinder.find_many([0], [0, 1]) excinfo.match(r'x and y must be array_like with same shape') def test_qhull_large_offset(): # github issue 8682. x = np.asarray([0, 1, 0, 1, 0.5]) y = np.asarray([0, 0, 1, 1, 0.5]) offset = 1e10 triang = mtri.Triangulation(x, y) triang_offset = mtri.Triangulation(x + offset, y + offset) assert len(triang.triangles) == len(triang_offset.triangles)
44,908
38.637246
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_texmanager.py
from __future__ import absolute_import, division, print_function import matplotlib.pyplot as plt from matplotlib.texmanager import TexManager def test_fontconfig_preamble(): """ Test that the preamble is included in _fontconfig """ plt.rcParams['text.usetex'] = True tm1 = TexManager() font_config1 = tm1.get_font_config() plt.rcParams['text.latex.preamble'] = ['\\usepackage{txfonts}'] tm2 = TexManager() font_config2 = tm2.get_font_config() assert font_config1 != font_config2
525
24.047619
67
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_preprocess_data.py
from __future__ import (absolute_import, division, print_function) import re import numpy as np import pytest from matplotlib import _preprocess_data # Notes on testing the plotting functions itself # * the individual decorated plotting functions are tested in 'test_axes.py' # * that pyplot functions accept a data kwarg is only tested in # test_axes.test_pie_linewidth_0 # these two get used in multiple tests, so define them here @_preprocess_data(replace_names=["x", "y"], label_namer="y") def plot_func(ax, x, y, ls="x", label=None, w="xyz"): return ("x: %s, y: %s, ls: %s, w: %s, label: %s" % ( list(x), list(y), ls, w, label)) @_preprocess_data(replace_names=["x", "y"], label_namer="y", positional_parameter_names=["x", "y", "ls", "label", "w"]) def plot_func_varargs(ax, *args, **kwargs): all_args = [None, None, "x", None, "xyz"] for i, v in enumerate(args): all_args[i] = v for i, k in enumerate(["x", "y", "ls", "label", "w"]): if k in kwargs: all_args[i] = kwargs[k] x, y, ls, label, w = all_args return ("x: %s, y: %s, ls: %s, w: %s, label: %s" % ( list(x), list(y), ls, w, label)) all_funcs = [plot_func, plot_func_varargs] all_func_ids = ['plot_func', 'plot_func_varargs'] def test_compiletime_checks(): """test decorator invocations -> no replacements""" def func(ax, x, y): pass def func_args(ax, x, y, *args): pass def func_kwargs(ax, x, y, **kwargs): pass def func_no_ax_args(*args, **kwargs): pass # this is ok _preprocess_data(replace_names=["x", "y"])(func) _preprocess_data(replace_names=["x", "y"])(func_kwargs) # this has "enough" information to do all the replaces _preprocess_data(replace_names=["x", "y"])(func_args) # no positional_parameter_names but needed due to replaces with pytest.raises(AssertionError): # z is unknown _preprocess_data(replace_names=["x", "y", "z"])(func_args) with pytest.raises(AssertionError): _preprocess_data(replace_names=["x", "y"])(func_no_ax_args) # no replacements at all -> all ok... _preprocess_data(replace_names=[], label_namer=None)(func) _preprocess_data(replace_names=[], label_namer=None)(func_args) _preprocess_data(replace_names=[], label_namer=None)(func_kwargs) _preprocess_data(replace_names=[], label_namer=None)(func_no_ax_args) # label namer is unknown with pytest.raises(AssertionError): _preprocess_data(label_namer="z")(func) with pytest.raises(AssertionError): _preprocess_data(label_namer="z")(func_args) # but "ok-ish", if func has kwargs -> will show up at runtime :-( _preprocess_data(label_namer="z")(func_kwargs) _preprocess_data(label_namer="z")(func_no_ax_args) def test_label_problems_at_runtime(): """Tests for behaviour which would actually be nice to get rid of.""" @_preprocess_data(label_namer="z") def func(*args, **kwargs): pass # This is a programming mistake: the parameter which should add the # label is not present in the function call. Unfortunately this was masked # due to the **kwargs usage # This would be nice to handle as a compiletime check (see above...) with pytest.warns(RuntimeWarning): func(None, x="a", y="b") def real_func(x, y): pass @_preprocess_data(label_namer="x") def func(*args, **kwargs): real_func(**kwargs) # This sets a label although the function can't handle it. with pytest.raises(TypeError): func(None, x="a", y="b") @pytest.mark.parametrize('func', all_funcs, ids=all_func_ids) def test_function_call_without_data(func): """test without data -> no replacements""" assert (func(None, "x", "y") == "x: ['x'], y: ['y'], ls: x, w: xyz, label: None") assert (func(None, x="x", y="y") == "x: ['x'], y: ['y'], ls: x, w: xyz, label: None") assert (func(None, "x", "y", label="") == "x: ['x'], y: ['y'], ls: x, w: xyz, label: ") assert (func(None, "x", "y", label="text") == "x: ['x'], y: ['y'], ls: x, w: xyz, label: text") assert (func(None, x="x", y="y", label="") == "x: ['x'], y: ['y'], ls: x, w: xyz, label: ") assert (func(None, x="x", y="y", label="text") == "x: ['x'], y: ['y'], ls: x, w: xyz, label: text") @pytest.mark.parametrize('func', all_funcs, ids=all_func_ids) def test_function_call_with_dict_data(func): """Test with dict data -> label comes from the value of 'x' parameter """ data = {"a": [1, 2], "b": [8, 9], "w": "NOT"} assert (func(None, "a", "b", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert (func(None, x="a", y="b", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert (func(None, "a", "b", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert (func(None, "a", "b", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") assert (func(None, x="a", y="b", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert (func(None, x="a", y="b", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") @pytest.mark.parametrize('func', all_funcs, ids=all_func_ids) def test_function_call_with_dict_data_not_in_data(func): "test for the case that one var is not in data -> half replaces, half kept" data = {"a": [1, 2], "w": "NOT"} assert (func(None, "a", "b", data=data) == "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b") assert (func(None, x="a", y="b", data=data) == "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b") assert (func(None, "a", "b", label="", data=data) == "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ") assert (func(None, "a", "b", label="text", data=data) == "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text") assert (func(None, x="a", y="b", label="", data=data) == "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ") assert (func(None, x="a", y="b", label="text", data=data) == "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text") @pytest.mark.parametrize('func', all_funcs, ids=all_func_ids) def test_function_call_with_pandas_data(func, pd): """test with pandas dataframe -> label comes from data["col"].name """ data = pd.DataFrame({"a": np.array([1, 2], dtype=np.int32), "b": np.array([8, 9], dtype=np.int32), "w": ["NOT", "NOT"]}) assert (func(None, "a", "b", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert (func(None, x="a", y="b", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert (func(None, "a", "b", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert (func(None, "a", "b", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") assert (func(None, x="a", y="b", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert (func(None, x="a", y="b", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") def test_function_call_replace_all(): """Test without a "replace_names" argument, all vars should be replaced""" data = {"a": [1, 2], "b": [8, 9], "x": "xyz"} @_preprocess_data(label_namer="y") def func_replace_all(ax, x, y, ls="x", label=None, w="NOT"): return "x: %s, y: %s, ls: %s, w: %s, label: %s" % ( list(x), list(y), ls, w, label) assert (func_replace_all(None, "a", "b", w="x", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert (func_replace_all(None, x="a", y="b", w="x", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert (func_replace_all(None, "a", "b", w="x", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert ( func_replace_all(None, "a", "b", w="x", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") assert ( func_replace_all(None, x="a", y="b", w="x", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert ( func_replace_all(None, x="a", y="b", w="x", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") @_preprocess_data(label_namer="y") def func_varags_replace_all(ax, *args, **kwargs): all_args = [None, None, "x", None, "xyz"] for i, v in enumerate(args): all_args[i] = v for i, k in enumerate(["x", "y", "ls", "label", "w"]): if k in kwargs: all_args[i] = kwargs[k] x, y, ls, label, w = all_args return "x: %s, y: %s, ls: %s, w: %s, label: %s" % ( list(x), list(y), ls, w, label) # in the first case, we can't get a "y" argument, # as we don't know the names of the *args assert (func_varags_replace_all(None, x="a", y="b", w="x", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert ( func_varags_replace_all(None, "a", "b", w="x", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert ( func_varags_replace_all(None, "a", "b", w="x", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") assert ( func_varags_replace_all(None, x="a", y="b", w="x", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert ( func_varags_replace_all(None, x="a", y="b", w="x", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") with pytest.warns(RuntimeWarning): assert (func_varags_replace_all(None, "a", "b", w="x", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None") def test_no_label_replacements(): """Test with "label_namer=None" -> no label replacement at all""" @_preprocess_data(replace_names=["x", "y"], label_namer=None) def func_no_label(ax, x, y, ls="x", label=None, w="xyz"): return "x: %s, y: %s, ls: %s, w: %s, label: %s" % ( list(x), list(y), ls, w, label) data = {"a": [1, 2], "b": [8, 9], "w": "NOT"} assert (func_no_label(None, "a", "b", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None") assert (func_no_label(None, x="a", y="b", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None") assert (func_no_label(None, "a", "b", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert (func_no_label(None, "a", "b", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") def test_more_args_than_pos_parameter(): @_preprocess_data(replace_names=["x", "y"], label_namer="y") def func(ax, x, y, z=1): pass data = {"a": [1, 2], "b": [8, 9], "w": "NOT"} with pytest.raises(RuntimeError): func(None, "a", "b", "z", "z", data=data) def test_function_call_with_replace_all_args(): """Test with a "replace_all_args" argument, all *args should be replaced""" data = {"a": [1, 2], "b": [8, 9], "x": "xyz"} def funcy(ax, *args, **kwargs): all_args = [None, None, "x", None, "NOT"] for i, v in enumerate(args): all_args[i] = v for i, k in enumerate(["x", "y", "ls", "label", "w"]): if k in kwargs: all_args[i] = kwargs[k] x, y, ls, label, w = all_args return "x: %s, y: %s, ls: %s, w: %s, label: %s" % ( list(x), list(y), ls, w, label) func = _preprocess_data(replace_all_args=True, replace_names=["w"], label_namer="y")(funcy) assert (func(None, "a", "b", w="x", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert (func(None, "a", "b", w="x", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") func2 = _preprocess_data(replace_all_args=True, replace_names=["w"], label_namer="y", positional_parameter_names=["x", "y", "ls", "label", "w"])(funcy) assert (func2(None, "a", "b", w="x", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") assert (func2(None, "a", "b", w="x", label="", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") assert (func2(None, "a", "b", w="x", label="text", data=data) == "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") def test_docstring_addition(): @_preprocess_data() def funcy(ax, *args, **kwargs): """Funcy does nothing""" pass assert re.search(r".*All positional and all keyword arguments\.", funcy.__doc__) assert not re.search(r".*All positional arguments\.", funcy.__doc__) assert not re.search(r".*All arguments with the following names: .*", funcy.__doc__) @_preprocess_data(replace_all_args=True, replace_names=[]) def funcy(ax, x, y, z, bar=None): """Funcy does nothing""" pass assert re.search(r".*All positional arguments\.", funcy.__doc__) assert not re.search(r".*All positional and all keyword arguments\.", funcy.__doc__) assert not re.search(r".*All arguments with the following names: .*", funcy.__doc__) @_preprocess_data(replace_all_args=True, replace_names=["bar"]) def funcy(ax, x, y, z, bar=None): """Funcy does nothing""" pass assert re.search(r".*All positional arguments\.", funcy.__doc__) assert re.search(r".*All arguments with the following names: 'bar'\.", funcy.__doc__) assert not re.search(r".*All positional and all keyword arguments\.", funcy.__doc__) @_preprocess_data(replace_names=["x", "bar"]) def funcy(ax, x, y, z, bar=None): """Funcy does nothing""" pass # lists can print in any order, so test for both x,bar and bar,x assert re.search(r".*All arguments with the following names: '.*', '.*'\.", funcy.__doc__) assert re.search(r".*'x'.*", funcy.__doc__) assert re.search(r".*'bar'.*", funcy.__doc__) assert not re.search(r".*All positional and all keyword arguments\.", funcy.__doc__) assert not re.search(r".*All positional arguments\.", funcy.__doc__) def test_positional_parameter_names_as_function(): # Also test the _plot_arg_replacer for plot... from matplotlib.axes._axes import _plot_args_replacer @_preprocess_data(replace_names=["x", "y"], positional_parameter_names=_plot_args_replacer) def funcy(ax, *args, **kwargs): return "{args} | {kwargs}".format(args=args, kwargs=kwargs) # the normal case... data = {"x": "X", "hy1": "Y"} assert funcy(None, "x", "hy1", data=data) == "('X', 'Y') | {}" assert funcy(None, "x", "hy1", "c", data=data) == "('X', 'Y', 'c') | {}" # no arbitrary long args with data with pytest.raises(ValueError): assert (funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}") # In the two arg case, if a valid color spec is in data, we warn but use # it as data... data = {"x": "X", "y": "Y", "ro": "!!"} with pytest.warns(RuntimeWarning): assert funcy(None, "y", "ro", data=data) == "('Y', '!!') | {}"
16,058
40.496124
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_dates.py
from __future__ import absolute_import, division, print_function from six.moves import map import datetime import dateutil import tempfile import numpy as np import pytest import pytz try: # mock in python 3.3+ from unittest import mock except ImportError: import mock from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib.dates as mdates def test_date_numpyx(): # test that numpy dates work properly... base = datetime.datetime(2017, 1, 1) time = [base + datetime.timedelta(days=x) for x in range(0, 3)] timenp = np.array(time, dtype='datetime64[ns]') data = np.array([0., 2., 1.]) fig = plt.figure(figsize=(10, 2)) ax = fig.add_subplot(1, 1, 1) h, = ax.plot(time, data) hnp, = ax.plot(timenp, data) assert np.array_equal(h.get_xdata(orig=False), hnp.get_xdata(orig=False)) fig = plt.figure(figsize=(10, 2)) ax = fig.add_subplot(1, 1, 1) h, = ax.plot(data, time) hnp, = ax.plot(data, timenp) assert np.array_equal(h.get_ydata(orig=False), hnp.get_ydata(orig=False)) @pytest.mark.parametrize('t0', [datetime.datetime(2017, 1, 1, 0, 1, 1), [datetime.datetime(2017, 1, 1, 0, 1, 1), datetime.datetime(2017, 1, 1, 1, 1, 1)], [[datetime.datetime(2017, 1, 1, 0, 1, 1), datetime.datetime(2017, 1, 1, 1, 1, 1)], [datetime.datetime(2017, 1, 1, 2, 1, 1), datetime.datetime(2017, 1, 1, 3, 1, 1)]]]) @pytest.mark.parametrize('dtype', ['datetime64[s]', 'datetime64[us]', 'datetime64[ms]', 'datetime64[ns]']) def test_date_date2num_numpy(t0, dtype): time = mdates.date2num(t0) tnp = np.array(t0, dtype=dtype) nptime = mdates.date2num(tnp) assert np.array_equal(time, nptime) @pytest.mark.parametrize('dtype', ['datetime64[s]', 'datetime64[us]', 'datetime64[ms]', 'datetime64[ns]']) def test_date2num_NaT(dtype): t0 = datetime.datetime(2017, 1, 1, 0, 1, 1) tmpl = [mdates.date2num(t0), np.nan] tnp = np.array([t0, 'NaT'], dtype=dtype) nptime = mdates.date2num(tnp) np.testing.assert_array_equal(tmpl, nptime) @pytest.mark.parametrize('units', ['s', 'ms', 'us', 'ns']) def test_date2num_NaT_scalar(units): tmpl = mdates.date2num(np.datetime64('NaT', units)) assert np.isnan(tmpl) @image_comparison(baseline_images=['date_empty'], extensions=['png']) def test_date_empty(): # make sure mpl does the right thing when told to plot dates even # if no date data has been presented, cf # http://sourceforge.net/tracker/?func=detail&aid=2850075&group_id=80706&atid=560720 fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis_date() @image_comparison(baseline_images=['date_axhspan'], extensions=['png']) def test_date_axhspan(): # test ax hspan with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvspan'], extensions=['png']) def test_date_axvspan(): # test ax hspan with date inputs t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2010, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_xlim(t0 - datetime.timedelta(days=720), tf + datetime.timedelta(days=720)) fig.autofmt_xdate() @image_comparison(baseline_images=['date_axhline'], extensions=['png']) def test_date_axhline(): # test ax hline with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvline'], extensions=['png']) def test_date_axvline(): # test ax hline with date inputs t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvline(t0, color="red", lw=3) ax.set_xlim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.autofmt_xdate() def test_too_many_date_ticks(): # Attempt to test SF 2715172, see # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720 # setting equal datetimes triggers and expander call in # transforms.nonsingular which results in too many ticks in the # DayLocator. This should trigger a Locator.MAXTICKS RuntimeError t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 20) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) with pytest.warns(UserWarning) as rec: ax.set_xlim((t0, tf), auto=True) assert len(rec) == 1 assert 'Attempting to set identical left==right' in str(rec[0].message) ax.plot([], []) ax.xaxis.set_major_locator(mdates.DayLocator()) with pytest.raises(RuntimeError): fig.savefig('junk.png') @image_comparison(baseline_images=['RRuleLocator_bounds'], extensions=['png']) def test_RRuleLocator(): import matplotlib.testing.jpl_units as units units.register() # This will cause the RRuleLocator to go out of bounds when it tries # to add padding to the limits, so we make sure it caps at the correct # boundary values. t0 = datetime.datetime(1000, 1, 1) tf = datetime.datetime(6000, 1, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') rrule = mdates.rrulewrapper(dateutil.rrule.YEARLY, interval=500) locator = mdates.RRuleLocator(rrule) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator)) ax.autoscale_view() fig.autofmt_xdate() def test_RRuleLocator_dayrange(): loc = mdates.DayLocator() x1 = datetime.datetime(year=1, month=1, day=1, tzinfo=pytz.UTC) y1 = datetime.datetime(year=1, month=1, day=16, tzinfo=pytz.UTC) loc.tick_values(x1, y1) # On success, no overflow error shall be thrown @image_comparison(baseline_images=['DateFormatter_fractionalSeconds'], extensions=['png']) def test_DateFormatter(): import matplotlib.testing.jpl_units as units units.register() # Lets make sure that DateFormatter will allow us to have tick marks # at intervals of fractional seconds. t0 = datetime.datetime(2001, 1, 1, 0, 0, 0) tf = datetime.datetime(2001, 1, 1, 0, 0, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') # rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 ) # locator = mpldates.RRuleLocator( rrule ) # ax.xaxis.set_major_locator( locator ) # ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) ) ax.autoscale_view() fig.autofmt_xdate() def test_date_formatter_strftime(): """ Tests that DateFormatter matches datetime.strftime, check microseconds for years before 1900 for bug #3179 as well as a few related issues for years before 1900. """ def test_strftime_fields(dt): """For datetime object dt, check DateFormatter fields""" # Note: the last couple of %%s are to check multiple %s are handled # properly; %% should get replaced by %. formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x") # Compute date fields without using datetime.strftime, # since datetime.strftime does not work before year 1900 formatted_date_str = ( "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} " "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} " "%{microsecond:06d} %x" .format( weekday=str((dt.weekday() + 1) % 7), day=dt.day, month=dt.month, year=dt.year % 100, full_year=dt.year, hour24=dt.hour, hour12=((dt.hour-1) % 12) + 1, minute=dt.minute, second=dt.second, microsecond=dt.microsecond)) assert formatter.strftime(dt) == formatted_date_str try: # Test strftime("%x") with the current locale. import locale # Might not exist on some platforms, such as Windows locale_formatter = mdates.DateFormatter("%x") locale_d_fmt = locale.nl_langinfo(locale.D_FMT) expanded_formatter = mdates.DateFormatter(locale_d_fmt) assert locale_formatter.strftime(dt) == \ expanded_formatter.strftime(dt) except (ImportError, AttributeError): pass for year in range(1, 3000, 71): # Iterate through random set of years test_strftime_fields(datetime.datetime(year, 1, 1)) test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) def test_date_formatter_callable(): scale = -11 locator = mock.Mock(_get_unit=mock.Mock(return_value=scale)) callable_formatting_function = (lambda dates, _: [dt.strftime('%d-%m//%Y') for dt in dates]) formatter = mdates.AutoDateFormatter(locator) formatter.scaled[-10] = callable_formatting_function assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] def test_drange(): """ This test should check if drange works as expected, and if all the rounding errors are fixed """ start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC) end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) delta = datetime.timedelta(hours=1) # We expect 24 values in drange(start, end, delta), because drange returns # dates from an half open interval [start, end) assert len(mdates.drange(start, end, delta)) == 24 # if end is a little bit later, we expect the range to contain one element # more end = end + datetime.timedelta(microseconds=1) assert len(mdates.drange(start, end, delta)) == 25 # reset end end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) # and tst drange with "complicated" floats: # 4 hours = 1/6 day, this is an "dangerous" float delta = datetime.timedelta(hours=4) daterange = mdates.drange(start, end, delta) assert len(daterange) == 6 assert mdates.num2date(daterange[-1]) == (end - delta) def test_empty_date_with_year_formatter(): # exposes sf bug 2861426: # https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720 # update: I am no longer believe this is a bug, as I commented on # the tracker. The question is now: what to do with this test import matplotlib.dates as dates fig = plt.figure() ax = fig.add_subplot(111) yearFmt = dates.DateFormatter('%Y') ax.xaxis.set_major_formatter(yearFmt) with tempfile.TemporaryFile() as fh: with pytest.raises(ValueError): fig.savefig(fh) def test_auto_date_locator(): def _create_auto_date_locator(date1, date2): locator = mdates.AutoDateLocator() locator.create_dummy_axis() locator.set_view_interval(mdates.date2num(date1), mdates.date2num(date2)) return locator d1 = datetime.datetime(1990, 1, 1) results = ([datetime.timedelta(weeks=52 * 200), ['1990-01-01 00:00:00+00:00', '2010-01-01 00:00:00+00:00', '2030-01-01 00:00:00+00:00', '2050-01-01 00:00:00+00:00', '2070-01-01 00:00:00+00:00', '2090-01-01 00:00:00+00:00', '2110-01-01 00:00:00+00:00', '2130-01-01 00:00:00+00:00', '2150-01-01 00:00:00+00:00', '2170-01-01 00:00:00+00:00'] ], [datetime.timedelta(weeks=52), ['1990-01-01 00:00:00+00:00', '1990-02-01 00:00:00+00:00', '1990-03-01 00:00:00+00:00', '1990-04-01 00:00:00+00:00', '1990-05-01 00:00:00+00:00', '1990-06-01 00:00:00+00:00', '1990-07-01 00:00:00+00:00', '1990-08-01 00:00:00+00:00', '1990-09-01 00:00:00+00:00', '1990-10-01 00:00:00+00:00', '1990-11-01 00:00:00+00:00', '1990-12-01 00:00:00+00:00'] ], [datetime.timedelta(days=141), ['1990-01-05 00:00:00+00:00', '1990-01-26 00:00:00+00:00', '1990-02-16 00:00:00+00:00', '1990-03-09 00:00:00+00:00', '1990-03-30 00:00:00+00:00', '1990-04-20 00:00:00+00:00', '1990-05-11 00:00:00+00:00'] ], [datetime.timedelta(days=40), ['1990-01-03 00:00:00+00:00', '1990-01-10 00:00:00+00:00', '1990-01-17 00:00:00+00:00', '1990-01-24 00:00:00+00:00', '1990-01-31 00:00:00+00:00', '1990-02-07 00:00:00+00:00'] ], [datetime.timedelta(hours=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 04:00:00+00:00', '1990-01-01 08:00:00+00:00', '1990-01-01 12:00:00+00:00', '1990-01-01 16:00:00+00:00', '1990-01-01 20:00:00+00:00', '1990-01-02 00:00:00+00:00', '1990-01-02 04:00:00+00:00', '1990-01-02 08:00:00+00:00', '1990-01-02 12:00:00+00:00', '1990-01-02 16:00:00+00:00'] ], [datetime.timedelta(minutes=20), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:05:00+00:00', '1990-01-01 00:10:00+00:00', '1990-01-01 00:15:00+00:00', '1990-01-01 00:20:00+00:00'] ], [datetime.timedelta(seconds=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:00:05+00:00', '1990-01-01 00:00:10+00:00', '1990-01-01 00:00:15+00:00', '1990-01-01 00:00:20+00:00', '1990-01-01 00:00:25+00:00', '1990-01-01 00:00:30+00:00', '1990-01-01 00:00:35+00:00', '1990-01-01 00:00:40+00:00'] ], [datetime.timedelta(microseconds=1500), ['1989-12-31 23:59:59.999500+00:00', '1990-01-01 00:00:00+00:00', '1990-01-01 00:00:00.000500+00:00', '1990-01-01 00:00:00.001000+00:00', '1990-01-01 00:00:00.001500+00:00'] ], ) for t_delta, expected in results: d2 = d1 + t_delta locator = _create_auto_date_locator(d1, d2) assert list(map(str, mdates.num2date(locator()))) == expected def test_auto_date_locator_intmult(): def _create_auto_date_locator(date1, date2): locator = mdates.AutoDateLocator(interval_multiples=True) locator.create_dummy_axis() locator.set_view_interval(mdates.date2num(date1), mdates.date2num(date2)) return locator d1 = datetime.datetime(1997, 1, 1) results = ([datetime.timedelta(weeks=52 * 200), ['1980-01-01 00:00:00+00:00', '2000-01-01 00:00:00+00:00', '2020-01-01 00:00:00+00:00', '2040-01-01 00:00:00+00:00', '2060-01-01 00:00:00+00:00', '2080-01-01 00:00:00+00:00', '2100-01-01 00:00:00+00:00', '2120-01-01 00:00:00+00:00', '2140-01-01 00:00:00+00:00', '2160-01-01 00:00:00+00:00', '2180-01-01 00:00:00+00:00', '2200-01-01 00:00:00+00:00'] ], [datetime.timedelta(weeks=52), ['1997-01-01 00:00:00+00:00', '1997-02-01 00:00:00+00:00', '1997-03-01 00:00:00+00:00', '1997-04-01 00:00:00+00:00', '1997-05-01 00:00:00+00:00', '1997-06-01 00:00:00+00:00', '1997-07-01 00:00:00+00:00', '1997-08-01 00:00:00+00:00', '1997-09-01 00:00:00+00:00', '1997-10-01 00:00:00+00:00', '1997-11-01 00:00:00+00:00', '1997-12-01 00:00:00+00:00'] ], [datetime.timedelta(days=141), ['1997-01-01 00:00:00+00:00', '1997-01-22 00:00:00+00:00', '1997-02-01 00:00:00+00:00', '1997-02-22 00:00:00+00:00', '1997-03-01 00:00:00+00:00', '1997-03-22 00:00:00+00:00', '1997-04-01 00:00:00+00:00', '1997-04-22 00:00:00+00:00', '1997-05-01 00:00:00+00:00', '1997-05-22 00:00:00+00:00'] ], [datetime.timedelta(days=40), ['1997-01-01 00:00:00+00:00', '1997-01-08 00:00:00+00:00', '1997-01-15 00:00:00+00:00', '1997-01-22 00:00:00+00:00', '1997-01-29 00:00:00+00:00', '1997-02-01 00:00:00+00:00', '1997-02-08 00:00:00+00:00'] ], [datetime.timedelta(hours=40), ['1997-01-01 00:00:00+00:00', '1997-01-01 04:00:00+00:00', '1997-01-01 08:00:00+00:00', '1997-01-01 12:00:00+00:00', '1997-01-01 16:00:00+00:00', '1997-01-01 20:00:00+00:00', '1997-01-02 00:00:00+00:00', '1997-01-02 04:00:00+00:00', '1997-01-02 08:00:00+00:00', '1997-01-02 12:00:00+00:00', '1997-01-02 16:00:00+00:00'] ], [datetime.timedelta(minutes=20), ['1997-01-01 00:00:00+00:00', '1997-01-01 00:05:00+00:00', '1997-01-01 00:10:00+00:00', '1997-01-01 00:15:00+00:00', '1997-01-01 00:20:00+00:00'] ], [datetime.timedelta(seconds=40), ['1997-01-01 00:00:00+00:00', '1997-01-01 00:00:05+00:00', '1997-01-01 00:00:10+00:00', '1997-01-01 00:00:15+00:00', '1997-01-01 00:00:20+00:00', '1997-01-01 00:00:25+00:00', '1997-01-01 00:00:30+00:00', '1997-01-01 00:00:35+00:00', '1997-01-01 00:00:40+00:00'] ], [datetime.timedelta(microseconds=1500), ['1996-12-31 23:59:59.999500+00:00', '1997-01-01 00:00:00+00:00', '1997-01-01 00:00:00.000500+00:00', '1997-01-01 00:00:00.001000+00:00', '1997-01-01 00:00:00.001500+00:00'] ], ) for t_delta, expected in results: d2 = d1 + t_delta locator = _create_auto_date_locator(d1, d2) assert list(map(str, mdates.num2date(locator()))) == expected @image_comparison(baseline_images=['date_inverted_limit'], extensions=['png']) def test_date_inverted_limit(): # test ax hline with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) ax.invert_yaxis() fig.subplots_adjust(left=0.25) def _test_date2num_dst(date_range, tz_convert): # Timezones BRUSSELS = pytz.timezone('Europe/Brussels') UTC = pytz.UTC # Create a list of timezone-aware datetime objects in UTC # Interval is 0b0.0000011 days, to prevent float rounding issues dtstart = datetime.datetime(2014, 3, 30, 0, 0, tzinfo=UTC) interval = datetime.timedelta(minutes=33, seconds=45) interval_days = 0.0234375 # 2025 / 86400 seconds N = 8 dt_utc = date_range(start=dtstart, freq=interval, periods=N) dt_bxl = tz_convert(dt_utc, BRUSSELS) expected_ordinalf = [735322.0 + (i * interval_days) for i in range(N)] actual_ordinalf = list(mdates.date2num(dt_bxl)) assert actual_ordinalf == expected_ordinalf def test_date2num_dst(): # Test for github issue #3896, but in date2num around DST transitions # with a timezone-aware pandas date_range object. class dt_tzaware(datetime.datetime): """ This bug specifically occurs because of the normalization behavior of pandas Timestamp objects, so in order to replicate it, we need a datetime-like object that applies timezone normalization after subtraction. """ def __sub__(self, other): r = super(dt_tzaware, self).__sub__(other) tzinfo = getattr(r, 'tzinfo', None) if tzinfo is not None: localizer = getattr(tzinfo, 'normalize', None) if localizer is not None: r = tzinfo.normalize(r) if isinstance(r, datetime.datetime): r = self.mk_tzaware(r) return r def __add__(self, other): return self.mk_tzaware(super(dt_tzaware, self).__add__(other)) def astimezone(self, tzinfo): dt = super(dt_tzaware, self).astimezone(tzinfo) return self.mk_tzaware(dt) @classmethod def mk_tzaware(cls, datetime_obj): kwargs = {} attrs = ('year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzinfo') for attr in attrs: val = getattr(datetime_obj, attr, None) if val is not None: kwargs[attr] = val return cls(**kwargs) # Define a date_range function similar to pandas.date_range def date_range(start, freq, periods): dtstart = dt_tzaware.mk_tzaware(start) return [dtstart + (i * freq) for i in range(periods)] # Define a tz_convert function that converts a list to a new time zone. def tz_convert(dt_list, tzinfo): return [d.astimezone(tzinfo) for d in dt_list] _test_date2num_dst(date_range, tz_convert) def test_date2num_dst_pandas(pd): # Test for github issue #3896, but in date2num around DST transitions # with a timezone-aware pandas date_range object. def tz_convert(*args): return pd.DatetimeIndex.tz_convert(*args).astype(object) _test_date2num_dst(pd.date_range, tz_convert) @pytest.mark.parametrize("attach_tz, get_tz", [ (lambda dt, zi: zi.localize(dt), lambda n: pytz.timezone(n)), (lambda dt, zi: dt.replace(tzinfo=zi), lambda n: dateutil.tz.gettz(n))]) def test_rrulewrapper(attach_tz, get_tz): SYD = get_tz('Australia/Sydney') dtstart = attach_tz(datetime.datetime(2017, 4, 1, 0), SYD) dtend = attach_tz(datetime.datetime(2017, 4, 4, 0), SYD) rule = mdates.rrulewrapper(freq=dateutil.rrule.DAILY, dtstart=dtstart) act = rule.between(dtstart, dtend) exp = [datetime.datetime(2017, 4, 1, 13, tzinfo=dateutil.tz.tzutc()), datetime.datetime(2017, 4, 2, 14, tzinfo=dateutil.tz.tzutc())] assert act == exp def test_DayLocator(): with pytest.raises(ValueError): mdates.DayLocator(interval=-1) with pytest.raises(ValueError): mdates.DayLocator(interval=-1.5) with pytest.raises(ValueError): mdates.DayLocator(interval=0) with pytest.raises(ValueError): mdates.DayLocator(interval=1.3) mdates.DayLocator(interval=1.0) def test_tz_utc(): dt = datetime.datetime(1970, 1, 1, tzinfo=mdates.UTC) dt.tzname() @pytest.mark.parametrize("x, tdelta", [(1, datetime.timedelta(days=1)), ([1, 1.5], [datetime.timedelta(days=1), datetime.timedelta(days=1.5)])]) def test_num2timedelta(x, tdelta): dt = mdates.num2timedelta(x) assert dt == tdelta
24,373
37.9984
89
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_lines.py
""" Tests specific to the lines module. """ from __future__ import absolute_import, division, print_function import itertools import matplotlib.lines as mlines import pytest from timeit import repeat import numpy as np from cycler import cycler import matplotlib import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison # Runtimes on a loaded system are inherently flaky. Not so much that a rerun # won't help, hopefully. @pytest.mark.flaky(reruns=3) def test_invisible_Line_rendering(): """ Github issue #1256 identified a bug in Line.draw method Despite visibility attribute set to False, the draw method was not returning early enough and some pre-rendering code was executed though not necessary. Consequence was an excessive draw time for invisible Line instances holding a large number of points (Npts> 10**6) """ # Creates big x and y data: N = 10**7 x = np.linspace(0,1,N) y = np.random.normal(size=N) # Create a plot figure: fig = plt.figure() ax = plt.subplot(111) # Create a "big" Line instance: l = mlines.Line2D(x,y) l.set_visible(False) # but don't add it to the Axis instance `ax` # [here Interactive panning and zooming is pretty responsive] # Time the canvas drawing: t_no_line = min(repeat(fig.canvas.draw, number=1, repeat=3)) # (gives about 25 ms) # Add the big invisible Line: ax.add_line(l) # [Now interactive panning and zooming is very slow] # Time the canvas drawing: t_unvisible_line = min(repeat(fig.canvas.draw, number=1, repeat=3)) # gives about 290 ms for N = 10**7 pts slowdown_factor = (t_unvisible_line/t_no_line) slowdown_threshold = 2 # trying to avoid false positive failures assert slowdown_factor < slowdown_threshold def test_set_line_coll_dash(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) np.random.seed(0) # Testing setting linestyles for line collections. # This should not produce an error. cs = ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) assert True @image_comparison(baseline_images=['line_dashes'], remove_text=True) def test_line_dashes(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(range(10), linestyle=(0, (3, 3)), lw=5) def test_line_colors(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(range(10), color='none') ax.plot(range(10), color='r') ax.plot(range(10), color='.3') ax.plot(range(10), color=(1, 0, 0, 1)) ax.plot(range(10), color=(1, 0, 0)) fig.canvas.draw() assert True def test_linestyle_variants(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for ls in ["-", "solid", "--", "dashed", "-.", "dashdot", ":", "dotted"]: ax.plot(range(10), linestyle=ls) fig.canvas.draw() assert True def test_valid_linestyles(): line = mlines.Line2D([], []) with pytest.raises(ValueError): line.set_linestyle('aardvark') @image_comparison(baseline_images=['drawstyle_variants'], remove_text=True, extensions=["png"]) def test_drawstyle_variants(): fig, axs = plt.subplots(6) dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None] # We want to check that drawstyles are properly handled even for very long # lines (for which the subslice optimization is on); however, we need # to zoom in so that the difference between the drawstyles is actually # visible. for ax, ds in zip(axs.flat, dss): ax.plot(range(2000), drawstyle=ds) ax.set(xlim=(0, 2), ylim=(0, 2)) def test_valid_drawstyles(): line = mlines.Line2D([], []) with pytest.raises(ValueError): line.set_drawstyle('foobar') def test_set_drawstyle(): x = np.linspace(0, 2*np.pi, 10) y = np.sin(x) fig, ax = plt.subplots() line, = ax.plot(x, y) line.set_drawstyle("steps-pre") assert len(line.get_path().vertices) == 2*len(x)-1 line.set_drawstyle("default") assert len(line.get_path().vertices) == len(x) @image_comparison(baseline_images=['line_collection_dashes'], remove_text=True) def test_set_line_coll_dash_image(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) np.random.seed(0) cs = ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) @image_comparison(baseline_images=['marker_fill_styles'], remove_text=True, extensions=['png']) def test_marker_fill_styles(): colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y', np.array([0, 0, 0])]) altcolor = 'lightgreen' y = np.array([1, 1]) x = np.array([0, 9]) fig, ax = plt.subplots() for j, marker in enumerate(mlines.Line2D.filled_markers): for i, fs in enumerate(mlines.Line2D.fillStyles): color = next(colors) ax.plot(j * 10 + x, y + i + .5 * (j % 2), marker=marker, markersize=20, markerfacecoloralt=altcolor, fillstyle=fs, label=fs, linewidth=5, color=color, markeredgecolor=color, markeredgewidth=2) ax.set_ylim([0, 7.5]) ax.set_xlim([-5, 155]) @image_comparison(baseline_images=['scaled_lines'], style='default') def test_lw_scaling(): th = np.linspace(0, 32) fig, ax = plt.subplots() lins_styles = ['dashed', 'dotted', 'dashdot'] cy = cycler(matplotlib.rcParams['axes.prop_cycle']) for j, (ls, sty) in enumerate(zip(lins_styles, cy)): for lw in np.linspace(.5, 10, 10): ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty) def test_nan_is_sorted(): line = mlines.Line2D([], []) assert line._is_sorted(np.array([1, 2, 3])) assert line._is_sorted(np.array([1, np.nan, 3])) assert not line._is_sorted([3, 5] + [np.nan] * 100 + [0, 2])
6,018
29.095
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_colors.py
from __future__ import absolute_import, division, print_function import copy import six import itertools import warnings from distutils.version import LooseVersion as V import numpy as np import pytest from numpy.testing.utils import assert_array_equal, assert_array_almost_equal from matplotlib import cycler import matplotlib import matplotlib.colors as mcolors import matplotlib.cm as cm import matplotlib.colorbar as mcolorbar import matplotlib.cbook as cbook import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison def test_resample(): """ Github issue #6025 pointed to incorrect ListedColormap._resample; here we test the method for LinearSegmentedColormap as well. """ n = 101 colorlist = np.empty((n, 4), float) colorlist[:, 0] = np.linspace(0, 1, n) colorlist[:, 1] = 0.2 colorlist[:, 2] = np.linspace(1, 0, n) colorlist[:, 3] = 0.7 lsc = mcolors.LinearSegmentedColormap.from_list('lsc', colorlist) lc = mcolors.ListedColormap(colorlist) lsc3 = lsc._resample(3) lc3 = lc._resample(3) expected = np.array([[0.0, 0.2, 1.0, 0.7], [0.5, 0.2, 0.5, 0.7], [1.0, 0.2, 0.0, 0.7]], float) assert_array_almost_equal(lsc3([0, 0.5, 1]), expected) assert_array_almost_equal(lc3([0, 0.5, 1]), expected) def test_colormap_copy(): cm = plt.cm.Reds cm_copy = copy.copy(cm) with np.errstate(invalid='ignore'): ret1 = cm_copy([-1, 0, .5, 1, np.nan, np.inf]) cm2 = copy.copy(cm_copy) cm2.set_bad('g') with np.errstate(invalid='ignore'): ret2 = cm_copy([-1, 0, .5, 1, np.nan, np.inf]) assert_array_equal(ret1, ret2) def test_colormap_endian(): """ Github issue #1005: a bug in putmask caused erroneous mapping of 1.0 when input from a non-native-byteorder array. """ cmap = cm.get_cmap("jet") # Test under, over, and invalid along with values 0 and 1. a = [-0.5, 0, 0.5, 1, 1.5, np.nan] for dt in ["f2", "f4", "f8"]: anative = np.ma.masked_invalid(np.array(a, dtype=dt)) aforeign = anative.byteswap().newbyteorder() assert_array_equal(cmap(anative), cmap(aforeign)) def test_BoundaryNorm(): """ Github issue #1258: interpolation was failing with numpy 1.7 pre-release. """ boundaries = [0, 1.1, 2.2] vals = [-1, 0, 1, 2, 2.2, 4] # Without interpolation expected = [-1, 0, 0, 1, 2, 2] ncolors = len(boundaries) - 1 bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # ncolors != len(boundaries) - 1 triggers interpolation expected = [-1, 0, 0, 2, 3, 3] ncolors = len(boundaries) bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # more boundaries for a third color boundaries = [0, 1, 2, 3] vals = [-1, 0.1, 1.1, 2.2, 4] ncolors = 5 expected = [-1, 0, 2, 4, 5] bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # a scalar as input should not trigger an error and should return a scalar boundaries = [0, 1, 2] vals = [-1, 0.1, 1.1, 2.2] bn = mcolors.BoundaryNorm(boundaries, 2) expected = [-1, 0, 1, 2] for v, ex in zip(vals, expected): ret = bn(v) assert isinstance(ret, six.integer_types) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) # same with interp bn = mcolors.BoundaryNorm(boundaries, 3) expected = [-1, 0, 2, 3] for v, ex in zip(vals, expected): ret = bn(v) assert isinstance(ret, six.integer_types) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) # Clipping bn = mcolors.BoundaryNorm(boundaries, 3, clip=True) expected = [0, 0, 2, 2] for v, ex in zip(vals, expected): ret = bn(v) assert isinstance(ret, six.integer_types) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) # Masked arrays boundaries = [0, 1.1, 2.2] vals = np.ma.masked_invalid([-1., np.NaN, 0, 1.4, 9]) # Without interpolation ncolors = len(boundaries) - 1 bn = mcolors.BoundaryNorm(boundaries, ncolors) expected = np.ma.masked_array([-1, -99, 0, 1, 2], mask=[0, 1, 0, 0, 0]) assert_array_equal(bn(vals), expected) # With interpolation bn = mcolors.BoundaryNorm(boundaries, len(boundaries)) expected = np.ma.masked_array([-1, -99, 0, 2, 3], mask=[0, 1, 0, 0, 0]) assert_array_equal(bn(vals), expected) # Non-trivial masked arrays vals = np.ma.masked_invalid([np.Inf, np.NaN]) assert np.all(bn(vals).mask) vals = np.ma.masked_invalid([np.Inf]) assert np.all(bn(vals).mask) def test_LogNorm(): """ LogNorm ignored clip, now it has the same behavior as Normalize, e.g., values > vmax are bigger than 1 without clip, with clip they are 1. """ ln = mcolors.LogNorm(clip=True, vmax=5) assert_array_equal(ln([1, 6]), [0, 1.0]) def test_PowerNorm(): a = np.array([0, 0.5, 1, 1.5], dtype=float) pnorm = mcolors.PowerNorm(1) norm = mcolors.Normalize() assert_array_almost_equal(norm(a), pnorm(a)) a = np.array([-0.5, 0, 2, 4, 8], dtype=float) expected = [0, 0, 1/16, 1/4, 1] pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8) assert_array_almost_equal(pnorm(a), expected) assert pnorm(a[0]) == expected[0] assert pnorm(a[2]) == expected[2] assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:]) # Clip = True a = np.array([-0.5, 0, 1, 8, 16], dtype=float) expected = [0, 0, 0, 1, 1] pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True) assert_array_almost_equal(pnorm(a), expected) assert pnorm(a[0]) == expected[0] assert pnorm(a[-1]) == expected[-1] # Clip = True at call time a = np.array([-0.5, 0, 1, 8, 16], dtype=float) expected = [0, 0, 0, 1, 1] pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False) assert_array_almost_equal(pnorm(a, clip=True), expected) assert pnorm(a[0], clip=True) == expected[0] assert pnorm(a[-1], clip=True) == expected[-1] def test_Normalize(): norm = mcolors.Normalize() vals = np.arange(-10, 10, 1, dtype=float) _inverse_tester(norm, vals) _scalar_tester(norm, vals) _mask_tester(norm, vals) # Handle integer input correctly (don't overflow when computing max-min, # i.e. 127-(-128) here). vals = np.array([-128, 127], dtype=np.int8) norm = mcolors.Normalize(vals.min(), vals.max()) assert_array_equal(np.asarray(norm(vals)), [0, 1]) # Don't lose precision on longdoubles (float128 on Linux): # for array inputs... vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble) norm = mcolors.Normalize(vals.min(), vals.max()) assert_array_equal(np.asarray(norm(vals)), [0, 1]) # and for scalar ones. eps = np.finfo(np.longdouble).resolution norm = plt.Normalize(1, 1 + 100 * eps) # This returns exactly 0.5 when longdouble is extended precision (80-bit), # but only a value close to it when it is quadruple precision (128-bit). assert 0 < norm(1 + 50 * eps) < 1 def test_SymLogNorm(): """ Test SymLogNorm behavior """ norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2) vals = np.array([-30, -1, 2, 6], dtype=float) normed_vals = norm(vals) expected = [0., 0.53980074, 0.826991, 1.02758204] assert_array_almost_equal(normed_vals, expected) _inverse_tester(norm, vals) _scalar_tester(norm, vals) _mask_tester(norm, vals) # Ensure that specifying vmin returns the same result as above norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2) normed_vals = norm(vals) assert_array_almost_equal(normed_vals, expected) def test_SymLogNorm_colorbar(): """ Test un-called SymLogNorm in a colorbar. """ norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1) fig = plt.figure() cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm) plt.close(fig) def test_SymLogNorm_single_zero(): """ Test SymLogNorm to ensure it is not adding sub-ticks to zero label """ fig = plt.figure() norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1) cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm) ticks = cbar.get_ticks() assert sum(ticks == 0) == 1 plt.close(fig) def _inverse_tester(norm_instance, vals): """ Checks if the inverse of the given normalization is working. """ assert_array_almost_equal(norm_instance.inverse(norm_instance(vals)), vals) def _scalar_tester(norm_instance, vals): """ Checks if scalars and arrays are handled the same way. Tests only for float. """ scalar_result = [norm_instance(float(v)) for v in vals] assert_array_almost_equal(scalar_result, norm_instance(vals)) def _mask_tester(norm_instance, vals): """ Checks mask handling """ masked_array = np.ma.array(vals) masked_array[0] = np.ma.masked assert_array_equal(masked_array.mask, norm_instance(masked_array).mask) @image_comparison(baseline_images=['levels_and_colors'], extensions=['png']) def test_cmap_and_norm_from_levels_and_colors(): data = np.linspace(-2, 4, 49).reshape(7, 7) levels = [-1, 2, 2.5, 3] colors = ['red', 'green', 'blue', 'yellow', 'black'] extend = 'both' cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend) ax = plt.axes() m = plt.pcolormesh(data, cmap=cmap, norm=norm) plt.colorbar(m) # Hide the axes labels (but not the colorbar ones, as they are useful) ax.tick_params(labelleft=False, labelbottom=False) def test_cmap_and_norm_from_levels_and_colors2(): levels = [-1, 2, 2.5, 3] colors = ['red', (0, 1, 0), 'blue', (0.5, 0.5, 0.5), (0.0, 0.0, 0.0, 1.0)] clr = mcolors.to_rgba_array(colors) bad = (0.1, 0.1, 0.1, 0.1) no_color = (0.0, 0.0, 0.0, 0.0) masked_value = 'masked_value' # Define the test values which are of interest. # Note: levels are lev[i] <= v < lev[i+1] tests = [('both', None, {-2: clr[0], -1: clr[1], 2: clr[2], 2.25: clr[2], 3: clr[4], 3.5: clr[4], masked_value: bad}), ('min', -1, {-2: clr[0], -1: clr[1], 2: clr[2], 2.25: clr[2], 3: no_color, 3.5: no_color, masked_value: bad}), ('max', -1, {-2: no_color, -1: clr[0], 2: clr[1], 2.25: clr[1], 3: clr[3], 3.5: clr[3], masked_value: bad}), ('neither', -2, {-2: no_color, -1: clr[0], 2: clr[1], 2.25: clr[1], 3: no_color, 3.5: no_color, masked_value: bad}), ] for extend, i1, cases in tests: cmap, norm = mcolors.from_levels_and_colors(levels, colors[0:i1], extend=extend) cmap.set_bad(bad) for d_val, expected_color in cases.items(): if d_val == masked_value: d_val = np.ma.array([1], mask=True) else: d_val = [d_val] assert_array_equal(expected_color, cmap(norm(d_val))[0], 'Wih extend={0!r} and data ' 'value={1!r}'.format(extend, d_val)) with pytest.raises(ValueError): mcolors.from_levels_and_colors(levels, colors) def test_rgb_hsv_round_trip(): for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]: np.random.seed(0) tt = np.random.random(a_shape) assert_array_almost_equal(tt, mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt))) assert_array_almost_equal(tt, mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt))) def test_autoscale_masked(): # Test for #2336. Previously fully masked data would trigger a ValueError. data = np.ma.masked_all((12, 20)) plt.pcolor(data) plt.draw() def test_colors_no_float(): # Gray must be a string to distinguish 3-4 grays from RGB or RGBA. with pytest.raises(ValueError): mcolors.to_rgba(0.4) @image_comparison(baseline_images=['light_source_shading_topo'], extensions=['png']) def test_light_source_topo_surface(): """Shades a DEM using different v.e.'s and blend modes.""" fname = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False) dem = np.load(fname) elev = dem['elevation'] # Get the true cellsize in meters for accurate vertical exaggeration # Convert from decimal degrees to meters dx, dy = dem['dx'], dem['dy'] dx = 111320.0 * dx * np.cos(dem['ymin']) dy = 111320.0 * dy dem.close() ls = mcolors.LightSource(315, 45) cmap = cm.gist_earth fig, axes = plt.subplots(nrows=3, ncols=3) for row, mode in zip(axes, ['hsv', 'overlay', 'soft']): for ax, ve in zip(row, [0.1, 1, 10]): rgb = ls.shade(elev, cmap, vert_exag=ve, dx=dx, dy=dy, blend_mode=mode) ax.imshow(rgb) ax.set(xticks=[], yticks=[]) def test_light_source_shading_default(): """Array comparison test for the default "hsv" blend mode. Ensure the default result doesn't change without warning.""" y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j] z = 10 * np.cos(x**2 + y**2) cmap = plt.cm.copper ls = mcolors.LightSource(315, 45) rgb = ls.shade(z, cmap) # Result stored transposed and rounded for more compact display... expect = np.array( [[[0.00, 0.45, 0.90, 0.90, 0.82, 0.62, 0.28, 0.00], [0.45, 0.94, 0.99, 1.00, 1.00, 0.96, 0.65, 0.17], [0.90, 0.99, 1.00, 1.00, 1.00, 1.00, 0.94, 0.35], [0.90, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.49], [0.82, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.41], [0.62, 0.96, 1.00, 1.00, 1.00, 1.00, 0.90, 0.07], [0.28, 0.65, 0.94, 1.00, 1.00, 0.90, 0.35, 0.01], [0.00, 0.17, 0.35, 0.49, 0.41, 0.07, 0.01, 0.00]], [[0.00, 0.28, 0.59, 0.72, 0.62, 0.40, 0.18, 0.00], [0.28, 0.78, 0.93, 0.92, 0.83, 0.66, 0.39, 0.11], [0.59, 0.93, 0.99, 1.00, 0.92, 0.75, 0.50, 0.21], [0.72, 0.92, 1.00, 0.99, 0.93, 0.76, 0.51, 0.18], [0.62, 0.83, 0.92, 0.93, 0.87, 0.68, 0.42, 0.08], [0.40, 0.66, 0.75, 0.76, 0.68, 0.52, 0.23, 0.02], [0.18, 0.39, 0.50, 0.51, 0.42, 0.23, 0.00, 0.00], [0.00, 0.11, 0.21, 0.18, 0.08, 0.02, 0.00, 0.00]], [[0.00, 0.18, 0.38, 0.46, 0.39, 0.26, 0.11, 0.00], [0.18, 0.50, 0.70, 0.75, 0.64, 0.44, 0.25, 0.07], [0.38, 0.70, 0.91, 0.98, 0.81, 0.51, 0.29, 0.13], [0.46, 0.75, 0.98, 0.96, 0.84, 0.48, 0.22, 0.12], [0.39, 0.64, 0.81, 0.84, 0.71, 0.31, 0.11, 0.05], [0.26, 0.44, 0.51, 0.48, 0.31, 0.10, 0.03, 0.01], [0.11, 0.25, 0.29, 0.22, 0.11, 0.03, 0.00, 0.00], [0.00, 0.07, 0.13, 0.12, 0.05, 0.01, 0.00, 0.00]], [[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]] ]).T if (V(np.__version__) == V('1.9.0')): # Numpy 1.9.0 uses a 2. order algorithm on the edges by default # This was changed back again in 1.9.1 expect = expect[1:-1, 1:-1, :] rgb = rgb[1:-1, 1:-1, :] assert_array_almost_equal(rgb, expect, decimal=2) @pytest.mark.xfail(V('1.7.0') <= V(np.__version__) <= V('1.9.0'), reason='NumPy version is not buggy') # Numpy 1.9.1 fixed a bug in masked arrays which resulted in # additional elements being masked when calculating the gradient thus # the output is different with earlier numpy versions. def test_light_source_masked_shading(): """Array comparison test for a surface with a masked portion. Ensures that we don't wind up with "fringes" of odd colors around masked regions.""" y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j] z = 10 * np.cos(x**2 + y**2) z = np.ma.masked_greater(z, 9.9) cmap = plt.cm.copper ls = mcolors.LightSource(315, 45) rgb = ls.shade(z, cmap) # Result stored transposed and rounded for more compact display... expect = np.array( [[[0.00, 0.46, 0.91, 0.91, 0.84, 0.64, 0.29, 0.00], [0.46, 0.96, 1.00, 1.00, 1.00, 0.97, 0.67, 0.18], [0.91, 1.00, 1.00, 1.00, 1.00, 1.00, 0.96, 0.36], [0.91, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 0.51], [0.84, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 0.44], [0.64, 0.97, 1.00, 1.00, 1.00, 1.00, 0.94, 0.09], [0.29, 0.67, 0.96, 1.00, 1.00, 0.94, 0.38, 0.01], [0.00, 0.18, 0.36, 0.51, 0.44, 0.09, 0.01, 0.00]], [[0.00, 0.29, 0.61, 0.75, 0.64, 0.41, 0.18, 0.00], [0.29, 0.81, 0.95, 0.93, 0.85, 0.68, 0.40, 0.11], [0.61, 0.95, 1.00, 0.78, 0.78, 0.77, 0.52, 0.22], [0.75, 0.93, 0.78, 0.00, 0.00, 0.78, 0.54, 0.19], [0.64, 0.85, 0.78, 0.00, 0.00, 0.78, 0.45, 0.08], [0.41, 0.68, 0.77, 0.78, 0.78, 0.55, 0.25, 0.02], [0.18, 0.40, 0.52, 0.54, 0.45, 0.25, 0.00, 0.00], [0.00, 0.11, 0.22, 0.19, 0.08, 0.02, 0.00, 0.00]], [[0.00, 0.19, 0.39, 0.48, 0.41, 0.26, 0.12, 0.00], [0.19, 0.52, 0.73, 0.78, 0.66, 0.46, 0.26, 0.07], [0.39, 0.73, 0.95, 0.50, 0.50, 0.53, 0.30, 0.14], [0.48, 0.78, 0.50, 0.00, 0.00, 0.50, 0.23, 0.12], [0.41, 0.66, 0.50, 0.00, 0.00, 0.50, 0.11, 0.05], [0.26, 0.46, 0.53, 0.50, 0.50, 0.11, 0.03, 0.01], [0.12, 0.26, 0.30, 0.23, 0.11, 0.03, 0.00, 0.00], [0.00, 0.07, 0.14, 0.12, 0.05, 0.01, 0.00, 0.00]], [[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]], ]).T assert_array_almost_equal(rgb, expect, decimal=2) def test_light_source_hillshading(): """Compare the current hillshading method against one that should be mathematically equivalent. Illuminates a cone from a range of angles.""" def alternative_hillshade(azimuth, elev, z): illum = _sph2cart(*_azimuth2math(azimuth, elev)) illum = np.array(illum) dy, dx = np.gradient(-z) dy = -dy dz = np.ones_like(dy) normals = np.dstack([dx, dy, dz]) dividers = np.zeros_like(z)[..., None] for i, mat in enumerate(normals): for j, vec in enumerate(mat): dividers[i, j, 0] = np.linalg.norm(vec) normals /= dividers # once we drop support for numpy 1.7.x the above can be written as # normals /= np.linalg.norm(normals, axis=2)[..., None] # aviding the double loop. intensity = np.tensordot(normals, illum, axes=(2, 0)) intensity -= intensity.min() intensity /= intensity.ptp() return intensity y, x = np.mgrid[5:0:-1, :5] z = -np.hypot(x - x.mean(), y - y.mean()) for az, elev in itertools.product(range(0, 390, 30), range(0, 105, 15)): ls = mcolors.LightSource(az, elev) h1 = ls.hillshade(z) h2 = alternative_hillshade(az, elev, z) assert_array_almost_equal(h1, h2) def test_light_source_planar_hillshading(): """Ensure that the illumination intensity is correct for planar surfaces.""" def plane(azimuth, elevation, x, y): """Create a plane whose normal vector is at the given azimuth and elevation.""" theta, phi = _azimuth2math(azimuth, elevation) a, b, c = _sph2cart(theta, phi) z = -(a*x + b*y) / c return z def angled_plane(azimuth, elevation, angle, x, y): """Create a plane whose normal vector is at an angle from the given azimuth and elevation.""" elevation = elevation + angle if elevation > 90: azimuth = (azimuth + 180) % 360 elevation = (90 - elevation) % 90 return plane(azimuth, elevation, x, y) y, x = np.mgrid[5:0:-1, :5] for az, elev in itertools.product(range(0, 390, 30), range(0, 105, 15)): ls = mcolors.LightSource(az, elev) # Make a plane at a range of angles to the illumination for angle in range(0, 105, 15): z = angled_plane(az, elev, angle, x, y) h = ls.hillshade(z) assert_array_almost_equal(h, np.cos(np.radians(angle))) def test_color_names(): assert mcolors.to_hex("blue") == "#0000ff" assert mcolors.to_hex("xkcd:blue") == "#0343df" assert mcolors.to_hex("tab:blue") == "#1f77b4" def _sph2cart(theta, phi): x = np.cos(theta) * np.sin(phi) y = np.sin(theta) * np.sin(phi) z = np.cos(phi) return x, y, z def _azimuth2math(azimuth, elevation): """Converts from clockwise-from-north and up-from-horizontal to mathematical conventions.""" theta = np.radians((90 - azimuth) % 360) phi = np.radians(90 - elevation) return theta, phi def test_pandas_iterable(pd): # Using a list or series yields equivalent # color maps, i.e the series isn't seen as # a single color lst = ['red', 'blue', 'green'] s = pd.Series(lst) cm1 = mcolors.ListedColormap(lst, N=5) cm2 = mcolors.ListedColormap(s, N=5) assert_array_equal(cm1.colors, cm2.colors) @pytest.mark.parametrize('name', sorted(cm.cmap_d)) def test_colormap_reversing(name): """Check the generated _lut data of a colormap and corresponding reversed colormap if they are almost the same.""" cmap = plt.get_cmap(name) cmap_r = cmap.reversed() if not cmap_r._isinit: cmap._init() cmap_r._init() assert_array_almost_equal(cmap._lut[:-3], cmap_r._lut[-4::-1]) def test_cn(): matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['blue', 'r']) assert mcolors.to_hex("C0") == '#0000ff' assert mcolors.to_hex("C1") == '#ff0000' matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['xkcd:blue', 'r']) assert mcolors.to_hex("C0") == '#0343df' assert mcolors.to_hex("C1") == '#ff0000' matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['8e4585', 'r']) assert mcolors.to_hex("C0") == '#8e4585' # if '8e4585' gets parsed as a float before it gets detected as a hex # colour it will be interpreted as a very large number. # this mustn't happen. assert mcolors.to_rgb("C0")[0] != np.inf def test_conversions(): # to_rgba_array("none") returns a (0, 4) array. assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4))) # a list of grayscale levels, not a single color. assert_array_equal( mcolors.to_rgba_array([".2", ".5", ".8"]), np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]])) # alpha is properly set. assert mcolors.to_rgba((1, 1, 1), .5) == (1, 1, 1, .5) assert mcolors.to_rgba(".1", .5) == (.1, .1, .1, .5) # builtin round differs between py2 and py3. assert mcolors.to_hex((.7, .7, .7)) == "#b2b2b2" # hex roundtrip. hex_color = "#1234abcd" assert mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True) == \ hex_color def test_grey_gray(): color_mapping = mcolors._colors_full_map for k in color_mapping.keys(): if 'grey' in k: assert color_mapping[k] == color_mapping[k.replace('grey', 'gray')] if 'gray' in k: assert color_mapping[k] == color_mapping[k.replace('gray', 'grey')] def test_tableau_order(): dflt_cycle = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] assert list(mcolors.TABLEAU_COLORS.values()) == dflt_cycle def test_ndarray_subclass_norm(recwarn): # Emulate an ndarray subclass that handles units # which objects when adding or subtracting with other # arrays. See #6622 and #8696 class MyArray(np.ndarray): def __isub__(self, other): raise RuntimeError def __add__(self, other): raise RuntimeError data = np.arange(-10, 10, 1, dtype=float) data.shape = (10, 2) mydata = data.view(MyArray) for norm in [mcolors.Normalize(), mcolors.LogNorm(), mcolors.SymLogNorm(3, vmax=5, linscale=1), mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()), mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()), mcolors.PowerNorm(1)]: assert_array_equal(norm(mydata), norm(data)) fig, ax = plt.subplots() ax.imshow(mydata, norm=norm) fig.canvas.draw() if isinstance(norm, mcolors.PowerNorm): assert len(recwarn) == 1 warn = recwarn.pop(UserWarning) assert ('Power-law scaling on negative values is ill-defined' in str(warn.message)) else: assert len(recwarn) == 0 recwarn.clear() def test_same_color(): assert mcolors.same_color('k', (0, 0, 0)) assert not mcolors.same_color('w', (1, 1, 0))
26,431
35.060027
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_mlab.py
from __future__ import absolute_import, division, print_function import six import tempfile import warnings from numpy.testing import (assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp) import numpy.ma.testutils as matest import numpy as np import datetime as datetime import pytest import matplotlib.mlab as mlab import matplotlib.cbook as cbook from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning try: from mpl_toolkits.natgrid import _natgrid HAS_NATGRID = True except ImportError: HAS_NATGRID = False ''' A lot of mlab.py has been deprecated in Matplotlib 2.2 and is scheduled for removal in the future. The tests that use deprecated methods have a block to catch the deprecation warning, and can be removed with the mlab code is removed. ''' def test_colinear_pca(): with pytest.warns(MatplotlibDeprecationWarning): a = mlab.PCA._get_colinear() pca = mlab.PCA(a) assert_allclose(pca.fracs[2:], 0., atol=1e-8) assert_allclose(pca.Y[:, 2:], 0., atol=1e-8) @pytest.mark.parametrize('input', [ # test odd lengths [1, 2, 3], # test even lengths [1, 2, 3, 4], # derived from email sent by jason-sage to MPL-user on 20090914 [1, 1, 2, 2, 1, 2, 4, 3, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 7, 6, 4, 5, 5], ], ids=[ 'odd length', 'even length', 'custom data', ]) @pytest.mark.parametrize('percentile', [ 0, 50, 75, 100, [0, 75, 100], ]) def test_prctile(input, percentile): with pytest.warns(MatplotlibDeprecationWarning): assert_allclose(mlab.prctile(input, percentile), np.percentile(input, percentile)) @pytest.mark.parametrize('xmin, xmax, N', [ (.01, 1000., 6), (.03, 1313., 7), (.03, 1313., 0), (.03, 1313., 1), ], ids=[ 'tens', 'primes', 'none', 'single', ]) def test_logspace(xmin, xmax, N): with pytest.warns(MatplotlibDeprecationWarning): res = mlab.logspace(xmin, xmax, N) targ = np.logspace(np.log10(xmin), np.log10(xmax), N) assert_allclose(targ, res) assert res.size == N class TestStride(object): def get_base(self, x): y = x while y.base is not None: y = y.base return y def calc_window_target(self, x, NFFT, noverlap=0, axis=0): '''This is an adaptation of the original window extraction algorithm. This is here to test to make sure the new implementation has the same result''' step = NFFT - noverlap ind = np.arange(0, len(x) - NFFT + 1, step) n = len(ind) result = np.zeros((NFFT, n)) # do the ffts of the slices for i in range(n): result[:, i] = x[ind[i]:ind[i]+NFFT] if axis == 1: result = result.T return result @pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D']) def test_stride_windows_invalid_input_shape(self, shape): x = np.arange(np.prod(shape)).reshape(shape) with pytest.raises(ValueError): mlab.stride_windows(x, 5) @pytest.mark.parametrize('n, noverlap', [(0, None), (11, None), (2, 2), (2, 3)], ids=['n less than 1', 'n greater than input', 'noverlap greater than n', 'noverlap equal to n']) def test_stride_windows_invalid_params(self, n, noverlap): x = np.arange(10) with pytest.raises(ValueError): mlab.stride_windows(x, n, noverlap) @pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D']) def test_stride_repeat_invalid_input_shape(self, shape): x = np.arange(np.prod(shape)).reshape(shape) with pytest.raises(ValueError): mlab.stride_repeat(x, 5) @pytest.mark.parametrize('axis', [-1, 2], ids=['axis less than 0', 'axis greater than input shape']) def test_stride_repeat_invalid_axis(self, axis): x = np.array(0) with pytest.raises(ValueError): mlab.stride_repeat(x, 5, axis=axis) def test_stride_repeat_n_lt_1_ValueError(self): x = np.arange(10) with pytest.raises(ValueError): mlab.stride_repeat(x, 0) @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1']) @pytest.mark.parametrize('n', [1, 5], ids=['n1', 'n5']) def test_stride_repeat(self, n, axis): x = np.arange(10) y = mlab.stride_repeat(x, n, axis=axis) expected_shape = [10, 10] expected_shape[axis] = n yr = np.repeat(np.expand_dims(x, axis), n, axis=axis) assert yr.shape == y.shape assert_array_equal(yr, y) assert tuple(expected_shape) == y.shape assert self.get_base(y) is x @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1']) @pytest.mark.parametrize('n, noverlap', [(1, 0), (5, 0), (15, 2), (13, -3)], ids=['n1-noverlap0', 'n5-noverlap0', 'n15-noverlap2', 'n13-noverlapn3']) def test_stride_windows(self, n, noverlap, axis): x = np.arange(100) y = mlab.stride_windows(x, n, noverlap=noverlap, axis=axis) expected_shape = [0, 0] expected_shape[axis] = n expected_shape[1 - axis] = 100 // (n - noverlap) yt = self.calc_window_target(x, n, noverlap=noverlap, axis=axis) assert yt.shape == y.shape assert_array_equal(yt, y) assert tuple(expected_shape) == y.shape assert self.get_base(y) is x @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1']) def test_stride_windows_n32_noverlap0_unflatten(self, axis): n = 32 x = np.arange(n)[np.newaxis] x1 = np.tile(x, (21, 1)) x2 = x1.flatten() y = mlab.stride_windows(x2, n, axis=axis) if axis == 0: x1 = x1.T assert y.shape == x1.shape assert_array_equal(y, x1) def test_stride_ensure_integer_type(self): N = 100 x = np.empty(N + 20, dtype='>f4') x.fill(np.NaN) y = x[10:-10] y.fill(0.3) # previous to #3845 lead to corrupt access y_strided = mlab.stride_windows(y, n=33, noverlap=0.6) assert_array_equal(y_strided, 0.3) # previous to #3845 lead to corrupt access y_strided = mlab.stride_windows(y, n=33.3, noverlap=0) assert_array_equal(y_strided, 0.3) # even previous to #3845 could not find any problematic # configuration however, let's be sure it's not accidentally # introduced y_strided = mlab.stride_repeat(y, n=33.815) assert_array_equal(y_strided, 0.3) @pytest.fixture def tempcsv(): if six.PY2: fd = tempfile.TemporaryFile(suffix='csv', mode="wb+") else: fd = tempfile.TemporaryFile(suffix='csv', mode="w+", newline='') with fd: yield fd def test_recarray_csv_roundtrip(tempcsv): expected = np.recarray((99,), [(str('x'), float), (str('y'), float), (str('t'), float)]) # initialising all values: uninitialised memory sometimes produces # floats that do not round-trip to string and back. expected['x'][:] = np.linspace(-1e9, -1, 99) expected['y'][:] = np.linspace(1, 1e9, 99) expected['t'][:] = np.linspace(0, 0.01, 99) with pytest.warns(MatplotlibDeprecationWarning): mlab.rec2csv(expected, tempcsv) tempcsv.seek(0) actual = mlab.csv2rec(tempcsv) assert_allclose(expected['x'], actual['x']) assert_allclose(expected['y'], actual['y']) assert_allclose(expected['t'], actual['t']) def test_rec2csv_bad_shape_ValueError(tempcsv): bad = np.recarray((99, 4), [(str('x'), float), (str('y'), float)]) # the bad recarray should trigger a ValueError for having ndim > 1. with pytest.warns(MatplotlibDeprecationWarning): with pytest.raises(ValueError): mlab.rec2csv(bad, tempcsv) def test_csv2rec_names_with_comments(tempcsv): tempcsv.write('# comment\n1,2,3\n4,5,6\n') tempcsv.seek(0) with pytest.warns(MatplotlibDeprecationWarning): array = mlab.csv2rec(tempcsv, names='a,b,c') assert len(array) == 2 assert len(array.dtype) == 3 @pytest.mark.parametrize('input, kwargs', [ ('01/11/14\n' '03/05/76 12:00:01 AM\n' '07/09/83 5:17:34 PM\n' '06/20/2054 2:31:45 PM\n' '10/31/00 11:50:23 AM\n', {}), ('11/01/14\n' '05/03/76 12:00:01 AM\n' '09/07/83 5:17:34 PM\n' '20/06/2054 2:31:45 PM\n' '31/10/00 11:50:23 AM\n', {'dayfirst': True}), ('14/01/11\n' '76/03/05 12:00:01 AM\n' '83/07/09 5:17:34 PM\n' '2054/06/20 2:31:45 PM\n' '00/10/31 11:50:23 AM\n', {'yearfirst': True}), ], ids=['usdate', 'dayfirst', 'yearfirst']) def test_csv2rec_dates(tempcsv, input, kwargs): tempcsv.write(input) expected = [datetime.datetime(2014, 1, 11, 0, 0), datetime.datetime(1976, 3, 5, 0, 0, 1), datetime.datetime(1983, 7, 9, 17, 17, 34), datetime.datetime(2054, 6, 20, 14, 31, 45), datetime.datetime(2000, 10, 31, 11, 50, 23)] tempcsv.seek(0) with pytest.warns(MatplotlibDeprecationWarning): array = mlab.csv2rec(tempcsv, names='a', **kwargs) assert_array_equal(array['a'].tolist(), expected) def test_rec2txt_basic(): # str() calls around field names necessary b/c as of numpy 1.11 # dtype doesn't like unicode names (caused by unicode_literals import) a = np.array([(1.0, 2, 'foo', 'bing'), (2.0, 3, 'bar', 'blah')], dtype=np.dtype([(str('x'), np.float32), (str('y'), np.int8), (str('s'), str, 3), (str('s2'), str, 4)])) truth = (' x y s s2\n' ' 1.000 2 foo bing \n' ' 2.000 3 bar blah ').splitlines() with pytest.warns(MatplotlibDeprecationWarning): assert mlab.rec2txt(a).splitlines() == truth class TestWindow(object): def setup(self): np.random.seed(0) n = 1000 self.sig_rand = np.random.standard_normal(n) + 100. self.sig_ones = np.ones(n) def check_window_apply_repeat(self, x, window, NFFT, noverlap): '''This is an adaptation of the original window application algorithm. This is here to test to make sure the new implementation has the same result''' step = NFFT - noverlap ind = np.arange(0, len(x) - NFFT + 1, step) n = len(ind) result = np.zeros((NFFT, n)) if cbook.iterable(window): windowVals = window else: windowVals = window(np.ones((NFFT,), x.dtype)) # do the ffts of the slices for i in range(n): result[:, i] = windowVals * x[ind[i]:ind[i]+NFFT] return result def test_window_none_rand(self): res = mlab.window_none(self.sig_ones) assert_array_equal(res, self.sig_ones) def test_window_none_ones(self): res = mlab.window_none(self.sig_rand) assert_array_equal(res, self.sig_rand) def test_window_hanning_rand(self): targ = np.hanning(len(self.sig_rand)) * self.sig_rand res = mlab.window_hanning(self.sig_rand) assert_allclose(targ, res, atol=1e-06) def test_window_hanning_ones(self): targ = np.hanning(len(self.sig_ones)) res = mlab.window_hanning(self.sig_ones) assert_allclose(targ, res, atol=1e-06) def test_apply_window_1D_axis1_ValueError(self): x = self.sig_rand window = mlab.window_hanning with pytest.raises(ValueError): mlab.apply_window(x, window, axis=1, return_window=False) def test_apply_window_1D_els_wrongsize_ValueError(self): x = self.sig_rand window = mlab.window_hanning(np.ones(x.shape[0]-1)) with pytest.raises(ValueError): mlab.apply_window(x, window) def test_apply_window_0D_ValueError(self): x = np.array(0) window = mlab.window_hanning with pytest.raises(ValueError): mlab.apply_window(x, window, axis=1, return_window=False) def test_apply_window_3D_ValueError(self): x = self.sig_rand[np.newaxis][np.newaxis] window = mlab.window_hanning with pytest.raises(ValueError): mlab.apply_window(x, window, axis=1, return_window=False) def test_apply_window_hanning_1D(self): x = self.sig_rand window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = mlab.apply_window(x, window, return_window=True) yt = window(x) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_1D_axis0(self): x = self.sig_rand window = mlab.window_hanning y = mlab.apply_window(x, window, axis=0, return_window=False) yt = window(x) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els_1D_axis0(self): x = self.sig_rand window = mlab.window_hanning(np.ones(x.shape[0])) window1 = mlab.window_hanning y = mlab.apply_window(x, window, axis=0, return_window=False) yt = window1(x) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning y = mlab.apply_window(x, window, axis=0, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window(x[:, i]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els1_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning(np.ones(x.shape[0])) window1 = mlab.window_hanning y = mlab.apply_window(x, window, axis=0, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window1(x[:, i]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els2_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = mlab.apply_window(x, window, axis=0, return_window=True) yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window1*x[:, i] assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_els3_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = mlab.apply_window(x, window, axis=0, return_window=True) yt = mlab.apply_window(x, window1, axis=0, return_window=False) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_2D_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning y = mlab.apply_window(x, window, axis=1, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window(x[i, :]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D__els1_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning(np.ones(x.shape[1])) window1 = mlab.window_hanning y = mlab.apply_window(x, window, axis=1, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window1(x[i, :]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_els2_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[1])) y, window2 = mlab.apply_window(x, window, axis=1, return_window=True) yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window1 * x[i, :] assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_2D_els3_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[1])) y = mlab.apply_window(x, window, axis=1, return_window=False) yt = mlab.apply_window(x, window1, axis=1, return_window=False) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_stride_windows_hanning_2D_n13_noverlapn3_axis0(self): x = self.sig_rand window = mlab.window_hanning yi = mlab.stride_windows(x, n=13, noverlap=2, axis=0) y = mlab.apply_window(yi, window, axis=0, return_window=False) yt = self.check_window_apply_repeat(x, window, 13, 2) assert yt.shape == y.shape assert x.shape != y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_stack_axis1(self): ydata = np.arange(32) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1 = mlab.apply_window(ydata1, mlab.window_hanning) ycontrol2 = mlab.window_hanning(ydata2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) result = mlab.apply_window(ydata, mlab.window_hanning, axis=1, return_window=False) assert_allclose(ycontrol, result, atol=1e-08) def test_apply_window_hanning_2D_stack_windows_axis1(self): ydata = np.arange(32) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1 = mlab.apply_window(ydata1, mlab.window_hanning) ycontrol2 = mlab.window_hanning(ydata2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) result = mlab.apply_window(ydata, mlab.window_hanning, axis=1, return_window=False) assert_allclose(ycontrol, result, atol=1e-08) def test_apply_window_hanning_2D_stack_windows_axis1_unflatten(self): n = 32 ydata = np.arange(n) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1 = mlab.apply_window(ydata1, mlab.window_hanning) ycontrol2 = mlab.window_hanning(ydata2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) ydata = ydata.flatten() ydata1 = mlab.stride_windows(ydata, 32, noverlap=0, axis=0) result = mlab.apply_window(ydata1, mlab.window_hanning, axis=0, return_window=False) assert_allclose(ycontrol.T, result, atol=1e-08) class TestDetrend(object): def setup(self): np.random.seed(0) n = 1000 x = np.linspace(0., 100, n) self.sig_zeros = np.zeros(n) self.sig_off = self.sig_zeros + 100. self.sig_slope = np.linspace(-10., 90., n) self.sig_slope_mean = x - x.mean() sig_rand = np.random.standard_normal(n) sig_sin = np.sin(x*2*np.pi/(n/100)) sig_rand -= sig_rand.mean() sig_sin -= sig_sin.mean() self.sig_base = sig_rand + sig_sin self.atol = 1e-08 def test_detrend_none_0D_zeros(self): input = 0. targ = input res = mlab.detrend_none(input) assert input == targ def test_detrend_none_0D_zeros_axis1(self): input = 0. targ = input res = mlab.detrend_none(input, axis=1) assert input == targ def test_detrend_str_none_0D_zeros(self): input = 0. targ = input res = mlab.detrend(input, key='none') assert input == targ def test_detrend_detrend_none_0D_zeros(self): input = 0. targ = input res = mlab.detrend(input, key=mlab.detrend_none) assert input == targ def test_detrend_none_0D_off(self): input = 5.5 targ = input res = mlab.detrend_none(input) assert input == targ def test_detrend_none_1D_off(self): input = self.sig_off targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_1D_slope(self): input = self.sig_slope targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_1D_base(self): input = self.sig_base targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_1D_base_slope_off_list(self): input = self.sig_base + self.sig_slope + self.sig_off targ = input.tolist() res = mlab.detrend_none(input.tolist()) assert res == targ def test_detrend_none_2D(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] input = np.vstack(arri) targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_2D_T(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] input = np.vstack(arri) targ = input res = mlab.detrend_none(input.T) assert_array_equal(res.T, targ) def test_detrend_mean_0D_zeros(self): input = 0. targ = 0. res = mlab.detrend_mean(input) assert_almost_equal(res, targ) def test_detrend_str_mean_0D_zeros(self): input = 0. targ = 0. res = mlab.detrend(input, key='mean') assert_almost_equal(res, targ) def test_detrend_detrend_mean_0D_zeros(self): input = 0. targ = 0. res = mlab.detrend(input, key=mlab.detrend_mean) assert_almost_equal(res, targ) def test_detrend_mean_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend_mean(input) assert_almost_equal(res, targ) def test_detrend_str_mean_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend(input, key='mean') assert_almost_equal(res, targ) def test_detrend_detrend_mean_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend(input, key=mlab.detrend_mean) assert_almost_equal(res, targ) def test_detrend_mean_1D_zeros(self): input = self.sig_zeros targ = self.sig_zeros res = mlab.detrend_mean(input) assert_allclose(res, targ, atol=self.atol) def test_detrend_mean_1D_base(self): input = self.sig_base targ = self.sig_base res = mlab.detrend_mean(input) assert_allclose(res, targ, atol=self.atol) def test_detrend_mean_1D_base_off(self): input = self.sig_base + self.sig_off targ = self.sig_base res = mlab.detrend_mean(input) assert_allclose(res, targ, atol=self.atol) def test_detrend_mean_1D_base_slope(self): input = self.sig_base + self.sig_slope targ = self.sig_base + self.sig_slope_mean res = mlab.detrend_mean(input) assert_allclose(res, targ, atol=self.atol) def test_detrend_mean_1D_base_slope_off(self): input = self.sig_base + self.sig_slope + self.sig_off targ = self.sig_base + self.sig_slope_mean res = mlab.detrend_mean(input) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_1D_base_slope_off_axis0(self): input = self.sig_base + self.sig_slope + self.sig_off targ = self.sig_base + self.sig_slope_mean res = mlab.detrend_mean(input, axis=0) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_1D_base_slope_off_list(self): input = self.sig_base + self.sig_slope + self.sig_off targ = self.sig_base + self.sig_slope_mean res = mlab.detrend_mean(input.tolist()) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_1D_base_slope_off_list_axis0(self): input = self.sig_base + self.sig_slope + self.sig_off targ = self.sig_base + self.sig_slope_mean res = mlab.detrend_mean(input.tolist(), axis=0) assert_allclose(res, targ, atol=1e-08) def test_demean_0D_off(self): input = 5.5 targ = 0. res = mlab.demean(input, axis=None) assert_almost_equal(res, targ) def test_demean_1D_base_slope_off(self): input = self.sig_base + self.sig_slope + self.sig_off targ = self.sig_base + self.sig_slope_mean res = mlab.demean(input) assert_allclose(res, targ, atol=1e-08) def test_demean_1D_base_slope_off_axis0(self): input = self.sig_base + self.sig_slope + self.sig_off targ = self.sig_base + self.sig_slope_mean res = mlab.demean(input, axis=0) assert_allclose(res, targ, atol=1e-08) def test_demean_1D_base_slope_off_list(self): input = self.sig_base + self.sig_slope + self.sig_off targ = self.sig_base + self.sig_slope_mean res = mlab.demean(input.tolist()) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_2D_default(self): arri = [self.sig_off, self.sig_base + self.sig_off] arrt = [self.sig_zeros, self.sig_base] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend_mean(input) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_2D_none(self): arri = [self.sig_off, self.sig_base + self.sig_off] arrt = [self.sig_zeros, self.sig_base] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend_mean(input, axis=None) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_2D_none_T(self): arri = [self.sig_off, self.sig_base + self.sig_off] arrt = [self.sig_zeros, self.sig_base] input = np.vstack(arri).T targ = np.vstack(arrt) res = mlab.detrend_mean(input, axis=None) assert_allclose(res.T, targ, atol=1e-08) def test_detrend_mean_2D_axis0(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri).T targ = np.vstack(arrt).T res = mlab.detrend_mean(input, axis=0) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_2D_axis1(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend_mean(input, axis=1) assert_allclose(res, targ, atol=1e-08) def test_detrend_mean_2D_axism1(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend_mean(input, axis=-1) assert_allclose(res, targ, atol=1e-08) def test_detrend_2D_default(self): arri = [self.sig_off, self.sig_base + self.sig_off] arrt = [self.sig_zeros, self.sig_base] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend(input) assert_allclose(res, targ, atol=1e-08) def test_detrend_2D_none(self): arri = [self.sig_off, self.sig_base + self.sig_off] arrt = [self.sig_zeros, self.sig_base] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend(input, axis=None) assert_allclose(res, targ, atol=1e-08) def test_detrend_str_mean_2D_axis0(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri).T targ = np.vstack(arrt).T res = mlab.detrend(input, key='mean', axis=0) assert_allclose(res, targ, atol=1e-08) def test_detrend_str_constant_2D_none_T(self): arri = [self.sig_off, self.sig_base + self.sig_off] arrt = [self.sig_zeros, self.sig_base] input = np.vstack(arri).T targ = np.vstack(arrt) res = mlab.detrend(input, key='constant', axis=None) assert_allclose(res.T, targ, atol=1e-08) def test_detrend_str_default_2D_axis1(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend(input, key='default', axis=1) assert_allclose(res, targ, atol=1e-08) def test_detrend_detrend_mean_2D_axis0(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri).T targ = np.vstack(arrt).T res = mlab.detrend(input, key=mlab.detrend_mean, axis=0) assert_allclose(res, targ, atol=1e-08) def test_demean_2D_default(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri).T targ = np.vstack(arrt).T res = mlab.demean(input) assert_allclose(res, targ, atol=1e-08) def test_demean_2D_none(self): arri = [self.sig_off, self.sig_base + self.sig_off] arrt = [self.sig_zeros, self.sig_base] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.demean(input, axis=None) assert_allclose(res, targ, atol=1e-08) def test_demean_2D_axis0(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri).T targ = np.vstack(arrt).T res = mlab.demean(input, axis=0) assert_allclose(res, targ, atol=1e-08) def test_demean_2D_axis1(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.demean(input, axis=1) assert_allclose(res, targ, atol=1e-08) def test_demean_2D_axism1(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] arrt = [self.sig_base, self.sig_base, self.sig_base + self.sig_slope_mean, self.sig_base + self.sig_slope_mean] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.demean(input, axis=-1) assert_allclose(res, targ, atol=1e-08) def test_detrend_bad_key_str_ValueError(self): input = self.sig_slope[np.newaxis] with pytest.raises(ValueError): mlab.detrend(input, key='spam') def test_detrend_bad_key_var_ValueError(self): input = self.sig_slope[np.newaxis] with pytest.raises(ValueError): mlab.detrend(input, key=5) def test_detrend_mean_0D_d0_ValueError(self): input = 5.5 with pytest.raises(ValueError): mlab.detrend_mean(input, axis=0) def test_detrend_0D_d0_ValueError(self): input = 5.5 with pytest.raises(ValueError): mlab.detrend(input, axis=0) def test_detrend_mean_1D_d1_ValueError(self): input = self.sig_slope with pytest.raises(ValueError): mlab.detrend_mean(input, axis=1) def test_detrend_1D_d1_ValueError(self): input = self.sig_slope with pytest.raises(ValueError): mlab.detrend(input, axis=1) def test_demean_1D_d1_ValueError(self): input = self.sig_slope with pytest.raises(ValueError): mlab.demean(input, axis=1) def test_detrend_mean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] with pytest.raises(ValueError): mlab.detrend_mean(input, axis=2) def test_detrend_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] with pytest.raises(ValueError): mlab.detrend(input, axis=2) def test_demean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] with pytest.raises(ValueError): mlab.demean(input, axis=2) def test_detrend_linear_0D_zeros(self): input = 0. targ = 0. res = mlab.detrend_linear(input) assert_almost_equal(res, targ) def test_detrend_linear_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend_linear(input) assert_almost_equal(res, targ) def test_detrend_str_linear_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend(input, key='linear') assert_almost_equal(res, targ) def test_detrend_detrend_linear_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend(input, key=mlab.detrend_linear) assert_almost_equal(res, targ) def test_detrend_linear_1d_off(self): input = self.sig_off targ = self.sig_zeros res = mlab.detrend_linear(input) assert_allclose(res, targ, atol=self.atol) def test_detrend_linear_1d_slope(self): input = self.sig_slope targ = self.sig_zeros res = mlab.detrend_linear(input) assert_allclose(res, targ, atol=self.atol) def test_detrend_linear_1d_slope_off(self): input = self.sig_slope + self.sig_off targ = self.sig_zeros res = mlab.detrend_linear(input) assert_allclose(res, targ, atol=self.atol) def test_detrend_str_linear_1d_slope_off(self): input = self.sig_slope + self.sig_off targ = self.sig_zeros res = mlab.detrend(input, key='linear') assert_allclose(res, targ, atol=self.atol) def test_detrend_detrend_linear_1d_slope_off(self): input = self.sig_slope + self.sig_off targ = self.sig_zeros res = mlab.detrend(input, key=mlab.detrend_linear) assert_allclose(res, targ, atol=self.atol) def test_detrend_linear_1d_slope_off_list(self): input = self.sig_slope + self.sig_off targ = self.sig_zeros res = mlab.detrend_linear(input.tolist()) assert_allclose(res, targ, atol=self.atol) def test_detrend_linear_2D_ValueError(self): input = self.sig_slope[np.newaxis] with pytest.raises(ValueError): mlab.detrend_linear(input) def test_detrend_str_linear_2d_slope_off_axis0(self): arri = [self.sig_off, self.sig_slope, self.sig_slope + self.sig_off] arrt = [self.sig_zeros, self.sig_zeros, self.sig_zeros] input = np.vstack(arri).T targ = np.vstack(arrt).T res = mlab.detrend(input, key='linear', axis=0) assert_allclose(res, targ, atol=self.atol) def test_detrend_detrend_linear_1d_slope_off_axis1(self): arri = [self.sig_off, self.sig_slope, self.sig_slope + self.sig_off] arrt = [self.sig_zeros, self.sig_zeros, self.sig_zeros] input = np.vstack(arri).T targ = np.vstack(arrt).T res = mlab.detrend(input, key=mlab.detrend_linear, axis=0) assert_allclose(res, targ, atol=self.atol) def test_detrend_str_linear_2d_slope_off_axis0(self): arri = [self.sig_off, self.sig_slope, self.sig_slope + self.sig_off] arrt = [self.sig_zeros, self.sig_zeros, self.sig_zeros] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend(input, key='linear', axis=1) assert_allclose(res, targ, atol=self.atol) def test_detrend_detrend_linear_1d_slope_off_axis1(self): arri = [self.sig_off, self.sig_slope, self.sig_slope + self.sig_off] arrt = [self.sig_zeros, self.sig_zeros, self.sig_zeros] input = np.vstack(arri) targ = np.vstack(arrt) res = mlab.detrend(input, key=mlab.detrend_linear, axis=1) assert_allclose(res, targ, atol=self.atol) @pytest.mark.parametrize('iscomplex', [False, True], ids=['real', 'complex'], scope='class') @pytest.mark.parametrize('sides', ['onesided', 'twosided', 'default'], scope='class') @pytest.mark.parametrize( 'fstims,len_x,NFFT_density,nover_density,pad_to_density,pad_to_spectrum', [ ([], None, -1, -1, -1, -1), ([4], None, -1, -1, -1, -1), ([4, 5, 10], None, -1, -1, -1, -1), ([], None, None, -1, -1, None), ([], None, -1, -1, None, None), ([], None, None, -1, None, None), ([], 1024, 512, -1, -1, 128), ([], 256, -1, -1, 33, 257), ([], 255, 33, -1, -1, None), ([], 256, 128, -1, 256, 256), ([], None, -1, 32, -1, -1), ], ids=[ 'nosig', 'Fs4', 'FsAll', 'nosig_noNFFT', 'nosig_nopad_to', 'nosig_noNFFT_no_pad_to', 'nosig_trim', 'nosig_odd', 'nosig_oddlen', 'nosig_stretch', 'nosig_overlap', ], scope='class') class TestSpectral(object): @pytest.fixture(scope='class', autouse=True) def stim(self, request, fstims, iscomplex, sides, len_x, NFFT_density, nover_density, pad_to_density, pad_to_spectrum): Fs = 100. x = np.arange(0, 10, 1 / Fs) if len_x is not None: x = x[:len_x] # get the stimulus frequencies, defaulting to None fstims = [Fs / fstim for fstim in fstims] # get the constants, default to calculated values if NFFT_density is None: NFFT_density_real = 256 elif NFFT_density < 0: NFFT_density_real = NFFT_density = 100 else: NFFT_density_real = NFFT_density if nover_density is None: nover_density_real = 0 elif nover_density < 0: nover_density_real = nover_density = NFFT_density_real // 2 else: nover_density_real = nover_density if pad_to_density is None: pad_to_density_real = NFFT_density_real elif pad_to_density < 0: pad_to_density = int(2**np.ceil(np.log2(NFFT_density_real))) pad_to_density_real = pad_to_density else: pad_to_density_real = pad_to_density if pad_to_spectrum is None: pad_to_spectrum_real = len(x) elif pad_to_spectrum < 0: pad_to_spectrum_real = pad_to_spectrum = len(x) else: pad_to_spectrum_real = pad_to_spectrum if pad_to_spectrum is None: NFFT_spectrum_real = NFFT_spectrum = pad_to_spectrum_real else: NFFT_spectrum_real = NFFT_spectrum = len(x) nover_spectrum_real = nover_spectrum = 0 NFFT_specgram = NFFT_density nover_specgram = nover_density pad_to_specgram = pad_to_density NFFT_specgram_real = NFFT_density_real nover_specgram_real = nover_density_real if sides == 'onesided' or (sides == 'default' and not iscomplex): # frequencies for specgram, psd, and csd # need to handle even and odd differently if pad_to_density_real % 2: freqs_density = np.linspace(0, Fs / 2, num=pad_to_density_real, endpoint=False)[::2] else: freqs_density = np.linspace(0, Fs / 2, num=pad_to_density_real // 2 + 1) # frequencies for complex, magnitude, angle, and phase spectrums # need to handle even and odd differently if pad_to_spectrum_real % 2: freqs_spectrum = np.linspace(0, Fs / 2, num=pad_to_spectrum_real, endpoint=False)[::2] else: freqs_spectrum = np.linspace(0, Fs / 2, num=pad_to_spectrum_real // 2 + 1) else: # frequencies for specgram, psd, and csd # need to handle even and odd differentl if pad_to_density_real % 2: freqs_density = np.linspace(-Fs / 2, Fs / 2, num=2 * pad_to_density_real, endpoint=False)[1::2] else: freqs_density = np.linspace(-Fs / 2, Fs / 2, num=pad_to_density_real, endpoint=False) # frequencies for complex, magnitude, angle, and phase spectrums # need to handle even and odd differently if pad_to_spectrum_real % 2: freqs_spectrum = np.linspace(-Fs / 2, Fs / 2, num=2 * pad_to_spectrum_real, endpoint=False)[1::2] else: freqs_spectrum = np.linspace(-Fs / 2, Fs / 2, num=pad_to_spectrum_real, endpoint=False) freqs_specgram = freqs_density # time points for specgram t_start = NFFT_specgram_real // 2 t_stop = len(x) - NFFT_specgram_real // 2 + 1 t_step = NFFT_specgram_real - nover_specgram_real t_specgram = x[t_start:t_stop:t_step] if NFFT_specgram_real % 2: t_specgram += 1 / Fs / 2 if len(t_specgram) == 0: t_specgram = np.array([NFFT_specgram_real / (2 * Fs)]) t_spectrum = np.array([NFFT_spectrum_real / (2 * Fs)]) t_density = t_specgram y = np.zeros_like(x) for i, fstim in enumerate(fstims): y += np.sin(fstim * x * np.pi * 2) * 10**i if iscomplex: y = y.astype('complex') # Interestingly, the instance on which this fixture is called is not # the same as the one on which a test is run. So we need to modify the # class itself when using a class-scoped fixture. cls = request.cls cls.Fs = Fs cls.sides = sides cls.fstims = fstims cls.NFFT_density = NFFT_density cls.nover_density = nover_density cls.pad_to_density = pad_to_density cls.NFFT_spectrum = NFFT_spectrum cls.nover_spectrum = nover_spectrum cls.pad_to_spectrum = pad_to_spectrum cls.NFFT_specgram = NFFT_specgram cls.nover_specgram = nover_specgram cls.pad_to_specgram = pad_to_specgram cls.t_specgram = t_specgram cls.t_density = t_density cls.t_spectrum = t_spectrum cls.y = y cls.freqs_density = freqs_density cls.freqs_spectrum = freqs_spectrum cls.freqs_specgram = freqs_specgram cls.NFFT_density_real = NFFT_density_real def check_freqs(self, vals, targfreqs, resfreqs, fstims): assert resfreqs.argmin() == 0 assert resfreqs.argmax() == len(resfreqs)-1 assert_allclose(resfreqs, targfreqs, atol=1e-06) for fstim in fstims: i = np.abs(resfreqs - fstim).argmin() assert vals[i] > vals[i+2] assert vals[i] > vals[i-2] def check_maxfreq(self, spec, fsp, fstims): # skip the test if there are no frequencies if len(fstims) == 0: return # if twosided, do the test for each side if fsp.min() < 0: fspa = np.abs(fsp) zeroind = fspa.argmin() self.check_maxfreq(spec[:zeroind], fspa[:zeroind], fstims) self.check_maxfreq(spec[zeroind:], fspa[zeroind:], fstims) return fstimst = fstims[:] spect = spec.copy() # go through each peak and make sure it is correctly the maximum peak while fstimst: maxind = spect.argmax() maxfreq = fsp[maxind] assert_almost_equal(maxfreq, fstimst[-1]) del fstimst[-1] spect[maxind-5:maxind+5] = 0 def test_spectral_helper_raises_complex_same_data(self): # test that mode 'complex' cannot be used if x is not y with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, y=self.y+1, mode='complex') def test_spectral_helper_raises_magnitude_same_data(self): # test that mode 'magnitude' cannot be used if x is not y with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, y=self.y+1, mode='magnitude') def test_spectral_helper_raises_angle_same_data(self): # test that mode 'angle' cannot be used if x is not y with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, y=self.y+1, mode='angle') def test_spectral_helper_raises_phase_same_data(self): # test that mode 'phase' cannot be used if x is not y with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, y=self.y+1, mode='phase') def test_spectral_helper_raises_unknown_mode(self): # test that unknown value for mode cannot be used with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, mode='spam') def test_spectral_helper_raises_unknown_sides(self): # test that unknown value for sides cannot be used with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, y=self.y, sides='eggs') def test_spectral_helper_raises_noverlap_gt_NFFT(self): # test that noverlap cannot be larger than NFFT with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, y=self.y, NFFT=10, noverlap=20) def test_spectral_helper_raises_noverlap_eq_NFFT(self): # test that noverlap cannot be equal to NFFT with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, NFFT=10, noverlap=10) def test_spectral_helper_raises_winlen_ne_NFFT(self): # test that the window length cannot be different from NFFT with pytest.raises(ValueError): mlab._spectral_helper(x=self.y, y=self.y, NFFT=10, window=np.ones(9)) def test_single_spectrum_helper_raises_mode_default(self): # test that mode 'default' cannot be used with _single_spectrum_helper with pytest.raises(ValueError): mlab._single_spectrum_helper(x=self.y, mode='default') def test_single_spectrum_helper_raises_mode_psd(self): # test that mode 'psd' cannot be used with _single_spectrum_helper with pytest.raises(ValueError): mlab._single_spectrum_helper(x=self.y, mode='psd') def test_spectral_helper_psd(self): freqs = self.freqs_density spec, fsp, t = mlab._spectral_helper(x=self.y, y=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides, mode='psd') assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_density, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] def test_spectral_helper_magnitude_specgram(self): freqs = self.freqs_specgram spec, fsp, t = mlab._spectral_helper(x=self.y, y=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='magnitude') assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] def test_spectral_helper_magnitude_magnitude_spectrum(self): freqs = self.freqs_spectrum spec, fsp, t = mlab._spectral_helper(x=self.y, y=self.y, NFFT=self.NFFT_spectrum, Fs=self.Fs, noverlap=self.nover_spectrum, pad_to=self.pad_to_spectrum, sides=self.sides, mode='magnitude') assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_spectrum, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == 1 def test_csd(self): freqs = self.freqs_density spec, fsp = mlab.csd(x=self.y, y=self.y+1, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides) assert_allclose(fsp, freqs, atol=1e-06) assert spec.shape == freqs.shape def test_csd_padding(self): """Test zero padding of csd(). """ if self.NFFT_density is None: # for derived classes return sargs = dict(x=self.y, y=self.y+1, Fs=self.Fs, window=mlab.window_none, sides=self.sides) spec0, _ = mlab.csd(NFFT=self.NFFT_density, **sargs) spec1, _ = mlab.csd(NFFT=self.NFFT_density*2, **sargs) assert_almost_equal(np.sum(np.conjugate(spec0)*spec0).real, np.sum(np.conjugate(spec1/2)*spec1/2).real) def test_psd(self): freqs = self.freqs_density spec, fsp = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides) assert spec.shape == freqs.shape self.check_freqs(spec, freqs, fsp, self.fstims) def test_psd_detrend_mean_func_offset(self): if self.NFFT_density is None: return freqs = self.freqs_density ydata = np.zeros(self.NFFT_density) ydata1 = ydata+5 ydata2 = ydata+3.3 ydata = np.vstack([ydata1, ydata2]) ydata = np.tile(ydata, (20, 1)) ydatab = ydata.T.flatten() ydata = ydata.flatten() ycontrol = np.zeros_like(ydata) spec_g, fsp_g = mlab.psd(x=ydata, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend=mlab.detrend_mean) spec_b, fsp_b = mlab.psd(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend=mlab.detrend_mean) spec_c, fsp_c = mlab.psd(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides) assert_array_equal(fsp_g, fsp_c) assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal with pytest.raises(AssertionError): assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_detrend_mean_str_offset(self): if self.NFFT_density is None: return freqs = self.freqs_density ydata = np.zeros(self.NFFT_density) ydata1 = ydata+5 ydata2 = ydata+3.3 ydata = np.vstack([ydata1, ydata2]) ydata = np.tile(ydata, (20, 1)) ydatab = ydata.T.flatten() ydata = ydata.flatten() ycontrol = np.zeros_like(ydata) spec_g, fsp_g = mlab.psd(x=ydata, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend='mean') spec_b, fsp_b = mlab.psd(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend='mean') spec_c, fsp_c = mlab.psd(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides) assert_array_equal(fsp_g, fsp_c) assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal with pytest.raises(AssertionError): assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_detrend_linear_func_trend(self): if self.NFFT_density is None: return freqs = self.freqs_density ydata = np.arange(self.NFFT_density) ydata1 = ydata+5 ydata2 = ydata+3.3 ydata = np.vstack([ydata1, ydata2]) ydata = np.tile(ydata, (20, 1)) ydatab = ydata.T.flatten() ydata = ydata.flatten() ycontrol = np.zeros_like(ydata) spec_g, fsp_g = mlab.psd(x=ydata, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend=mlab.detrend_linear) spec_b, fsp_b = mlab.psd(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend=mlab.detrend_linear) spec_c, fsp_c = mlab.psd(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides) assert_array_equal(fsp_g, fsp_c) assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal with pytest.raises(AssertionError): assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_detrend_linear_str_trend(self): if self.NFFT_density is None: return freqs = self.freqs_density ydata = np.arange(self.NFFT_density) ydata1 = ydata+5 ydata2 = ydata+3.3 ydata = np.vstack([ydata1, ydata2]) ydata = np.tile(ydata, (20, 1)) ydatab = ydata.T.flatten() ydata = ydata.flatten() ycontrol = np.zeros_like(ydata) spec_g, fsp_g = mlab.psd(x=ydata, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend='linear') spec_b, fsp_b = mlab.psd(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend='linear') spec_c, fsp_c = mlab.psd(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides) assert_array_equal(fsp_g, fsp_c) assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal with pytest.raises(AssertionError): assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_window_hanning(self): if self.NFFT_density is None: return freqs = self.freqs_density ydata = np.arange(self.NFFT_density) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1, windowVals = mlab.apply_window(ydata1, mlab.window_hanning, return_window=True) ycontrol2 = mlab.window_hanning(ydata2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) ydatab = ydata.T.flatten() ydataf = ydata.flatten() ycontrol = ycontrol.flatten() spec_g, fsp_g = mlab.psd(x=ydataf, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, window=mlab.window_hanning) spec_b, fsp_b = mlab.psd(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, window=mlab.window_hanning) spec_c, fsp_c = mlab.psd(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, window=mlab.window_none) spec_c *= len(ycontrol1)/(np.abs(windowVals)**2).sum() assert_array_equal(fsp_g, fsp_c) assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal with pytest.raises(AssertionError): assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_window_hanning_detrend_linear(self): if self.NFFT_density is None: return freqs = self.freqs_density ydata = np.arange(self.NFFT_density) ycontrol = np.zeros(self.NFFT_density) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1 = ycontrol ycontrol2 = ycontrol ycontrol1, windowVals = mlab.apply_window(ycontrol1, mlab.window_hanning, return_window=True) ycontrol2 = mlab.window_hanning(ycontrol2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) ydatab = ydata.T.flatten() ydataf = ydata.flatten() ycontrol = ycontrol.flatten() spec_g, fsp_g = mlab.psd(x=ydataf, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend=mlab.detrend_linear, window=mlab.window_hanning) spec_b, fsp_b = mlab.psd(x=ydatab, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, detrend=mlab.detrend_linear, window=mlab.window_hanning) spec_c, fsp_c = mlab.psd(x=ycontrol, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=0, sides=self.sides, window=mlab.window_none) spec_c *= len(ycontrol1)/(np.abs(windowVals)**2).sum() assert_array_equal(fsp_g, fsp_c) assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal with pytest.raises(AssertionError): assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_windowarray(self): freqs = self.freqs_density spec, fsp = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides, window=np.ones(self.NFFT_density_real)) assert_allclose(fsp, freqs, atol=1e-06) assert spec.shape == freqs.shape def test_psd_windowarray_scale_by_freq(self): freqs = self.freqs_density win = mlab.window_hanning(np.ones(self.NFFT_density_real)) spec, fsp = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides, window=mlab.window_hanning) spec_s, fsp_s = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides, window=mlab.window_hanning, scale_by_freq=True) spec_n, fsp_n = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides, window=mlab.window_hanning, scale_by_freq=False) assert_array_equal(fsp, fsp_s) assert_array_equal(fsp, fsp_n) assert_array_equal(spec, spec_s) assert_allclose(spec_s*(win**2).sum(), spec_n/self.Fs*win.sum()**2, atol=1e-08) def test_complex_spectrum(self): freqs = self.freqs_spectrum spec, fsp = mlab.complex_spectrum(x=self.y, Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum) assert_allclose(fsp, freqs, atol=1e-06) assert spec.shape == freqs.shape def test_magnitude_spectrum(self): freqs = self.freqs_spectrum spec, fsp = mlab.magnitude_spectrum(x=self.y, Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum) assert spec.shape == freqs.shape self.check_maxfreq(spec, fsp, self.fstims) self.check_freqs(spec, freqs, fsp, self.fstims) def test_angle_spectrum(self): freqs = self.freqs_spectrum spec, fsp = mlab.angle_spectrum(x=self.y, Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum) assert_allclose(fsp, freqs, atol=1e-06) assert spec.shape == freqs.shape def test_phase_spectrum(self): freqs = self.freqs_spectrum spec, fsp = mlab.phase_spectrum(x=self.y, Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum) assert_allclose(fsp, freqs, atol=1e-06) assert spec.shape == freqs.shape def test_specgram_auto(self): freqs = self.freqs_specgram spec, fsp, t = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides) specm = np.mean(spec, axis=1) assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same if np.abs(spec.max()) != 0: assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0, atol=1e-02) self.check_freqs(specm, freqs, fsp, self.fstims) def test_specgram_default(self): freqs = self.freqs_specgram spec, fsp, t = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='default') specm = np.mean(spec, axis=1) assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same if np.abs(spec.max()) != 0: assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0, atol=1e-02) self.check_freqs(specm, freqs, fsp, self.fstims) def test_specgram_psd(self): freqs = self.freqs_specgram spec, fsp, t = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='psd') specm = np.mean(spec, axis=1) assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same if np.abs(spec.max()) != 0: assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0, atol=1e-02) self.check_freqs(specm, freqs, fsp, self.fstims) def test_specgram_complex(self): freqs = self.freqs_specgram spec, fsp, t = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='complex') specm = np.mean(np.abs(spec), axis=1) assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] self.check_freqs(specm, freqs, fsp, self.fstims) def test_specgram_magnitude(self): freqs = self.freqs_specgram spec, fsp, t = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='magnitude') specm = np.mean(spec, axis=1) assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same if np.abs(spec.max()) != 0: assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0, atol=1e-02) self.check_freqs(specm, freqs, fsp, self.fstims) def test_specgram_angle(self): freqs = self.freqs_specgram spec, fsp, t = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='angle') specm = np.mean(spec, axis=1) assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] def test_specgram_phase(self): freqs = self.freqs_specgram spec, fsp, t = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='phase') specm = np.mean(spec, axis=1) assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) assert spec.shape[0] == freqs.shape[0] assert spec.shape[1] == self.t_specgram.shape[0] def test_specgram_warn_only1seg(self): """Warning should be raised if len(x) <= NFFT. """ with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", category=UserWarning) mlab.specgram(x=self.y, NFFT=len(self.y), Fs=self.Fs) assert len(w) == 1 assert issubclass(w[0].category, UserWarning) assert str(w[0].message).startswith("Only one segment is calculated") def test_psd_csd_equal(self): freqs = self.freqs_density Pxx, freqsxx = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides) Pxy, freqsxy = mlab.csd(x=self.y, y=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides) assert_array_almost_equal_nulp(Pxx, Pxy) assert_array_equal(freqsxx, freqsxy) def test_specgram_auto_default_equal(self): '''test that mlab.specgram without mode and with mode 'default' and 'psd' are all the same''' freqs = self.freqs_specgram speca, freqspeca, ta = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides) specb, freqspecb, tb = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='default') assert_array_equal(speca, specb) assert_array_equal(freqspeca, freqspecb) assert_array_equal(ta, tb) def test_specgram_auto_psd_equal(self): '''test that mlab.specgram without mode and with mode 'default' and 'psd' are all the same''' freqs = self.freqs_specgram speca, freqspeca, ta = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides) specc, freqspecc, tc = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='psd') assert_array_equal(speca, specc) assert_array_equal(freqspeca, freqspecc) assert_array_equal(ta, tc) def test_specgram_complex_mag_equivalent(self): freqs = self.freqs_specgram specc, freqspecc, tc = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='complex') specm, freqspecm, tm = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='magnitude') assert_array_equal(freqspecc, freqspecm) assert_array_equal(tc, tm) assert_allclose(np.abs(specc), specm, atol=1e-06) def test_specgram_complex_angle_equivalent(self): freqs = self.freqs_specgram specc, freqspecc, tc = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='complex') speca, freqspeca, ta = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='angle') assert_array_equal(freqspecc, freqspeca) assert_array_equal(tc, ta) assert_allclose(np.angle(specc), speca, atol=1e-06) def test_specgram_complex_phase_equivalent(self): freqs = self.freqs_specgram specc, freqspecc, tc = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='complex') specp, freqspecp, tp = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='phase') assert_array_equal(freqspecc, freqspecp) assert_array_equal(tc, tp) assert_allclose(np.unwrap(np.angle(specc), axis=0), specp, atol=1e-06) def test_specgram_angle_phase_equivalent(self): freqs = self.freqs_specgram speca, freqspeca, ta = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='angle') specp, freqspecp, tp = mlab.specgram(x=self.y, NFFT=self.NFFT_specgram, Fs=self.Fs, noverlap=self.nover_specgram, pad_to=self.pad_to_specgram, sides=self.sides, mode='phase') assert_array_equal(freqspeca, freqspecp) assert_array_equal(ta, tp) assert_allclose(np.unwrap(speca, axis=0), specp, atol=1e-06) def test_psd_windowarray_equal(self): freqs = self.freqs_density win = mlab.window_hanning(np.ones(self.NFFT_density_real)) speca, fspa = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides, window=win) specb, fspb = mlab.psd(x=self.y, NFFT=self.NFFT_density, Fs=self.Fs, noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides) assert_array_equal(fspa, fspb) assert_allclose(speca, specb, atol=1e-08) # extra test for cohere... def test_cohere(): N = 1024 np.random.seed(19680801) x = np.random.randn(N) # phase offset y = np.roll(x, 20) # high-freq roll-off y = np.convolve(y, np.ones(20) / 20., mode='same') cohsq, f = mlab.cohere(x, y, NFFT=256, Fs=2, noverlap=128) assert_allclose(np.mean(cohsq), 0.837, atol=1.e-3) assert np.isreal(np.mean(cohsq)) def test_griddata_linear(): # z is a linear function of x and y. def get_z(x, y): return 3.0*x - y # Passing 1D xi and yi arrays to griddata. x = np.asarray([0.0, 1.0, 0.0, 1.0, 0.5]) y = np.asarray([0.0, 0.0, 1.0, 1.0, 0.5]) z = get_z(x, y) xi = [0.2, 0.4, 0.6, 0.8] yi = [0.1, 0.3, 0.7, 0.9] with pytest.warns(MatplotlibDeprecationWarning): zi = mlab.griddata(x, y, z, xi, yi, interp='linear') xi, yi = np.meshgrid(xi, yi) np.testing.assert_array_almost_equal(zi, get_z(xi, yi)) # Passing 2D xi and yi arrays to griddata. with pytest.warns(MatplotlibDeprecationWarning): zi = mlab.griddata(x, y, z, xi, yi, interp='linear') np.testing.assert_array_almost_equal(zi, get_z(xi, yi)) # Masking z array. z_masked = np.ma.array(z, mask=[False, False, False, True, False]) correct_zi_masked = np.ma.masked_where(xi + yi > 1.0, get_z(xi, yi)) with pytest.warns(MatplotlibDeprecationWarning): zi = mlab.griddata(x, y, z_masked, xi, yi, interp='linear') matest.assert_array_almost_equal(zi, correct_zi_masked) np.testing.assert_array_equal(np.ma.getmask(zi), np.ma.getmask(correct_zi_masked)) @pytest.mark.xfail(not HAS_NATGRID, reason='natgrid not installed') def test_griddata_nn(): # z is a linear function of x and y. def get_z(x, y): return 3.0*x - y # Passing 1D xi and yi arrays to griddata. x = np.asarray([0.0, 1.0, 0.0, 1.0, 0.5]) y = np.asarray([0.0, 0.0, 1.0, 1.0, 0.5]) z = get_z(x, y) xi = [0.2, 0.4, 0.6, 0.8] yi = [0.1, 0.3, 0.7, 0.9] correct_zi = [[0.49999252, 1.0999978, 1.7000030, 2.3000080], [0.29999208, 0.8999978, 1.5000029, 2.1000059], [-0.1000099, 0.4999943, 1.0999964, 1.6999979], [-0.3000128, 0.2999894, 0.8999913, 1.4999933]] with pytest.warns(MatplotlibDeprecationWarning): zi = mlab.griddata(x, y, z, xi, yi, interp='nn') np.testing.assert_array_almost_equal(zi, correct_zi, 5) with pytest.warns(MatplotlibDeprecationWarning): # Decreasing xi or yi should raise ValueError. with pytest.raises(ValueError): mlab.griddata(x, y, z, xi[::-1], yi, interp='nn') with pytest.raises(ValueError): mlab.griddata(x, y, z, xi, yi[::-1], interp='nn') # Passing 2D xi and yi arrays to griddata. xi, yi = np.meshgrid(xi, yi) with pytest.warns(MatplotlibDeprecationWarning): zi = mlab.griddata(x, y, z, xi, yi, interp='nn') np.testing.assert_array_almost_equal(zi, correct_zi, 5) # Masking z array. z_masked = np.ma.array(z, mask=[False, False, False, True, False]) correct_zi_masked = np.ma.masked_where(xi + yi > 1.0, correct_zi) with pytest.warns(MatplotlibDeprecationWarning): zi = mlab.griddata(x, y, z_masked, xi, yi, interp='nn') np.testing.assert_array_almost_equal(zi, correct_zi_masked, 5) np.testing.assert_array_equal(np.ma.getmask(zi), np.ma.getmask(correct_zi_masked)) #***************************************************************** # These Tests where taken from SCIPY with some minor modifications # this can be retrieved from: # https://github.com/scipy/scipy/blob/master/scipy/stats/tests/test_kdeoth.py #***************************************************************** class TestGaussianKDE(object): def test_kde_integer_input(self): """Regression test for #1181.""" x1 = np.arange(5) kde = mlab.GaussianKDE(x1) y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869, 0.13480721] np.testing.assert_array_almost_equal(kde(x1), y_expected, decimal=6) def test_gaussian_kde_covariance_caching(self): x1 = np.array([-7, -5, 1, 4, 5], dtype=float) xs = np.linspace(-10, 10, num=5) # These expected values are from scipy 0.10, before some changes to # gaussian_kde. They were not compared with any external reference. y_expected = [0.02463386, 0.04689208, 0.05395444, 0.05337754, 0.01664475] # set it to the default bandwidth. kde2 = mlab.GaussianKDE(x1, 'scott') y2 = kde2(xs) np.testing.assert_array_almost_equal(y_expected, y2, decimal=7) def test_kde_bandwidth_method(self): np.random.seed(8765678) n_basesample = 50 xn = np.random.randn(n_basesample) # Default gkde = mlab.GaussianKDE(xn) # Supply a callable gkde2 = mlab.GaussianKDE(xn, 'scott') # Supply a scalar gkde3 = mlab.GaussianKDE(xn, bw_method=gkde.factor) xs = np.linspace(-7, 7, 51) kdepdf = gkde.evaluate(xs) kdepdf2 = gkde2.evaluate(xs) assert kdepdf.all() == kdepdf2.all() kdepdf3 = gkde3.evaluate(xs) assert kdepdf.all() == kdepdf3.all() class TestGaussianKDECustom(object): def test_no_data(self): """Pass no data into the GaussianKDE class.""" with pytest.raises(ValueError): mlab.GaussianKDE([]) def test_single_dataset_element(self): """Pass a single dataset element into the GaussianKDE class.""" with pytest.raises(ValueError): mlab.GaussianKDE([42]) def test_silverman_multidim_dataset(self): """Use a multi-dimensional array as the dataset and test silverman's output""" x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) with pytest.raises(np.linalg.LinAlgError): mlab.GaussianKDE(x1, "silverman") def test_silverman_singledim_dataset(self): """Use a single dimension list as the dataset and test silverman's output.""" x1 = np.array([-7, -5, 1, 4, 5]) mygauss = mlab.GaussianKDE(x1, "silverman") y_expected = 0.76770389927475502 assert_almost_equal(mygauss.covariance_factor(), y_expected, 7) def test_scott_multidim_dataset(self): """Use a multi-dimensional array as the dataset and test scott's output """ x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) with pytest.raises(np.linalg.LinAlgError): mlab.GaussianKDE(x1, "scott") def test_scott_singledim_dataset(self): """Use a single-dimensional array as the dataset and test scott's output""" x1 = np.array([-7, -5, 1, 4, 5]) mygauss = mlab.GaussianKDE(x1, "scott") y_expected = 0.72477966367769553 assert_almost_equal(mygauss.covariance_factor(), y_expected, 7) def test_scalar_empty_dataset(self): """Use an empty array as the dataset and test the scalar's cov factor """ with pytest.raises(ValueError): mlab.GaussianKDE([], bw_method=5) def test_scalar_covariance_dataset(self): """Use a dataset and test a scalar's cov factor """ np.random.seed(8765678) n_basesample = 50 multidim_data = [np.random.randn(n_basesample) for i in range(5)] kde = mlab.GaussianKDE(multidim_data, bw_method=0.5) assert kde.covariance_factor() == 0.5 def test_callable_covariance_dataset(self): """Use a multi-dimensional array as the dataset and test the callable's cov factor""" np.random.seed(8765678) n_basesample = 50 multidim_data = [np.random.randn(n_basesample) for i in range(5)] def callable_fun(x): return 0.55 kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun) assert kde.covariance_factor() == 0.55 def test_callable_singledim_dataset(self): """Use a single-dimensional array as the dataset and test the callable's cov factor""" np.random.seed(8765678) n_basesample = 50 multidim_data = np.random.randn(n_basesample) kde = mlab.GaussianKDE(multidim_data, bw_method='silverman') y_expected = 0.48438841363348911 assert_almost_equal(kde.covariance_factor(), y_expected, 7) def test_wrong_bw_method(self): """Test the error message that should be called when bw is invalid.""" np.random.seed(8765678) n_basesample = 50 data = np.random.randn(n_basesample) with pytest.raises(ValueError): mlab.GaussianKDE(data, bw_method="invalid") class TestGaussianKDEEvaluate(object): def test_evaluate_diff_dim(self): """Test the evaluate method when the dim's of dataset and points are different dimensions""" x1 = np.arange(3, 10, 2) kde = mlab.GaussianKDE(x1) x2 = np.arange(3, 12, 2) y_expected = [ 0.08797252, 0.11774109, 0.11774109, 0.08797252, 0.0370153 ] y = kde.evaluate(x2) np.testing.assert_array_almost_equal(y, y_expected, 7) def test_evaluate_inv_dim(self): """ Invert the dimensions. i.e., Give the dataset a dimension of 1 [3,2,4], and the points will have a dimension of 3 [[3],[2],[4]]. ValueError should be raised""" np.random.seed(8765678) n_basesample = 50 multidim_data = np.random.randn(n_basesample) kde = mlab.GaussianKDE(multidim_data) x2 = [[1], [2], [3]] with pytest.raises(ValueError): kde.evaluate(x2) def test_evaluate_dim_and_num(self): """ Tests if evaluated against a one by one array""" x1 = np.arange(3, 10, 2) x2 = np.array([3]) kde = mlab.GaussianKDE(x1) y_expected = [0.08797252] y = kde.evaluate(x2) np.testing.assert_array_almost_equal(y, y_expected, 7) def test_evaluate_point_dim_not_one(self): """Test""" x1 = np.arange(3, 10, 2) x2 = [np.arange(3, 10, 2), np.arange(3, 10, 2)] kde = mlab.GaussianKDE(x1) with pytest.raises(ValueError): kde.evaluate(x2) def test_evaluate_equal_dim_and_num_lt(self): """Test when line 3810 fails""" x1 = np.arange(3, 10, 2) x2 = np.arange(3, 8, 2) kde = mlab.GaussianKDE(x1) y_expected = [0.08797252, 0.11774109, 0.11774109] y = kde.evaluate(x2) np.testing.assert_array_almost_equal(y, y_expected, 7) def test_contiguous_regions(): a, b, c = 3, 4, 5 # Starts and ends with True mask = [True]*a + [False]*b + [True]*c expected = [(0, a), (a+b, a+b+c)] with pytest.warns(MatplotlibDeprecationWarning): assert mlab.contiguous_regions(mask) == expected d, e = 6, 7 # Starts with True ends with False mask = mask + [False]*e with pytest.warns(MatplotlibDeprecationWarning): assert mlab.contiguous_regions(mask) == expected # Starts with False ends with True mask = [False]*d + mask[:-e] expected = [(d, d+a), (d+a+b, d+a+b+c)] with pytest.warns(MatplotlibDeprecationWarning): assert mlab.contiguous_regions(mask) == expected # Starts and ends with False mask = mask + [False]*e with pytest.warns(MatplotlibDeprecationWarning): assert mlab.contiguous_regions(mask) == expected # No True in mask assert mlab.contiguous_regions([False]*5) == [] # Empty mask assert mlab.contiguous_regions([]) == [] def test_psd_onesided_norm(): u = np.array([0, 1, 2, 3, 1, 2, 1]) dt = 1.0 Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size) P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none, detrend=mlab.detrend_none, noverlap=0, pad_to=None, scale_by_freq=None, sides='onesided') Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1]) assert_allclose(P, Su_1side, atol=1e-06) def test_psd_oversampling(): """Test the case len(x) < NFFT for psd().""" u = np.array([0, 1, 2, 3, 1, 2, 1]) dt = 1.0 Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size) P, f = mlab.psd(u, NFFT=u.size*2, Fs=1/dt, window=mlab.window_none, detrend=mlab.detrend_none, noverlap=0, pad_to=None, scale_by_freq=None, sides='onesided') Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1]) assert_almost_equal(np.sum(P), np.sum(Su_1side)) # same energy
97,575
38.392814
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backend_svg.py
from __future__ import absolute_import, division, print_function import six import numpy as np from io import BytesIO import os import tempfile import xml.parsers.expat import pytest import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison import matplotlib from matplotlib import dviread needs_usetex = pytest.mark.xfail( not matplotlib.checkdep_usetex(True), reason="This test needs a TeX installation") def test_visibility(): fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(0, 4 * np.pi, 50) y = np.sin(x) yerr = np.ones_like(y) a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko') for artist in b: artist.set_visible(False) fd = BytesIO() fig.savefig(fd, format='svg') fd.seek(0) buf = fd.read() fd.close() parser = xml.parsers.expat.ParserCreate() parser.Parse(buf) # this will raise ExpatError if the svg is invalid @image_comparison(baseline_images=['fill_black_with_alpha'], remove_text=True, extensions=['svg']) def test_fill_black_with_alpha(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.scatter(x=[0, 0.1, 1], y=[0, 0, 0], c='k', alpha=0.1, s=10000) @image_comparison(baseline_images=['noscale'], remove_text=True) def test_noscale(): X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.imshow(Z, cmap='gray', interpolation='none') def test_text_urls(): fig = plt.figure() test_url = "http://test_text_urls.matplotlib.org" fig.suptitle("test_text_urls", url=test_url) fd = BytesIO() fig.savefig(fd, format='svg') fd.seek(0) buf = fd.read().decode() fd.close() expected = '<a xlink:href="{0}">'.format(test_url) assert expected in buf @image_comparison(baseline_images=['bold_font_output'], extensions=['svg']) def test_bold_font_output(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.arange(10), np.arange(10)) ax.set_xlabel('nonbold-xlabel') ax.set_ylabel('bold-ylabel', fontweight='bold') ax.set_title('bold-title', fontweight='bold') @image_comparison(baseline_images=['bold_font_output_with_none_fonttype'], extensions=['svg']) def test_bold_font_output_with_none_fonttype(): plt.rcParams['svg.fonttype'] = 'none' fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.arange(10), np.arange(10)) ax.set_xlabel('nonbold-xlabel') ax.set_ylabel('bold-ylabel', fontweight='bold') ax.set_title('bold-title', fontweight='bold') def _test_determinism_save(filename, usetex): # This function is mostly copy&paste from "def test_visibility" # To require no GUI, we use Figure and FigureCanvasSVG # instead of plt.figure and fig.savefig from matplotlib.figure import Figure from matplotlib.backends.backend_svg import FigureCanvasSVG from matplotlib import rc rc('svg', hashsalt='asdf') rc('text', usetex=usetex) fig = Figure() ax = fig.add_subplot(111) x = np.linspace(0, 4 * np.pi, 50) y = np.sin(x) yerr = np.ones_like(y) a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko') for artist in b: artist.set_visible(False) ax.set_title('A string $1+2+\\sigma$') ax.set_xlabel('A string $1+2+\\sigma$') ax.set_ylabel('A string $1+2+\\sigma$') FigureCanvasSVG(fig).print_svg(filename) @pytest.mark.parametrize( "filename, usetex", # unique filenames to allow for parallel testing [("determinism_notex.svg", False), needs_usetex(("determinism_tex.svg", True))]) def test_determinism(filename, usetex): import sys from subprocess import check_output, STDOUT, CalledProcessError plots = [] for i in range(3): # Using check_output and setting stderr to STDOUT will capture the real # problem in the output property of the exception try: check_output( [sys.executable, '-R', '-c', 'import matplotlib; ' 'matplotlib._called_from_pytest = True; ' 'matplotlib.use("svg"); ' 'from matplotlib.tests.test_backend_svg ' 'import _test_determinism_save;' '_test_determinism_save(%r, %r)' % (filename, usetex)], stderr=STDOUT) except CalledProcessError as e: # it's easier to use utf8 and ask for forgiveness than try # to figure out what the current console has as an # encoding :-/ print(e.output.decode(encoding="utf-8", errors="ignore")) raise e else: with open(filename, 'rb') as fd: plots.append(fd.read()) finally: os.unlink(filename) for p in plots[1:]: assert p == plots[0] @needs_usetex def test_missing_psfont(monkeypatch): """An error is raised if a TeX font lacks a Type-1 equivalent""" from matplotlib import rc def psfont(*args, **kwargs): return dviread.PsFont(texname='texfont', psname='Some Font', effects=None, encoding=None, filename=None) monkeypatch.setattr(dviread.PsfontsMap, '__getitem__', psfont) rc('text', usetex=True) fig, ax = plt.subplots() ax.text(0.5, 0.5, 'hello') with tempfile.TemporaryFile() as tmpfile, pytest.raises(ValueError): fig.savefig(tmpfile, format='svg')
5,510
29.28022
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backend_qt5.py
from __future__ import absolute_import, division, print_function import copy import matplotlib from matplotlib import pyplot as plt from matplotlib._pylab_helpers import Gcf from numpy.testing import assert_equal import pytest try: # mock in python 3.3+ from unittest import mock except ImportError: import mock with matplotlib.rc_context(rc={'backend': 'Qt5Agg'}): qt_compat = pytest.importorskip('matplotlib.backends.qt_compat', minversion='5') from matplotlib.backends.backend_qt5 import ( MODIFIER_KEYS, SUPER, ALT, CTRL, SHIFT) # noqa QtCore = qt_compat.QtCore _, ControlModifier, ControlKey = MODIFIER_KEYS[CTRL] _, AltModifier, AltKey = MODIFIER_KEYS[ALT] _, SuperModifier, SuperKey = MODIFIER_KEYS[SUPER] _, ShiftModifier, ShiftKey = MODIFIER_KEYS[SHIFT] @pytest.mark.backend('Qt5Agg') def test_fig_close(): # save the state of Gcf.figs init_figs = copy.copy(Gcf.figs) # make a figure using pyplot interface fig = plt.figure() # simulate user clicking the close button by reaching in # and calling close on the underlying Qt object fig.canvas.manager.window.close() # assert that we have removed the reference to the FigureManager # that got added by plt.figure() assert init_figs == Gcf.figs @pytest.mark.parametrize( 'qt_key, qt_mods, answer', [ (QtCore.Qt.Key_A, ShiftModifier, 'A'), (QtCore.Qt.Key_A, QtCore.Qt.NoModifier, 'a'), (QtCore.Qt.Key_A, ControlModifier, 'ctrl+a'), (QtCore.Qt.Key_Aacute, ShiftModifier, '\N{LATIN CAPITAL LETTER A WITH ACUTE}'), (QtCore.Qt.Key_Aacute, QtCore.Qt.NoModifier, '\N{LATIN SMALL LETTER A WITH ACUTE}'), (ControlKey, AltModifier, 'alt+control'), (AltKey, ControlModifier, 'ctrl+alt'), (QtCore.Qt.Key_Aacute, (ControlModifier | AltModifier | SuperModifier), 'ctrl+alt+super+\N{LATIN SMALL LETTER A WITH ACUTE}'), (QtCore.Qt.Key_Backspace, QtCore.Qt.NoModifier, 'backspace'), (QtCore.Qt.Key_Backspace, ControlModifier, 'ctrl+backspace'), (QtCore.Qt.Key_Play, QtCore.Qt.NoModifier, None), ], ids=[ 'shift', 'lower', 'control', 'unicode_upper', 'unicode_lower', 'alt_control', 'control_alt', 'modifier_order', 'backspace', 'backspace_mod', 'non_unicode_key', ] ) @pytest.mark.backend('Qt5Agg') def test_correct_key(qt_key, qt_mods, answer): """ Make a figure Send a key_press_event event (using non-public, qt5 backend specific api) Catch the event Assert sent and caught keys are the same """ qt_canvas = plt.figure().canvas event = mock.Mock() event.isAutoRepeat.return_value = False event.key.return_value = qt_key event.modifiers.return_value = qt_mods def receive(event): assert event.key == answer qt_canvas.mpl_connect('key_press_event', receive) qt_canvas.keyPressEvent(event) @pytest.mark.backend('Qt5Agg') def test_dpi_ratio_change(): """ Make sure that if _dpi_ratio changes, the figure dpi changes but the widget remains the same physical size. """ prop = 'matplotlib.backends.backend_qt5.FigureCanvasQT._dpi_ratio' with mock.patch(prop, new_callable=mock.PropertyMock) as p: p.return_value = 3 fig = plt.figure(figsize=(5, 2), dpi=120) qt_canvas = fig.canvas qt_canvas.show() from matplotlib.backends.backend_qt5 import qApp # Make sure the mocking worked assert qt_canvas._dpi_ratio == 3 size = qt_canvas.size() qt_canvas.manager.show() qt_canvas.draw() qApp.processEvents() # The DPI and the renderer width/height change assert fig.dpi == 360 assert qt_canvas.renderer.width == 1800 assert qt_canvas.renderer.height == 720 # The actual widget size and figure physical size don't change assert size.width() == 600 assert size.height() == 240 assert_equal(qt_canvas.get_width_height(), (600, 240)) assert_equal(fig.get_size_inches(), (5, 2)) p.return_value = 2 assert qt_canvas._dpi_ratio == 2 qt_canvas.draw() qApp.processEvents() # this second processEvents is required to fully run the draw. # On `update` we notice the DPI has changed and trigger a # resize event to refresh, the second processEvents is # required to process that and fully update the window sizes. qApp.processEvents() # The DPI and the renderer width/height change assert fig.dpi == 240 assert qt_canvas.renderer.width == 1200 assert qt_canvas.renderer.height == 480 # The actual widget size and figure physical size don't change assert size.width() == 600 assert size.height() == 240 assert_equal(qt_canvas.get_width_height(), (600, 240)) assert_equal(fig.get_size_inches(), (5, 2)) @pytest.mark.backend('Qt5Agg') def test_subplottool(): fig, ax = plt.subplots() with mock.patch( "matplotlib.backends.backend_qt5.SubplotToolQt.exec_", lambda self: None): fig.canvas.manager.toolbar.configure_subplots() @pytest.mark.backend('Qt5Agg') def test_figureoptions(): fig, ax = plt.subplots() ax.plot([1, 2]) ax.imshow([[1]]) with mock.patch( "matplotlib.backends.qt_editor.formlayout.FormDialog.exec_", lambda self: None): fig.canvas.manager.toolbar.edit_parameters()
5,629
29.765027
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_legend.py
from __future__ import absolute_import, division, print_function try: # mock in python 3.3+ from unittest import mock except ImportError: import mock import collections import numpy as np import pytest from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.transforms as mtransforms import matplotlib.collections as mcollections from matplotlib.legend_handler import HandlerTuple import matplotlib.legend as mlegend import inspect # test that docstrigs are the same def get_docstring_section(func, section): """ extract a section from the docstring of a function """ ll = inspect.getdoc(func) lines = ll.splitlines() insec = False st = '' for ind in range(len(lines)): if lines[ind][:len(section)] == section and lines[ind+1][:3] == '---': insec = True ind = ind+1 if insec: if len(lines[ind + 1]) > 3 and lines[ind + 1][0:3] == '---': insec = False break else: st += lines[ind] + '\n' return st def test_legend_kwdocstrings(): stax = get_docstring_section(mpl.axes.Axes.legend, 'Parameters') stfig = get_docstring_section(mpl.figure.Figure.legend, 'Parameters') assert stfig == stax stleg = get_docstring_section(mpl.legend.Legend.__init__, 'Other Parameters') stax = get_docstring_section(mpl.axes.Axes.legend, 'Other Parameters') stfig = get_docstring_section(mpl.figure.Figure.legend, 'Other Parameters') assert stleg == stax assert stfig == stax assert stleg == stfig def test_legend_ordereddict(): # smoketest that ordereddict inputs work... X = np.random.randn(10) Y = np.random.randn(10) labels = ['a'] * 5 + ['b'] * 5 colors = ['r'] * 5 + ['g'] * 5 fig, ax = plt.subplots() for x, y, label, color in zip(X, Y, labels, colors): ax.scatter(x, y, label=label, c=color) handles, labels = ax.get_legend_handles_labels() legend = collections.OrderedDict(zip(labels, handles)) ax.legend(legend.values(), legend.keys(), loc=6, bbox_to_anchor=(1, .5)) @image_comparison(baseline_images=['legend_auto1'], remove_text=True) def test_legend_auto1(): 'Test automatic legend placement' fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(100) ax.plot(x, 50 - x, 'o', label='y=1') ax.plot(x, x - 50, 'o', label='y=-1') ax.legend(loc=0) @image_comparison(baseline_images=['legend_auto2'], remove_text=True) def test_legend_auto2(): 'Test automatic legend placement' fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(100) b1 = ax.bar(x, x, color='m') b2 = ax.bar(x, x[::-1], color='g') ax.legend([b1[0], b2[0]], ['up', 'down'], loc=0) @image_comparison(baseline_images=['legend_auto3']) def test_legend_auto3(): 'Test automatic legend placement' fig = plt.figure() ax = fig.add_subplot(111) x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5] y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5] ax.plot(x, y, 'o-', label='line') ax.set_xlim(0.0, 1.0) ax.set_ylim(0.0, 1.0) ax.legend(loc=0) @image_comparison(baseline_images=['legend_various_labels'], remove_text=True) def test_various_labels(): # tests all sorts of label types fig = plt.figure() ax = fig.add_subplot(121) ax.plot(np.arange(4), 'o', label=1) ax.plot(np.linspace(4, 4.1), 'o', label=u'D\xe9velopp\xe9s') ax.plot(np.arange(4, 1, -1), 'o', label='__nolegend__') ax.legend(numpoints=1, loc=0) @image_comparison(baseline_images=['legend_labels_first'], extensions=['png'], remove_text=True) def test_labels_first(): # test labels to left of markers fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.arange(10), '-o', label=1) ax.plot(np.ones(10)*5, ':x', label="x") ax.plot(np.arange(20, 10, -1), 'd', label="diamond") ax.legend(loc=0, markerfirst=False) @image_comparison(baseline_images=['legend_multiple_keys'], extensions=['png'], remove_text=True) def test_multiple_keys(): # test legend entries with multiple keys fig = plt.figure() ax = fig.add_subplot(111) p1, = ax.plot([1, 2, 3], '-o') p2, = ax.plot([2, 3, 4], '-x') p3, = ax.plot([3, 4, 5], '-d') ax.legend([(p1, p2), (p2, p1), p3], ['two keys', 'pad=0', 'one key'], numpoints=1, handler_map={(p1, p2): HandlerTuple(ndivide=None), (p2, p1): HandlerTuple(ndivide=None, pad=0)}) @image_comparison(baseline_images=['rgba_alpha'], extensions=['png'], remove_text=True) def test_alpha_rgba(): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.plot(range(10), lw=5) leg = plt.legend(['Longlabel that will go away'], loc=10) leg.legendPatch.set_facecolor([1, 0, 0, 0.5]) @image_comparison(baseline_images=['rcparam_alpha'], extensions=['png'], remove_text=True) def test_alpha_rcparam(): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.plot(range(10), lw=5) with mpl.rc_context(rc={'legend.framealpha': .75}): leg = plt.legend(['Longlabel that will go away'], loc=10) # this alpha is going to be over-ridden by the rcparam with # sets the alpha of the patch to be non-None which causes the alpha # value of the face color to be discarded. This behavior may not be # ideal, but it is what it is and we should keep track of it changing leg.legendPatch.set_facecolor([1, 0, 0, 0.5]) @image_comparison(baseline_images=['fancy'], remove_text=True) def test_fancy(): # using subplot triggers some offsetbox functionality untested elsewhere plt.subplot(121) plt.scatter(np.arange(10), np.arange(10, 0, -1), label='XX\nXX') plt.plot([5] * 10, 'o--', label='XX') plt.errorbar(np.arange(10), np.arange(10), xerr=0.5, yerr=0.5, label='XX') plt.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], ncol=2, shadow=True, title="My legend", numpoints=1) @image_comparison(baseline_images=['framealpha'], remove_text=True) def test_framealpha(): x = np.linspace(1, 100, 100) y = x plt.plot(x, y, label='mylabel', lw=10) plt.legend(framealpha=0.5) @image_comparison(baseline_images=['scatter_rc3', 'scatter_rc1'], remove_text=True) def test_rc(): # using subplot triggers some offsetbox functionality untested elsewhere plt.figure() ax = plt.subplot(121) ax.scatter(np.arange(10), np.arange(10, 0, -1), label='three') ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], title="My legend") mpl.rcParams['legend.scatterpoints'] = 1 plt.figure() ax = plt.subplot(121) ax.scatter(np.arange(10), np.arange(10, 0, -1), label='one') ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], title="My legend") @image_comparison(baseline_images=['legend_expand'], remove_text=True) def test_legend_expand(): 'Test expand mode' legend_modes = [None, "expand"] fig, axes_list = plt.subplots(len(legend_modes), 1) x = np.arange(100) for ax, mode in zip(axes_list, legend_modes): ax.plot(x, 50 - x, 'o', label='y=1') l1 = ax.legend(loc=2, mode=mode) ax.add_artist(l1) ax.plot(x, x - 50, 'o', label='y=-1') l2 = ax.legend(loc=5, mode=mode) ax.add_artist(l2) ax.legend(loc=3, mode=mode, ncol=2) @image_comparison(baseline_images=['hatching'], remove_text=True, style='default') def test_hatching(): fig, ax = plt.subplots() # Patches patch = plt.Rectangle((0, 0), 0.3, 0.3, hatch='xx', label='Patch\ndefault color\nfilled') ax.add_patch(patch) patch = plt.Rectangle((0.33, 0), 0.3, 0.3, hatch='||', edgecolor='C1', label='Patch\nexplicit color\nfilled') ax.add_patch(patch) patch = plt.Rectangle((0, 0.4), 0.3, 0.3, hatch='xx', fill=False, label='Patch\ndefault color\nunfilled') ax.add_patch(patch) patch = plt.Rectangle((0.33, 0.4), 0.3, 0.3, hatch='||', fill=False, edgecolor='C1', label='Patch\nexplicit color\nunfilled') ax.add_patch(patch) # Paths ax.fill_between([0, .15, .3], [.8, .8, .8], [.9, 1.0, .9], hatch='+', label='Path\ndefault color') ax.fill_between([.33, .48, .63], [.8, .8, .8], [.9, 1.0, .9], hatch='+', edgecolor='C2', label='Path\nexplicit color') ax.set_xlim(-0.01, 1.1) ax.set_ylim(-0.01, 1.1) ax.legend(handlelength=4, handleheight=4) def test_legend_remove(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) lines = ax.plot(range(10)) leg = fig.legend(lines, "test") leg.remove() assert fig.legends == [] leg = ax.legend("test") leg.remove() assert ax.get_legend() is None class TestLegendFunction(object): # Tests the legend function on the Axes and pyplot. def test_legend_handle_label(self): lines = plt.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend(lines, ['hello world']) Legend.assert_called_with(plt.gca(), lines, ['hello world']) def test_legend_no_args(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend() Legend.assert_called_with(plt.gca(), lines, ['hello world']) def test_legend_label_args(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend(['foobar']) Legend.assert_called_with(plt.gca(), lines, ['foobar']) def test_legend_three_args(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend(lines, ['foobar'], loc='right') Legend.assert_called_with(plt.gca(), lines, ['foobar'], loc='right') def test_legend_handler_map(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.' '_get_legend_handles_labels') as handles_labels: handles_labels.return_value = lines, ['hello world'] plt.legend(handler_map={'1': 2}) handles_labels.assert_called_with([plt.gca()], {'1': 2}) def test_kwargs(self): fig, ax = plt.subplots(1, 1) th = np.linspace(0, 2*np.pi, 1024) lns, = ax.plot(th, np.sin(th), label='sin', lw=5) lnc, = ax.plot(th, np.cos(th), label='cos', lw=5) with mock.patch('matplotlib.legend.Legend') as Legend: ax.legend(labels=('a', 'b'), handles=(lnc, lns)) Legend.assert_called_with(ax, (lnc, lns), ('a', 'b')) def test_warn_args_kwargs(self): fig, ax = plt.subplots(1, 1) th = np.linspace(0, 2*np.pi, 1024) lns, = ax.plot(th, np.sin(th), label='sin', lw=5) lnc, = ax.plot(th, np.cos(th), label='cos', lw=5) with mock.patch('warnings.warn') as warn: ax.legend((lnc, lns), labels=('a', 'b')) warn.assert_called_with("You have mixed positional and keyword " "arguments, some input may be " "discarded.") def test_parasite(self): from mpl_toolkits.axes_grid1 import host_subplot host = host_subplot(111) par = host.twinx() p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density") p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature") with mock.patch('matplotlib.legend.Legend') as Legend: leg = plt.legend() Legend.assert_called_with(host, [p1, p2], ['Density', 'Temperature']) class TestLegendFigureFunction(object): # Tests the legend function for figure def test_legend_handle_label(self): fig, ax = plt.subplots() lines = ax.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(lines, ['hello world']) Legend.assert_called_with(fig, lines, ['hello world']) def test_legend_no_args(self): fig, ax = plt.subplots() lines = ax.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend() Legend.assert_called_with(fig, lines, ['hello world']) def test_legend_label_arg(self): fig, ax = plt.subplots() lines = ax.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(['foobar']) Legend.assert_called_with(fig, lines, ['foobar']) def test_legend_label_three_args(self): fig, ax = plt.subplots() lines = ax.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(lines, ['foobar'], 'right') Legend.assert_called_with(fig, lines, ['foobar'], 'right') def test_legend_label_three_args_pluskw(self): # test that third argument and loc= called together give # Exception fig, ax = plt.subplots() lines = ax.plot(range(10)) with pytest.raises(Exception): fig.legend(lines, ['foobar'], 'right', loc='left') def test_legend_kw_args(self): fig, axs = plt.subplots(1, 2) lines = axs[0].plot(range(10)) lines2 = axs[1].plot(np.arange(10) * 2.) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(loc='right', labels=('a', 'b'), handles=(lines, lines2)) Legend.assert_called_with(fig, (lines, lines2), ('a', 'b'), loc='right') def test_warn_args_kwargs(self): fig, axs = plt.subplots(1, 2) lines = axs[0].plot(range(10)) lines2 = axs[1].plot(np.arange(10) * 2.) with mock.patch('warnings.warn') as warn: fig.legend((lines, lines2), labels=('a', 'b')) warn.assert_called_with("You have mixed positional and keyword " "arguments, some input may be " "discarded.") @image_comparison(baseline_images=['legend_stackplot'], extensions=['png']) def test_legend_stackplot(): '''test legend for PolyCollection using stackplot''' # related to #1341, #1943, and PR #3303 fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(0, 10, 10) y1 = 1.0 * x y2 = 2.0 * x + 1 y3 = 3.0 * x + 2 ax.stackplot(x, y1, y2, y3, labels=['y1', 'y2', 'y3']) ax.set_xlim((0, 10)) ax.set_ylim((0, 70)) ax.legend(loc=0) def test_cross_figure_patch_legend(): fig, ax = plt.subplots() fig2, ax2 = plt.subplots() brs = ax.bar(range(3), range(3)) fig2.legend(brs, 'foo') def test_nanscatter(): fig, ax = plt.subplots() h = ax.scatter([np.nan], [np.nan], marker="o", facecolor="r", edgecolor="r", s=3) ax.legend([h], ["scatter"]) fig, ax = plt.subplots() for color in ['red', 'green', 'blue']: n = 750 x, y = np.random.rand(2, n) scale = 200.0 * np.random.rand(n) ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none') ax.legend() ax.grid(True) def test_legend_repeatcheckok(): fig, ax = plt.subplots() ax.scatter(0.0, 1.0, color='k', marker='o', label='test') ax.scatter(0.5, 0.0, color='r', marker='v', label='test') hl = ax.legend() hand, lab = mlegend._get_legend_handles_labels([ax]) assert len(lab) == 2 fig, ax = plt.subplots() ax.scatter(0.0, 1.0, color='k', marker='o', label='test') ax.scatter(0.5, 0.0, color='k', marker='v', label='test') hl = ax.legend() hand, lab = mlegend._get_legend_handles_labels([ax]) assert len(lab) == 2 @image_comparison(baseline_images=['not_covering_scatter'], extensions=['png']) def test_not_covering_scatter(): colors = ['b', 'g', 'r'] for n in range(3): plt.scatter([n], [n], color=colors[n]) plt.legend(['foo', 'foo', 'foo'], loc='best') plt.gca().set_xlim(-0.5, 2.2) plt.gca().set_ylim(-0.5, 2.2) @image_comparison(baseline_images=['not_covering_scatter_transform'], extensions=['png']) def test_not_covering_scatter_transform(): # Offsets point to top left, the default auto position offset = mtransforms.Affine2D().translate(-20, 20) x = np.linspace(0, 30, 1000) plt.plot(x, x) plt.scatter([20], [10], transform=offset + plt.gca().transData) plt.legend(['foo', 'bar'], loc='best') def test_linecollection_scaled_dashes(): lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]] lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]] lines3 = [[[0.6, .2], [.8, .4]], [[.5, .7], [.1, .1]]] lc1 = mcollections.LineCollection(lines1, linestyles="--", lw=3) lc2 = mcollections.LineCollection(lines2, linestyles="-.") lc3 = mcollections.LineCollection(lines3, linestyles=":", lw=.5) fig, ax = plt.subplots() ax.add_collection(lc1) ax.add_collection(lc2) ax.add_collection(lc3) leg = ax.legend([lc1, lc2, lc3], ["line1", "line2", 'line 3']) h1, h2, h3 = leg.legendHandles for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)): assert oh.get_linestyles()[0][1] == lh._dashSeq assert oh.get_linestyles()[0][0] == lh._dashOffset def test_handler_numpoints(): '''test legend handler with numponts less than or equal to 1''' # related to #6921 and PR #8478 fig, ax = plt.subplots() ax.plot(range(5), label='test') ax.legend(numpoints=0.5) def test_shadow_framealpha(): # Test if framealpha is activated when shadow is True # and framealpha is not explicitly passed''' fig, ax = plt.subplots() ax.plot(range(100), label="test") leg = ax.legend(shadow=True, facecolor='w') assert leg.get_frame().get_alpha() == 1
18,218
34.036538
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_skew.py
""" Testing that skewed axes properly work """ from __future__ import absolute_import, division, print_function import itertools import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison from matplotlib.axes import Axes import matplotlib.transforms as transforms import matplotlib.axis as maxis import matplotlib.spines as mspines import matplotlib.patches as mpatch from matplotlib.projections import register_projection # The sole purpose of this class is to look at the upper, lower, or total # interval as appropriate and see what parts of the tick to draw, if any. class SkewXTick(maxis.XTick): def update_position(self, loc): # This ensures that the new value of the location is set before # any other updates take place self._loc = loc super(SkewXTick, self).update_position(loc) def _has_default_loc(self): return self.get_loc() is None def _need_lower(self): return (self._has_default_loc() or transforms.interval_contains(self.axes.lower_xlim, self.get_loc())) def _need_upper(self): return (self._has_default_loc() or transforms.interval_contains(self.axes.upper_xlim, self.get_loc())) @property def gridOn(self): return (self._gridOn and (self._has_default_loc() or transforms.interval_contains(self.get_view_interval(), self.get_loc()))) @gridOn.setter def gridOn(self, value): self._gridOn = value @property def tick1On(self): return self._tick1On and self._need_lower() @tick1On.setter def tick1On(self, value): self._tick1On = value @property def label1On(self): return self._label1On and self._need_lower() @label1On.setter def label1On(self, value): self._label1On = value @property def tick2On(self): return self._tick2On and self._need_upper() @tick2On.setter def tick2On(self, value): self._tick2On = value @property def label2On(self): return self._label2On and self._need_upper() @label2On.setter def label2On(self, value): self._label2On = value def get_view_interval(self): return self.axes.xaxis.get_view_interval() # This class exists to provide two separate sets of intervals to the tick, # as well as create instances of the custom tick class SkewXAxis(maxis.XAxis): def _get_tick(self, major): return SkewXTick(self.axes, None, '', major=major) def get_view_interval(self): return self.axes.upper_xlim[0], self.axes.lower_xlim[1] # This class exists to calculate the separate data range of the # upper X-axis and draw the spine there. It also provides this range # to the X-axis artist for ticking and gridlines class SkewSpine(mspines.Spine): def _adjust_location(self): pts = self._path.vertices if self.spine_type == 'top': pts[:, 0] = self.axes.upper_xlim else: pts[:, 0] = self.axes.lower_xlim # This class handles registration of the skew-xaxes as a projection as well # as setting up the appropriate transformations. It also overrides standard # spines and axes instances as appropriate. class SkewXAxes(Axes): # The projection must specify a name. This will be used be the # user to select the projection, i.e. ``subplot(111, # projection='skewx')``. name = 'skewx' def _init_axis(self): # Taken from Axes and modified to use our modified X-axis self.xaxis = SkewXAxis(self) self.spines['top'].register_axis(self.xaxis) self.spines['bottom'].register_axis(self.xaxis) self.yaxis = maxis.YAxis(self) self.spines['left'].register_axis(self.yaxis) self.spines['right'].register_axis(self.yaxis) def _gen_axes_spines(self): spines = {'top': SkewSpine.linear_spine(self, 'top'), 'bottom': mspines.Spine.linear_spine(self, 'bottom'), 'left': mspines.Spine.linear_spine(self, 'left'), 'right': mspines.Spine.linear_spine(self, 'right')} return spines def _set_lim_and_transforms(self): """ This is called once when the plot is created to set up all the transforms for the data, text and grids. """ rot = 30 # Get the standard transform setup from the Axes base class Axes._set_lim_and_transforms(self) # Need to put the skew in the middle, after the scale and limits, # but before the transAxes. This way, the skew is done in Axes # coordinates thus performing the transform around the proper origin # We keep the pre-transAxes transform around for other users, like the # spines for finding bounds self.transDataToAxes = (self.transScale + (self.transLimits + transforms.Affine2D().skew_deg(rot, 0))) # Create the full transform from Data to Pixels self.transData = self.transDataToAxes + self.transAxes # Blended transforms like this need to have the skewing applied using # both axes, in axes coords like before. self._xaxis_transform = (transforms.blended_transform_factory( self.transScale + self.transLimits, transforms.IdentityTransform()) + transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes @property def lower_xlim(self): return self.axes.viewLim.intervalx @property def upper_xlim(self): pts = [[0., 1.], [1., 1.]] return self.transDataToAxes.inverted().transform(pts)[:, 0] # Now register the projection with matplotlib so the user can select # it. register_projection(SkewXAxes) @image_comparison(baseline_images=['skew_axes'], remove_text=True) def test_set_line_coll_dash_image(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='skewx') ax.set_xlim(-50, 50) ax.set_ylim(50, -50) ax.grid(True) # An example of a slanted line at constant X ax.axvline(0, color='b') @image_comparison(baseline_images=['skew_rects'], remove_text=True) def test_skew_rectangle(): fix, axes = plt.subplots(5, 5, sharex=True, sharey=True, figsize=(8, 8)) axes = axes.flat rotations = list(itertools.product([-3, -1, 0, 1, 3], repeat=2)) axes[0].set_xlim([-3, 3]) axes[0].set_ylim([-3, 3]) axes[0].set_aspect('equal', share=True) for ax, (xrots, yrots) in zip(axes, rotations): xdeg, ydeg = 45 * xrots, 45 * yrots t = transforms.Affine2D().skew_deg(xdeg, ydeg) ax.set_title('Skew of {0} in X and {1} in Y'.format(xdeg, ydeg)) ax.add_patch(mpatch.Rectangle([-1, -1], 2, 2, transform=t + ax.transData, alpha=0.5, facecolor='coral')) plt.subplots_adjust(wspace=0, left=0.01, right=0.99, bottom=0.01, top=0.99)
7,139
32.679245
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_arrow_patches.py
from __future__ import absolute_import, division, print_function import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison import matplotlib.patches as mpatches def draw_arrow(ax, t, r): ax.annotate('', xy=(0.5, 0.5 + r), xytext=(0.5, 0.5), size=30, arrowprops=dict(arrowstyle=t, fc="b", ec='k')) @image_comparison(baseline_images=['fancyarrow_test_image']) def test_fancyarrow(): # Added 0 to test division by zero error described in issue 3930 r = [0.4, 0.3, 0.2, 0.1, 0] t = ["fancy", "simple", mpatches.ArrowStyle.Fancy()] fig, axes = plt.subplots(len(t), len(r), squeeze=False, subplot_kw=dict(aspect=True), figsize=(8, 4.5)) for i_r, r1 in enumerate(r): for i_t, t1 in enumerate(t): ax = axes[i_t, i_r] draw_arrow(ax, t1, r1) ax.tick_params(labelleft=False, labelbottom=False) @image_comparison(baseline_images=['boxarrow_test_image'], extensions=['png']) def test_boxarrow(): styles = mpatches.BoxStyle.get_styles() n = len(styles) spacing = 1.2 figheight = (n * spacing + .5) fig1 = plt.figure(1, figsize=(4 / 1.5, figheight / 1.5)) fontsize = 0.3 * 72 for i, stylename in enumerate(sorted(styles)): fig1.text(0.5, ((n - i) * spacing - 0.5)/figheight, stylename, ha="center", size=fontsize, transform=fig1.transFigure, bbox=dict(boxstyle=stylename, fc="w", ec="k")) def __prepare_fancyarrow_dpi_cor_test(): """ Convenience function that prepares and returns a FancyArrowPatch. It aims at being used to test that the size of the arrow head does not depend on the DPI value of the exported picture. NB: this function *is not* a test in itself! """ fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50) ax = fig2.add_subplot(111) ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6), lw=3, arrowstyle=u'->', mutation_scale=100)) return fig2 @image_comparison(baseline_images=['fancyarrow_dpi_cor_100dpi'], remove_text=True, extensions=['png'], savefig_kwarg=dict(dpi=100)) def test_fancyarrow_dpi_cor_100dpi(): """ Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is instantiated through a dedicated function because another similar test checks a similar export but with a different DPI value. Remark: test only a rasterized format. """ __prepare_fancyarrow_dpi_cor_test() @image_comparison(baseline_images=['fancyarrow_dpi_cor_200dpi'], remove_text=True, extensions=['png'], savefig_kwarg=dict(dpi=200)) def test_fancyarrow_dpi_cor_200dpi(): """ As test_fancyarrow_dpi_cor_100dpi, but exports @ 200 DPI. The relative size of the arrow head should be the same. """ __prepare_fancyarrow_dpi_cor_test() @image_comparison(baseline_images=['fancyarrow_dash'], remove_text=True, extensions=['png'], style='default') def test_fancyarrow_dash(): from matplotlib.patches import FancyArrowPatch fig, ax = plt.subplots() e = FancyArrowPatch((0, 0), (0.5, 0.5), arrowstyle='-|>', connectionstyle='angle3,angleA=0,angleB=90', mutation_scale=10.0, linewidth=2, linestyle='dashed', color='k') e2 = FancyArrowPatch((0, 0), (0.5, 0.5), arrowstyle='-|>', connectionstyle='angle3', mutation_scale=10.0, linewidth=2, linestyle='dotted', color='k') ax.add_patch(e) ax.add_patch(e2) @image_comparison(baseline_images=['arrow_styles'], extensions=['png'], style='mpl20', remove_text=True) def test_arrow_styles(): styles = mpatches.ArrowStyle.get_styles() n = len(styles) fig, ax = plt.subplots(figsize=(6, 10)) ax.set_xlim(0, 1) ax.set_ylim(-1, n) for i, stylename in enumerate(sorted(styles)): patch = mpatches.FancyArrowPatch((0.1, i), (0.8, i), arrowstyle=stylename, mutation_scale=25) ax.add_patch(patch)
4,675
32.884058
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_collections.py
""" Tests specific to the collections module. """ from __future__ import absolute_import, division, print_function import io import numpy as np from numpy.testing import ( assert_array_equal, assert_array_almost_equal, assert_equal) import pytest import matplotlib.pyplot as plt import matplotlib.collections as mcollections import matplotlib.transforms as mtransforms from matplotlib.collections import Collection, LineCollection, EventCollection from matplotlib.testing.decorators import image_comparison def generate_EventCollection_plot(): ''' generate the initial collection and plot it ''' positions = np.array([0., 1., 2., 3., 5., 8., 13., 21.]) extra_positions = np.array([34., 55., 89.]) orientation = 'horizontal' lineoffset = 1 linelength = .5 linewidth = 2 color = [1, 0, 0, 1] linestyle = 'solid' antialiased = True coll = EventCollection(positions, orientation=orientation, lineoffset=lineoffset, linelength=linelength, linewidth=linewidth, color=color, linestyle=linestyle, antialiased=antialiased ) fig = plt.figure() splt = fig.add_subplot(1, 1, 1) splt.add_collection(coll) splt.set_title('EventCollection: default') props = {'positions': positions, 'extra_positions': extra_positions, 'orientation': orientation, 'lineoffset': lineoffset, 'linelength': linelength, 'linewidth': linewidth, 'color': color, 'linestyle': linestyle, 'antialiased': antialiased } splt.set_xlim(-1, 22) splt.set_ylim(0, 2) return splt, coll, props @image_comparison(baseline_images=['EventCollection_plot__default']) def test__EventCollection__get_segments(): ''' check to make sure the default segments have the correct coordinates ''' _, coll, props = generate_EventCollection_plot() check_segments(coll, props['positions'], props['linelength'], props['lineoffset'], props['orientation']) def test__EventCollection__get_positions(): ''' check to make sure the default positions match the input positions ''' _, coll, props = generate_EventCollection_plot() np.testing.assert_array_equal(props['positions'], coll.get_positions()) def test__EventCollection__get_orientation(): ''' check to make sure the default orientation matches the input orientation ''' _, coll, props = generate_EventCollection_plot() assert_equal(props['orientation'], coll.get_orientation()) def test__EventCollection__is_horizontal(): ''' check to make sure the default orientation matches the input orientation ''' _, coll, _ = generate_EventCollection_plot() assert_equal(True, coll.is_horizontal()) def test__EventCollection__get_linelength(): ''' check to make sure the default linelength matches the input linelength ''' _, coll, props = generate_EventCollection_plot() assert_equal(props['linelength'], coll.get_linelength()) def test__EventCollection__get_lineoffset(): ''' check to make sure the default lineoffset matches the input lineoffset ''' _, coll, props = generate_EventCollection_plot() assert_equal(props['lineoffset'], coll.get_lineoffset()) def test__EventCollection__get_linestyle(): ''' check to make sure the default linestyle matches the input linestyle ''' _, coll, _ = generate_EventCollection_plot() assert_equal(coll.get_linestyle(), [(None, None)]) def test__EventCollection__get_color(): ''' check to make sure the default color matches the input color ''' _, coll, props = generate_EventCollection_plot() np.testing.assert_array_equal(props['color'], coll.get_color()) check_allprop_array(coll.get_colors(), props['color']) @image_comparison(baseline_images=['EventCollection_plot__set_positions']) def test__EventCollection__set_positions(): ''' check to make sure set_positions works properly ''' splt, coll, props = generate_EventCollection_plot() new_positions = np.hstack([props['positions'], props['extra_positions']]) coll.set_positions(new_positions) np.testing.assert_array_equal(new_positions, coll.get_positions()) check_segments(coll, new_positions, props['linelength'], props['lineoffset'], props['orientation']) splt.set_title('EventCollection: set_positions') splt.set_xlim(-1, 90) @image_comparison(baseline_images=['EventCollection_plot__add_positions']) def test__EventCollection__add_positions(): ''' check to make sure add_positions works properly ''' splt, coll, props = generate_EventCollection_plot() new_positions = np.hstack([props['positions'], props['extra_positions'][0]]) coll.add_positions(props['extra_positions'][0]) np.testing.assert_array_equal(new_positions, coll.get_positions()) check_segments(coll, new_positions, props['linelength'], props['lineoffset'], props['orientation']) splt.set_title('EventCollection: add_positions') splt.set_xlim(-1, 35) @image_comparison(baseline_images=['EventCollection_plot__append_positions']) def test__EventCollection__append_positions(): ''' check to make sure append_positions works properly ''' splt, coll, props = generate_EventCollection_plot() new_positions = np.hstack([props['positions'], props['extra_positions'][2]]) coll.append_positions(props['extra_positions'][2]) np.testing.assert_array_equal(new_positions, coll.get_positions()) check_segments(coll, new_positions, props['linelength'], props['lineoffset'], props['orientation']) splt.set_title('EventCollection: append_positions') splt.set_xlim(-1, 90) @image_comparison(baseline_images=['EventCollection_plot__extend_positions']) def test__EventCollection__extend_positions(): ''' check to make sure extend_positions works properly ''' splt, coll, props = generate_EventCollection_plot() new_positions = np.hstack([props['positions'], props['extra_positions'][1:]]) coll.extend_positions(props['extra_positions'][1:]) np.testing.assert_array_equal(new_positions, coll.get_positions()) check_segments(coll, new_positions, props['linelength'], props['lineoffset'], props['orientation']) splt.set_title('EventCollection: extend_positions') splt.set_xlim(-1, 90) @image_comparison(baseline_images=['EventCollection_plot__switch_orientation']) def test__EventCollection__switch_orientation(): ''' check to make sure switch_orientation works properly ''' splt, coll, props = generate_EventCollection_plot() new_orientation = 'vertical' coll.switch_orientation() assert_equal(new_orientation, coll.get_orientation()) assert_equal(False, coll.is_horizontal()) new_positions = coll.get_positions() check_segments(coll, new_positions, props['linelength'], props['lineoffset'], new_orientation) splt.set_title('EventCollection: switch_orientation') splt.set_ylim(-1, 22) splt.set_xlim(0, 2) @image_comparison( baseline_images=['EventCollection_plot__switch_orientation__2x']) def test__EventCollection__switch_orientation_2x(): ''' check to make sure calling switch_orientation twice sets the orientation back to the default ''' splt, coll, props = generate_EventCollection_plot() coll.switch_orientation() coll.switch_orientation() new_positions = coll.get_positions() assert_equal(props['orientation'], coll.get_orientation()) assert_equal(True, coll.is_horizontal()) np.testing.assert_array_equal(props['positions'], new_positions) check_segments(coll, new_positions, props['linelength'], props['lineoffset'], props['orientation']) splt.set_title('EventCollection: switch_orientation 2x') @image_comparison(baseline_images=['EventCollection_plot__set_orientation']) def test__EventCollection__set_orientation(): ''' check to make sure set_orientation works properly ''' splt, coll, props = generate_EventCollection_plot() new_orientation = 'vertical' coll.set_orientation(new_orientation) assert_equal(new_orientation, coll.get_orientation()) assert_equal(False, coll.is_horizontal()) check_segments(coll, props['positions'], props['linelength'], props['lineoffset'], new_orientation) splt.set_title('EventCollection: set_orientation') splt.set_ylim(-1, 22) splt.set_xlim(0, 2) @image_comparison(baseline_images=['EventCollection_plot__set_linelength']) def test__EventCollection__set_linelength(): ''' check to make sure set_linelength works properly ''' splt, coll, props = generate_EventCollection_plot() new_linelength = 15 coll.set_linelength(new_linelength) assert_equal(new_linelength, coll.get_linelength()) check_segments(coll, props['positions'], new_linelength, props['lineoffset'], props['orientation']) splt.set_title('EventCollection: set_linelength') splt.set_ylim(-20, 20) @image_comparison(baseline_images=['EventCollection_plot__set_lineoffset']) def test__EventCollection__set_lineoffset(): ''' check to make sure set_lineoffset works properly ''' splt, coll, props = generate_EventCollection_plot() new_lineoffset = -5. coll.set_lineoffset(new_lineoffset) assert_equal(new_lineoffset, coll.get_lineoffset()) check_segments(coll, props['positions'], props['linelength'], new_lineoffset, props['orientation']) splt.set_title('EventCollection: set_lineoffset') splt.set_ylim(-6, -4) @image_comparison(baseline_images=['EventCollection_plot__set_linestyle']) def test__EventCollection__set_linestyle(): ''' check to make sure set_linestyle works properly ''' splt, coll, _ = generate_EventCollection_plot() new_linestyle = 'dashed' coll.set_linestyle(new_linestyle) assert_equal(coll.get_linestyle(), [(0, (6.0, 6.0))]) splt.set_title('EventCollection: set_linestyle') @image_comparison(baseline_images=['EventCollection_plot__set_ls_dash'], remove_text=True) def test__EventCollection__set_linestyle_single_dash(): ''' check to make sure set_linestyle accepts a single dash pattern ''' splt, coll, _ = generate_EventCollection_plot() new_linestyle = (0, (6., 6.)) coll.set_linestyle(new_linestyle) assert_equal(coll.get_linestyle(), [(0, (6.0, 6.0))]) splt.set_title('EventCollection: set_linestyle') @image_comparison(baseline_images=['EventCollection_plot__set_linewidth']) def test__EventCollection__set_linewidth(): ''' check to make sure set_linestyle works properly ''' splt, coll, _ = generate_EventCollection_plot() new_linewidth = 5 coll.set_linewidth(new_linewidth) assert_equal(coll.get_linewidth(), new_linewidth) splt.set_title('EventCollection: set_linewidth') @image_comparison(baseline_images=['EventCollection_plot__set_color']) def test__EventCollection__set_color(): ''' check to make sure set_color works properly ''' splt, coll, _ = generate_EventCollection_plot() new_color = np.array([0, 1, 1, 1]) coll.set_color(new_color) np.testing.assert_array_equal(new_color, coll.get_color()) check_allprop_array(coll.get_colors(), new_color) splt.set_title('EventCollection: set_color') def check_segments(coll, positions, linelength, lineoffset, orientation): ''' check to make sure all values in the segment are correct, given a particular set of inputs note: this is not a test, it is used by tests ''' segments = coll.get_segments() if (orientation.lower() == 'horizontal' or orientation.lower() == 'none' or orientation is None): # if horizontal, the position in is in the y-axis pos1 = 1 pos2 = 0 elif orientation.lower() == 'vertical': # if vertical, the position in is in the x-axis pos1 = 0 pos2 = 1 else: raise ValueError("orientation must be 'horizontal' or 'vertical'") # test to make sure each segment is correct for i, segment in enumerate(segments): assert_equal(segment[0, pos1], lineoffset + linelength / 2.) assert_equal(segment[1, pos1], lineoffset - linelength / 2.) assert_equal(segment[0, pos2], positions[i]) assert_equal(segment[1, pos2], positions[i]) def check_allprop_array(values, target): ''' check to make sure all values match the given target if arrays note: this is not a test, it is used by tests ''' for value in values: np.testing.assert_array_equal(value, target) def test_null_collection_datalim(): col = mcollections.PathCollection([]) col_data_lim = col.get_datalim(mtransforms.IdentityTransform()) assert_array_equal(col_data_lim.get_points(), mtransforms.Bbox.null().get_points()) def test_add_collection(): # Test if data limits are unchanged by adding an empty collection. # Github issue #1490, pull #1497. plt.figure() ax = plt.axes() coll = ax.scatter([0, 1], [0, 1]) ax.add_collection(coll) bounds = ax.dataLim.bounds coll = ax.scatter([], []) assert_equal(ax.dataLim.bounds, bounds) def test_quiver_limits(): ax = plt.axes() x, y = np.arange(8), np.arange(10) u = v = np.linspace(0, 10, 80).reshape(10, 8) q = plt.quiver(x, y, u, v) assert_equal(q.get_datalim(ax.transData).bounds, (0., 0., 7., 9.)) plt.figure() ax = plt.axes() x = np.linspace(-5, 10, 20) y = np.linspace(-2, 4, 10) y, x = np.meshgrid(y, x) trans = mtransforms.Affine2D().translate(25, 32) + ax.transData plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans) assert_equal(ax.dataLim.bounds, (20.0, 30.0, 15.0, 6.0)) def test_barb_limits(): ax = plt.axes() x = np.linspace(-5, 10, 20) y = np.linspace(-2, 4, 10) y, x = np.meshgrid(y, x) trans = mtransforms.Affine2D().translate(25, 32) + ax.transData plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans) # The calculated bounds are approximately the bounds of the original data, # this is because the entire path is taken into account when updating the # datalim. assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6), decimal=1) @image_comparison(baseline_images=['EllipseCollection_test_image'], extensions=['png'], remove_text=True) def test_EllipseCollection(): # Test basic functionality fig, ax = plt.subplots() x = np.arange(4) y = np.arange(3) X, Y = np.meshgrid(x, y) XY = np.vstack((X.ravel(), Y.ravel())).T ww = X / x[-1] hh = Y / y[-1] aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis ec = mcollections.EllipseCollection(ww, hh, aa, units='x', offsets=XY, transOffset=ax.transData, facecolors='none') ax.add_collection(ec) ax.autoscale_view() @image_comparison(baseline_images=['polycollection_close'], extensions=['png'], remove_text=True) def test_polycollection_close(): from mpl_toolkits.mplot3d import Axes3D vertsQuad = [ [[0., 0.], [0., 1.], [1., 1.], [1., 0.]], [[0., 1.], [2., 3.], [2., 2.], [1., 1.]], [[2., 2.], [2., 3.], [4., 1.], [3., 1.]], [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]] fig = plt.figure() ax = Axes3D(fig) colors = ['r', 'g', 'b', 'y', 'k'] zpos = list(range(5)) poly = mcollections.PolyCollection( vertsQuad * len(zpos), linewidth=0.25) poly.set_alpha(0.7) # need to have a z-value for *each* polygon = element! zs = [] cs = [] for z, c in zip(zpos, colors): zs.extend([z] * len(vertsQuad)) cs.extend([c] * len(vertsQuad)) poly.set_color(cs) ax.add_collection3d(poly, zs=zs, zdir='y') # axis limit settings: ax.set_xlim3d(0, 4) ax.set_zlim3d(0, 3) ax.set_ylim3d(0, 4) @image_comparison(baseline_images=['regularpolycollection_rotate'], extensions=['png'], remove_text=True) def test_regularpolycollection_rotate(): xx, yy = np.mgrid[:10, :10] xy_points = np.transpose([xx.flatten(), yy.flatten()]) rotations = np.linspace(0, 2*np.pi, len(xy_points)) fig, ax = plt.subplots() for xy, alpha in zip(xy_points, rotations): col = mcollections.RegularPolyCollection( 4, sizes=(100,), rotation=alpha, offsets=[xy], transOffset=ax.transData) ax.add_collection(col, autolim=True) ax.autoscale_view() @image_comparison(baseline_images=['regularpolycollection_scale'], extensions=['png'], remove_text=True) def test_regularpolycollection_scale(): # See issue #3860 class SquareCollection(mcollections.RegularPolyCollection): def __init__(self, **kwargs): super(SquareCollection, self).__init__( 4, rotation=np.pi/4., **kwargs) def get_transform(self): """Return transform scaling circle areas to data space.""" ax = self.axes pts2pixels = 72.0 / ax.figure.dpi scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height return mtransforms.Affine2D().scale(scale_x, scale_y) fig, ax = plt.subplots() xy = [(0, 0)] # Unit square has a half-diagonal of `1 / sqrt(2)`, so `pi * r**2` # equals... circle_areas = [np.pi / 2] squares = SquareCollection(sizes=circle_areas, offsets=xy, transOffset=ax.transData) ax.add_collection(squares, autolim=True) ax.axis([-1, 1, -1, 1]) def test_picking(): fig, ax = plt.subplots() col = ax.scatter([0], [0], [1000], picker=True) fig.savefig(io.BytesIO(), dpi=fig.dpi) class MouseEvent(object): pass event = MouseEvent() event.x = 325 event.y = 240 found, indices = col.contains(event) assert found assert_array_equal(indices['ind'], [0]) def test_linestyle_single_dashes(): plt.scatter([0, 1, 2], [0, 1, 2], linestyle=(0., [2., 2.])) plt.draw() @image_comparison(baseline_images=['size_in_xy'], remove_text=True, extensions=['png']) def test_size_in_xy(): fig, ax = plt.subplots() widths, heights, angles = (10, 10), 10, 0 widths = 10, 10 coords = [(10, 10), (15, 15)] e = mcollections.EllipseCollection( widths, heights, angles, units='xy', offsets=coords, transOffset=ax.transData) ax.add_collection(e) ax.set_xlim(0, 30) ax.set_ylim(0, 30) def test_pandas_indexing(pd): # Should not fail break when faced with a # non-zero indexed series index = [11, 12, 13] ec = fc = pd.Series(['red', 'blue', 'green'], index=index) lw = pd.Series([1, 2, 3], index=index) ls = pd.Series(['solid', 'dashed', 'dashdot'], index=index) aa = pd.Series([True, False, True], index=index) Collection(edgecolors=ec) Collection(facecolors=fc) Collection(linewidths=lw) Collection(linestyles=ls) Collection(antialiaseds=aa) @pytest.mark.style('default') def test_lslw_bcast(): col = mcollections.PathCollection([]) col.set_linestyles(['-', '-']) col.set_linewidths([1, 2, 3]) assert_equal(col.get_linestyles(), [(None, None)] * 6) assert_equal(col.get_linewidths(), [1, 2, 3] * 2) col.set_linestyles(['-', '-', '-']) assert_equal(col.get_linestyles(), [(None, None)] * 3) assert_equal(col.get_linewidths(), [1, 2, 3]) @pytest.mark.style('default') def test_capstyle(): col = mcollections.PathCollection([], capstyle='round') assert_equal(col.get_capstyle(), 'round') col.set_capstyle('butt') assert_equal(col.get_capstyle(), 'butt') @pytest.mark.style('default') def test_joinstyle(): col = mcollections.PathCollection([], joinstyle='round') assert_equal(col.get_joinstyle(), 'round') col.set_joinstyle('miter') assert_equal(col.get_joinstyle(), 'miter') @image_comparison(baseline_images=['cap_and_joinstyle'], extensions=['png']) def test_cap_and_joinstyle_image(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim([-0.5, 1.5]) ax.set_ylim([-0.5, 2.5]) x = np.array([0.0, 1.0, 0.5]) ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]]) segs = np.zeros((3, 3, 2)) segs[:, :, 0] = x segs[:, :, 1] = ys line_segments = LineCollection(segs, linewidth=[10, 15, 20]) line_segments.set_capstyle("round") line_segments.set_joinstyle("miter") ax.add_collection(line_segments) ax.set_title('Line collection with customized caps and joinstyle') @image_comparison(baseline_images=['scatter_post_alpha'], extensions=['png'], remove_text=True, style='default') def test_scatter_post_alpha(): fig, ax = plt.subplots() sc = ax.scatter(range(5), range(5), c=range(5)) # this needs to be here to update internal state fig.canvas.draw() sc.set_alpha(.1)
22,315
32.109792
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_container.py
from __future__ import absolute_import, division, print_function import six import matplotlib.pyplot as plt def test_stem_remove(): ax = plt.gca() st = ax.stem([1, 2], [1, 2]) st.remove() def test_errorbar_remove(): # Regression test for a bug that caused remove to fail when using # fmt='none' ax = plt.gca() eb = ax.errorbar([1], [1]) eb.remove() eb = ax.errorbar([1], [1], xerr=1) eb.remove() eb = ax.errorbar([1], [1], yerr=2) eb.remove() eb = ax.errorbar([1], [1], xerr=[2], yerr=2) eb.remove() eb = ax.errorbar([1], [1], fmt='none') eb.remove()
627
17.470588
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/__init__.py
from __future__ import absolute_import, division, print_function import six import difflib import os from matplotlib import cbook from matplotlib.testing import setup # Check that the test directories exist if not os.path.exists(os.path.join( os.path.dirname(__file__), 'baseline_images')): raise IOError( 'The baseline image directory does not exist. ' 'This is most likely because the test data is not installed. ' 'You may need to install matplotlib from source to get the ' 'test data.') @cbook.deprecated("2.1") def assert_str_equal(reference_str, test_str, format_str=('String {str1} and {str2} do not ' 'match:\n{differences}')): """ Assert the two strings are equal. If not, fail and print their diffs using difflib. """ if reference_str != test_str: diff = difflib.unified_diff(reference_str.splitlines(1), test_str.splitlines(1), 'Reference', 'Test result', '', '', 0) raise ValueError(format_str.format(str1=reference_str, str2=test_str, differences=''.join(diff)))
1,313
32.692308
70
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_png.py
from __future__ import absolute_import, division, print_function import six from six import BytesIO import glob import os import numpy as np import pytest from matplotlib.testing.decorators import image_comparison from matplotlib import pyplot as plt import matplotlib.cm as cm import sys on_win = (sys.platform == 'win32') @image_comparison(baseline_images=['pngsuite'], extensions=['png'], tol=0.03) def test_pngsuite(): dirname = os.path.join( os.path.dirname(__file__), 'baseline_images', 'pngsuite') files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png'))) fig = plt.figure(figsize=(len(files), 2)) for i, fname in enumerate(files): data = plt.imread(fname) cmap = None # use default colormap if data.ndim == 2: # keep grayscale images gray cmap = cm.gray plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap) plt.gca().patch.set_facecolor("#ddffff") plt.gca().set_xlim(0, len(files)) def test_imread_png_uint16(): from matplotlib import _png img = _png.read_png_int(os.path.join(os.path.dirname(__file__), 'baseline_images/test_png/uint16.png')) assert (img.dtype == np.uint16) assert np.sum(img.flatten()) == 134184960 def test_truncated_file(tmpdir): d = tmpdir.mkdir('test') fname = str(d.join('test.png')) fname_t = str(d.join('test_truncated.png')) plt.savefig(fname) with open(fname, 'rb') as fin: buf = fin.read() with open(fname_t, 'wb') as fout: fout.write(buf[:20]) with pytest.raises(Exception): plt.imread(fname_t) def test_truncated_buffer(): b = BytesIO() plt.savefig(b) b.seek(0) b2 = BytesIO(b.read(20)) b2.seek(0) with pytest.raises(Exception): plt.imread(b2)
1,864
24.902778
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_transforms.py
from __future__ import absolute_import, division, print_function from six.moves import zip import unittest import numpy as np from numpy.testing import (assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal) import pytest import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.transforms as mtransforms from matplotlib.path import Path from matplotlib.scale import LogScale from matplotlib.testing.decorators import image_comparison def test_non_affine_caching(): class AssertingNonAffineTransform(mtransforms.Transform): """ This transform raises an assertion error when called when it shouldn't be and self.raise_on_transform is True. """ input_dims = output_dims = 2 is_affine = False def __init__(self, *args, **kwargs): mtransforms.Transform.__init__(self, *args, **kwargs) self.raise_on_transform = False self.underlying_transform = mtransforms.Affine2D().scale(10, 10) def transform_path_non_affine(self, path): assert not self.raise_on_transform, \ 'Invalidated affine part of transform unnecessarily.' return self.underlying_transform.transform_path(path) transform_path = transform_path_non_affine def transform_non_affine(self, path): assert not self.raise_on_transform, \ 'Invalidated affine part of transform unnecessarily.' return self.underlying_transform.transform(path) transform = transform_non_affine my_trans = AssertingNonAffineTransform() ax = plt.axes() plt.plot(np.arange(10), transform=my_trans + ax.transData) plt.draw() # enable the transform to raise an exception if it's non-affine transform # method is triggered again. my_trans.raise_on_transform = True ax.transAxes.invalidate() plt.draw() def test_external_transform_api(): class ScaledBy(object): def __init__(self, scale_factor): self._scale_factor = scale_factor def _as_mpl_transform(self, axes): return (mtransforms.Affine2D().scale(self._scale_factor) + axes.transData) ax = plt.axes() line, = plt.plot(np.arange(10), transform=ScaledBy(10)) ax.set_xlim(0, 100) ax.set_ylim(0, 100) # assert that the top transform of the line is the scale transform. assert_allclose(line.get_transform()._a.get_matrix(), mtransforms.Affine2D().scale(10).get_matrix()) @image_comparison(baseline_images=['pre_transform_data'], tol=0.08) def test_pre_transform_plotting(): # a catch-all for as many as possible plot layouts which handle # pre-transforming the data NOTE: The axis range is important in this # plot. It should be x10 what the data suggests it should be ax = plt.axes() times10 = mtransforms.Affine2D().scale(10) ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData) ax.pcolormesh(np.linspace(0, 4, 7), np.linspace(5.5, 8, 9), np.arange(48).reshape(8, 6), transform=times10 + ax.transData) ax.scatter(np.linspace(0, 10), np.linspace(10, 0), transform=times10 + ax.transData) x = np.linspace(8, 10, 20) y = np.linspace(1, 5, 20) u = 2*np.sin(x) + np.cos(y[:, np.newaxis]) v = np.sin(x) - np.cos(y[:, np.newaxis]) df = 25. / 30. # Compatibility factor for old test image ax.streamplot(x, y, u, v, transform=times10 + ax.transData, density=(df, df), linewidth=u**2 + v**2) # reduce the vector data down a bit for barb and quiver plotting x, y = x[::3], y[::3] u, v = u[::3, ::3], v[::3, ::3] ax.quiver(x, y + 5, u, v, transform=times10 + ax.transData) ax.barbs(x - 3, y + 5, u**2, v**2, transform=times10 + ax.transData) def test_contour_pre_transform_limits(): ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.contourf(xs, ys, np.log(xs * ys), transform=mtransforms.Affine2D().scale(0.1) + ax.transData) expected = np.array([[1.5, 1.24], [2., 1.25]]) assert_almost_equal(expected, ax.dataLim.get_points()) def test_pcolor_pre_transform_limits(): # Based on test_contour_pre_transform_limits() ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.pcolor(xs, ys, np.log(xs * ys), transform=mtransforms.Affine2D().scale(0.1) + ax.transData) expected = np.array([[1.5, 1.24], [2., 1.25]]) assert_almost_equal(expected, ax.dataLim.get_points()) def test_pcolormesh_pre_transform_limits(): # Based on test_contour_pre_transform_limits() ax = plt.axes() xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) ax.pcolormesh(xs, ys, np.log(xs * ys), transform=mtransforms.Affine2D().scale(0.1) + ax.transData) expected = np.array([[1.5, 1.24], [2., 1.25]]) assert_almost_equal(expected, ax.dataLim.get_points()) def test_Affine2D_from_values(): points = np.array([[0, 0], [10, 20], [-1, 0], ]) t = mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [10, 0], [-1, 0]]) assert_almost_equal(actual, expected) t = mtransforms.Affine2D.from_values(0, 2, 0, 0, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [0, 20], [0, -2]]) assert_almost_equal(actual, expected) t = mtransforms.Affine2D.from_values(0, 0, 3, 0, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [60, 0], [0, 0]]) assert_almost_equal(actual, expected) t = mtransforms.Affine2D.from_values(0, 0, 0, 4, 0, 0) actual = t.transform(points) expected = np.array([[0, 0], [0, 80], [0, 0]]) assert_almost_equal(actual, expected) t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 5, 0) actual = t.transform(points) expected = np.array([[5, 0], [5, 0], [5, 0]]) assert_almost_equal(actual, expected) t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 0, 6) actual = t.transform(points) expected = np.array([[0, 6], [0, 6], [0, 6]]) assert_almost_equal(actual, expected) def test_clipping_of_log(): # issue 804 M, L, C = Path.MOVETO, Path.LINETO, Path.CLOSEPOLY points = [(0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20), (0.2, -99)] codes = [M, L, L, L, C] path = Path(points, codes) # something like this happens in plotting logarithmic histograms trans = mtransforms.BlendedGenericTransform(mtransforms.Affine2D(), LogScale.Log10Transform('clip')) tpath = trans.transform_path_non_affine(path) result = tpath.iter_segments(trans.get_affine(), clip=(0, 0, 100, 100), simplify=False) tpoints, tcodes = zip(*result) assert_allclose(tcodes, [M, L, L, L, C]) class NonAffineForTest(mtransforms.Transform): """ A class which looks like a non affine transform, but does whatever the given transform does (even if it is affine). This is very useful for testing NonAffine behaviour with a simple Affine transform. """ is_affine = False output_dims = 2 input_dims = 2 def __init__(self, real_trans, *args, **kwargs): self.real_trans = real_trans mtransforms.Transform.__init__(self, *args, **kwargs) def transform_non_affine(self, values): return self.real_trans.transform(values) def transform_path_non_affine(self, path): return self.real_trans.transform_path(path) class BasicTransformTests(unittest.TestCase): def setUp(self): self.ta1 = mtransforms.Affine2D(shorthand_name='ta1').rotate(np.pi / 2) self.ta2 = mtransforms.Affine2D(shorthand_name='ta2').translate(10, 0) self.ta3 = mtransforms.Affine2D(shorthand_name='ta3').scale(1, 2) self.tn1 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), shorthand_name='tn1') self.tn2 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), shorthand_name='tn2') self.tn3 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), shorthand_name='tn3') # creates a transform stack which looks like ((A, (N, A)), A) self.stack1 = (self.ta1 + (self.tn1 + self.ta2)) + self.ta3 # creates a transform stack which looks like (((A, N), A), A) self.stack2 = self.ta1 + self.tn1 + self.ta2 + self.ta3 # creates a transform stack which is a subset of stack2 self.stack2_subset = self.tn1 + self.ta2 + self.ta3 # when in debug, the transform stacks can produce dot images: # self.stack1.write_graphviz(file('stack1.dot', 'w')) # self.stack2.write_graphviz(file('stack2.dot', 'w')) # self.stack2_subset.write_graphviz(file('stack2_subset.dot', 'w')) def test_transform_depth(self): assert self.stack1.depth == 4 assert self.stack2.depth == 4 assert self.stack2_subset.depth == 3 def test_left_to_right_iteration(self): stack3 = (self.ta1 + (self.tn1 + (self.ta2 + self.tn2))) + self.ta3 # stack3.write_graphviz(file('stack3.dot', 'w')) target_transforms = [stack3, (self.tn1 + (self.ta2 + self.tn2)) + self.ta3, (self.ta2 + self.tn2) + self.ta3, self.tn2 + self.ta3, self.ta3, ] r = [rh for _, rh in stack3._iter_break_from_left_to_right()] assert len(r) == len(target_transforms) for target_stack, stack in zip(target_transforms, r): assert target_stack == stack def test_transform_shortcuts(self): assert self.stack1 - self.stack2_subset == self.ta1 assert self.stack2 - self.stack2_subset == self.ta1 assert self.stack2_subset - self.stack2 == self.ta1.inverted() assert (self.stack2_subset - self.stack2).depth == 1 with pytest.raises(ValueError): self.stack1 - self.stack2 aff1 = self.ta1 + (self.ta2 + self.ta3) aff2 = self.ta2 + self.ta3 assert aff1 - aff2 == self.ta1 assert aff1 - self.ta2 == aff1 + self.ta2.inverted() assert self.stack1 - self.ta3 == self.ta1 + (self.tn1 + self.ta2) assert self.stack2 - self.ta3 == self.ta1 + self.tn1 + self.ta2 assert ((self.ta2 + self.ta3) - self.ta3 + self.ta3 == self.ta2 + self.ta3) def test_contains_branch(self): r1 = (self.ta2 + self.ta1) r2 = (self.ta2 + self.ta1) assert r1 == r2 assert r1 != self.ta1 assert r1.contains_branch(r2) assert r1.contains_branch(self.ta1) assert not r1.contains_branch(self.ta2) assert not r1.contains_branch((self.ta2 + self.ta2)) assert r1 == r2 assert self.stack1.contains_branch(self.ta3) assert self.stack2.contains_branch(self.ta3) assert self.stack1.contains_branch(self.stack2_subset) assert self.stack2.contains_branch(self.stack2_subset) assert not self.stack2_subset.contains_branch(self.stack1) assert not self.stack2_subset.contains_branch(self.stack2) assert self.stack1.contains_branch((self.ta2 + self.ta3)) assert self.stack2.contains_branch((self.ta2 + self.ta3)) assert not self.stack1.contains_branch((self.tn1 + self.ta2)) def test_affine_simplification(self): # tests that a transform stack only calls as much is absolutely # necessary "non-affine" allowing the best possible optimization with # complex transformation stacks. points = np.array([[0, 0], [10, 20], [np.nan, 1], [-1, 0]], dtype=np.float64) na_pts = self.stack1.transform_non_affine(points) all_pts = self.stack1.transform(points) na_expected = np.array([[1., 2.], [-19., 12.], [np.nan, np.nan], [1., 1.]], dtype=np.float64) all_expected = np.array([[11., 4.], [-9., 24.], [np.nan, np.nan], [11., 2.]], dtype=np.float64) # check we have the expected results from doing the affine part only assert_array_almost_equal(na_pts, na_expected) # check we have the expected results from a full transformation assert_array_almost_equal(all_pts, all_expected) # check we have the expected results from doing the transformation in # two steps assert_array_almost_equal(self.stack1.transform_affine(na_pts), all_expected) # check that getting the affine transformation first, then fully # transforming using that yields the same result as before. assert_array_almost_equal(self.stack1.get_affine().transform(na_pts), all_expected) # check that the affine part of stack1 & stack2 are equivalent # (i.e. the optimization is working) expected_result = (self.ta2 + self.ta3).get_matrix() result = self.stack1.get_affine().get_matrix() assert_array_equal(expected_result, result) result = self.stack2.get_affine().get_matrix() assert_array_equal(expected_result, result) class TestTransformPlotInterface(unittest.TestCase): def tearDown(self): plt.close() def test_line_extent_axes_coords(self): # a simple line in axes coordinates ax = plt.axes() ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transAxes) assert_array_equal(ax.dataLim.get_points(), np.array([[np.inf, np.inf], [-np.inf, -np.inf]])) def test_line_extent_data_coords(self): # a simple line in data coordinates ax = plt.axes() ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transData) assert_array_equal(ax.dataLim.get_points(), np.array([[0.1, 0.5], [1.2, 0.9]])) def test_line_extent_compound_coords1(self): # a simple line in data coordinates in the y component, and in axes # coordinates in the x ax = plt.axes() trans = mtransforms.blended_transform_factory(ax.transAxes, ax.transData) ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[np.inf, -5.], [-np.inf, 35.]])) plt.close() def test_line_extent_predata_transform_coords(self): # a simple line in (offset + data) coordinates ax = plt.axes() trans = mtransforms.Affine2D().scale(10) + ax.transData ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[1., -50.], [12., 350.]])) plt.close() def test_line_extent_compound_coords2(self): # a simple line in (offset + data) coordinates in the y component, and # in axes coordinates in the x ax = plt.axes() trans = mtransforms.blended_transform_factory(ax.transAxes, mtransforms.Affine2D().scale(10) + ax.transData) ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) assert_array_equal(ax.dataLim.get_points(), np.array([[np.inf, -50.], [-np.inf, 350.]])) plt.close() def test_line_extents_affine(self): ax = plt.axes() offset = mtransforms.Affine2D().translate(10, 10) plt.plot(np.arange(10), transform=offset + ax.transData) expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 10 assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) def test_line_extents_non_affine(self): ax = plt.axes() offset = mtransforms.Affine2D().translate(10, 10) na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10)) plt.plot(np.arange(10), transform=offset + na_offset + ax.transData) expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 20 assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) def test_pathc_extents_non_affine(self): ax = plt.axes() offset = mtransforms.Affine2D().translate(10, 10) na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10)) pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]])) patch = mpatches.PathPatch(pth, transform=offset + na_offset + ax.transData) ax.add_patch(patch) expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 20 assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) def test_pathc_extents_affine(self): ax = plt.axes() offset = mtransforms.Affine2D().translate(10, 10) pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]])) patch = mpatches.PathPatch(pth, transform=offset + ax.transData) ax.add_patch(patch) expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 10 assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) def test_line_extents_for_non_affine_transData(self): ax = plt.axes(projection='polar') # add 10 to the radius of the data offset = mtransforms.Affine2D().translate(0, 10) plt.plot(np.arange(10), transform=offset + ax.transData) # the data lim of a polar plot is stored in coordinates # before a transData transformation, hence the data limits # are not what is being shown on the actual plot. expected_data_lim = np.array([[0., 0.], [9., 9.]]) + [0, 10] assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) def assert_bbox_eq(bbox1, bbox2): assert_array_equal(bbox1.bounds, bbox2.bounds) def test_bbox_intersection(): bbox_from_ext = mtransforms.Bbox.from_extents inter = mtransforms.Bbox.intersection r1 = bbox_from_ext(0, 0, 1, 1) r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5) r3 = bbox_from_ext(0.5, 0, 0.75, 0.75) r4 = bbox_from_ext(0.5, 1.5, 1, 2.5) r5 = bbox_from_ext(1, 1, 2, 2) # self intersection -> no change assert_bbox_eq(inter(r1, r1), r1) # simple intersection assert_bbox_eq(inter(r1, r2), bbox_from_ext(0.5, 0.5, 1, 1)) # r3 contains r2 assert_bbox_eq(inter(r1, r3), r3) # no intersection assert inter(r1, r4) is None # single point assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1)) def test_bbox_as_strings(): b = mtransforms.Bbox([[.5, 0], [.75, .75]]) assert_bbox_eq(b, eval(repr(b), {'Bbox': mtransforms.Bbox})) asdict = eval(str(b), {'Bbox': dict}) for k, v in asdict.items(): assert getattr(b, k) == v fmt = '.1f' asdict = eval(format(b, fmt), {'Bbox': dict}) for k, v in asdict.items(): assert eval(format(getattr(b, k), fmt)) == v def test_transform_single_point(): t = mtransforms.Affine2D() r = t.transform_affine((1, 1)) assert r.shape == (2,) def test_log_transform(): # Tests that the last line runs without exception (previously the # transform would fail if one of the axes was logarithmic). fig, ax = plt.subplots() ax.set_yscale('log') ax.transData.transform((1, 1)) def test_nan_overlap(): a = mtransforms.Bbox([[0, 0], [1, 1]]) b = mtransforms.Bbox([[0, 0], [1, np.nan]]) assert not a.overlaps(b) def test_transform_angles(): t = mtransforms.Affine2D() # Identity transform angles = np.array([20, 45, 60]) points = np.array([[0, 0], [1, 1], [2, 2]]) # Identity transform does not change angles new_angles = t.transform_angles(angles, points) assert_array_almost_equal(angles, new_angles) # points missing a 2nd dimension with pytest.raises(ValueError): t.transform_angles(angles, points[0:2, 0:1]) # Number of angles != Number of points with pytest.raises(ValueError): t.transform_angles(angles, points[0:2, :]) def test_nonsingular(): # test for zero-expansion type cases; other cases may be added later zero_expansion = np.array([-0.001, 0.001]) cases = [(0, np.nan), (0, 0), (0, 7.9e-317)] for args in cases: out = np.array(mtransforms.nonsingular(*args)) assert_array_equal(out, zero_expansion) def test_invalid_arguments(): t = mtransforms.Affine2D() # There are two different exceptions, since the wrong number of # dimensions is caught when constructing an array_view, and that # raises a ValueError, and a wrong shape with a possible number # of dimensions is caught by our CALL_CPP macro, which always # raises the less precise RuntimeError. with pytest.raises(ValueError): t.transform(1) with pytest.raises(ValueError): t.transform([[[1]]]) with pytest.raises(RuntimeError): t.transform([]) with pytest.raises(RuntimeError): t.transform([1]) with pytest.raises(RuntimeError): t.transform([[1]]) with pytest.raises(RuntimeError): t.transform([[1, 2, 3]]) def test_transformed_path(): points = [(0, 0), (1, 0), (1, 1), (0, 1)] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] path = Path(points, codes) trans = mtransforms.Affine2D() trans_path = mtransforms.TransformedPath(path, trans) assert_allclose(trans_path.get_fully_transformed_path().vertices, points) # Changing the transform should change the result. r2 = 1 / np.sqrt(2) trans.rotate(np.pi / 4) assert_allclose(trans_path.get_fully_transformed_path().vertices, [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)], atol=1e-15) # Changing the path does not change the result (it's cached). path.points = [(0, 0)] * 4 assert_allclose(trans_path.get_fully_transformed_path().vertices, [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)], atol=1e-15) def test_transformed_patch_path(): trans = mtransforms.Affine2D() patch = mpatches.Wedge((0, 0), 1, 45, 135, transform=trans) tpatch = mtransforms.TransformedPatchPath(patch) points = tpatch.get_fully_transformed_path().vertices # Changing the transform should change the result. trans.scale(2) assert_allclose(tpatch.get_fully_transformed_path().vertices, points * 2) # Changing the path should change the result (and cancel out the scaling # from the transform). patch.set_radius(0.5) assert_allclose(tpatch.get_fully_transformed_path().vertices, points) @pytest.mark.parametrize('locked_element', ['x0', 'y0', 'x1', 'y1']) def test_lockable_bbox(locked_element): other_elements = ['x0', 'y0', 'x1', 'y1'] other_elements.remove(locked_element) orig = mtransforms.Bbox.unit() locked = mtransforms.LockableBbox(orig, **{locked_element: 2}) # LockableBbox should keep its locked element as specified in __init__. assert getattr(locked, locked_element) == 2 assert getattr(locked, 'locked_' + locked_element) == 2 for elem in other_elements: assert getattr(locked, elem) == getattr(orig, elem) # Changing underlying Bbox should update everything but locked element. orig.set_points(orig.get_points() + 10) assert getattr(locked, locked_element) == 2 assert getattr(locked, 'locked_' + locked_element) == 2 for elem in other_elements: assert getattr(locked, elem) == getattr(orig, elem) # Unlocking element should revert values back to the underlying Bbox. setattr(locked, 'locked_' + locked_element, None) assert getattr(locked, 'locked_' + locked_element) is None assert np.all(orig.get_points() == locked.get_points()) # Relocking an element should change its value, but not others. setattr(locked, 'locked_' + locked_element, 3) assert getattr(locked, locked_element) == 3 assert getattr(locked, 'locked_' + locked_element) == 3 for elem in other_elements: assert getattr(locked, elem) == getattr(orig, elem)
24,773
37.95283
79
py