desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add the lines from a non-filled :class:`~matplotlib.contour.ContourSet` to the colorbar.'
def add_lines(self, CS):
if ((not isinstance(CS, contour.ContourSet)) or CS.filled): raise ValueError('add_lines is only for a ContourSet of lines') tcolors = [c[0] for c in CS.tcolors] tlinewidths = [t[0] for t in CS.tlinewidths] ColorbarBase.add_lines(self, CS.levels, tcolors, tlinewidths)
'Manually change any contour line colors. This is called when the image or contour plot to which this colorbar belongs is changed.'
def update_bruteforce(self, mappable):
self.ax.cla() self.draw_all() if isinstance(self.mappable, contour.ContourSet): CS = self.mappable if (not CS.filled): self.add_lines(CS)
'set the verbosity to one of the Verbose.levels strings'
def set_level(self, level):
if (self._commandLineVerbose is not None): level = self._commandLineVerbose if (level not in self.levels): raise ValueError(('Illegal verbose string "%s". Legal values are %s' % (level, self.levels))) self.level = level
'print message s to self.fileo if self.level>=level. Return value indicates whether a message was issued'
def report(self, s, level='helpful'):
if self.ge(level): print >>self.fileo, s return True return False
'return a callable function that wraps func and reports it output through the verbose handler if current verbosity level is higher than level if always is True, the report will occur on every function call; otherwise only on the first time the function is called'
def wrap(self, fmt, func, level='helpful', always=True):
assert callable(func) def wrapper(*args, **kwargs): ret = func(*args, **kwargs) if (always or (not wrapper._spoke)): spoke = self.report((fmt % ret), level) if (not wrapper._spoke): wrapper._spoke = spoke return ret wrapper._spoke = False wrapper.__doc__ = func.__doc__ return wrapper
'return true if self.level is >= level'
def ge(self, level):
return (self.vald[self.level] >= self.vald[level])
'*control_points* : location of contol points. It needs have a shpae of n * 2, where n is the order of the bezier line. 1<= n <= 3 is supported.'
def __init__(self, control_points):
_o = len(control_points) self._orders = np.arange(_o) _coeff = BezierSegment._binom_coeff[(_o - 1)] _control_points = np.asarray(control_points) xx = _control_points[:, 0] yy = _control_points[:, 1] self._px = (xx * _coeff) self._py = (yy * _coeff)
'evaluate a point at t'
def point_at_t(self, t):
one_minus_t_powers = np.power((1.0 - t), self._orders)[::(-1)] t_powers = np.power(t, self._orders) tt = (one_minus_t_powers * t_powers) _x = sum((tt * self._px)) _y = sum((tt * self._py)) return (_x, _y)
'Event handler that will be passed to the current figure to retrieve events.'
def on_event(self, event):
self.add_event(event) verbose.report(('Event %i' % len(self.events))) self.post_event() if ((len(self.events) >= self.n) and (self.n > 0)): self.fig.canvas.stop_event_loop()
'For baseclass, do nothing but collect events'
def post_event(self):
pass
'Disconnect all callbacks'
def cleanup(self):
for cb in self.callbacks: self.fig.canvas.mpl_disconnect(cb) self.callbacks = []
'For base class, this just appends an event to events.'
def add_event(self, event):
self.events.append(event)
'This removes an event from the event list. Defaults to removing last event, but an index can be supplied. Note that this does not check that there are events, much like the normal pop method. If not events exist, this will throw an exception.'
def pop_event(self, index=(-1)):
self.events.pop(index)
'Blocking call to retrieve n events'
def __call__(self, n=1, timeout=30):
assert isinstance(n, int), 'Requires an integer argument' self.n = n self.events = [] self.callbacks = [] self.fig.show() for n in self.eventslist: self.callbacks.append(self.fig.canvas.mpl_connect(n, self.on_event)) try: self.fig.canvas.start_event_loop(timeout=timeout) finally: self.cleanup() return self.events
'This will be called to process events'
def post_event(self):
assert (len(self.events) > 0), 'No events yet' if (self.events[(-1)].name == 'key_press_event'): self.key_event() else: self.mouse_event()
'Process a mouse click event'
def mouse_event(self):
event = self.events[(-1)] button = event.button if (button == 3): self.button3(event) elif (button == 2): self.button2(event) else: self.button1(event)
'Process a key click event. This maps certain keys to appropriate mouse click events.'
def key_event(self):
event = self.events[(-1)] key = event.key if ((key == 'backspace') or (key == 'delete')): self.button3(event) elif (key == 'enter'): self.button2(event) else: self.button1(event)
'Will be called for any event involving a button other than button 2 or 3. This will add a click if it is inside axes.'
def button1(self, event):
if event.inaxes: self.add_click(event) else: BlockingInput.pop(self)
'Will be called for any event involving button 2. Button 2 ends blocking input.'
def button2(self, event):
BlockingInput.pop(self) self.fig.canvas.stop_event_loop()
'Will be called for any event involving button 3. Button 3 removes the last click.'
def button3(self, event):
BlockingInput.pop(self) if (len(self.events) > 0): self.pop()
'This add the coordinates of an event to the list of clicks'
def add_click(self, event):
self.clicks.append((event.xdata, event.ydata)) verbose.report(('input %i: %f,%f' % (len(self.clicks), event.xdata, event.ydata))) if self.show_clicks: self.marks.extend(event.inaxes.plot([event.xdata], [event.ydata], 'r+')) self.fig.canvas.draw()
'This removes a click from the list of clicks. Defaults to removing the last click.'
def pop_click(self, index=(-1)):
self.clicks.pop(index) if self.show_clicks: mark = self.marks.pop(index) mark.remove() self.fig.canvas.draw()
'This removes a click and the associated event from the object. Defaults to removing the last click, but any index can be supplied.'
def pop(self, index=(-1)):
self.pop_click(index) BlockingInput.pop(self, index)
'Blocking call to retrieve n coordinate pairs through mouse clicks.'
def __call__(self, n=1, timeout=30, show_clicks=True):
self.show_clicks = show_clicks self.clicks = [] self.marks = [] BlockingInput.__call__(self, n=n, timeout=timeout) return self.clicks
'This will be called if an event involving a button other than 2 or 3 occcurs. This will add a label to a contour.'
def button1(self, event):
cs = self.cs if (event.inaxes == cs.ax): (conmin, segmin, imin, xmin, ymin) = cs.find_nearest_contour(event.x, event.y, cs.labelIndiceList)[:5] lmin = cs.labelIndiceList.index(conmin) paths = cs.collections[conmin].get_paths() lc = paths[segmin].vertices slc = cs.ax.transData.transform(lc) lw = cs.get_label_width(cs.labelLevelList[lmin], cs.labelFmt, cs.labelFontSizeList[lmin]) '\n # requires python 2.5\n # Figure out label rotation.\n rotation,nlc = cs.calc_label_rot_and_inline(\n slc, imin, lw, lc if self.inline else [],\n self.inline_spacing )\n ' if self.inline: lcarg = lc else: lcarg = None (rotation, nlc) = cs.calc_label_rot_and_inline(slc, imin, lw, lcarg, self.inline_spacing) cs.add_label(xmin, ymin, rotation, cs.labelLevelList[lmin], cs.labelCValueList[lmin]) if self.inline: paths.pop(segmin) for n in nlc: if (len(n) > 1): paths.append(path.Path(n)) self.fig.canvas.draw() else: BlockingInput.pop(self)
'This will be called if button 3 is clicked. This will remove a label if not in inline mode. Unfortunately, if one is doing inline labels, then there is currently no way to fix the broken contour - once humpty-dumpty is broken, he can\'t be put back together. In inline mode, this does nothing.'
def button3(self, event):
BlockingInput.pop(self) if self.inline: pass else: self.cs.pop_label() self.cs.ax.figure.canvas.draw()
'Determines if it is a key event'
def post_event(self):
assert (len(self.events) > 0), 'No events yet' self.keyormouse = (self.events[(-1)].name == 'key_press_event')
'Blocking call to retrieve a single mouse or key click Returns True if key click, False if mouse, or None if timeout'
def __call__(self, timeout=30):
self.keyormouse = None BlockingInput.__call__(self, n=1, timeout=timeout) return self.keyormouse
'Create a new path with the given vertices and codes. *vertices* is an Nx2 numpy float array, masked array or Python sequence. *codes* is an N-length numpy array or Python sequence of type :attr:`matplotlib.path.Path.code_type`. These two arrays must have the same length in the first dimension. If *codes* is None, *vertices* will be treated as a series of line segments. If *vertices* contains masked values, they will be converted to NaNs which are then handled correctly by the Agg PathIterator and other consumers of path data, such as :meth:`iter_segments`.'
def __init__(self, vertices, codes=None):
if ma.isMaskedArray(vertices): vertices = vertices.astype(np.float_).filled(np.nan) else: vertices = np.asarray(vertices, np.float_) if (codes is not None): codes = np.asarray(codes, self.code_type) assert (codes.ndim == 1) assert (len(codes) == len(vertices)) assert (vertices.ndim == 2) assert (vertices.shape[1] == 2) self.should_simplify = ((len(vertices) >= 128) and ((codes is None) or np.all((codes <= Path.LINETO)))) self.has_nonfinite = (not np.isfinite(vertices).all()) self.codes = codes self.vertices = vertices
'(staticmethod) Make a compound path from a list of Path objects. Only polygons (not curves) are supported.'
def make_compound_path(*args):
for p in args: assert (p.codes is None) lengths = [len(x) for x in args] total_length = sum(lengths) vertices = np.vstack([x.vertices for x in args]) vertices.reshape((total_length, 2)) codes = (Path.LINETO * np.ones(total_length)) i = 0 for length in lengths: codes[i] = Path.MOVETO i += length return Path(vertices, codes)
'Iterates over all of the curve segments in the path. Each iteration returns a 2-tuple (*vertices*, *code*), where *vertices* is a sequence of 1 - 3 coordinate pairs, and *code* is one of the :class:`Path` codes. If *simplify* is provided, it must be a tuple (*width*, *height*) defining the size of the figure, in native units (e.g. pixels or points). Simplification implies both removing adjacent line segments that are very close to parallel, and removing line segments outside of the figure. The path will be simplified *only* if :attr:`should_simplify` is True, which is determined in the constructor by this criteria: - No curves - More than 128 vertices'
def iter_segments(self, simplify=None):
vertices = self.vertices if (not len(vertices)): return codes = self.codes len_vertices = len(vertices) isfinite = np.isfinite NUM_VERTICES = self.NUM_VERTICES MOVETO = self.MOVETO LINETO = self.LINETO CLOSEPOLY = self.CLOSEPOLY STOP = self.STOP if ((simplify is not None) and self.should_simplify): polygons = self.to_polygons(None, *simplify) for vertices in polygons: (yield (vertices[0], MOVETO)) for v in vertices[1:]: (yield (v, LINETO)) elif (codes is None): if self.has_nonfinite: next_code = MOVETO for v in vertices: if np.isfinite(v).all(): (yield (v, next_code)) next_code = LINETO else: next_code = MOVETO else: (yield (vertices[0], MOVETO)) for v in vertices[1:]: (yield (v, LINETO)) else: i = 0 was_nan = False while (i < len_vertices): code = codes[i] if (code == CLOSEPOLY): (yield ([], code)) i += 1 elif (code == STOP): return else: num_vertices = NUM_VERTICES[int(code)] curr_vertices = vertices[i:(i + num_vertices)].flatten() if (not isfinite(curr_vertices).all()): was_nan = True elif was_nan: (yield (curr_vertices[(-2):], MOVETO)) was_nan = False else: (yield (curr_vertices, code)) i += num_vertices
'Return a transformed copy of the path. .. seealso:: :class:`matplotlib.transforms.TransformedPath`: A specialized path class that will cache the transformed result and automatically update when the transform changes.'
def transformed(self, transform):
return Path(transform.transform(self.vertices), self.codes)
'Returns *True* if the path contains the given point. If *transform* is not *None*, the path will be transformed before performing the test.'
def contains_point(self, point, transform=None):
if (transform is not None): transform = transform.frozen() return point_in_path(point[0], point[1], self, transform)
'Returns *True* if this path completely contains the given path. If *transform* is not *None*, the path will be transformed before performing the test.'
def contains_path(self, path, transform=None):
if (transform is not None): transform = transform.frozen() return path_in_path(self, None, path, transform)
'Returns the extents (*xmin*, *ymin*, *xmax*, *ymax*) of the path. Unlike computing the extents on the *vertices* alone, this algorithm will take into account the curves and deal with control points appropriately.'
def get_extents(self, transform=None):
from transforms import Bbox if (transform is not None): transform = transform.frozen() return Bbox(get_path_extents(self, transform))
'Returns *True* if this path intersects another given path. *filled*, when True, treats the paths as if they were filled. That is, if one path completely encloses the other, :meth:`intersects_path` will return True.'
def intersects_path(self, other, filled=True):
return path_intersects_path(self, other, filled)
'Returns *True* if this path intersects a given :class:`~matplotlib.transforms.Bbox`. *filled*, when True, treats the path as if it was filled. That is, if one path completely encloses the other, :meth:`intersects_path` will return True.'
def intersects_bbox(self, bbox, filled=True):
from transforms import BboxTransformTo rectangle = self.unit_rectangle().transformed(BboxTransformTo(bbox)) result = self.intersects_path(rectangle, filled) return result
'Returns a new path resampled to length N x steps. Does not currently handle interpolating curves.'
def interpolated(self, steps):
vertices = simple_linear_interpolation(self.vertices, steps) codes = self.codes if (codes is not None): new_codes = (Path.LINETO * np.ones(((((len(codes) - 1) * steps) + 1),))) new_codes[0::steps] = codes else: new_codes = None return Path(vertices, new_codes)
'Convert this path to a list of polygons. Each polygon is an Nx2 array of vertices. In other words, each polygon has no ``MOVETO`` instructions or curves. This is useful for displaying in backends that do not support compound paths or Bezier curves, such as GDK. If *width* and *height* are both non-zero then the lines will be simplified so that vertices outside of (0, 0), (width, height) will be clipped.'
def to_polygons(self, transform=None, width=0, height=0):
if (len(self.vertices) == 0): return [] if (transform is not None): transform = transform.frozen() if ((self.codes is None) and ((width == 0) or (height == 0))): if (transform is None): return [self.vertices] else: return [transform.transform(self.vertices)] return convert_path_to_polygons(self, transform, width, height)
'(staticmethod) Returns a :class:`Path` of the unit rectangle from (0, 0) to (1, 1).'
def unit_rectangle(cls):
if (cls._unit_rectangle is None): cls._unit_rectangle = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]]) return cls._unit_rectangle
'(staticmethod) Returns a :class:`Path` for a unit regular polygon with the given *numVertices* and radius of 1.0, centered at (0, 0).'
def unit_regular_polygon(cls, numVertices):
if (numVertices <= 16): path = cls._unit_regular_polygons.get(numVertices) else: path = None if (path is None): theta = (((2 * np.pi) / numVertices) * np.arange((numVertices + 1)).reshape(((numVertices + 1), 1))) theta += (np.pi / 2.0) verts = np.concatenate((np.cos(theta), np.sin(theta)), 1) path = Path(verts) cls._unit_regular_polygons[numVertices] = path return path
'(staticmethod) Returns a :class:`Path` for a unit regular star with the given numVertices and radius of 1.0, centered at (0, 0).'
def unit_regular_star(cls, numVertices, innerCircle=0.5):
if (numVertices <= 16): path = cls._unit_regular_stars.get((numVertices, innerCircle)) else: path = None if (path is None): ns2 = (numVertices * 2) theta = (((2 * np.pi) / ns2) * np.arange((ns2 + 1))) theta += (np.pi / 2.0) r = np.ones((ns2 + 1)) r[1::2] = innerCircle verts = np.vstack(((r * np.cos(theta)), (r * np.sin(theta)))).transpose() path = Path(verts) cls._unit_regular_polygons[(numVertices, innerCircle)] = path return path
'(staticmethod) Returns a :class:`Path` for a unit regular asterisk with the given numVertices and radius of 1.0, centered at (0, 0).'
def unit_regular_asterisk(cls, numVertices):
return cls.unit_regular_star(numVertices, 0.0)
'(staticmethod) Returns a :class:`Path` of the unit circle. The circle is approximated using cubic Bezier curves. This uses 8 splines around the circle using the approach presented here: Lancaster, Don. `Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines <http://www.tinaja.com/glib/ellipse4.pdf>`_.'
def unit_circle(cls):
if (cls._unit_circle is None): MAGIC = 0.2652031 SQRTHALF = np.sqrt(0.5) MAGIC45 = np.sqrt(((MAGIC * MAGIC) / 2.0)) vertices = np.array([[0.0, (-1.0)], [MAGIC, (-1.0)], [(SQRTHALF - MAGIC45), ((- SQRTHALF) - MAGIC45)], [SQRTHALF, (- SQRTHALF)], [(SQRTHALF + MAGIC45), ((- SQRTHALF) + MAGIC45)], [1.0, (- MAGIC)], [1.0, 0.0], [1.0, MAGIC], [(SQRTHALF + MAGIC45), (SQRTHALF - MAGIC45)], [SQRTHALF, SQRTHALF], [(SQRTHALF - MAGIC45), (SQRTHALF + MAGIC45)], [MAGIC, 1.0], [0.0, 1.0], [(- MAGIC), 1.0], [((- SQRTHALF) + MAGIC45), (SQRTHALF + MAGIC45)], [(- SQRTHALF), SQRTHALF], [((- SQRTHALF) - MAGIC45), (SQRTHALF - MAGIC45)], [(-1.0), MAGIC], [(-1.0), 0.0], [(-1.0), (- MAGIC)], [((- SQRTHALF) - MAGIC45), ((- SQRTHALF) + MAGIC45)], [(- SQRTHALF), (- SQRTHALF)], [((- SQRTHALF) + MAGIC45), ((- SQRTHALF) - MAGIC45)], [(- MAGIC), (-1.0)], [0.0, (-1.0)], [0.0, (-1.0)]], np.float_) codes = (cls.CURVE4 * np.ones(26)) codes[0] = cls.MOVETO codes[(-1)] = cls.CLOSEPOLY cls._unit_circle = Path(vertices, codes) return cls._unit_circle
'(staticmethod) Returns an arc on the unit circle from angle *theta1* to angle *theta2* (in degrees). If *n* is provided, it is the number of spline segments to make. If *n* is not provided, the number of spline segments is determined based on the delta between *theta1* and *theta2*. Masionobe, L. 2003. `Drawing an elliptical arc using polylines, quadratic or cubic Bezier curves <http://www.spaceroots.org/documents/ellipse/index.html>`_.'
def arc(cls, theta1, theta2, n=None, is_wedge=False):
theta1 *= (np.pi / 180.0) theta2 *= (np.pi / 180.0) twopi = (np.pi * 2.0) halfpi = (np.pi * 0.5) eta1 = np.arctan2(np.sin(theta1), np.cos(theta1)) eta2 = np.arctan2(np.sin(theta2), np.cos(theta2)) eta2 -= (twopi * np.floor(((eta2 - eta1) / twopi))) if (((theta2 - theta1) > np.pi) and ((eta2 - eta1) < np.pi)): eta2 += twopi if (n is None): n = int((2 ** np.ceil(((eta2 - eta1) / halfpi)))) if (n < 1): raise ValueError('n must be >= 1 or None') deta = ((eta2 - eta1) / n) t = np.tan((0.5 * deta)) alpha = ((np.sin(deta) * (np.sqrt((4.0 + ((3.0 * t) * t))) - 1)) / 3.0) steps = np.linspace(eta1, eta2, (n + 1), True) cos_eta = np.cos(steps) sin_eta = np.sin(steps) xA = cos_eta[:(-1)] yA = sin_eta[:(-1)] xA_dot = (- yA) yA_dot = xA xB = cos_eta[1:] yB = sin_eta[1:] xB_dot = (- yB) yB_dot = xB if is_wedge: length = ((n * 3) + 4) vertices = np.zeros((length, 2), np.float_) codes = (Path.CURVE4 * np.ones((length,), Path.code_type)) vertices[1] = [xA[0], yA[0]] codes[0:2] = [Path.MOVETO, Path.LINETO] codes[(-2):] = [Path.LINETO, Path.CLOSEPOLY] vertex_offset = 2 end = (length - 2) else: length = ((n * 3) + 1) vertices = np.zeros((length, 2), np.float_) codes = (Path.CURVE4 * np.ones((length,), Path.code_type)) vertices[0] = [xA[0], yA[0]] codes[0] = Path.MOVETO vertex_offset = 1 end = length vertices[vertex_offset:end:3, 0] = (xA + (alpha * xA_dot)) vertices[vertex_offset:end:3, 1] = (yA + (alpha * yA_dot)) vertices[(vertex_offset + 1):end:3, 0] = (xB - (alpha * xB_dot)) vertices[(vertex_offset + 1):end:3, 1] = (yB - (alpha * yB_dot)) vertices[(vertex_offset + 2):end:3, 0] = xB vertices[(vertex_offset + 2):end:3, 1] = yB return Path(vertices, codes)
'(staticmethod) Returns a wedge of the unit circle from angle *theta1* to angle *theta2* (in degrees). If *n* is provided, it is the number of spline segments to make. If *n* is not provided, the number of spline segments is determined based on the delta between *theta1* and *theta2*.'
def wedge(cls, theta1, theta2, n=None):
return cls.arc(theta1, theta2, n, True)
'Dimension the drawing canvas'
def set_canvas_size(self, w, h, d):
self.width = w self.height = h self.depth = d
'Draw a glyph described by *info* to the reference point (*ox*, *oy*).'
def render_glyph(self, ox, oy, info):
raise NotImplementedError()
'Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).'
def render_filled_rect(self, x1, y1, x2, y2):
raise NotImplementedError()
'Return a backend-specific tuple to return to the backend after all processing is done.'
def get_results(self, box):
raise NotImplementedError()
'Get the Freetype hinting type to use with this particular backend.'
def get_hinting_type(self):
return LOAD_NO_HINTING
'*default_font_prop*: A :class:`~matplotlib.font_manager.FontProperties` object to use for the default non-math font, or the base font for Unicode (generic) font rendering. *mathtext_backend*: A subclass of :class:`MathTextBackend` used to delegate the actual rendering.'
def __init__(self, default_font_prop, mathtext_backend):
self.default_font_prop = default_font_prop self.mathtext_backend = mathtext_backend self.mathtext_backend.fonts_object = self self.used_characters = {}
'Fix any cyclical references before the object is about to be destroyed.'
def destroy(self):
self.used_characters = None
'Get the kerning distance for font between *sym1* and *sym2*. *fontX*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default (non-math) *fontclassX*: TODO *symX*: a symbol in raw TeX form. e.g. \'1\', \'x\' or \'\sigma\' *fontsizeX*: the fontsize in points *dpi*: the current dots-per-inch'
def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi):
return 0.0
'*font*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default (non-math) *font_class*: TODO *sym*: a symbol in raw TeX form. e.g. \'1\', \'x\' or \'\sigma\' *fontsize*: font size in points *dpi*: current dots-per-inch Returns an object with the following attributes: - *advance*: The advance distance (in points) of the glyph. - *height*: The height of the glyph in points. - *width*: The width of the glyph in points. - *xmin*, *xmax*, *ymin*, *ymax* - the ink rectangle of the glyph - *iceberg* - the distance from the baseline to the top of the glyph. This corresponds to TeX\'s definition of "height".'
def get_metrics(self, font, font_class, sym, fontsize, dpi):
info = self._get_info(font, font_class, sym, fontsize, dpi) return info.metrics
'Set the size of the buffer used to render the math expression. Only really necessary for the bitmap backends.'
def set_canvas_size(self, w, h, d):
(self.width, self.height, self.depth) = (ceil(w), ceil(h), ceil(d)) self.mathtext_backend.set_canvas_size(self.width, self.height, self.depth)
'Draw a glyph at - *ox*, *oy*: position - *facename*: One of the TeX face names - *font_class*: - *sym*: TeX symbol name or single character - *fontsize*: fontsize in points - *dpi*: The dpi to draw at.'
def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi):
info = self._get_info(facename, font_class, sym, fontsize, dpi) (realpath, stat_key) = get_realpath_and_stat(info.font.fname) used_characters = self.used_characters.setdefault(stat_key, (realpath, set())) used_characters[1].add(info.num) self.mathtext_backend.render_glyph(ox, oy, info)
'Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*).'
def render_rect_filled(self, x1, y1, x2, y2):
self.mathtext_backend.render_rect_filled(x1, y1, x2, y2)
'Get the xheight for the given *font* and *fontsize*.'
def get_xheight(self, font, fontsize, dpi):
raise NotImplementedError()
'Get the line thickness that matches the given font. Used as a base unit for drawing lines such as in a fraction or radical.'
def get_underline_thickness(self, font, fontsize, dpi):
raise NotImplementedError()
'Get the set of characters that were used in the math expression. Used by backends that need to subset fonts so they know which glyphs to include.'
def get_used_characters(self):
return self.used_characters
'Get the data needed by the backend to render the math expression. The return value is backend-specific.'
def get_results(self, box):
return self.mathtext_backend.get_results(box)
'Override if your font provides multiple sizes of the same symbol. Should return a list of symbols matching *sym* in various sizes. The expression renderer will select the most appropriate size for a given situation from this list.'
def get_sized_alternatives_for_symbol(self, fontname, sym):
return [(fontname, sym)]
'load the cmfont, metrics and glyph with caching'
def _get_info(self, fontname, font_class, sym, fontsize, dpi):
key = (fontname, sym, fontsize, dpi) tup = self.glyphd.get(key) if (tup is not None): return tup if ((fontname == 'it') and ((len(sym) > 1) or (not unicodedata.category(unicode(sym)).startswith('L')))): fontname = 'rm' found_symbol = False if (sym in latex_to_standard): (fontname, num) = latex_to_standard[sym] glyph = chr(num) found_symbol = True elif (len(sym) == 1): glyph = sym num = ord(glyph) found_symbol = True else: warn(("No TeX to built-in Postscript mapping for '%s'" % sym), MathTextWarning) slanted = (fontname == 'it') font = self._get_font(fontname) if found_symbol: try: symbol_name = font.get_name_char(glyph) except KeyError: warn(("No glyph in standard Postscript font '%s' for '%s'" % (font.postscript_name, sym)), MathTextWarning) found_symbol = False if (not found_symbol): glyph = sym = '?' num = ord(glyph) symbol_name = font.get_name_char(glyph) offset = 0 scale = (0.001 * fontsize) (xmin, ymin, xmax, ymax) = [(val * scale) for val in font.get_bbox_char(glyph)] metrics = Bunch(advance=(font.get_width_char(glyph) * scale), width=(font.get_width_char(glyph) * scale), height=(font.get_height_char(glyph) * scale), xmin=xmin, xmax=xmax, ymin=(ymin + offset), ymax=(ymax + offset), iceberg=(ymax + offset), slanted=slanted) self.glyphd[key] = Bunch(font=font, fontsize=fontsize, postscript_name=font.get_fontname(), metrics=metrics, symbol_name=symbol_name, num=num, glyph=glyph, offset=offset) return self.glyphd[key]
'Shrinks one level smaller. There are only three levels of sizes, after which things will no longer get smaller.'
def shrink(self):
self.size += 1
'Grows one level larger. There is no limit to how big something can get.'
def grow(self):
self.size -= 1
'Return the amount of kerning between this and the given character. Called when characters are strung together into :class:`Hlist` to create :class:`Kern` nodes.'
def get_kerning(self, next):
advance = (self._metrics.advance - self.width) kern = 0.0 if isinstance(next, Char): kern = self.font_output.get_kern(self.font, self.font_class, self.c, self.fontsize, next.font, next.font_class, next.c, next.fontsize, self.dpi) return (advance + kern)
'Render the character to the canvas'
def render(self, x, y):
self.font_output.render_glyph(x, y, self.font, self.font_class, self.c, self.fontsize, self.dpi)
'Render the character to the canvas.'
def render(self, x, y):
self.font_output.render_glyph((x - self._metrics.xmin), (y + self._metrics.ymin), self.font, self.font_class, self.c, self.fontsize, self.dpi)
'A helper function to determine the highest order of glue used by the members of this list. Used by vpack and hpack.'
def _determine_order(self, totals):
o = 0 for i in range((len(totals) - 1), 0, (-1)): if (totals[i] != 0.0): o = i break return o
'Insert :class:`Kern` nodes between :class:`Char` nodes to set kerning. The :class:`Char` nodes themselves determine the amount of kerning they need (in :meth:`~Char.get_kerning`), and this function just creates the linked list in the correct way.'
def kern(self):
new_children = [] num_children = len(self.children) if num_children: for i in range(num_children): elem = self.children[i] if (i < (num_children - 1)): next = self.children[(i + 1)] else: next = None new_children.append(elem) kerning_distance = elem.get_kerning(next) if (kerning_distance != 0.0): kern = Kern(kerning_distance) new_children.append(kern) self.children = new_children
'The main duty of :meth:`hpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. The computed sizes normally enclose all of the material inside the new box; but some items may stick out if negative glue is used, if the box is overfull, or if a ``\vbox`` includes other boxes that have been shifted left. - *w*: specifies a width - *m*: is either \'exactly\' or \'additional\'. Thus, ``hpack(w, \'exactly\')`` produces a box whose width is exactly *w*, while ``hpack(w, \'additional\')`` yields a box whose width is the natural width plus *w*. The default values produce a box with the natural width.'
def hpack(self, w=0.0, m='additional'):
h = 0.0 d = 0.0 x = 0.0 total_stretch = ([0.0] * 4) total_shrink = ([0.0] * 4) for p in self.children: if isinstance(p, Char): x += p.width h = max(h, p.height) d = max(d, p.depth) elif isinstance(p, Box): x += p.width if ((not isinf(p.height)) and (not isinf(p.depth))): s = getattr(p, 'shift_amount', 0.0) h = max(h, (p.height - s)) d = max(d, (p.depth + s)) elif isinstance(p, Glue): glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += p.width self.height = h self.depth = d if (m == 'additional'): w += x self.width = w x = (w - x) if (x == 0.0): self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0.0 return if (x > 0.0): self._set_glue(x, 1, total_stretch, 'Overfull') else: self._set_glue(x, (-1), total_shrink, 'Underfull')
'The main duty of :meth:`vpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. - *h*: specifies a height - *m*: is either \'exactly\' or \'additional\'. - *l*: a maximum height Thus, ``vpack(h, \'exactly\')`` produces a box whose height is exactly *h*, while ``vpack(h, \'additional\')`` yields a box whose height is the natural height plus *h*. The default values produce a box with the natural width.'
def vpack(self, h=0.0, m='additional', l=float(inf)):
w = 0.0 d = 0.0 x = 0.0 total_stretch = ([0.0] * 4) total_shrink = ([0.0] * 4) for p in self.children: if isinstance(p, Box): x += (d + p.height) d = p.depth if (not isinf(p.width)): s = getattr(p, 'shift_amount', 0.0) w = max(w, (p.width + s)) elif isinstance(p, Glue): x += d d = 0.0 glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += (d + p.width) d = 0.0 elif isinstance(p, Char): raise RuntimeError('Internal mathtext error: Char node found in Vlist.') self.width = w if (d > l): x += (d - l) self.depth = l else: self.depth = d if (m == 'additional'): h += x self.height = h x = (h - x) if (x == 0): self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0.0 return if (x > 0.0): self._set_glue(x, 1, total_stretch, 'Overfull') else: self._set_glue(x, (-1), total_shrink, 'Underfull')
'Clear any state before parsing.'
def clear(self):
self._expr = None self._state_stack = None self._em_width_cache = {}
'Parse expression *s* using the given *fonts_object* for output, at the given *fontsize* and *dpi*. Returns the parse tree of :class:`Node` instances.'
def parse(self, s, fonts_object, fontsize, dpi):
self._state_stack = [self.State(fonts_object, 'default', 'rm', fontsize, dpi)] try: self._expression.parseString(s) except ParseException as err: raise ValueError('\n'.join(['', err.line, ((' ' * (err.column - 1)) + '^'), str(err)])) return self._expr
'Get the current :class:`State` of the parser.'
def get_state(self):
return self._state_stack[(-1)]
'Pop a :class:`State` off of the stack.'
def pop_state(self):
self._state_stack.pop()
'Push a new :class:`State` onto the stack which is just a copy of the current state.'
def push_state(self):
self._state_stack.append(self.get_state().copy())
'Create a MathTextParser for the given backend *output*.'
def __init__(self, output):
self._output = output.lower() self._cache = maxdict(50)
'Parse the given math expression *s* at the given *dpi*. If *prop* is provided, it is a :class:`~matplotlib.font_manager.FontProperties` object specifying the "default" font to use in the math expression, used for all non-math text. The results are cached, so multiple calls to :meth:`parse` with the same expression should be fast.'
def parse(self, s, dpi=72, prop=None):
if (prop is None): prop = FontProperties() cacheKey = (s, dpi, hash(prop)) result = self._cache.get(cacheKey) if (result is not None): return result if ((self._output == 'ps') and rcParams['ps.useafm']): font_output = StandardPsFonts(prop) else: backend = self._backend_mapping[self._output]() fontset = rcParams['mathtext.fontset'] fontset_class = self._font_type_mapping.get(fontset.lower()) if (fontset_class is not None): font_output = fontset_class(prop, backend) else: raise ValueError("mathtext.fontset must be either 'cm', 'stix', 'stixsans', or 'custom'") fontsize = prop.get_size_in_points() if (self._parser is None): self.__class__._parser = Parser() box = self._parser.parse(s, font_output, fontsize, dpi) font_output.set_canvas_size(box.width, box.height, box.depth) result = font_output.get_results(box) self._cache[cacheKey] = result self._parser.clear() font_output.destroy() font_output.mathtext_backend.fonts_object = None font_output.mathtext_backend = None return result
'*texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels.'
def to_mask(self, texstr, dpi=120, fontsize=14):
assert (self._output == 'bitmap') prop = FontProperties(size=fontsize) (ftimage, depth) = self.parse(texstr, dpi=dpi, prop=prop) x = ftimage.as_array() return (x, depth)
'*texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *color* Any matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels.'
def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
(x, depth) = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) (r, g, b) = mcolors.colorConverter.to_rgb(color) RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8) RGBA[:, :, 0] = int((255 * r)) RGBA[:, :, 1] = int((255 * g)) RGBA[:, :, 2] = int((255 * b)) RGBA[:, :, 3] = x return (RGBA, depth)
'Writes a tex expression to a PNG file. Returns the offset of the baseline from the bottom of the image in pixels. *filename* A writable filename or fileobject *texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *color* A valid matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns the offset of the baseline from the bottom of the image in pixels.'
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
(rgba, depth) = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) (numrows, numcols, tmp) = rgba.shape _png.write_png(rgba.tostring(), numcols, numrows, filename) return depth
'Returns the offset of the baseline from the bottom of the image in pixels. *texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *dpi* The dots-per-inch to render the text *fontsize* The font size in points'
def get_depth(self, texstr, dpi=120, fontsize=14):
assert (self._output == 'bitmap') prop = FontProperties(size=fontsize) (ftimage, depth) = self.parse(texstr, dpi=dpi, prop=prop) return depth
'Returns an *RGB* tuple of three floats from 0-1. *arg* can be an *RGB* or *RGBA* sequence or a string in any of several forms: 1) a letter from the set \'rgbcmykw\' 2) a hex color string, like \'#00FFFF\' 3) a standard name, like \'aqua\' 4) a float, like \'0.4\', indicating gray on a 0-1 scale if *arg* is *RGBA*, the *A* will simply be discarded.'
def to_rgb(self, arg):
try: return self.cache[arg] except KeyError: pass except TypeError: arg = tuple(arg) try: return self.cache[arg] except KeyError: pass except TypeError: raise ValueError(('to_rgb: arg "%s" is unhashable even inside a tuple' % (str(arg),))) try: if cbook.is_string_like(arg): color = self.colors.get(arg, None) if (color is None): str1 = cnames.get(arg, arg) if str1.startswith('#'): color = hex2color(str1) else: fl = float(arg) if ((fl < 0) or (fl > 1)): raise ValueError('gray (string) must be in range 0-1') color = tuple(([fl] * 3)) elif cbook.iterable(arg): if ((len(arg) > 4) or (len(arg) < 3)): raise ValueError(('sequence length is %d; must be 3 or 4' % len(arg))) color = tuple(arg[:3]) if [x for x in color if ((float(x) < 0) or (x > 1))]: raise ValueError('number in rbg sequence outside 0-1 range') else: raise ValueError('cannot convert argument to rgb sequence') self.cache[arg] = color except (KeyError, ValueError, TypeError) as exc: raise ValueError(('to_rgb: Invalid rgb arg "%s"\n%s' % (str(arg), exc))) return color
'Returns an *RGBA* tuple of four floats from 0-1. For acceptable values of *arg*, see :meth:`to_rgb`. If *arg* is an *RGBA* sequence and *alpha* is not *None*, *alpha* will replace the original *A*.'
def to_rgba(self, arg, alpha=None):
try: if ((not cbook.is_string_like(arg)) and cbook.iterable(arg)): if (len(arg) == 4): if [x for x in arg if ((float(x) < 0) or (x > 1))]: raise ValueError('number in rbga sequence outside 0-1 range') if (alpha is None): return tuple(arg) if ((alpha < 0.0) or (alpha > 1.0)): raise ValueError('alpha must be in range 0-1') return (arg[0], arg[1], arg[2], (arg[3] * alpha)) (r, g, b) = arg[:3] if [x for x in (r, g, b) if ((float(x) < 0) or (x > 1))]: raise ValueError('number in rbg sequence outside 0-1 range') else: (r, g, b) = self.to_rgb(arg) if (alpha is None): alpha = 1.0 return (r, g, b, alpha) except (TypeError, ValueError) as exc: raise ValueError(('to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc)))
'Returns a numpy array of *RGBA* tuples. Accepts a single mpl color spec or a sequence of specs. Special case to handle "no color": if *c* is "none" (case-insensitive), then an empty array will be returned. Same for an empty list.'
def to_rgba_array(self, c, alpha=None):
try: if (c.lower() == 'none'): return np.zeros((0, 4), dtype=np.float_) except AttributeError: pass if (len(c) == 0): return np.zeros((0, 4), dtype=np.float_) try: result = np.array([self.to_rgba(c, alpha)], dtype=np.float_) except ValueError: if isinstance(c, np.ndarray): if ((c.ndim != 2) and (c.dtype.kind not in 'SU')): raise ValueError('Color array must be two-dimensional') result = np.zeros((len(c), 4)) for (i, cc) in enumerate(c): result[i] = self.to_rgba(cc, alpha) return np.asarray(result, np.float_)
'Public class attributes: :attr:`N` : number of rgb quantization levels :attr:`name` : name of colormap'
def __init__(self, name, N=256):
self.name = name self.N = N self._rgba_bad = (0.0, 0.0, 0.0, 0.0) self._rgba_under = None self._rgba_over = None self._i_under = N self._i_over = (N + 1) self._i_bad = (N + 2) self._isinit = False
'*X* is either a scalar or an array (of any dimension). If scalar, a tuple of rgba values is returned, otherwise an array with the new shape = oldshape+(4,). If the X-values are integers, then they are used as indices into the array. If they are floating point, then they must be in the interval (0.0, 1.0). Alpha must be a scalar. If bytes is False, the rgba values will be floats on a 0-1 scale; if True, they will be uint8, 0-255.'
def __call__(self, X, alpha=1.0, bytes=False):
if (not self._isinit): self._init() alpha = min(alpha, 1.0) alpha = max(alpha, 0.0) self._lut[:(-3), (-1)] = alpha mask_bad = None if (not cbook.iterable(X)): vtype = 'scalar' xa = np.array([X]) else: vtype = 'array' xma = ma.asarray(X) xa = xma.filled(0) mask_bad = ma.getmask(xma) if (xa.dtype.char in np.typecodes['Float']): np.putmask(xa, (xa == 1.0), 0.9999999) if NP_CLIP_OUT: np.clip((xa * self.N), (-1), self.N, out=xa) else: xa = np.clip((xa * self.N), (-1), self.N) xa = xa.astype(int) np.putmask(xa, (xa > (self.N - 1)), self._i_over) np.putmask(xa, (xa < 0), self._i_under) if ((mask_bad is not None) and (mask_bad.shape == xa.shape)): np.putmask(xa, mask_bad, self._i_bad) if bytes: lut = (self._lut * 255).astype(np.uint8) else: lut = self._lut rgba = np.empty(shape=(xa.shape + (4,)), dtype=lut.dtype) lut.take(xa, axis=0, mode='clip', out=rgba) if (vtype == 'scalar'): rgba = tuple(rgba[0, :]) return rgba
'Set color to be used for masked values.'
def set_bad(self, color='k', alpha=1.0):
self._rgba_bad = colorConverter.to_rgba(color, alpha) if self._isinit: self._set_extremes()
'Set color to be used for low out-of-range values. Requires norm.clip = False'
def set_under(self, color='k', alpha=1.0):
self._rgba_under = colorConverter.to_rgba(color, alpha) if self._isinit: self._set_extremes()
'Set color to be used for high out-of-range values. Requires norm.clip = False'
def set_over(self, color='k', alpha=1.0):
self._rgba_over = colorConverter.to_rgba(color, alpha) if self._isinit: self._set_extremes()
'Generate the lookup table, self._lut'
def _init():
raise NotImplementedError('Abstract class only')
'Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use:: cdict = {\'red\': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], \'green\': [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)], \'blue\': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)]} Each row in the table for a given color is a sequence of *x*, *y0*, *y1* tuples. In each sequence, *x* must increase monotonically from 0 to 1. For any input value *z* falling between *x[i]* and *x[i+1]*, the output value of a given color will be linearly interpolated between *y1[i]* and *y0[i+1]*:: row i: x y0 y1 row i+1: x y0 y1 Hence y0 in the first row and y1 in the last row are never used. .. seealso:: :func:`makeMappingArray`'
def __init__(self, name, segmentdata, N=256):
self.monochrome = False Colormap.__init__(self, name, N) self._segmentdata = segmentdata
'Make a colormap from a list of colors. *colors* a list of matplotlib color specifications, or an equivalent Nx3 floating point array (*N* rgb values) *name* a string to identify the colormap *N* the number of entries in the map. The default is *None*, in which case there is one colormap entry for each element in the list of colors. If:: N < len(colors) the list will be truncated at *N*. If:: N > len(colors) the list will be extended by repetition.'
def __init__(self, colors, name='from_list', N=None):
self.colors = colors self.monochrome = False if (N is None): N = len(self.colors) elif cbook.is_string_like(self.colors): self.colors = ([self.colors] * N) self.monochrome = True elif cbook.iterable(self.colors): self.colors = list(self.colors) if (len(self.colors) == 1): self.monochrome = True if (len(self.colors) < N): self.colors = (list(self.colors) * N) del self.colors[N:] else: try: gray = float(self.colors) except TypeError: pass else: self.colors = ([gray] * N) self.monochrome = True Colormap.__init__(self, name, N)
'If *vmin* or *vmax* is not given, they are taken from the input\'s minimum and maximum value respectively. If *clip* is *True* and the given value falls outside the range, the returned value will be 0 or 1, whichever is closer. Returns 0 if:: vmin==vmax Works with scalars or arrays, including masked arrays. If *clip* is *True*, masked values are set to 1; otherwise they remain masked. Clipping silently defeats the purpose of setting the over, under, and masked colors in the colormap, so it is likely to lead to surprises; therefore the default is *clip* = *False*.'
def __init__(self, vmin=None, vmax=None, clip=False):
self.vmin = vmin self.vmax = vmax self.clip = clip
'Set *vmin*, *vmax* to min, max of *A*.'
def autoscale(self, A):
self.vmin = ma.minimum(A) self.vmax = ma.maximum(A)
'autoscale only None-valued vmin or vmax'
def autoscale_None(self, A):
if (self.vmin is None): self.vmin = ma.minimum(A) if (self.vmax is None): self.vmax = ma.maximum(A)
'return true if vmin and vmax set'
def scaled(self):
return ((self.vmin is not None) and (self.vmax is not None))
'*boundaries* a monotonically increasing sequence *ncolors* number of colors in the colormap to be used If:: b[i] <= v < b[i+1] then v is mapped to color j; as i varies from 0 to len(boundaries)-2, j goes from 0 to ncolors-1. Out-of-range values are mapped to -1 if low and ncolors if high; these are converted to valid indices by :meth:`Colormap.__call__` .'
def __init__(self, boundaries, ncolors, clip=False):
self.clip = clip self.vmin = boundaries[0] self.vmax = boundaries[(-1)] self.boundaries = np.asarray(boundaries) self.N = len(self.boundaries) self.Ncmap = ncolors if ((self.N - 1) == self.Ncmap): self._interp = False else: self._interp = True