id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
171,210 | import inspect
import textwrap
import numpy as np
import matplotlib as mpl
from matplotlib import _api, _docstring
from matplotlib.ticker import (
NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
SymmetricalLogLocator, AsinhLocator, LogitLocator)
from matplotlib.transforms import Transform, IdentityTransform
_scale_mapping = {
'linear': LinearScale,
'log': LogScale,
'symlog': SymmetricalLogScale,
'asinh': AsinhScale,
'logit': LogitScale,
'function': FuncScale,
'functionlog': FuncScaleLog,
}
The provided code snippet includes necessary dependencies for implementing the `get_scale_names` function. Write a Python function `def get_scale_names()` to solve the following problem:
Return the names of the available scales.
Here is the function:
def get_scale_names():
"""Return the names of the available scales."""
return sorted(_scale_mapping) | Return the names of the available scales. |
171,211 | import inspect
import textwrap
import numpy as np
import matplotlib as mpl
from matplotlib import _api, _docstring
from matplotlib.ticker import (
NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
SymmetricalLogLocator, AsinhLocator, LogitLocator)
from matplotlib.transforms import Transform, IdentityTransform
_scale_mapping = {
'linear': LinearScale,
'log': LogScale,
'symlog': SymmetricalLogScale,
'asinh': AsinhScale,
'logit': LogitScale,
'function': FuncScale,
'functionlog': FuncScaleLog,
}
The provided code snippet includes necessary dependencies for implementing the `scale_factory` function. Write a Python function `def scale_factory(scale, axis, **kwargs)` to solve the following problem:
Return a scale class by name. Parameters ---------- scale : {%(names)s} axis : `matplotlib.axis.Axis`
Here is the function:
def scale_factory(scale, axis, **kwargs):
"""
Return a scale class by name.
Parameters
----------
scale : {%(names)s}
axis : `matplotlib.axis.Axis`
"""
scale_cls = _api.check_getitem(_scale_mapping, scale=scale)
return scale_cls(axis, **kwargs) | Return a scale class by name. Parameters ---------- scale : {%(names)s} axis : `matplotlib.axis.Axis` |
171,212 | import inspect
import textwrap
import numpy as np
import matplotlib as mpl
from matplotlib import _api, _docstring
from matplotlib.ticker import (
NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
SymmetricalLogLocator, AsinhLocator, LogitLocator)
from matplotlib.transforms import Transform, IdentityTransform
_scale_mapping = {
'linear': LinearScale,
'log': LogScale,
'symlog': SymmetricalLogScale,
'asinh': AsinhScale,
'logit': LogitScale,
'function': FuncScale,
'functionlog': FuncScaleLog,
}
The provided code snippet includes necessary dependencies for implementing the `register_scale` function. Write a Python function `def register_scale(scale_class)` to solve the following problem:
Register a new kind of scale. Parameters ---------- scale_class : subclass of `ScaleBase` The scale to register.
Here is the function:
def register_scale(scale_class):
"""
Register a new kind of scale.
Parameters
----------
scale_class : subclass of `ScaleBase`
The scale to register.
"""
_scale_mapping[scale_class.name] = scale_class | Register a new kind of scale. Parameters ---------- scale_class : subclass of `ScaleBase` The scale to register. |
171,213 | import inspect
import textwrap
import numpy as np
import matplotlib as mpl
from matplotlib import _api, _docstring
from matplotlib.ticker import (
NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
SymmetricalLogLocator, AsinhLocator, LogitLocator)
from matplotlib.transforms import Transform, IdentityTransform
_scale_mapping = {
'linear': LinearScale,
'log': LogScale,
'symlog': SymmetricalLogScale,
'asinh': AsinhScale,
'logit': LogitScale,
'function': FuncScale,
'functionlog': FuncScaleLog,
}
The provided code snippet includes necessary dependencies for implementing the `_get_scale_docs` function. Write a Python function `def _get_scale_docs()` to solve the following problem:
Helper function for generating docstrings related to scales.
Here is the function:
def _get_scale_docs():
"""
Helper function for generating docstrings related to scales.
"""
docs = []
for name, scale_class in _scale_mapping.items():
docstring = inspect.getdoc(scale_class.__init__) or ""
docs.extend([
f" {name!r}",
"",
textwrap.indent(docstring, " " * 8),
""
])
return "\n".join(docs) | Helper function for generating docstrings related to scales. |
171,214 | from functools import lru_cache
import math
import warnings
import numpy as np
from matplotlib import _api
def _comb(n, k):
if k > n:
return 0
k = min(k, n - k)
i = np.arange(1, k + 1)
return np.prod((n + 1 - i)/i).astype(int) | null |
171,215 | from functools import lru_cache
import math
import warnings
import numpy as np
from matplotlib import _api
def split_bezier_intersecting_with_closedpath(
bezier, inside_closedpath, tolerance=0.01):
"""
Split a Bézier curve into two at the intersection with a closed path.
Parameters
----------
bezier : (N, 2) array-like
Control points of the Bézier segment. See `.BezierSegment`.
inside_closedpath : callable
A function returning True if a given point (x, y) is inside the
closed path. See also `.find_bezier_t_intersecting_with_closedpath`.
tolerance : float
The tolerance for the intersection. See also
`.find_bezier_t_intersecting_with_closedpath`.
Returns
-------
left, right
Lists of control points for the two Bézier segments.
"""
bz = BezierSegment(bezier)
bezier_point_at_t = bz.point_at_t
t0, t1 = find_bezier_t_intersecting_with_closedpath(
bezier_point_at_t, inside_closedpath, tolerance=tolerance)
_left, _right = split_de_casteljau(bezier, (t0 + t1) / 2.)
return _left, _right
class Path:
"""
A series of possibly disconnected, possibly closed, line and curve
segments.
The underlying storage is made up of two parallel numpy arrays:
- *vertices*: an Nx2 float array of vertices
- *codes*: an N-length uint8 array of path codes, or None
These two arrays always have the same length in the first
dimension. For example, to represent a cubic curve, you must
provide three vertices and three ``CURVE4`` codes.
The code types are:
- ``STOP`` : 1 vertex (ignored)
A marker for the end of the entire path (currently not required and
ignored)
- ``MOVETO`` : 1 vertex
Pick up the pen and move to the given vertex.
- ``LINETO`` : 1 vertex
Draw a line from the current position to the given vertex.
- ``CURVE3`` : 1 control point, 1 endpoint
Draw a quadratic Bézier curve from the current position, with the given
control point, to the given end point.
- ``CURVE4`` : 2 control points, 1 endpoint
Draw a cubic Bézier curve from the current position, with the given
control points, to the given end point.
- ``CLOSEPOLY`` : 1 vertex (ignored)
Draw a line segment to the start point of the current polyline.
If *codes* is None, it is interpreted as a ``MOVETO`` followed by a series
of ``LINETO``.
Users of Path objects should not access the vertices and codes arrays
directly. Instead, they should use `iter_segments` or `cleaned` to get the
vertex/code pairs. This helps, in particular, to consistently handle the
case of *codes* being None.
Some behavior of Path objects can be controlled by rcParams. See the
rcParams whose keys start with 'path.'.
.. note::
The vertices and codes arrays should be treated as
immutable -- there are a number of optimizations and assumptions
made up front in the constructor that will not change when the
data changes.
"""
code_type = np.uint8
# Path codes
STOP = code_type(0) # 1 vertex
MOVETO = code_type(1) # 1 vertex
LINETO = code_type(2) # 1 vertex
CURVE3 = code_type(3) # 2 vertices
CURVE4 = code_type(4) # 3 vertices
CLOSEPOLY = code_type(79) # 1 vertex
#: A dictionary mapping Path codes to the number of vertices that the
#: code expects.
NUM_VERTICES_FOR_CODE = {STOP: 1,
MOVETO: 1,
LINETO: 1,
CURVE3: 2,
CURVE4: 3,
CLOSEPOLY: 1}
def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
"""
Create a new path with the given vertices and codes.
Parameters
----------
vertices : (N, 2) array-like
The path vertices, as an array, masked array or sequence of pairs.
Masked values, if any, 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`.
codes : array-like or None, optional
N-length array of integers representing the codes of the path.
If not None, codes must be the same length as vertices.
If None, *vertices* will be treated as a series of line segments.
_interpolation_steps : int, optional
Used as a hint to certain projections, such as Polar, that this
path should be linearly interpolated immediately before drawing.
This attribute is primarily an implementation detail and is not
intended for public use.
closed : bool, optional
If *codes* is None and closed is True, vertices will be treated as
line segments of a closed polygon. Note that the last vertex will
then be ignored (as the corresponding code will be set to
CLOSEPOLY).
readonly : bool, optional
Makes the path behave in an immutable way and sets the vertices
and codes as read-only arrays.
"""
vertices = _to_unmasked_float_array(vertices)
_api.check_shape((None, 2), vertices=vertices)
if codes is not None:
codes = np.asarray(codes, self.code_type)
if codes.ndim != 1 or len(codes) != len(vertices):
raise ValueError("'codes' must be a 1D list or array with the "
"same length of 'vertices'. "
f"Your vertices have shape {vertices.shape} "
f"but your codes have shape {codes.shape}")
if len(codes) and codes[0] != self.MOVETO:
raise ValueError("The first element of 'code' must be equal "
f"to 'MOVETO' ({self.MOVETO}). "
f"Your first code is {codes[0]}")
elif closed and len(vertices):
codes = np.empty(len(vertices), dtype=self.code_type)
codes[0] = self.MOVETO
codes[1:-1] = self.LINETO
codes[-1] = self.CLOSEPOLY
self._vertices = vertices
self._codes = codes
self._interpolation_steps = _interpolation_steps
self._update_values()
if readonly:
self._vertices.flags.writeable = False
if self._codes is not None:
self._codes.flags.writeable = False
self._readonly = True
else:
self._readonly = False
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
"""
Create a Path instance without the expense of calling the constructor.
Parameters
----------
verts : numpy array
codes : numpy array
internals_from : Path or None
If not None, another `Path` from which the attributes
``should_simplify``, ``simplify_threshold``, and
``interpolation_steps`` will be copied. Note that ``readonly`` is
never copied, and always set to ``False`` by this constructor.
"""
pth = cls.__new__(cls)
pth._vertices = _to_unmasked_float_array(verts)
pth._codes = codes
pth._readonly = False
if internals_from is not None:
pth._should_simplify = internals_from._should_simplify
pth._simplify_threshold = internals_from._simplify_threshold
pth._interpolation_steps = internals_from._interpolation_steps
else:
pth._should_simplify = True
pth._simplify_threshold = mpl.rcParams['path.simplify_threshold']
pth._interpolation_steps = 1
return pth
def _create_closed(cls, vertices):
"""
Create a closed polygonal path going through *vertices*.
Unlike ``Path(..., closed=True)``, *vertices* should **not** end with
an entry for the CLOSEPATH; this entry is added by `._create_closed`.
"""
v = _to_unmasked_float_array(vertices)
return cls(np.concatenate([v, v[:1]]), closed=True)
def _update_values(self):
self._simplify_threshold = mpl.rcParams['path.simplify_threshold']
self._should_simplify = (
self._simplify_threshold > 0 and
mpl.rcParams['path.simplify'] and
len(self._vertices) >= 128 and
(self._codes is None or np.all(self._codes <= Path.LINETO))
)
def vertices(self):
"""
The list of vertices in the `Path` as an Nx2 numpy array.
"""
return self._vertices
def vertices(self, vertices):
if self._readonly:
raise AttributeError("Can't set vertices on a readonly Path")
self._vertices = vertices
self._update_values()
def codes(self):
"""
The list of codes in the `Path` as a 1D numpy array. Each
code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4`
or `CLOSEPOLY`. For codes that correspond to more than one
vertex (`CURVE3` and `CURVE4`), that code will be repeated so
that the length of `vertices` and `codes` is always
the same.
"""
return self._codes
def codes(self, codes):
if self._readonly:
raise AttributeError("Can't set codes on a readonly Path")
self._codes = codes
self._update_values()
def simplify_threshold(self):
"""
The fraction of a pixel difference below which vertices will
be simplified out.
"""
return self._simplify_threshold
def simplify_threshold(self, threshold):
self._simplify_threshold = threshold
def should_simplify(self):
"""
`True` if the vertices array should be simplified.
"""
return self._should_simplify
def should_simplify(self, should_simplify):
self._should_simplify = should_simplify
def readonly(self):
"""
`True` if the `Path` is read-only.
"""
return self._readonly
def copy(self):
"""
Return a shallow copy of the `Path`, which will share the
vertices and codes with the source `Path`.
"""
return copy.copy(self)
def __deepcopy__(self, memo=None):
"""
Return a deepcopy of the `Path`. The `Path` will not be
readonly, even if the source `Path` is.
"""
# Deepcopying arrays (vertices, codes) strips the writeable=False flag.
p = copy.deepcopy(super(), memo)
p._readonly = False
return p
deepcopy = __deepcopy__
def make_compound_path_from_polys(cls, XY):
"""
Make a compound `Path` object to draw a number of polygons with equal
numbers of sides.
.. plot:: gallery/misc/histogram_path.py
Parameters
----------
XY : (numpolys, numsides, 2) array
"""
# for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
# the CLOSEPOLY; the vert for the closepoly is ignored but we still
# need it to keep the codes aligned with the vertices
numpolys, numsides, two = XY.shape
if two != 2:
raise ValueError("The third dimension of 'XY' must be 2")
stride = numsides + 1
nverts = numpolys * stride
verts = np.zeros((nverts, 2))
codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
codes[0::stride] = cls.MOVETO
codes[numsides::stride] = cls.CLOSEPOLY
for i in range(numsides):
verts[i::stride] = XY[:, i]
return cls(verts, codes)
def make_compound_path(cls, *args):
"""
Make a compound path from a list of `Path` objects. Blindly removes
all `Path.STOP` control points.
"""
# Handle an empty list in args (i.e. no args).
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0
for path in args:
if path.codes is None:
codes[i] = cls.MOVETO
codes[i + 1:i + len(path.vertices)] = cls.LINETO
else:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
# remove STOP's, since internal STOPs are a bug
not_stop_mask = codes != cls.STOP
vertices = vertices[not_stop_mask, :]
codes = codes[not_stop_mask]
return cls(vertices, codes)
def __repr__(self):
return "Path(%r, %r)" % (self.vertices, self.codes)
def __len__(self):
return len(self.vertices)
def iter_segments(self, transform=None, remove_nans=True, clip=None,
snap=False, stroke_width=1.0, simplify=None,
curves=True, sketch=None):
"""
Iterate over all curve segments in the path.
Each iteration returns a pair ``(vertices, code)``, where ``vertices``
is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
Additionally, this method can provide a number of standard cleanups and
conversions to the path.
Parameters
----------
transform : None or :class:`~matplotlib.transforms.Transform`
If not None, the given affine transformation will be applied to the
path.
remove_nans : bool, optional
Whether to remove all NaNs from the path and skip over them using
MOVETO commands.
clip : None or (float, float, float, float), optional
If not None, must be a four-tuple (x1, y1, x2, y2)
defining a rectangle in which to clip the path.
snap : None or bool, optional
If True, snap all nodes to pixels; if False, don't snap them.
If None, snap if the path contains only segments
parallel to the x or y axes, and no more than 1024 of them.
stroke_width : float, optional
The width of the stroke being drawn (used for path snapping).
simplify : None or bool, optional
Whether to simplify the path by removing vertices
that do not affect its appearance. If None, use the
:attr:`should_simplify` attribute. See also :rc:`path.simplify`
and :rc:`path.simplify_threshold`.
curves : bool, optional
If True, curve segments will be returned as curve segments.
If False, all curves will be converted to line segments.
sketch : None or sequence, optional
If not None, must be a 3-tuple of the form
(scale, length, randomness), representing the sketch parameters.
"""
if not len(self):
return
cleaned = self.cleaned(transform=transform,
remove_nans=remove_nans, clip=clip,
snap=snap, stroke_width=stroke_width,
simplify=simplify, curves=curves,
sketch=sketch)
# Cache these object lookups for performance in the loop.
NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
STOP = self.STOP
vertices = iter(cleaned.vertices)
codes = iter(cleaned.codes)
for curr_vertices, code in zip(vertices, codes):
if code == STOP:
break
extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
if extra_vertices:
for i in range(extra_vertices):
next(codes)
curr_vertices = np.append(curr_vertices, next(vertices))
yield curr_vertices, code
def iter_bezier(self, **kwargs):
"""
Iterate over each Bézier curve (lines included) in a Path.
Parameters
----------
**kwargs
Forwarded to `.iter_segments`.
Yields
------
B : matplotlib.bezier.BezierSegment
The Bézier curves that make up the current path. Note in particular
that freestanding points are Bézier curves of order 0, and lines
are Bézier curves of order 1 (with two control points).
code : Path.code_type
The code describing what kind of curve is being returned.
Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE4 correspond to
Bézier curves with 1, 2, 3, and 4 control points (respectively).
Path.CLOSEPOLY is a Path.LINETO with the control points correctly
chosen based on the start/end points of the current stroke.
"""
first_vert = None
prev_vert = None
for verts, code in self.iter_segments(**kwargs):
if first_vert is None:
if code != Path.MOVETO:
raise ValueError("Malformed path, must start with MOVETO.")
if code == Path.MOVETO: # a point is like "CURVE1"
first_vert = verts
yield BezierSegment(np.array([first_vert])), code
elif code == Path.LINETO: # "CURVE2"
yield BezierSegment(np.array([prev_vert, verts])), code
elif code == Path.CURVE3:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:]])), code
elif code == Path.CURVE4:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:4], verts[4:]])), code
elif code == Path.CLOSEPOLY:
yield BezierSegment(np.array([prev_vert, first_vert])), code
elif code == Path.STOP:
return
else:
raise ValueError(f"Invalid Path.code_type: {code}")
prev_vert = verts[-2:]
def cleaned(self, transform=None, remove_nans=False, clip=None,
*, simplify=False, curves=False,
stroke_width=1.0, snap=False, sketch=None):
"""
Return a new Path with vertices and codes cleaned according to the
parameters.
See Also
--------
Path.iter_segments : for details of the keyword arguments.
"""
vertices, codes = _path.cleanup_path(
self, transform, remove_nans, clip, snap, stroke_width, simplify,
curves, sketch)
pth = Path._fast_from_codes_and_verts(vertices, codes, self)
if not simplify:
pth._should_simplify = False
return pth
def transformed(self, transform):
"""
Return a transformed copy of the path.
See Also
--------
matplotlib.transforms.TransformedPath
A specialized path class that will cache the transformed result and
automatically update when the transform changes.
"""
return Path(transform.transform(self.vertices), self.codes,
self._interpolation_steps)
def contains_point(self, point, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given point.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
point : (float, float)
The point (x, y) to check.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *point* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *point*.
radius : float, default: 0
Additional margin on the path in coordinates of *point*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
bool
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
# `point_in_path` does not handle nonlinear transforms, so we
# transform the path ourselves. If *transform* is affine, letting
# `point_in_path` handle the transform avoids allocating an extra
# buffer.
if transform and not transform.is_affine:
self = transform.transform_path(self)
transform = None
return _path.point_in_path(point[0], point[1], radius, self, transform)
def contains_points(self, points, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given points.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
points : (N, 2) array
The points to check. Columns contain x and y values.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *points* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *points*.
radius : float, default: 0
Additional margin on the path in coordinates of *points*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
length-N bool array
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
result = _path.points_in_path(points, radius, self, transform)
return result.astype('bool')
def contains_path(self, path, transform=None):
"""
Return whether this (closed) path completely contains the given path.
If *transform* is not ``None``, the path will be transformed before
checking for containment.
"""
if transform is not None:
transform = transform.frozen()
return _path.path_in_path(self, None, path, transform)
def get_extents(self, transform=None, **kwargs):
"""
Get Bbox of the path.
Parameters
----------
transform : matplotlib.transforms.Transform, optional
Transform to apply to path before computing extents, if any.
**kwargs
Forwarded to `.iter_bezier`.
Returns
-------
matplotlib.transforms.Bbox
The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
"""
from .transforms import Bbox
if transform is not None:
self = transform.transform_path(self)
if self.codes is None:
xys = self.vertices
elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
# Optimization for the straight line case.
# Instead of iterating through each curve, consider
# each line segment's end-points
# (recall that STOP and CLOSEPOLY vertices are ignored)
xys = self.vertices[np.isin(self.codes,
[Path.MOVETO, Path.LINETO])]
else:
xys = []
for curve, code in self.iter_bezier(**kwargs):
# places where the derivative is zero can be extrema
_, dzeros = curve.axis_aligned_extrema()
# as can the ends of the curve
xys.append(curve([0, *dzeros, 1]))
xys = np.concatenate(xys)
if len(xys):
return Bbox([xys.min(axis=0), xys.max(axis=0)])
else:
return Bbox.null()
def intersects_path(self, other, filled=True):
"""
Return whether if this path intersects another given path.
If *filled* is True, then this also returns True if one path completely
encloses the other (i.e., the paths are treated as filled).
"""
return _path.path_intersects_path(self, other, filled)
def intersects_bbox(self, bbox, filled=True):
"""
Return whether this path intersects a given `~.transforms.Bbox`.
If *filled* is True, then this also returns True if the path completely
encloses the `.Bbox` (i.e., the path is treated as filled).
The bounding box is always considered filled.
"""
return _path.path_intersects_rectangle(
self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
def interpolated(self, steps):
"""
Return a new path resampled to length N x steps.
Codes other than LINETO are not handled correctly.
"""
if steps == 1:
return self
vertices = simple_linear_interpolation(self.vertices, steps)
codes = self.codes
if codes is not None:
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
dtype=self.code_type)
new_codes[0::steps] = codes
else:
new_codes = None
return Path(vertices, new_codes)
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
"""
Convert this path to a list of polygons or polylines. Each
polygon/polyline 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 Bézier curves.
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.
If *closed_only* is `True` (default), only closed polygons,
with the last point being the same as the first point, will be
returned. Any unclosed polylines in the path will be
explicitly closed. If *closed_only* is `False`, any unclosed
polygons in the path will be returned as unclosed polygons,
and the closed polygons will be returned explicitly closed by
setting the last point to the same as the first point.
"""
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):
vertices = self.vertices
if closed_only:
if len(vertices) < 3:
return []
elif np.any(vertices[0] != vertices[-1]):
vertices = [*vertices, vertices[0]]
if transform is None:
return [vertices]
else:
return [transform.transform(vertices)]
# Deal with the case where there are curves and/or multiple
# subpaths (using extension code)
return _path.convert_path_to_polygons(
self, transform, width, height, closed_only)
_unit_rectangle = None
def unit_rectangle(cls):
"""
Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
"""
if cls._unit_rectangle is None:
cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
closed=True, readonly=True)
return cls._unit_rectangle
_unit_regular_polygons = WeakValueDictionary()
def unit_regular_polygon(cls, numVertices):
"""
Return a :class:`Path` instance for a unit regular polygon with the
given *numVertices* such that the circumscribing circle has radius 1.0,
centered at (0, 0).
"""
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)
# This initial rotation is to make sure the polygon always
# "points-up".
+ np.pi / 2)
verts = np.column_stack((np.cos(theta), np.sin(theta)))
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_polygons[numVertices] = path
return path
_unit_regular_stars = WeakValueDictionary()
def unit_regular_star(cls, numVertices, innerCircle=0.5):
"""
Return a :class:`Path` for a unit regular star with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
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))
# This initial rotation is to make sure the polygon always
# "points-up"
theta += np.pi / 2.0
r = np.ones(ns2 + 1)
r[1::2] = innerCircle
verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_stars[(numVertices, innerCircle)] = path
return path
def unit_regular_asterisk(cls, numVertices):
"""
Return a :class:`Path` for a unit regular asterisk with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
return cls.unit_regular_star(numVertices, 0.0)
_unit_circle = None
def unit_circle(cls):
"""
Return the readonly :class:`Path` of the unit circle.
For most cases, :func:`Path.circle` will be what you want.
"""
if cls._unit_circle is None:
cls._unit_circle = cls.circle(center=(0, 0), radius=1,
readonly=True)
return cls._unit_circle
def circle(cls, center=(0., 0.), radius=1., readonly=False):
"""
Return a `Path` representing a circle of a given radius and center.
Parameters
----------
center : (float, float), default: (0, 0)
The center of the circle.
radius : float, default: 1
The radius of the circle.
readonly : bool
Whether the created path should have the "readonly" argument
set when creating the Path instance.
Notes
-----
The circle is approximated using 8 cubic Bézier curves, as described in
Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
Bezier Cubic Splines <https://www.tinaja.com/glib/ellipse4.pdf>`_.
"""
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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]],
dtype=float)
codes = [cls.CURVE4] * 26
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
return Path(vertices * radius + center, codes, readonly=readonly)
_unit_circle_righthalf = None
def unit_circle_righthalf(cls):
"""
Return a `Path` of the right half of a unit circle.
See `Path.circle` for the reference on the approximation used.
"""
if cls._unit_circle_righthalf is None:
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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],
[0.0, -1.0]],
float)
codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
return cls._unit_circle_righthalf
def arc(cls, theta1, theta2, n=None, is_wedge=False):
"""
Return a `Path` for the unit circle arc from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest arc within 360 degrees.
That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
*theta2* - 360 and not a full circle plus some extra overlap.
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
<https://web.archive.org/web/20190318044212/http://www.spaceroots.org/documents/ellipse/index.html>`_.
"""
halfpi = np.pi * 0.5
eta1 = theta1
eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
# Ensure 2pi range is not flattened to 0 due to floating-point errors,
# but don't try to expand existing 0 range.
if theta2 != theta1 and eta2 <= eta1:
eta2 += 360
eta1, eta2 = np.deg2rad([eta1, eta2])
# number of curve segments to make
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), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[1] = [xA[0], yA[0]]
codes[0:2] = [cls.MOVETO, cls.LINETO]
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
vertex_offset = 2
end = length - 2
else:
length = n * 3 + 1
vertices = np.empty((length, 2), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[0] = [xA[0], yA[0]]
codes[0] = cls.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 cls(vertices, codes, readonly=True)
def wedge(cls, theta1, theta2, n=None):
"""
Return a `Path` for the unit circle wedge from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest wedge within 360 degrees.
That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
to *theta2* - 360 and not a full circle plus some extra overlap.
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*.
See `Path.arc` for the reference on the approximation used.
"""
return cls.arc(theta1, theta2, n, True)
def hatch(hatchpattern, density=6):
"""
Given a hatch specifier, *hatchpattern*, generates a Path that
can be used in a repeated hatching pattern. *density* is the
number of lines per unit square.
"""
from matplotlib.hatch import get_path
return (get_path(hatchpattern, density)
if hatchpattern is not None else None)
def clip_to_bbox(self, bbox, inside=True):
"""
Clip the path to the given bounding box.
The path must be made up of one or more closed polygons. This
algorithm will not behave correctly for unclosed paths.
If *inside* is `True`, clip to the inside of the box, otherwise
to the outside of the box.
"""
verts = _path.clip_path_to_rect(self, bbox, inside)
paths = [Path(poly) for poly in verts]
return self.make_compound_path(*paths)
The provided code snippet includes necessary dependencies for implementing the `split_path_inout` function. Write a Python function `def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False)` to solve the following problem:
Divide a path into two segments at the point where ``inside(x, y)`` becomes False.
Here is the function:
def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False):
"""
Divide a path into two segments at the point where ``inside(x, y)`` becomes
False.
"""
from .path import Path
path_iter = path.iter_segments()
ctl_points, command = next(path_iter)
begin_inside = inside(ctl_points[-2:]) # true if begin point is inside
ctl_points_old = ctl_points
iold = 0
i = 1
for ctl_points, command in path_iter:
iold = i
i += len(ctl_points) // 2
if inside(ctl_points[-2:]) != begin_inside:
bezier_path = np.concatenate([ctl_points_old[-2:], ctl_points])
break
ctl_points_old = ctl_points
else:
raise ValueError("The path does not intersect with the patch")
bp = bezier_path.reshape((-1, 2))
left, right = split_bezier_intersecting_with_closedpath(
bp, inside, tolerance)
if len(left) == 2:
codes_left = [Path.LINETO]
codes_right = [Path.MOVETO, Path.LINETO]
elif len(left) == 3:
codes_left = [Path.CURVE3, Path.CURVE3]
codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
elif len(left) == 4:
codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4]
codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
else:
raise AssertionError("This should never be reached")
verts_left = left[1:]
verts_right = right[:]
if path.codes is None:
path_in = Path(np.concatenate([path.vertices[:i], verts_left]))
path_out = Path(np.concatenate([verts_right, path.vertices[i:]]))
else:
path_in = Path(np.concatenate([path.vertices[:iold], verts_left]),
np.concatenate([path.codes[:iold], codes_left]))
path_out = Path(np.concatenate([verts_right, path.vertices[i:]]),
np.concatenate([codes_right, path.codes[i:]]))
if reorder_inout and not begin_inside:
path_in, path_out = path_out, path_in
return path_in, path_out | Divide a path into two segments at the point where ``inside(x, y)`` becomes False. |
171,216 | from functools import lru_cache
import math
import warnings
import numpy as np
from matplotlib import _api
The provided code snippet includes necessary dependencies for implementing the `inside_circle` function. Write a Python function `def inside_circle(cx, cy, r)` to solve the following problem:
Return a function that checks whether a point is in a circle with center (*cx*, *cy*) and radius *r*. The returned function has the signature:: f(xy: tuple[float, float]) -> bool
Here is the function:
def inside_circle(cx, cy, r):
"""
Return a function that checks whether a point is in a circle with center
(*cx*, *cy*) and radius *r*.
The returned function has the signature::
f(xy: tuple[float, float]) -> bool
"""
r2 = r ** 2
def _f(xy):
x, y = xy
return (x - cx) ** 2 + (y - cy) ** 2 < r2
return _f | Return a function that checks whether a point is in a circle with center (*cx*, *cy*) and radius *r*. The returned function has the signature:: f(xy: tuple[float, float]) -> bool |
171,217 | from functools import lru_cache
import math
import warnings
import numpy as np
from matplotlib import _api
def get_intersection(cx1, cy1, cos_t1, sin_t1,
cx2, cy2, cos_t2, sin_t2):
"""
Return the intersection between the line through (*cx1*, *cy1*) at angle
*t1* and the line through (*cx2*, *cy2*) at angle *t2*.
"""
# line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0.
# line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1
line1_rhs = sin_t1 * cx1 - cos_t1 * cy1
line2_rhs = sin_t2 * cx2 - cos_t2 * cy2
# rhs matrix
a, b = sin_t1, -cos_t1
c, d = sin_t2, -cos_t2
ad_bc = a * d - b * c
if abs(ad_bc) < 1e-12:
raise ValueError("Given lines do not intersect. Please verify that "
"the angles are not equal or differ by 180 degrees.")
# rhs_inverse
a_, b_ = d, -b
c_, d_ = -c, a
a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]]
x = a_ * line1_rhs + b_ * line2_rhs
y = c_ * line1_rhs + d_ * line2_rhs
return x, y
def get_normal_points(cx, cy, cos_t, sin_t, length):
"""
For a line passing through (*cx*, *cy*) and having an angle *t*, return
locations of the two points located along its perpendicular line at the
distance of *length*.
"""
if length == 0.:
return cx, cy, cx, cy
cos_t1, sin_t1 = sin_t, -cos_t
cos_t2, sin_t2 = -sin_t, cos_t
x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy
x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy
return x1, y1, x2, y2
def get_cos_sin(x0, y0, x1, y1):
dx, dy = x1 - x0, y1 - y0
d = (dx * dx + dy * dy) ** .5
# Account for divide by zero
if d == 0:
return 0.0, 0.0
return dx / d, dy / d
def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1.e-5):
"""
Check if two lines are parallel.
Parameters
----------
dx1, dy1, dx2, dy2 : float
The gradients *dy*/*dx* of the two lines.
tolerance : float
The angular tolerance in radians up to which the lines are considered
parallel.
Returns
-------
is_parallel
- 1 if two lines are parallel in same direction.
- -1 if two lines are parallel in opposite direction.
- False otherwise.
"""
theta1 = np.arctan2(dx1, dy1)
theta2 = np.arctan2(dx2, dy2)
dtheta = abs(theta1 - theta2)
if dtheta < tolerance:
return 1
elif abs(dtheta - np.pi) < tolerance:
return -1
else:
return False
The provided code snippet includes necessary dependencies for implementing the `get_parallels` function. Write a Python function `def get_parallels(bezier2, width)` to solve the following problem:
Given the quadratic Bézier control points *bezier2*, returns control points of quadratic Bézier lines roughly parallel to given one separated by *width*.
Here is the function:
def get_parallels(bezier2, width):
"""
Given the quadratic Bézier control points *bezier2*, returns
control points of quadratic Bézier lines roughly parallel to given
one separated by *width*.
"""
# The parallel Bezier lines are constructed by following ways.
# c1 and c2 are control points representing the start and end of the
# Bezier line.
# cm is the middle point
c1x, c1y = bezier2[0]
cmx, cmy = bezier2[1]
c2x, c2y = bezier2[2]
parallel_test = check_if_parallel(c1x - cmx, c1y - cmy,
cmx - c2x, cmy - c2y)
if parallel_test == -1:
_api.warn_external(
"Lines do not intersect. A straight line is used instead.")
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y)
cos_t2, sin_t2 = cos_t1, sin_t1
else:
# t1 and t2 is the angle between c1 and cm, cm, c2. They are
# also an angle of the tangential line of the path at c1 and c2
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y)
# find c1_left, c1_right which are located along the lines
# through c1 and perpendicular to the tangential lines of the
# Bezier path at a distance of width. Same thing for c2_left and
# c2_right with respect to c2.
c1x_left, c1y_left, c1x_right, c1y_right = (
get_normal_points(c1x, c1y, cos_t1, sin_t1, width)
)
c2x_left, c2y_left, c2x_right, c2y_right = (
get_normal_points(c2x, c2y, cos_t2, sin_t2, width)
)
# find cm_left which is the intersecting point of a line through
# c1_left with angle t1 and a line through c2_left with angle
# t2. Same with cm_right.
try:
cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1,
sin_t1, c2x_left, c2y_left,
cos_t2, sin_t2)
cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1,
sin_t1, c2x_right, c2y_right,
cos_t2, sin_t2)
except ValueError:
# Special case straight lines, i.e., angle between two lines is
# less than the threshold used by get_intersection (we don't use
# check_if_parallel as the threshold is not the same).
cmx_left, cmy_left = (
0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left)
)
cmx_right, cmy_right = (
0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right)
)
# the parallel Bezier lines are created with control points of
# [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right]
path_left = [(c1x_left, c1y_left),
(cmx_left, cmy_left),
(c2x_left, c2y_left)]
path_right = [(c1x_right, c1y_right),
(cmx_right, cmy_right),
(c2x_right, c2y_right)]
return path_left, path_right | Given the quadratic Bézier control points *bezier2*, returns control points of quadratic Bézier lines roughly parallel to given one separated by *width*. |
171,218 | from functools import lru_cache
import math
import warnings
import numpy as np
from matplotlib import _api
def get_normal_points(cx, cy, cos_t, sin_t, length):
"""
For a line passing through (*cx*, *cy*) and having an angle *t*, return
locations of the two points located along its perpendicular line at the
distance of *length*.
"""
if length == 0.:
return cx, cy, cx, cy
cos_t1, sin_t1 = sin_t, -cos_t
cos_t2, sin_t2 = -sin_t, cos_t
x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy
x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy
return x1, y1, x2, y2
def get_cos_sin(x0, y0, x1, y1):
dx, dy = x1 - x0, y1 - y0
d = (dx * dx + dy * dy) ** .5
# Account for divide by zero
if d == 0:
return 0.0, 0.0
return dx / d, dy / d
def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y):
"""
Find control points of the Bézier curve passing through (*c1x*, *c1y*),
(*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1.
"""
cmx = .5 * (4 * mmx - (c1x + c2x))
cmy = .5 * (4 * mmy - (c1y + c2y))
return [(c1x, c1y), (cmx, cmy), (c2x, c2y)]
The provided code snippet includes necessary dependencies for implementing the `make_wedged_bezier2` function. Write a Python function `def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.)` to solve the following problem:
Being similar to `get_parallels`, returns control points of two quadratic Bézier lines having a width roughly parallel to given one separated by *width*.
Here is the function:
def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.):
"""
Being similar to `get_parallels`, returns control points of two quadratic
Bézier lines having a width roughly parallel to given one separated by
*width*.
"""
# c1, cm, c2
c1x, c1y = bezier2[0]
cmx, cmy = bezier2[1]
c3x, c3y = bezier2[2]
# t1 and t2 is the angle between c1 and cm, cm, c3.
# They are also an angle of the tangential line of the path at c1 and c3
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y)
# find c1_left, c1_right which are located along the lines
# through c1 and perpendicular to the tangential lines of the
# Bezier path at a distance of width. Same thing for c3_left and
# c3_right with respect to c3.
c1x_left, c1y_left, c1x_right, c1y_right = (
get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1)
)
c3x_left, c3y_left, c3x_right, c3y_right = (
get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2)
)
# find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and
# c12-c23
c12x, c12y = (c1x + cmx) * .5, (c1y + cmy) * .5
c23x, c23y = (cmx + c3x) * .5, (cmy + c3y) * .5
c123x, c123y = (c12x + c23x) * .5, (c12y + c23y) * .5
# tangential angle of c123 (angle between c12 and c23)
cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y)
c123x_left, c123y_left, c123x_right, c123y_right = (
get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm)
)
path_left = find_control_points(c1x_left, c1y_left,
c123x_left, c123y_left,
c3x_left, c3y_left)
path_right = find_control_points(c1x_right, c1y_right,
c123x_right, c123y_right,
c3x_right, c3y_right)
return path_left, path_right | Being similar to `get_parallels`, returns control points of two quadratic Bézier lines having a width roughly parallel to given one separated by *width*. |
171,219 | import abc
import base64
import contextlib
from io import BytesIO, TextIOWrapper
import itertools
import logging
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import uuid
import warnings
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib._animation_data import (
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
from matplotlib import _api, cbook
import matplotlib.colors as mcolors
The provided code snippet includes necessary dependencies for implementing the `adjusted_figsize` function. Write a Python function `def adjusted_figsize(w, h, dpi, n)` to solve the following problem:
Compute figure size so that pixels are a multiple of n. Parameters ---------- w, h : float Size in inches. dpi : float The dpi. n : int The target multiple. Returns ------- wnew, hnew : float The new figure size in inches.
Here is the function:
def adjusted_figsize(w, h, dpi, n):
"""
Compute figure size so that pixels are a multiple of n.
Parameters
----------
w, h : float
Size in inches.
dpi : float
The dpi.
n : int
The target multiple.
Returns
-------
wnew, hnew : float
The new figure size in inches.
"""
# this maybe simplified if / when we adopt consistent rounding for
# pixel size across the whole library
def correct_roundoff(x, dpi, n):
if int(x*dpi) % n != 0:
if int(np.nextafter(x, np.inf)*dpi) % n == 0:
x = np.nextafter(x, np.inf)
elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
x = np.nextafter(x, -np.inf)
return x
wnew = int(w * dpi / n) * n / dpi
hnew = int(h * dpi / n) * n / dpi
return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n) | Compute figure size so that pixels are a multiple of n. Parameters ---------- w, h : float Size in inches. dpi : float The dpi. n : int The target multiple. Returns ------- wnew, hnew : float The new figure size in inches. |
171,220 | import abc
import base64
import contextlib
from io import BytesIO, TextIOWrapper
import itertools
import logging
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import uuid
import warnings
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib._animation_data import (
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
from matplotlib import _api, cbook
import matplotlib.colors as mcolors
INCLUDED_FRAMES = """
for (var i=0; i<{Nframes}; i++){{
frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) +
".{frame_format}";
}}
"""
def _included_frames(frame_count, frame_format, frame_dir):
return INCLUDED_FRAMES.format(Nframes=frame_count,
frame_dir=frame_dir,
frame_format=frame_format) | null |
171,221 | import abc
import base64
import contextlib
from io import BytesIO, TextIOWrapper
import itertools
import logging
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import uuid
import warnings
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib._animation_data import (
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
from matplotlib import _api, cbook
import matplotlib.colors as mcolors
The provided code snippet includes necessary dependencies for implementing the `_embedded_frames` function. Write a Python function `def _embedded_frames(frame_list, frame_format)` to solve the following problem:
frame_list should be a list of base64-encoded png files
Here is the function:
def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
if frame_format == 'svg':
# Fix MIME type for svg
frame_format = 'svg+xml'
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
return "\n" + "".join(
template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
for i, frame_data in enumerate(frame_list)) | frame_list should be a list of base64-encoded png files |
171,222 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
def _sanitize_extrema(ex):
if ex is None:
return ex
try:
ret = ex.item()
except AttributeError:
ret = float(ex)
return ret | null |
171,223 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
The provided code snippet includes necessary dependencies for implementing the `_has_alpha_channel` function. Write a Python function `def _has_alpha_channel(c)` to solve the following problem:
Return whether *c* is a color with an alpha channel.
Here is the function:
def _has_alpha_channel(c):
"""Return whether *c* is a color with an alpha channel."""
# 4-element sequences are interpreted as r, g, b, a
return not isinstance(c, str) and len(c) == 4 | Return whether *c* is a color with an alpha channel. |
171,224 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
def is_color_like(c):
"""Return whether *c* can be interpreted as an RGB(A) color."""
# Special-case nth color syntax because it cannot be parsed during setup.
if _is_nth_color(c):
return True
try:
to_rgba(c)
except ValueError:
return False
else:
return True
The provided code snippet includes necessary dependencies for implementing the `_check_color_like` function. Write a Python function `def _check_color_like(**kwargs)` to solve the following problem:
For each *key, value* pair in *kwargs*, check that *value* is color-like.
Here is the function:
def _check_color_like(**kwargs):
"""
For each *key, value* pair in *kwargs*, check that *value* is color-like.
"""
for k, v in kwargs.items():
if not is_color_like(v):
raise ValueError(f"{v!r} is not a valid value for {k}") | For each *key, value* pair in *kwargs*, check that *value* is color-like. |
171,225 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
def to_rgba_array(c, alpha=None):
"""
Convert *c* to a (n, 4) array of RGBA colors.
Parameters
----------
c : Matplotlib color or array of colors
If *c* is a masked array, an `~numpy.ndarray` is returned with a
(0, 0, 0, 0) row for each masked value or row in *c*.
alpha : float or sequence of floats, optional
If *alpha* is given, force the alpha value of the returned RGBA tuple
to *alpha*.
If None, the alpha value from *c* is used. If *c* does not have an
alpha channel, then alpha defaults to 1.
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
which always maps to ``(0, 0, 0, 0)``.
If *alpha* is a sequence and *c* is a single color, *c* will be
repeated to match the length of *alpha*.
Returns
-------
array
(n, 4) array of RGBA colors, where each channel (red, green, blue,
alpha) can assume values between 0 and 1.
"""
# Special-case inputs that are already arrays, for performance. (If the
# array has the wrong kind or shape, raise the error during one-at-a-time
# conversion.)
if np.iterable(alpha):
alpha = np.asarray(alpha).ravel()
if (isinstance(c, np.ndarray) and c.dtype.kind in "if"
and c.ndim == 2 and c.shape[1] in [3, 4]):
mask = c.mask.any(axis=1) if np.ma.is_masked(c) else None
c = np.ma.getdata(c)
if np.iterable(alpha):
if c.shape[0] == 1 and alpha.shape[0] > 1:
c = np.tile(c, (alpha.shape[0], 1))
elif c.shape[0] != alpha.shape[0]:
raise ValueError("The number of colors must match the number"
" of alpha values if there are more than one"
" of each.")
if c.shape[1] == 3:
result = np.column_stack([c, np.zeros(len(c))])
result[:, -1] = alpha if alpha is not None else 1.
elif c.shape[1] == 4:
result = c.copy()
if alpha is not None:
result[:, -1] = alpha
if mask is not None:
result[mask] = 0
if np.any((result < 0) | (result > 1)):
raise ValueError("RGBA values should be within 0-1 range")
return result
# Handle single values.
# Note that this occurs *after* handling inputs that are already arrays, as
# `to_rgba(c, alpha)` (below) is expensive for such inputs, due to the need
# to format the array in the ValueError message(!).
if cbook._str_lower_equal(c, "none"):
return np.zeros((0, 4), float)
try:
if np.iterable(alpha):
return np.array([to_rgba(c, a) for a in alpha], float)
else:
return np.array([to_rgba(c, alpha)], float)
except (ValueError, TypeError):
pass
if isinstance(c, str):
raise ValueError(f"{c!r} is not a valid color value.")
if len(c) == 0:
return np.zeros((0, 4), float)
# Quick path if the whole sequence can be directly converted to a numpy
# array in one shot.
if isinstance(c, Sequence):
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
if lens == {3}:
rgba = np.column_stack([c, np.ones(len(c))])
elif lens == {4}:
rgba = np.array(c)
else:
rgba = np.array([to_rgba(cc) for cc in c])
else:
rgba = np.array([to_rgba(cc) for cc in c])
if alpha is not None:
rgba[:, 3] = alpha
return rgba
The provided code snippet includes necessary dependencies for implementing the `same_color` function. Write a Python function `def same_color(c1, c2)` to solve the following problem:
Return whether the colors *c1* and *c2* are the same. *c1*, *c2* can be single colors or lists/arrays of colors.
Here is the function:
def same_color(c1, c2):
"""
Return whether the colors *c1* and *c2* are the same.
*c1*, *c2* can be single colors or lists/arrays of colors.
"""
c1 = to_rgba_array(c1)
c2 = to_rgba_array(c2)
n1 = max(c1.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
n2 = max(c2.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
if n1 != n2:
raise ValueError('Different number of elements passed.')
# The following shape test is needed to correctly handle comparisons with
# 'none', which results in a shape (0, 4) array and thus cannot be tested
# via value comparison.
return c1.shape == c2.shape and (c1 == c2).all() | Return whether the colors *c1* and *c2* are the same. *c1*, *c2* can be single colors or lists/arrays of colors. |
171,226 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
The provided code snippet includes necessary dependencies for implementing the `_create_lookup_table` function. Write a Python function `def _create_lookup_table(N, data, gamma=1.0)` to solve the following problem:
r""" Create an *N* -element 1D lookup table. This assumes a mapping :math:`f : [0, 1] \rightarrow [0, 1]`. The returned data is an array of N values :math:`y = f(x)` where x is sampled from [0, 1]. By default (*gamma* = 1) x is equidistantly sampled from [0, 1]. The *gamma* correction factor :math:`\gamma` distorts this equidistant sampling by :math:`x \rightarrow x^\gamma`. Parameters ---------- N : int The number of elements of the created lookup table; at least 1. data : (M, 3) array-like or callable Defines the mapping :math:`f`. If a (M, 3) array-like, the rows define values (x, y0, y1). The x values must start with x=0, end with x=1, and all x values be in increasing order. A value between :math:`x_i` and :math:`x_{i+1}` is mapped to the range :math:`y^1_{i-1} \ldots y^0_i` by linear interpolation. For the simple case of a y-continuous mapping, y0 and y1 are identical. The two values of y are to allow for discontinuous mapping functions. E.g. a sawtooth with a period of 0.2 and an amplitude of 1 would be:: [(0, 1, 0), (0.2, 1, 0), (0.4, 1, 0), ..., [(1, 1, 0)] In the special case of ``N == 1``, by convention the returned value is y0 for x == 1. If *data* is a callable, it must accept and return numpy arrays:: data(x : ndarray) -> ndarray and map values between 0 - 1 to 0 - 1. gamma : float Gamma correction factor for input distribution x of the mapping. See also https://en.wikipedia.org/wiki/Gamma_correction. Returns ------- array The lookup table where ``lut[x * (N-1)]`` gives the closest value for values of x between 0 and 1. Notes ----- This function is internally used for `.LinearSegmentedColormap`.
Here is the function:
def _create_lookup_table(N, data, gamma=1.0):
r"""
Create an *N* -element 1D lookup table.
This assumes a mapping :math:`f : [0, 1] \rightarrow [0, 1]`. The returned
data is an array of N values :math:`y = f(x)` where x is sampled from
[0, 1].
By default (*gamma* = 1) x is equidistantly sampled from [0, 1]. The
*gamma* correction factor :math:`\gamma` distorts this equidistant
sampling by :math:`x \rightarrow x^\gamma`.
Parameters
----------
N : int
The number of elements of the created lookup table; at least 1.
data : (M, 3) array-like or callable
Defines the mapping :math:`f`.
If a (M, 3) array-like, the rows define values (x, y0, y1). The x
values must start with x=0, end with x=1, and all x values be in
increasing order.
A value between :math:`x_i` and :math:`x_{i+1}` is mapped to the range
:math:`y^1_{i-1} \ldots y^0_i` by linear interpolation.
For the simple case of a y-continuous mapping, y0 and y1 are identical.
The two values of y are to allow for discontinuous mapping functions.
E.g. a sawtooth with a period of 0.2 and an amplitude of 1 would be::
[(0, 1, 0), (0.2, 1, 0), (0.4, 1, 0), ..., [(1, 1, 0)]
In the special case of ``N == 1``, by convention the returned value
is y0 for x == 1.
If *data* is a callable, it must accept and return numpy arrays::
data(x : ndarray) -> ndarray
and map values between 0 - 1 to 0 - 1.
gamma : float
Gamma correction factor for input distribution x of the mapping.
See also https://en.wikipedia.org/wiki/Gamma_correction.
Returns
-------
array
The lookup table where ``lut[x * (N-1)]`` gives the closest value
for values of x between 0 and 1.
Notes
-----
This function is internally used for `.LinearSegmentedColormap`.
"""
if callable(data):
xind = np.linspace(0, 1, N) ** gamma
lut = np.clip(np.array(data(xind), dtype=float), 0, 1)
return lut
try:
adata = np.array(data)
except Exception as err:
raise TypeError("data must be convertible to an array") from err
_api.check_shape((None, 3), data=adata)
x = adata[:, 0]
y0 = adata[:, 1]
y1 = adata[:, 2]
if x[0] != 0. or x[-1] != 1.0:
raise ValueError(
"data mapping points must start with x=0 and end with x=1")
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
if N == 1:
# convention: use the y = f(x=1) value for a 1-element lookup table
lut = np.array(y0[-1])
else:
x = x * (N - 1)
xind = (N - 1) * np.linspace(0, 1, N) ** gamma
ind = np.searchsorted(x, xind)[1:-1]
distance = (xind[1:-1] - x[ind - 1]) / (x[ind] - x[ind - 1])
lut = np.concatenate([
[y1[0]],
distance * (y0[ind] - y1[ind - 1]) + y1[ind - 1],
[y0[-1]],
])
# ensure that the lut is confined to values between 0 and 1 by clipping it
return np.clip(lut, 0.0, 1.0) | r""" Create an *N* -element 1D lookup table. This assumes a mapping :math:`f : [0, 1] \rightarrow [0, 1]`. The returned data is an array of N values :math:`y = f(x)` where x is sampled from [0, 1]. By default (*gamma* = 1) x is equidistantly sampled from [0, 1]. The *gamma* correction factor :math:`\gamma` distorts this equidistant sampling by :math:`x \rightarrow x^\gamma`. Parameters ---------- N : int The number of elements of the created lookup table; at least 1. data : (M, 3) array-like or callable Defines the mapping :math:`f`. If a (M, 3) array-like, the rows define values (x, y0, y1). The x values must start with x=0, end with x=1, and all x values be in increasing order. A value between :math:`x_i` and :math:`x_{i+1}` is mapped to the range :math:`y^1_{i-1} \ldots y^0_i` by linear interpolation. For the simple case of a y-continuous mapping, y0 and y1 are identical. The two values of y are to allow for discontinuous mapping functions. E.g. a sawtooth with a period of 0.2 and an amplitude of 1 would be:: [(0, 1, 0), (0.2, 1, 0), (0.4, 1, 0), ..., [(1, 1, 0)] In the special case of ``N == 1``, by convention the returned value is y0 for x == 1. If *data* is a callable, it must accept and return numpy arrays:: data(x : ndarray) -> ndarray and map values between 0 - 1 to 0 - 1. gamma : float Gamma correction factor for input distribution x of the mapping. See also https://en.wikipedia.org/wiki/Gamma_correction. Returns ------- array The lookup table where ``lut[x * (N-1)]`` gives the closest value for values of x between 0 and 1. Notes ----- This function is internally used for `.LinearSegmentedColormap`. |
171,227 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
The provided code snippet includes necessary dependencies for implementing the `rgb_to_hsv` function. Write a Python function `def rgb_to_hsv(arr)` to solve the following problem:
Convert float RGB values (in the range [0, 1]), in a numpy array to HSV values. Parameters ---------- arr : (..., 3) array-like All values must be in the range [0, 1] Returns ------- (..., 3) `~numpy.ndarray` Colors converted to HSV values in range [0, 1]
Here is the function:
def rgb_to_hsv(arr):
"""
Convert float RGB values (in the range [0, 1]), in a numpy array to HSV
values.
Parameters
----------
arr : (..., 3) array-like
All values must be in the range [0, 1]
Returns
-------
(..., 3) `~numpy.ndarray`
Colors converted to HSV values in range [0, 1]
"""
arr = np.asarray(arr)
# check length of the last dimension, should be _some_ sort of rgb
if arr.shape[-1] != 3:
raise ValueError("Last dimension of input array must be 3; "
"shape {} was found.".format(arr.shape))
in_shape = arr.shape
arr = np.array(
arr, copy=False,
dtype=np.promote_types(arr.dtype, np.float32), # Don't work on ints.
ndmin=2, # In case input was 1D.
)
out = np.zeros_like(arr)
arr_max = arr.max(-1)
ipos = arr_max > 0
delta = arr.ptp(-1)
s = np.zeros_like(delta)
s[ipos] = delta[ipos] / arr_max[ipos]
ipos = delta > 0
# red is max
idx = (arr[..., 0] == arr_max) & ipos
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
# green is max
idx = (arr[..., 1] == arr_max) & ipos
out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
# blue is max
idx = (arr[..., 2] == arr_max) & ipos
out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
out[..., 0] = (out[..., 0] / 6.0) % 1.0
out[..., 1] = s
out[..., 2] = arr_max
return out.reshape(in_shape) | Convert float RGB values (in the range [0, 1]), in a numpy array to HSV values. Parameters ---------- arr : (..., 3) array-like All values must be in the range [0, 1] Returns ------- (..., 3) `~numpy.ndarray` Colors converted to HSV values in range [0, 1] |
171,228 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
The provided code snippet includes necessary dependencies for implementing the `hsv_to_rgb` function. Write a Python function `def hsv_to_rgb(hsv)` to solve the following problem:
Convert HSV values to RGB. Parameters ---------- hsv : (..., 3) array-like All values assumed to be in range [0, 1] Returns ------- (..., 3) `~numpy.ndarray` Colors converted to RGB values in range [0, 1]
Here is the function:
def hsv_to_rgb(hsv):
"""
Convert HSV values to RGB.
Parameters
----------
hsv : (..., 3) array-like
All values assumed to be in range [0, 1]
Returns
-------
(..., 3) `~numpy.ndarray`
Colors converted to RGB values in range [0, 1]
"""
hsv = np.asarray(hsv)
# check length of the last dimension, should be _some_ sort of rgb
if hsv.shape[-1] != 3:
raise ValueError("Last dimension of input array must be 3; "
"shape {shp} was found.".format(shp=hsv.shape))
in_shape = hsv.shape
hsv = np.array(
hsv, copy=False,
dtype=np.promote_types(hsv.dtype, np.float32), # Don't work on ints.
ndmin=2, # In case input was 1D.
)
h = hsv[..., 0]
s = hsv[..., 1]
v = hsv[..., 2]
r = np.empty_like(h)
g = np.empty_like(h)
b = np.empty_like(h)
i = (h * 6.0).astype(int)
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
idx = i % 6 == 0
r[idx] = v[idx]
g[idx] = t[idx]
b[idx] = p[idx]
idx = i == 1
r[idx] = q[idx]
g[idx] = v[idx]
b[idx] = p[idx]
idx = i == 2
r[idx] = p[idx]
g[idx] = v[idx]
b[idx] = t[idx]
idx = i == 3
r[idx] = p[idx]
g[idx] = q[idx]
b[idx] = v[idx]
idx = i == 4
r[idx] = t[idx]
g[idx] = p[idx]
b[idx] = v[idx]
idx = i == 5
r[idx] = v[idx]
g[idx] = p[idx]
b[idx] = q[idx]
idx = s == 0
r[idx] = v[idx]
g[idx] = v[idx]
b[idx] = v[idx]
rgb = np.stack([r, g, b], axis=-1)
return rgb.reshape(in_shape) | Convert HSV values to RGB. Parameters ---------- hsv : (..., 3) array-like All values assumed to be in range [0, 1] Returns ------- (..., 3) `~numpy.ndarray` Colors converted to RGB values in range [0, 1] |
171,229 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
def _vector_magnitude(arr):
# things that don't work here:
# * np.linalg.norm: drops mask from ma.array
# * np.sum: drops mask from ma.array unless entire vector is masked
sum_sq = 0
for i in range(arr.shape[-1]):
sum_sq += arr[..., i, np.newaxis] ** 2
return np.sqrt(sum_sq) | null |
171,230 | import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import matplotlib as mpl
import numpy as np
from matplotlib import _api, _cm, cbook, scale
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
class ListedColormap(Colormap):
"""
Colormap object generated from a list of colors.
This may be most useful when indexing directly into a colormap,
but it can also be used to generate special colormaps for ordinary
mapping.
Parameters
----------
colors : list, array
List of Matplotlib color specifications, or an equivalent Nx3 or Nx4
floating point array (*N* RGB or RGBA values).
name : str, optional
String to identify the colormap.
N : int, optional
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.monochrome = False # Are all colors identical? (for contour.py)
if N is None:
self.colors = colors
N = len(colors)
else:
if isinstance(colors, str):
self.colors = [colors] * N
self.monochrome = True
elif np.iterable(colors):
if len(colors) == 1:
self.monochrome = True
self.colors = list(
itertools.islice(itertools.cycle(colors), N))
else:
try:
gray = float(colors)
except TypeError:
pass
else:
self.colors = [gray] * N
self.monochrome = True
super().__init__(name, N)
def _init(self):
self._lut = np.zeros((self.N + 3, 4), float)
self._lut[:-3] = to_rgba_array(self.colors)
self._isinit = True
self._set_extremes()
def resampled(self, lutsize):
"""Return a new colormap with *lutsize* entries."""
colors = self(np.linspace(0, 1, lutsize))
new_cmap = ListedColormap(colors, name=self.name)
# Keep the over/under values too
new_cmap._rgba_over = self._rgba_over
new_cmap._rgba_under = self._rgba_under
new_cmap._rgba_bad = self._rgba_bad
return new_cmap
def reversed(self, name=None):
"""
Return a reversed instance of the Colormap.
Parameters
----------
name : str, optional
The name for the reversed colormap. If None, the
name is set to ``self.name + "_r"``.
Returns
-------
ListedColormap
A reversed instance of the colormap.
"""
if name is None:
name = self.name + "_r"
colors_r = list(reversed(self.colors))
new_cmap = ListedColormap(colors_r, name=name, N=self.N)
# Reverse the over/under values too
new_cmap._rgba_over = self._rgba_under
new_cmap._rgba_under = self._rgba_over
new_cmap._rgba_bad = self._rgba_bad
return new_cmap
class BoundaryNorm(Normalize):
"""
Generate a colormap index based on discrete intervals.
Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
instead of to the interval 0-1.
"""
# Mapping to the 0-1 interval could have been done via piece-wise linear
# interpolation, but using integers seems simpler, and reduces the number
# of conversions back and forth between int and float.
def __init__(self, boundaries, ncolors, clip=False, *, extend='neither'):
"""
Parameters
----------
boundaries : array-like
Monotonically increasing sequence of at least 2 bin edges: data
falling in the n-th bin will be mapped to the n-th color.
ncolors : int
Number of colors in the colormap to be used.
clip : bool, optional
If clip is ``True``, out of range values are mapped to 0 if they
are below ``boundaries[0]`` or mapped to ``ncolors - 1`` if they
are above ``boundaries[-1]``.
If clip is ``False``, out of range values are mapped to -1 if
they are below ``boundaries[0]`` or mapped to *ncolors* if they are
above ``boundaries[-1]``. These are then converted to valid indices
by `Colormap.__call__`.
extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
Extend the number of bins to include one or both of the
regions beyond the boundaries. For example, if ``extend``
is 'min', then the color to which the region between the first
pair of boundaries is mapped will be distinct from the first
color in the colormap, and by default a
`~matplotlib.colorbar.Colorbar` will be drawn with
the triangle extension on the left or lower end.
Notes
-----
If there are fewer bins (including extensions) than colors, then the
color index is chosen by linearly interpolating the ``[0, nbins - 1]``
range onto the ``[0, ncolors - 1]`` range, effectively skipping some
colors in the middle of the colormap.
"""
if clip and extend != 'neither':
raise ValueError("'clip=True' is not compatible with 'extend'")
super().__init__(vmin=boundaries[0], vmax=boundaries[-1], clip=clip)
self.boundaries = np.asarray(boundaries)
self.N = len(self.boundaries)
if self.N < 2:
raise ValueError("You must provide at least 2 boundaries "
f"(1 region) but you passed in {boundaries!r}")
self.Ncmap = ncolors
self.extend = extend
self._scale = None # don't use the default scale.
self._n_regions = self.N - 1 # number of colors needed
self._offset = 0
if extend in ('min', 'both'):
self._n_regions += 1
self._offset = 1
if extend in ('max', 'both'):
self._n_regions += 1
if self._n_regions > self.Ncmap:
raise ValueError(f"There are {self._n_regions} color bins "
"including extensions, but ncolors = "
f"{ncolors}; ncolors must equal or exceed the "
"number of bins")
def __call__(self, value, clip=None):
"""
This method behaves similarly to `.Normalize.__call__`, except that it
returns integers or arrays of int16.
"""
if clip is None:
clip = self.clip
xx, is_scalar = self.process_value(value)
mask = np.ma.getmaskarray(xx)
# Fill masked values a value above the upper boundary
xx = np.atleast_1d(xx.filled(self.vmax + 1))
if clip:
np.clip(xx, self.vmin, self.vmax, out=xx)
max_col = self.Ncmap - 1
else:
max_col = self.Ncmap
# this gives us the bins in the lookup table in the range
# [0, _n_regions - 1] (the offset is set in the init)
iret = np.digitize(xx, self.boundaries) - 1 + self._offset
# if we have more colors than regions, stretch the region
# index computed above to full range of the color bins. This
# will make use of the full range (but skip some of the colors
# in the middle) such that the first region is mapped to the
# first color and the last region is mapped to the last color.
if self.Ncmap > self._n_regions:
if self._n_regions == 1:
# special case the 1 region case, pick the middle color
iret[iret == 0] = (self.Ncmap - 1) // 2
else:
# otherwise linearly remap the values from the region index
# to the color index spaces
iret = (self.Ncmap - 1) / (self._n_regions - 1) * iret
# cast to 16bit integers in all cases
iret = iret.astype(np.int16)
iret[xx < self.vmin] = -1
iret[xx >= self.vmax] = max_col
ret = np.ma.array(iret, mask=mask)
if is_scalar:
ret = int(ret[0]) # assume python scalar
return ret
def inverse(self, value):
"""
Raises
------
ValueError
BoundaryNorm is not invertible, so calling this method will always
raise an error
"""
raise ValueError("BoundaryNorm is not invertible")
The provided code snippet includes necessary dependencies for implementing the `from_levels_and_colors` function. Write a Python function `def from_levels_and_colors(levels, colors, extend='neither')` to solve the following problem:
A helper routine to generate a cmap and a norm instance which behave similar to contourf's levels and colors arguments. Parameters ---------- levels : sequence of numbers The quantization levels used to construct the `BoundaryNorm`. Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``. colors : sequence of colors The fill color to use for each level. If *extend* is "neither" there must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add one extra color, and for an *extend* of "both" add two colors. extend : {'neither', 'min', 'max', 'both'}, optional The behaviour when a value falls out of range of the given levels. See `~.Axes.contourf` for details. Returns ------- cmap : `~matplotlib.colors.Normalize` norm : `~matplotlib.colors.Colormap`
Here is the function:
def from_levels_and_colors(levels, colors, extend='neither'):
"""
A helper routine to generate a cmap and a norm instance which
behave similar to contourf's levels and colors arguments.
Parameters
----------
levels : sequence of numbers
The quantization levels used to construct the `BoundaryNorm`.
Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``.
colors : sequence of colors
The fill color to use for each level. If *extend* is "neither" there
must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add
one extra color, and for an *extend* of "both" add two colors.
extend : {'neither', 'min', 'max', 'both'}, optional
The behaviour when a value falls out of range of the given levels.
See `~.Axes.contourf` for details.
Returns
-------
cmap : `~matplotlib.colors.Normalize`
norm : `~matplotlib.colors.Colormap`
"""
slice_map = {
'both': slice(1, -1),
'min': slice(1, None),
'max': slice(0, -1),
'neither': slice(0, None),
}
_api.check_in_list(slice_map, extend=extend)
color_slice = slice_map[extend]
n_data_colors = len(levels) - 1
n_expected = n_data_colors + color_slice.start - (color_slice.stop or 0)
if len(colors) != n_expected:
raise ValueError(
f'With extend == {extend!r} and {len(levels)} levels, '
f'expected {n_expected} colors, but got {len(colors)}')
cmap = ListedColormap(colors[color_slice], N=n_data_colors)
if extend in ['min', 'both']:
cmap.set_under(colors[0])
else:
cmap.set_under('none')
if extend in ['max', 'both']:
cmap.set_over(colors[-1])
else:
cmap.set_over('none')
cmap.colorbar_extend = extend
norm = BoundaryNorm(levels, ncolors=n_data_colors)
return cmap, norm | A helper routine to generate a cmap and a norm instance which behave similar to contourf's levels and colors arguments. Parameters ---------- levels : sequence of numbers The quantization levels used to construct the `BoundaryNorm`. Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``. colors : sequence of colors The fill color to use for each level. If *extend* is "neither" there must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add one extra color, and for an *extend* of "both" add two colors. extend : {'neither', 'min', 'max', 'both'}, optional The behaviour when a value falls out of range of the given levels. See `~.Axes.contourf` for details. Returns ------- cmap : `~matplotlib.colors.Normalize` norm : `~matplotlib.colors.Colormap` |
171,231 | from io import StringIO
from pathlib import Path
import subprocess
from matplotlib.transforms import TransformNode
class StringIO(TextIOWrapper):
def __init__(self, initial_value: Optional[str] = ..., newline: Optional[str] = ...) -> None: ...
# StringIO does not contain a "name" field. This workaround is necessary
# to allow StringIO sub-classes to add this field, as it is defined
# as a read-only property on IO[].
name: Any
def getvalue(self) -> str: ...
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__(self: _P) -> _P: ...
def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]
) -> Optional[bool]: ...
def cwd(cls: Type[_P]) -> _P: ...
def stat(self) -> os.stat_result: ...
def chmod(self, mode: int) -> None: ...
def exists(self) -> bool: ...
def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def group(self) -> str: ...
def is_dir(self) -> bool: ...
def is_file(self) -> bool: ...
if sys.version_info >= (3, 7):
def is_mount(self) -> bool: ...
def is_symlink(self) -> bool: ...
def is_socket(self) -> bool: ...
def is_fifo(self) -> bool: ...
def is_block_device(self) -> bool: ...
def is_char_device(self) -> bool: ...
def iterdir(self: _P) -> Generator[_P, None, None]: ...
def lchmod(self, mode: int) -> None: ...
def lstat(self) -> os.stat_result: ...
def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ...
# Adapted from builtins.open
# Text mode: always returns a TextIOWrapper
def open(
self,
mode: OpenTextMode = ...,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> TextIOWrapper: ...
# Unbuffered binary mode: returns a FileIO
def open(
self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ...
) -> FileIO: ...
# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter
def open(
self,
mode: OpenBinaryModeUpdating,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedRandom: ...
def open(
self,
mode: OpenBinaryModeWriting,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedWriter: ...
def open(
self,
mode: OpenBinaryModeReading,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedReader: ...
# Buffering cannot be determined: fall back to BinaryIO
def open(
self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ...
) -> BinaryIO: ...
# Fallback if mode is not specified
def open(
self,
mode: str,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> IO[Any]: ...
def owner(self) -> str: ...
if sys.version_info >= (3, 9):
def readlink(self: _P) -> _P: ...
if sys.version_info >= (3, 8):
def rename(self: _P, target: Union[str, PurePath]) -> _P: ...
def replace(self: _P, target: Union[str, PurePath]) -> _P: ...
else:
def rename(self, target: Union[str, PurePath]) -> None: ...
def replace(self, target: Union[str, PurePath]) -> None: ...
def resolve(self: _P, strict: bool = ...) -> _P: ...
def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def rmdir(self) -> None: ...
def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ...
def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ...
if sys.version_info >= (3, 8):
def unlink(self, missing_ok: bool = ...) -> None: ...
else:
def unlink(self) -> None: ...
def home(cls: Type[_P]) -> _P: ...
def absolute(self: _P) -> _P: ...
def expanduser(self: _P) -> _P: ...
def read_bytes(self) -> bytes: ...
def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ...
def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ...
def write_bytes(self, data: bytes) -> int: ...
def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ...
if sys.version_info >= (3, 8):
def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ...
class TransformNode:
"""
The base class for anything that participates in the transform tree
and needs to invalidate its parents or be invalidated. This includes
classes that are not really transforms, such as bounding boxes, since some
transforms depend on bounding boxes to compute their values.
"""
# Invalidation may affect only the affine part. If the
# invalidation was "affine-only", the _invalid member is set to
# INVALID_AFFINE_ONLY
INVALID_NON_AFFINE = 1
INVALID_AFFINE = 2
INVALID = INVALID_NON_AFFINE | INVALID_AFFINE
# Some metadata about the transform, used to determine whether an
# invalidation is affine-only
is_affine = False
is_bbox = False
pass_through = False
"""
If pass_through is True, all ancestors will always be
invalidated, even if 'self' is already invalid.
"""
def __init__(self, shorthand_name=None):
"""
Parameters
----------
shorthand_name : str
A string representing the "name" of the transform. The name carries
no significance other than to improve the readability of
``str(transform)`` when DEBUG=True.
"""
self._parents = {}
# TransformNodes start out as invalid until their values are
# computed for the first time.
self._invalid = 1
self._shorthand_name = shorthand_name or ''
if DEBUG:
def __str__(self):
# either just return the name of this TransformNode, or its repr
return self._shorthand_name or repr(self)
def __getstate__(self):
# turn the dictionary with weak values into a normal dictionary
return {**self.__dict__,
'_parents': {k: v() for k, v in self._parents.items()}}
def __setstate__(self, data_dict):
self.__dict__ = data_dict
# turn the normal dictionary back into a dictionary with weak values
# The extra lambda is to provide a callback to remove dead
# weakrefs from the dictionary when garbage collection is done.
self._parents = {
k: weakref.ref(v, lambda _, pop=self._parents.pop, k=k: pop(k))
for k, v in self._parents.items() if v is not None}
def __copy__(self):
other = copy.copy(super())
# If `c = a + b; a1 = copy(a)`, then modifications to `a1` do not
# propagate back to `c`, i.e. we need to clear the parents of `a1`.
other._parents = {}
# If `c = a + b; c1 = copy(c)`, then modifications to `a` also need to
# be propagated to `c1`.
for key, val in vars(self).items():
if isinstance(val, TransformNode) and id(self) in val._parents:
other.set_children(val) # val == getattr(other, key)
return other
def invalidate(self):
"""
Invalidate this `TransformNode` and triggers an invalidation of its
ancestors. Should be called any time the transform changes.
"""
value = self.INVALID
if self.is_affine:
value = self.INVALID_AFFINE
return self._invalidate_internal(value, invalidating_node=self)
def _invalidate_internal(self, value, invalidating_node):
"""
Called by :meth:`invalidate` and subsequently ascends the transform
stack calling each TransformNode's _invalidate_internal method.
"""
# determine if this call will be an extension to the invalidation
# status. If not, then a shortcut means that we needn't invoke an
# invalidation up the transform stack as it will already have been
# invalidated.
# N.B This makes the invalidation sticky, once a transform has been
# invalidated as NON_AFFINE, then it will always be invalidated as
# NON_AFFINE even when triggered with a AFFINE_ONLY invalidation.
# In most cases this is not a problem (i.e. for interactive panning and
# zooming) and the only side effect will be on performance.
status_changed = self._invalid < value
if self.pass_through or status_changed:
self._invalid = value
for parent in list(self._parents.values()):
# Dereference the weak reference
parent = parent()
if parent is not None:
parent._invalidate_internal(
value=value, invalidating_node=self)
def set_children(self, *children):
"""
Set the children of the transform, to let the invalidation
system know which transforms can invalidate this transform.
Should be called from the constructor of any transforms that
depend on other transforms.
"""
# Parents are stored as weak references, so that if the
# parents are destroyed, references from the children won't
# keep them alive.
for child in children:
# Use weak references so this dictionary won't keep obsolete nodes
# alive; the callback deletes the dictionary entry. This is a
# performance improvement over using WeakValueDictionary.
ref = weakref.ref(
self, lambda _, pop=child._parents.pop, k=id(self): pop(k))
child._parents[id(self)] = ref
def frozen(self):
"""
Return a frozen copy of this transform node. The frozen copy will not
be updated when its children change. Useful for storing a previously
known state of a transform where ``copy.deepcopy()`` might normally be
used.
"""
return self
The provided code snippet includes necessary dependencies for implementing the `graphviz_dump_transform` function. Write a Python function `def graphviz_dump_transform(transform, dest, *, highlight=None)` to solve the following problem:
Generate a graphical representation of the transform tree for *transform* using the :program:`dot` program (which this function depends on). The output format (png, dot, etc.) is determined from the suffix of *dest*. Parameters ---------- transform : `~matplotlib.transform.Transform` The represented transform. dest : str Output filename. The extension must be one of the formats supported by :program:`dot`, e.g. png, svg, dot, ... (see https://www.graphviz.org/doc/info/output.html). highlight : list of `~matplotlib.transform.Transform` or None The transforms in the tree to be drawn in bold. If *None*, *transform* is highlighted.
Here is the function:
def graphviz_dump_transform(transform, dest, *, highlight=None):
"""
Generate a graphical representation of the transform tree for *transform*
using the :program:`dot` program (which this function depends on). The
output format (png, dot, etc.) is determined from the suffix of *dest*.
Parameters
----------
transform : `~matplotlib.transform.Transform`
The represented transform.
dest : str
Output filename. The extension must be one of the formats supported
by :program:`dot`, e.g. png, svg, dot, ...
(see https://www.graphviz.org/doc/info/output.html).
highlight : list of `~matplotlib.transform.Transform` or None
The transforms in the tree to be drawn in bold.
If *None*, *transform* is highlighted.
"""
if highlight is None:
highlight = [transform]
seen = set()
def recurse(root, buf):
if id(root) in seen:
return
seen.add(id(root))
props = {}
label = type(root).__name__
if root._invalid:
label = f'[{label}]'
if root in highlight:
props['style'] = 'bold'
props['shape'] = 'box'
props['label'] = '"%s"' % label
props = ' '.join(map('{0[0]}={0[1]}'.format, props.items()))
buf.write(f'{id(root)} [{props}];\n')
for key, val in vars(root).items():
if isinstance(val, TransformNode) and id(root) in val._parents:
buf.write(f'"{id(root)}" -> "{id(val)}" '
f'[label="{key}", fontsize=10];\n')
recurse(val, buf)
buf = StringIO()
buf.write('digraph G {\n')
recurse(transform, buf)
buf.write('}\n')
subprocess.run(
['dot', '-T', Path(dest).suffix[1:], '-o', dest],
input=buf.getvalue().encode('utf-8'), check=True) | Generate a graphical representation of the transform tree for *transform* using the :program:`dot` program (which this function depends on). The output format (png, dot, etc.) is determined from the suffix of *dest*. Parameters ---------- transform : `~matplotlib.transform.Transform` The represented transform. dest : str Output filename. The extension must be one of the formats supported by :program:`dot`, e.g. png, svg, dot, ... (see https://www.graphviz.org/doc/info/output.html). highlight : list of `~matplotlib.transform.Transform` or None The transforms in the tree to be drawn in bold. If *None*, *transform* is highlighted. |
171,232 | import numpy as np
import matplotlib as mpl
from matplotlib import _api, artist as martist
from matplotlib.font_manager import FontProperties
from matplotlib.transforms import Bbox
The provided code snippet includes necessary dependencies for implementing the `get_subplotspec_list` function. Write a Python function `def get_subplotspec_list(axes_list, grid_spec=None)` to solve the following problem:
Return a list of subplotspec from the given list of axes. For an instance of axes that does not support subplotspec, None is inserted in the list. If grid_spec is given, None is inserted for those not from the given grid_spec.
Here is the function:
def get_subplotspec_list(axes_list, grid_spec=None):
"""
Return a list of subplotspec from the given list of axes.
For an instance of axes that does not support subplotspec, None is inserted
in the list.
If grid_spec is given, None is inserted for those not from the given
grid_spec.
"""
subplotspec_list = []
for ax in axes_list:
axes_or_locator = ax.get_axes_locator()
if axes_or_locator is None:
axes_or_locator = ax
if hasattr(axes_or_locator, "get_subplotspec"):
subplotspec = axes_or_locator.get_subplotspec()
if subplotspec is not None:
subplotspec = subplotspec.get_topmost_subplotspec()
gs = subplotspec.get_gridspec()
if grid_spec is not None:
if gs != grid_spec:
subplotspec = None
elif gs.locally_modified_subplot_params():
subplotspec = None
else:
subplotspec = None
subplotspec_list.append(subplotspec)
return subplotspec_list | Return a list of subplotspec from the given list of axes. For an instance of axes that does not support subplotspec, None is inserted in the list. If grid_spec is given, None is inserted for those not from the given grid_spec. |
171,233 | import numpy as np
import matplotlib as mpl
from matplotlib import _api, artist as martist
from matplotlib.font_manager import FontProperties
from matplotlib.transforms import Bbox
def _auto_adjust_subplotpars(
fig, renderer, shape, span_pairs, subplot_list,
ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None):
"""
Return a dict of subplot parameters to adjust spacing between subplots
or ``None`` if resulting axes would have zero height or width.
Note that this function ignores geometry information of subplot itself, but
uses what is given by the *shape* and *subplot_list* parameters. Also, the
results could be incorrect if some subplots have ``adjustable=datalim``.
Parameters
----------
shape : tuple[int, int]
Number of rows and columns of the grid.
span_pairs : list[tuple[slice, slice]]
List of rowspans and colspans occupied by each subplot.
subplot_list : list of subplots
List of subplots that will be used to calculate optimal subplot_params.
pad : float
Padding between the figure edge and the edges of subplots, as a
fraction of the font size.
h_pad, w_pad : float
Padding (height/width) between edges of adjacent subplots, as a
fraction of the font size. Defaults to *pad*.
rect : tuple
(left, bottom, right, top), default: None.
"""
rows, cols = shape
font_size_inch = (FontProperties(
size=mpl.rcParams["font.size"]).get_size_in_points() / 72)
pad_inch = pad * font_size_inch
vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch
hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch
if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0:
raise ValueError
if rect is None:
margin_left = margin_bottom = margin_right = margin_top = None
else:
margin_left, margin_bottom, _right, _top = rect
margin_right = 1 - _right if _right else None
margin_top = 1 - _top if _top else None
vspaces = np.zeros((rows + 1, cols))
hspaces = np.zeros((rows, cols + 1))
if ax_bbox_list is None:
ax_bbox_list = [
Bbox.union([ax.get_position(original=True) for ax in subplots])
for subplots in subplot_list]
for subplots, ax_bbox, (rowspan, colspan) in zip(
subplot_list, ax_bbox_list, span_pairs):
if all(not ax.get_visible() for ax in subplots):
continue
bb = []
for ax in subplots:
if ax.get_visible():
bb += [martist._get_tightbbox_for_layout_only(ax, renderer)]
tight_bbox_raw = Bbox.union(bb)
tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw)
hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l
hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r
vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t
vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b
fig_width_inch, fig_height_inch = fig.get_size_inches()
# margins can be negative for axes with aspect applied, so use max(, 0) to
# make them nonnegative.
if not margin_left:
margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch
suplabel = fig._supylabel
if suplabel and suplabel.get_in_layout():
rel_width = fig.transFigure.inverted().transform_bbox(
suplabel.get_window_extent(renderer)).width
margin_left += rel_width + pad_inch/fig_width_inch
if not margin_right:
margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch
if not margin_top:
margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch
if fig._suptitle and fig._suptitle.get_in_layout():
rel_height = fig.transFigure.inverted().transform_bbox(
fig._suptitle.get_window_extent(renderer)).height
margin_top += rel_height + pad_inch/fig_height_inch
if not margin_bottom:
margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch
suplabel = fig._supxlabel
if suplabel and suplabel.get_in_layout():
rel_height = fig.transFigure.inverted().transform_bbox(
suplabel.get_window_extent(renderer)).height
margin_bottom += rel_height + pad_inch/fig_height_inch
if margin_left + margin_right >= 1:
_api.warn_external('Tight layout not applied. The left and right '
'margins cannot be made large enough to '
'accommodate all axes decorations.')
return None
if margin_bottom + margin_top >= 1:
_api.warn_external('Tight layout not applied. The bottom and top '
'margins cannot be made large enough to '
'accommodate all axes decorations.')
return None
kwargs = dict(left=margin_left,
right=1 - margin_right,
bottom=margin_bottom,
top=1 - margin_top)
if cols > 1:
hspace = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch
# axes widths:
h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols
if h_axes < 0:
_api.warn_external('Tight layout not applied. tight_layout '
'cannot make axes width small enough to '
'accommodate all axes decorations')
return None
else:
kwargs["wspace"] = hspace / h_axes
if rows > 1:
vspace = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch
v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows
if v_axes < 0:
_api.warn_external('Tight layout not applied. tight_layout '
'cannot make axes height small enough to '
'accommodate all axes decorations.')
return None
else:
kwargs["hspace"] = vspace / v_axes
return kwargs
The provided code snippet includes necessary dependencies for implementing the `get_tight_layout_figure` function. Write a Python function `def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, pad=1.08, h_pad=None, w_pad=None, rect=None)` to solve the following problem:
Return subplot parameters for tight-layouted-figure with specified padding. Parameters ---------- fig : Figure axes_list : list of Axes subplotspec_list : list of `.SubplotSpec` The subplotspecs of each axes. renderer : renderer pad : float Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float Padding (height/width) between edges of adjacent subplots. Defaults to *pad*. rect : tuple (left, bottom, right, top), default: None. rectangle in normalized figure coordinates that the whole subplots area (including labels) will fit into. Defaults to using the entire figure. Returns ------- subplotspec or None subplotspec kwargs to be passed to `.Figure.subplots_adjust` or None if tight_layout could not be accomplished.
Here is the function:
def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,
pad=1.08, h_pad=None, w_pad=None, rect=None):
"""
Return subplot parameters for tight-layouted-figure with specified padding.
Parameters
----------
fig : Figure
axes_list : list of Axes
subplotspec_list : list of `.SubplotSpec`
The subplotspecs of each axes.
renderer : renderer
pad : float
Padding between the figure edge and the edges of subplots, as a
fraction of the font size.
h_pad, w_pad : float
Padding (height/width) between edges of adjacent subplots. Defaults to
*pad*.
rect : tuple (left, bottom, right, top), default: None.
rectangle in normalized figure coordinates
that the whole subplots area (including labels) will fit into.
Defaults to using the entire figure.
Returns
-------
subplotspec or None
subplotspec kwargs to be passed to `.Figure.subplots_adjust` or
None if tight_layout could not be accomplished.
"""
# Multiple axes can share same subplotspec (e.g., if using axes_grid1);
# we need to group them together.
ss_to_subplots = {ss: [] for ss in subplotspec_list}
for ax, ss in zip(axes_list, subplotspec_list):
ss_to_subplots[ss].append(ax)
if ss_to_subplots.pop(None, None):
_api.warn_external(
"This figure includes Axes that are not compatible with "
"tight_layout, so results might be incorrect.")
if not ss_to_subplots:
return {}
subplot_list = list(ss_to_subplots.values())
ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots]
max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots)
max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots)
span_pairs = []
for ss in ss_to_subplots:
# The intent here is to support axes from different gridspecs where
# one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4),
# but this doesn't actually work because the computed wspace, in
# relative-axes-height, corresponds to different physical spacings for
# the 2-row grid and the 4-row grid. Still, this code is left, mostly
# for backcompat.
rows, cols = ss.get_gridspec().get_geometry()
div_row, mod_row = divmod(max_nrows, rows)
div_col, mod_col = divmod(max_ncols, cols)
if mod_row != 0:
_api.warn_external('tight_layout not applied: number of rows '
'in subplot specifications must be '
'multiples of one another.')
return {}
if mod_col != 0:
_api.warn_external('tight_layout not applied: number of '
'columns in subplot specifications must be '
'multiples of one another.')
return {}
span_pairs.append((
slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row),
slice(ss.colspan.start * div_col, ss.colspan.stop * div_col)))
kwargs = _auto_adjust_subplotpars(fig, renderer,
shape=(max_nrows, max_ncols),
span_pairs=span_pairs,
subplot_list=subplot_list,
ax_bbox_list=ax_bbox_list,
pad=pad, h_pad=h_pad, w_pad=w_pad)
# kwargs can be none if tight_layout fails...
if rect is not None and kwargs is not None:
# if rect is given, the whole subplots area (including
# labels) will fit into the rect instead of the
# figure. Note that the rect argument of
# *auto_adjust_subplotpars* specify the area that will be
# covered by the total area of axes.bbox. Thus we call
# auto_adjust_subplotpars twice, where the second run
# with adjusted rect parameters.
left, bottom, right, top = rect
if left is not None:
left += kwargs["left"]
if bottom is not None:
bottom += kwargs["bottom"]
if right is not None:
right -= (1 - kwargs["right"])
if top is not None:
top -= (1 - kwargs["top"])
kwargs = _auto_adjust_subplotpars(fig, renderer,
shape=(max_nrows, max_ncols),
span_pairs=span_pairs,
subplot_list=subplot_list,
ax_bbox_list=ax_bbox_list,
pad=pad, h_pad=h_pad, w_pad=w_pad,
rect=(left, bottom, right, top))
return kwargs | Return subplot parameters for tight-layouted-figure with specified padding. Parameters ---------- fig : Figure axes_list : list of Axes subplotspec_list : list of `.SubplotSpec` The subplotspecs of each axes. renderer : renderer pad : float Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float Padding (height/width) between edges of adjacent subplots. Defaults to *pad*. rect : tuple (left, bottom, right, top), default: None. rectangle in normalized figure coordinates that the whole subplots area (including labels) will fit into. Defaults to using the entire figure. Returns ------- subplotspec or None subplotspec kwargs to be passed to `.Figure.subplots_adjust` or None if tight_layout could not be accomplished. |
171,234 | import contextlib
import functools
import inspect
import math
import warnings
def warn_deprecated(
since, *, message='', name='', alternative='', pending=False,
obj_type='', addendum='', removal=''):
"""
Display a standardized deprecation.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The ``%(since)s``,
``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``,
and ``%(removal)s`` format specifiers will be replaced by the values
of the respective arguments passed to this function.
name : str, optional
The name of the deprecated object.
alternative : str, optional
An alternative API that the user may use in place of the deprecated
API. The deprecation warning will tell the user about this alternative
if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with *removal*.
obj_type : str, optional
The object type being deprecated.
addendum : str, optional
Additional text appended directly to the final message.
removal : str, optional
The expected removal version. With the default (an empty string), a
removal version is automatically computed from *since*. Set to other
Falsy values to not schedule a removal date. Cannot be used together
with *pending*.
Examples
--------
::
# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',
obj_type='module')
"""
warning = _generate_deprecation_warning(
since, message, name, alternative, pending, obj_type, addendum,
removal=removal)
from . import warn_external
warn_external(warning, category=MatplotlibDeprecationWarning)
class classproperty:
"""
Like `property`, but also triggers on access via the class, and it is the
*class* that's passed as argument.
Examples
--------
::
class C:
def foo(cls):
return cls.__name__
assert C.foo == "C"
"""
def __init__(self, fget, fset=None, fdel=None, doc=None):
self._fget = fget
if fset is not None or fdel is not None:
raise ValueError('classproperty only implements fget.')
self.fset = fset
self.fdel = fdel
# docs are ignored for now
self._doc = doc
def __get__(self, instance, owner):
return self._fget(owner)
def fget(self):
return self._fget
The provided code snippet includes necessary dependencies for implementing the `deprecated` function. Write a Python function `def deprecated(since, *, message='', name='', alternative='', pending=False, obj_type=None, addendum='', removal='')` to solve the following problem:
Decorator to mark a function, a class, or a property as deprecated. When deprecating a classmethod, a staticmethod, or a property, the ``@deprecated`` decorator should go *under* ``@classmethod`` and ``@staticmethod`` (i.e., `deprecated` should directly decorate the underlying callable), but *over* ``@property``. When deprecating a class ``C`` intended to be used as a base class in a multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method (if ``C`` instead inherited its ``__init__`` from its own base class, then ``@deprecated`` would mess up ``__init__`` inheritance when installing its own (deprecation-emitting) ``C.__init__``). Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to 'class' if decorating a class, 'attribute' if decorating a property, and 'function' otherwise. Examples -------- :: @deprecated('1.4.0') def the_function_to_deprecate(): pass
Here is the function:
def deprecated(since, *, message='', name='', alternative='', pending=False,
obj_type=None, addendum='', removal=''):
"""
Decorator to mark a function, a class, or a property as deprecated.
When deprecating a classmethod, a staticmethod, or a property, the
``@deprecated`` decorator should go *under* ``@classmethod`` and
``@staticmethod`` (i.e., `deprecated` should directly decorate the
underlying callable), but *over* ``@property``.
When deprecating a class ``C`` intended to be used as a base class in a
multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method
(if ``C`` instead inherited its ``__init__`` from its own base class, then
``@deprecated`` would mess up ``__init__`` inheritance when installing its
own (deprecation-emitting) ``C.__init__``).
Parameters are the same as for `warn_deprecated`, except that *obj_type*
defaults to 'class' if decorating a class, 'attribute' if decorating a
property, and 'function' otherwise.
Examples
--------
::
@deprecated('1.4.0')
def the_function_to_deprecate():
pass
"""
def deprecate(obj, message=message, name=name, alternative=alternative,
pending=pending, obj_type=obj_type, addendum=addendum):
from matplotlib._api import classproperty
if isinstance(obj, type):
if obj_type is None:
obj_type = "class"
func = obj.__init__
name = name or obj.__name__
old_doc = obj.__doc__
def finalize(wrapper, new_doc):
try:
obj.__doc__ = new_doc
except AttributeError: # Can't set on some extension objects.
pass
obj.__init__ = functools.wraps(obj.__init__)(wrapper)
return obj
elif isinstance(obj, (property, classproperty)):
if obj_type is None:
obj_type = "attribute"
func = None
name = name or obj.fget.__name__
old_doc = obj.__doc__
class _deprecated_property(type(obj)):
def __get__(self, instance, owner=None):
if instance is not None or owner is not None \
and isinstance(self, classproperty):
emit_warning()
return super().__get__(instance, owner)
def __set__(self, instance, value):
if instance is not None:
emit_warning()
return super().__set__(instance, value)
def __delete__(self, instance):
if instance is not None:
emit_warning()
return super().__delete__(instance)
def __set_name__(self, owner, set_name):
nonlocal name
if name == "<lambda>":
name = set_name
def finalize(_, new_doc):
return _deprecated_property(
fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc)
else:
if obj_type is None:
obj_type = "function"
func = obj
name = name or obj.__name__
old_doc = func.__doc__
def finalize(wrapper, new_doc):
wrapper = functools.wraps(func)(wrapper)
wrapper.__doc__ = new_doc
return wrapper
def emit_warning():
warn_deprecated(
since, message=message, name=name, alternative=alternative,
pending=pending, obj_type=obj_type, addendum=addendum,
removal=removal)
def wrapper(*args, **kwargs):
emit_warning()
return func(*args, **kwargs)
old_doc = inspect.cleandoc(old_doc or '').strip('\n')
notes_header = '\nNotes\n-----'
second_arg = ' '.join([t.strip() for t in
(message, f"Use {alternative} instead."
if alternative else "", addendum) if t])
new_doc = (f"[*Deprecated*] {old_doc}\n"
f"{notes_header if notes_header not in old_doc else ''}\n"
f".. deprecated:: {since}\n"
f" {second_arg}")
if not old_doc:
# This is to prevent a spurious 'unexpected unindent' warning from
# docutils when the original docstring was blank.
new_doc += r'\ '
return finalize(wrapper, new_doc)
return deprecate | Decorator to mark a function, a class, or a property as deprecated. When deprecating a classmethod, a staticmethod, or a property, the ``@deprecated`` decorator should go *under* ``@classmethod`` and ``@staticmethod`` (i.e., `deprecated` should directly decorate the underlying callable), but *over* ``@property``. When deprecating a class ``C`` intended to be used as a base class in a multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method (if ``C`` instead inherited its ``__init__`` from its own base class, then ``@deprecated`` would mess up ``__init__`` inheritance when installing its own (deprecation-emitting) ``C.__init__``). Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to 'class' if decorating a class, 'attribute' if decorating a property, and 'function' otherwise. Examples -------- :: @deprecated('1.4.0') def the_function_to_deprecate(): pass |
171,235 | import contextlib
import functools
import inspect
import math
import warnings
def warn_deprecated(
since, *, message='', name='', alternative='', pending=False,
obj_type='', addendum='', removal=''):
"""
Display a standardized deprecation.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The ``%(since)s``,
``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``,
and ``%(removal)s`` format specifiers will be replaced by the values
of the respective arguments passed to this function.
name : str, optional
The name of the deprecated object.
alternative : str, optional
An alternative API that the user may use in place of the deprecated
API. The deprecation warning will tell the user about this alternative
if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with *removal*.
obj_type : str, optional
The object type being deprecated.
addendum : str, optional
Additional text appended directly to the final message.
removal : str, optional
The expected removal version. With the default (an empty string), a
removal version is automatically computed from *since*. Set to other
Falsy values to not schedule a removal date. Cannot be used together
with *pending*.
Examples
--------
::
# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',
obj_type='module')
"""
warning = _generate_deprecation_warning(
since, message, name, alternative, pending, obj_type, addendum,
removal=removal)
from . import warn_external
warn_external(warning, category=MatplotlibDeprecationWarning)
DECORATORS = {}
The provided code snippet includes necessary dependencies for implementing the `rename_parameter` function. Write a Python function `def rename_parameter(since, old, new, func=None)` to solve the following problem:
Decorator indicating that parameter *old* of *func* is renamed to *new*. The actual implementation of *func* should use *new*, not *old*. If *old* is passed to *func*, a DeprecationWarning is emitted, and its value is used, even if *new* is also passed by keyword (this is to simplify pyplot wrapper functions, which always pass *new* explicitly to the Axes method). If *new* is also passed but positionally, a TypeError will be raised by the underlying function during argument binding. Examples -------- :: @_api.rename_parameter("3.1", "bad_name", "good_name") def func(good_name): ...
Here is the function:
def rename_parameter(since, old, new, func=None):
"""
Decorator indicating that parameter *old* of *func* is renamed to *new*.
The actual implementation of *func* should use *new*, not *old*. If *old*
is passed to *func*, a DeprecationWarning is emitted, and its value is
used, even if *new* is also passed by keyword (this is to simplify pyplot
wrapper functions, which always pass *new* explicitly to the Axes method).
If *new* is also passed but positionally, a TypeError will be raised by the
underlying function during argument binding.
Examples
--------
::
@_api.rename_parameter("3.1", "bad_name", "good_name")
def func(good_name): ...
"""
decorator = functools.partial(rename_parameter, since, old, new)
if func is None:
return decorator
signature = inspect.signature(func)
assert old not in signature.parameters, (
f"Matplotlib internal error: {old!r} cannot be a parameter for "
f"{func.__name__}()")
assert new in signature.parameters, (
f"Matplotlib internal error: {new!r} must be a parameter for "
f"{func.__name__}()")
@functools.wraps(func)
def wrapper(*args, **kwargs):
if old in kwargs:
warn_deprecated(
since, message=f"The {old!r} parameter of {func.__name__}() "
f"has been renamed {new!r} since Matplotlib {since}; support "
f"for the old name will be dropped %(removal)s.")
kwargs[new] = kwargs.pop(old)
return func(*args, **kwargs)
# wrapper() must keep the same documented signature as func(): if we
# instead made both *old* and *new* appear in wrapper()'s signature, they
# would both show up in the pyplot function for an Axes method as well and
# pyplot would explicitly pass both arguments to the Axes method.
DECORATORS[wrapper] = decorator
return wrapper | Decorator indicating that parameter *old* of *func* is renamed to *new*. The actual implementation of *func* should use *new*, not *old*. If *old* is passed to *func*, a DeprecationWarning is emitted, and its value is used, even if *new* is also passed by keyword (this is to simplify pyplot wrapper functions, which always pass *new* explicitly to the Axes method). If *new* is also passed but positionally, a TypeError will be raised by the underlying function during argument binding. Examples -------- :: @_api.rename_parameter("3.1", "bad_name", "good_name") def func(good_name): ... |
171,236 | import contextlib
import functools
import inspect
import math
import warnings
def warn_deprecated(
since, *, message='', name='', alternative='', pending=False,
obj_type='', addendum='', removal=''):
"""
Display a standardized deprecation.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The ``%(since)s``,
``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``,
and ``%(removal)s`` format specifiers will be replaced by the values
of the respective arguments passed to this function.
name : str, optional
The name of the deprecated object.
alternative : str, optional
An alternative API that the user may use in place of the deprecated
API. The deprecation warning will tell the user about this alternative
if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with *removal*.
obj_type : str, optional
The object type being deprecated.
addendum : str, optional
Additional text appended directly to the final message.
removal : str, optional
The expected removal version. With the default (an empty string), a
removal version is automatically computed from *since*. Set to other
Falsy values to not schedule a removal date. Cannot be used together
with *pending*.
Examples
--------
::
# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',
obj_type='module')
"""
warning = _generate_deprecation_warning(
since, message, name, alternative, pending, obj_type, addendum,
removal=removal)
from . import warn_external
warn_external(warning, category=MatplotlibDeprecationWarning)
DECORATORS = {}
_deprecated_parameter = _deprecated_parameter_class()
The provided code snippet includes necessary dependencies for implementing the `delete_parameter` function. Write a Python function `def delete_parameter(since, name, func=None, **kwargs)` to solve the following problem:
Decorator indicating that parameter *name* of *func* is being deprecated. The actual implementation of *func* should keep the *name* parameter in its signature, or accept a ``**kwargs`` argument (through which *name* would be passed). Parameters that come after the deprecated parameter effectively become keyword-only (as they cannot be passed positionally without triggering the DeprecationWarning on the deprecated parameter), and should be marked as such after the deprecation period has passed and the deprecated parameter is removed. Parameters other than *since*, *name*, and *func* are keyword-only and forwarded to `.warn_deprecated`. Examples -------- :: @_api.delete_parameter("3.1", "unused") def func(used_arg, other_arg, unused, more_args): ...
Here is the function:
def delete_parameter(since, name, func=None, **kwargs):
"""
Decorator indicating that parameter *name* of *func* is being deprecated.
The actual implementation of *func* should keep the *name* parameter in its
signature, or accept a ``**kwargs`` argument (through which *name* would be
passed).
Parameters that come after the deprecated parameter effectively become
keyword-only (as they cannot be passed positionally without triggering the
DeprecationWarning on the deprecated parameter), and should be marked as
such after the deprecation period has passed and the deprecated parameter
is removed.
Parameters other than *since*, *name*, and *func* are keyword-only and
forwarded to `.warn_deprecated`.
Examples
--------
::
@_api.delete_parameter("3.1", "unused")
def func(used_arg, other_arg, unused, more_args): ...
"""
decorator = functools.partial(delete_parameter, since, name, **kwargs)
if func is None:
return decorator
signature = inspect.signature(func)
# Name of `**kwargs` parameter of the decorated function, typically
# "kwargs" if such a parameter exists, or None if the decorated function
# doesn't accept `**kwargs`.
kwargs_name = next((param.name for param in signature.parameters.values()
if param.kind == inspect.Parameter.VAR_KEYWORD), None)
if name in signature.parameters:
kind = signature.parameters[name].kind
is_varargs = kind is inspect.Parameter.VAR_POSITIONAL
is_varkwargs = kind is inspect.Parameter.VAR_KEYWORD
if not is_varargs and not is_varkwargs:
name_idx = (
# Deprecated parameter can't be passed positionally.
math.inf if kind is inspect.Parameter.KEYWORD_ONLY
# If call site has no more than this number of parameters, the
# deprecated parameter can't have been passed positionally.
else [*signature.parameters].index(name))
func.__signature__ = signature = signature.replace(parameters=[
param.replace(default=_deprecated_parameter)
if param.name == name else param
for param in signature.parameters.values()])
else:
name_idx = -1 # Deprecated parameter can always have been passed.
else:
is_varargs = is_varkwargs = False
# Deprecated parameter can't be passed positionally.
name_idx = math.inf
assert kwargs_name, (
f"Matplotlib internal error: {name!r} must be a parameter for "
f"{func.__name__}()")
addendum = kwargs.pop('addendum', None)
@functools.wraps(func)
def wrapper(*inner_args, **inner_kwargs):
if len(inner_args) <= name_idx and name not in inner_kwargs:
# Early return in the simple, non-deprecated case (much faster than
# calling bind()).
return func(*inner_args, **inner_kwargs)
arguments = signature.bind(*inner_args, **inner_kwargs).arguments
if is_varargs and arguments.get(name):
warn_deprecated(
since, message=f"Additional positional arguments to "
f"{func.__name__}() are deprecated since %(since)s and "
f"support for them will be removed %(removal)s.")
elif is_varkwargs and arguments.get(name):
warn_deprecated(
since, message=f"Additional keyword arguments to "
f"{func.__name__}() are deprecated since %(since)s and "
f"support for them will be removed %(removal)s.")
# We cannot just check `name not in arguments` because the pyplot
# wrappers always pass all arguments explicitly.
elif any(name in d and d[name] != _deprecated_parameter
for d in [arguments, arguments.get(kwargs_name, {})]):
deprecation_addendum = (
f"If any parameter follows {name!r}, they should be passed as "
f"keyword, not positionally.")
warn_deprecated(
since,
name=repr(name),
obj_type=f"parameter of {func.__name__}()",
addendum=(addendum + " " + deprecation_addendum) if addendum
else deprecation_addendum,
**kwargs)
return func(*inner_args, **inner_kwargs)
DECORATORS[wrapper] = decorator
return wrapper | Decorator indicating that parameter *name* of *func* is being deprecated. The actual implementation of *func* should keep the *name* parameter in its signature, or accept a ``**kwargs`` argument (through which *name* would be passed). Parameters that come after the deprecated parameter effectively become keyword-only (as they cannot be passed positionally without triggering the DeprecationWarning on the deprecated parameter), and should be marked as such after the deprecation period has passed and the deprecated parameter is removed. Parameters other than *since*, *name*, and *func* are keyword-only and forwarded to `.warn_deprecated`. Examples -------- :: @_api.delete_parameter("3.1", "unused") def func(used_arg, other_arg, unused, more_args): ... |
171,237 | import contextlib
import functools
import inspect
import math
import warnings
def warn_deprecated(
since, *, message='', name='', alternative='', pending=False,
obj_type='', addendum='', removal=''):
"""
Display a standardized deprecation.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The ``%(since)s``,
``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``,
and ``%(removal)s`` format specifiers will be replaced by the values
of the respective arguments passed to this function.
name : str, optional
The name of the deprecated object.
alternative : str, optional
An alternative API that the user may use in place of the deprecated
API. The deprecation warning will tell the user about this alternative
if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with *removal*.
obj_type : str, optional
The object type being deprecated.
addendum : str, optional
Additional text appended directly to the final message.
removal : str, optional
The expected removal version. With the default (an empty string), a
removal version is automatically computed from *since*. Set to other
Falsy values to not schedule a removal date. Cannot be used together
with *pending*.
Examples
--------
::
# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',
obj_type='module')
"""
warning = _generate_deprecation_warning(
since, message, name, alternative, pending, obj_type, addendum,
removal=removal)
from . import warn_external
warn_external(warning, category=MatplotlibDeprecationWarning)
DECORATORS = {}
The provided code snippet includes necessary dependencies for implementing the `make_keyword_only` function. Write a Python function `def make_keyword_only(since, name, func=None)` to solve the following problem:
Decorator indicating that passing parameter *name* (or any of the following ones) positionally to *func* is being deprecated. When used on a method that has a pyplot wrapper, this should be the outermost decorator, so that :file:`boilerplate.py` can access the original signature.
Here is the function:
def make_keyword_only(since, name, func=None):
"""
Decorator indicating that passing parameter *name* (or any of the following
ones) positionally to *func* is being deprecated.
When used on a method that has a pyplot wrapper, this should be the
outermost decorator, so that :file:`boilerplate.py` can access the original
signature.
"""
decorator = functools.partial(make_keyword_only, since, name)
if func is None:
return decorator
signature = inspect.signature(func)
POK = inspect.Parameter.POSITIONAL_OR_KEYWORD
KWO = inspect.Parameter.KEYWORD_ONLY
assert (name in signature.parameters
and signature.parameters[name].kind == POK), (
f"Matplotlib internal error: {name!r} must be a positional-or-keyword "
f"parameter for {func.__name__}()")
names = [*signature.parameters]
name_idx = names.index(name)
kwonly = [name for name in names[name_idx:]
if signature.parameters[name].kind == POK]
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Don't use signature.bind here, as it would fail when stacked with
# rename_parameter and an "old" argument name is passed in
# (signature.bind would fail, but the actual call would succeed).
if len(args) > name_idx:
warn_deprecated(
since, message="Passing the %(name)s %(obj_type)s "
"positionally is deprecated since Matplotlib %(since)s; the "
"parameter will become keyword-only %(removal)s.",
name=name, obj_type=f"parameter of {func.__name__}()")
return func(*args, **kwargs)
# Don't modify *func*'s signature, as boilerplate.py needs it.
wrapper.__signature__ = signature.replace(parameters=[
param.replace(kind=KWO) if param.name in kwonly else param
for param in signature.parameters.values()])
DECORATORS[wrapper] = decorator
return wrapper | Decorator indicating that passing parameter *name* (or any of the following ones) positionally to *func* is being deprecated. When used on a method that has a pyplot wrapper, this should be the outermost decorator, so that :file:`boilerplate.py` can access the original signature. |
171,238 | import contextlib
import functools
import inspect
import math
import warnings
def warn_deprecated(
since, *, message='', name='', alternative='', pending=False,
obj_type='', addendum='', removal=''):
"""
Display a standardized deprecation.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The ``%(since)s``,
``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``,
and ``%(removal)s`` format specifiers will be replaced by the values
of the respective arguments passed to this function.
name : str, optional
The name of the deprecated object.
alternative : str, optional
An alternative API that the user may use in place of the deprecated
API. The deprecation warning will tell the user about this alternative
if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with *removal*.
obj_type : str, optional
The object type being deprecated.
addendum : str, optional
Additional text appended directly to the final message.
removal : str, optional
The expected removal version. With the default (an empty string), a
removal version is automatically computed from *since*. Set to other
Falsy values to not schedule a removal date. Cannot be used together
with *pending*.
Examples
--------
::
# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',
obj_type='module')
"""
warning = _generate_deprecation_warning(
since, message, name, alternative, pending, obj_type, addendum,
removal=removal)
from . import warn_external
warn_external(warning, category=MatplotlibDeprecationWarning)
The provided code snippet includes necessary dependencies for implementing the `deprecate_method_override` function. Write a Python function `def deprecate_method_override(method, obj, *, allow_empty=False, **kwargs)` to solve the following problem:
Return ``obj.method`` with a deprecation if it was overridden, else None. Parameters ---------- method An unbound method, i.e. an expression of the form ``Class.method_name``. Remember that within the body of a method, one can always use ``__class__`` to refer to the class that is currently being defined. obj Either an object of the class where *method* is defined, or a subclass of that class. allow_empty : bool, default: False Whether to allow overrides by "empty" methods without emitting a warning. **kwargs Additional parameters passed to `warn_deprecated` to generate the deprecation warning; must at least include the "since" key.
Here is the function:
def deprecate_method_override(method, obj, *, allow_empty=False, **kwargs):
"""
Return ``obj.method`` with a deprecation if it was overridden, else None.
Parameters
----------
method
An unbound method, i.e. an expression of the form
``Class.method_name``. Remember that within the body of a method, one
can always use ``__class__`` to refer to the class that is currently
being defined.
obj
Either an object of the class where *method* is defined, or a subclass
of that class.
allow_empty : bool, default: False
Whether to allow overrides by "empty" methods without emitting a
warning.
**kwargs
Additional parameters passed to `warn_deprecated` to generate the
deprecation warning; must at least include the "since" key.
"""
def empty(): pass
def empty_with_docstring(): """doc"""
name = method.__name__
bound_child = getattr(obj, name)
bound_base = (
method # If obj is a class, then we need to use unbound methods.
if isinstance(bound_child, type(empty)) and isinstance(obj, type)
else method.__get__(obj))
if (bound_child != bound_base
and (not allow_empty
or (getattr(getattr(bound_child, "__code__", None),
"co_code", None)
not in [empty.__code__.co_code,
empty_with_docstring.__code__.co_code]))):
warn_deprecated(**{"name": name, "obj_type": "method", **kwargs})
return bound_child
return None | Return ``obj.method`` with a deprecation if it was overridden, else None. Parameters ---------- method An unbound method, i.e. an expression of the form ``Class.method_name``. Remember that within the body of a method, one can always use ``__class__`` to refer to the class that is currently being defined. obj Either an object of the class where *method* is defined, or a subclass of that class. allow_empty : bool, default: False Whether to allow overrides by "empty" methods without emitting a warning. **kwargs Additional parameters passed to `warn_deprecated` to generate the deprecation warning; must at least include the "since" key. |
171,239 | import contextlib
import functools
import inspect
import math
import warnings
class MatplotlibDeprecationWarning(DeprecationWarning):
"""A class for issuing deprecation warnings for Matplotlib users."""
def suppress_matplotlib_deprecation_warning():
with warnings.catch_warnings():
warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
yield | null |
171,240 | import contextlib
import doctest
from io import StringIO
import itertools
import os
from os.path import relpath
from pathlib import Path
import re
import shutil
import sys
import textwrap
import traceback
from docutils.parsers.rst import directives, Directive
from docutils.parsers.rst.directives.images import Image
import jinja2
import matplotlib
from matplotlib.backend_bases import FigureManagerBase
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers, cbook
def _option_boolean(arg):
if not arg or not arg.strip():
# no argument given, assume used as a flag
return True
elif arg.strip().lower() in ('no', '0', 'false'):
return False
elif arg.strip().lower() in ('yes', '1', 'true'):
return True
else:
raise ValueError(f'{arg!r} unknown boolean') | null |
171,241 | import contextlib
import doctest
from io import StringIO
import itertools
import os
from os.path import relpath
from pathlib import Path
import re
import shutil
import sys
import textwrap
import traceback
from docutils.parsers.rst import directives, Directive
from docutils.parsers.rst.directives.images import Image
import jinja2
import matplotlib
from matplotlib.backend_bases import FigureManagerBase
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers, cbook
def _option_context(arg):
if arg in [None, 'reset', 'close-figs']:
return arg
raise ValueError("Argument should be None or 'reset' or 'close-figs'") | null |
171,242 | import contextlib
import doctest
from io import StringIO
import itertools
import os
from os.path import relpath
from pathlib import Path
import re
import shutil
import sys
import textwrap
import traceback
from docutils.parsers.rst import directives, Directive
from docutils.parsers.rst.directives.images import Image
import jinja2
import matplotlib
from matplotlib.backend_bases import FigureManagerBase
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers, cbook
def _option_format(arg):
return directives.choice(arg, ('python', 'doctest')) | null |
171,243 | import contextlib
import doctest
from io import StringIO
import itertools
import os
from os.path import relpath
from pathlib import Path
import re
import shutil
import sys
import textwrap
import traceback
from docutils.parsers.rst import directives, Directive
from docutils.parsers.rst.directives.images import Image
import jinja2
import matplotlib
from matplotlib.backend_bases import FigureManagerBase
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers, cbook
def setup(app):
setup.app = app
setup.config = app.config
setup.confdir = app.confdir
app.add_directive('plot', PlotDirective)
app.add_config_value('plot_pre_code', None, True)
app.add_config_value('plot_include_source', False, True)
app.add_config_value('plot_html_show_source_link', True, True)
app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
app.add_config_value('plot_basedir', None, True)
app.add_config_value('plot_html_show_formats', True, True)
app.add_config_value('plot_rcparams', {}, True)
app.add_config_value('plot_apply_rcparams', False, True)
app.add_config_value('plot_working_directory', None, True)
app.add_config_value('plot_template', None, True)
app.connect('doctree-read', mark_plot_labels)
app.add_css_file('plot_directive.css')
app.connect('build-finished', _copy_css_file)
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,
'version': matplotlib.__version__}
return metadata
def contains_doctest(text):
try:
# check if it's valid Python as-is
compile(text, '<string>', 'exec')
return False
except SyntaxError:
pass
r = re.compile(r'^\s*>>>', re.M)
m = r.search(text)
return bool(m)
TEMPLATE = """
{{ source_code }}
.. only:: html
{% if src_name or (html_show_formats and not multi_image) %}
(
{%- if src_name -%}
:download:`Source code <{{ build_dir }}/{{ src_name }}>`
{%- endif -%}
{%- if html_show_formats and not multi_image -%}
{%- for img in images -%}
{%- for fmt in img.formats -%}
{%- if src_name or not loop.first -%}, {% endif -%}
:download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`
{%- endfor -%}
{%- endfor -%}
{%- endif -%}
)
{% endif %}
{% for img in images %}
.. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
{% for option in options -%}
{{ option }}
{% endfor %}
{% if html_show_formats and multi_image -%}
(
{%- for fmt in img.formats -%}
{%- if not loop.first -%}, {% endif -%}
:download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`
{%- endfor -%}
)
{%- endif -%}
{{ caption }} {# appropriate leading whitespace added beforehand #}
{% endfor %}
.. only:: not html
{% for img in images %}
.. figure:: {{ build_dir }}/{{ img.basename }}.*
{% for option in options -%}
{{ option }}
{% endfor -%}
{{ caption }} {# appropriate leading whitespace added beforehand #}
{% endfor %}
"""
class PlotError(RuntimeError):
pass
def get_plot_formats(config):
default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}
formats = []
plot_formats = config.plot_formats
for fmt in plot_formats:
if isinstance(fmt, str):
if ':' in fmt:
suffix, dpi = fmt.split(':')
formats.append((str(suffix), int(dpi)))
else:
formats.append((fmt, default_dpi.get(fmt, 80)))
elif isinstance(fmt, (tuple, list)) and len(fmt) == 2:
formats.append((str(fmt[0]), int(fmt[1])))
else:
raise PlotError('invalid image format "%r" in plot_formats' % fmt)
return formats
def render_figures(code, code_path, output_dir, output_base, context,
function_name, config, context_reset=False,
close_figs=False,
code_includes=None):
"""
Run a pyplot script and save the images in *output_dir*.
Save the images under *output_dir* with file names derived from
*output_base*
"""
if function_name is not None:
output_base = f'{output_base}_{function_name}'
formats = get_plot_formats(config)
# Try to determine if all images already exist
is_doctest, code_pieces = _split_code_at_show(code, function_name)
# Look for single-figure output files first
img = ImageFile(output_base, output_dir)
for format, dpi in formats:
if context or out_of_date(code_path, img.filename(format),
includes=code_includes):
all_exists = False
break
img.formats.append(format)
else:
all_exists = True
if all_exists:
return [(code, [img])]
# Then look for multi-figure output files
results = []
for i, code_piece in enumerate(code_pieces):
images = []
for j in itertools.count():
if len(code_pieces) > 1:
img = ImageFile('%s_%02d_%02d' % (output_base, i, j),
output_dir)
else:
img = ImageFile('%s_%02d' % (output_base, j), output_dir)
for fmt, dpi in formats:
if context or out_of_date(code_path, img.filename(fmt),
includes=code_includes):
all_exists = False
break
img.formats.append(fmt)
# assume that if we have one, we have them all
if not all_exists:
all_exists = (j > 0)
break
images.append(img)
if not all_exists:
break
results.append((code_piece, images))
else:
all_exists = True
if all_exists:
return results
# We didn't find the files, so build them
results = []
ns = plot_context if context else {}
if context_reset:
clear_state(config.plot_rcparams)
plot_context.clear()
close_figs = not context or close_figs
for i, code_piece in enumerate(code_pieces):
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams, close_figs)
elif close_figs:
plt.close('all')
_run_code(doctest.script_from_examples(code_piece) if is_doctest
else code_piece,
code_path, ns, function_name)
images = []
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
for j, figman in enumerate(fig_managers):
if len(fig_managers) == 1 and len(code_pieces) == 1:
img = ImageFile(output_base, output_dir)
elif len(code_pieces) == 1:
img = ImageFile("%s_%02d" % (output_base, j), output_dir)
else:
img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
output_dir)
images.append(img)
for fmt, dpi in formats:
try:
figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi)
except Exception as err:
raise PlotError(traceback.format_exc()) from err
img.formats.append(fmt)
results.append((code_piece, images))
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams, close=not context)
return results
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__(self: _P) -> _P: ...
def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]
) -> Optional[bool]: ...
def cwd(cls: Type[_P]) -> _P: ...
def stat(self) -> os.stat_result: ...
def chmod(self, mode: int) -> None: ...
def exists(self) -> bool: ...
def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def group(self) -> str: ...
def is_dir(self) -> bool: ...
def is_file(self) -> bool: ...
if sys.version_info >= (3, 7):
def is_mount(self) -> bool: ...
def is_symlink(self) -> bool: ...
def is_socket(self) -> bool: ...
def is_fifo(self) -> bool: ...
def is_block_device(self) -> bool: ...
def is_char_device(self) -> bool: ...
def iterdir(self: _P) -> Generator[_P, None, None]: ...
def lchmod(self, mode: int) -> None: ...
def lstat(self) -> os.stat_result: ...
def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ...
# Adapted from builtins.open
# Text mode: always returns a TextIOWrapper
def open(
self,
mode: OpenTextMode = ...,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> TextIOWrapper: ...
# Unbuffered binary mode: returns a FileIO
def open(
self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ...
) -> FileIO: ...
# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter
def open(
self,
mode: OpenBinaryModeUpdating,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedRandom: ...
def open(
self,
mode: OpenBinaryModeWriting,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedWriter: ...
def open(
self,
mode: OpenBinaryModeReading,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedReader: ...
# Buffering cannot be determined: fall back to BinaryIO
def open(
self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ...
) -> BinaryIO: ...
# Fallback if mode is not specified
def open(
self,
mode: str,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> IO[Any]: ...
def owner(self) -> str: ...
if sys.version_info >= (3, 9):
def readlink(self: _P) -> _P: ...
if sys.version_info >= (3, 8):
def rename(self: _P, target: Union[str, PurePath]) -> _P: ...
def replace(self: _P, target: Union[str, PurePath]) -> _P: ...
else:
def rename(self, target: Union[str, PurePath]) -> None: ...
def replace(self, target: Union[str, PurePath]) -> None: ...
def resolve(self: _P, strict: bool = ...) -> _P: ...
def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def rmdir(self) -> None: ...
def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ...
def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ...
if sys.version_info >= (3, 8):
def unlink(self, missing_ok: bool = ...) -> None: ...
else:
def unlink(self) -> None: ...
def home(cls: Type[_P]) -> _P: ...
def absolute(self: _P) -> _P: ...
def expanduser(self: _P) -> _P: ...
def read_bytes(self) -> bytes: ...
def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ...
def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ...
def write_bytes(self, data: bytes) -> int: ...
def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ...
if sys.version_info >= (3, 8):
def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ...
def run(arguments, content, options, state_machine, state, lineno):
document = state_machine.document
config = document.settings.env.config
nofigs = 'nofigs' in options
formats = get_plot_formats(config)
default_fmt = formats[0][0]
options.setdefault('include-source', config.plot_include_source)
options.setdefault('show-source-link', config.plot_html_show_source_link)
if 'class' in options:
# classes are parsed into a list of string, and output by simply
# printing the list, abusing the fact that RST guarantees to strip
# non-conforming characters
options['class'] = ['plot-directive'] + options['class']
else:
options.setdefault('class', ['plot-directive'])
keep_context = 'context' in options
context_opt = None if not keep_context else options['context']
rst_file = document.attributes['source']
rst_dir = os.path.dirname(rst_file)
if len(arguments):
if not config.plot_basedir:
source_file_name = os.path.join(setup.app.builder.srcdir,
directives.uri(arguments[0]))
else:
source_file_name = os.path.join(setup.confdir, config.plot_basedir,
directives.uri(arguments[0]))
# If there is content, it will be passed as a caption.
caption = '\n'.join(content)
# Enforce unambiguous use of captions.
if "caption" in options:
if caption:
raise ValueError(
'Caption specified in both content and options.'
' Please remove ambiguity.'
)
# Use caption option
caption = options["caption"]
# If the optional function name is provided, use it
if len(arguments) == 2:
function_name = arguments[1]
else:
function_name = None
code = Path(source_file_name).read_text(encoding='utf-8')
output_base = os.path.basename(source_file_name)
else:
source_file_name = rst_file
code = textwrap.dedent("\n".join(map(str, content)))
counter = document.attributes.get('_plot_counter', 0) + 1
document.attributes['_plot_counter'] = counter
base, ext = os.path.splitext(os.path.basename(source_file_name))
output_base = '%s-%d.py' % (base, counter)
function_name = None
caption = options.get('caption', '')
base, source_ext = os.path.splitext(output_base)
if source_ext in ('.py', '.rst', '.txt'):
output_base = base
else:
source_ext = ''
# ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
output_base = output_base.replace('.', '-')
# is it in doctest format?
is_doctest = contains_doctest(code)
if 'format' in options:
if options['format'] == 'python':
is_doctest = False
else:
is_doctest = True
# determine output directory name fragment
source_rel_name = relpath(source_file_name, setup.confdir)
source_rel_dir = os.path.dirname(source_rel_name).lstrip(os.path.sep)
# build_dir: where to place output files (temporarily)
build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
'plot_directive',
source_rel_dir)
# get rid of .. in paths, also changes pathsep
# see note in Python docs for warning about symbolic links on Windows.
# need to compare source and dest paths at end
build_dir = os.path.normpath(build_dir)
os.makedirs(build_dir, exist_ok=True)
# how to link to files from the RST file
try:
build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
except ValueError:
# on Windows, relpath raises ValueError when path and start are on
# different mounts/drives
build_dir_link = build_dir
# get list of included rst files so that the output is updated when any
# plots in the included files change. These attributes are modified by the
# include directive (see the docutils.parsers.rst.directives.misc module).
try:
source_file_includes = [os.path.join(os.getcwd(), t[0])
for t in state.document.include_log]
except AttributeError:
# the document.include_log attribute only exists in docutils >=0.17,
# before that we need to inspect the state machine
possible_sources = {os.path.join(setup.confdir, t[0])
for t in state_machine.input_lines.items}
source_file_includes = [f for f in possible_sources
if os.path.isfile(f)]
# remove the source file itself from the includes
try:
source_file_includes.remove(source_file_name)
except ValueError:
pass
# save script (if necessary)
if options['show-source-link']:
Path(build_dir, output_base + source_ext).write_text(
doctest.script_from_examples(code)
if source_file_name == rst_file and is_doctest
else code,
encoding='utf-8')
# make figures
try:
results = render_figures(code=code,
code_path=source_file_name,
output_dir=build_dir,
output_base=output_base,
context=keep_context,
function_name=function_name,
config=config,
context_reset=context_opt == 'reset',
close_figs=context_opt == 'close-figs',
code_includes=source_file_includes)
errors = []
except PlotError as err:
reporter = state.memo.reporter
sm = reporter.system_message(
2, "Exception occurred in plotting {}\n from {}:\n{}".format(
output_base, source_file_name, err),
line=lineno)
results = [(code, [])]
errors = [sm]
# Properly indent the caption
caption = '\n' + '\n'.join(' ' + line.strip()
for line in caption.split('\n'))
# generate output restructuredtext
total_lines = []
for j, (code_piece, images) in enumerate(results):
if options['include-source']:
if is_doctest:
lines = ['', *code_piece.splitlines()]
else:
lines = ['.. code-block:: python', '',
*textwrap.indent(code_piece, ' ').splitlines()]
source_code = "\n".join(lines)
else:
source_code = ""
if nofigs:
images = []
opts = [
':%s: %s' % (key, val) for key, val in options.items()
if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]
# Not-None src_name signals the need for a source download in the
# generated html
if j == 0 and options['show-source-link']:
src_name = output_base + source_ext
else:
src_name = None
result = jinja2.Template(config.plot_template or TEMPLATE).render(
default_fmt=default_fmt,
build_dir=build_dir_link,
src_name=src_name,
multi_image=len(images) > 1,
options=opts,
images=images,
source_code=source_code,
html_show_formats=config.plot_html_show_formats and len(images),
caption=caption)
total_lines.extend(result.split("\n"))
total_lines.extend("\n")
if total_lines:
state_machine.insert_input(total_lines, source=source_file_name)
return errors | null |
171,244 | import hashlib
from pathlib import Path
from docutils import nodes
from docutils.parsers.rst import Directive, directives
import sphinx
from sphinx.errors import ConfigError, ExtensionError
import matplotlib as mpl
from matplotlib import _api, mathtext
from matplotlib.rcsetup import validate_float_or_None
def fontset_choice(arg):
return directives.choice(arg, mathtext.MathTextParser._font_type_mapping) | null |
171,245 | import enum
import functools
import re
import time
from types import SimpleNamespace
import uuid
from weakref import WeakKeyDictionary
import numpy as np
import matplotlib as mpl
from matplotlib._pylab_helpers import Gcf
from matplotlib import _api, cbook
_tool_registry = set()
The provided code snippet includes necessary dependencies for implementing the `_register_tool_class` function. Write a Python function `def _register_tool_class(canvas_cls, tool_cls=None)` to solve the following problem:
Decorator registering *tool_cls* as a tool class for *canvas_cls*.
Here is the function:
def _register_tool_class(canvas_cls, tool_cls=None):
"""Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
if tool_cls is None:
return functools.partial(_register_tool_class, canvas_cls)
_tool_registry.add((canvas_cls, tool_cls))
return tool_cls | Decorator registering *tool_cls* as a tool class for *canvas_cls*. |
171,246 | import enum
import functools
import re
import time
from types import SimpleNamespace
import uuid
from weakref import WeakKeyDictionary
import numpy as np
import matplotlib as mpl
from matplotlib._pylab_helpers import Gcf
from matplotlib import _api, cbook
_tool_registry = set()
The provided code snippet includes necessary dependencies for implementing the `_find_tool_class` function. Write a Python function `def _find_tool_class(canvas_cls, tool_cls)` to solve the following problem:
Find a subclass of *tool_cls* registered for *canvas_cls*.
Here is the function:
def _find_tool_class(canvas_cls, tool_cls):
"""Find a subclass of *tool_cls* registered for *canvas_cls*."""
for canvas_parent in canvas_cls.__mro__:
for tool_child in _api.recursive_subclasses(tool_cls):
if (canvas_parent, tool_child) in _tool_registry:
return tool_child
return tool_cls | Find a subclass of *tool_cls* registered for *canvas_cls*. |
171,247 | import enum
import functools
import re
import time
from types import SimpleNamespace
import uuid
from weakref import WeakKeyDictionary
import numpy as np
import matplotlib as mpl
from matplotlib._pylab_helpers import Gcf
from matplotlib import _api, cbook
default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
'zoom': ToolZoom, 'pan': ToolPan,
'subplots': ConfigureSubplotsBase,
'save': SaveFigureBase,
'grid': ToolGrid,
'grid_minor': ToolMinorGrid,
'fullscreen': ToolFullScreen,
'quit': ToolQuit,
'quit_all': ToolQuitAll,
'xscale': ToolXScale,
'yscale': ToolYScale,
'position': ToolCursorPosition,
_views_positions: ToolViewsPositions,
'cursor': ToolSetCursor,
'rubberband': RubberbandBase,
'help': ToolHelpBase,
'copy': ToolCopyToClipboardBase,
}
The provided code snippet includes necessary dependencies for implementing the `add_tools_to_manager` function. Write a Python function `def add_tools_to_manager(toolmanager, tools=default_tools)` to solve the following problem:
Add multiple tools to a `.ToolManager`. Parameters ---------- toolmanager : `.backend_managers.ToolManager` Manager to which the tools are added. tools : {str: class_like}, optional The tools to add in a {name: tool} dict, see `.backend_managers.ToolManager.add_tool` for more info.
Here is the function:
def add_tools_to_manager(toolmanager, tools=default_tools):
"""
Add multiple tools to a `.ToolManager`.
Parameters
----------
toolmanager : `.backend_managers.ToolManager`
Manager to which the tools are added.
tools : {str: class_like}, optional
The tools to add in a {name: tool} dict, see
`.backend_managers.ToolManager.add_tool` for more info.
"""
for name, tool in tools.items():
toolmanager.add_tool(name, tool) | Add multiple tools to a `.ToolManager`. Parameters ---------- toolmanager : `.backend_managers.ToolManager` Manager to which the tools are added. tools : {str: class_like}, optional The tools to add in a {name: tool} dict, see `.backend_managers.ToolManager.add_tool` for more info. |
171,248 | import enum
import functools
import re
import time
from types import SimpleNamespace
import uuid
from weakref import WeakKeyDictionary
import numpy as np
import matplotlib as mpl
from matplotlib._pylab_helpers import Gcf
from matplotlib import _api, cbook
default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
['zoompan', ['pan', 'zoom', 'subplots']],
['io', ['save', 'help']]]
The provided code snippet includes necessary dependencies for implementing the `add_tools_to_container` function. Write a Python function `def add_tools_to_container(container, tools=default_toolbar_tools)` to solve the following problem:
Add multiple tools to the container. Parameters ---------- container : Container `.backend_bases.ToolContainerBase` object that will get the tools added. tools : list, optional List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]`` where the tools ``[tool1, tool2, ...]`` will display in group1. See `.backend_bases.ToolContainerBase.add_tool` for details.
Here is the function:
def add_tools_to_container(container, tools=default_toolbar_tools):
"""
Add multiple tools to the container.
Parameters
----------
container : Container
`.backend_bases.ToolContainerBase` object that will get the tools
added.
tools : list, optional
List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
where the tools ``[tool1, tool2, ...]`` will display in group1.
See `.backend_bases.ToolContainerBase.add_tool` for details.
"""
for group, grouptools in tools:
for position, tool in enumerate(grouptools):
container.add_tool(tool, group, position) | Add multiple tools to the container. Parameters ---------- container : Container `.backend_bases.ToolContainerBase` object that will get the tools added. tools : list, optional List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]`` where the tools ``[tool1, tool2, ...]`` will display in group1. See `.backend_bases.ToolContainerBase.add_tool` for details. |
171,249 | import numpy as np
from matplotlib import _api
from matplotlib.collections import PolyCollection, TriMesh
from matplotlib.colors import Normalize
from matplotlib.tri._triangulation import Triangulation
"antialiased": ["antialiaseds", "aa"],
"edgecolor": ["edgecolors", "ec"],
"facecolor": ["facecolors", "fc"],
"linestyle": ["linestyles", "dashes", "ls"],
"linewidth": ["linewidths", "lw"],
"offset_transform": ["transOffset"],
})
class PolyCollection(_CollectionWithSizes):
def __init__(self, verts, sizes=None, closed=True, **kwargs):
"""
Parameters
----------
verts : list of array-like
The sequence of polygons [*verts0*, *verts1*, ...] where each
element *verts_i* defines the vertices of polygon *i* as a 2D
array-like of shape (M, 2).
sizes : array-like, default: None
Squared scaling factors for the polygons. The coordinates of each
polygon *verts_i* are multiplied by the square-root of the
corresponding entry in *sizes* (i.e., *sizes* specify the scaling
of areas). The scaling is applied before the Artist master
transform.
closed : bool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY
connection at the end.
**kwargs
Forwarded to `.Collection`.
"""
super().__init__(**kwargs)
self.set_sizes(sizes)
self.set_verts(verts, closed)
self.stale = True
def set_verts(self, verts, closed=True):
"""
Set the vertices of the polygons.
Parameters
----------
verts : list of array-like
The sequence of polygons [*verts0*, *verts1*, ...] where each
element *verts_i* defines the vertices of polygon *i* as a 2D
array-like of shape (M, 2).
closed : bool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY
connection at the end.
"""
self.stale = True
if isinstance(verts, np.ma.MaskedArray):
verts = verts.astype(float).filled(np.nan)
# No need to do anything fancy if the path isn't closed.
if not closed:
self._paths = [mpath.Path(xy) for xy in verts]
return
# Fast path for arrays
if isinstance(verts, np.ndarray) and len(verts.shape) == 3:
verts_pad = np.concatenate((verts, verts[:, :1]), axis=1)
# Creating the codes once is much faster than having Path do it
# separately each time by passing closed=True.
codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type)
codes[:] = mpath.Path.LINETO
codes[0] = mpath.Path.MOVETO
codes[-1] = mpath.Path.CLOSEPOLY
self._paths = [mpath.Path(xy, codes) for xy in verts_pad]
return
self._paths = []
for xy in verts:
if len(xy):
self._paths.append(mpath.Path._create_closed(xy))
else:
self._paths.append(mpath.Path(xy))
set_paths = set_verts
def set_verts_and_codes(self, verts, codes):
"""Initialize vertices with path codes."""
if len(verts) != len(codes):
raise ValueError("'codes' must be a 1D list or array "
"with the same length of 'verts'")
self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy)
for xy, cds in zip(verts, codes)]
self.stale = True
def span_where(cls, x, ymin, ymax, where, **kwargs):
"""
Return a `.BrokenBarHCollection` that plots horizontal bars from
over the regions in *x* where *where* is True. The bars range
on the y-axis from *ymin* to *ymax*
*kwargs* are passed on to the collection.
"""
xranges = []
for ind0, ind1 in cbook.contiguous_regions(where):
xslice = x[ind0:ind1]
if not len(xslice):
continue
xranges.append((xslice[0], xslice[-1] - xslice[0]))
return BrokenBarHCollection(xranges, [ymin, ymax - ymin], **kwargs)
class TriMesh(Collection):
"""
Class for the efficient drawing of a triangular mesh using Gouraud shading.
A triangular mesh is a `~matplotlib.tri.Triangulation` object.
"""
def __init__(self, triangulation, **kwargs):
super().__init__(**kwargs)
self._triangulation = triangulation
self._shading = 'gouraud'
self._bbox = transforms.Bbox.unit()
# Unfortunately this requires a copy, unless Triangulation
# was rewritten.
xy = np.hstack((triangulation.x.reshape(-1, 1),
triangulation.y.reshape(-1, 1)))
self._bbox.update_from_data_xy(xy)
def get_paths(self):
if self._paths is None:
self.set_paths()
return self._paths
def set_paths(self):
self._paths = self.convert_mesh_to_paths(self._triangulation)
def convert_mesh_to_paths(tri):
"""
Convert a given mesh into a sequence of `.Path` objects.
This function is primarily of use to implementers of backends that do
not directly support meshes.
"""
triangles = tri.get_masked_triangles()
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
return [mpath.Path(x) for x in verts]
def draw(self, renderer):
if not self.get_visible():
return
renderer.open_group(self.__class__.__name__, gid=self.get_gid())
transform = self.get_transform()
# Get a list of triangles and the color at each vertex.
tri = self._triangulation
triangles = tri.get_masked_triangles()
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
self.update_scalarmappable()
colors = self._facecolors[triangles]
gc = renderer.new_gc()
self._set_gc_clip(gc)
gc.set_linewidth(self.get_linewidth()[0])
renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
gc.restore()
renderer.close_group(self.__class__.__name__)
class Normalize:
"""
A class which, when called, linearly normalizes data into the
``[0.0, 1.0]`` interval.
"""
def __init__(self, vmin=None, vmax=None, clip=False):
"""
Parameters
----------
vmin, vmax : float or None
If *vmin* and/or *vmax* is not given, they are initialized from the
minimum and maximum value, respectively, of the first input
processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
clip : bool, default: False
If ``True`` values falling outside the range ``[vmin, vmax]``,
are mapped to 0 or 1, whichever is closer, and masked values are
set to 1. If ``False`` masked values remain masked.
Clipping silently defeats the purpose of setting the over, under,
and masked colors in a colormap, so it is likely to lead to
surprises; therefore the default is ``clip=False``.
Notes
-----
Returns 0 if ``vmin == vmax``.
"""
self._vmin = _sanitize_extrema(vmin)
self._vmax = _sanitize_extrema(vmax)
self._clip = clip
self._scale = None
self.callbacks = cbook.CallbackRegistry(signals=["changed"])
def vmin(self):
return self._vmin
def vmin(self, value):
value = _sanitize_extrema(value)
if value != self._vmin:
self._vmin = value
self._changed()
def vmax(self):
return self._vmax
def vmax(self, value):
value = _sanitize_extrema(value)
if value != self._vmax:
self._vmax = value
self._changed()
def clip(self):
return self._clip
def clip(self, value):
if value != self._clip:
self._clip = value
self._changed()
def _changed(self):
"""
Call this whenever the norm is changed to notify all the
callback listeners to the 'changed' signal.
"""
self.callbacks.process('changed')
def process_value(value):
"""
Homogenize the input *value* for easy and efficient normalization.
*value* can be a scalar or sequence.
Returns
-------
result : masked array
Masked array with the same shape as *value*.
is_scalar : bool
Whether *value* is a scalar.
Notes
-----
Float dtypes are preserved; integer types with two bytes or smaller are
converted to np.float32, and larger types are converted to np.float64.
Preserving float32 when possible, and using in-place operations,
greatly improves speed for large arrays.
"""
is_scalar = not np.iterable(value)
if is_scalar:
value = [value]
dtype = np.min_scalar_type(value)
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
# bool_/int8/int16 -> float32; int32/int64 -> float64
dtype = np.promote_types(dtype, np.float32)
# ensure data passed in as an ndarray subclass are interpreted as
# an ndarray. See issue #6622.
mask = np.ma.getmask(value)
data = np.asarray(value)
result = np.ma.array(data, mask=mask, dtype=dtype, copy=True)
return result, is_scalar
def __call__(self, value, clip=None):
"""
Normalize *value* data in the ``[vmin, vmax]`` interval into the
``[0.0, 1.0]`` interval and return it.
Parameters
----------
value
Data to normalize.
clip : bool, optional
If ``None``, defaults to ``self.clip`` (which defaults to
``False``).
Notes
-----
If not already initialized, ``self.vmin`` and ``self.vmax`` are
initialized using ``self.autoscale_None(value)``.
"""
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
if self.vmin is None or self.vmax is None:
self.autoscale_None(result)
# Convert at least to float, without losing precision.
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if vmin == vmax:
result.fill(0) # Or should it be all masked? Or 0.5?
elif vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
mask=mask)
# ma division is very slow; we can take a shortcut
resdat = result.data
resdat -= vmin
resdat /= (vmax - vmin)
result = np.ma.array(resdat, mask=result.mask, copy=False)
if is_scalar:
result = result[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until both vmin and vmax are set")
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if np.iterable(value):
val = np.ma.asarray(value)
return vmin + val * (vmax - vmin)
else:
return vmin + value * (vmax - vmin)
def autoscale(self, A):
"""Set *vmin*, *vmax* to min, max of *A*."""
with self.callbacks.blocked():
# Pause callbacks while we are updating so we only get
# a single update signal at the end
self.vmin = self.vmax = None
self.autoscale_None(A)
self._changed()
def autoscale_None(self, A):
"""If vmin or vmax are not set, use the min/max of *A* to set them."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
def scaled(self):
"""Return whether vmin and vmax are set."""
return self.vmin is not None and self.vmax is not None
class Triangulation:
"""
An unstructured triangular grid consisting of npoints points and
ntri triangles. The triangles can either be specified by the user
or automatically generated using a Delaunay triangulation.
Parameters
----------
x, y : (npoints,) array-like
Coordinates of grid points.
triangles : (ntri, 3) array-like of int, optional
For each triangle, the indices of the three points that make
up the triangle, ordered in an anticlockwise manner. If not
specified, the Delaunay triangulation is calculated.
mask : (ntri,) array-like of bool, optional
Which triangles are masked out.
Attributes
----------
triangles : (ntri, 3) array of int
For each triangle, the indices of the three points that make
up the triangle, ordered in an anticlockwise manner. If you want to
take the *mask* into account, use `get_masked_triangles` instead.
mask : (ntri, 3) array of bool
Masked out triangles.
is_delaunay : bool
Whether the Triangulation is a calculated Delaunay
triangulation (where *triangles* was not specified) or not.
Notes
-----
For a Triangulation to be valid it must not have duplicate points,
triangles formed from colinear points, or overlapping triangles.
"""
def __init__(self, x, y, triangles=None, mask=None):
from matplotlib import _qhull
self.x = np.asarray(x, dtype=np.float64)
self.y = np.asarray(y, dtype=np.float64)
if self.x.shape != self.y.shape or self.x.ndim != 1:
raise ValueError("x and y must be equal-length 1D arrays, but "
f"found shapes {self.x.shape!r} and "
f"{self.y.shape!r}")
self.mask = None
self._edges = None
self._neighbors = None
self.is_delaunay = False
if triangles is None:
# No triangulation specified, so use matplotlib._qhull to obtain
# Delaunay triangulation.
self.triangles, self._neighbors = _qhull.delaunay(x, y)
self.is_delaunay = True
else:
# Triangulation specified. Copy, since we may correct triangle
# orientation.
try:
self.triangles = np.array(triangles, dtype=np.int32, order='C')
except ValueError as e:
raise ValueError('triangles must be a (N, 3) int array, not '
f'{triangles!r}') from e
if self.triangles.ndim != 2 or self.triangles.shape[1] != 3:
raise ValueError(
'triangles must be a (N, 3) int array, but found shape '
f'{self.triangles.shape!r}')
if self.triangles.max() >= len(self.x):
raise ValueError(
'triangles are indices into the points and must be in the '
f'range 0 <= i < {len(self.x)} but found value '
f'{self.triangles.max()}')
if self.triangles.min() < 0:
raise ValueError(
'triangles are indices into the points and must be in the '
f'range 0 <= i < {len(self.x)} but found value '
f'{self.triangles.min()}')
# Underlying C++ object is not created until first needed.
self._cpp_triangulation = None
# Default TriFinder not created until needed.
self._trifinder = None
self.set_mask(mask)
def calculate_plane_coefficients(self, z):
"""
Calculate plane equation coefficients for all unmasked triangles from
the point (x, y) coordinates and specified z-array of shape (npoints).
The returned array has shape (npoints, 3) and allows z-value at (x, y)
position in triangle tri to be calculated using
``z = array[tri, 0] * x + array[tri, 1] * y + array[tri, 2]``.
"""
return self.get_cpp_triangulation().calculate_plane_coefficients(z)
def edges(self):
"""
Return integer array of shape (nedges, 2) containing all edges of
non-masked triangles.
Each row defines an edge by its start point index and end point
index. Each edge appears only once, i.e. for an edge between points
*i* and *j*, there will only be either *(i, j)* or *(j, i)*.
"""
if self._edges is None:
self._edges = self.get_cpp_triangulation().get_edges()
return self._edges
def get_cpp_triangulation(self):
"""
Return the underlying C++ Triangulation object, creating it
if necessary.
"""
from matplotlib import _tri
if self._cpp_triangulation is None:
self._cpp_triangulation = _tri.Triangulation(
# For unset arrays use empty tuple which has size of zero.
self.x, self.y, self.triangles,
self.mask if self.mask is not None else (),
self._edges if self._edges is not None else (),
self._neighbors if self._neighbors is not None else (),
not self.is_delaunay)
return self._cpp_triangulation
def get_masked_triangles(self):
"""
Return an array of triangles taking the mask into account.
"""
if self.mask is not None:
return self.triangles[~self.mask]
else:
return self.triangles
def get_from_args_and_kwargs(*args, **kwargs):
"""
Return a Triangulation object from the args and kwargs, and
the remaining args and kwargs with the consumed values removed.
There are two alternatives: either the first argument is a
Triangulation object, in which case it is returned, or the args
and kwargs are sufficient to create a new Triangulation to
return. In the latter case, see Triangulation.__init__ for
the possible args and kwargs.
"""
if isinstance(args[0], Triangulation):
triangulation, *args = args
if 'triangles' in kwargs:
_api.warn_external(
"Passing the keyword 'triangles' has no effect when also "
"passing a Triangulation")
if 'mask' in kwargs:
_api.warn_external(
"Passing the keyword 'mask' has no effect when also "
"passing a Triangulation")
else:
x, y, triangles, mask, args, kwargs = \
Triangulation._extract_triangulation_params(args, kwargs)
triangulation = Triangulation(x, y, triangles, mask)
return triangulation, args, kwargs
def _extract_triangulation_params(args, kwargs):
x, y, *args = args
# Check triangles in kwargs then args.
triangles = kwargs.pop('triangles', None)
from_args = False
if triangles is None and args:
triangles = args[0]
from_args = True
if triangles is not None:
try:
triangles = np.asarray(triangles, dtype=np.int32)
except ValueError:
triangles = None
if triangles is not None and (triangles.ndim != 2 or
triangles.shape[1] != 3):
triangles = None
if triangles is not None and from_args:
args = args[1:] # Consumed first item in args.
# Check for mask in kwargs.
mask = kwargs.pop('mask', None)
return x, y, triangles, mask, args, kwargs
def get_trifinder(self):
"""
Return the default `matplotlib.tri.TriFinder` of this
triangulation, creating it if necessary. This allows the same
TriFinder object to be easily shared.
"""
if self._trifinder is None:
# Default TriFinder class.
from matplotlib.tri._trifinder import TrapezoidMapTriFinder
self._trifinder = TrapezoidMapTriFinder(self)
return self._trifinder
def neighbors(self):
"""
Return integer array of shape (ntri, 3) containing neighbor triangles.
For each triangle, the indices of the three triangles that
share the same edges, or -1 if there is no such neighboring
triangle. ``neighbors[i, j]`` is the triangle that is the neighbor
to the edge from point index ``triangles[i, j]`` to point index
``triangles[i, (j+1)%3]``.
"""
if self._neighbors is None:
self._neighbors = self.get_cpp_triangulation().get_neighbors()
return self._neighbors
def set_mask(self, mask):
"""
Set or clear the mask array.
Parameters
----------
mask : None or bool array of length ntri
"""
if mask is None:
self.mask = None
else:
self.mask = np.asarray(mask, dtype=bool)
if self.mask.shape != (self.triangles.shape[0],):
raise ValueError('mask array must have same length as '
'triangles array')
# Set mask in C++ Triangulation.
if self._cpp_triangulation is not None:
self._cpp_triangulation.set_mask(
self.mask if self.mask is not None else ())
# Clear derived fields so they are recalculated when needed.
self._edges = None
self._neighbors = None
# Recalculate TriFinder if it exists.
if self._trifinder is not None:
self._trifinder._initialize()
The provided code snippet includes necessary dependencies for implementing the `tripcolor` function. Write a Python function `def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, shading='flat', facecolors=None, **kwargs)` to solve the following problem:
Create a pseudocolor plot of an unstructured triangular grid. Call signatures:: tripcolor(triangulation, c, *, ...) tripcolor(x, y, c, *, [triangles=triangles], [mask=mask], ...) The triangular grid can be specified either by passing a `.Triangulation` object as the first parameter, or by passing the points *x*, *y* and optionally the *triangles* and a *mask*. See `.Triangulation` for an explanation of these parameters. It is possible to pass the triangles positionally, i.e. ``tripcolor(x, y, triangles, c, ...)``. However, this is discouraged. For more clarity, pass *triangles* via keyword argument. If neither of *triangulation* or *triangles* are given, the triangulation is calculated on the fly. In this case, it does not make sense to provide colors at the triangle faces via *c* or *facecolors* because there are multiple possible triangulations for a group of points and you don't know which triangles will be constructed. Parameters ---------- triangulation : `.Triangulation` An already created triangular grid. x, y, triangles, mask Parameters defining the triangular grid. See `.Triangulation`. This is mutually exclusive with specifying *triangulation*. c : array-like The color values, either for the points or for the triangles. Which one is automatically inferred from the length of *c*, i.e. does it match the number of points or the number of triangles. If there are the same number of points and triangles in the triangulation it is assumed that color values are defined at points; to force the use of color values at triangles use the keyword argument ``facecolors=c`` instead of just ``c``. This parameter is position-only. facecolors : array-like, optional Can be used alternatively to *c* to specify colors at the triangle faces. This parameter takes precedence over *c*. shading : {'flat', 'gouraud'}, default: 'flat' If 'flat' and the color values *c* are defined at points, the color values used for each triangle are from the mean c of the triangle's three points. If *shading* is 'gouraud' then color values must be defined at points. other_parameters All other parameters are the same as for `~.Axes.pcolor`.
Here is the function:
def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None,
vmax=None, shading='flat', facecolors=None, **kwargs):
"""
Create a pseudocolor plot of an unstructured triangular grid.
Call signatures::
tripcolor(triangulation, c, *, ...)
tripcolor(x, y, c, *, [triangles=triangles], [mask=mask], ...)
The triangular grid can be specified either by passing a `.Triangulation`
object as the first parameter, or by passing the points *x*, *y* and
optionally the *triangles* and a *mask*. See `.Triangulation` for an
explanation of these parameters.
It is possible to pass the triangles positionally, i.e.
``tripcolor(x, y, triangles, c, ...)``. However, this is discouraged.
For more clarity, pass *triangles* via keyword argument.
If neither of *triangulation* or *triangles* are given, the triangulation
is calculated on the fly. In this case, it does not make sense to provide
colors at the triangle faces via *c* or *facecolors* because there are
multiple possible triangulations for a group of points and you don't know
which triangles will be constructed.
Parameters
----------
triangulation : `.Triangulation`
An already created triangular grid.
x, y, triangles, mask
Parameters defining the triangular grid. See `.Triangulation`.
This is mutually exclusive with specifying *triangulation*.
c : array-like
The color values, either for the points or for the triangles. Which one
is automatically inferred from the length of *c*, i.e. does it match
the number of points or the number of triangles. If there are the same
number of points and triangles in the triangulation it is assumed that
color values are defined at points; to force the use of color values at
triangles use the keyword argument ``facecolors=c`` instead of just
``c``.
This parameter is position-only.
facecolors : array-like, optional
Can be used alternatively to *c* to specify colors at the triangle
faces. This parameter takes precedence over *c*.
shading : {'flat', 'gouraud'}, default: 'flat'
If 'flat' and the color values *c* are defined at points, the color
values used for each triangle are from the mean c of the triangle's
three points. If *shading* is 'gouraud' then color values must be
defined at points.
other_parameters
All other parameters are the same as for `~.Axes.pcolor`.
"""
_api.check_in_list(['flat', 'gouraud'], shading=shading)
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
# Parse the color to be in one of (the other variable will be None):
# - facecolors: if specified at the triangle faces
# - point_colors: if specified at the points
if facecolors is not None:
if args:
_api.warn_external(
"Positional parameter c has no effect when the keyword "
"facecolors is given")
point_colors = None
if len(facecolors) != len(tri.triangles):
raise ValueError("The length of facecolors must match the number "
"of triangles")
else:
# Color from positional parameter c
if not args:
raise TypeError(
"tripcolor() missing 1 required positional argument: 'c'; or "
"1 required keyword-only argument: 'facecolors'")
elif len(args) > 1:
_api.warn_deprecated(
"3.6", message=f"Additional positional parameters "
f"{args[1:]!r} are ignored; support for them is deprecated "
f"since %(since)s and will be removed %(removal)s")
c = np.asarray(args[0])
if len(c) == len(tri.x):
# having this before the len(tri.triangles) comparison gives
# precedence to nodes if there are as many nodes as triangles
point_colors = c
facecolors = None
elif len(c) == len(tri.triangles):
point_colors = None
facecolors = c
else:
raise ValueError('The length of c must match either the number '
'of points or the number of triangles')
# Handling of linewidths, shading, edgecolors and antialiased as
# in Axes.pcolor
linewidths = (0.25,)
if 'linewidth' in kwargs:
kwargs['linewidths'] = kwargs.pop('linewidth')
kwargs.setdefault('linewidths', linewidths)
edgecolors = 'none'
if 'edgecolor' in kwargs:
kwargs['edgecolors'] = kwargs.pop('edgecolor')
ec = kwargs.setdefault('edgecolors', edgecolors)
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and ec.lower() == "none":
kwargs['antialiaseds'] = False
_api.check_isinstance((Normalize, None), norm=norm)
if shading == 'gouraud':
if facecolors is not None:
raise ValueError(
"shading='gouraud' can only be used when the colors "
"are specified at the points, not at the faces.")
collection = TriMesh(tri, alpha=alpha, array=point_colors,
cmap=cmap, norm=norm, **kwargs)
else: # 'flat'
# Vertices of triangles.
maskedTris = tri.get_masked_triangles()
verts = np.stack((tri.x[maskedTris], tri.y[maskedTris]), axis=-1)
# Color values.
if facecolors is None:
# One color per triangle, the mean of the 3 vertex color values.
colors = point_colors[maskedTris].mean(axis=1)
elif tri.mask is not None:
# Remove color values of masked triangles.
colors = facecolors[~tri.mask]
else:
colors = facecolors
collection = PolyCollection(verts, alpha=alpha, array=colors,
cmap=cmap, norm=norm, **kwargs)
collection._scale_norm(norm, vmin, vmax)
ax.grid(False)
minx = tri.x.min()
maxx = tri.x.max()
miny = tri.y.min()
maxy = tri.y.max()
corners = (minx, miny), (maxx, maxy)
ax.update_datalim(corners)
ax.autoscale_view()
ax.add_collection(collection)
return collection | Create a pseudocolor plot of an unstructured triangular grid. Call signatures:: tripcolor(triangulation, c, *, ...) tripcolor(x, y, c, *, [triangles=triangles], [mask=mask], ...) The triangular grid can be specified either by passing a `.Triangulation` object as the first parameter, or by passing the points *x*, *y* and optionally the *triangles* and a *mask*. See `.Triangulation` for an explanation of these parameters. It is possible to pass the triangles positionally, i.e. ``tripcolor(x, y, triangles, c, ...)``. However, this is discouraged. For more clarity, pass *triangles* via keyword argument. If neither of *triangulation* or *triangles* are given, the triangulation is calculated on the fly. In this case, it does not make sense to provide colors at the triangle faces via *c* or *facecolors* because there are multiple possible triangulations for a group of points and you don't know which triangles will be constructed. Parameters ---------- triangulation : `.Triangulation` An already created triangular grid. x, y, triangles, mask Parameters defining the triangular grid. See `.Triangulation`. This is mutually exclusive with specifying *triangulation*. c : array-like The color values, either for the points or for the triangles. Which one is automatically inferred from the length of *c*, i.e. does it match the number of points or the number of triangles. If there are the same number of points and triangles in the triangulation it is assumed that color values are defined at points; to force the use of color values at triangles use the keyword argument ``facecolors=c`` instead of just ``c``. This parameter is position-only. facecolors : array-like, optional Can be used alternatively to *c* to specify colors at the triangle faces. This parameter takes precedence over *c*. shading : {'flat', 'gouraud'}, default: 'flat' If 'flat' and the color values *c* are defined at points, the color values used for each triangle are from the mean c of the triangle's three points. If *shading* is 'gouraud' then color values must be defined at points. other_parameters All other parameters are the same as for `~.Axes.pcolor`. |
171,250 | import numpy as np
from matplotlib import _docstring
from matplotlib.contour import ContourSet
from matplotlib.tri._triangulation import Triangulation
class TriContourSet(ContourSet):
"""
Create and store a set of contour lines or filled regions for
a triangular grid.
This class is typically not instantiated directly by the user but by
`~.Axes.tricontour` and `~.Axes.tricontourf`.
%(contour_set_attributes)s
"""
def __init__(self, ax, *args, **kwargs):
"""
Draw triangular grid contour lines or filled regions,
depending on whether keyword arg *filled* is False
(default) or True.
The first argument of the initializer must be an `~.axes.Axes`
object. The remaining arguments and keyword arguments
are described in the docstring of `~.Axes.tricontour`.
"""
super().__init__(ax, *args, **kwargs)
def _process_args(self, *args, **kwargs):
"""
Process args and kwargs.
"""
if isinstance(args[0], TriContourSet):
C = args[0]._contour_generator
if self.levels is None:
self.levels = args[0].levels
self.zmin = args[0].zmin
self.zmax = args[0].zmax
self._mins = args[0]._mins
self._maxs = args[0]._maxs
else:
from matplotlib import _tri
tri, z = self._contour_args(args, kwargs)
C = _tri.TriContourGenerator(tri.get_cpp_triangulation(), z)
self._mins = [tri.x.min(), tri.y.min()]
self._maxs = [tri.x.max(), tri.y.max()]
self._contour_generator = C
return kwargs
def _contour_args(self, args, kwargs):
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args,
**kwargs)
z, *args = args
z = np.ma.asarray(z)
if z.shape != tri.x.shape:
raise ValueError('z array must have same length as triangulation x'
' and y arrays')
# z values must be finite, only need to check points that are included
# in the triangulation.
z_check = z[np.unique(tri.get_masked_triangles())]
if np.ma.is_masked(z_check):
raise ValueError('z must not contain masked points within the '
'triangulation')
if not np.isfinite(z_check).all():
raise ValueError('z array must not contain non-finite values '
'within the triangulation')
z = np.ma.masked_invalid(z, copy=False)
self.zmax = float(z_check.max())
self.zmin = float(z_check.min())
if self.logscale and self.zmin <= 0:
func = 'contourf' if self.filled else 'contour'
raise ValueError(f'Cannot {func} log of negative values.')
self._process_contour_level_args(args, z.dtype)
return (tri, z)
The provided code snippet includes necessary dependencies for implementing the `tricontour` function. Write a Python function `def tricontour(ax, *args, **kwargs)` to solve the following problem:
%(_tricontour_doc)s linewidths : float or array-like, default: :rc:`contour.linewidth` The line width of the contour lines. If a number, all levels will be plotted with this linewidth. If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified. If None, this falls back to :rc:`lines.linewidth`. linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional If *linestyles* is *None*, the default is 'solid' unless the lines are monochrome. In that case, negative contours will take their linestyle from :rc:`contour.negative_linestyle` setting. *linestyles* can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
Here is the function:
def tricontour(ax, *args, **kwargs):
"""
%(_tricontour_doc)s
linewidths : float or array-like, default: :rc:`contour.linewidth`
The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with
the linewidths in the order specified.
If None, this falls back to :rc:`lines.linewidth`.
linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
If *linestyles* is *None*, the default is 'solid' unless the lines are
monochrome. In that case, negative contours will take their linestyle
from :rc:`contour.negative_linestyle` setting.
*linestyles* can also be an iterable of the above strings specifying a
set of linestyles to be used. If this iterable is shorter than the
number of contour levels it will be repeated as necessary.
"""
kwargs['filled'] = False
return TriContourSet(ax, *args, **kwargs) | %(_tricontour_doc)s linewidths : float or array-like, default: :rc:`contour.linewidth` The line width of the contour lines. If a number, all levels will be plotted with this linewidth. If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified. If None, this falls back to :rc:`lines.linewidth`. linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional If *linestyles* is *None*, the default is 'solid' unless the lines are monochrome. In that case, negative contours will take their linestyle from :rc:`contour.negative_linestyle` setting. *linestyles* can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary. |
171,251 | import numpy as np
from matplotlib import _docstring
from matplotlib.contour import ContourSet
from matplotlib.tri._triangulation import Triangulation
class TriContourSet(ContourSet):
"""
Create and store a set of contour lines or filled regions for
a triangular grid.
This class is typically not instantiated directly by the user but by
`~.Axes.tricontour` and `~.Axes.tricontourf`.
%(contour_set_attributes)s
"""
def __init__(self, ax, *args, **kwargs):
"""
Draw triangular grid contour lines or filled regions,
depending on whether keyword arg *filled* is False
(default) or True.
The first argument of the initializer must be an `~.axes.Axes`
object. The remaining arguments and keyword arguments
are described in the docstring of `~.Axes.tricontour`.
"""
super().__init__(ax, *args, **kwargs)
def _process_args(self, *args, **kwargs):
"""
Process args and kwargs.
"""
if isinstance(args[0], TriContourSet):
C = args[0]._contour_generator
if self.levels is None:
self.levels = args[0].levels
self.zmin = args[0].zmin
self.zmax = args[0].zmax
self._mins = args[0]._mins
self._maxs = args[0]._maxs
else:
from matplotlib import _tri
tri, z = self._contour_args(args, kwargs)
C = _tri.TriContourGenerator(tri.get_cpp_triangulation(), z)
self._mins = [tri.x.min(), tri.y.min()]
self._maxs = [tri.x.max(), tri.y.max()]
self._contour_generator = C
return kwargs
def _contour_args(self, args, kwargs):
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args,
**kwargs)
z, *args = args
z = np.ma.asarray(z)
if z.shape != tri.x.shape:
raise ValueError('z array must have same length as triangulation x'
' and y arrays')
# z values must be finite, only need to check points that are included
# in the triangulation.
z_check = z[np.unique(tri.get_masked_triangles())]
if np.ma.is_masked(z_check):
raise ValueError('z must not contain masked points within the '
'triangulation')
if not np.isfinite(z_check).all():
raise ValueError('z array must not contain non-finite values '
'within the triangulation')
z = np.ma.masked_invalid(z, copy=False)
self.zmax = float(z_check.max())
self.zmin = float(z_check.min())
if self.logscale and self.zmin <= 0:
func = 'contourf' if self.filled else 'contour'
raise ValueError(f'Cannot {func} log of negative values.')
self._process_contour_level_args(args, z.dtype)
return (tri, z)
The provided code snippet includes necessary dependencies for implementing the `tricontourf` function. Write a Python function `def tricontourf(ax, *args, **kwargs)` to solve the following problem:
%(_tricontour_doc)s hatches : list[str], optional A list of crosshatch patterns to use on the filled areas. If None, no hatching will be added to the contour. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Notes ----- `.tricontourf` fills intervals that are closed at the top; that is, for boundaries *z1* and *z2*, the filled region is:: z1 < Z <= z2 except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
Here is the function:
def tricontourf(ax, *args, **kwargs):
"""
%(_tricontour_doc)s
hatches : list[str], optional
A list of crosshatch patterns to use on the filled areas.
If None, no hatching will be added to the contour.
Hatching is supported in the PostScript, PDF, SVG and Agg
backends only.
Notes
-----
`.tricontourf` fills intervals that are closed at the top; that is, for
boundaries *z1* and *z2*, the filled region is::
z1 < Z <= z2
except for the lowest interval, which is closed on both sides (i.e. it
includes the lowest value).
"""
kwargs['filled'] = True
return TriContourSet(ax, *args, **kwargs) | %(_tricontour_doc)s hatches : list[str], optional A list of crosshatch patterns to use on the filled areas. If None, no hatching will be added to the contour. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Notes ----- `.tricontourf` fills intervals that are closed at the top; that is, for boundaries *z1* and *z2*, the filled region is:: z1 < Z <= z2 except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value). |
171,252 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_cg` function. Write a Python function `def _cg(A, b, x0=None, tol=1.e-10, maxiter=1000)` to solve the following problem:
Use Preconditioned Conjugate Gradient iteration to solve A x = b A simple Jacobi (diagonal) preconditioner is used. Parameters ---------- A : _Sparse_Matrix_coo *A* must have been compressed before by compress_csc or compress_csr method. b : array Right hand side of the linear system. x0 : array, optional Starting guess for the solution. Defaults to the zero vector. tol : float, optional Tolerance to achieve. The algorithm terminates when the relative residual is below tol. Default is 1e-10. maxiter : int, optional Maximum number of iterations. Iteration will stop after *maxiter* steps even if the specified tolerance has not been achieved. Defaults to 1000. Returns ------- x : array The converged solution. err : float The absolute error np.linalg.norm(A.dot(x) - b)
Here is the function:
def _cg(A, b, x0=None, tol=1.e-10, maxiter=1000):
"""
Use Preconditioned Conjugate Gradient iteration to solve A x = b
A simple Jacobi (diagonal) preconditioner is used.
Parameters
----------
A : _Sparse_Matrix_coo
*A* must have been compressed before by compress_csc or
compress_csr method.
b : array
Right hand side of the linear system.
x0 : array, optional
Starting guess for the solution. Defaults to the zero vector.
tol : float, optional
Tolerance to achieve. The algorithm terminates when the relative
residual is below tol. Default is 1e-10.
maxiter : int, optional
Maximum number of iterations. Iteration will stop after *maxiter*
steps even if the specified tolerance has not been achieved. Defaults
to 1000.
Returns
-------
x : array
The converged solution.
err : float
The absolute error np.linalg.norm(A.dot(x) - b)
"""
n = b.size
assert A.n == n
assert A.m == n
b_norm = np.linalg.norm(b)
# Jacobi pre-conditioner
kvec = A.diag
# For diag elem < 1e-6 we keep 1e-6.
kvec = np.maximum(kvec, 1e-6)
# Initial guess
if x0 is None:
x = np.zeros(n)
else:
x = x0
r = b - A.dot(x)
w = r/kvec
p = np.zeros(n)
beta = 0.0
rho = np.dot(r, w)
k = 0
# Following C. T. Kelley
while (np.sqrt(abs(rho)) > tol*b_norm) and (k < maxiter):
p = w + beta*p
z = A.dot(p)
alpha = rho/np.dot(p, z)
r = r - alpha*z
w = r/kvec
rhoold = rho
rho = np.dot(r, w)
x = x + alpha*p
beta = rho/rhoold
# err = np.linalg.norm(A.dot(x) - b) # absolute accuracy - not used
k += 1
err = np.linalg.norm(A.dot(x) - b)
return x, err | Use Preconditioned Conjugate Gradient iteration to solve A x = b A simple Jacobi (diagonal) preconditioner is used. Parameters ---------- A : _Sparse_Matrix_coo *A* must have been compressed before by compress_csc or compress_csr method. b : array Right hand side of the linear system. x0 : array, optional Starting guess for the solution. Defaults to the zero vector. tol : float, optional Tolerance to achieve. The algorithm terminates when the relative residual is below tol. Default is 1e-10. maxiter : int, optional Maximum number of iterations. Iteration will stop after *maxiter* steps even if the specified tolerance has not been achieved. Defaults to 1000. Returns ------- x : array The converged solution. err : float The absolute error np.linalg.norm(A.dot(x) - b) |
171,253 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_safe_inv22_vectorized` function. Write a Python function `def _safe_inv22_vectorized(M)` to solve the following problem:
Inversion of arrays of (2, 2) matrices, returns 0 for rank-deficient matrices. *M* : array of (2, 2) matrices to inverse, shape (n, 2, 2)
Here is the function:
def _safe_inv22_vectorized(M):
"""
Inversion of arrays of (2, 2) matrices, returns 0 for rank-deficient
matrices.
*M* : array of (2, 2) matrices to inverse, shape (n, 2, 2)
"""
_api.check_shape((None, 2, 2), M=M)
M_inv = np.empty_like(M)
prod1 = M[:, 0, 0]*M[:, 1, 1]
delta = prod1 - M[:, 0, 1]*M[:, 1, 0]
# We set delta_inv to 0. in case of a rank deficient matrix; a
# rank-deficient input matrix *M* will lead to a null matrix in output
rank2 = (np.abs(delta) > 1e-8*np.abs(prod1))
if np.all(rank2):
# Normal 'optimized' flow.
delta_inv = 1./delta
else:
# 'Pathologic' flow.
delta_inv = np.zeros(M.shape[0])
delta_inv[rank2] = 1./delta[rank2]
M_inv[:, 0, 0] = M[:, 1, 1]*delta_inv
M_inv[:, 0, 1] = -M[:, 0, 1]*delta_inv
M_inv[:, 1, 0] = -M[:, 1, 0]*delta_inv
M_inv[:, 1, 1] = M[:, 0, 0]*delta_inv
return M_inv | Inversion of arrays of (2, 2) matrices, returns 0 for rank-deficient matrices. *M* : array of (2, 2) matrices to inverse, shape (n, 2, 2) |
171,254 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_pseudo_inv22sym_vectorized` function. Write a Python function `def _pseudo_inv22sym_vectorized(M)` to solve the following problem:
Inversion of arrays of (2, 2) SYMMETRIC matrices; returns the (Moore-Penrose) pseudo-inverse for rank-deficient matrices. In case M is of rank 1, we have M = trace(M) x P where P is the orthogonal projection on Im(M), and we return trace(M)^-1 x P == M / trace(M)**2 In case M is of rank 0, we return the null matrix. *M* : array of (2, 2) matrices to inverse, shape (n, 2, 2)
Here is the function:
def _pseudo_inv22sym_vectorized(M):
"""
Inversion of arrays of (2, 2) SYMMETRIC matrices; returns the
(Moore-Penrose) pseudo-inverse for rank-deficient matrices.
In case M is of rank 1, we have M = trace(M) x P where P is the orthogonal
projection on Im(M), and we return trace(M)^-1 x P == M / trace(M)**2
In case M is of rank 0, we return the null matrix.
*M* : array of (2, 2) matrices to inverse, shape (n, 2, 2)
"""
_api.check_shape((None, 2, 2), M=M)
M_inv = np.empty_like(M)
prod1 = M[:, 0, 0]*M[:, 1, 1]
delta = prod1 - M[:, 0, 1]*M[:, 1, 0]
rank2 = (np.abs(delta) > 1e-8*np.abs(prod1))
if np.all(rank2):
# Normal 'optimized' flow.
M_inv[:, 0, 0] = M[:, 1, 1] / delta
M_inv[:, 0, 1] = -M[:, 0, 1] / delta
M_inv[:, 1, 0] = -M[:, 1, 0] / delta
M_inv[:, 1, 1] = M[:, 0, 0] / delta
else:
# 'Pathologic' flow.
# Here we have to deal with 2 sub-cases
# 1) First sub-case: matrices of rank 2:
delta = delta[rank2]
M_inv[rank2, 0, 0] = M[rank2, 1, 1] / delta
M_inv[rank2, 0, 1] = -M[rank2, 0, 1] / delta
M_inv[rank2, 1, 0] = -M[rank2, 1, 0] / delta
M_inv[rank2, 1, 1] = M[rank2, 0, 0] / delta
# 2) Second sub-case: rank-deficient matrices of rank 0 and 1:
rank01 = ~rank2
tr = M[rank01, 0, 0] + M[rank01, 1, 1]
tr_zeros = (np.abs(tr) < 1.e-8)
sq_tr_inv = (1.-tr_zeros) / (tr**2+tr_zeros)
# sq_tr_inv = 1. / tr**2
M_inv[rank01, 0, 0] = M[rank01, 0, 0] * sq_tr_inv
M_inv[rank01, 0, 1] = M[rank01, 0, 1] * sq_tr_inv
M_inv[rank01, 1, 0] = M[rank01, 1, 0] * sq_tr_inv
M_inv[rank01, 1, 1] = M[rank01, 1, 1] * sq_tr_inv
return M_inv | Inversion of arrays of (2, 2) SYMMETRIC matrices; returns the (Moore-Penrose) pseudo-inverse for rank-deficient matrices. In case M is of rank 1, we have M = trace(M) x P where P is the orthogonal projection on Im(M), and we return trace(M)^-1 x P == M / trace(M)**2 In case M is of rank 0, we return the null matrix. *M* : array of (2, 2) matrices to inverse, shape (n, 2, 2) |
171,255 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_scalar_vectorized` function. Write a Python function `def _scalar_vectorized(scalar, M)` to solve the following problem:
Scalar product between scalars and matrices.
Here is the function:
def _scalar_vectorized(scalar, M):
"""
Scalar product between scalars and matrices.
"""
return scalar[:, np.newaxis, np.newaxis]*M | Scalar product between scalars and matrices. |
171,256 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_transpose_vectorized` function. Write a Python function `def _transpose_vectorized(M)` to solve the following problem:
Transposition of an array of matrices *M*.
Here is the function:
def _transpose_vectorized(M):
"""
Transposition of an array of matrices *M*.
"""
return np.transpose(M, [0, 2, 1]) | Transposition of an array of matrices *M*. |
171,257 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_roll_vectorized` function. Write a Python function `def _roll_vectorized(M, roll_indices, axis)` to solve the following problem:
Roll an array of matrices along *axis* (0: rows, 1: columns) according to an array of indices *roll_indices*.
Here is the function:
def _roll_vectorized(M, roll_indices, axis):
"""
Roll an array of matrices along *axis* (0: rows, 1: columns) according to
an array of indices *roll_indices*.
"""
assert axis in [0, 1]
ndim = M.ndim
assert ndim == 3
ndim_roll = roll_indices.ndim
assert ndim_roll == 1
sh = M.shape
r, c = sh[-2:]
assert sh[0] == roll_indices.shape[0]
vec_indices = np.arange(sh[0], dtype=np.int32)
# Builds the rolled matrix
M_roll = np.empty_like(M)
if axis == 0:
for ir in range(r):
for ic in range(c):
M_roll[:, ir, ic] = M[vec_indices, (-roll_indices+ir) % r, ic]
else: # 1
for ir in range(r):
for ic in range(c):
M_roll[:, ir, ic] = M[vec_indices, ir, (-roll_indices+ic) % c]
return M_roll | Roll an array of matrices along *axis* (0: rows, 1: columns) according to an array of indices *roll_indices*. |
171,258 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_to_matrix_vectorized` function. Write a Python function `def _to_matrix_vectorized(M)` to solve the following problem:
Build an array of matrices from individuals np.arrays of identical shapes. Parameters ---------- M ncols-list of nrows-lists of shape sh. Returns ------- M_res : np.array of shape (sh, nrow, ncols) *M_res* satisfies ``M_res[..., i, j] = M[i][j]``.
Here is the function:
def _to_matrix_vectorized(M):
"""
Build an array of matrices from individuals np.arrays of identical shapes.
Parameters
----------
M
ncols-list of nrows-lists of shape sh.
Returns
-------
M_res : np.array of shape (sh, nrow, ncols)
*M_res* satisfies ``M_res[..., i, j] = M[i][j]``.
"""
assert isinstance(M, (tuple, list))
assert all(isinstance(item, (tuple, list)) for item in M)
c_vec = np.asarray([len(item) for item in M])
assert np.all(c_vec-c_vec[0] == 0)
r = len(M)
c = c_vec[0]
M00 = np.asarray(M[0][0])
dt = M00.dtype
sh = [M00.shape[0], r, c]
M_ret = np.empty(sh, dtype=dt)
for irow in range(r):
for icol in range(c):
M_ret[:, irow, icol] = np.asarray(M[irow][icol])
return M_ret | Build an array of matrices from individuals np.arrays of identical shapes. Parameters ---------- M ncols-list of nrows-lists of shape sh. Returns ------- M_res : np.array of shape (sh, nrow, ncols) *M_res* satisfies ``M_res[..., i, j] = M[i][j]``. |
171,259 | import numpy as np
from matplotlib import _api
from matplotlib.tri import Triangulation
from matplotlib.tri._trifinder import TriFinder
from matplotlib.tri._tritools import TriAnalyzer
The provided code snippet includes necessary dependencies for implementing the `_extract_submatrices` function. Write a Python function `def _extract_submatrices(M, block_indices, block_size, axis)` to solve the following problem:
Extract selected blocks of a matrices *M* depending on parameters *block_indices* and *block_size*. Returns the array of extracted matrices *Mres* so that :: M_res[..., ir, :] = M[(block_indices*block_size+ir), :]
Here is the function:
def _extract_submatrices(M, block_indices, block_size, axis):
"""
Extract selected blocks of a matrices *M* depending on parameters
*block_indices* and *block_size*.
Returns the array of extracted matrices *Mres* so that ::
M_res[..., ir, :] = M[(block_indices*block_size+ir), :]
"""
assert block_indices.ndim == 1
assert axis in [0, 1]
r, c = M.shape
if axis == 0:
sh = [block_indices.shape[0], block_size, c]
else: # 1
sh = [block_indices.shape[0], r, block_size]
dt = M.dtype
M_res = np.empty(sh, dtype=dt)
if axis == 0:
for ir in range(block_size):
M_res[:, ir, :] = M[(block_indices*block_size+ir), :]
else: # 1
for ic in range(block_size):
M_res[:, :, ic] = M[:, (block_indices*block_size+ic)]
return M_res | Extract selected blocks of a matrices *M* depending on parameters *block_indices* and *block_size*. Returns the array of extracted matrices *Mres* so that :: M_res[..., ir, :] = M[(block_indices*block_size+ir), :] |
171,260 | import numpy as np
from matplotlib.tri._triangulation import Triangulation
import matplotlib.cbook as cbook
import matplotlib.lines as mlines
class Triangulation:
"""
An unstructured triangular grid consisting of npoints points and
ntri triangles. The triangles can either be specified by the user
or automatically generated using a Delaunay triangulation.
Parameters
----------
x, y : (npoints,) array-like
Coordinates of grid points.
triangles : (ntri, 3) array-like of int, optional
For each triangle, the indices of the three points that make
up the triangle, ordered in an anticlockwise manner. If not
specified, the Delaunay triangulation is calculated.
mask : (ntri,) array-like of bool, optional
Which triangles are masked out.
Attributes
----------
triangles : (ntri, 3) array of int
For each triangle, the indices of the three points that make
up the triangle, ordered in an anticlockwise manner. If you want to
take the *mask* into account, use `get_masked_triangles` instead.
mask : (ntri, 3) array of bool
Masked out triangles.
is_delaunay : bool
Whether the Triangulation is a calculated Delaunay
triangulation (where *triangles* was not specified) or not.
Notes
-----
For a Triangulation to be valid it must not have duplicate points,
triangles formed from colinear points, or overlapping triangles.
"""
def __init__(self, x, y, triangles=None, mask=None):
from matplotlib import _qhull
self.x = np.asarray(x, dtype=np.float64)
self.y = np.asarray(y, dtype=np.float64)
if self.x.shape != self.y.shape or self.x.ndim != 1:
raise ValueError("x and y must be equal-length 1D arrays, but "
f"found shapes {self.x.shape!r} and "
f"{self.y.shape!r}")
self.mask = None
self._edges = None
self._neighbors = None
self.is_delaunay = False
if triangles is None:
# No triangulation specified, so use matplotlib._qhull to obtain
# Delaunay triangulation.
self.triangles, self._neighbors = _qhull.delaunay(x, y)
self.is_delaunay = True
else:
# Triangulation specified. Copy, since we may correct triangle
# orientation.
try:
self.triangles = np.array(triangles, dtype=np.int32, order='C')
except ValueError as e:
raise ValueError('triangles must be a (N, 3) int array, not '
f'{triangles!r}') from e
if self.triangles.ndim != 2 or self.triangles.shape[1] != 3:
raise ValueError(
'triangles must be a (N, 3) int array, but found shape '
f'{self.triangles.shape!r}')
if self.triangles.max() >= len(self.x):
raise ValueError(
'triangles are indices into the points and must be in the '
f'range 0 <= i < {len(self.x)} but found value '
f'{self.triangles.max()}')
if self.triangles.min() < 0:
raise ValueError(
'triangles are indices into the points and must be in the '
f'range 0 <= i < {len(self.x)} but found value '
f'{self.triangles.min()}')
# Underlying C++ object is not created until first needed.
self._cpp_triangulation = None
# Default TriFinder not created until needed.
self._trifinder = None
self.set_mask(mask)
def calculate_plane_coefficients(self, z):
"""
Calculate plane equation coefficients for all unmasked triangles from
the point (x, y) coordinates and specified z-array of shape (npoints).
The returned array has shape (npoints, 3) and allows z-value at (x, y)
position in triangle tri to be calculated using
``z = array[tri, 0] * x + array[tri, 1] * y + array[tri, 2]``.
"""
return self.get_cpp_triangulation().calculate_plane_coefficients(z)
def edges(self):
"""
Return integer array of shape (nedges, 2) containing all edges of
non-masked triangles.
Each row defines an edge by its start point index and end point
index. Each edge appears only once, i.e. for an edge between points
*i* and *j*, there will only be either *(i, j)* or *(j, i)*.
"""
if self._edges is None:
self._edges = self.get_cpp_triangulation().get_edges()
return self._edges
def get_cpp_triangulation(self):
"""
Return the underlying C++ Triangulation object, creating it
if necessary.
"""
from matplotlib import _tri
if self._cpp_triangulation is None:
self._cpp_triangulation = _tri.Triangulation(
# For unset arrays use empty tuple which has size of zero.
self.x, self.y, self.triangles,
self.mask if self.mask is not None else (),
self._edges if self._edges is not None else (),
self._neighbors if self._neighbors is not None else (),
not self.is_delaunay)
return self._cpp_triangulation
def get_masked_triangles(self):
"""
Return an array of triangles taking the mask into account.
"""
if self.mask is not None:
return self.triangles[~self.mask]
else:
return self.triangles
def get_from_args_and_kwargs(*args, **kwargs):
"""
Return a Triangulation object from the args and kwargs, and
the remaining args and kwargs with the consumed values removed.
There are two alternatives: either the first argument is a
Triangulation object, in which case it is returned, or the args
and kwargs are sufficient to create a new Triangulation to
return. In the latter case, see Triangulation.__init__ for
the possible args and kwargs.
"""
if isinstance(args[0], Triangulation):
triangulation, *args = args
if 'triangles' in kwargs:
_api.warn_external(
"Passing the keyword 'triangles' has no effect when also "
"passing a Triangulation")
if 'mask' in kwargs:
_api.warn_external(
"Passing the keyword 'mask' has no effect when also "
"passing a Triangulation")
else:
x, y, triangles, mask, args, kwargs = \
Triangulation._extract_triangulation_params(args, kwargs)
triangulation = Triangulation(x, y, triangles, mask)
return triangulation, args, kwargs
def _extract_triangulation_params(args, kwargs):
x, y, *args = args
# Check triangles in kwargs then args.
triangles = kwargs.pop('triangles', None)
from_args = False
if triangles is None and args:
triangles = args[0]
from_args = True
if triangles is not None:
try:
triangles = np.asarray(triangles, dtype=np.int32)
except ValueError:
triangles = None
if triangles is not None and (triangles.ndim != 2 or
triangles.shape[1] != 3):
triangles = None
if triangles is not None and from_args:
args = args[1:] # Consumed first item in args.
# Check for mask in kwargs.
mask = kwargs.pop('mask', None)
return x, y, triangles, mask, args, kwargs
def get_trifinder(self):
"""
Return the default `matplotlib.tri.TriFinder` of this
triangulation, creating it if necessary. This allows the same
TriFinder object to be easily shared.
"""
if self._trifinder is None:
# Default TriFinder class.
from matplotlib.tri._trifinder import TrapezoidMapTriFinder
self._trifinder = TrapezoidMapTriFinder(self)
return self._trifinder
def neighbors(self):
"""
Return integer array of shape (ntri, 3) containing neighbor triangles.
For each triangle, the indices of the three triangles that
share the same edges, or -1 if there is no such neighboring
triangle. ``neighbors[i, j]`` is the triangle that is the neighbor
to the edge from point index ``triangles[i, j]`` to point index
``triangles[i, (j+1)%3]``.
"""
if self._neighbors is None:
self._neighbors = self.get_cpp_triangulation().get_neighbors()
return self._neighbors
def set_mask(self, mask):
"""
Set or clear the mask array.
Parameters
----------
mask : None or bool array of length ntri
"""
if mask is None:
self.mask = None
else:
self.mask = np.asarray(mask, dtype=bool)
if self.mask.shape != (self.triangles.shape[0],):
raise ValueError('mask array must have same length as '
'triangles array')
# Set mask in C++ Triangulation.
if self._cpp_triangulation is not None:
self._cpp_triangulation.set_mask(
self.mask if self.mask is not None else ())
# Clear derived fields so they are recalculated when needed.
self._edges = None
self._neighbors = None
# Recalculate TriFinder if it exists.
if self._trifinder is not None:
self._trifinder._initialize()
})
The provided code snippet includes necessary dependencies for implementing the `triplot` function. Write a Python function `def triplot(ax, *args, **kwargs)` to solve the following problem:
Draw an unstructured triangular grid as lines and/or markers. Call signatures:: triplot(triangulation, ...) triplot(x, y, [triangles], *, [mask=mask], ...) The triangular grid can be specified either by passing a `.Triangulation` object as the first parameter, or by passing the points *x*, *y* and optionally the *triangles* and a *mask*. If neither of *triangulation* or *triangles* are given, the triangulation is calculated on the fly. Parameters ---------- triangulation : `.Triangulation` An already created triangular grid. x, y, triangles, mask Parameters defining the triangular grid. See `.Triangulation`. This is mutually exclusive with specifying *triangulation*. other_parameters All other args and kwargs are forwarded to `~.Axes.plot`. Returns ------- lines : `~matplotlib.lines.Line2D` The drawn triangles edges. markers : `~matplotlib.lines.Line2D` The drawn marker nodes.
Here is the function:
def triplot(ax, *args, **kwargs):
"""
Draw an unstructured triangular grid as lines and/or markers.
Call signatures::
triplot(triangulation, ...)
triplot(x, y, [triangles], *, [mask=mask], ...)
The triangular grid can be specified either by passing a `.Triangulation`
object as the first parameter, or by passing the points *x*, *y* and
optionally the *triangles* and a *mask*. If neither of *triangulation* or
*triangles* are given, the triangulation is calculated on the fly.
Parameters
----------
triangulation : `.Triangulation`
An already created triangular grid.
x, y, triangles, mask
Parameters defining the triangular grid. See `.Triangulation`.
This is mutually exclusive with specifying *triangulation*.
other_parameters
All other args and kwargs are forwarded to `~.Axes.plot`.
Returns
-------
lines : `~matplotlib.lines.Line2D`
The drawn triangles edges.
markers : `~matplotlib.lines.Line2D`
The drawn marker nodes.
"""
import matplotlib.axes
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
x, y, edges = (tri.x, tri.y, tri.edges)
# Decode plot format string, e.g., 'ro-'
fmt = args[0] if args else ""
linestyle, marker, color = matplotlib.axes._base._process_plot_format(fmt)
# Insert plot format string into a copy of kwargs (kwargs values prevail).
kw = cbook.normalize_kwargs(kwargs, mlines.Line2D)
for key, val in zip(('linestyle', 'marker', 'color'),
(linestyle, marker, color)):
if val is not None:
kw.setdefault(key, val)
# Draw lines without markers.
# Note 1: If we drew markers here, most markers would be drawn more than
# once as they belong to several edges.
# Note 2: We insert nan values in the flattened edges arrays rather than
# plotting directly (triang.x[edges].T, triang.y[edges].T)
# as it considerably speeds-up code execution.
linestyle = kw['linestyle']
kw_lines = {
**kw,
'marker': 'None', # No marker to draw.
'zorder': kw.get('zorder', 1), # Path default zorder is used.
}
if linestyle not in [None, 'None', '', ' ']:
tri_lines_x = np.insert(x[edges], 2, np.nan, axis=1)
tri_lines_y = np.insert(y[edges], 2, np.nan, axis=1)
tri_lines = ax.plot(tri_lines_x.ravel(), tri_lines_y.ravel(),
**kw_lines)
else:
tri_lines = ax.plot([], [], **kw_lines)
# Draw markers separately.
marker = kw['marker']
kw_markers = {
**kw,
'linestyle': 'None', # No line to draw.
}
kw_markers.pop('label', None)
if marker not in [None, 'None', '', ' ']:
tri_markers = ax.plot(x, y, **kw_markers)
else:
tri_markers = ax.plot([], [], **kw_markers)
return tri_lines + tri_markers | Draw an unstructured triangular grid as lines and/or markers. Call signatures:: triplot(triangulation, ...) triplot(x, y, [triangles], *, [mask=mask], ...) The triangular grid can be specified either by passing a `.Triangulation` object as the first parameter, or by passing the points *x*, *y* and optionally the *triangles* and a *mask*. If neither of *triangulation* or *triangles* are given, the triangulation is calculated on the fly. Parameters ---------- triangulation : `.Triangulation` An already created triangular grid. x, y, triangles, mask Parameters defining the triangular grid. See `.Triangulation`. This is mutually exclusive with specifying *triangulation*. other_parameters All other args and kwargs are forwarded to `~.Axes.plot`. Returns ------- lines : `~matplotlib.lines.Line2D` The drawn triangles edges. markers : `~matplotlib.lines.Line2D` The drawn marker nodes. |
171,261 | import itertools
import logging
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, _docstring, colors, offsetbox
from matplotlib.artist import Artist, allow_rasterization
from matplotlib.cbook import silent_list
from matplotlib.font_manager import FontProperties
from matplotlib.lines import Line2D
from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch,
StepPatch)
from matplotlib.collections import (
Collection, CircleCollection, LineCollection, PathCollection,
PolyCollection, RegularPolyCollection)
from matplotlib.text import Text
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
from matplotlib.offsetbox import (
AnchoredOffsetbox, DraggableOffsetBox,
HPacker, VPacker,
DrawingArea, TextArea,
)
from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer
from . import legend_handler
def _get_legend_handles(axs, legend_handler_map=None):
"""Yield artists that can be used as handles in a legend."""
handles_original = []
for ax in axs:
handles_original += [
*(a for a in ax._children
if isinstance(a, (Line2D, Patch, Collection, Text))),
*ax.containers]
# support parasite axes:
if hasattr(ax, 'parasites'):
for axx in ax.parasites:
handles_original += [
*(a for a in axx._children
if isinstance(a, (Line2D, Patch, Collection, Text))),
*axx.containers]
handler_map = {**Legend.get_default_handler_map(),
**(legend_handler_map or {})}
has_handler = Legend.get_legend_handler
for handle in handles_original:
label = handle.get_label()
if label != '_nolegend_' and has_handler(handler_map, handle):
yield handle
elif (label and not label.startswith('_') and
not has_handler(handler_map, handle)):
_api.warn_external(
"Legend does not support handles for {0} "
"instances.\nSee: https://matplotlib.org/stable/"
"tutorials/intermediate/legend_guide.html"
"#implementing-a-custom-legend-handler".format(
type(handle).__name__))
continue
def _get_legend_handles_labels(axs, legend_handler_map=None):
"""Return handles and labels for legend."""
handles = []
labels = []
for handle in _get_legend_handles(axs, legend_handler_map):
label = handle.get_label()
if label and not label.startswith('_'):
handles.append(handle)
labels.append(label)
return handles, labels
class Artist:
"""
Abstract base class for objects that render into a FigureCanvas.
Typically, all visible elements in a figure are subclasses of Artist.
"""
zorder = 0
def __init_subclass__(cls):
# Decorate draw() method so that all artists are able to stop
# rastrization when necessary. If the artist's draw method is already
# decorated (has a `_supports_rasterization` attribute), it won't be
# decorated.
if not hasattr(cls.draw, "_supports_rasterization"):
cls.draw = _prevent_rasterization(cls.draw)
# Inject custom set() methods into the subclass with signature and
# docstring based on the subclasses' properties.
if not hasattr(cls.set, '_autogenerated_signature'):
# Don't overwrite cls.set if the subclass or one of its parents
# has defined a set method set itself.
# If there was no explicit definition, cls.set is inherited from
# the hierarchy of auto-generated set methods, which hold the
# flag _autogenerated_signature.
return
cls.set = lambda self, **kwargs: Artist.set(self, **kwargs)
cls.set.__name__ = "set"
cls.set.__qualname__ = f"{cls.__qualname__}.set"
cls._update_set_signature_and_docstring()
_PROPERTIES_EXCLUDED_FROM_SET = [
'navigate_mode', # not a user-facing function
'figure', # changing the figure is such a profound operation
# that we don't want this in set()
'3d_properties', # cannot be used as a keyword due to leading digit
]
def _update_set_signature_and_docstring(cls):
"""
Update the signature of the set function to list all properties
as keyword arguments.
Property aliases are not listed in the signature for brevity, but
are still accepted as keyword arguments.
"""
cls.set.__signature__ = Signature(
[Parameter("self", Parameter.POSITIONAL_OR_KEYWORD),
*[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET)
for prop in ArtistInspector(cls).get_setters()
if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]])
cls.set._autogenerated_signature = True
cls.set.__doc__ = (
"Set multiple properties at once.\n\n"
"Supported properties are\n\n"
+ kwdoc(cls))
def __init__(self):
self._stale = True
self.stale_callback = None
self._axes = None
self.figure = None
self._transform = None
self._transformSet = False
self._visible = True
self._animated = False
self._alpha = None
self.clipbox = None
self._clippath = None
self._clipon = True
self._label = ''
self._picker = None
self._rasterized = False
self._agg_filter = None
# Normally, artist classes need to be queried for mouseover info if and
# only if they override get_cursor_data.
self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data
self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
try:
self.axes = None
except AttributeError:
# Handle self.axes as a read-only property, as in Figure.
pass
self._remove_method = None
self._url = None
self._gid = None
self._snap = None
self._sketch = mpl.rcParams['path.sketch']
self._path_effects = mpl.rcParams['path.effects']
self._sticky_edges = _XYPair([], [])
self._in_layout = True
def __getstate__(self):
d = self.__dict__.copy()
# remove the unpicklable remove method, this will get re-added on load
# (by the Axes) if the artist lives on an Axes.
d['stale_callback'] = None
return d
def remove(self):
"""
Remove the artist from the figure if possible.
The effect will not be visible until the figure is redrawn, e.g.,
with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to
update the axes limits if desired.
Note: `~.axes.Axes.relim` will not see collections even if the
collection was added to the axes with *autolim* = True.
Note: there is no support for removing the artist's legend entry.
"""
# There is no method to set the callback. Instead, the parent should
# set the _remove_method attribute directly. This would be a
# protected attribute if Python supported that sort of thing. The
# callback has one parameter, which is the child to be removed.
if self._remove_method is not None:
self._remove_method(self)
# clear stale callback
self.stale_callback = None
_ax_flag = False
if hasattr(self, 'axes') and self.axes:
# remove from the mouse hit list
self.axes._mouseover_set.discard(self)
self.axes.stale = True
self.axes = None # decouple the artist from the Axes
_ax_flag = True
if self.figure:
self.figure = None
if not _ax_flag:
self.figure = True
else:
raise NotImplementedError('cannot remove artist')
# TODO: the fix for the collections relim problem is to move the
# limits calculation into the artist itself, including the property of
# whether or not the artist should affect the limits. Then there will
# be no distinction between axes.add_line, axes.add_patch, etc.
# TODO: add legend support
def have_units(self):
"""Return whether units are set on any axis."""
ax = self.axes
return ax and any(axis.have_units() for axis in ax._axis_map.values())
def convert_xunits(self, x):
"""
Convert *x* using the unit type of the xaxis.
If the artist is not contained in an Axes or if the xaxis does not
have units, *x* itself is returned.
"""
ax = getattr(self, 'axes', None)
if ax is None or ax.xaxis is None:
return x
return ax.xaxis.convert_units(x)
def convert_yunits(self, y):
"""
Convert *y* using the unit type of the yaxis.
If the artist is not contained in an Axes or if the yaxis does not
have units, *y* itself is returned.
"""
ax = getattr(self, 'axes', None)
if ax is None or ax.yaxis is None:
return y
return ax.yaxis.convert_units(y)
def axes(self):
"""The `~.axes.Axes` instance the artist resides in, or *None*."""
return self._axes
def axes(self, new_axes):
if (new_axes is not None and self._axes is not None
and new_axes != self._axes):
raise ValueError("Can not reset the axes. You are probably "
"trying to re-use an artist in more than one "
"Axes which is not supported")
self._axes = new_axes
if new_axes is not None and new_axes is not self:
self.stale_callback = _stale_axes_callback
def stale(self):
"""
Whether the artist is 'stale' and needs to be re-drawn for the output
to match the internal state of the artist.
"""
return self._stale
def stale(self, val):
self._stale = val
# if the artist is animated it does not take normal part in the
# draw stack and is not expected to be drawn as part of the normal
# draw loop (when not saving) so do not propagate this change
if self.get_animated():
return
if val and self.stale_callback is not None:
self.stale_callback(self, val)
def get_window_extent(self, renderer=None):
"""
Get the artist's bounding box in display space.
The bounding box' width and height are nonnegative.
Subclasses should override for inclusion in the bounding box
"tight" calculation. Default is to return an empty bounding
box at 0, 0.
Be careful when using this function, the results will not update
if the artist window extent of the artist changes. The extent
can change due to any changes in the transform stack, such as
changing the axes limits, the figure size, or the canvas used
(as is done when saving a figure). This can lead to unexpected
behavior where interactive figures will look fine on the screen,
but will save incorrectly.
"""
return Bbox([[0, 0], [0, 0]])
def get_tightbbox(self, renderer=None):
"""
Like `.Artist.get_window_extent`, but includes any clipping.
Parameters
----------
renderer : `.RendererBase` subclass
renderer that will be used to draw the figures (i.e.
``fig.canvas.get_renderer()``)
Returns
-------
`.Bbox`
The enclosing bounding box (in figure pixel coordinates).
"""
bbox = self.get_window_extent(renderer)
if self.get_clip_on():
clip_box = self.get_clip_box()
if clip_box is not None:
bbox = Bbox.intersection(bbox, clip_box)
clip_path = self.get_clip_path()
if clip_path is not None:
clip_path = clip_path.get_fully_transformed_path()
bbox = Bbox.intersection(bbox, clip_path.get_extents())
return bbox
def add_callback(self, func):
"""
Add a callback function that will be called whenever one of the
`.Artist`'s properties changes.
Parameters
----------
func : callable
The callback function. It must have the signature::
def func(artist: Artist) -> Any
where *artist* is the calling `.Artist`. Return values may exist
but are ignored.
Returns
-------
int
The observer id associated with the callback. This id can be
used for removing the callback with `.remove_callback` later.
See Also
--------
remove_callback
"""
# Wrapping func in a lambda ensures it can be connected multiple times
# and never gets weakref-gc'ed.
return self._callbacks.connect("pchanged", lambda: func(self))
def remove_callback(self, oid):
"""
Remove a callback based on its observer id.
See Also
--------
add_callback
"""
self._callbacks.disconnect(oid)
def pchanged(self):
"""
Call all of the registered callbacks.
This function is triggered internally when a property is changed.
See Also
--------
add_callback
remove_callback
"""
self._callbacks.process("pchanged")
def is_transform_set(self):
"""
Return whether the Artist has an explicitly set transform.
This is *True* after `.set_transform` has been called.
"""
return self._transformSet
def set_transform(self, t):
"""
Set the artist transform.
Parameters
----------
t : `.Transform`
"""
self._transform = t
self._transformSet = True
self.pchanged()
self.stale = True
def get_transform(self):
"""Return the `.Transform` instance used by this artist."""
if self._transform is None:
self._transform = IdentityTransform()
elif (not isinstance(self._transform, Transform)
and hasattr(self._transform, '_as_mpl_transform')):
self._transform = self._transform._as_mpl_transform(self.axes)
return self._transform
def get_children(self):
r"""Return a list of the child `.Artist`\s of this `.Artist`."""
return []
def _default_contains(self, mouseevent, figure=None):
"""
Base impl. for checking whether a mouseevent happened in an artist.
1. If the artist figure is known and the event did not occur in that
figure (by checking its ``canvas`` attribute), reject it.
2. Otherwise, return `None, {}`, indicating that the subclass'
implementation should be used.
Subclasses should start their definition of `contains` as follows:
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
# subclass-specific implementation follows
The *figure* kwarg is provided for the implementation of
`.Figure.contains`.
"""
if figure is not None and mouseevent.canvas is not figure.canvas:
return False, {}
return None, {}
def contains(self, mouseevent):
"""
Test whether the artist contains the mouse event.
Parameters
----------
mouseevent : `matplotlib.backend_bases.MouseEvent`
Returns
-------
contains : bool
Whether any values are within the radius.
details : dict
An artist-specific dictionary of details of the event context,
such as which points are contained in the pick radius. See the
individual Artist subclasses for details.
"""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
_log.warning("%r needs 'contains' method", self.__class__.__name__)
return False, {}
def pickable(self):
"""
Return whether the artist is pickable.
See Also
--------
set_picker, get_picker, pick
"""
return self.figure is not None and self._picker is not None
def pick(self, mouseevent):
"""
Process a pick event.
Each child artist will fire a pick event if *mouseevent* is over
the artist and the artist has picker set.
See Also
--------
set_picker, get_picker, pickable
"""
from .backend_bases import PickEvent # Circular import.
# Pick self
if self.pickable():
picker = self.get_picker()
if callable(picker):
inside, prop = picker(self, mouseevent)
else:
inside, prop = self.contains(mouseevent)
if inside:
PickEvent("pick_event", self.figure.canvas,
mouseevent, self, **prop)._process()
# Pick children
for a in self.get_children():
# make sure the event happened in the same Axes
ax = getattr(a, 'axes', None)
if (mouseevent.inaxes is None or ax is None
or mouseevent.inaxes == ax):
# we need to check if mouseevent.inaxes is None
# because some objects associated with an Axes (e.g., a
# tick label) can be outside the bounding box of the
# Axes and inaxes will be None
# also check that ax is None so that it traverse objects
# which do not have an axes property but children might
a.pick(mouseevent)
def set_picker(self, picker):
"""
Define the picking behavior of the artist.
Parameters
----------
picker : None or bool or float or callable
This can be one of the following:
- *None*: Picking is disabled for this artist (default).
- A boolean: If *True* then picking will be enabled and the
artist will fire a pick event if the mouse event is over
the artist.
- A float: If picker is a number it is interpreted as an
epsilon tolerance in points and the artist will fire
off an event if its data is within epsilon of the mouse
event. For some artists like lines and patch collections,
the artist may provide additional data to the pick event
that is generated, e.g., the indices of the data within
epsilon of the pick event
- A function: If picker is callable, it is a user supplied
function which determines whether the artist is hit by the
mouse event::
hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the
artist, return *hit=True* and props is a dictionary of
properties you want added to the PickEvent attributes.
"""
self._picker = picker
def get_picker(self):
"""
Return the picking behavior of the artist.
The possible values are described in `.set_picker`.
See Also
--------
set_picker, pickable, pick
"""
return self._picker
def get_url(self):
"""Return the url."""
return self._url
def set_url(self, url):
"""
Set the url for the artist.
Parameters
----------
url : str
"""
self._url = url
def get_gid(self):
"""Return the group id."""
return self._gid
def set_gid(self, gid):
"""
Set the (group) id for the artist.
Parameters
----------
gid : str
"""
self._gid = gid
def get_snap(self):
"""
Return the snap setting.
See `.set_snap` for details.
"""
if mpl.rcParams['path.snap']:
return self._snap
else:
return False
def set_snap(self, snap):
"""
Set the snapping behavior.
Snapping aligns positions with the pixel grid, which results in
clearer images. For example, if a black line of 1px width was
defined at a position in between two pixels, the resulting image
would contain the interpolated value of that line in the pixel grid,
which would be a grey value on both adjacent pixel positions. In
contrast, snapping will move the line to the nearest integer pixel
value, so that the resulting image will really contain a 1px wide
black line.
Snapping is currently only supported by the Agg and MacOSX backends.
Parameters
----------
snap : bool or None
Possible values:
- *True*: Snap vertices to the nearest pixel center.
- *False*: Do not modify vertex positions.
- *None*: (auto) If the path contains only rectilinear line
segments, round to the nearest pixel center.
"""
self._snap = snap
self.stale = True
def get_sketch_params(self):
"""
Return the sketch parameters for the artist.
Returns
-------
tuple or None
A 3-tuple with the following elements:
- *scale*: The amplitude of the wiggle perpendicular to the
source line.
- *length*: The length of the wiggle along the line.
- *randomness*: The scale factor by which the length is
shrunken or expanded.
Returns *None* if no sketch parameters were set.
"""
return self._sketch
def set_sketch_params(self, scale=None, length=None, randomness=None):
"""
Set the sketch parameters.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source
line, in pixels. If scale is `None`, or not provided, no
sketch filter will be provided.
length : float, optional
The length of the wiggle along the line, in pixels
(default 128.0)
randomness : float, optional
The scale factor by which the length is shrunken or
expanded (default 16.0)
The PGF backend uses this argument as an RNG seed and not as
described above. Using the same seed yields the same random shape.
.. ACCEPTS: (scale: float, length: float, randomness: float)
"""
if scale is None:
self._sketch = None
else:
self._sketch = (scale, length or 128.0, randomness or 16.0)
self.stale = True
def set_path_effects(self, path_effects):
"""
Set the path effects.
Parameters
----------
path_effects : `.AbstractPathEffect`
"""
self._path_effects = path_effects
self.stale = True
def get_path_effects(self):
return self._path_effects
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
def set_figure(self, fig):
"""
Set the `.Figure` instance the artist belongs to.
Parameters
----------
fig : `.Figure`
"""
# if this is a no-op just return
if self.figure is fig:
return
# if we currently have a figure (the case of both `self.figure`
# and *fig* being none is taken care of above) we then user is
# trying to change the figure an artist is associated with which
# is not allowed for the same reason as adding the same instance
# to more than one Axes
if self.figure is not None:
raise RuntimeError("Can not put single artist in "
"more than one figure")
self.figure = fig
if self.figure and self.figure is not self:
self.pchanged()
self.stale = True
def set_clip_box(self, clipbox):
"""
Set the artist's clip `.Bbox`.
Parameters
----------
clipbox : `.Bbox`
Typically would be created from a `.TransformedBbox`. For
instance ``TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes)``
is the default clipping for an artist added to an Axes.
"""
self.clipbox = clipbox
self.pchanged()
self.stale = True
def set_clip_path(self, path, transform=None):
"""
Set the artist's clip path.
Parameters
----------
path : `.Patch` or `.Path` or `.TransformedPath` or None
The clip path. If given a `.Path`, *transform* must be provided as
well. If *None*, a previously set clip path is removed.
transform : `~matplotlib.transforms.Transform`, optional
Only used if *path* is a `.Path`, in which case the given `.Path`
is converted to a `.TransformedPath` using *transform*.
Notes
-----
For efficiency, if *path* is a `.Rectangle` this method will set the
clipping box to the corresponding rectangle and set the clipping path
to ``None``.
For technical reasons (support of `~.Artist.set`), a tuple
(*path*, *transform*) is also accepted as a single positional
parameter.
.. ACCEPTS: Patch or (Path, Transform) or None
"""
from matplotlib.patches import Patch, Rectangle
success = False
if transform is None:
if isinstance(path, Rectangle):
self.clipbox = TransformedBbox(Bbox.unit(),
path.get_transform())
self._clippath = None
success = True
elif isinstance(path, Patch):
self._clippath = TransformedPatchPath(path)
success = True
elif isinstance(path, tuple):
path, transform = path
if path is None:
self._clippath = None
success = True
elif isinstance(path, Path):
self._clippath = TransformedPath(path, transform)
success = True
elif isinstance(path, TransformedPatchPath):
self._clippath = path
success = True
elif isinstance(path, TransformedPath):
self._clippath = path
success = True
if not success:
raise TypeError(
"Invalid arguments to set_clip_path, of type {} and {}"
.format(type(path).__name__, type(transform).__name__))
# This may result in the callbacks being hit twice, but guarantees they
# will be hit at least once.
self.pchanged()
self.stale = True
def get_alpha(self):
"""
Return the alpha value used for blending - not supported on all
backends.
"""
return self._alpha
def get_visible(self):
"""Return the visibility."""
return self._visible
def get_animated(self):
"""Return whether the artist is animated."""
return self._animated
def get_in_layout(self):
"""
Return boolean flag, ``True`` if artist is included in layout
calculations.
E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,
`.Figure.tight_layout()`, and
``fig.savefig(fname, bbox_inches='tight')``.
"""
return self._in_layout
def _fully_clipped_to_axes(self):
"""
Return a boolean flag, ``True`` if the artist is clipped to the Axes
and can thus be skipped in layout calculations. Requires `get_clip_on`
is True, one of `clip_box` or `clip_path` is set, ``clip_box.extents``
is equivalent to ``ax.bbox.extents`` (if set), and ``clip_path._patch``
is equivalent to ``ax.patch`` (if set).
"""
# Note that ``clip_path.get_fully_transformed_path().get_extents()``
# cannot be directly compared to ``axes.bbox.extents`` because the
# extents may be undefined (i.e. equivalent to ``Bbox.null()``)
# before the associated artist is drawn, and this method is meant
# to determine whether ``axes.get_tightbbox()`` may bypass drawing
clip_box = self.get_clip_box()
clip_path = self.get_clip_path()
return (self.axes is not None
and self.get_clip_on()
and (clip_box is not None or clip_path is not None)
and (clip_box is None
or np.all(clip_box.extents == self.axes.bbox.extents))
and (clip_path is None
or isinstance(clip_path, TransformedPatchPath)
and clip_path._patch is self.axes.patch))
def get_clip_on(self):
"""Return whether the artist uses clipping."""
return self._clipon
def get_clip_box(self):
"""Return the clipbox."""
return self.clipbox
def get_clip_path(self):
"""Return the clip path."""
return self._clippath
def get_transformed_clip_path_and_affine(self):
"""
Return the clip path with the non-affine part of its
transformation applied, and the remaining affine part of its
transformation.
"""
if self._clippath is not None:
return self._clippath.get_transformed_path_and_affine()
return None, None
def set_clip_on(self, b):
"""
Set whether the artist uses clipping.
When False, artists will be visible outside the Axes which
can lead to unexpected results.
Parameters
----------
b : bool
"""
self._clipon = b
# This may result in the callbacks being hit twice, but ensures they
# are hit at least once
self.pchanged()
self.stale = True
def _set_gc_clip(self, gc):
"""Set the clip properly for the gc."""
if self._clipon:
if self.clipbox is not None:
gc.set_clip_rectangle(self.clipbox)
gc.set_clip_path(self._clippath)
else:
gc.set_clip_rectangle(None)
gc.set_clip_path(None)
def get_rasterized(self):
"""Return whether the artist is to be rasterized."""
return self._rasterized
def set_rasterized(self, rasterized):
"""
Force rasterized (bitmap) drawing for vector graphics output.
Rasterized drawing is not supported by all artists. If you try to
enable this on an artist that does not support it, the command has no
effect and a warning will be issued.
This setting is ignored for pixel-based output.
See also :doc:`/gallery/misc/rasterization_demo`.
Parameters
----------
rasterized : bool
"""
supports_rasterization = getattr(self.draw,
"_supports_rasterization", False)
if rasterized and not supports_rasterization:
_api.warn_external(f"Rasterization of '{self}' will be ignored")
self._rasterized = rasterized
def get_agg_filter(self):
"""Return filter function to be used for agg filter."""
return self._agg_filter
def set_agg_filter(self, filter_func):
"""
Set the agg filter.
Parameters
----------
filter_func : callable
A filter function, which takes a (m, n, depth) float array
and a dpi value, and returns a (m, n, depth) array and two
offsets from the bottom left corner of the image
.. ACCEPTS: a filter function, which takes a (m, n, 3) float array
and a dpi value, and returns a (m, n, 3) array and two offsets
from the bottom left corner of the image
"""
self._agg_filter = filter_func
self.stale = True
def draw(self, renderer):
"""
Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (`.Artist.get_visible`
returns False).
Parameters
----------
renderer : `.RendererBase` subclass.
Notes
-----
This method is overridden in the Artist subclasses.
"""
if not self.get_visible():
return
self.stale = False
def set_alpha(self, alpha):
"""
Set the alpha value used for blending - not supported on all backends.
Parameters
----------
alpha : scalar or None
*alpha* must be within the 0-1 range, inclusive.
"""
if alpha is not None and not isinstance(alpha, Number):
raise TypeError(
f'alpha must be numeric or None, not {type(alpha)}')
if alpha is not None and not (0 <= alpha <= 1):
raise ValueError(f'alpha ({alpha}) is outside 0-1 range')
self._alpha = alpha
self.pchanged()
self.stale = True
def _set_alpha_for_array(self, alpha):
"""
Set the alpha value used for blending - not supported on all backends.
Parameters
----------
alpha : array-like or scalar or None
All values must be within the 0-1 range, inclusive.
Masked values and nans are not supported.
"""
if isinstance(alpha, str):
raise TypeError("alpha must be numeric or None, not a string")
if not np.iterable(alpha):
Artist.set_alpha(self, alpha)
return
alpha = np.asarray(alpha)
if not (0 <= alpha.min() and alpha.max() <= 1):
raise ValueError('alpha must be between 0 and 1, inclusive, '
f'but min is {alpha.min()}, max is {alpha.max()}')
self._alpha = alpha
self.pchanged()
self.stale = True
def set_visible(self, b):
"""
Set the artist's visibility.
Parameters
----------
b : bool
"""
self._visible = b
self.pchanged()
self.stale = True
def set_animated(self, b):
"""
Set whether the artist is intended to be used in an animation.
If True, the artist is excluded from regular drawing of the figure.
You have to call `.Figure.draw_artist` / `.Axes.draw_artist`
explicitly on the artist. This approach is used to speed up animations
using blitting.
See also `matplotlib.animation` and
:doc:`/tutorials/advanced/blitting`.
Parameters
----------
b : bool
"""
if self._animated != b:
self._animated = b
self.pchanged()
def set_in_layout(self, in_layout):
"""
Set if artist is to be included in layout calculations,
E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,
`.Figure.tight_layout()`, and
``fig.savefig(fname, bbox_inches='tight')``.
Parameters
----------
in_layout : bool
"""
self._in_layout = in_layout
def get_label(self):
"""Return the label used for this artist in the legend."""
return self._label
def set_label(self, s):
"""
Set a label that will be displayed in the legend.
Parameters
----------
s : object
*s* will be converted to a string by calling `str`.
"""
if s is not None:
self._label = str(s)
else:
self._label = None
self.pchanged()
self.stale = True
def get_zorder(self):
"""Return the artist's zorder."""
return self.zorder
def set_zorder(self, level):
"""
Set the zorder for the artist. Artists with lower zorder
values are drawn first.
Parameters
----------
level : float
"""
if level is None:
level = self.__class__.zorder
self.zorder = level
self.pchanged()
self.stale = True
def sticky_edges(self):
"""
``x`` and ``y`` sticky edge lists for autoscaling.
When performing autoscaling, if a data limit coincides with a value in
the corresponding sticky_edges list, then no margin will be added--the
view limit "sticks" to the edge. A typical use case is histograms,
where one usually expects no margin on the bottom edge (0) of the
histogram.
Moreover, margin expansion "bumps" against sticky edges and cannot
cross them. For example, if the upper data limit is 1.0, the upper
view limit computed by simple margin application is 1.2, but there is a
sticky edge at 1.1, then the actual upper view limit will be 1.1.
This attribute cannot be assigned to; however, the ``x`` and ``y``
lists can be modified in place as needed.
Examples
--------
>>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
"""
return self._sticky_edges
def update_from(self, other):
"""Copy properties from *other* to *self*."""
self._transform = other._transform
self._transformSet = other._transformSet
self._visible = other._visible
self._alpha = other._alpha
self.clipbox = other.clipbox
self._clipon = other._clipon
self._clippath = other._clippath
self._label = other._label
self._sketch = other._sketch
self._path_effects = other._path_effects
self.sticky_edges.x[:] = other.sticky_edges.x.copy()
self.sticky_edges.y[:] = other.sticky_edges.y.copy()
self.pchanged()
self.stale = True
def properties(self):
"""Return a dictionary of all the properties of the artist."""
return ArtistInspector(self).properties()
def _update_props(self, props, errfmt):
"""
Helper for `.Artist.set` and `.Artist.update`.
*errfmt* is used to generate error messages for invalid property
names; it gets formatted with ``type(self)`` and the property name.
"""
ret = []
with cbook._setattr_cm(self, eventson=False):
for k, v in props.items():
# Allow attributes we want to be able to update through
# art.update, art.set, setp.
if k == "axes":
ret.append(setattr(self, k, v))
else:
func = getattr(self, f"set_{k}", None)
if not callable(func):
raise AttributeError(
errfmt.format(cls=type(self), prop_name=k))
ret.append(func(v))
if ret:
self.pchanged()
self.stale = True
return ret
def update(self, props):
"""
Update this artist's properties from the dict *props*.
Parameters
----------
props : dict
"""
return self._update_props(
props, "{cls.__name__!r} object has no property {prop_name!r}")
def _internal_update(self, kwargs):
"""
Update artist properties without prenormalizing them, but generating
errors as if calling `set`.
The lack of prenormalization is to maintain backcompatibility.
"""
return self._update_props(
kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
"{prop_name!r}")
def set(self, **kwargs):
# docstring and signature are auto-generated via
# Artist._update_set_signature_and_docstring() at the end of the
# module.
return self._internal_update(cbook.normalize_kwargs(kwargs, self))
def _cm_set(self, **kwargs):
"""
`.Artist.set` context-manager that restores original values at exit.
"""
orig_vals = {k: getattr(self, f"get_{k}")() for k in kwargs}
try:
self.set(**kwargs)
yield
finally:
self.set(**orig_vals)
def findobj(self, match=None, include_self=True):
"""
Find artist objects.
Recursively find all `.Artist` instances contained in the artist.
Parameters
----------
match
A filter criterion for the matches. This can be
- *None*: Return all objects contained in artist.
- A function with signature ``def match(artist: Artist) -> bool``.
The result will only contain artists for which the function
returns *True*.
- A class instance: e.g., `.Line2D`. The result will only contain
artists of this class or its subclasses (``isinstance`` check).
include_self : bool
Include *self* in the list to be checked for a match.
Returns
-------
list of `.Artist`
"""
if match is None: # always return True
def matchfunc(x):
return True
elif isinstance(match, type) and issubclass(match, Artist):
def matchfunc(x):
return isinstance(x, match)
elif callable(match):
matchfunc = match
else:
raise ValueError('match must be None, a matplotlib.artist.Artist '
'subclass, or a callable')
artists = sum([c.findobj(matchfunc) for c in self.get_children()], [])
if include_self and matchfunc(self):
artists.append(self)
return artists
def get_cursor_data(self, event):
"""
Return the cursor data for a given event.
.. note::
This method is intended to be overridden by artist subclasses.
As an end-user of Matplotlib you will most likely not call this
method yourself.
Cursor data can be used by Artists to provide additional context
information for a given event. The default implementation just returns
*None*.
Subclasses can override the method and return arbitrary data. However,
when doing so, they must ensure that `.format_cursor_data` can convert
the data to a string representation.
The only current use case is displaying the z-value of an `.AxesImage`
in the status bar of a plot window, while moving the mouse.
Parameters
----------
event : `matplotlib.backend_bases.MouseEvent`
See Also
--------
format_cursor_data
"""
return None
def format_cursor_data(self, data):
"""
Return a string representation of *data*.
.. note::
This method is intended to be overridden by artist subclasses.
As an end-user of Matplotlib you will most likely not call this
method yourself.
The default implementation converts ints and floats and arrays of ints
and floats into a comma-separated string enclosed in square brackets,
unless the artist has an associated colorbar, in which case scalar
values are formatted using the colorbar's formatter.
See Also
--------
get_cursor_data
"""
if np.ndim(data) == 0 and isinstance(self, ScalarMappable):
# This block logically belongs to ScalarMappable, but can't be
# implemented in it because most ScalarMappable subclasses inherit
# from Artist first and from ScalarMappable second, so
# Artist.format_cursor_data would always have precedence over
# ScalarMappable.format_cursor_data.
n = self.cmap.N
if np.ma.getmask(data):
return "[]"
normed = self.norm(data)
if np.isfinite(normed):
if isinstance(self.norm, BoundaryNorm):
# not an invertible normalization mapping
cur_idx = np.argmin(np.abs(self.norm.boundaries - data))
neigh_idx = max(0, cur_idx - 1)
# use max diff to prevent delta == 0
delta = np.diff(
self.norm.boundaries[neigh_idx:cur_idx + 2]
).max()
else:
# Midpoints of neighboring color intervals.
neighbors = self.norm.inverse(
(int(normed * n) + np.array([0, 1])) / n)
delta = abs(neighbors - data).max()
g_sig_digits = cbook._g_sig_digits(data, delta)
else:
g_sig_digits = 3 # Consistent with default below.
return "[{:-#.{}g}]".format(data, g_sig_digits)
else:
try:
data[0]
except (TypeError, IndexError):
data = [data]
data_str = ', '.join('{:0.3g}'.format(item) for item in data
if isinstance(item, Number))
return "[" + data_str + "]"
def get_mouseover(self):
"""
Return whether this artist is queried for custom context information
when the mouse cursor moves over it.
"""
return self._mouseover
def set_mouseover(self, mouseover):
"""
Set whether this artist is queried for custom context information when
the mouse cursor moves over it.
Parameters
----------
mouseover : bool
See Also
--------
get_cursor_data
.ToolCursorPosition
.NavigationToolbar2
"""
self._mouseover = bool(mouseover)
ax = self.axes
if ax:
if self._mouseover:
ax._mouseover_set.add(self)
else:
ax._mouseover_set.discard(self)
mouseover = property(get_mouseover, set_mouseover) # backcompat.
Artist._update_set_signature_and_docstring()
The provided code snippet includes necessary dependencies for implementing the `_parse_legend_args` function. Write a Python function `def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs)` to solve the following problem:
Get the handles and labels from the calls to either ``figure.legend`` or ``axes.legend``. The parser is a bit involved because we support:: legend() legend(labels) legend(handles, labels) legend(labels=labels) legend(handles=handles) legend(handles=handles, labels=labels) The behavior for a mixture of positional and keyword handles and labels is undefined and issues a warning. Parameters ---------- axs : list of `.Axes` If handles are not given explicitly, the artists in these Axes are used as handles. *args : tuple Positional parameters passed to ``legend()``. handles The value of the keyword argument ``legend(handles=...)``, or *None* if that keyword argument was not used. labels The value of the keyword argument ``legend(labels=...)``, or *None* if that keyword argument was not used. **kwargs All other keyword arguments passed to ``legend()``. Returns ------- handles : list of `.Artist` The legend handles. labels : list of str The legend labels. extra_args : tuple *args* with positional handles and labels removed. kwargs : dict *kwargs* with keywords handles and labels removed.
Here is the function:
def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
"""
Get the handles and labels from the calls to either ``figure.legend``
or ``axes.legend``.
The parser is a bit involved because we support::
legend()
legend(labels)
legend(handles, labels)
legend(labels=labels)
legend(handles=handles)
legend(handles=handles, labels=labels)
The behavior for a mixture of positional and keyword handles and labels
is undefined and issues a warning.
Parameters
----------
axs : list of `.Axes`
If handles are not given explicitly, the artists in these Axes are
used as handles.
*args : tuple
Positional parameters passed to ``legend()``.
handles
The value of the keyword argument ``legend(handles=...)``, or *None*
if that keyword argument was not used.
labels
The value of the keyword argument ``legend(labels=...)``, or *None*
if that keyword argument was not used.
**kwargs
All other keyword arguments passed to ``legend()``.
Returns
-------
handles : list of `.Artist`
The legend handles.
labels : list of str
The legend labels.
extra_args : tuple
*args* with positional handles and labels removed.
kwargs : dict
*kwargs* with keywords handles and labels removed.
"""
log = logging.getLogger(__name__)
handlers = kwargs.get('handler_map')
extra_args = ()
if (handles is not None or labels is not None) and args:
_api.warn_external("You have mixed positional and keyword arguments, "
"some input may be discarded.")
# if got both handles and labels as kwargs, make same length
if handles and labels:
handles, labels = zip(*zip(handles, labels))
elif handles is not None and labels is None:
labels = [handle.get_label() for handle in handles]
elif labels is not None and handles is None:
# Get as many handles as there are labels.
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]
# No arguments - automatically detect labels and handles.
elif len(args) == 0:
handles, labels = _get_legend_handles_labels(axs, handlers)
if not handles:
log.warning(
"No artists with labels found to put in legend. Note that "
"artists whose label start with an underscore are ignored "
"when legend() is called with no argument.")
# One argument. User defined labels - automatic handle detection.
elif len(args) == 1:
labels, = args
if any(isinstance(l, Artist) for l in labels):
raise TypeError("A single argument passed to legend() must be a "
"list of labels, but found an Artist in there.")
# Get as many handles as there are labels.
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]
# Two arguments:
# * user defined handles and labels
elif len(args) >= 2:
handles, labels = args[:2]
extra_args = args[2:]
else:
raise TypeError('Invalid arguments to legend.')
return handles, labels, extra_args, kwargs | Get the handles and labels from the calls to either ``figure.legend`` or ``axes.legend``. The parser is a bit involved because we support:: legend() legend(labels) legend(handles, labels) legend(labels=labels) legend(handles=handles) legend(handles=handles, labels=labels) The behavior for a mixture of positional and keyword handles and labels is undefined and issues a warning. Parameters ---------- axs : list of `.Axes` If handles are not given explicitly, the artists in these Axes are used as handles. *args : tuple Positional parameters passed to ``legend()``. handles The value of the keyword argument ``legend(handles=...)``, or *None* if that keyword argument was not used. labels The value of the keyword argument ``legend(labels=...)``, or *None* if that keyword argument was not used. **kwargs All other keyword arguments passed to ``legend()``. Returns ------- handles : list of `.Artist` The legend handles. labels : list of str The legend labels. extra_args : tuple *args* with positional handles and labels removed. kwargs : dict *kwargs* with keywords handles and labels removed. |
171,262 | import functools
from numbers import Number
import numpy as np
from matplotlib import _api, _docstring, cbook
The provided code snippet includes necessary dependencies for implementing the `window_none` function. Write a Python function `def window_none(x)` to solve the following problem:
No window function; simply return *x*. See Also -------- window_hanning : Another window algorithm.
Here is the function:
def window_none(x):
"""
No window function; simply return *x*.
See Also
--------
window_hanning : Another window algorithm.
"""
return x | No window function; simply return *x*. See Also -------- window_hanning : Another window algorithm. |
171,263 | import functools
from numbers import Number
import numpy as np
from matplotlib import _api, _docstring, cbook
def _stride_windows(x, n, noverlap=0, axis=0):
# np>=1.20 provides sliding_window_view, and we only ever use axis=0.
if hasattr(np.lib.stride_tricks, "sliding_window_view") and axis == 0:
if noverlap >= n:
raise ValueError('noverlap must be less than n')
return np.lib.stride_tricks.sliding_window_view(
x, n, axis=0)[::n - noverlap].T
if noverlap >= n:
raise ValueError('noverlap must be less than n')
if n < 1:
raise ValueError('n cannot be less than 1')
x = np.asarray(x)
if n == 1 and noverlap == 0:
if axis == 0:
return x[np.newaxis]
else:
return x[np.newaxis].T
if n > x.size:
raise ValueError('n cannot be greater than the length of x')
# np.lib.stride_tricks.as_strided easily leads to memory corruption for
# non integer shape and strides, i.e. noverlap or n. See #3845.
noverlap = int(noverlap)
n = int(n)
step = n - noverlap
if axis == 0:
shape = (n, (x.shape[-1]-noverlap)//step)
strides = (x.strides[0], step*x.strides[0])
else:
shape = ((x.shape[-1]-noverlap)//step, n)
strides = (step*x.strides[0], x.strides[0])
return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
The provided code snippet includes necessary dependencies for implementing the `stride_windows` function. Write a Python function `def stride_windows(x, n, noverlap=None, axis=0)` to solve the following problem:
Get all windows of *x* with length *n* as a single array, using strides to avoid data duplication. .. warning:: It is not safe to write to the output array. Multiple elements may point to the same piece of memory, so modifying one value may change others. Parameters ---------- x : 1D array or sequence Array or sequence containing the data. n : int The number of data points in each window. noverlap : int, default: 0 (no overlap) The overlap between adjacent windows. axis : int The axis along which the windows will run. References ---------- `stackoverflow: Rolling window for 1D arrays in Numpy? <https://stackoverflow.com/a/6811241>`_ `stackoverflow: Using strides for an efficient moving average filter <https://stackoverflow.com/a/4947453>`_
Here is the function:
def stride_windows(x, n, noverlap=None, axis=0):
"""
Get all windows of *x* with length *n* as a single array,
using strides to avoid data duplication.
.. warning::
It is not safe to write to the output array. Multiple
elements may point to the same piece of memory,
so modifying one value may change others.
Parameters
----------
x : 1D array or sequence
Array or sequence containing the data.
n : int
The number of data points in each window.
noverlap : int, default: 0 (no overlap)
The overlap between adjacent windows.
axis : int
The axis along which the windows will run.
References
----------
`stackoverflow: Rolling window for 1D arrays in Numpy?
<https://stackoverflow.com/a/6811241>`_
`stackoverflow: Using strides for an efficient moving average filter
<https://stackoverflow.com/a/4947453>`_
"""
if noverlap is None:
noverlap = 0
if np.ndim(x) != 1:
raise ValueError('only 1-dimensional arrays can be used')
return _stride_windows(x, n, noverlap, axis) | Get all windows of *x* with length *n* as a single array, using strides to avoid data duplication. .. warning:: It is not safe to write to the output array. Multiple elements may point to the same piece of memory, so modifying one value may change others. Parameters ---------- x : 1D array or sequence Array or sequence containing the data. n : int The number of data points in each window. noverlap : int, default: 0 (no overlap) The overlap between adjacent windows. axis : int The axis along which the windows will run. References ---------- `stackoverflow: Rolling window for 1D arrays in Numpy? <https://stackoverflow.com/a/6811241>`_ `stackoverflow: Using strides for an efficient moving average filter <https://stackoverflow.com/a/4947453>`_ |
171,264 | import functools
from numbers import Number
import numpy as np
from matplotlib import _api, _docstring, cbook
def detrend_none(x, axis=None):
"""
Return *x*: no detrending.
Parameters
----------
x : any object
An object containing the data
axis : int
This parameter is ignored.
It is included for compatibility with detrend_mean
See Also
--------
detrend_mean : Another detrend algorithm.
detrend_linear : Another detrend algorithm.
detrend : A wrapper around all the detrend algorithms.
"""
return x
def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
window=None, noverlap=None, pad_to=None,
sides=None, scale_by_freq=None, mode=None):
"""
Private helper implementing the common parts between the psd, csd,
spectrogram and complex, magnitude, angle, and phase spectrums.
"""
if y is None:
# if y is None use x for y
same_data = True
else:
# The checks for if y is x are so that we can use the same function to
# implement the core of psd(), csd(), and spectrogram() without doing
# extra calculations. We return the unaveraged Pxy, freqs, and t.
same_data = y is x
if Fs is None:
Fs = 2
if noverlap is None:
noverlap = 0
if detrend_func is None:
detrend_func = detrend_none
if window is None:
window = window_hanning
# if NFFT is set to None use the whole signal
if NFFT is None:
NFFT = 256
if mode is None or mode == 'default':
mode = 'psd'
_api.check_in_list(
['default', 'psd', 'complex', 'magnitude', 'angle', 'phase'],
mode=mode)
if not same_data and mode != 'psd':
raise ValueError("x and y must be equal if mode is not 'psd'")
# Make sure we're dealing with a numpy array. If y and x were the same
# object to start with, keep them that way
x = np.asarray(x)
if not same_data:
y = np.asarray(y)
if sides is None or sides == 'default':
if np.iscomplexobj(x):
sides = 'twosided'
else:
sides = 'onesided'
_api.check_in_list(['default', 'onesided', 'twosided'], sides=sides)
# zero pad x and y up to NFFT if they are shorter than NFFT
if len(x) < NFFT:
n = len(x)
x = np.resize(x, NFFT)
x[n:] = 0
if not same_data and len(y) < NFFT:
n = len(y)
y = np.resize(y, NFFT)
y[n:] = 0
if pad_to is None:
pad_to = NFFT
if mode != 'psd':
scale_by_freq = False
elif scale_by_freq is None:
scale_by_freq = True
# For real x, ignore the negative frequencies unless told otherwise
if sides == 'twosided':
numFreqs = pad_to
if pad_to % 2:
freqcenter = (pad_to - 1)//2 + 1
else:
freqcenter = pad_to//2
scaling_factor = 1.
elif sides == 'onesided':
if pad_to % 2:
numFreqs = (pad_to + 1)//2
else:
numFreqs = pad_to//2 + 1
scaling_factor = 2.
if not np.iterable(window):
window = window(np.ones(NFFT, x.dtype))
if len(window) != NFFT:
raise ValueError(
"The window length must match the data's first dimension")
result = _stride_windows(x, NFFT, noverlap)
result = detrend(result, detrend_func, axis=0)
result = result * window.reshape((-1, 1))
result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :]
freqs = np.fft.fftfreq(pad_to, 1/Fs)[:numFreqs]
if not same_data:
# if same_data is False, mode must be 'psd'
resultY = _stride_windows(y, NFFT, noverlap)
resultY = detrend(resultY, detrend_func, axis=0)
resultY = resultY * window.reshape((-1, 1))
resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :]
result = np.conj(result) * resultY
elif mode == 'psd':
result = np.conj(result) * result
elif mode == 'magnitude':
result = np.abs(result) / window.sum()
elif mode == 'angle' or mode == 'phase':
# we unwrap the phase later to handle the onesided vs. twosided case
result = np.angle(result)
elif mode == 'complex':
result /= window.sum()
if mode == 'psd':
# Also include scaling factors for one-sided densities and dividing by
# the sampling frequency, if desired. Scale everything, except the DC
# component and the NFFT/2 component:
# if we have a even number of frequencies, don't scale NFFT/2
if not NFFT % 2:
slc = slice(1, -1, None)
# if we have an odd number, just don't scale DC
else:
slc = slice(1, None, None)
result[slc] *= scaling_factor
# MATLAB divides by the sampling frequency so that density function
# has units of dB/Hz and can be integrated by the plotted frequency
# values. Perform the same scaling here.
if scale_by_freq:
result /= Fs
# Scale the spectrum by the norm of the window to compensate for
# windowing loss; see Bendat & Piersol Sec 11.5.2.
result /= (window**2).sum()
else:
# In this case, preserve power in the segment, not amplitude
result /= window.sum()**2
t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs
if sides == 'twosided':
# center the frequency range at zero
freqs = np.roll(freqs, -freqcenter, axis=0)
result = np.roll(result, -freqcenter, axis=0)
elif not pad_to % 2:
# get the last value correctly, it is negative otherwise
freqs[-1] *= -1
# we unwrap the phase here to handle the onesided vs. twosided case
if mode == 'phase':
result = np.unwrap(result, axis=0)
return result, freqs, t
The provided code snippet includes necessary dependencies for implementing the `_single_spectrum_helper` function. Write a Python function `def _single_spectrum_helper( mode, x, Fs=None, window=None, pad_to=None, sides=None)` to solve the following problem:
Private helper implementing the commonality between the complex, magnitude, angle, and phase spectrums.
Here is the function:
def _single_spectrum_helper(
mode, x, Fs=None, window=None, pad_to=None, sides=None):
"""
Private helper implementing the commonality between the complex, magnitude,
angle, and phase spectrums.
"""
_api.check_in_list(['complex', 'magnitude', 'angle', 'phase'], mode=mode)
if pad_to is None:
pad_to = len(x)
spec, freqs, _ = _spectral_helper(x=x, y=None, NFFT=len(x), Fs=Fs,
detrend_func=detrend_none, window=window,
noverlap=0, pad_to=pad_to,
sides=sides,
scale_by_freq=False,
mode=mode)
if mode != 'complex':
spec = spec.real
if spec.ndim == 2 and spec.shape[1] == 1:
spec = spec[:, 0]
return spec, freqs | Private helper implementing the commonality between the complex, magnitude, angle, and phase spectrums. |
171,265 | import functools
from numbers import Number
import numpy as np
from matplotlib import _api, _docstring, cbook
def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
window=None, noverlap=None, pad_to=None,
sides=None, scale_by_freq=None, mode=None):
"""
Private helper implementing the common parts between the psd, csd,
spectrogram and complex, magnitude, angle, and phase spectrums.
"""
if y is None:
# if y is None use x for y
same_data = True
else:
# The checks for if y is x are so that we can use the same function to
# implement the core of psd(), csd(), and spectrogram() without doing
# extra calculations. We return the unaveraged Pxy, freqs, and t.
same_data = y is x
if Fs is None:
Fs = 2
if noverlap is None:
noverlap = 0
if detrend_func is None:
detrend_func = detrend_none
if window is None:
window = window_hanning
# if NFFT is set to None use the whole signal
if NFFT is None:
NFFT = 256
if mode is None or mode == 'default':
mode = 'psd'
_api.check_in_list(
['default', 'psd', 'complex', 'magnitude', 'angle', 'phase'],
mode=mode)
if not same_data and mode != 'psd':
raise ValueError("x and y must be equal if mode is not 'psd'")
# Make sure we're dealing with a numpy array. If y and x were the same
# object to start with, keep them that way
x = np.asarray(x)
if not same_data:
y = np.asarray(y)
if sides is None or sides == 'default':
if np.iscomplexobj(x):
sides = 'twosided'
else:
sides = 'onesided'
_api.check_in_list(['default', 'onesided', 'twosided'], sides=sides)
# zero pad x and y up to NFFT if they are shorter than NFFT
if len(x) < NFFT:
n = len(x)
x = np.resize(x, NFFT)
x[n:] = 0
if not same_data and len(y) < NFFT:
n = len(y)
y = np.resize(y, NFFT)
y[n:] = 0
if pad_to is None:
pad_to = NFFT
if mode != 'psd':
scale_by_freq = False
elif scale_by_freq is None:
scale_by_freq = True
# For real x, ignore the negative frequencies unless told otherwise
if sides == 'twosided':
numFreqs = pad_to
if pad_to % 2:
freqcenter = (pad_to - 1)//2 + 1
else:
freqcenter = pad_to//2
scaling_factor = 1.
elif sides == 'onesided':
if pad_to % 2:
numFreqs = (pad_to + 1)//2
else:
numFreqs = pad_to//2 + 1
scaling_factor = 2.
if not np.iterable(window):
window = window(np.ones(NFFT, x.dtype))
if len(window) != NFFT:
raise ValueError(
"The window length must match the data's first dimension")
result = _stride_windows(x, NFFT, noverlap)
result = detrend(result, detrend_func, axis=0)
result = result * window.reshape((-1, 1))
result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :]
freqs = np.fft.fftfreq(pad_to, 1/Fs)[:numFreqs]
if not same_data:
# if same_data is False, mode must be 'psd'
resultY = _stride_windows(y, NFFT, noverlap)
resultY = detrend(resultY, detrend_func, axis=0)
resultY = resultY * window.reshape((-1, 1))
resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :]
result = np.conj(result) * resultY
elif mode == 'psd':
result = np.conj(result) * result
elif mode == 'magnitude':
result = np.abs(result) / window.sum()
elif mode == 'angle' or mode == 'phase':
# we unwrap the phase later to handle the onesided vs. twosided case
result = np.angle(result)
elif mode == 'complex':
result /= window.sum()
if mode == 'psd':
# Also include scaling factors for one-sided densities and dividing by
# the sampling frequency, if desired. Scale everything, except the DC
# component and the NFFT/2 component:
# if we have a even number of frequencies, don't scale NFFT/2
if not NFFT % 2:
slc = slice(1, -1, None)
# if we have an odd number, just don't scale DC
else:
slc = slice(1, None, None)
result[slc] *= scaling_factor
# MATLAB divides by the sampling frequency so that density function
# has units of dB/Hz and can be integrated by the plotted frequency
# values. Perform the same scaling here.
if scale_by_freq:
result /= Fs
# Scale the spectrum by the norm of the window to compensate for
# windowing loss; see Bendat & Piersol Sec 11.5.2.
result /= (window**2).sum()
else:
# In this case, preserve power in the segment, not amplitude
result /= window.sum()**2
t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs
if sides == 'twosided':
# center the frequency range at zero
freqs = np.roll(freqs, -freqcenter, axis=0)
result = np.roll(result, -freqcenter, axis=0)
elif not pad_to % 2:
# get the last value correctly, it is negative otherwise
freqs[-1] *= -1
# we unwrap the phase here to handle the onesided vs. twosided case
if mode == 'phase':
result = np.unwrap(result, axis=0)
return result, freqs, t
The provided code snippet includes necessary dependencies for implementing the `specgram` function. Write a Python function `def specgram(x, NFFT=None, Fs=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, mode=None)` to solve the following problem:
Compute a spectrogram. Compute and plot a spectrogram of data in *x*. Data are split into *NFFT* length segments and the spectrum of each section is computed. The windowing function *window* is applied to each segment, and the amount of overlap of each segment is specified with *noverlap*. Parameters ---------- x : array-like 1-D array or sequence. %(Spectral)s %(PSD)s noverlap : int, default: 128 The number of points of overlap between blocks. mode : str, default: 'psd' What sort of spectrum to use: 'psd' Returns the power spectral density. 'complex' Returns the complex-valued frequency spectrum. 'magnitude' Returns the magnitude spectrum. 'angle' Returns the phase spectrum without unwrapping. 'phase' Returns the phase spectrum with unwrapping. Returns ------- spectrum : array-like 2D array, columns are the periodograms of successive segments. freqs : array-like 1-D array, frequencies corresponding to the rows in *spectrum*. t : array-like 1-D array, the times corresponding to midpoints of segments (i.e the columns in *spectrum*). See Also -------- psd : differs in the overlap and in the return values. complex_spectrum : similar, but with complex valued frequencies. magnitude_spectrum : similar single segment when *mode* is 'magnitude'. angle_spectrum : similar to single segment when *mode* is 'angle'. phase_spectrum : similar to single segment when *mode* is 'phase'. Notes ----- *detrend* and *scale_by_freq* only apply when *mode* is set to 'psd'.
Here is the function:
def specgram(x, NFFT=None, Fs=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
mode=None):
"""
Compute a spectrogram.
Compute and plot a spectrogram of data in *x*. Data are split into
*NFFT* length segments and the spectrum of each section is
computed. The windowing function *window* is applied to each
segment, and the amount of overlap of each segment is
specified with *noverlap*.
Parameters
----------
x : array-like
1-D array or sequence.
%(Spectral)s
%(PSD)s
noverlap : int, default: 128
The number of points of overlap between blocks.
mode : str, default: 'psd'
What sort of spectrum to use:
'psd'
Returns the power spectral density.
'complex'
Returns the complex-valued frequency spectrum.
'magnitude'
Returns the magnitude spectrum.
'angle'
Returns the phase spectrum without unwrapping.
'phase'
Returns the phase spectrum with unwrapping.
Returns
-------
spectrum : array-like
2D array, columns are the periodograms of successive segments.
freqs : array-like
1-D array, frequencies corresponding to the rows in *spectrum*.
t : array-like
1-D array, the times corresponding to midpoints of segments
(i.e the columns in *spectrum*).
See Also
--------
psd : differs in the overlap and in the return values.
complex_spectrum : similar, but with complex valued frequencies.
magnitude_spectrum : similar single segment when *mode* is 'magnitude'.
angle_spectrum : similar to single segment when *mode* is 'angle'.
phase_spectrum : similar to single segment when *mode* is 'phase'.
Notes
-----
*detrend* and *scale_by_freq* only apply when *mode* is set to 'psd'.
"""
if noverlap is None:
noverlap = 128 # default in _spectral_helper() is noverlap = 0
if NFFT is None:
NFFT = 256 # same default as in _spectral_helper()
if len(x) <= NFFT:
_api.warn_external("Only one segment is calculated since parameter "
f"NFFT (={NFFT}) >= signal length (={len(x)}).")
spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs,
detrend_func=detrend, window=window,
noverlap=noverlap, pad_to=pad_to,
sides=sides,
scale_by_freq=scale_by_freq,
mode=mode)
if mode != 'complex':
spec = spec.real # Needed since helper implements generically
return spec, freqs, t | Compute a spectrogram. Compute and plot a spectrogram of data in *x*. Data are split into *NFFT* length segments and the spectrum of each section is computed. The windowing function *window* is applied to each segment, and the amount of overlap of each segment is specified with *noverlap*. Parameters ---------- x : array-like 1-D array or sequence. %(Spectral)s %(PSD)s noverlap : int, default: 128 The number of points of overlap between blocks. mode : str, default: 'psd' What sort of spectrum to use: 'psd' Returns the power spectral density. 'complex' Returns the complex-valued frequency spectrum. 'magnitude' Returns the magnitude spectrum. 'angle' Returns the phase spectrum without unwrapping. 'phase' Returns the phase spectrum with unwrapping. Returns ------- spectrum : array-like 2D array, columns are the periodograms of successive segments. freqs : array-like 1-D array, frequencies corresponding to the rows in *spectrum*. t : array-like 1-D array, the times corresponding to midpoints of segments (i.e the columns in *spectrum*). See Also -------- psd : differs in the overlap and in the return values. complex_spectrum : similar, but with complex valued frequencies. magnitude_spectrum : similar single segment when *mode* is 'magnitude'. angle_spectrum : similar to single segment when *mode* is 'angle'. phase_spectrum : similar to single segment when *mode* is 'phase'. Notes ----- *detrend* and *scale_by_freq* only apply when *mode* is set to 'psd'. |
171,266 | import functools
from numbers import Number
import numpy as np
from matplotlib import _api, _docstring, cbook
def window_hanning(x):
"""
Return *x* times the Hanning (or Hann) window of len(*x*).
See Also
--------
window_none : Another window algorithm.
"""
return np.hanning(len(x))*x
def detrend_none(x, axis=None):
"""
Return *x*: no detrending.
Parameters
----------
x : any object
An object containing the data
axis : int
This parameter is ignored.
It is included for compatibility with detrend_mean
See Also
--------
detrend_mean : Another detrend algorithm.
detrend_linear : Another detrend algorithm.
detrend : A wrapper around all the detrend algorithms.
"""
return x
def psd(x, NFFT=None, Fs=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
r"""
Compute the power spectral density.
The power spectral density :math:`P_{xx}` by Welch's average
periodogram method. The vector *x* is divided into *NFFT* length
segments. Each segment is detrended by function *detrend* and
windowed by function *window*. *noverlap* gives the length of
the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
of each segment :math:`i` are averaged to compute :math:`P_{xx}`.
If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(PSD)s
noverlap : int, default: 0 (no overlap)
The number of points of overlap between segments.
Returns
-------
Pxx : 1-D array
The values for the power spectrum :math:`P_{xx}` (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *Pxx*
References
----------
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
Wiley & Sons (1986)
See Also
--------
specgram
`specgram` differs in the default overlap; in not returning the mean of
the segment periodograms; and in returning the times of the segments.
magnitude_spectrum : returns the magnitude spectrum.
csd : returns the spectral density between two signals.
"""
Pxx, freqs = csd(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend=detrend,
window=window, noverlap=noverlap, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq)
return Pxx.real, freqs
def csd(x, y, NFFT=None, Fs=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
"""
Compute the cross-spectral density.
The cross spectral density :math:`P_{xy}` by Welch's average
periodogram method. The vectors *x* and *y* are divided into
*NFFT* length segments. Each segment is detrended by function
*detrend* and windowed by function *window*. *noverlap* gives
the length of the overlap between segments. The product of
the direct FFTs of *x* and *y* are averaged over each segment
to compute :math:`P_{xy}`, with a scaling to correct for power
loss due to windowing.
If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
padded to *NFFT*.
Parameters
----------
x, y : 1-D arrays or sequences
Arrays or sequences containing the data
%(Spectral)s
%(PSD)s
noverlap : int, default: 0 (no overlap)
The number of points of overlap between segments.
Returns
-------
Pxy : 1-D array
The values for the cross spectrum :math:`P_{xy}` before scaling (real
valued)
freqs : 1-D array
The frequencies corresponding to the elements in *Pxy*
References
----------
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
Wiley & Sons (1986)
See Also
--------
psd : equivalent to setting ``y = x``.
"""
if NFFT is None:
NFFT = 256
Pxy, freqs, _ = _spectral_helper(x=x, y=y, NFFT=NFFT, Fs=Fs,
detrend_func=detrend, window=window,
noverlap=noverlap, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq,
mode='psd')
if Pxy.ndim == 2:
if Pxy.shape[1] > 1:
Pxy = Pxy.mean(axis=1)
else:
Pxy = Pxy[:, 0]
return Pxy, freqs
The provided code snippet includes necessary dependencies for implementing the `cohere` function. Write a Python function `def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None)` to solve the following problem:
r""" The coherence between *x* and *y*. Coherence is the normalized cross spectral density: .. math:: C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}} Parameters ---------- x, y Array or sequence containing the data %(Spectral)s %(PSD)s noverlap : int, default: 0 (no overlap) The number of points of overlap between segments. Returns ------- Cxy : 1-D array The coherence vector. freqs : 1-D array The frequencies for the elements in *Cxy*. See Also -------- :func:`psd`, :func:`csd` : For information about the methods used to compute :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`.
Here is the function:
def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
r"""
The coherence between *x* and *y*. Coherence is the normalized
cross spectral density:
.. math::
C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}
Parameters
----------
x, y
Array or sequence containing the data
%(Spectral)s
%(PSD)s
noverlap : int, default: 0 (no overlap)
The number of points of overlap between segments.
Returns
-------
Cxy : 1-D array
The coherence vector.
freqs : 1-D array
The frequencies for the elements in *Cxy*.
See Also
--------
:func:`psd`, :func:`csd` :
For information about the methods used to compute :math:`P_{xy}`,
:math:`P_{xx}` and :math:`P_{yy}`.
"""
if len(x) < 2 * NFFT:
raise ValueError(
"Coherence is calculated by averaging over *NFFT* length "
"segments. Your signal is too short for your choice of *NFFT*.")
Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
scale_by_freq)
Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
scale_by_freq)
Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
scale_by_freq)
Cxy = np.abs(Pxy) ** 2 / (Pxx * Pyy)
return Cxy, f | r""" The coherence between *x* and *y*. Coherence is the normalized cross spectral density: .. math:: C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}} Parameters ---------- x, y Array or sequence containing the data %(Spectral)s %(PSD)s noverlap : int, default: 0 (no overlap) The number of points of overlap between segments. Returns ------- Cxy : 1-D array The coherence vector. freqs : 1-D array The frequencies for the elements in *Cxy*. See Also -------- :func:`psd`, :func:`csd` : For information about the methods used to compute :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`. |
171,267 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
The provided code snippet includes necessary dependencies for implementing the `_arg_raw` function. Write a Python function `def _arg_raw(dvi, delta)` to solve the following problem:
Return *delta* without reading anything more from the dvi file.
Here is the function:
def _arg_raw(dvi, delta):
"""Return *delta* without reading anything more from the dvi file."""
return delta | Return *delta* without reading anything more from the dvi file. |
171,268 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
def _arg(nbytes, signed, dvi, _):
"""
Read *nbytes* bytes, returning the bytes interpreted as a signed integer
if *signed* is true, unsigned otherwise.
"""
return dvi._arg(nbytes, signed)
The provided code snippet includes necessary dependencies for implementing the `_arg_slen` function. Write a Python function `def _arg_slen(dvi, delta)` to solve the following problem:
Read *delta* bytes, returning None if *delta* is zero, and the bytes interpreted as a signed integer otherwise.
Here is the function:
def _arg_slen(dvi, delta):
"""
Read *delta* bytes, returning None if *delta* is zero, and the bytes
interpreted as a signed integer otherwise.
"""
if delta == 0:
return None
return dvi._arg(delta, True) | Read *delta* bytes, returning None if *delta* is zero, and the bytes interpreted as a signed integer otherwise. |
171,269 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
def _arg(nbytes, signed, dvi, _):
"""
Read *nbytes* bytes, returning the bytes interpreted as a signed integer
if *signed* is true, unsigned otherwise.
"""
return dvi._arg(nbytes, signed)
The provided code snippet includes necessary dependencies for implementing the `_arg_slen1` function. Write a Python function `def _arg_slen1(dvi, delta)` to solve the following problem:
Read *delta*+1 bytes, returning the bytes interpreted as signed.
Here is the function:
def _arg_slen1(dvi, delta):
"""
Read *delta*+1 bytes, returning the bytes interpreted as signed.
"""
return dvi._arg(delta + 1, True) | Read *delta*+1 bytes, returning the bytes interpreted as signed. |
171,270 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
def _arg(nbytes, signed, dvi, _):
"""
Read *nbytes* bytes, returning the bytes interpreted as a signed integer
if *signed* is true, unsigned otherwise.
"""
return dvi._arg(nbytes, signed)
The provided code snippet includes necessary dependencies for implementing the `_arg_ulen1` function. Write a Python function `def _arg_ulen1(dvi, delta)` to solve the following problem:
Read *delta*+1 bytes, returning the bytes interpreted as unsigned.
Here is the function:
def _arg_ulen1(dvi, delta):
"""
Read *delta*+1 bytes, returning the bytes interpreted as unsigned.
"""
return dvi._arg(delta + 1, False) | Read *delta*+1 bytes, returning the bytes interpreted as unsigned. |
171,271 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
def _arg(nbytes, signed, dvi, _):
"""
Read *nbytes* bytes, returning the bytes interpreted as a signed integer
if *signed* is true, unsigned otherwise.
"""
return dvi._arg(nbytes, signed)
The provided code snippet includes necessary dependencies for implementing the `_arg_olen1` function. Write a Python function `def _arg_olen1(dvi, delta)` to solve the following problem:
Read *delta*+1 bytes, returning the bytes interpreted as unsigned integer for 0<=*delta*<3 and signed if *delta*==3.
Here is the function:
def _arg_olen1(dvi, delta):
"""
Read *delta*+1 bytes, returning the bytes interpreted as
unsigned integer for 0<=*delta*<3 and signed if *delta*==3.
"""
return dvi._arg(delta + 1, delta == 3) | Read *delta*+1 bytes, returning the bytes interpreted as unsigned integer for 0<=*delta*<3 and signed if *delta*==3. |
171,272 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
_arg_mapping = dict(raw=_arg_raw,
u1=partial(_arg, 1, False),
u4=partial(_arg, 4, False),
s4=partial(_arg, 4, True),
slen=_arg_slen,
olen1=_arg_olen1,
slen1=_arg_slen1,
ulen1=_arg_ulen1)
def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ...
The provided code snippet includes necessary dependencies for implementing the `_dispatch` function. Write a Python function `def _dispatch(table, min, max=None, state=None, args=('raw',))` to solve the following problem:
Decorator for dispatch by opcode. Sets the values in *table* from *min* to *max* to this method, adds a check that the Dvi state matches *state* if not None, reads arguments from the file according to *args*. Parameters ---------- table : dict[int, callable] The dispatch table to be filled in. min, max : int Range of opcodes that calls the registered function; *max* defaults to *min*. state : _dvistate, optional State of the Dvi object in which these opcodes are allowed. args : list[str], default: ['raw'] Sequence of argument specifications: - 'raw': opcode minus minimum - 'u1': read one unsigned byte - 'u4': read four bytes, treat as an unsigned number - 's4': read four bytes, treat as a signed number - 'slen': read (opcode - minimum) bytes, treat as signed - 'slen1': read (opcode - minimum + 1) bytes, treat as signed - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned if under four bytes, signed if four bytes
Here is the function:
def _dispatch(table, min, max=None, state=None, args=('raw',)):
"""
Decorator for dispatch by opcode. Sets the values in *table*
from *min* to *max* to this method, adds a check that the Dvi state
matches *state* if not None, reads arguments from the file according
to *args*.
Parameters
----------
table : dict[int, callable]
The dispatch table to be filled in.
min, max : int
Range of opcodes that calls the registered function; *max* defaults to
*min*.
state : _dvistate, optional
State of the Dvi object in which these opcodes are allowed.
args : list[str], default: ['raw']
Sequence of argument specifications:
- 'raw': opcode minus minimum
- 'u1': read one unsigned byte
- 'u4': read four bytes, treat as an unsigned number
- 's4': read four bytes, treat as a signed number
- 'slen': read (opcode - minimum) bytes, treat as signed
- 'slen1': read (opcode - minimum + 1) bytes, treat as signed
- 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned
- 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned
if under four bytes, signed if four bytes
"""
def decorate(method):
get_args = [_arg_mapping[x] for x in args]
@wraps(method)
def wrapper(self, byte):
if state is not None and self.state != state:
raise ValueError("state precondition failed")
return method(self, *[f(self, byte-min) for f in get_args])
if max is None:
table[min] = wrapper
else:
for i in range(min, max+1):
assert table[i] is None
table[i] = wrapper
return wrapper
return decorate | Decorator for dispatch by opcode. Sets the values in *table* from *min* to *max* to this method, adds a check that the Dvi state matches *state* if not None, reads arguments from the file according to *args*. Parameters ---------- table : dict[int, callable] The dispatch table to be filled in. min, max : int Range of opcodes that calls the registered function; *max* defaults to *min*. state : _dvistate, optional State of the Dvi object in which these opcodes are allowed. args : list[str], default: ['raw'] Sequence of argument specifications: - 'raw': opcode minus minimum - 'u1': read one unsigned byte - 'u4': read four bytes, treat as an unsigned number - 's4': read four bytes, treat as a signed number - 'slen': read (opcode - minimum) bytes, treat as signed - 'slen1': read (opcode - minimum + 1) bytes, treat as signed - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned if under four bytes, signed if four bytes |
171,273 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
The provided code snippet includes necessary dependencies for implementing the `_mul2012` function. Write a Python function `def _mul2012(num1, num2)` to solve the following problem:
Multiply two numbers in 20.12 fixed point format.
Here is the function:
def _mul2012(num1, num2):
"""Multiply two numbers in 20.12 fixed point format."""
# Separated into a function because >> has surprising precedence
return (num1*num2) >> 20 | Multiply two numbers in 20.12 fixed point format. |
171,274 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__(self: _P) -> _P: ...
def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]
) -> Optional[bool]: ...
def cwd(cls: Type[_P]) -> _P: ...
def stat(self) -> os.stat_result: ...
def chmod(self, mode: int) -> None: ...
def exists(self) -> bool: ...
def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def group(self) -> str: ...
def is_dir(self) -> bool: ...
def is_file(self) -> bool: ...
if sys.version_info >= (3, 7):
def is_mount(self) -> bool: ...
def is_symlink(self) -> bool: ...
def is_socket(self) -> bool: ...
def is_fifo(self) -> bool: ...
def is_block_device(self) -> bool: ...
def is_char_device(self) -> bool: ...
def iterdir(self: _P) -> Generator[_P, None, None]: ...
def lchmod(self, mode: int) -> None: ...
def lstat(self) -> os.stat_result: ...
def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ...
# Adapted from builtins.open
# Text mode: always returns a TextIOWrapper
def open(
self,
mode: OpenTextMode = ...,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> TextIOWrapper: ...
# Unbuffered binary mode: returns a FileIO
def open(
self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ...
) -> FileIO: ...
# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter
def open(
self,
mode: OpenBinaryModeUpdating,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedRandom: ...
def open(
self,
mode: OpenBinaryModeWriting,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedWriter: ...
def open(
self,
mode: OpenBinaryModeReading,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedReader: ...
# Buffering cannot be determined: fall back to BinaryIO
def open(
self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ...
) -> BinaryIO: ...
# Fallback if mode is not specified
def open(
self,
mode: str,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> IO[Any]: ...
def owner(self) -> str: ...
if sys.version_info >= (3, 9):
def readlink(self: _P) -> _P: ...
if sys.version_info >= (3, 8):
def rename(self: _P, target: Union[str, PurePath]) -> _P: ...
def replace(self: _P, target: Union[str, PurePath]) -> _P: ...
else:
def rename(self, target: Union[str, PurePath]) -> None: ...
def replace(self, target: Union[str, PurePath]) -> None: ...
def resolve(self: _P, strict: bool = ...) -> _P: ...
def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def rmdir(self) -> None: ...
def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ...
def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ...
if sys.version_info >= (3, 8):
def unlink(self, missing_ok: bool = ...) -> None: ...
else:
def unlink(self) -> None: ...
def home(cls: Type[_P]) -> _P: ...
def absolute(self: _P) -> _P: ...
def expanduser(self: _P) -> _P: ...
def read_bytes(self) -> bytes: ...
def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ...
def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ...
def write_bytes(self, data: bytes) -> int: ...
def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ...
if sys.version_info >= (3, 8):
def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ...
The provided code snippet includes necessary dependencies for implementing the `_parse_enc` function. Write a Python function `def _parse_enc(path)` to solve the following problem:
r""" Parse a \*.enc file referenced from a psfonts.map style file. The format supported by this function is a tiny subset of PostScript. Parameters ---------- path : `os.PathLike` Returns ------- list The nth entry of the list is the PostScript glyph name of the nth glyph.
Here is the function:
def _parse_enc(path):
r"""
Parse a \*.enc file referenced from a psfonts.map style file.
The format supported by this function is a tiny subset of PostScript.
Parameters
----------
path : `os.PathLike`
Returns
-------
list
The nth entry of the list is the PostScript glyph name of the nth
glyph.
"""
no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii"))
array = re.search(r"(?s)\[(.*)\]", no_comments).group(1)
lines = [line for line in array.split() if line]
if all(line.startswith("/") for line in lines):
return [line[1:] for line in lines]
else:
raise ValueError(
"Failed to parse {} as Postscript encoding".format(path)) | r""" Parse a \*.enc file referenced from a psfonts.map style file. The format supported by this function is a tiny subset of PostScript. Parameters ---------- path : `os.PathLike` Returns ------- list The nth entry of the list is the PostScript glyph name of the nth glyph. |
171,275 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
def _find_tex_file(filename):
def find_tex_file(filename):
try:
return _find_tex_file(filename)
except FileNotFoundError as exc:
_api.warn_deprecated(
"3.6", message=f"{exc.args[0]}; in the future, this will raise a "
f"FileNotFoundError.")
return "" | null |
171,276 | from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
from matplotlib import _api, cbook
def _find_tex_file(filename):
"""
Find a file in the texmf tree using kpathsea_.
The kpathsea library, provided by most existing TeX distributions, both
on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived
luatex process if luatex is installed, or via kpsewhich otherwise.
.. _kpathsea: https://www.tug.org/kpathsea/
Parameters
----------
filename : str or path-like
Raises
------
FileNotFoundError
If the file is not found.
"""
# we expect these to always be ascii encoded, but use utf-8
# out of caution
if isinstance(filename, bytes):
filename = filename.decode('utf-8', errors='replace')
try:
lk = _LuatexKpsewhich()
except FileNotFoundError:
lk = None # Fallback to directly calling kpsewhich, as below.
if lk:
path = lk.search(filename)
else:
if os.name == 'nt':
# On Windows only, kpathsea can use utf-8 for cmd args and output.
# The `command_line_encoding` environment variable is set to force
# it to always use utf-8 encoding. See Matplotlib issue #11848.
kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'},
'encoding': 'utf-8'}
else: # On POSIX, run through the equivalent of os.fsdecode().
kwargs = {'encoding': sys.getfilesystemencoding(),
'errors': 'surrogateescape'}
try:
path = (cbook._check_and_log_subprocess(['kpsewhich', filename],
_log, **kwargs)
.rstrip('\n'))
except (FileNotFoundError, RuntimeError):
path = None
if path:
return path
else:
raise FileNotFoundError(
f"Matplotlib's TeX implementation searched for a file named "
f"{filename!r} in your texmf tree, but could not find it")
def _fontfile(cls, suffix, texname):
return cls(_find_tex_file(texname + suffix)) | null |
171,277 | import wx
from .. import _api
from .backend_agg import FigureCanvasAgg
from .backend_wx import _BackendWx, _FigureCanvasWxBase, FigureFrameWx
from .backend_wx import ( # noqa: F401 # pylint: disable=W0611
NavigationToolbar2Wx as NavigationToolbar2WxAgg)
"3.6", alternative="FigureFrameWx(..., canvas_class=FigureCanvasWxAgg)")
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 _rgba_to_wx_bitmap(rgba):
"""Convert an RGBA buffer to a wx.Bitmap."""
h, w, _ = rgba.shape
return wx.Bitmap.FromBufferRGBA(w, h, rgba)
class _BackendWxAgg(_BackendWx):
FigureCanvas = FigureCanvasWxAgg
The provided code snippet includes necessary dependencies for implementing the `_rgba_to_wx_bitmap` function. Write a Python function `def _rgba_to_wx_bitmap(rgba)` to solve the following problem:
Convert an RGBA buffer to a wx.Bitmap.
Here is the function:
def _rgba_to_wx_bitmap(rgba):
"""Convert an RGBA buffer to a wx.Bitmap."""
h, w, _ = rgba.shape
return wx.Bitmap.FromBufferRGBA(w, h, rgba) | Convert an RGBA buffer to a wx.Bitmap. |
171,278 | import logging
import sys
import matplotlib as mpl
from matplotlib import _api, backend_tools, cbook
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
TimerBase)
from matplotlib.backend_tools import Cursors
import gi
from gi.repository import Gdk, Gio, GLib, Gtk
_application = None
def _shutdown_application(app):
# The application might prematurely shut down if Ctrl-C'd out of IPython,
# so close all windows.
for win in app.get_windows():
win.close()
# The PyGObject wrapper incorrectly thinks that None is not allowed, or we
# would call this:
# Gio.Application.set_default(None)
# Instead, we set this property and ignore default applications with it:
app._created_by_matplotlib = True
global _application
_application = None
def _create_application():
global _application
if _application is None:
app = Gio.Application.get_default()
if app is None or getattr(app, '_created_by_matplotlib', False):
# display_is_valid returns False only if on Linux and neither X11
# nor Wayland display can be opened.
if not mpl._c_internal_utils.display_is_valid():
raise RuntimeError('Invalid DISPLAY variable')
_application = Gtk.Application.new('org.matplotlib.Matplotlib3',
Gio.ApplicationFlags.NON_UNIQUE)
# The activate signal must be connected, but we don't care for
# handling it, since we don't do any remote processing.
_application.connect('activate', lambda *args, **kwargs: None)
_application.connect('shutdown', _shutdown_application)
_application.register()
cbook._setup_new_guiapp()
else:
_application = app
return _application | null |
171,279 | import functools
import gzip
import math
import numpy as np
import matplotlib as mpl
from .. import _api, cbook, font_manager
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
RendererBase)
from matplotlib.font_manager import ttfFontProperty
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
class Path:
"""
A series of possibly disconnected, possibly closed, line and curve
segments.
The underlying storage is made up of two parallel numpy arrays:
- *vertices*: an Nx2 float array of vertices
- *codes*: an N-length uint8 array of path codes, or None
These two arrays always have the same length in the first
dimension. For example, to represent a cubic curve, you must
provide three vertices and three ``CURVE4`` codes.
The code types are:
- ``STOP`` : 1 vertex (ignored)
A marker for the end of the entire path (currently not required and
ignored)
- ``MOVETO`` : 1 vertex
Pick up the pen and move to the given vertex.
- ``LINETO`` : 1 vertex
Draw a line from the current position to the given vertex.
- ``CURVE3`` : 1 control point, 1 endpoint
Draw a quadratic Bézier curve from the current position, with the given
control point, to the given end point.
- ``CURVE4`` : 2 control points, 1 endpoint
Draw a cubic Bézier curve from the current position, with the given
control points, to the given end point.
- ``CLOSEPOLY`` : 1 vertex (ignored)
Draw a line segment to the start point of the current polyline.
If *codes* is None, it is interpreted as a ``MOVETO`` followed by a series
of ``LINETO``.
Users of Path objects should not access the vertices and codes arrays
directly. Instead, they should use `iter_segments` or `cleaned` to get the
vertex/code pairs. This helps, in particular, to consistently handle the
case of *codes* being None.
Some behavior of Path objects can be controlled by rcParams. See the
rcParams whose keys start with 'path.'.
.. note::
The vertices and codes arrays should be treated as
immutable -- there are a number of optimizations and assumptions
made up front in the constructor that will not change when the
data changes.
"""
code_type = np.uint8
# Path codes
STOP = code_type(0) # 1 vertex
MOVETO = code_type(1) # 1 vertex
LINETO = code_type(2) # 1 vertex
CURVE3 = code_type(3) # 2 vertices
CURVE4 = code_type(4) # 3 vertices
CLOSEPOLY = code_type(79) # 1 vertex
#: A dictionary mapping Path codes to the number of vertices that the
#: code expects.
NUM_VERTICES_FOR_CODE = {STOP: 1,
MOVETO: 1,
LINETO: 1,
CURVE3: 2,
CURVE4: 3,
CLOSEPOLY: 1}
def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
"""
Create a new path with the given vertices and codes.
Parameters
----------
vertices : (N, 2) array-like
The path vertices, as an array, masked array or sequence of pairs.
Masked values, if any, 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`.
codes : array-like or None, optional
N-length array of integers representing the codes of the path.
If not None, codes must be the same length as vertices.
If None, *vertices* will be treated as a series of line segments.
_interpolation_steps : int, optional
Used as a hint to certain projections, such as Polar, that this
path should be linearly interpolated immediately before drawing.
This attribute is primarily an implementation detail and is not
intended for public use.
closed : bool, optional
If *codes* is None and closed is True, vertices will be treated as
line segments of a closed polygon. Note that the last vertex will
then be ignored (as the corresponding code will be set to
CLOSEPOLY).
readonly : bool, optional
Makes the path behave in an immutable way and sets the vertices
and codes as read-only arrays.
"""
vertices = _to_unmasked_float_array(vertices)
_api.check_shape((None, 2), vertices=vertices)
if codes is not None:
codes = np.asarray(codes, self.code_type)
if codes.ndim != 1 or len(codes) != len(vertices):
raise ValueError("'codes' must be a 1D list or array with the "
"same length of 'vertices'. "
f"Your vertices have shape {vertices.shape} "
f"but your codes have shape {codes.shape}")
if len(codes) and codes[0] != self.MOVETO:
raise ValueError("The first element of 'code' must be equal "
f"to 'MOVETO' ({self.MOVETO}). "
f"Your first code is {codes[0]}")
elif closed and len(vertices):
codes = np.empty(len(vertices), dtype=self.code_type)
codes[0] = self.MOVETO
codes[1:-1] = self.LINETO
codes[-1] = self.CLOSEPOLY
self._vertices = vertices
self._codes = codes
self._interpolation_steps = _interpolation_steps
self._update_values()
if readonly:
self._vertices.flags.writeable = False
if self._codes is not None:
self._codes.flags.writeable = False
self._readonly = True
else:
self._readonly = False
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
"""
Create a Path instance without the expense of calling the constructor.
Parameters
----------
verts : numpy array
codes : numpy array
internals_from : Path or None
If not None, another `Path` from which the attributes
``should_simplify``, ``simplify_threshold``, and
``interpolation_steps`` will be copied. Note that ``readonly`` is
never copied, and always set to ``False`` by this constructor.
"""
pth = cls.__new__(cls)
pth._vertices = _to_unmasked_float_array(verts)
pth._codes = codes
pth._readonly = False
if internals_from is not None:
pth._should_simplify = internals_from._should_simplify
pth._simplify_threshold = internals_from._simplify_threshold
pth._interpolation_steps = internals_from._interpolation_steps
else:
pth._should_simplify = True
pth._simplify_threshold = mpl.rcParams['path.simplify_threshold']
pth._interpolation_steps = 1
return pth
def _create_closed(cls, vertices):
"""
Create a closed polygonal path going through *vertices*.
Unlike ``Path(..., closed=True)``, *vertices* should **not** end with
an entry for the CLOSEPATH; this entry is added by `._create_closed`.
"""
v = _to_unmasked_float_array(vertices)
return cls(np.concatenate([v, v[:1]]), closed=True)
def _update_values(self):
self._simplify_threshold = mpl.rcParams['path.simplify_threshold']
self._should_simplify = (
self._simplify_threshold > 0 and
mpl.rcParams['path.simplify'] and
len(self._vertices) >= 128 and
(self._codes is None or np.all(self._codes <= Path.LINETO))
)
def vertices(self):
"""
The list of vertices in the `Path` as an Nx2 numpy array.
"""
return self._vertices
def vertices(self, vertices):
if self._readonly:
raise AttributeError("Can't set vertices on a readonly Path")
self._vertices = vertices
self._update_values()
def codes(self):
"""
The list of codes in the `Path` as a 1D numpy array. Each
code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4`
or `CLOSEPOLY`. For codes that correspond to more than one
vertex (`CURVE3` and `CURVE4`), that code will be repeated so
that the length of `vertices` and `codes` is always
the same.
"""
return self._codes
def codes(self, codes):
if self._readonly:
raise AttributeError("Can't set codes on a readonly Path")
self._codes = codes
self._update_values()
def simplify_threshold(self):
"""
The fraction of a pixel difference below which vertices will
be simplified out.
"""
return self._simplify_threshold
def simplify_threshold(self, threshold):
self._simplify_threshold = threshold
def should_simplify(self):
"""
`True` if the vertices array should be simplified.
"""
return self._should_simplify
def should_simplify(self, should_simplify):
self._should_simplify = should_simplify
def readonly(self):
"""
`True` if the `Path` is read-only.
"""
return self._readonly
def copy(self):
"""
Return a shallow copy of the `Path`, which will share the
vertices and codes with the source `Path`.
"""
return copy.copy(self)
def __deepcopy__(self, memo=None):
"""
Return a deepcopy of the `Path`. The `Path` will not be
readonly, even if the source `Path` is.
"""
# Deepcopying arrays (vertices, codes) strips the writeable=False flag.
p = copy.deepcopy(super(), memo)
p._readonly = False
return p
deepcopy = __deepcopy__
def make_compound_path_from_polys(cls, XY):
"""
Make a compound `Path` object to draw a number of polygons with equal
numbers of sides.
.. plot:: gallery/misc/histogram_path.py
Parameters
----------
XY : (numpolys, numsides, 2) array
"""
# for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
# the CLOSEPOLY; the vert for the closepoly is ignored but we still
# need it to keep the codes aligned with the vertices
numpolys, numsides, two = XY.shape
if two != 2:
raise ValueError("The third dimension of 'XY' must be 2")
stride = numsides + 1
nverts = numpolys * stride
verts = np.zeros((nverts, 2))
codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
codes[0::stride] = cls.MOVETO
codes[numsides::stride] = cls.CLOSEPOLY
for i in range(numsides):
verts[i::stride] = XY[:, i]
return cls(verts, codes)
def make_compound_path(cls, *args):
"""
Make a compound path from a list of `Path` objects. Blindly removes
all `Path.STOP` control points.
"""
# Handle an empty list in args (i.e. no args).
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0
for path in args:
if path.codes is None:
codes[i] = cls.MOVETO
codes[i + 1:i + len(path.vertices)] = cls.LINETO
else:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
# remove STOP's, since internal STOPs are a bug
not_stop_mask = codes != cls.STOP
vertices = vertices[not_stop_mask, :]
codes = codes[not_stop_mask]
return cls(vertices, codes)
def __repr__(self):
return "Path(%r, %r)" % (self.vertices, self.codes)
def __len__(self):
return len(self.vertices)
def iter_segments(self, transform=None, remove_nans=True, clip=None,
snap=False, stroke_width=1.0, simplify=None,
curves=True, sketch=None):
"""
Iterate over all curve segments in the path.
Each iteration returns a pair ``(vertices, code)``, where ``vertices``
is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
Additionally, this method can provide a number of standard cleanups and
conversions to the path.
Parameters
----------
transform : None or :class:`~matplotlib.transforms.Transform`
If not None, the given affine transformation will be applied to the
path.
remove_nans : bool, optional
Whether to remove all NaNs from the path and skip over them using
MOVETO commands.
clip : None or (float, float, float, float), optional
If not None, must be a four-tuple (x1, y1, x2, y2)
defining a rectangle in which to clip the path.
snap : None or bool, optional
If True, snap all nodes to pixels; if False, don't snap them.
If None, snap if the path contains only segments
parallel to the x or y axes, and no more than 1024 of them.
stroke_width : float, optional
The width of the stroke being drawn (used for path snapping).
simplify : None or bool, optional
Whether to simplify the path by removing vertices
that do not affect its appearance. If None, use the
:attr:`should_simplify` attribute. See also :rc:`path.simplify`
and :rc:`path.simplify_threshold`.
curves : bool, optional
If True, curve segments will be returned as curve segments.
If False, all curves will be converted to line segments.
sketch : None or sequence, optional
If not None, must be a 3-tuple of the form
(scale, length, randomness), representing the sketch parameters.
"""
if not len(self):
return
cleaned = self.cleaned(transform=transform,
remove_nans=remove_nans, clip=clip,
snap=snap, stroke_width=stroke_width,
simplify=simplify, curves=curves,
sketch=sketch)
# Cache these object lookups for performance in the loop.
NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
STOP = self.STOP
vertices = iter(cleaned.vertices)
codes = iter(cleaned.codes)
for curr_vertices, code in zip(vertices, codes):
if code == STOP:
break
extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
if extra_vertices:
for i in range(extra_vertices):
next(codes)
curr_vertices = np.append(curr_vertices, next(vertices))
yield curr_vertices, code
def iter_bezier(self, **kwargs):
"""
Iterate over each Bézier curve (lines included) in a Path.
Parameters
----------
**kwargs
Forwarded to `.iter_segments`.
Yields
------
B : matplotlib.bezier.BezierSegment
The Bézier curves that make up the current path. Note in particular
that freestanding points are Bézier curves of order 0, and lines
are Bézier curves of order 1 (with two control points).
code : Path.code_type
The code describing what kind of curve is being returned.
Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE4 correspond to
Bézier curves with 1, 2, 3, and 4 control points (respectively).
Path.CLOSEPOLY is a Path.LINETO with the control points correctly
chosen based on the start/end points of the current stroke.
"""
first_vert = None
prev_vert = None
for verts, code in self.iter_segments(**kwargs):
if first_vert is None:
if code != Path.MOVETO:
raise ValueError("Malformed path, must start with MOVETO.")
if code == Path.MOVETO: # a point is like "CURVE1"
first_vert = verts
yield BezierSegment(np.array([first_vert])), code
elif code == Path.LINETO: # "CURVE2"
yield BezierSegment(np.array([prev_vert, verts])), code
elif code == Path.CURVE3:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:]])), code
elif code == Path.CURVE4:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:4], verts[4:]])), code
elif code == Path.CLOSEPOLY:
yield BezierSegment(np.array([prev_vert, first_vert])), code
elif code == Path.STOP:
return
else:
raise ValueError(f"Invalid Path.code_type: {code}")
prev_vert = verts[-2:]
def cleaned(self, transform=None, remove_nans=False, clip=None,
*, simplify=False, curves=False,
stroke_width=1.0, snap=False, sketch=None):
"""
Return a new Path with vertices and codes cleaned according to the
parameters.
See Also
--------
Path.iter_segments : for details of the keyword arguments.
"""
vertices, codes = _path.cleanup_path(
self, transform, remove_nans, clip, snap, stroke_width, simplify,
curves, sketch)
pth = Path._fast_from_codes_and_verts(vertices, codes, self)
if not simplify:
pth._should_simplify = False
return pth
def transformed(self, transform):
"""
Return a transformed copy of the path.
See Also
--------
matplotlib.transforms.TransformedPath
A specialized path class that will cache the transformed result and
automatically update when the transform changes.
"""
return Path(transform.transform(self.vertices), self.codes,
self._interpolation_steps)
def contains_point(self, point, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given point.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
point : (float, float)
The point (x, y) to check.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *point* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *point*.
radius : float, default: 0
Additional margin on the path in coordinates of *point*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
bool
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
# `point_in_path` does not handle nonlinear transforms, so we
# transform the path ourselves. If *transform* is affine, letting
# `point_in_path` handle the transform avoids allocating an extra
# buffer.
if transform and not transform.is_affine:
self = transform.transform_path(self)
transform = None
return _path.point_in_path(point[0], point[1], radius, self, transform)
def contains_points(self, points, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given points.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
points : (N, 2) array
The points to check. Columns contain x and y values.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *points* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *points*.
radius : float, default: 0
Additional margin on the path in coordinates of *points*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
length-N bool array
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
result = _path.points_in_path(points, radius, self, transform)
return result.astype('bool')
def contains_path(self, path, transform=None):
"""
Return whether this (closed) path completely contains the given path.
If *transform* is not ``None``, the path will be transformed before
checking for containment.
"""
if transform is not None:
transform = transform.frozen()
return _path.path_in_path(self, None, path, transform)
def get_extents(self, transform=None, **kwargs):
"""
Get Bbox of the path.
Parameters
----------
transform : matplotlib.transforms.Transform, optional
Transform to apply to path before computing extents, if any.
**kwargs
Forwarded to `.iter_bezier`.
Returns
-------
matplotlib.transforms.Bbox
The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
"""
from .transforms import Bbox
if transform is not None:
self = transform.transform_path(self)
if self.codes is None:
xys = self.vertices
elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
# Optimization for the straight line case.
# Instead of iterating through each curve, consider
# each line segment's end-points
# (recall that STOP and CLOSEPOLY vertices are ignored)
xys = self.vertices[np.isin(self.codes,
[Path.MOVETO, Path.LINETO])]
else:
xys = []
for curve, code in self.iter_bezier(**kwargs):
# places where the derivative is zero can be extrema
_, dzeros = curve.axis_aligned_extrema()
# as can the ends of the curve
xys.append(curve([0, *dzeros, 1]))
xys = np.concatenate(xys)
if len(xys):
return Bbox([xys.min(axis=0), xys.max(axis=0)])
else:
return Bbox.null()
def intersects_path(self, other, filled=True):
"""
Return whether if this path intersects another given path.
If *filled* is True, then this also returns True if one path completely
encloses the other (i.e., the paths are treated as filled).
"""
return _path.path_intersects_path(self, other, filled)
def intersects_bbox(self, bbox, filled=True):
"""
Return whether this path intersects a given `~.transforms.Bbox`.
If *filled* is True, then this also returns True if the path completely
encloses the `.Bbox` (i.e., the path is treated as filled).
The bounding box is always considered filled.
"""
return _path.path_intersects_rectangle(
self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
def interpolated(self, steps):
"""
Return a new path resampled to length N x steps.
Codes other than LINETO are not handled correctly.
"""
if steps == 1:
return self
vertices = simple_linear_interpolation(self.vertices, steps)
codes = self.codes
if codes is not None:
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
dtype=self.code_type)
new_codes[0::steps] = codes
else:
new_codes = None
return Path(vertices, new_codes)
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
"""
Convert this path to a list of polygons or polylines. Each
polygon/polyline 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 Bézier curves.
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.
If *closed_only* is `True` (default), only closed polygons,
with the last point being the same as the first point, will be
returned. Any unclosed polylines in the path will be
explicitly closed. If *closed_only* is `False`, any unclosed
polygons in the path will be returned as unclosed polygons,
and the closed polygons will be returned explicitly closed by
setting the last point to the same as the first point.
"""
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):
vertices = self.vertices
if closed_only:
if len(vertices) < 3:
return []
elif np.any(vertices[0] != vertices[-1]):
vertices = [*vertices, vertices[0]]
if transform is None:
return [vertices]
else:
return [transform.transform(vertices)]
# Deal with the case where there are curves and/or multiple
# subpaths (using extension code)
return _path.convert_path_to_polygons(
self, transform, width, height, closed_only)
_unit_rectangle = None
def unit_rectangle(cls):
"""
Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
"""
if cls._unit_rectangle is None:
cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
closed=True, readonly=True)
return cls._unit_rectangle
_unit_regular_polygons = WeakValueDictionary()
def unit_regular_polygon(cls, numVertices):
"""
Return a :class:`Path` instance for a unit regular polygon with the
given *numVertices* such that the circumscribing circle has radius 1.0,
centered at (0, 0).
"""
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)
# This initial rotation is to make sure the polygon always
# "points-up".
+ np.pi / 2)
verts = np.column_stack((np.cos(theta), np.sin(theta)))
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_polygons[numVertices] = path
return path
_unit_regular_stars = WeakValueDictionary()
def unit_regular_star(cls, numVertices, innerCircle=0.5):
"""
Return a :class:`Path` for a unit regular star with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
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))
# This initial rotation is to make sure the polygon always
# "points-up"
theta += np.pi / 2.0
r = np.ones(ns2 + 1)
r[1::2] = innerCircle
verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_stars[(numVertices, innerCircle)] = path
return path
def unit_regular_asterisk(cls, numVertices):
"""
Return a :class:`Path` for a unit regular asterisk with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
return cls.unit_regular_star(numVertices, 0.0)
_unit_circle = None
def unit_circle(cls):
"""
Return the readonly :class:`Path` of the unit circle.
For most cases, :func:`Path.circle` will be what you want.
"""
if cls._unit_circle is None:
cls._unit_circle = cls.circle(center=(0, 0), radius=1,
readonly=True)
return cls._unit_circle
def circle(cls, center=(0., 0.), radius=1., readonly=False):
"""
Return a `Path` representing a circle of a given radius and center.
Parameters
----------
center : (float, float), default: (0, 0)
The center of the circle.
radius : float, default: 1
The radius of the circle.
readonly : bool
Whether the created path should have the "readonly" argument
set when creating the Path instance.
Notes
-----
The circle is approximated using 8 cubic Bézier curves, as described in
Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
Bezier Cubic Splines <https://www.tinaja.com/glib/ellipse4.pdf>`_.
"""
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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]],
dtype=float)
codes = [cls.CURVE4] * 26
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
return Path(vertices * radius + center, codes, readonly=readonly)
_unit_circle_righthalf = None
def unit_circle_righthalf(cls):
"""
Return a `Path` of the right half of a unit circle.
See `Path.circle` for the reference on the approximation used.
"""
if cls._unit_circle_righthalf is None:
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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],
[0.0, -1.0]],
float)
codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
return cls._unit_circle_righthalf
def arc(cls, theta1, theta2, n=None, is_wedge=False):
"""
Return a `Path` for the unit circle arc from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest arc within 360 degrees.
That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
*theta2* - 360 and not a full circle plus some extra overlap.
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
<https://web.archive.org/web/20190318044212/http://www.spaceroots.org/documents/ellipse/index.html>`_.
"""
halfpi = np.pi * 0.5
eta1 = theta1
eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
# Ensure 2pi range is not flattened to 0 due to floating-point errors,
# but don't try to expand existing 0 range.
if theta2 != theta1 and eta2 <= eta1:
eta2 += 360
eta1, eta2 = np.deg2rad([eta1, eta2])
# number of curve segments to make
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), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[1] = [xA[0], yA[0]]
codes[0:2] = [cls.MOVETO, cls.LINETO]
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
vertex_offset = 2
end = length - 2
else:
length = n * 3 + 1
vertices = np.empty((length, 2), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[0] = [xA[0], yA[0]]
codes[0] = cls.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 cls(vertices, codes, readonly=True)
def wedge(cls, theta1, theta2, n=None):
"""
Return a `Path` for the unit circle wedge from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest wedge within 360 degrees.
That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
to *theta2* - 360 and not a full circle plus some extra overlap.
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*.
See `Path.arc` for the reference on the approximation used.
"""
return cls.arc(theta1, theta2, n, True)
def hatch(hatchpattern, density=6):
"""
Given a hatch specifier, *hatchpattern*, generates a Path that
can be used in a repeated hatching pattern. *density* is the
number of lines per unit square.
"""
from matplotlib.hatch import get_path
return (get_path(hatchpattern, density)
if hatchpattern is not None else None)
def clip_to_bbox(self, bbox, inside=True):
"""
Clip the path to the given bounding box.
The path must be made up of one or more closed polygons. This
algorithm will not behave correctly for unclosed paths.
If *inside* is `True`, clip to the inside of the box, otherwise
to the outside of the box.
"""
verts = _path.clip_path_to_rect(self, bbox, inside)
paths = [Path(poly) for poly in verts]
return self.make_compound_path(*paths)
def _append_path(ctx, path, transform, clip=None):
for points, code in path.iter_segments(
transform, remove_nans=True, 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:
cur = np.asarray(ctx.get_current_point())
a = points[:2]
b = points[-2:]
ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)
elif code == Path.CURVE4:
ctx.curve_to(*points) | null |
171,280 | import functools
import gzip
import math
import numpy as np
try:
import cairo
if cairo.version_info < (1, 14, 0): # Introduced set_device_scale.
raise ImportError
except ImportError:
try:
import cairocffi as cairo
except ImportError as err:
raise ImportError(
"cairo backend requires that pycairo>=1.14.0 or cairocffi "
"is installed") from err
import matplotlib as mpl
from .. import _api, cbook, font_manager
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
RendererBase)
from matplotlib.font_manager import ttfFontProperty
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
The provided code snippet includes necessary dependencies for implementing the `_cairo_font_args_from_font_prop` function. Write a Python function `def _cairo_font_args_from_font_prop(prop)` to solve the following problem:
Convert a `.FontProperties` or a `.FontEntry` to arguments that can be passed to `.Context.select_font_face`.
Here is the function:
def _cairo_font_args_from_font_prop(prop):
"""
Convert a `.FontProperties` or a `.FontEntry` to arguments that can be
passed to `.Context.select_font_face`.
"""
def attr(field):
try:
return getattr(prop, f"get_{field}")()
except AttributeError:
return getattr(prop, field)
name = attr("name")
slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}")
weight = attr("weight")
weight = (cairo.FONT_WEIGHT_NORMAL
if font_manager.weight_dict.get(weight, weight) < 550
else cairo.FONT_WEIGHT_BOLD)
return name, slant, weight | Convert a `.FontProperties` or a `.FontEntry` to arguments that can be passed to `.Context.select_font_face`. |
171,281 | import functools
import operator
import os
import platform
import sys
import signal
import socket
import contextlib
from packaging.version import parse as parse_version
import matplotlib as mpl
from . import _QT_FORCE_QT5_BINDING
QT_API_PYQT6 = "PyQt6"
QT_API_PYSIDE6 = "PySide6"
QT_API_PYQT5 = "PyQt5"
QT_API_PYSIDE2 = "PySide2"
if QT_API in [QT_API_PYQT6, QT_API_PYQT5, QT_API_PYSIDE6, QT_API_PYSIDE2]:
_setup_pyqt5plus()
elif QT_API is None: # See above re: dict.__getitem__.
if _QT_FORCE_QT5_BINDING:
_candidates = [
(_setup_pyqt5plus, QT_API_PYQT5),
(_setup_pyqt5plus, QT_API_PYSIDE2),
]
else:
_candidates = [
(_setup_pyqt5plus, QT_API_PYQT6),
(_setup_pyqt5plus, QT_API_PYSIDE6),
(_setup_pyqt5plus, QT_API_PYQT5),
(_setup_pyqt5plus, QT_API_PYSIDE2),
]
for _setup, QT_API in _candidates:
try:
_setup()
except ImportError:
continue
break
else:
raise ImportError(
"Failed to import any of the following Qt binding modules: {}"
.format(", ".join(_ETS.values())))
else: # We should not get there.
raise AssertionError(f"Unexpected QT_API: {QT_API}")
def _setup_pyqt5plus():
global QtCore, QtGui, QtWidgets, __version__
global _getSaveFileName, _isdeleted, _to_int
if QT_API == QT_API_PYQT6:
from PyQt6 import QtCore, QtGui, QtWidgets, sip
__version__ = QtCore.PYQT_VERSION_STR
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
QtCore.Property = QtCore.pyqtProperty
_isdeleted = sip.isdeleted
_to_int = operator.attrgetter('value')
elif QT_API == QT_API_PYSIDE6:
from PySide6 import QtCore, QtGui, QtWidgets, __version__
import shiboken6
def _isdeleted(obj): return not shiboken6.isValid(obj)
if parse_version(__version__) >= parse_version('6.4'):
_to_int = operator.attrgetter('value')
else:
_to_int = int
elif QT_API == QT_API_PYQT5:
from PyQt5 import QtCore, QtGui, QtWidgets
import sip
__version__ = QtCore.PYQT_VERSION_STR
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
QtCore.Property = QtCore.pyqtProperty
_isdeleted = sip.isdeleted
_to_int = int
elif QT_API == QT_API_PYSIDE2:
from PySide2 import QtCore, QtGui, QtWidgets, __version__
try:
from PySide2 import shiboken2
except ImportError:
import shiboken2
def _isdeleted(obj):
return not shiboken2.isValid(obj)
_to_int = int
else:
raise AssertionError(f"Unexpected QT_API: {QT_API}")
_getSaveFileName = QtWidgets.QFileDialog.getSaveFileName | null |
171,282 | import functools
import operator
import os
import platform
import sys
import signal
import socket
import contextlib
from packaging.version import parse as parse_version
import matplotlib as mpl
from . import _QT_FORCE_QT5_BINDING
def _exec(obj):
# exec on PyQt6, exec_ elsewhere.
obj.exec() if hasattr(obj, "exec") else obj.exec_() | null |
171,283 | import functools
import operator
import os
import platform
import sys
import signal
import socket
import contextlib
from packaging.version import parse as parse_version
import matplotlib as mpl
from . import _QT_FORCE_QT5_BINDING
def _enum(name):
# foo.bar.Enum.Entry (PyQt6) <=> foo.bar.Entry (non-PyQt6).
return operator.attrgetter(
name if QT_API == 'PyQt6' else name.rpartition(".")[0]
)(sys.modules[QtCore.__package__])
The provided code snippet includes necessary dependencies for implementing the `_maybe_allow_interrupt` function. Write a Python function `def _maybe_allow_interrupt(qapp)` to solve the following problem:
This manager allows to terminate a plot by sending a SIGINT. It is necessary because the running Qt backend prevents Python interpreter to run and process signals (i.e., to raise KeyboardInterrupt exception). To solve this one needs to somehow wake up the interpreter and make it close the plot window. We do this by using the signal.set_wakeup_fd() function which organizes a write of the signal number into a socketpair connected to the QSocketNotifier (since it is part of the Qt backend, it can react to that write event). Afterwards, the Qt handler empties the socketpair by a recv() command to re-arm it (we need this if a signal different from SIGINT was caught by set_wakeup_fd() and we shall continue waiting). If the SIGINT was caught indeed, after exiting the on_signal() function the interpreter reacts to the SIGINT according to the handle() function which had been set up by a signal.signal() call: it causes the qt_object to exit by calling its quit() method. Finally, we call the old SIGINT handler with the same arguments that were given to our custom handle() handler. We do this only if the old handler for SIGINT was not None, which means that a non-python handler was installed, i.e. in Julia, and not SIG_IGN which means we should ignore the interrupts.
Here is the function:
def _maybe_allow_interrupt(qapp):
"""
This manager allows to terminate a plot by sending a SIGINT. It is
necessary because the running Qt backend prevents Python interpreter to
run and process signals (i.e., to raise KeyboardInterrupt exception). To
solve this one needs to somehow wake up the interpreter and make it close
the plot window. We do this by using the signal.set_wakeup_fd() function
which organizes a write of the signal number into a socketpair connected
to the QSocketNotifier (since it is part of the Qt backend, it can react
to that write event). Afterwards, the Qt handler empties the socketpair
by a recv() command to re-arm it (we need this if a signal different from
SIGINT was caught by set_wakeup_fd() and we shall continue waiting). If
the SIGINT was caught indeed, after exiting the on_signal() function the
interpreter reacts to the SIGINT according to the handle() function which
had been set up by a signal.signal() call: it causes the qt_object to
exit by calling its quit() method. Finally, we call the old SIGINT
handler with the same arguments that were given to our custom handle()
handler.
We do this only if the old handler for SIGINT was not None, which means
that a non-python handler was installed, i.e. in Julia, and not SIG_IGN
which means we should ignore the interrupts.
"""
old_sigint_handler = signal.getsignal(signal.SIGINT)
handler_args = None
skip = False
if old_sigint_handler in (None, signal.SIG_IGN, signal.SIG_DFL):
skip = True
else:
wsock, rsock = socket.socketpair()
wsock.setblocking(False)
old_wakeup_fd = signal.set_wakeup_fd(wsock.fileno())
sn = QtCore.QSocketNotifier(
rsock.fileno(), _enum('QtCore.QSocketNotifier.Type').Read
)
# We do not actually care about this value other than running some
# Python code to ensure that the interpreter has a chance to handle the
# signal in Python land. We also need to drain the socket because it
# will be written to as part of the wakeup! There are some cases where
# this may fire too soon / more than once on Windows so we should be
# forgiving about reading an empty socket.
rsock.setblocking(False)
# Clear the socket to re-arm the notifier.
@sn.activated.connect
def _may_clear_sock(*args):
try:
rsock.recv(1)
except BlockingIOError:
pass
def handle(*args):
nonlocal handler_args
handler_args = args
qapp.quit()
signal.signal(signal.SIGINT, handle)
try:
yield
finally:
if not skip:
wsock.close()
rsock.close()
sn.setEnabled(False)
signal.set_wakeup_fd(old_wakeup_fd)
signal.signal(signal.SIGINT, old_sigint_handler)
if handler_args is not None:
old_sigint_handler(*handler_args) | This manager allows to terminate a plot by sending a SIGINT. It is necessary because the running Qt backend prevents Python interpreter to run and process signals (i.e., to raise KeyboardInterrupt exception). To solve this one needs to somehow wake up the interpreter and make it close the plot window. We do this by using the signal.set_wakeup_fd() function which organizes a write of the signal number into a socketpair connected to the QSocketNotifier (since it is part of the Qt backend, it can react to that write event). Afterwards, the Qt handler empties the socketpair by a recv() command to re-arm it (we need this if a signal different from SIGINT was caught by set_wakeup_fd() and we shall continue waiting). If the SIGINT was caught indeed, after exiting the on_signal() function the interpreter reacts to the SIGINT according to the handle() function which had been set up by a signal.signal() call: it causes the qt_object to exit by calling its quit() method. Finally, we call the old SIGINT handler with the same arguments that were given to our custom handle() handler. We do this only if the old handler for SIGINT was not None, which means that a non-python handler was installed, i.e. in Julia, and not SIG_IGN which means we should ignore the interrupts. |
171,284 | from .. import backends
from .backend_qt import ( # noqa
SPECIAL_KEYS,
# Public API
cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT,
FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt,
SaveFigureQt, ConfigureSubplotsQt, RubberbandQt,
HelpQt, ToolCopyToClipboardQT,
# internal re-exports
FigureCanvasBase, FigureManagerBase, MouseButton, NavigationToolbar2,
TimerBase, ToolContainerBase, figureoptions, Gcf
)
from . import backend_qt as _backend_qt
def __getattr__(name):
if name == 'qApp':
return _backend_qt.qApp
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") | null |
171,285 | from base64 import b64encode
import io
import json
import pathlib
import uuid
from ipykernel.comm import Comm
from IPython.display import display, Javascript, HTML
from matplotlib import is_interactive
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2
from .backend_webagg_core import (
FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg)
from .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611
TimerTornado, TimerAsyncio)
)
def is_interactive():
"""
Return whether to redraw after every plotting command.
.. note::
This function is only intended for use in backends. End users should
use `.pyplot.isinteractive` instead.
"""
return rcParams['interactive']
class Gcf:
"""
Singleton to maintain the relation between figures and their managers, and
keep track of and "active" figure and manager.
The canvas of a figure created through pyplot is associated with a figure
manager, which handles the interaction between the figure and the backend.
pyplot keeps track of figure managers using an identifier, the "figure
number" or "manager number" (which can actually be any hashable value);
this number is available as the :attr:`number` attribute of the manager.
This class is never instantiated; it consists of an `OrderedDict` mapping
figure/manager numbers to managers, and a set of class methods that
manipulate this `OrderedDict`.
Attributes
----------
figs : OrderedDict
`OrderedDict` mapping numbers to managers; the active manager is at the
end.
"""
figs = OrderedDict()
def get_fig_manager(cls, num):
"""
If manager number *num* exists, make it the active one and return it;
otherwise return *None*.
"""
manager = cls.figs.get(num, None)
if manager is not None:
cls.set_active(manager)
return manager
def destroy(cls, num):
"""
Destroy manager *num* -- either a manager instance or a manager number.
In the interactive backends, this is bound to the window "destroy" and
"delete" events.
It is recommended to pass a manager instance, to avoid confusion when
two managers share the same number.
"""
if all(hasattr(num, attr) for attr in ["num", "destroy"]):
manager = num
if cls.figs.get(manager.num) is manager:
cls.figs.pop(manager.num)
else:
try:
manager = cls.figs.pop(num)
except KeyError:
return
if hasattr(manager, "_cidgcf"):
manager.canvas.mpl_disconnect(manager._cidgcf)
manager.destroy()
del manager, num
def destroy_fig(cls, fig):
"""Destroy figure *fig*."""
num = next((manager.num for manager in cls.figs.values()
if manager.canvas.figure == fig), None)
if num is not None:
cls.destroy(num)
def destroy_all(cls):
"""Destroy all figures."""
for manager in list(cls.figs.values()):
manager.canvas.mpl_disconnect(manager._cidgcf)
manager.destroy()
cls.figs.clear()
def has_fignum(cls, num):
"""Return whether figure number *num* exists."""
return num in cls.figs
def get_all_fig_managers(cls):
"""Return a list of figure managers."""
return list(cls.figs.values())
def get_num_fig_managers(cls):
"""Return the number of figures being managed."""
return len(cls.figs)
def get_active(cls):
"""Return the active manager, or *None* if there is no manager."""
return next(reversed(cls.figs.values())) if cls.figs else None
def _set_new_active_manager(cls, manager):
"""Adopt *manager* into pyplot and make it the active manager."""
if not hasattr(manager, "_cidgcf"):
manager._cidgcf = manager.canvas.mpl_connect(
"button_press_event", lambda event: cls.set_active(manager))
fig = manager.canvas.figure
fig.number = manager.num
label = fig.get_label()
if label:
manager.set_window_title(label)
cls.set_active(manager)
def set_active(cls, manager):
"""Make *manager* the active manager."""
cls.figs[manager.num] = manager
cls.figs.move_to_end(manager.num)
def draw_all(cls, force=False):
"""
Redraw all stale managed figures, or, if *force* is True, all managed
figures.
"""
for manager in cls.get_all_fig_managers():
if force or manager.canvas.figure.stale:
manager.canvas.draw_idle()
The provided code snippet includes necessary dependencies for implementing the `connection_info` function. Write a Python function `def connection_info()` to solve the following problem:
Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use.
Here is the function:
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 = [
'{fig} - {socket}'.format(
fig=(manager.canvas.figure.get_label()
or "Figure {}".format(manager.num)),
socket=manager.web_sockets)
for manager in Gcf.get_all_fig_managers()
]
if not is_interactive():
result.append(f'Figures pending show: {len(Gcf.figs)}')
return '\n'.join(result) | Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use. |
171,286 | from io import BytesIO
import functools
from fontTools import subset
import matplotlib as mpl
from .. import font_manager, ft2font
from .._afm import AFM
from ..backend_bases import RendererBase
class AFM:
def __init__(self, fh):
"""Parse the AFM file in file object *fh*."""
self._header = _parse_header(fh)
self._metrics, self._metrics_by_name = _parse_char_metrics(fh)
self._kern, self._composite = _parse_optional(fh)
def get_bbox_char(self, c, isord=False):
if not isord:
c = ord(c)
return self._metrics[c].bbox
def string_width_height(self, s):
"""
Return the string width (including kerning) and string height
as a (*w*, *h*) tuple.
"""
if not len(s):
return 0, 0
total_width = 0
namelast = None
miny = 1e9
maxy = 0
for c in s:
if c == '\n':
continue
wx, name, bbox = self._metrics[ord(c)]
total_width += wx + self._kern.get((namelast, name), 0)
l, b, w, h = bbox
miny = min(miny, b)
maxy = max(maxy, b + h)
namelast = name
return total_width, maxy - miny
def get_str_bbox_and_descent(self, s):
"""Return the string bounding box and the maximal descent."""
if not len(s):
return 0, 0, 0, 0, 0
total_width = 0
namelast = None
miny = 1e9
maxy = 0
left = 0
if not isinstance(s, str):
s = _to_str(s)
for c in s:
if c == '\n':
continue
name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
try:
wx, _, bbox = self._metrics_by_name[name]
except KeyError:
name = 'question'
wx, _, bbox = self._metrics_by_name[name]
total_width += wx + self._kern.get((namelast, name), 0)
l, b, w, h = bbox
left = min(left, l)
miny = min(miny, b)
maxy = max(maxy, b + h)
namelast = name
return left, miny, total_width, maxy - miny, -miny
def get_str_bbox(self, s):
"""Return the string bounding box."""
return self.get_str_bbox_and_descent(s)[:4]
def get_name_char(self, c, isord=False):
"""Get the name of the character, i.e., ';' is 'semicolon'."""
if not isord:
c = ord(c)
return self._metrics[c].name
def get_width_char(self, c, isord=False):
"""
Get the width of the character from the character metric WX field.
"""
if not isord:
c = ord(c)
return self._metrics[c].width
def get_width_from_char_name(self, name):
"""Get the width of the character from a type1 character name."""
return self._metrics_by_name[name].width
def get_height_char(self, c, isord=False):
"""Get the bounding box (ink) height of character *c* (space is 0)."""
if not isord:
c = ord(c)
return self._metrics[c].bbox[-1]
def get_kern_dist(self, c1, c2):
"""
Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
"""
name1, name2 = self.get_name_char(c1), self.get_name_char(c2)
return self.get_kern_dist_from_name(name1, name2)
def get_kern_dist_from_name(self, name1, name2):
"""
Return the kerning pair distance (possibly 0) for chars
*name1* and *name2*.
"""
return self._kern.get((name1, name2), 0)
def get_fontname(self):
"""Return the font name, e.g., 'Times-Roman'."""
return self._header[b'FontName']
def postscript_name(self): # For consistency with FT2Font.
return self.get_fontname()
def get_fullname(self):
"""Return the font full name, e.g., 'Times-Roman'."""
name = self._header.get(b'FullName')
if name is None: # use FontName as a substitute
name = self._header[b'FontName']
return name
def get_familyname(self):
"""Return the font family name, e.g., 'Times'."""
name = self._header.get(b'FamilyName')
if name is not None:
return name
# FamilyName not specified so we'll make a guess
name = self.get_fullname()
extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
r'light|ultralight|extra|condensed))+$')
return re.sub(extras, '', name)
def family_name(self):
"""The font family name, e.g., 'Times'."""
return self.get_familyname()
def get_weight(self):
"""Return the font weight, e.g., 'Bold' or 'Roman'."""
return self._header[b'Weight']
def get_angle(self):
"""Return the fontangle as float."""
return self._header[b'ItalicAngle']
def get_capheight(self):
"""Return the cap height as float."""
return self._header[b'CapHeight']
def get_xheight(self):
"""Return the xheight as float."""
return self._header[b'XHeight']
def get_underline_thickness(self):
"""Return the underline thickness as float."""
return self._header[b'UnderlineThickness']
def get_horizontal_stem_width(self):
"""
Return the standard horizontal stem width as float, or *None* if
not specified in AFM file.
"""
return self._header.get(b'StdHW', None)
def get_vertical_stem_width(self):
"""
Return the standard vertical stem width as float, or *None* if
not specified in AFM file.
"""
return self._header.get(b'StdVW', None)
def _cached_get_afm_from_fname(fname):
with open(fname, "rb") as fh:
return AFM(fh) | null |
171,287 | from contextlib import nullcontext
from math import radians, cos, sin
import threading
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.font_manager import fontManager as _fontManager, get_font
from matplotlib.ft2font import (LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING,
LOAD_DEFAULT, LOAD_NO_AUTOHINT)
from matplotlib.mathtext import MathTextParser
from matplotlib.path import Path
from matplotlib.transforms import Bbox, BboxBase
from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
def get_hinting_flag():
mapping = {
'default': LOAD_DEFAULT,
'no_autohint': LOAD_NO_AUTOHINT,
'force_autohint': LOAD_FORCE_AUTOHINT,
'no_hinting': LOAD_NO_HINTING,
True: LOAD_FORCE_AUTOHINT,
False: LOAD_NO_HINTING,
'either': LOAD_DEFAULT,
'native': LOAD_NO_AUTOHINT,
'auto': LOAD_FORCE_AUTOHINT,
'none': LOAD_NO_HINTING,
}
return mapping[mpl.rcParams['text.hinting']] | null |
171,288 | import functools
import logging
import os
from pathlib import Path
import sys
import matplotlib as mpl
from matplotlib import _api, backend_tools, cbook
from matplotlib.backend_bases import (
ToolContainerBase, CloseEvent, KeyEvent, LocationEvent, MouseEvent,
ResizeEvent)
from gi.repository import Gio, GLib, GObject, Gtk, Gdk
from . import _backend_gtk
from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611
_BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,
TimerGTK as TimerGTK3,
)
def _mpl_to_gtk_cursor(mpl_cursor):
return Gdk.Cursor.new_from_name(
Gdk.Display.get_default(),
_backend_gtk.mpl_to_gtk_cursor_name(mpl_cursor)) | null |
171,289 | import functools
import logging
import os
from pathlib import Path
import sys
import matplotlib as mpl
from matplotlib import _api, backend_tools, cbook
from matplotlib.backend_bases import (
ToolContainerBase, CloseEvent, KeyEvent, LocationEvent, MouseEvent,
ResizeEvent)
from gi.repository import Gio, GLib, GObject, Gtk, Gdk
from . import _backend_gtk
from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611
_BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,
TimerGTK as TimerGTK3,
)
def error_msg_gtk(msg, parent=None):
if parent is not None: # find the toplevel Gtk.Window
parent = parent.get_toplevel()
if not parent.is_toplevel():
parent = None
if not isinstance(msg, str):
msg = ','.join(map(str, msg))
dialog = Gtk.MessageDialog(
parent=parent, type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
message_format=msg)
dialog.run()
dialog.destroy() | null |
171,290 | import functools
import logging
import math
import pathlib
import sys
import weakref
import numpy as np
import PIL
import matplotlib as mpl
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase,
GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase,
TimerBase, ToolContainerBase, cursors,
CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
from matplotlib import _api, cbook, backend_tools
from matplotlib._pylab_helpers import Gcf
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
import wx
class FigureManagerWx(FigureManagerBase):
"""
Container/controller for the FigureCanvas and GUI frame.
It is instantiated by Gcf whenever a new figure is created. Gcf 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 _load_bitmap(filename):
"""
Load a wx.Bitmap from a file in the "images" directory of the Matplotlib
data.
"""
return wx.Bitmap(str(cbook._get_data_path('images', filename)))
def _set_frame_icon(frame):
bundle = wx.IconBundle()
for image in ('matplotlib.png', 'matplotlib_large.png'):
icon = wx.Icon(_load_bitmap(image))
if not icon.IsOk():
return
bundle.AddIcon(icon)
frame.SetIcons(bundle)
class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar):
The provided code snippet includes necessary dependencies for implementing the `error_msg_wx` function. Write a Python function `def error_msg_wx(msg, parent=None)` to solve the following problem:
Signal an error condition with a popup error dialog.
Here is the function:
def error_msg_wx(msg, parent=None):
"""Signal an error condition with a popup 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 | Signal an error condition with a popup error dialog. |
171,291 | import functools
import logging
import math
import pathlib
import sys
import weakref
import numpy as np
import PIL
import matplotlib as mpl
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase,
GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase,
TimerBase, ToolContainerBase, cursors,
CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
from matplotlib import _api, cbook, backend_tools
from matplotlib._pylab_helpers import Gcf
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
import wx
class FigureManagerWx(FigureManagerBase):
"""
Container/controller for the FigureCanvas and GUI frame.
It is instantiated by Gcf whenever a new figure is created. Gcf 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 _load_bitmap(filename):
"""
Load a wx.Bitmap from a file in the "images" directory of the Matplotlib
data.
"""
return wx.Bitmap(str(cbook._get_data_path('images', filename)))
def _set_frame_icon(frame):
bundle = wx.IconBundle()
for image in ('matplotlib.png', 'matplotlib_large.png'):
icon = wx.Icon(_load_bitmap(image))
if not icon.IsOk():
return
bundle.AddIcon(icon)
frame.SetIcons(bundle)
class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar):
def _create_wxapp():
wxapp = wx.App(False)
wxapp.SetExitOnFrameDelete(True)
cbook._setup_new_guiapp()
return wxapp | null |
171,292 | import functools
import logging
import math
import pathlib
import sys
import weakref
import numpy as np
import PIL
import matplotlib as mpl
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase,
GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase,
TimerBase, ToolContainerBase, cursors,
CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
from matplotlib import _api, cbook, backend_tools
from matplotlib._pylab_helpers import Gcf
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
import wx
class FigureManagerWx(FigureManagerBase):
"""
Container/controller for the FigureCanvas and GUI frame.
It is instantiated by Gcf whenever a new figure is created. Gcf 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 _load_bitmap(filename):
"""
Load a wx.Bitmap from a file in the "images" directory of the Matplotlib
data.
"""
return wx.Bitmap(str(cbook._get_data_path('images', filename)))
def _set_frame_icon(frame):
bundle = wx.IconBundle()
for image in ('matplotlib.png', 'matplotlib_large.png'):
icon = wx.Icon(_load_bitmap(image))
if not icon.IsOk():
return
bundle.AddIcon(icon)
frame.SetIcons(bundle)
class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar):
def _set_frame_icon(frame):
bundle = wx.IconBundle()
for image in ('matplotlib.png', 'matplotlib_large.png'):
icon = wx.Icon(_load_bitmap(image))
if not icon.IsOk():
return
bundle.AddIcon(icon)
frame.SetIcons(bundle) | null |
171,293 | import codecs
from datetime import datetime
from enum import Enum
from functools import total_ordering
from io import BytesIO
import itertools
import logging
import math
import os
import string
import struct
import sys
import time
import types
import warnings
import zlib
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib import _api, _text_helpers, _type1font, cbook, dviread
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.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font)
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from . import _backend_pdf_ps
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)
def fill(strings, linelen=75):
return _fill(strings, linelen=linelen) | null |
171,294 | import codecs
from datetime import datetime
from enum import Enum
from functools import total_ordering
from io import BytesIO
import itertools
import logging
import math
import os
import string
import struct
import sys
import time
import types
import warnings
import zlib
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib import _api, _text_helpers, _type1font, cbook, dviread
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.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font)
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from . import _backend_pdf_ps
class Name:
"""PDF name object."""
__slots__ = ('name',)
_hexify = {c: '#%02x' % c
for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}}
def __init__(self, name):
if isinstance(name, Name):
self.name = name.name
else:
if isinstance(name, bytes):
name = name.decode('ascii')
self.name = name.translate(self._hexify).encode('ascii')
def __repr__(self):
return "<Name %s>" % self.name
def __str__(self):
return '/' + self.name.decode('ascii')
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)
def hexify(match):
return '#%02x' % ord(match.group())
def pdfRepr(self):
return b'/' + self.name
class datetime(date):
min: ClassVar[datetime]
max: ClassVar[datetime]
resolution: ClassVar[timedelta]
if sys.version_info >= (3, 6):
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> _S: ...
else:
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> _S: ...
def year(self) -> int: ...
def month(self) -> int: ...
def day(self) -> int: ...
def hour(self) -> int: ...
def minute(self) -> int: ...
def second(self) -> int: ...
def microsecond(self) -> int: ...
def tzinfo(self) -> Optional[_tzinfo]: ...
if sys.version_info >= (3, 6):
def fold(self) -> int: ...
def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ...
def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ...
def today(cls: Type[_S]) -> _S: ...
def fromordinal(cls: Type[_S], n: int) -> _S: ...
if sys.version_info >= (3, 8):
def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ...
else:
def now(cls: Type[_S], tz: None = ...) -> _S: ...
def now(cls, tz: _tzinfo) -> datetime: ...
def utcnow(cls: Type[_S]) -> _S: ...
if sys.version_info >= (3, 6):
def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ...
else:
def combine(cls, date: _date, time: _time) -> datetime: ...
if sys.version_info >= (3, 7):
def fromisoformat(cls: Type[_S], date_string: str) -> _S: ...
def strftime(self, fmt: _Text) -> str: ...
if sys.version_info >= (3,):
def __format__(self, fmt: str) -> str: ...
else:
def __format__(self, fmt: AnyStr) -> AnyStr: ...
def toordinal(self) -> int: ...
def timetuple(self) -> struct_time: ...
if sys.version_info >= (3, 3):
def timestamp(self) -> float: ...
def utctimetuple(self) -> struct_time: ...
def date(self) -> _date: ...
def time(self) -> _time: ...
def timetz(self) -> _time: ...
if sys.version_info >= (3, 6):
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> datetime: ...
else:
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> datetime: ...
if sys.version_info >= (3, 8):
def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ...
elif sys.version_info >= (3, 3):
def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ...
else:
def astimezone(self, tz: _tzinfo) -> datetime: ...
def ctime(self) -> str: ...
if sys.version_info >= (3, 6):
def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ...
else:
def isoformat(self, sep: str = ...) -> str: ...
def strptime(cls, date_string: _Text, format: _Text) -> datetime: ...
def utcoffset(self) -> Optional[timedelta]: ...
def tzname(self) -> Optional[str]: ...
def dst(self) -> Optional[timedelta]: ...
def __le__(self, other: datetime) -> bool: ... # type: ignore
def __lt__(self, other: datetime) -> bool: ... # type: ignore
def __ge__(self, other: datetime) -> bool: ... # type: ignore
def __gt__(self, other: datetime) -> bool: ... # type: ignore
if sys.version_info >= (3, 8):
def __add__(self: _S, other: timedelta) -> _S: ...
def __radd__(self: _S, other: timedelta) -> _S: ...
else:
def __add__(self, other: timedelta) -> datetime: ...
def __radd__(self, other: timedelta) -> datetime: ...
def __sub__(self, other: datetime) -> timedelta: ...
def __sub__(self, other: timedelta) -> datetime: ...
def __hash__(self) -> int: ...
def weekday(self) -> int: ...
def isoweekday(self) -> int: ...
def isocalendar(self) -> Tuple[int, int, int]: ...
UTC = datetime.timezone.utc
The provided code snippet includes necessary dependencies for implementing the `_create_pdf_info_dict` function. Write a Python function `def _create_pdf_info_dict(backend, metadata)` to solve the following problem:
Create a PDF infoDict based on user-supplied metadata. A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though the user metadata may override it. The date may be the current time, or a time set by the ``SOURCE_DATE_EPOCH`` environment variable. Metadata is verified to have the correct keys and their expected types. Any unknown keys/types will raise a warning. Parameters ---------- backend : str The name of the backend to use in the Producer value. metadata : dict[str, Union[str, datetime, Name]] A dictionary of metadata supplied by the user with information following the PDF specification, also defined in `~.backend_pdf.PdfPages` below. If any value is *None*, then the key will be removed. This can be used to remove any pre-defined values. Returns ------- dict[str, Union[str, datetime, Name]] A validated dictionary of metadata.
Here is the function:
def _create_pdf_info_dict(backend, metadata):
"""
Create a PDF infoDict based on user-supplied metadata.
A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though
the user metadata may override it. The date may be the current time, or a
time set by the ``SOURCE_DATE_EPOCH`` environment variable.
Metadata is verified to have the correct keys and their expected types. Any
unknown keys/types will raise a warning.
Parameters
----------
backend : str
The name of the backend to use in the Producer value.
metadata : dict[str, Union[str, datetime, Name]]
A dictionary of metadata supplied by the user with information
following the PDF specification, also defined in
`~.backend_pdf.PdfPages` below.
If any value is *None*, then the key will be removed. This can be used
to remove any pre-defined values.
Returns
-------
dict[str, Union[str, datetime, Name]]
A validated dictionary of metadata.
"""
# 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()
info = {
'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org',
'Producer': f'Matplotlib {backend} backend v{mpl.__version__}',
'CreationDate': source_date,
**metadata
}
info = {k: v for (k, v) in info.items() if v is not None}
def is_string_like(x):
return isinstance(x, str)
is_string_like.text_for_warning = "an instance of str"
def is_date(x):
return isinstance(x, datetime)
is_date.text_for_warning = "an instance of datetime.datetime"
def check_trapped(x):
if isinstance(x, Name):
return x.name in (b'True', b'False', b'Unknown')
else:
return x in ('True', 'False', 'Unknown')
check_trapped.text_for_warning = 'one of {"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 info:
if k not in keywords:
_api.warn_external(f'Unknown infodict keyword: {k!r}. '
f'Must be one of {set(keywords)!r}.')
elif not keywords[k](info[k]):
_api.warn_external(f'Bad value for infodict keyword {k}. '
f'Got {info[k]!r} which is not '
f'{keywords[k].text_for_warning}.')
if 'Trapped' in info:
info['Trapped'] = Name(info['Trapped'])
return info | Create a PDF infoDict based on user-supplied metadata. A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though the user metadata may override it. The date may be the current time, or a time set by the ``SOURCE_DATE_EPOCH`` environment variable. Metadata is verified to have the correct keys and their expected types. Any unknown keys/types will raise a warning. Parameters ---------- backend : str The name of the backend to use in the Producer value. metadata : dict[str, Union[str, datetime, Name]] A dictionary of metadata supplied by the user with information following the PDF specification, also defined in `~.backend_pdf.PdfPages` below. If any value is *None*, then the key will be removed. This can be used to remove any pre-defined values. Returns ------- dict[str, Union[str, datetime, Name]] A validated dictionary of metadata. |
171,295 | import codecs
from datetime import datetime
from enum import Enum
from functools import total_ordering
from io import BytesIO
import itertools
import logging
import math
import os
import string
import struct
import sys
import time
import types
import warnings
import zlib
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib import _api, _text_helpers, _type1font, cbook, dviread
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.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font)
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from . import _backend_pdf_ps
def _get_coordinates_of_block(x, y, width, height, angle=0):
"""
Get the coordinates of rotated rectangle and rectangle that covers the
rotated rectangle.
"""
vertices = _calculate_quad_point_coordinates(x, y, width,
height, angle)
# Find min and max values for rectangle
# adjust so that QuadPoints is inside Rect
# PDF docs says that QuadPoints should be ignored if any point lies
# outside Rect, but for Acrobat it is enough that QuadPoints is on the
# border of Rect.
pad = 0.00001 if angle % 90 else 0
min_x = min(v[0] for v in vertices) - pad
min_y = min(v[1] for v in vertices) - pad
max_x = max(v[0] for v in vertices) + pad
max_y = max(v[1] for v in vertices) + pad
return (tuple(itertools.chain.from_iterable(vertices)),
(min_x, min_y, max_x, max_y))
class Name:
"""PDF name object."""
__slots__ = ('name',)
_hexify = {c: '#%02x' % c
for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}}
def __init__(self, name):
if isinstance(name, Name):
self.name = name.name
else:
if isinstance(name, bytes):
name = name.decode('ascii')
self.name = name.translate(self._hexify).encode('ascii')
def __repr__(self):
return "<Name %s>" % self.name
def __str__(self):
return '/' + self.name.decode('ascii')
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)
def hexify(match):
return '#%02x' % ord(match.group())
def pdfRepr(self):
return b'/' + self.name
The provided code snippet includes necessary dependencies for implementing the `_get_link_annotation` function. Write a Python function `def _get_link_annotation(gc, x, y, width, height, angle=0)` to solve the following problem:
Create a link annotation object for embedding URLs.
Here is the function:
def _get_link_annotation(gc, x, y, width, height, angle=0):
"""
Create a link annotation object for embedding URLs.
"""
quadpoints, rect = _get_coordinates_of_block(x, y, width, height, angle)
link_annotation = {
'Type': Name('Annot'),
'Subtype': Name('Link'),
'Rect': rect,
'Border': [0, 0, 0],
'A': {
'S': Name('URI'),
'URI': gc.get_url(),
},
}
if angle % 90:
# Add QuadPoints
link_annotation['QuadPoints'] = quadpoints
return link_annotation | Create a link annotation object for embedding URLs. |
171,296 | import codecs
from datetime import datetime
from enum import Enum
from functools import total_ordering
from io import BytesIO
import itertools
import logging
import math
import os
import string
import struct
import sys
import time
import types
import warnings
import zlib
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib import _api, _text_helpers, _type1font, cbook, dviread
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.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font)
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from . import _backend_pdf_ps
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)
def _datetime_to_pdf(d):
"""
Convert a datetime to a PDF string representing it.
Used for PDF and PGF.
"""
r = d.strftime('D:%Y%m%d%H%M%S')
z = d.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 r
_str_escapes = str.maketrans({
'\\': '\\\\', '(': '\\(', ')': '\\)', '\n': '\\n', '\r': '\\r'})
class Name:
"""PDF name object."""
__slots__ = ('name',)
_hexify = {c: '#%02x' % c
for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}}
def __init__(self, name):
if isinstance(name, Name):
self.name = name.name
else:
if isinstance(name, bytes):
name = name.decode('ascii')
self.name = name.translate(self._hexify).encode('ascii')
def __repr__(self):
return "<Name %s>" % self.name
def __str__(self):
return '/' + self.name.decode('ascii')
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)
def hexify(match):
return '#%02x' % ord(match.group())
def pdfRepr(self):
return b'/' + self.name
class datetime(date):
min: ClassVar[datetime]
max: ClassVar[datetime]
resolution: ClassVar[timedelta]
if sys.version_info >= (3, 6):
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> _S: ...
else:
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> _S: ...
def year(self) -> int: ...
def month(self) -> int: ...
def day(self) -> int: ...
def hour(self) -> int: ...
def minute(self) -> int: ...
def second(self) -> int: ...
def microsecond(self) -> int: ...
def tzinfo(self) -> Optional[_tzinfo]: ...
if sys.version_info >= (3, 6):
def fold(self) -> int: ...
def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ...
def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ...
def today(cls: Type[_S]) -> _S: ...
def fromordinal(cls: Type[_S], n: int) -> _S: ...
if sys.version_info >= (3, 8):
def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ...
else:
def now(cls: Type[_S], tz: None = ...) -> _S: ...
def now(cls, tz: _tzinfo) -> datetime: ...
def utcnow(cls: Type[_S]) -> _S: ...
if sys.version_info >= (3, 6):
def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ...
else:
def combine(cls, date: _date, time: _time) -> datetime: ...
if sys.version_info >= (3, 7):
def fromisoformat(cls: Type[_S], date_string: str) -> _S: ...
def strftime(self, fmt: _Text) -> str: ...
if sys.version_info >= (3,):
def __format__(self, fmt: str) -> str: ...
else:
def __format__(self, fmt: AnyStr) -> AnyStr: ...
def toordinal(self) -> int: ...
def timetuple(self) -> struct_time: ...
if sys.version_info >= (3, 3):
def timestamp(self) -> float: ...
def utctimetuple(self) -> struct_time: ...
def date(self) -> _date: ...
def time(self) -> _time: ...
def timetz(self) -> _time: ...
if sys.version_info >= (3, 6):
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> datetime: ...
else:
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> datetime: ...
if sys.version_info >= (3, 8):
def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ...
elif sys.version_info >= (3, 3):
def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ...
else:
def astimezone(self, tz: _tzinfo) -> datetime: ...
def ctime(self) -> str: ...
if sys.version_info >= (3, 6):
def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ...
else:
def isoformat(self, sep: str = ...) -> str: ...
def strptime(cls, date_string: _Text, format: _Text) -> datetime: ...
def utcoffset(self) -> Optional[timedelta]: ...
def tzname(self) -> Optional[str]: ...
def dst(self) -> Optional[timedelta]: ...
def __le__(self, other: datetime) -> bool: ... # type: ignore
def __lt__(self, other: datetime) -> bool: ... # type: ignore
def __ge__(self, other: datetime) -> bool: ... # type: ignore
def __gt__(self, other: datetime) -> bool: ... # type: ignore
if sys.version_info >= (3, 8):
def __add__(self: _S, other: timedelta) -> _S: ...
def __radd__(self: _S, other: timedelta) -> _S: ...
else:
def __add__(self, other: timedelta) -> datetime: ...
def __radd__(self, other: timedelta) -> datetime: ...
def __sub__(self, other: datetime) -> timedelta: ...
def __sub__(self, other: timedelta) -> datetime: ...
def __hash__(self) -> int: ...
def weekday(self) -> int: ...
def isoweekday(self) -> int: ...
def isocalendar(self) -> Tuple[int, int, int]: ...
class BboxBase(TransformNode):
"""
The base class of all bounding boxes.
This class is immutable; `Bbox` is a mutable subclass.
The canonical representation is as two points, with no
restrictions on their ordering. Convenience properties are
provided to get the left, bottom, right and top edges and width
and height, but these are not stored explicitly.
"""
is_bbox = True
is_affine = True
if DEBUG:
def _check(points):
if isinstance(points, np.ma.MaskedArray):
_api.warn_external("Bbox bounds are a masked array.")
points = np.asarray(points)
if any((points[1, :] - points[0, :]) == 0):
_api.warn_external("Singular Bbox.")
def frozen(self):
return Bbox(self.get_points().copy())
frozen.__doc__ = TransformNode.__doc__
def __array__(self, *args, **kwargs):
return self.get_points()
def x0(self):
"""
The first of the pair of *x* coordinates that define the bounding box.
This is not guaranteed to be less than :attr:`x1` (for that, use
:attr:`xmin`).
"""
return self.get_points()[0, 0]
def y0(self):
"""
The first of the pair of *y* coordinates that define the bounding box.
This is not guaranteed to be less than :attr:`y1` (for that, use
:attr:`ymin`).
"""
return self.get_points()[0, 1]
def x1(self):
"""
The second of the pair of *x* coordinates that define the bounding box.
This is not guaranteed to be greater than :attr:`x0` (for that, use
:attr:`xmax`).
"""
return self.get_points()[1, 0]
def y1(self):
"""
The second of the pair of *y* coordinates that define the bounding box.
This is not guaranteed to be greater than :attr:`y0` (for that, use
:attr:`ymax`).
"""
return self.get_points()[1, 1]
def p0(self):
"""
The first pair of (*x*, *y*) coordinates that define the bounding box.
This is not guaranteed to be the bottom-left corner (for that, use
:attr:`min`).
"""
return self.get_points()[0]
def p1(self):
"""
The second pair of (*x*, *y*) coordinates that define the bounding box.
This is not guaranteed to be the top-right corner (for that, use
:attr:`max`).
"""
return self.get_points()[1]
def xmin(self):
"""The left edge of the bounding box."""
return np.min(self.get_points()[:, 0])
def ymin(self):
"""The bottom edge of the bounding box."""
return np.min(self.get_points()[:, 1])
def xmax(self):
"""The right edge of the bounding box."""
return np.max(self.get_points()[:, 0])
def ymax(self):
"""The top edge of the bounding box."""
return np.max(self.get_points()[:, 1])
def min(self):
"""The bottom-left corner of the bounding box."""
return np.min(self.get_points(), axis=0)
def max(self):
"""The top-right corner of the bounding box."""
return np.max(self.get_points(), axis=0)
def intervalx(self):
"""
The pair of *x* coordinates that define the bounding box.
This is not guaranteed to be sorted from left to right.
"""
return self.get_points()[:, 0]
def intervaly(self):
"""
The pair of *y* coordinates that define the bounding box.
This is not guaranteed to be sorted from bottom to top.
"""
return self.get_points()[:, 1]
def width(self):
"""The (signed) width of the bounding box."""
points = self.get_points()
return points[1, 0] - points[0, 0]
def height(self):
"""The (signed) height of the bounding box."""
points = self.get_points()
return points[1, 1] - points[0, 1]
def size(self):
"""The (signed) width and height of the bounding box."""
points = self.get_points()
return points[1] - points[0]
def bounds(self):
"""Return (:attr:`x0`, :attr:`y0`, :attr:`width`, :attr:`height`)."""
(x0, y0), (x1, y1) = self.get_points()
return (x0, y0, x1 - x0, y1 - y0)
def extents(self):
"""Return (:attr:`x0`, :attr:`y0`, :attr:`x1`, :attr:`y1`)."""
return self.get_points().flatten() # flatten returns a copy.
def get_points(self):
raise NotImplementedError
def containsx(self, x):
"""
Return whether *x* is in the closed (:attr:`x0`, :attr:`x1`) interval.
"""
x0, x1 = self.intervalx
return x0 <= x <= x1 or x0 >= x >= x1
def containsy(self, y):
"""
Return whether *y* is in the closed (:attr:`y0`, :attr:`y1`) interval.
"""
y0, y1 = self.intervaly
return y0 <= y <= y1 or y0 >= y >= y1
def contains(self, x, y):
"""
Return whether ``(x, y)`` is in the bounding box or on its edge.
"""
return self.containsx(x) and self.containsy(y)
def overlaps(self, other):
"""
Return whether this bounding box overlaps with the other bounding box.
Parameters
----------
other : `.BboxBase`
"""
ax1, ay1, ax2, ay2 = self.extents
bx1, by1, bx2, by2 = other.extents
if ax2 < ax1:
ax2, ax1 = ax1, ax2
if ay2 < ay1:
ay2, ay1 = ay1, ay2
if bx2 < bx1:
bx2, bx1 = bx1, bx2
if by2 < by1:
by2, by1 = by1, by2
return ax1 <= bx2 and bx1 <= ax2 and ay1 <= by2 and by1 <= ay2
def fully_containsx(self, x):
"""
Return whether *x* is in the open (:attr:`x0`, :attr:`x1`) interval.
"""
x0, x1 = self.intervalx
return x0 < x < x1 or x0 > x > x1
def fully_containsy(self, y):
"""
Return whether *y* is in the open (:attr:`y0`, :attr:`y1`) interval.
"""
y0, y1 = self.intervaly
return y0 < y < y1 or y0 > y > y1
def fully_contains(self, x, y):
"""
Return whether ``x, y`` is in the bounding box, but not on its edge.
"""
return self.fully_containsx(x) and self.fully_containsy(y)
def fully_overlaps(self, other):
"""
Return whether this bounding box overlaps with the other bounding box,
not including the edges.
Parameters
----------
other : `.BboxBase`
"""
ax1, ay1, ax2, ay2 = self.extents
bx1, by1, bx2, by2 = other.extents
if ax2 < ax1:
ax2, ax1 = ax1, ax2
if ay2 < ay1:
ay2, ay1 = ay1, ay2
if bx2 < bx1:
bx2, bx1 = bx1, bx2
if by2 < by1:
by2, by1 = by1, by2
return ax1 < bx2 and bx1 < ax2 and ay1 < by2 and by1 < ay2
def transformed(self, transform):
"""
Construct a `Bbox` by statically transforming this one by *transform*.
"""
pts = self.get_points()
ll, ul, lr = transform.transform(np.array(
[pts[0], [pts[0, 0], pts[1, 1]], [pts[1, 0], pts[0, 1]]]))
return Bbox([ll, [lr[0], ul[1]]])
coefs = {'C': (0.5, 0.5),
'SW': (0, 0),
'S': (0.5, 0),
'SE': (1.0, 0),
'E': (1.0, 0.5),
'NE': (1.0, 1.0),
'N': (0.5, 1.0),
'NW': (0, 1.0),
'W': (0, 0.5)}
def anchored(self, c, container=None):
"""
Return a copy of the `Bbox` anchored to *c* within *container*.
Parameters
----------
c : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
Either an (*x*, *y*) pair of relative coordinates (0 is left or
bottom, 1 is right or top), 'C' (center), or a cardinal direction
('SW', southwest, is bottom left, etc.).
container : `Bbox`, optional
The box within which the `Bbox` is positioned; it defaults
to the initial `Bbox`.
See Also
--------
.Axes.set_anchor
"""
if container is None:
container = self
l, b, w, h = container.bounds
if isinstance(c, str):
cx, cy = self.coefs[c]
else:
cx, cy = c
L, B, W, H = self.bounds
return Bbox(self._points +
[(l + cx * (w - W)) - L,
(b + cy * (h - H)) - B])
def shrunk(self, mx, my):
"""
Return a copy of the `Bbox`, shrunk by the factor *mx*
in the *x* direction and the factor *my* in the *y* direction.
The lower left corner of the box remains unchanged. Normally
*mx* and *my* will be less than 1, but this is not enforced.
"""
w, h = self.size
return Bbox([self._points[0],
self._points[0] + [mx * w, my * h]])
def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0):
"""
Return a copy of the `Bbox`, shrunk so that it is as
large as it can be while having the desired aspect ratio,
*box_aspect*. If the box coordinates are relative (i.e.
fractions of a larger box such as a figure) then the
physical aspect ratio of that figure is specified with
*fig_aspect*, so that *box_aspect* can also be given as a
ratio of the absolute dimensions, not the relative dimensions.
"""
if box_aspect <= 0 or fig_aspect <= 0:
raise ValueError("'box_aspect' and 'fig_aspect' must be positive")
if container is None:
container = self
w, h = container.size
H = w * box_aspect / fig_aspect
if H <= h:
W = w
else:
W = h * fig_aspect / box_aspect
H = h
return Bbox([self._points[0],
self._points[0] + (W, H)])
def splitx(self, *args):
"""
Return a list of new `Bbox` objects formed by splitting the original
one with vertical lines at fractional positions given by *args*.
"""
xf = [0, *args, 1]
x0, y0, x1, y1 = self.extents
w = x1 - x0
return [Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]])
for xf0, xf1 in zip(xf[:-1], xf[1:])]
def splity(self, *args):
"""
Return a list of new `Bbox` objects formed by splitting the original
one with horizontal lines at fractional positions given by *args*.
"""
yf = [0, *args, 1]
x0, y0, x1, y1 = self.extents
h = y1 - y0
return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]])
for yf0, yf1 in zip(yf[:-1], yf[1:])]
def count_contains(self, vertices):
"""
Count the number of vertices contained in the `Bbox`.
Any vertices with a non-finite x or y value are ignored.
Parameters
----------
vertices : Nx2 Numpy array.
"""
if len(vertices) == 0:
return 0
vertices = np.asarray(vertices)
with np.errstate(invalid='ignore'):
return (((self.min < vertices) &
(vertices < self.max)).all(axis=1).sum())
def count_overlaps(self, bboxes):
"""
Count the number of bounding boxes that overlap this one.
Parameters
----------
bboxes : sequence of `.BboxBase`
"""
return count_bboxes_overlapping_bbox(
self, np.atleast_3d([np.array(x) for x in bboxes]))
def expanded(self, sw, sh):
"""
Construct a `Bbox` by expanding this one around its center by the
factors *sw* and *sh*.
"""
width = self.width
height = self.height
deltaw = (sw * width - width) / 2.0
deltah = (sh * height - height) / 2.0
a = np.array([[-deltaw, -deltah], [deltaw, deltah]])
return Bbox(self._points + a)
def padded(self, p):
"""Construct a `Bbox` by padding this one on all four sides by *p*."""
points = self.get_points()
return Bbox(points + [[-p, -p], [p, p]])
def translated(self, tx, ty):
"""Construct a `Bbox` by translating this one by *tx* and *ty*."""
return Bbox(self._points + (tx, ty))
def corners(self):
"""
Return the corners of this rectangle as an array of points.
Specifically, this returns the array
``[[x0, y0], [x0, y1], [x1, y0], [x1, y1]]``.
"""
(x0, y0), (x1, y1) = self.get_points()
return np.array([[x0, y0], [x0, y1], [x1, y0], [x1, y1]])
def rotated(self, radians):
"""
Return the axes-aligned bounding box that bounds the result of rotating
this `Bbox` by an angle of *radians*.
"""
corners = self.corners()
corners_rotated = Affine2D().rotate(radians).transform(corners)
bbox = Bbox.unit()
bbox.update_from_data_xy(corners_rotated, ignore=True)
return bbox
def union(bboxes):
"""Return a `Bbox` that contains all of the given *bboxes*."""
if not len(bboxes):
raise ValueError("'bboxes' cannot be empty")
x0 = np.min([bbox.xmin for bbox in bboxes])
x1 = np.max([bbox.xmax for bbox in bboxes])
y0 = np.min([bbox.ymin for bbox in bboxes])
y1 = np.max([bbox.ymax for bbox in bboxes])
return Bbox([[x0, y0], [x1, y1]])
def intersection(bbox1, bbox2):
"""
Return the intersection of *bbox1* and *bbox2* if they intersect, or
None if they don't.
"""
x0 = np.maximum(bbox1.xmin, bbox2.xmin)
x1 = np.minimum(bbox1.xmax, bbox2.xmax)
y0 = np.maximum(bbox1.ymin, bbox2.ymin)
y1 = np.minimum(bbox1.ymax, bbox2.ymax)
return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None
The provided code snippet includes necessary dependencies for implementing the `pdfRepr` function. Write a Python function `def pdfRepr(obj)` to solve the following problem:
Map Python objects to PDF syntax.
Here is the function:
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 = b"%.10f" % obj
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, (int, np.integer)):
return b"%d" % obj
# Non-ASCII Unicode strings are encoded in UTF-16BE with byte-order mark.
elif isinstance(obj, str):
return pdfRepr(obj.encode('ascii') if obj.isascii()
else codecs.BOM_UTF16_BE + obj.encode('UTF-16BE'))
# 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.
# Despite the extra decode/encode, translate is faster than regex.
elif isinstance(obj, bytes):
return (
b'(' +
obj.decode('latin-1').translate(_str_escapes).encode('latin-1')
+ 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):
return _fill([
b"<<",
*[Name(k).pdfRepr() + b" " + pdfRepr(v) for k, v in obj.items()],
b">>",
])
# Lists.
elif isinstance(obj, (list, tuple)):
return _fill([b"[", *[pdfRepr(val) for val in obj], b"]"])
# The null keyword.
elif obj is None:
return b'null'
# A date.
elif isinstance(obj, datetime):
return pdfRepr(_datetime_to_pdf(obj))
# 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))) | Map Python objects to PDF syntax. |
171,297 | import codecs
from datetime import datetime
from enum import Enum
from functools import total_ordering
from io import BytesIO
import itertools
import logging
import math
import os
import string
import struct
import sys
import time
import types
import warnings
import zlib
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib import _api, _text_helpers, _type1font, cbook, dviread
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.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font)
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from . import _backend_pdf_ps
The provided code snippet includes necessary dependencies for implementing the `_font_supports_glyph` function. Write a Python function `def _font_supports_glyph(fonttype, glyph)` to solve the following problem:
Returns True if the font is able to provide codepoint *glyph* in a PDF. For a Type 3 font, this method returns True only for single-byte characters. For Type 42 fonts this method return True if the character is from the Basic Multilingual Plane.
Here is the function:
def _font_supports_glyph(fonttype, glyph):
"""
Returns True if the font is able to provide codepoint *glyph* in a PDF.
For a Type 3 font, this method returns True only for single-byte
characters. For Type 42 fonts this method return True if the character is
from the Basic Multilingual Plane.
"""
if fonttype == 3:
return glyph <= 255
if fonttype == 42:
return glyph <= 65535
raise NotImplementedError() | Returns True if the font is able to provide codepoint *glyph* in a PDF. For a Type 3 font, this method returns True only for single-byte characters. For Type 42 fonts this method return True if the character is from the Basic Multilingual Plane. |
171,298 | import codecs
from datetime import datetime
from enum import Enum
from functools import total_ordering
from io import BytesIO
import itertools
import logging
import math
import os
import string
import struct
import sys
import time
import types
import warnings
import zlib
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib import _api, _text_helpers, _type1font, cbook, dviread
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.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font)
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from . import _backend_pdf_ps
def get_font(font_filepaths, hinting_factor=None):
class Path:
def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
def _create_closed(cls, vertices):
def _update_values(self):
def vertices(self):
def vertices(self, vertices):
def codes(self):
def codes(self, codes):
def simplify_threshold(self):
def simplify_threshold(self, threshold):
def should_simplify(self):
def should_simplify(self, should_simplify):
def readonly(self):
def copy(self):
def __deepcopy__(self, memo=None):
def make_compound_path_from_polys(cls, XY):
def make_compound_path(cls, *args):
def __repr__(self):
def __len__(self):
def iter_segments(self, transform=None, remove_nans=True, clip=None,
snap=False, stroke_width=1.0, simplify=None,
curves=True, sketch=None):
def iter_bezier(self, **kwargs):
def cleaned(self, transform=None, remove_nans=False, clip=None,
*, simplify=False, curves=False,
stroke_width=1.0, snap=False, sketch=None):
def transformed(self, transform):
def contains_point(self, point, transform=None, radius=0.0):
def contains_points(self, points, transform=None, radius=0.0):
def contains_path(self, path, transform=None):
def get_extents(self, transform=None, **kwargs):
def intersects_path(self, other, filled=True):
def intersects_bbox(self, bbox, filled=True):
def interpolated(self, steps):
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
def unit_rectangle(cls):
def unit_regular_polygon(cls, numVertices):
def unit_regular_star(cls, numVertices, innerCircle=0.5):
def unit_regular_asterisk(cls, numVertices):
def unit_circle(cls):
def circle(cls, center=(0., 0.), radius=1., readonly=False):
def unit_circle_righthalf(cls):
def arc(cls, theta1, theta2, n=None, is_wedge=False):
def wedge(cls, theta1, theta2, n=None):
def hatch(hatchpattern, density=6):
def clip_to_bbox(self, bbox, inside=True):
def _get_pdf_charprocs(font_path, glyph_ids):
font = get_font(font_path, hinting_factor=1)
conv = 1000 / font.units_per_EM # Conversion to PS units (1/1000's).
procs = {}
for glyph_id in glyph_ids:
g = font.load_glyph(glyph_id, LOAD_NO_SCALE)
# NOTE: We should be using round(), but instead use
# "(x+.5).astype(int)" to keep backcompat with the old ttconv code
# (this is different for negative x's).
d1 = (np.array([g.horiAdvance, 0, *g.bbox]) * conv + .5).astype(int)
v, c = font.get_path()
v = (v * 64).astype(int) # Back to TrueType's internal units (1/64's).
# Backcompat with old ttconv code: control points between two quads are
# omitted if they are exactly at the midpoint between the control of
# the quad before and the quad after, but ttconv used to interpolate
# *after* conversion to PS units, causing floating point errors. Here
# we reproduce ttconv's logic, detecting these "implicit" points and
# re-interpolating them. Note that occasionally (e.g. with DejaVu Sans
# glyph "0") a point detected as "implicit" is actually explicit, and
# will thus be shifted by 1.
quads, = np.nonzero(c == 3)
quads_on = quads[1::2]
quads_mid_on = np.array(
sorted({*quads_on} & {*(quads - 1)} & {*(quads + 1)}), int)
implicit = quads_mid_on[
(v[quads_mid_on] # As above, use astype(int), not // division
== ((v[quads_mid_on - 1] + v[quads_mid_on + 1]) / 2).astype(int))
.all(axis=1)]
if (font.postscript_name, glyph_id) in [
("DejaVuSerif-Italic", 77), # j
("DejaVuSerif-Italic", 135), # \AA
]:
v[:, 0] -= 1 # Hard-coded backcompat (FreeType shifts glyph by 1).
v = (v * conv + .5).astype(int) # As above re: truncation vs rounding.
v[implicit] = (( # Fix implicit points; again, truncate.
(v[implicit - 1] + v[implicit + 1]) / 2).astype(int))
procs[font.get_glyph_name(glyph_id)] = (
" ".join(map(str, d1)).encode("ascii") + b" d1\n"
+ _path.convert_to_string(
Path(v, c), None, None, False, None, -1,
# no code for quad Beziers triggers auto-conversion to cubics.
[b"m", b"l", b"", b"c", b"h"], True)
+ b"f")
return procs | null |
171,299 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
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.05, 2.91),
'a9': (1.46, 2.05),
'a10': (1.02, 1.46),
'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):
for key, (pw, ph) in sorted(papersize.items(), reverse=True):
if key.startswith('l'):
continue
if w < pw and h < ph:
return key
return 'a0' | null |
171,300 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
def _nums_to_str(*args):
return " ".join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args) | null |
171,301 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
The provided code snippet includes necessary dependencies for implementing the `quote_ps_string` function. Write a Python function `def quote_ps_string(s)` to solve the following problem:
Quote dangerous characters of S for use in a PostScript string constant.
Here is the function:
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') | Quote dangerous characters of S for use in a PostScript string constant. |
171,302 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
def is_writable_file_like(obj):
"""Return whether *obj* looks like a file object with a *write* method."""
return callable(getattr(obj, 'write', None))
def file_requires_unicode(x):
"""
Return whether the given writable file-like object requires Unicode to be
written to it.
"""
try:
x.write(b'')
except TypeError:
return True
else:
return False
The provided code snippet includes necessary dependencies for implementing the `_move_path_to_path_or_stream` function. Write a Python function `def _move_path_to_path_or_stream(src, dst)` to solve the following problem:
Move the contents of file at *src* to path-or-filelike *dst*. If *dst* is a path, the metadata of *src* are *not* copied.
Here is the function:
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 = (open(src, 'r', encoding='latin-1')
if file_requires_unicode(dst)
else open(src, 'rb'))
with fh:
shutil.copyfileobj(fh, dst)
else:
shutil.move(src, dst, copy_function=shutil.copyfile) | Move the contents of file at *src* to path-or-filelike *dst*. If *dst* is a path, the metadata of *src* are *not* copied. |
171,303 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
def get_font(font_filepaths, hinting_factor=None):
"""
Get an `.ft2font.FT2Font` object given a list of file paths.
Parameters
----------
font_filepaths : Iterable[str, Path, bytes], str, Path, bytes
Relative or absolute paths to the font files to be used.
If a single string, bytes, or `pathlib.Path`, then it will be treated
as a list with that entry only.
If more than one filepath is passed, then the returned FT2Font object
will fall back through the fonts, in the order given, to find a needed
glyph.
Returns
-------
`.ft2font.FT2Font`
"""
if isinstance(font_filepaths, (str, Path, bytes)):
paths = (_cached_realpath(font_filepaths),)
else:
paths = tuple(_cached_realpath(fname) for fname in font_filepaths)
if hinting_factor is None:
hinting_factor = mpl.rcParams['text.hinting_factor']
return _get_font(
# must be a tuple to be cached
paths,
hinting_factor,
_kerning_factor=mpl.rcParams['text.kerning_factor'],
# also key on the thread ID to prevent segfaults with multi-threading
thread_id=threading.get_ident()
)
class Path:
"""
A series of possibly disconnected, possibly closed, line and curve
segments.
The underlying storage is made up of two parallel numpy arrays:
- *vertices*: an Nx2 float array of vertices
- *codes*: an N-length uint8 array of path codes, or None
These two arrays always have the same length in the first
dimension. For example, to represent a cubic curve, you must
provide three vertices and three ``CURVE4`` codes.
The code types are:
- ``STOP`` : 1 vertex (ignored)
A marker for the end of the entire path (currently not required and
ignored)
- ``MOVETO`` : 1 vertex
Pick up the pen and move to the given vertex.
- ``LINETO`` : 1 vertex
Draw a line from the current position to the given vertex.
- ``CURVE3`` : 1 control point, 1 endpoint
Draw a quadratic Bézier curve from the current position, with the given
control point, to the given end point.
- ``CURVE4`` : 2 control points, 1 endpoint
Draw a cubic Bézier curve from the current position, with the given
control points, to the given end point.
- ``CLOSEPOLY`` : 1 vertex (ignored)
Draw a line segment to the start point of the current polyline.
If *codes* is None, it is interpreted as a ``MOVETO`` followed by a series
of ``LINETO``.
Users of Path objects should not access the vertices and codes arrays
directly. Instead, they should use `iter_segments` or `cleaned` to get the
vertex/code pairs. This helps, in particular, to consistently handle the
case of *codes* being None.
Some behavior of Path objects can be controlled by rcParams. See the
rcParams whose keys start with 'path.'.
.. note::
The vertices and codes arrays should be treated as
immutable -- there are a number of optimizations and assumptions
made up front in the constructor that will not change when the
data changes.
"""
code_type = np.uint8
# Path codes
STOP = code_type(0) # 1 vertex
MOVETO = code_type(1) # 1 vertex
LINETO = code_type(2) # 1 vertex
CURVE3 = code_type(3) # 2 vertices
CURVE4 = code_type(4) # 3 vertices
CLOSEPOLY = code_type(79) # 1 vertex
#: A dictionary mapping Path codes to the number of vertices that the
#: code expects.
NUM_VERTICES_FOR_CODE = {STOP: 1,
MOVETO: 1,
LINETO: 1,
CURVE3: 2,
CURVE4: 3,
CLOSEPOLY: 1}
def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
"""
Create a new path with the given vertices and codes.
Parameters
----------
vertices : (N, 2) array-like
The path vertices, as an array, masked array or sequence of pairs.
Masked values, if any, 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`.
codes : array-like or None, optional
N-length array of integers representing the codes of the path.
If not None, codes must be the same length as vertices.
If None, *vertices* will be treated as a series of line segments.
_interpolation_steps : int, optional
Used as a hint to certain projections, such as Polar, that this
path should be linearly interpolated immediately before drawing.
This attribute is primarily an implementation detail and is not
intended for public use.
closed : bool, optional
If *codes* is None and closed is True, vertices will be treated as
line segments of a closed polygon. Note that the last vertex will
then be ignored (as the corresponding code will be set to
CLOSEPOLY).
readonly : bool, optional
Makes the path behave in an immutable way and sets the vertices
and codes as read-only arrays.
"""
vertices = _to_unmasked_float_array(vertices)
_api.check_shape((None, 2), vertices=vertices)
if codes is not None:
codes = np.asarray(codes, self.code_type)
if codes.ndim != 1 or len(codes) != len(vertices):
raise ValueError("'codes' must be a 1D list or array with the "
"same length of 'vertices'. "
f"Your vertices have shape {vertices.shape} "
f"but your codes have shape {codes.shape}")
if len(codes) and codes[0] != self.MOVETO:
raise ValueError("The first element of 'code' must be equal "
f"to 'MOVETO' ({self.MOVETO}). "
f"Your first code is {codes[0]}")
elif closed and len(vertices):
codes = np.empty(len(vertices), dtype=self.code_type)
codes[0] = self.MOVETO
codes[1:-1] = self.LINETO
codes[-1] = self.CLOSEPOLY
self._vertices = vertices
self._codes = codes
self._interpolation_steps = _interpolation_steps
self._update_values()
if readonly:
self._vertices.flags.writeable = False
if self._codes is not None:
self._codes.flags.writeable = False
self._readonly = True
else:
self._readonly = False
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
"""
Create a Path instance without the expense of calling the constructor.
Parameters
----------
verts : numpy array
codes : numpy array
internals_from : Path or None
If not None, another `Path` from which the attributes
``should_simplify``, ``simplify_threshold``, and
``interpolation_steps`` will be copied. Note that ``readonly`` is
never copied, and always set to ``False`` by this constructor.
"""
pth = cls.__new__(cls)
pth._vertices = _to_unmasked_float_array(verts)
pth._codes = codes
pth._readonly = False
if internals_from is not None:
pth._should_simplify = internals_from._should_simplify
pth._simplify_threshold = internals_from._simplify_threshold
pth._interpolation_steps = internals_from._interpolation_steps
else:
pth._should_simplify = True
pth._simplify_threshold = mpl.rcParams['path.simplify_threshold']
pth._interpolation_steps = 1
return pth
def _create_closed(cls, vertices):
"""
Create a closed polygonal path going through *vertices*.
Unlike ``Path(..., closed=True)``, *vertices* should **not** end with
an entry for the CLOSEPATH; this entry is added by `._create_closed`.
"""
v = _to_unmasked_float_array(vertices)
return cls(np.concatenate([v, v[:1]]), closed=True)
def _update_values(self):
self._simplify_threshold = mpl.rcParams['path.simplify_threshold']
self._should_simplify = (
self._simplify_threshold > 0 and
mpl.rcParams['path.simplify'] and
len(self._vertices) >= 128 and
(self._codes is None or np.all(self._codes <= Path.LINETO))
)
def vertices(self):
"""
The list of vertices in the `Path` as an Nx2 numpy array.
"""
return self._vertices
def vertices(self, vertices):
if self._readonly:
raise AttributeError("Can't set vertices on a readonly Path")
self._vertices = vertices
self._update_values()
def codes(self):
"""
The list of codes in the `Path` as a 1D numpy array. Each
code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4`
or `CLOSEPOLY`. For codes that correspond to more than one
vertex (`CURVE3` and `CURVE4`), that code will be repeated so
that the length of `vertices` and `codes` is always
the same.
"""
return self._codes
def codes(self, codes):
if self._readonly:
raise AttributeError("Can't set codes on a readonly Path")
self._codes = codes
self._update_values()
def simplify_threshold(self):
"""
The fraction of a pixel difference below which vertices will
be simplified out.
"""
return self._simplify_threshold
def simplify_threshold(self, threshold):
self._simplify_threshold = threshold
def should_simplify(self):
"""
`True` if the vertices array should be simplified.
"""
return self._should_simplify
def should_simplify(self, should_simplify):
self._should_simplify = should_simplify
def readonly(self):
"""
`True` if the `Path` is read-only.
"""
return self._readonly
def copy(self):
"""
Return a shallow copy of the `Path`, which will share the
vertices and codes with the source `Path`.
"""
return copy.copy(self)
def __deepcopy__(self, memo=None):
"""
Return a deepcopy of the `Path`. The `Path` will not be
readonly, even if the source `Path` is.
"""
# Deepcopying arrays (vertices, codes) strips the writeable=False flag.
p = copy.deepcopy(super(), memo)
p._readonly = False
return p
deepcopy = __deepcopy__
def make_compound_path_from_polys(cls, XY):
"""
Make a compound `Path` object to draw a number of polygons with equal
numbers of sides.
.. plot:: gallery/misc/histogram_path.py
Parameters
----------
XY : (numpolys, numsides, 2) array
"""
# for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
# the CLOSEPOLY; the vert for the closepoly is ignored but we still
# need it to keep the codes aligned with the vertices
numpolys, numsides, two = XY.shape
if two != 2:
raise ValueError("The third dimension of 'XY' must be 2")
stride = numsides + 1
nverts = numpolys * stride
verts = np.zeros((nverts, 2))
codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
codes[0::stride] = cls.MOVETO
codes[numsides::stride] = cls.CLOSEPOLY
for i in range(numsides):
verts[i::stride] = XY[:, i]
return cls(verts, codes)
def make_compound_path(cls, *args):
"""
Make a compound path from a list of `Path` objects. Blindly removes
all `Path.STOP` control points.
"""
# Handle an empty list in args (i.e. no args).
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0
for path in args:
if path.codes is None:
codes[i] = cls.MOVETO
codes[i + 1:i + len(path.vertices)] = cls.LINETO
else:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
# remove STOP's, since internal STOPs are a bug
not_stop_mask = codes != cls.STOP
vertices = vertices[not_stop_mask, :]
codes = codes[not_stop_mask]
return cls(vertices, codes)
def __repr__(self):
return "Path(%r, %r)" % (self.vertices, self.codes)
def __len__(self):
return len(self.vertices)
def iter_segments(self, transform=None, remove_nans=True, clip=None,
snap=False, stroke_width=1.0, simplify=None,
curves=True, sketch=None):
"""
Iterate over all curve segments in the path.
Each iteration returns a pair ``(vertices, code)``, where ``vertices``
is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
Additionally, this method can provide a number of standard cleanups and
conversions to the path.
Parameters
----------
transform : None or :class:`~matplotlib.transforms.Transform`
If not None, the given affine transformation will be applied to the
path.
remove_nans : bool, optional
Whether to remove all NaNs from the path and skip over them using
MOVETO commands.
clip : None or (float, float, float, float), optional
If not None, must be a four-tuple (x1, y1, x2, y2)
defining a rectangle in which to clip the path.
snap : None or bool, optional
If True, snap all nodes to pixels; if False, don't snap them.
If None, snap if the path contains only segments
parallel to the x or y axes, and no more than 1024 of them.
stroke_width : float, optional
The width of the stroke being drawn (used for path snapping).
simplify : None or bool, optional
Whether to simplify the path by removing vertices
that do not affect its appearance. If None, use the
:attr:`should_simplify` attribute. See also :rc:`path.simplify`
and :rc:`path.simplify_threshold`.
curves : bool, optional
If True, curve segments will be returned as curve segments.
If False, all curves will be converted to line segments.
sketch : None or sequence, optional
If not None, must be a 3-tuple of the form
(scale, length, randomness), representing the sketch parameters.
"""
if not len(self):
return
cleaned = self.cleaned(transform=transform,
remove_nans=remove_nans, clip=clip,
snap=snap, stroke_width=stroke_width,
simplify=simplify, curves=curves,
sketch=sketch)
# Cache these object lookups for performance in the loop.
NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
STOP = self.STOP
vertices = iter(cleaned.vertices)
codes = iter(cleaned.codes)
for curr_vertices, code in zip(vertices, codes):
if code == STOP:
break
extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
if extra_vertices:
for i in range(extra_vertices):
next(codes)
curr_vertices = np.append(curr_vertices, next(vertices))
yield curr_vertices, code
def iter_bezier(self, **kwargs):
"""
Iterate over each Bézier curve (lines included) in a Path.
Parameters
----------
**kwargs
Forwarded to `.iter_segments`.
Yields
------
B : matplotlib.bezier.BezierSegment
The Bézier curves that make up the current path. Note in particular
that freestanding points are Bézier curves of order 0, and lines
are Bézier curves of order 1 (with two control points).
code : Path.code_type
The code describing what kind of curve is being returned.
Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE4 correspond to
Bézier curves with 1, 2, 3, and 4 control points (respectively).
Path.CLOSEPOLY is a Path.LINETO with the control points correctly
chosen based on the start/end points of the current stroke.
"""
first_vert = None
prev_vert = None
for verts, code in self.iter_segments(**kwargs):
if first_vert is None:
if code != Path.MOVETO:
raise ValueError("Malformed path, must start with MOVETO.")
if code == Path.MOVETO: # a point is like "CURVE1"
first_vert = verts
yield BezierSegment(np.array([first_vert])), code
elif code == Path.LINETO: # "CURVE2"
yield BezierSegment(np.array([prev_vert, verts])), code
elif code == Path.CURVE3:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:]])), code
elif code == Path.CURVE4:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:4], verts[4:]])), code
elif code == Path.CLOSEPOLY:
yield BezierSegment(np.array([prev_vert, first_vert])), code
elif code == Path.STOP:
return
else:
raise ValueError(f"Invalid Path.code_type: {code}")
prev_vert = verts[-2:]
def cleaned(self, transform=None, remove_nans=False, clip=None,
*, simplify=False, curves=False,
stroke_width=1.0, snap=False, sketch=None):
"""
Return a new Path with vertices and codes cleaned according to the
parameters.
See Also
--------
Path.iter_segments : for details of the keyword arguments.
"""
vertices, codes = _path.cleanup_path(
self, transform, remove_nans, clip, snap, stroke_width, simplify,
curves, sketch)
pth = Path._fast_from_codes_and_verts(vertices, codes, self)
if not simplify:
pth._should_simplify = False
return pth
def transformed(self, transform):
"""
Return a transformed copy of the path.
See Also
--------
matplotlib.transforms.TransformedPath
A specialized path class that will cache the transformed result and
automatically update when the transform changes.
"""
return Path(transform.transform(self.vertices), self.codes,
self._interpolation_steps)
def contains_point(self, point, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given point.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
point : (float, float)
The point (x, y) to check.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *point* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *point*.
radius : float, default: 0
Additional margin on the path in coordinates of *point*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
bool
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
# `point_in_path` does not handle nonlinear transforms, so we
# transform the path ourselves. If *transform* is affine, letting
# `point_in_path` handle the transform avoids allocating an extra
# buffer.
if transform and not transform.is_affine:
self = transform.transform_path(self)
transform = None
return _path.point_in_path(point[0], point[1], radius, self, transform)
def contains_points(self, points, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given points.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
points : (N, 2) array
The points to check. Columns contain x and y values.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *points* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *points*.
radius : float, default: 0
Additional margin on the path in coordinates of *points*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
length-N bool array
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
result = _path.points_in_path(points, radius, self, transform)
return result.astype('bool')
def contains_path(self, path, transform=None):
"""
Return whether this (closed) path completely contains the given path.
If *transform* is not ``None``, the path will be transformed before
checking for containment.
"""
if transform is not None:
transform = transform.frozen()
return _path.path_in_path(self, None, path, transform)
def get_extents(self, transform=None, **kwargs):
"""
Get Bbox of the path.
Parameters
----------
transform : matplotlib.transforms.Transform, optional
Transform to apply to path before computing extents, if any.
**kwargs
Forwarded to `.iter_bezier`.
Returns
-------
matplotlib.transforms.Bbox
The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
"""
from .transforms import Bbox
if transform is not None:
self = transform.transform_path(self)
if self.codes is None:
xys = self.vertices
elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
# Optimization for the straight line case.
# Instead of iterating through each curve, consider
# each line segment's end-points
# (recall that STOP and CLOSEPOLY vertices are ignored)
xys = self.vertices[np.isin(self.codes,
[Path.MOVETO, Path.LINETO])]
else:
xys = []
for curve, code in self.iter_bezier(**kwargs):
# places where the derivative is zero can be extrema
_, dzeros = curve.axis_aligned_extrema()
# as can the ends of the curve
xys.append(curve([0, *dzeros, 1]))
xys = np.concatenate(xys)
if len(xys):
return Bbox([xys.min(axis=0), xys.max(axis=0)])
else:
return Bbox.null()
def intersects_path(self, other, filled=True):
"""
Return whether if this path intersects another given path.
If *filled* is True, then this also returns True if one path completely
encloses the other (i.e., the paths are treated as filled).
"""
return _path.path_intersects_path(self, other, filled)
def intersects_bbox(self, bbox, filled=True):
"""
Return whether this path intersects a given `~.transforms.Bbox`.
If *filled* is True, then this also returns True if the path completely
encloses the `.Bbox` (i.e., the path is treated as filled).
The bounding box is always considered filled.
"""
return _path.path_intersects_rectangle(
self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
def interpolated(self, steps):
"""
Return a new path resampled to length N x steps.
Codes other than LINETO are not handled correctly.
"""
if steps == 1:
return self
vertices = simple_linear_interpolation(self.vertices, steps)
codes = self.codes
if codes is not None:
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
dtype=self.code_type)
new_codes[0::steps] = codes
else:
new_codes = None
return Path(vertices, new_codes)
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
"""
Convert this path to a list of polygons or polylines. Each
polygon/polyline 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 Bézier curves.
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.
If *closed_only* is `True` (default), only closed polygons,
with the last point being the same as the first point, will be
returned. Any unclosed polylines in the path will be
explicitly closed. If *closed_only* is `False`, any unclosed
polygons in the path will be returned as unclosed polygons,
and the closed polygons will be returned explicitly closed by
setting the last point to the same as the first point.
"""
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):
vertices = self.vertices
if closed_only:
if len(vertices) < 3:
return []
elif np.any(vertices[0] != vertices[-1]):
vertices = [*vertices, vertices[0]]
if transform is None:
return [vertices]
else:
return [transform.transform(vertices)]
# Deal with the case where there are curves and/or multiple
# subpaths (using extension code)
return _path.convert_path_to_polygons(
self, transform, width, height, closed_only)
_unit_rectangle = None
def unit_rectangle(cls):
"""
Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
"""
if cls._unit_rectangle is None:
cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
closed=True, readonly=True)
return cls._unit_rectangle
_unit_regular_polygons = WeakValueDictionary()
def unit_regular_polygon(cls, numVertices):
"""
Return a :class:`Path` instance for a unit regular polygon with the
given *numVertices* such that the circumscribing circle has radius 1.0,
centered at (0, 0).
"""
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)
# This initial rotation is to make sure the polygon always
# "points-up".
+ np.pi / 2)
verts = np.column_stack((np.cos(theta), np.sin(theta)))
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_polygons[numVertices] = path
return path
_unit_regular_stars = WeakValueDictionary()
def unit_regular_star(cls, numVertices, innerCircle=0.5):
"""
Return a :class:`Path` for a unit regular star with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
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))
# This initial rotation is to make sure the polygon always
# "points-up"
theta += np.pi / 2.0
r = np.ones(ns2 + 1)
r[1::2] = innerCircle
verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_stars[(numVertices, innerCircle)] = path
return path
def unit_regular_asterisk(cls, numVertices):
"""
Return a :class:`Path` for a unit regular asterisk with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
return cls.unit_regular_star(numVertices, 0.0)
_unit_circle = None
def unit_circle(cls):
"""
Return the readonly :class:`Path` of the unit circle.
For most cases, :func:`Path.circle` will be what you want.
"""
if cls._unit_circle is None:
cls._unit_circle = cls.circle(center=(0, 0), radius=1,
readonly=True)
return cls._unit_circle
def circle(cls, center=(0., 0.), radius=1., readonly=False):
"""
Return a `Path` representing a circle of a given radius and center.
Parameters
----------
center : (float, float), default: (0, 0)
The center of the circle.
radius : float, default: 1
The radius of the circle.
readonly : bool
Whether the created path should have the "readonly" argument
set when creating the Path instance.
Notes
-----
The circle is approximated using 8 cubic Bézier curves, as described in
Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
Bezier Cubic Splines <https://www.tinaja.com/glib/ellipse4.pdf>`_.
"""
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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]],
dtype=float)
codes = [cls.CURVE4] * 26
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
return Path(vertices * radius + center, codes, readonly=readonly)
_unit_circle_righthalf = None
def unit_circle_righthalf(cls):
"""
Return a `Path` of the right half of a unit circle.
See `Path.circle` for the reference on the approximation used.
"""
if cls._unit_circle_righthalf is None:
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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],
[0.0, -1.0]],
float)
codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
return cls._unit_circle_righthalf
def arc(cls, theta1, theta2, n=None, is_wedge=False):
"""
Return a `Path` for the unit circle arc from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest arc within 360 degrees.
That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
*theta2* - 360 and not a full circle plus some extra overlap.
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
<https://web.archive.org/web/20190318044212/http://www.spaceroots.org/documents/ellipse/index.html>`_.
"""
halfpi = np.pi * 0.5
eta1 = theta1
eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
# Ensure 2pi range is not flattened to 0 due to floating-point errors,
# but don't try to expand existing 0 range.
if theta2 != theta1 and eta2 <= eta1:
eta2 += 360
eta1, eta2 = np.deg2rad([eta1, eta2])
# number of curve segments to make
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), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[1] = [xA[0], yA[0]]
codes[0:2] = [cls.MOVETO, cls.LINETO]
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
vertex_offset = 2
end = length - 2
else:
length = n * 3 + 1
vertices = np.empty((length, 2), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[0] = [xA[0], yA[0]]
codes[0] = cls.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 cls(vertices, codes, readonly=True)
def wedge(cls, theta1, theta2, n=None):
"""
Return a `Path` for the unit circle wedge from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest wedge within 360 degrees.
That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
to *theta2* - 360 and not a full circle plus some extra overlap.
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*.
See `Path.arc` for the reference on the approximation used.
"""
return cls.arc(theta1, theta2, n, True)
def hatch(hatchpattern, density=6):
"""
Given a hatch specifier, *hatchpattern*, generates a Path that
can be used in a repeated hatching pattern. *density* is the
number of lines per unit square.
"""
from matplotlib.hatch import get_path
return (get_path(hatchpattern, density)
if hatchpattern is not None else None)
def clip_to_bbox(self, bbox, inside=True):
"""
Clip the path to the given bounding box.
The path must be made up of one or more closed polygons. This
algorithm will not behave correctly for unclosed paths.
If *inside* is `True`, clip to the inside of the box, otherwise
to the outside of the box.
"""
verts = _path.clip_path_to_rect(self, bbox, inside)
paths = [Path(poly) for poly in verts]
return self.make_compound_path(*paths)
The provided code snippet includes necessary dependencies for implementing the `_font_to_ps_type3` function. Write a Python function `def _font_to_ps_type3(font_path, chars)` to solve the following problem:
Subset *chars* from the font at *font_path* into a Type 3 font. Parameters ---------- font_path : path-like Path to the font to be subsetted. chars : str The characters to include in the subsetted font. Returns ------- str The string representation of a Type 3 font, which can be included verbatim into a PostScript file.
Here is the function:
def _font_to_ps_type3(font_path, chars):
"""
Subset *chars* from the font at *font_path* into a Type 3 font.
Parameters
----------
font_path : path-like
Path to the font to be subsetted.
chars : str
The characters to include in the subsetted font.
Returns
-------
str
The string representation of a Type 3 font, which can be included
verbatim into a PostScript file.
"""
font = get_font(font_path, hinting_factor=1)
glyph_ids = [font.get_char_index(c) for c in chars]
preamble = """\
%!PS-Adobe-3.0 Resource-Font
%%Creator: Converted from TrueType to Type 3 by Matplotlib.
10 dict begin
/FontName /{font_name} def
/PaintType 0 def
/FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
/FontBBox [{bbox}] def
/FontType 3 def
/Encoding [{encoding}] def
/CharStrings {num_glyphs} dict dup begin
/.notdef 0 def
""".format(font_name=font.postscript_name,
inv_units_per_em=1 / font.units_per_EM,
bbox=" ".join(map(str, font.bbox)),
encoding=" ".join("/{}".format(font.get_glyph_name(glyph_id))
for glyph_id in glyph_ids),
num_glyphs=len(glyph_ids) + 1)
postamble = """
end readonly def
/BuildGlyph {
exch begin
CharStrings exch
2 copy known not {pop /.notdef} if
true 3 1 roll get exec
end
} _d
/BuildChar {
1 index /Encoding get exch get
1 index /BuildGlyph get exec
} _d
FontName currentdict end definefont pop
"""
entries = []
for glyph_id in glyph_ids:
g = font.load_glyph(glyph_id, LOAD_NO_SCALE)
v, c = font.get_path()
entries.append(
"/%(name)s{%(bbox)s sc\n" % {
"name": font.get_glyph_name(glyph_id),
"bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),
}
+ _path.convert_to_string(
# Convert back to TrueType's internal units (1/64's).
# (Other dimensions are already in these units.)
Path(v * 64, c), None, None, False, None, 0,
# No code for quad Beziers triggers auto-conversion to cubics.
# Drop intermediate closepolys (relying on the outline
# decomposer always explicitly moving to the closing point
# first).
[b"m", b"l", b"", b"c", b""], True).decode("ascii")
+ "ce} _d"
)
return preamble + "\n".join(entries) + postamble | Subset *chars* from the font at *font_path* into a Type 3 font. Parameters ---------- font_path : path-like Path to the font to be subsetted. chars : str The characters to include in the subsetted font. Returns ------- str The string representation of a Type 3 font, which can be included verbatim into a PostScript file. |
171,304 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
_log = logging.getLogger(__name__)
class TemporaryDirectory(Generic[AnyStr]):
name: str
def __init__(
self, suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ...
) -> None: ...
def cleanup(self) -> None: ...
def __enter__(self) -> AnyStr: ...
def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]
) -> None: ...
if sys.version_info >= (3, 9):
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
The provided code snippet includes necessary dependencies for implementing the `_font_to_ps_type42` function. Write a Python function `def _font_to_ps_type42(font_path, chars, fh)` to solve the following problem:
Subset *chars* from the font at *font_path* into a Type 42 font at *fh*. Parameters ---------- font_path : path-like Path to the font to be subsetted. chars : str The characters to include in the subsetted font. fh : file-like Where to write the font.
Here is the function:
def _font_to_ps_type42(font_path, chars, fh):
"""
Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.
Parameters
----------
font_path : path-like
Path to the font to be subsetted.
chars : str
The characters to include in the subsetted font.
fh : file-like
Where to write the font.
"""
subset_str = ''.join(chr(c) for c in chars)
_log.debug("SUBSET %s characters: %s", font_path, subset_str)
try:
fontdata = _backend_pdf_ps.get_glyphs_subset(font_path, subset_str)
_log.debug("SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size,
fontdata.getbuffer().nbytes)
# Give ttconv a subsetted font along with updated glyph_ids.
font = FT2Font(fontdata)
glyph_ids = [font.get_char_index(c) for c in chars]
with TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, "tmp.ttf")
with open(tmpfile, 'wb') as tmp:
tmp.write(fontdata.getvalue())
# TODO: allow convert_ttf_to_ps to input file objects (BytesIO)
convert_ttf_to_ps(os.fsencode(tmpfile), fh, 42, glyph_ids)
except RuntimeError:
_log.warning(
"The PostScript backend does not currently "
"support the selected font.")
raise | Subset *chars* from the font at *font_path* into a Type 42 font at *fh*. Parameters ---------- font_path : path-like Path to the font to be subsetted. chars : str The characters to include in the subsetted font. fh : file-like Where to write the font. |
171,305 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
debugPS = False
The provided code snippet includes necessary dependencies for implementing the `_log_if_debug_on` function. Write a Python function `def _log_if_debug_on(meth)` to solve the following problem:
Wrap `RendererPS` method *meth* to emit a PS comment with the method name, if the global flag `debugPS` is set.
Here is the function:
def _log_if_debug_on(meth):
"""
Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
if the global flag `debugPS` is set.
"""
@functools.wraps(meth)
def wrapper(self, *args, **kwargs):
if debugPS:
self._pswriter.write(f"% {meth.__name__}\n")
return meth(self, *args, **kwargs)
return wrapper | Wrap `RendererPS` method *meth* to emit a PS comment with the method name, if the global flag `debugPS` is set. |
171,306 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):
class Path:
def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
def _create_closed(cls, vertices):
def _update_values(self):
def vertices(self):
def vertices(self, vertices):
def codes(self):
def codes(self, codes):
def simplify_threshold(self):
def simplify_threshold(self, threshold):
def should_simplify(self):
def should_simplify(self, should_simplify):
def readonly(self):
def copy(self):
def __deepcopy__(self, memo=None):
def make_compound_path_from_polys(cls, XY):
def make_compound_path(cls, *args):
def __repr__(self):
def __len__(self):
def iter_segments(self, transform=None, remove_nans=True, clip=None,
snap=False, stroke_width=1.0, simplify=None,
curves=True, sketch=None):
def iter_bezier(self, **kwargs):
def cleaned(self, transform=None, remove_nans=False, clip=None,
*, simplify=False, curves=False,
stroke_width=1.0, snap=False, sketch=None):
def transformed(self, transform):
def contains_point(self, point, transform=None, radius=0.0):
def contains_points(self, points, transform=None, radius=0.0):
def contains_path(self, path, transform=None):
def get_extents(self, transform=None, **kwargs):
def intersects_path(self, other, filled=True):
def intersects_bbox(self, bbox, filled=True):
def interpolated(self, steps):
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
def unit_rectangle(cls):
def unit_regular_polygon(cls, numVertices):
def unit_regular_star(cls, numVertices, innerCircle=0.5):
def unit_regular_asterisk(cls, numVertices):
def unit_circle(cls):
def circle(cls, center=(0., 0.), radius=1., readonly=False):
def unit_circle_righthalf(cls):
def arc(cls, theta1, theta2, n=None, is_wedge=False):
def wedge(cls, theta1, theta2, n=None):
def hatch(hatchpattern, density=6):
def clip_to_bbox(self, bbox, inside=True):
def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble,
paper_width, paper_height, orientation):
return _convert_psfrags(
pathlib.Path(tmpfile), psfrags, paper_width, paper_height, orientation) | null |
171,307 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
_log = logging.getLogger(__name__)
def _try_distill(func, tmppath, *args, **kwargs):
try:
func(str(tmppath), *args, **kwargs)
except mpl.ExecutableNotFoundError as exc:
_log.warning("%s. Distillation step skipped.", exc) | null |
171,308 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
_log = logging.getLogger(__name__)
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 open(epsfile, 'wb') as epsh, 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)
The provided code snippet includes necessary dependencies for implementing the `gs_distill` function. Write a Python function `def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False)` to solve the following problem:
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.
Here is the function:
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 = mpl.rcParams['ps.distiller.res']
cbook._check_and_log_subprocess(
[mpl._get_executable_info("gs").executable,
"-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
paper_option, "-sOutputFile=%s" % psfile, tmpfile],
_log)
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 a ps file where the
# original bbox is no more correct. Do not adjust bbox for now.
pstoeps(tmpfile, bbox, rotated=rotated) | 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. |
171,309 | import codecs
import datetime
from enum import Enum
import functools
from io import StringIO
import itertools
import logging
import os
import pathlib
import re
import shutil
from tempfile import TemporaryDirectory
import time
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _path, _text_helpers
from matplotlib._afm import AFM
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
from matplotlib.font_manager import get_font
from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
from matplotlib._ttconv import convert_ttf_to_ps
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.texmanager import TexManager
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
_log = logging.getLogger(__name__)
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 open(epsfile, 'wb') as epsh, 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 TemporaryDirectory(Generic[AnyStr]):
name: str
def __init__(
self, suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ...
) -> None: ...
def cleanup(self) -> None: ...
def __enter__(self) -> AnyStr: ...
def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]
) -> None: ...
if sys.version_info >= (3, 9):
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
class Path:
"""
A series of possibly disconnected, possibly closed, line and curve
segments.
The underlying storage is made up of two parallel numpy arrays:
- *vertices*: an Nx2 float array of vertices
- *codes*: an N-length uint8 array of path codes, or None
These two arrays always have the same length in the first
dimension. For example, to represent a cubic curve, you must
provide three vertices and three ``CURVE4`` codes.
The code types are:
- ``STOP`` : 1 vertex (ignored)
A marker for the end of the entire path (currently not required and
ignored)
- ``MOVETO`` : 1 vertex
Pick up the pen and move to the given vertex.
- ``LINETO`` : 1 vertex
Draw a line from the current position to the given vertex.
- ``CURVE3`` : 1 control point, 1 endpoint
Draw a quadratic Bézier curve from the current position, with the given
control point, to the given end point.
- ``CURVE4`` : 2 control points, 1 endpoint
Draw a cubic Bézier curve from the current position, with the given
control points, to the given end point.
- ``CLOSEPOLY`` : 1 vertex (ignored)
Draw a line segment to the start point of the current polyline.
If *codes* is None, it is interpreted as a ``MOVETO`` followed by a series
of ``LINETO``.
Users of Path objects should not access the vertices and codes arrays
directly. Instead, they should use `iter_segments` or `cleaned` to get the
vertex/code pairs. This helps, in particular, to consistently handle the
case of *codes* being None.
Some behavior of Path objects can be controlled by rcParams. See the
rcParams whose keys start with 'path.'.
.. note::
The vertices and codes arrays should be treated as
immutable -- there are a number of optimizations and assumptions
made up front in the constructor that will not change when the
data changes.
"""
code_type = np.uint8
# Path codes
STOP = code_type(0) # 1 vertex
MOVETO = code_type(1) # 1 vertex
LINETO = code_type(2) # 1 vertex
CURVE3 = code_type(3) # 2 vertices
CURVE4 = code_type(4) # 3 vertices
CLOSEPOLY = code_type(79) # 1 vertex
#: A dictionary mapping Path codes to the number of vertices that the
#: code expects.
NUM_VERTICES_FOR_CODE = {STOP: 1,
MOVETO: 1,
LINETO: 1,
CURVE3: 2,
CURVE4: 3,
CLOSEPOLY: 1}
def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
"""
Create a new path with the given vertices and codes.
Parameters
----------
vertices : (N, 2) array-like
The path vertices, as an array, masked array or sequence of pairs.
Masked values, if any, 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`.
codes : array-like or None, optional
N-length array of integers representing the codes of the path.
If not None, codes must be the same length as vertices.
If None, *vertices* will be treated as a series of line segments.
_interpolation_steps : int, optional
Used as a hint to certain projections, such as Polar, that this
path should be linearly interpolated immediately before drawing.
This attribute is primarily an implementation detail and is not
intended for public use.
closed : bool, optional
If *codes* is None and closed is True, vertices will be treated as
line segments of a closed polygon. Note that the last vertex will
then be ignored (as the corresponding code will be set to
CLOSEPOLY).
readonly : bool, optional
Makes the path behave in an immutable way and sets the vertices
and codes as read-only arrays.
"""
vertices = _to_unmasked_float_array(vertices)
_api.check_shape((None, 2), vertices=vertices)
if codes is not None:
codes = np.asarray(codes, self.code_type)
if codes.ndim != 1 or len(codes) != len(vertices):
raise ValueError("'codes' must be a 1D list or array with the "
"same length of 'vertices'. "
f"Your vertices have shape {vertices.shape} "
f"but your codes have shape {codes.shape}")
if len(codes) and codes[0] != self.MOVETO:
raise ValueError("The first element of 'code' must be equal "
f"to 'MOVETO' ({self.MOVETO}). "
f"Your first code is {codes[0]}")
elif closed and len(vertices):
codes = np.empty(len(vertices), dtype=self.code_type)
codes[0] = self.MOVETO
codes[1:-1] = self.LINETO
codes[-1] = self.CLOSEPOLY
self._vertices = vertices
self._codes = codes
self._interpolation_steps = _interpolation_steps
self._update_values()
if readonly:
self._vertices.flags.writeable = False
if self._codes is not None:
self._codes.flags.writeable = False
self._readonly = True
else:
self._readonly = False
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
"""
Create a Path instance without the expense of calling the constructor.
Parameters
----------
verts : numpy array
codes : numpy array
internals_from : Path or None
If not None, another `Path` from which the attributes
``should_simplify``, ``simplify_threshold``, and
``interpolation_steps`` will be copied. Note that ``readonly`` is
never copied, and always set to ``False`` by this constructor.
"""
pth = cls.__new__(cls)
pth._vertices = _to_unmasked_float_array(verts)
pth._codes = codes
pth._readonly = False
if internals_from is not None:
pth._should_simplify = internals_from._should_simplify
pth._simplify_threshold = internals_from._simplify_threshold
pth._interpolation_steps = internals_from._interpolation_steps
else:
pth._should_simplify = True
pth._simplify_threshold = mpl.rcParams['path.simplify_threshold']
pth._interpolation_steps = 1
return pth
def _create_closed(cls, vertices):
"""
Create a closed polygonal path going through *vertices*.
Unlike ``Path(..., closed=True)``, *vertices* should **not** end with
an entry for the CLOSEPATH; this entry is added by `._create_closed`.
"""
v = _to_unmasked_float_array(vertices)
return cls(np.concatenate([v, v[:1]]), closed=True)
def _update_values(self):
self._simplify_threshold = mpl.rcParams['path.simplify_threshold']
self._should_simplify = (
self._simplify_threshold > 0 and
mpl.rcParams['path.simplify'] and
len(self._vertices) >= 128 and
(self._codes is None or np.all(self._codes <= Path.LINETO))
)
def vertices(self):
"""
The list of vertices in the `Path` as an Nx2 numpy array.
"""
return self._vertices
def vertices(self, vertices):
if self._readonly:
raise AttributeError("Can't set vertices on a readonly Path")
self._vertices = vertices
self._update_values()
def codes(self):
"""
The list of codes in the `Path` as a 1D numpy array. Each
code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4`
or `CLOSEPOLY`. For codes that correspond to more than one
vertex (`CURVE3` and `CURVE4`), that code will be repeated so
that the length of `vertices` and `codes` is always
the same.
"""
return self._codes
def codes(self, codes):
if self._readonly:
raise AttributeError("Can't set codes on a readonly Path")
self._codes = codes
self._update_values()
def simplify_threshold(self):
"""
The fraction of a pixel difference below which vertices will
be simplified out.
"""
return self._simplify_threshold
def simplify_threshold(self, threshold):
self._simplify_threshold = threshold
def should_simplify(self):
"""
`True` if the vertices array should be simplified.
"""
return self._should_simplify
def should_simplify(self, should_simplify):
self._should_simplify = should_simplify
def readonly(self):
"""
`True` if the `Path` is read-only.
"""
return self._readonly
def copy(self):
"""
Return a shallow copy of the `Path`, which will share the
vertices and codes with the source `Path`.
"""
return copy.copy(self)
def __deepcopy__(self, memo=None):
"""
Return a deepcopy of the `Path`. The `Path` will not be
readonly, even if the source `Path` is.
"""
# Deepcopying arrays (vertices, codes) strips the writeable=False flag.
p = copy.deepcopy(super(), memo)
p._readonly = False
return p
deepcopy = __deepcopy__
def make_compound_path_from_polys(cls, XY):
"""
Make a compound `Path` object to draw a number of polygons with equal
numbers of sides.
.. plot:: gallery/misc/histogram_path.py
Parameters
----------
XY : (numpolys, numsides, 2) array
"""
# for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
# the CLOSEPOLY; the vert for the closepoly is ignored but we still
# need it to keep the codes aligned with the vertices
numpolys, numsides, two = XY.shape
if two != 2:
raise ValueError("The third dimension of 'XY' must be 2")
stride = numsides + 1
nverts = numpolys * stride
verts = np.zeros((nverts, 2))
codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
codes[0::stride] = cls.MOVETO
codes[numsides::stride] = cls.CLOSEPOLY
for i in range(numsides):
verts[i::stride] = XY[:, i]
return cls(verts, codes)
def make_compound_path(cls, *args):
"""
Make a compound path from a list of `Path` objects. Blindly removes
all `Path.STOP` control points.
"""
# Handle an empty list in args (i.e. no args).
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0
for path in args:
if path.codes is None:
codes[i] = cls.MOVETO
codes[i + 1:i + len(path.vertices)] = cls.LINETO
else:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
# remove STOP's, since internal STOPs are a bug
not_stop_mask = codes != cls.STOP
vertices = vertices[not_stop_mask, :]
codes = codes[not_stop_mask]
return cls(vertices, codes)
def __repr__(self):
return "Path(%r, %r)" % (self.vertices, self.codes)
def __len__(self):
return len(self.vertices)
def iter_segments(self, transform=None, remove_nans=True, clip=None,
snap=False, stroke_width=1.0, simplify=None,
curves=True, sketch=None):
"""
Iterate over all curve segments in the path.
Each iteration returns a pair ``(vertices, code)``, where ``vertices``
is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
Additionally, this method can provide a number of standard cleanups and
conversions to the path.
Parameters
----------
transform : None or :class:`~matplotlib.transforms.Transform`
If not None, the given affine transformation will be applied to the
path.
remove_nans : bool, optional
Whether to remove all NaNs from the path and skip over them using
MOVETO commands.
clip : None or (float, float, float, float), optional
If not None, must be a four-tuple (x1, y1, x2, y2)
defining a rectangle in which to clip the path.
snap : None or bool, optional
If True, snap all nodes to pixels; if False, don't snap them.
If None, snap if the path contains only segments
parallel to the x or y axes, and no more than 1024 of them.
stroke_width : float, optional
The width of the stroke being drawn (used for path snapping).
simplify : None or bool, optional
Whether to simplify the path by removing vertices
that do not affect its appearance. If None, use the
:attr:`should_simplify` attribute. See also :rc:`path.simplify`
and :rc:`path.simplify_threshold`.
curves : bool, optional
If True, curve segments will be returned as curve segments.
If False, all curves will be converted to line segments.
sketch : None or sequence, optional
If not None, must be a 3-tuple of the form
(scale, length, randomness), representing the sketch parameters.
"""
if not len(self):
return
cleaned = self.cleaned(transform=transform,
remove_nans=remove_nans, clip=clip,
snap=snap, stroke_width=stroke_width,
simplify=simplify, curves=curves,
sketch=sketch)
# Cache these object lookups for performance in the loop.
NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
STOP = self.STOP
vertices = iter(cleaned.vertices)
codes = iter(cleaned.codes)
for curr_vertices, code in zip(vertices, codes):
if code == STOP:
break
extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
if extra_vertices:
for i in range(extra_vertices):
next(codes)
curr_vertices = np.append(curr_vertices, next(vertices))
yield curr_vertices, code
def iter_bezier(self, **kwargs):
"""
Iterate over each Bézier curve (lines included) in a Path.
Parameters
----------
**kwargs
Forwarded to `.iter_segments`.
Yields
------
B : matplotlib.bezier.BezierSegment
The Bézier curves that make up the current path. Note in particular
that freestanding points are Bézier curves of order 0, and lines
are Bézier curves of order 1 (with two control points).
code : Path.code_type
The code describing what kind of curve is being returned.
Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE4 correspond to
Bézier curves with 1, 2, 3, and 4 control points (respectively).
Path.CLOSEPOLY is a Path.LINETO with the control points correctly
chosen based on the start/end points of the current stroke.
"""
first_vert = None
prev_vert = None
for verts, code in self.iter_segments(**kwargs):
if first_vert is None:
if code != Path.MOVETO:
raise ValueError("Malformed path, must start with MOVETO.")
if code == Path.MOVETO: # a point is like "CURVE1"
first_vert = verts
yield BezierSegment(np.array([first_vert])), code
elif code == Path.LINETO: # "CURVE2"
yield BezierSegment(np.array([prev_vert, verts])), code
elif code == Path.CURVE3:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:]])), code
elif code == Path.CURVE4:
yield BezierSegment(np.array([prev_vert, verts[:2],
verts[2:4], verts[4:]])), code
elif code == Path.CLOSEPOLY:
yield BezierSegment(np.array([prev_vert, first_vert])), code
elif code == Path.STOP:
return
else:
raise ValueError(f"Invalid Path.code_type: {code}")
prev_vert = verts[-2:]
def cleaned(self, transform=None, remove_nans=False, clip=None,
*, simplify=False, curves=False,
stroke_width=1.0, snap=False, sketch=None):
"""
Return a new Path with vertices and codes cleaned according to the
parameters.
See Also
--------
Path.iter_segments : for details of the keyword arguments.
"""
vertices, codes = _path.cleanup_path(
self, transform, remove_nans, clip, snap, stroke_width, simplify,
curves, sketch)
pth = Path._fast_from_codes_and_verts(vertices, codes, self)
if not simplify:
pth._should_simplify = False
return pth
def transformed(self, transform):
"""
Return a transformed copy of the path.
See Also
--------
matplotlib.transforms.TransformedPath
A specialized path class that will cache the transformed result and
automatically update when the transform changes.
"""
return Path(transform.transform(self.vertices), self.codes,
self._interpolation_steps)
def contains_point(self, point, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given point.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
point : (float, float)
The point (x, y) to check.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *point* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *point*.
radius : float, default: 0
Additional margin on the path in coordinates of *point*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
bool
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
# `point_in_path` does not handle nonlinear transforms, so we
# transform the path ourselves. If *transform* is affine, letting
# `point_in_path` handle the transform avoids allocating an extra
# buffer.
if transform and not transform.is_affine:
self = transform.transform_path(self)
transform = None
return _path.point_in_path(point[0], point[1], radius, self, transform)
def contains_points(self, points, transform=None, radius=0.0):
"""
Return whether the area enclosed by the path contains the given points.
The path is always treated as closed; i.e. if the last code is not
CLOSEPOLY an implicit segment connecting the last vertex to the first
vertex is assumed.
Parameters
----------
points : (N, 2) array
The points to check. Columns contain x and y values.
transform : `matplotlib.transforms.Transform`, optional
If not ``None``, *points* will be compared to ``self`` transformed
by *transform*; i.e. for a correct check, *transform* should
transform the path into the coordinate system of *points*.
radius : float, default: 0
Additional margin on the path in coordinates of *points*.
The path is extended tangentially by *radius/2*; i.e. if you would
draw the path with a linewidth of *radius*, all points on the line
would still be considered to be contained in the area. Conversely,
negative values shrink the area: Points on the imaginary line
will be considered outside the area.
Returns
-------
length-N bool array
Notes
-----
The current algorithm has some limitations:
- The result is undefined for points exactly at the boundary
(i.e. at the path shifted by *radius/2*).
- The result is undefined if there is no enclosed area, i.e. all
vertices are on a straight line.
- If bounding lines start to cross each other due to *radius* shift,
the result is not guaranteed to be correct.
"""
if transform is not None:
transform = transform.frozen()
result = _path.points_in_path(points, radius, self, transform)
return result.astype('bool')
def contains_path(self, path, transform=None):
"""
Return whether this (closed) path completely contains the given path.
If *transform* is not ``None``, the path will be transformed before
checking for containment.
"""
if transform is not None:
transform = transform.frozen()
return _path.path_in_path(self, None, path, transform)
def get_extents(self, transform=None, **kwargs):
"""
Get Bbox of the path.
Parameters
----------
transform : matplotlib.transforms.Transform, optional
Transform to apply to path before computing extents, if any.
**kwargs
Forwarded to `.iter_bezier`.
Returns
-------
matplotlib.transforms.Bbox
The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
"""
from .transforms import Bbox
if transform is not None:
self = transform.transform_path(self)
if self.codes is None:
xys = self.vertices
elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
# Optimization for the straight line case.
# Instead of iterating through each curve, consider
# each line segment's end-points
# (recall that STOP and CLOSEPOLY vertices are ignored)
xys = self.vertices[np.isin(self.codes,
[Path.MOVETO, Path.LINETO])]
else:
xys = []
for curve, code in self.iter_bezier(**kwargs):
# places where the derivative is zero can be extrema
_, dzeros = curve.axis_aligned_extrema()
# as can the ends of the curve
xys.append(curve([0, *dzeros, 1]))
xys = np.concatenate(xys)
if len(xys):
return Bbox([xys.min(axis=0), xys.max(axis=0)])
else:
return Bbox.null()
def intersects_path(self, other, filled=True):
"""
Return whether if this path intersects another given path.
If *filled* is True, then this also returns True if one path completely
encloses the other (i.e., the paths are treated as filled).
"""
return _path.path_intersects_path(self, other, filled)
def intersects_bbox(self, bbox, filled=True):
"""
Return whether this path intersects a given `~.transforms.Bbox`.
If *filled* is True, then this also returns True if the path completely
encloses the `.Bbox` (i.e., the path is treated as filled).
The bounding box is always considered filled.
"""
return _path.path_intersects_rectangle(
self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
def interpolated(self, steps):
"""
Return a new path resampled to length N x steps.
Codes other than LINETO are not handled correctly.
"""
if steps == 1:
return self
vertices = simple_linear_interpolation(self.vertices, steps)
codes = self.codes
if codes is not None:
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
dtype=self.code_type)
new_codes[0::steps] = codes
else:
new_codes = None
return Path(vertices, new_codes)
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
"""
Convert this path to a list of polygons or polylines. Each
polygon/polyline 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 Bézier curves.
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.
If *closed_only* is `True` (default), only closed polygons,
with the last point being the same as the first point, will be
returned. Any unclosed polylines in the path will be
explicitly closed. If *closed_only* is `False`, any unclosed
polygons in the path will be returned as unclosed polygons,
and the closed polygons will be returned explicitly closed by
setting the last point to the same as the first point.
"""
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):
vertices = self.vertices
if closed_only:
if len(vertices) < 3:
return []
elif np.any(vertices[0] != vertices[-1]):
vertices = [*vertices, vertices[0]]
if transform is None:
return [vertices]
else:
return [transform.transform(vertices)]
# Deal with the case where there are curves and/or multiple
# subpaths (using extension code)
return _path.convert_path_to_polygons(
self, transform, width, height, closed_only)
_unit_rectangle = None
def unit_rectangle(cls):
"""
Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
"""
if cls._unit_rectangle is None:
cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
closed=True, readonly=True)
return cls._unit_rectangle
_unit_regular_polygons = WeakValueDictionary()
def unit_regular_polygon(cls, numVertices):
"""
Return a :class:`Path` instance for a unit regular polygon with the
given *numVertices* such that the circumscribing circle has radius 1.0,
centered at (0, 0).
"""
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)
# This initial rotation is to make sure the polygon always
# "points-up".
+ np.pi / 2)
verts = np.column_stack((np.cos(theta), np.sin(theta)))
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_polygons[numVertices] = path
return path
_unit_regular_stars = WeakValueDictionary()
def unit_regular_star(cls, numVertices, innerCircle=0.5):
"""
Return a :class:`Path` for a unit regular star with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
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))
# This initial rotation is to make sure the polygon always
# "points-up"
theta += np.pi / 2.0
r = np.ones(ns2 + 1)
r[1::2] = innerCircle
verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
path = cls(verts, closed=True, readonly=True)
if numVertices <= 16:
cls._unit_regular_stars[(numVertices, innerCircle)] = path
return path
def unit_regular_asterisk(cls, numVertices):
"""
Return a :class:`Path` for a unit regular asterisk with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
return cls.unit_regular_star(numVertices, 0.0)
_unit_circle = None
def unit_circle(cls):
"""
Return the readonly :class:`Path` of the unit circle.
For most cases, :func:`Path.circle` will be what you want.
"""
if cls._unit_circle is None:
cls._unit_circle = cls.circle(center=(0, 0), radius=1,
readonly=True)
return cls._unit_circle
def circle(cls, center=(0., 0.), radius=1., readonly=False):
"""
Return a `Path` representing a circle of a given radius and center.
Parameters
----------
center : (float, float), default: (0, 0)
The center of the circle.
radius : float, default: 1
The radius of the circle.
readonly : bool
Whether the created path should have the "readonly" argument
set when creating the Path instance.
Notes
-----
The circle is approximated using 8 cubic Bézier curves, as described in
Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
Bezier Cubic Splines <https://www.tinaja.com/glib/ellipse4.pdf>`_.
"""
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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]],
dtype=float)
codes = [cls.CURVE4] * 26
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
return Path(vertices * radius + center, codes, readonly=readonly)
_unit_circle_righthalf = None
def unit_circle_righthalf(cls):
"""
Return a `Path` of the right half of a unit circle.
See `Path.circle` for the reference on the approximation used.
"""
if cls._unit_circle_righthalf is None:
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
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],
[0.0, -1.0]],
float)
codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
return cls._unit_circle_righthalf
def arc(cls, theta1, theta2, n=None, is_wedge=False):
"""
Return a `Path` for the unit circle arc from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest arc within 360 degrees.
That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
*theta2* - 360 and not a full circle plus some extra overlap.
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
<https://web.archive.org/web/20190318044212/http://www.spaceroots.org/documents/ellipse/index.html>`_.
"""
halfpi = np.pi * 0.5
eta1 = theta1
eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
# Ensure 2pi range is not flattened to 0 due to floating-point errors,
# but don't try to expand existing 0 range.
if theta2 != theta1 and eta2 <= eta1:
eta2 += 360
eta1, eta2 = np.deg2rad([eta1, eta2])
# number of curve segments to make
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), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[1] = [xA[0], yA[0]]
codes[0:2] = [cls.MOVETO, cls.LINETO]
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
vertex_offset = 2
end = length - 2
else:
length = n * 3 + 1
vertices = np.empty((length, 2), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[0] = [xA[0], yA[0]]
codes[0] = cls.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 cls(vertices, codes, readonly=True)
def wedge(cls, theta1, theta2, n=None):
"""
Return a `Path` for the unit circle wedge from angles *theta1* to
*theta2* (in degrees).
*theta2* is unwrapped to produce the shortest wedge within 360 degrees.
That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
to *theta2* - 360 and not a full circle plus some extra overlap.
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*.
See `Path.arc` for the reference on the approximation used.
"""
return cls.arc(theta1, theta2, n, True)
def hatch(hatchpattern, density=6):
"""
Given a hatch specifier, *hatchpattern*, generates a Path that
can be used in a repeated hatching pattern. *density* is the
number of lines per unit square.
"""
from matplotlib.hatch import get_path
return (get_path(hatchpattern, density)
if hatchpattern is not None else None)
def clip_to_bbox(self, bbox, inside=True):
"""
Clip the path to the given bounding box.
The path must be made up of one or more closed polygons. This
algorithm will not behave correctly for unclosed paths.
If *inside* is `True`, clip to the inside of the box, otherwise
to the outside of the box.
"""
verts = _path.clip_path_to_rect(self, bbox, inside)
paths = [Path(poly) for poly in verts]
return self.make_compound_path(*paths)
The provided code snippet includes necessary dependencies for implementing the `xpdf_distill` function. Write a Python function `def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False)` to solve the following problem:
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.
Here is the function:
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.
"""
mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
mpl._get_executable_info("pdftops")
with TemporaryDirectory() as tmpdir:
tmppdf = pathlib.Path(tmpdir, "tmp.pdf")
tmpps = pathlib.Path(tmpdir, "tmp.ps")
# Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows
# happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).
cbook._check_and_log_subprocess(
["ps2pdf",
"-dAutoFilterColorImages#false",
"-dAutoFilterGrayImages#false",
"-sAutoRotatePages#None",
"-sGrayImageFilter#FlateEncode",
"-sColorImageFilter#FlateEncode",
"-dEPSCrop" if eps else "-sPAPERSIZE#%s" % ptype,
tmpfile, tmppdf], _log)
cbook._check_and_log_subprocess(
["pdftops", "-paper", "match", "-level2", tmppdf, tmpps], _log)
shutil.move(tmpps, tmpfile)
if eps:
pstoeps(tmpfile) | 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.