content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
# This style is used for the plot_types gallery. It is considered private.\n\naxes.grid: False\naxes.axisbelow: True\n\nfigure.figsize: 2, 2\n# make it so the axes labels don't show up. Obviously \n# not good style for any quantitative analysis:\nfigure.subplot.left: 0.01\nfigure.subplot.right: 0.99\nfigure.subplot.bottom: 0.01\nfigure.subplot.top: 0.99\n\nxtick.major.size: 0.0\nytick.major.size: 0.0\n\n# colors:\nimage.cmap : Blues\naxes.prop_cycle: cycler('color', ['1f77b4', '82bbdb', 'ccdff1'])\n | .venv\Lib\site-packages\matplotlib\mpl-data\stylelib\_mpl-gallery-nogrid.mplstyle | _mpl-gallery-nogrid.mplstyle | Other | 489 | 0.8 | 0.105263 | 0.266667 | vue-tools | 809 | 2023-08-07T10:58:42.322854 | BSD-3-Clause | false | 13563171d62c92569424808dc1c81fed |
# This style is used for the plot_types gallery. It is considered part of the private API.\n\naxes.grid: True\naxes.axisbelow: True\n\nfigure.figsize: 2, 2\n# make it so the axes labels don't show up. Obviously \n# not good style for any quantitative analysis:\nfigure.subplot.left: 0.01\nfigure.subplot.right: 0.99\nfigure.subplot.bottom: 0.01\nfigure.subplot.top: 0.99\n\nxtick.major.size: 0.0\nytick.major.size: 0.0\n\n# colors:\nimage.cmap : Blues\naxes.prop_cycle: cycler('color', ['1f77b4', '58a1cf', 'abd0e6'])\n | .venv\Lib\site-packages\matplotlib\mpl-data\stylelib\_mpl-gallery.mplstyle | _mpl-gallery.mplstyle | Other | 504 | 0.8 | 0.105263 | 0.266667 | react-lib | 224 | 2023-10-12T14:12:08.673910 | GPL-3.0 | false | 23f1d4dc684fd9c47c8d76f78f292979 |
import numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api\nfrom matplotlib.axes import Axes\nimport matplotlib.axis as maxis\nfrom matplotlib.patches import Circle\nfrom matplotlib.path import Path\nimport matplotlib.spines as mspines\nfrom matplotlib.ticker import (\n Formatter, NullLocator, FixedLocator, NullFormatter)\nfrom matplotlib.transforms import Affine2D, BboxTransformTo, Transform\n\n\nclass GeoAxes(Axes):\n """An abstract base class for geographic projections."""\n\n class ThetaFormatter(Formatter):\n """\n Used to format the theta tick labels. Converts the native\n unit of radians into degrees and adds a degree symbol.\n """\n def __init__(self, round_to=1.0):\n self._round_to = round_to\n\n def __call__(self, x, pos=None):\n degrees = round(np.rad2deg(x) / self._round_to) * self._round_to\n return f"{degrees:0.0f}\N{DEGREE SIGN}"\n\n RESOLUTION = 75\n\n def _init_axis(self):\n self.xaxis = maxis.XAxis(self, clear=False)\n self.yaxis = maxis.YAxis(self, clear=False)\n self.spines['geo'].register_axis(self.yaxis)\n\n def clear(self):\n # docstring inherited\n super().clear()\n\n self.set_longitude_grid(30)\n self.set_latitude_grid(15)\n self.set_longitude_grid_ends(75)\n self.xaxis.set_minor_locator(NullLocator())\n self.yaxis.set_minor_locator(NullLocator())\n self.xaxis.set_ticks_position('none')\n self.yaxis.set_ticks_position('none')\n self.yaxis.set_tick_params(label1On=True)\n # Why do we need to turn on yaxis tick labels, but\n # xaxis tick labels are already on?\n\n self.grid(mpl.rcParams['axes.grid'])\n\n Axes.set_xlim(self, -np.pi, np.pi)\n Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)\n\n def _set_lim_and_transforms(self):\n # A (possibly non-linear) projection on the (already scaled) data\n self.transProjection = self._get_core_transform(self.RESOLUTION)\n\n self.transAffine = self._get_affine_transform()\n\n self.transAxes = BboxTransformTo(self.bbox)\n\n # The complete data transformation stack -- from data all the\n # way to display coordinates\n self.transData = \\n self.transProjection + \\n self.transAffine + \\n self.transAxes\n\n # This is the transform for longitude ticks.\n self._xaxis_pretransform = \\n Affine2D() \\n .scale(1, self._longitude_cap * 2) \\n .translate(0, -self._longitude_cap)\n self._xaxis_transform = \\n self._xaxis_pretransform + \\n self.transData\n self._xaxis_text1_transform = \\n Affine2D().scale(1, 0) + \\n self.transData + \\n Affine2D().translate(0, 4)\n self._xaxis_text2_transform = \\n Affine2D().scale(1, 0) + \\n self.transData + \\n Affine2D().translate(0, -4)\n\n # This is the transform for latitude ticks.\n yaxis_stretch = Affine2D().scale(np.pi * 2, 1).translate(-np.pi, 0)\n yaxis_space = Affine2D().scale(1, 1.1)\n self._yaxis_transform = \\n yaxis_stretch + \\n self.transData\n yaxis_text_base = \\n yaxis_stretch + \\n self.transProjection + \\n (yaxis_space +\n self.transAffine +\n self.transAxes)\n self._yaxis_text1_transform = \\n yaxis_text_base + \\n Affine2D().translate(-8, 0)\n self._yaxis_text2_transform = \\n yaxis_text_base + \\n Affine2D().translate(8, 0)\n\n def _get_affine_transform(self):\n transform = self._get_core_transform(1)\n xscale, _ = transform.transform((np.pi, 0))\n _, yscale = transform.transform((0, np.pi/2))\n return Affine2D() \\n .scale(0.5 / xscale, 0.5 / yscale) \\n .translate(0.5, 0.5)\n\n def get_xaxis_transform(self, which='grid'):\n _api.check_in_list(['tick1', 'tick2', 'grid'], which=which)\n return self._xaxis_transform\n\n def get_xaxis_text1_transform(self, pad):\n return self._xaxis_text1_transform, 'bottom', 'center'\n\n def get_xaxis_text2_transform(self, pad):\n return self._xaxis_text2_transform, 'top', 'center'\n\n def get_yaxis_transform(self, which='grid'):\n _api.check_in_list(['tick1', 'tick2', 'grid'], which=which)\n return self._yaxis_transform\n\n def get_yaxis_text1_transform(self, pad):\n return self._yaxis_text1_transform, 'center', 'right'\n\n def get_yaxis_text2_transform(self, pad):\n return self._yaxis_text2_transform, 'center', 'left'\n\n def _gen_axes_patch(self):\n return Circle((0.5, 0.5), 0.5)\n\n def _gen_axes_spines(self):\n return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)}\n\n def set_yscale(self, *args, **kwargs):\n if args[0] != 'linear':\n raise NotImplementedError\n\n set_xscale = set_yscale\n\n def set_xlim(self, *args, **kwargs):\n """Not supported. Please consider using Cartopy."""\n raise TypeError("Changing axes limits of a geographic projection is "\n "not supported. Please consider using Cartopy.")\n\n set_ylim = set_xlim\n set_xbound = set_xlim\n set_ybound = set_ylim\n\n def invert_xaxis(self):\n """Not supported. Please consider using Cartopy."""\n raise TypeError("Changing axes limits of a geographic projection is "\n "not supported. Please consider using Cartopy.")\n\n invert_yaxis = invert_xaxis\n\n def format_coord(self, lon, lat):\n """Return a format string formatting the coordinate."""\n lon, lat = np.rad2deg([lon, lat])\n ns = 'N' if lat >= 0.0 else 'S'\n ew = 'E' if lon >= 0.0 else 'W'\n return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s'\n % (abs(lat), ns, abs(lon), ew))\n\n def set_longitude_grid(self, degrees):\n """\n Set the number of degrees between each longitude grid.\n """\n # Skip -180 and 180, which are the fixed limits.\n grid = np.arange(-180 + degrees, 180, degrees)\n self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))\n self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))\n\n def set_latitude_grid(self, degrees):\n """\n Set the number of degrees between each latitude grid.\n """\n # Skip -90 and 90, which are the fixed limits.\n grid = np.arange(-90 + degrees, 90, degrees)\n self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))\n self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))\n\n def set_longitude_grid_ends(self, degrees):\n """\n Set the latitude(s) at which to stop drawing the longitude grids.\n """\n self._longitude_cap = np.deg2rad(degrees)\n self._xaxis_pretransform \\n .clear() \\n .scale(1.0, self._longitude_cap * 2.0) \\n .translate(0.0, -self._longitude_cap)\n\n def get_data_ratio(self):\n """Return the aspect ratio of the data itself."""\n return 1.0\n\n ### Interactive panning\n\n def can_zoom(self):\n """\n Return whether this Axes supports the zoom box button functionality.\n\n This Axes object does not support interactive zoom box.\n """\n return False\n\n def can_pan(self):\n """\n Return whether this Axes supports the pan/zoom button functionality.\n\n This Axes object does not support interactive pan/zoom.\n """\n return False\n\n def start_pan(self, x, y, button):\n pass\n\n def end_pan(self):\n pass\n\n def drag_pan(self, button, key, x, y):\n pass\n\n\nclass _GeoTransform(Transform):\n # Factoring out some common functionality.\n input_dims = output_dims = 2\n\n def __init__(self, resolution):\n """\n Create a new geographical transform.\n\n Resolution is the number of steps to interpolate between each input\n line segment to approximate its path in curved space.\n """\n super().__init__()\n self._resolution = resolution\n\n def __str__(self):\n return f"{type(self).__name__}({self._resolution})"\n\n def transform_path_non_affine(self, path):\n # docstring inherited\n ipath = path.interpolated(self._resolution)\n return Path(self.transform(ipath.vertices), ipath.codes)\n\n\nclass AitoffAxes(GeoAxes):\n name = 'aitoff'\n\n class AitoffTransform(_GeoTransform):\n """The base Aitoff transform."""\n\n def transform_non_affine(self, values):\n # docstring inherited\n longitude, latitude = values.T\n\n # Pre-compute some values\n half_long = longitude / 2.0\n cos_latitude = np.cos(latitude)\n\n alpha = np.arccos(cos_latitude * np.cos(half_long))\n sinc_alpha = np.sinc(alpha / np.pi) # np.sinc is sin(pi*x)/(pi*x).\n\n x = (cos_latitude * np.sin(half_long)) / sinc_alpha\n y = np.sin(latitude) / sinc_alpha\n return np.column_stack([x, y])\n\n def inverted(self):\n # docstring inherited\n return AitoffAxes.InvertedAitoffTransform(self._resolution)\n\n class InvertedAitoffTransform(_GeoTransform):\n\n def transform_non_affine(self, values):\n # docstring inherited\n # MGDTODO: Math is hard ;(\n return np.full_like(values, np.nan)\n\n def inverted(self):\n # docstring inherited\n return AitoffAxes.AitoffTransform(self._resolution)\n\n def __init__(self, *args, **kwargs):\n self._longitude_cap = np.pi / 2.0\n super().__init__(*args, **kwargs)\n self.set_aspect(0.5, adjustable='box', anchor='C')\n self.clear()\n\n def _get_core_transform(self, resolution):\n return self.AitoffTransform(resolution)\n\n\nclass HammerAxes(GeoAxes):\n name = 'hammer'\n\n class HammerTransform(_GeoTransform):\n """The base Hammer transform."""\n\n def transform_non_affine(self, values):\n # docstring inherited\n longitude, latitude = values.T\n half_long = longitude / 2.0\n cos_latitude = np.cos(latitude)\n sqrt2 = np.sqrt(2.0)\n alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long))\n x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha\n y = (sqrt2 * np.sin(latitude)) / alpha\n return np.column_stack([x, y])\n\n def inverted(self):\n # docstring inherited\n return HammerAxes.InvertedHammerTransform(self._resolution)\n\n class InvertedHammerTransform(_GeoTransform):\n\n def transform_non_affine(self, values):\n # docstring inherited\n x, y = values.T\n z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2)\n longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1)))\n latitude = np.arcsin(y*z)\n return np.column_stack([longitude, latitude])\n\n def inverted(self):\n # docstring inherited\n return HammerAxes.HammerTransform(self._resolution)\n\n def __init__(self, *args, **kwargs):\n self._longitude_cap = np.pi / 2.0\n super().__init__(*args, **kwargs)\n self.set_aspect(0.5, adjustable='box', anchor='C')\n self.clear()\n\n def _get_core_transform(self, resolution):\n return self.HammerTransform(resolution)\n\n\nclass MollweideAxes(GeoAxes):\n name = 'mollweide'\n\n class MollweideTransform(_GeoTransform):\n """The base Mollweide transform."""\n\n def transform_non_affine(self, values):\n # docstring inherited\n def d(theta):\n delta = (-(theta + np.sin(theta) - pi_sin_l)\n / (1 + np.cos(theta)))\n return delta, np.abs(delta) > 0.001\n\n longitude, latitude = values.T\n\n clat = np.pi/2 - np.abs(latitude)\n ihigh = clat < 0.087 # within 5 degrees of the poles\n ilow = ~ihigh\n aux = np.empty(latitude.shape, dtype=float)\n\n if ilow.any(): # Newton-Raphson iteration\n pi_sin_l = np.pi * np.sin(latitude[ilow])\n theta = 2.0 * latitude[ilow]\n delta, large_delta = d(theta)\n while np.any(large_delta):\n theta[large_delta] += delta[large_delta]\n delta, large_delta = d(theta)\n aux[ilow] = theta / 2\n\n if ihigh.any(): # Taylor series-based approx. solution\n e = clat[ihigh]\n d = 0.5 * (3 * np.pi * e**2) ** (1.0/3)\n aux[ihigh] = (np.pi/2 - d) * np.sign(latitude[ihigh])\n\n xy = np.empty(values.shape, dtype=float)\n xy[:, 0] = (2.0 * np.sqrt(2.0) / np.pi) * longitude * np.cos(aux)\n xy[:, 1] = np.sqrt(2.0) * np.sin(aux)\n\n return xy\n\n def inverted(self):\n # docstring inherited\n return MollweideAxes.InvertedMollweideTransform(self._resolution)\n\n class InvertedMollweideTransform(_GeoTransform):\n\n def transform_non_affine(self, values):\n # docstring inherited\n x, y = values.T\n # from Equations (7, 8) of\n # https://mathworld.wolfram.com/MollweideProjection.html\n theta = np.arcsin(y / np.sqrt(2))\n longitude = (np.pi / (2 * np.sqrt(2))) * x / np.cos(theta)\n latitude = np.arcsin((2 * theta + np.sin(2 * theta)) / np.pi)\n return np.column_stack([longitude, latitude])\n\n def inverted(self):\n # docstring inherited\n return MollweideAxes.MollweideTransform(self._resolution)\n\n def __init__(self, *args, **kwargs):\n self._longitude_cap = np.pi / 2.0\n super().__init__(*args, **kwargs)\n self.set_aspect(0.5, adjustable='box', anchor='C')\n self.clear()\n\n def _get_core_transform(self, resolution):\n return self.MollweideTransform(resolution)\n\n\nclass LambertAxes(GeoAxes):\n name = 'lambert'\n\n class LambertTransform(_GeoTransform):\n """The base Lambert transform."""\n\n def __init__(self, center_longitude, center_latitude, resolution):\n """\n Create a new Lambert transform. Resolution is the number of steps\n to interpolate between each input line segment to approximate its\n path in curved Lambert space.\n """\n _GeoTransform.__init__(self, resolution)\n self._center_longitude = center_longitude\n self._center_latitude = center_latitude\n\n def transform_non_affine(self, values):\n # docstring inherited\n longitude, latitude = values.T\n clong = self._center_longitude\n clat = self._center_latitude\n cos_lat = np.cos(latitude)\n sin_lat = np.sin(latitude)\n diff_long = longitude - clong\n cos_diff_long = np.cos(diff_long)\n\n inner_k = np.maximum( # Prevent divide-by-zero problems\n 1 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long,\n 1e-15)\n k = np.sqrt(2 / inner_k)\n x = k * cos_lat*np.sin(diff_long)\n y = k * (np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long)\n\n return np.column_stack([x, y])\n\n def inverted(self):\n # docstring inherited\n return LambertAxes.InvertedLambertTransform(\n self._center_longitude,\n self._center_latitude,\n self._resolution)\n\n class InvertedLambertTransform(_GeoTransform):\n\n def __init__(self, center_longitude, center_latitude, resolution):\n _GeoTransform.__init__(self, resolution)\n self._center_longitude = center_longitude\n self._center_latitude = center_latitude\n\n def transform_non_affine(self, values):\n # docstring inherited\n x, y = values.T\n clong = self._center_longitude\n clat = self._center_latitude\n p = np.maximum(np.hypot(x, y), 1e-9)\n c = 2 * np.arcsin(0.5 * p)\n sin_c = np.sin(c)\n cos_c = np.cos(c)\n\n latitude = np.arcsin(cos_c*np.sin(clat) +\n ((y*sin_c*np.cos(clat)) / p))\n longitude = clong + np.arctan(\n (x*sin_c) / (p*np.cos(clat)*cos_c - y*np.sin(clat)*sin_c))\n\n return np.column_stack([longitude, latitude])\n\n def inverted(self):\n # docstring inherited\n return LambertAxes.LambertTransform(\n self._center_longitude,\n self._center_latitude,\n self._resolution)\n\n def __init__(self, *args, center_longitude=0, center_latitude=0, **kwargs):\n self._longitude_cap = np.pi / 2\n self._center_longitude = center_longitude\n self._center_latitude = center_latitude\n super().__init__(*args, **kwargs)\n self.set_aspect('equal', adjustable='box', anchor='C')\n self.clear()\n\n def clear(self):\n # docstring inherited\n super().clear()\n self.yaxis.set_major_formatter(NullFormatter())\n\n def _get_core_transform(self, resolution):\n return self.LambertTransform(\n self._center_longitude,\n self._center_latitude,\n resolution)\n\n def _get_affine_transform(self):\n return Affine2D() \\n .scale(0.25) \\n .translate(0.5, 0.5)\n | .venv\Lib\site-packages\matplotlib\projections\geo.py | geo.py | Python | 17,605 | 0.95 | 0.164384 | 0.084367 | awesome-app | 513 | 2024-11-06T06:23:48.838889 | BSD-3-Clause | false | cbed23f80710855beacd296d8760e758 |
from matplotlib.axes import Axes\nfrom matplotlib.ticker import Formatter\nfrom matplotlib.transforms import Transform\n\nfrom typing import Any, Literal\n\nclass GeoAxes(Axes):\n class ThetaFormatter(Formatter):\n def __init__(self, round_to: float = ...) -> None: ...\n def __call__(self, x: float, pos: Any | None = ...): ...\n RESOLUTION: float\n def get_xaxis_transform(\n self, which: Literal["tick1", "tick2", "grid"] = ...\n ) -> Transform: ...\n def get_xaxis_text1_transform(\n self, pad: float\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_xaxis_text2_transform(\n self, pad: float\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_yaxis_transform(\n self, which: Literal["tick1", "tick2", "grid"] = ...\n ) -> Transform: ...\n def get_yaxis_text1_transform(\n self, pad: float\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_yaxis_text2_transform(\n self, pad: float\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def set_xlim(self, *args, **kwargs) -> tuple[float, float]: ...\n def set_ylim(self, *args, **kwargs) -> tuple[float, float]: ...\n def format_coord(self, lon: float, lat: float) -> str: ...\n def set_longitude_grid(self, degrees: float) -> None: ...\n def set_latitude_grid(self, degrees: float) -> None: ...\n def set_longitude_grid_ends(self, degrees: float) -> None: ...\n def get_data_ratio(self) -> float: ...\n def can_zoom(self) -> bool: ...\n def can_pan(self) -> bool: ...\n def start_pan(self, x, y, button) -> None: ...\n def end_pan(self) -> None: ...\n def drag_pan(self, button, key, x, y) -> None: ...\n\nclass _GeoTransform(Transform):\n input_dims: int\n output_dims: int\n def __init__(self, resolution: int) -> None: ...\n\nclass AitoffAxes(GeoAxes):\n name: str\n\n class AitoffTransform(_GeoTransform):\n def inverted(self) -> AitoffAxes.InvertedAitoffTransform: ...\n\n class InvertedAitoffTransform(_GeoTransform):\n def inverted(self) -> AitoffAxes.AitoffTransform: ...\n\nclass HammerAxes(GeoAxes):\n name: str\n\n class HammerTransform(_GeoTransform):\n def inverted(self) -> HammerAxes.InvertedHammerTransform: ...\n\n class InvertedHammerTransform(_GeoTransform):\n def inverted(self) -> HammerAxes.HammerTransform: ...\n\nclass MollweideAxes(GeoAxes):\n name: str\n\n class MollweideTransform(_GeoTransform):\n def inverted(self) -> MollweideAxes.InvertedMollweideTransform: ...\n\n class InvertedMollweideTransform(_GeoTransform):\n def inverted(self) -> MollweideAxes.MollweideTransform: ...\n\nclass LambertAxes(GeoAxes):\n name: str\n\n class LambertTransform(_GeoTransform):\n def __init__(\n self, center_longitude: float, center_latitude: float, resolution: int\n ) -> None: ...\n def inverted(self) -> LambertAxes.InvertedLambertTransform: ...\n\n class InvertedLambertTransform(_GeoTransform):\n def __init__(\n self, center_longitude: float, center_latitude: float, resolution: int\n ) -> None: ...\n def inverted(self) -> LambertAxes.LambertTransform: ...\n\n def __init__(\n self,\n *args,\n center_longitude: float = ...,\n center_latitude: float = ...,\n **kwargs\n ) -> None: ...\n | .venv\Lib\site-packages\matplotlib\projections\geo.pyi | geo.pyi | Other | 3,775 | 0.85 | 0.419643 | 0.020833 | node-utils | 217 | 2025-03-31T02:49:25.978343 | BSD-3-Clause | false | be43ae1c7bbb484bbd8c90972498a3ca |
import math\nimport types\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api, cbook\nfrom matplotlib.axes import Axes\nimport matplotlib.axis as maxis\nimport matplotlib.markers as mmarkers\nimport matplotlib.patches as mpatches\nfrom matplotlib.path import Path\nimport matplotlib.ticker as mticker\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.spines import Spine\n\n\ndef _apply_theta_transforms_warn():\n _api.warn_deprecated(\n "3.9",\n message=(\n "Passing `apply_theta_transforms=True` (the default) "\n "is deprecated since Matplotlib %(since)s. "\n "Support for this will be removed in Matplotlib in %(removal)s. "\n "To prevent this warning, set `apply_theta_transforms=False`, "\n "and make sure to shift theta values before being passed to "\n "this transform."\n )\n )\n\n\nclass PolarTransform(mtransforms.Transform):\n r"""\n The base polar transform.\n\n This transform maps polar coordinates :math:`\theta, r` into Cartesian\n coordinates :math:`x, y = r \cos(\theta), r \sin(\theta)`\n (but does not fully transform into Axes coordinates or\n handle positioning in screen space).\n\n This transformation is designed to be applied to data after any scaling\n along the radial axis (e.g. log-scaling) has been applied to the input\n data.\n\n Path segments at a fixed radius are automatically transformed to circular\n arcs as long as ``path._interpolation_steps > 1``.\n """\n\n input_dims = output_dims = 2\n\n def __init__(self, axis=None, use_rmin=True, *,\n apply_theta_transforms=True, scale_transform=None):\n """\n Parameters\n ----------\n axis : `~matplotlib.axis.Axis`, optional\n Axis associated with this transform. This is used to get the\n minimum radial limit.\n use_rmin : `bool`, optional\n If ``True``, subtract the minimum radial axis limit before\n transforming to Cartesian coordinates. *axis* must also be\n specified for this to take effect.\n """\n super().__init__()\n self._axis = axis\n self._use_rmin = use_rmin\n self._apply_theta_transforms = apply_theta_transforms\n self._scale_transform = scale_transform\n if apply_theta_transforms:\n _apply_theta_transforms_warn()\n\n __str__ = mtransforms._make_str_method(\n "_axis",\n use_rmin="_use_rmin",\n apply_theta_transforms="_apply_theta_transforms")\n\n def _get_rorigin(self):\n # Get lower r limit after being scaled by the radial scale transform\n return self._scale_transform.transform(\n (0, self._axis.get_rorigin()))[1]\n\n def transform_non_affine(self, values):\n # docstring inherited\n theta, r = np.transpose(values)\n # PolarAxes does not use the theta transforms here, but apply them for\n # backwards-compatibility if not being used by it.\n if self._apply_theta_transforms and self._axis is not None:\n theta *= self._axis.get_theta_direction()\n theta += self._axis.get_theta_offset()\n if self._use_rmin and self._axis is not None:\n r = (r - self._get_rorigin()) * self._axis.get_rsign()\n r = np.where(r >= 0, r, np.nan)\n return np.column_stack([r * np.cos(theta), r * np.sin(theta)])\n\n def transform_path_non_affine(self, path):\n # docstring inherited\n if not len(path) or path._interpolation_steps == 1:\n return Path(self.transform_non_affine(path.vertices), path.codes)\n xys = []\n codes = []\n last_t = last_r = None\n for trs, c in path.iter_segments():\n trs = trs.reshape((-1, 2))\n if c == Path.LINETO:\n (t, r), = trs\n if t == last_t: # Same angle: draw a straight line.\n xys.extend(self.transform_non_affine(trs))\n codes.append(Path.LINETO)\n elif r == last_r: # Same radius: draw an arc.\n # The following is complicated by Path.arc() being\n # "helpful" and unwrapping the angles, but we don't want\n # that behavior here.\n last_td, td = np.rad2deg([last_t, t])\n if self._use_rmin and self._axis is not None:\n r = ((r - self._get_rorigin())\n * self._axis.get_rsign())\n if last_td <= td:\n while td - last_td > 360:\n arc = Path.arc(last_td, last_td + 360)\n xys.extend(arc.vertices[1:] * r)\n codes.extend(arc.codes[1:])\n last_td += 360\n arc = Path.arc(last_td, td)\n xys.extend(arc.vertices[1:] * r)\n codes.extend(arc.codes[1:])\n else:\n # The reverse version also relies on the fact that all\n # codes but the first one are the same.\n while last_td - td > 360:\n arc = Path.arc(last_td - 360, last_td)\n xys.extend(arc.vertices[::-1][1:] * r)\n codes.extend(arc.codes[1:])\n last_td -= 360\n arc = Path.arc(td, last_td)\n xys.extend(arc.vertices[::-1][1:] * r)\n codes.extend(arc.codes[1:])\n else: # Interpolate.\n trs = cbook.simple_linear_interpolation(\n np.vstack([(last_t, last_r), trs]),\n path._interpolation_steps)[1:]\n xys.extend(self.transform_non_affine(trs))\n codes.extend([Path.LINETO] * len(trs))\n else: # Not a straight line.\n xys.extend(self.transform_non_affine(trs))\n codes.extend([c] * len(trs))\n last_t, last_r = trs[-1]\n return Path(xys, codes)\n\n def inverted(self):\n # docstring inherited\n return PolarAxes.InvertedPolarTransform(\n self._axis, self._use_rmin,\n apply_theta_transforms=self._apply_theta_transforms\n )\n\n\nclass PolarAffine(mtransforms.Affine2DBase):\n r"""\n The affine part of the polar projection.\n\n Scales the output so that maximum radius rests on the edge of the Axes\n circle and the origin is mapped to (0.5, 0.5). The transform applied is\n the same to x and y components and given by:\n\n .. math::\n\n x_{1} = 0.5 \left [ \frac{x_{0}}{(r_{\max} - r_{\min})} + 1 \right ]\n\n :math:`r_{\min}, r_{\max}` are the minimum and maximum radial limits after\n any scaling (e.g. log scaling) has been removed.\n """\n def __init__(self, scale_transform, limits):\n """\n Parameters\n ----------\n scale_transform : `~matplotlib.transforms.Transform`\n Scaling transform for the data. This is used to remove any scaling\n from the radial view limits.\n limits : `~matplotlib.transforms.BboxBase`\n View limits of the data. The only part of its bounds that is used\n is the y limits (for the radius limits).\n """\n super().__init__()\n self._scale_transform = scale_transform\n self._limits = limits\n self.set_children(scale_transform, limits)\n self._mtx = None\n\n __str__ = mtransforms._make_str_method("_scale_transform", "_limits")\n\n def get_matrix(self):\n # docstring inherited\n if self._invalid:\n limits_scaled = self._limits.transformed(self._scale_transform)\n yscale = limits_scaled.ymax - limits_scaled.ymin\n affine = mtransforms.Affine2D() \\n .scale(0.5 / yscale) \\n .translate(0.5, 0.5)\n self._mtx = affine.get_matrix()\n self._inverted = None\n self._invalid = 0\n return self._mtx\n\n\nclass InvertedPolarTransform(mtransforms.Transform):\n """\n The inverse of the polar transform, mapping Cartesian\n coordinate space *x* and *y* back to *theta* and *r*.\n """\n input_dims = output_dims = 2\n\n def __init__(self, axis=None, use_rmin=True,\n *, apply_theta_transforms=True):\n """\n Parameters\n ----------\n axis : `~matplotlib.axis.Axis`, optional\n Axis associated with this transform. This is used to get the\n minimum radial limit.\n use_rmin : `bool`, optional\n If ``True``, add the minimum radial axis limit after\n transforming from Cartesian coordinates. *axis* must also be\n specified for this to take effect.\n """\n super().__init__()\n self._axis = axis\n self._use_rmin = use_rmin\n self._apply_theta_transforms = apply_theta_transforms\n if apply_theta_transforms:\n _apply_theta_transforms_warn()\n\n __str__ = mtransforms._make_str_method(\n "_axis",\n use_rmin="_use_rmin",\n apply_theta_transforms="_apply_theta_transforms")\n\n def transform_non_affine(self, values):\n # docstring inherited\n x, y = values.T\n r = np.hypot(x, y)\n theta = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi)\n # PolarAxes does not use the theta transforms here, but apply them for\n # backwards-compatibility if not being used by it.\n if self._apply_theta_transforms and self._axis is not None:\n theta -= self._axis.get_theta_offset()\n theta *= self._axis.get_theta_direction()\n theta %= 2 * np.pi\n if self._use_rmin and self._axis is not None:\n r += self._axis.get_rorigin()\n r *= self._axis.get_rsign()\n return np.column_stack([theta, r])\n\n def inverted(self):\n # docstring inherited\n return PolarAxes.PolarTransform(\n self._axis, self._use_rmin,\n apply_theta_transforms=self._apply_theta_transforms\n )\n\n\nclass ThetaFormatter(mticker.Formatter):\n """\n Used to format the *theta* tick labels. Converts the native\n unit of radians into degrees and adds a degree symbol.\n """\n\n def __call__(self, x, pos=None):\n vmin, vmax = self.axis.get_view_interval()\n d = np.rad2deg(abs(vmax - vmin))\n digits = max(-int(np.log10(d) - 1.5), 0)\n return f"{np.rad2deg(x):0.{digits}f}\N{DEGREE SIGN}"\n\n\nclass _AxisWrapper:\n def __init__(self, axis):\n self._axis = axis\n\n def get_view_interval(self):\n return np.rad2deg(self._axis.get_view_interval())\n\n def set_view_interval(self, vmin, vmax):\n self._axis.set_view_interval(*np.deg2rad((vmin, vmax)))\n\n def get_minpos(self):\n return np.rad2deg(self._axis.get_minpos())\n\n def get_data_interval(self):\n return np.rad2deg(self._axis.get_data_interval())\n\n def set_data_interval(self, vmin, vmax):\n self._axis.set_data_interval(*np.deg2rad((vmin, vmax)))\n\n def get_tick_space(self):\n return self._axis.get_tick_space()\n\n\nclass ThetaLocator(mticker.Locator):\n """\n Used to locate theta ticks.\n\n This will work the same as the base locator except in the case that the\n view spans the entire circle. In such cases, the previously used default\n locations of every 45 degrees are returned.\n """\n\n def __init__(self, base):\n self.base = base\n self.axis = self.base.axis = _AxisWrapper(self.base.axis)\n\n def set_axis(self, axis):\n self.axis = _AxisWrapper(axis)\n self.base.set_axis(self.axis)\n\n def __call__(self):\n lim = self.axis.get_view_interval()\n if _is_full_circle_deg(lim[0], lim[1]):\n return np.deg2rad(min(lim)) + np.arange(8) * 2 * np.pi / 8\n else:\n return np.deg2rad(self.base())\n\n def view_limits(self, vmin, vmax):\n vmin, vmax = np.rad2deg((vmin, vmax))\n return np.deg2rad(self.base.view_limits(vmin, vmax))\n\n\nclass ThetaTick(maxis.XTick):\n """\n A theta-axis tick.\n\n This subclass of `.XTick` provides angular ticks with some small\n modification to their re-positioning such that ticks are rotated based on\n tick location. This results in ticks that are correctly perpendicular to\n the arc spine.\n\n When 'auto' rotation is enabled, labels are also rotated to be parallel to\n the spine. The label padding is also applied here since it's not possible\n to use a generic axes transform to produce tick-specific padding.\n """\n\n def __init__(self, axes, *args, **kwargs):\n self._text1_translate = mtransforms.ScaledTranslation(\n 0, 0, axes.get_figure(root=False).dpi_scale_trans)\n self._text2_translate = mtransforms.ScaledTranslation(\n 0, 0, axes.get_figure(root=False).dpi_scale_trans)\n super().__init__(axes, *args, **kwargs)\n self.label1.set(\n rotation_mode='anchor',\n transform=self.label1.get_transform() + self._text1_translate)\n self.label2.set(\n rotation_mode='anchor',\n transform=self.label2.get_transform() + self._text2_translate)\n\n def _apply_params(self, **kwargs):\n super()._apply_params(**kwargs)\n # Ensure transform is correct; sometimes this gets reset.\n trans = self.label1.get_transform()\n if not trans.contains_branch(self._text1_translate):\n self.label1.set_transform(trans + self._text1_translate)\n trans = self.label2.get_transform()\n if not trans.contains_branch(self._text2_translate):\n self.label2.set_transform(trans + self._text2_translate)\n\n def _update_padding(self, pad, angle):\n padx = pad * np.cos(angle) / 72\n pady = pad * np.sin(angle) / 72\n self._text1_translate._t = (padx, pady)\n self._text1_translate.invalidate()\n self._text2_translate._t = (-padx, -pady)\n self._text2_translate.invalidate()\n\n def update_position(self, loc):\n super().update_position(loc)\n axes = self.axes\n angle = loc * axes.get_theta_direction() + axes.get_theta_offset()\n text_angle = np.rad2deg(angle) % 360 - 90\n angle -= np.pi / 2\n\n marker = self.tick1line.get_marker()\n if marker in (mmarkers.TICKUP, '|'):\n trans = mtransforms.Affine2D().scale(1, 1).rotate(angle)\n elif marker == mmarkers.TICKDOWN:\n trans = mtransforms.Affine2D().scale(1, -1).rotate(angle)\n else:\n # Don't modify custom tick line markers.\n trans = self.tick1line._marker._transform\n self.tick1line._marker._transform = trans\n\n marker = self.tick2line.get_marker()\n if marker in (mmarkers.TICKUP, '|'):\n trans = mtransforms.Affine2D().scale(1, 1).rotate(angle)\n elif marker == mmarkers.TICKDOWN:\n trans = mtransforms.Affine2D().scale(1, -1).rotate(angle)\n else:\n # Don't modify custom tick line markers.\n trans = self.tick2line._marker._transform\n self.tick2line._marker._transform = trans\n\n mode, user_angle = self._labelrotation\n if mode == 'default':\n text_angle = user_angle\n else:\n if text_angle > 90:\n text_angle -= 180\n elif text_angle < -90:\n text_angle += 180\n text_angle += user_angle\n self.label1.set_rotation(text_angle)\n self.label2.set_rotation(text_angle)\n\n # This extra padding helps preserve the look from previous releases but\n # is also needed because labels are anchored to their center.\n pad = self._pad + 7\n self._update_padding(pad,\n self._loc * axes.get_theta_direction() +\n axes.get_theta_offset())\n\n\nclass ThetaAxis(maxis.XAxis):\n """\n A theta Axis.\n\n This overrides certain properties of an `.XAxis` to provide special-casing\n for an angular axis.\n """\n __name__ = 'thetaaxis'\n axis_name = 'theta' #: Read-only name identifying the axis.\n _tick_class = ThetaTick\n\n def _wrap_locator_formatter(self):\n self.set_major_locator(ThetaLocator(self.get_major_locator()))\n self.set_major_formatter(ThetaFormatter())\n self.isDefault_majloc = True\n self.isDefault_majfmt = True\n\n def clear(self):\n # docstring inherited\n super().clear()\n self.set_ticks_position('none')\n self._wrap_locator_formatter()\n\n def _set_scale(self, value, **kwargs):\n if value != 'linear':\n raise NotImplementedError(\n "The xscale cannot be set on a polar plot")\n super()._set_scale(value, **kwargs)\n # LinearScale.set_default_locators_and_formatters just set the major\n # locator to be an AutoLocator, so we customize it here to have ticks\n # at sensible degree multiples.\n self.get_major_locator().set_params(steps=[1, 1.5, 3, 4.5, 9, 10])\n self._wrap_locator_formatter()\n\n def _copy_tick_props(self, src, dest):\n """Copy the props from src tick to dest tick."""\n if src is None or dest is None:\n return\n super()._copy_tick_props(src, dest)\n\n # Ensure that tick transforms are independent so that padding works.\n trans = dest._get_text1_transform()[0]\n dest.label1.set_transform(trans + dest._text1_translate)\n trans = dest._get_text2_transform()[0]\n dest.label2.set_transform(trans + dest._text2_translate)\n\n\nclass RadialLocator(mticker.Locator):\n """\n Used to locate radius ticks.\n\n Ensures that all ticks are strictly positive. For all other tasks, it\n delegates to the base `.Locator` (which may be different depending on the\n scale of the *r*-axis).\n """\n\n def __init__(self, base, axes=None):\n self.base = base\n self._axes = axes\n\n def set_axis(self, axis):\n self.base.set_axis(axis)\n\n def __call__(self):\n # Ensure previous behaviour with full circle non-annular views.\n if self._axes:\n if _is_full_circle_rad(*self._axes.viewLim.intervalx):\n rorigin = self._axes.get_rorigin() * self._axes.get_rsign()\n if self._axes.get_rmin() <= rorigin:\n return [tick for tick in self.base() if tick > rorigin]\n return self.base()\n\n def _zero_in_bounds(self):\n """\n Return True if zero is within the valid values for the\n scale of the radial axis.\n """\n vmin, vmax = self._axes.yaxis._scale.limit_range_for_scale(0, 1, 1e-5)\n return vmin == 0\n\n def nonsingular(self, vmin, vmax):\n # docstring inherited\n if self._zero_in_bounds() and (vmin, vmax) == (-np.inf, np.inf):\n # Initial view limits\n return (0, 1)\n else:\n return self.base.nonsingular(vmin, vmax)\n\n def view_limits(self, vmin, vmax):\n vmin, vmax = self.base.view_limits(vmin, vmax)\n if self._zero_in_bounds() and vmax > vmin:\n # this allows inverted r/y-lims\n vmin = min(0, vmin)\n return mtransforms.nonsingular(vmin, vmax)\n\n\nclass _ThetaShift(mtransforms.ScaledTranslation):\n """\n Apply a padding shift based on axes theta limits.\n\n This is used to create padding for radial ticks.\n\n Parameters\n ----------\n axes : `~matplotlib.axes.Axes`\n The owning Axes; used to determine limits.\n pad : float\n The padding to apply, in points.\n mode : {'min', 'max', 'rlabel'}\n Whether to shift away from the start (``'min'``) or the end (``'max'``)\n of the axes, or using the rlabel position (``'rlabel'``).\n """\n def __init__(self, axes, pad, mode):\n super().__init__(pad, pad, axes.get_figure(root=False).dpi_scale_trans)\n self.set_children(axes._realViewLim)\n self.axes = axes\n self.mode = mode\n self.pad = pad\n\n __str__ = mtransforms._make_str_method("axes", "pad", "mode")\n\n def get_matrix(self):\n if self._invalid:\n if self.mode == 'rlabel':\n angle = (\n np.deg2rad(self.axes.get_rlabel_position()\n * self.axes.get_theta_direction())\n + self.axes.get_theta_offset()\n - np.pi / 2\n )\n elif self.mode == 'min':\n angle = self.axes._realViewLim.xmin - np.pi / 2\n elif self.mode == 'max':\n angle = self.axes._realViewLim.xmax + np.pi / 2\n self._t = (self.pad * np.cos(angle) / 72, self.pad * np.sin(angle) / 72)\n return super().get_matrix()\n\n\nclass RadialTick(maxis.YTick):\n """\n A radial-axis tick.\n\n This subclass of `.YTick` provides radial ticks with some small\n modification to their re-positioning such that ticks are rotated based on\n axes limits. This results in ticks that are correctly perpendicular to\n the spine. Labels are also rotated to be perpendicular to the spine, when\n 'auto' rotation is enabled.\n """\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.label1.set_rotation_mode('anchor')\n self.label2.set_rotation_mode('anchor')\n\n def _determine_anchor(self, mode, angle, start):\n # Note: angle is the (spine angle - 90) because it's used for the tick\n # & text setup, so all numbers below are -90 from (normed) spine angle.\n if mode == 'auto':\n if start:\n if -90 <= angle <= 90:\n return 'left', 'center'\n else:\n return 'right', 'center'\n else:\n if -90 <= angle <= 90:\n return 'right', 'center'\n else:\n return 'left', 'center'\n else:\n if start:\n if angle < -68.5:\n return 'center', 'top'\n elif angle < -23.5:\n return 'left', 'top'\n elif angle < 22.5:\n return 'left', 'center'\n elif angle < 67.5:\n return 'left', 'bottom'\n elif angle < 112.5:\n return 'center', 'bottom'\n elif angle < 157.5:\n return 'right', 'bottom'\n elif angle < 202.5:\n return 'right', 'center'\n elif angle < 247.5:\n return 'right', 'top'\n else:\n return 'center', 'top'\n else:\n if angle < -68.5:\n return 'center', 'bottom'\n elif angle < -23.5:\n return 'right', 'bottom'\n elif angle < 22.5:\n return 'right', 'center'\n elif angle < 67.5:\n return 'right', 'top'\n elif angle < 112.5:\n return 'center', 'top'\n elif angle < 157.5:\n return 'left', 'top'\n elif angle < 202.5:\n return 'left', 'center'\n elif angle < 247.5:\n return 'left', 'bottom'\n else:\n return 'center', 'bottom'\n\n def update_position(self, loc):\n super().update_position(loc)\n axes = self.axes\n thetamin = axes.get_thetamin()\n thetamax = axes.get_thetamax()\n direction = axes.get_theta_direction()\n offset_rad = axes.get_theta_offset()\n offset = np.rad2deg(offset_rad)\n full = _is_full_circle_deg(thetamin, thetamax)\n\n if full:\n angle = (axes.get_rlabel_position() * direction +\n offset) % 360 - 90\n tick_angle = 0\n else:\n angle = (thetamin * direction + offset) % 360 - 90\n if direction > 0:\n tick_angle = np.deg2rad(angle)\n else:\n tick_angle = np.deg2rad(angle + 180)\n text_angle = (angle + 90) % 180 - 90 # between -90 and +90.\n mode, user_angle = self._labelrotation\n if mode == 'auto':\n text_angle += user_angle\n else:\n text_angle = user_angle\n\n if full:\n ha = self.label1.get_horizontalalignment()\n va = self.label1.get_verticalalignment()\n else:\n ha, va = self._determine_anchor(mode, angle, direction > 0)\n self.label1.set_horizontalalignment(ha)\n self.label1.set_verticalalignment(va)\n self.label1.set_rotation(text_angle)\n\n marker = self.tick1line.get_marker()\n if marker == mmarkers.TICKLEFT:\n trans = mtransforms.Affine2D().rotate(tick_angle)\n elif marker == '_':\n trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)\n elif marker == mmarkers.TICKRIGHT:\n trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)\n else:\n # Don't modify custom tick line markers.\n trans = self.tick1line._marker._transform\n self.tick1line._marker._transform = trans\n\n if full:\n self.label2.set_visible(False)\n self.tick2line.set_visible(False)\n angle = (thetamax * direction + offset) % 360 - 90\n if direction > 0:\n tick_angle = np.deg2rad(angle)\n else:\n tick_angle = np.deg2rad(angle + 180)\n text_angle = (angle + 90) % 180 - 90 # between -90 and +90.\n mode, user_angle = self._labelrotation\n if mode == 'auto':\n text_angle += user_angle\n else:\n text_angle = user_angle\n\n ha, va = self._determine_anchor(mode, angle, direction < 0)\n self.label2.set_ha(ha)\n self.label2.set_va(va)\n self.label2.set_rotation(text_angle)\n\n marker = self.tick2line.get_marker()\n if marker == mmarkers.TICKLEFT:\n trans = mtransforms.Affine2D().rotate(tick_angle)\n elif marker == '_':\n trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)\n elif marker == mmarkers.TICKRIGHT:\n trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)\n else:\n # Don't modify custom tick line markers.\n trans = self.tick2line._marker._transform\n self.tick2line._marker._transform = trans\n\n\nclass RadialAxis(maxis.YAxis):\n """\n A radial Axis.\n\n This overrides certain properties of a `.YAxis` to provide special-casing\n for a radial axis.\n """\n __name__ = 'radialaxis'\n axis_name = 'radius' #: Read-only name identifying the axis.\n _tick_class = RadialTick\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.sticky_edges.y.append(0)\n\n def _wrap_locator_formatter(self):\n self.set_major_locator(RadialLocator(self.get_major_locator(),\n self.axes))\n self.isDefault_majloc = True\n\n def clear(self):\n # docstring inherited\n super().clear()\n self.set_ticks_position('none')\n self._wrap_locator_formatter()\n\n def _set_scale(self, value, **kwargs):\n super()._set_scale(value, **kwargs)\n self._wrap_locator_formatter()\n\n\ndef _is_full_circle_deg(thetamin, thetamax):\n """\n Determine if a wedge (in degrees) spans the full circle.\n\n The condition is derived from :class:`~matplotlib.patches.Wedge`.\n """\n return abs(abs(thetamax - thetamin) - 360.0) < 1e-12\n\n\ndef _is_full_circle_rad(thetamin, thetamax):\n """\n Determine if a wedge (in radians) spans the full circle.\n\n The condition is derived from :class:`~matplotlib.patches.Wedge`.\n """\n return abs(abs(thetamax - thetamin) - 2 * np.pi) < 1.74e-14\n\n\nclass _WedgeBbox(mtransforms.Bbox):\n """\n Transform (theta, r) wedge Bbox into Axes bounding box.\n\n Parameters\n ----------\n center : (float, float)\n Center of the wedge\n viewLim : `~matplotlib.transforms.Bbox`\n Bbox determining the boundaries of the wedge\n originLim : `~matplotlib.transforms.Bbox`\n Bbox determining the origin for the wedge, if different from *viewLim*\n """\n def __init__(self, center, viewLim, originLim, **kwargs):\n super().__init__([[0, 0], [1, 1]], **kwargs)\n self._center = center\n self._viewLim = viewLim\n self._originLim = originLim\n self.set_children(viewLim, originLim)\n\n __str__ = mtransforms._make_str_method("_center", "_viewLim", "_originLim")\n\n def get_points(self):\n # docstring inherited\n if self._invalid:\n points = self._viewLim.get_points().copy()\n # Scale angular limits to work with Wedge.\n points[:, 0] *= 180 / np.pi\n if points[0, 0] > points[1, 0]:\n points[:, 0] = points[::-1, 0]\n\n # Scale radial limits based on origin radius.\n points[:, 1] -= self._originLim.y0\n\n # Scale radial limits to match axes limits.\n rscale = 0.5 / points[1, 1]\n points[:, 1] *= rscale\n width = min(points[1, 1] - points[0, 1], 0.5)\n\n # Generate bounding box for wedge.\n wedge = mpatches.Wedge(self._center, points[1, 1],\n points[0, 0], points[1, 0],\n width=width)\n self.update_from_path(wedge.get_path())\n\n # Ensure equal aspect ratio.\n w, h = self._points[1] - self._points[0]\n deltah = max(w - h, 0) / 2\n deltaw = max(h - w, 0) / 2\n self._points += np.array([[-deltaw, -deltah], [deltaw, deltah]])\n\n self._invalid = 0\n\n return self._points\n\n\nclass PolarAxes(Axes):\n """\n A polar graph projection, where the input dimensions are *theta*, *r*.\n\n Theta starts pointing east and goes anti-clockwise.\n """\n name = 'polar'\n\n def __init__(self, *args,\n theta_offset=0, theta_direction=1, rlabel_position=22.5,\n **kwargs):\n # docstring inherited\n self._default_theta_offset = theta_offset\n self._default_theta_direction = theta_direction\n self._default_rlabel_position = np.deg2rad(rlabel_position)\n super().__init__(*args, **kwargs)\n self.use_sticky_edges = True\n self.set_aspect('equal', adjustable='box', anchor='C')\n self.clear()\n\n def clear(self):\n # docstring inherited\n super().clear()\n\n self.title.set_y(1.05)\n\n start = self.spines.get('start', None)\n if start:\n start.set_visible(False)\n end = self.spines.get('end', None)\n if end:\n end.set_visible(False)\n self.set_xlim(0.0, 2 * np.pi)\n\n self.grid(mpl.rcParams['polaraxes.grid'])\n inner = self.spines.get('inner', None)\n if inner:\n inner.set_visible(False)\n\n self.set_rorigin(None)\n self.set_theta_offset(self._default_theta_offset)\n self.set_theta_direction(self._default_theta_direction)\n\n def _init_axis(self):\n # This is moved out of __init__ because non-separable axes don't use it\n self.xaxis = ThetaAxis(self, clear=False)\n self.yaxis = RadialAxis(self, clear=False)\n self.spines['polar'].register_axis(self.yaxis)\n\n def _set_lim_and_transforms(self):\n # A view limit where the minimum radius can be locked if the user\n # specifies an alternate origin.\n self._originViewLim = mtransforms.LockableBbox(self.viewLim)\n\n # Handle angular offset and direction.\n self._direction = mtransforms.Affine2D() \\n .scale(self._default_theta_direction, 1.0)\n self._theta_offset = mtransforms.Affine2D() \\n .translate(self._default_theta_offset, 0.0)\n self.transShift = self._direction + self._theta_offset\n # A view limit shifted to the correct location after accounting for\n # orientation and offset.\n self._realViewLim = mtransforms.TransformedBbox(self.viewLim,\n self.transShift)\n\n # Transforms the x and y axis separately by a scale factor\n # It is assumed that this part will have non-linear components\n self.transScale = mtransforms.TransformWrapper(\n mtransforms.IdentityTransform())\n\n # Scale view limit into a bbox around the selected wedge. This may be\n # smaller than the usual unit axes rectangle if not plotting the full\n # circle.\n self.axesLim = _WedgeBbox((0.5, 0.5),\n self._realViewLim, self._originViewLim)\n\n # Scale the wedge to fill the axes.\n self.transWedge = mtransforms.BboxTransformFrom(self.axesLim)\n\n # Scale the axes to fill the figure.\n self.transAxes = mtransforms.BboxTransformTo(self.bbox)\n\n # A (possibly non-linear) projection on the (already scaled)\n # data. This one is aware of rmin\n self.transProjection = self.PolarTransform(\n self,\n apply_theta_transforms=False,\n scale_transform=self.transScale\n )\n # Add dependency on rorigin.\n self.transProjection.set_children(self._originViewLim)\n\n # An affine transformation on the data, generally to limit the\n # range of the axes\n self.transProjectionAffine = self.PolarAffine(self.transScale,\n self._originViewLim)\n\n # The complete data transformation stack -- from data all the\n # way to display coordinates\n #\n # 1. Remove any radial axis scaling (e.g. log scaling)\n # 2. Shift data in the theta direction\n # 3. Project the data from polar to cartesian values\n # (with the origin in the same place)\n # 4. Scale and translate the cartesian values to Axes coordinates\n # (here the origin is moved to the lower left of the Axes)\n # 5. Move and scale to fill the Axes\n # 6. Convert from Axes coordinates to Figure coordinates\n self.transData = (\n self.transScale +\n self.transShift +\n self.transProjection +\n (\n self.transProjectionAffine +\n self.transWedge +\n self.transAxes\n )\n )\n\n # This is the transform for theta-axis ticks. It is\n # equivalent to transData, except it always puts r == 0.0 and r == 1.0\n # at the edge of the axis circles.\n self._xaxis_transform = (\n mtransforms.blended_transform_factory(\n mtransforms.IdentityTransform(),\n mtransforms.BboxTransformTo(self.viewLim)) +\n self.transData)\n # The theta labels are flipped along the radius, so that text 1 is on\n # the outside by default. This should work the same as before.\n flipr_transform = mtransforms.Affine2D() \\n .translate(0.0, -0.5) \\n .scale(1.0, -1.0) \\n .translate(0.0, 0.5)\n self._xaxis_text_transform = flipr_transform + self._xaxis_transform\n\n # This is the transform for r-axis ticks. It scales the theta\n # axis so the gridlines from 0.0 to 1.0, now go from thetamin to\n # thetamax.\n self._yaxis_transform = (\n mtransforms.blended_transform_factory(\n mtransforms.BboxTransformTo(self.viewLim),\n mtransforms.IdentityTransform()) +\n self.transData)\n # The r-axis labels are put at an angle and padded in the r-direction\n self._r_label_position = mtransforms.Affine2D() \\n .translate(self._default_rlabel_position, 0.0)\n self._yaxis_text_transform = mtransforms.TransformWrapper(\n self._r_label_position + self.transData)\n\n def get_xaxis_transform(self, which='grid'):\n _api.check_in_list(['tick1', 'tick2', 'grid'], which=which)\n return self._xaxis_transform\n\n def get_xaxis_text1_transform(self, pad):\n return self._xaxis_text_transform, 'center', 'center'\n\n def get_xaxis_text2_transform(self, pad):\n return self._xaxis_text_transform, 'center', 'center'\n\n def get_yaxis_transform(self, which='grid'):\n if which in ('tick1', 'tick2'):\n return self._yaxis_text_transform\n elif which == 'grid':\n return self._yaxis_transform\n else:\n _api.check_in_list(['tick1', 'tick2', 'grid'], which=which)\n\n def get_yaxis_text1_transform(self, pad):\n thetamin, thetamax = self._realViewLim.intervalx\n if _is_full_circle_rad(thetamin, thetamax):\n return self._yaxis_text_transform, 'bottom', 'left'\n elif self.get_theta_direction() > 0:\n halign = 'left'\n pad_shift = _ThetaShift(self, pad, 'min')\n else:\n halign = 'right'\n pad_shift = _ThetaShift(self, pad, 'max')\n return self._yaxis_text_transform + pad_shift, 'center', halign\n\n def get_yaxis_text2_transform(self, pad):\n if self.get_theta_direction() > 0:\n halign = 'right'\n pad_shift = _ThetaShift(self, pad, 'max')\n else:\n halign = 'left'\n pad_shift = _ThetaShift(self, pad, 'min')\n return self._yaxis_text_transform + pad_shift, 'center', halign\n\n def draw(self, renderer):\n self._unstale_viewLim()\n thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)\n if thetamin > thetamax:\n thetamin, thetamax = thetamax, thetamin\n rmin, rmax = ((self._realViewLim.intervaly - self.get_rorigin()) *\n self.get_rsign())\n if isinstance(self.patch, mpatches.Wedge):\n # Backwards-compatibility: Any subclassed Axes might override the\n # patch to not be the Wedge that PolarAxes uses.\n center = self.transWedge.transform((0.5, 0.5))\n self.patch.set_center(center)\n self.patch.set_theta1(thetamin)\n self.patch.set_theta2(thetamax)\n\n edge, _ = self.transWedge.transform((1, 0))\n radius = edge - center[0]\n width = min(radius * (rmax - rmin) / rmax, radius)\n self.patch.set_radius(radius)\n self.patch.set_width(width)\n\n inner_width = radius - width\n inner = self.spines.get('inner', None)\n if inner:\n inner.set_visible(inner_width != 0.0)\n\n visible = not _is_full_circle_deg(thetamin, thetamax)\n # For backwards compatibility, any subclassed Axes might override the\n # spines to not include start/end that PolarAxes uses.\n start = self.spines.get('start', None)\n end = self.spines.get('end', None)\n if start:\n start.set_visible(visible)\n if end:\n end.set_visible(visible)\n if visible:\n yaxis_text_transform = self._yaxis_transform\n else:\n yaxis_text_transform = self._r_label_position + self.transData\n if self._yaxis_text_transform != yaxis_text_transform:\n self._yaxis_text_transform.set(yaxis_text_transform)\n self.yaxis.reset_ticks()\n self.yaxis.set_clip_path(self.patch)\n\n super().draw(renderer)\n\n def _gen_axes_patch(self):\n return mpatches.Wedge((0.5, 0.5), 0.5, 0.0, 360.0)\n\n def _gen_axes_spines(self):\n spines = {\n 'polar': Spine.arc_spine(self, 'top', (0.5, 0.5), 0.5, 0, 360),\n 'start': Spine.linear_spine(self, 'left'),\n 'end': Spine.linear_spine(self, 'right'),\n 'inner': Spine.arc_spine(self, 'bottom', (0.5, 0.5), 0.0, 0, 360),\n }\n spines['polar'].set_transform(self.transWedge + self.transAxes)\n spines['inner'].set_transform(self.transWedge + self.transAxes)\n spines['start'].set_transform(self._yaxis_transform)\n spines['end'].set_transform(self._yaxis_transform)\n return spines\n\n def set_thetamax(self, thetamax):\n """Set the maximum theta limit in degrees."""\n self.viewLim.x1 = np.deg2rad(thetamax)\n\n def get_thetamax(self):\n """Return the maximum theta limit in degrees."""\n return np.rad2deg(self.viewLim.xmax)\n\n def set_thetamin(self, thetamin):\n """Set the minimum theta limit in degrees."""\n self.viewLim.x0 = np.deg2rad(thetamin)\n\n def get_thetamin(self):\n """Get the minimum theta limit in degrees."""\n return np.rad2deg(self.viewLim.xmin)\n\n def set_thetalim(self, *args, **kwargs):\n r"""\n Set the minimum and maximum theta values.\n\n Can take the following signatures:\n\n - ``set_thetalim(minval, maxval)``: Set the limits in radians.\n - ``set_thetalim(thetamin=minval, thetamax=maxval)``: Set the limits\n in degrees.\n\n where minval and maxval are the minimum and maximum limits. Values are\n wrapped in to the range :math:`[0, 2\pi]` (in radians), so for example\n it is possible to do ``set_thetalim(-np.pi / 2, np.pi / 2)`` to have\n an axis symmetric around 0. A ValueError is raised if the absolute\n angle difference is larger than a full circle.\n """\n orig_lim = self.get_xlim() # in radians\n if 'thetamin' in kwargs:\n kwargs['xmin'] = np.deg2rad(kwargs.pop('thetamin'))\n if 'thetamax' in kwargs:\n kwargs['xmax'] = np.deg2rad(kwargs.pop('thetamax'))\n new_min, new_max = self.set_xlim(*args, **kwargs)\n # Parsing all permutations of *args, **kwargs is tricky; it is simpler\n # to let set_xlim() do it and then validate the limits.\n if abs(new_max - new_min) > 2 * np.pi:\n self.set_xlim(orig_lim) # un-accept the change\n raise ValueError("The angle range must be less than a full circle")\n return tuple(np.rad2deg((new_min, new_max)))\n\n def set_theta_offset(self, offset):\n """\n Set the offset for the location of 0 in radians.\n """\n mtx = self._theta_offset.get_matrix()\n mtx[0, 2] = offset\n self._theta_offset.invalidate()\n\n def get_theta_offset(self):\n """\n Get the offset for the location of 0 in radians.\n """\n return self._theta_offset.get_matrix()[0, 2]\n\n def set_theta_zero_location(self, loc, offset=0.0):\n """\n Set the location of theta's zero.\n\n This simply calls `set_theta_offset` with the correct value in radians.\n\n Parameters\n ----------\n loc : str\n May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE".\n offset : float, default: 0\n An offset in degrees to apply from the specified *loc*. **Note:**\n this offset is *always* applied counter-clockwise regardless of\n the direction setting.\n """\n mapping = {\n 'N': np.pi * 0.5,\n 'NW': np.pi * 0.75,\n 'W': np.pi,\n 'SW': np.pi * 1.25,\n 'S': np.pi * 1.5,\n 'SE': np.pi * 1.75,\n 'E': 0,\n 'NE': np.pi * 0.25}\n return self.set_theta_offset(mapping[loc] + np.deg2rad(offset))\n\n def set_theta_direction(self, direction):\n """\n Set the direction in which theta increases.\n\n clockwise, -1:\n Theta increases in the clockwise direction\n\n counterclockwise, anticlockwise, 1:\n Theta increases in the counterclockwise direction\n """\n mtx = self._direction.get_matrix()\n if direction in ('clockwise', -1):\n mtx[0, 0] = -1\n elif direction in ('counterclockwise', 'anticlockwise', 1):\n mtx[0, 0] = 1\n else:\n _api.check_in_list(\n [-1, 1, 'clockwise', 'counterclockwise', 'anticlockwise'],\n direction=direction)\n self._direction.invalidate()\n\n def get_theta_direction(self):\n """\n Get the direction in which theta increases.\n\n -1:\n Theta increases in the clockwise direction\n\n 1:\n Theta increases in the counterclockwise direction\n """\n return self._direction.get_matrix()[0, 0]\n\n def set_rmax(self, rmax):\n """\n Set the outer radial limit.\n\n Parameters\n ----------\n rmax : float\n """\n self.viewLim.y1 = rmax\n\n def get_rmax(self):\n """\n Returns\n -------\n float\n Outer radial limit.\n """\n return self.viewLim.ymax\n\n def set_rmin(self, rmin):\n """\n Set the inner radial limit.\n\n Parameters\n ----------\n rmin : float\n """\n self.viewLim.y0 = rmin\n\n def get_rmin(self):\n """\n Returns\n -------\n float\n The inner radial limit.\n """\n return self.viewLim.ymin\n\n def set_rorigin(self, rorigin):\n """\n Update the radial origin.\n\n Parameters\n ----------\n rorigin : float\n """\n self._originViewLim.locked_y0 = rorigin\n\n def get_rorigin(self):\n """\n Returns\n -------\n float\n """\n return self._originViewLim.y0\n\n def get_rsign(self):\n return np.sign(self._originViewLim.y1 - self._originViewLim.y0)\n\n def set_rlim(self, bottom=None, top=None, *,\n emit=True, auto=False, **kwargs):\n """\n Set the radial axis view limits.\n\n This function behaves like `.Axes.set_ylim`, but additionally supports\n *rmin* and *rmax* as aliases for *bottom* and *top*.\n\n See Also\n --------\n .Axes.set_ylim\n """\n if 'rmin' in kwargs:\n if bottom is None:\n bottom = kwargs.pop('rmin')\n else:\n raise ValueError('Cannot supply both positional "bottom"'\n 'argument and kwarg "rmin"')\n if 'rmax' in kwargs:\n if top is None:\n top = kwargs.pop('rmax')\n else:\n raise ValueError('Cannot supply both positional "top"'\n 'argument and kwarg "rmax"')\n return self.set_ylim(bottom=bottom, top=top, emit=emit, auto=auto,\n **kwargs)\n\n def get_rlabel_position(self):\n """\n Returns\n -------\n float\n The theta position of the radius labels in degrees.\n """\n return np.rad2deg(self._r_label_position.get_matrix()[0, 2])\n\n def set_rlabel_position(self, value):\n """\n Update the theta position of the radius labels.\n\n Parameters\n ----------\n value : number\n The angular position of the radius labels in degrees.\n """\n self._r_label_position.clear().translate(np.deg2rad(value), 0.0)\n\n def set_yscale(self, *args, **kwargs):\n super().set_yscale(*args, **kwargs)\n self.yaxis.set_major_locator(\n self.RadialLocator(self.yaxis.get_major_locator(), self))\n\n def set_rscale(self, *args, **kwargs):\n return Axes.set_yscale(self, *args, **kwargs)\n\n def set_rticks(self, *args, **kwargs):\n return Axes.set_yticks(self, *args, **kwargs)\n\n def set_thetagrids(self, angles, labels=None, fmt=None, **kwargs):\n """\n Set the theta gridlines in a polar plot.\n\n Parameters\n ----------\n angles : tuple with floats, degrees\n The angles of the theta gridlines.\n\n labels : tuple with strings or None\n The labels to use at each theta gridline. The\n `.projections.polar.ThetaFormatter` will be used if None.\n\n fmt : str or None\n Format string used in `matplotlib.ticker.FormatStrFormatter`.\n For example '%f'. Note that the angle that is used is in\n radians.\n\n Returns\n -------\n lines : list of `.lines.Line2D`\n The theta gridlines.\n\n labels : list of `.text.Text`\n The tick labels.\n\n Other Parameters\n ----------------\n **kwargs\n *kwargs* are optional `.Text` properties for the labels.\n\n .. warning::\n\n This only sets the properties of the current ticks.\n Ticks are not guaranteed to be persistent. Various operations\n can create, delete and modify the Tick instances. There is an\n imminent risk that these settings can get lost if you work on\n the figure further (including also panning/zooming on a\n displayed figure).\n\n Use `.set_tick_params` instead if possible.\n\n See Also\n --------\n .PolarAxes.set_rgrids\n .Axis.get_gridlines\n .Axis.get_ticklabels\n """\n\n # Make sure we take into account unitized data\n angles = self.convert_yunits(angles)\n angles = np.deg2rad(angles)\n self.set_xticks(angles)\n if labels is not None:\n self.set_xticklabels(labels)\n elif fmt is not None:\n self.xaxis.set_major_formatter(mticker.FormatStrFormatter(fmt))\n for t in self.xaxis.get_ticklabels():\n t._internal_update(kwargs)\n return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels()\n\n def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs):\n """\n Set the radial gridlines on a polar plot.\n\n Parameters\n ----------\n radii : tuple with floats\n The radii for the radial gridlines\n\n labels : tuple with strings or None\n The labels to use at each radial gridline. The\n `matplotlib.ticker.ScalarFormatter` will be used if None.\n\n angle : float\n The angular position of the radius labels in degrees.\n\n fmt : str or None\n Format string used in `matplotlib.ticker.FormatStrFormatter`.\n For example '%f'.\n\n Returns\n -------\n lines : list of `.lines.Line2D`\n The radial gridlines.\n\n labels : list of `.text.Text`\n The tick labels.\n\n Other Parameters\n ----------------\n **kwargs\n *kwargs* are optional `.Text` properties for the labels.\n\n .. warning::\n\n This only sets the properties of the current ticks.\n Ticks are not guaranteed to be persistent. Various operations\n can create, delete and modify the Tick instances. There is an\n imminent risk that these settings can get lost if you work on\n the figure further (including also panning/zooming on a\n displayed figure).\n\n Use `.set_tick_params` instead if possible.\n\n See Also\n --------\n .PolarAxes.set_thetagrids\n .Axis.get_gridlines\n .Axis.get_ticklabels\n """\n # Make sure we take into account unitized data\n radii = self.convert_xunits(radii)\n radii = np.asarray(radii)\n\n self.set_yticks(radii)\n if labels is not None:\n self.set_yticklabels(labels)\n elif fmt is not None:\n self.yaxis.set_major_formatter(mticker.FormatStrFormatter(fmt))\n if angle is None:\n angle = self.get_rlabel_position()\n self.set_rlabel_position(angle)\n for t in self.yaxis.get_ticklabels():\n t._internal_update(kwargs)\n return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()\n\n def format_coord(self, theta, r):\n # docstring inherited\n screen_xy = self.transData.transform((theta, r))\n screen_xys = screen_xy + np.stack(\n np.meshgrid([-1, 0, 1], [-1, 0, 1])).reshape((2, -1)).T\n ts, rs = self.transData.inverted().transform(screen_xys).T\n delta_t = abs((ts - theta + np.pi) % (2 * np.pi) - np.pi).max()\n delta_t_halfturns = delta_t / np.pi\n delta_t_degrees = delta_t_halfturns * 180\n delta_r = abs(rs - r).max()\n if theta < 0:\n theta += 2 * np.pi\n theta_halfturns = theta / np.pi\n theta_degrees = theta_halfturns * 180\n\n # See ScalarFormatter.format_data_short. For r, use #g-formatting\n # (as for linear axes), but for theta, use f-formatting as scientific\n # notation doesn't make sense and the trailing dot is ugly.\n def format_sig(value, delta, opt, fmt):\n # For "f", only count digits after decimal point.\n prec = (max(0, -math.floor(math.log10(delta))) if fmt == "f" else\n cbook._g_sig_digits(value, delta))\n return f"{value:-{opt}.{prec}{fmt}}"\n\n # In case fmt_xdata was not specified, resort to default\n\n if self.fmt_ydata is None:\n r_label = format_sig(r, delta_r, "#", "g")\n else:\n r_label = self.format_ydata(r)\n\n if self.fmt_xdata is None:\n return ('\N{GREEK SMALL LETTER THETA}={}\N{GREEK SMALL LETTER PI} '\n '({}\N{DEGREE SIGN}), r={}').format(\n format_sig(theta_halfturns, delta_t_halfturns, "", "f"),\n format_sig(theta_degrees, delta_t_degrees, "", "f"),\n r_label\n )\n else:\n return '\N{GREEK SMALL LETTER THETA}={}, r={}'.format(\n self.format_xdata(theta),\n r_label\n )\n\n def get_data_ratio(self):\n """\n Return the aspect ratio of the data itself. For a polar plot,\n this should always be 1.0\n """\n return 1.0\n\n # # # Interactive panning\n\n def can_zoom(self):\n """\n Return whether this Axes supports the zoom box button functionality.\n\n A polar Axes does not support zoom boxes.\n """\n return False\n\n def can_pan(self):\n """\n Return whether this Axes supports the pan/zoom button functionality.\n\n For a polar Axes, this is slightly misleading. Both panning and\n zooming are performed by the same button. Panning is performed\n in azimuth while zooming is done along the radial.\n """\n return True\n\n def start_pan(self, x, y, button):\n angle = np.deg2rad(self.get_rlabel_position())\n mode = ''\n if button == 1:\n epsilon = np.pi / 45.0\n t, r = self.transData.inverted().transform((x, y))\n if angle - epsilon <= t <= angle + epsilon:\n mode = 'drag_r_labels'\n elif button == 3:\n mode = 'zoom'\n\n self._pan_start = types.SimpleNamespace(\n rmax=self.get_rmax(),\n trans=self.transData.frozen(),\n trans_inverse=self.transData.inverted().frozen(),\n r_label_angle=self.get_rlabel_position(),\n x=x,\n y=y,\n mode=mode)\n\n def end_pan(self):\n del self._pan_start\n\n def drag_pan(self, button, key, x, y):\n p = self._pan_start\n\n if p.mode == 'drag_r_labels':\n (startt, startr), (t, r) = p.trans_inverse.transform(\n [(p.x, p.y), (x, y)])\n\n # Deal with theta\n dt = np.rad2deg(startt - t)\n self.set_rlabel_position(p.r_label_angle - dt)\n\n trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0)\n trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0)\n for t in self.yaxis.majorTicks + self.yaxis.minorTicks:\n t.label1.set_va(vert1)\n t.label1.set_ha(horiz1)\n t.label2.set_va(vert2)\n t.label2.set_ha(horiz2)\n\n elif p.mode == 'zoom':\n (startt, startr), (t, r) = p.trans_inverse.transform(\n [(p.x, p.y), (x, y)])\n\n # Deal with r\n scale = r / startr\n self.set_rmax(p.rmax / scale)\n\n\n# To keep things all self-contained, we can put aliases to the Polar classes\n# defined above. This isn't strictly necessary, but it makes some of the\n# code more readable, and provides a backwards compatible Polar API. In\n# particular, this is used by the :doc:`/gallery/specialty_plots/radar_chart`\n# example to override PolarTransform on a PolarAxes subclass, so make sure that\n# that example is unaffected before changing this.\nPolarAxes.PolarTransform = PolarTransform\nPolarAxes.PolarAffine = PolarAffine\nPolarAxes.InvertedPolarTransform = InvertedPolarTransform\nPolarAxes.ThetaFormatter = ThetaFormatter\nPolarAxes.RadialLocator = RadialLocator\nPolarAxes.ThetaLocator = ThetaLocator\n | .venv\Lib\site-packages\matplotlib\projections\polar.py | polar.py | Python | 56,939 | 0.75 | 0.154143 | 0.086429 | awesome-app | 845 | 2024-03-30T06:27:32.638361 | BSD-3-Clause | false | 3c87ee3312e79360c750ed9be3b461c5 |
import matplotlib.axis as maxis\nimport matplotlib.ticker as mticker\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.axes import Axes\nfrom matplotlib.lines import Line2D\nfrom matplotlib.text import Text\n\nimport numpy as np\nfrom numpy.typing import ArrayLike\nfrom collections.abc import Sequence\nfrom typing import Any, ClassVar, Literal, overload\n\nclass PolarTransform(mtransforms.Transform):\n input_dims: int\n output_dims: int\n def __init__(\n self,\n axis: PolarAxes | None = ...,\n use_rmin: bool = ...,\n *,\n apply_theta_transforms: bool = ...,\n scale_transform: mtransforms.Transform | None = ...,\n ) -> None: ...\n def inverted(self) -> InvertedPolarTransform: ...\n\nclass PolarAffine(mtransforms.Affine2DBase):\n def __init__(\n self, scale_transform: mtransforms.Transform, limits: mtransforms.BboxBase\n ) -> None: ...\n\nclass InvertedPolarTransform(mtransforms.Transform):\n input_dims: int\n output_dims: int\n def __init__(\n self,\n axis: PolarAxes | None = ...,\n use_rmin: bool = ...,\n *,\n apply_theta_transforms: bool = ...,\n ) -> None: ...\n def inverted(self) -> PolarTransform: ...\n\nclass ThetaFormatter(mticker.Formatter): ...\n\nclass _AxisWrapper:\n def __init__(self, axis: maxis.Axis) -> None: ...\n def get_view_interval(self) -> np.ndarray: ...\n def set_view_interval(self, vmin: float, vmax: float) -> None: ...\n def get_minpos(self) -> float: ...\n def get_data_interval(self) -> np.ndarray: ...\n def set_data_interval(self, vmin: float, vmax: float) -> None: ...\n def get_tick_space(self) -> int: ...\n\nclass ThetaLocator(mticker.Locator):\n base: mticker.Locator\n axis: _AxisWrapper | None\n def __init__(self, base: mticker.Locator) -> None: ...\n\nclass ThetaTick(maxis.XTick):\n def __init__(self, axes: PolarAxes, *args, **kwargs) -> None: ...\n\nclass ThetaAxis(maxis.XAxis):\n axis_name: str\n\nclass RadialLocator(mticker.Locator):\n base: mticker.Locator\n def __init__(self, base, axes: PolarAxes | None = ...) -> None: ...\n\nclass RadialTick(maxis.YTick): ...\n\nclass RadialAxis(maxis.YAxis):\n axis_name: str\n\nclass _WedgeBbox(mtransforms.Bbox):\n def __init__(\n self,\n center: tuple[float, float],\n viewLim: mtransforms.Bbox,\n originLim: mtransforms.Bbox,\n **kwargs,\n ) -> None: ...\n\nclass PolarAxes(Axes):\n\n PolarTransform: ClassVar[type] = PolarTransform\n PolarAffine: ClassVar[type] = PolarAffine\n InvertedPolarTransform: ClassVar[type] = InvertedPolarTransform\n ThetaFormatter: ClassVar[type] = ThetaFormatter\n RadialLocator: ClassVar[type] = RadialLocator\n ThetaLocator: ClassVar[type] = ThetaLocator\n\n name: str\n use_sticky_edges: bool\n def __init__(\n self,\n *args,\n theta_offset: float = ...,\n theta_direction: float = ...,\n rlabel_position: float = ...,\n **kwargs,\n ) -> None: ...\n def get_xaxis_transform(\n self, which: Literal["tick1", "tick2", "grid"] = ...\n ) -> mtransforms.Transform: ...\n def get_xaxis_text1_transform(\n self, pad: float\n ) -> tuple[\n mtransforms.Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_xaxis_text2_transform(\n self, pad: float\n ) -> tuple[\n mtransforms.Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_yaxis_transform(\n self, which: Literal["tick1", "tick2", "grid"] = ...\n ) -> mtransforms.Transform: ...\n def get_yaxis_text1_transform(\n self, pad: float\n ) -> tuple[\n mtransforms.Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_yaxis_text2_transform(\n self, pad: float\n ) -> tuple[\n mtransforms.Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def set_thetamax(self, thetamax: float) -> None: ...\n def get_thetamax(self) -> float: ...\n def set_thetamin(self, thetamin: float) -> None: ...\n def get_thetamin(self) -> float: ...\n @overload\n def set_thetalim(self, minval: float, maxval: float, /) -> tuple[float, float]: ...\n @overload\n def set_thetalim(self, *, thetamin: float, thetamax: float) -> tuple[float, float]: ...\n def set_theta_offset(self, offset: float) -> None: ...\n def get_theta_offset(self) -> float: ...\n def set_theta_zero_location(\n self,\n loc: Literal["N", "NW", "W", "SW", "S", "SE", "E", "NE"],\n offset: float = ...,\n ) -> None: ...\n def set_theta_direction(\n self,\n direction: Literal[-1, 1, "clockwise", "counterclockwise", "anticlockwise"],\n ) -> None: ...\n def get_theta_direction(self) -> Literal[-1, 1]: ...\n def set_rmax(self, rmax: float) -> None: ...\n def get_rmax(self) -> float: ...\n def set_rmin(self, rmin: float) -> None: ...\n def get_rmin(self) -> float: ...\n def set_rorigin(self, rorigin: float | None) -> None: ...\n def get_rorigin(self) -> float: ...\n def get_rsign(self) -> float: ...\n def set_rlim(\n self,\n bottom: float | tuple[float, float] | None = ...,\n top: float | None = ...,\n *,\n emit: bool = ...,\n auto: bool = ...,\n **kwargs,\n ) -> tuple[float, float]: ...\n def get_rlabel_position(self) -> float: ...\n def set_rlabel_position(self, value: float) -> None: ...\n def set_rscale(self, *args, **kwargs) -> None: ...\n def set_rticks(self, *args, **kwargs) -> None: ...\n def set_thetagrids(\n self,\n angles: ArrayLike,\n labels: Sequence[str | Text] | None = ...,\n fmt: str | None = ...,\n **kwargs,\n ) -> tuple[list[Line2D], list[Text]]: ...\n def set_rgrids(\n self,\n radii: ArrayLike,\n labels: Sequence[str | Text] | None = ...,\n angle: float | None = ...,\n fmt: str | None = ...,\n **kwargs,\n ) -> tuple[list[Line2D], list[Text]]: ...\n def format_coord(self, theta: float, r: float) -> str: ...\n def get_data_ratio(self) -> float: ...\n def can_zoom(self) -> bool: ...\n def can_pan(self) -> bool: ...\n def start_pan(self, x: float, y: float, button: int) -> None: ...\n def end_pan(self) -> None: ...\n def drag_pan(self, button: Any, key: Any, x: float, y: float) -> None: ...\n | .venv\Lib\site-packages\matplotlib\projections\polar.pyi | polar.pyi | Other | 6,636 | 0.85 | 0.345178 | 0.049724 | react-lib | 735 | 2024-05-21T08:53:46.766665 | BSD-3-Clause | false | f434dc4d59e1b4314be8ac4d3d4147c0 |
"""\nNon-separable transforms that map from data space to screen space.\n\nProjections are defined as `~.axes.Axes` subclasses. They include the\nfollowing elements:\n\n- A transformation from data coordinates into display coordinates.\n\n- An inverse of that transformation. This is used, for example, to convert\n mouse positions from screen space back into data space.\n\n- Transformations for the gridlines, ticks and ticklabels. Custom projections\n will often need to place these elements in special locations, and Matplotlib\n has a facility to help with doing so.\n\n- Setting up default values (overriding `~.axes.Axes.cla`), since the defaults\n for a rectilinear Axes may not be appropriate.\n\n- Defining the shape of the Axes, for example, an elliptical Axes, that will be\n used to draw the background of the plot and for clipping any data elements.\n\n- Defining custom locators and formatters for the projection. For example, in\n a geographic projection, it may be more convenient to display the grid in\n degrees, even if the data is in radians.\n\n- Set up interactive panning and zooming. This is left as an "advanced"\n feature left to the reader, but there is an example of this for polar plots\n in `matplotlib.projections.polar`.\n\n- Any additional methods for additional convenience or features.\n\nOnce the projection Axes is defined, it can be used in one of two ways:\n\n- By defining the class attribute ``name``, the projection Axes can be\n registered with `matplotlib.projections.register_projection` and subsequently\n simply invoked by name::\n\n fig.add_subplot(projection="my_proj_name")\n\n- For more complex, parameterisable projections, a generic "projection" object\n may be defined which includes the method ``_as_mpl_axes``. ``_as_mpl_axes``\n should take no arguments and return the projection's Axes subclass and a\n dictionary of additional arguments to pass to the subclass' ``__init__``\n method. Subsequently a parameterised projection can be initialised with::\n\n fig.add_subplot(projection=MyProjection(param1=param1_value))\n\n where MyProjection is an object which implements a ``_as_mpl_axes`` method.\n\nA full-fledged and heavily annotated example is in\n:doc:`/gallery/misc/custom_projection`. The polar plot functionality in\n`matplotlib.projections.polar` may also be of interest.\n"""\n\nfrom .. import axes, _docstring\nfrom .geo import AitoffAxes, HammerAxes, LambertAxes, MollweideAxes\nfrom .polar import PolarAxes\n\ntry:\n from mpl_toolkits.mplot3d import Axes3D\nexcept Exception:\n import warnings\n warnings.warn("Unable to import Axes3D. This may be due to multiple versions of "\n "Matplotlib being installed (e.g. as a system package and as a pip "\n "package). As a result, the 3D projection is not available.")\n Axes3D = None\n\n\nclass ProjectionRegistry:\n """A mapping of registered projection names to projection classes."""\n\n def __init__(self):\n self._all_projection_types = {}\n\n def register(self, *projections):\n """Register a new set of projections."""\n for projection in projections:\n name = projection.name\n self._all_projection_types[name] = projection\n\n def get_projection_class(self, name):\n """Get a projection class from its *name*."""\n return self._all_projection_types[name]\n\n def get_projection_names(self):\n """Return the names of all projections currently registered."""\n return sorted(self._all_projection_types)\n\n\nprojection_registry = ProjectionRegistry()\nprojection_registry.register(\n axes.Axes,\n PolarAxes,\n AitoffAxes,\n HammerAxes,\n LambertAxes,\n MollweideAxes,\n)\nif Axes3D is not None:\n projection_registry.register(Axes3D)\nelse:\n # remove from namespace if not importable\n del Axes3D\n\n\ndef register_projection(cls):\n projection_registry.register(cls)\n\n\ndef get_projection_class(projection=None):\n """\n Get a projection class from its name.\n\n If *projection* is None, a standard rectilinear projection is returned.\n """\n if projection is None:\n projection = 'rectilinear'\n\n try:\n return projection_registry.get_projection_class(projection)\n except KeyError as err:\n raise ValueError("Unknown projection %r" % projection) from err\n\n\nget_projection_names = projection_registry.get_projection_names\n_docstring.interpd.register(projection_names=get_projection_names())\n | .venv\Lib\site-packages\matplotlib\projections\__init__.py | __init__.py | Python | 4,438 | 0.95 | 0.198413 | 0.01087 | vue-tools | 211 | 2023-10-06T17:44:53.701094 | GPL-3.0 | false | 7bbbcddf7ae9f240df1d4caef12e0bd2 |
from .geo import (\n AitoffAxes as AitoffAxes,\n HammerAxes as HammerAxes,\n LambertAxes as LambertAxes,\n MollweideAxes as MollweideAxes,\n)\nfrom .polar import PolarAxes as PolarAxes\nfrom ..axes import Axes\n\nclass ProjectionRegistry:\n def __init__(self) -> None: ...\n def register(self, *projections: type[Axes]) -> None: ...\n def get_projection_class(self, name: str) -> type[Axes]: ...\n def get_projection_names(self) -> list[str]: ...\n\nprojection_registry: ProjectionRegistry\n\ndef register_projection(cls: type[Axes]) -> None: ...\ndef get_projection_class(projection: str | None = ...) -> type[Axes]: ...\ndef get_projection_names() -> list[str]: ...\n | .venv\Lib\site-packages\matplotlib\projections\__init__.pyi | __init__.pyi | Other | 673 | 0.85 | 0.4 | 0 | vue-tools | 988 | 2024-02-25T00:01:28.067806 | GPL-3.0 | false | 552dac1c73e7d8b2e8b018c705d1dc24 |
\n\n | .venv\Lib\site-packages\matplotlib\projections\__pycache__\geo.cpython-313.pyc | geo.cpython-313.pyc | Other | 30,150 | 0.95 | 0.007605 | 0.004167 | react-lib | 699 | 2024-06-29T16:28:51.345656 | BSD-3-Clause | false | 3731d4468e125dd19032cd25d975c9ad |
\n\n | .venv\Lib\site-packages\matplotlib\projections\__pycache__\polar.cpython-313.pyc | polar.cpython-313.pyc | Other | 74,110 | 0.75 | 0.035398 | 0.006039 | python-kit | 688 | 2024-06-01T10:55:56.972081 | BSD-3-Clause | false | a982a3e1f37089072b28dfd472bdef6f |
\n\n | .venv\Lib\site-packages\matplotlib\projections\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 5,542 | 0.95 | 0.148148 | 0 | node-utils | 752 | 2024-03-09T18:29:42.072638 | MIT | false | ed0fbea322367c975608d204fe2ebad3 |
"""\nAdd a ``figure-mpl`` directive that is a responsive version of ``figure``.\n\nThis implementation is very similar to ``.. figure::``, except it also allows a\n``srcset=`` argument to be passed to the image tag, hence allowing responsive\nresolution images.\n\nThere is no particular reason this could not be used standalone, but is meant\nto be used with :doc:`/api/sphinxext_plot_directive_api`.\n\nNote that the directory organization is a bit different than ``.. figure::``.\nSee the *FigureMpl* documentation below.\n\n"""\nimport os\nfrom os.path import relpath\nfrom pathlib import PurePath, Path\nimport shutil\n\nfrom docutils import nodes\nfrom docutils.parsers.rst import directives\nfrom docutils.parsers.rst.directives.images import Figure, Image\nfrom sphinx.errors import ExtensionError\n\nimport matplotlib\n\n\nclass figmplnode(nodes.General, nodes.Element):\n pass\n\n\nclass FigureMpl(Figure):\n """\n Implements a directive to allow an optional hidpi image.\n\n Meant to be used with the *plot_srcset* configuration option in conf.py,\n and gets set in the TEMPLATE of plot_directive.py\n\n e.g.::\n\n .. figure-mpl:: plot_directive/some_plots-1.png\n :alt: bar\n :srcset: plot_directive/some_plots-1.png,\n plot_directive/some_plots-1.2x.png 2.00x\n :class: plot-directive\n\n The resulting html (at ``some_plots.html``) is::\n\n <img src="sphx_glr_bar_001_hidpi.png"\n srcset="_images/some_plot-1.png,\n _images/some_plots-1.2x.png 2.00x",\n alt="bar"\n class="plot_directive" />\n\n Note that the handling of subdirectories is different than that used by the sphinx\n figure directive::\n\n .. figure-mpl:: plot_directive/nestedpage/index-1.png\n :alt: bar\n :srcset: plot_directive/nestedpage/index-1.png\n plot_directive/nestedpage/index-1.2x.png 2.00x\n :class: plot_directive\n\n The resulting html (at ``nestedpage/index.html``)::\n\n <img src="../_images/nestedpage-index-1.png"\n srcset="../_images/nestedpage-index-1.png,\n ../_images/_images/nestedpage-index-1.2x.png 2.00x",\n alt="bar"\n class="sphx-glr-single-img" />\n\n where the subdirectory is included in the image name for uniqueness.\n """\n\n has_content = False\n required_arguments = 1\n optional_arguments = 2\n final_argument_whitespace = False\n option_spec = {\n 'alt': directives.unchanged,\n 'height': directives.length_or_unitless,\n 'width': directives.length_or_percentage_or_unitless,\n 'scale': directives.nonnegative_int,\n 'align': Image.align,\n 'class': directives.class_option,\n 'caption': directives.unchanged,\n 'srcset': directives.unchanged,\n }\n\n def run(self):\n\n image_node = figmplnode()\n\n imagenm = self.arguments[0]\n image_node['alt'] = self.options.get('alt', '')\n image_node['align'] = self.options.get('align', None)\n image_node['class'] = self.options.get('class', None)\n image_node['width'] = self.options.get('width', None)\n image_node['height'] = self.options.get('height', None)\n image_node['scale'] = self.options.get('scale', None)\n image_node['caption'] = self.options.get('caption', None)\n\n # we would like uri to be the highest dpi version so that\n # latex etc will use that. But for now, lets just make\n # imagenm... maybe pdf one day?\n\n image_node['uri'] = imagenm\n image_node['srcset'] = self.options.get('srcset', None)\n\n return [image_node]\n\n\ndef _parse_srcsetNodes(st):\n """\n parse srcset...\n """\n entries = st.split(',')\n srcset = {}\n for entry in entries:\n spl = entry.strip().split(' ')\n if len(spl) == 1:\n srcset[0] = spl[0]\n elif len(spl) == 2:\n mult = spl[1][:-1]\n srcset[float(mult)] = spl[0]\n else:\n raise ExtensionError(f'srcset argument "{entry}" is invalid.')\n return srcset\n\n\ndef _copy_images_figmpl(self, node):\n\n # these will be the temporary place the plot-directive put the images eg:\n # ../../../build/html/plot_directive/users/explain/artists/index-1.png\n if node['srcset']:\n srcset = _parse_srcsetNodes(node['srcset'])\n else:\n srcset = None\n\n # the rst file's location: eg /Users/username/matplotlib/doc/users/explain/artists\n docsource = PurePath(self.document['source']).parent\n\n # get the relpath relative to root:\n srctop = self.builder.srcdir\n rel = relpath(docsource, srctop).replace('.', '').replace(os.sep, '-')\n if len(rel):\n rel += '-'\n # eg: users/explain/artists\n\n imagedir = PurePath(self.builder.outdir, self.builder.imagedir)\n # eg: /Users/username/matplotlib/doc/build/html/_images/users/explain/artists\n\n Path(imagedir).mkdir(parents=True, exist_ok=True)\n\n # copy all the sources to the imagedir:\n if srcset:\n for src in srcset.values():\n # the entries in srcset are relative to docsource's directory\n abspath = PurePath(docsource, src)\n name = rel + abspath.name\n shutil.copyfile(abspath, imagedir / name)\n else:\n abspath = PurePath(docsource, node['uri'])\n name = rel + abspath.name\n shutil.copyfile(abspath, imagedir / name)\n\n return imagedir, srcset, rel\n\n\ndef visit_figmpl_html(self, node):\n\n imagedir, srcset, rel = _copy_images_figmpl(self, node)\n\n # /doc/examples/subd/plot_1.rst\n docsource = PurePath(self.document['source'])\n # /doc/\n # make sure to add the trailing slash:\n srctop = PurePath(self.builder.srcdir, '')\n # examples/subd/plot_1.rst\n relsource = relpath(docsource, srctop)\n # /doc/build/html\n desttop = PurePath(self.builder.outdir, '')\n # /doc/build/html/examples/subd\n dest = desttop / relsource\n\n # ../../_images/ for dirhtml and ../_images/ for html\n imagerel = PurePath(relpath(imagedir, dest.parent)).as_posix()\n if self.builder.name == "dirhtml":\n imagerel = f'..{imagerel}'\n\n # make uri also be relative...\n nm = PurePath(node['uri'][1:]).name\n uri = f'{imagerel}/{rel}{nm}'\n img_attrs = {'src': uri, 'alt': node['alt']}\n\n # make srcset str. Need to change all the prefixes!\n maxsrc = uri\n if srcset:\n maxmult = -1\n srcsetst = ''\n for mult, src in srcset.items():\n nm = PurePath(src[1:]).name\n # ../../_images/plot_1_2_0x.png\n path = f'{imagerel}/{rel}{nm}'\n srcsetst += path\n if mult == 0:\n srcsetst += ', '\n else:\n srcsetst += f' {mult:1.2f}x, '\n\n if mult > maxmult:\n maxmult = mult\n maxsrc = path\n\n # trim trailing comma and space...\n img_attrs['srcset'] = srcsetst[:-2]\n\n if node['class'] is not None:\n img_attrs['class'] = ' '.join(node['class'])\n for style in ['width', 'height', 'scale']:\n if node[style]:\n if 'style' not in img_attrs:\n img_attrs['style'] = f'{style}: {node[style]};'\n else:\n img_attrs['style'] += f'{style}: {node[style]};'\n\n # <figure class="align-default" id="id1">\n # <a class="reference internal image-reference" href="_images/index-1.2x.png">\n # <img alt="_images/index-1.2x.png"\n # src="_images/index-1.2x.png" style="width: 53%;" />\n # </a>\n # <figcaption>\n # <p><span class="caption-text">Figure caption is here....</span>\n # <a class="headerlink" href="#id1" title="Permalink to this image">#</a></p>\n # </figcaption>\n # </figure>\n self.body.append(\n self.starttag(\n node, 'figure',\n CLASS=f'align-{node["align"]}' if node['align'] else 'align-center'))\n self.body.append(\n self.starttag(node, 'a', CLASS='reference internal image-reference',\n href=maxsrc) +\n self.emptytag(node, 'img', **img_attrs) +\n '</a>\n')\n if node['caption']:\n self.body.append(self.starttag(node, 'figcaption'))\n self.body.append(self.starttag(node, 'p'))\n self.body.append(self.starttag(node, 'span', CLASS='caption-text'))\n self.body.append(node['caption'])\n self.body.append('</span></p></figcaption>\n')\n self.body.append('</figure>\n')\n\n\ndef visit_figmpl_latex(self, node):\n\n if node['srcset'] is not None:\n imagedir, srcset = _copy_images_figmpl(self, node)\n maxmult = -1\n # choose the highest res version for latex:\n maxmult = max(srcset, default=-1)\n node['uri'] = PurePath(srcset[maxmult]).name\n\n self.visit_figure(node)\n\n\ndef depart_figmpl_html(self, node):\n pass\n\n\ndef depart_figmpl_latex(self, node):\n self.depart_figure(node)\n\n\ndef figurempl_addnode(app):\n app.add_node(figmplnode,\n html=(visit_figmpl_html, depart_figmpl_html),\n latex=(visit_figmpl_latex, depart_figmpl_latex))\n\n\ndef setup(app):\n app.add_directive("figure-mpl", FigureMpl)\n figurempl_addnode(app)\n metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,\n 'version': matplotlib.__version__}\n return metadata\n | .venv\Lib\site-packages\matplotlib\sphinxext\figmpl_directive.py | figmpl_directive.py | Python | 9,308 | 0.95 | 0.167832 | 0.146667 | python-kit | 702 | 2024-10-20T16:58:28.668765 | GPL-3.0 | false | dfed8a7497cbfbf7e59576e5ea8897ec |
r"""\nA role and directive to display mathtext in Sphinx\n==================================================\n\nThe ``mathmpl`` Sphinx extension creates a mathtext image in Matplotlib and\nshows it in html output. Thus, it is a true and faithful representation of what\nyou will see if you pass a given LaTeX string to Matplotlib (see\n:ref:`mathtext`).\n\n.. warning::\n In most cases, you will likely want to use one of `Sphinx's builtin Math\n extensions\n <https://www.sphinx-doc.org/en/master/usage/extensions/math.html>`__\n instead of this one. The builtin Sphinx math directive uses MathJax to\n render mathematical expressions, and addresses accessibility concerns that\n ``mathmpl`` doesn't address.\n\nMathtext may be included in two ways:\n\n1. Inline, using the role::\n\n This text uses inline math: :mathmpl:`\alpha > \beta`.\n\n which produces:\n\n This text uses inline math: :mathmpl:`\alpha > \beta`.\n\n2. Standalone, using the directive::\n\n Here is some standalone math:\n\n .. mathmpl::\n\n \alpha > \beta\n\n which produces:\n\n Here is some standalone math:\n\n .. mathmpl::\n\n \alpha > \beta\n\nOptions\n-------\n\nThe ``mathmpl`` role and directive both support the following options:\n\nfontset : str, default: 'cm'\n The font set to use when displaying math. See :rc:`mathtext.fontset`.\n\nfontsize : float\n The font size, in points. Defaults to the value from the extension\n configuration option defined below.\n\nConfiguration options\n---------------------\n\nThe mathtext extension has the following configuration options:\n\nmathmpl_fontsize : float, default: 10.0\n Default font size, in points.\n\nmathmpl_srcset : list of str, default: []\n Additional image sizes to generate when embedding in HTML, to support\n `responsive resolution images\n <https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images>`__.\n The list should contain additional x-descriptors (``'1.5x'``, ``'2x'``,\n etc.) to generate (1x is the default and always included.)\n\n"""\n\nimport hashlib\nfrom pathlib import Path\n\nfrom docutils import nodes\nfrom docutils.parsers.rst import Directive, directives\nimport sphinx\nfrom sphinx.errors import ConfigError, ExtensionError\n\nimport matplotlib as mpl\nfrom matplotlib import _api, mathtext\nfrom matplotlib.rcsetup import validate_float_or_None\n\n\n# Define LaTeX math node:\nclass latex_math(nodes.General, nodes.Element):\n pass\n\n\ndef fontset_choice(arg):\n return directives.choice(arg, mathtext.MathTextParser._font_type_mapping)\n\n\ndef math_role(role, rawtext, text, lineno, inliner,\n options={}, content=[]):\n i = rawtext.find('`')\n latex = rawtext[i+1:-1]\n node = latex_math(rawtext)\n node['latex'] = latex\n node['fontset'] = options.get('fontset', 'cm')\n node['fontsize'] = options.get('fontsize',\n setup.app.config.mathmpl_fontsize)\n return [node], []\nmath_role.options = {'fontset': fontset_choice,\n 'fontsize': validate_float_or_None}\n\n\nclass MathDirective(Directive):\n """\n The ``.. mathmpl::`` directive, as documented in the module's docstring.\n """\n has_content = True\n required_arguments = 0\n optional_arguments = 0\n final_argument_whitespace = False\n option_spec = {'fontset': fontset_choice,\n 'fontsize': validate_float_or_None}\n\n def run(self):\n latex = ''.join(self.content)\n node = latex_math(self.block_text)\n node['latex'] = latex\n node['fontset'] = self.options.get('fontset', 'cm')\n node['fontsize'] = self.options.get('fontsize',\n setup.app.config.mathmpl_fontsize)\n return [node]\n\n\n# This uses mathtext to render the expression\ndef latex2png(latex, filename, fontset='cm', fontsize=10, dpi=100):\n with mpl.rc_context({'mathtext.fontset': fontset, 'font.size': fontsize}):\n try:\n depth = mathtext.math_to_image(\n f"${latex}$", filename, dpi=dpi, format="png")\n except Exception:\n _api.warn_external(f"Could not render math expression {latex}")\n depth = 0\n return depth\n\n\n# LaTeX to HTML translation stuff:\ndef latex2html(node, source):\n inline = isinstance(node.parent, nodes.TextElement)\n latex = node['latex']\n fontset = node['fontset']\n fontsize = node['fontsize']\n name = 'math-{}'.format(\n hashlib.sha256(\n f'{latex}{fontset}{fontsize}'.encode(),\n usedforsecurity=False,\n ).hexdigest()[-10:])\n\n destdir = Path(setup.app.builder.outdir, '_images', 'mathmpl')\n destdir.mkdir(parents=True, exist_ok=True)\n\n dest = destdir / f'{name}.png'\n depth = latex2png(latex, dest, fontset, fontsize=fontsize)\n\n srcset = []\n for size in setup.app.config.mathmpl_srcset:\n filename = f'{name}-{size.replace(".", "_")}.png'\n latex2png(latex, destdir / filename, fontset, fontsize=fontsize,\n dpi=100 * float(size[:-1]))\n srcset.append(\n f'{setup.app.builder.imgpath}/mathmpl/{filename} {size}')\n if srcset:\n srcset = (f'srcset="{setup.app.builder.imgpath}/mathmpl/{name}.png, ' +\n ', '.join(srcset) + '" ')\n\n if inline:\n cls = ''\n else:\n cls = 'class="center" '\n if inline and depth != 0:\n style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)\n else:\n style = ''\n\n return (f'<img src="{setup.app.builder.imgpath}/mathmpl/{name}.png"'\n f' {srcset}{cls}{style}/>')\n\n\ndef _config_inited(app, config):\n # Check for srcset hidpi images\n for i, size in enumerate(app.config.mathmpl_srcset):\n if size[-1] == 'x': # "2x" = "2.0"\n try:\n float(size[:-1])\n except ValueError:\n raise ConfigError(\n f'Invalid value for mathmpl_srcset parameter: {size!r}. '\n 'Must be a list of strings with the multiplicative '\n 'factor followed by an "x". e.g. ["2.0x", "1.5x"]')\n else:\n raise ConfigError(\n f'Invalid value for mathmpl_srcset parameter: {size!r}. '\n 'Must be a list of strings with the multiplicative '\n 'factor followed by an "x". e.g. ["2.0x", "1.5x"]')\n\n\ndef setup(app):\n setup.app = app\n app.add_config_value('mathmpl_fontsize', 10.0, True)\n app.add_config_value('mathmpl_srcset', [], True)\n try:\n app.connect('config-inited', _config_inited) # Sphinx 1.8+\n except ExtensionError:\n app.connect('env-updated', lambda app, env: _config_inited(app, None))\n\n # Add visit/depart methods to HTML-Translator:\n def visit_latex_math_html(self, node):\n source = self.document.attributes['source']\n self.body.append(latex2html(node, source))\n\n def depart_latex_math_html(self, node):\n pass\n\n # Add visit/depart methods to LaTeX-Translator:\n def visit_latex_math_latex(self, node):\n inline = isinstance(node.parent, nodes.TextElement)\n if inline:\n self.body.append('$%s$' % node['latex'])\n else:\n self.body.extend(['\\begin{equation}',\n node['latex'],\n '\\end{equation}'])\n\n def depart_latex_math_latex(self, node):\n pass\n\n app.add_node(latex_math,\n html=(visit_latex_math_html, depart_latex_math_html),\n latex=(visit_latex_math_latex, depart_latex_math_latex))\n app.add_role('mathmpl', math_role)\n app.add_directive('mathmpl', MathDirective)\n if sphinx.version_info < (1, 8):\n app.add_role('math', math_role)\n app.add_directive('math', MathDirective)\n\n metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}\n return metadata\n | .venv\Lib\site-packages\matplotlib\sphinxext\mathmpl.py | mathmpl.py | Python | 7,871 | 0.95 | 0.119835 | 0.032086 | awesome-app | 664 | 2024-11-11T07:55:00.257639 | BSD-3-Clause | false | 540d927722ca0745424beb82ce039969 |
"""\nA directive for including a Matplotlib plot in a Sphinx document\n================================================================\n\nThis is a Sphinx extension providing a reStructuredText directive\n``.. plot::`` for including a plot in a Sphinx document.\n\nIn HTML output, ``.. plot::`` will include a .png file with a link\nto a high-res .png and .pdf. In LaTeX output, it will include a .pdf.\n\nThe plot content may be defined in one of three ways:\n\n1. **A path to a source file** as the argument to the directive::\n\n .. plot:: path/to/plot.py\n\n When a path to a source file is given, the content of the\n directive may optionally contain a caption for the plot::\n\n .. plot:: path/to/plot.py\n\n The plot caption.\n\n Additionally, one may specify the name of a function to call (with\n no arguments) immediately after importing the module::\n\n .. plot:: path/to/plot.py plot_function1\n\n2. Included as **inline content** to the directive::\n\n .. plot::\n\n import matplotlib.pyplot as plt\n plt.plot([1, 2, 3], [4, 5, 6])\n plt.title("A plotting exammple")\n\n3. Using **doctest** syntax::\n\n .. plot::\n\n A plotting example:\n >>> import matplotlib.pyplot as plt\n >>> plt.plot([1, 2, 3], [4, 5, 6])\n\nOptions\n-------\n\nThe ``.. plot::`` directive supports the following options:\n\n``:format:`` : {'python', 'doctest'}\n The format of the input. If unset, the format is auto-detected.\n\n``:include-source:`` : bool\n Whether to display the source code. The default can be changed using\n the ``plot_include_source`` variable in :file:`conf.py` (which itself\n defaults to False).\n\n``:show-source-link:`` : bool\n Whether to show a link to the source in HTML. The default can be\n changed using the ``plot_html_show_source_link`` variable in\n :file:`conf.py` (which itself defaults to True).\n\n``:context:`` : bool or str\n If provided, the code will be run in the context of all previous plot\n directives for which the ``:context:`` option was specified. This only\n applies to inline code plot directives, not those run from files. If\n the ``:context: reset`` option is specified, the context is reset\n for this and future plots, and previous figures are closed prior to\n running the code. ``:context: close-figs`` keeps the context but closes\n previous figures before running the code.\n\n``:nofigs:`` : bool\n If specified, the code block will be run, but no figures will be\n inserted. This is usually useful with the ``:context:`` option.\n\n``:caption:`` : str\n If specified, the option's argument will be used as a caption for the\n figure. This overwrites the caption given in the content, when the plot\n is generated from a file.\n\nAdditionally, this directive supports all the options of the `image directive\n<https://docutils.sourceforge.io/docs/ref/rst/directives.html#image>`_,\nexcept for ``:target:`` (since plot will add its own target). These include\n``:alt:``, ``:height:``, ``:width:``, ``:scale:``, ``:align:`` and ``:class:``.\n\nConfiguration options\n---------------------\n\nThe plot directive has the following configuration options:\n\nplot_include_source\n Default value for the include-source option (default: False).\n\nplot_html_show_source_link\n Whether to show a link to the source in HTML (default: True).\n\nplot_pre_code\n Code that should be executed before each plot. If None (the default),\n it will default to a string containing::\n\n import numpy as np\n from matplotlib import pyplot as plt\n\nplot_basedir\n Base directory, to which ``plot::`` file names are relative to.\n If None or empty (the default), file names are relative to the\n directory where the file containing the directive is.\n\nplot_formats\n File formats to generate (default: ['png', 'hires.png', 'pdf']).\n List of tuples or strings::\n\n [(suffix, dpi), suffix, ...]\n\n that determine the file format and the DPI. For entries whose\n DPI was omitted, sensible defaults are chosen. When passing from\n the command line through sphinx_build the list should be passed as\n suffix:dpi,suffix:dpi, ...\n\nplot_html_show_formats\n Whether to show links to the files in HTML (default: True).\n\nplot_rcparams\n A dictionary containing any non-standard rcParams that should\n be applied before each plot (default: {}).\n\nplot_apply_rcparams\n By default, rcParams are applied when ``:context:`` option is not used\n in a plot directive. If set, this configuration option overrides this\n behavior and applies rcParams before each plot.\n\nplot_working_directory\n By default, the working directory will be changed to the directory of\n the example, so the code can get at its data files, if any. Also its\n path will be added to `sys.path` so it can import any helper modules\n sitting beside it. This configuration option can be used to specify\n a central directory (also added to `sys.path`) where data files and\n helper modules for all code are located.\n\nplot_template\n Provide a customized template for preparing restructured text.\n\nplot_srcset\n Allow the srcset image option for responsive image resolutions. List of\n strings with the multiplicative factors followed by an "x".\n e.g. ["2.0x", "1.5x"]. "2.0x" will create a png with the default "png"\n resolution from plot_formats, multiplied by 2. If plot_srcset is\n specified, the plot directive uses the\n :doc:`/api/sphinxext_figmpl_directive_api` (instead of the usual figure\n directive) in the intermediary rst file that is generated.\n The plot_srcset option is incompatible with *singlehtml* builds, and an\n error will be raised.\n\nNotes on how it works\n---------------------\n\nThe plot directive runs the code it is given, either in the source file or the\ncode under the directive. The figure created (if any) is saved in the sphinx\nbuild directory under a subdirectory named ``plot_directive``. It then creates\nan intermediate rst file that calls a ``.. figure:`` directive (or\n``.. figmpl::`` directive if ``plot_srcset`` is being used) and has links to\nthe ``*.png`` files in the ``plot_directive`` directory. These translations can\nbe customized by changing the *plot_template*. See the source of\n:doc:`/api/sphinxext_plot_directive_api` for the templates defined in *TEMPLATE*\nand *TEMPLATE_SRCSET*.\n"""\n\nimport contextlib\nimport doctest\nfrom io import StringIO\nimport itertools\nimport os\nfrom os.path import relpath\nfrom pathlib import Path\nimport re\nimport shutil\nimport sys\nimport textwrap\nimport traceback\n\nfrom docutils.parsers.rst import directives, Directive\nfrom docutils.parsers.rst.directives.images import Image\nimport jinja2 # Sphinx dependency.\n\nfrom sphinx.errors import ExtensionError\n\nimport matplotlib\nfrom matplotlib.backend_bases import FigureManagerBase\nimport matplotlib.pyplot as plt\nfrom matplotlib import _pylab_helpers, cbook\n\nmatplotlib.use("agg")\n\n__version__ = 2\n\n\n# -----------------------------------------------------------------------------\n# Registration hook\n# -----------------------------------------------------------------------------\n\n\ndef _option_boolean(arg):\n if not arg or not arg.strip():\n # no argument given, assume used as a flag\n return True\n elif arg.strip().lower() in ('no', '0', 'false'):\n return False\n elif arg.strip().lower() in ('yes', '1', 'true'):\n return True\n else:\n raise ValueError(f'{arg!r} unknown boolean')\n\n\ndef _option_context(arg):\n if arg in [None, 'reset', 'close-figs']:\n return arg\n raise ValueError("Argument should be None or 'reset' or 'close-figs'")\n\n\ndef _option_format(arg):\n return directives.choice(arg, ('python', 'doctest'))\n\n\ndef mark_plot_labels(app, document):\n """\n To make plots referenceable, we need to move the reference from the\n "htmlonly" (or "latexonly") node to the actual figure node itself.\n """\n for name, explicit in document.nametypes.items():\n if not explicit:\n continue\n labelid = document.nameids[name]\n if labelid is None:\n continue\n node = document.ids[labelid]\n if node.tagname in ('html_only', 'latex_only'):\n for n in node:\n if n.tagname == 'figure':\n sectname = name\n for c in n:\n if c.tagname == 'caption':\n sectname = c.astext()\n break\n\n node['ids'].remove(labelid)\n node['names'].remove(name)\n n['ids'].append(labelid)\n n['names'].append(name)\n document.settings.env.labels[name] = \\n document.settings.env.docname, labelid, sectname\n break\n\n\nclass PlotDirective(Directive):\n """The ``.. plot::`` directive, as documented in the module's docstring."""\n\n has_content = True\n required_arguments = 0\n optional_arguments = 2\n final_argument_whitespace = False\n option_spec = {\n 'alt': directives.unchanged,\n 'height': directives.length_or_unitless,\n 'width': directives.length_or_percentage_or_unitless,\n 'scale': directives.nonnegative_int,\n 'align': Image.align,\n 'class': directives.class_option,\n 'include-source': _option_boolean,\n 'show-source-link': _option_boolean,\n 'format': _option_format,\n 'context': _option_context,\n 'nofigs': directives.flag,\n 'caption': directives.unchanged,\n }\n\n def run(self):\n """Run the plot directive."""\n try:\n return run(self.arguments, self.content, self.options,\n self.state_machine, self.state, self.lineno)\n except Exception as e:\n raise self.error(str(e))\n\n\ndef _copy_css_file(app, exc):\n if exc is None and app.builder.format == 'html':\n src = cbook._get_data_path('plot_directive/plot_directive.css')\n dst = app.outdir / Path('_static')\n dst.mkdir(exist_ok=True)\n # Use copyfile because we do not want to copy src's permissions.\n shutil.copyfile(src, dst / Path('plot_directive.css'))\n\n\ndef setup(app):\n setup.app = app\n setup.config = app.config\n setup.confdir = app.confdir\n app.add_directive('plot', PlotDirective)\n app.add_config_value('plot_pre_code', None, True)\n app.add_config_value('plot_include_source', False, True)\n app.add_config_value('plot_html_show_source_link', True, True)\n app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)\n app.add_config_value('plot_basedir', None, True)\n app.add_config_value('plot_html_show_formats', True, True)\n app.add_config_value('plot_rcparams', {}, True)\n app.add_config_value('plot_apply_rcparams', False, True)\n app.add_config_value('plot_working_directory', None, True)\n app.add_config_value('plot_template', None, True)\n app.add_config_value('plot_srcset', [], True)\n app.connect('doctree-read', mark_plot_labels)\n app.add_css_file('plot_directive.css')\n app.connect('build-finished', _copy_css_file)\n metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,\n 'version': matplotlib.__version__}\n return metadata\n\n\n# -----------------------------------------------------------------------------\n# Doctest handling\n# -----------------------------------------------------------------------------\n\n\ndef contains_doctest(text):\n try:\n # check if it's valid Python as-is\n compile(text, '<string>', 'exec')\n return False\n except SyntaxError:\n pass\n r = re.compile(r'^\s*>>>', re.M)\n m = r.search(text)\n return bool(m)\n\n\ndef _split_code_at_show(text, function_name):\n """Split code at plt.show()."""\n\n is_doctest = contains_doctest(text)\n if function_name is None:\n parts = []\n part = []\n for line in text.split("\n"):\n if ((not is_doctest and line.startswith('plt.show(')) or\n (is_doctest and line.strip() == '>>> plt.show()')):\n part.append(line)\n parts.append("\n".join(part))\n part = []\n else:\n part.append(line)\n if "\n".join(part).strip():\n parts.append("\n".join(part))\n else:\n parts = [text]\n return is_doctest, parts\n\n\n# -----------------------------------------------------------------------------\n# Template\n# -----------------------------------------------------------------------------\n\n_SOURCECODE = """\n{{ source_code }}\n\n.. only:: html\n\n {% if src_name or (html_show_formats and not multi_image) %}\n (\n {%- if src_name -%}\n :download:`Source code <{{ build_dir }}/{{ src_name }}>`\n {%- endif -%}\n {%- if html_show_formats and not multi_image -%}\n {%- for img in images -%}\n {%- for fmt in img.formats -%}\n {%- if src_name or not loop.first -%}, {% endif -%}\n :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`\n {%- endfor -%}\n {%- endfor -%}\n {%- endif -%}\n )\n {% endif %}\n"""\n\nTEMPLATE_SRCSET = _SOURCECODE + """\n {% for img in images %}\n .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}\n {% for option in options -%}\n {{ option }}\n {% endfor %}\n {%- if caption -%}\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endif -%}\n {%- if srcset -%}\n :srcset: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}\n {%- for sr in srcset -%}\n , {{ build_dir }}/{{ img.basename }}.{{ sr }}.{{ default_fmt }} {{sr}}\n {%- endfor -%}\n {% endif %}\n\n {% if html_show_formats and multi_image %}\n (\n {%- for fmt in img.formats -%}\n {%- if not loop.first -%}, {% endif -%}\n :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`\n {%- endfor -%}\n )\n {% endif %}\n\n\n {% endfor %}\n\n.. only:: not html\n\n {% for img in images %}\n .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.*\n {% for option in options -%}\n {{ option }}\n {% endfor -%}\n\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endfor %}\n\n"""\n\nTEMPLATE = _SOURCECODE + """\n\n {% for img in images %}\n .. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}\n {% for option in options -%}\n {{ option }}\n {% endfor %}\n\n {% if html_show_formats and multi_image -%}\n (\n {%- for fmt in img.formats -%}\n {%- if not loop.first -%}, {% endif -%}\n :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`\n {%- endfor -%}\n )\n {%- endif -%}\n\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endfor %}\n\n.. only:: not html\n\n {% for img in images %}\n .. figure:: {{ build_dir }}/{{ img.basename }}.*\n {% for option in options -%}\n {{ option }}\n {% endfor -%}\n\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endfor %}\n\n"""\n\nexception_template = """\n.. only:: html\n\n [`source code <%(linkdir)s/%(basename)s.py>`__]\n\nException occurred rendering plot.\n\n"""\n\n# the context of the plot for all directives specified with the\n# :context: option\nplot_context = dict()\n\n\nclass ImageFile:\n def __init__(self, basename, dirname):\n self.basename = basename\n self.dirname = dirname\n self.formats = []\n\n def filename(self, format):\n return os.path.join(self.dirname, f"{self.basename}.{format}")\n\n def filenames(self):\n return [self.filename(fmt) for fmt in self.formats]\n\n\ndef out_of_date(original, derived, includes=None):\n """\n Return whether *derived* is out-of-date relative to *original* or any of\n the RST files included in it using the RST include directive (*includes*).\n *derived* and *original* are full paths, and *includes* is optionally a\n list of full paths which may have been included in the *original*.\n """\n if not os.path.exists(derived):\n return True\n\n if includes is None:\n includes = []\n files_to_check = [original, *includes]\n\n def out_of_date_one(original, derived_mtime):\n return (os.path.exists(original) and\n derived_mtime < os.stat(original).st_mtime)\n\n derived_mtime = os.stat(derived).st_mtime\n return any(out_of_date_one(f, derived_mtime) for f in files_to_check)\n\n\nclass PlotError(RuntimeError):\n pass\n\n\ndef _run_code(code, code_path, ns=None, function_name=None):\n """\n Import a Python module from a path, and run the function given by\n name, if function_name is not None.\n """\n\n # Change the working directory to the directory of the example, so\n # it can get at its data files, if any. Add its path to sys.path\n # so it can import any helper modules sitting beside it.\n pwd = os.getcwd()\n if setup.config.plot_working_directory is not None:\n try:\n os.chdir(setup.config.plot_working_directory)\n except OSError as err:\n raise OSError(f'{err}\n`plot_working_directory` option in '\n f'Sphinx configuration file must be a valid '\n f'directory path') from err\n except TypeError as err:\n raise TypeError(f'{err}\n`plot_working_directory` option in '\n f'Sphinx configuration file must be a string or '\n f'None') from err\n elif code_path is not None:\n dirname = os.path.abspath(os.path.dirname(code_path))\n os.chdir(dirname)\n\n with cbook._setattr_cm(\n sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \\n contextlib.redirect_stdout(StringIO()):\n try:\n if ns is None:\n ns = {}\n if not ns:\n if setup.config.plot_pre_code is None:\n exec('import numpy as np\n'\n 'from matplotlib import pyplot as plt\n', ns)\n else:\n exec(str(setup.config.plot_pre_code), ns)\n if "__main__" in code:\n ns['__name__'] = '__main__'\n\n # Patch out non-interactive show() to avoid triggering a warning.\n with cbook._setattr_cm(FigureManagerBase, show=lambda self: None):\n exec(code, ns)\n if function_name is not None:\n exec(function_name + "()", ns)\n\n except (Exception, SystemExit) as err:\n raise PlotError(traceback.format_exc()) from err\n finally:\n os.chdir(pwd)\n return ns\n\n\ndef clear_state(plot_rcparams, close=True):\n if close:\n plt.close('all')\n matplotlib.rc_file_defaults()\n matplotlib.rcParams.update(plot_rcparams)\n\n\ndef get_plot_formats(config):\n default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}\n formats = []\n plot_formats = config.plot_formats\n for fmt in plot_formats:\n if isinstance(fmt, str):\n if ':' in fmt:\n suffix, dpi = fmt.split(':')\n formats.append((str(suffix), int(dpi)))\n else:\n formats.append((fmt, default_dpi.get(fmt, 80)))\n elif isinstance(fmt, (tuple, list)) and len(fmt) == 2:\n formats.append((str(fmt[0]), int(fmt[1])))\n else:\n raise PlotError('invalid image format "%r" in plot_formats' % fmt)\n return formats\n\n\ndef _parse_srcset(entries):\n """\n Parse srcset for multiples...\n """\n srcset = {}\n for entry in entries:\n entry = entry.strip()\n if len(entry) >= 2:\n mult = entry[:-1]\n srcset[float(mult)] = entry\n else:\n raise ExtensionError(f'srcset argument {entry!r} is invalid.')\n return srcset\n\n\ndef render_figures(code, code_path, output_dir, output_base, context,\n function_name, config, context_reset=False,\n close_figs=False,\n code_includes=None):\n """\n Run a pyplot script and save the images in *output_dir*.\n\n Save the images under *output_dir* with file names derived from\n *output_base*\n """\n\n if function_name is not None:\n output_base = f'{output_base}_{function_name}'\n formats = get_plot_formats(config)\n\n # Try to determine if all images already exist\n\n is_doctest, code_pieces = _split_code_at_show(code, function_name)\n # Look for single-figure output files first\n img = ImageFile(output_base, output_dir)\n for format, dpi in formats:\n if context or out_of_date(code_path, img.filename(format),\n includes=code_includes):\n all_exists = False\n break\n img.formats.append(format)\n else:\n all_exists = True\n\n if all_exists:\n return [(code, [img])]\n\n # Then look for multi-figure output files\n results = []\n for i, code_piece in enumerate(code_pieces):\n images = []\n for j in itertools.count():\n if len(code_pieces) > 1:\n img = ImageFile('%s_%02d_%02d' % (output_base, i, j),\n output_dir)\n else:\n img = ImageFile('%s_%02d' % (output_base, j), output_dir)\n for fmt, dpi in formats:\n if context or out_of_date(code_path, img.filename(fmt),\n includes=code_includes):\n all_exists = False\n break\n img.formats.append(fmt)\n\n # assume that if we have one, we have them all\n if not all_exists:\n all_exists = (j > 0)\n break\n images.append(img)\n if not all_exists:\n break\n results.append((code_piece, images))\n else:\n all_exists = True\n\n if all_exists:\n return results\n\n # We didn't find the files, so build them\n\n results = []\n ns = plot_context if context else {}\n\n if context_reset:\n clear_state(config.plot_rcparams)\n plot_context.clear()\n\n close_figs = not context or close_figs\n\n for i, code_piece in enumerate(code_pieces):\n\n if not context or config.plot_apply_rcparams:\n clear_state(config.plot_rcparams, close_figs)\n elif close_figs:\n plt.close('all')\n\n _run_code(doctest.script_from_examples(code_piece) if is_doctest\n else code_piece,\n code_path, ns, function_name)\n\n images = []\n fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()\n for j, figman in enumerate(fig_managers):\n if len(fig_managers) == 1 and len(code_pieces) == 1:\n img = ImageFile(output_base, output_dir)\n elif len(code_pieces) == 1:\n img = ImageFile("%s_%02d" % (output_base, j), output_dir)\n else:\n img = ImageFile("%s_%02d_%02d" % (output_base, i, j),\n output_dir)\n images.append(img)\n\n for fmt, dpi in formats:\n try:\n figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi)\n if fmt == formats[0][0] and config.plot_srcset:\n # save a 2x, 3x etc version of the default...\n srcset = _parse_srcset(config.plot_srcset)\n for mult, suffix in srcset.items():\n fm = f'{suffix}.{fmt}'\n img.formats.append(fm)\n figman.canvas.figure.savefig(img.filename(fm),\n dpi=int(dpi * mult))\n except Exception as err:\n raise PlotError(traceback.format_exc()) from err\n img.formats.append(fmt)\n\n results.append((code_piece, images))\n\n if not context or config.plot_apply_rcparams:\n clear_state(config.plot_rcparams, close=not context)\n\n return results\n\n\ndef run(arguments, content, options, state_machine, state, lineno):\n document = state_machine.document\n config = document.settings.env.config\n nofigs = 'nofigs' in options\n\n if config.plot_srcset and setup.app.builder.name == 'singlehtml':\n raise ExtensionError(\n 'plot_srcset option not compatible with single HTML writer')\n\n formats = get_plot_formats(config)\n default_fmt = formats[0][0]\n\n options.setdefault('include-source', config.plot_include_source)\n options.setdefault('show-source-link', config.plot_html_show_source_link)\n\n if 'class' in options:\n # classes are parsed into a list of string, and output by simply\n # printing the list, abusing the fact that RST guarantees to strip\n # non-conforming characters\n options['class'] = ['plot-directive'] + options['class']\n else:\n options.setdefault('class', ['plot-directive'])\n keep_context = 'context' in options\n context_opt = None if not keep_context else options['context']\n\n rst_file = document.attributes['source']\n rst_dir = os.path.dirname(rst_file)\n\n if len(arguments):\n if not config.plot_basedir:\n source_file_name = os.path.join(setup.app.builder.srcdir,\n directives.uri(arguments[0]))\n else:\n source_file_name = os.path.join(setup.confdir, config.plot_basedir,\n directives.uri(arguments[0]))\n # If there is content, it will be passed as a caption.\n caption = '\n'.join(content)\n\n # Enforce unambiguous use of captions.\n if "caption" in options:\n if caption:\n raise ValueError(\n 'Caption specified in both content and options.'\n ' Please remove ambiguity.'\n )\n # Use caption option\n caption = options["caption"]\n\n # If the optional function name is provided, use it\n if len(arguments) == 2:\n function_name = arguments[1]\n else:\n function_name = None\n\n code = Path(source_file_name).read_text(encoding='utf-8')\n output_base = os.path.basename(source_file_name)\n else:\n source_file_name = rst_file\n code = textwrap.dedent("\n".join(map(str, content)))\n counter = document.attributes.get('_plot_counter', 0) + 1\n document.attributes['_plot_counter'] = counter\n base, ext = os.path.splitext(os.path.basename(source_file_name))\n output_base = '%s-%d.py' % (base, counter)\n function_name = None\n caption = options.get('caption', '')\n\n base, source_ext = os.path.splitext(output_base)\n if source_ext in ('.py', '.rst', '.txt'):\n output_base = base\n else:\n source_ext = ''\n\n # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames\n output_base = output_base.replace('.', '-')\n\n # is it in doctest format?\n is_doctest = contains_doctest(code)\n if 'format' in options:\n if options['format'] == 'python':\n is_doctest = False\n else:\n is_doctest = True\n\n # determine output directory name fragment\n source_rel_name = relpath(source_file_name, setup.confdir)\n source_rel_dir = os.path.dirname(source_rel_name).lstrip(os.path.sep)\n\n # build_dir: where to place output files (temporarily)\n build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),\n 'plot_directive',\n source_rel_dir)\n # get rid of .. in paths, also changes pathsep\n # see note in Python docs for warning about symbolic links on Windows.\n # need to compare source and dest paths at end\n build_dir = os.path.normpath(build_dir)\n os.makedirs(build_dir, exist_ok=True)\n\n # how to link to files from the RST file\n try:\n build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')\n except ValueError:\n # on Windows, relpath raises ValueError when path and start are on\n # different mounts/drives\n build_dir_link = build_dir\n\n # get list of included rst files so that the output is updated when any\n # plots in the included files change. These attributes are modified by the\n # include directive (see the docutils.parsers.rst.directives.misc module).\n try:\n source_file_includes = [os.path.join(os.getcwd(), t[0])\n for t in state.document.include_log]\n except AttributeError:\n # the document.include_log attribute only exists in docutils >=0.17,\n # before that we need to inspect the state machine\n possible_sources = {os.path.join(setup.confdir, t[0])\n for t in state_machine.input_lines.items}\n source_file_includes = [f for f in possible_sources\n if os.path.isfile(f)]\n # remove the source file itself from the includes\n try:\n source_file_includes.remove(source_file_name)\n except ValueError:\n pass\n\n # save script (if necessary)\n if options['show-source-link']:\n Path(build_dir, output_base + source_ext).write_text(\n doctest.script_from_examples(code)\n if source_file_name == rst_file and is_doctest\n else code,\n encoding='utf-8')\n\n # make figures\n try:\n results = render_figures(code=code,\n code_path=source_file_name,\n output_dir=build_dir,\n output_base=output_base,\n context=keep_context,\n function_name=function_name,\n config=config,\n context_reset=context_opt == 'reset',\n close_figs=context_opt == 'close-figs',\n code_includes=source_file_includes)\n errors = []\n except PlotError as err:\n reporter = state.memo.reporter\n sm = reporter.system_message(\n 2, "Exception occurred in plotting {}\n from {}:\n{}".format(\n output_base, source_file_name, err),\n line=lineno)\n results = [(code, [])]\n errors = [sm]\n\n # Properly indent the caption\n if caption and config.plot_srcset:\n caption = ':caption: ' + caption.replace('\n', ' ')\n elif caption:\n caption = '\n' + '\n'.join(' ' + line.strip()\n for line in caption.split('\n'))\n # generate output restructuredtext\n total_lines = []\n for j, (code_piece, images) in enumerate(results):\n if options['include-source']:\n if is_doctest:\n lines = ['', *code_piece.splitlines()]\n else:\n lines = ['.. code-block:: python', '',\n *textwrap.indent(code_piece, ' ').splitlines()]\n source_code = "\n".join(lines)\n else:\n source_code = ""\n\n if nofigs:\n images = []\n\n if 'alt' in options:\n options['alt'] = options['alt'].replace('\n', ' ')\n\n opts = [\n f':{key}: {val}' for key, val in options.items()\n if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]\n\n # Not-None src_name signals the need for a source download in the\n # generated html\n if j == 0 and options['show-source-link']:\n src_name = output_base + source_ext\n else:\n src_name = None\n if config.plot_srcset:\n srcset = [*_parse_srcset(config.plot_srcset).values()]\n template = TEMPLATE_SRCSET\n else:\n srcset = None\n template = TEMPLATE\n\n result = jinja2.Template(config.plot_template or template).render(\n default_fmt=default_fmt,\n build_dir=build_dir_link,\n src_name=src_name,\n multi_image=len(images) > 1,\n options=opts,\n srcset=srcset,\n images=images,\n source_code=source_code,\n html_show_formats=config.plot_html_show_formats and len(images),\n caption=caption)\n total_lines.extend(result.split("\n"))\n total_lines.extend("\n")\n\n if total_lines:\n state_machine.insert_input(total_lines, source=source_file_name)\n\n return errors\n | .venv\Lib\site-packages\matplotlib\sphinxext\plot_directive.py | plot_directive.py | Python | 32,542 | 0.95 | 0.186966 | 0.073491 | node-utils | 195 | 2025-02-02T04:03:42.579347 | GPL-3.0 | false | c8263f2c43439ab650dcec04aa4e80da |
"""\nCustom roles for the Matplotlib documentation.\n\n.. warning::\n\n These roles are considered semi-public. They are only intended to be used in\n the Matplotlib documentation.\n\nHowever, it can happen that downstream packages end up pulling these roles into\ntheir documentation, which will result in documentation build errors. The following\ndescribes the exact mechanism and how to fix the errors.\n\nThere are two ways, Matplotlib docstrings can end up in downstream documentation.\nYou have to subclass a Matplotlib class and either use the ``:inherited-members:``\noption in your autodoc configuration, or you have to override a method without\nspecifying a new docstring; the new method will inherit the original docstring and\nstill render in your autodoc. If the docstring contains one of the custom sphinx\nroles, you'll see one of the following error messages:\n\n.. code-block:: none\n\n Unknown interpreted text role "mpltype".\n Unknown interpreted text role "rc".\n\nTo fix this, you can add this module as extension to your sphinx :file:`conf.py`::\n\n extensions = [\n 'matplotlib.sphinxext.roles',\n # Other extensions.\n ]\n\n.. warning::\n\n Direct use of these roles in other packages is not officially supported. We\n reserve the right to modify or remove these roles without prior notification.\n"""\n\nfrom urllib.parse import urlsplit, urlunsplit\n\nfrom docutils import nodes\n\nimport matplotlib\nfrom matplotlib import rcParamsDefault\n\n\nclass _QueryReference(nodes.Inline, nodes.TextElement):\n """\n Wraps a reference or pending reference to add a query string.\n\n The query string is generated from the attributes added to this node.\n\n Also equivalent to a `~docutils.nodes.literal` node.\n """\n\n def to_query_string(self):\n """Generate query string from node attributes."""\n return '&'.join(f'{name}={value}' for name, value in self.attlist())\n\n\ndef _visit_query_reference_node(self, node):\n """\n Resolve *node* into query strings on its ``reference`` children.\n\n Then act as if this is a `~docutils.nodes.literal`.\n """\n query = node.to_query_string()\n for refnode in node.findall(nodes.reference):\n uri = urlsplit(refnode['refuri'])._replace(query=query)\n refnode['refuri'] = urlunsplit(uri)\n\n self.visit_literal(node)\n\n\ndef _depart_query_reference_node(self, node):\n """\n Act as if this is a `~docutils.nodes.literal`.\n """\n self.depart_literal(node)\n\n\ndef _rcparam_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n """\n Sphinx role ``:rc:`` to highlight and link ``rcParams`` entries.\n\n Usage: Give the desired ``rcParams`` key as parameter.\n\n :code:`:rc:`figure.dpi`` will render as: :rc:`figure.dpi`\n """\n # Generate a pending cross-reference so that Sphinx will ensure this link\n # isn't broken at some point in the future.\n title = f'rcParams["{text}"]'\n target = 'matplotlibrc-sample'\n ref_nodes, messages = inliner.interpreted(title, f'{title} <{target}>',\n 'ref', lineno)\n\n qr = _QueryReference(rawtext, highlight=text)\n qr += ref_nodes\n node_list = [qr]\n\n # The default backend would be printed as "agg", but that's not correct (as\n # the default is actually determined by fallback).\n if text in rcParamsDefault and text != "backend":\n node_list.extend([\n nodes.Text(' (default: '),\n nodes.literal('', repr(rcParamsDefault[text])),\n nodes.Text(')'),\n ])\n\n return node_list, messages\n\n\ndef _mpltype_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n """\n Sphinx role ``:mpltype:`` for custom matplotlib types.\n\n In Matplotlib, there are a number of type-like concepts that do not have a\n direct type representation; example: color. This role allows to properly\n highlight them in the docs and link to their definition.\n\n Currently supported values:\n\n - :code:`:mpltype:`color`` will render as: :mpltype:`color`\n\n """\n mpltype = text\n type_to_link_target = {\n 'color': 'colors_def',\n }\n if mpltype not in type_to_link_target:\n raise ValueError(f"Unknown mpltype: {mpltype!r}")\n\n node_list, messages = inliner.interpreted(\n mpltype, f'{mpltype} <{type_to_link_target[mpltype]}>', 'ref', lineno)\n return node_list, messages\n\n\ndef setup(app):\n app.add_role("rc", _rcparam_role)\n app.add_role("mpltype", _mpltype_role)\n app.add_node(\n _QueryReference,\n html=(_visit_query_reference_node, _depart_query_reference_node),\n latex=(_visit_query_reference_node, _depart_query_reference_node),\n text=(_visit_query_reference_node, _depart_query_reference_node),\n )\n return {"version": matplotlib.__version__,\n "parallel_read_safe": True, "parallel_write_safe": True}\n | .venv\Lib\site-packages\matplotlib\sphinxext\roles.py | roles.py | Python | 4,882 | 0.95 | 0.108844 | 0.046729 | python-kit | 197 | 2025-03-15T04:32:06.564626 | MIT | false | ec158c791cce49e5bf3ddd061c44787f |
\n\n | .venv\Lib\site-packages\matplotlib\sphinxext\__pycache__\figmpl_directive.cpython-313.pyc | figmpl_directive.cpython-313.pyc | Other | 11,115 | 0.95 | 0.039474 | 0 | python-kit | 221 | 2024-04-05T19:52:10.772954 | MIT | false | 0ff9c23ec38bf39e5280e7feb7842dc3 |
\n\n | .venv\Lib\site-packages\matplotlib\sphinxext\__pycache__\mathmpl.cpython-313.pyc | mathmpl.cpython-313.pyc | Other | 11,134 | 0.95 | 0.018634 | 0 | node-utils | 135 | 2023-07-15T06:25:58.749264 | BSD-3-Clause | false | 17d9e3f7c0ee0e70c462ce5f34588d6b |
\n\n | .venv\Lib\site-packages\matplotlib\sphinxext\__pycache__\plot_directive.cpython-313.pyc | plot_directive.cpython-313.pyc | Other | 37,807 | 0.95 | 0.08413 | 0.004425 | awesome-app | 874 | 2025-03-28T09:53:48.954105 | Apache-2.0 | false | 1844e3f67caab5e5bc627113b3856ff5 |
\n\n | .venv\Lib\site-packages\matplotlib\sphinxext\__pycache__\roles.cpython-313.pyc | roles.cpython-313.pyc | Other | 6,152 | 0.95 | 0.05102 | 0.012821 | awesome-app | 925 | 2024-01-27T11:18:36.181807 | GPL-3.0 | false | b2b8a3ce8f9066224d2c5ceed00d6ae5 |
\n\n | .venv\Lib\site-packages\matplotlib\sphinxext\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 195 | 0.7 | 0 | 0 | vue-tools | 701 | 2025-05-17T15:00:47.158030 | Apache-2.0 | false | 580e74157c28a1d9974c451bd8141315 |
"""\nCore functions and attributes for the matplotlib style library:\n\n``use``\n Select style sheet to override the current matplotlib settings.\n``context``\n Context manager to use a style sheet temporarily.\n``available``\n List available style sheets.\n``library``\n A dictionary of style names and matplotlib settings.\n"""\n\nimport contextlib\nimport importlib.resources\nimport logging\nimport os\nfrom pathlib import Path\nimport warnings\n\nimport matplotlib as mpl\nfrom matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault\n\n_log = logging.getLogger(__name__)\n\n__all__ = ['use', 'context', 'available', 'library', 'reload_library']\n\n\nBASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib')\n# Users may want multiple library paths, so store a list of paths.\nUSER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')]\nSTYLE_EXTENSION = 'mplstyle'\n# A list of rcParams that should not be applied from styles\nSTYLE_BLACKLIST = {\n 'interactive', 'backend', 'webagg.port', 'webagg.address',\n 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback',\n 'toolbar', 'timezone', 'figure.max_open_warning',\n 'figure.raise_window', 'savefig.directory', 'tk.window_focus',\n 'docstring.hardcopy', 'date.epoch'}\n\n\n@_docstring.Substitution(\n "\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower)))\n)\ndef use(style):\n """\n Use Matplotlib style settings from a style specification.\n\n The style name of 'default' is reserved for reverting back to\n the default style settings.\n\n .. note::\n\n This updates the `.rcParams` with the settings from the style.\n `.rcParams` not defined in the style are kept.\n\n Parameters\n ----------\n style : str, dict, Path or list\n\n A style specification. Valid options are:\n\n str\n - One of the style names in `.style.available` (a builtin style or\n a style installed in the user library path).\n\n - A dotted name of the form "package.style_name"; in that case,\n "package" should be an importable Python package name, e.g. at\n ``/path/to/package/__init__.py``; the loaded style file is\n ``/path/to/package/style_name.mplstyle``. (Style files in\n subpackages are likewise supported.)\n\n - The path or URL to a style file, which gets loaded by\n `.rc_params_from_file`.\n\n dict\n A mapping of key/value pairs for `matplotlib.rcParams`.\n\n Path\n The path to a style file, which gets loaded by\n `.rc_params_from_file`.\n\n list\n A list of style specifiers (str, Path or dict), which are applied\n from first to last in the list.\n\n Notes\n -----\n The following `.rcParams` are not related to style and will be ignored if\n found in a style specification:\n\n %s\n """\n if isinstance(style, (str, Path)) or hasattr(style, 'keys'):\n # If name is a single str, Path or dict, make it a single element list.\n styles = [style]\n else:\n styles = style\n\n style_alias = {'mpl20': 'default', 'mpl15': 'classic'}\n\n for style in styles:\n if isinstance(style, str):\n style = style_alias.get(style, style)\n if style == "default":\n # Deprecation warnings were already handled when creating\n # rcParamsDefault, no need to reemit them here.\n with _api.suppress_matplotlib_deprecation_warning():\n # don't trigger RcParams.__getitem__('backend')\n style = {k: rcParamsDefault[k] for k in rcParamsDefault\n if k not in STYLE_BLACKLIST}\n elif style in library:\n style = library[style]\n elif "." in style:\n pkg, _, name = style.rpartition(".")\n try:\n path = importlib.resources.files(pkg) / f"{name}.{STYLE_EXTENSION}"\n style = _rc_params_in_file(path)\n except (ModuleNotFoundError, OSError, TypeError) as exc:\n # There is an ambiguity whether a dotted name refers to a\n # package.style_name or to a dotted file path. Currently,\n # we silently try the first form and then the second one;\n # in the future, we may consider forcing file paths to\n # either use Path objects or be prepended with "./" and use\n # the slash as marker for file paths.\n pass\n if isinstance(style, (str, Path)):\n try:\n style = _rc_params_in_file(style)\n except OSError as err:\n raise OSError(\n f"{style!r} is not a valid package style, path of style "\n f"file, URL of style file, or library style name (library "\n f"styles are listed in `style.available`)") from err\n filtered = {}\n for k in style: # don't trigger RcParams.__getitem__('backend')\n if k in STYLE_BLACKLIST:\n _api.warn_external(\n f"Style includes a parameter, {k!r}, that is not "\n f"related to style. Ignoring this parameter.")\n else:\n filtered[k] = style[k]\n mpl.rcParams.update(filtered)\n\n\n@contextlib.contextmanager\ndef context(style, after_reset=False):\n """\n Context manager for using style settings temporarily.\n\n Parameters\n ----------\n style : str, dict, Path or list\n A style specification. Valid options are:\n\n str\n - One of the style names in `.style.available` (a builtin style or\n a style installed in the user library path).\n\n - A dotted name of the form "package.style_name"; in that case,\n "package" should be an importable Python package name, e.g. at\n ``/path/to/package/__init__.py``; the loaded style file is\n ``/path/to/package/style_name.mplstyle``. (Style files in\n subpackages are likewise supported.)\n\n - The path or URL to a style file, which gets loaded by\n `.rc_params_from_file`.\n dict\n A mapping of key/value pairs for `matplotlib.rcParams`.\n\n Path\n The path to a style file, which gets loaded by\n `.rc_params_from_file`.\n\n list\n A list of style specifiers (str, Path or dict), which are applied\n from first to last in the list.\n\n after_reset : bool\n If True, apply style after resetting settings to their defaults;\n otherwise, apply style on top of the current settings.\n """\n with mpl.rc_context():\n if after_reset:\n mpl.rcdefaults()\n use(style)\n yield\n\n\ndef update_user_library(library):\n """Update style library with user-defined rc files."""\n for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS):\n styles = read_style_directory(stylelib_path)\n update_nested_dict(library, styles)\n return library\n\n\ndef read_style_directory(style_dir):\n """Return dictionary of styles defined in *style_dir*."""\n styles = dict()\n for path in Path(style_dir).glob(f"*.{STYLE_EXTENSION}"):\n with warnings.catch_warnings(record=True) as warns:\n styles[path.stem] = _rc_params_in_file(path)\n for w in warns:\n _log.warning('In %s: %s', path, w.message)\n return styles\n\n\ndef update_nested_dict(main_dict, new_dict):\n """\n Update nested dict (only level of nesting) with new values.\n\n Unlike `dict.update`, this assumes that the values of the parent dict are\n dicts (or dict-like), so you shouldn't replace the nested dict if it\n already exists. Instead you should update the sub-dict.\n """\n # update named styles specified by user\n for name, rc_dict in new_dict.items():\n main_dict.setdefault(name, {}).update(rc_dict)\n return main_dict\n\n\n# Load style library\n# ==================\n_base_library = read_style_directory(BASE_LIBRARY_PATH)\nlibrary = {}\navailable = []\n\n\ndef reload_library():\n """Reload the style library."""\n library.clear()\n library.update(update_user_library(_base_library))\n available[:] = sorted(library.keys())\n\n\nreload_library()\n | .venv\Lib\site-packages\matplotlib\style\core.py | core.py | Python | 8,362 | 0.95 | 0.130802 | 0.078534 | python-kit | 535 | 2024-11-15T20:35:43.492999 | MIT | false | 7254a2f984e99622fe94a06bb9040af2 |
from collections.abc import Generator\nimport contextlib\n\nfrom matplotlib import RcParams\nfrom matplotlib.typing import RcStyleType\n\nUSER_LIBRARY_PATHS: list[str] = ...\nSTYLE_EXTENSION: str = ...\n\ndef use(style: RcStyleType) -> None: ...\n@contextlib.contextmanager\ndef context(\n style: RcStyleType, after_reset: bool = ...\n) -> Generator[None, None, None]: ...\n\nlibrary: dict[str, RcParams]\navailable: list[str]\n\ndef reload_library() -> None: ...\n\n__all__ = ['use', 'context', 'available', 'library', 'reload_library']\n | .venv\Lib\site-packages\matplotlib\style\core.pyi | core.pyi | Other | 521 | 0.85 | 0.142857 | 0 | node-utils | 257 | 2023-12-03T14:30:13.933424 | GPL-3.0 | false | fa513199bfba589e253b3761412ec5dc |
from .core import available, context, library, reload_library, use\n\n\n__all__ = ["available", "context", "library", "reload_library", "use"]\n | .venv\Lib\site-packages\matplotlib\style\__init__.py | __init__.py | Python | 140 | 0.85 | 0 | 0 | react-lib | 364 | 2023-09-21T13:50:28.142219 | GPL-3.0 | false | 17b3817749ce8cca4d7c493c6ba9e8b1 |
\n\n | .venv\Lib\site-packages\matplotlib\style\__pycache__\core.cpython-313.pyc | core.cpython-313.pyc | Other | 9,421 | 0.95 | 0.042945 | 0 | react-lib | 296 | 2023-10-20T10:03:52.047870 | BSD-3-Clause | false | 873b2c4b90e98a350d1a65ef7af82575 |
\n\n | .venv\Lib\site-packages\matplotlib\style\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 335 | 0.7 | 0 | 0 | node-utils | 549 | 2024-12-10T22:28:27.929531 | MIT | false | 1c1f2407e1858bd8d1e5f23f907d7af6 |
"""\nUtilities for comparing image results.\n"""\n\nimport atexit\nimport functools\nimport hashlib\nimport logging\nimport os\nfrom pathlib import Path\nimport shutil\nimport subprocess\nimport sys\nfrom tempfile import TemporaryDirectory, TemporaryFile\nimport weakref\nimport re\n\nimport numpy as np\nfrom PIL import Image\n\nimport matplotlib as mpl\nfrom matplotlib import cbook\nfrom matplotlib.testing.exceptions import ImageComparisonFailure\n\n_log = logging.getLogger(__name__)\n\n__all__ = ['calculate_rms', 'comparable_formats', 'compare_images']\n\n\ndef make_test_filename(fname, purpose):\n """\n Make a new filename by inserting *purpose* before the file's extension.\n """\n base, ext = os.path.splitext(fname)\n return f'{base}-{purpose}{ext}'\n\n\ndef _get_cache_path():\n cache_dir = Path(mpl.get_cachedir(), 'test_cache')\n cache_dir.mkdir(parents=True, exist_ok=True)\n return cache_dir\n\n\ndef get_cache_dir():\n return str(_get_cache_path())\n\n\ndef get_file_hash(path, block_size=2 ** 20):\n sha256 = hashlib.sha256(usedforsecurity=False)\n with open(path, 'rb') as fd:\n while True:\n data = fd.read(block_size)\n if not data:\n break\n sha256.update(data)\n\n if Path(path).suffix == '.pdf':\n sha256.update(str(mpl._get_executable_info("gs").version).encode('utf-8'))\n elif Path(path).suffix == '.svg':\n sha256.update(str(mpl._get_executable_info("inkscape").version).encode('utf-8'))\n\n return sha256.hexdigest()\n\n\nclass _ConverterError(Exception):\n pass\n\n\nclass _Converter:\n def __init__(self):\n self._proc = None\n # Explicitly register deletion from an atexit handler because if we\n # wait until the object is GC'd (which occurs later), then some module\n # globals (e.g. signal.SIGKILL) has already been set to None, and\n # kill() doesn't work anymore...\n atexit.register(self.__del__)\n\n def __del__(self):\n if self._proc:\n self._proc.kill()\n self._proc.wait()\n for stream in filter(None, [self._proc.stdin,\n self._proc.stdout,\n self._proc.stderr]):\n stream.close()\n self._proc = None\n\n def _read_until(self, terminator):\n """Read until the prompt is reached."""\n buf = bytearray()\n while True:\n c = self._proc.stdout.read(1)\n if not c:\n raise _ConverterError(os.fsdecode(bytes(buf)))\n buf.extend(c)\n if buf.endswith(terminator):\n return bytes(buf)\n\n\nclass _GSConverter(_Converter):\n def __call__(self, orig, dest):\n if not self._proc:\n self._proc = subprocess.Popen(\n [mpl._get_executable_info("gs").executable,\n "-dNOSAFER", "-dNOPAUSE", "-dEPSCrop", "-sDEVICE=png16m"],\n # As far as I can see, ghostscript never outputs to stderr.\n stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n try:\n self._read_until(b"\nGS")\n except _ConverterError as e:\n raise OSError(f"Failed to start Ghostscript:\n\n{e.args[0]}") from None\n\n def encode_and_escape(name):\n return (os.fsencode(name)\n .replace(b"\\", b"\\\\")\n .replace(b"(", br"\(")\n .replace(b")", br"\)"))\n\n self._proc.stdin.write(\n b"<< /OutputFile ("\n + encode_and_escape(dest)\n + b") >> setpagedevice ("\n + encode_and_escape(orig)\n + b") run flush\n")\n self._proc.stdin.flush()\n # GS> if nothing left on the stack; GS<n> if n items left on the stack.\n err = self._read_until((b"GS<", b"GS>"))\n stack = self._read_until(b">") if err.endswith(b"GS<") else b""\n if stack or not os.path.exists(dest):\n stack_size = int(stack[:-1]) if stack else 0\n self._proc.stdin.write(b"pop\n" * stack_size)\n # Using the systemencoding should at least get the filenames right.\n raise ImageComparisonFailure(\n (err + stack).decode(sys.getfilesystemencoding(), "replace"))\n\n\nclass _SVGConverter(_Converter):\n def __call__(self, orig, dest):\n old_inkscape = mpl._get_executable_info("inkscape").version.major < 1\n terminator = b"\n>" if old_inkscape else b"> "\n if not hasattr(self, "_tmpdir"):\n self._tmpdir = TemporaryDirectory()\n # On Windows, we must make sure that self._proc has terminated\n # (which __del__ does) before clearing _tmpdir.\n weakref.finalize(self._tmpdir, self.__del__)\n if (not self._proc # First run.\n or self._proc.poll() is not None): # Inkscape terminated.\n if self._proc is not None and self._proc.poll() is not None:\n for stream in filter(None, [self._proc.stdin,\n self._proc.stdout,\n self._proc.stderr]):\n stream.close()\n env = {\n **os.environ,\n # If one passes e.g. a png file to Inkscape, it will try to\n # query the user for conversion options via a GUI (even with\n # `--without-gui`). Unsetting `DISPLAY` prevents this (and\n # causes GTK to crash and Inkscape to terminate, but that'll\n # just be reported as a regular exception below).\n "DISPLAY": "",\n # Do not load any user options.\n "INKSCAPE_PROFILE_DIR": self._tmpdir.name,\n }\n # Old versions of Inkscape (e.g. 0.48.3.1) seem to sometimes\n # deadlock when stderr is redirected to a pipe, so we redirect it\n # to a temporary file instead. This is not necessary anymore as of\n # Inkscape 0.92.1.\n stderr = TemporaryFile()\n self._proc = subprocess.Popen(\n ["inkscape", "--without-gui", "--shell"] if old_inkscape else\n ["inkscape", "--shell"],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr,\n env=env, cwd=self._tmpdir.name)\n # Slight abuse, but makes shutdown handling easier.\n self._proc.stderr = stderr\n try:\n self._read_until(terminator)\n except _ConverterError as err:\n raise OSError(\n "Failed to start Inkscape in interactive mode:\n\n"\n + err.args[0]) from err\n\n # Inkscape's shell mode does not support escaping metacharacters in the\n # filename ("\n", and ":;" for inkscape>=1). Avoid any problems by\n # running from a temporary directory and using fixed filenames.\n inkscape_orig = Path(self._tmpdir.name, os.fsdecode(b"f.svg"))\n inkscape_dest = Path(self._tmpdir.name, os.fsdecode(b"f.png"))\n try:\n inkscape_orig.symlink_to(Path(orig).resolve())\n except OSError:\n shutil.copyfile(orig, inkscape_orig)\n self._proc.stdin.write(\n b"f.svg --export-png=f.png\n" if old_inkscape else\n b"file-open:f.svg;export-filename:f.png;export-do;file-close\n")\n self._proc.stdin.flush()\n try:\n self._read_until(terminator)\n except _ConverterError as err:\n # Inkscape's output is not localized but gtk's is, so the output\n # stream probably has a mixed encoding. Using the filesystem\n # encoding should at least get the filenames right...\n self._proc.stderr.seek(0)\n raise ImageComparisonFailure(\n self._proc.stderr.read().decode(\n sys.getfilesystemencoding(), "replace")) from err\n os.remove(inkscape_orig)\n shutil.move(inkscape_dest, dest)\n\n def __del__(self):\n super().__del__()\n if hasattr(self, "_tmpdir"):\n self._tmpdir.cleanup()\n\n\nclass _SVGWithMatplotlibFontsConverter(_SVGConverter):\n """\n A SVG converter which explicitly adds the fonts shipped by Matplotlib to\n Inkspace's font search path, to better support `svg.fonttype = "none"`\n (which is in particular used by certain mathtext tests).\n """\n\n def __call__(self, orig, dest):\n if not hasattr(self, "_tmpdir"):\n self._tmpdir = TemporaryDirectory()\n shutil.copytree(cbook._get_data_path("fonts/ttf"),\n Path(self._tmpdir.name, "fonts"))\n return super().__call__(orig, dest)\n\n\ndef _update_converter():\n try:\n mpl._get_executable_info("gs")\n except mpl.ExecutableNotFoundError:\n pass\n else:\n converter['pdf'] = converter['eps'] = _GSConverter()\n try:\n mpl._get_executable_info("inkscape")\n except mpl.ExecutableNotFoundError:\n pass\n else:\n converter['svg'] = _SVGConverter()\n\n\n#: A dictionary that maps filename extensions to functions which themselves\n#: convert between arguments `old` and `new` (filenames).\nconverter = {}\n_update_converter()\n_svg_with_matplotlib_fonts_converter = _SVGWithMatplotlibFontsConverter()\n\n\ndef comparable_formats():\n """\n Return the list of file formats that `.compare_images` can compare\n on this system.\n\n Returns\n -------\n list of str\n E.g. ``['png', 'pdf', 'svg', 'eps']``.\n\n """\n return ['png', *converter]\n\n\ndef convert(filename, cache):\n """\n Convert the named file to png; return the name of the created file.\n\n If *cache* is True, the result of the conversion is cached in\n `matplotlib.get_cachedir() + '/test_cache/'`. The caching is based on a\n hash of the exact contents of the input file. Old cache entries are\n automatically deleted as needed to keep the size of the cache capped to\n twice the size of all baseline images.\n """\n path = Path(filename)\n if not path.exists():\n raise OSError(f"{path} does not exist")\n if path.suffix[1:] not in converter:\n import pytest\n pytest.skip(f"Don't know how to convert {path.suffix} files to png")\n newpath = path.parent / f"{path.stem}_{path.suffix[1:]}.png"\n\n # Only convert the file if the destination doesn't already exist or\n # is out of date.\n if not newpath.exists() or newpath.stat().st_mtime < path.stat().st_mtime:\n cache_dir = _get_cache_path() if cache else None\n\n if cache_dir is not None:\n _register_conversion_cache_cleaner_once()\n hash_value = get_file_hash(path)\n cached_path = cache_dir / (hash_value + newpath.suffix)\n if cached_path.exists():\n _log.debug("For %s: reusing cached conversion.", filename)\n shutil.copyfile(cached_path, newpath)\n return str(newpath)\n\n _log.debug("For %s: converting to png.", filename)\n convert = converter[path.suffix[1:]]\n if path.suffix == ".svg":\n contents = path.read_text()\n # NOTE: This check should be kept in sync with font styling in\n # `lib/matplotlib/backends/backend_svg.py`. If it changes, then be sure to\n # re-generate any SVG test files using this mode, or else such tests will\n # fail to use the converter for the expected images (but will for the\n # results), and the tests will fail strangely.\n if re.search(\n # searches for attributes :\n # style=[font|font-size|font-weight|\n # font-family|font-variant|font-style]\n # taking care of the possibility of multiple style attributes\n # before the font styling (i.e. opacity)\n r'style="[^"]*font(|-size|-weight|-family|-variant|-style):',\n contents # raw contents of the svg file\n ):\n # for svg.fonttype = none, we explicitly patch the font search\n # path so that fonts shipped by Matplotlib are found.\n convert = _svg_with_matplotlib_fonts_converter\n convert(path, newpath)\n\n if cache_dir is not None:\n _log.debug("For %s: caching conversion result.", filename)\n shutil.copyfile(newpath, cached_path)\n\n return str(newpath)\n\n\ndef _clean_conversion_cache():\n # This will actually ignore mpl_toolkits baseline images, but they're\n # relatively small.\n baseline_images_size = sum(\n path.stat().st_size\n for path in Path(mpl.__file__).parent.glob("**/baseline_images/**/*"))\n # 2x: one full copy of baselines, and one full copy of test results\n # (actually an overestimate: we don't convert png baselines and results).\n max_cache_size = 2 * baseline_images_size\n # Reduce cache until it fits.\n with cbook._lock_path(_get_cache_path()):\n cache_stat = {\n path: path.stat() for path in _get_cache_path().glob("*")}\n cache_size = sum(stat.st_size for stat in cache_stat.values())\n paths_by_atime = sorted( # Oldest at the end.\n cache_stat, key=lambda path: cache_stat[path].st_atime,\n reverse=True)\n while cache_size > max_cache_size:\n path = paths_by_atime.pop()\n cache_size -= cache_stat[path].st_size\n path.unlink()\n\n\n@functools.cache # Ensure this is only registered once.\ndef _register_conversion_cache_cleaner_once():\n atexit.register(_clean_conversion_cache)\n\n\ndef crop_to_same(actual_path, actual_image, expected_path, expected_image):\n # clip the images to the same size -- this is useful only when\n # comparing eps to pdf\n if actual_path[-7:-4] == 'eps' and expected_path[-7:-4] == 'pdf':\n aw, ah, ad = actual_image.shape\n ew, eh, ed = expected_image.shape\n actual_image = actual_image[int(aw / 2 - ew / 2):int(\n aw / 2 + ew / 2), int(ah / 2 - eh / 2):int(ah / 2 + eh / 2)]\n return actual_image, expected_image\n\n\ndef calculate_rms(expected_image, actual_image):\n """\n Calculate the per-pixel errors, then compute the root mean square error.\n """\n if expected_image.shape != actual_image.shape:\n raise ImageComparisonFailure(\n f"Image sizes do not match expected size: {expected_image.shape} "\n f"actual size {actual_image.shape}")\n # Convert to float to avoid overflowing finite integer types.\n return np.sqrt(((expected_image - actual_image).astype(float) ** 2).mean())\n\n\n# NOTE: compare_image and save_diff_image assume that the image does not have\n# 16-bit depth, as Pillow converts these to RGB incorrectly.\n\n\ndef _load_image(path):\n img = Image.open(path)\n # In an RGBA image, if the smallest value in the alpha channel is 255, all\n # values in it must be 255, meaning that the image is opaque. If so,\n # discard the alpha channel so that it may compare equal to an RGB image.\n if img.mode != "RGBA" or img.getextrema()[3][0] == 255:\n img = img.convert("RGB")\n return np.asarray(img)\n\n\ndef compare_images(expected, actual, tol, in_decorator=False):\n """\n Compare two "image" files checking differences within a tolerance.\n\n The two given filenames may point to files which are convertible to\n PNG via the `.converter` dictionary. The underlying RMS is calculated\n with the `.calculate_rms` function.\n\n Parameters\n ----------\n expected : str\n The filename of the expected image.\n actual : str\n The filename of the actual image.\n tol : float\n The tolerance (a color value difference, where 255 is the\n maximal difference). The test fails if the average pixel\n difference is greater than this value.\n in_decorator : bool\n Determines the output format. If called from image_comparison\n decorator, this should be True. (default=False)\n\n Returns\n -------\n None or dict or str\n Return *None* if the images are equal within the given tolerance.\n\n If the images differ, the return value depends on *in_decorator*.\n If *in_decorator* is true, a dict with the following entries is\n returned:\n\n - *rms*: The RMS of the image difference.\n - *expected*: The filename of the expected image.\n - *actual*: The filename of the actual image.\n - *diff_image*: The filename of the difference image.\n - *tol*: The comparison tolerance.\n\n Otherwise, a human-readable multi-line string representation of this\n information is returned.\n\n Examples\n --------\n ::\n\n img1 = "./baseline/plot.png"\n img2 = "./output/plot.png"\n compare_images(img1, img2, 0.001)\n\n """\n actual = os.fspath(actual)\n if not os.path.exists(actual):\n raise Exception(f"Output image {actual} does not exist.")\n if os.stat(actual).st_size == 0:\n raise Exception(f"Output image file {actual} is empty.")\n\n # Convert the image to png\n expected = os.fspath(expected)\n if not os.path.exists(expected):\n raise OSError(f'Baseline image {expected!r} does not exist.')\n extension = expected.split('.')[-1]\n if extension != 'png':\n actual = convert(actual, cache=True)\n expected = convert(expected, cache=True)\n\n # open the image files\n expected_image = _load_image(expected)\n actual_image = _load_image(actual)\n\n actual_image, expected_image = crop_to_same(\n actual, actual_image, expected, expected_image)\n\n diff_image = make_test_filename(actual, 'failed-diff')\n\n if tol <= 0:\n if np.array_equal(expected_image, actual_image):\n return None\n\n # convert to signed integers, so that the images can be subtracted without\n # overflow\n expected_image = expected_image.astype(np.int16)\n actual_image = actual_image.astype(np.int16)\n\n rms = calculate_rms(expected_image, actual_image)\n\n if rms <= tol:\n return None\n\n save_diff_image(expected, actual, diff_image)\n\n results = dict(rms=rms, expected=str(expected),\n actual=str(actual), diff=str(diff_image), tol=tol)\n\n if not in_decorator:\n # Then the results should be a string suitable for stdout.\n template = ['Error: Image files did not match.',\n 'RMS Value: {rms}',\n 'Expected: \n {expected}',\n 'Actual: \n {actual}',\n 'Difference:\n {diff}',\n 'Tolerance: \n {tol}', ]\n results = '\n '.join([line.format(**results) for line in template])\n return results\n\n\ndef save_diff_image(expected, actual, output):\n """\n Parameters\n ----------\n expected : str\n File path of expected image.\n actual : str\n File path of actual image.\n output : str\n File path to save difference image to.\n """\n expected_image = _load_image(expected)\n actual_image = _load_image(actual)\n actual_image, expected_image = crop_to_same(\n actual, actual_image, expected, expected_image)\n expected_image = np.array(expected_image, float)\n actual_image = np.array(actual_image, float)\n if expected_image.shape != actual_image.shape:\n raise ImageComparisonFailure(\n f"Image sizes do not match expected size: {expected_image.shape} "\n f"actual size {actual_image.shape}")\n abs_diff = np.abs(expected_image - actual_image)\n\n # expand differences in luminance domain\n abs_diff *= 10\n abs_diff = np.clip(abs_diff, 0, 255).astype(np.uint8)\n\n if abs_diff.shape[2] == 4: # Hard-code the alpha channel to fully solid\n abs_diff[:, :, 3] = 255\n\n Image.fromarray(abs_diff).save(output, format="png")\n | .venv\Lib\site-packages\matplotlib\testing\compare.py | compare.py | Python | 19,780 | 0.95 | 0.185958 | 0.140909 | awesome-app | 499 | 2024-10-01T02:07:10.670850 | Apache-2.0 | true | c9567c90f672d7ddd7c9707161bfd0fe |
from collections.abc import Callable\nfrom typing import Literal, overload\n\nfrom numpy.typing import NDArray\n\n__all__ = ["calculate_rms", "comparable_formats", "compare_images"]\n\ndef make_test_filename(fname: str, purpose: str) -> str: ...\ndef get_cache_dir() -> str: ...\ndef get_file_hash(path: str, block_size: int = ...) -> str: ...\n\nconverter: dict[str, Callable[[str, str], None]] = {}\n\ndef comparable_formats() -> list[str]: ...\ndef convert(filename: str, cache: bool) -> str: ...\ndef crop_to_same(\n actual_path: str, actual_image: NDArray, expected_path: str, expected_image: NDArray\n) -> tuple[NDArray, NDArray]: ...\ndef calculate_rms(expected_image: NDArray, actual_image: NDArray) -> float: ...\n@overload\ndef compare_images(\n expected: str, actual: str, tol: float, in_decorator: Literal[True]\n) -> None | dict[str, float | str]: ...\n@overload\ndef compare_images(\n expected: str, actual: str, tol: float, in_decorator: Literal[False]\n) -> None | str: ...\n@overload\ndef compare_images(\n expected: str, actual: str, tol: float, in_decorator: bool = ...\n) -> None | str | dict[str, float | str]: ...\ndef save_diff_image(expected: str, actual: str, output: str) -> None: ...\n | .venv\Lib\site-packages\matplotlib\testing\compare.pyi | compare.pyi | Other | 1,192 | 0.85 | 0.34375 | 0 | awesome-app | 561 | 2023-10-15T16:12:13.170851 | BSD-3-Clause | true | 48a3bcbbd7b05252a304652181306150 |
import pytest\nimport sys\nimport matplotlib\nfrom matplotlib import _api\n\n\ndef pytest_configure(config):\n # config is initialized here rather than in pytest.ini so that `pytest\n # --pyargs matplotlib` (which would not find pytest.ini) works. The only\n # entries in pytest.ini set minversion (which is checked earlier),\n # testpaths/python_files, as they are required to properly find the tests\n for key, value in [\n ("markers", "flaky: (Provided by pytest-rerunfailures.)"),\n ("markers", "timeout: (Provided by pytest-timeout.)"),\n ("markers", "backend: Set alternate Matplotlib backend temporarily."),\n ("markers", "baseline_images: Compare output against references."),\n ("markers", "pytz: Tests that require pytz to be installed."),\n ("filterwarnings", "error"),\n ("filterwarnings",\n "ignore:.*The py23 module has been deprecated:DeprecationWarning"),\n ("filterwarnings",\n r"ignore:DynamicImporter.find_spec\(\) not found; "\n r"falling back to find_module\(\):ImportWarning"),\n ]:\n config.addinivalue_line(key, value)\n\n matplotlib.use('agg', force=True)\n matplotlib._called_from_pytest = True\n matplotlib._init_tests()\n\n\ndef pytest_unconfigure(config):\n matplotlib._called_from_pytest = False\n\n\n@pytest.fixture(autouse=True)\ndef mpl_test_settings(request):\n from matplotlib.testing.decorators import _cleanup_cm\n\n with _cleanup_cm():\n\n backend = None\n backend_marker = request.node.get_closest_marker('backend')\n prev_backend = matplotlib.get_backend()\n if backend_marker is not None:\n assert len(backend_marker.args) == 1, \\n "Marker 'backend' must specify 1 backend."\n backend, = backend_marker.args\n skip_on_importerror = backend_marker.kwargs.get(\n 'skip_on_importerror', False)\n\n # special case Qt backend importing to avoid conflicts\n if backend.lower().startswith('qt5'):\n if any(sys.modules.get(k) for k in ('PyQt4', 'PySide')):\n pytest.skip('Qt4 binding already imported')\n\n matplotlib.testing.setup()\n with _api.suppress_matplotlib_deprecation_warning():\n if backend is not None:\n # This import must come after setup() so it doesn't load the\n # default backend prematurely.\n import matplotlib.pyplot as plt\n try:\n plt.switch_backend(backend)\n except ImportError as exc:\n # Should only occur for the cairo backend tests, if neither\n # pycairo nor cairocffi are installed.\n if 'cairo' in backend.lower() or skip_on_importerror:\n pytest.skip("Failed to switch to backend "\n f"{backend} ({exc}).")\n else:\n raise\n # Default of cleanup and image_comparison too.\n matplotlib.style.use(["classic", "_classic_test_patch"])\n try:\n yield\n finally:\n if backend is not None:\n plt.close("all")\n matplotlib.use(prev_backend)\n\n\n@pytest.fixture\ndef pd():\n """\n Fixture to import and configure pandas. Using this fixture, the test is skipped when\n pandas is not installed. Use this fixture instead of importing pandas in test files.\n\n Examples\n --------\n Request the pandas fixture by passing in ``pd`` as an argument to the test ::\n\n def test_matshow_pandas(pd):\n\n df = pd.DataFrame({'x':[1,2,3], 'y':[4,5,6]})\n im = plt.figure().subplots().matshow(df)\n np.testing.assert_array_equal(im.get_array(), df)\n """\n pd = pytest.importorskip('pandas')\n try:\n from pandas.plotting import (\n deregister_matplotlib_converters as deregister)\n deregister()\n except ImportError:\n pass\n return pd\n\n\n@pytest.fixture\ndef xr():\n """\n Fixture to import xarray so that the test is skipped when xarray is not installed.\n Use this fixture instead of importing xrray in test files.\n\n Examples\n --------\n Request the xarray fixture by passing in ``xr`` as an argument to the test ::\n\n def test_imshow_xarray(xr):\n\n ds = xr.DataArray(np.random.randn(2, 3))\n im = plt.figure().subplots().imshow(ds)\n np.testing.assert_array_equal(im.get_array(), ds)\n """\n\n xr = pytest.importorskip('xarray')\n return xr\n\n\n@pytest.fixture\ndef text_placeholders(monkeypatch):\n """\n Replace texts with placeholder rectangles.\n\n The rectangle size only depends on the font size and the number of characters. It is\n thus insensitive to font properties and rendering details. This should be used for\n tests that depend on text geometries but not the actual text rendering, e.g. layout\n tests.\n """\n from matplotlib.patches import Rectangle\n\n def patched_get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):\n """\n Replace ``_get_text_metrics_with_cache`` with fixed results.\n\n The usual ``renderer.get_text_width_height_descent`` would depend on font\n metrics; instead the fixed results are based on font size and the length of the\n string only.\n """\n # While get_window_extent returns pixels and font size is in points, font size\n # includes ascenders and descenders. Leaving out this factor and setting\n # descent=0 ends up with a box that is relatively close to DejaVu Sans.\n height = fontprop.get_size()\n width = len(text) * height / 1.618 # Golden ratio for character size.\n descent = 0\n return width, height, descent\n\n def patched_text_draw(self, renderer):\n """\n Replace ``Text.draw`` with a fixed bounding box Rectangle.\n\n The bounding box corresponds to ``Text.get_window_extent``, which ultimately\n depends on the above patched ``_get_text_metrics_with_cache``.\n """\n if renderer is not None:\n self._renderer = renderer\n if not self.get_visible():\n return\n if self.get_text() == '':\n return\n bbox = self.get_window_extent()\n rect = Rectangle(bbox.p0, bbox.width, bbox.height,\n facecolor=self.get_color(), edgecolor='none')\n rect.draw(renderer)\n\n monkeypatch.setattr('matplotlib.text._get_text_metrics_with_cache',\n patched_get_text_metrics_with_cache)\n monkeypatch.setattr('matplotlib.text.Text.draw', patched_text_draw)\n | .venv\Lib\site-packages\matplotlib\testing\conftest.py | conftest.py | Python | 6,683 | 0.95 | 0.162921 | 0.087838 | awesome-app | 225 | 2025-05-29T03:50:48.031371 | GPL-3.0 | true | e3230b5a33a723f39ef68dde3b203dc4 |
from types import ModuleType\n\nimport pytest\n\ndef pytest_configure(config: pytest.Config) -> None: ...\ndef pytest_unconfigure(config: pytest.Config) -> None: ...\n@pytest.fixture\ndef mpl_test_settings(request: pytest.FixtureRequest) -> None: ...\n@pytest.fixture\ndef pd() -> ModuleType: ...\n@pytest.fixture\ndef xr() -> ModuleType: ...\n@pytest.fixture\ndef text_placeholders(monkeypatch: pytest.MonkeyPatch) -> None: ...\n | .venv\Lib\site-packages\matplotlib\testing\conftest.pyi | conftest.pyi | Other | 416 | 0.85 | 0.428571 | 0 | node-utils | 834 | 2023-07-28T16:17:08.312561 | MIT | true | 1108d80c0bcadf6b909a509655af01c6 |
import contextlib\nimport functools\nimport inspect\nimport os\nfrom platform import uname\nfrom pathlib import Path\nimport shutil\nimport string\nimport sys\nimport warnings\n\nfrom packaging.version import parse as parse_version\n\nimport matplotlib.style\nimport matplotlib.units\nimport matplotlib.testing\nfrom matplotlib import _pylab_helpers, cbook, ft2font, pyplot as plt, ticker\nfrom .compare import comparable_formats, compare_images, make_test_filename\nfrom .exceptions import ImageComparisonFailure\n\n\n@contextlib.contextmanager\ndef _cleanup_cm():\n orig_units_registry = matplotlib.units.registry.copy()\n try:\n with warnings.catch_warnings(), matplotlib.rc_context():\n yield\n finally:\n matplotlib.units.registry.clear()\n matplotlib.units.registry.update(orig_units_registry)\n plt.close("all")\n\n\ndef _check_freetype_version(ver):\n if ver is None:\n return True\n\n if isinstance(ver, str):\n ver = (ver, ver)\n ver = [parse_version(x) for x in ver]\n found = parse_version(ft2font.__freetype_version__)\n\n return ver[0] <= found <= ver[1]\n\n\ndef _checked_on_freetype_version(required_freetype_version):\n import pytest\n return pytest.mark.xfail(\n not _check_freetype_version(required_freetype_version),\n reason=f"Mismatched version of freetype. "\n f"Test requires '{required_freetype_version}', "\n f"you have '{ft2font.__freetype_version__}'",\n raises=ImageComparisonFailure, strict=False)\n\n\ndef remove_ticks_and_titles(figure):\n figure.suptitle("")\n null_formatter = ticker.NullFormatter()\n def remove_ticks(ax):\n """Remove ticks in *ax* and all its child Axes."""\n ax.set_title("")\n ax.xaxis.set_major_formatter(null_formatter)\n ax.xaxis.set_minor_formatter(null_formatter)\n ax.yaxis.set_major_formatter(null_formatter)\n ax.yaxis.set_minor_formatter(null_formatter)\n try:\n ax.zaxis.set_major_formatter(null_formatter)\n ax.zaxis.set_minor_formatter(null_formatter)\n except AttributeError:\n pass\n for child in ax.child_axes:\n remove_ticks(child)\n for ax in figure.get_axes():\n remove_ticks(ax)\n\n\n@contextlib.contextmanager\ndef _collect_new_figures():\n """\n After::\n\n with _collect_new_figures() as figs:\n some_code()\n\n the list *figs* contains the figures that have been created during the\n execution of ``some_code``, sorted by figure number.\n """\n managers = _pylab_helpers.Gcf.figs\n preexisting = [manager for manager in managers.values()]\n new_figs = []\n try:\n yield new_figs\n finally:\n new_managers = sorted([manager for manager in managers.values()\n if manager not in preexisting],\n key=lambda manager: manager.num)\n new_figs[:] = [manager.canvas.figure for manager in new_managers]\n\n\ndef _raise_on_image_difference(expected, actual, tol):\n __tracebackhide__ = True\n\n err = compare_images(expected, actual, tol, in_decorator=True)\n if err:\n for key in ["actual", "expected", "diff"]:\n err[key] = os.path.relpath(err[key])\n raise ImageComparisonFailure(\n ('images not close (RMS %(rms).3f):'\n '\n\t%(actual)s\n\t%(expected)s\n\t%(diff)s') % err)\n\n\nclass _ImageComparisonBase:\n """\n Image comparison base class\n\n This class provides *just* the comparison-related functionality and avoids\n any code that would be specific to any testing framework.\n """\n\n def __init__(self, func, tol, remove_text, savefig_kwargs):\n self.func = func\n self.baseline_dir, self.result_dir = _image_directories(func)\n self.tol = tol\n self.remove_text = remove_text\n self.savefig_kwargs = savefig_kwargs\n\n def copy_baseline(self, baseline, extension):\n baseline_path = self.baseline_dir / baseline\n orig_expected_path = baseline_path.with_suffix(f'.{extension}')\n if extension == 'eps' and not orig_expected_path.exists():\n orig_expected_path = orig_expected_path.with_suffix('.pdf')\n expected_fname = make_test_filename(\n self.result_dir / orig_expected_path.name, 'expected')\n try:\n # os.symlink errors if the target already exists.\n with contextlib.suppress(OSError):\n os.remove(expected_fname)\n try:\n if 'microsoft' in uname().release.lower():\n raise OSError # On WSL, symlink breaks silently\n os.symlink(orig_expected_path, expected_fname)\n except OSError: # On Windows, symlink *may* be unavailable.\n shutil.copyfile(orig_expected_path, expected_fname)\n except OSError as err:\n raise ImageComparisonFailure(\n f"Missing baseline image {expected_fname} because the "\n f"following file cannot be accessed: "\n f"{orig_expected_path}") from err\n return expected_fname\n\n def compare(self, fig, baseline, extension, *, _lock=False):\n __tracebackhide__ = True\n\n if self.remove_text:\n remove_ticks_and_titles(fig)\n\n actual_path = (self.result_dir / baseline).with_suffix(f'.{extension}')\n kwargs = self.savefig_kwargs.copy()\n if extension == 'pdf':\n kwargs.setdefault('metadata',\n {'Creator': None, 'Producer': None,\n 'CreationDate': None})\n\n lock = (cbook._lock_path(actual_path)\n if _lock else contextlib.nullcontext())\n with lock:\n try:\n fig.savefig(actual_path, **kwargs)\n finally:\n # Matplotlib has an autouse fixture to close figures, but this\n # makes things more convenient for third-party users.\n plt.close(fig)\n expected_path = self.copy_baseline(baseline, extension)\n _raise_on_image_difference(expected_path, actual_path, self.tol)\n\n\ndef _pytest_image_comparison(baseline_images, extensions, tol,\n freetype_version, remove_text, savefig_kwargs,\n style):\n """\n Decorate function with image comparison for pytest.\n\n This function creates a decorator that wraps a figure-generating function\n with image comparison code.\n """\n import pytest\n\n KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY\n\n def decorator(func):\n old_sig = inspect.signature(func)\n\n @functools.wraps(func)\n @pytest.mark.parametrize('extension', extensions)\n @matplotlib.style.context(style)\n @_checked_on_freetype_version(freetype_version)\n @functools.wraps(func)\n def wrapper(*args, extension, request, **kwargs):\n __tracebackhide__ = True\n if 'extension' in old_sig.parameters:\n kwargs['extension'] = extension\n if 'request' in old_sig.parameters:\n kwargs['request'] = request\n\n if extension not in comparable_formats():\n reason = {\n 'pdf': 'because Ghostscript is not installed',\n 'eps': 'because Ghostscript is not installed',\n 'svg': 'because Inkscape is not installed',\n }.get(extension, 'on this system')\n pytest.skip(f"Cannot compare {extension} files {reason}")\n\n img = _ImageComparisonBase(func, tol=tol, remove_text=remove_text,\n savefig_kwargs=savefig_kwargs)\n matplotlib.testing.set_font_settings_for_testing()\n\n with _collect_new_figures() as figs:\n func(*args, **kwargs)\n\n # If the test is parametrized in any way other than applied via\n # this decorator, then we need to use a lock to prevent two\n # processes from touching the same output file.\n needs_lock = any(\n marker.args[0] != 'extension'\n for marker in request.node.iter_markers('parametrize'))\n\n if baseline_images is not None:\n our_baseline_images = baseline_images\n else:\n # Allow baseline image list to be produced on the fly based on\n # current parametrization.\n our_baseline_images = request.getfixturevalue(\n 'baseline_images')\n\n assert len(figs) == len(our_baseline_images), (\n f"Test generated {len(figs)} images but there are "\n f"{len(our_baseline_images)} baseline images")\n for fig, baseline in zip(figs, our_baseline_images):\n img.compare(fig, baseline, extension, _lock=needs_lock)\n\n parameters = list(old_sig.parameters.values())\n if 'extension' not in old_sig.parameters:\n parameters += [inspect.Parameter('extension', KEYWORD_ONLY)]\n if 'request' not in old_sig.parameters:\n parameters += [inspect.Parameter("request", KEYWORD_ONLY)]\n new_sig = old_sig.replace(parameters=parameters)\n wrapper.__signature__ = new_sig\n\n # Reach a bit into pytest internals to hoist the marks from our wrapped\n # function.\n new_marks = getattr(func, 'pytestmark', []) + wrapper.pytestmark\n wrapper.pytestmark = new_marks\n\n return wrapper\n\n return decorator\n\n\ndef image_comparison(baseline_images, extensions=None, tol=0,\n freetype_version=None, remove_text=False,\n savefig_kwarg=None,\n # Default of mpl_test_settings fixture and cleanup too.\n style=("classic", "_classic_test_patch")):\n """\n Compare images generated by the test with those specified in\n *baseline_images*, which must correspond, else an `.ImageComparisonFailure`\n exception will be raised.\n\n Parameters\n ----------\n baseline_images : list or None\n A list of strings specifying the names of the images generated by\n calls to `.Figure.savefig`.\n\n If *None*, the test function must use the ``baseline_images`` fixture,\n either as a parameter or with `pytest.mark.usefixtures`. This value is\n only allowed when using pytest.\n\n extensions : None or list of str\n The list of extensions to test, e.g. ``['png', 'pdf']``.\n\n If *None*, defaults to all supported extensions: png, pdf, and svg.\n\n When testing a single extension, it can be directly included in the\n names passed to *baseline_images*. In that case, *extensions* must not\n be set.\n\n In order to keep the size of the test suite from ballooning, we only\n include the ``svg`` or ``pdf`` outputs if the test is explicitly\n exercising a feature dependent on that backend (see also the\n `check_figures_equal` decorator for that purpose).\n\n tol : float, default: 0\n The RMS threshold above which the test is considered failed.\n\n Due to expected small differences in floating-point calculations, on\n 32-bit systems an additional 0.06 is added to this threshold.\n\n freetype_version : str or tuple\n The expected freetype version or range of versions for this test to\n pass.\n\n remove_text : bool\n Remove the title and tick text from the figure before comparison. This\n is useful to make the baseline images independent of variations in text\n rendering between different versions of FreeType.\n\n This does not remove other, more deliberate, text, such as legends and\n annotations.\n\n savefig_kwarg : dict\n Optional arguments that are passed to the savefig method.\n\n style : str, dict, or list\n The optional style(s) to apply to the image test. The test itself\n can also apply additional styles if desired. Defaults to ``["classic",\n "_classic_test_patch"]``.\n """\n\n if baseline_images is not None:\n # List of non-empty filename extensions.\n baseline_exts = [*filter(None, {Path(baseline).suffix[1:]\n for baseline in baseline_images})]\n if baseline_exts:\n if extensions is not None:\n raise ValueError(\n "When including extensions directly in 'baseline_images', "\n "'extensions' cannot be set as well")\n if len(baseline_exts) > 1:\n raise ValueError(\n "When including extensions directly in 'baseline_images', "\n "all baselines must share the same suffix")\n extensions = baseline_exts\n baseline_images = [ # Chop suffix out from baseline_images.\n Path(baseline).stem for baseline in baseline_images]\n if extensions is None:\n # Default extensions to test, if not set via baseline_images.\n extensions = ['png', 'pdf', 'svg']\n if savefig_kwarg is None:\n savefig_kwarg = dict() # default no kwargs to savefig\n if sys.maxsize <= 2**32:\n tol += 0.06\n return _pytest_image_comparison(\n baseline_images=baseline_images, extensions=extensions, tol=tol,\n freetype_version=freetype_version, remove_text=remove_text,\n savefig_kwargs=savefig_kwarg, style=style)\n\n\ndef check_figures_equal(*, extensions=("png", "pdf", "svg"), tol=0):\n """\n Decorator for test cases that generate and compare two figures.\n\n The decorated function must take two keyword arguments, *fig_test*\n and *fig_ref*, and draw the test and reference images on them.\n After the function returns, the figures are saved and compared.\n\n This decorator should be preferred over `image_comparison` when possible in\n order to keep the size of the test suite from ballooning.\n\n Parameters\n ----------\n extensions : list, default: ["png", "pdf", "svg"]\n The extensions to test.\n tol : float\n The RMS threshold above which the test is considered failed.\n\n Raises\n ------\n RuntimeError\n If any new figures are created (and not subsequently closed) inside\n the test function.\n\n Examples\n --------\n Check that calling `.Axes.plot` with a single argument plots it against\n ``[0, 1, 2, ...]``::\n\n @check_figures_equal()\n def test_plot(fig_test, fig_ref):\n fig_test.subplots().plot([1, 3, 5])\n fig_ref.subplots().plot([0, 1, 2], [1, 3, 5])\n\n """\n ALLOWED_CHARS = set(string.digits + string.ascii_letters + '_-[]()')\n KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY\n\n def decorator(func):\n import pytest\n\n _, result_dir = _image_directories(func)\n old_sig = inspect.signature(func)\n\n if not {"fig_test", "fig_ref"}.issubset(old_sig.parameters):\n raise ValueError("The decorated function must have at least the "\n "parameters 'fig_test' and 'fig_ref', but your "\n f"function has the signature {old_sig}")\n\n @pytest.mark.parametrize("ext", extensions)\n def wrapper(*args, ext, request, **kwargs):\n if 'ext' in old_sig.parameters:\n kwargs['ext'] = ext\n if 'request' in old_sig.parameters:\n kwargs['request'] = request\n\n file_name = "".join(c for c in request.node.name\n if c in ALLOWED_CHARS)\n try:\n fig_test = plt.figure("test")\n fig_ref = plt.figure("reference")\n with _collect_new_figures() as figs:\n func(*args, fig_test=fig_test, fig_ref=fig_ref, **kwargs)\n if figs:\n raise RuntimeError('Number of open figures changed during '\n 'test. Make sure you are plotting to '\n 'fig_test or fig_ref, or if this is '\n 'deliberate explicitly close the '\n 'new figure(s) inside the test.')\n test_image_path = result_dir / (file_name + "." + ext)\n ref_image_path = result_dir / (file_name + "-expected." + ext)\n fig_test.savefig(test_image_path)\n fig_ref.savefig(ref_image_path)\n _raise_on_image_difference(\n ref_image_path, test_image_path, tol=tol\n )\n finally:\n plt.close(fig_test)\n plt.close(fig_ref)\n\n parameters = [\n param\n for param in old_sig.parameters.values()\n if param.name not in {"fig_test", "fig_ref"}\n ]\n if 'ext' not in old_sig.parameters:\n parameters += [inspect.Parameter("ext", KEYWORD_ONLY)]\n if 'request' not in old_sig.parameters:\n parameters += [inspect.Parameter("request", KEYWORD_ONLY)]\n new_sig = old_sig.replace(parameters=parameters)\n wrapper.__signature__ = new_sig\n\n # reach a bit into pytest internals to hoist the marks from\n # our wrapped function\n new_marks = getattr(func, "pytestmark", []) + wrapper.pytestmark\n wrapper.pytestmark = new_marks\n\n return wrapper\n\n return decorator\n\n\ndef _image_directories(func):\n """\n Compute the baseline and result image directories for testing *func*.\n\n For test module ``foo.bar.test_baz``, the baseline directory is at\n ``foo/bar/baseline_images/test_baz`` and the result directory at\n ``$(pwd)/result_images/test_baz``. The result directory is created if it\n doesn't exist.\n """\n module_path = Path(inspect.getfile(func))\n baseline_dir = module_path.parent / "baseline_images" / module_path.stem\n result_dir = Path().resolve() / "result_images" / module_path.stem\n result_dir.mkdir(parents=True, exist_ok=True)\n return baseline_dir, result_dir\n | .venv\Lib\site-packages\matplotlib\testing\decorators.py | decorators.py | Python | 18,022 | 0.95 | 0.204741 | 0.041775 | awesome-app | 102 | 2024-04-27T07:20:51.865287 | Apache-2.0 | true | 8ff295df2db5eeb63f9f94967da91a67 |
from collections.abc import Callable, Sequence\nfrom pathlib import Path\nfrom typing import Any, TypeVar\nfrom typing_extensions import ParamSpec\n\nfrom matplotlib.figure import Figure\nfrom matplotlib.typing import RcStyleType\n\n_P = ParamSpec("_P")\n_R = TypeVar("_R")\n\ndef remove_ticks_and_titles(figure: Figure) -> None: ...\ndef image_comparison(\n baseline_images: list[str] | None,\n extensions: list[str] | None = ...,\n tol: float = ...,\n freetype_version: tuple[str, str] | str | None = ...,\n remove_text: bool = ...,\n savefig_kwarg: dict[str, Any] | None = ...,\n style: RcStyleType = ...,\n) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...\ndef check_figures_equal(\n *, extensions: Sequence[str] = ..., tol: float = ...\n) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...\ndef _image_directories(func: Callable) -> tuple[Path, Path]: ...\n | .venv\Lib\site-packages\matplotlib\testing\decorators.pyi | decorators.pyi | Other | 872 | 0.85 | 0.16 | 0.045455 | vue-tools | 335 | 2023-11-02T06:39:27.528694 | MIT | true | 737bf4f27782866af1ef9082131d4765 |
class ImageComparisonFailure(AssertionError):\n """\n Raise this exception to mark a test as a comparison between two images.\n """\n | .venv\Lib\site-packages\matplotlib\testing\exceptions.py | exceptions.py | Python | 138 | 0.85 | 0.25 | 0 | awesome-app | 112 | 2023-12-23T21:34:54.638903 | MIT | true | 325cb4147f18a55a435591c1d73007aa |
"""\n========================\nWidget testing utilities\n========================\n\nSee also :mod:`matplotlib.tests.test_widgets`.\n"""\n\nfrom unittest import mock\n\nimport matplotlib.pyplot as plt\n\n\ndef get_ax():\n """Create a plot and return its Axes."""\n fig, ax = plt.subplots(1, 1)\n ax.plot([0, 200], [0, 200])\n ax.set_aspect(1.0)\n fig.canvas.draw()\n return ax\n\n\ndef noop(*args, **kwargs):\n pass\n\n\ndef mock_event(ax, button=1, xdata=0, ydata=0, key=None, step=1):\n r"""\n Create a mock event that can stand in for `.Event` and its subclasses.\n\n This event is intended to be used in tests where it can be passed into\n event handling functions.\n\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n The Axes the event will be in.\n xdata : float\n x coord of mouse in data coords.\n ydata : float\n y coord of mouse in data coords.\n button : None or `MouseButton` or {'up', 'down'}\n The mouse button pressed in this event (see also `.MouseEvent`).\n key : None or str\n The key pressed when the mouse event triggered (see also `.KeyEvent`).\n step : int\n Number of scroll steps (positive for 'up', negative for 'down').\n\n Returns\n -------\n event\n A `.Event`\-like Mock instance.\n """\n event = mock.Mock()\n event.button = button\n event.x, event.y = ax.transData.transform([(xdata, ydata),\n (xdata, ydata)])[0]\n event.xdata, event.ydata = xdata, ydata\n event.inaxes = ax\n event.canvas = ax.get_figure(root=True).canvas\n event.key = key\n event.step = step\n event.guiEvent = None\n event.name = 'Custom'\n return event\n\n\ndef do_event(tool, etype, button=1, xdata=0, ydata=0, key=None, step=1):\n """\n Trigger an event on the given tool.\n\n Parameters\n ----------\n tool : matplotlib.widgets.AxesWidget\n etype : str\n The event to trigger.\n xdata : float\n x coord of mouse in data coords.\n ydata : float\n y coord of mouse in data coords.\n button : None or `MouseButton` or {'up', 'down'}\n The mouse button pressed in this event (see also `.MouseEvent`).\n key : None or str\n The key pressed when the mouse event triggered (see also `.KeyEvent`).\n step : int\n Number of scroll steps (positive for 'up', negative for 'down').\n """\n event = mock_event(tool.ax, button, xdata, ydata, key, step)\n func = getattr(tool, etype)\n func(event)\n\n\ndef click_and_drag(tool, start, end, key=None):\n """\n Helper to simulate a mouse drag operation.\n\n Parameters\n ----------\n tool : `~matplotlib.widgets.Widget`\n start : [float, float]\n Starting point in data coordinates.\n end : [float, float]\n End point in data coordinates.\n key : None or str\n An optional key that is pressed during the whole operation\n (see also `.KeyEvent`).\n """\n if key is not None:\n # Press key\n do_event(tool, 'on_key_press', xdata=start[0], ydata=start[1],\n button=1, key=key)\n # Click, move, and release mouse\n do_event(tool, 'press', xdata=start[0], ydata=start[1], button=1)\n do_event(tool, 'onmove', xdata=end[0], ydata=end[1], button=1)\n do_event(tool, 'release', xdata=end[0], ydata=end[1], button=1)\n if key is not None:\n # Release key\n do_event(tool, 'on_key_release', xdata=end[0], ydata=end[1],\n button=1, key=key)\n | .venv\Lib\site-packages\matplotlib\testing\widgets.py | widgets.py | Python | 3,480 | 0.95 | 0.10084 | 0.029703 | python-kit | 991 | 2025-06-26T20:42:24.716406 | GPL-3.0 | true | 2f10b5c5d1c45b6356ea837fe24826b3 |
from typing import Any, Literal\n\nfrom matplotlib.axes import Axes\nfrom matplotlib.backend_bases import Event, MouseButton\nfrom matplotlib.widgets import AxesWidget, Widget\n\ndef get_ax() -> Axes: ...\ndef noop(*args: Any, **kwargs: Any) -> None: ...\ndef mock_event(\n ax: Axes,\n button: MouseButton | int | Literal["up", "down"] | None = ...,\n xdata: float = ...,\n ydata: float = ...,\n key: str | None = ...,\n step: int = ...,\n) -> Event: ...\ndef do_event(\n tool: AxesWidget,\n etype: str,\n button: MouseButton | int | Literal["up", "down"] | None = ...,\n xdata: float = ...,\n ydata: float = ...,\n key: str | None = ...,\n step: int = ...,\n) -> None: ...\ndef click_and_drag(\n tool: Widget,\n start: tuple[float, float],\n end: tuple[float, float],\n key: str | None = ...,\n) -> None: ...\n | .venv\Lib\site-packages\matplotlib\testing\widgets.pyi | widgets.pyi | Other | 831 | 0.85 | 0.16129 | 0 | awesome-app | 409 | 2025-01-27T12:03:51.952481 | GPL-3.0 | true | 1b1165253556b8a736d6b2966290f449 |
"""\npytest markers for the internal Matplotlib test suite.\n"""\n\nimport logging\nimport shutil\n\nimport pytest\n\nimport matplotlib.testing\nimport matplotlib.testing.compare\nfrom matplotlib import _get_executable_info, ExecutableNotFoundError\n\n\n_log = logging.getLogger(__name__)\n\n\ndef _checkdep_usetex() -> bool:\n if not shutil.which("tex"):\n _log.warning("usetex mode requires TeX.")\n return False\n try:\n _get_executable_info("dvipng")\n except ExecutableNotFoundError:\n _log.warning("usetex mode requires dvipng.")\n return False\n try:\n _get_executable_info("gs")\n except ExecutableNotFoundError:\n _log.warning("usetex mode requires ghostscript.")\n return False\n return True\n\n\nneeds_ghostscript = pytest.mark.skipif(\n "eps" not in matplotlib.testing.compare.converter,\n reason="This test needs a ghostscript installation")\nneeds_pgf_lualatex = pytest.mark.skipif(\n not matplotlib.testing._check_for_pgf('lualatex'),\n reason='lualatex + pgf is required')\nneeds_pgf_pdflatex = pytest.mark.skipif(\n not matplotlib.testing._check_for_pgf('pdflatex'),\n reason='pdflatex + pgf is required')\nneeds_pgf_xelatex = pytest.mark.skipif(\n not matplotlib.testing._check_for_pgf('xelatex'),\n reason='xelatex + pgf is required')\nneeds_usetex = pytest.mark.skipif(\n not _checkdep_usetex(),\n reason="This test needs a TeX installation")\n | .venv\Lib\site-packages\matplotlib\testing\_markers.py | _markers.py | Python | 1,419 | 0.85 | 0.102041 | 0 | react-lib | 43 | 2025-06-09T05:53:27.087811 | BSD-3-Clause | true | 86be8a5b3a83d4b6f9c60cf1285e2a4f |
"""\nHelper functions for testing.\n"""\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nimport locale\nimport logging\nimport os\nimport subprocess\nimport sys\n\nimport matplotlib as mpl\nfrom matplotlib import _api\n\n_log = logging.getLogger(__name__)\n\n\ndef set_font_settings_for_testing():\n mpl.rcParams['font.family'] = 'DejaVu Sans'\n mpl.rcParams['text.hinting'] = 'none'\n mpl.rcParams['text.hinting_factor'] = 8\n\n\ndef set_reproducibility_for_testing():\n mpl.rcParams['svg.hashsalt'] = 'matplotlib'\n\n\ndef setup():\n # The baseline images are created in this locale, so we should use\n # it during all of the tests.\n\n try:\n locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\n except locale.Error:\n try:\n locale.setlocale(locale.LC_ALL, 'English_United States.1252')\n except locale.Error:\n _log.warning(\n "Could not set locale to English/United States. "\n "Some date-related tests may fail.")\n\n mpl.use('Agg')\n\n with _api.suppress_matplotlib_deprecation_warning():\n mpl.rcdefaults() # Start with all defaults\n\n # These settings *must* be hardcoded for running the comparison tests and\n # are not necessarily the default values as specified in rcsetup.py.\n set_font_settings_for_testing()\n set_reproducibility_for_testing()\n\n\ndef subprocess_run_for_testing(command, env=None, timeout=60, stdout=None,\n stderr=None, check=False, text=True,\n capture_output=False):\n """\n Create and run a subprocess.\n\n Thin wrapper around `subprocess.run`, intended for testing. Will\n mark fork() failures on Cygwin as expected failures: not a\n success, but not indicating a problem with the code either.\n\n Parameters\n ----------\n args : list of str\n env : dict[str, str]\n timeout : float\n stdout, stderr\n check : bool\n text : bool\n Also called ``universal_newlines`` in subprocess. I chose this\n name since the main effect is returning bytes (`False`) vs. str\n (`True`), though it also tries to normalize newlines across\n platforms.\n capture_output : bool\n Set stdout and stderr to subprocess.PIPE\n\n Returns\n -------\n proc : subprocess.Popen\n\n See Also\n --------\n subprocess.run\n\n Raises\n ------\n pytest.xfail\n If platform is Cygwin and subprocess reports a fork() failure.\n """\n if capture_output:\n stdout = stderr = subprocess.PIPE\n try:\n proc = subprocess.run(\n command, env=env,\n timeout=timeout, check=check,\n stdout=stdout, stderr=stderr,\n text=text\n )\n except BlockingIOError:\n if sys.platform == "cygwin":\n # Might want to make this more specific\n import pytest\n pytest.xfail("Fork failure")\n raise\n return proc\n\n\ndef subprocess_run_helper(func, *args, timeout, extra_env=None):\n """\n Run a function in a sub-process.\n\n Parameters\n ----------\n func : function\n The function to be run. It must be in a module that is importable.\n *args : str\n Any additional command line arguments to be passed in\n the first argument to ``subprocess.run``.\n extra_env : dict[str, str]\n Any additional environment variables to be set for the subprocess.\n """\n target = func.__name__\n module = func.__module__\n file = func.__code__.co_filename\n proc = subprocess_run_for_testing(\n [\n sys.executable,\n "-c",\n f"import importlib.util;"\n f"_spec = importlib.util.spec_from_file_location({module!r}, {file!r});"\n f"_module = importlib.util.module_from_spec(_spec);"\n f"_spec.loader.exec_module(_module);"\n f"_module.{target}()",\n *args\n ],\n env={**os.environ, "SOURCE_DATE_EPOCH": "0", **(extra_env or {})},\n timeout=timeout, check=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n text=True\n )\n return proc\n\n\ndef _check_for_pgf(texsystem):\n """\n Check if a given TeX system + pgf is available\n\n Parameters\n ----------\n texsystem : str\n The executable name to check\n """\n with TemporaryDirectory() as tmpdir:\n tex_path = Path(tmpdir, "test.tex")\n tex_path.write_text(r"""\n \documentclass{article}\n \usepackage{pgf}\n \begin{document}\n \typeout{pgfversion=\pgfversion}\n \makeatletter\n \@@end\n """, encoding="utf-8")\n try:\n subprocess.check_call(\n [texsystem, "-halt-on-error", str(tex_path)], cwd=tmpdir,\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n except (OSError, subprocess.CalledProcessError):\n return False\n return True\n\n\ndef _has_tex_package(package):\n try:\n mpl.dviread.find_tex_file(f"{package}.sty")\n return True\n except FileNotFoundError:\n return False\n\n\ndef ipython_in_subprocess(requested_backend_or_gui_framework, all_expected_backends):\n import pytest\n IPython = pytest.importorskip("IPython")\n\n if sys.platform == "win32":\n pytest.skip("Cannot change backend running IPython in subprocess on Windows")\n\n if (IPython.version_info[:3] == (8, 24, 0) and\n requested_backend_or_gui_framework == "osx"):\n pytest.skip("Bug using macosx backend in IPython 8.24.0 fixed in 8.24.1")\n\n # This code can be removed when Python 3.12, the latest version supported\n # by IPython < 8.24, reaches end-of-life in late 2028.\n for min_version, backend in all_expected_backends.items():\n if IPython.version_info[:2] >= min_version:\n expected_backend = backend\n break\n\n code = ("import matplotlib as mpl, matplotlib.pyplot as plt;"\n "fig, ax=plt.subplots(); ax.plot([1, 3, 2]); mpl.get_backend()")\n proc = subprocess_run_for_testing(\n [\n "ipython",\n "--no-simple-prompt",\n f"--matplotlib={requested_backend_or_gui_framework}",\n "-c", code,\n ],\n check=True,\n capture_output=True,\n )\n\n assert proc.stdout.strip().endswith(f"'{expected_backend}'")\n\n\ndef is_ci_environment():\n # Common CI variables\n ci_environment_variables = [\n 'CI', # Generic CI environment variable\n 'CONTINUOUS_INTEGRATION', # Generic CI environment variable\n 'TRAVIS', # Travis CI\n 'CIRCLECI', # CircleCI\n 'JENKINS', # Jenkins\n 'GITLAB_CI', # GitLab CI\n 'GITHUB_ACTIONS', # GitHub Actions\n 'TEAMCITY_VERSION' # TeamCity\n # Add other CI environment variables as needed\n ]\n\n for env_var in ci_environment_variables:\n if os.getenv(env_var):\n return True\n\n return False\n | .venv\Lib\site-packages\matplotlib\testing\__init__.py | __init__.py | Python | 6,942 | 0.95 | 0.128205 | 0.056122 | vue-tools | 544 | 2024-12-02T21:14:55.387025 | Apache-2.0 | true | 7cb8b5857d43a48555668a15bb4731bc |
from collections.abc import Callable\nimport subprocess\nfrom typing import Any, IO, Literal, overload\n\ndef set_font_settings_for_testing() -> None: ...\ndef set_reproducibility_for_testing() -> None: ...\ndef setup() -> None: ...\n@overload\ndef subprocess_run_for_testing(\n command: list[str],\n env: dict[str, str] | None = ...,\n timeout: float | None = ...,\n stdout: int | IO[Any] | None = ...,\n stderr: int | IO[Any] | None = ...,\n check: bool = ...,\n *,\n text: Literal[True],\n capture_output: bool = ...,\n) -> subprocess.CompletedProcess[str]: ...\n@overload\ndef subprocess_run_for_testing(\n command: list[str],\n env: dict[str, str] | None = ...,\n timeout: float | None = ...,\n stdout: int | IO[Any] | None = ...,\n stderr: int | IO[Any] | None = ...,\n check: bool = ...,\n text: Literal[False] = ...,\n capture_output: bool = ...,\n) -> subprocess.CompletedProcess[bytes]: ...\n@overload\ndef subprocess_run_for_testing(\n command: list[str],\n env: dict[str, str] | None = ...,\n timeout: float | None = ...,\n stdout: int | IO[Any] | None = ...,\n stderr: int | IO[Any] | None = ...,\n check: bool = ...,\n text: bool = ...,\n capture_output: bool = ...,\n) -> subprocess.CompletedProcess[bytes] | subprocess.CompletedProcess[str]: ...\ndef subprocess_run_helper(\n func: Callable[[], None],\n *args: Any,\n timeout: float,\n extra_env: dict[str, str] | None = ...,\n) -> subprocess.CompletedProcess[str]: ...\ndef _check_for_pgf(texsystem: str) -> bool: ...\ndef _has_tex_package(package: str) -> bool: ...\ndef ipython_in_subprocess(\n requested_backend_or_gui_framework: str,\n all_expected_backends: dict[tuple[int, int], str],\n) -> None: ...\ndef is_ci_environment() -> bool: ...\n | .venv\Lib\site-packages\matplotlib\testing\__init__.pyi | __init__.pyi | Other | 1,752 | 0.85 | 0.203704 | 0.037736 | awesome-app | 509 | 2024-10-10T19:26:18.934622 | BSD-3-Clause | true | 53e2c95c0ea1febb3e05d1afae7557db |
"""Duration module."""\n\nimport functools\nimport operator\n\nfrom matplotlib import _api\n\n\nclass Duration:\n """Class Duration in development."""\n\n allowed = ["ET", "UTC"]\n\n def __init__(self, frame, seconds):\n """\n Create a new Duration object.\n\n = ERROR CONDITIONS\n - If the input frame is not in the allowed list, an error is thrown.\n\n = INPUT VARIABLES\n - frame The frame of the duration. Must be 'ET' or 'UTC'\n - seconds The number of seconds in the Duration.\n """\n _api.check_in_list(self.allowed, frame=frame)\n self._frame = frame\n self._seconds = seconds\n\n def frame(self):\n """Return the frame the duration is in."""\n return self._frame\n\n def __abs__(self):\n """Return the absolute value of the duration."""\n return Duration(self._frame, abs(self._seconds))\n\n def __neg__(self):\n """Return the negative value of this Duration."""\n return Duration(self._frame, -self._seconds)\n\n def seconds(self):\n """Return the number of seconds in the Duration."""\n return self._seconds\n\n def __bool__(self):\n return self._seconds != 0\n\n def _cmp(self, op, rhs):\n """\n Check that *self* and *rhs* share frames; compare them using *op*.\n """\n self.checkSameFrame(rhs, "compare")\n return op(self._seconds, rhs._seconds)\n\n __eq__ = functools.partialmethod(_cmp, operator.eq)\n __ne__ = functools.partialmethod(_cmp, operator.ne)\n __lt__ = functools.partialmethod(_cmp, operator.lt)\n __le__ = functools.partialmethod(_cmp, operator.le)\n __gt__ = functools.partialmethod(_cmp, operator.gt)\n __ge__ = functools.partialmethod(_cmp, operator.ge)\n\n def __add__(self, rhs):\n """\n Add two Durations.\n\n = ERROR CONDITIONS\n - If the input rhs is not in the same frame, an error is thrown.\n\n = INPUT VARIABLES\n - rhs The Duration to add.\n\n = RETURN VALUE\n - Returns the sum of ourselves and the input Duration.\n """\n # Delay-load due to circular dependencies.\n import matplotlib.testing.jpl_units as U\n\n if isinstance(rhs, U.Epoch):\n return rhs + self\n\n self.checkSameFrame(rhs, "add")\n return Duration(self._frame, self._seconds + rhs._seconds)\n\n def __sub__(self, rhs):\n """\n Subtract two Durations.\n\n = ERROR CONDITIONS\n - If the input rhs is not in the same frame, an error is thrown.\n\n = INPUT VARIABLES\n - rhs The Duration to subtract.\n\n = RETURN VALUE\n - Returns the difference of ourselves and the input Duration.\n """\n self.checkSameFrame(rhs, "sub")\n return Duration(self._frame, self._seconds - rhs._seconds)\n\n def __mul__(self, rhs):\n """\n Scale a UnitDbl by a value.\n\n = INPUT VARIABLES\n - rhs The scalar to multiply by.\n\n = RETURN VALUE\n - Returns the scaled Duration.\n """\n return Duration(self._frame, self._seconds * float(rhs))\n\n __rmul__ = __mul__\n\n def __str__(self):\n """Print the Duration."""\n return f"{self._seconds:g} {self._frame}"\n\n def __repr__(self):\n """Print the Duration."""\n return f"Duration('{self._frame}', {self._seconds:g})"\n\n def checkSameFrame(self, rhs, func):\n """\n Check to see if frames are the same.\n\n = ERROR CONDITIONS\n - If the frame of the rhs Duration is not the same as our frame,\n an error is thrown.\n\n = INPUT VARIABLES\n - rhs The Duration to check for the same frame\n - func The name of the function doing the check.\n """\n if self._frame != rhs._frame:\n raise ValueError(\n f"Cannot {func} Durations with different frames.\n"\n f"LHS: {self._frame}\n"\n f"RHS: {rhs._frame}")\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\Duration.py | Duration.py | Python | 3,966 | 0.95 | 0.137681 | 0.009615 | node-utils | 8 | 2024-06-24T05:20:32.004024 | GPL-3.0 | true | 1620def7daea4d62d0d66dd0a3a75618 |
"""Epoch module."""\n\nimport functools\nimport operator\nimport math\nimport datetime as DT\n\nfrom matplotlib import _api\nfrom matplotlib.dates import date2num\n\n\nclass Epoch:\n # Frame conversion offsets in seconds\n # t(TO) = t(FROM) + allowed[ FROM ][ TO ]\n allowed = {\n "ET": {\n "UTC": +64.1839,\n },\n "UTC": {\n "ET": -64.1839,\n },\n }\n\n def __init__(self, frame, sec=None, jd=None, daynum=None, dt=None):\n """\n Create a new Epoch object.\n\n Build an epoch 1 of 2 ways:\n\n Using seconds past a Julian date:\n # Epoch('ET', sec=1e8, jd=2451545)\n\n or using a matplotlib day number\n # Epoch('ET', daynum=730119.5)\n\n = ERROR CONDITIONS\n - If the input units are not in the allowed list, an error is thrown.\n\n = INPUT VARIABLES\n - frame The frame of the epoch. Must be 'ET' or 'UTC'\n - sec The number of seconds past the input JD.\n - jd The Julian date of the epoch.\n - daynum The matplotlib day number of the epoch.\n - dt A python datetime instance.\n """\n if ((sec is None and jd is not None) or\n (sec is not None and jd is None) or\n (daynum is not None and\n (sec is not None or jd is not None)) or\n (daynum is None and dt is None and\n (sec is None or jd is None)) or\n (daynum is not None and dt is not None) or\n (dt is not None and (sec is not None or jd is not None)) or\n ((dt is not None) and not isinstance(dt, DT.datetime))):\n raise ValueError(\n "Invalid inputs. Must enter sec and jd together, "\n "daynum by itself, or dt (must be a python datetime).\n"\n "Sec = %s\n"\n "JD = %s\n"\n "dnum= %s\n"\n "dt = %s" % (sec, jd, daynum, dt))\n\n _api.check_in_list(self.allowed, frame=frame)\n self._frame = frame\n\n if dt is not None:\n daynum = date2num(dt)\n\n if daynum is not None:\n # 1-JAN-0001 in JD = 1721425.5\n jd = float(daynum) + 1721425.5\n self._jd = math.floor(jd)\n self._seconds = (jd - self._jd) * 86400.0\n\n else:\n self._seconds = float(sec)\n self._jd = float(jd)\n\n # Resolve seconds down to [ 0, 86400)\n deltaDays = math.floor(self._seconds / 86400)\n self._jd += deltaDays\n self._seconds -= deltaDays * 86400.0\n\n def convert(self, frame):\n if self._frame == frame:\n return self\n\n offset = self.allowed[self._frame][frame]\n\n return Epoch(frame, self._seconds + offset, self._jd)\n\n def frame(self):\n return self._frame\n\n def julianDate(self, frame):\n t = self\n if frame != self._frame:\n t = self.convert(frame)\n\n return t._jd + t._seconds / 86400.0\n\n def secondsPast(self, frame, jd):\n t = self\n if frame != self._frame:\n t = self.convert(frame)\n\n delta = t._jd - jd\n return t._seconds + delta * 86400\n\n def _cmp(self, op, rhs):\n """Compare Epochs *self* and *rhs* using operator *op*."""\n t = self\n if self._frame != rhs._frame:\n t = self.convert(rhs._frame)\n if t._jd != rhs._jd:\n return op(t._jd, rhs._jd)\n return op(t._seconds, rhs._seconds)\n\n __eq__ = functools.partialmethod(_cmp, operator.eq)\n __ne__ = functools.partialmethod(_cmp, operator.ne)\n __lt__ = functools.partialmethod(_cmp, operator.lt)\n __le__ = functools.partialmethod(_cmp, operator.le)\n __gt__ = functools.partialmethod(_cmp, operator.gt)\n __ge__ = functools.partialmethod(_cmp, operator.ge)\n\n def __add__(self, rhs):\n """\n Add a duration to an Epoch.\n\n = INPUT VARIABLES\n - rhs The Epoch to subtract.\n\n = RETURN VALUE\n - Returns the difference of ourselves and the input Epoch.\n """\n t = self\n if self._frame != rhs.frame():\n t = self.convert(rhs._frame)\n\n sec = t._seconds + rhs.seconds()\n\n return Epoch(t._frame, sec, t._jd)\n\n def __sub__(self, rhs):\n """\n Subtract two Epoch's or a Duration from an Epoch.\n\n Valid:\n Duration = Epoch - Epoch\n Epoch = Epoch - Duration\n\n = INPUT VARIABLES\n - rhs The Epoch to subtract.\n\n = RETURN VALUE\n - Returns either the duration between to Epoch's or the a new\n Epoch that is the result of subtracting a duration from an epoch.\n """\n # Delay-load due to circular dependencies.\n import matplotlib.testing.jpl_units as U\n\n # Handle Epoch - Duration\n if isinstance(rhs, U.Duration):\n return self + -rhs\n\n t = self\n if self._frame != rhs._frame:\n t = self.convert(rhs._frame)\n\n days = t._jd - rhs._jd\n sec = t._seconds - rhs._seconds\n\n return U.Duration(rhs._frame, days*86400 + sec)\n\n def __str__(self):\n """Print the Epoch."""\n return f"{self.julianDate(self._frame):22.15e} {self._frame}"\n\n def __repr__(self):\n """Print the Epoch."""\n return str(self)\n\n @staticmethod\n def range(start, stop, step):\n """\n Generate a range of Epoch objects.\n\n Similar to the Python range() method. Returns the range [\n start, stop) at the requested step. Each element will be a\n Epoch object.\n\n = INPUT VARIABLES\n - start The starting value of the range.\n - stop The stop value of the range.\n - step Step to use.\n\n = RETURN VALUE\n - Returns a list containing the requested Epoch values.\n """\n elems = []\n\n i = 0\n while True:\n d = start + i * step\n if d >= stop:\n break\n\n elems.append(d)\n i += 1\n\n return elems\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\Epoch.py | Epoch.py | Python | 6,100 | 0.95 | 0.118483 | 0.04878 | awesome-app | 837 | 2024-08-23T04:13:26.654851 | Apache-2.0 | true | 79683f4fd6c228a4d6784f6e989c9cca |
"""EpochConverter module containing class EpochConverter."""\n\nfrom matplotlib import cbook, units\nimport matplotlib.dates as date_ticker\n\n__all__ = ['EpochConverter']\n\n\nclass EpochConverter(units.ConversionInterface):\n """\n Provides Matplotlib conversion functionality for Monte Epoch and Duration\n classes.\n """\n\n jdRef = 1721425.5\n\n @staticmethod\n def axisinfo(unit, axis):\n # docstring inherited\n majloc = date_ticker.AutoDateLocator()\n majfmt = date_ticker.AutoDateFormatter(majloc)\n return units.AxisInfo(majloc=majloc, majfmt=majfmt, label=unit)\n\n @staticmethod\n def float2epoch(value, unit):\n """\n Convert a Matplotlib floating-point date into an Epoch of the specified\n units.\n\n = INPUT VARIABLES\n - value The Matplotlib floating-point date.\n - unit The unit system to use for the Epoch.\n\n = RETURN VALUE\n - Returns the value converted to an Epoch in the specified time system.\n """\n # Delay-load due to circular dependencies.\n import matplotlib.testing.jpl_units as U\n\n secPastRef = value * 86400.0 * U.UnitDbl(1.0, 'sec')\n return U.Epoch(unit, secPastRef, EpochConverter.jdRef)\n\n @staticmethod\n def epoch2float(value, unit):\n """\n Convert an Epoch value to a float suitable for plotting as a python\n datetime object.\n\n = INPUT VARIABLES\n - value An Epoch or list of Epochs that need to be converted.\n - unit The units to use for an axis with Epoch data.\n\n = RETURN VALUE\n - Returns the value parameter converted to floats.\n """\n return value.julianDate(unit) - EpochConverter.jdRef\n\n @staticmethod\n def duration2float(value):\n """\n Convert a Duration value to a float suitable for plotting as a python\n datetime object.\n\n = INPUT VARIABLES\n - value A Duration or list of Durations that need to be converted.\n\n = RETURN VALUE\n - Returns the value parameter converted to floats.\n """\n return value.seconds() / 86400.0\n\n @staticmethod\n def convert(value, unit, axis):\n # docstring inherited\n\n # Delay-load due to circular dependencies.\n import matplotlib.testing.jpl_units as U\n\n if not cbook.is_scalar_or_string(value):\n return [EpochConverter.convert(x, unit, axis) for x in value]\n if unit is None:\n unit = EpochConverter.default_units(value, axis)\n if isinstance(value, U.Duration):\n return EpochConverter.duration2float(value)\n else:\n return EpochConverter.epoch2float(value, unit)\n\n @staticmethod\n def default_units(value, axis):\n # docstring inherited\n if cbook.is_scalar_or_string(value):\n return value.frame()\n else:\n return EpochConverter.default_units(value[0], axis)\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\EpochConverter.py | EpochConverter.py | Python | 2,944 | 0.95 | 0.191489 | 0.067568 | vue-tools | 225 | 2024-04-25T15:25:58.589183 | GPL-3.0 | true | f7f4e2993f0c15803c4d2b46e8c9b0cb |
"""StrConverter module containing class StrConverter."""\n\nimport numpy as np\n\nimport matplotlib.units as units\n\n__all__ = ['StrConverter']\n\n\nclass StrConverter(units.ConversionInterface):\n """\n A Matplotlib converter class for string data values.\n\n Valid units for string are:\n - 'indexed' : Values are indexed as they are specified for plotting.\n - 'sorted' : Values are sorted alphanumerically.\n - 'inverted' : Values are inverted so that the first value is on top.\n - 'sorted-inverted' : A combination of 'sorted' and 'inverted'\n """\n\n @staticmethod\n def axisinfo(unit, axis):\n # docstring inherited\n return None\n\n @staticmethod\n def convert(value, unit, axis):\n # docstring inherited\n\n if value == []:\n return []\n\n # we delay loading to make matplotlib happy\n ax = axis.axes\n if axis is ax.xaxis:\n isXAxis = True\n else:\n isXAxis = False\n\n axis.get_major_ticks()\n ticks = axis.get_ticklocs()\n labels = axis.get_ticklabels()\n\n labels = [l.get_text() for l in labels if l.get_text()]\n\n if not labels:\n ticks = []\n labels = []\n\n if not np.iterable(value):\n value = [value]\n\n newValues = []\n for v in value:\n if v not in labels and v not in newValues:\n newValues.append(v)\n\n labels.extend(newValues)\n\n # DISABLED: This is disabled because matplotlib bar plots do not\n # DISABLED: recalculate the unit conversion of the data values\n # DISABLED: this is due to design and is not really a bug.\n # DISABLED: If this gets changed, then we can activate the following\n # DISABLED: block of code. Note that this works for line plots.\n # DISABLED if unit:\n # DISABLED if unit.find("sorted") > -1:\n # DISABLED labels.sort()\n # DISABLED if unit.find("inverted") > -1:\n # DISABLED labels = labels[::-1]\n\n # add padding (so they do not appear on the axes themselves)\n labels = [''] + labels + ['']\n ticks = list(range(len(labels)))\n ticks[0] = 0.5\n ticks[-1] = ticks[-1] - 0.5\n\n axis.set_ticks(ticks)\n axis.set_ticklabels(labels)\n # we have to do the following lines to make ax.autoscale_view work\n loc = axis.get_major_locator()\n loc.set_bounds(ticks[0], ticks[-1])\n\n if isXAxis:\n ax.set_xlim(ticks[0], ticks[-1])\n else:\n ax.set_ylim(ticks[0], ticks[-1])\n\n result = [ticks[labels.index(v)] for v in value]\n\n ax.viewLim.ignore(-1)\n return result\n\n @staticmethod\n def default_units(value, axis):\n # docstring inherited\n # The default behavior for string indexing.\n return "indexed"\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\StrConverter.py | StrConverter.py | Python | 2,865 | 0.95 | 0.247423 | 0.22973 | node-utils | 654 | 2024-10-02T16:07:09.317901 | GPL-3.0 | true | 7692fde864fd88899e50b6f3497dcd62 |
"""UnitDbl module."""\n\nimport functools\nimport operator\n\nfrom matplotlib import _api\n\n\nclass UnitDbl:\n """Class UnitDbl in development."""\n\n # Unit conversion table. Small subset of the full one but enough\n # to test the required functions. First field is a scale factor to\n # convert the input units to the units of the second field. Only\n # units in this table are allowed.\n allowed = {\n "m": (0.001, "km"),\n "km": (1, "km"),\n "mile": (1.609344, "km"),\n\n "rad": (1, "rad"),\n "deg": (1.745329251994330e-02, "rad"),\n\n "sec": (1, "sec"),\n "min": (60.0, "sec"),\n "hour": (3600, "sec"),\n }\n\n _types = {\n "km": "distance",\n "rad": "angle",\n "sec": "time",\n }\n\n def __init__(self, value, units):\n """\n Create a new UnitDbl object.\n\n Units are internally converted to km, rad, and sec. The only\n valid inputs for units are [m, km, mile, rad, deg, sec, min, hour].\n\n The field UnitDbl.value will contain the converted value. Use\n the convert() method to get a specific type of units back.\n\n = ERROR CONDITIONS\n - If the input units are not in the allowed list, an error is thrown.\n\n = INPUT VARIABLES\n - value The numeric value of the UnitDbl.\n - units The string name of the units the value is in.\n """\n data = _api.check_getitem(self.allowed, units=units)\n self._value = float(value * data[0])\n self._units = data[1]\n\n def convert(self, units):\n """\n Convert the UnitDbl to a specific set of units.\n\n = ERROR CONDITIONS\n - If the input units are not in the allowed list, an error is thrown.\n\n = INPUT VARIABLES\n - units The string name of the units to convert to.\n\n = RETURN VALUE\n - Returns the value of the UnitDbl in the requested units as a floating\n point number.\n """\n if self._units == units:\n return self._value\n data = _api.check_getitem(self.allowed, units=units)\n if self._units != data[1]:\n raise ValueError(f"Error trying to convert to different units.\n"\n f" Invalid conversion requested.\n"\n f" UnitDbl: {self}\n"\n f" Units: {units}\n")\n return self._value / data[0]\n\n def __abs__(self):\n """Return the absolute value of this UnitDbl."""\n return UnitDbl(abs(self._value), self._units)\n\n def __neg__(self):\n """Return the negative value of this UnitDbl."""\n return UnitDbl(-self._value, self._units)\n\n def __bool__(self):\n """Return the truth value of a UnitDbl."""\n return bool(self._value)\n\n def _cmp(self, op, rhs):\n """Check that *self* and *rhs* share units; compare them using *op*."""\n self.checkSameUnits(rhs, "compare")\n return op(self._value, rhs._value)\n\n __eq__ = functools.partialmethod(_cmp, operator.eq)\n __ne__ = functools.partialmethod(_cmp, operator.ne)\n __lt__ = functools.partialmethod(_cmp, operator.lt)\n __le__ = functools.partialmethod(_cmp, operator.le)\n __gt__ = functools.partialmethod(_cmp, operator.gt)\n __ge__ = functools.partialmethod(_cmp, operator.ge)\n\n def _binop_unit_unit(self, op, rhs):\n """Check that *self* and *rhs* share units; combine them using *op*."""\n self.checkSameUnits(rhs, op.__name__)\n return UnitDbl(op(self._value, rhs._value), self._units)\n\n __add__ = functools.partialmethod(_binop_unit_unit, operator.add)\n __sub__ = functools.partialmethod(_binop_unit_unit, operator.sub)\n\n def _binop_unit_scalar(self, op, scalar):\n """Combine *self* and *scalar* using *op*."""\n return UnitDbl(op(self._value, scalar), self._units)\n\n __mul__ = functools.partialmethod(_binop_unit_scalar, operator.mul)\n __rmul__ = functools.partialmethod(_binop_unit_scalar, operator.mul)\n\n def __str__(self):\n """Print the UnitDbl."""\n return f"{self._value:g} *{self._units}"\n\n def __repr__(self):\n """Print the UnitDbl."""\n return f"UnitDbl({self._value:g}, '{self._units}')"\n\n def type(self):\n """Return the type of UnitDbl data."""\n return self._types[self._units]\n\n @staticmethod\n def range(start, stop, step=None):\n """\n Generate a range of UnitDbl objects.\n\n Similar to the Python range() method. Returns the range [\n start, stop) at the requested step. Each element will be a\n UnitDbl object.\n\n = INPUT VARIABLES\n - start The starting value of the range.\n - stop The stop value of the range.\n - step Optional step to use. If set to None, then a UnitDbl of\n value 1 w/ the units of the start is used.\n\n = RETURN VALUE\n - Returns a list containing the requested UnitDbl values.\n """\n if step is None:\n step = UnitDbl(1, start._units)\n\n elems = []\n\n i = 0\n while True:\n d = start + i * step\n if d >= stop:\n break\n\n elems.append(d)\n i += 1\n\n return elems\n\n def checkSameUnits(self, rhs, func):\n """\n Check to see if units are the same.\n\n = ERROR CONDITIONS\n - If the units of the rhs UnitDbl are not the same as our units,\n an error is thrown.\n\n = INPUT VARIABLES\n - rhs The UnitDbl to check for the same units\n - func The name of the function doing the check.\n """\n if self._units != rhs._units:\n raise ValueError(f"Cannot {func} units of different types.\n"\n f"LHS: {self._units}\n"\n f"RHS: {rhs._units}")\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\UnitDbl.py | UnitDbl.py | Python | 5,882 | 0.95 | 0.133333 | 0.028571 | react-lib | 977 | 2024-11-03T02:31:36.322173 | MIT | true | 8cfc3878d1ab7f9b3723b4bf0612ed23 |
"""UnitDblConverter module containing class UnitDblConverter."""\n\nimport numpy as np\n\nfrom matplotlib import cbook, units\nimport matplotlib.projections.polar as polar\n\n__all__ = ['UnitDblConverter']\n\n\n# A special function for use with the matplotlib FuncFormatter class\n# for formatting axes with radian units.\n# This was copied from matplotlib example code.\ndef rad_fn(x, pos=None):\n """Radian function formatter."""\n n = int((x / np.pi) * 2.0 + 0.25)\n if n == 0:\n return str(x)\n elif n == 1:\n return r'$\pi/2$'\n elif n == 2:\n return r'$\pi$'\n elif n % 2 == 0:\n return fr'${n//2}\pi$'\n else:\n return fr'${n}\pi/2$'\n\n\nclass UnitDblConverter(units.ConversionInterface):\n """\n Provides Matplotlib conversion functionality for the Monte UnitDbl class.\n """\n # default for plotting\n defaults = {\n "distance": 'km',\n "angle": 'deg',\n "time": 'sec',\n }\n\n @staticmethod\n def axisinfo(unit, axis):\n # docstring inherited\n\n # Delay-load due to circular dependencies.\n import matplotlib.testing.jpl_units as U\n\n # Check to see if the value used for units is a string unit value\n # or an actual instance of a UnitDbl so that we can use the unit\n # value for the default axis label value.\n if unit:\n label = unit if isinstance(unit, str) else unit.label()\n else:\n label = None\n\n if label == "deg" and isinstance(axis.axes, polar.PolarAxes):\n # If we want degrees for a polar plot, use the PolarPlotFormatter\n majfmt = polar.PolarAxes.ThetaFormatter()\n else:\n majfmt = U.UnitDblFormatter(useOffset=False)\n\n return units.AxisInfo(majfmt=majfmt, label=label)\n\n @staticmethod\n def convert(value, unit, axis):\n # docstring inherited\n if not cbook.is_scalar_or_string(value):\n return [UnitDblConverter.convert(x, unit, axis) for x in value]\n # If no units were specified, then get the default units to use.\n if unit is None:\n unit = UnitDblConverter.default_units(value, axis)\n # Convert the incoming UnitDbl value/values to float/floats\n if isinstance(axis.axes, polar.PolarAxes) and value.type() == "angle":\n # Guarantee that units are radians for polar plots.\n return value.convert("rad")\n return value.convert(unit)\n\n @staticmethod\n def default_units(value, axis):\n # docstring inherited\n # Determine the default units based on the user preferences set for\n # default units when printing a UnitDbl.\n if cbook.is_scalar_or_string(value):\n return UnitDblConverter.defaults[value.type()]\n else:\n return UnitDblConverter.default_units(value[0], axis)\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\UnitDblConverter.py | UnitDblConverter.py | Python | 2,828 | 0.95 | 0.341176 | 0.239437 | python-kit | 119 | 2023-12-27T04:59:16.718910 | MIT | true | 2576aeae66b60f5d87266ab0ea1bd494 |
"""UnitDblFormatter module containing class UnitDblFormatter."""\n\nimport matplotlib.ticker as ticker\n\n__all__ = ['UnitDblFormatter']\n\n\nclass UnitDblFormatter(ticker.ScalarFormatter):\n """\n The formatter for UnitDbl data types.\n\n This allows for formatting with the unit string.\n """\n\n def __call__(self, x, pos=None):\n # docstring inherited\n if len(self.locs) == 0:\n return ''\n else:\n return f'{x:.12}'\n\n def format_data_short(self, value):\n # docstring inherited\n return f'{value:.12}'\n\n def format_data(self, value):\n # docstring inherited\n return f'{value:.12}'\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\UnitDblFormatter.py | UnitDblFormatter.py | Python | 657 | 0.95 | 0.285714 | 0.15 | awesome-app | 680 | 2024-11-01T06:12:10.584929 | BSD-3-Clause | true | b8c1054ddddce651c5e99582650615f1 |
"""\nA sample set of units for use with testing unit conversion\nof Matplotlib routines. These are used because they use very strict\nenforcement of unitized data which will test the entire spectrum of how\nunitized data might be used (it is not always meaningful to convert to\na float without specific units given).\n\nUnitDbl is essentially a unitized floating point number. It has a\nminimal set of supported units (enough for testing purposes). All\nof the mathematical operation are provided to fully test any behaviour\nthat might occur with unitized data. Remember that unitized data has\nrules as to how it can be applied to one another (a value of distance\ncannot be added to a value of time). Thus we need to guard against any\naccidental "default" conversion that will strip away the meaning of the\ndata and render it neutered.\n\nEpoch is different than a UnitDbl of time. Time is something that can be\nmeasured where an Epoch is a specific moment in time. Epochs are typically\nreferenced as an offset from some predetermined epoch.\n\nA difference of two epochs is a Duration. The distinction between a Duration\nand a UnitDbl of time is made because an Epoch can have different frames (or\nunits). In the case of our test Epoch class the two allowed frames are 'UTC'\nand 'ET' (Note that these are rough estimates provided for testing purposes\nand should not be used in production code where accuracy of time frames is\ndesired). As such a Duration also has a frame of reference and therefore needs\nto be called out as different that a simple measurement of time since a delta-t\nin one frame may not be the same in another.\n"""\n\nfrom .Duration import Duration\nfrom .Epoch import Epoch\nfrom .UnitDbl import UnitDbl\n\nfrom .StrConverter import StrConverter\nfrom .EpochConverter import EpochConverter\nfrom .UnitDblConverter import UnitDblConverter\n\nfrom .UnitDblFormatter import UnitDblFormatter\n\n\n__version__ = "1.0"\n\n__all__ = [\n 'register',\n 'Duration',\n 'Epoch',\n 'UnitDbl',\n 'UnitDblFormatter',\n ]\n\n\ndef register():\n """Register the unit conversion classes with matplotlib."""\n import matplotlib.units as mplU\n\n mplU.registry[str] = StrConverter()\n mplU.registry[Epoch] = EpochConverter()\n mplU.registry[Duration] = EpochConverter()\n mplU.registry[UnitDbl] = UnitDblConverter()\n\n\n# Some default unit instances\n# Distances\nm = UnitDbl(1.0, "m")\nkm = UnitDbl(1.0, "km")\nmile = UnitDbl(1.0, "mile")\n# Angles\ndeg = UnitDbl(1.0, "deg")\nrad = UnitDbl(1.0, "rad")\n# Time\nsec = UnitDbl(1.0, "sec")\nmin = UnitDbl(1.0, "min")\nhr = UnitDbl(1.0, "hour")\nday = UnitDbl(24.0, "hour")\nsec = UnitDbl(1.0, "sec")\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__init__.py | __init__.py | Python | 2,684 | 0.95 | 0.065789 | 0.064516 | node-utils | 161 | 2025-04-01T13:11:16.386624 | GPL-3.0 | true | b47657c0b45027604bc04eae91cb2d2d |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\Duration.cpython-313.pyc | Duration.cpython-313.pyc | Other | 6,025 | 0.95 | 0.025424 | 0 | python-kit | 298 | 2024-04-14T22:27:25.693225 | MIT | true | 19e5124b62c8ad6a4360f796c64a7116 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\Epoch.cpython-313.pyc | Epoch.cpython-313.pyc | Other | 7,863 | 0.8 | 0 | 0.015038 | vue-tools | 630 | 2025-02-23T02:49:50.293049 | Apache-2.0 | true | 269b74f64019008d692a283cd13a91fb |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\EpochConverter.cpython-313.pyc | EpochConverter.cpython-313.pyc | Other | 4,185 | 0.95 | 0.1 | 0 | node-utils | 232 | 2025-01-02T00:35:39.257064 | BSD-3-Clause | true | affafef5ab3fcec7631de1a3e11c0610 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\StrConverter.cpython-313.pyc | StrConverter.cpython-313.pyc | Other | 3,284 | 0.95 | 0.138889 | 0 | react-lib | 560 | 2023-10-14T22:10:52.252159 | BSD-3-Clause | true | 47d2d3009dcf9df8de1e823994dbc95b |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\UnitDbl.cpython-313.pyc | UnitDbl.cpython-313.pyc | Other | 7,755 | 0.95 | 0.033898 | 0 | vue-tools | 898 | 2024-10-29T13:23:49.381227 | MIT | true | 1b284d360162b0ac586d48ee6a4ab883 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\UnitDblConverter.cpython-313.pyc | UnitDblConverter.cpython-313.pyc | Other | 3,466 | 0.95 | 0.16 | 0 | python-kit | 378 | 2024-01-17T10:55:50.106830 | GPL-3.0 | true | 9a3c0fce0b057d4480ffe99df542f752 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\UnitDblFormatter.cpython-313.pyc | UnitDblFormatter.cpython-313.pyc | Other | 1,300 | 0.85 | 0.3 | 0 | react-lib | 278 | 2025-06-04T05:02:56.161487 | GPL-3.0 | true | 7af40394aac5877382a1b3751761c83b |
\n\n | .venv\Lib\site-packages\matplotlib\testing\jpl_units\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 3,114 | 0.95 | 0.088889 | 0 | react-lib | 525 | 2024-02-11T03:30:43.340604 | MIT | true | b47924072ee19774978c2618665194b4 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\__pycache__\compare.cpython-313.pyc | compare.cpython-313.pyc | Other | 24,921 | 0.95 | 0.013986 | 0 | vue-tools | 403 | 2024-06-13T16:57:41.134404 | MIT | true | 7ddf2d5fcfb9581ce9f1d11689337bac |
\n\n | .venv\Lib\site-packages\matplotlib\testing\__pycache__\conftest.cpython-313.pyc | conftest.cpython-313.pyc | Other | 7,934 | 0.95 | 0.046512 | 0 | vue-tools | 4 | 2024-03-07T04:38:17.410445 | Apache-2.0 | true | 063f5907b6bc7a98a0c3d25b95312c03 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\__pycache__\decorators.cpython-313.pyc | decorators.cpython-313.pyc | Other | 23,181 | 0.95 | 0.072165 | 0.015385 | node-utils | 965 | 2023-10-18T15:26:33.170087 | Apache-2.0 | true | 3dbda4e69f97d20fcb497272cd5f5a54 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\__pycache__\exceptions.cpython-313.pyc | exceptions.cpython-313.pyc | Other | 547 | 0.7 | 0 | 0 | node-utils | 714 | 2025-01-05T00:17:57.848941 | BSD-3-Clause | true | 423614aee1aadef0b497841d1c8b78f2 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\__pycache__\widgets.cpython-313.pyc | widgets.cpython-313.pyc | Other | 4,233 | 0.95 | 0.064935 | 0 | vue-tools | 463 | 2025-01-11T01:10:47.829351 | Apache-2.0 | true | ab94876bde108adfa1461f9668e7f13f |
\n\n | .venv\Lib\site-packages\matplotlib\testing\__pycache__\_markers.cpython-313.pyc | _markers.cpython-313.pyc | Other | 2,450 | 0.95 | 0.0625 | 0 | vue-tools | 770 | 2025-06-14T07:23:24.340057 | MIT | true | ff3f01b6179604bcf26056fc3500d569 |
\n\n | .venv\Lib\site-packages\matplotlib\testing\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 8,225 | 0.95 | 0.051852 | 0.007874 | python-kit | 163 | 2023-10-27T09:15:28.975123 | GPL-3.0 | true | 6a9fba473b017453a0076fcd645e7aa1 |
from matplotlib.testing.conftest import ( # noqa\n mpl_test_settings, pytest_configure, pytest_unconfigure, pd, text_placeholders, xr)\n | .venv\Lib\site-packages\matplotlib\tests\conftest.py | conftest.py | Python | 138 | 0.95 | 0 | 0 | vue-tools | 414 | 2024-12-25T23:59:01.836192 | MIT | true | b448d04b01026f6b4ce0a8625f23b90c |
from io import BytesIO\nimport pytest\nimport logging\n\nfrom matplotlib import _afm\nfrom matplotlib import font_manager as fm\n\n\n# See note in afm.py re: use of comma as decimal separator in the\n# UnderlineThickness field and re: use of non-ASCII characters in the Notice\n# field.\nAFM_TEST_DATA = b"""StartFontMetrics 2.0\nComment Comments are ignored.\nComment Creation Date:Mon Nov 13 12:34:11 GMT 2017\nFontName MyFont-Bold\nEncodingScheme FontSpecific\nFullName My Font Bold\nFamilyName Test Fonts\nWeight Bold\nItalicAngle 0.0\nIsFixedPitch false\nUnderlinePosition -100\nUnderlineThickness 56,789\nVersion 001.000\nNotice Copyright \xa9 2017 No one.\nFontBBox 0 -321 1234 369\nStartCharMetrics 3\nC 0 ; WX 250 ; N space ; B 0 0 0 0 ;\nC 42 ; WX 1141 ; N foo ; B 40 60 800 360 ;\nC 99 ; WX 583 ; N bar ; B 40 -10 543 210 ;\nEndCharMetrics\nEndFontMetrics\n"""\n\n\ndef test_nonascii_str():\n # This tests that we also decode bytes as utf-8 properly.\n # Else, font files with non ascii characters fail to load.\n inp_str = "привет"\n byte_str = inp_str.encode("utf8")\n\n ret = _afm._to_str(byte_str)\n assert ret == inp_str\n\n\ndef test_parse_header():\n fh = BytesIO(AFM_TEST_DATA)\n header = _afm._parse_header(fh)\n assert header == {\n b'StartFontMetrics': 2.0,\n b'FontName': 'MyFont-Bold',\n b'EncodingScheme': 'FontSpecific',\n b'FullName': 'My Font Bold',\n b'FamilyName': 'Test Fonts',\n b'Weight': 'Bold',\n b'ItalicAngle': 0.0,\n b'IsFixedPitch': False,\n b'UnderlinePosition': -100,\n b'UnderlineThickness': 56.789,\n b'Version': '001.000',\n b'Notice': b'Copyright \xa9 2017 No one.',\n b'FontBBox': [0, -321, 1234, 369],\n b'StartCharMetrics': 3,\n }\n\n\ndef test_parse_char_metrics():\n fh = BytesIO(AFM_TEST_DATA)\n _afm._parse_header(fh) # position\n metrics = _afm._parse_char_metrics(fh)\n assert metrics == (\n {0: (250.0, 'space', [0, 0, 0, 0]),\n 42: (1141.0, 'foo', [40, 60, 800, 360]),\n 99: (583.0, 'bar', [40, -10, 543, 210]),\n },\n {'space': (250.0, 'space', [0, 0, 0, 0]),\n 'foo': (1141.0, 'foo', [40, 60, 800, 360]),\n 'bar': (583.0, 'bar', [40, -10, 543, 210]),\n })\n\n\ndef test_get_familyname_guessed():\n fh = BytesIO(AFM_TEST_DATA)\n font = _afm.AFM(fh)\n del font._header[b'FamilyName'] # remove FamilyName, so we have to guess\n assert font.get_familyname() == 'My Font'\n\n\ndef test_font_manager_weight_normalization():\n font = _afm.AFM(BytesIO(\n AFM_TEST_DATA.replace(b"Weight Bold\n", b"Weight Custom\n")))\n assert fm.afmFontProperty("", font).weight == "normal"\n\n\n@pytest.mark.parametrize(\n "afm_data",\n [\n b"""nope\nreally nope""",\n b"""StartFontMetrics 2.0\nComment Comments are ignored.\nComment Creation Date:Mon Nov 13 12:34:11 GMT 2017\nFontName MyFont-Bold\nEncodingScheme FontSpecific""",\n ],\n)\ndef test_bad_afm(afm_data):\n fh = BytesIO(afm_data)\n with pytest.raises(RuntimeError):\n _afm._parse_header(fh)\n\n\n@pytest.mark.parametrize(\n "afm_data",\n [\n b"""StartFontMetrics 2.0\nComment Comments are ignored.\nComment Creation Date:Mon Nov 13 12:34:11 GMT 2017\nAardvark bob\nFontName MyFont-Bold\nEncodingScheme FontSpecific\nStartCharMetrics 3""",\n b"""StartFontMetrics 2.0\nComment Comments are ignored.\nComment Creation Date:Mon Nov 13 12:34:11 GMT 2017\nItalicAngle zero degrees\nFontName MyFont-Bold\nEncodingScheme FontSpecific\nStartCharMetrics 3""",\n ],\n)\ndef test_malformed_header(afm_data, caplog):\n fh = BytesIO(afm_data)\n with caplog.at_level(logging.ERROR):\n _afm._parse_header(fh)\n\n assert len(caplog.records) == 1\n | .venv\Lib\site-packages\matplotlib\tests\test_afm.py | test_afm.py | Python | 3,701 | 0.95 | 0.051095 | 0.042373 | python-kit | 84 | 2023-10-31T03:21:40.176953 | GPL-3.0 | true | f5ad0caace031c3d386345ffd838b318 |
import io\n\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal\nfrom PIL import features, Image, TiffTags\nimport pytest\n\n\nfrom matplotlib import (\n collections, patheffects, pyplot as plt, transforms as mtransforms,\n rcParams, rc_context)\nfrom matplotlib.backends.backend_agg import RendererAgg\nfrom matplotlib.figure import Figure\nfrom matplotlib.image import imread\nfrom matplotlib.path import Path\nfrom matplotlib.testing.decorators import image_comparison\nfrom matplotlib.transforms import IdentityTransform\n\n\ndef test_repeated_save_with_alpha():\n # We want an image which has a background color of bluish green, with an\n # alpha of 0.25.\n\n fig = Figure([1, 0.4])\n fig.set_facecolor((0, 1, 0.4))\n fig.patch.set_alpha(0.25)\n\n # The target color is fig.patch.get_facecolor()\n\n buf = io.BytesIO()\n\n fig.savefig(buf,\n facecolor=fig.get_facecolor(),\n edgecolor='none')\n\n # Save the figure again to check that the\n # colors don't bleed from the previous renderer.\n buf.seek(0)\n fig.savefig(buf,\n facecolor=fig.get_facecolor(),\n edgecolor='none')\n\n # Check the first pixel has the desired color & alpha\n # (approx: 0, 1.0, 0.4, 0.25)\n buf.seek(0)\n assert_array_almost_equal(tuple(imread(buf)[0, 0]),\n (0.0, 1.0, 0.4, 0.250),\n decimal=3)\n\n\ndef test_large_single_path_collection():\n buff = io.BytesIO()\n\n # Generates a too-large single path in a path collection that\n # would cause a segfault if the draw_markers optimization is\n # applied.\n f, ax = plt.subplots()\n collection = collections.PathCollection(\n [Path([[-10, 5], [10, 5], [10, -5], [-10, -5], [-10, 5]])])\n ax.add_artist(collection)\n ax.set_xlim(10**-3, 1)\n plt.savefig(buff)\n\n\ndef test_marker_with_nan():\n # This creates a marker with nans in it, which was segfaulting the\n # Agg backend (see #3722)\n fig, ax = plt.subplots(1)\n steps = 1000\n data = np.arange(steps)\n ax.semilogx(data)\n ax.fill_between(data, data*0.8, data*1.2)\n buf = io.BytesIO()\n fig.savefig(buf, format='png')\n\n\ndef test_long_path():\n buff = io.BytesIO()\n fig = Figure()\n ax = fig.subplots()\n points = np.ones(100_000)\n points[::2] *= -1\n ax.plot(points)\n fig.savefig(buff, format='png')\n\n\n@image_comparison(['agg_filter.png'], remove_text=True)\ndef test_agg_filter():\n def smooth1d(x, window_len):\n # copied from https://scipy-cookbook.readthedocs.io/\n s = np.r_[\n 2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]]\n w = np.hanning(window_len)\n y = np.convolve(w/w.sum(), s, mode='same')\n return y[window_len-1:-window_len+1]\n\n def smooth2d(A, sigma=3):\n window_len = max(int(sigma), 3) * 2 + 1\n A = np.apply_along_axis(smooth1d, 0, A, window_len)\n A = np.apply_along_axis(smooth1d, 1, A, window_len)\n return A\n\n class BaseFilter:\n\n def get_pad(self, dpi):\n return 0\n\n def process_image(self, padded_src, dpi):\n raise NotImplementedError("Should be overridden by subclasses")\n\n def __call__(self, im, dpi):\n pad = self.get_pad(dpi)\n padded_src = np.pad(im, [(pad, pad), (pad, pad), (0, 0)],\n "constant")\n tgt_image = self.process_image(padded_src, dpi)\n return tgt_image, -pad, -pad\n\n class OffsetFilter(BaseFilter):\n\n def __init__(self, offsets=(0, 0)):\n self.offsets = offsets\n\n def get_pad(self, dpi):\n return int(max(self.offsets) / 72 * dpi)\n\n def process_image(self, padded_src, dpi):\n ox, oy = self.offsets\n a1 = np.roll(padded_src, int(ox / 72 * dpi), axis=1)\n a2 = np.roll(a1, -int(oy / 72 * dpi), axis=0)\n return a2\n\n class GaussianFilter(BaseFilter):\n """Simple Gaussian filter."""\n\n def __init__(self, sigma, alpha=0.5, color=(0, 0, 0)):\n self.sigma = sigma\n self.alpha = alpha\n self.color = color\n\n def get_pad(self, dpi):\n return int(self.sigma*3 / 72 * dpi)\n\n def process_image(self, padded_src, dpi):\n tgt_image = np.empty_like(padded_src)\n tgt_image[:, :, :3] = self.color\n tgt_image[:, :, 3] = smooth2d(padded_src[:, :, 3] * self.alpha,\n self.sigma / 72 * dpi)\n return tgt_image\n\n class DropShadowFilter(BaseFilter):\n\n def __init__(self, sigma, alpha=0.3, color=(0, 0, 0), offsets=(0, 0)):\n self.gauss_filter = GaussianFilter(sigma, alpha, color)\n self.offset_filter = OffsetFilter(offsets)\n\n def get_pad(self, dpi):\n return max(self.gauss_filter.get_pad(dpi),\n self.offset_filter.get_pad(dpi))\n\n def process_image(self, padded_src, dpi):\n t1 = self.gauss_filter.process_image(padded_src, dpi)\n t2 = self.offset_filter.process_image(t1, dpi)\n return t2\n\n fig, ax = plt.subplots()\n\n # draw lines\n line1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",\n mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1")\n line2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-",\n mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1")\n\n gauss = DropShadowFilter(4)\n\n for line in [line1, line2]:\n\n # draw shadows with same lines with slight offset.\n xx = line.get_xdata()\n yy = line.get_ydata()\n shadow, = ax.plot(xx, yy)\n shadow.update_from(line)\n\n # offset transform\n transform = mtransforms.offset_copy(\n line.get_transform(), fig, x=4.0, y=-6.0, units='points')\n shadow.set_transform(transform)\n\n # adjust zorder of the shadow lines so that it is drawn below the\n # original lines\n shadow.set_zorder(line.get_zorder() - 0.5)\n shadow.set_agg_filter(gauss)\n shadow.set_rasterized(True) # to support mixed-mode renderers\n\n ax.set_xlim(0., 1.)\n ax.set_ylim(0., 1.)\n\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n\ndef test_too_large_image():\n fig = plt.figure(figsize=(300, 2**25))\n buff = io.BytesIO()\n with pytest.raises(ValueError):\n fig.savefig(buff)\n\n\ndef test_chunksize():\n x = range(200)\n\n # Test without chunksize\n fig, ax = plt.subplots()\n ax.plot(x, np.sin(x))\n fig.canvas.draw()\n\n # Test with chunksize\n fig, ax = plt.subplots()\n rcParams['agg.path.chunksize'] = 105\n ax.plot(x, np.sin(x))\n fig.canvas.draw()\n\n\n@pytest.mark.backend('Agg')\ndef test_jpeg_dpi():\n # Check that dpi is set correctly in jpg files.\n plt.plot([0, 1, 2], [0, 1, 0])\n buf = io.BytesIO()\n plt.savefig(buf, format="jpg", dpi=200)\n im = Image.open(buf)\n assert im.info['dpi'] == (200, 200)\n\n\ndef test_pil_kwargs_png():\n from PIL.PngImagePlugin import PngInfo\n buf = io.BytesIO()\n pnginfo = PngInfo()\n pnginfo.add_text("Software", "test")\n plt.figure().savefig(buf, format="png", pil_kwargs={"pnginfo": pnginfo})\n im = Image.open(buf)\n assert im.info["Software"] == "test"\n\n\ndef test_pil_kwargs_tiff():\n buf = io.BytesIO()\n pil_kwargs = {"description": "test image"}\n plt.figure().savefig(buf, format="tiff", pil_kwargs=pil_kwargs)\n im = Image.open(buf)\n tags = {TiffTags.TAGS_V2[k].name: v for k, v in im.tag_v2.items()}\n assert tags["ImageDescription"] == "test image"\n\n\n@pytest.mark.skipif(not features.check("webp"), reason="WebP support not available")\ndef test_pil_kwargs_webp():\n plt.plot([0, 1, 2], [0, 1, 0])\n buf_small = io.BytesIO()\n pil_kwargs_low = {"quality": 1}\n plt.savefig(buf_small, format="webp", pil_kwargs=pil_kwargs_low)\n assert len(pil_kwargs_low) == 1\n buf_large = io.BytesIO()\n pil_kwargs_high = {"quality": 100}\n plt.savefig(buf_large, format="webp", pil_kwargs=pil_kwargs_high)\n assert len(pil_kwargs_high) == 1\n assert buf_large.getbuffer().nbytes > buf_small.getbuffer().nbytes\n\n\n@pytest.mark.skipif(not features.check("webp"), reason="WebP support not available")\ndef test_webp_alpha():\n plt.plot([0, 1, 2], [0, 1, 0])\n buf = io.BytesIO()\n plt.savefig(buf, format="webp", transparent=True)\n im = Image.open(buf)\n assert im.mode == "RGBA"\n\n\ndef test_draw_path_collection_error_handling():\n fig, ax = plt.subplots()\n ax.scatter([1], [1]).set_paths(Path([(0, 1), (2, 3)]))\n with pytest.raises(TypeError):\n fig.canvas.draw()\n\n\ndef test_chunksize_fails():\n # NOTE: This test covers multiple independent test scenarios in a single\n # function, because each scenario uses ~2GB of memory and we don't\n # want parallel test executors to accidentally run multiple of these\n # at the same time.\n\n N = 100_000\n dpi = 500\n w = 5*dpi\n h = 6*dpi\n\n # make a Path that spans the whole w-h rectangle\n x = np.linspace(0, w, N)\n y = np.ones(N) * h\n y[::2] = 0\n path = Path(np.vstack((x, y)).T)\n # effectively disable path simplification (but leaving it "on")\n path.simplify_threshold = 0\n\n # setup the minimal GraphicsContext to draw a Path\n ra = RendererAgg(w, h, dpi)\n gc = ra.new_gc()\n gc.set_linewidth(1)\n gc.set_foreground('r')\n\n gc.set_hatch('/')\n with pytest.raises(OverflowError, match='cannot split hatched path'):\n ra.draw_path(gc, path, IdentityTransform())\n gc.set_hatch(None)\n\n with pytest.raises(OverflowError, match='cannot split filled path'):\n ra.draw_path(gc, path, IdentityTransform(), (1, 0, 0))\n\n # Set to zero to disable, currently defaults to 0, but let's be sure.\n with rc_context({'agg.path.chunksize': 0}):\n with pytest.raises(OverflowError, match='Please set'):\n ra.draw_path(gc, path, IdentityTransform())\n\n # Set big enough that we do not try to chunk.\n with rc_context({'agg.path.chunksize': 1_000_000}):\n with pytest.raises(OverflowError, match='Please reduce'):\n ra.draw_path(gc, path, IdentityTransform())\n\n # Small enough we will try to chunk, but big enough we will fail to render.\n with rc_context({'agg.path.chunksize': 90_000}):\n with pytest.raises(OverflowError, match='Please reduce'):\n ra.draw_path(gc, path, IdentityTransform())\n\n path.should_simplify = False\n with pytest.raises(OverflowError, match="should_simplify is False"):\n ra.draw_path(gc, path, IdentityTransform())\n\n\ndef test_non_tuple_rgbaface():\n # This passes rgbaFace as a ndarray to draw_path.\n fig = plt.figure()\n fig.add_subplot(projection="3d").scatter(\n [0, 1, 2], [0, 1, 2], path_effects=[patheffects.Stroke(linewidth=4)])\n fig.canvas.draw()\n | .venv\Lib\site-packages\matplotlib\tests\test_agg.py | test_agg.py | Python | 10,884 | 0.95 | 0.114706 | 0.121673 | python-kit | 23 | 2025-03-26T06:21:13.789778 | GPL-3.0 | true | cadbff8488a70ab6b854f73382d74e21 |
import numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\n\n\n@image_comparison(baseline_images=['agg_filter_alpha'],\n extensions=['png', 'pdf'])\ndef test_agg_filter_alpha():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n ax = plt.axes()\n x, y = np.mgrid[0:7, 0:8]\n data = x**2 - y**2\n mesh = ax.pcolormesh(data, cmap='Reds', zorder=5)\n\n def manual_alpha(im, dpi):\n im[:, :, 3] *= 0.6\n print('CALLED')\n return im, 0, 0\n\n # Note: Doing alpha like this is not the same as setting alpha on\n # the mesh itself. Currently meshes are drawn as independent patches,\n # and we see fine borders around the blocks of color. See the SO\n # question for an example: https://stackoverflow.com/q/20678817/\n mesh.set_agg_filter(manual_alpha)\n\n # Currently we must enable rasterization for this to have an effect in\n # the PDF backend.\n mesh.set_rasterized(True)\n\n ax.plot([0, 4, 7], [1, 3, 8])\n | .venv\Lib\site-packages\matplotlib\tests\test_agg_filter.py | test_agg_filter.py | Python | 1,067 | 0.95 | 0.121212 | 0.28 | vue-tools | 783 | 2024-03-28T00:59:45.893236 | Apache-2.0 | true | f13ac60cc2ef06297755c32bec06e0c0 |
import os\nfrom pathlib import Path\nimport platform\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport weakref\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\nfrom matplotlib.animation import PillowWriter\nfrom matplotlib.testing.decorators import check_figures_equal\n\n\n@pytest.fixture()\ndef anim(request):\n """Create a simple animation (with options)."""\n fig, ax = plt.subplots()\n line, = ax.plot([], [])\n\n ax.set_xlim(0, 10)\n ax.set_ylim(-1, 1)\n\n def init():\n line.set_data([], [])\n return line,\n\n def animate(i):\n x = np.linspace(0, 10, 100)\n y = np.sin(x + i)\n line.set_data(x, y)\n return line,\n\n # "klass" can be passed to determine the class returned by the fixture\n kwargs = dict(getattr(request, 'param', {})) # make a copy\n klass = kwargs.pop('klass', animation.FuncAnimation)\n if 'frames' not in kwargs:\n kwargs['frames'] = 5\n return klass(fig=fig, func=animate, init_func=init, **kwargs)\n\n\nclass NullMovieWriter(animation.AbstractMovieWriter):\n """\n A minimal MovieWriter. It doesn't actually write anything.\n It just saves the arguments that were given to the setup() and\n grab_frame() methods as attributes, and counts how many times\n grab_frame() is called.\n\n This class doesn't have an __init__ method with the appropriate\n signature, and it doesn't define an isAvailable() method, so\n it cannot be added to the 'writers' registry.\n """\n\n def setup(self, fig, outfile, dpi, *args):\n self.fig = fig\n self.outfile = outfile\n self.dpi = dpi\n self.args = args\n self._count = 0\n\n def grab_frame(self, **savefig_kwargs):\n from matplotlib.animation import _validate_grabframe_kwargs\n _validate_grabframe_kwargs(savefig_kwargs)\n self.savefig_kwargs = savefig_kwargs\n self._count += 1\n\n def finish(self):\n pass\n\n\ndef test_null_movie_writer(anim):\n # Test running an animation with NullMovieWriter.\n plt.rcParams["savefig.facecolor"] = "auto"\n filename = "unused.null"\n dpi = 50\n savefig_kwargs = dict(foo=0)\n writer = NullMovieWriter()\n\n anim.save(filename, dpi=dpi, writer=writer,\n savefig_kwargs=savefig_kwargs)\n\n assert writer.fig == plt.figure(1) # The figure used by anim fixture\n assert writer.outfile == filename\n assert writer.dpi == dpi\n assert writer.args == ()\n # we enrich the savefig kwargs to ensure we composite transparent\n # output to an opaque background\n for k, v in savefig_kwargs.items():\n assert writer.savefig_kwargs[k] == v\n assert writer._count == anim._save_count\n\n\n@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])\ndef test_animation_delete(anim):\n if platform.python_implementation() == 'PyPy':\n # Something in the test setup fixture lingers around into the test and\n # breaks pytest.warns on PyPy. This garbage collection fixes it.\n # https://foss.heptapod.net/pypy/pypy/-/issues/3536\n np.testing.break_cycles()\n anim = animation.FuncAnimation(**anim)\n with pytest.warns(Warning, match='Animation was deleted'):\n del anim\n np.testing.break_cycles()\n\n\ndef test_movie_writer_dpi_default():\n class DummyMovieWriter(animation.MovieWriter):\n def _run(self):\n pass\n\n # Test setting up movie writer with figure.dpi default.\n fig = plt.figure()\n\n filename = "unused.null"\n fps = 5\n codec = "unused"\n bitrate = 1\n extra_args = ["unused"]\n\n writer = DummyMovieWriter(fps, codec, bitrate, extra_args)\n writer.setup(fig, filename)\n assert writer.dpi == fig.dpi\n\n\n@animation.writers.register('null')\nclass RegisteredNullMovieWriter(NullMovieWriter):\n\n # To be able to add NullMovieWriter to the 'writers' registry,\n # we must define an __init__ method with a specific signature,\n # and we must define the class method isAvailable().\n # (These methods are not actually required to use an instance\n # of this class as the 'writer' argument of Animation.save().)\n\n def __init__(self, fps=None, codec=None, bitrate=None,\n extra_args=None, metadata=None):\n pass\n\n @classmethod\n def isAvailable(cls):\n return True\n\n\nWRITER_OUTPUT = [\n ('ffmpeg', 'movie.mp4'),\n ('ffmpeg_file', 'movie.mp4'),\n ('imagemagick', 'movie.gif'),\n ('imagemagick_file', 'movie.gif'),\n ('pillow', 'movie.gif'),\n ('html', 'movie.html'),\n ('null', 'movie.null')\n]\n\n\ndef gen_writers():\n for writer, output in WRITER_OUTPUT:\n if not animation.writers.is_available(writer):\n mark = pytest.mark.skip(\n f"writer '{writer}' not available on this system")\n yield pytest.param(writer, None, output, marks=[mark])\n yield pytest.param(writer, None, Path(output), marks=[mark])\n continue\n\n writer_class = animation.writers[writer]\n for frame_format in getattr(writer_class, 'supported_formats', [None]):\n yield writer, frame_format, output\n yield writer, frame_format, Path(output)\n\n\n# Smoke test for saving animations. In the future, we should probably\n# design more sophisticated tests which compare resulting frames a-la\n# matplotlib.testing.image_comparison\n@pytest.mark.parametrize('writer, frame_format, output', gen_writers())\n@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])\ndef test_save_animation_smoketest(tmpdir, writer, frame_format, output, anim):\n if frame_format is not None:\n plt.rcParams["animation.frame_format"] = frame_format\n anim = animation.FuncAnimation(**anim)\n dpi = None\n codec = None\n if writer == 'ffmpeg':\n # Issue #8253\n anim._fig.set_size_inches((10.85, 9.21))\n dpi = 100.\n codec = 'h264'\n\n # Use temporary directory for the file-based writers, which produce a file\n # per frame with known names.\n with tmpdir.as_cwd():\n anim.save(output, fps=30, writer=writer, bitrate=500, dpi=dpi,\n codec=codec)\n\n del anim\n\n\n@pytest.mark.parametrize('writer, frame_format, output', gen_writers())\ndef test_grabframe(tmpdir, writer, frame_format, output):\n WriterClass = animation.writers[writer]\n\n if frame_format is not None:\n plt.rcParams["animation.frame_format"] = frame_format\n\n fig, ax = plt.subplots()\n\n dpi = None\n codec = None\n if writer == 'ffmpeg':\n # Issue #8253\n fig.set_size_inches((10.85, 9.21))\n dpi = 100.\n codec = 'h264'\n\n test_writer = WriterClass()\n # Use temporary directory for the file-based writers, which produce a file\n # per frame with known names.\n with tmpdir.as_cwd():\n with test_writer.saving(fig, output, dpi):\n # smoke test it works\n test_writer.grab_frame()\n for k in {'dpi', 'bbox_inches', 'format'}:\n with pytest.raises(\n TypeError,\n match=f"grab_frame got an unexpected keyword argument {k!r}"\n ):\n test_writer.grab_frame(**{k: object()})\n\n\n@pytest.mark.parametrize('writer', [\n pytest.param(\n 'ffmpeg', marks=pytest.mark.skipif(\n not animation.FFMpegWriter.isAvailable(),\n reason='Requires FFMpeg')),\n pytest.param(\n 'imagemagick', marks=pytest.mark.skipif(\n not animation.ImageMagickWriter.isAvailable(),\n reason='Requires ImageMagick')),\n])\n@pytest.mark.parametrize('html, want', [\n ('none', None),\n ('html5', '<video width'),\n ('jshtml', '<script ')\n])\n@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])\ndef test_animation_repr_html(writer, html, want, anim):\n if platform.python_implementation() == 'PyPy':\n # Something in the test setup fixture lingers around into the test and\n # breaks pytest.warns on PyPy. This garbage collection fixes it.\n # https://foss.heptapod.net/pypy/pypy/-/issues/3536\n np.testing.break_cycles()\n if (writer == 'imagemagick' and html == 'html5'\n # ImageMagick delegates to ffmpeg for this format.\n and not animation.FFMpegWriter.isAvailable()):\n pytest.skip('Requires FFMpeg')\n # create here rather than in the fixture otherwise we get __del__ warnings\n # about producing no output\n anim = animation.FuncAnimation(**anim)\n with plt.rc_context({'animation.writer': writer,\n 'animation.html': html}):\n html = anim._repr_html_()\n if want is None:\n assert html is None\n with pytest.warns(UserWarning):\n del anim # Animation was never run, so will warn on cleanup.\n np.testing.break_cycles()\n else:\n assert want in html\n\n\n@pytest.mark.parametrize(\n 'anim',\n [{'save_count': 10, 'frames': iter(range(5))}],\n indirect=['anim']\n)\ndef test_no_length_frames(anim):\n anim.save('unused.null', writer=NullMovieWriter())\n\n\ndef test_movie_writer_registry():\n assert len(animation.writers._registered) > 0\n mpl.rcParams['animation.ffmpeg_path'] = "not_available_ever_xxxx"\n assert not animation.writers.is_available("ffmpeg")\n # something guaranteed to be available in path and exits immediately\n bin = "true" if sys.platform != 'win32' else "where"\n mpl.rcParams['animation.ffmpeg_path'] = bin\n assert animation.writers.is_available("ffmpeg")\n\n\n@pytest.mark.parametrize(\n "method_name",\n [pytest.param("to_html5_video", marks=pytest.mark.skipif(\n not animation.writers.is_available(mpl.rcParams["animation.writer"]),\n reason="animation writer not installed")),\n "to_jshtml"])\n@pytest.mark.parametrize('anim', [dict(frames=1)], indirect=['anim'])\ndef test_embed_limit(method_name, caplog, tmpdir, anim):\n caplog.set_level("WARNING")\n with tmpdir.as_cwd():\n with mpl.rc_context({"animation.embed_limit": 1e-6}): # ~1 byte.\n getattr(anim, method_name)()\n assert len(caplog.records) == 1\n record, = caplog.records\n assert (record.name == "matplotlib.animation"\n and record.levelname == "WARNING")\n\n\n@pytest.mark.parametrize(\n "method_name",\n [pytest.param("to_html5_video", marks=pytest.mark.skipif(\n not animation.writers.is_available(mpl.rcParams["animation.writer"]),\n reason="animation writer not installed")),\n "to_jshtml"])\n@pytest.mark.parametrize('anim', [dict(frames=1)], indirect=['anim'])\ndef test_cleanup_temporaries(method_name, tmpdir, anim):\n with tmpdir.as_cwd():\n getattr(anim, method_name)()\n assert list(Path(str(tmpdir)).iterdir()) == []\n\n\n@pytest.mark.skipif(shutil.which("/bin/sh") is None, reason="requires a POSIX OS")\ndef test_failing_ffmpeg(tmpdir, monkeypatch, anim):\n """\n Test that we correctly raise a CalledProcessError when ffmpeg fails.\n\n To do so, mock ffmpeg using a simple executable shell script that\n succeeds when called with no arguments (so that it gets registered by\n `isAvailable`), but fails otherwise, and add it to the $PATH.\n """\n with tmpdir.as_cwd():\n monkeypatch.setenv("PATH", ".:" + os.environ["PATH"])\n exe_path = Path(str(tmpdir), "ffmpeg")\n exe_path.write_bytes(b"#!/bin/sh\n[[ $@ -eq 0 ]]\n")\n os.chmod(exe_path, 0o755)\n with pytest.raises(subprocess.CalledProcessError):\n anim.save("test.mpeg")\n\n\n@pytest.mark.parametrize("cache_frame_data", [False, True])\ndef test_funcanimation_cache_frame_data(cache_frame_data):\n fig, ax = plt.subplots()\n line, = ax.plot([], [])\n\n class Frame(dict):\n # this subclassing enables to use weakref.ref()\n pass\n\n def init():\n line.set_data([], [])\n return line,\n\n def animate(frame):\n line.set_data(frame['x'], frame['y'])\n return line,\n\n frames_generated = []\n\n def frames_generator():\n for _ in range(5):\n x = np.linspace(0, 10, 100)\n y = np.random.rand(100)\n\n frame = Frame(x=x, y=y)\n\n # collect weak references to frames\n # to validate their references later\n frames_generated.append(weakref.ref(frame))\n\n yield frame\n\n MAX_FRAMES = 100\n anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=frames_generator,\n cache_frame_data=cache_frame_data,\n save_count=MAX_FRAMES)\n\n writer = NullMovieWriter()\n anim.save('unused.null', writer=writer)\n assert len(frames_generated) == 5\n np.testing.break_cycles()\n for f in frames_generated:\n # If cache_frame_data is True, then the weakref should be alive;\n # if cache_frame_data is False, then the weakref should be dead (None).\n assert (f() is None) != cache_frame_data\n\n\n@pytest.mark.parametrize('return_value', [\n # User forgot to return (returns None).\n None,\n # User returned a string.\n 'string',\n # User returned an int.\n 1,\n # User returns a sequence of other objects, e.g., string instead of Artist.\n ('string', ),\n # User forgot to return a sequence (handled in `animate` below.)\n 'artist',\n])\ndef test_draw_frame(return_value):\n # test _draw_frame method\n\n fig, ax = plt.subplots()\n line, = ax.plot([])\n\n def animate(i):\n # general update func\n line.set_data([0, 1], [0, i])\n if return_value == 'artist':\n # *not* a sequence\n return line\n else:\n return return_value\n\n with pytest.raises(RuntimeError):\n animation.FuncAnimation(\n fig, animate, blit=True, cache_frame_data=False\n )\n\n\ndef test_exhausted_animation(tmpdir):\n fig, ax = plt.subplots()\n\n def update(frame):\n return []\n\n anim = animation.FuncAnimation(\n fig, update, frames=iter(range(10)), repeat=False,\n cache_frame_data=False\n )\n\n with tmpdir.as_cwd():\n anim.save("test.gif", writer='pillow')\n\n with pytest.warns(UserWarning, match="exhausted"):\n anim._start()\n\n\ndef test_no_frame_warning(tmpdir):\n fig, ax = plt.subplots()\n\n def update(frame):\n return []\n\n anim = animation.FuncAnimation(\n fig, update, frames=[], repeat=False,\n cache_frame_data=False\n )\n\n with pytest.warns(UserWarning, match="exhausted"):\n anim._start()\n\n\n@check_figures_equal(extensions=["png"])\ndef test_animation_frame(tmpdir, fig_test, fig_ref):\n # Test the expected image after iterating through a few frames\n # we save the animation to get the iteration because we are not\n # in an interactive framework.\n ax = fig_test.add_subplot()\n ax.set_xlim(0, 2 * np.pi)\n ax.set_ylim(-1, 1)\n x = np.linspace(0, 2 * np.pi, 100)\n line, = ax.plot([], [])\n\n def init():\n line.set_data([], [])\n return line,\n\n def animate(i):\n line.set_data(x, np.sin(x + i / 100))\n return line,\n\n anim = animation.FuncAnimation(\n fig_test, animate, init_func=init, frames=5,\n blit=True, repeat=False)\n with tmpdir.as_cwd():\n anim.save("test.gif")\n\n # Reference figure without animation\n ax = fig_ref.add_subplot()\n ax.set_xlim(0, 2 * np.pi)\n ax.set_ylim(-1, 1)\n\n # 5th frame's data\n ax.plot(x, np.sin(x + 4 / 100))\n\n\n@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])\ndef test_save_count_override_warnings_has_length(anim):\n\n save_count = 5\n frames = list(range(2))\n match_target = (\n f'You passed in an explicit {save_count=} '\n "which is being ignored in favor of "\n f"{len(frames)=}."\n )\n\n with pytest.warns(UserWarning, match=re.escape(match_target)):\n anim = animation.FuncAnimation(\n **{**anim, 'frames': frames, 'save_count': save_count}\n )\n assert anim._save_count == len(frames)\n anim._init_draw()\n\n\n@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])\ndef test_save_count_override_warnings_scaler(anim):\n save_count = 5\n frames = 7\n match_target = (\n f'You passed in an explicit {save_count=} ' +\n "which is being ignored in favor of " +\n f"{frames=}."\n )\n\n with pytest.warns(UserWarning, match=re.escape(match_target)):\n anim = animation.FuncAnimation(\n **{**anim, 'frames': frames, 'save_count': save_count}\n )\n\n assert anim._save_count == frames\n anim._init_draw()\n\n\n@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])\ndef test_disable_cache_warning(anim):\n cache_frame_data = True\n frames = iter(range(5))\n match_target = (\n f"{frames=!r} which we can infer the length of, "\n "did not pass an explicit *save_count* "\n f"and passed {cache_frame_data=}. To avoid a possibly "\n "unbounded cache, frame data caching has been disabled. "\n "To suppress this warning either pass "\n "`cache_frame_data=False` or `save_count=MAX_FRAMES`."\n )\n with pytest.warns(UserWarning, match=re.escape(match_target)):\n anim = animation.FuncAnimation(\n **{**anim, 'cache_frame_data': cache_frame_data, 'frames': frames}\n )\n assert anim._cache_frame_data is False\n anim._init_draw()\n\n\ndef test_movie_writer_invalid_path(anim):\n if sys.platform == "win32":\n match_str = r"\[WinError 3] .*'\\\\foo\\\\bar\\\\aardvark'"\n else:\n match_str = r"\[Errno 2] .*'/foo"\n with pytest.raises(FileNotFoundError, match=match_str):\n anim.save("/foo/bar/aardvark/thiscannotreallyexist.mp4",\n writer=animation.FFMpegFileWriter())\n\n\ndef test_animation_with_transparency():\n """Test animation exhaustion with transparency using PillowWriter directly"""\n fig, ax = plt.subplots()\n rect = plt.Rectangle((0, 0), 1, 1, color='red', alpha=0.5)\n ax.add_patch(rect)\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 1)\n\n writer = PillowWriter(fps=30)\n writer.setup(fig, 'unused.gif', dpi=100)\n writer.grab_frame(transparent=True)\n frame = writer._frames[-1]\n # Check that the alpha channel is not 255, so frame has transparency\n assert frame.getextrema()[3][0] < 255\n plt.close(fig)\n | .venv\Lib\site-packages\matplotlib\tests\test_animation.py | test_animation.py | Python | 18,357 | 0.95 | 0.124343 | 0.112311 | react-lib | 336 | 2023-07-26T04:06:07.507089 | MIT | true | c9b7c3f748fca529c6f1025af42b7c76 |
from __future__ import annotations\n\nfrom collections.abc import Callable\nimport re\nimport typing\nfrom typing import Any, TypeVar\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import _api\n\n\nif typing.TYPE_CHECKING:\n from typing_extensions import Self\n\nT = TypeVar('T')\n\n\n@pytest.mark.parametrize('target,shape_repr,test_shape',\n [((None, ), "(N,)", (1, 3)),\n ((None, 3), "(N, 3)", (1,)),\n ((None, 3), "(N, 3)", (1, 2)),\n ((1, 5), "(1, 5)", (1, 9)),\n ((None, 2, None), "(M, 2, N)", (1, 3, 1))\n ])\ndef test_check_shape(target: tuple[int | None, ...],\n shape_repr: str,\n test_shape: tuple[int, ...]) -> None:\n error_pattern = "^" + re.escape(\n f"'aardvark' must be {len(target)}D with shape {shape_repr}, but your input "\n f"has shape {test_shape}")\n data = np.zeros(test_shape)\n with pytest.raises(ValueError, match=error_pattern):\n _api.check_shape(target, aardvark=data)\n\n\ndef test_classproperty_deprecation() -> None:\n class A:\n @_api.deprecated("0.0.0")\n @_api.classproperty\n def f(cls: Self) -> None:\n pass\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n A.f\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n a = A()\n a.f\n\n\ndef test_warn_deprecated():\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match=r'foo was deprecated in Matplotlib 3\.10 and will be '\n r'removed in 3\.12\.'):\n _api.warn_deprecated('3.10', name='foo')\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match=r'The foo class was deprecated in Matplotlib 3\.10 and '\n r'will be removed in 3\.12\.'):\n _api.warn_deprecated('3.10', name='foo', obj_type='class')\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match=r'foo was deprecated in Matplotlib 3\.10 and will be '\n r'removed in 3\.12\. Use bar instead\.'):\n _api.warn_deprecated('3.10', name='foo', alternative='bar')\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match=r'foo was deprecated in Matplotlib 3\.10 and will be '\n r'removed in 3\.12\. More information\.'):\n _api.warn_deprecated('3.10', name='foo', addendum='More information.')\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match=r'foo was deprecated in Matplotlib 3\.10 and will be '\n r'removed in 4\.0\.'):\n _api.warn_deprecated('3.10', name='foo', removal='4.0')\n with pytest.warns(mpl.MatplotlibDeprecationWarning,\n match=r'foo was deprecated in Matplotlib 3\.10\.'):\n _api.warn_deprecated('3.10', name='foo', removal=False)\n with pytest.warns(PendingDeprecationWarning,\n match=r'foo will be deprecated in a future version'):\n _api.warn_deprecated('3.10', name='foo', pending=True)\n with pytest.raises(ValueError, match=r'cannot have a scheduled removal'):\n _api.warn_deprecated('3.10', name='foo', pending=True, removal='3.12')\n with pytest.warns(mpl.MatplotlibDeprecationWarning, match=r'Complete replacement'):\n _api.warn_deprecated('3.10', message='Complete replacement', name='foo',\n alternative='bar', addendum='More information.',\n obj_type='class', removal='4.0')\n\n\ndef test_deprecate_privatize_attribute() -> None:\n class C:\n def __init__(self) -> None: self._attr = 1\n def _meth(self, arg: T) -> T: return arg\n attr: int = _api.deprecate_privatize_attribute("0.0")\n meth: Callable = _api.deprecate_privatize_attribute("0.0")\n\n c = C()\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n assert c.attr == 1\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n c.attr = 2\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n assert c.attr == 2\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n assert c.meth(42) == 42\n\n\ndef test_delete_parameter() -> None:\n @_api.delete_parameter("3.0", "foo")\n def func1(foo: Any = None) -> None:\n pass\n\n @_api.delete_parameter("3.0", "foo")\n def func2(**kwargs: Any) -> None:\n pass\n\n for func in [func1, func2]: # type: ignore[list-item]\n func() # No warning.\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n func(foo="bar")\n\n def pyplot_wrapper(foo: Any = _api.deprecation._deprecated_parameter) -> None:\n func1(foo)\n\n pyplot_wrapper() # No warning.\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n func(foo="bar")\n\n\ndef test_make_keyword_only() -> None:\n @_api.make_keyword_only("3.0", "arg")\n def func(pre: Any, arg: Any, post: Any = None) -> None:\n pass\n\n func(1, arg=2) # Check that no warning is emitted.\n\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n func(1, 2)\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n func(1, 2, 3)\n\n\ndef test_deprecation_alternative() -> None:\n alternative = "`.f1`, `f2`, `f3(x) <.f3>` or `f4(x)<f4>`"\n @_api.deprecated("1", alternative=alternative)\n def f() -> None:\n pass\n if f.__doc__ is None:\n pytest.skip('Documentation is disabled')\n assert alternative in f.__doc__\n\n\ndef test_empty_check_in_list() -> None:\n with pytest.raises(TypeError, match="No argument to check!"):\n _api.check_in_list(["a"])\n | .venv\Lib\site-packages\matplotlib\tests\test_api.py | test_api.py | Python | 5,736 | 0.95 | 0.157895 | 0 | awesome-app | 791 | 2024-11-26T16:06:21.920999 | GPL-3.0 | true | 20607d0ec74c4d4118cb5d6c6af0a8ae |
import pytest\nimport platform\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.patches as mpatches\n\n\ndef draw_arrow(ax, t, r):\n ax.annotate('', xy=(0.5, 0.5 + r), xytext=(0.5, 0.5), size=30,\n arrowprops=dict(arrowstyle=t,\n fc="b", ec='k'))\n\n\n@image_comparison(['fancyarrow_test_image.png'],\n tol=0 if platform.machine() == 'x86_64' else 0.012)\ndef test_fancyarrow():\n # Added 0 to test division by zero error described in issue 3930\n r = [0.4, 0.3, 0.2, 0.1, 0]\n t = ["fancy", "simple", mpatches.ArrowStyle.Fancy()]\n\n fig, axs = plt.subplots(len(t), len(r), squeeze=False,\n figsize=(8, 4.5), subplot_kw=dict(aspect=1))\n\n for i_r, r1 in enumerate(r):\n for i_t, t1 in enumerate(t):\n ax = axs[i_t, i_r]\n draw_arrow(ax, t1, r1)\n ax.tick_params(labelleft=False, labelbottom=False)\n\n\n@image_comparison(['boxarrow_test_image.png'])\ndef test_boxarrow():\n\n styles = mpatches.BoxStyle.get_styles()\n\n n = len(styles)\n spacing = 1.2\n\n figheight = (n * spacing + .5)\n fig = plt.figure(figsize=(4 / 1.5, figheight / 1.5))\n\n fontsize = 0.3 * 72\n\n for i, stylename in enumerate(sorted(styles)):\n fig.text(0.5, ((n - i) * spacing - 0.5)/figheight, stylename,\n ha="center",\n size=fontsize,\n transform=fig.transFigure,\n bbox=dict(boxstyle=stylename, fc="w", ec="k"))\n\n\ndef __prepare_fancyarrow_dpi_cor_test():\n """\n Convenience function that prepares and returns a FancyArrowPatch. It aims\n at being used to test that the size of the arrow head does not depend on\n the DPI value of the exported picture.\n\n NB: this function *is not* a test in itself!\n """\n fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50)\n ax = fig2.add_subplot()\n ax.set_xlim([0, 1])\n ax.set_ylim([0, 1])\n ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6),\n lw=3, arrowstyle='->',\n mutation_scale=100))\n return fig2\n\n\n@image_comparison(['fancyarrow_dpi_cor_100dpi.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.02,\n savefig_kwarg=dict(dpi=100))\ndef test_fancyarrow_dpi_cor_100dpi():\n """\n Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is\n instantiated through a dedicated function because another similar test\n checks a similar export but with a different DPI value.\n\n Remark: test only a rasterized format.\n """\n\n __prepare_fancyarrow_dpi_cor_test()\n\n\n@image_comparison(['fancyarrow_dpi_cor_200dpi.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.02,\n savefig_kwarg=dict(dpi=200))\ndef test_fancyarrow_dpi_cor_200dpi():\n """\n As test_fancyarrow_dpi_cor_100dpi, but exports @ 200 DPI. The relative size\n of the arrow head should be the same.\n """\n\n __prepare_fancyarrow_dpi_cor_test()\n\n\n@image_comparison(['fancyarrow_dash.png'], remove_text=True, style='default')\ndef test_fancyarrow_dash():\n fig, ax = plt.subplots()\n e = mpatches.FancyArrowPatch((0, 0), (0.5, 0.5),\n arrowstyle='-|>',\n connectionstyle='angle3,angleA=0,angleB=90',\n mutation_scale=10.0,\n linewidth=2,\n linestyle='dashed',\n color='k')\n e2 = mpatches.FancyArrowPatch((0, 0), (0.5, 0.5),\n arrowstyle='-|>',\n connectionstyle='angle3',\n mutation_scale=10.0,\n linewidth=2,\n linestyle='dotted',\n color='k')\n ax.add_patch(e)\n ax.add_patch(e2)\n\n\n@image_comparison(['arrow_styles.png'], style='mpl20', remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.02)\ndef test_arrow_styles():\n styles = mpatches.ArrowStyle.get_styles()\n\n n = len(styles)\n fig, ax = plt.subplots(figsize=(8, 8))\n ax.set_xlim(0, 1)\n ax.set_ylim(-1, n)\n fig.subplots_adjust(left=0, right=1, bottom=0, top=1)\n\n for i, stylename in enumerate(sorted(styles)):\n patch = mpatches.FancyArrowPatch((0.1 + (i % 2)*0.05, i),\n (0.45 + (i % 2)*0.05, i),\n arrowstyle=stylename,\n mutation_scale=25)\n ax.add_patch(patch)\n\n for i, stylename in enumerate([']-[', ']-', '-[', '|-|']):\n style = stylename\n if stylename[0] != '-':\n style += ',angleA=ANGLE'\n if stylename[-1] != '-':\n style += ',angleB=ANGLE'\n\n for j, angle in enumerate([-30, 60]):\n arrowstyle = style.replace('ANGLE', str(angle))\n patch = mpatches.FancyArrowPatch((0.55, 2*i + j), (0.9, 2*i + j),\n arrowstyle=arrowstyle,\n mutation_scale=25)\n ax.add_patch(patch)\n\n\n@image_comparison(['connection_styles.png'], style='mpl20', remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.013)\ndef test_connection_styles():\n styles = mpatches.ConnectionStyle.get_styles()\n\n n = len(styles)\n fig, ax = plt.subplots(figsize=(6, 10))\n ax.set_xlim(0, 1)\n ax.set_ylim(-1, n)\n\n for i, stylename in enumerate(sorted(styles)):\n patch = mpatches.FancyArrowPatch((0.1, i), (0.8, i + 0.5),\n arrowstyle="->",\n connectionstyle=stylename,\n mutation_scale=25)\n ax.add_patch(patch)\n\n\ndef test_invalid_intersection():\n conn_style_1 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=200)\n p1 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),\n connectionstyle=conn_style_1)\n with pytest.raises(ValueError):\n plt.gca().add_patch(p1)\n\n conn_style_2 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=199.9)\n p2 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),\n connectionstyle=conn_style_2)\n plt.gca().add_patch(p2)\n | .venv\Lib\site-packages\matplotlib\tests\test_arrow_patches.py | test_arrow_patches.py | Python | 6,577 | 0.95 | 0.150838 | 0.007092 | vue-tools | 381 | 2025-05-08T23:03:36.358710 | Apache-2.0 | true | 01ee55afb92cd47fbdea9d0fd598a7ac |
import io\nfrom itertools import chain\n\nimport numpy as np\n\nimport pytest\n\nimport matplotlib.colors as mcolors\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport matplotlib.lines as mlines\nimport matplotlib.path as mpath\nimport matplotlib.transforms as mtransforms\nimport matplotlib.collections as mcollections\nimport matplotlib.artist as martist\nimport matplotlib.backend_bases as mbackend_bases\nimport matplotlib as mpl\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\n\n\ndef test_patch_transform_of_none():\n # tests the behaviour of patches added to an Axes with various transform\n # specifications\n\n ax = plt.axes()\n ax.set_xlim(1, 3)\n ax.set_ylim(1, 3)\n\n # Draw an ellipse over data coord (2, 2) by specifying device coords.\n xy_data = (2, 2)\n xy_pix = ax.transData.transform(xy_data)\n\n # Not providing a transform of None puts the ellipse in data coordinates .\n e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5)\n ax.add_patch(e)\n assert e._transform == ax.transData\n\n # Providing a transform of None puts the ellipse in device coordinates.\n e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',\n transform=None, alpha=0.5)\n assert e.is_transform_set()\n ax.add_patch(e)\n assert isinstance(e._transform, mtransforms.IdentityTransform)\n\n # Providing an IdentityTransform puts the ellipse in device coordinates.\n e = mpatches.Ellipse(xy_pix, width=100, height=100,\n transform=mtransforms.IdentityTransform(), alpha=0.5)\n ax.add_patch(e)\n assert isinstance(e._transform, mtransforms.IdentityTransform)\n\n # Not providing a transform, and then subsequently "get_transform" should\n # not mean that "is_transform_set".\n e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',\n alpha=0.5)\n intermediate_transform = e.get_transform()\n assert not e.is_transform_set()\n ax.add_patch(e)\n assert e.get_transform() != intermediate_transform\n assert e.is_transform_set()\n assert e._transform == ax.transData\n\n\ndef test_collection_transform_of_none():\n # tests the behaviour of collections added to an Axes with various\n # transform specifications\n\n ax = plt.axes()\n ax.set_xlim(1, 3)\n ax.set_ylim(1, 3)\n\n # draw an ellipse over data coord (2, 2) by specifying device coords\n xy_data = (2, 2)\n xy_pix = ax.transData.transform(xy_data)\n\n # not providing a transform of None puts the ellipse in data coordinates\n e = mpatches.Ellipse(xy_data, width=1, height=1)\n c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5)\n ax.add_collection(c)\n # the collection should be in data coordinates\n assert c.get_offset_transform() + c.get_transform() == ax.transData\n\n # providing a transform of None puts the ellipse in device coordinates\n e = mpatches.Ellipse(xy_pix, width=120, height=120)\n c = mcollections.PatchCollection([e], facecolor='coral',\n alpha=0.5)\n c.set_transform(None)\n ax.add_collection(c)\n assert isinstance(c.get_transform(), mtransforms.IdentityTransform)\n\n # providing an IdentityTransform puts the ellipse in device coordinates\n e = mpatches.Ellipse(xy_pix, width=100, height=100)\n c = mcollections.PatchCollection([e],\n transform=mtransforms.IdentityTransform(),\n alpha=0.5)\n ax.add_collection(c)\n assert isinstance(c.get_offset_transform(), mtransforms.IdentityTransform)\n\n\n@image_comparison(["clip_path_clipping"], remove_text=True)\ndef test_clipping():\n exterior = mpath.Path.unit_rectangle().deepcopy()\n exterior.vertices *= 4\n exterior.vertices -= 2\n interior = mpath.Path.unit_circle().deepcopy()\n interior.vertices = interior.vertices[::-1]\n clip_path = mpath.Path.make_compound_path(exterior, interior)\n\n star = mpath.Path.unit_regular_star(6).deepcopy()\n star.vertices *= 2.6\n\n fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)\n\n col = mcollections.PathCollection([star], lw=5, edgecolor='blue',\n facecolor='red', alpha=0.7, hatch='*')\n col.set_clip_path(clip_path, ax1.transData)\n ax1.add_collection(col)\n\n patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red',\n alpha=0.7, hatch='*')\n patch.set_clip_path(clip_path, ax2.transData)\n ax2.add_patch(patch)\n\n ax1.set_xlim([-3, 3])\n ax1.set_ylim([-3, 3])\n\n\n@check_figures_equal(extensions=['png'])\ndef test_clipping_zoom(fig_test, fig_ref):\n # This test places the Axes and sets its limits such that the clip path is\n # outside the figure entirely. This should not break the clip path.\n ax_test = fig_test.add_axes([0, 0, 1, 1])\n l, = ax_test.plot([-3, 3], [-3, 3])\n # Explicit Path instead of a Rectangle uses clip path processing, instead\n # of a clip box optimization.\n p = mpath.Path([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])\n p = mpatches.PathPatch(p, transform=ax_test.transData)\n l.set_clip_path(p)\n\n ax_ref = fig_ref.add_axes([0, 0, 1, 1])\n ax_ref.plot([-3, 3], [-3, 3])\n\n ax_ref.set(xlim=(0.5, 0.75), ylim=(0.5, 0.75))\n ax_test.set(xlim=(0.5, 0.75), ylim=(0.5, 0.75))\n\n\ndef test_cull_markers():\n x = np.random.random(20000)\n y = np.random.random(20000)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, 'k.')\n ax.set_xlim(2, 3)\n\n pdf = io.BytesIO()\n fig.savefig(pdf, format="pdf")\n assert len(pdf.getvalue()) < 8000\n\n svg = io.BytesIO()\n fig.savefig(svg, format="svg")\n assert len(svg.getvalue()) < 20000\n\n\n@image_comparison(['hatching'], remove_text=True, style='default')\ndef test_hatching():\n fig, ax = plt.subplots(1, 1)\n\n # Default hatch color.\n rect1 = mpatches.Rectangle((0, 0), 3, 4, hatch='/')\n ax.add_patch(rect1)\n\n rect2 = mcollections.RegularPolyCollection(\n 4, sizes=[16000], offsets=[(1.5, 6.5)], offset_transform=ax.transData,\n hatch='/')\n ax.add_collection(rect2)\n\n # Ensure edge color is not applied to hatching.\n rect3 = mpatches.Rectangle((4, 0), 3, 4, hatch='/', edgecolor='C1')\n ax.add_patch(rect3)\n\n rect4 = mcollections.RegularPolyCollection(\n 4, sizes=[16000], offsets=[(5.5, 6.5)], offset_transform=ax.transData,\n hatch='/', edgecolor='C1')\n ax.add_collection(rect4)\n\n ax.set_xlim(0, 7)\n ax.set_ylim(0, 9)\n\n\ndef test_remove():\n fig, ax = plt.subplots()\n im = ax.imshow(np.arange(36).reshape(6, 6))\n ln, = ax.plot(range(5))\n\n assert fig.stale\n assert ax.stale\n\n fig.canvas.draw()\n assert not fig.stale\n assert not ax.stale\n assert not ln.stale\n\n assert im in ax._mouseover_set\n assert ln not in ax._mouseover_set\n assert im.axes is ax\n\n im.remove()\n ln.remove()\n\n for art in [im, ln]:\n assert art.axes is None\n assert art.get_figure() is None\n\n assert im not in ax._mouseover_set\n assert fig.stale\n assert ax.stale\n\n\n@image_comparison(["default_edges.png"], remove_text=True, style='default')\ndef test_default_edges():\n # Remove this line when this test image is regenerated.\n plt.rcParams['text.kerning_factor'] = 6\n\n fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2)\n\n ax1.plot(np.arange(10), np.arange(10), 'x',\n np.arange(10) + 1, np.arange(10), 'o')\n ax2.bar(np.arange(10), np.arange(10), align='edge')\n ax3.text(0, 0, "BOX", size=24, bbox=dict(boxstyle='sawtooth'))\n ax3.set_xlim((-1, 1))\n ax3.set_ylim((-1, 1))\n pp1 = mpatches.PathPatch(\n mpath.Path([(0, 0), (1, 0), (1, 1), (0, 0)],\n [mpath.Path.MOVETO, mpath.Path.CURVE3,\n mpath.Path.CURVE3, mpath.Path.CLOSEPOLY]),\n fc="none", transform=ax4.transData)\n ax4.add_patch(pp1)\n\n\ndef test_properties():\n ln = mlines.Line2D([], [])\n ln.properties() # Check that no warning is emitted.\n\n\ndef test_setp():\n # Check empty list\n plt.setp([])\n plt.setp([[]])\n\n # Check arbitrary iterables\n fig, ax = plt.subplots()\n lines1 = ax.plot(range(3))\n lines2 = ax.plot(range(3))\n martist.setp(chain(lines1, lines2), 'lw', 5)\n plt.setp(ax.spines.values(), color='green')\n\n # Check *file* argument\n sio = io.StringIO()\n plt.setp(lines1, 'zorder', file=sio)\n assert sio.getvalue() == ' zorder: float\n'\n\n\ndef test_None_zorder():\n fig, ax = plt.subplots()\n ln, = ax.plot(range(5), zorder=None)\n assert ln.get_zorder() == mlines.Line2D.zorder\n ln.set_zorder(123456)\n assert ln.get_zorder() == 123456\n ln.set_zorder(None)\n assert ln.get_zorder() == mlines.Line2D.zorder\n\n\n@pytest.mark.parametrize('accept_clause, expected', [\n ('', 'unknown'),\n ("ACCEPTS: [ '-' | '--' | '-.' ]", "[ '-' | '--' | '-.' ]"),\n ('ACCEPTS: Some description.', 'Some description.'),\n ('.. ACCEPTS: Some description.', 'Some description.'),\n ('arg : int', 'int'),\n ('*arg : int', 'int'),\n ('arg : int\nACCEPTS: Something else.', 'Something else. '),\n])\ndef test_artist_inspector_get_valid_values(accept_clause, expected):\n class TestArtist(martist.Artist):\n def set_f(self, arg):\n pass\n\n TestArtist.set_f.__doc__ = """\n Some text.\n\n %s\n """ % accept_clause\n valid_values = martist.ArtistInspector(TestArtist).get_valid_values('f')\n assert valid_values == expected\n\n\ndef test_artist_inspector_get_aliases():\n # test the correct format and type of get_aliases method\n ai = martist.ArtistInspector(mlines.Line2D)\n aliases = ai.get_aliases()\n assert aliases["linewidth"] == {"lw"}\n\n\ndef test_set_alpha():\n art = martist.Artist()\n with pytest.raises(TypeError, match='^alpha must be numeric or None'):\n art.set_alpha('string')\n with pytest.raises(TypeError, match='^alpha must be numeric or None'):\n art.set_alpha([1, 2, 3])\n with pytest.raises(ValueError, match="outside 0-1 range"):\n art.set_alpha(1.1)\n with pytest.raises(ValueError, match="outside 0-1 range"):\n art.set_alpha(np.nan)\n\n\ndef test_set_alpha_for_array():\n art = martist.Artist()\n with pytest.raises(TypeError, match='^alpha must be numeric or None'):\n art._set_alpha_for_array('string')\n with pytest.raises(ValueError, match="outside 0-1 range"):\n art._set_alpha_for_array(1.1)\n with pytest.raises(ValueError, match="outside 0-1 range"):\n art._set_alpha_for_array(np.nan)\n with pytest.raises(ValueError, match="alpha must be between 0 and 1"):\n art._set_alpha_for_array([0.5, 1.1])\n with pytest.raises(ValueError, match="alpha must be between 0 and 1"):\n art._set_alpha_for_array([0.5, np.nan])\n\n\ndef test_callbacks():\n def func(artist):\n func.counter += 1\n\n func.counter = 0\n\n art = martist.Artist()\n oid = art.add_callback(func)\n assert func.counter == 0\n art.pchanged() # must call the callback\n assert func.counter == 1\n art.set_zorder(10) # setting a property must also call the callback\n assert func.counter == 2\n art.remove_callback(oid)\n art.pchanged() # must not call the callback anymore\n assert func.counter == 2\n\n\ndef test_set_signature():\n """Test autogenerated ``set()`` for Artist subclasses."""\n class MyArtist1(martist.Artist):\n def set_myparam1(self, val):\n pass\n\n assert hasattr(MyArtist1.set, '_autogenerated_signature')\n assert 'myparam1' in MyArtist1.set.__doc__\n\n class MyArtist2(MyArtist1):\n def set_myparam2(self, val):\n pass\n\n assert hasattr(MyArtist2.set, '_autogenerated_signature')\n assert 'myparam1' in MyArtist2.set.__doc__\n assert 'myparam2' in MyArtist2.set.__doc__\n\n\ndef test_set_is_overwritten():\n """set() defined in Artist subclasses should not be overwritten."""\n class MyArtist3(martist.Artist):\n\n def set(self, **kwargs):\n """Not overwritten."""\n\n assert not hasattr(MyArtist3.set, '_autogenerated_signature')\n assert MyArtist3.set.__doc__ == "Not overwritten."\n\n class MyArtist4(MyArtist3):\n pass\n\n assert MyArtist4.set is MyArtist3.set\n\n\ndef test_format_cursor_data_BoundaryNorm():\n """Test if cursor data is correct when using BoundaryNorm."""\n X = np.empty((3, 3))\n X[0, 0] = 0.9\n X[0, 1] = 0.99\n X[0, 2] = 0.999\n X[1, 0] = -1\n X[1, 1] = 0\n X[1, 2] = 1\n X[2, 0] = 0.09\n X[2, 1] = 0.009\n X[2, 2] = 0.0009\n\n # map range -1..1 to 0..256 in 0.1 steps\n fig, ax = plt.subplots()\n fig.suptitle("-1..1 to 0..256 in 0.1")\n norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 20), 256)\n img = ax.imshow(X, cmap='RdBu_r', norm=norm)\n\n labels_list = [\n "[0.9]",\n "[1.]",\n "[1.]",\n "[-1.0]",\n "[0.0]",\n "[1.0]",\n "[0.09]",\n "[0.009]",\n "[0.0009]",\n ]\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.1))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n # map range -1..1 to 0..256 in 0.01 steps\n fig, ax = plt.subplots()\n fig.suptitle("-1..1 to 0..256 in 0.01")\n cmap = mpl.colormaps['RdBu_r'].resampled(200)\n norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 200), 200)\n img = ax.imshow(X, cmap=cmap, norm=norm)\n\n labels_list = [\n "[0.90]",\n "[0.99]",\n "[1.0]",\n "[-1.00]",\n "[0.00]",\n "[1.00]",\n "[0.09]",\n "[0.009]",\n "[0.0009]",\n ]\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.01))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n # map range -1..1 to 0..256 in 0.01 steps\n fig, ax = plt.subplots()\n fig.suptitle("-1..1 to 0..256 in 0.001")\n cmap = mpl.colormaps['RdBu_r'].resampled(2000)\n norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 2000), 2000)\n img = ax.imshow(X, cmap=cmap, norm=norm)\n\n labels_list = [\n "[0.900]",\n "[0.990]",\n "[0.999]",\n "[-1.000]",\n "[0.000]",\n "[1.000]",\n "[0.090]",\n "[0.009]",\n "[0.0009]",\n ]\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.001))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n # different testing data set with\n # out of bounds values for 0..1 range\n X = np.empty((7, 1))\n X[0] = -1.0\n X[1] = 0.0\n X[2] = 0.1\n X[3] = 0.5\n X[4] = 0.9\n X[5] = 1.0\n X[6] = 2.0\n\n labels_list = [\n "[-1.0]",\n "[0.0]",\n "[0.1]",\n "[0.5]",\n "[0.9]",\n "[1.0]",\n "[2.0]",\n ]\n\n fig, ax = plt.subplots()\n fig.suptitle("noclip, neither")\n norm = mcolors.BoundaryNorm(\n np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='neither')\n img = ax.imshow(X, cmap='RdBu_r', norm=norm)\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n fig, ax = plt.subplots()\n fig.suptitle("noclip, min")\n norm = mcolors.BoundaryNorm(\n np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='min')\n img = ax.imshow(X, cmap='RdBu_r', norm=norm)\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n fig, ax = plt.subplots()\n fig.suptitle("noclip, max")\n norm = mcolors.BoundaryNorm(\n np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='max')\n img = ax.imshow(X, cmap='RdBu_r', norm=norm)\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n fig, ax = plt.subplots()\n fig.suptitle("noclip, both")\n norm = mcolors.BoundaryNorm(\n np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='both')\n img = ax.imshow(X, cmap='RdBu_r', norm=norm)\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n fig, ax = plt.subplots()\n fig.suptitle("clip, neither")\n norm = mcolors.BoundaryNorm(\n np.linspace(0, 1, 4, endpoint=True), 256, clip=True, extend='neither')\n img = ax.imshow(X, cmap='RdBu_r', norm=norm)\n for v, label in zip(X.flat, labels_list):\n # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))\n assert img.format_cursor_data(v) == label\n\n plt.close()\n\n\ndef test_auto_no_rasterize():\n class Gen1(martist.Artist):\n ...\n\n assert 'draw' in Gen1.__dict__\n assert Gen1.__dict__['draw'] is Gen1.draw\n\n class Gen2(Gen1):\n ...\n\n assert 'draw' not in Gen2.__dict__\n assert Gen2.draw is Gen1.draw\n\n\ndef test_draw_wraper_forward_input():\n class TestKlass(martist.Artist):\n def draw(self, renderer, extra):\n return extra\n\n art = TestKlass()\n renderer = mbackend_bases.RendererBase()\n\n assert 'aardvark' == art.draw(renderer, 'aardvark')\n assert 'aardvark' == art.draw(renderer, extra='aardvark')\n\n\ndef test_get_figure():\n fig = plt.figure()\n sfig1 = fig.subfigures()\n sfig2 = sfig1.subfigures()\n ax = sfig2.subplots()\n\n assert fig.get_figure(root=True) is fig\n assert fig.get_figure(root=False) is fig\n\n assert ax.get_figure() is sfig2\n assert ax.get_figure(root=False) is sfig2\n assert ax.get_figure(root=True) is fig\n\n # SubFigure.get_figure has separate implementation but should give consistent\n # results to other artists.\n assert sfig2.get_figure(root=False) is sfig1\n assert sfig2.get_figure(root=True) is fig\n # Currently different results by default.\n with pytest.warns(mpl.MatplotlibDeprecationWarning):\n assert sfig2.get_figure() is fig\n # No deprecation warning if root and parent figure are the same.\n assert sfig1.get_figure() is fig\n\n # An artist not yet attached to anything has no figure.\n ln = mlines.Line2D([], [])\n assert ln.get_figure(root=True) is None\n assert ln.get_figure(root=False) is None\n\n # figure attribute is root for (Sub)Figures but parent for other artists.\n assert ax.figure is sfig2\n assert fig.figure is fig\n assert sfig2.figure is fig\n | .venv\Lib\site-packages\matplotlib\tests\test_artist.py | test_artist.py | Python | 18,599 | 0.95 | 0.085284 | 0.095137 | react-lib | 329 | 2023-09-21T15:52:46.476631 | BSD-3-Clause | true | 0fa34f8a4bcaf5979c33ae08640b9adb |
import numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.axis import XTick\n\n\ndef test_tick_labelcolor_array():\n # Smoke test that we can instantiate a Tick with labelcolor as array.\n ax = plt.axes()\n XTick(ax, 0, labelcolor=np.array([1, 0, 0, 1]))\n\n\ndef test_axis_not_in_layout():\n fig1, (ax1_left, ax1_right) = plt.subplots(ncols=2, layout='constrained')\n fig2, (ax2_left, ax2_right) = plt.subplots(ncols=2, layout='constrained')\n\n # 100 label overlapping the end of the axis\n ax1_left.set_xlim([0, 100])\n # 100 label not overlapping the end of the axis\n ax2_left.set_xlim([0, 120])\n\n for ax in ax1_left, ax2_left:\n ax.set_xticks([0, 100])\n ax.xaxis.set_in_layout(False)\n\n for fig in fig1, fig2:\n fig.draw_without_rendering()\n\n # Positions should not be affected by overlapping 100 label\n assert ax1_left.get_position().bounds == ax2_left.get_position().bounds\n assert ax1_right.get_position().bounds == ax2_right.get_position().bounds\n\n\ndef test_translate_tick_params_reverse():\n fig, ax = plt.subplots()\n kw = {'label1On': 'a', 'label2On': 'b', 'tick1On': 'c', 'tick2On': 'd'}\n assert (ax.xaxis._translate_tick_params(kw, reverse=True) ==\n {'labelbottom': 'a', 'labeltop': 'b', 'bottom': 'c', 'top': 'd'})\n assert (ax.yaxis._translate_tick_params(kw, reverse=True) ==\n {'labelleft': 'a', 'labelright': 'b', 'left': 'c', 'right': 'd'})\n | .venv\Lib\site-packages\matplotlib\tests\test_axis.py | test_axis.py | Python | 1,446 | 0.95 | 0.125 | 0.137931 | node-utils | 872 | 2023-11-07T05:30:33.618874 | GPL-3.0 | true | f1afab48d2d889fbe3f5c1e5f644ec5f |
import functools\nimport importlib\nimport importlib.util\nimport inspect\nimport json\nimport os\nimport platform\nimport signal\nimport subprocess\nimport sys\nimport tempfile\nimport time\nimport urllib.request\n\nfrom PIL import Image\n\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import _c_internal_utils\nfrom matplotlib.backend_tools import ToolToggleBase\nfrom matplotlib.testing import subprocess_run_helper as _run_helper, is_ci_environment\n\n\nclass _WaitForStringPopen(subprocess.Popen):\n """\n A Popen that passes flags that allow triggering KeyboardInterrupt.\n """\n\n def __init__(self, *args, **kwargs):\n if sys.platform == 'win32':\n kwargs['creationflags'] = subprocess.CREATE_NEW_CONSOLE\n super().__init__(\n *args, **kwargs,\n # Force Agg so that each test can switch to its desired backend.\n env={**os.environ, "MPLBACKEND": "Agg", "SOURCE_DATE_EPOCH": "0"},\n stdout=subprocess.PIPE, universal_newlines=True)\n\n def wait_for(self, terminator):\n """Read until the terminator is reached."""\n buf = ''\n while True:\n c = self.stdout.read(1)\n if not c:\n raise RuntimeError(\n f'Subprocess died before emitting expected {terminator!r}')\n buf += c\n if buf.endswith(terminator):\n return\n\n\n# Minimal smoke-testing of the backends for which the dependencies are\n# PyPI-installable on CI. They are not available for all tested Python\n# versions so we don't fail on missing backends.\n\n@functools.lru_cache\ndef _get_available_interactive_backends():\n _is_linux_and_display_invalid = (sys.platform == "linux" and\n not _c_internal_utils.display_is_valid())\n _is_linux_and_xdisplay_invalid = (sys.platform == "linux" and\n not _c_internal_utils.xdisplay_is_valid())\n envs = []\n for deps, env in [\n *[([qt_api],\n {"MPLBACKEND": "qtagg", "QT_API": qt_api})\n for qt_api in ["PyQt6", "PySide6", "PyQt5", "PySide2"]],\n *[([qt_api, "cairocffi"],\n {"MPLBACKEND": "qtcairo", "QT_API": qt_api})\n for qt_api in ["PyQt6", "PySide6", "PyQt5", "PySide2"]],\n *[(["cairo", "gi"], {"MPLBACKEND": f"gtk{version}{renderer}"})\n for version in [3, 4] for renderer in ["agg", "cairo"]],\n (["tkinter"], {"MPLBACKEND": "tkagg"}),\n (["wx"], {"MPLBACKEND": "wx"}),\n (["wx"], {"MPLBACKEND": "wxagg"}),\n (["matplotlib.backends._macosx"], {"MPLBACKEND": "macosx"}),\n ]:\n reason = None\n missing = [dep for dep in deps if not importlib.util.find_spec(dep)]\n if missing:\n reason = "{} cannot be imported".format(", ".join(missing))\n elif _is_linux_and_xdisplay_invalid and (\n env["MPLBACKEND"] == "tkagg"\n # Remove when https://github.com/wxWidgets/Phoenix/pull/2638 is out.\n or env["MPLBACKEND"].startswith("wx")):\n reason = "$DISPLAY is unset"\n elif _is_linux_and_display_invalid:\n reason = "$DISPLAY and $WAYLAND_DISPLAY are unset"\n elif env["MPLBACKEND"] == 'macosx' and os.environ.get('TF_BUILD'):\n reason = "macosx backend fails on Azure"\n elif env["MPLBACKEND"].startswith('gtk'):\n try:\n import gi # type: ignore[import]\n except ImportError:\n # Though we check that `gi` exists above, it is possible that its\n # C-level dependencies are not available, and then it still raises an\n # `ImportError`, so guard against that.\n available_gtk_versions = []\n else:\n gi_repo = gi.Repository.get_default()\n available_gtk_versions = gi_repo.enumerate_versions('Gtk')\n version = env["MPLBACKEND"][3]\n if f'{version}.0' not in available_gtk_versions:\n reason = "no usable GTK bindings"\n marks = []\n if reason:\n marks.append(pytest.mark.skip(reason=f"Skipping {env} because {reason}"))\n elif env["MPLBACKEND"].startswith('wx') and sys.platform == 'darwin':\n # ignore on macosx because that's currently broken (github #16849)\n marks.append(pytest.mark.xfail(reason='github #16849'))\n elif (env['MPLBACKEND'] == 'tkagg' and\n ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and\n sys.platform == 'darwin' and\n sys.version_info[:2] < (3, 11)\n ):\n marks.append( # https://github.com/actions/setup-python/issues/649\n pytest.mark.xfail(reason='Tk version mismatch on Azure macOS CI'))\n envs.append(({**env, 'BACKEND_DEPS': ','.join(deps)}, marks))\n return envs\n\n\ndef _get_testable_interactive_backends():\n # We re-create this because some of the callers below might modify the markers.\n return [pytest.param({**env}, marks=[*marks],\n id='-'.join(f'{k}={v}' for k, v in env.items()))\n for env, marks in _get_available_interactive_backends()]\n\n\n# Reasonable safe values for slower CI/Remote and local architectures.\n_test_timeout = 120 if is_ci_environment() else 20\n\n\ndef _test_toolbar_button_la_mode_icon(fig):\n # test a toolbar button icon using an image in LA mode (GH issue 25174)\n # create an icon in LA mode\n with tempfile.TemporaryDirectory() as tempdir:\n img = Image.new("LA", (26, 26))\n tmp_img_path = os.path.join(tempdir, "test_la_icon.png")\n img.save(tmp_img_path)\n\n class CustomTool(ToolToggleBase):\n image = tmp_img_path\n description = "" # gtk3 backend does not allow None\n\n toolmanager = fig.canvas.manager.toolmanager\n toolbar = fig.canvas.manager.toolbar\n toolmanager.add_tool("test", CustomTool)\n toolbar.add_tool("test", "group")\n\n\n# The source of this function gets extracted and run in another process, so it\n# must be fully self-contained.\n# Using a timer not only allows testing of timers (on other backends), but is\n# also necessary on gtk3 and wx, where directly processing a KeyEvent() for "q"\n# from draw_event causes breakage as the canvas widget gets deleted too early.\ndef _test_interactive_impl():\n import importlib.util\n import io\n import json\n import sys\n\n import pytest\n\n import matplotlib as mpl\n from matplotlib import pyplot as plt\n from matplotlib.backend_bases import KeyEvent\n mpl.rcParams.update({\n "webagg.open_in_browser": False,\n "webagg.port_retries": 1,\n })\n\n mpl.rcParams.update(json.loads(sys.argv[1]))\n backend = plt.rcParams["backend"].lower()\n\n if backend.endswith("agg") and not backend.startswith(("gtk", "web")):\n # Force interactive framework setup.\n fig = plt.figure()\n plt.close(fig)\n\n # Check that we cannot switch to a backend using another interactive\n # framework, but can switch to a backend using cairo instead of agg,\n # or a non-interactive backend. In the first case, we use tkagg as\n # the "other" interactive backend as it is (essentially) guaranteed\n # to be present. Moreover, don't test switching away from gtk3 (as\n # Gtk.main_level() is not set up at this point yet) and webagg (which\n # uses no interactive framework).\n\n if backend != "tkagg":\n with pytest.raises(ImportError):\n mpl.use("tkagg", force=True)\n\n def check_alt_backend(alt_backend):\n mpl.use(alt_backend, force=True)\n fig = plt.figure()\n assert (type(fig.canvas).__module__ ==\n f"matplotlib.backends.backend_{alt_backend}")\n plt.close("all")\n\n if importlib.util.find_spec("cairocffi"):\n check_alt_backend(backend[:-3] + "cairo")\n check_alt_backend("svg")\n mpl.use(backend, force=True)\n\n fig, ax = plt.subplots()\n assert type(fig.canvas).__module__ == f"matplotlib.backends.backend_{backend}"\n\n assert fig.canvas.manager.get_window_title() == "Figure 1"\n\n if mpl.rcParams["toolbar"] == "toolmanager":\n # test toolbar button icon LA mode see GH issue 25174\n _test_toolbar_button_la_mode_icon(fig)\n\n ax.plot([0, 1], [2, 3])\n if fig.canvas.toolbar: # i.e toolbar2.\n fig.canvas.toolbar.draw_rubberband(None, 1., 1, 2., 2)\n\n timer = fig.canvas.new_timer(1.) # Test that floats are cast to int.\n timer.add_callback(KeyEvent("key_press_event", fig.canvas, "q")._process)\n # Trigger quitting upon draw.\n fig.canvas.mpl_connect("draw_event", lambda event: timer.start())\n fig.canvas.mpl_connect("close_event", print)\n\n result = io.BytesIO()\n fig.savefig(result, format='png')\n\n plt.show()\n\n # Ensure that the window is really closed.\n plt.pause(0.5)\n\n # Test that saving works after interactive window is closed, but the figure\n # is not deleted.\n result_after = io.BytesIO()\n fig.savefig(result_after, format='png')\n\n assert result.getvalue() == result_after.getvalue()\n\n\n@pytest.mark.parametrize("env", _get_testable_interactive_backends())\n@pytest.mark.parametrize("toolbar", ["toolbar2", "toolmanager"])\n@pytest.mark.flaky(reruns=3)\ndef test_interactive_backend(env, toolbar):\n if env["MPLBACKEND"] == "macosx":\n if toolbar == "toolmanager":\n pytest.skip("toolmanager is not implemented for macosx.")\n if env["MPLBACKEND"] == "wx":\n pytest.skip("wx backend is deprecated; tests failed on appveyor")\n if env["MPLBACKEND"] == "wxagg" and toolbar == "toolmanager":\n pytest.skip("Temporarily deactivated: show() changes figure height "\n "and thus fails the test")\n try:\n proc = _run_helper(\n _test_interactive_impl,\n json.dumps({"toolbar": toolbar}),\n timeout=_test_timeout,\n extra_env=env,\n )\n except subprocess.CalledProcessError as err:\n pytest.fail(\n "Subprocess failed to test intended behavior\n"\n + str(err.stderr))\n assert proc.stdout.count("CloseEvent") == 1\n\n\ndef _test_thread_impl():\n from concurrent.futures import ThreadPoolExecutor\n\n import matplotlib as mpl\n from matplotlib import pyplot as plt\n\n mpl.rcParams.update({\n "webagg.open_in_browser": False,\n "webagg.port_retries": 1,\n })\n\n # Test artist creation and drawing does not crash from thread\n # No other guarantees!\n fig, ax = plt.subplots()\n # plt.pause needed vs plt.show(block=False) at least on toolbar2-tkagg\n plt.pause(0.5)\n\n future = ThreadPoolExecutor().submit(ax.plot, [1, 3, 6])\n future.result() # Joins the thread; rethrows any exception.\n\n fig.canvas.mpl_connect("close_event", print)\n future = ThreadPoolExecutor().submit(fig.canvas.draw)\n plt.pause(0.5) # flush_events fails here on at least Tkagg (bpo-41176)\n future.result() # Joins the thread; rethrows any exception.\n plt.close() # backend is responsible for flushing any events here\n if plt.rcParams["backend"].lower().startswith("wx"):\n # TODO: debug why WX needs this only on py >= 3.8\n fig.canvas.flush_events()\n\n\n_thread_safe_backends = _get_testable_interactive_backends()\n# Known unsafe backends. Remove the xfails if they start to pass!\nfor param in _thread_safe_backends:\n backend = param.values[0]["MPLBACKEND"]\n if "cairo" in backend:\n # Cairo backends save a cairo_t on the graphics context, and sharing\n # these is not threadsafe.\n param.marks.append(\n pytest.mark.xfail(raises=subprocess.CalledProcessError))\n elif backend == "wx":\n param.marks.append(\n pytest.mark.xfail(raises=subprocess.CalledProcessError))\n elif backend == "macosx":\n from packaging.version import parse\n mac_ver = platform.mac_ver()[0]\n # Note, macOS Big Sur is both 11 and 10.16, depending on SDK that\n # Python was compiled against.\n if mac_ver and parse(mac_ver) < parse('10.16'):\n param.marks.append(\n pytest.mark.xfail(raises=subprocess.TimeoutExpired,\n strict=True))\n elif param.values[0].get("QT_API") == "PySide2":\n param.marks.append(\n pytest.mark.xfail(raises=subprocess.CalledProcessError))\n elif backend == "tkagg" and platform.python_implementation() != 'CPython':\n param.marks.append(\n pytest.mark.xfail(\n reason='PyPy does not support Tkinter threading: '\n 'https://foss.heptapod.net/pypy/pypy/-/issues/1929',\n strict=True))\n elif (backend == 'tkagg' and\n ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and\n sys.platform == 'darwin' and sys.version_info[:2] < (3, 11)):\n param.marks.append( # https://github.com/actions/setup-python/issues/649\n pytest.mark.xfail('Tk version mismatch on Azure macOS CI'))\n\n\n@pytest.mark.parametrize("env", _thread_safe_backends)\n@pytest.mark.flaky(reruns=3)\ndef test_interactive_thread_safety(env):\n proc = _run_helper(_test_thread_impl, timeout=_test_timeout, extra_env=env)\n assert proc.stdout.count("CloseEvent") == 1\n\n\ndef _impl_test_lazy_auto_backend_selection():\n import matplotlib\n import matplotlib.pyplot as plt\n # just importing pyplot should not be enough to trigger resolution\n bk = matplotlib.rcParams._get('backend')\n assert not isinstance(bk, str)\n assert plt._backend_mod is None\n # but actually plotting should\n plt.plot(5)\n assert plt._backend_mod is not None\n bk = matplotlib.rcParams._get('backend')\n assert isinstance(bk, str)\n\n\ndef test_lazy_auto_backend_selection():\n _run_helper(_impl_test_lazy_auto_backend_selection,\n timeout=_test_timeout)\n\n\ndef _implqt5agg():\n import matplotlib.backends.backend_qt5agg # noqa\n import sys\n\n assert 'PyQt6' not in sys.modules\n assert 'pyside6' not in sys.modules\n assert 'PyQt5' in sys.modules or 'pyside2' in sys.modules\n\n\ndef _implcairo():\n import matplotlib.backends.backend_qt5cairo # noqa\n import sys\n\n assert 'PyQt6' not in sys.modules\n assert 'pyside6' not in sys.modules\n assert 'PyQt5' in sys.modules or 'pyside2' in sys.modules\n\n\ndef _implcore():\n import matplotlib.backends.backend_qt5 # noqa\n import sys\n\n assert 'PyQt6' not in sys.modules\n assert 'pyside6' not in sys.modules\n assert 'PyQt5' in sys.modules or 'pyside2' in sys.modules\n\n\ndef test_qt5backends_uses_qt5():\n qt5_bindings = [\n dep for dep in ['PyQt5', 'pyside2']\n if importlib.util.find_spec(dep) is not None\n ]\n qt6_bindings = [\n dep for dep in ['PyQt6', 'pyside6']\n if importlib.util.find_spec(dep) is not None\n ]\n if len(qt5_bindings) == 0 or len(qt6_bindings) == 0:\n pytest.skip('need both QT6 and QT5 bindings')\n _run_helper(_implqt5agg, timeout=_test_timeout)\n if importlib.util.find_spec('pycairo') is not None:\n _run_helper(_implcairo, timeout=_test_timeout)\n _run_helper(_implcore, timeout=_test_timeout)\n\n\ndef _impl_missing():\n import sys\n # Simulate uninstalled\n sys.modules["PyQt6"] = None\n sys.modules["PyQt5"] = None\n sys.modules["PySide2"] = None\n sys.modules["PySide6"] = None\n\n import matplotlib.pyplot as plt\n with pytest.raises(ImportError, match="Failed to import any of the following Qt"):\n plt.switch_backend("qtagg")\n # Specifically ensure that Pyside6/Pyqt6 are not in the error message for qt5agg\n with pytest.raises(ImportError, match="^(?:(?!(PySide6|PyQt6)).)*$"):\n plt.switch_backend("qt5agg")\n\n\ndef test_qt_missing():\n _run_helper(_impl_missing, timeout=_test_timeout)\n\n\ndef _impl_test_cross_Qt_imports():\n import importlib\n import sys\n import warnings\n\n _, host_binding, mpl_binding = sys.argv\n # import the mpl binding. This will force us to use that binding\n importlib.import_module(f'{mpl_binding}.QtCore')\n mpl_binding_qwidgets = importlib.import_module(f'{mpl_binding}.QtWidgets')\n import matplotlib.backends.backend_qt\n host_qwidgets = importlib.import_module(f'{host_binding}.QtWidgets')\n\n host_app = host_qwidgets.QApplication(["mpl testing"])\n warnings.filterwarnings("error", message=r".*Mixing Qt major.*",\n category=UserWarning)\n matplotlib.backends.backend_qt._create_qApp()\n\n\ndef qt5_and_qt6_pairs():\n qt5_bindings = [\n dep for dep in ['PyQt5', 'PySide2']\n if importlib.util.find_spec(dep) is not None\n ]\n qt6_bindings = [\n dep for dep in ['PyQt6', 'PySide6']\n if importlib.util.find_spec(dep) is not None\n ]\n if len(qt5_bindings) == 0 or len(qt6_bindings) == 0:\n yield pytest.param(None, None,\n marks=[pytest.mark.skip('need both QT6 and QT5 bindings')])\n return\n\n for qt5 in qt5_bindings:\n for qt6 in qt6_bindings:\n yield from ([qt5, qt6], [qt6, qt5])\n\n\n@pytest.mark.skipif(\n sys.platform == "linux" and not _c_internal_utils.display_is_valid(),\n reason="$DISPLAY and $WAYLAND_DISPLAY are unset")\n@pytest.mark.parametrize('host, mpl', [*qt5_and_qt6_pairs()])\ndef test_cross_Qt_imports(host, mpl):\n try:\n proc = _run_helper(_impl_test_cross_Qt_imports, host, mpl,\n timeout=_test_timeout)\n except subprocess.CalledProcessError as ex:\n # We do try to warn the user they are doing something that we do not\n # expect to work, so we're going to ignore if the subprocess crashes or\n # is killed, and just check that the warning is printed.\n stderr = ex.stderr\n else:\n stderr = proc.stderr\n assert "Mixing Qt major versions may not work as expected." in stderr\n\n\n@pytest.mark.skipif('TF_BUILD' in os.environ,\n reason="this test fails an azure for unknown reasons")\n@pytest.mark.skipif(sys.platform == "win32", reason="Cannot send SIGINT on Windows.")\ndef test_webagg():\n pytest.importorskip("tornado")\n proc = subprocess.Popen(\n [sys.executable, "-c",\n inspect.getsource(_test_interactive_impl)\n + "\n_test_interactive_impl()", "{}"],\n env={**os.environ, "MPLBACKEND": "webagg", "SOURCE_DATE_EPOCH": "0"})\n url = f'http://{mpl.rcParams["webagg.address"]}:{mpl.rcParams["webagg.port"]}'\n timeout = time.perf_counter() + _test_timeout\n try:\n while True:\n try:\n retcode = proc.poll()\n # check that the subprocess for the server is not dead\n assert retcode is None\n conn = urllib.request.urlopen(url)\n break\n except urllib.error.URLError:\n if time.perf_counter() > timeout:\n pytest.fail("Failed to connect to the webagg server.")\n else:\n continue\n conn.close()\n proc.send_signal(signal.SIGINT)\n assert proc.wait(timeout=_test_timeout) == 0\n finally:\n if proc.poll() is None:\n proc.kill()\n\n\ndef _lazy_headless():\n import os\n import sys\n\n backend, deps = sys.argv[1:]\n deps = deps.split(',')\n\n # make it look headless\n os.environ.pop('DISPLAY', None)\n os.environ.pop('WAYLAND_DISPLAY', None)\n for dep in deps:\n assert dep not in sys.modules\n\n # we should fast-track to Agg\n import matplotlib.pyplot as plt\n assert plt.get_backend() == 'agg'\n for dep in deps:\n assert dep not in sys.modules\n\n # make sure we really have dependencies installed\n for dep in deps:\n importlib.import_module(dep)\n assert dep in sys.modules\n\n # try to switch and make sure we fail with ImportError\n try:\n plt.switch_backend(backend)\n except ImportError:\n pass\n else:\n sys.exit(1)\n\n\n@pytest.mark.skipif(sys.platform != "linux", reason="this a linux-only test")\n@pytest.mark.parametrize("env", _get_testable_interactive_backends())\ndef test_lazy_linux_headless(env):\n proc = _run_helper(\n _lazy_headless,\n env.pop('MPLBACKEND'), env.pop("BACKEND_DEPS"),\n timeout=_test_timeout,\n extra_env={**env, 'DISPLAY': '', 'WAYLAND_DISPLAY': ''}\n )\n\n\ndef _test_number_of_draws_script():\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n\n # animated=True tells matplotlib to only draw the artist when we\n # explicitly request it\n ln, = ax.plot([0, 1], [1, 2], animated=True)\n\n # make sure the window is raised, but the script keeps going\n plt.show(block=False)\n plt.pause(0.3)\n # Connect to draw_event to count the occurrences\n fig.canvas.mpl_connect('draw_event', print)\n\n # get copy of entire figure (everything inside fig.bbox)\n # sans animated artist\n bg = fig.canvas.copy_from_bbox(fig.bbox)\n # draw the animated artist, this uses a cached renderer\n ax.draw_artist(ln)\n # show the result to the screen\n fig.canvas.blit(fig.bbox)\n\n for j in range(10):\n # reset the background back in the canvas state, screen unchanged\n fig.canvas.restore_region(bg)\n # Create a **new** artist here, this is poor usage of blitting\n # but good for testing to make sure that this doesn't create\n # excessive draws\n ln, = ax.plot([0, 1], [1, 2])\n # render the artist, updating the canvas state, but not the screen\n ax.draw_artist(ln)\n # copy the image to the GUI state, but screen might not changed yet\n fig.canvas.blit(fig.bbox)\n # flush any pending GUI events, re-painting the screen if needed\n fig.canvas.flush_events()\n\n # Let the event loop process everything before leaving\n plt.pause(0.1)\n\n\n_blit_backends = _get_testable_interactive_backends()\nfor param in _blit_backends:\n backend = param.values[0]["MPLBACKEND"]\n if backend == "gtk3cairo":\n # copy_from_bbox only works when rendering to an ImageSurface\n param.marks.append(\n pytest.mark.skip("gtk3cairo does not support blitting"))\n elif backend == "gtk4cairo":\n # copy_from_bbox only works when rendering to an ImageSurface\n param.marks.append(\n pytest.mark.skip("gtk4cairo does not support blitting"))\n elif backend == "wx":\n param.marks.append(\n pytest.mark.skip("wx does not support blitting"))\n elif (backend == 'tkagg' and\n ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and\n sys.platform == 'darwin' and\n sys.version_info[:2] < (3, 11)\n ):\n param.marks.append( # https://github.com/actions/setup-python/issues/649\n pytest.mark.xfail('Tk version mismatch on Azure macOS CI')\n )\n\n\n@pytest.mark.parametrize("env", _blit_backends)\n# subprocesses can struggle to get the display, so rerun a few times\n@pytest.mark.flaky(reruns=4)\ndef test_blitting_events(env):\n proc = _run_helper(\n _test_number_of_draws_script, timeout=_test_timeout, extra_env=env)\n # Count the number of draw_events we got. We could count some initial\n # canvas draws (which vary in number by backend), but the critical\n # check here is that it isn't 10 draws, which would be called if\n # blitting is not properly implemented\n ndraws = proc.stdout.count("DrawEvent")\n assert 0 < ndraws < 5\n\n\ndef _impl_test_interactive_timers():\n # A timer with <1 millisecond gets converted to int and therefore 0\n # milliseconds, which the mac framework interprets as singleshot.\n # We only want singleshot if we specify that ourselves, otherwise we want\n # a repeating timer\n import os\n from unittest.mock import Mock\n import matplotlib.pyplot as plt\n # increase pause duration on CI to let things spin up\n # particularly relevant for gtk3cairo\n pause_time = 2 if os.getenv("CI") else 0.5\n fig = plt.figure()\n plt.pause(pause_time)\n timer = fig.canvas.new_timer(0.1)\n mock = Mock()\n timer.add_callback(mock)\n timer.start()\n plt.pause(pause_time)\n timer.stop()\n assert mock.call_count > 1\n\n # Now turn it into a single shot timer and verify only one gets triggered\n mock.call_count = 0\n timer.single_shot = True\n timer.start()\n plt.pause(pause_time)\n assert mock.call_count == 1\n\n # Make sure we can start the timer a second time\n timer.start()\n plt.pause(pause_time)\n assert mock.call_count == 2\n plt.close("all")\n\n\n@pytest.mark.parametrize("env", _get_testable_interactive_backends())\ndef test_interactive_timers(env):\n if env["MPLBACKEND"] == "gtk3cairo" and os.getenv("CI"):\n pytest.skip("gtk3cairo timers do not work in remote CI")\n if env["MPLBACKEND"] == "wx":\n pytest.skip("wx backend is deprecated; tests failed on appveyor")\n _run_helper(_impl_test_interactive_timers,\n timeout=_test_timeout, extra_env=env)\n\n\ndef _test_sigint_impl(backend, target_name, kwargs):\n import sys\n import matplotlib.pyplot as plt\n import os\n import threading\n\n plt.switch_backend(backend)\n\n def interrupter():\n if sys.platform == 'win32':\n import win32api\n win32api.GenerateConsoleCtrlEvent(0, 0)\n else:\n import signal\n os.kill(os.getpid(), signal.SIGINT)\n\n target = getattr(plt, target_name)\n timer = threading.Timer(1, interrupter)\n fig = plt.figure()\n fig.canvas.mpl_connect(\n 'draw_event',\n lambda *args: print('DRAW', flush=True)\n )\n fig.canvas.mpl_connect(\n 'draw_event',\n lambda *args: timer.start()\n )\n try:\n target(**kwargs)\n except KeyboardInterrupt:\n print('SUCCESS', flush=True)\n\n\n@pytest.mark.parametrize("env", _get_testable_interactive_backends())\n@pytest.mark.parametrize("target, kwargs", [\n ('show', {'block': True}),\n ('pause', {'interval': 10})\n])\ndef test_sigint(env, target, kwargs):\n backend = env.get("MPLBACKEND")\n if not backend.startswith(("qt", "macosx")):\n pytest.skip("SIGINT currently only tested on qt and macosx")\n proc = _WaitForStringPopen(\n [sys.executable, "-c",\n inspect.getsource(_test_sigint_impl) +\n f"\n_test_sigint_impl({backend!r}, {target!r}, {kwargs!r})"])\n try:\n proc.wait_for('DRAW')\n stdout, _ = proc.communicate(timeout=_test_timeout)\n except Exception:\n proc.kill()\n stdout, _ = proc.communicate()\n raise\n assert 'SUCCESS' in stdout\n\n\ndef _test_other_signal_before_sigint_impl(backend, target_name, kwargs):\n import signal\n import matplotlib.pyplot as plt\n\n plt.switch_backend(backend)\n\n target = getattr(plt, target_name)\n\n fig = plt.figure()\n fig.canvas.mpl_connect('draw_event', lambda *args: print('DRAW', flush=True))\n\n timer = fig.canvas.new_timer(interval=1)\n timer.single_shot = True\n timer.add_callback(print, 'SIGUSR1', flush=True)\n\n def custom_signal_handler(signum, frame):\n timer.start()\n signal.signal(signal.SIGUSR1, custom_signal_handler)\n\n try:\n target(**kwargs)\n except KeyboardInterrupt:\n print('SUCCESS', flush=True)\n\n\n@pytest.mark.skipif(sys.platform == 'win32',\n reason='No other signal available to send on Windows')\n@pytest.mark.parametrize("env", _get_testable_interactive_backends())\n@pytest.mark.parametrize("target, kwargs", [\n ('show', {'block': True}),\n ('pause', {'interval': 10})\n])\ndef test_other_signal_before_sigint(env, target, kwargs, request):\n backend = env.get("MPLBACKEND")\n if not backend.startswith(("qt", "macosx")):\n pytest.skip("SIGINT currently only tested on qt and macosx")\n if backend == "macosx":\n request.node.add_marker(pytest.mark.xfail(reason="macosx backend is buggy"))\n if sys.platform == "darwin" and target == "show":\n # We've not previously had these toolkits installed on CI, and so were never\n # aware that this was crashing. However, we've had little luck reproducing it\n # locally, so mark it xfail for now. For more information, see\n # https://github.com/matplotlib/matplotlib/issues/27984\n request.node.add_marker(\n pytest.mark.xfail(reason="Qt backend is buggy on macOS"))\n proc = _WaitForStringPopen(\n [sys.executable, "-c",\n inspect.getsource(_test_other_signal_before_sigint_impl) +\n "\n_test_other_signal_before_sigint_impl("\n f"{backend!r}, {target!r}, {kwargs!r})"])\n try:\n proc.wait_for('DRAW')\n os.kill(proc.pid, signal.SIGUSR1)\n proc.wait_for('SIGUSR1')\n os.kill(proc.pid, signal.SIGINT)\n stdout, _ = proc.communicate(timeout=_test_timeout)\n except Exception:\n proc.kill()\n stdout, _ = proc.communicate()\n raise\n print(stdout)\n assert 'SUCCESS' in stdout\n | .venv\Lib\site-packages\matplotlib\tests\test_backends_interactive.py | test_backends_interactive.py | Python | 29,020 | 0.95 | 0.163728 | 0.137725 | node-utils | 696 | 2024-02-04T12:39:16.636191 | MIT | true | e49e04f3b0dc1a68672b3d397ef51a2f |
import importlib\n\nfrom matplotlib import path, transforms\nfrom matplotlib.backend_bases import (\n FigureCanvasBase, KeyEvent, LocationEvent, MouseButton, MouseEvent,\n NavigationToolbar2, RendererBase)\nfrom matplotlib.backend_tools import RubberbandBase\nfrom matplotlib.figure import Figure\nfrom matplotlib.testing._markers import needs_pgf_xelatex\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport pytest\n\n\n_EXPECTED_WARNING_TOOLMANAGER = (\n r"Treat the new Tool classes introduced in "\n r"v[0-9]*.[0-9]* as experimental for now; "\n "the API and rcParam may change in future versions.")\n\n\ndef test_uses_per_path():\n id = transforms.Affine2D()\n paths = [path.Path.unit_regular_polygon(i) for i in range(3, 7)]\n tforms_matrices = [id.rotate(i).get_matrix().copy() for i in range(1, 5)]\n offsets = np.arange(20).reshape((10, 2))\n facecolors = ['red', 'green']\n edgecolors = ['red', 'green']\n\n def check(master_transform, paths, all_transforms,\n offsets, facecolors, edgecolors):\n rb = RendererBase()\n raw_paths = list(rb._iter_collection_raw_paths(\n master_transform, paths, all_transforms))\n gc = rb.new_gc()\n ids = [path_id for xo, yo, path_id, gc0, rgbFace in\n rb._iter_collection(\n gc, range(len(raw_paths)), offsets,\n transforms.AffineDeltaTransform(master_transform),\n facecolors, edgecolors, [], [], [False],\n [], 'screen')]\n uses = rb._iter_collection_uses_per_path(\n paths, all_transforms, offsets, facecolors, edgecolors)\n if raw_paths:\n seen = np.bincount(ids, minlength=len(raw_paths))\n assert set(seen).issubset([uses - 1, uses])\n\n check(id, paths, tforms_matrices, offsets, facecolors, edgecolors)\n check(id, paths[0:1], tforms_matrices, offsets, facecolors, edgecolors)\n check(id, [], tforms_matrices, offsets, facecolors, edgecolors)\n check(id, paths, tforms_matrices[0:1], offsets, facecolors, edgecolors)\n check(id, paths, [], offsets, facecolors, edgecolors)\n for n in range(0, offsets.shape[0]):\n check(id, paths, tforms_matrices, offsets[0:n, :],\n facecolors, edgecolors)\n check(id, paths, tforms_matrices, offsets, [], edgecolors)\n check(id, paths, tforms_matrices, offsets, facecolors, [])\n check(id, paths, tforms_matrices, offsets, [], [])\n check(id, paths, tforms_matrices, offsets, facecolors[0:1], edgecolors)\n\n\ndef test_canvas_ctor():\n assert isinstance(FigureCanvasBase().figure, Figure)\n\n\ndef test_get_default_filename():\n fig = plt.figure()\n assert fig.canvas.get_default_filename() == "Figure_1.png"\n fig.canvas.manager.set_window_title("0:1/2<3")\n assert fig.canvas.get_default_filename() == "0_1_2_3.png"\n\n\ndef test_canvas_change():\n fig = plt.figure()\n # Replaces fig.canvas\n canvas = FigureCanvasBase(fig)\n # Should still work.\n plt.close(fig)\n assert not plt.fignum_exists(fig.number)\n\n\n@pytest.mark.backend('pdf')\ndef test_non_gui_warning(monkeypatch):\n plt.subplots()\n\n monkeypatch.setenv("DISPLAY", ":999")\n\n with pytest.warns(UserWarning) as rec:\n plt.show()\n assert len(rec) == 1\n assert ('FigureCanvasPdf is non-interactive, and thus cannot be shown'\n in str(rec[0].message))\n\n with pytest.warns(UserWarning) as rec:\n plt.gcf().show()\n assert len(rec) == 1\n assert ('FigureCanvasPdf is non-interactive, and thus cannot be shown'\n in str(rec[0].message))\n\n\ndef test_grab_clear():\n fig, ax = plt.subplots()\n\n fig.canvas.grab_mouse(ax)\n assert fig.canvas.mouse_grabber == ax\n\n fig.clear()\n assert fig.canvas.mouse_grabber is None\n\n\n@pytest.mark.parametrize(\n "x, y", [(42, 24), (None, 42), (None, None), (200, 100.01), (205.75, 2.0)])\ndef test_location_event_position(x, y):\n # LocationEvent should cast its x and y arguments to int unless it is None.\n fig, ax = plt.subplots()\n canvas = FigureCanvasBase(fig)\n event = LocationEvent("test_event", canvas, x, y)\n if x is None:\n assert event.x is None\n else:\n assert event.x == int(x)\n assert isinstance(event.x, int)\n if y is None:\n assert event.y is None\n else:\n assert event.y == int(y)\n assert isinstance(event.y, int)\n if x is not None and y is not None:\n assert (ax.format_coord(x, y)\n == f"(x, y) = ({ax.format_xdata(x)}, {ax.format_ydata(y)})")\n ax.fmt_xdata = ax.fmt_ydata = lambda x: "foo"\n assert ax.format_coord(x, y) == "(x, y) = (foo, foo)"\n\n\ndef test_location_event_position_twin():\n fig, ax = plt.subplots()\n ax.set(xlim=(0, 10), ylim=(0, 20))\n assert ax.format_coord(5., 5.) == "(x, y) = (5.00, 5.00)"\n ax.twinx().set(ylim=(0, 40))\n assert ax.format_coord(5., 5.) == "(x, y) = (5.00, 5.00) | (5.00, 10.0)"\n ax.twiny().set(xlim=(0, 5))\n assert (ax.format_coord(5., 5.)\n == "(x, y) = (5.00, 5.00) | (5.00, 10.0) | (2.50, 5.00)")\n\n\ndef test_pick():\n fig = plt.figure()\n fig.text(.5, .5, "hello", ha="center", va="center", picker=True)\n fig.canvas.draw()\n\n picks = []\n def handle_pick(event):\n assert event.mouseevent.key == "a"\n picks.append(event)\n fig.canvas.mpl_connect("pick_event", handle_pick)\n\n KeyEvent("key_press_event", fig.canvas, "a")._process()\n MouseEvent("button_press_event", fig.canvas,\n *fig.transFigure.transform((.5, .5)),\n MouseButton.LEFT)._process()\n KeyEvent("key_release_event", fig.canvas, "a")._process()\n assert len(picks) == 1\n\n\ndef test_interactive_zoom():\n fig, ax = plt.subplots()\n ax.set(xscale="logit")\n assert ax.get_navigate_mode() is None\n\n tb = NavigationToolbar2(fig.canvas)\n tb.zoom()\n assert ax.get_navigate_mode() == 'ZOOM'\n\n xlim0 = ax.get_xlim()\n ylim0 = ax.get_ylim()\n\n # Zoom from x=1e-6, y=0.1 to x=1-1e-5, 0.8 (data coordinates, "d").\n d0 = (1e-6, 0.1)\n d1 = (1-1e-5, 0.8)\n # Convert to screen coordinates ("s"). Events are defined only with pixel\n # precision, so round the pixel values, and below, check against the\n # corresponding xdata/ydata, which are close but not equal to d0/d1.\n s0 = ax.transData.transform(d0).astype(int)\n s1 = ax.transData.transform(d1).astype(int)\n\n # Zoom in.\n start_event = MouseEvent(\n "button_press_event", fig.canvas, *s0, MouseButton.LEFT)\n fig.canvas.callbacks.process(start_event.name, start_event)\n stop_event = MouseEvent(\n "button_release_event", fig.canvas, *s1, MouseButton.LEFT)\n fig.canvas.callbacks.process(stop_event.name, stop_event)\n assert ax.get_xlim() == (start_event.xdata, stop_event.xdata)\n assert ax.get_ylim() == (start_event.ydata, stop_event.ydata)\n\n # Zoom out.\n start_event = MouseEvent(\n "button_press_event", fig.canvas, *s1, MouseButton.RIGHT)\n fig.canvas.callbacks.process(start_event.name, start_event)\n stop_event = MouseEvent(\n "button_release_event", fig.canvas, *s0, MouseButton.RIGHT)\n fig.canvas.callbacks.process(stop_event.name, stop_event)\n # Absolute tolerance much less than original xmin (1e-7).\n assert ax.get_xlim() == pytest.approx(xlim0, rel=0, abs=1e-10)\n assert ax.get_ylim() == pytest.approx(ylim0, rel=0, abs=1e-10)\n\n tb.zoom()\n assert ax.get_navigate_mode() is None\n\n assert not ax.get_autoscalex_on() and not ax.get_autoscaley_on()\n\n\ndef test_widgetlock_zoompan():\n fig, ax = plt.subplots()\n ax.plot([0, 1], [0, 1])\n fig.canvas.widgetlock(ax)\n tb = NavigationToolbar2(fig.canvas)\n tb.zoom()\n assert ax.get_navigate_mode() is None\n tb.pan()\n assert ax.get_navigate_mode() is None\n\n\n@pytest.mark.parametrize("plot_func", ["imshow", "contourf"])\n@pytest.mark.parametrize("orientation", ["vertical", "horizontal"])\n@pytest.mark.parametrize("tool,button,expected",\n [("zoom", MouseButton.LEFT, (4, 6)), # zoom in\n ("zoom", MouseButton.RIGHT, (-20, 30)), # zoom out\n ("pan", MouseButton.LEFT, (-2, 8)),\n ("pan", MouseButton.RIGHT, (1.47, 7.78))]) # zoom\ndef test_interactive_colorbar(plot_func, orientation, tool, button, expected):\n fig, ax = plt.subplots()\n data = np.arange(12).reshape((4, 3))\n vmin0, vmax0 = 0, 10\n coll = getattr(ax, plot_func)(data, vmin=vmin0, vmax=vmax0)\n\n cb = fig.colorbar(coll, ax=ax, orientation=orientation)\n if plot_func == "contourf":\n # Just determine we can't navigate and exit out of the test\n assert not cb.ax.get_navigate()\n return\n\n assert cb.ax.get_navigate()\n\n # Mouse from 4 to 6 (data coordinates, "d").\n vmin, vmax = 4, 6\n # The y coordinate doesn't matter, it just needs to be between 0 and 1\n # However, we will set d0/d1 to the same y coordinate to test that small\n # pixel changes in that coordinate doesn't cancel the zoom like a normal\n # axes would.\n d0 = (vmin, 0.5)\n d1 = (vmax, 0.5)\n # Swap them if the orientation is vertical\n if orientation == "vertical":\n d0 = d0[::-1]\n d1 = d1[::-1]\n # Convert to screen coordinates ("s"). Events are defined only with pixel\n # precision, so round the pixel values, and below, check against the\n # corresponding xdata/ydata, which are close but not equal to d0/d1.\n s0 = cb.ax.transData.transform(d0).astype(int)\n s1 = cb.ax.transData.transform(d1).astype(int)\n\n # Set up the mouse movements\n start_event = MouseEvent(\n "button_press_event", fig.canvas, *s0, button)\n stop_event = MouseEvent(\n "button_release_event", fig.canvas, *s1, button)\n\n tb = NavigationToolbar2(fig.canvas)\n if tool == "zoom":\n tb.zoom()\n tb.press_zoom(start_event)\n tb.drag_zoom(stop_event)\n tb.release_zoom(stop_event)\n else:\n tb.pan()\n tb.press_pan(start_event)\n tb.drag_pan(stop_event)\n tb.release_pan(stop_event)\n\n # Should be close, but won't be exact due to screen integer resolution\n assert (cb.vmin, cb.vmax) == pytest.approx(expected, abs=0.15)\n\n\ndef test_toolbar_zoompan():\n with pytest.warns(UserWarning, match=_EXPECTED_WARNING_TOOLMANAGER):\n plt.rcParams['toolbar'] = 'toolmanager'\n ax = plt.gca()\n fig = ax.get_figure()\n assert ax.get_navigate_mode() is None\n fig.canvas.manager.toolmanager.trigger_tool('zoom')\n assert ax.get_navigate_mode() == "ZOOM"\n fig.canvas.manager.toolmanager.trigger_tool('pan')\n assert ax.get_navigate_mode() == "PAN"\n\n\ndef test_toolbar_home_restores_autoscale():\n fig, ax = plt.subplots()\n ax.plot(range(11), range(11))\n\n tb = NavigationToolbar2(fig.canvas)\n tb.zoom()\n\n # Switch to log.\n KeyEvent("key_press_event", fig.canvas, "k", 100, 100)._process()\n KeyEvent("key_press_event", fig.canvas, "l", 100, 100)._process()\n assert ax.get_xlim() == ax.get_ylim() == (1, 10) # Autolimits excluding 0.\n # Switch back to linear.\n KeyEvent("key_press_event", fig.canvas, "k", 100, 100)._process()\n KeyEvent("key_press_event", fig.canvas, "l", 100, 100)._process()\n assert ax.get_xlim() == ax.get_ylim() == (0, 10) # Autolimits.\n\n # Zoom in from (x, y) = (2, 2) to (5, 5).\n start, stop = ax.transData.transform([(2, 2), (5, 5)])\n MouseEvent("button_press_event", fig.canvas, *start, MouseButton.LEFT)._process()\n MouseEvent("button_release_event", fig.canvas, *stop, MouseButton.LEFT)._process()\n # Go back to home.\n KeyEvent("key_press_event", fig.canvas, "h")._process()\n\n assert ax.get_xlim() == ax.get_ylim() == (0, 10)\n # Switch to log.\n KeyEvent("key_press_event", fig.canvas, "k", 100, 100)._process()\n KeyEvent("key_press_event", fig.canvas, "l", 100, 100)._process()\n assert ax.get_xlim() == ax.get_ylim() == (1, 10) # Autolimits excluding 0.\n\n\n@pytest.mark.parametrize(\n "backend", ['svg', 'ps', 'pdf',\n pytest.param('pgf', marks=needs_pgf_xelatex)]\n)\ndef test_draw(backend):\n from matplotlib.figure import Figure\n from matplotlib.backends.backend_agg import FigureCanvas\n test_backend = importlib.import_module(f'matplotlib.backends.backend_{backend}')\n TestCanvas = test_backend.FigureCanvas\n fig_test = Figure(constrained_layout=True)\n TestCanvas(fig_test)\n axes_test = fig_test.subplots(2, 2)\n\n # defaults to FigureCanvasBase\n fig_agg = Figure(constrained_layout=True)\n # put a backends.backend_agg.FigureCanvas on it\n FigureCanvas(fig_agg)\n axes_agg = fig_agg.subplots(2, 2)\n\n init_pos = [ax.get_position() for ax in axes_test.ravel()]\n\n fig_test.canvas.draw()\n fig_agg.canvas.draw()\n\n layed_out_pos_test = [ax.get_position() for ax in axes_test.ravel()]\n layed_out_pos_agg = [ax.get_position() for ax in axes_agg.ravel()]\n\n for init, placed in zip(init_pos, layed_out_pos_test):\n assert not np.allclose(init, placed, atol=0.005)\n\n for ref, test in zip(layed_out_pos_agg, layed_out_pos_test):\n np.testing.assert_allclose(ref, test, atol=0.005)\n\n\n@pytest.mark.parametrize(\n "key,mouseend,expectedxlim,expectedylim",\n [(None, (0.2, 0.2), (3.49, 12.49), (2.7, 11.7)),\n (None, (0.2, 0.5), (3.49, 12.49), (0, 9)),\n (None, (0.5, 0.2), (0, 9), (2.7, 11.7)),\n (None, (0.5, 0.5), (0, 9), (0, 9)), # No move\n (None, (0.8, 0.25), (-3.47, 5.53), (2.25, 11.25)),\n (None, (0.2, 0.25), (3.49, 12.49), (2.25, 11.25)),\n (None, (0.8, 0.85), (-3.47, 5.53), (-3.14, 5.86)),\n (None, (0.2, 0.85), (3.49, 12.49), (-3.14, 5.86)),\n ("shift", (0.2, 0.4), (3.49, 12.49), (0, 9)), # snap to x\n ("shift", (0.4, 0.2), (0, 9), (2.7, 11.7)), # snap to y\n ("shift", (0.2, 0.25), (3.49, 12.49), (3.49, 12.49)), # snap to diagonal\n ("shift", (0.8, 0.25), (-3.47, 5.53), (3.47, 12.47)), # snap to diagonal\n ("shift", (0.8, 0.9), (-3.58, 5.41), (-3.58, 5.41)), # snap to diagonal\n ("shift", (0.2, 0.85), (3.49, 12.49), (-3.49, 5.51)), # snap to diagonal\n ("x", (0.2, 0.1), (3.49, 12.49), (0, 9)), # only x\n ("y", (0.1, 0.2), (0, 9), (2.7, 11.7)), # only y\n ("control", (0.2, 0.2), (3.49, 12.49), (3.49, 12.49)), # diagonal\n ("control", (0.4, 0.2), (2.72, 11.72), (2.72, 11.72)), # diagonal\n ])\ndef test_interactive_pan(key, mouseend, expectedxlim, expectedylim):\n fig, ax = plt.subplots()\n ax.plot(np.arange(10))\n assert ax.get_navigate()\n # Set equal aspect ratio to easier see diagonal snap\n ax.set_aspect('equal')\n\n # Mouse move starts from 0.5, 0.5\n mousestart = (0.5, 0.5)\n # Convert to screen coordinates ("s"). Events are defined only with pixel\n # precision, so round the pixel values, and below, check against the\n # corresponding xdata/ydata, which are close but not equal to d0/d1.\n sstart = ax.transData.transform(mousestart).astype(int)\n send = ax.transData.transform(mouseend).astype(int)\n\n # Set up the mouse movements\n start_event = MouseEvent(\n "button_press_event", fig.canvas, *sstart, button=MouseButton.LEFT,\n key=key)\n stop_event = MouseEvent(\n "button_release_event", fig.canvas, *send, button=MouseButton.LEFT,\n key=key)\n\n tb = NavigationToolbar2(fig.canvas)\n tb.pan()\n tb.press_pan(start_event)\n tb.drag_pan(stop_event)\n tb.release_pan(stop_event)\n # Should be close, but won't be exact due to screen integer resolution\n assert tuple(ax.get_xlim()) == pytest.approx(expectedxlim, abs=0.02)\n assert tuple(ax.get_ylim()) == pytest.approx(expectedylim, abs=0.02)\n\n\ndef test_toolmanager_remove():\n with pytest.warns(UserWarning, match=_EXPECTED_WARNING_TOOLMANAGER):\n plt.rcParams['toolbar'] = 'toolmanager'\n fig = plt.gcf()\n initial_len = len(fig.canvas.manager.toolmanager.tools)\n assert 'forward' in fig.canvas.manager.toolmanager.tools\n fig.canvas.manager.toolmanager.remove_tool('forward')\n assert len(fig.canvas.manager.toolmanager.tools) == initial_len - 1\n assert 'forward' not in fig.canvas.manager.toolmanager.tools\n\n\ndef test_toolmanager_get_tool():\n with pytest.warns(UserWarning, match=_EXPECTED_WARNING_TOOLMANAGER):\n plt.rcParams['toolbar'] = 'toolmanager'\n fig = plt.gcf()\n rubberband = fig.canvas.manager.toolmanager.get_tool('rubberband')\n assert isinstance(rubberband, RubberbandBase)\n assert fig.canvas.manager.toolmanager.get_tool(rubberband) is rubberband\n with pytest.warns(UserWarning,\n match="ToolManager does not control tool 'foo'"):\n assert fig.canvas.manager.toolmanager.get_tool('foo') is None\n assert fig.canvas.manager.toolmanager.get_tool('foo', warn=False) is None\n\n with pytest.warns(UserWarning,\n match="ToolManager does not control tool 'foo'"):\n assert fig.canvas.manager.toolmanager.trigger_tool('foo') is None\n\n\ndef test_toolmanager_update_keymap():\n with pytest.warns(UserWarning, match=_EXPECTED_WARNING_TOOLMANAGER):\n plt.rcParams['toolbar'] = 'toolmanager'\n fig = plt.gcf()\n assert 'v' in fig.canvas.manager.toolmanager.get_tool_keymap('forward')\n with pytest.warns(UserWarning,\n match="Key c changed from back to forward"):\n fig.canvas.manager.toolmanager.update_keymap('forward', 'c')\n assert fig.canvas.manager.toolmanager.get_tool_keymap('forward') == ['c']\n with pytest.raises(KeyError, match="'foo' not in Tools"):\n fig.canvas.manager.toolmanager.update_keymap('foo', 'c')\n\n\n@pytest.mark.parametrize("tool", ["zoom", "pan"])\n@pytest.mark.parametrize("button", [MouseButton.LEFT, MouseButton.RIGHT])\n@pytest.mark.parametrize("patch_vis", [True, False])\n@pytest.mark.parametrize("forward_nav", [True, False, "auto"])\n@pytest.mark.parametrize("t_s", ["twin", "share"])\ndef test_interactive_pan_zoom_events(tool, button, patch_vis, forward_nav, t_s):\n # Bottom axes: ax_b Top axes: ax_t\n fig, ax_b = plt.subplots()\n ax_t = fig.add_subplot(221, zorder=99)\n ax_t.set_forward_navigation_events(forward_nav)\n ax_t.patch.set_visible(patch_vis)\n\n # ----------------------------\n if t_s == "share":\n ax_t_twin = fig.add_subplot(222)\n ax_t_twin.sharex(ax_t)\n ax_t_twin.sharey(ax_t)\n\n ax_b_twin = fig.add_subplot(223)\n ax_b_twin.sharex(ax_b)\n ax_b_twin.sharey(ax_b)\n elif t_s == "twin":\n ax_t_twin = ax_t.twinx()\n ax_b_twin = ax_b.twinx()\n\n # just some styling to simplify manual checks\n ax_t.set_label("ax_t")\n ax_t.patch.set_facecolor((1, 0, 0, 0.5))\n\n ax_t_twin.set_label("ax_t_twin")\n ax_t_twin.patch.set_facecolor("r")\n\n ax_b.set_label("ax_b")\n ax_b.patch.set_facecolor((0, 0, 1, 0.5))\n\n ax_b_twin.set_label("ax_b_twin")\n ax_b_twin.patch.set_facecolor("b")\n\n # ----------------------------\n\n # Set initial axis limits\n init_xlim, init_ylim = (0, 10), (0, 10)\n for ax in [ax_t, ax_b]:\n ax.set_xlim(*init_xlim)\n ax.set_ylim(*init_ylim)\n\n # Mouse from 2 to 1 (in data-coordinates of ax_t).\n xstart_t, xstop_t, ystart_t, ystop_t = 1, 2, 1, 2\n # Convert to screen coordinates ("s"). Events are defined only with pixel\n # precision, so round the pixel values, and below, check against the\n # corresponding xdata/ydata, which are close but not equal to s0/s1.\n s0 = ax_t.transData.transform((xstart_t, ystart_t)).astype(int)\n s1 = ax_t.transData.transform((xstop_t, ystop_t)).astype(int)\n\n # Calculate the mouse-distance in data-coordinates of the bottom-axes\n xstart_b, ystart_b = ax_b.transData.inverted().transform(s0)\n xstop_b, ystop_b = ax_b.transData.inverted().transform(s1)\n\n # Set up the mouse movements\n start_event = MouseEvent("button_press_event", fig.canvas, *s0, button)\n stop_event = MouseEvent("button_release_event", fig.canvas, *s1, button)\n\n tb = NavigationToolbar2(fig.canvas)\n\n if tool == "zoom":\n # Evaluate expected limits before executing the zoom-event\n direction = ("in" if button == 1 else "out")\n\n xlim_t, ylim_t = ax_t._prepare_view_from_bbox([*s0, *s1], direction)\n\n if ax_t.get_forward_navigation_events() is True:\n xlim_b, ylim_b = ax_b._prepare_view_from_bbox([*s0, *s1], direction)\n elif ax_t.get_forward_navigation_events() is False:\n xlim_b = init_xlim\n ylim_b = init_ylim\n else:\n if not ax_t.patch.get_visible():\n xlim_b, ylim_b = ax_b._prepare_view_from_bbox([*s0, *s1], direction)\n else:\n xlim_b = init_xlim\n ylim_b = init_ylim\n\n tb.zoom()\n tb.press_zoom(start_event)\n tb.drag_zoom(stop_event)\n tb.release_zoom(stop_event)\n\n assert ax_t.get_xlim() == pytest.approx(xlim_t, abs=0.15)\n assert ax_t.get_ylim() == pytest.approx(ylim_t, abs=0.15)\n assert ax_b.get_xlim() == pytest.approx(xlim_b, abs=0.15)\n assert ax_b.get_ylim() == pytest.approx(ylim_b, abs=0.15)\n\n # Check if twin-axes are properly triggered\n assert ax_t.get_xlim() == pytest.approx(ax_t_twin.get_xlim(), abs=0.15)\n assert ax_b.get_xlim() == pytest.approx(ax_b_twin.get_xlim(), abs=0.15)\n else:\n # Evaluate expected limits\n # (call start_pan to make sure ax._pan_start is set)\n ax_t.start_pan(*s0, button)\n xlim_t, ylim_t = ax_t._get_pan_points(button, None, *s1).T.astype(float)\n ax_t.end_pan()\n\n if ax_t.get_forward_navigation_events() is True:\n ax_b.start_pan(*s0, button)\n xlim_b, ylim_b = ax_b._get_pan_points(button, None, *s1).T.astype(float)\n ax_b.end_pan()\n elif ax_t.get_forward_navigation_events() is False:\n xlim_b = init_xlim\n ylim_b = init_ylim\n else:\n if not ax_t.patch.get_visible():\n ax_b.start_pan(*s0, button)\n xlim_b, ylim_b = ax_b._get_pan_points(button, None, *s1).T.astype(float)\n ax_b.end_pan()\n else:\n xlim_b = init_xlim\n ylim_b = init_ylim\n\n tb.pan()\n tb.press_pan(start_event)\n tb.drag_pan(stop_event)\n tb.release_pan(stop_event)\n\n assert ax_t.get_xlim() == pytest.approx(xlim_t, abs=0.15)\n assert ax_t.get_ylim() == pytest.approx(ylim_t, abs=0.15)\n assert ax_b.get_xlim() == pytest.approx(xlim_b, abs=0.15)\n assert ax_b.get_ylim() == pytest.approx(ylim_b, abs=0.15)\n\n # Check if twin-axes are properly triggered\n assert ax_t.get_xlim() == pytest.approx(ax_t_twin.get_xlim(), abs=0.15)\n assert ax_b.get_xlim() == pytest.approx(ax_b_twin.get_xlim(), abs=0.15)\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_bases.py | test_backend_bases.py | Python | 22,775 | 0.95 | 0.085324 | 0.109504 | node-utils | 201 | 2023-10-31T00:18:15.716239 | GPL-3.0 | true | 8b60125226adc452161d6703485b5b00 |
import numpy as np\n\nimport pytest\n\nfrom matplotlib.testing.decorators import check_figures_equal\nfrom matplotlib import (\n collections as mcollections, patches as mpatches, path as mpath)\n\n\n@pytest.mark.backend('cairo')\n@check_figures_equal(extensions=["png"])\ndef test_patch_alpha_coloring(fig_test, fig_ref):\n """\n Test checks that the patch and collection are rendered with the specified\n alpha values in their facecolor and edgecolor.\n """\n star = mpath.Path.unit_regular_star(6)\n circle = mpath.Path.unit_circle()\n # concatenate the star with an internal cutout of the circle\n verts = np.concatenate([circle.vertices, star.vertices[::-1]])\n codes = np.concatenate([circle.codes, star.codes])\n cut_star1 = mpath.Path(verts, codes)\n cut_star2 = mpath.Path(verts + 1, codes)\n\n # Reference: two separate patches\n ax = fig_ref.subplots()\n ax.set_xlim([-1, 2])\n ax.set_ylim([-1, 2])\n patch = mpatches.PathPatch(cut_star1,\n linewidth=5, linestyle='dashdot',\n facecolor=(1, 0, 0, 0.5),\n edgecolor=(0, 0, 1, 0.75))\n ax.add_patch(patch)\n patch = mpatches.PathPatch(cut_star2,\n linewidth=5, linestyle='dashdot',\n facecolor=(1, 0, 0, 0.5),\n edgecolor=(0, 0, 1, 0.75))\n ax.add_patch(patch)\n\n # Test: path collection\n ax = fig_test.subplots()\n ax.set_xlim([-1, 2])\n ax.set_ylim([-1, 2])\n col = mcollections.PathCollection([cut_star1, cut_star2],\n linewidth=5, linestyles='dashdot',\n facecolor=(1, 0, 0, 0.5),\n edgecolor=(0, 0, 1, 0.75))\n ax.add_collection(col)\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_cairo.py | test_backend_cairo.py | Python | 1,821 | 0.95 | 0.020833 | 0.071429 | react-lib | 125 | 2024-10-23T04:22:06.772829 | MIT | true | ca675356d566c6a0bffc305ea346c09c |
import os\nfrom matplotlib import pyplot as plt\n\nimport pytest\nfrom unittest import mock\n\n\n@pytest.mark.backend("gtk3agg", skip_on_importerror=True)\ndef test_correct_key():\n pytest.xfail("test_widget_send_event is not triggering key_press_event")\n\n from gi.repository import Gdk, Gtk # type: ignore[import]\n fig = plt.figure()\n buf = []\n\n def send(event):\n for key, mod in [\n (Gdk.KEY_a, Gdk.ModifierType.SHIFT_MASK),\n (Gdk.KEY_a, 0),\n (Gdk.KEY_a, Gdk.ModifierType.CONTROL_MASK),\n (Gdk.KEY_agrave, 0),\n (Gdk.KEY_Control_L, Gdk.ModifierType.MOD1_MASK),\n (Gdk.KEY_Alt_L, Gdk.ModifierType.CONTROL_MASK),\n (Gdk.KEY_agrave,\n Gdk.ModifierType.CONTROL_MASK\n | Gdk.ModifierType.MOD1_MASK\n | Gdk.ModifierType.MOD4_MASK),\n (0xfd16, 0), # KEY_3270_Play.\n (Gdk.KEY_BackSpace, 0),\n (Gdk.KEY_BackSpace, Gdk.ModifierType.CONTROL_MASK),\n ]:\n # This is not actually really the right API: it depends on the\n # actual keymap (e.g. on Azerty, shift+agrave -> 0).\n Gtk.test_widget_send_key(fig.canvas, key, mod)\n\n def receive(event):\n buf.append(event.key)\n if buf == [\n "A", "a", "ctrl+a",\n "\N{LATIN SMALL LETTER A WITH GRAVE}",\n "alt+control", "ctrl+alt",\n "ctrl+alt+super+\N{LATIN SMALL LETTER A WITH GRAVE}",\n # (No entry for KEY_3270_Play.)\n "backspace", "ctrl+backspace",\n ]:\n plt.close(fig)\n\n fig.canvas.mpl_connect("draw_event", send)\n fig.canvas.mpl_connect("key_press_event", receive)\n plt.show()\n\n\n@pytest.mark.backend("gtk3agg", skip_on_importerror=True)\ndef test_save_figure_return():\n from gi.repository import Gtk\n fig, ax = plt.subplots()\n ax.imshow([[1]])\n with mock.patch("gi.repository.Gtk.FileFilter") as fileFilter:\n filt = fileFilter.return_value\n filt.get_name.return_value = "Portable Network Graphics"\n with mock.patch("gi.repository.Gtk.FileChooserDialog") as dialogChooser:\n dialog = dialogChooser.return_value\n dialog.get_filter.return_value = filt\n dialog.get_filename.return_value = "foobar.png"\n dialog.run.return_value = Gtk.ResponseType.OK\n fname = fig.canvas.manager.toolbar.save_figure()\n os.remove("foobar.png")\n assert fname == "foobar.png"\n\n with mock.patch("gi.repository.Gtk.MessageDialog"):\n dialog.get_filename.return_value = None\n dialog.run.return_value = Gtk.ResponseType.OK\n fname = fig.canvas.manager.toolbar.save_figure()\n assert fname is None\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_gtk3.py | test_backend_gtk3.py | Python | 2,849 | 0.95 | 0.094595 | 0.046875 | awesome-app | 821 | 2025-05-17T20:37:13.996335 | GPL-3.0 | true | 414238f202a04bb7f310fa55544e62e9 |
import os\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nimport pytest\n\nfrom matplotlib.testing import subprocess_run_for_testing\n\nnbformat = pytest.importorskip('nbformat')\npytest.importorskip('nbconvert')\npytest.importorskip('ipykernel')\npytest.importorskip('matplotlib_inline')\n\n\ndef test_ipynb():\n nb_path = Path(__file__).parent / 'test_inline_01.ipynb'\n\n with TemporaryDirectory() as tmpdir:\n out_path = Path(tmpdir, "out.ipynb")\n\n subprocess_run_for_testing(\n ["jupyter", "nbconvert", "--to", "notebook",\n "--execute", "--ExecutePreprocessor.timeout=500",\n "--output", str(out_path), str(nb_path)],\n env={**os.environ, "IPYTHONDIR": tmpdir},\n check=True)\n with out_path.open() as out:\n nb = nbformat.read(out, nbformat.current_nbformat)\n\n errors = [output for cell in nb.cells for output in cell.get("outputs", [])\n if output.output_type == "error"]\n assert not errors\n\n import IPython\n if IPython.version_info[:2] >= (8, 24):\n expected_backend = "inline"\n else:\n # This code can be removed when Python 3.12, the latest version supported by\n # IPython < 8.24, reaches end-of-life in late 2028.\n expected_backend = "module://matplotlib_inline.backend_inline"\n backend_outputs = nb.cells[2]["outputs"]\n assert backend_outputs[0]["data"]["text/plain"] == f"'{expected_backend}'"\n\n image = nb.cells[1]["outputs"][1]["data"]\n assert image["text/plain"] == "<Figure size 300x200 with 1 Axes>"\n assert "image/png" in image\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_inline.py | test_backend_inline.py | Python | 1,608 | 0.95 | 0.108696 | 0.055556 | node-utils | 405 | 2024-01-14T01:04:34.504291 | MIT | true | 4cf5d4140a7a00626362a9e04bb5462a |
import os\n\nimport pytest\nfrom unittest import mock\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\ntry:\n from matplotlib.backends import _macosx\nexcept ImportError:\n pytest.skip("These are mac only tests", allow_module_level=True)\n\n\n@pytest.mark.backend('macosx')\ndef test_cached_renderer():\n # Make sure that figures have an associated renderer after\n # a fig.canvas.draw() call\n fig = plt.figure(1)\n fig.canvas.draw()\n assert fig.canvas.get_renderer()._renderer is not None\n\n fig = plt.figure(2)\n fig.draw_without_rendering()\n assert fig.canvas.get_renderer()._renderer is not None\n\n\n@pytest.mark.backend('macosx')\ndef test_savefig_rcparam(monkeypatch, tmp_path):\n\n def new_choose_save_file(title, directory, filename):\n # Replacement function instead of opening a GUI window\n # Make a new directory for testing the update of the rcParams\n assert directory == str(tmp_path)\n os.makedirs(f"{directory}/test")\n return f"{directory}/test/{filename}"\n\n monkeypatch.setattr(_macosx, "choose_save_file", new_choose_save_file)\n fig = plt.figure()\n with mpl.rc_context({"savefig.directory": tmp_path}):\n fig.canvas.toolbar.save_figure()\n # Check the saved location got created\n save_file = f"{tmp_path}/test/{fig.canvas.get_default_filename()}"\n assert os.path.exists(save_file)\n\n # Check the savefig.directory rcParam got updated because\n # we added a subdirectory "test"\n assert mpl.rcParams["savefig.directory"] == f"{tmp_path}/test"\n\n\n@pytest.mark.backend('macosx')\ndef test_ipython():\n from matplotlib.testing import ipython_in_subprocess\n ipython_in_subprocess("osx", {(8, 24): "macosx", (7, 0): "MacOSX"})\n\n\n@pytest.mark.backend('macosx')\ndef test_save_figure_return():\n fig, ax = plt.subplots()\n ax.imshow([[1]])\n prop = "matplotlib.backends._macosx.choose_save_file"\n with mock.patch(prop, return_value="foobar.png"):\n fname = fig.canvas.manager.toolbar.save_figure()\n os.remove("foobar.png")\n assert fname == "foobar.png"\n with mock.patch(prop, return_value=None):\n fname = fig.canvas.manager.toolbar.save_figure()\n assert fname is None\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_macosx.py | test_backend_macosx.py | Python | 2,233 | 0.95 | 0.119403 | 0.132075 | node-utils | 846 | 2024-04-05T17:52:50.502073 | BSD-3-Clause | true | 2e56e48ff2ed92cc4b7a488bd03d3f75 |
import os\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nimport pytest\n\nfrom matplotlib.testing import subprocess_run_for_testing\n\nnbformat = pytest.importorskip('nbformat')\npytest.importorskip('nbconvert')\npytest.importorskip('ipykernel')\n\n# From https://blog.thedataincubator.com/2016/06/testing-jupyter-notebooks/\n\n\ndef test_ipynb():\n nb_path = Path(__file__).parent / 'test_nbagg_01.ipynb'\n\n with TemporaryDirectory() as tmpdir:\n out_path = Path(tmpdir, "out.ipynb")\n subprocess_run_for_testing(\n ["jupyter", "nbconvert", "--to", "notebook",\n "--execute", "--ExecutePreprocessor.timeout=500",\n "--output", str(out_path), str(nb_path)],\n env={**os.environ, "IPYTHONDIR": tmpdir},\n check=True)\n with out_path.open() as out:\n nb = nbformat.read(out, nbformat.current_nbformat)\n\n errors = [output for cell in nb.cells for output in cell.get("outputs", [])\n if output.output_type == "error"]\n assert not errors\n\n import IPython\n if IPython.version_info[:2] >= (8, 24):\n expected_backend = "notebook"\n else:\n # This code can be removed when Python 3.12, the latest version supported by\n # IPython < 8.24, reaches end-of-life in late 2028.\n expected_backend = "nbAgg"\n backend_outputs = nb.cells[2]["outputs"]\n assert backend_outputs[0]["data"]["text/plain"] == f"'{expected_backend}'"\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_nbagg.py | test_backend_nbagg.py | Python | 1,459 | 0.95 | 0.119048 | 0.090909 | vue-tools | 936 | 2024-08-28T06:33:07.954561 | Apache-2.0 | true | 2989463af6664d3fece8b60e1dd2db35 |
import datetime\nimport decimal\nimport io\nimport os\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib import (\n pyplot as plt, rcParams, font_manager as fm\n)\nfrom matplotlib.cbook import _get_data_path\nfrom matplotlib.ft2font import FT2Font\nfrom matplotlib.font_manager import findfont, FontProperties\nfrom matplotlib.backends._backend_pdf_ps import get_glyphs_subset, font_as_file\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nfrom matplotlib.testing._markers import needs_usetex\n\n\n@image_comparison(['pdf_use14corefonts.pdf'])\ndef test_use14corefonts():\n rcParams['pdf.use14corefonts'] = True\n rcParams['font.family'] = 'sans-serif'\n rcParams['font.size'] = 8\n rcParams['font.sans-serif'] = ['Helvetica']\n rcParams['pdf.compression'] = 0\n\n text = '''A three-line text positioned just above a blue line\nand containing some French characters and the euro symbol:\n"Merci pépé pour les 10 €"'''\n\n fig, ax = plt.subplots()\n ax.set_title('Test PDF backend with option use14corefonts=True')\n ax.text(0.5, 0.5, text, horizontalalignment='center',\n verticalalignment='bottom',\n fontsize=14)\n ax.axhline(0.5, linewidth=0.5)\n\n\n@pytest.mark.parametrize('fontname, fontfile', [\n ('DejaVu Sans', 'DejaVuSans.ttf'),\n ('WenQuanYi Zen Hei', 'wqy-zenhei.ttc'),\n])\n@pytest.mark.parametrize('fonttype', [3, 42])\ndef test_embed_fonts(fontname, fontfile, fonttype):\n if Path(findfont(FontProperties(family=[fontname]))).name != fontfile:\n pytest.skip(f'Font {fontname!r} may be missing')\n\n rcParams['pdf.fonttype'] = fonttype\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3])\n ax.set_title('Axes Title', font=fontname)\n fig.savefig(io.BytesIO(), format='pdf')\n\n\ndef test_multipage_pagecount():\n with PdfPages(io.BytesIO()) as pdf:\n assert pdf.get_pagecount() == 0\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3])\n fig.savefig(pdf, format="pdf")\n assert pdf.get_pagecount() == 1\n pdf.savefig()\n assert pdf.get_pagecount() == 2\n\n\ndef test_multipage_properfinalize():\n pdfio = io.BytesIO()\n with PdfPages(pdfio) as pdf:\n for i in range(10):\n fig, ax = plt.subplots()\n ax.set_title('This is a long title')\n fig.savefig(pdf, format="pdf")\n s = pdfio.getvalue()\n assert s.count(b'startxref') == 1\n assert len(s) < 40000\n\n\ndef test_multipage_keep_empty(tmp_path):\n # An empty pdf deletes itself afterwards.\n fn = tmp_path / "a.pdf"\n with PdfPages(fn) as pdf:\n pass\n assert not fn.exists()\n\n # Test pdf files with content, they should never be deleted.\n fn = tmp_path / "b.pdf"\n with PdfPages(fn) as pdf:\n pdf.savefig(plt.figure())\n assert fn.exists()\n\n\ndef test_composite_image():\n # Test that figures can be saved with and without combining multiple images\n # (on a single set of axes) into a single composite image.\n X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))\n Z = np.sin(Y ** 2)\n fig, ax = plt.subplots()\n ax.set_xlim(0, 3)\n ax.imshow(Z, extent=[0, 1, 0, 1])\n ax.imshow(Z[::-1], extent=[2, 3, 0, 1])\n plt.rcParams['image.composite_image'] = True\n with PdfPages(io.BytesIO()) as pdf:\n fig.savefig(pdf, format="pdf")\n assert len(pdf._file._images) == 1\n plt.rcParams['image.composite_image'] = False\n with PdfPages(io.BytesIO()) as pdf:\n fig.savefig(pdf, format="pdf")\n assert len(pdf._file._images) == 2\n\n\ndef test_indexed_image():\n # An image with low color count should compress to a palette-indexed format.\n pikepdf = pytest.importorskip('pikepdf')\n\n data = np.zeros((256, 1, 3), dtype=np.uint8)\n data[:, 0, 0] = np.arange(256) # Maximum unique colours for an indexed image.\n\n rcParams['pdf.compression'] = True\n fig = plt.figure()\n fig.figimage(data, resize=True)\n buf = io.BytesIO()\n fig.savefig(buf, format='pdf', dpi='figure')\n\n with pikepdf.Pdf.open(buf) as pdf:\n page, = pdf.pages\n image, = page.images.values()\n pdf_image = pikepdf.PdfImage(image)\n assert pdf_image.indexed\n pil_image = pdf_image.as_pil_image()\n rgb = np.asarray(pil_image.convert('RGB'))\n\n np.testing.assert_array_equal(data, rgb)\n\n\ndef test_savefig_metadata(monkeypatch):\n pikepdf = pytest.importorskip('pikepdf')\n monkeypatch.setenv('SOURCE_DATE_EPOCH', '0')\n\n fig, ax = plt.subplots()\n ax.plot(range(5))\n\n md = {\n 'Author': 'me',\n 'Title': 'Multipage PDF',\n 'Subject': 'Test page',\n 'Keywords': 'test,pdf,multipage',\n 'ModDate': datetime.datetime(\n 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))),\n 'Trapped': 'True'\n }\n buf = io.BytesIO()\n fig.savefig(buf, metadata=md, format='pdf')\n\n with pikepdf.Pdf.open(buf) as pdf:\n info = {k: str(v) for k, v in pdf.docinfo.items()}\n\n assert info == {\n '/Author': 'me',\n '/CreationDate': 'D:19700101000000Z',\n '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org',\n '/Keywords': 'test,pdf,multipage',\n '/ModDate': 'D:19680801000000Z',\n '/Producer': f'Matplotlib pdf backend v{mpl.__version__}',\n '/Subject': 'Test page',\n '/Title': 'Multipage PDF',\n '/Trapped': '/True',\n }\n\n\ndef test_invalid_metadata():\n fig, ax = plt.subplots()\n\n with pytest.warns(UserWarning,\n match="Unknown infodict keyword: 'foobar'."):\n fig.savefig(io.BytesIO(), format='pdf', metadata={'foobar': 'invalid'})\n\n with pytest.warns(UserWarning,\n match='not an instance of datetime.datetime.'):\n fig.savefig(io.BytesIO(), format='pdf',\n metadata={'ModDate': '1968-08-01'})\n\n with pytest.warns(UserWarning,\n match='not one of {"True", "False", "Unknown"}'):\n fig.savefig(io.BytesIO(), format='pdf', metadata={'Trapped': 'foo'})\n\n with pytest.warns(UserWarning, match='not an instance of str.'):\n fig.savefig(io.BytesIO(), format='pdf', metadata={'Title': 1234})\n\n\ndef test_multipage_metadata(monkeypatch):\n pikepdf = pytest.importorskip('pikepdf')\n monkeypatch.setenv('SOURCE_DATE_EPOCH', '0')\n\n fig, ax = plt.subplots()\n ax.plot(range(5))\n\n md = {\n 'Author': 'me',\n 'Title': 'Multipage PDF',\n 'Subject': 'Test page',\n 'Keywords': 'test,pdf,multipage',\n 'ModDate': datetime.datetime(\n 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))),\n 'Trapped': 'True'\n }\n buf = io.BytesIO()\n with PdfPages(buf, metadata=md) as pdf:\n pdf.savefig(fig)\n pdf.savefig(fig)\n\n with pikepdf.Pdf.open(buf) as pdf:\n info = {k: str(v) for k, v in pdf.docinfo.items()}\n\n assert info == {\n '/Author': 'me',\n '/CreationDate': 'D:19700101000000Z',\n '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org',\n '/Keywords': 'test,pdf,multipage',\n '/ModDate': 'D:19680801000000Z',\n '/Producer': f'Matplotlib pdf backend v{mpl.__version__}',\n '/Subject': 'Test page',\n '/Title': 'Multipage PDF',\n '/Trapped': '/True',\n }\n\n\ndef test_text_urls():\n pikepdf = pytest.importorskip('pikepdf')\n\n test_url = 'https://test_text_urls.matplotlib.org/'\n\n fig = plt.figure(figsize=(2, 1))\n fig.text(0.1, 0.1, 'test plain 123', url=f'{test_url}plain')\n fig.text(0.1, 0.4, 'test mathtext $123$', url=f'{test_url}mathtext')\n\n with io.BytesIO() as fd:\n fig.savefig(fd, format='pdf')\n\n with pikepdf.Pdf.open(fd) as pdf:\n annots = pdf.pages[0].Annots\n\n # Iteration over Annots must occur within the context manager,\n # otherwise it may fail depending on the pdf structure.\n for y, fragment in [('0.1', 'plain'), ('0.4', 'mathtext')]:\n annot = next(\n (a for a in annots if a.A.URI == f'{test_url}{fragment}'),\n None)\n assert annot is not None\n assert getattr(annot, 'QuadPoints', None) is None\n # Positions in points (72 per inch.)\n assert annot.Rect[1] == decimal.Decimal(y) * 72\n\n\ndef test_text_rotated_urls():\n pikepdf = pytest.importorskip('pikepdf')\n\n test_url = 'https://test_text_urls.matplotlib.org/'\n\n fig = plt.figure(figsize=(1, 1))\n fig.text(0.1, 0.1, 'N', rotation=45, url=f'{test_url}')\n\n with io.BytesIO() as fd:\n fig.savefig(fd, format='pdf')\n\n with pikepdf.Pdf.open(fd) as pdf:\n annots = pdf.pages[0].Annots\n\n # Iteration over Annots must occur within the context manager,\n # otherwise it may fail depending on the pdf structure.\n annot = next(\n (a for a in annots if a.A.URI == f'{test_url}'),\n None)\n assert annot is not None\n assert getattr(annot, 'QuadPoints', None) is not None\n # Positions in points (72 per inch)\n assert annot.Rect[0] == \\n annot.QuadPoints[6] - decimal.Decimal('0.00001')\n\n\n@needs_usetex\ndef test_text_urls_tex():\n pikepdf = pytest.importorskip('pikepdf')\n\n test_url = 'https://test_text_urls.matplotlib.org/'\n\n fig = plt.figure(figsize=(2, 1))\n fig.text(0.1, 0.7, 'test tex $123$', usetex=True, url=f'{test_url}tex')\n\n with io.BytesIO() as fd:\n fig.savefig(fd, format='pdf')\n\n with pikepdf.Pdf.open(fd) as pdf:\n annots = pdf.pages[0].Annots\n\n # Iteration over Annots must occur within the context manager,\n # otherwise it may fail depending on the pdf structure.\n annot = next(\n (a for a in annots if a.A.URI == f'{test_url}tex'),\n None)\n assert annot is not None\n # Positions in points (72 per inch.)\n assert annot.Rect[1] == decimal.Decimal('0.7') * 72\n\n\ndef test_pdfpages_fspath():\n with PdfPages(Path(os.devnull)) as pdf:\n pdf.savefig(plt.figure())\n\n\n@image_comparison(['hatching_legend.pdf'])\ndef test_hatching_legend():\n """Test for correct hatching on patches in legend"""\n fig = plt.figure(figsize=(1, 2))\n\n a = Rectangle([0, 0], 0, 0, facecolor="green", hatch="XXXX")\n b = Rectangle([0, 0], 0, 0, facecolor="blue", hatch="XXXX")\n\n fig.legend([a, b, a, b], ["", "", "", ""])\n\n\n@image_comparison(['grayscale_alpha.pdf'])\ndef test_grayscale_alpha():\n """Masking images with NaN did not work for grayscale images"""\n x, y = np.ogrid[-2:2:.1, -2:2:.1]\n dd = np.exp(-(x**2 + y**2))\n dd[dd < .1] = np.nan\n fig, ax = plt.subplots()\n ax.imshow(dd, interpolation='none', cmap='gray_r')\n ax.set_xticks([])\n ax.set_yticks([])\n\n\n@mpl.style.context('default')\n@check_figures_equal(extensions=["pdf", "eps"])\ndef test_pdf_eps_savefig_when_color_is_none(fig_test, fig_ref):\n ax_test = fig_test.add_subplot()\n ax_test.set_axis_off()\n ax_test.plot(np.sin(np.linspace(-5, 5, 100)), "v", c="none")\n ax_ref = fig_ref.add_subplot()\n ax_ref.set_axis_off()\n\n\n@needs_usetex\ndef test_failing_latex():\n """Test failing latex subprocess call"""\n plt.xlabel("$22_2_2$", usetex=True) # This fails with "Double subscript"\n with pytest.raises(RuntimeError):\n plt.savefig(io.BytesIO(), format="pdf")\n\n\ndef test_empty_rasterized():\n # Check that empty figures that are rasterised save to pdf files fine\n fig, ax = plt.subplots()\n ax.plot([], [], rasterized=True)\n fig.savefig(io.BytesIO(), format="pdf")\n\n\n@image_comparison(['kerning.pdf'])\ndef test_kerning():\n fig = plt.figure()\n s = "AVAVAVAVAVAVAVAV€AAVV"\n fig.text(0, .25, s, size=5)\n fig.text(0, .75, s, size=20)\n\n\ndef test_glyphs_subset():\n fpath = str(_get_data_path("fonts/ttf/DejaVuSerif.ttf"))\n chars = "these should be subsetted! 1234567890"\n\n # non-subsetted FT2Font\n nosubfont = FT2Font(fpath)\n nosubfont.set_text(chars)\n\n # subsetted FT2Font\n with get_glyphs_subset(fpath, chars) as subset:\n subfont = FT2Font(font_as_file(subset))\n subfont.set_text(chars)\n\n nosubcmap = nosubfont.get_charmap()\n subcmap = subfont.get_charmap()\n\n # all unique chars must be available in subsetted font\n assert {*chars} == {chr(key) for key in subcmap}\n\n # subsetted font's charmap should have less entries\n assert len(subcmap) < len(nosubcmap)\n\n # since both objects are assigned same characters\n assert subfont.get_num_glyphs() == nosubfont.get_num_glyphs()\n\n\n@image_comparison(["multi_font_type3.pdf"], tol=4.6)\ndef test_multi_font_type3():\n fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font may be missing")\n\n plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)\n plt.rc('pdf', fonttype=3)\n\n fig = plt.figure()\n fig.text(0.15, 0.475, "There are 几个汉字 in between!")\n\n\n@image_comparison(["multi_font_type42.pdf"], tol=2.2)\ndef test_multi_font_type42():\n fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font may be missing")\n\n plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)\n plt.rc('pdf', fonttype=42)\n\n fig = plt.figure()\n fig.text(0.15, 0.475, "There are 几个汉字 in between!")\n\n\n@pytest.mark.parametrize('family_name, file_name',\n [("Noto Sans", "NotoSans-Regular.otf"),\n ("FreeMono", "FreeMono.otf")])\ndef test_otf_font_smoke(family_name, file_name):\n # checks that there's no segfault\n fp = fm.FontProperties(family=[family_name])\n if Path(fm.findfont(fp)).name != file_name:\n pytest.skip(f"Font {family_name} may be missing")\n\n plt.rc('font', family=[family_name], size=27)\n\n fig = plt.figure()\n fig.text(0.15, 0.475, "Привет мир!")\n fig.savefig(io.BytesIO(), format="pdf")\n\n\n@image_comparison(["truetype-conversion.pdf"])\n# mpltest.ttf does not have "l"/"p" glyphs so we get a warning when trying to\n# get the font extents.\ndef test_truetype_conversion(recwarn):\n mpl.rcParams['pdf.fonttype'] = 3\n fig, ax = plt.subplots()\n ax.text(0, 0, "ABCDE",\n font=Path(__file__).with_name("mpltest.ttf"), fontsize=80)\n ax.set_xticks([])\n ax.set_yticks([])\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_pdf.py | test_backend_pdf.py | Python | 14,602 | 0.95 | 0.095982 | 0.066282 | python-kit | 795 | 2023-12-06T00:32:06.354725 | MIT | true | b5354c4ac21675ad8552eb797b76b7c1 |
import datetime\nfrom io import BytesIO\nimport os\nimport shutil\n\nimport numpy as np\nfrom packaging.version import parse as parse_version\nimport pytest\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing import _has_tex_package, _check_for_pgf\nfrom matplotlib.testing.exceptions import ImageComparisonFailure\nfrom matplotlib.testing.compare import compare_images\nfrom matplotlib.backends.backend_pgf import PdfPages\nfrom matplotlib.testing.decorators import (\n _image_directories, check_figures_equal, image_comparison)\nfrom matplotlib.testing._markers import (\n needs_ghostscript, needs_pgf_lualatex, needs_pgf_pdflatex,\n needs_pgf_xelatex)\n\n\nbaseline_dir, result_dir = _image_directories(lambda: 'dummy func')\n\n\ndef compare_figure(fname, savefig_kwargs={}, tol=0):\n actual = os.path.join(result_dir, fname)\n plt.savefig(actual, **savefig_kwargs)\n\n expected = os.path.join(result_dir, "expected_%s" % fname)\n shutil.copyfile(os.path.join(baseline_dir, fname), expected)\n err = compare_images(expected, actual, tol=tol)\n if err:\n raise ImageComparisonFailure(err)\n\n\n@needs_pgf_xelatex\n@needs_ghostscript\n@pytest.mark.backend('pgf')\ndef test_tex_special_chars(tmp_path):\n fig = plt.figure()\n fig.text(.5, .5, "%_^ $a_b^c$")\n buf = BytesIO()\n fig.savefig(buf, format="png", backend="pgf")\n buf.seek(0)\n t = plt.imread(buf)\n assert not (t == 1).all() # The leading "%" didn't eat up everything.\n\n\ndef create_figure():\n plt.figure()\n x = np.linspace(0, 1, 15)\n\n # line plot\n plt.plot(x, x ** 2, "b-")\n\n # marker\n plt.plot(x, 1 - x**2, "g>")\n\n # filled paths and patterns\n plt.fill_between([0., .4], [.4, 0.], hatch='//', facecolor="lightgray",\n edgecolor="red")\n plt.fill([3, 3, .8, .8, 3], [2, -2, -2, 0, 2], "b")\n\n # text and typesetting\n plt.plot([0.9], [0.5], "ro", markersize=3)\n plt.text(0.9, 0.5, 'unicode (ü, °, \N{Section Sign}) and math ($\\mu_i = x_i^2$)',\n ha='right', fontsize=20)\n plt.ylabel('sans-serif, blue, $\\frac{\\sqrt{x}}{y^2}$..',\n family='sans-serif', color='blue')\n plt.text(1, 1, 'should be clipped as default clip_box is Axes bbox',\n fontsize=20, clip_on=True)\n\n plt.xlim(0, 1)\n plt.ylim(0, 1)\n\n\n# test compiling a figure to pdf with xelatex\n@needs_pgf_xelatex\n@pytest.mark.backend('pgf')\n@image_comparison(['pgf_xelatex.pdf'], style='default')\ndef test_xelatex():\n rc_xelatex = {'font.family': 'serif',\n 'pgf.rcfonts': False}\n mpl.rcParams.update(rc_xelatex)\n create_figure()\n\n\ntry:\n _old_gs_version = \\n mpl._get_executable_info('gs').version < parse_version('9.50')\nexcept mpl.ExecutableNotFoundError:\n _old_gs_version = True\n\n\n# test compiling a figure to pdf with pdflatex\n@needs_pgf_pdflatex\n@pytest.mark.skipif(not _has_tex_package('type1ec'), reason='needs type1ec.sty')\n@pytest.mark.skipif(not _has_tex_package('ucs'), reason='needs ucs.sty')\n@pytest.mark.backend('pgf')\n@image_comparison(['pgf_pdflatex.pdf'], style='default',\n tol=11.71 if _old_gs_version else 0)\ndef test_pdflatex():\n rc_pdflatex = {'font.family': 'serif',\n 'pgf.rcfonts': False,\n 'pgf.texsystem': 'pdflatex',\n 'pgf.preamble': ('\\usepackage[utf8x]{inputenc}'\n '\\usepackage[T1]{fontenc}')}\n mpl.rcParams.update(rc_pdflatex)\n create_figure()\n\n\n# test updating the rc parameters for each figure\n@needs_pgf_xelatex\n@needs_pgf_pdflatex\n@mpl.style.context('default')\n@pytest.mark.backend('pgf')\ndef test_rcupdate():\n rc_sets = [{'font.family': 'sans-serif',\n 'font.size': 30,\n 'figure.subplot.left': .2,\n 'lines.markersize': 10,\n 'pgf.rcfonts': False,\n 'pgf.texsystem': 'xelatex'},\n {'font.family': 'monospace',\n 'font.size': 10,\n 'figure.subplot.left': .1,\n 'lines.markersize': 20,\n 'pgf.rcfonts': False,\n 'pgf.texsystem': 'pdflatex',\n 'pgf.preamble': ('\\usepackage[utf8x]{inputenc}'\n '\\usepackage[T1]{fontenc}'\n '\\usepackage{sfmath}')}]\n tol = [0, 13.2] if _old_gs_version else [0, 0]\n for i, rc_set in enumerate(rc_sets):\n with mpl.rc_context(rc_set):\n for substring, pkg in [('sfmath', 'sfmath'), ('utf8x', 'ucs')]:\n if (substring in mpl.rcParams['pgf.preamble']\n and not _has_tex_package(pkg)):\n pytest.skip(f'needs {pkg}.sty')\n create_figure()\n compare_figure(f'pgf_rcupdate{i + 1}.pdf', tol=tol[i])\n\n\n# test backend-side clipping, since large numbers are not supported by TeX\n@needs_pgf_xelatex\n@mpl.style.context('default')\n@pytest.mark.backend('pgf')\ndef test_pathclip():\n np.random.seed(19680801)\n mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False})\n fig, axs = plt.subplots(1, 2)\n\n axs[0].plot([0., 1e100], [0., 1e100])\n axs[0].set_xlim(0, 1)\n axs[0].set_ylim(0, 1)\n\n axs[1].scatter([0, 1], [1, 1])\n axs[1].hist(np.random.normal(size=1000), bins=20, range=[-10, 10])\n axs[1].set_xscale('log')\n\n fig.savefig(BytesIO(), format="pdf") # No image comparison.\n\n\n# test mixed mode rendering\n@needs_pgf_xelatex\n@pytest.mark.backend('pgf')\n@image_comparison(['pgf_mixedmode.pdf'], style='default')\ndef test_mixedmode():\n mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False})\n Y, X = np.ogrid[-1:1:40j, -1:1:40j]\n plt.pcolor(X**2 + Y**2).set_rasterized(True)\n\n\n# test bbox_inches clipping\n@needs_pgf_xelatex\n@mpl.style.context('default')\n@pytest.mark.backend('pgf')\ndef test_bbox_inches():\n mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False})\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax1.plot(range(5))\n ax2.plot(range(5))\n plt.tight_layout()\n bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox},\n tol=0)\n\n\n@mpl.style.context('default')\n@pytest.mark.backend('pgf')\n@pytest.mark.parametrize('system', [\n pytest.param('lualatex', marks=[needs_pgf_lualatex]),\n pytest.param('pdflatex', marks=[needs_pgf_pdflatex]),\n pytest.param('xelatex', marks=[needs_pgf_xelatex]),\n])\ndef test_pdf_pages(system):\n rc_pdflatex = {\n 'font.family': 'serif',\n 'pgf.rcfonts': False,\n 'pgf.texsystem': system,\n }\n mpl.rcParams.update(rc_pdflatex)\n\n fig1, ax1 = plt.subplots()\n ax1.plot(range(5))\n fig1.tight_layout()\n\n fig2, ax2 = plt.subplots(figsize=(3, 2))\n ax2.plot(range(5))\n fig2.tight_layout()\n\n path = os.path.join(result_dir, f'pdfpages_{system}.pdf')\n md = {\n 'Author': 'me',\n 'Title': 'Multipage PDF with pgf',\n 'Subject': 'Test page',\n 'Keywords': 'test,pdf,multipage',\n 'ModDate': datetime.datetime(\n 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))),\n 'Trapped': 'Unknown'\n }\n\n with PdfPages(path, metadata=md) as pdf:\n pdf.savefig(fig1)\n pdf.savefig(fig2)\n pdf.savefig(fig1)\n\n assert pdf.get_pagecount() == 3\n\n\n@mpl.style.context('default')\n@pytest.mark.backend('pgf')\n@pytest.mark.parametrize('system', [\n pytest.param('lualatex', marks=[needs_pgf_lualatex]),\n pytest.param('pdflatex', marks=[needs_pgf_pdflatex]),\n pytest.param('xelatex', marks=[needs_pgf_xelatex]),\n])\ndef test_pdf_pages_metadata_check(monkeypatch, system):\n # Basically the same as test_pdf_pages, but we keep it separate to leave\n # pikepdf as an optional dependency.\n pikepdf = pytest.importorskip('pikepdf')\n monkeypatch.setenv('SOURCE_DATE_EPOCH', '0')\n\n mpl.rcParams.update({'pgf.texsystem': system})\n\n fig, ax = plt.subplots()\n ax.plot(range(5))\n\n md = {\n 'Author': 'me',\n 'Title': 'Multipage PDF with pgf',\n 'Subject': 'Test page',\n 'Keywords': 'test,pdf,multipage',\n 'ModDate': datetime.datetime(\n 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))),\n 'Trapped': 'True'\n }\n path = os.path.join(result_dir, f'pdfpages_meta_check_{system}.pdf')\n with PdfPages(path, metadata=md) as pdf:\n pdf.savefig(fig)\n\n with pikepdf.Pdf.open(path) as pdf:\n info = {k: str(v) for k, v in pdf.docinfo.items()}\n\n # Not set by us, so don't bother checking.\n if '/PTEX.FullBanner' in info:\n del info['/PTEX.FullBanner']\n if '/PTEX.Fullbanner' in info:\n del info['/PTEX.Fullbanner']\n\n # Some LaTeX engines ignore this setting, and state themselves as producer.\n producer = info.pop('/Producer')\n assert producer == f'Matplotlib pgf backend v{mpl.__version__}' or (\n system == 'lualatex' and 'LuaTeX' in producer)\n\n assert info == {\n '/Author': 'me',\n '/CreationDate': 'D:19700101000000Z',\n '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org',\n '/Keywords': 'test,pdf,multipage',\n '/ModDate': 'D:19680801000000Z',\n '/Subject': 'Test page',\n '/Title': 'Multipage PDF with pgf',\n '/Trapped': '/True',\n }\n\n\n@needs_pgf_xelatex\ndef test_multipage_keep_empty(tmp_path):\n # An empty pdf deletes itself afterwards.\n fn = tmp_path / "a.pdf"\n with PdfPages(fn) as pdf:\n pass\n assert not fn.exists()\n\n # Test pdf files with content, they should never be deleted.\n fn = tmp_path / "b.pdf"\n with PdfPages(fn) as pdf:\n pdf.savefig(plt.figure())\n assert fn.exists()\n\n\n@needs_pgf_xelatex\ndef test_tex_restart_after_error():\n fig = plt.figure()\n fig.suptitle(r"\oops")\n with pytest.raises(ValueError):\n fig.savefig(BytesIO(), format="pgf")\n\n fig = plt.figure() # start from scratch\n fig.suptitle(r"this is ok")\n fig.savefig(BytesIO(), format="pgf")\n\n\n@needs_pgf_xelatex\ndef test_bbox_inches_tight():\n fig, ax = plt.subplots()\n ax.imshow([[0, 1], [2, 3]])\n fig.savefig(BytesIO(), format="pdf", backend="pgf", bbox_inches="tight")\n\n\n@needs_pgf_xelatex\n@needs_ghostscript\ndef test_png_transparency(): # Actually, also just testing that png works.\n buf = BytesIO()\n plt.figure().savefig(buf, format="png", backend="pgf", transparent=True)\n buf.seek(0)\n t = plt.imread(buf)\n assert (t[..., 3] == 0).all() # fully transparent.\n\n\n@needs_pgf_xelatex\ndef test_unknown_font(caplog):\n with caplog.at_level("WARNING"):\n mpl.rcParams["font.family"] = "this-font-does-not-exist"\n plt.figtext(.5, .5, "hello, world")\n plt.savefig(BytesIO(), format="pgf")\n assert "Ignoring unknown font: this-font-does-not-exist" in [\n r.getMessage() for r in caplog.records]\n\n\n@check_figures_equal(extensions=["pdf"])\n@pytest.mark.parametrize("texsystem", ("pdflatex", "xelatex", "lualatex"))\n@pytest.mark.backend("pgf")\ndef test_minus_signs_with_tex(fig_test, fig_ref, texsystem):\n if not _check_for_pgf(texsystem):\n pytest.skip(texsystem + ' + pgf is required')\n mpl.rcParams["pgf.texsystem"] = texsystem\n fig_test.text(.5, .5, "$-1$")\n fig_ref.text(.5, .5, "$\N{MINUS SIGN}1$")\n\n\n@pytest.mark.backend("pgf")\ndef test_sketch_params():\n fig, ax = plt.subplots(figsize=(3, 3))\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_frame_on(False)\n handle, = ax.plot([0, 1])\n handle.set_sketch_params(scale=5, length=30, randomness=42)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='pgf')\n buf = fd.getvalue().decode()\n\n baseline = r"""\pgfpathmoveto{\pgfqpoint{0.375000in}{0.300000in}}%\n\pgfpathlineto{\pgfqpoint{2.700000in}{2.700000in}}%\n\usepgfmodule{decorations}%\n\usepgflibrary{decorations.pathmorphing}%\n\pgfkeys{/pgf/decoration/.cd, """ \\n r"""segment length = 0.150000in, amplitude = 0.100000in}%\n\pgfmathsetseed{42}%\n\pgfdecoratecurrentpath{random steps}%\n\pgfusepath{stroke}%"""\n # \pgfdecoratecurrentpath must be after the path definition and before the\n # path is used (\pgfusepath)\n assert baseline in buf\n\n\n# test to make sure that the document font size is set consistently (see #26892)\n@needs_pgf_xelatex\n@pytest.mark.skipif(\n not _has_tex_package('unicode-math'), reason='needs unicode-math.sty'\n)\n@pytest.mark.backend('pgf')\n@image_comparison(['pgf_document_font_size.pdf'], style='default', remove_text=True)\ndef test_document_font_size():\n mpl.rcParams.update({\n 'pgf.texsystem': 'xelatex',\n 'pgf.rcfonts': False,\n 'pgf.preamble': r'\usepackage{unicode-math}',\n })\n plt.figure()\n plt.plot([],\n label=r'$this is a very very very long math label a \times b + 10^{-3}$ '\n r'and some text'\n )\n plt.plot([],\n label=r'\normalsize the document font size is \the\fontdimen6\font'\n )\n plt.legend()\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_pgf.py | test_backend_pgf.py | Python | 13,028 | 0.95 | 0.079602 | 0.057057 | vue-tools | 491 | 2023-10-09T00:47:04.598731 | Apache-2.0 | true | a0e650be6fb28ecf892eb1de60727a67 |
from collections import Counter\nfrom pathlib import Path\nimport io\nimport re\nimport tempfile\n\nimport numpy as np\nimport pytest\n\nfrom matplotlib import cbook, path, patheffects, font_manager as fm\nfrom matplotlib.figure import Figure\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.testing._markers import needs_ghostscript, needs_usetex\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nimport matplotlib as mpl\nimport matplotlib.collections as mcollections\nimport matplotlib.colors as mcolors\nimport matplotlib.pyplot as plt\n\n\n# This tests tends to hit a TeX cache lock on AppVeyor.\n@pytest.mark.flaky(reruns=3)\n@pytest.mark.parametrize('papersize', ['letter', 'figure'])\n@pytest.mark.parametrize('orientation', ['portrait', 'landscape'])\n@pytest.mark.parametrize('format, use_log, rcParams', [\n ('ps', False, {}),\n ('ps', False, {'ps.usedistiller': 'ghostscript'}),\n ('ps', False, {'ps.usedistiller': 'xpdf'}),\n ('ps', False, {'text.usetex': True}),\n ('eps', False, {}),\n ('eps', True, {'ps.useafm': True}),\n ('eps', False, {'text.usetex': True}),\n], ids=[\n 'ps',\n 'ps with distiller=ghostscript',\n 'ps with distiller=xpdf',\n 'ps with usetex',\n 'eps',\n 'eps afm',\n 'eps with usetex'\n])\ndef test_savefig_to_stringio(format, use_log, rcParams, orientation, papersize):\n mpl.rcParams.update(rcParams)\n if mpl.rcParams["ps.usedistiller"] == "ghostscript":\n try:\n mpl._get_executable_info("gs")\n except mpl.ExecutableNotFoundError as exc:\n pytest.skip(str(exc))\n elif mpl.rcParams["ps.usedistiller"] == "xpdf":\n try:\n mpl._get_executable_info("gs") # Effectively checks for ps2pdf.\n mpl._get_executable_info("pdftops")\n except mpl.ExecutableNotFoundError as exc:\n pytest.skip(str(exc))\n\n fig, ax = plt.subplots()\n\n with io.StringIO() as s_buf, io.BytesIO() as b_buf:\n\n if use_log:\n ax.set_yscale('log')\n\n ax.plot([1, 2], [1, 2])\n title = "Déjà vu"\n if not mpl.rcParams["text.usetex"]:\n title += " \N{MINUS SIGN}\N{EURO SIGN}"\n ax.set_title(title)\n allowable_exceptions = []\n if mpl.rcParams["text.usetex"]:\n allowable_exceptions.append(RuntimeError)\n if mpl.rcParams["ps.useafm"]:\n allowable_exceptions.append(mpl.MatplotlibDeprecationWarning)\n try:\n fig.savefig(s_buf, format=format, orientation=orientation,\n papertype=papersize)\n fig.savefig(b_buf, format=format, orientation=orientation,\n papertype=papersize)\n except tuple(allowable_exceptions) as exc:\n pytest.skip(str(exc))\n\n assert not s_buf.closed\n assert not b_buf.closed\n s_val = s_buf.getvalue().encode('ascii')\n b_val = b_buf.getvalue()\n\n if format == 'ps':\n # Default figsize = (8, 6) inches = (576, 432) points = (203.2, 152.4) mm.\n # Landscape orientation will swap dimensions.\n if mpl.rcParams["ps.usedistiller"] == "xpdf":\n # Some versions specifically show letter/203x152, but not all,\n # so we can only use this simpler test.\n if papersize == 'figure':\n assert b'letter' not in s_val.lower()\n else:\n assert b'letter' in s_val.lower()\n elif mpl.rcParams["ps.usedistiller"] or mpl.rcParams["text.usetex"]:\n width = b'432.0' if orientation == 'landscape' else b'576.0'\n wanted = (b'-dDEVICEWIDTHPOINTS=' + width if papersize == 'figure'\n else b'-sPAPERSIZE')\n assert wanted in s_val\n else:\n if papersize == 'figure':\n assert b'%%DocumentPaperSizes' not in s_val\n else:\n assert b'%%DocumentPaperSizes' in s_val\n\n # Strip out CreationDate: ghostscript and cairo don't obey\n # SOURCE_DATE_EPOCH, and that environment variable is already tested in\n # test_determinism.\n s_val = re.sub(b"(?<=\n%%CreationDate: ).*", b"", s_val)\n b_val = re.sub(b"(?<=\n%%CreationDate: ).*", b"", b_val)\n\n assert s_val == b_val.replace(b'\r\n', b'\n')\n\n\ndef test_patheffects():\n mpl.rcParams['path.effects'] = [\n patheffects.withStroke(linewidth=4, foreground='w')]\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3])\n with io.BytesIO() as ps:\n fig.savefig(ps, format='ps')\n\n\n@needs_usetex\n@needs_ghostscript\ndef test_tilde_in_tempfilename(tmp_path):\n # Tilde ~ in the tempdir path (e.g. TMPDIR, TMP or TEMP on windows\n # when the username is very long and windows uses a short name) breaks\n # latex before https://github.com/matplotlib/matplotlib/pull/5928\n base_tempdir = tmp_path / "short-1"\n base_tempdir.mkdir()\n # Change the path for new tempdirs, which is used internally by the ps\n # backend to write a file.\n with cbook._setattr_cm(tempfile, tempdir=str(base_tempdir)):\n # usetex results in the latex call, which does not like the ~\n mpl.rcParams['text.usetex'] = True\n plt.plot([1, 2, 3, 4])\n plt.xlabel(r'\textbf{time} (s)')\n # use the PS backend to write the file...\n plt.savefig(base_tempdir / 'tex_demo.eps', format="ps")\n\n\n@image_comparison(["empty.eps"])\ndef test_transparency():\n fig, ax = plt.subplots()\n ax.set_axis_off()\n ax.plot([0, 1], color="r", alpha=0)\n ax.text(.5, .5, "foo", color="r", alpha=0)\n\n\n@needs_usetex\n@image_comparison(["empty.eps"])\ndef test_transparency_tex():\n mpl.rcParams['text.usetex'] = True\n fig, ax = plt.subplots()\n ax.set_axis_off()\n ax.plot([0, 1], color="r", alpha=0)\n ax.text(.5, .5, "foo", color="r", alpha=0)\n\n\ndef test_bbox():\n fig, ax = plt.subplots()\n with io.BytesIO() as buf:\n fig.savefig(buf, format='eps')\n buf = buf.getvalue()\n\n bb = re.search(b'^%%BoundingBox: (.+) (.+) (.+) (.+)$', buf, re.MULTILINE)\n assert bb\n hibb = re.search(b'^%%HiResBoundingBox: (.+) (.+) (.+) (.+)$', buf,\n re.MULTILINE)\n assert hibb\n\n for i in range(1, 5):\n # BoundingBox must use integers, and be ceil/floor of the hi res.\n assert b'.' not in bb.group(i)\n assert int(bb.group(i)) == pytest.approx(float(hibb.group(i)), 1)\n\n\n@needs_usetex\ndef test_failing_latex():\n """Test failing latex subprocess call"""\n mpl.rcParams['text.usetex'] = True\n # This fails with "Double subscript"\n plt.xlabel("$22_2_2$")\n with pytest.raises(RuntimeError):\n plt.savefig(io.BytesIO(), format="ps")\n\n\n@needs_usetex\ndef test_partial_usetex(caplog):\n caplog.set_level("WARNING")\n plt.figtext(.1, .1, "foo", usetex=True)\n plt.figtext(.2, .2, "bar", usetex=True)\n plt.savefig(io.BytesIO(), format="ps")\n record, = caplog.records # asserts there's a single record.\n assert "as if usetex=False" in record.getMessage()\n\n\n@needs_usetex\ndef test_usetex_preamble(caplog):\n mpl.rcParams.update({\n "text.usetex": True,\n # Check that these don't conflict with the packages loaded by default.\n "text.latex.preamble": r"\usepackage{color,graphicx,textcomp}",\n })\n plt.figtext(.5, .5, "foo")\n plt.savefig(io.BytesIO(), format="ps")\n\n\n@image_comparison(["useafm.eps"])\ndef test_useafm():\n mpl.rcParams["ps.useafm"] = True\n fig, ax = plt.subplots()\n ax.set_axis_off()\n ax.axhline(.5)\n ax.text(.5, .5, "qk")\n\n\n@image_comparison(["type3.eps"])\ndef test_type3_font():\n plt.figtext(.5, .5, "I/J")\n\n\n@image_comparison(["coloredhatcheszerolw.eps"])\ndef test_colored_hatch_zero_linewidth():\n ax = plt.gca()\n ax.add_patch(Ellipse((0, 0), 1, 1, hatch='/', facecolor='none',\n edgecolor='r', linewidth=0))\n ax.add_patch(Ellipse((0.5, 0.5), 0.5, 0.5, hatch='+', facecolor='none',\n edgecolor='g', linewidth=0.2))\n ax.add_patch(Ellipse((1, 1), 0.3, 0.8, hatch='\\', facecolor='none',\n edgecolor='b', linewidth=0))\n ax.set_axis_off()\n\n\n@check_figures_equal(extensions=["eps"])\ndef test_text_clip(fig_test, fig_ref):\n ax = fig_test.add_subplot()\n # Fully clipped-out text should not appear.\n ax.text(0, 0, "hello", transform=fig_test.transFigure, clip_on=True)\n fig_ref.add_subplot()\n\n\n@needs_ghostscript\ndef test_d_glyph(tmp_path):\n # Ensure that we don't have a procedure defined as /d, which would be\n # overwritten by the glyph definition for "d".\n fig = plt.figure()\n fig.text(.5, .5, "def")\n out = tmp_path / "test.eps"\n fig.savefig(out)\n mpl.testing.compare.convert(out, cache=False) # Should not raise.\n\n\n@image_comparison(["type42_without_prep.eps"], style='mpl20')\ndef test_type42_font_without_prep():\n # Test whether Type 42 fonts without prep table are properly embedded\n mpl.rcParams["ps.fonttype"] = 42\n mpl.rcParams["mathtext.fontset"] = "stix"\n\n plt.figtext(0.5, 0.5, "Mass $m$")\n\n\n@pytest.mark.parametrize('fonttype', ["3", "42"])\ndef test_fonttype(fonttype):\n mpl.rcParams["ps.fonttype"] = fonttype\n fig, ax = plt.subplots()\n\n ax.text(0.25, 0.5, "Forty-two is the answer to everything!")\n\n buf = io.BytesIO()\n fig.savefig(buf, format="ps")\n\n test = b'/FontType ' + bytes(f"{fonttype}", encoding='utf-8') + b' def'\n\n assert re.search(test, buf.getvalue(), re.MULTILINE)\n\n\ndef test_linedash():\n """Test that dashed lines do not break PS output"""\n fig, ax = plt.subplots()\n\n ax.plot([0, 1], linestyle="--")\n\n buf = io.BytesIO()\n fig.savefig(buf, format="ps")\n\n assert buf.tell() > 0\n\n\ndef test_empty_line():\n # Smoke-test for gh#23954\n figure = Figure()\n figure.text(0.5, 0.5, "\nfoo\n\n")\n buf = io.BytesIO()\n figure.savefig(buf, format='eps')\n figure.savefig(buf, format='ps')\n\n\ndef test_no_duplicate_definition():\n\n fig = Figure()\n axs = fig.subplots(4, 4, subplot_kw=dict(projection="polar"))\n for ax in axs.flat:\n ax.set(xticks=[], yticks=[])\n ax.plot([1, 2])\n fig.suptitle("hello, world")\n\n buf = io.StringIO()\n fig.savefig(buf, format='eps')\n buf.seek(0)\n\n wds = [ln.partition(' ')[0] for\n ln in buf.readlines()\n if ln.startswith('/')]\n\n assert max(Counter(wds).values()) == 1\n\n\n@image_comparison(["multi_font_type3.eps"], tol=0.51)\ndef test_multi_font_type3():\n fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font may be missing")\n\n plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)\n plt.rc('ps', fonttype=3)\n\n fig = plt.figure()\n fig.text(0.15, 0.475, "There are 几个汉字 in between!")\n\n\n@image_comparison(["multi_font_type42.eps"], tol=1.6)\ndef test_multi_font_type42():\n fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font may be missing")\n\n plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)\n plt.rc('ps', fonttype=42)\n\n fig = plt.figure()\n fig.text(0.15, 0.475, "There are 几个汉字 in between!")\n\n\n@image_comparison(["scatter.eps"])\ndef test_path_collection():\n rng = np.random.default_rng(19680801)\n xvals = rng.uniform(0, 1, 10)\n yvals = rng.uniform(0, 1, 10)\n sizes = rng.uniform(30, 100, 10)\n fig, ax = plt.subplots()\n ax.scatter(xvals, yvals, sizes, edgecolor=[0.9, 0.2, 0.1], marker='<')\n ax.set_axis_off()\n paths = [path.Path.unit_regular_polygon(i) for i in range(3, 7)]\n offsets = rng.uniform(0, 200, 20).reshape(10, 2)\n sizes = [0.02, 0.04]\n pc = mcollections.PathCollection(paths, sizes, zorder=-1,\n facecolors='yellow', offsets=offsets)\n ax.add_collection(pc)\n ax.set_xlim(0, 1)\n\n\n@image_comparison(["colorbar_shift.eps"], savefig_kwarg={"bbox_inches": "tight"},\n style="mpl20")\ndef test_colorbar_shift(tmp_path):\n cmap = mcolors.ListedColormap(["r", "g", "b"])\n norm = mcolors.BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)\n plt.scatter([0, 1], [1, 1], c=[0, 1], cmap=cmap, norm=norm)\n plt.colorbar()\n\n\ndef test_auto_papersize_removal():\n fig = plt.figure()\n with pytest.raises(ValueError, match="'auto' is not a valid value"):\n fig.savefig(io.BytesIO(), format='eps', papertype='auto')\n\n with pytest.raises(ValueError, match="'auto' is not a valid value"):\n mpl.rcParams['ps.papersize'] = 'auto'\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_ps.py | test_backend_ps.py | Python | 12,600 | 0.95 | 0.136842 | 0.075908 | react-lib | 207 | 2024-10-25T21:36:40.932812 | GPL-3.0 | true | 5c20b9abbc9c928c012fb2f6386f6412 |
import copy\nimport importlib\nimport os\nimport signal\nimport sys\n\nfrom datetime import date, datetime\nfrom unittest import mock\n\nimport pytest\n\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib import _c_internal_utils\n\ntry:\n from matplotlib.backends.qt_compat import QtGui # type: ignore[attr-defined] # noqa: E501, F401\n from matplotlib.backends.qt_compat import QtWidgets # type: ignore[attr-defined]\n from matplotlib.backends.qt_editor import _formlayout\nexcept ImportError:\n pytestmark = pytest.mark.skip('No usable Qt bindings')\n\n\n_test_timeout = 60 # A reasonably safe value for slower architectures.\n\n\n@pytest.fixture\ndef qt_core(request):\n from matplotlib.backends.qt_compat import QtCore\n return QtCore\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_fig_close():\n\n # save the state of Gcf.figs\n init_figs = copy.copy(Gcf.figs)\n\n # make a figure using pyplot interface\n fig = plt.figure()\n\n # simulate user clicking the close button by reaching in\n # and calling close on the underlying Qt object\n fig.canvas.manager.window.close()\n\n # assert that we have removed the reference to the FigureManager\n # that got added by plt.figure()\n assert init_figs == Gcf.figs\n\n\n@pytest.mark.parametrize(\n "qt_key, qt_mods, answer",\n [\n ("Key_A", ["ShiftModifier"], "A"),\n ("Key_A", [], "a"),\n ("Key_A", ["ControlModifier"], ("ctrl+a")),\n (\n "Key_Aacute",\n ["ShiftModifier"],\n "\N{LATIN CAPITAL LETTER A WITH ACUTE}",\n ),\n ("Key_Aacute", [], "\N{LATIN SMALL LETTER A WITH ACUTE}"),\n ("Key_Control", ["AltModifier"], ("alt+control")),\n ("Key_Alt", ["ControlModifier"], "ctrl+alt"),\n (\n "Key_Aacute",\n ["ControlModifier", "AltModifier", "MetaModifier"],\n ("ctrl+alt+meta+\N{LATIN SMALL LETTER A WITH ACUTE}"),\n ),\n # We do not currently map the media keys, this may change in the\n # future. This means the callback will never fire\n ("Key_Play", [], None),\n ("Key_Backspace", [], "backspace"),\n (\n "Key_Backspace",\n ["ControlModifier"],\n "ctrl+backspace",\n ),\n ],\n ids=[\n 'shift',\n 'lower',\n 'control',\n 'unicode_upper',\n 'unicode_lower',\n 'alt_control',\n 'control_alt',\n 'modifier_order',\n 'non_unicode_key',\n 'backspace',\n 'backspace_mod',\n ]\n)\n@pytest.mark.parametrize('backend', [\n # Note: the value is irrelevant; the important part is the marker.\n pytest.param(\n 'Qt5Agg',\n marks=pytest.mark.backend('Qt5Agg', skip_on_importerror=True)),\n pytest.param(\n 'QtAgg',\n marks=pytest.mark.backend('QtAgg', skip_on_importerror=True)),\n])\ndef test_correct_key(backend, qt_core, qt_key, qt_mods, answer, monkeypatch):\n """\n Make a figure.\n Send a key_press_event event (using non-public, qtX backend specific api).\n Catch the event.\n Assert sent and caught keys are the same.\n """\n from matplotlib.backends.qt_compat import _to_int, QtCore\n\n if sys.platform == "darwin" and answer is not None:\n answer = answer.replace("ctrl", "cmd")\n answer = answer.replace("control", "cmd")\n answer = answer.replace("meta", "ctrl")\n result = None\n qt_mod = QtCore.Qt.KeyboardModifier.NoModifier\n for mod in qt_mods:\n qt_mod |= getattr(QtCore.Qt.KeyboardModifier, mod)\n\n class _Event:\n def isAutoRepeat(self): return False\n def key(self): return _to_int(getattr(QtCore.Qt.Key, qt_key))\n\n monkeypatch.setattr(QtWidgets.QApplication, "keyboardModifiers",\n lambda self: qt_mod)\n\n def on_key_press(event):\n nonlocal result\n result = event.key\n\n qt_canvas = plt.figure().canvas\n qt_canvas.mpl_connect('key_press_event', on_key_press)\n qt_canvas.keyPressEvent(_Event())\n assert result == answer\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_device_pixel_ratio_change():\n """\n Make sure that if the pixel ratio changes, the figure dpi changes but the\n widget remains the same logical size.\n """\n\n prop = 'matplotlib.backends.backend_qt.FigureCanvasQT.devicePixelRatioF'\n with mock.patch(prop) as p:\n p.return_value = 3\n\n fig = plt.figure(figsize=(5, 2), dpi=120)\n qt_canvas = fig.canvas\n qt_canvas.show()\n\n def set_device_pixel_ratio(ratio):\n p.return_value = ratio\n\n # The value here doesn't matter, as we can't mock the C++ QScreen\n # object, but can override the functional wrapper around it.\n # Emitting this event is simply to trigger the DPI change handler\n # in Matplotlib in the same manner that it would occur normally.\n screen.logicalDotsPerInchChanged.emit(96)\n\n qt_canvas.draw()\n qt_canvas.flush_events()\n\n # Make sure the mocking worked\n assert qt_canvas.device_pixel_ratio == ratio\n\n qt_canvas.manager.show()\n size = qt_canvas.size()\n screen = qt_canvas.window().windowHandle().screen()\n set_device_pixel_ratio(3)\n\n # The DPI and the renderer width/height change\n assert fig.dpi == 360\n assert qt_canvas.renderer.width == 1800\n assert qt_canvas.renderer.height == 720\n\n # The actual widget size and figure logical size don't change.\n assert size.width() == 600\n assert size.height() == 240\n assert qt_canvas.get_width_height() == (600, 240)\n assert (fig.get_size_inches() == (5, 2)).all()\n\n set_device_pixel_ratio(2)\n\n # The DPI and the renderer width/height change\n assert fig.dpi == 240\n assert qt_canvas.renderer.width == 1200\n assert qt_canvas.renderer.height == 480\n\n # The actual widget size and figure logical size don't change.\n assert size.width() == 600\n assert size.height() == 240\n assert qt_canvas.get_width_height() == (600, 240)\n assert (fig.get_size_inches() == (5, 2)).all()\n\n set_device_pixel_ratio(1.5)\n\n # The DPI and the renderer width/height change\n assert fig.dpi == 180\n assert qt_canvas.renderer.width == 900\n assert qt_canvas.renderer.height == 360\n\n # The actual widget size and figure logical size don't change.\n assert size.width() == 600\n assert size.height() == 240\n assert qt_canvas.get_width_height() == (600, 240)\n assert (fig.get_size_inches() == (5, 2)).all()\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_subplottool():\n fig, ax = plt.subplots()\n with mock.patch("matplotlib.backends.qt_compat._exec", lambda obj: None):\n fig.canvas.manager.toolbar.configure_subplots()\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_figureoptions():\n fig, ax = plt.subplots()\n ax.plot([1, 2])\n ax.imshow([[1]])\n ax.scatter(range(3), range(3), c=range(3))\n with mock.patch("matplotlib.backends.qt_compat._exec", lambda obj: None):\n fig.canvas.manager.toolbar.edit_parameters()\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_save_figure_return():\n fig, ax = plt.subplots()\n ax.imshow([[1]])\n prop = "matplotlib.backends.qt_compat.QtWidgets.QFileDialog.getSaveFileName"\n with mock.patch(prop, return_value=("foobar.png", None)):\n fname = fig.canvas.manager.toolbar.save_figure()\n os.remove("foobar.png")\n assert fname == "foobar.png"\n with mock.patch(prop, return_value=(None, None)):\n fname = fig.canvas.manager.toolbar.save_figure()\n assert fname is None\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_figureoptions_with_datetime_axes():\n fig, ax = plt.subplots()\n xydata = [\n datetime(year=2021, month=1, day=1),\n datetime(year=2021, month=2, day=1)\n ]\n ax.plot(xydata, xydata)\n with mock.patch("matplotlib.backends.qt_compat._exec", lambda obj: None):\n fig.canvas.manager.toolbar.edit_parameters()\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_double_resize():\n # Check that resizing a figure twice keeps the same window size\n fig, ax = plt.subplots()\n fig.canvas.draw()\n window = fig.canvas.manager.window\n\n w, h = 3, 2\n fig.set_size_inches(w, h)\n assert fig.canvas.width() == w * matplotlib.rcParams['figure.dpi']\n assert fig.canvas.height() == h * matplotlib.rcParams['figure.dpi']\n\n old_width = window.width()\n old_height = window.height()\n\n fig.set_size_inches(w, h)\n assert window.width() == old_width\n assert window.height() == old_height\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_canvas_reinit():\n from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg\n\n called = False\n\n def crashing_callback(fig, stale):\n nonlocal called\n fig.canvas.draw_idle()\n called = True\n\n fig, ax = plt.subplots()\n fig.stale_callback = crashing_callback\n # this should not raise\n canvas = FigureCanvasQTAgg(fig)\n fig.stale = True\n assert called\n\n\n@pytest.mark.backend('Qt5Agg', skip_on_importerror=True)\ndef test_form_widget_get_with_datetime_and_date_fields():\n from matplotlib.backends.backend_qt import _create_qApp\n _create_qApp()\n\n form = [\n ("Datetime field", datetime(year=2021, month=3, day=11)),\n ("Date field", date(year=2021, month=3, day=11))\n ]\n widget = _formlayout.FormWidget(form)\n widget.setup()\n values = widget.get()\n assert values == [\n datetime(year=2021, month=3, day=11),\n date(year=2021, month=3, day=11)\n ]\n\n\ndef _get_testable_qt_backends():\n envs = []\n for deps, env in [\n ([qt_api], {"MPLBACKEND": "qtagg", "QT_API": qt_api})\n for qt_api in ["PyQt6", "PySide6", "PyQt5", "PySide2"]\n ]:\n reason = None\n missing = [dep for dep in deps if not importlib.util.find_spec(dep)]\n if (sys.platform == "linux" and\n not _c_internal_utils.display_is_valid()):\n reason = "$DISPLAY and $WAYLAND_DISPLAY are unset"\n elif missing:\n reason = "{} cannot be imported".format(", ".join(missing))\n elif env["MPLBACKEND"] == 'macosx' and os.environ.get('TF_BUILD'):\n reason = "macosx backend fails on Azure"\n marks = []\n if reason:\n marks.append(pytest.mark.skip(\n reason=f"Skipping {env} because {reason}"))\n envs.append(pytest.param(env, marks=marks, id=str(env)))\n return envs\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_fig_sigint_override(qt_core):\n from matplotlib.backends.backend_qt5 import _BackendQT5\n # Create a figure\n plt.figure()\n\n # Variable to access the handler from the inside of the event loop\n event_loop_handler = None\n\n # Callback to fire during event loop: save SIGINT handler, then exit\n def fire_signal_and_quit():\n # Save event loop signal\n nonlocal event_loop_handler\n event_loop_handler = signal.getsignal(signal.SIGINT)\n\n # Request event loop exit\n qt_core.QCoreApplication.exit()\n\n # Timer to exit event loop\n qt_core.QTimer.singleShot(0, fire_signal_and_quit)\n\n # Save original SIGINT handler\n original_handler = signal.getsignal(signal.SIGINT)\n\n # Use our own SIGINT handler to be 100% sure this is working\n def custom_handler(signum, frame):\n pass\n\n signal.signal(signal.SIGINT, custom_handler)\n\n try:\n # mainloop() sets SIGINT, starts Qt event loop (which triggers timer\n # and exits) and then mainloop() resets SIGINT\n matplotlib.backends.backend_qt._BackendQT.mainloop()\n\n # Assert: signal handler during loop execution is changed\n # (can't test equality with func)\n assert event_loop_handler != custom_handler\n\n # Assert: current signal handler is the same as the one we set before\n assert signal.getsignal(signal.SIGINT) == custom_handler\n\n # Repeat again to test that SIG_DFL and SIG_IGN will not be overridden\n for custom_handler in (signal.SIG_DFL, signal.SIG_IGN):\n qt_core.QTimer.singleShot(0, fire_signal_and_quit)\n signal.signal(signal.SIGINT, custom_handler)\n\n _BackendQT5.mainloop()\n\n assert event_loop_handler == custom_handler\n assert signal.getsignal(signal.SIGINT) == custom_handler\n\n finally:\n # Reset SIGINT handler to what it was before the test\n signal.signal(signal.SIGINT, original_handler)\n\n\n@pytest.mark.backend('QtAgg', skip_on_importerror=True)\ndef test_ipython():\n from matplotlib.testing import ipython_in_subprocess\n ipython_in_subprocess("qt", {(8, 24): "qtagg", (8, 15): "QtAgg", (7, 0): "Qt5Agg"})\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_qt.py | test_backend_qt.py | Python | 13,000 | 0.95 | 0.088608 | 0.117089 | vue-tools | 728 | 2024-12-17T02:11:13.272379 | GPL-3.0 | true | 44371f6a9fc602a8bd97068f2267596d |
from collections.abc import Sequence\nfrom typing import Any\n\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib.backends import BackendFilter, backend_registry\n\n\n@pytest.fixture\ndef clear_backend_registry():\n # Fixture that clears the singleton backend_registry before and after use\n # so that the test state remains isolated.\n backend_registry._clear()\n yield\n backend_registry._clear()\n\n\ndef has_duplicates(seq: Sequence[Any]) -> bool:\n return len(seq) > len(set(seq))\n\n\n@pytest.mark.parametrize(\n 'framework,expected',\n [\n ('qt', 'qtagg'),\n ('gtk3', 'gtk3agg'),\n ('gtk4', 'gtk4agg'),\n ('wx', 'wxagg'),\n ('tk', 'tkagg'),\n ('macosx', 'macosx'),\n ('headless', 'agg'),\n ('does not exist', None),\n ]\n)\ndef test_backend_for_gui_framework(framework, expected):\n assert backend_registry.backend_for_gui_framework(framework) == expected\n\n\ndef test_list_builtin():\n backends = backend_registry.list_builtin()\n assert not has_duplicates(backends)\n # Compare using sets as order is not important\n assert {*backends} == {\n 'gtk3agg', 'gtk3cairo', 'gtk4agg', 'gtk4cairo', 'macosx', 'nbagg', 'notebook',\n 'qtagg', 'qtcairo', 'qt5agg', 'qt5cairo', 'tkagg',\n 'tkcairo', 'webagg', 'wx', 'wxagg', 'wxcairo', 'agg', 'cairo', 'pdf', 'pgf',\n 'ps', 'svg', 'template',\n }\n\n\n@pytest.mark.parametrize(\n 'filter,expected',\n [\n (BackendFilter.INTERACTIVE,\n ['gtk3agg', 'gtk3cairo', 'gtk4agg', 'gtk4cairo', 'macosx', 'nbagg', 'notebook',\n 'qtagg', 'qtcairo', 'qt5agg', 'qt5cairo', 'tkagg',\n 'tkcairo', 'webagg', 'wx', 'wxagg', 'wxcairo']),\n (BackendFilter.NON_INTERACTIVE,\n ['agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']),\n ]\n)\ndef test_list_builtin_with_filter(filter, expected):\n backends = backend_registry.list_builtin(filter)\n assert not has_duplicates(backends)\n # Compare using sets as order is not important\n assert {*backends} == {*expected}\n\n\ndef test_list_gui_frameworks():\n frameworks = backend_registry.list_gui_frameworks()\n assert not has_duplicates(frameworks)\n # Compare using sets as order is not important\n assert {*frameworks} == {\n "gtk3", "gtk4", "macosx", "qt", "qt5", "qt6", "tk", "wx",\n }\n\n\n@pytest.mark.parametrize("backend, is_valid", [\n ("agg", True),\n ("QtAgg", True),\n ("module://anything", True),\n ("made-up-name", False),\n])\ndef test_is_valid_backend(backend, is_valid):\n assert backend_registry.is_valid_backend(backend) == is_valid\n\n\n@pytest.mark.parametrize("backend, normalized", [\n ("agg", "matplotlib.backends.backend_agg"),\n ("QtAgg", "matplotlib.backends.backend_qtagg"),\n ("module://Anything", "Anything"),\n])\ndef test_backend_normalization(backend, normalized):\n assert backend_registry._backend_module_name(backend) == normalized\n\n\ndef test_deprecated_rcsetup_attributes():\n match = "was deprecated in Matplotlib 3.9"\n with pytest.warns(mpl.MatplotlibDeprecationWarning, match=match):\n mpl.rcsetup.interactive_bk\n with pytest.warns(mpl.MatplotlibDeprecationWarning, match=match):\n mpl.rcsetup.non_interactive_bk\n with pytest.warns(mpl.MatplotlibDeprecationWarning, match=match):\n mpl.rcsetup.all_backends\n\n\ndef test_entry_points_inline():\n pytest.importorskip('matplotlib_inline')\n backends = backend_registry.list_all()\n assert 'inline' in backends\n\n\ndef test_entry_points_ipympl():\n pytest.importorskip('ipympl')\n backends = backend_registry.list_all()\n assert 'ipympl' in backends\n assert 'widget' in backends\n\n\ndef test_entry_point_name_shadows_builtin(clear_backend_registry):\n with pytest.raises(RuntimeError):\n backend_registry._validate_and_store_entry_points(\n [('qtagg', 'module1')])\n\n\ndef test_entry_point_name_duplicate(clear_backend_registry):\n with pytest.raises(RuntimeError):\n backend_registry._validate_and_store_entry_points(\n [('some_name', 'module1'), ('some_name', 'module2')])\n\n\ndef test_entry_point_identical(clear_backend_registry):\n # Issue https://github.com/matplotlib/matplotlib/issues/28367\n # Multiple entry points with the same name and value (value is the module)\n # are acceptable.\n n = len(backend_registry._name_to_module)\n backend_registry._validate_and_store_entry_points(\n [('some_name', 'some.module'), ('some_name', 'some.module')])\n assert len(backend_registry._name_to_module) == n+1\n assert backend_registry._name_to_module['some_name'] == 'module://some.module'\n\n\ndef test_entry_point_name_is_module(clear_backend_registry):\n with pytest.raises(RuntimeError):\n backend_registry._validate_and_store_entry_points(\n [('module://backend.something', 'module1')])\n\n\n@pytest.mark.parametrize('backend', [\n 'agg',\n 'module://matplotlib.backends.backend_agg',\n])\ndef test_load_entry_points_only_if_needed(clear_backend_registry, backend):\n assert not backend_registry._loaded_entry_points\n check = backend_registry.resolve_backend(backend)\n assert check == (backend, None)\n assert not backend_registry._loaded_entry_points\n backend_registry.list_all() # Force load of entry points\n assert backend_registry._loaded_entry_points\n\n\n@pytest.mark.parametrize(\n 'gui_or_backend, expected_backend, expected_gui',\n [\n ('agg', 'agg', None),\n ('qt', 'qtagg', 'qt'),\n ('TkCairo', 'tkcairo', 'tk'),\n ]\n)\ndef test_resolve_gui_or_backend(gui_or_backend, expected_backend, expected_gui):\n backend, gui = backend_registry.resolve_gui_or_backend(gui_or_backend)\n assert backend == expected_backend\n assert gui == expected_gui\n\n\ndef test_resolve_gui_or_backend_invalid():\n match = "is not a recognised GUI loop or backend name"\n with pytest.raises(RuntimeError, match=match):\n backend_registry.resolve_gui_or_backend('no-such-name')\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_registry.py | test_backend_registry.py | Python | 5,950 | 0.95 | 0.1 | 0.056338 | awesome-app | 926 | 2024-02-14T03:59:57.014009 | Apache-2.0 | true | d8c0805622b4156df793895300198240 |
import datetime\nfrom io import BytesIO\nfrom pathlib import Path\nimport xml.etree.ElementTree\nimport xml.parsers.expat\n\nimport pytest\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib.figure import Figure\nfrom matplotlib.patches import Circle\nfrom matplotlib.text import Text\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nfrom matplotlib.testing._markers import needs_usetex\nfrom matplotlib import font_manager as fm\nfrom matplotlib.offsetbox import (OffsetImage, AnnotationBbox)\n\n\ndef test_visibility():\n fig, ax = plt.subplots()\n\n x = np.linspace(0, 4 * np.pi, 50)\n y = np.sin(x)\n yerr = np.ones_like(y)\n\n a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')\n for artist in b:\n artist.set_visible(False)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue()\n\n parser = xml.parsers.expat.ParserCreate()\n parser.Parse(buf) # this will raise ExpatError if the svg is invalid\n\n\n@image_comparison(['fill_black_with_alpha.svg'], remove_text=True)\ndef test_fill_black_with_alpha():\n fig, ax = plt.subplots()\n ax.scatter(x=[0, 0.1, 1], y=[0, 0, 0], c='k', alpha=0.1, s=10000)\n\n\n@image_comparison(['noscale'], remove_text=True)\ndef test_noscale():\n X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))\n Z = np.sin(Y ** 2)\n\n fig, ax = plt.subplots()\n ax.imshow(Z, cmap='gray', interpolation='none')\n\n\ndef test_text_urls():\n fig = plt.figure()\n\n test_url = "http://test_text_urls.matplotlib.org"\n fig.suptitle("test_text_urls", url=test_url)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode()\n\n expected = f'<a xlink:href="{test_url}">'\n assert expected in buf\n\n\n@image_comparison(['bold_font_output.svg'])\ndef test_bold_font_output():\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10))\n ax.set_xlabel('nonbold-xlabel')\n ax.set_ylabel('bold-ylabel', fontweight='bold')\n ax.set_title('bold-title', fontweight='bold')\n\n\n@image_comparison(['bold_font_output_with_none_fonttype.svg'])\ndef test_bold_font_output_with_none_fonttype():\n plt.rcParams['svg.fonttype'] = 'none'\n fig, ax = plt.subplots()\n ax.plot(np.arange(10), np.arange(10))\n ax.set_xlabel('nonbold-xlabel')\n ax.set_ylabel('bold-ylabel', fontweight='bold')\n ax.set_title('bold-title', fontweight='bold')\n\n\n@check_figures_equal(tol=20)\ndef test_rasterized(fig_test, fig_ref):\n t = np.arange(0, 100) * (2.3)\n x = np.cos(t)\n y = np.sin(t)\n\n ax_ref = fig_ref.subplots()\n ax_ref.plot(x, y, "-", c="r", lw=10)\n ax_ref.plot(x+1, y, "-", c="b", lw=10)\n\n ax_test = fig_test.subplots()\n ax_test.plot(x, y, "-", c="r", lw=10, rasterized=True)\n ax_test.plot(x+1, y, "-", c="b", lw=10, rasterized=True)\n\n\n@check_figures_equal(extensions=['svg'])\ndef test_rasterized_ordering(fig_test, fig_ref):\n t = np.arange(0, 100) * (2.3)\n x = np.cos(t)\n y = np.sin(t)\n\n ax_ref = fig_ref.subplots()\n ax_ref.set_xlim(0, 3)\n ax_ref.set_ylim(-1.1, 1.1)\n ax_ref.plot(x, y, "-", c="r", lw=10, rasterized=True)\n ax_ref.plot(x+1, y, "-", c="b", lw=10, rasterized=False)\n ax_ref.plot(x+2, y, "-", c="g", lw=10, rasterized=True)\n ax_ref.plot(x+3, y, "-", c="m", lw=10, rasterized=True)\n\n ax_test = fig_test.subplots()\n ax_test.set_xlim(0, 3)\n ax_test.set_ylim(-1.1, 1.1)\n ax_test.plot(x, y, "-", c="r", lw=10, rasterized=True, zorder=1.1)\n ax_test.plot(x+2, y, "-", c="g", lw=10, rasterized=True, zorder=1.3)\n ax_test.plot(x+3, y, "-", c="m", lw=10, rasterized=True, zorder=1.4)\n ax_test.plot(x+1, y, "-", c="b", lw=10, rasterized=False, zorder=1.2)\n\n\n@check_figures_equal(tol=5, extensions=['svg', 'pdf'])\ndef test_prevent_rasterization(fig_test, fig_ref):\n loc = [0.05, 0.05]\n\n ax_ref = fig_ref.subplots()\n\n ax_ref.plot([loc[0]], [loc[1]], marker="x", c="black", zorder=2)\n\n b = mpl.offsetbox.TextArea("X")\n abox = mpl.offsetbox.AnnotationBbox(b, loc, zorder=2.1)\n ax_ref.add_artist(abox)\n\n ax_test = fig_test.subplots()\n ax_test.plot([loc[0]], [loc[1]], marker="x", c="black", zorder=2,\n rasterized=True)\n\n b = mpl.offsetbox.TextArea("X")\n abox = mpl.offsetbox.AnnotationBbox(b, loc, zorder=2.1)\n ax_test.add_artist(abox)\n\n\ndef test_count_bitmaps():\n def count_tag(fig, tag):\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode()\n return buf.count(f"<{tag}")\n\n # No rasterized elements\n fig1 = plt.figure()\n ax1 = fig1.add_subplot(1, 1, 1)\n ax1.set_axis_off()\n for n in range(5):\n ax1.plot([0, 20], [0, n], "b-", rasterized=False)\n assert count_tag(fig1, "image") == 0\n assert count_tag(fig1, "path") == 6 # axis patch plus lines\n\n # rasterized can be merged\n fig2 = plt.figure()\n ax2 = fig2.add_subplot(1, 1, 1)\n ax2.set_axis_off()\n for n in range(5):\n ax2.plot([0, 20], [0, n], "b-", rasterized=True)\n assert count_tag(fig2, "image") == 1\n assert count_tag(fig2, "path") == 1 # axis patch\n\n # rasterized can't be merged without affecting draw order\n fig3 = plt.figure()\n ax3 = fig3.add_subplot(1, 1, 1)\n ax3.set_axis_off()\n for n in range(5):\n ax3.plot([0, 20], [n, 0], "b-", rasterized=False)\n ax3.plot([0, 20], [0, n], "b-", rasterized=True)\n assert count_tag(fig3, "image") == 5\n assert count_tag(fig3, "path") == 6\n\n # rasterized whole axes\n fig4 = plt.figure()\n ax4 = fig4.add_subplot(1, 1, 1)\n ax4.set_axis_off()\n ax4.set_rasterized(True)\n for n in range(5):\n ax4.plot([0, 20], [n, 0], "b-", rasterized=False)\n ax4.plot([0, 20], [0, n], "b-", rasterized=True)\n assert count_tag(fig4, "image") == 1\n assert count_tag(fig4, "path") == 1\n\n # rasterized can be merged, but inhibited by suppressComposite\n fig5 = plt.figure()\n fig5.suppressComposite = True\n ax5 = fig5.add_subplot(1, 1, 1)\n ax5.set_axis_off()\n for n in range(5):\n ax5.plot([0, 20], [0, n], "b-", rasterized=True)\n assert count_tag(fig5, "image") == 5\n assert count_tag(fig5, "path") == 1 # axis patch\n\n\n# Use Computer Modern Sans Serif, not Helvetica (which has no \textwon).\n@mpl.style.context('default')\n@needs_usetex\ndef test_unicode_won():\n fig = Figure()\n fig.text(.5, .5, r'\textwon', usetex=True)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue()\n\n tree = xml.etree.ElementTree.fromstring(buf)\n ns = 'http://www.w3.org/2000/svg'\n won_id = 'SFSS3583-8e'\n assert len(tree.findall(f'.//{{{ns}}}path[@d][@id="{won_id}"]')) == 1\n assert f'#{won_id}' in tree.find(f'.//{{{ns}}}use').attrib.values()\n\n\ndef test_svgnone_with_data_coordinates():\n plt.rcParams.update({'svg.fonttype': 'none', 'font.stretch': 'condensed'})\n expected = 'Unlikely to appear by chance'\n\n fig, ax = plt.subplots()\n ax.text(np.datetime64('2019-06-30'), 1, expected)\n ax.set_xlim(np.datetime64('2019-01-01'), np.datetime64('2019-12-31'))\n ax.set_ylim(0, 2)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n fd.seek(0)\n buf = fd.read().decode()\n\n assert expected in buf and "condensed" in buf\n\n\ndef test_gid():\n """Test that object gid appears in output svg."""\n from matplotlib.offsetbox import OffsetBox\n from matplotlib.axis import Tick\n\n fig = plt.figure()\n\n ax1 = fig.add_subplot(131)\n ax1.imshow([[1., 2.], [2., 3.]], aspect="auto")\n ax1.scatter([1, 2, 3], [1, 2, 3], label="myscatter")\n ax1.plot([2, 3, 1], label="myplot")\n ax1.legend()\n ax1a = ax1.twinx()\n ax1a.bar([1, 2, 3], [1, 2, 3])\n\n ax2 = fig.add_subplot(132, projection="polar")\n ax2.plot([0, 1.5, 3], [1, 2, 3])\n\n ax3 = fig.add_subplot(133, projection="3d")\n ax3.plot([1, 2], [1, 2], [1, 2])\n\n fig.canvas.draw()\n\n gdic = {}\n for idx, obj in enumerate(fig.findobj(include_self=True)):\n if obj.get_visible():\n gid = f"test123{obj.__class__.__name__}_{idx}"\n gdic[gid] = obj\n obj.set_gid(gid)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode()\n\n def include(gid, obj):\n # we need to exclude certain objects which will not appear in the svg\n if isinstance(obj, OffsetBox):\n return False\n if isinstance(obj, Text):\n if obj.get_text() == "":\n return False\n elif obj.axes is None:\n return False\n if isinstance(obj, plt.Line2D):\n xdata, ydata = obj.get_data()\n if len(xdata) == len(ydata) == 1:\n return False\n elif not hasattr(obj, "axes") or obj.axes is None:\n return False\n if isinstance(obj, Tick):\n loc = obj.get_loc()\n if loc == 0:\n return False\n vi = obj.get_view_interval()\n if loc < min(vi) or loc > max(vi):\n return False\n return True\n\n for gid, obj in gdic.items():\n if include(gid, obj):\n assert gid in buf\n\n\ndef test_clip_path_ids_reuse():\n fig, circle = Figure(), Circle((0, 0), radius=10)\n for i in range(5):\n ax = fig.add_subplot()\n aimg = ax.imshow([[i]])\n aimg.set_clip_path(circle)\n\n inner_circle = Circle((0, 0), radius=1)\n ax = fig.add_subplot()\n aimg = ax.imshow([[0]])\n aimg.set_clip_path(inner_circle)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue()\n\n tree = xml.etree.ElementTree.fromstring(buf)\n ns = 'http://www.w3.org/2000/svg'\n\n clip_path_ids = set()\n for node in tree.findall(f'.//{{{ns}}}clipPath[@id]'):\n node_id = node.attrib['id']\n assert node_id not in clip_path_ids # assert ID uniqueness\n clip_path_ids.add(node_id)\n assert len(clip_path_ids) == 2 # only two clipPaths despite reuse in multiple axes\n\n\ndef test_savefig_tight():\n # Check that the draw-disabled renderer correctly disables open/close_group\n # as well.\n plt.savefig(BytesIO(), format="svgz", bbox_inches="tight")\n\n\ndef test_url():\n # Test that object url appears in output svg.\n\n fig, ax = plt.subplots()\n\n # collections\n s = ax.scatter([1, 2, 3], [4, 5, 6])\n s.set_urls(['https://example.com/foo', 'https://example.com/bar', None])\n\n # Line2D\n p, = plt.plot([2, 3, 4], [4, 5, 6])\n p.set_url('https://example.com/baz')\n\n # Line2D markers-only\n p, = plt.plot([3, 4, 5], [4, 5, 6], linestyle='none', marker='x')\n p.set_url('https://example.com/quux')\n\n b = BytesIO()\n fig.savefig(b, format='svg')\n b = b.getvalue()\n for v in [b'foo', b'bar', b'baz', b'quux']:\n assert b'https://example.com/' + v in b\n\n\ndef test_url_tick(monkeypatch):\n monkeypatch.setenv('SOURCE_DATE_EPOCH', '19680801')\n\n fig1, ax = plt.subplots()\n ax.scatter([1, 2, 3], [4, 5, 6])\n for i, tick in enumerate(ax.yaxis.get_major_ticks()):\n tick.set_url(f'https://example.com/{i}')\n\n fig2, ax = plt.subplots()\n ax.scatter([1, 2, 3], [4, 5, 6])\n for i, tick in enumerate(ax.yaxis.get_major_ticks()):\n tick.label1.set_url(f'https://example.com/{i}')\n tick.label2.set_url(f'https://example.com/{i}')\n\n b1 = BytesIO()\n fig1.savefig(b1, format='svg')\n b1 = b1.getvalue()\n\n b2 = BytesIO()\n fig2.savefig(b2, format='svg')\n b2 = b2.getvalue()\n\n for i in range(len(ax.yaxis.get_major_ticks())):\n assert f'https://example.com/{i}'.encode('ascii') in b1\n assert b1 == b2\n\n\ndef test_svg_default_metadata(monkeypatch):\n # Values have been predefined for 'Creator', 'Date', 'Format', and 'Type'.\n monkeypatch.setenv('SOURCE_DATE_EPOCH', '19680801')\n\n fig, ax = plt.subplots()\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode()\n\n # Creator\n assert mpl.__version__ in buf\n # Date\n assert '1970-08-16' in buf\n # Format\n assert 'image/svg+xml' in buf\n # Type\n assert 'StillImage' in buf\n\n # Now make sure all the default metadata can be cleared.\n with BytesIO() as fd:\n fig.savefig(fd, format='svg', metadata={'Date': None, 'Creator': None,\n 'Format': None, 'Type': None})\n buf = fd.getvalue().decode()\n\n # Creator\n assert mpl.__version__ not in buf\n # Date\n assert '1970-08-16' not in buf\n # Format\n assert 'image/svg+xml' not in buf\n # Type\n assert 'StillImage' not in buf\n\n\ndef test_svg_clear_default_metadata(monkeypatch):\n # Makes sure that setting a default metadata to `None`\n # removes the corresponding tag from the metadata.\n monkeypatch.setenv('SOURCE_DATE_EPOCH', '19680801')\n\n metadata_contains = {'creator': mpl.__version__, 'date': '1970-08-16',\n 'format': 'image/svg+xml', 'type': 'StillImage'}\n\n SVGNS = '{http://www.w3.org/2000/svg}'\n RDFNS = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'\n CCNS = '{http://creativecommons.org/ns#}'\n DCNS = '{http://purl.org/dc/elements/1.1/}'\n\n fig, ax = plt.subplots()\n for name in metadata_contains:\n with BytesIO() as fd:\n fig.savefig(fd, format='svg', metadata={name.title(): None})\n buf = fd.getvalue().decode()\n\n root = xml.etree.ElementTree.fromstring(buf)\n work, = root.findall(f'./{SVGNS}metadata/{RDFNS}RDF/{CCNS}Work')\n for key in metadata_contains:\n data = work.findall(f'./{DCNS}{key}')\n if key == name:\n # The one we cleared is not there\n assert not data\n continue\n # Everything else should be there\n data, = data\n xmlstr = xml.etree.ElementTree.tostring(data, encoding="unicode")\n assert metadata_contains[key] in xmlstr\n\n\ndef test_svg_clear_all_metadata():\n # Makes sure that setting all default metadata to `None`\n # removes the metadata tag from the output.\n\n fig, ax = plt.subplots()\n with BytesIO() as fd:\n fig.savefig(fd, format='svg', metadata={'Date': None, 'Creator': None,\n 'Format': None, 'Type': None})\n buf = fd.getvalue().decode()\n\n SVGNS = '{http://www.w3.org/2000/svg}'\n\n root = xml.etree.ElementTree.fromstring(buf)\n assert not root.findall(f'./{SVGNS}metadata')\n\n\ndef test_svg_metadata():\n single_value = ['Coverage', 'Identifier', 'Language', 'Relation', 'Source',\n 'Title', 'Type']\n multi_value = ['Contributor', 'Creator', 'Keywords', 'Publisher', 'Rights']\n metadata = {\n 'Date': [datetime.date(1968, 8, 1),\n datetime.datetime(1968, 8, 2, 1, 2, 3)],\n 'Description': 'description\ntext',\n **{k: f'{k} foo' for k in single_value},\n **{k: [f'{k} bar', f'{k} baz'] for k in multi_value},\n }\n\n fig = plt.figure()\n with BytesIO() as fd:\n fig.savefig(fd, format='svg', metadata=metadata)\n buf = fd.getvalue().decode()\n\n SVGNS = '{http://www.w3.org/2000/svg}'\n RDFNS = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'\n CCNS = '{http://creativecommons.org/ns#}'\n DCNS = '{http://purl.org/dc/elements/1.1/}'\n\n root = xml.etree.ElementTree.fromstring(buf)\n rdf, = root.findall(f'./{SVGNS}metadata/{RDFNS}RDF')\n\n # Check things that are single entries.\n titles = [node.text for node in root.findall(f'./{SVGNS}title')]\n assert titles == [metadata['Title']]\n types = [node.attrib[f'{RDFNS}resource']\n for node in rdf.findall(f'./{CCNS}Work/{DCNS}type')]\n assert types == [metadata['Type']]\n for k in ['Description', *single_value]:\n if k == 'Type':\n continue\n values = [node.text\n for node in rdf.findall(f'./{CCNS}Work/{DCNS}{k.lower()}')]\n assert values == [metadata[k]]\n\n # Check things that are multi-value entries.\n for k in multi_value:\n if k == 'Keywords':\n continue\n values = [\n node.text\n for node in rdf.findall(\n f'./{CCNS}Work/{DCNS}{k.lower()}/{CCNS}Agent/{DCNS}title')]\n assert values == metadata[k]\n\n # Check special things.\n dates = [node.text for node in rdf.findall(f'./{CCNS}Work/{DCNS}date')]\n assert dates == ['1968-08-01/1968-08-02T01:02:03']\n\n values = [node.text for node in\n rdf.findall(f'./{CCNS}Work/{DCNS}subject/{RDFNS}Bag/{RDFNS}li')]\n assert values == metadata['Keywords']\n\n\n@image_comparison(["multi_font_aspath.svg"], tol=1.8)\ndef test_multi_font_type3():\n fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font may be missing")\n\n plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)\n plt.rc('svg', fonttype='path')\n\n fig = plt.figure()\n fig.text(0.15, 0.475, "There are 几个汉字 in between!")\n\n\n@image_comparison(["multi_font_astext.svg"])\ndef test_multi_font_type42():\n fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font may be missing")\n\n fig = plt.figure()\n plt.rc('svg', fonttype='none')\n\n plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)\n fig.text(0.15, 0.475, "There are 几个汉字 in between!")\n\n\n@pytest.mark.parametrize('metadata,error,message', [\n ({'Date': 1}, TypeError, "Invalid type for Date metadata. Expected str"),\n ({'Date': [1]}, TypeError,\n "Invalid type for Date metadata. Expected iterable"),\n ({'Keywords': 1}, TypeError,\n "Invalid type for Keywords metadata. Expected str"),\n ({'Keywords': [1]}, TypeError,\n "Invalid type for Keywords metadata. Expected iterable"),\n ({'Creator': 1}, TypeError,\n "Invalid type for Creator metadata. Expected str"),\n ({'Creator': [1]}, TypeError,\n "Invalid type for Creator metadata. Expected iterable"),\n ({'Title': 1}, TypeError,\n "Invalid type for Title metadata. Expected str"),\n ({'Format': 1}, TypeError,\n "Invalid type for Format metadata. Expected str"),\n ({'Foo': 'Bar'}, ValueError, "Unknown metadata key"),\n ])\ndef test_svg_incorrect_metadata(metadata, error, message):\n with pytest.raises(error, match=message), BytesIO() as fd:\n fig = plt.figure()\n fig.savefig(fd, format='svg', metadata=metadata)\n\n\ndef test_svg_escape():\n fig = plt.figure()\n fig.text(0.5, 0.5, "<\'\"&>", gid="<\'\"&>")\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode()\n assert '<'"&>"' in buf\n\n\n@pytest.mark.parametrize("font_str", [\n "'DejaVu Sans', 'WenQuanYi Zen Hei', 'Arial', sans-serif",\n "'DejaVu Serif', 'WenQuanYi Zen Hei', 'Times New Roman', serif",\n "'Arial', 'WenQuanYi Zen Hei', cursive",\n "'Impact', 'WenQuanYi Zen Hei', fantasy",\n "'DejaVu Sans Mono', 'WenQuanYi Zen Hei', 'Courier New', monospace",\n # These do not work because the logic to get the font metrics will not find\n # WenQuanYi as the fallback logic stops with the first fallback font:\n # "'DejaVu Sans Mono', 'Courier New', 'WenQuanYi Zen Hei', monospace",\n # "'DejaVu Sans', 'Arial', 'WenQuanYi Zen Hei', sans-serif",\n # "'DejaVu Serif', 'Times New Roman', 'WenQuanYi Zen Hei', serif",\n])\n@pytest.mark.parametrize("include_generic", [True, False])\ndef test_svg_font_string(font_str, include_generic):\n fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])\n if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":\n pytest.skip("Font may be missing")\n\n explicit, *rest, generic = map(\n lambda x: x.strip("'"), font_str.split(", ")\n )\n size = len(generic)\n if include_generic:\n rest = rest + [generic]\n plt.rcParams[f"font.{generic}"] = rest\n plt.rcParams["font.size"] = size\n plt.rcParams["svg.fonttype"] = "none"\n\n fig, ax = plt.subplots()\n if generic == "sans-serif":\n generic_options = ["sans", "sans-serif", "sans serif"]\n else:\n generic_options = [generic]\n\n for generic_name in generic_options:\n # test that fallback works\n ax.text(0.5, 0.5, "There are 几个汉字 in between!",\n family=[explicit, generic_name], ha="center")\n # test deduplication works\n ax.text(0.5, 0.1, "There are 几个汉字 in between!",\n family=[explicit, *rest, generic_name], ha="center")\n ax.axis("off")\n\n with BytesIO() as fd:\n fig.savefig(fd, format="svg")\n buf = fd.getvalue()\n\n tree = xml.etree.ElementTree.fromstring(buf)\n ns = "http://www.w3.org/2000/svg"\n text_count = 0\n for text_element in tree.findall(f".//{{{ns}}}text"):\n text_count += 1\n font_style = dict(\n map(lambda x: x.strip(), _.strip().split(":"))\n for _ in dict(text_element.items())["style"].split(";")\n )\n\n assert font_style["font-size"] == f"{size}px"\n assert font_style["font-family"] == font_str\n assert text_count == len(ax.texts)\n\n\ndef test_annotationbbox_gid():\n # Test that object gid appears in the AnnotationBbox\n # in output svg.\n fig = plt.figure()\n ax = fig.add_subplot()\n arr_img = np.ones((32, 32))\n xy = (0.3, 0.55)\n\n imagebox = OffsetImage(arr_img, zoom=0.1)\n imagebox.image.axes = ax\n\n ab = AnnotationBbox(imagebox, xy,\n xybox=(120., -80.),\n xycoords='data',\n boxcoords="offset points",\n pad=0.5,\n arrowprops=dict(\n arrowstyle="->",\n connectionstyle="angle,angleA=0,angleB=90,rad=3")\n )\n ab.set_gid("a test for issue 20044")\n ax.add_artist(ab)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode('utf-8')\n\n expected = '<g id="a test for issue 20044">'\n assert expected in buf\n\n\ndef test_svgid():\n """Test that `svg.id` rcparam appears in output svg if not None."""\n\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3], [3, 2, 1])\n fig.canvas.draw()\n\n # Default: svg.id = None\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode()\n\n tree = xml.etree.ElementTree.fromstring(buf)\n\n assert plt.rcParams['svg.id'] is None\n assert not tree.findall('.[@id]')\n\n # String: svg.id = str\n svg_id = 'a test for issue 28535'\n plt.rc('svg', id=svg_id)\n\n with BytesIO() as fd:\n fig.savefig(fd, format='svg')\n buf = fd.getvalue().decode()\n\n tree = xml.etree.ElementTree.fromstring(buf)\n\n assert plt.rcParams['svg.id'] == svg_id\n assert tree.findall(f'.[@id="{svg_id}"]')\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_svg.py | test_backend_svg.py | Python | 22,930 | 0.95 | 0.128713 | 0.080645 | awesome-app | 412 | 2023-12-13T20:14:27.499481 | Apache-2.0 | true | 49332bc70d062398f7650246e6853d8f |
"""\nBackend-loading machinery tests, using variations on the template backend.\n"""\n\nimport sys\nfrom types import SimpleNamespace\nfrom unittest.mock import MagicMock\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom matplotlib.backends import backend_template\nfrom matplotlib.backends.backend_template import (\n FigureCanvasTemplate, FigureManagerTemplate)\n\n\ndef test_load_template():\n mpl.use("template")\n assert type(plt.figure().canvas) == FigureCanvasTemplate\n\n\ndef test_load_old_api(monkeypatch):\n mpl_test_backend = SimpleNamespace(**vars(backend_template))\n mpl_test_backend.new_figure_manager = (\n lambda num, *args, FigureClass=mpl.figure.Figure, **kwargs:\n FigureManagerTemplate(\n FigureCanvasTemplate(FigureClass(*args, **kwargs)), num))\n monkeypatch.setitem(sys.modules, "mpl_test_backend", mpl_test_backend)\n mpl.use("module://mpl_test_backend")\n assert type(plt.figure().canvas) == FigureCanvasTemplate\n plt.draw_if_interactive()\n\n\ndef test_show(monkeypatch):\n mpl_test_backend = SimpleNamespace(**vars(backend_template))\n mock_show = MagicMock()\n monkeypatch.setattr(\n mpl_test_backend.FigureManagerTemplate, "pyplot_show", mock_show)\n monkeypatch.setitem(sys.modules, "mpl_test_backend", mpl_test_backend)\n mpl.use("module://mpl_test_backend")\n plt.show()\n mock_show.assert_called_with()\n\n\ndef test_show_old_global_api(monkeypatch):\n mpl_test_backend = SimpleNamespace(**vars(backend_template))\n mock_show = MagicMock()\n monkeypatch.setattr(mpl_test_backend, "show", mock_show, raising=False)\n monkeypatch.setitem(sys.modules, "mpl_test_backend", mpl_test_backend)\n mpl.use("module://mpl_test_backend")\n plt.show()\n mock_show.assert_called_with()\n\n\ndef test_load_case_sensitive(monkeypatch):\n mpl_test_backend = SimpleNamespace(**vars(backend_template))\n mock_show = MagicMock()\n monkeypatch.setattr(\n mpl_test_backend.FigureManagerTemplate, "pyplot_show", mock_show)\n monkeypatch.setitem(sys.modules, "mpl_Test_Backend", mpl_test_backend)\n mpl.use("module://mpl_Test_Backend")\n plt.show()\n mock_show.assert_called_with()\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_template.py | test_backend_template.py | Python | 2,184 | 0.95 | 0.080645 | 0 | react-lib | 108 | 2023-09-30T12:31:58.082431 | MIT | true | ddf5be646473a9d9a944591b89845f31 |
import functools\nimport importlib\nimport os\nimport platform\nimport subprocess\nimport sys\n\nimport pytest\n\nfrom matplotlib import _c_internal_utils\nfrom matplotlib.testing import subprocess_run_helper\n\n\n_test_timeout = 60 # A reasonably safe value for slower architectures.\n\n\ndef _isolated_tk_test(success_count, func=None):\n """\n A decorator to run *func* in a subprocess and assert that it prints\n "success" *success_count* times and nothing on stderr.\n\n TkAgg tests seem to have interactions between tests, so isolate each test\n in a subprocess. See GH#18261\n """\n\n if func is None:\n return functools.partial(_isolated_tk_test, success_count)\n\n if "MPL_TEST_ESCAPE_HATCH" in os.environ:\n # set in subprocess_run_helper() below\n return func\n\n @pytest.mark.skipif(\n not importlib.util.find_spec('tkinter'),\n reason="missing tkinter"\n )\n @pytest.mark.skipif(\n sys.platform == "linux" and not _c_internal_utils.xdisplay_is_valid(),\n reason="$DISPLAY is unset"\n )\n @pytest.mark.xfail( # https://github.com/actions/setup-python/issues/649\n ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and\n sys.platform == 'darwin' and sys.version_info[:2] < (3, 11),\n reason='Tk version mismatch on Azure macOS CI'\n )\n @functools.wraps(func)\n def test_func():\n # even if the package exists, may not actually be importable this can\n # be the case on some CI systems.\n pytest.importorskip('tkinter')\n try:\n proc = subprocess_run_helper(\n func, timeout=_test_timeout, extra_env=dict(\n MPLBACKEND="TkAgg", MPL_TEST_ESCAPE_HATCH="1"))\n except subprocess.TimeoutExpired:\n pytest.fail("Subprocess timed out")\n except subprocess.CalledProcessError as e:\n pytest.fail("Subprocess failed to test intended behavior\n"\n + str(e.stderr))\n else:\n # macOS may actually emit irrelevant errors about Accelerated\n # OpenGL vs. software OpenGL, or some permission error on Azure, so\n # suppress them.\n # Asserting stderr first (and printing it on failure) should be\n # more helpful for debugging that printing a failed success count.\n ignored_lines = ["OpenGL", "CFMessagePort: bootstrap_register",\n "/usr/include/servers/bootstrap_defs.h"]\n assert not [line for line in proc.stderr.splitlines()\n if all(msg not in line for msg in ignored_lines)]\n assert proc.stdout.count("success") == success_count\n\n return test_func\n\n\n@_isolated_tk_test(success_count=6) # len(bad_boxes)\ndef test_blit():\n import matplotlib.pyplot as plt\n import numpy as np\n import matplotlib.backends.backend_tkagg # noqa\n from matplotlib.backends import _backend_tk, _tkagg\n\n fig, ax = plt.subplots()\n photoimage = fig.canvas._tkphoto\n data = np.ones((4, 4, 4), dtype=np.uint8)\n # Test out of bounds blitting.\n bad_boxes = ((-1, 2, 0, 2),\n (2, 0, 0, 2),\n (1, 6, 0, 2),\n (0, 2, -1, 2),\n (0, 2, 2, 0),\n (0, 2, 1, 6))\n for bad_box in bad_boxes:\n try:\n _tkagg.blit(\n photoimage.tk.interpaddr(), str(photoimage), data,\n _tkagg.TK_PHOTO_COMPOSITE_OVERLAY, (0, 1, 2, 3), bad_box)\n except ValueError:\n print("success")\n\n # Test blitting to a destroyed canvas.\n plt.close(fig)\n _backend_tk.blit(photoimage, data, (0, 1, 2, 3))\n\n\n@_isolated_tk_test(success_count=1)\ndef test_figuremanager_preserves_host_mainloop():\n import tkinter\n import matplotlib.pyplot as plt\n success = []\n\n def do_plot():\n plt.figure()\n plt.plot([1, 2], [3, 5])\n plt.close()\n root.after(0, legitimate_quit)\n\n def legitimate_quit():\n root.quit()\n success.append(True)\n\n root = tkinter.Tk()\n root.after(0, do_plot)\n root.mainloop()\n\n if success:\n print("success")\n\n\n@pytest.mark.skipif(platform.python_implementation() != 'CPython',\n reason='PyPy does not support Tkinter threading: '\n 'https://foss.heptapod.net/pypy/pypy/-/issues/1929')\n@pytest.mark.flaky(reruns=3)\n@_isolated_tk_test(success_count=1)\ndef test_figuremanager_cleans_own_mainloop():\n import tkinter\n import time\n import matplotlib.pyplot as plt\n import threading\n from matplotlib.cbook import _get_running_interactive_framework\n\n root = tkinter.Tk()\n plt.plot([1, 2, 3], [1, 2, 5])\n\n def target():\n while not 'tk' == _get_running_interactive_framework():\n time.sleep(.01)\n plt.close()\n if show_finished_event.wait():\n print('success')\n\n show_finished_event = threading.Event()\n thread = threading.Thread(target=target, daemon=True)\n thread.start()\n plt.show(block=True) # Testing if this function hangs.\n show_finished_event.set()\n thread.join()\n\n\n@pytest.mark.flaky(reruns=3)\n@_isolated_tk_test(success_count=0)\ndef test_never_update():\n import tkinter\n del tkinter.Misc.update\n del tkinter.Misc.update_idletasks\n\n import matplotlib.pyplot as plt\n fig = plt.figure()\n plt.show(block=False)\n\n plt.draw() # Test FigureCanvasTkAgg.\n fig.canvas.toolbar.configure_subplots() # Test NavigationToolbar2Tk.\n # Test FigureCanvasTk filter_destroy callback\n fig.canvas.get_tk_widget().after(100, plt.close, fig)\n\n # Check for update() or update_idletasks() in the event queue, functionally\n # equivalent to tkinter.Misc.update.\n plt.show(block=True)\n\n # Note that exceptions would be printed to stderr; _isolated_tk_test\n # checks them.\n\n\n@_isolated_tk_test(success_count=2)\ndef test_missing_back_button():\n import matplotlib.pyplot as plt\n from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk\n\n class Toolbar(NavigationToolbar2Tk):\n # Only display the buttons we need.\n toolitems = [t for t in NavigationToolbar2Tk.toolitems if\n t[0] in ('Home', 'Pan', 'Zoom')]\n\n fig = plt.figure()\n print("success")\n Toolbar(fig.canvas, fig.canvas.manager.window) # This should not raise.\n print("success")\n\n\n@_isolated_tk_test(success_count=2)\ndef test_save_figure_return():\n import matplotlib.pyplot as plt\n from unittest import mock\n fig = plt.figure()\n prop = "tkinter.filedialog.asksaveasfilename"\n with mock.patch(prop, return_value="foobar.png"):\n fname = fig.canvas.manager.toolbar.save_figure()\n os.remove("foobar.png")\n assert fname == "foobar.png"\n print("success")\n with mock.patch(prop, return_value=""):\n fname = fig.canvas.manager.toolbar.save_figure()\n assert fname is None\n print("success")\n\n\n@_isolated_tk_test(success_count=1)\ndef test_canvas_focus():\n import tkinter as tk\n import matplotlib.pyplot as plt\n success = []\n\n def check_focus():\n tkcanvas = fig.canvas.get_tk_widget()\n # Give the plot window time to appear\n if not tkcanvas.winfo_viewable():\n tkcanvas.wait_visibility()\n # Make sure the canvas has the focus, so that it's able to receive\n # keyboard events.\n if tkcanvas.focus_lastfor() == tkcanvas:\n success.append(True)\n plt.close()\n root.destroy()\n\n root = tk.Tk()\n fig = plt.figure()\n plt.plot([1, 2, 3])\n root.after(0, plt.show)\n root.after(100, check_focus)\n root.mainloop()\n\n if success:\n print("success")\n\n\n@_isolated_tk_test(success_count=2)\ndef test_embedding():\n import tkinter as tk\n from matplotlib.backends.backend_tkagg import (\n FigureCanvasTkAgg, NavigationToolbar2Tk)\n from matplotlib.backend_bases import key_press_handler\n from matplotlib.figure import Figure\n\n root = tk.Tk()\n\n def test_figure(master):\n fig = Figure()\n ax = fig.add_subplot()\n ax.plot([1, 2, 3])\n\n canvas = FigureCanvasTkAgg(fig, master=master)\n canvas.draw()\n canvas.mpl_connect("key_press_event", key_press_handler)\n canvas.get_tk_widget().pack(expand=True, fill="both")\n\n toolbar = NavigationToolbar2Tk(canvas, master, pack_toolbar=False)\n toolbar.pack(expand=True, fill="x")\n\n canvas.get_tk_widget().forget()\n toolbar.forget()\n\n test_figure(root)\n print("success")\n\n # Test with a dark button color. Doesn't actually check whether the icon\n # color becomes lighter, just that the code doesn't break.\n\n root.tk_setPalette(background="sky blue", selectColor="midnight blue",\n foreground="white")\n test_figure(root)\n print("success")\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_tk.py | test_backend_tk.py | Python | 8,850 | 0.95 | 0.135714 | 0.092511 | awesome-app | 612 | 2024-10-02T17:50:21.274907 | GPL-3.0 | true | 751259ea0facdf38b9b7fb7d19c63986 |
import pytest\n\nfrom matplotlib.backend_tools import ToolHelpBase\n\n\n@pytest.mark.parametrize('rc_shortcut,expected', [\n ('home', 'Home'),\n ('backspace', 'Backspace'),\n ('f1', 'F1'),\n ('ctrl+a', 'Ctrl+A'),\n ('ctrl+A', 'Ctrl+Shift+A'),\n ('a', 'a'),\n ('A', 'A'),\n ('ctrl+shift+f1', 'Ctrl+Shift+F1'),\n ('1', '1'),\n ('cmd+p', 'Cmd+P'),\n ('cmd+1', 'Cmd+1'),\n])\ndef test_format_shortcut(rc_shortcut, expected):\n assert ToolHelpBase.format_shortcut(rc_shortcut) == expected\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_tools.py | test_backend_tools.py | Python | 501 | 0.85 | 0.05 | 0 | react-lib | 662 | 2025-07-04T06:48:54.608398 | BSD-3-Clause | true | 79f27eaca5969e6ba1c00c7f52cb2795 |
import os\nimport sys\nimport pytest\n\nimport matplotlib.backends.backend_webagg_core\nfrom matplotlib.testing import subprocess_run_for_testing\n\n\n@pytest.mark.parametrize("backend", ["webagg", "nbagg"])\ndef test_webagg_fallback(backend):\n pytest.importorskip("tornado")\n if backend == "nbagg":\n pytest.importorskip("IPython")\n env = dict(os.environ)\n if sys.platform != "win32":\n env["DISPLAY"] = ""\n\n env["MPLBACKEND"] = backend\n\n test_code = (\n "import os;"\n + f"assert os.environ['MPLBACKEND'] == '{backend}';"\n + "import matplotlib.pyplot as plt; "\n + "print(plt.get_backend());"\n f"assert '{backend}' == plt.get_backend().lower();"\n )\n subprocess_run_for_testing([sys.executable, "-c", test_code], env=env, check=True)\n\n\ndef test_webagg_core_no_toolbar():\n fm = matplotlib.backends.backend_webagg_core.FigureManagerWebAgg\n assert fm._toolbar2_class is None\n | .venv\Lib\site-packages\matplotlib\tests\test_backend_webagg.py | test_backend_webagg.py | Python | 938 | 0.85 | 0.125 | 0 | node-utils | 872 | 2025-06-21T16:00:16.772065 | MIT | true | bcbf78153bd4e37e72ff510c1115cee4 |
import builtins\nimport os\nimport sys\nimport textwrap\n\nfrom matplotlib.testing import subprocess_run_for_testing\n\n\ndef test_simple():\n assert 1 + 1 == 2\n\n\ndef test_override_builtins():\n import pylab # type: ignore[import]\n ok_to_override = {\n '__name__',\n '__doc__',\n '__package__',\n '__loader__',\n '__spec__',\n 'any',\n 'all',\n 'sum',\n 'divmod'\n }\n overridden = {key for key in {*dir(pylab)} & {*dir(builtins)}\n if getattr(pylab, key) != getattr(builtins, key)}\n assert overridden <= ok_to_override\n\n\ndef test_lazy_imports():\n source = textwrap.dedent("""\n import sys\n\n import matplotlib.figure\n import matplotlib.backend_bases\n import matplotlib.pyplot\n\n assert 'matplotlib._tri' not in sys.modules\n assert 'matplotlib._qhull' not in sys.modules\n assert 'matplotlib._contour' not in sys.modules\n assert 'urllib.request' not in sys.modules\n """)\n\n subprocess_run_for_testing(\n [sys.executable, '-c', source],\n env={**os.environ, "MPLBACKEND": "", "MATPLOTLIBRC": os.devnull},\n check=True)\n | .venv\Lib\site-packages\matplotlib\tests\test_basic.py | test_basic.py | Python | 1,141 | 0.95 | 0.104167 | 0 | awesome-app | 854 | 2024-05-02T06:44:56.131425 | BSD-3-Clause | true | 6c203bbeece362ca2436290e7b934d53 |
from io import BytesIO\nimport platform\n\nimport numpy as np\n\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.pyplot as plt\nimport matplotlib.path as mpath\nimport matplotlib.patches as mpatches\nfrom matplotlib.ticker import FuncFormatter\n\n\n@image_comparison(['bbox_inches_tight'], remove_text=True,\n savefig_kwarg={'bbox_inches': 'tight'})\ndef test_bbox_inches_tight():\n #: Test that a figure saved using bbox_inches='tight' is clipped correctly\n data = [[66386, 174296, 75131, 577908, 32015],\n [58230, 381139, 78045, 99308, 160454],\n [89135, 80552, 152558, 497981, 603535],\n [78415, 81858, 150656, 193263, 69638],\n [139361, 331509, 343164, 781380, 52269]]\n\n col_labels = row_labels = [''] * 5\n\n rows = len(data)\n ind = np.arange(len(col_labels)) + 0.3 # the x locations for the groups\n cell_text = []\n width = 0.4 # the width of the bars\n yoff = np.zeros(len(col_labels))\n # the bottom values for stacked bar chart\n fig, ax = plt.subplots(1, 1)\n for row in range(rows):\n ax.bar(ind, data[row], width, bottom=yoff, align='edge', color='b')\n yoff = yoff + data[row]\n cell_text.append([''])\n plt.xticks([])\n plt.xlim(0, 5)\n plt.legend([''] * 5, loc=(1.2, 0.2))\n fig.legend([''] * 5, bbox_to_anchor=(0, 0.2), loc='lower left')\n # Add a table at the bottom of the axes\n cell_text.reverse()\n plt.table(cellText=cell_text, rowLabels=row_labels, colLabels=col_labels,\n loc='bottom')\n\n\n@image_comparison(['bbox_inches_tight_suptile_legend'],\n savefig_kwarg={'bbox_inches': 'tight'},\n tol=0 if platform.machine() == 'x86_64' else 0.02)\ndef test_bbox_inches_tight_suptile_legend():\n plt.plot(np.arange(10), label='a straight line')\n plt.legend(bbox_to_anchor=(0.9, 1), loc='upper left')\n plt.title('Axis title')\n plt.suptitle('Figure title')\n\n # put an extra long y tick on to see that the bbox is accounted for\n def y_formatter(y, pos):\n if int(y) == 4:\n return 'The number 4'\n else:\n return str(y)\n plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter))\n\n plt.xlabel('X axis')\n\n\n@image_comparison(['bbox_inches_tight_suptile_non_default.png'],\n savefig_kwarg={'bbox_inches': 'tight'},\n tol=0.1) # large tolerance because only testing clipping.\ndef test_bbox_inches_tight_suptitle_non_default():\n fig, ax = plt.subplots()\n fig.suptitle('Booo', x=0.5, y=1.1)\n\n\n@image_comparison(['bbox_inches_tight_layout.png'], remove_text=True,\n style='mpl20',\n savefig_kwarg=dict(bbox_inches='tight', pad_inches='layout'))\ndef test_bbox_inches_tight_layout_constrained():\n fig, ax = plt.subplots(layout='constrained')\n fig.get_layout_engine().set(h_pad=0.5)\n ax.set_aspect('equal')\n\n\ndef test_bbox_inches_tight_layout_notconstrained(tmp_path):\n # pad_inches='layout' should be ignored when not using constrained/\n # compressed layout. Smoke test that savefig doesn't error in this case.\n fig, ax = plt.subplots()\n fig.savefig(tmp_path / 'foo.png', bbox_inches='tight', pad_inches='layout')\n\n\n@image_comparison(['bbox_inches_tight_clipping'],\n remove_text=True, savefig_kwarg={'bbox_inches': 'tight'})\ndef test_bbox_inches_tight_clipping():\n # tests bbox clipping on scatter points, and path clipping on a patch\n # to generate an appropriately tight bbox\n plt.scatter(np.arange(10), np.arange(10))\n ax = plt.gca()\n ax.set_xlim(0, 5)\n ax.set_ylim(0, 5)\n\n # make a massive rectangle and clip it with a path\n patch = mpatches.Rectangle([-50, -50], 100, 100,\n transform=ax.transData,\n facecolor='blue', alpha=0.5)\n\n path = mpath.Path.unit_regular_star(5).deepcopy()\n path.vertices *= 0.25\n patch.set_clip_path(path, transform=ax.transAxes)\n plt.gcf().artists.append(patch)\n\n\n@image_comparison(['bbox_inches_tight_raster'],\n remove_text=True, savefig_kwarg={'bbox_inches': 'tight'})\ndef test_bbox_inches_tight_raster():\n """Test rasterization with tight_layout"""\n fig, ax = plt.subplots()\n ax.plot([1.0, 2.0], rasterized=True)\n\n\ndef test_only_on_non_finite_bbox():\n fig, ax = plt.subplots()\n ax.annotate("", xy=(0, float('nan')))\n ax.set_axis_off()\n # we only need to test that it does not error out on save\n fig.savefig(BytesIO(), bbox_inches='tight', format='png')\n\n\ndef test_tight_pcolorfast():\n fig, ax = plt.subplots()\n ax.pcolorfast(np.arange(4).reshape((2, 2)))\n ax.set(ylim=(0, .1))\n buf = BytesIO()\n fig.savefig(buf, bbox_inches="tight")\n buf.seek(0)\n height, width, _ = plt.imread(buf).shape\n # Previously, the bbox would include the area of the image clipped out by\n # the axes, resulting in a very tall image given the y limits of (0, 0.1).\n assert width > height\n\n\ndef test_noop_tight_bbox():\n from PIL import Image\n x_size, y_size = (10, 7)\n dpi = 100\n # make the figure just the right size up front\n fig = plt.figure(frameon=False, dpi=dpi, figsize=(x_size/dpi, y_size/dpi))\n ax = fig.add_axes((0, 0, 1, 1))\n ax.set_axis_off()\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n data = np.arange(x_size * y_size).reshape(y_size, x_size)\n ax.imshow(data, rasterized=True)\n\n # When a rasterized Artist is included, a mixed-mode renderer does\n # additional bbox adjustment. It should also be a no-op, and not affect the\n # next save.\n fig.savefig(BytesIO(), bbox_inches='tight', pad_inches=0, format='pdf')\n\n out = BytesIO()\n fig.savefig(out, bbox_inches='tight', pad_inches=0)\n out.seek(0)\n im = np.asarray(Image.open(out))\n assert (im[:, :, 3] == 255).all()\n assert not (im[:, :, :3] == 255).all()\n assert im.shape == (7, 10, 4)\n\n\n@image_comparison(['bbox_inches_fixed_aspect'], extensions=['png'],\n remove_text=True, savefig_kwarg={'bbox_inches': 'tight'})\ndef test_bbox_inches_fixed_aspect():\n with plt.rc_context({'figure.constrained_layout.use': True}):\n fig, ax = plt.subplots()\n ax.plot([0, 1])\n ax.set_xlim(0, 1)\n ax.set_aspect('equal')\n | .venv\Lib\site-packages\matplotlib\tests\test_bbox_tight.py | test_bbox_tight.py | Python | 6,314 | 0.95 | 0.102857 | 0.112676 | python-kit | 441 | 2023-07-15T19:36:00.987317 | BSD-3-Clause | true | 6052d5d83fedd620c84b18cd1fa65120 |
"""\nTests specific to the bezier module.\n"""\n\nfrom matplotlib.bezier import inside_circle, split_bezier_intersecting_with_closedpath\n\n\ndef test_split_bezier_with_large_values():\n # These numbers come from gh-27753\n arrow_path = [(96950809781500.0, 804.7503795623779),\n (96950809781500.0, 859.6242585800646),\n (96950809781500.0, 914.4981375977513)]\n in_f = inside_circle(96950809781500.0, 804.7503795623779, 0.06)\n split_bezier_intersecting_with_closedpath(arrow_path, in_f)\n # All we are testing is that this completes\n # The failure case is an infinite loop resulting from floating point precision\n # pytest will timeout if that occurs\n | .venv\Lib\site-packages\matplotlib\tests\test_bezier.py | test_bezier.py | Python | 692 | 0.95 | 0.117647 | 0.285714 | node-utils | 792 | 2024-12-19T11:06:43.571092 | MIT | true | 4c47f5482d112cc83bca40afb60eb634 |
"""Catch all for categorical functions"""\nimport warnings\n\nimport pytest\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib.axes import Axes\nimport matplotlib.pyplot as plt\nimport matplotlib.category as cat\nfrom matplotlib.testing.decorators import check_figures_equal\n\n\nclass TestUnitData:\n test_cases = [('single', (["hello world"], [0])),\n ('unicode', (["Здравствуйте мир"], [0])),\n ('mixed', (['A', "np.nan", 'B', "3.14", "мир"],\n [0, 1, 2, 3, 4]))]\n ids, data = zip(*test_cases)\n\n @pytest.mark.parametrize("data, locs", data, ids=ids)\n def test_unit(self, data, locs):\n unit = cat.UnitData(data)\n assert list(unit._mapping.keys()) == data\n assert list(unit._mapping.values()) == locs\n\n def test_update(self):\n data = ['a', 'd']\n locs = [0, 1]\n\n data_update = ['b', 'd', 'e']\n unique_data = ['a', 'd', 'b', 'e']\n updated_locs = [0, 1, 2, 3]\n\n unit = cat.UnitData(data)\n assert list(unit._mapping.keys()) == data\n assert list(unit._mapping.values()) == locs\n\n unit.update(data_update)\n assert list(unit._mapping.keys()) == unique_data\n assert list(unit._mapping.values()) == updated_locs\n\n failing_test_cases = [("number", 3.14), ("nan", np.nan),\n ("list", [3.14, 12]), ("mixed type", ["A", 2])]\n\n fids, fdata = zip(*test_cases)\n\n @pytest.mark.parametrize("fdata", fdata, ids=fids)\n def test_non_string_fails(self, fdata):\n with pytest.raises(TypeError):\n cat.UnitData(fdata)\n\n @pytest.mark.parametrize("fdata", fdata, ids=fids)\n def test_non_string_update_fails(self, fdata):\n unitdata = cat.UnitData()\n with pytest.raises(TypeError):\n unitdata.update(fdata)\n\n\nclass FakeAxis:\n def __init__(self, units):\n self.units = units\n\n\nclass TestStrCategoryConverter:\n """\n Based on the pandas conversion and factorization tests:\n\n ref: /pandas/tseries/tests/test_converter.py\n /pandas/tests/test_algos.py:TestFactorize\n """\n test_cases = [("unicode", ["Здравствуйте мир"]),\n ("ascii", ["hello world"]),\n ("single", ['a', 'b', 'c']),\n ("integer string", ["1", "2"]),\n ("single + values>10", ["A", "B", "C", "D", "E", "F", "G",\n "H", "I", "J", "K", "L", "M", "N",\n "O", "P", "Q", "R", "S", "T", "U",\n "V", "W", "X", "Y", "Z"])]\n\n ids, values = zip(*test_cases)\n\n failing_test_cases = [("mixed", [3.14, 'A', np.inf]),\n ("string integer", ['42', 42])]\n\n fids, fvalues = zip(*failing_test_cases)\n\n @pytest.fixture(autouse=True)\n def mock_axis(self, request):\n self.cc = cat.StrCategoryConverter()\n # self.unit should be probably be replaced with real mock unit\n self.unit = cat.UnitData()\n self.ax = FakeAxis(self.unit)\n\n @pytest.mark.parametrize("vals", values, ids=ids)\n def test_convert(self, vals):\n np.testing.assert_allclose(self.cc.convert(vals, self.ax.units,\n self.ax),\n range(len(vals)))\n\n @pytest.mark.parametrize("value", ["hi", "мир"], ids=["ascii", "unicode"])\n def test_convert_one_string(self, value):\n assert self.cc.convert(value, self.unit, self.ax) == 0\n\n @pytest.mark.parametrize("fvals", fvalues, ids=fids)\n def test_convert_fail(self, fvals):\n with pytest.raises(TypeError):\n self.cc.convert(fvals, self.unit, self.ax)\n\n def test_axisinfo(self):\n axis = self.cc.axisinfo(self.unit, self.ax)\n assert isinstance(axis.majloc, cat.StrCategoryLocator)\n assert isinstance(axis.majfmt, cat.StrCategoryFormatter)\n\n def test_default_units(self):\n assert isinstance(self.cc.default_units(["a"], self.ax), cat.UnitData)\n\n\nPLOT_LIST = [Axes.scatter, Axes.plot, Axes.bar]\nPLOT_IDS = ["scatter", "plot", "bar"]\n\n\nclass TestStrCategoryLocator:\n def test_StrCategoryLocator(self):\n locs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n unit = cat.UnitData([str(j) for j in locs])\n ticks = cat.StrCategoryLocator(unit._mapping)\n np.testing.assert_array_equal(ticks.tick_values(None, None), locs)\n\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n def test_StrCategoryLocatorPlot(self, plotter):\n ax = plt.figure().subplots()\n plotter(ax, [1, 2, 3], ["a", "b", "c"])\n np.testing.assert_array_equal(ax.yaxis.major.locator(), range(3))\n\n\nclass TestStrCategoryFormatter:\n test_cases = [("ascii", ["hello", "world", "hi"]),\n ("unicode", ["Здравствуйте", "привет"])]\n\n ids, cases = zip(*test_cases)\n\n @pytest.mark.parametrize("ydata", cases, ids=ids)\n def test_StrCategoryFormatter(self, ydata):\n unit = cat.UnitData(ydata)\n labels = cat.StrCategoryFormatter(unit._mapping)\n for i, d in enumerate(ydata):\n assert labels(i, i) == d\n assert labels(i, None) == d\n\n @pytest.mark.parametrize("ydata", cases, ids=ids)\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n def test_StrCategoryFormatterPlot(self, ydata, plotter):\n ax = plt.figure().subplots()\n plotter(ax, range(len(ydata)), ydata)\n for i, d in enumerate(ydata):\n assert ax.yaxis.major.formatter(i) == d\n assert ax.yaxis.major.formatter(i+1) == ""\n\n\ndef axis_test(axis, labels):\n ticks = list(range(len(labels)))\n np.testing.assert_array_equal(axis.get_majorticklocs(), ticks)\n graph_labels = [axis.major.formatter(i, i) for i in ticks]\n # _text also decodes bytes as utf-8.\n assert graph_labels == [cat.StrCategoryFormatter._text(l) for l in labels]\n assert list(axis.units._mapping.keys()) == [l for l in labels]\n assert list(axis.units._mapping.values()) == ticks\n\n\nclass TestPlotBytes:\n bytes_cases = [('string list', ['a', 'b', 'c']),\n ('bytes list', [b'a', b'b', b'c']),\n ('bytes ndarray', np.array([b'a', b'b', b'c']))]\n\n bytes_ids, bytes_data = zip(*bytes_cases)\n\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n @pytest.mark.parametrize("bdata", bytes_data, ids=bytes_ids)\n def test_plot_bytes(self, plotter, bdata):\n ax = plt.figure().subplots()\n counts = np.array([4, 6, 5])\n plotter(ax, bdata, counts)\n axis_test(ax.xaxis, bdata)\n\n\nclass TestPlotNumlike:\n numlike_cases = [('string list', ['1', '11', '3']),\n ('string ndarray', np.array(['1', '11', '3'])),\n ('bytes list', [b'1', b'11', b'3']),\n ('bytes ndarray', np.array([b'1', b'11', b'3']))]\n numlike_ids, numlike_data = zip(*numlike_cases)\n\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n @pytest.mark.parametrize("ndata", numlike_data, ids=numlike_ids)\n def test_plot_numlike(self, plotter, ndata):\n ax = plt.figure().subplots()\n counts = np.array([4, 6, 5])\n plotter(ax, ndata, counts)\n axis_test(ax.xaxis, ndata)\n\n\nclass TestPlotTypes:\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n def test_plot_unicode(self, plotter):\n ax = plt.figure().subplots()\n words = ['Здравствуйте', 'привет']\n plotter(ax, words, [0, 1])\n axis_test(ax.xaxis, words)\n\n @pytest.fixture\n def test_data(self):\n self.x = ["hello", "happy", "world"]\n self.xy = [2, 6, 3]\n self.y = ["Python", "is", "fun"]\n self.yx = [3, 4, 5]\n\n @pytest.mark.usefixtures("test_data")\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n def test_plot_xaxis(self, test_data, plotter):\n ax = plt.figure().subplots()\n plotter(ax, self.x, self.xy)\n axis_test(ax.xaxis, self.x)\n\n @pytest.mark.usefixtures("test_data")\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n def test_plot_yaxis(self, test_data, plotter):\n ax = plt.figure().subplots()\n plotter(ax, self.yx, self.y)\n axis_test(ax.yaxis, self.y)\n\n @pytest.mark.usefixtures("test_data")\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n def test_plot_xyaxis(self, test_data, plotter):\n ax = plt.figure().subplots()\n plotter(ax, self.x, self.y)\n axis_test(ax.xaxis, self.x)\n axis_test(ax.yaxis, self.y)\n\n @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS)\n def test_update_plot(self, plotter):\n ax = plt.figure().subplots()\n plotter(ax, ['a', 'b'], ['e', 'g'])\n plotter(ax, ['a', 'b', 'd'], ['f', 'a', 'b'])\n plotter(ax, ['b', 'c', 'd'], ['g', 'e', 'd'])\n axis_test(ax.xaxis, ['a', 'b', 'd', 'c'])\n axis_test(ax.yaxis, ['e', 'g', 'f', 'a', 'b', 'd'])\n\n def test_update_plot_heterogenous_plotter(self):\n ax = plt.figure().subplots()\n ax.scatter(['a', 'b'], ['e', 'g'])\n ax.plot(['a', 'b', 'd'], ['f', 'a', 'b'])\n ax.bar(['b', 'c', 'd'], ['g', 'e', 'd'])\n axis_test(ax.xaxis, ['a', 'b', 'd', 'c'])\n axis_test(ax.yaxis, ['e', 'g', 'f', 'a', 'b', 'd'])\n\n failing_test_cases = [("mixed", ['A', 3.14]),\n ("number integer", ['1', 1]),\n ("string integer", ['42', 42]),\n ("missing", ['12', np.nan])]\n\n fids, fvalues = zip(*failing_test_cases)\n\n plotters = [Axes.scatter, Axes.bar,\n pytest.param(Axes.plot, marks=pytest.mark.xfail)]\n\n @pytest.mark.parametrize("plotter", plotters)\n @pytest.mark.parametrize("xdata", fvalues, ids=fids)\n def test_mixed_type_exception(self, plotter, xdata):\n ax = plt.figure().subplots()\n with pytest.raises(TypeError):\n plotter(ax, xdata, [1, 2])\n\n @pytest.mark.parametrize("plotter", plotters)\n @pytest.mark.parametrize("xdata", fvalues, ids=fids)\n def test_mixed_type_update_exception(self, plotter, xdata):\n ax = plt.figure().subplots()\n with pytest.raises(TypeError):\n plotter(ax, [0, 3], [1, 3])\n plotter(ax, xdata, [1, 2])\n\n\n@mpl.style.context('default')\n@check_figures_equal(extensions=["png"])\ndef test_overriding_units_in_plot(fig_test, fig_ref):\n from datetime import datetime\n\n t0 = datetime(2018, 3, 1)\n t1 = datetime(2018, 3, 2)\n t2 = datetime(2018, 3, 3)\n t3 = datetime(2018, 3, 4)\n\n ax_test = fig_test.subplots()\n ax_ref = fig_ref.subplots()\n for ax, kwargs in zip([ax_test, ax_ref],\n ({}, dict(xunits=None, yunits=None))):\n # First call works\n ax.plot([t0, t1], ["V1", "V2"], **kwargs)\n x_units = ax.xaxis.units\n y_units = ax.yaxis.units\n # this should not raise\n ax.plot([t2, t3], ["V1", "V2"], **kwargs)\n # assert that we have not re-set the units attribute at all\n assert x_units is ax.xaxis.units\n assert y_units is ax.yaxis.units\n\n\ndef test_no_deprecation_on_empty_data():\n """\n Smoke test to check that no deprecation warning is emitted. See #22640.\n """\n f, ax = plt.subplots()\n ax.xaxis.update_units(["a", "b"])\n ax.plot([], [])\n\n\ndef test_hist():\n fig, ax = plt.subplots()\n n, bins, patches = ax.hist(['a', 'b', 'a', 'c', 'ff'])\n assert n.shape == (10,)\n np.testing.assert_allclose(n, [2., 0., 0., 1., 0., 0., 1., 0., 0., 1.])\n\n\ndef test_set_lim():\n # Numpy 1.25 deprecated casting [2.] to float, catch_warnings added to error\n # with numpy 1.25 and prior to the change from gh-26597\n # can be removed once the minimum numpy version has expired the warning\n f, ax = plt.subplots()\n ax.plot(["a", "b", "c", "d"], [1, 2, 3, 4])\n with warnings.catch_warnings():\n ax.set_xlim("b", "c")\n | .venv\Lib\site-packages\matplotlib\tests\test_category.py | test_category.py | Python | 12,043 | 0.95 | 0.141994 | 0.030534 | awesome-app | 143 | 2024-10-04T06:55:20.689206 | MIT | true | b3db82d0e181076f14518d1cef46a242 |
from __future__ import annotations\n\nimport itertools\nimport pathlib\nimport pickle\nimport sys\n\nfrom typing import Any\nfrom unittest.mock import patch, Mock\n\nfrom datetime import datetime, date, timedelta\n\nimport numpy as np\nfrom numpy.testing import (assert_array_equal, assert_approx_equal,\n assert_array_almost_equal)\nimport pytest\n\nfrom matplotlib import _api, cbook\nimport matplotlib.colors as mcolors\nfrom matplotlib.cbook import delete_masked_points, strip_math\nfrom types import ModuleType\n\n\nclass Test_delete_masked_points:\n def test_bad_first_arg(self):\n with pytest.raises(ValueError):\n delete_masked_points('a string', np.arange(1.0, 7.0))\n\n def test_string_seq(self):\n a1 = ['a', 'b', 'c', 'd', 'e', 'f']\n a2 = [1, 2, 3, np.nan, np.nan, 6]\n result1, result2 = delete_masked_points(a1, a2)\n ind = [0, 1, 2, 5]\n assert_array_equal(result1, np.array(a1)[ind])\n assert_array_equal(result2, np.array(a2)[ind])\n\n def test_datetime(self):\n dates = [datetime(2008, 1, 1), datetime(2008, 1, 2),\n datetime(2008, 1, 3), datetime(2008, 1, 4),\n datetime(2008, 1, 5), datetime(2008, 1, 6)]\n a_masked = np.ma.array([1, 2, 3, np.nan, np.nan, 6],\n mask=[False, False, True, True, False, False])\n actual = delete_masked_points(dates, a_masked)\n ind = [0, 1, 5]\n assert_array_equal(actual[0], np.array(dates)[ind])\n assert_array_equal(actual[1], a_masked[ind].compressed())\n\n def test_rgba(self):\n a_masked = np.ma.array([1, 2, 3, np.nan, np.nan, 6],\n mask=[False, False, True, True, False, False])\n a_rgba = mcolors.to_rgba_array(['r', 'g', 'b', 'c', 'm', 'y'])\n actual = delete_masked_points(a_masked, a_rgba)\n ind = [0, 1, 5]\n assert_array_equal(actual[0], a_masked[ind].compressed())\n assert_array_equal(actual[1], a_rgba[ind])\n\n\nclass Test_boxplot_stats:\n def setup_method(self):\n np.random.seed(937)\n self.nrows = 37\n self.ncols = 4\n self.data = np.random.lognormal(size=(self.nrows, self.ncols),\n mean=1.5, sigma=1.75)\n self.known_keys = sorted([\n 'mean', 'med', 'q1', 'q3', 'iqr',\n 'cilo', 'cihi', 'whislo', 'whishi',\n 'fliers', 'label'\n ])\n self.std_results = cbook.boxplot_stats(self.data)\n\n self.known_nonbootstrapped_res = {\n 'cihi': 6.8161283264444847,\n 'cilo': -0.1489815330368689,\n 'iqr': 13.492709959447094,\n 'mean': 13.00447442387868,\n 'med': 3.3335733967038079,\n 'fliers': np.array([\n 92.55467075, 87.03819018, 42.23204914, 39.29390996\n ]),\n 'q1': 1.3597529879465153,\n 'q3': 14.85246294739361,\n 'whishi': 27.899688243699629,\n 'whislo': 0.042143774965502923\n }\n\n self.known_bootstrapped_ci = {\n 'cihi': 8.939577523357828,\n 'cilo': 1.8692703958676578,\n }\n\n self.known_whis3_res = {\n 'whishi': 42.232049135969874,\n 'whislo': 0.042143774965502923,\n 'fliers': np.array([92.55467075, 87.03819018]),\n }\n\n self.known_res_percentiles = {\n 'whislo': 0.1933685896907924,\n 'whishi': 42.232049135969874\n }\n\n self.known_res_range = {\n 'whislo': 0.042143774965502923,\n 'whishi': 92.554670752188699\n\n }\n\n def test_form_main_list(self):\n assert isinstance(self.std_results, list)\n\n def test_form_each_dict(self):\n for res in self.std_results:\n assert isinstance(res, dict)\n\n def test_form_dict_keys(self):\n for res in self.std_results:\n assert set(res) <= set(self.known_keys)\n\n def test_results_baseline(self):\n res = self.std_results[0]\n for key, value in self.known_nonbootstrapped_res.items():\n assert_array_almost_equal(res[key], value)\n\n def test_results_bootstrapped(self):\n results = cbook.boxplot_stats(self.data, bootstrap=10000)\n res = results[0]\n for key, value in self.known_bootstrapped_ci.items():\n assert_approx_equal(res[key], value)\n\n def test_results_whiskers_float(self):\n results = cbook.boxplot_stats(self.data, whis=3)\n res = results[0]\n for key, value in self.known_whis3_res.items():\n assert_array_almost_equal(res[key], value)\n\n def test_results_whiskers_range(self):\n results = cbook.boxplot_stats(self.data, whis=[0, 100])\n res = results[0]\n for key, value in self.known_res_range.items():\n assert_array_almost_equal(res[key], value)\n\n def test_results_whiskers_percentiles(self):\n results = cbook.boxplot_stats(self.data, whis=[5, 95])\n res = results[0]\n for key, value in self.known_res_percentiles.items():\n assert_array_almost_equal(res[key], value)\n\n def test_results_withlabels(self):\n labels = ['Test1', 2, 'Aardvark', 4]\n results = cbook.boxplot_stats(self.data, labels=labels)\n for lab, res in zip(labels, results):\n assert res['label'] == lab\n\n results = cbook.boxplot_stats(self.data)\n for res in results:\n assert 'label' not in res\n\n def test_label_error(self):\n labels = [1, 2]\n with pytest.raises(ValueError):\n cbook.boxplot_stats(self.data, labels=labels)\n\n def test_bad_dims(self):\n data = np.random.normal(size=(34, 34, 34))\n with pytest.raises(ValueError):\n cbook.boxplot_stats(data)\n\n def test_boxplot_stats_autorange_false(self):\n x = np.zeros(shape=140)\n x = np.hstack([-25, x, 25])\n bstats_false = cbook.boxplot_stats(x, autorange=False)\n bstats_true = cbook.boxplot_stats(x, autorange=True)\n\n assert bstats_false[0]['whislo'] == 0\n assert bstats_false[0]['whishi'] == 0\n assert_array_almost_equal(bstats_false[0]['fliers'], [-25, 25])\n\n assert bstats_true[0]['whislo'] == -25\n assert bstats_true[0]['whishi'] == 25\n assert_array_almost_equal(bstats_true[0]['fliers'], [])\n\n\nclass Hashable:\n def dummy(self): pass\n\n\nclass Unhashable:\n __hash__ = None # type: ignore[assignment]\n def dummy(self): pass\n\n\nclass Test_callback_registry:\n def setup_method(self):\n self.signal = 'test'\n self.callbacks = cbook.CallbackRegistry()\n\n def connect(self, s, func, pickle):\n if pickle:\n return self.callbacks.connect(s, func)\n else:\n return self.callbacks._connect_picklable(s, func)\n\n def disconnect(self, cid):\n return self.callbacks.disconnect(cid)\n\n def count(self):\n count1 = sum(s == self.signal for s, p in self.callbacks._func_cid_map)\n count2 = len(self.callbacks.callbacks.get(self.signal))\n assert count1 == count2\n return count1\n\n def is_empty(self):\n np.testing.break_cycles()\n assert [*self.callbacks._func_cid_map] == []\n assert self.callbacks.callbacks == {}\n assert self.callbacks._pickled_cids == set()\n\n def is_not_empty(self):\n np.testing.break_cycles()\n assert [*self.callbacks._func_cid_map] != []\n assert self.callbacks.callbacks != {}\n\n def test_cid_restore(self):\n cb = cbook.CallbackRegistry()\n cb.connect('a', lambda: None)\n cb2 = pickle.loads(pickle.dumps(cb))\n cid = cb2.connect('c', lambda: None)\n assert cid == 1\n\n @pytest.mark.parametrize('pickle', [True, False])\n @pytest.mark.parametrize('cls', [Hashable, Unhashable])\n def test_callback_complete(self, pickle, cls):\n # ensure we start with an empty registry\n self.is_empty()\n\n # create a class for testing\n mini_me = cls()\n\n # test that we can add a callback\n cid1 = self.connect(self.signal, mini_me.dummy, pickle)\n assert type(cid1) is int\n self.is_not_empty()\n\n # test that we don't add a second callback\n cid2 = self.connect(self.signal, mini_me.dummy, pickle)\n assert cid1 == cid2\n self.is_not_empty()\n assert len([*self.callbacks._func_cid_map]) == 1\n assert len(self.callbacks.callbacks) == 1\n\n del mini_me\n\n # check we now have no callbacks registered\n self.is_empty()\n\n @pytest.mark.parametrize('pickle', [True, False])\n @pytest.mark.parametrize('cls', [Hashable, Unhashable])\n def test_callback_disconnect(self, pickle, cls):\n # ensure we start with an empty registry\n self.is_empty()\n\n # create a class for testing\n mini_me = cls()\n\n # test that we can add a callback\n cid1 = self.connect(self.signal, mini_me.dummy, pickle)\n assert type(cid1) is int\n self.is_not_empty()\n\n self.disconnect(cid1)\n\n # check we now have no callbacks registered\n self.is_empty()\n\n @pytest.mark.parametrize('pickle', [True, False])\n @pytest.mark.parametrize('cls', [Hashable, Unhashable])\n def test_callback_wrong_disconnect(self, pickle, cls):\n # ensure we start with an empty registry\n self.is_empty()\n\n # create a class for testing\n mini_me = cls()\n\n # test that we can add a callback\n cid1 = self.connect(self.signal, mini_me.dummy, pickle)\n assert type(cid1) is int\n self.is_not_empty()\n\n self.disconnect("foo")\n\n # check we still have callbacks registered\n self.is_not_empty()\n\n @pytest.mark.parametrize('pickle', [True, False])\n @pytest.mark.parametrize('cls', [Hashable, Unhashable])\n def test_registration_on_non_empty_registry(self, pickle, cls):\n # ensure we start with an empty registry\n self.is_empty()\n\n # setup the registry with a callback\n mini_me = cls()\n self.connect(self.signal, mini_me.dummy, pickle)\n\n # Add another callback\n mini_me2 = cls()\n self.connect(self.signal, mini_me2.dummy, pickle)\n\n # Remove and add the second callback\n mini_me2 = cls()\n self.connect(self.signal, mini_me2.dummy, pickle)\n\n # We still have 2 references\n self.is_not_empty()\n assert self.count() == 2\n\n # Removing the last 2 references\n mini_me = None\n mini_me2 = None\n self.is_empty()\n\n def test_pickling(self):\n assert hasattr(pickle.loads(pickle.dumps(cbook.CallbackRegistry())),\n "callbacks")\n\n\ndef test_callbackregistry_default_exception_handler(capsys, monkeypatch):\n cb = cbook.CallbackRegistry()\n cb.connect("foo", lambda: None)\n\n monkeypatch.setattr(\n cbook, "_get_running_interactive_framework", lambda: None)\n with pytest.raises(TypeError):\n cb.process("foo", "argument mismatch")\n outerr = capsys.readouterr()\n assert outerr.out == outerr.err == ""\n\n monkeypatch.setattr(\n cbook, "_get_running_interactive_framework", lambda: "not-none")\n cb.process("foo", "argument mismatch") # No error in that case.\n outerr = capsys.readouterr()\n assert outerr.out == ""\n assert "takes 0 positional arguments but 1 was given" in outerr.err\n\n\ndef raising_cb_reg(func):\n class TestException(Exception):\n pass\n\n def raise_runtime_error():\n raise RuntimeError\n\n def raise_value_error():\n raise ValueError\n\n def transformer(excp):\n if isinstance(excp, RuntimeError):\n raise TestException\n raise excp\n\n # old default\n cb_old = cbook.CallbackRegistry(exception_handler=None)\n cb_old.connect('foo', raise_runtime_error)\n\n # filter\n cb_filt = cbook.CallbackRegistry(exception_handler=transformer)\n cb_filt.connect('foo', raise_runtime_error)\n\n # filter\n cb_filt_pass = cbook.CallbackRegistry(exception_handler=transformer)\n cb_filt_pass.connect('foo', raise_value_error)\n\n return pytest.mark.parametrize('cb, excp',\n [[cb_old, RuntimeError],\n [cb_filt, TestException],\n [cb_filt_pass, ValueError]])(func)\n\n\n@raising_cb_reg\ndef test_callbackregistry_custom_exception_handler(monkeypatch, cb, excp):\n monkeypatch.setattr(\n cbook, "_get_running_interactive_framework", lambda: None)\n with pytest.raises(excp):\n cb.process('foo')\n\n\ndef test_callbackregistry_signals():\n cr = cbook.CallbackRegistry(signals=["foo"])\n results = []\n def cb(x): results.append(x)\n cr.connect("foo", cb)\n with pytest.raises(ValueError):\n cr.connect("bar", cb)\n cr.process("foo", 1)\n with pytest.raises(ValueError):\n cr.process("bar", 1)\n assert results == [1]\n\n\ndef test_callbackregistry_blocking():\n # Needs an exception handler for interactive testing environments\n # that would only print this out instead of raising the exception\n def raise_handler(excp):\n raise excp\n cb = cbook.CallbackRegistry(exception_handler=raise_handler)\n def test_func1():\n raise ValueError("1 should be blocked")\n def test_func2():\n raise ValueError("2 should be blocked")\n cb.connect("test1", test_func1)\n cb.connect("test2", test_func2)\n\n # block all of the callbacks to make sure they aren't processed\n with cb.blocked():\n cb.process("test1")\n cb.process("test2")\n\n # block individual callbacks to make sure the other is still processed\n with cb.blocked(signal="test1"):\n # Blocked\n cb.process("test1")\n # Should raise\n with pytest.raises(ValueError, match="2 should be blocked"):\n cb.process("test2")\n\n # Make sure the original callback functions are there after blocking\n with pytest.raises(ValueError, match="1 should be blocked"):\n cb.process("test1")\n with pytest.raises(ValueError, match="2 should be blocked"):\n cb.process("test2")\n\n\n@pytest.mark.parametrize('line, result', [\n ('a : no_comment', 'a : no_comment'),\n ('a : "quoted str"', 'a : "quoted str"'),\n ('a : "quoted str" # comment', 'a : "quoted str"'),\n ('a : "#000000"', 'a : "#000000"'),\n ('a : "#000000" # comment', 'a : "#000000"'),\n ('a : ["#000000", "#FFFFFF"]', 'a : ["#000000", "#FFFFFF"]'),\n ('a : ["#000000", "#FFFFFF"] # comment', 'a : ["#000000", "#FFFFFF"]'),\n ('a : val # a comment "with quotes"', 'a : val'),\n ('# only comment "with quotes" xx', ''),\n])\ndef test_strip_comment(line, result):\n """Strip everything from the first unquoted #."""\n assert cbook._strip_comment(line) == result\n\n\ndef test_strip_comment_invalid():\n with pytest.raises(ValueError, match="Missing closing quote"):\n cbook._strip_comment('grid.color: "aa')\n\n\ndef test_sanitize_sequence():\n d = {'a': 1, 'b': 2, 'c': 3}\n k = ['a', 'b', 'c']\n v = [1, 2, 3]\n i = [('a', 1), ('b', 2), ('c', 3)]\n assert k == sorted(cbook.sanitize_sequence(d.keys()))\n assert v == sorted(cbook.sanitize_sequence(d.values()))\n assert i == sorted(cbook.sanitize_sequence(d.items()))\n assert i == cbook.sanitize_sequence(i)\n assert k == cbook.sanitize_sequence(k)\n\n\nfail_mapping: tuple[tuple[dict, dict], ...] = (\n ({'a': 1, 'b': 2}, {'alias_mapping': {'a': ['b']}}),\n ({'a': 1, 'b': 2}, {'alias_mapping': {'a': ['a', 'b']}}),\n)\n\npass_mapping: tuple[tuple[Any, dict, dict], ...] = (\n (None, {}, {}),\n ({'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {}),\n ({'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}),\n)\n\n\n@pytest.mark.parametrize('inp, kwargs_to_norm', fail_mapping)\ndef test_normalize_kwargs_fail(inp, kwargs_to_norm):\n with pytest.raises(TypeError), _api.suppress_matplotlib_deprecation_warning():\n cbook.normalize_kwargs(inp, **kwargs_to_norm)\n\n\n@pytest.mark.parametrize('inp, expected, kwargs_to_norm',\n pass_mapping)\ndef test_normalize_kwargs_pass(inp, expected, kwargs_to_norm):\n with _api.suppress_matplotlib_deprecation_warning():\n # No other warning should be emitted.\n assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm)\n\n\ndef test_warn_external(recwarn):\n _api.warn_external("oops")\n assert len(recwarn) == 1\n if sys.version_info[:2] >= (3, 12):\n # With Python 3.12, we let Python figure out the stacklevel using the\n # `skip_file_prefixes` argument, which cannot exempt tests, so just confirm\n # the filename is not in the package.\n basedir = pathlib.Path(__file__).parents[2]\n assert not recwarn[0].filename.startswith((str(basedir / 'matplotlib'),\n str(basedir / 'mpl_toolkits')))\n else:\n # On older Python versions, we manually calculated the stacklevel, and had an\n # exception for our own tests.\n assert recwarn[0].filename == __file__\n\n\ndef test_warn_external_frame_embedded_python():\n with patch.object(cbook, "sys") as mock_sys:\n mock_sys._getframe = Mock(return_value=None)\n with pytest.warns(UserWarning, match=r"\Adummy\Z"):\n _api.warn_external("dummy")\n\n\ndef test_to_prestep():\n x = np.arange(4)\n y1 = np.arange(4)\n y2 = np.arange(4)[::-1]\n\n xs, y1s, y2s = cbook.pts_to_prestep(x, y1, y2)\n\n x_target = np.asarray([0, 0, 1, 1, 2, 2, 3], dtype=float)\n y1_target = np.asarray([0, 1, 1, 2, 2, 3, 3], dtype=float)\n y2_target = np.asarray([3, 2, 2, 1, 1, 0, 0], dtype=float)\n\n assert_array_equal(x_target, xs)\n assert_array_equal(y1_target, y1s)\n assert_array_equal(y2_target, y2s)\n\n xs, y1s = cbook.pts_to_prestep(x, y1)\n assert_array_equal(x_target, xs)\n assert_array_equal(y1_target, y1s)\n\n\ndef test_to_prestep_empty():\n steps = cbook.pts_to_prestep([], [])\n assert steps.shape == (2, 0)\n\n\ndef test_to_poststep():\n x = np.arange(4)\n y1 = np.arange(4)\n y2 = np.arange(4)[::-1]\n\n xs, y1s, y2s = cbook.pts_to_poststep(x, y1, y2)\n\n x_target = np.asarray([0, 1, 1, 2, 2, 3, 3], dtype=float)\n y1_target = np.asarray([0, 0, 1, 1, 2, 2, 3], dtype=float)\n y2_target = np.asarray([3, 3, 2, 2, 1, 1, 0], dtype=float)\n\n assert_array_equal(x_target, xs)\n assert_array_equal(y1_target, y1s)\n assert_array_equal(y2_target, y2s)\n\n xs, y1s = cbook.pts_to_poststep(x, y1)\n assert_array_equal(x_target, xs)\n assert_array_equal(y1_target, y1s)\n\n\ndef test_to_poststep_empty():\n steps = cbook.pts_to_poststep([], [])\n assert steps.shape == (2, 0)\n\n\ndef test_to_midstep():\n x = np.arange(4)\n y1 = np.arange(4)\n y2 = np.arange(4)[::-1]\n\n xs, y1s, y2s = cbook.pts_to_midstep(x, y1, y2)\n\n x_target = np.asarray([0, .5, .5, 1.5, 1.5, 2.5, 2.5, 3], dtype=float)\n y1_target = np.asarray([0, 0, 1, 1, 2, 2, 3, 3], dtype=float)\n y2_target = np.asarray([3, 3, 2, 2, 1, 1, 0, 0], dtype=float)\n\n assert_array_equal(x_target, xs)\n assert_array_equal(y1_target, y1s)\n assert_array_equal(y2_target, y2s)\n\n xs, y1s = cbook.pts_to_midstep(x, y1)\n assert_array_equal(x_target, xs)\n assert_array_equal(y1_target, y1s)\n\n\ndef test_to_midstep_empty():\n steps = cbook.pts_to_midstep([], [])\n assert steps.shape == (2, 0)\n\n\n@pytest.mark.parametrize(\n "args",\n [(np.arange(12).reshape(3, 4), 'a'),\n (np.arange(12), 'a'),\n (np.arange(12), np.arange(3))])\ndef test_step_fails(args):\n with pytest.raises(ValueError):\n cbook.pts_to_prestep(*args)\n\n\ndef test_grouper():\n class Dummy:\n pass\n a, b, c, d, e = objs = [Dummy() for _ in range(5)]\n g = cbook.Grouper()\n g.join(*objs)\n assert set(list(g)[0]) == set(objs)\n assert set(g.get_siblings(a)) == set(objs)\n\n for other in objs[1:]:\n assert g.joined(a, other)\n\n g.remove(a)\n for other in objs[1:]:\n assert not g.joined(a, other)\n\n for A, B in itertools.product(objs[1:], objs[1:]):\n assert g.joined(A, B)\n\n\ndef test_grouper_private():\n class Dummy:\n pass\n objs = [Dummy() for _ in range(5)]\n g = cbook.Grouper()\n g.join(*objs)\n # reach in and touch the internals !\n mapping = g._mapping\n\n for o in objs:\n assert o in mapping\n\n base_set = mapping[objs[0]]\n for o in objs[1:]:\n assert mapping[o] is base_set\n\n\ndef test_flatiter():\n x = np.arange(5)\n it = x.flat\n assert 0 == next(it)\n assert 1 == next(it)\n ret = cbook._safe_first_finite(it)\n assert ret == 0\n\n assert 0 == next(it)\n assert 1 == next(it)\n\n\ndef test__safe_first_finite_all_nan():\n arr = np.full(2, np.nan)\n ret = cbook._safe_first_finite(arr)\n assert np.isnan(ret)\n\n\ndef test__safe_first_finite_all_inf():\n arr = np.full(2, np.inf)\n ret = cbook._safe_first_finite(arr)\n assert np.isinf(ret)\n\n\ndef test_reshape2d():\n\n class Dummy:\n pass\n\n xnew = cbook._reshape_2D([], 'x')\n assert np.shape(xnew) == (1, 0)\n\n x = [Dummy() for _ in range(5)]\n\n xnew = cbook._reshape_2D(x, 'x')\n assert np.shape(xnew) == (1, 5)\n\n x = np.arange(5)\n xnew = cbook._reshape_2D(x, 'x')\n assert np.shape(xnew) == (1, 5)\n\n x = [[Dummy() for _ in range(5)] for _ in range(3)]\n xnew = cbook._reshape_2D(x, 'x')\n assert np.shape(xnew) == (3, 5)\n\n # this is strange behaviour, but...\n x = np.random.rand(3, 5)\n xnew = cbook._reshape_2D(x, 'x')\n assert np.shape(xnew) == (5, 3)\n\n # Test a list of lists which are all of length 1\n x = [[1], [2], [3]]\n xnew = cbook._reshape_2D(x, 'x')\n assert isinstance(xnew, list)\n assert isinstance(xnew[0], np.ndarray) and xnew[0].shape == (1,)\n assert isinstance(xnew[1], np.ndarray) and xnew[1].shape == (1,)\n assert isinstance(xnew[2], np.ndarray) and xnew[2].shape == (1,)\n\n # Test a list of zero-dimensional arrays\n x = [np.array(0), np.array(1), np.array(2)]\n xnew = cbook._reshape_2D(x, 'x')\n assert isinstance(xnew, list)\n assert len(xnew) == 1\n assert isinstance(xnew[0], np.ndarray) and xnew[0].shape == (3,)\n\n # Now test with a list of lists with different lengths, which means the\n # array will internally be converted to a 1D object array of lists\n x = [[1, 2, 3], [3, 4], [2]]\n xnew = cbook._reshape_2D(x, 'x')\n assert isinstance(xnew, list)\n assert isinstance(xnew[0], np.ndarray) and xnew[0].shape == (3,)\n assert isinstance(xnew[1], np.ndarray) and xnew[1].shape == (2,)\n assert isinstance(xnew[2], np.ndarray) and xnew[2].shape == (1,)\n\n # We now need to make sure that this works correctly for Numpy subclasses\n # where iterating over items can return subclasses too, which may be\n # iterable even if they are scalars. To emulate this, we make a Numpy\n # array subclass that returns Numpy 'scalars' when iterating or accessing\n # values, and these are technically iterable if checking for example\n # isinstance(x, collections.abc.Iterable).\n\n class ArraySubclass(np.ndarray):\n\n def __iter__(self):\n for value in super().__iter__():\n yield np.array(value)\n\n def __getitem__(self, item):\n return np.array(super().__getitem__(item))\n\n v = np.arange(10, dtype=float)\n x = ArraySubclass((10,), dtype=float, buffer=v.data)\n\n xnew = cbook._reshape_2D(x, 'x')\n\n # We check here that the array wasn't split up into many individual\n # ArraySubclass, which is what used to happen due to a bug in _reshape_2D\n assert len(xnew) == 1\n assert isinstance(xnew[0], ArraySubclass)\n\n # check list of strings:\n x = ['a', 'b', 'c', 'c', 'dd', 'e', 'f', 'ff', 'f']\n xnew = cbook._reshape_2D(x, 'x')\n assert len(xnew[0]) == len(x)\n assert isinstance(xnew[0], np.ndarray)\n\n\ndef test_reshape2d_pandas(pd):\n # separate to allow the rest of the tests to run if no pandas...\n X = np.arange(30).reshape(10, 3)\n x = pd.DataFrame(X, columns=["a", "b", "c"])\n Xnew = cbook._reshape_2D(x, 'x')\n # Need to check each row because _reshape_2D returns a list of arrays:\n for x, xnew in zip(X.T, Xnew):\n np.testing.assert_array_equal(x, xnew)\n\n\ndef test_reshape2d_xarray(xr):\n # separate to allow the rest of the tests to run if no xarray...\n X = np.arange(30).reshape(10, 3)\n x = xr.DataArray(X, dims=["x", "y"])\n Xnew = cbook._reshape_2D(x, 'x')\n # Need to check each row because _reshape_2D returns a list of arrays:\n for x, xnew in zip(X.T, Xnew):\n np.testing.assert_array_equal(x, xnew)\n\n\ndef test_index_of_pandas(pd):\n # separate to allow the rest of the tests to run if no pandas...\n X = np.arange(30).reshape(10, 3)\n x = pd.DataFrame(X, columns=["a", "b", "c"])\n Idx, Xnew = cbook.index_of(x)\n np.testing.assert_array_equal(X, Xnew)\n IdxRef = np.arange(10)\n np.testing.assert_array_equal(Idx, IdxRef)\n\n\ndef test_index_of_xarray(xr):\n # separate to allow the rest of the tests to run if no xarray...\n X = np.arange(30).reshape(10, 3)\n x = xr.DataArray(X, dims=["x", "y"])\n Idx, Xnew = cbook.index_of(x)\n np.testing.assert_array_equal(X, Xnew)\n IdxRef = np.arange(10)\n np.testing.assert_array_equal(Idx, IdxRef)\n\n\ndef test_contiguous_regions():\n a, b, c = 3, 4, 5\n # Starts and ends with True\n mask = [True]*a + [False]*b + [True]*c\n expected = [(0, a), (a+b, a+b+c)]\n assert cbook.contiguous_regions(mask) == expected\n d, e = 6, 7\n # Starts with True ends with False\n mask = mask + [False]*e\n assert cbook.contiguous_regions(mask) == expected\n # Starts with False ends with True\n mask = [False]*d + mask[:-e]\n expected = [(d, d+a), (d+a+b, d+a+b+c)]\n assert cbook.contiguous_regions(mask) == expected\n # Starts and ends with False\n mask = mask + [False]*e\n assert cbook.contiguous_regions(mask) == expected\n # No True in mask\n assert cbook.contiguous_regions([False]*5) == []\n # Empty mask\n assert cbook.contiguous_regions([]) == []\n\n\ndef test_safe_first_element_pandas_series(pd):\n # deliberately create a pandas series with index not starting from 0\n s = pd.Series(range(5), index=range(10, 15))\n actual = cbook._safe_first_finite(s)\n assert actual == 0\n\n\ndef test_array_patch_perimeters():\n # This compares the old implementation as a reference for the\n # vectorized one.\n def check(x, rstride, cstride):\n rows, cols = x.shape\n row_inds = [*range(0, rows-1, rstride), rows-1]\n col_inds = [*range(0, cols-1, cstride), cols-1]\n polys = []\n for rs, rs_next in itertools.pairwise(row_inds):\n for cs, cs_next in itertools.pairwise(col_inds):\n # +1 ensures we share edges between polygons\n ps = cbook._array_perimeter(x[rs:rs_next+1, cs:cs_next+1]).T\n polys.append(ps)\n polys = np.asarray(polys)\n assert np.array_equal(polys,\n cbook._array_patch_perimeters(\n x, rstride=rstride, cstride=cstride))\n\n def divisors(n):\n return [i for i in range(1, n + 1) if n % i == 0]\n\n for rows, cols in [(5, 5), (7, 14), (13, 9)]:\n x = np.arange(rows * cols).reshape(rows, cols)\n for rstride, cstride in itertools.product(divisors(rows - 1),\n divisors(cols - 1)):\n check(x, rstride=rstride, cstride=cstride)\n\n\ndef test_setattr_cm():\n class A:\n cls_level = object()\n override = object()\n\n def __init__(self):\n self.aardvark = 'aardvark'\n self.override = 'override'\n self._p = 'p'\n\n def meth(self):\n ...\n\n @classmethod\n def classy(cls):\n ...\n\n @staticmethod\n def static():\n ...\n\n @property\n def prop(self):\n return self._p\n\n @prop.setter\n def prop(self, val):\n self._p = val\n\n class B(A):\n ...\n\n other = A()\n\n def verify_pre_post_state(obj):\n # When you access a Python method the function is bound\n # to the object at access time so you get a new instance\n # of MethodType every time.\n #\n # https://docs.python.org/3/howto/descriptor.html#functions-and-methods\n assert obj.meth is not obj.meth\n # normal attribute should give you back the same instance every time\n assert obj.aardvark is obj.aardvark\n assert a.aardvark == 'aardvark'\n # and our property happens to give the same instance every time\n assert obj.prop is obj.prop\n assert obj.cls_level is A.cls_level\n assert obj.override == 'override'\n assert not hasattr(obj, 'extra')\n assert obj.prop == 'p'\n assert obj.monkey == other.meth\n assert obj.cls_level is A.cls_level\n assert 'cls_level' not in obj.__dict__\n assert 'classy' not in obj.__dict__\n assert 'static' not in obj.__dict__\n\n a = B()\n\n a.monkey = other.meth\n verify_pre_post_state(a)\n with cbook._setattr_cm(\n a, prop='squirrel',\n aardvark='moose', meth=lambda: None,\n override='boo', extra='extra',\n monkey=lambda: None, cls_level='bob',\n classy='classy', static='static'):\n # because we have set a lambda, it is normal attribute access\n # and the same every time\n assert a.meth is a.meth\n assert a.aardvark is a.aardvark\n assert a.aardvark == 'moose'\n assert a.override == 'boo'\n assert a.extra == 'extra'\n assert a.prop == 'squirrel'\n assert a.monkey != other.meth\n assert a.cls_level == 'bob'\n assert a.classy == 'classy'\n assert a.static == 'static'\n\n verify_pre_post_state(a)\n\n\ndef test_format_approx():\n f = cbook._format_approx\n assert f(0, 1) == '0'\n assert f(0, 2) == '0'\n assert f(0, 3) == '0'\n assert f(-0.0123, 1) == '-0'\n assert f(1e-7, 5) == '0'\n assert f(0.0012345600001, 5) == '0.00123'\n assert f(-0.0012345600001, 5) == '-0.00123'\n assert f(0.0012345600001, 8) == f(0.0012345600001, 10) == '0.00123456'\n\n\ndef test_safe_first_element_with_none():\n datetime_lst = [date.today() + timedelta(days=i) for i in range(10)]\n datetime_lst[0] = None\n actual = cbook._safe_first_finite(datetime_lst)\n assert actual is not None and actual == datetime_lst[1]\n\n\ndef test_strip_math():\n assert strip_math(r'1 \times 2') == r'1 \times 2'\n assert strip_math(r'$1 \times 2$') == '1 x 2'\n assert strip_math(r'$\rm{hi}$') == 'hi'\n\n\n@pytest.mark.parametrize('fmt, value, result', [\n ('%.2f m', 0.2, '0.20 m'),\n ('{:.2f} m', 0.2, '0.20 m'),\n ('{} m', 0.2, '0.2 m'),\n ('const', 0.2, 'const'),\n ('%d or {}', 0.2, '0 or {}'),\n ('{{{:,.0f}}}', 2e5, '{200,000}'),\n ('{:.2%}', 2/3, '66.67%'),\n ('$%g', 2.54, '$2.54'),\n])\ndef test_auto_format_str(fmt, value, result):\n """Apply *value* to the format string *fmt*."""\n assert cbook._auto_format_str(fmt, value) == result\n assert cbook._auto_format_str(fmt, np.float64(value)) == result\n\n\ndef test_unpack_to_numpy_from_torch():\n """\n Test that torch tensors are converted to NumPy arrays.\n\n We don't want to create a dependency on torch in the test suite, so we mock it.\n """\n class Tensor:\n def __init__(self, data):\n self.data = data\n\n def __array__(self):\n return self.data\n\n torch = ModuleType('torch')\n torch.Tensor = Tensor\n sys.modules['torch'] = torch\n\n data = np.arange(10)\n torch_tensor = torch.Tensor(data)\n\n result = cbook._unpack_to_numpy(torch_tensor)\n # compare results, do not check for identity: the latter would fail\n # if not mocked, and the implementation does not guarantee it\n # is the same Python object, just the same values.\n assert_array_equal(result, data)\n\n\ndef test_unpack_to_numpy_from_jax():\n """\n Test that jax arrays are converted to NumPy arrays.\n\n We don't want to create a dependency on jax in the test suite, so we mock it.\n """\n class Array:\n def __init__(self, data):\n self.data = data\n\n def __array__(self):\n return self.data\n\n jax = ModuleType('jax')\n jax.Array = Array\n\n sys.modules['jax'] = jax\n\n data = np.arange(10)\n jax_array = jax.Array(data)\n\n result = cbook._unpack_to_numpy(jax_array)\n # compare results, do not check for identity: the latter would fail\n # if not mocked, and the implementation does not guarantee it\n # is the same Python object, just the same values.\n assert_array_equal(result, data)\n\n\ndef test_unpack_to_numpy_from_tensorflow():\n """\n Test that tensorflow arrays are converted to NumPy arrays.\n\n We don't want to create a dependency on tensorflow in the test suite, so we mock it.\n """\n class Tensor:\n def __init__(self, data):\n self.data = data\n\n def __array__(self):\n return self.data\n\n tensorflow = ModuleType('tensorflow')\n tensorflow.is_tensor = lambda x: isinstance(x, Tensor)\n tensorflow.Tensor = Tensor\n\n sys.modules['tensorflow'] = tensorflow\n\n data = np.arange(10)\n tf_tensor = tensorflow.Tensor(data)\n\n result = cbook._unpack_to_numpy(tf_tensor)\n # compare results, do not check for identity: the latter would fail\n # if not mocked, and the implementation does not guarantee it\n # is the same Python object, just the same values.\n assert_array_equal(result, data)\n | .venv\Lib\site-packages\matplotlib\tests\test_cbook.py | test_cbook.py | Python | 33,530 | 0.95 | 0.159656 | 0.102941 | awesome-app | 389 | 2025-06-21T05:56:46.671965 | GPL-3.0 | true | e9e03a753b31e6a408bc777f89e8de52 |
from datetime import datetime\nimport io\nimport itertools\nimport platform\nimport re\nfrom types import SimpleNamespace\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nimport pytest\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.collections as mcollections\nimport matplotlib.colors as mcolors\nimport matplotlib.path as mpath\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.collections import (Collection, LineCollection,\n EventCollection, PolyCollection)\nfrom matplotlib.collections import FillBetweenPolyCollection\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\n\n\n@pytest.fixture(params=["pcolormesh", "pcolor"])\ndef pcfunc(request):\n return request.param\n\n\ndef generate_EventCollection_plot():\n """Generate the initial collection and plot it."""\n positions = np.array([0., 1., 2., 3., 5., 8., 13., 21.])\n extra_positions = np.array([34., 55., 89.])\n orientation = 'horizontal'\n lineoffset = 1\n linelength = .5\n linewidth = 2\n color = [1, 0, 0, 1]\n linestyle = 'solid'\n antialiased = True\n\n coll = EventCollection(positions,\n orientation=orientation,\n lineoffset=lineoffset,\n linelength=linelength,\n linewidth=linewidth,\n color=color,\n linestyle=linestyle,\n antialiased=antialiased\n )\n\n fig, ax = plt.subplots()\n ax.add_collection(coll)\n ax.set_title('EventCollection: default')\n props = {'positions': positions,\n 'extra_positions': extra_positions,\n 'orientation': orientation,\n 'lineoffset': lineoffset,\n 'linelength': linelength,\n 'linewidth': linewidth,\n 'color': color,\n 'linestyle': linestyle,\n 'antialiased': antialiased\n }\n ax.set_xlim(-1, 22)\n ax.set_ylim(0, 2)\n return ax, coll, props\n\n\n@image_comparison(['EventCollection_plot__default.png'])\ndef test__EventCollection__get_props():\n _, coll, props = generate_EventCollection_plot()\n # check that the default segments have the correct coordinates\n check_segments(coll,\n props['positions'],\n props['linelength'],\n props['lineoffset'],\n props['orientation'])\n # check that the default positions match the input positions\n np.testing.assert_array_equal(props['positions'], coll.get_positions())\n # check that the default orientation matches the input orientation\n assert props['orientation'] == coll.get_orientation()\n # check that the default orientation matches the input orientation\n assert coll.is_horizontal()\n # check that the default linelength matches the input linelength\n assert props['linelength'] == coll.get_linelength()\n # check that the default lineoffset matches the input lineoffset\n assert props['lineoffset'] == coll.get_lineoffset()\n # check that the default linestyle matches the input linestyle\n assert coll.get_linestyle() == [(0, None)]\n # check that the default color matches the input color\n for color in [coll.get_color(), *coll.get_colors()]:\n np.testing.assert_array_equal(color, props['color'])\n\n\n@image_comparison(['EventCollection_plot__set_positions.png'])\ndef test__EventCollection__set_positions():\n splt, coll, props = generate_EventCollection_plot()\n new_positions = np.hstack([props['positions'], props['extra_positions']])\n coll.set_positions(new_positions)\n np.testing.assert_array_equal(new_positions, coll.get_positions())\n check_segments(coll, new_positions,\n props['linelength'],\n props['lineoffset'],\n props['orientation'])\n splt.set_title('EventCollection: set_positions')\n splt.set_xlim(-1, 90)\n\n\n@image_comparison(['EventCollection_plot__add_positions.png'])\ndef test__EventCollection__add_positions():\n splt, coll, props = generate_EventCollection_plot()\n new_positions = np.hstack([props['positions'],\n props['extra_positions'][0]])\n coll.switch_orientation() # Test adding in the vertical orientation, too.\n coll.add_positions(props['extra_positions'][0])\n coll.switch_orientation()\n np.testing.assert_array_equal(new_positions, coll.get_positions())\n check_segments(coll,\n new_positions,\n props['linelength'],\n props['lineoffset'],\n props['orientation'])\n splt.set_title('EventCollection: add_positions')\n splt.set_xlim(-1, 35)\n\n\n@image_comparison(['EventCollection_plot__append_positions.png'])\ndef test__EventCollection__append_positions():\n splt, coll, props = generate_EventCollection_plot()\n new_positions = np.hstack([props['positions'],\n props['extra_positions'][2]])\n coll.append_positions(props['extra_positions'][2])\n np.testing.assert_array_equal(new_positions, coll.get_positions())\n check_segments(coll,\n new_positions,\n props['linelength'],\n props['lineoffset'],\n props['orientation'])\n splt.set_title('EventCollection: append_positions')\n splt.set_xlim(-1, 90)\n\n\n@image_comparison(['EventCollection_plot__extend_positions.png'])\ndef test__EventCollection__extend_positions():\n splt, coll, props = generate_EventCollection_plot()\n new_positions = np.hstack([props['positions'],\n props['extra_positions'][1:]])\n coll.extend_positions(props['extra_positions'][1:])\n np.testing.assert_array_equal(new_positions, coll.get_positions())\n check_segments(coll,\n new_positions,\n props['linelength'],\n props['lineoffset'],\n props['orientation'])\n splt.set_title('EventCollection: extend_positions')\n splt.set_xlim(-1, 90)\n\n\n@image_comparison(['EventCollection_plot__switch_orientation.png'])\ndef test__EventCollection__switch_orientation():\n splt, coll, props = generate_EventCollection_plot()\n new_orientation = 'vertical'\n coll.switch_orientation()\n assert new_orientation == coll.get_orientation()\n assert not coll.is_horizontal()\n new_positions = coll.get_positions()\n check_segments(coll,\n new_positions,\n props['linelength'],\n props['lineoffset'], new_orientation)\n splt.set_title('EventCollection: switch_orientation')\n splt.set_ylim(-1, 22)\n splt.set_xlim(0, 2)\n\n\n@image_comparison(['EventCollection_plot__switch_orientation__2x.png'])\ndef test__EventCollection__switch_orientation_2x():\n """\n Check that calling switch_orientation twice sets the orientation back to\n the default.\n """\n splt, coll, props = generate_EventCollection_plot()\n coll.switch_orientation()\n coll.switch_orientation()\n new_positions = coll.get_positions()\n assert props['orientation'] == coll.get_orientation()\n assert coll.is_horizontal()\n np.testing.assert_array_equal(props['positions'], new_positions)\n check_segments(coll,\n new_positions,\n props['linelength'],\n props['lineoffset'],\n props['orientation'])\n splt.set_title('EventCollection: switch_orientation 2x')\n\n\n@image_comparison(['EventCollection_plot__set_orientation.png'])\ndef test__EventCollection__set_orientation():\n splt, coll, props = generate_EventCollection_plot()\n new_orientation = 'vertical'\n coll.set_orientation(new_orientation)\n assert new_orientation == coll.get_orientation()\n assert not coll.is_horizontal()\n check_segments(coll,\n props['positions'],\n props['linelength'],\n props['lineoffset'],\n new_orientation)\n splt.set_title('EventCollection: set_orientation')\n splt.set_ylim(-1, 22)\n splt.set_xlim(0, 2)\n\n\n@image_comparison(['EventCollection_plot__set_linelength.png'])\ndef test__EventCollection__set_linelength():\n splt, coll, props = generate_EventCollection_plot()\n new_linelength = 15\n coll.set_linelength(new_linelength)\n assert new_linelength == coll.get_linelength()\n check_segments(coll,\n props['positions'],\n new_linelength,\n props['lineoffset'],\n props['orientation'])\n splt.set_title('EventCollection: set_linelength')\n splt.set_ylim(-20, 20)\n\n\n@image_comparison(['EventCollection_plot__set_lineoffset.png'])\ndef test__EventCollection__set_lineoffset():\n splt, coll, props = generate_EventCollection_plot()\n new_lineoffset = -5.\n coll.set_lineoffset(new_lineoffset)\n assert new_lineoffset == coll.get_lineoffset()\n check_segments(coll,\n props['positions'],\n props['linelength'],\n new_lineoffset,\n props['orientation'])\n splt.set_title('EventCollection: set_lineoffset')\n splt.set_ylim(-6, -4)\n\n\n@image_comparison([\n 'EventCollection_plot__set_linestyle.png',\n 'EventCollection_plot__set_linestyle.png',\n 'EventCollection_plot__set_linewidth.png',\n])\ndef test__EventCollection__set_prop():\n for prop, value, expected in [\n ('linestyle', 'dashed', [(0, (6.0, 6.0))]),\n ('linestyle', (0, (6., 6.)), [(0, (6.0, 6.0))]),\n ('linewidth', 5, 5),\n ]:\n splt, coll, _ = generate_EventCollection_plot()\n coll.set(**{prop: value})\n assert plt.getp(coll, prop) == expected\n splt.set_title(f'EventCollection: set_{prop}')\n\n\n@image_comparison(['EventCollection_plot__set_color.png'])\ndef test__EventCollection__set_color():\n splt, coll, _ = generate_EventCollection_plot()\n new_color = np.array([0, 1, 1, 1])\n coll.set_color(new_color)\n for color in [coll.get_color(), *coll.get_colors()]:\n np.testing.assert_array_equal(color, new_color)\n splt.set_title('EventCollection: set_color')\n\n\ndef check_segments(coll, positions, linelength, lineoffset, orientation):\n """\n Test helper checking that all values in the segment are correct, given a\n particular set of inputs.\n """\n segments = coll.get_segments()\n if (orientation.lower() == 'horizontal'\n or orientation.lower() == 'none' or orientation is None):\n # if horizontal, the position in is in the y-axis\n pos1 = 1\n pos2 = 0\n elif orientation.lower() == 'vertical':\n # if vertical, the position in is in the x-axis\n pos1 = 0\n pos2 = 1\n else:\n raise ValueError("orientation must be 'horizontal' or 'vertical'")\n\n # test to make sure each segment is correct\n for i, segment in enumerate(segments):\n assert segment[0, pos1] == lineoffset + linelength / 2\n assert segment[1, pos1] == lineoffset - linelength / 2\n assert segment[0, pos2] == positions[i]\n assert segment[1, pos2] == positions[i]\n\n\ndef test_collection_norm_autoscale():\n # norm should be autoscaled when array is set, not deferred to draw time\n lines = np.arange(24).reshape((4, 3, 2))\n coll = mcollections.LineCollection(lines, array=np.arange(4))\n assert coll.norm(2) == 2 / 3\n # setting a new array shouldn't update the already scaled limits\n coll.set_array(np.arange(4) + 5)\n assert coll.norm(2) == 2 / 3\n\n\ndef test_null_collection_datalim():\n col = mcollections.PathCollection([])\n col_data_lim = col.get_datalim(mtransforms.IdentityTransform())\n assert_array_equal(col_data_lim.get_points(),\n mtransforms.Bbox.null().get_points())\n\n\ndef test_no_offsets_datalim():\n # A collection with no offsets and a non transData\n # transform should return a null bbox\n ax = plt.axes()\n coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])])\n ax.add_collection(coll)\n coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform())\n assert_array_equal(coll_data_lim.get_points(),\n mtransforms.Bbox.null().get_points())\n\n\ndef test_add_collection():\n # Test if data limits are unchanged by adding an empty collection.\n # GitHub issue #1490, pull #1497.\n plt.figure()\n ax = plt.axes()\n ax.scatter([0, 1], [0, 1])\n bounds = ax.dataLim.bounds\n ax.scatter([], [])\n assert ax.dataLim.bounds == bounds\n\n\n@mpl.style.context('mpl20')\n@check_figures_equal(extensions=['png'])\ndef test_collection_log_datalim(fig_test, fig_ref):\n # Data limits should respect the minimum x/y when using log scale.\n x_vals = [4.38462e-6, 5.54929e-6, 7.02332e-6, 8.88889e-6, 1.12500e-5,\n 1.42383e-5, 1.80203e-5, 2.28070e-5, 2.88651e-5, 3.65324e-5,\n 4.62363e-5, 5.85178e-5, 7.40616e-5, 9.37342e-5, 1.18632e-4]\n y_vals = [0.0, 0.1, 0.182, 0.332, 0.604, 1.1, 2.0, 3.64, 6.64, 12.1, 22.0,\n 39.6, 71.3]\n\n x, y = np.meshgrid(x_vals, y_vals)\n x = x.flatten()\n y = y.flatten()\n\n ax_test = fig_test.subplots()\n ax_test.set_xscale('log')\n ax_test.set_yscale('log')\n ax_test.margins = 0\n ax_test.scatter(x, y)\n\n ax_ref = fig_ref.subplots()\n ax_ref.set_xscale('log')\n ax_ref.set_yscale('log')\n ax_ref.plot(x, y, marker="o", ls="")\n\n\ndef test_quiver_limits():\n ax = plt.axes()\n x, y = np.arange(8), np.arange(10)\n u = v = np.linspace(0, 10, 80).reshape(10, 8)\n q = plt.quiver(x, y, u, v)\n assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)\n\n plt.figure()\n ax = plt.axes()\n x = np.linspace(-5, 10, 20)\n y = np.linspace(-2, 4, 10)\n y, x = np.meshgrid(y, x)\n trans = mtransforms.Affine2D().translate(25, 32) + ax.transData\n plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)\n assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0)\n\n\ndef test_barb_limits():\n ax = plt.axes()\n x = np.linspace(-5, 10, 20)\n y = np.linspace(-2, 4, 10)\n y, x = np.meshgrid(y, x)\n trans = mtransforms.Affine2D().translate(25, 32) + ax.transData\n plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans)\n # The calculated bounds are approximately the bounds of the original data,\n # this is because the entire path is taken into account when updating the\n # datalim.\n assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6),\n decimal=1)\n\n\n@image_comparison(['EllipseCollection_test_image.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.021)\ndef test_EllipseCollection():\n # Test basic functionality\n fig, ax = plt.subplots()\n x = np.arange(4)\n y = np.arange(3)\n X, Y = np.meshgrid(x, y)\n XY = np.vstack((X.ravel(), Y.ravel())).T\n\n ww = X / x[-1]\n hh = Y / y[-1]\n aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis\n\n ec = mcollections.EllipseCollection(\n ww, hh, aa, units='x', offsets=XY, offset_transform=ax.transData,\n facecolors='none')\n ax.add_collection(ec)\n ax.autoscale_view()\n\n\ndef test_EllipseCollection_setter_getter():\n # Test widths, heights and angle setter\n rng = np.random.default_rng(0)\n\n widths = (2, )\n heights = (3, )\n angles = (45, )\n offsets = rng.random((10, 2)) * 10\n\n fig, ax = plt.subplots()\n\n ec = mcollections.EllipseCollection(\n widths=widths,\n heights=heights,\n angles=angles,\n offsets=offsets,\n units='x',\n offset_transform=ax.transData,\n )\n\n assert_array_almost_equal(ec._widths, np.array(widths).ravel() * 0.5)\n assert_array_almost_equal(ec._heights, np.array(heights).ravel() * 0.5)\n assert_array_almost_equal(ec._angles, np.deg2rad(angles).ravel())\n\n assert_array_almost_equal(ec.get_widths(), widths)\n assert_array_almost_equal(ec.get_heights(), heights)\n assert_array_almost_equal(ec.get_angles(), angles)\n\n ax.add_collection(ec)\n ax.set_xlim(-2, 12)\n ax.set_ylim(-2, 12)\n\n new_widths = rng.random((10, 2)) * 2\n new_heights = rng.random((10, 2)) * 3\n new_angles = rng.random((10, 2)) * 180\n\n ec.set(widths=new_widths, heights=new_heights, angles=new_angles)\n\n assert_array_almost_equal(ec.get_widths(), new_widths.ravel())\n assert_array_almost_equal(ec.get_heights(), new_heights.ravel())\n assert_array_almost_equal(ec.get_angles(), new_angles.ravel())\n\n\n@image_comparison(['polycollection_close.png'], remove_text=True, style='mpl20')\ndef test_polycollection_close():\n from mpl_toolkits.mplot3d import Axes3D # type: ignore[import]\n plt.rcParams['axes3d.automargin'] = True\n\n vertsQuad = [\n [[0., 0.], [0., 1.], [1., 1.], [1., 0.]],\n [[0., 1.], [2., 3.], [2., 2.], [1., 1.]],\n [[2., 2.], [2., 3.], [4., 1.], [3., 1.]],\n [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]]\n\n fig = plt.figure()\n ax = fig.add_axes(Axes3D(fig))\n\n colors = ['r', 'g', 'b', 'y', 'k']\n zpos = list(range(5))\n\n poly = mcollections.PolyCollection(\n vertsQuad * len(zpos), linewidth=0.25)\n poly.set_alpha(0.7)\n\n # need to have a z-value for *each* polygon = element!\n zs = []\n cs = []\n for z, c in zip(zpos, colors):\n zs.extend([z] * len(vertsQuad))\n cs.extend([c] * len(vertsQuad))\n\n poly.set_color(cs)\n\n ax.add_collection3d(poly, zs=zs, zdir='y')\n\n # axis limit settings:\n ax.set_xlim3d(0, 4)\n ax.set_zlim3d(0, 3)\n ax.set_ylim3d(0, 4)\n\n\n@image_comparison(['regularpolycollection_rotate.png'], remove_text=True)\ndef test_regularpolycollection_rotate():\n xx, yy = np.mgrid[:10, :10]\n xy_points = np.transpose([xx.flatten(), yy.flatten()])\n rotations = np.linspace(0, 2*np.pi, len(xy_points))\n\n fig, ax = plt.subplots()\n for xy, alpha in zip(xy_points, rotations):\n col = mcollections.RegularPolyCollection(\n 4, sizes=(100,), rotation=alpha,\n offsets=[xy], offset_transform=ax.transData)\n ax.add_collection(col, autolim=True)\n ax.autoscale_view()\n\n\n@image_comparison(['regularpolycollection_scale.png'], remove_text=True)\ndef test_regularpolycollection_scale():\n # See issue #3860\n\n class SquareCollection(mcollections.RegularPolyCollection):\n def __init__(self, **kwargs):\n super().__init__(4, rotation=np.pi/4., **kwargs)\n\n def get_transform(self):\n """Return transform scaling circle areas to data space."""\n ax = self.axes\n\n pts2pixels = 72.0 / ax.get_figure(root=True).dpi\n\n scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width\n scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height\n return mtransforms.Affine2D().scale(scale_x, scale_y)\n\n fig, ax = plt.subplots()\n\n xy = [(0, 0)]\n # Unit square has a half-diagonal of `1/sqrt(2)`, so `pi * r**2` equals...\n circle_areas = [np.pi / 2]\n squares = SquareCollection(\n sizes=circle_areas, offsets=xy, offset_transform=ax.transData)\n ax.add_collection(squares, autolim=True)\n ax.axis([-1, 1, -1, 1])\n\n\ndef test_picking():\n fig, ax = plt.subplots()\n col = ax.scatter([0], [0], [1000], picker=True)\n fig.savefig(io.BytesIO(), dpi=fig.dpi)\n mouse_event = SimpleNamespace(x=325, y=240)\n found, indices = col.contains(mouse_event)\n assert found\n assert_array_equal(indices['ind'], [0])\n\n\ndef test_quadmesh_contains():\n x = np.arange(4)\n X = x[:, None] * x[None, :]\n\n fig, ax = plt.subplots()\n mesh = ax.pcolormesh(X)\n fig.draw_without_rendering()\n xdata, ydata = 0.5, 0.5\n x, y = mesh.get_transform().transform((xdata, ydata))\n mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)\n found, indices = mesh.contains(mouse_event)\n assert found\n assert_array_equal(indices['ind'], [0])\n\n xdata, ydata = 1.5, 1.5\n x, y = mesh.get_transform().transform((xdata, ydata))\n mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)\n found, indices = mesh.contains(mouse_event)\n assert found\n assert_array_equal(indices['ind'], [5])\n\n\ndef test_quadmesh_contains_concave():\n # Test a concave polygon, V-like shape\n x = [[0, -1], [1, 0]]\n y = [[0, 1], [1, -1]]\n fig, ax = plt.subplots()\n mesh = ax.pcolormesh(x, y, [[0]])\n fig.draw_without_rendering()\n # xdata, ydata, expected\n points = [(-0.5, 0.25, True), # left wing\n (0, 0.25, False), # between the two wings\n (0.5, 0.25, True), # right wing\n (0, -0.25, True), # main body\n ]\n for point in points:\n xdata, ydata, expected = point\n x, y = mesh.get_transform().transform((xdata, ydata))\n mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)\n found, indices = mesh.contains(mouse_event)\n assert found is expected\n\n\ndef test_quadmesh_cursor_data():\n x = np.arange(4)\n X = x[:, None] * x[None, :]\n\n fig, ax = plt.subplots()\n mesh = ax.pcolormesh(X)\n # Empty array data\n mesh._A = None\n fig.draw_without_rendering()\n xdata, ydata = 0.5, 0.5\n x, y = mesh.get_transform().transform((xdata, ydata))\n mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)\n # Empty collection should return None\n assert mesh.get_cursor_data(mouse_event) is None\n\n # Now test adding the array data, to make sure we do get a value\n mesh.set_array(np.ones(X.shape))\n assert_array_equal(mesh.get_cursor_data(mouse_event), [1])\n\n\ndef test_quadmesh_cursor_data_multiple_points():\n x = [1, 2, 1, 2]\n fig, ax = plt.subplots()\n mesh = ax.pcolormesh(x, x, np.ones((3, 3)))\n fig.draw_without_rendering()\n xdata, ydata = 1.5, 1.5\n x, y = mesh.get_transform().transform((xdata, ydata))\n mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)\n # All quads are covering the same square\n assert_array_equal(mesh.get_cursor_data(mouse_event), np.ones(9))\n\n\ndef test_linestyle_single_dashes():\n plt.scatter([0, 1, 2], [0, 1, 2], linestyle=(0., [2., 2.]))\n plt.draw()\n\n\n@image_comparison(['size_in_xy.png'], remove_text=True)\ndef test_size_in_xy():\n fig, ax = plt.subplots()\n\n widths, heights, angles = (10, 10), 10, 0\n widths = 10, 10\n coords = [(10, 10), (15, 15)]\n e = mcollections.EllipseCollection(\n widths, heights, angles, units='xy',\n offsets=coords, offset_transform=ax.transData)\n\n ax.add_collection(e)\n\n ax.set_xlim(0, 30)\n ax.set_ylim(0, 30)\n\n\ndef test_pandas_indexing(pd):\n\n # Should not fail break when faced with a\n # non-zero indexed series\n index = [11, 12, 13]\n ec = fc = pd.Series(['red', 'blue', 'green'], index=index)\n lw = pd.Series([1, 2, 3], index=index)\n ls = pd.Series(['solid', 'dashed', 'dashdot'], index=index)\n aa = pd.Series([True, False, True], index=index)\n\n Collection(edgecolors=ec)\n Collection(facecolors=fc)\n Collection(linewidths=lw)\n Collection(linestyles=ls)\n Collection(antialiaseds=aa)\n\n\n@mpl.style.context('default')\ndef test_lslw_bcast():\n col = mcollections.PathCollection([])\n col.set_linestyles(['-', '-'])\n col.set_linewidths([1, 2, 3])\n\n assert col.get_linestyles() == [(0, None)] * 6\n assert col.get_linewidths() == [1, 2, 3] * 2\n\n col.set_linestyles(['-', '-', '-'])\n assert col.get_linestyles() == [(0, None)] * 3\n assert (col.get_linewidths() == [1, 2, 3]).all()\n\n\ndef test_set_wrong_linestyle():\n c = Collection()\n with pytest.raises(ValueError, match="Do not know how to convert 'fuzzy'"):\n c.set_linestyle('fuzzy')\n\n\n@mpl.style.context('default')\ndef test_capstyle():\n col = mcollections.PathCollection([])\n assert col.get_capstyle() is None\n col = mcollections.PathCollection([], capstyle='round')\n assert col.get_capstyle() == 'round'\n col.set_capstyle('butt')\n assert col.get_capstyle() == 'butt'\n\n\n@mpl.style.context('default')\ndef test_joinstyle():\n col = mcollections.PathCollection([])\n assert col.get_joinstyle() is None\n col = mcollections.PathCollection([], joinstyle='round')\n assert col.get_joinstyle() == 'round'\n col.set_joinstyle('miter')\n assert col.get_joinstyle() == 'miter'\n\n\n@image_comparison(['cap_and_joinstyle.png'])\ndef test_cap_and_joinstyle_image():\n fig, ax = plt.subplots()\n ax.set_xlim([-0.5, 1.5])\n ax.set_ylim([-0.5, 2.5])\n\n x = np.array([0.0, 1.0, 0.5])\n ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]])\n\n segs = np.zeros((3, 3, 2))\n segs[:, :, 0] = x\n segs[:, :, 1] = ys\n line_segments = LineCollection(segs, linewidth=[10, 15, 20])\n line_segments.set_capstyle("round")\n line_segments.set_joinstyle("miter")\n\n ax.add_collection(line_segments)\n ax.set_title('Line collection with customized caps and joinstyle')\n\n\n@image_comparison(['scatter_post_alpha.png'],\n remove_text=True, style='default')\ndef test_scatter_post_alpha():\n fig, ax = plt.subplots()\n sc = ax.scatter(range(5), range(5), c=range(5))\n sc.set_alpha(.1)\n\n\ndef test_scatter_alpha_array():\n x = np.arange(5)\n alpha = x / 5\n # With colormapping.\n fig, (ax0, ax1) = plt.subplots(2)\n sc0 = ax0.scatter(x, x, c=x, alpha=alpha)\n sc1 = ax1.scatter(x, x, c=x)\n sc1.set_alpha(alpha)\n plt.draw()\n assert_array_equal(sc0.get_facecolors()[:, -1], alpha)\n assert_array_equal(sc1.get_facecolors()[:, -1], alpha)\n # Without colormapping.\n fig, (ax0, ax1) = plt.subplots(2)\n sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'], alpha=alpha)\n sc1 = ax1.scatter(x, x, color='r', alpha=alpha)\n plt.draw()\n assert_array_equal(sc0.get_facecolors()[:, -1], alpha)\n assert_array_equal(sc1.get_facecolors()[:, -1], alpha)\n # Without colormapping, and set alpha afterward.\n fig, (ax0, ax1) = plt.subplots(2)\n sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'])\n sc0.set_alpha(alpha)\n sc1 = ax1.scatter(x, x, color='r')\n sc1.set_alpha(alpha)\n plt.draw()\n assert_array_equal(sc0.get_facecolors()[:, -1], alpha)\n assert_array_equal(sc1.get_facecolors()[:, -1], alpha)\n\n\ndef test_pathcollection_legend_elements():\n np.random.seed(19680801)\n x, y = np.random.rand(2, 10)\n y = np.random.rand(10)\n c = np.random.randint(0, 5, size=10)\n s = np.random.randint(10, 300, size=10)\n\n fig, ax = plt.subplots()\n sc = ax.scatter(x, y, c=c, s=s, cmap="jet", marker="o", linewidths=0)\n\n h, l = sc.legend_elements(fmt="{x:g}")\n assert len(h) == 5\n assert l == ["0", "1", "2", "3", "4"]\n colors = np.array([line.get_color() for line in h])\n colors2 = sc.cmap(np.arange(5)/4)\n assert_array_equal(colors, colors2)\n l1 = ax.legend(h, l, loc=1)\n\n h2, lab2 = sc.legend_elements(num=9)\n assert len(h2) == 9\n l2 = ax.legend(h2, lab2, loc=2)\n\n h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red")\n assert all(line.get_alpha() == 0.5 for line in h)\n assert all(line.get_markerfacecolor() == "red" for line in h)\n l3 = ax.legend(h, l, loc=4)\n\n h, l = sc.legend_elements(prop="sizes", num=4, fmt="{x:.2f}",\n func=lambda x: 2*x)\n actsizes = [line.get_markersize() for line in h]\n labeledsizes = np.sqrt(np.array(l, float) / 2)\n assert_array_almost_equal(actsizes, labeledsizes)\n l4 = ax.legend(h, l, loc=3)\n\n loc = mpl.ticker.MaxNLocator(nbins=9, min_n_ticks=9-1,\n steps=[1, 2, 2.5, 3, 5, 6, 8, 10])\n h5, lab5 = sc.legend_elements(num=loc)\n assert len(h2) == len(h5)\n\n levels = [-1, 0, 55.4, 260]\n h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}")\n assert [float(l) for l in lab6] == levels[2:]\n\n for l in [l1, l2, l3, l4]:\n ax.add_artist(l)\n\n fig.canvas.draw()\n\n\ndef test_EventCollection_nosort():\n # Check that EventCollection doesn't modify input in place\n arr = np.array([3, 2, 1, 10])\n coll = EventCollection(arr)\n np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10]))\n\n\ndef test_collection_set_verts_array():\n verts = np.arange(80, dtype=np.double).reshape(10, 4, 2)\n col_arr = PolyCollection(verts)\n col_list = PolyCollection(list(verts))\n assert len(col_arr._paths) == len(col_list._paths)\n for ap, lp in zip(col_arr._paths, col_list._paths):\n assert np.array_equal(ap._vertices, lp._vertices)\n assert np.array_equal(ap._codes, lp._codes)\n\n verts_tuple = np.empty(10, dtype=object)\n verts_tuple[:] = [tuple(tuple(y) for y in x) for x in verts]\n col_arr_tuple = PolyCollection(verts_tuple)\n assert len(col_arr._paths) == len(col_arr_tuple._paths)\n for ap, atp in zip(col_arr._paths, col_arr_tuple._paths):\n assert np.array_equal(ap._vertices, atp._vertices)\n assert np.array_equal(ap._codes, atp._codes)\n\n\n@check_figures_equal(extensions=["png"])\n@pytest.mark.parametrize("kwargs", [{}, {"step": "pre"}])\ndef test_fill_between_poly_collection_set_data(fig_test, fig_ref, kwargs):\n t = np.linspace(0, 16)\n f1 = np.sin(t)\n f2 = f1 + 0.2\n\n fig_ref.subplots().fill_between(t, f1, f2, **kwargs)\n\n coll = fig_test.subplots().fill_between(t, -1, 1.2, **kwargs)\n coll.set_data(t, f1, f2)\n\n\n@pytest.mark.parametrize(("t_direction", "f1", "shape", "where", "msg"), [\n ("z", None, None, None, r"t_direction must be 'x' or 'y', got 'z'"),\n ("x", None, (-1, 1), None, r"'x' is not 1-dimensional"),\n ("x", None, None, [False] * 3, r"where size \(3\) does not match 'x' size \(\d+\)"),\n ("y", [1, 2], None, None, r"'y' has size \d+, but 'x1' has an unequal size of \d+"),\n])\ndef test_fill_between_poly_collection_raise(t_direction, f1, shape, where, msg):\n t = np.linspace(0, 16)\n f1 = np.sin(t) if f1 is None else np.asarray(f1)\n f2 = f1 + 0.2\n if shape:\n t = t.reshape(*shape)\n with pytest.raises(ValueError, match=msg):\n FillBetweenPolyCollection(t_direction, t, f1, f2, where=where)\n\n\ndef test_collection_set_array():\n vals = [*range(10)]\n\n # Test set_array with list\n c = Collection()\n c.set_array(vals)\n\n # Test set_array with wrong dtype\n with pytest.raises(TypeError, match="^Image data of dtype"):\n c.set_array("wrong_input")\n\n # Test if array kwarg is copied\n vals[5] = 45\n assert np.not_equal(vals, c.get_array()).any()\n\n\ndef test_blended_collection_autolim():\n a = [1, 2, 4]\n height = .2\n\n xy_pairs = np.column_stack([np.repeat(a, 2), np.tile([0, height], len(a))])\n line_segs = xy_pairs.reshape([len(a), 2, 2])\n\n f, ax = plt.subplots()\n trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)\n ax.add_collection(LineCollection(line_segs, transform=trans))\n ax.autoscale_view(scalex=True, scaley=False)\n np.testing.assert_allclose(ax.get_xlim(), [1., 4.])\n\n\ndef test_singleton_autolim():\n fig, ax = plt.subplots()\n ax.scatter(0, 0)\n np.testing.assert_allclose(ax.get_ylim(), [-0.06, 0.06])\n np.testing.assert_allclose(ax.get_xlim(), [-0.06, 0.06])\n\n\n@pytest.mark.parametrize("transform, expected", [\n ("transData", (-0.5, 3.5)),\n ("transAxes", (2.8, 3.2)),\n])\ndef test_autolim_with_zeros(transform, expected):\n # 1) Test that a scatter at (0, 0) data coordinates contributes to\n # autoscaling even though any(offsets) would be False in that situation.\n # 2) Test that specifying transAxes for the transform does not contribute\n # to the autoscaling.\n fig, ax = plt.subplots()\n ax.scatter(0, 0, transform=getattr(ax, transform))\n ax.scatter(3, 3)\n np.testing.assert_allclose(ax.get_ylim(), expected)\n np.testing.assert_allclose(ax.get_xlim(), expected)\n\n\ndef test_quadmesh_set_array_validation(pcfunc):\n x = np.arange(11)\n y = np.arange(8)\n z = np.random.random((7, 10))\n fig, ax = plt.subplots()\n coll = getattr(ax, pcfunc)(x, y, z)\n\n with pytest.raises(ValueError, match=re.escape(\n "For X (11) and Y (8) with flat shading, A should have shape "\n "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (10, 7)")):\n coll.set_array(z.reshape(10, 7))\n\n z = np.arange(54).reshape((6, 9))\n with pytest.raises(ValueError, match=re.escape(\n "For X (11) and Y (8) with flat shading, A should have shape "\n "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (6, 9)")):\n coll.set_array(z)\n with pytest.raises(ValueError, match=re.escape(\n "For X (11) and Y (8) with flat shading, A should have shape "\n "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (54,)")):\n coll.set_array(z.ravel())\n\n # RGB(A) tests\n z = np.ones((9, 6, 3)) # RGB with wrong X/Y dims\n with pytest.raises(ValueError, match=re.escape(\n "For X (11) and Y (8) with flat shading, A should have shape "\n "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 3)")):\n coll.set_array(z)\n\n z = np.ones((9, 6, 4)) # RGBA with wrong X/Y dims\n with pytest.raises(ValueError, match=re.escape(\n "For X (11) and Y (8) with flat shading, A should have shape "\n "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 4)")):\n coll.set_array(z)\n\n z = np.ones((7, 10, 2)) # Right X/Y dims, bad 3rd dim\n with pytest.raises(ValueError, match=re.escape(\n "For X (11) and Y (8) with flat shading, A should have shape "\n "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (7, 10, 2)")):\n coll.set_array(z)\n\n x = np.arange(10)\n y = np.arange(7)\n z = np.random.random((7, 10))\n fig, ax = plt.subplots()\n coll = ax.pcolormesh(x, y, z, shading='gouraud')\n\n\ndef test_polyquadmesh_masked_vertices_array():\n xx, yy = np.meshgrid([0, 1, 2], [0, 1, 2, 3])\n # 2 x 3 mesh data\n zz = (xx*yy)[:-1, :-1]\n quadmesh = plt.pcolormesh(xx, yy, zz)\n quadmesh.update_scalarmappable()\n quadmesh_fc = quadmesh.get_facecolor()[1:, :]\n # Mask the origin vertex in x\n xx = np.ma.masked_where((xx == 0) & (yy == 0), xx)\n polymesh = plt.pcolor(xx, yy, zz)\n polymesh.update_scalarmappable()\n # One cell should be left out\n assert len(polymesh.get_paths()) == 5\n # Poly version should have the same facecolors as the end of the quadmesh\n assert_array_equal(quadmesh_fc, polymesh.get_facecolor())\n\n # Mask the origin vertex in y\n yy = np.ma.masked_where((xx == 0) & (yy == 0), yy)\n polymesh = plt.pcolor(xx, yy, zz)\n polymesh.update_scalarmappable()\n # One cell should be left out\n assert len(polymesh.get_paths()) == 5\n # Poly version should have the same facecolors as the end of the quadmesh\n assert_array_equal(quadmesh_fc, polymesh.get_facecolor())\n\n # Mask the origin cell data\n zz = np.ma.masked_where((xx[:-1, :-1] == 0) & (yy[:-1, :-1] == 0), zz)\n polymesh = plt.pcolor(zz)\n polymesh.update_scalarmappable()\n # One cell should be left out\n assert len(polymesh.get_paths()) == 5\n # Poly version should have the same facecolors as the end of the quadmesh\n assert_array_equal(quadmesh_fc, polymesh.get_facecolor())\n\n # We should also be able to call set_array with a new mask and get\n # updated polys\n # Remove mask, should add all polys back\n zz = np.arange(6).reshape((3, 2))\n polymesh.set_array(zz)\n polymesh.update_scalarmappable()\n assert len(polymesh.get_paths()) == 6\n # Add mask should remove polys\n zz = np.ma.masked_less(zz, 2)\n polymesh.set_array(zz)\n polymesh.update_scalarmappable()\n assert len(polymesh.get_paths()) == 4\n\n\ndef test_quadmesh_get_coordinates(pcfunc):\n x = [0, 1, 2]\n y = [2, 4, 6]\n z = np.ones(shape=(2, 2))\n xx, yy = np.meshgrid(x, y)\n coll = getattr(plt, pcfunc)(xx, yy, z)\n\n # shape (3, 3, 2)\n coords = np.stack([xx.T, yy.T]).T\n assert_array_equal(coll.get_coordinates(), coords)\n\n\ndef test_quadmesh_set_array():\n x = np.arange(4)\n y = np.arange(4)\n z = np.arange(9).reshape((3, 3))\n fig, ax = plt.subplots()\n coll = ax.pcolormesh(x, y, np.ones(z.shape))\n # Test that the collection is able to update with a 2d array\n coll.set_array(z)\n fig.canvas.draw()\n assert np.array_equal(coll.get_array(), z)\n\n # Check that pre-flattened arrays work too\n coll.set_array(np.ones(9))\n fig.canvas.draw()\n assert np.array_equal(coll.get_array(), np.ones(9))\n\n z = np.arange(16).reshape((4, 4))\n fig, ax = plt.subplots()\n coll = ax.pcolormesh(x, y, np.ones(z.shape), shading='gouraud')\n # Test that the collection is able to update with a 2d array\n coll.set_array(z)\n fig.canvas.draw()\n assert np.array_equal(coll.get_array(), z)\n\n # Check that pre-flattened arrays work too\n coll.set_array(np.ones(16))\n fig.canvas.draw()\n assert np.array_equal(coll.get_array(), np.ones(16))\n\n\ndef test_quadmesh_vmin_vmax(pcfunc):\n # test when vmin/vmax on the norm changes, the quadmesh gets updated\n fig, ax = plt.subplots()\n cmap = mpl.colormaps['plasma']\n norm = mpl.colors.Normalize(vmin=0, vmax=1)\n coll = getattr(ax, pcfunc)([[1]], cmap=cmap, norm=norm)\n fig.canvas.draw()\n assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1)))\n\n # Change the vmin/vmax of the norm so that the color is from\n # the bottom of the colormap now\n norm.vmin, norm.vmax = 1, 2\n fig.canvas.draw()\n assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1)))\n\n\ndef test_quadmesh_alpha_array(pcfunc):\n x = np.arange(4)\n y = np.arange(4)\n z = np.arange(9).reshape((3, 3))\n alpha = z / z.max()\n alpha_flat = alpha.ravel()\n # Provide 2-D alpha:\n fig, (ax0, ax1) = plt.subplots(2)\n coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha)\n coll2 = getattr(ax0, pcfunc)(x, y, z)\n coll2.set_alpha(alpha)\n plt.draw()\n assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat)\n assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat)\n # Or provide 1-D alpha:\n fig, (ax0, ax1) = plt.subplots(2)\n coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha)\n coll2 = getattr(ax1, pcfunc)(x, y, z)\n coll2.set_alpha(alpha)\n plt.draw()\n assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat)\n assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat)\n\n\ndef test_alpha_validation(pcfunc):\n # Most of the relevant testing is in test_artist and test_colors.\n fig, ax = plt.subplots()\n pc = getattr(ax, pcfunc)(np.arange(12).reshape((3, 4)))\n with pytest.raises(ValueError, match="^Data array shape"):\n pc.set_alpha([0.5, 0.6])\n pc.update_scalarmappable()\n\n\ndef test_legend_inverse_size_label_relationship():\n """\n Ensure legend markers scale appropriately when label and size are\n inversely related.\n Here label = 5 / size\n """\n\n np.random.seed(19680801)\n X = np.random.random(50)\n Y = np.random.random(50)\n C = 1 - np.random.random(50)\n S = 5 / C\n\n legend_sizes = [0.2, 0.4, 0.6, 0.8]\n fig, ax = plt.subplots()\n sc = ax.scatter(X, Y, s=S)\n handles, labels = sc.legend_elements(\n prop='sizes', num=legend_sizes, func=lambda s: 5 / s\n )\n\n # Convert markersize scale to 's' scale\n handle_sizes = [x.get_markersize() for x in handles]\n handle_sizes = [5 / x**2 for x in handle_sizes]\n\n assert_array_almost_equal(handle_sizes, legend_sizes, decimal=1)\n\n\n@mpl.style.context('default')\ndef test_color_logic(pcfunc):\n pcfunc = getattr(plt, pcfunc)\n z = np.arange(12).reshape(3, 4)\n # Explicitly set an edgecolor.\n pc = pcfunc(z, edgecolors='red', facecolors='none')\n pc.update_scalarmappable() # This is called in draw().\n # Define 2 reference "colors" here for multiple use.\n face_default = mcolors.to_rgba_array(pc._get_default_facecolor())\n mapped = pc.get_cmap()(pc.norm(z.ravel()))\n # GitHub issue #1302:\n assert mcolors.same_color(pc.get_edgecolor(), 'red')\n # Check setting attributes after initialization:\n pc = pcfunc(z)\n pc.set_facecolor('none')\n pc.set_edgecolor('red')\n pc.update_scalarmappable()\n assert mcolors.same_color(pc.get_facecolor(), 'none')\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])\n pc.set_alpha(0.5)\n pc.update_scalarmappable()\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]])\n pc.set_alpha(None) # restore default alpha\n pc.update_scalarmappable()\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])\n # Reset edgecolor to default.\n pc.set_edgecolor(None)\n pc.update_scalarmappable()\n assert np.array_equal(pc.get_edgecolor(), mapped)\n pc.set_facecolor(None) # restore default for facecolor\n pc.update_scalarmappable()\n assert np.array_equal(pc.get_facecolor(), mapped)\n assert mcolors.same_color(pc.get_edgecolor(), 'none')\n # Turn off colormapping entirely:\n pc.set_array(None)\n pc.update_scalarmappable()\n assert mcolors.same_color(pc.get_edgecolor(), 'none')\n assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped\n # Turn it back on by restoring the array (must be 1D!):\n pc.set_array(z)\n pc.update_scalarmappable()\n assert np.array_equal(pc.get_facecolor(), mapped)\n assert mcolors.same_color(pc.get_edgecolor(), 'none')\n # Give color via tuple rather than string.\n pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0))\n pc.update_scalarmappable()\n assert np.array_equal(pc.get_facecolor(), mapped)\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])\n # Provide an RGB array; mapping overrides it.\n pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3)))\n pc.update_scalarmappable()\n assert np.array_equal(pc.get_facecolor(), mapped)\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])\n # Turn off the mapping.\n pc.set_array(None)\n pc.update_scalarmappable()\n assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3)))\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])\n # And an RGBA array.\n pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4)))\n pc.update_scalarmappable()\n assert np.array_equal(pc.get_facecolor(), mapped)\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])\n # Turn off the mapping.\n pc.set_array(None)\n pc.update_scalarmappable()\n assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4)))\n assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])\n\n\ndef test_LineCollection_args():\n lc = LineCollection(None, linewidth=2.2, edgecolor='r',\n zorder=3, facecolors=[0, 1, 0, 1])\n assert lc.get_linewidth()[0] == 2.2\n assert mcolors.same_color(lc.get_edgecolor(), 'r')\n assert lc.get_zorder() == 3\n assert mcolors.same_color(lc.get_facecolor(), [[0, 1, 0, 1]])\n # To avoid breaking mplot3d, LineCollection internally sets the facecolor\n # kwarg if it has not been specified. Hence we need the following test\n # for LineCollection._set_default().\n lc = LineCollection(None, facecolor=None)\n assert mcolors.same_color(lc.get_facecolor(), 'none')\n\n\ndef test_array_dimensions(pcfunc):\n # Make sure we can set the 1D, 2D, and 3D array shapes\n z = np.arange(12).reshape(3, 4)\n pc = getattr(plt, pcfunc)(z)\n # 1D\n pc.set_array(z.ravel())\n pc.update_scalarmappable()\n # 2D\n pc.set_array(z)\n pc.update_scalarmappable()\n # 3D RGB is OK as well\n z = np.arange(36, dtype=np.uint8).reshape(3, 4, 3)\n pc.set_array(z)\n pc.update_scalarmappable()\n\n\ndef test_get_segments():\n segments = np.tile(np.linspace(0, 1, 256), (2, 1)).T\n lc = LineCollection([segments])\n\n readback, = lc.get_segments()\n # these should comeback un-changed!\n assert np.all(segments == readback)\n\n\ndef test_set_offsets_late():\n identity = mtransforms.IdentityTransform()\n sizes = [2]\n\n null = mcollections.CircleCollection(sizes=sizes)\n\n init = mcollections.CircleCollection(sizes=sizes, offsets=(10, 10))\n\n late = mcollections.CircleCollection(sizes=sizes)\n late.set_offsets((10, 10))\n\n # Bbox.__eq__ doesn't compare bounds\n null_bounds = null.get_datalim(identity).bounds\n init_bounds = init.get_datalim(identity).bounds\n late_bounds = late.get_datalim(identity).bounds\n\n # offsets and transform are applied when set after initialization\n assert null_bounds != init_bounds\n assert init_bounds == late_bounds\n\n\ndef test_set_offset_transform():\n skew = mtransforms.Affine2D().skew(2, 2)\n init = mcollections.Collection(offset_transform=skew)\n\n late = mcollections.Collection()\n late.set_offset_transform(skew)\n\n assert skew == init.get_offset_transform() == late.get_offset_transform()\n\n\ndef test_set_offset_units():\n # passing the offsets in initially (i.e. via scatter)\n # should yield the same results as `set_offsets`\n x = np.linspace(0, 10, 5)\n y = np.sin(x)\n d = x * np.timedelta64(24, 'h') + np.datetime64('2021-11-29')\n\n sc = plt.scatter(d, y)\n off0 = sc.get_offsets()\n sc.set_offsets(list(zip(d, y)))\n np.testing.assert_allclose(off0, sc.get_offsets())\n\n # try the other way around\n fig, ax = plt.subplots()\n sc = ax.scatter(y, d)\n off0 = sc.get_offsets()\n sc.set_offsets(list(zip(y, d)))\n np.testing.assert_allclose(off0, sc.get_offsets())\n\n\n@image_comparison(baseline_images=["test_check_masked_offsets"],\n extensions=["png"], remove_text=True, style="mpl20")\ndef test_check_masked_offsets():\n # Check if masked data is respected by scatter\n # Ref: Issue #24545\n unmasked_x = [\n datetime(2022, 12, 15, 4, 49, 52),\n datetime(2022, 12, 15, 4, 49, 53),\n datetime(2022, 12, 15, 4, 49, 54),\n datetime(2022, 12, 15, 4, 49, 55),\n datetime(2022, 12, 15, 4, 49, 56),\n ]\n\n masked_y = np.ma.array([1, 2, 3, 4, 5], mask=[0, 1, 1, 0, 0])\n\n fig, ax = plt.subplots()\n ax.scatter(unmasked_x, masked_y)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_masked_set_offsets(fig_ref, fig_test):\n x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0])\n y = np.arange(1, 6)\n\n ax_test = fig_test.add_subplot()\n scat = ax_test.scatter(x, y)\n scat.set_offsets(np.ma.column_stack([x, y]))\n ax_test.set_xticks([])\n ax_test.set_yticks([])\n\n ax_ref = fig_ref.add_subplot()\n ax_ref.scatter([1, 2, 5], [1, 2, 5])\n ax_ref.set_xticks([])\n ax_ref.set_yticks([])\n\n\ndef test_check_offsets_dtype():\n # Check that setting offsets doesn't change dtype\n x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0])\n y = np.arange(1, 6)\n\n fig, ax = plt.subplots()\n scat = ax.scatter(x, y)\n masked_offsets = np.ma.column_stack([x, y])\n scat.set_offsets(masked_offsets)\n assert isinstance(scat.get_offsets(), type(masked_offsets))\n\n unmasked_offsets = np.column_stack([x, y])\n scat.set_offsets(unmasked_offsets)\n assert isinstance(scat.get_offsets(), type(unmasked_offsets))\n\n\n@pytest.mark.parametrize('gapcolor', ['orange', ['r', 'k']])\n@check_figures_equal(extensions=['png'])\ndef test_striped_lines(fig_test, fig_ref, gapcolor):\n ax_test = fig_test.add_subplot(111)\n ax_ref = fig_ref.add_subplot(111)\n\n for ax in [ax_test, ax_ref]:\n ax.set_xlim(0, 6)\n ax.set_ylim(0, 1)\n\n x = range(1, 6)\n linestyles = [':', '-', '--']\n\n ax_test.vlines(x, 0, 1, linewidth=20, linestyle=linestyles, gapcolor=gapcolor,\n alpha=0.5)\n\n if isinstance(gapcolor, str):\n gapcolor = [gapcolor]\n\n for x, gcol, ls in zip(x, itertools.cycle(gapcolor),\n itertools.cycle(linestyles)):\n ax_ref.axvline(x, 0, 1, linewidth=20, linestyle=ls, gapcolor=gcol, alpha=0.5)\n\n\n@check_figures_equal(extensions=['png', 'pdf', 'svg', 'eps'])\ndef test_hatch_linewidth(fig_test, fig_ref):\n ax_test = fig_test.add_subplot()\n ax_ref = fig_ref.add_subplot()\n\n lw = 2.0\n\n polygons = [\n [(0.1, 0.1), (0.1, 0.4), (0.4, 0.4), (0.4, 0.1)],\n [(0.6, 0.6), (0.6, 0.9), (0.9, 0.9), (0.9, 0.6)],\n ]\n ref = PolyCollection(polygons, hatch="x")\n ref.set_hatch_linewidth(lw)\n\n with mpl.rc_context({"hatch.linewidth": lw}):\n test = PolyCollection(polygons, hatch="x")\n\n ax_ref.add_collection(ref)\n ax_test.add_collection(test)\n\n assert test.get_hatch_linewidth() == ref.get_hatch_linewidth() == lw\n | .venv\Lib\site-packages\matplotlib\tests\test_collections.py | test_collections.py | Python | 48,406 | 0.95 | 0.080808 | 0.089065 | awesome-app | 33 | 2025-05-30T21:47:08.507275 | BSD-3-Clause | true | 5fb44b81acd8417d0b3fcaa10b60d4a2 |
import platform\n\nimport numpy as np\nimport pytest\n\nfrom matplotlib import cm\nimport matplotlib.colors as mcolors\nimport matplotlib as mpl\n\n\nfrom matplotlib import rc_context\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import (\n BoundaryNorm, LogNorm, PowerNorm, Normalize, NoNorm\n)\nfrom matplotlib.colorbar import Colorbar\nfrom matplotlib.ticker import FixedLocator, LogFormatter, StrMethodFormatter\nfrom matplotlib.testing.decorators import check_figures_equal\n\n\ndef _get_cmap_norms():\n """\n Define a colormap and appropriate norms for each of the four\n possible settings of the extend keyword.\n\n Helper function for _colorbar_extension_shape and\n colorbar_extension_length.\n """\n # Create a colormap and specify the levels it represents.\n cmap = mpl.colormaps["RdBu"].resampled(5)\n clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]\n # Define norms for the colormaps.\n norms = dict()\n norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)\n norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)\n norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)\n norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)\n return cmap, norms\n\n\ndef _colorbar_extension_shape(spacing):\n """\n Produce 4 colorbars with rectangular extensions for either uniform\n or proportional spacing.\n\n Helper function for test_colorbar_extension_shape.\n """\n # Get a colormap and appropriate norms for each extension type.\n cmap, norms = _get_cmap_norms()\n # Create a figure and adjust whitespace for subplots.\n fig = plt.figure()\n fig.subplots_adjust(hspace=4)\n for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):\n # Get the appropriate norm and use it to get colorbar boundaries.\n norm = norms[extension_type]\n boundaries = values = norm.boundaries\n # note that the last value was silently dropped pre 3.3:\n values = values[:-1]\n # Create a subplot.\n cax = fig.add_subplot(4, 1, i + 1)\n # Generate the colorbar.\n Colorbar(cax, cmap=cmap, norm=norm,\n boundaries=boundaries, values=values,\n extend=extension_type, extendrect=True,\n orientation='horizontal', spacing=spacing)\n # Turn off text and ticks.\n cax.tick_params(left=False, labelleft=False,\n bottom=False, labelbottom=False)\n # Return the figure to the caller.\n return fig\n\n\ndef _colorbar_extension_length(spacing):\n """\n Produce 12 colorbars with variable length extensions for either\n uniform or proportional spacing.\n\n Helper function for test_colorbar_extension_length.\n """\n # Get a colormap and appropriate norms for each extension type.\n cmap, norms = _get_cmap_norms()\n # Create a figure and adjust whitespace for subplots.\n fig = plt.figure()\n fig.subplots_adjust(hspace=.6)\n for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):\n # Get the appropriate norm and use it to get colorbar boundaries.\n norm = norms[extension_type]\n boundaries = values = norm.boundaries\n values = values[:-1]\n for j, extendfrac in enumerate((None, 'auto', 0.1)):\n # Create a subplot.\n cax = fig.add_subplot(12, 1, i*3 + j + 1)\n # Generate the colorbar.\n Colorbar(cax, cmap=cmap, norm=norm,\n boundaries=boundaries, values=values,\n extend=extension_type, extendfrac=extendfrac,\n orientation='horizontal', spacing=spacing)\n # Turn off text and ticks.\n cax.tick_params(left=False, labelleft=False,\n bottom=False, labelbottom=False)\n # Return the figure to the caller.\n return fig\n\n\n@image_comparison(['colorbar_extensions_shape_uniform.png',\n 'colorbar_extensions_shape_proportional.png'])\ndef test_colorbar_extension_shape():\n """Test rectangular colorbar extensions."""\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n # Create figures for uniform and proportionally spaced colorbars.\n _colorbar_extension_shape('uniform')\n _colorbar_extension_shape('proportional')\n\n\n@image_comparison(['colorbar_extensions_uniform.png',\n 'colorbar_extensions_proportional.png'],\n tol=1.0)\ndef test_colorbar_extension_length():\n """Test variable length colorbar extensions."""\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n # Create figures for uniform and proportionally spaced colorbars.\n _colorbar_extension_length('uniform')\n _colorbar_extension_length('proportional')\n\n\n@pytest.mark.parametrize("orientation", ["horizontal", "vertical"])\n@pytest.mark.parametrize("extend,expected", [("min", (0, 0, 0, 1)),\n ("max", (1, 1, 1, 1)),\n ("both", (1, 1, 1, 1))])\ndef test_colorbar_extension_inverted_axis(orientation, extend, expected):\n """Test extension color with an inverted axis"""\n data = np.arange(12).reshape(3, 4)\n fig, ax = plt.subplots()\n cmap = mpl.colormaps["viridis"].with_extremes(under=(0, 0, 0, 1),\n over=(1, 1, 1, 1))\n im = ax.imshow(data, cmap=cmap)\n cbar = fig.colorbar(im, orientation=orientation, extend=extend)\n if orientation == "horizontal":\n cbar.ax.invert_xaxis()\n else:\n cbar.ax.invert_yaxis()\n assert cbar._extend_patches[0].get_facecolor() == expected\n if extend == "both":\n assert len(cbar._extend_patches) == 2\n assert cbar._extend_patches[1].get_facecolor() == (0, 0, 0, 1)\n else:\n assert len(cbar._extend_patches) == 1\n\n\n@pytest.mark.parametrize('use_gridspec', [True, False])\n@image_comparison(['cbar_with_orientation',\n 'cbar_locationing',\n 'double_cbar',\n 'cbar_sharing',\n ],\n extensions=['png'], remove_text=True,\n savefig_kwarg={'dpi': 40})\ndef test_colorbar_positioning(use_gridspec):\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n data = np.arange(1200).reshape(30, 40)\n levels = [0, 200, 400, 600, 800, 1000, 1200]\n\n # -------------------\n plt.figure()\n plt.contourf(data, levels=levels)\n plt.colorbar(orientation='horizontal', use_gridspec=use_gridspec)\n\n locations = ['left', 'right', 'top', 'bottom']\n plt.figure()\n for i, location in enumerate(locations):\n plt.subplot(2, 2, i + 1)\n plt.contourf(data, levels=levels)\n plt.colorbar(location=location, use_gridspec=use_gridspec)\n\n # -------------------\n plt.figure()\n # make some other data (random integers)\n data_2nd = np.array([[2, 3, 2, 3], [1.5, 2, 2, 3], [2, 3, 3, 4]])\n # make the random data expand to the shape of the main data\n data_2nd = np.repeat(np.repeat(data_2nd, 10, axis=1), 10, axis=0)\n\n color_mappable = plt.contourf(data, levels=levels, extend='both')\n # test extend frac here\n hatch_mappable = plt.contourf(data_2nd, levels=[1, 2, 3], colors='none',\n hatches=['/', 'o', '+'], extend='max')\n plt.contour(hatch_mappable, colors='black')\n\n plt.colorbar(color_mappable, location='left', label='variable 1',\n use_gridspec=use_gridspec)\n plt.colorbar(hatch_mappable, location='right', label='variable 2',\n use_gridspec=use_gridspec)\n\n # -------------------\n plt.figure()\n ax1 = plt.subplot(211, anchor='NE', aspect='equal')\n plt.contourf(data, levels=levels)\n ax2 = plt.subplot(223)\n plt.contourf(data, levels=levels)\n ax3 = plt.subplot(224)\n plt.contourf(data, levels=levels)\n\n plt.colorbar(ax=[ax2, ax3, ax1], location='right', pad=0.0, shrink=0.5,\n panchor=False, use_gridspec=use_gridspec)\n plt.colorbar(ax=[ax2, ax3, ax1], location='left', shrink=0.5,\n panchor=False, use_gridspec=use_gridspec)\n plt.colorbar(ax=[ax1], location='bottom', panchor=False,\n anchor=(0.8, 0.5), shrink=0.6, use_gridspec=use_gridspec)\n\n\ndef test_colorbar_single_ax_panchor_false():\n # Note that this differs from the tests above with panchor=False because\n # there use_gridspec is actually ineffective: passing *ax* as lists always\n # disables use_gridspec.\n ax = plt.subplot(111, anchor='N')\n plt.imshow([[0, 1]])\n plt.colorbar(panchor=False)\n assert ax.get_anchor() == 'N'\n\n\n@pytest.mark.parametrize('constrained', [False, True],\n ids=['standard', 'constrained'])\ndef test_colorbar_single_ax_panchor_east(constrained):\n fig = plt.figure(constrained_layout=constrained)\n ax = fig.add_subplot(111, anchor='N')\n plt.imshow([[0, 1]])\n plt.colorbar(panchor='E')\n assert ax.get_anchor() == 'E'\n\n\n@image_comparison(['contour_colorbar.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.054)\ndef test_contour_colorbar():\n fig, ax = plt.subplots(figsize=(4, 2))\n data = np.arange(1200).reshape(30, 40) - 500\n levels = np.array([0, 200, 400, 600, 800, 1000, 1200]) - 500\n\n CS = ax.contour(data, levels=levels, extend='both')\n fig.colorbar(CS, orientation='horizontal', extend='both')\n fig.colorbar(CS, orientation='vertical')\n\n\n@image_comparison(['cbar_with_subplots_adjust.png'], remove_text=True,\n savefig_kwarg={'dpi': 40})\ndef test_gridspec_make_colorbar():\n plt.figure()\n data = np.arange(1200).reshape(30, 40)\n levels = [0, 200, 400, 600, 800, 1000, 1200]\n\n plt.subplot(121)\n plt.contourf(data, levels=levels)\n plt.colorbar(use_gridspec=True, orientation='vertical')\n\n plt.subplot(122)\n plt.contourf(data, levels=levels)\n plt.colorbar(use_gridspec=True, orientation='horizontal')\n\n plt.subplots_adjust(top=0.95, right=0.95, bottom=0.2, hspace=0.25)\n\n\n@image_comparison(['colorbar_single_scatter.png'], remove_text=True,\n savefig_kwarg={'dpi': 40})\ndef test_colorbar_single_scatter():\n # Issue #2642: if a path collection has only one entry,\n # the norm scaling within the colorbar must ensure a\n # finite range, otherwise a zero denominator will occur in _locate.\n plt.figure()\n x = y = [0]\n z = [50]\n cmap = mpl.colormaps['jet'].resampled(16)\n cs = plt.scatter(x, y, z, c=z, cmap=cmap)\n plt.colorbar(cs)\n\n\n@pytest.mark.parametrize('use_gridspec', [True, False])\n@pytest.mark.parametrize('nested_gridspecs', [True, False])\ndef test_remove_from_figure(nested_gridspecs, use_gridspec):\n """Test `remove` with the specified ``use_gridspec`` setting."""\n fig = plt.figure()\n if nested_gridspecs:\n gs = fig.add_gridspec(2, 2)[1, 1].subgridspec(2, 2)\n ax = fig.add_subplot(gs[1, 1])\n else:\n ax = fig.add_subplot()\n sc = ax.scatter([1, 2], [3, 4])\n sc.set_array(np.array([5, 6]))\n pre_position = ax.get_position()\n cb = fig.colorbar(sc, use_gridspec=use_gridspec)\n fig.subplots_adjust()\n cb.remove()\n fig.subplots_adjust()\n post_position = ax.get_position()\n assert (pre_position.get_points() == post_position.get_points()).all()\n\n\ndef test_remove_from_figure_cl():\n """Test `remove` with constrained_layout."""\n fig, ax = plt.subplots(constrained_layout=True)\n sc = ax.scatter([1, 2], [3, 4])\n sc.set_array(np.array([5, 6]))\n fig.draw_without_rendering()\n pre_position = ax.get_position()\n cb = fig.colorbar(sc)\n cb.remove()\n fig.draw_without_rendering()\n post_position = ax.get_position()\n np.testing.assert_allclose(pre_position.get_points(),\n post_position.get_points())\n\n\ndef test_colorbarbase():\n # smoke test from #3805\n ax = plt.gca()\n Colorbar(ax, cmap=plt.cm.bone)\n\n\ndef test_parentless_mappable():\n pc = mpl.collections.PatchCollection([], cmap=plt.get_cmap('viridis'), array=[])\n with pytest.raises(ValueError, match='Unable to determine Axes to steal'):\n plt.colorbar(pc)\n\n\n@image_comparison(['colorbar_closed_patch.png'], remove_text=True)\ndef test_colorbar_closed_patch():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n fig = plt.figure(figsize=(8, 6))\n ax1 = fig.add_axes([0.05, 0.85, 0.9, 0.1])\n ax2 = fig.add_axes([0.1, 0.65, 0.75, 0.1])\n ax3 = fig.add_axes([0.05, 0.45, 0.9, 0.1])\n ax4 = fig.add_axes([0.05, 0.25, 0.9, 0.1])\n ax5 = fig.add_axes([0.05, 0.05, 0.9, 0.1])\n\n cmap = mpl.colormaps["RdBu"].resampled(5)\n\n im = ax1.pcolormesh(np.linspace(0, 10, 16).reshape((4, 4)), cmap=cmap)\n\n # The use of a "values" kwarg here is unusual. It works only\n # because it is matched to the data range in the image and to\n # the number of colors in the LUT.\n values = np.linspace(0, 10, 5)\n cbar_kw = dict(orientation='horizontal', values=values, ticks=[])\n\n # The wide line is to show that the closed path is being handled\n # correctly. See PR #4186.\n with rc_context({'axes.linewidth': 16}):\n plt.colorbar(im, cax=ax2, extend='both', extendfrac=0.5, **cbar_kw)\n plt.colorbar(im, cax=ax3, extend='both', **cbar_kw)\n plt.colorbar(im, cax=ax4, extend='both', extendrect=True, **cbar_kw)\n plt.colorbar(im, cax=ax5, extend='neither', **cbar_kw)\n\n\ndef test_colorbar_ticks():\n # test fix for #5673\n fig, ax = plt.subplots()\n x = np.arange(-3.0, 4.001)\n y = np.arange(-4.0, 3.001)\n X, Y = np.meshgrid(x, y)\n Z = X * Y\n clevs = np.array([-12, -5, 0, 5, 12], dtype=float)\n colors = ['r', 'g', 'b', 'c']\n cs = ax.contourf(X, Y, Z, clevs, colors=colors, extend='neither')\n cbar = fig.colorbar(cs, ax=ax, orientation='horizontal', ticks=clevs)\n assert len(cbar.ax.xaxis.get_ticklocs()) == len(clevs)\n\n\ndef test_colorbar_minorticks_on_off():\n # test for github issue #11510 and PR #11584\n np.random.seed(seed=12345)\n data = np.random.randn(20, 20)\n with rc_context({'_internal.classic_mode': False}):\n fig, ax = plt.subplots()\n # purposefully setting vmin and vmax to odd fractions\n # so as to check for the correct locations of the minor ticks\n im = ax.pcolormesh(data, vmin=-2.3, vmax=3.3)\n\n cbar = fig.colorbar(im, extend='both')\n # testing after minorticks_on()\n cbar.minorticks_on()\n np.testing.assert_almost_equal(\n cbar.ax.yaxis.get_minorticklocs(),\n [-2.2, -1.8, -1.6, -1.4, -1.2, -0.8, -0.6, -0.4, -0.2,\n 0.2, 0.4, 0.6, 0.8, 1.2, 1.4, 1.6, 1.8, 2.2, 2.4, 2.6, 2.8, 3.2])\n # testing after minorticks_off()\n cbar.minorticks_off()\n np.testing.assert_almost_equal(cbar.ax.yaxis.get_minorticklocs(), [])\n\n im.set_clim(vmin=-1.2, vmax=1.2)\n cbar.minorticks_on()\n np.testing.assert_almost_equal(\n cbar.ax.yaxis.get_minorticklocs(),\n [-1.2, -1.1, -0.9, -0.8, -0.7, -0.6, -0.4, -0.3, -0.2, -0.1,\n 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.1, 1.2])\n\n # tests for github issue #13257 and PR #13265\n data = np.random.uniform(low=1, high=10, size=(20, 20))\n\n fig, ax = plt.subplots()\n im = ax.pcolormesh(data, norm=LogNorm())\n cbar = fig.colorbar(im)\n fig.canvas.draw()\n default_minorticklocks = cbar.ax.yaxis.get_minorticklocs()\n # test that minorticks turn off for LogNorm\n cbar.minorticks_off()\n np.testing.assert_equal(cbar.ax.yaxis.get_minorticklocs(), [])\n\n # test that minorticks turn back on for LogNorm\n cbar.minorticks_on()\n np.testing.assert_equal(cbar.ax.yaxis.get_minorticklocs(),\n default_minorticklocks)\n\n # test issue #13339: minorticks for LogNorm should stay off\n cbar.minorticks_off()\n cbar.set_ticks([3, 5, 7, 9])\n np.testing.assert_equal(cbar.ax.yaxis.get_minorticklocs(), [])\n\n\ndef test_cbar_minorticks_for_rc_xyminortickvisible():\n """\n issue gh-16468.\n\n Making sure that minor ticks on the colorbar are turned on\n (internally) using the cbar.minorticks_on() method when\n rcParams['xtick.minor.visible'] = True (for horizontal cbar)\n rcParams['ytick.minor.visible'] = True (for vertical cbar).\n Using cbar.minorticks_on() ensures that the minor ticks\n don't overflow into the extend regions of the colorbar.\n """\n\n plt.rcParams['ytick.minor.visible'] = True\n plt.rcParams['xtick.minor.visible'] = True\n\n vmin, vmax = 0.4, 2.6\n fig, ax = plt.subplots()\n im = ax.pcolormesh([[1, 2]], vmin=vmin, vmax=vmax)\n\n cbar = fig.colorbar(im, extend='both', orientation='vertical')\n assert cbar.ax.yaxis.get_minorticklocs()[0] >= vmin\n assert cbar.ax.yaxis.get_minorticklocs()[-1] <= vmax\n\n cbar = fig.colorbar(im, extend='both', orientation='horizontal')\n assert cbar.ax.xaxis.get_minorticklocs()[0] >= vmin\n assert cbar.ax.xaxis.get_minorticklocs()[-1] <= vmax\n\n\ndef test_colorbar_autoticks():\n # Test new autotick modes. Needs to be classic because\n # non-classic doesn't go this route.\n with rc_context({'_internal.classic_mode': False}):\n fig, ax = plt.subplots(2, 1)\n x = np.arange(-3.0, 4.001)\n y = np.arange(-4.0, 3.001)\n X, Y = np.meshgrid(x, y)\n Z = X * Y\n Z = Z[:-1, :-1]\n pcm = ax[0].pcolormesh(X, Y, Z)\n cbar = fig.colorbar(pcm, ax=ax[0], extend='both',\n orientation='vertical')\n\n pcm = ax[1].pcolormesh(X, Y, Z)\n cbar2 = fig.colorbar(pcm, ax=ax[1], extend='both',\n orientation='vertical', shrink=0.4)\n # note only -10 to 10 are visible,\n np.testing.assert_almost_equal(cbar.ax.yaxis.get_ticklocs(),\n np.arange(-15, 16, 5))\n # note only -10 to 10 are visible\n np.testing.assert_almost_equal(cbar2.ax.yaxis.get_ticklocs(),\n np.arange(-20, 21, 10))\n\n\ndef test_colorbar_autotickslog():\n # Test new autotick modes...\n with rc_context({'_internal.classic_mode': False}):\n fig, ax = plt.subplots(2, 1)\n x = np.arange(-3.0, 4.001)\n y = np.arange(-4.0, 3.001)\n X, Y = np.meshgrid(x, y)\n Z = X * Y\n Z = Z[:-1, :-1]\n pcm = ax[0].pcolormesh(X, Y, 10**Z, norm=LogNorm())\n cbar = fig.colorbar(pcm, ax=ax[0], extend='both',\n orientation='vertical')\n\n pcm = ax[1].pcolormesh(X, Y, 10**Z, norm=LogNorm())\n cbar2 = fig.colorbar(pcm, ax=ax[1], extend='both',\n orientation='vertical', shrink=0.4)\n # note only -12 to +12 are visible\n np.testing.assert_almost_equal(cbar.ax.yaxis.get_ticklocs(),\n 10**np.arange(-16., 16.2, 4.))\n # note only -24 to +24 are visible\n np.testing.assert_almost_equal(cbar2.ax.yaxis.get_ticklocs(),\n 10**np.arange(-24., 25., 12.))\n\n\ndef test_colorbar_get_ticks():\n # test feature for #5792\n plt.figure()\n data = np.arange(1200).reshape(30, 40)\n levels = [0, 200, 400, 600, 800, 1000, 1200]\n\n plt.contourf(data, levels=levels)\n\n # testing getter for user set ticks\n userTicks = plt.colorbar(ticks=[0, 600, 1200])\n assert userTicks.get_ticks().tolist() == [0, 600, 1200]\n\n # testing for getter after calling set_ticks\n userTicks.set_ticks([600, 700, 800])\n assert userTicks.get_ticks().tolist() == [600, 700, 800]\n\n # testing for getter after calling set_ticks with some ticks out of bounds\n # removed #20054: other axes don't trim fixed lists, so colorbars\n # should not either:\n # userTicks.set_ticks([600, 1300, 1400, 1500])\n # assert userTicks.get_ticks().tolist() == [600]\n\n # testing getter when no ticks are assigned\n defTicks = plt.colorbar(orientation='horizontal')\n np.testing.assert_allclose(defTicks.get_ticks().tolist(), levels)\n\n # test normal ticks and minor ticks\n fig, ax = plt.subplots()\n x = np.arange(-3.0, 4.001)\n y = np.arange(-4.0, 3.001)\n X, Y = np.meshgrid(x, y)\n Z = X * Y\n Z = Z[:-1, :-1]\n pcm = ax.pcolormesh(X, Y, Z)\n cbar = fig.colorbar(pcm, ax=ax, extend='both',\n orientation='vertical')\n ticks = cbar.get_ticks()\n np.testing.assert_allclose(ticks, np.arange(-15, 16, 5))\n assert len(cbar.get_ticks(minor=True)) == 0\n\n\n@pytest.mark.parametrize("extend", ['both', 'min', 'max'])\ndef test_colorbar_lognorm_extension(extend):\n # Test that colorbar with lognorm is extended correctly\n f, ax = plt.subplots()\n cb = Colorbar(ax, norm=LogNorm(vmin=0.1, vmax=1000.0),\n orientation='vertical', extend=extend)\n assert cb._values[0] >= 0.0\n\n\ndef test_colorbar_powernorm_extension():\n # Test that colorbar with powernorm is extended correctly\n # Just a smoke test that adding the colorbar doesn't raise an error or warning\n fig, ax = plt.subplots()\n Colorbar(ax, norm=PowerNorm(gamma=0.5, vmin=0.0, vmax=1.0),\n orientation='vertical', extend='both')\n\n\ndef test_colorbar_axes_kw():\n # test fix for #8493: This does only test, that axes-related keywords pass\n # and do not raise an exception.\n plt.figure()\n plt.imshow([[1, 2], [3, 4]])\n plt.colorbar(orientation='horizontal', fraction=0.2, pad=0.2, shrink=0.5,\n aspect=10, anchor=(0., 0.), panchor=(0., 1.))\n\n\ndef test_colorbar_log_minortick_labels():\n with rc_context({'_internal.classic_mode': False}):\n fig, ax = plt.subplots()\n pcm = ax.imshow([[10000, 50000]], norm=LogNorm())\n cb = fig.colorbar(pcm)\n fig.canvas.draw()\n lb = [l.get_text() for l in cb.ax.yaxis.get_ticklabels(which='both')]\n expected = [r'$\mathdefault{10^{4}}$',\n r'$\mathdefault{2\times10^{4}}$',\n r'$\mathdefault{3\times10^{4}}$',\n r'$\mathdefault{4\times10^{4}}$']\n for exp in expected:\n assert exp in lb\n\n\ndef test_colorbar_renorm():\n x, y = np.ogrid[-4:4:31j, -4:4:31j]\n z = 120000*np.exp(-x**2 - y**2)\n\n fig, ax = plt.subplots()\n im = ax.imshow(z)\n cbar = fig.colorbar(im)\n np.testing.assert_allclose(cbar.ax.yaxis.get_majorticklocs(),\n np.arange(0, 120000.1, 20000))\n\n cbar.set_ticks([1, 2, 3])\n assert isinstance(cbar.locator, FixedLocator)\n\n norm = LogNorm(z.min(), z.max())\n im.set_norm(norm)\n np.testing.assert_allclose(cbar.ax.yaxis.get_majorticklocs(),\n np.logspace(-10, 7, 18))\n # note that set_norm removes the FixedLocator...\n assert np.isclose(cbar.vmin, z.min())\n cbar.set_ticks([1, 2, 3])\n assert isinstance(cbar.locator, FixedLocator)\n np.testing.assert_allclose(cbar.ax.yaxis.get_majorticklocs(),\n [1.0, 2.0, 3.0])\n\n norm = LogNorm(z.min() * 1000, z.max() * 1000)\n im.set_norm(norm)\n assert np.isclose(cbar.vmin, z.min() * 1000)\n assert np.isclose(cbar.vmax, z.max() * 1000)\n\n\n@pytest.mark.parametrize('fmt', ['%4.2e', '{x:.2e}'])\ndef test_colorbar_format(fmt):\n # make sure that format is passed properly\n x, y = np.ogrid[-4:4:31j, -4:4:31j]\n z = 120000*np.exp(-x**2 - y**2)\n\n fig, ax = plt.subplots()\n im = ax.imshow(z)\n cbar = fig.colorbar(im, format=fmt)\n fig.canvas.draw()\n assert cbar.ax.yaxis.get_ticklabels()[4].get_text() == '8.00e+04'\n\n # make sure that if we change the clim of the mappable that the\n # formatting is *not* lost:\n im.set_clim([4, 200])\n fig.canvas.draw()\n assert cbar.ax.yaxis.get_ticklabels()[4].get_text() == '2.00e+02'\n\n # but if we change the norm:\n im.set_norm(LogNorm(vmin=0.1, vmax=10))\n fig.canvas.draw()\n assert (cbar.ax.yaxis.get_ticklabels()[0].get_text() ==\n '$\\mathdefault{10^{-2}}$')\n\n\ndef test_colorbar_scale_reset():\n x, y = np.ogrid[-4:4:31j, -4:4:31j]\n z = 120000*np.exp(-x**2 - y**2)\n\n fig, ax = plt.subplots()\n pcm = ax.pcolormesh(z, cmap='RdBu_r', rasterized=True)\n cbar = fig.colorbar(pcm, ax=ax)\n cbar.outline.set_edgecolor('red')\n assert cbar.ax.yaxis.get_scale() == 'linear'\n\n pcm.set_norm(LogNorm(vmin=1, vmax=100))\n assert cbar.ax.yaxis.get_scale() == 'log'\n pcm.set_norm(Normalize(vmin=-20, vmax=20))\n assert cbar.ax.yaxis.get_scale() == 'linear'\n\n assert cbar.outline.get_edgecolor() == mcolors.to_rgba('red')\n\n # log scale with no vmin/vmax set should scale to the data if there\n # is a mappable already associated with the colorbar, not (0, 1)\n pcm.norm = LogNorm()\n assert pcm.norm.vmin == z.min()\n assert pcm.norm.vmax == z.max()\n\n\ndef test_colorbar_get_ticks_2():\n plt.rcParams['_internal.classic_mode'] = False\n fig, ax = plt.subplots()\n pc = ax.pcolormesh([[.05, .95]])\n cb = fig.colorbar(pc)\n np.testing.assert_allclose(cb.get_ticks(), [0., 0.2, 0.4, 0.6, 0.8, 1.0])\n\n\ndef test_colorbar_inverted_ticks():\n fig, axs = plt.subplots(2)\n ax = axs[0]\n pc = ax.pcolormesh(10**np.arange(1, 5).reshape(2, 2), norm=LogNorm())\n cbar = fig.colorbar(pc, ax=ax, extend='both')\n ticks = cbar.get_ticks()\n cbar.ax.invert_yaxis()\n np.testing.assert_allclose(ticks, cbar.get_ticks())\n\n ax = axs[1]\n pc = ax.pcolormesh(np.arange(1, 5).reshape(2, 2))\n cbar = fig.colorbar(pc, ax=ax, extend='both')\n cbar.minorticks_on()\n ticks = cbar.get_ticks()\n minorticks = cbar.get_ticks(minor=True)\n assert isinstance(minorticks, np.ndarray)\n cbar.ax.invert_yaxis()\n np.testing.assert_allclose(ticks, cbar.get_ticks())\n np.testing.assert_allclose(minorticks, cbar.get_ticks(minor=True))\n\n\ndef test_mappable_no_alpha():\n fig, ax = plt.subplots()\n sm = cm.ScalarMappable(norm=mcolors.Normalize(), cmap='viridis')\n fig.colorbar(sm, ax=ax)\n sm.set_cmap('plasma')\n plt.draw()\n\n\ndef test_mappable_2d_alpha():\n fig, ax = plt.subplots()\n x = np.arange(1, 5).reshape(2, 2)/4\n pc = ax.pcolormesh(x, alpha=x)\n cb = fig.colorbar(pc, ax=ax)\n # The colorbar's alpha should be None and the mappable should still have\n # the original alpha array\n assert cb.alpha is None\n assert pc.get_alpha() is x\n fig.draw_without_rendering()\n\n\ndef test_colorbar_label():\n """\n Test the label parameter. It should just be mapped to the xlabel/ylabel of\n the axes, depending on the orientation.\n """\n fig, ax = plt.subplots()\n im = ax.imshow([[1, 2], [3, 4]])\n cbar = fig.colorbar(im, label='cbar')\n assert cbar.ax.get_ylabel() == 'cbar'\n cbar.set_label(None)\n assert cbar.ax.get_ylabel() == ''\n cbar.set_label('cbar 2')\n assert cbar.ax.get_ylabel() == 'cbar 2'\n\n cbar2 = fig.colorbar(im, label=None)\n assert cbar2.ax.get_ylabel() == ''\n\n cbar3 = fig.colorbar(im, orientation='horizontal', label='horizontal cbar')\n assert cbar3.ax.get_xlabel() == 'horizontal cbar'\n\n\n@image_comparison(['colorbar_keeping_xlabel.png'], style='mpl20')\ndef test_keeping_xlabel():\n # github issue #23398 - xlabels being ignored in colorbar axis\n arr = np.arange(25).reshape((5, 5))\n fig, ax = plt.subplots()\n im = ax.imshow(arr)\n cbar = plt.colorbar(im)\n cbar.ax.set_xlabel('Visible Xlabel')\n cbar.set_label('YLabel')\n\n\n@pytest.mark.parametrize("clim", [(-20000, 20000), (-32768, 0)])\ndef test_colorbar_int(clim):\n # Check that we cast to float early enough to not\n # overflow ``int16(20000) - int16(-20000)`` or\n # run into ``abs(int16(-32768)) == -32768``.\n fig, ax = plt.subplots()\n im = ax.imshow([[*map(np.int16, clim)]])\n fig.colorbar(im)\n assert (im.norm.vmin, im.norm.vmax) == clim\n\n\ndef test_anchored_cbar_position_using_specgrid():\n data = np.arange(1200).reshape(30, 40)\n levels = [0, 200, 400, 600, 800, 1000, 1200]\n shrink = 0.5\n anchor_y = 0.3\n # right\n fig, ax = plt.subplots()\n cs = ax.contourf(data, levels=levels)\n cbar = plt.colorbar(\n cs, ax=ax, use_gridspec=True,\n location='right', anchor=(1, anchor_y), shrink=shrink)\n\n # the bottom left corner of one ax is (x0, y0)\n # the top right corner of one ax is (x1, y1)\n # p0: the vertical / horizontal position of anchor\n x0, y0, x1, y1 = ax.get_position().extents\n cx0, cy0, cx1, cy1 = cbar.ax.get_position().extents\n p0 = (y1 - y0) * anchor_y + y0\n\n np.testing.assert_allclose(\n [cy1, cy0],\n [y1 * shrink + (1 - shrink) * p0, p0 * (1 - shrink) + y0 * shrink])\n\n # left\n fig, ax = plt.subplots()\n cs = ax.contourf(data, levels=levels)\n cbar = plt.colorbar(\n cs, ax=ax, use_gridspec=True,\n location='left', anchor=(1, anchor_y), shrink=shrink)\n\n # the bottom left corner of one ax is (x0, y0)\n # the top right corner of one ax is (x1, y1)\n # p0: the vertical / horizontal position of anchor\n x0, y0, x1, y1 = ax.get_position().extents\n cx0, cy0, cx1, cy1 = cbar.ax.get_position().extents\n p0 = (y1 - y0) * anchor_y + y0\n\n np.testing.assert_allclose(\n [cy1, cy0],\n [y1 * shrink + (1 - shrink) * p0, p0 * (1 - shrink) + y0 * shrink])\n\n # top\n shrink = 0.5\n anchor_x = 0.3\n fig, ax = plt.subplots()\n cs = ax.contourf(data, levels=levels)\n cbar = plt.colorbar(\n cs, ax=ax, use_gridspec=True,\n location='top', anchor=(anchor_x, 1), shrink=shrink)\n\n # the bottom left corner of one ax is (x0, y0)\n # the top right corner of one ax is (x1, y1)\n # p0: the vertical / horizontal position of anchor\n x0, y0, x1, y1 = ax.get_position().extents\n cx0, cy0, cx1, cy1 = cbar.ax.get_position().extents\n p0 = (x1 - x0) * anchor_x + x0\n\n np.testing.assert_allclose(\n [cx1, cx0],\n [x1 * shrink + (1 - shrink) * p0, p0 * (1 - shrink) + x0 * shrink])\n\n # bottom\n shrink = 0.5\n anchor_x = 0.3\n fig, ax = plt.subplots()\n cs = ax.contourf(data, levels=levels)\n cbar = plt.colorbar(\n cs, ax=ax, use_gridspec=True,\n location='bottom', anchor=(anchor_x, 1), shrink=shrink)\n\n # the bottom left corner of one ax is (x0, y0)\n # the top right corner of one ax is (x1, y1)\n # p0: the vertical / horizontal position of anchor\n x0, y0, x1, y1 = ax.get_position().extents\n cx0, cy0, cx1, cy1 = cbar.ax.get_position().extents\n p0 = (x1 - x0) * anchor_x + x0\n\n np.testing.assert_allclose(\n [cx1, cx0],\n [x1 * shrink + (1 - shrink) * p0, p0 * (1 - shrink) + x0 * shrink])\n\n\n@image_comparison(['colorbar_change_lim_scale.png'], remove_text=True,\n style='mpl20')\ndef test_colorbar_change_lim_scale():\n fig, ax = plt.subplots(1, 2, constrained_layout=True)\n pc = ax[0].pcolormesh(np.arange(100).reshape(10, 10)+1)\n cb = fig.colorbar(pc, ax=ax[0], extend='both')\n cb.ax.set_yscale('log')\n\n pc = ax[1].pcolormesh(np.arange(100).reshape(10, 10)+1)\n cb = fig.colorbar(pc, ax=ax[1], extend='both')\n cb.ax.set_ylim([20, 90])\n\n\n@check_figures_equal(extensions=["png"])\ndef test_axes_handles_same_functions(fig_ref, fig_test):\n # prove that cax and cb.ax are functionally the same\n for nn, fig in enumerate([fig_ref, fig_test]):\n ax = fig.add_subplot()\n pc = ax.pcolormesh(np.ones(300).reshape(10, 30))\n cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])\n cb = fig.colorbar(pc, cax=cax)\n if nn == 0:\n caxx = cax\n else:\n caxx = cb.ax\n caxx.set_yticks(np.arange(0, 20))\n caxx.set_yscale('log')\n caxx.set_position([0.92, 0.1, 0.02, 0.7])\n\n\ndef test_inset_colorbar_layout():\n fig, ax = plt.subplots(constrained_layout=True, figsize=(3, 6))\n pc = ax.imshow(np.arange(100).reshape(10, 10))\n cax = ax.inset_axes([1.02, 0.1, 0.03, 0.8])\n cb = fig.colorbar(pc, cax=cax)\n\n fig.draw_without_rendering()\n # make sure this is in the figure. In the colorbar swapping\n # it was being dropped from the list of children...\n np.testing.assert_allclose(cb.ax.get_position().bounds,\n [0.87, 0.342, 0.0237, 0.315], atol=0.01)\n assert cb.ax in ax.child_axes\n\n\n@image_comparison(['colorbar_twoslope.png'], remove_text=True,\n style='mpl20')\ndef test_twoslope_colorbar():\n # Note that the second tick = 20, and should be in the middle\n # of the colorbar (white)\n # There should be no tick right at the bottom, nor at the top.\n fig, ax = plt.subplots()\n\n norm = mcolors.TwoSlopeNorm(20, 5, 95)\n pc = ax.pcolormesh(np.arange(1, 11), np.arange(1, 11),\n np.arange(100).reshape(10, 10),\n norm=norm, cmap='RdBu_r')\n fig.colorbar(pc)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_remove_cb_whose_mappable_has_no_figure(fig_ref, fig_test):\n ax = fig_test.add_subplot()\n cb = fig_test.colorbar(cm.ScalarMappable(), cax=ax)\n cb.remove()\n\n\ndef test_aspects():\n fig, ax = plt.subplots(3, 2, figsize=(8, 8))\n aspects = [20, 20, 10]\n extends = ['neither', 'both', 'both']\n cb = [[None, None, None], [None, None, None]]\n for nn, orient in enumerate(['vertical', 'horizontal']):\n for mm, (aspect, extend) in enumerate(zip(aspects, extends)):\n pc = ax[mm, nn].pcolormesh(np.arange(100).reshape(10, 10))\n cb[nn][mm] = fig.colorbar(pc, ax=ax[mm, nn], orientation=orient,\n aspect=aspect, extend=extend)\n fig.draw_without_rendering()\n # check the extends are right ratio:\n np.testing.assert_almost_equal(cb[0][1].ax.get_position().height,\n cb[0][0].ax.get_position().height * 0.9,\n decimal=2)\n # horizontal\n np.testing.assert_almost_equal(cb[1][1].ax.get_position().width,\n cb[1][0].ax.get_position().width * 0.9,\n decimal=2)\n # check correct aspect:\n pos = cb[0][0].ax.get_position(original=False)\n np.testing.assert_almost_equal(pos.height, pos.width * 20, decimal=2)\n pos = cb[1][0].ax.get_position(original=False)\n np.testing.assert_almost_equal(pos.height * 20, pos.width, decimal=2)\n # check twice as wide if aspect is 10 instead of 20\n np.testing.assert_almost_equal(\n cb[0][0].ax.get_position(original=False).width * 2,\n cb[0][2].ax.get_position(original=False).width, decimal=2)\n np.testing.assert_almost_equal(\n cb[1][0].ax.get_position(original=False).height * 2,\n cb[1][2].ax.get_position(original=False).height, decimal=2)\n\n\n@image_comparison(['proportional_colorbars.png'], remove_text=True,\n style='mpl20')\ndef test_proportional_colorbars():\n\n x = y = np.arange(-3.0, 3.01, 0.025)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-X**2 - Y**2)\n Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n Z = (Z1 - Z2) * 2\n\n levels = [-1.25, -0.5, -0.125, 0.125, 0.5, 1.25]\n cmap = mcolors.ListedColormap(\n ['0.3', '0.5', 'white', 'lightblue', 'steelblue'])\n cmap.set_under('darkred')\n cmap.set_over('crimson')\n norm = mcolors.BoundaryNorm(levels, cmap.N)\n\n extends = ['neither', 'both']\n spacings = ['uniform', 'proportional']\n fig, axs = plt.subplots(2, 2)\n for i in range(2):\n for j in range(2):\n CS3 = axs[i, j].contourf(X, Y, Z, levels, cmap=cmap, norm=norm,\n extend=extends[i])\n fig.colorbar(CS3, spacing=spacings[j], ax=axs[i, j])\n\n\n@image_comparison(['extend_drawedges.png'], remove_text=True, style='mpl20')\ndef test_colorbar_extend_drawedges():\n params = [\n ('both', 1, [[[1.1, 0], [1.1, 1]],\n [[2, 0], [2, 1]],\n [[2.9, 0], [2.9, 1]]]),\n ('min', 0, [[[1.1, 0], [1.1, 1]],\n [[2, 0], [2, 1]]]),\n ('max', 0, [[[2, 0], [2, 1]],\n [[2.9, 0], [2.9, 1]]]),\n ('neither', -1, [[[2, 0], [2, 1]]]),\n ]\n\n plt.rcParams['axes.linewidth'] = 2\n\n fig = plt.figure(figsize=(10, 4))\n subfigs = fig.subfigures(1, 2)\n\n for orientation, subfig in zip(['horizontal', 'vertical'], subfigs):\n if orientation == 'horizontal':\n axs = subfig.subplots(4, 1)\n else:\n axs = subfig.subplots(1, 4)\n fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)\n\n for ax, (extend, coloroffset, res) in zip(axs, params):\n cmap = mpl.colormaps["viridis"]\n bounds = np.arange(5)\n nb_colors = len(bounds) + coloroffset\n colors = cmap(np.linspace(100, 255, nb_colors).astype(int))\n cmap, norm = mcolors.from_levels_and_colors(bounds, colors,\n extend=extend)\n\n cbar = Colorbar(ax, cmap=cmap, norm=norm, orientation=orientation,\n drawedges=True)\n # Set limits such that only two colours are visible, and the\n # dividers would be outside the Axes, to ensure that a) they are\n # not drawn outside, and b) a divider still appears between the\n # main colour and the extension.\n if orientation == 'horizontal':\n ax.set_xlim(1.1, 2.9)\n else:\n ax.set_ylim(1.1, 2.9)\n res = np.array(res)[:, :, [1, 0]]\n np.testing.assert_array_equal(cbar.dividers.get_segments(), res)\n\n\n@image_comparison(['contourf_extend_patches.png'], remove_text=True,\n style='mpl20')\ndef test_colorbar_contourf_extend_patches():\n params = [\n ('both', 5, ['\\', '//']),\n ('min', 7, ['+']),\n ('max', 2, ['|', '-', '/', '\\', '//']),\n ('neither', 10, ['//', '\\', '||']),\n ]\n\n plt.rcParams['axes.linewidth'] = 2\n\n fig = plt.figure(figsize=(10, 4))\n subfigs = fig.subfigures(1, 2)\n fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)\n\n x = np.linspace(-2, 3, 50)\n y = np.linspace(-2, 3, 30)\n z = np.cos(x[np.newaxis, :]) + np.sin(y[:, np.newaxis])\n\n cmap = mpl.colormaps["viridis"]\n for orientation, subfig in zip(['horizontal', 'vertical'], subfigs):\n axs = subfig.subplots(2, 2).ravel()\n for ax, (extend, levels, hatches) in zip(axs, params):\n cs = ax.contourf(x, y, z, levels, hatches=hatches,\n cmap=cmap, extend=extend)\n subfig.colorbar(cs, ax=ax, orientation=orientation, fraction=0.4,\n extendfrac=0.2, aspect=5)\n\n\ndef test_negative_boundarynorm():\n fig, ax = plt.subplots(figsize=(1, 3))\n cmap = mpl.colormaps["viridis"]\n\n clevs = np.arange(-94, -85)\n norm = BoundaryNorm(clevs, cmap.N)\n cb = fig.colorbar(cm.ScalarMappable(cmap=cmap, norm=norm), cax=ax)\n np.testing.assert_allclose(cb.ax.get_ylim(), [clevs[0], clevs[-1]])\n np.testing.assert_allclose(cb.ax.get_yticks(), clevs)\n\n clevs = np.arange(85, 94)\n norm = BoundaryNorm(clevs, cmap.N)\n cb = fig.colorbar(cm.ScalarMappable(cmap=cmap, norm=norm), cax=ax)\n np.testing.assert_allclose(cb.ax.get_ylim(), [clevs[0], clevs[-1]])\n np.testing.assert_allclose(cb.ax.get_yticks(), clevs)\n\n clevs = np.arange(-3, 3)\n norm = BoundaryNorm(clevs, cmap.N)\n cb = fig.colorbar(cm.ScalarMappable(cmap=cmap, norm=norm), cax=ax)\n np.testing.assert_allclose(cb.ax.get_ylim(), [clevs[0], clevs[-1]])\n np.testing.assert_allclose(cb.ax.get_yticks(), clevs)\n\n clevs = np.arange(-8, 1)\n norm = BoundaryNorm(clevs, cmap.N)\n cb = fig.colorbar(cm.ScalarMappable(cmap=cmap, norm=norm), cax=ax)\n np.testing.assert_allclose(cb.ax.get_ylim(), [clevs[0], clevs[-1]])\n np.testing.assert_allclose(cb.ax.get_yticks(), clevs)\n\n\ndef test_centerednorm():\n # Test default centered norm gets expanded with non-singular limits\n # when plot data is all equal (autoscale halfrange == 0)\n fig, ax = plt.subplots(figsize=(1, 3))\n\n norm = mcolors.CenteredNorm()\n mappable = ax.pcolormesh(np.zeros((3, 3)), norm=norm)\n fig.colorbar(mappable)\n assert (norm.vmin, norm.vmax) == (-0.1, 0.1)\n\n\n@image_comparison(['nonorm_colorbars.svg'], style='mpl20')\ndef test_nonorm():\n plt.rcParams['svg.fonttype'] = 'none'\n data = [1, 2, 3, 4, 5]\n\n fig, ax = plt.subplots(figsize=(6, 1))\n fig.subplots_adjust(bottom=0.5)\n\n norm = NoNorm(vmin=min(data), vmax=max(data))\n cmap = mpl.colormaps["viridis"].resampled(len(data))\n mappable = cm.ScalarMappable(norm=norm, cmap=cmap)\n cbar = fig.colorbar(mappable, cax=ax, orientation="horizontal")\n\n\n@image_comparison(['test_boundaries.png'], remove_text=True,\n style='mpl20')\ndef test_boundaries():\n np.random.seed(seed=19680808)\n fig, ax = plt.subplots(figsize=(2, 2))\n pc = ax.pcolormesh(np.random.randn(10, 10), cmap='RdBu_r')\n cb = fig.colorbar(pc, ax=ax, boundaries=np.linspace(-3, 3, 7))\n\n\ndef test_colorbar_no_warning_rcparams_grid_true():\n # github issue #21723 - If mpl style has 'axes.grid' = True,\n # fig.colorbar raises a warning about Auto-removal of grids\n # by pcolor() and pcolormesh(). This is fixed by PR #22216.\n plt.rcParams['axes.grid'] = True\n fig, ax = plt.subplots()\n ax.grid(False)\n im = ax.pcolormesh([0, 1], [0, 1], [[1]])\n # make sure that no warning is raised by fig.colorbar\n fig.colorbar(im)\n\n\ndef test_colorbar_set_formatter_locator():\n # check that the locator properties echo what is on the axis:\n fig, ax = plt.subplots()\n pc = ax.pcolormesh(np.random.randn(10, 10))\n cb = fig.colorbar(pc)\n cb.ax.yaxis.set_major_locator(FixedLocator(np.arange(10)))\n cb.ax.yaxis.set_minor_locator(FixedLocator(np.arange(0, 10, 0.2)))\n assert cb.locator is cb.ax.yaxis.get_major_locator()\n assert cb.minorlocator is cb.ax.yaxis.get_minor_locator()\n cb.ax.yaxis.set_major_formatter(LogFormatter())\n cb.ax.yaxis.set_minor_formatter(LogFormatter())\n assert cb.formatter is cb.ax.yaxis.get_major_formatter()\n assert cb.minorformatter is cb.ax.yaxis.get_minor_formatter()\n\n # check that the setter works as expected:\n loc = FixedLocator(np.arange(7))\n cb.locator = loc\n assert cb.ax.yaxis.get_major_locator() is loc\n loc = FixedLocator(np.arange(0, 7, 0.1))\n cb.minorlocator = loc\n assert cb.ax.yaxis.get_minor_locator() is loc\n fmt = LogFormatter()\n cb.formatter = fmt\n assert cb.ax.yaxis.get_major_formatter() is fmt\n fmt = LogFormatter()\n cb.minorformatter = fmt\n assert cb.ax.yaxis.get_minor_formatter() is fmt\n assert cb.long_axis is cb.ax.yaxis\n\n\n@image_comparison(['colorbar_extend_alpha.png'], remove_text=True,\n savefig_kwarg={'dpi': 40})\ndef test_colorbar_extend_alpha():\n fig, ax = plt.subplots()\n im = ax.imshow([[0, 1], [2, 3]], alpha=0.3, interpolation="none")\n fig.colorbar(im, extend='both', boundaries=[0.5, 1.5, 2.5])\n\n\ndef test_offset_text_loc():\n plt.style.use('mpl20')\n fig, ax = plt.subplots()\n np.random.seed(seed=19680808)\n pc = ax.pcolormesh(np.random.randn(10, 10)*1e6)\n cb = fig.colorbar(pc, location='right', extend='max')\n fig.draw_without_rendering()\n # check that the offsetText is in the proper place above the\n # colorbar axes. In this case the colorbar axes is the same\n # height as the parent, so use the parents bbox.\n assert cb.ax.yaxis.offsetText.get_position()[1] > ax.bbox.y1\n\n\ndef test_title_text_loc():\n plt.style.use('mpl20')\n fig, ax = plt.subplots()\n np.random.seed(seed=19680808)\n pc = ax.pcolormesh(np.random.randn(10, 10))\n cb = fig.colorbar(pc, location='right', extend='max')\n cb.ax.set_title('Aardvark')\n fig.draw_without_rendering()\n # check that the title is in the proper place above the\n # colorbar axes, including its extend triangles....\n assert (cb.ax.title.get_window_extent(fig.canvas.get_renderer()).ymax >\n cb.ax.spines['outline'].get_window_extent().ymax)\n\n\n@check_figures_equal(extensions=["png"])\ndef test_passing_location(fig_ref, fig_test):\n ax_ref = fig_ref.add_subplot()\n im = ax_ref.imshow([[0, 1], [2, 3]])\n ax_ref.get_figure().colorbar(im, cax=ax_ref.inset_axes([0, 1.05, 1, 0.05]),\n orientation="horizontal", ticklocation="top")\n ax_test = fig_test.add_subplot()\n im = ax_test.imshow([[0, 1], [2, 3]])\n ax_test.get_figure().colorbar(im, cax=ax_test.inset_axes([0, 1.05, 1, 0.05]),\n location="top")\n\n\n@pytest.mark.parametrize("kwargs,error,message", [\n ({'location': 'top', 'orientation': 'vertical'}, TypeError,\n "location and orientation are mutually exclusive"),\n ({'location': 'top', 'orientation': 'vertical', 'cax': True}, TypeError,\n "location and orientation are mutually exclusive"), # Different to above\n ({'ticklocation': 'top', 'orientation': 'vertical', 'cax': True},\n ValueError, "'top' is not a valid value for position"),\n ({'location': 'top', 'extendfrac': (0, None)}, ValueError,\n "invalid value for extendfrac"),\n ])\ndef test_colorbar_errors(kwargs, error, message):\n fig, ax = plt.subplots()\n im = ax.imshow([[0, 1], [2, 3]])\n if kwargs.get('cax', None) is True:\n kwargs['cax'] = ax.inset_axes([0, 1.05, 1, 0.05])\n with pytest.raises(error, match=message):\n fig.colorbar(im, **kwargs)\n\n\ndef test_colorbar_axes_parmeters():\n fig, ax = plt.subplots(2)\n im = ax[0].imshow([[0, 1], [2, 3]])\n # colorbar should accept any form of axes sequence:\n fig.colorbar(im, ax=ax)\n fig.colorbar(im, ax=ax[0])\n fig.colorbar(im, ax=[_ax for _ax in ax])\n fig.colorbar(im, ax=(ax[0], ax[1]))\n fig.colorbar(im, ax={i: _ax for i, _ax in enumerate(ax)}.values())\n fig.draw_without_rendering()\n\n\ndef test_colorbar_wrong_figure():\n # If we decide in the future to disallow calling colorbar() on the "wrong" figure,\n # just delete this test.\n fig_tl = plt.figure(layout="tight")\n fig_cl = plt.figure(layout="constrained")\n im = fig_cl.add_subplot().imshow([[0, 1]])\n # Make sure this doesn't try to setup a gridspec-controlled colorbar on fig_cl,\n # which would crash CL.\n with pytest.warns(UserWarning, match="different Figure"):\n fig_tl.colorbar(im)\n fig_tl.draw_without_rendering()\n fig_cl.draw_without_rendering()\n\n\ndef test_colorbar_format_string_and_old():\n plt.imshow([[0, 1]])\n cb = plt.colorbar(format="{x}%")\n assert isinstance(cb._formatter, StrMethodFormatter)\n | .venv\Lib\site-packages\matplotlib\tests\test_colorbar.py | test_colorbar.py | Python | 46,711 | 0.95 | 0.1 | 0.130732 | node-utils | 415 | 2024-07-09T17:58:52.243068 | Apache-2.0 | true | cf79c69e3ff91da8e3c1d34360407164 |
import copy\nimport itertools\nimport unittest.mock\n\nfrom io import BytesIO\nimport numpy as np\nfrom PIL import Image\nimport pytest\nimport base64\n\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom matplotlib import cbook, cm\nimport matplotlib\nimport matplotlib as mpl\nimport matplotlib.colors as mcolors\nimport matplotlib.colorbar as mcolorbar\nimport matplotlib.colorizer as mcolorizer\nimport matplotlib.pyplot as plt\nimport matplotlib.scale as mscale\nfrom matplotlib.rcsetup import cycler\nfrom matplotlib.testing.decorators import image_comparison, check_figures_equal\nfrom matplotlib.colors import is_color_like, to_rgba_array\n\n\n@pytest.mark.parametrize('N, result', [\n (5, [1, .6, .2, .1, 0]),\n (2, [1, 0]),\n (1, [0]),\n])\ndef test_create_lookup_table(N, result):\n data = [(0.0, 1.0, 1.0), (0.5, 0.2, 0.2), (1.0, 0.0, 0.0)]\n assert_array_almost_equal(mcolors._create_lookup_table(N, data), result)\n\n\n@pytest.mark.parametrize("dtype", [np.uint8, int, np.float16, float])\ndef test_index_dtype(dtype):\n # We use subtraction in the indexing, so need to verify that uint8 works\n cm = mpl.colormaps["viridis"]\n assert_array_equal(cm(dtype(0)), cm(0))\n\n\ndef test_resampled():\n """\n GitHub issue #6025 pointed to incorrect ListedColormap.resampled;\n here we test the method for LinearSegmentedColormap as well.\n """\n n = 101\n colorlist = np.empty((n, 4), float)\n colorlist[:, 0] = np.linspace(0, 1, n)\n colorlist[:, 1] = 0.2\n colorlist[:, 2] = np.linspace(1, 0, n)\n colorlist[:, 3] = 0.7\n lsc = mcolors.LinearSegmentedColormap.from_list('lsc', colorlist)\n lc = mcolors.ListedColormap(colorlist)\n # Set some bad values for testing too\n for cmap in [lsc, lc]:\n cmap.set_under('r')\n cmap.set_over('g')\n cmap.set_bad('b')\n lsc3 = lsc.resampled(3)\n lc3 = lc.resampled(3)\n expected = np.array([[0.0, 0.2, 1.0, 0.7],\n [0.5, 0.2, 0.5, 0.7],\n [1.0, 0.2, 0.0, 0.7]], float)\n assert_array_almost_equal(lsc3([0, 0.5, 1]), expected)\n assert_array_almost_equal(lc3([0, 0.5, 1]), expected)\n # Test over/under was copied properly\n assert_array_almost_equal(lsc(np.inf), lsc3(np.inf))\n assert_array_almost_equal(lsc(-np.inf), lsc3(-np.inf))\n assert_array_almost_equal(lsc(np.nan), lsc3(np.nan))\n assert_array_almost_equal(lc(np.inf), lc3(np.inf))\n assert_array_almost_equal(lc(-np.inf), lc3(-np.inf))\n assert_array_almost_equal(lc(np.nan), lc3(np.nan))\n\n\ndef test_colormaps_get_cmap():\n cr = mpl.colormaps\n\n # check str, and Colormap pass\n assert cr.get_cmap('plasma') == cr["plasma"]\n assert cr.get_cmap(cr["magma"]) == cr["magma"]\n\n # check default\n assert cr.get_cmap(None) == cr[mpl.rcParams['image.cmap']]\n\n # check ValueError on bad name\n bad_cmap = 'AardvarksAreAwkward'\n with pytest.raises(ValueError, match=bad_cmap):\n cr.get_cmap(bad_cmap)\n\n # check TypeError on bad type\n with pytest.raises(TypeError, match='object'):\n cr.get_cmap(object())\n\n\ndef test_double_register_builtin_cmap():\n name = "viridis"\n match = f"Re-registering the builtin cmap {name!r}."\n with pytest.raises(ValueError, match=match):\n matplotlib.colormaps.register(mpl.colormaps[name], name=name, force=True)\n\n\ndef test_colormap_copy():\n cmap = plt.cm.Reds\n copied_cmap = copy.copy(cmap)\n with np.errstate(invalid='ignore'):\n ret1 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf])\n cmap2 = copy.copy(copied_cmap)\n cmap2.set_bad('g')\n with np.errstate(invalid='ignore'):\n ret2 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf])\n assert_array_equal(ret1, ret2)\n # again with the .copy method:\n cmap = plt.cm.Reds\n copied_cmap = cmap.copy()\n with np.errstate(invalid='ignore'):\n ret1 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf])\n cmap2 = copy.copy(copied_cmap)\n cmap2.set_bad('g')\n with np.errstate(invalid='ignore'):\n ret2 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf])\n assert_array_equal(ret1, ret2)\n\n\ndef test_colormap_equals():\n cmap = mpl.colormaps["plasma"]\n cm_copy = cmap.copy()\n # different object id's\n assert cm_copy is not cmap\n # But the same data should be equal\n assert cm_copy == cmap\n # Change the copy\n cm_copy.set_bad('y')\n assert cm_copy != cmap\n # Make sure we can compare different sizes without failure\n cm_copy._lut = cm_copy._lut[:10, :]\n assert cm_copy != cmap\n # Test different names are equal if the lookup table is the same\n cm_copy = cmap.copy()\n cm_copy.name = "Test"\n assert cm_copy == cmap\n # Test colorbar extends\n cm_copy = cmap.copy()\n cm_copy.colorbar_extend = not cmap.colorbar_extend\n assert cm_copy != cmap\n\n\ndef test_colormap_endian():\n """\n GitHub issue #1005: a bug in putmask caused erroneous\n mapping of 1.0 when input from a non-native-byteorder\n array.\n """\n cmap = mpl.colormaps["jet"]\n # Test under, over, and invalid along with values 0 and 1.\n a = [-0.5, 0, 0.5, 1, 1.5, np.nan]\n for dt in ["f2", "f4", "f8"]:\n anative = np.ma.masked_invalid(np.array(a, dtype=dt))\n aforeign = anative.byteswap().view(anative.dtype.newbyteorder())\n assert_array_equal(cmap(anative), cmap(aforeign))\n\n\ndef test_colormap_invalid():\n """\n GitHub issue #9892: Handling of nan's were getting mapped to under\n rather than bad. This tests to make sure all invalid values\n (-inf, nan, inf) are mapped respectively to (under, bad, over).\n """\n cmap = mpl.colormaps["plasma"]\n x = np.array([-np.inf, -1, 0, np.nan, .7, 2, np.inf])\n\n expected = np.array([[0.050383, 0.029803, 0.527975, 1.],\n [0.050383, 0.029803, 0.527975, 1.],\n [0.050383, 0.029803, 0.527975, 1.],\n [0., 0., 0., 0.],\n [0.949217, 0.517763, 0.295662, 1.],\n [0.940015, 0.975158, 0.131326, 1.],\n [0.940015, 0.975158, 0.131326, 1.]])\n assert_array_equal(cmap(x), expected)\n\n # Test masked representation (-inf, inf) are now masked\n expected = np.array([[0., 0., 0., 0.],\n [0.050383, 0.029803, 0.527975, 1.],\n [0.050383, 0.029803, 0.527975, 1.],\n [0., 0., 0., 0.],\n [0.949217, 0.517763, 0.295662, 1.],\n [0.940015, 0.975158, 0.131326, 1.],\n [0., 0., 0., 0.]])\n assert_array_equal(cmap(np.ma.masked_invalid(x)), expected)\n\n # Test scalar representations\n assert_array_equal(cmap(-np.inf), cmap(0))\n assert_array_equal(cmap(np.inf), cmap(1.0))\n assert_array_equal(cmap(np.nan), [0., 0., 0., 0.])\n\n\ndef test_colormap_return_types():\n """\n Make sure that tuples are returned for scalar input and\n that the proper shapes are returned for ndarrays.\n """\n cmap = mpl.colormaps["plasma"]\n # Test return types and shapes\n # scalar input needs to return a tuple of length 4\n assert isinstance(cmap(0.5), tuple)\n assert len(cmap(0.5)) == 4\n\n # input array returns an ndarray of shape x.shape + (4,)\n x = np.ones(4)\n assert cmap(x).shape == x.shape + (4,)\n\n # multi-dimensional array input\n x2d = np.zeros((2, 2))\n assert cmap(x2d).shape == x2d.shape + (4,)\n\n\ndef test_BoundaryNorm():\n """\n GitHub issue #1258: interpolation was failing with numpy\n 1.7 pre-release.\n """\n\n boundaries = [0, 1.1, 2.2]\n vals = [-1, 0, 1, 2, 2.2, 4]\n\n # Without interpolation\n expected = [-1, 0, 0, 1, 2, 2]\n ncolors = len(boundaries) - 1\n bn = mcolors.BoundaryNorm(boundaries, ncolors)\n assert_array_equal(bn(vals), expected)\n\n # ncolors != len(boundaries) - 1 triggers interpolation\n expected = [-1, 0, 0, 2, 3, 3]\n ncolors = len(boundaries)\n bn = mcolors.BoundaryNorm(boundaries, ncolors)\n assert_array_equal(bn(vals), expected)\n\n # with a single region and interpolation\n expected = [-1, 1, 1, 1, 3, 3]\n bn = mcolors.BoundaryNorm([0, 2.2], ncolors)\n assert_array_equal(bn(vals), expected)\n\n # more boundaries for a third color\n boundaries = [0, 1, 2, 3]\n vals = [-1, 0.1, 1.1, 2.2, 4]\n ncolors = 5\n expected = [-1, 0, 2, 4, 5]\n bn = mcolors.BoundaryNorm(boundaries, ncolors)\n assert_array_equal(bn(vals), expected)\n\n # a scalar as input should not trigger an error and should return a scalar\n boundaries = [0, 1, 2]\n vals = [-1, 0.1, 1.1, 2.2]\n bn = mcolors.BoundaryNorm(boundaries, 2)\n expected = [-1, 0, 1, 2]\n for v, ex in zip(vals, expected):\n ret = bn(v)\n assert isinstance(ret, int)\n assert_array_equal(ret, ex)\n assert_array_equal(bn([v]), ex)\n\n # same with interp\n bn = mcolors.BoundaryNorm(boundaries, 3)\n expected = [-1, 0, 2, 3]\n for v, ex in zip(vals, expected):\n ret = bn(v)\n assert isinstance(ret, int)\n assert_array_equal(ret, ex)\n assert_array_equal(bn([v]), ex)\n\n # Clipping\n bn = mcolors.BoundaryNorm(boundaries, 3, clip=True)\n expected = [0, 0, 2, 2]\n for v, ex in zip(vals, expected):\n ret = bn(v)\n assert isinstance(ret, int)\n assert_array_equal(ret, ex)\n assert_array_equal(bn([v]), ex)\n\n # Masked arrays\n boundaries = [0, 1.1, 2.2]\n vals = np.ma.masked_invalid([-1., np.nan, 0, 1.4, 9])\n\n # Without interpolation\n ncolors = len(boundaries) - 1\n bn = mcolors.BoundaryNorm(boundaries, ncolors)\n expected = np.ma.masked_array([-1, -99, 0, 1, 2], mask=[0, 1, 0, 0, 0])\n assert_array_equal(bn(vals), expected)\n\n # With interpolation\n bn = mcolors.BoundaryNorm(boundaries, len(boundaries))\n expected = np.ma.masked_array([-1, -99, 0, 2, 3], mask=[0, 1, 0, 0, 0])\n assert_array_equal(bn(vals), expected)\n\n # Non-trivial masked arrays\n vals = np.ma.masked_invalid([np.inf, np.nan])\n assert np.all(bn(vals).mask)\n vals = np.ma.masked_invalid([np.inf])\n assert np.all(bn(vals).mask)\n\n # Incompatible extend and clip\n with pytest.raises(ValueError, match="not compatible"):\n mcolors.BoundaryNorm(np.arange(4), 5, extend='both', clip=True)\n\n # Too small ncolors argument\n with pytest.raises(ValueError, match="ncolors must equal or exceed"):\n mcolors.BoundaryNorm(np.arange(4), 2)\n\n with pytest.raises(ValueError, match="ncolors must equal or exceed"):\n mcolors.BoundaryNorm(np.arange(4), 3, extend='min')\n\n with pytest.raises(ValueError, match="ncolors must equal or exceed"):\n mcolors.BoundaryNorm(np.arange(4), 4, extend='both')\n\n # Testing extend keyword, with interpolation (large cmap)\n bounds = [1, 2, 3]\n cmap = mpl.colormaps['viridis']\n mynorm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both')\n refnorm = mcolors.BoundaryNorm([0] + bounds + [4], cmap.N)\n x = np.random.randn(100) * 10 + 2\n ref = refnorm(x)\n ref[ref == 0] = -1\n ref[ref == cmap.N - 1] = cmap.N\n assert_array_equal(mynorm(x), ref)\n\n # Without interpolation\n cmref = mcolors.ListedColormap(['blue', 'red'])\n cmref.set_over('black')\n cmref.set_under('white')\n cmshould = mcolors.ListedColormap(['white', 'blue', 'red', 'black'])\n\n assert mcolors.same_color(cmref.get_over(), 'black')\n assert mcolors.same_color(cmref.get_under(), 'white')\n\n refnorm = mcolors.BoundaryNorm(bounds, cmref.N)\n mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='both')\n assert mynorm.vmin == refnorm.vmin\n assert mynorm.vmax == refnorm.vmax\n\n assert mynorm(bounds[0] - 0.1) == -1 # under\n assert mynorm(bounds[0] + 0.1) == 1 # first bin -> second color\n assert mynorm(bounds[-1] - 0.1) == cmshould.N - 2 # next-to-last color\n assert mynorm(bounds[-1] + 0.1) == cmshould.N # over\n\n x = [-1, 1.2, 2.3, 9.6]\n assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2, 3]))\n x = np.random.randn(100) * 10 + 2\n assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x)))\n\n # Just min\n cmref = mcolors.ListedColormap(['blue', 'red'])\n cmref.set_under('white')\n cmshould = mcolors.ListedColormap(['white', 'blue', 'red'])\n\n assert mcolors.same_color(cmref.get_under(), 'white')\n\n assert cmref.N == 2\n assert cmshould.N == 3\n refnorm = mcolors.BoundaryNorm(bounds, cmref.N)\n mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='min')\n assert mynorm.vmin == refnorm.vmin\n assert mynorm.vmax == refnorm.vmax\n x = [-1, 1.2, 2.3]\n assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2]))\n x = np.random.randn(100) * 10 + 2\n assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x)))\n\n # Just max\n cmref = mcolors.ListedColormap(['blue', 'red'])\n cmref.set_over('black')\n cmshould = mcolors.ListedColormap(['blue', 'red', 'black'])\n\n assert mcolors.same_color(cmref.get_over(), 'black')\n\n assert cmref.N == 2\n assert cmshould.N == 3\n refnorm = mcolors.BoundaryNorm(bounds, cmref.N)\n mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='max')\n assert mynorm.vmin == refnorm.vmin\n assert mynorm.vmax == refnorm.vmax\n x = [1.2, 2.3, 4]\n assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2]))\n x = np.random.randn(100) * 10 + 2\n assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x)))\n\n\ndef test_CenteredNorm():\n np.random.seed(0)\n\n # Assert equivalence to symmetrical Normalize.\n x = np.random.normal(size=100)\n x_maxabs = np.max(np.abs(x))\n norm_ref = mcolors.Normalize(vmin=-x_maxabs, vmax=x_maxabs)\n norm = mcolors.CenteredNorm()\n assert_array_almost_equal(norm_ref(x), norm(x))\n\n # Check that vcenter is in the center of vmin and vmax\n # when vcenter is set.\n vcenter = int(np.random.normal(scale=50))\n norm = mcolors.CenteredNorm(vcenter=vcenter)\n norm.autoscale_None([1, 2])\n assert norm.vmax + norm.vmin == 2 * vcenter\n\n # Check that halfrange can be set without setting vcenter and that it is\n # not reset through autoscale_None.\n norm = mcolors.CenteredNorm(halfrange=1.0)\n norm.autoscale_None([1, 3000])\n assert norm.halfrange == 1.0\n\n # Check that halfrange input works correctly.\n x = np.random.normal(size=10)\n norm = mcolors.CenteredNorm(vcenter=0.5, halfrange=0.5)\n assert_array_almost_equal(x, norm(x))\n norm = mcolors.CenteredNorm(vcenter=1, halfrange=1)\n assert_array_almost_equal(x, 2 * norm(x))\n\n # Check that halfrange input works correctly and use setters.\n norm = mcolors.CenteredNorm()\n norm.vcenter = 2\n norm.halfrange = 2\n assert_array_almost_equal(x, 4 * norm(x))\n\n # Check that prior to adding data, setting halfrange first has same effect.\n norm = mcolors.CenteredNorm()\n norm.halfrange = 2\n norm.vcenter = 2\n assert_array_almost_equal(x, 4 * norm(x))\n\n # Check that manual change of vcenter adjusts halfrange accordingly.\n norm = mcolors.CenteredNorm()\n assert norm.vcenter == 0\n # add data\n norm(np.linspace(-1.0, 0.0, 10))\n assert norm.vmax == 1.0\n assert norm.halfrange == 1.0\n # set vcenter to 1, which should move the center but leave the\n # halfrange unchanged\n norm.vcenter = 1\n assert norm.vmin == 0\n assert norm.vmax == 2\n assert norm.halfrange == 1\n\n # Check setting vmin directly updates the halfrange and vmax, but\n # leaves vcenter alone\n norm.vmin = -1\n assert norm.halfrange == 2\n assert norm.vmax == 3\n assert norm.vcenter == 1\n\n # also check vmax updates\n norm.vmax = 2\n assert norm.halfrange == 1\n assert norm.vmin == 0\n assert norm.vcenter == 1\n\n\n@pytest.mark.parametrize("vmin,vmax", [[-1, 2], [3, 1]])\ndef test_lognorm_invalid(vmin, vmax):\n # Check that invalid limits in LogNorm error\n norm = mcolors.LogNorm(vmin=vmin, vmax=vmax)\n with pytest.raises(ValueError):\n norm(1)\n with pytest.raises(ValueError):\n norm.inverse(1)\n\n\ndef test_LogNorm():\n """\n LogNorm ignored clip, now it has the same\n behavior as Normalize, e.g., values > vmax are bigger than 1\n without clip, with clip they are 1.\n """\n ln = mcolors.LogNorm(clip=True, vmax=5)\n assert_array_equal(ln([1, 6]), [0, 1.0])\n\n\ndef test_LogNorm_inverse():\n """\n Test that lists work, and that the inverse works\n """\n norm = mcolors.LogNorm(vmin=0.1, vmax=10)\n assert_array_almost_equal(norm([0.5, 0.4]), [0.349485, 0.30103])\n assert_array_almost_equal([0.5, 0.4], norm.inverse([0.349485, 0.30103]))\n assert_array_almost_equal(norm(0.4), [0.30103])\n assert_array_almost_equal([0.4], norm.inverse([0.30103]))\n\n\ndef test_PowerNorm():\n # Check an exponent of 1 gives same results as a normal linear\n # normalization. Also implicitly checks that vmin/vmax are\n # automatically initialized from first array input.\n a = np.array([0, 0.5, 1, 1.5], dtype=float)\n pnorm = mcolors.PowerNorm(1)\n norm = mcolors.Normalize()\n assert_array_almost_equal(norm(a), pnorm(a))\n\n a = np.array([-0.5, 0, 2, 4, 8], dtype=float)\n expected = [-1/16, 0, 1/16, 1/4, 1]\n pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)\n assert_array_almost_equal(pnorm(a), expected)\n assert pnorm(a[0]) == expected[0]\n assert pnorm(a[2]) == expected[2]\n # Check inverse\n a_roundtrip = pnorm.inverse(pnorm(a))\n assert_array_almost_equal(a, a_roundtrip)\n # PowerNorm inverse adds a mask, so check that is correct too\n assert_array_equal(a_roundtrip.mask, np.zeros(a.shape, dtype=bool))\n\n # Clip = True\n a = np.array([-0.5, 0, 1, 8, 16], dtype=float)\n expected = [0, 0, 0, 1, 1]\n # Clip = True when creating the norm\n pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)\n assert_array_almost_equal(pnorm(a), expected)\n assert pnorm(a[0]) == expected[0]\n assert pnorm(a[-1]) == expected[-1]\n # Clip = True at call time\n pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)\n assert_array_almost_equal(pnorm(a, clip=True), expected)\n assert pnorm(a[0], clip=True) == expected[0]\n assert pnorm(a[-1], clip=True) == expected[-1]\n\n # Check clip=True preserves masked values\n a = np.ma.array([5, 2], mask=[True, False])\n out = pnorm(a, clip=True)\n assert_array_equal(out.mask, [True, False])\n\n\ndef test_PowerNorm_translation_invariance():\n a = np.array([0, 1/2, 1], dtype=float)\n expected = [0, 1/8, 1]\n pnorm = mcolors.PowerNorm(vmin=0, vmax=1, gamma=3)\n assert_array_almost_equal(pnorm(a), expected)\n pnorm = mcolors.PowerNorm(vmin=-2, vmax=-1, gamma=3)\n assert_array_almost_equal(pnorm(a - 2), expected)\n\n\ndef test_powernorm_cbar_limits():\n fig, ax = plt.subplots()\n vmin, vmax = 300, 1000\n data = np.arange(10*10).reshape(10, 10) + vmin\n im = ax.imshow(data, norm=mcolors.PowerNorm(gamma=0.2, vmin=vmin, vmax=vmax))\n cbar = fig.colorbar(im)\n assert cbar.ax.get_ylim() == (vmin, vmax)\n\n\ndef test_Normalize():\n norm = mcolors.Normalize()\n vals = np.arange(-10, 10, 1, dtype=float)\n _inverse_tester(norm, vals)\n _scalar_tester(norm, vals)\n _mask_tester(norm, vals)\n\n # Handle integer input correctly (don't overflow when computing max-min,\n # i.e. 127-(-128) here).\n vals = np.array([-128, 127], dtype=np.int8)\n norm = mcolors.Normalize(vals.min(), vals.max())\n assert_array_equal(norm(vals), [0, 1])\n\n # Don't lose precision on longdoubles (float128 on Linux):\n # for array inputs...\n vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)\n norm = mcolors.Normalize(vals[0], vals[1])\n assert norm(vals).dtype == np.longdouble\n assert_array_equal(norm(vals), [0, 1])\n # and for scalar ones.\n eps = np.finfo(np.longdouble).resolution\n norm = plt.Normalize(1, 1 + 100 * eps)\n # This returns exactly 0.5 when longdouble is extended precision (80-bit),\n # but only a value close to it when it is quadruple precision (128-bit).\n assert_array_almost_equal(norm(1 + 50 * eps), 0.5, decimal=3)\n\n\ndef test_FuncNorm():\n def forward(x):\n return (x**2)\n def inverse(x):\n return np.sqrt(x)\n\n norm = mcolors.FuncNorm((forward, inverse), vmin=0, vmax=10)\n expected = np.array([0, 0.25, 1])\n input = np.array([0, 5, 10])\n assert_array_almost_equal(norm(input), expected)\n assert_array_almost_equal(norm.inverse(expected), input)\n\n def forward(x):\n return np.log10(x)\n def inverse(x):\n return 10**x\n norm = mcolors.FuncNorm((forward, inverse), vmin=0.1, vmax=10)\n lognorm = mcolors.LogNorm(vmin=0.1, vmax=10)\n assert_array_almost_equal(norm([0.2, 5, 10]), lognorm([0.2, 5, 10]))\n assert_array_almost_equal(norm.inverse([0.2, 5, 10]),\n lognorm.inverse([0.2, 5, 10]))\n\n\ndef test_TwoSlopeNorm_autoscale():\n norm = mcolors.TwoSlopeNorm(vcenter=20)\n norm.autoscale([10, 20, 30, 40])\n assert norm.vmin == 10.\n assert norm.vmax == 40.\n\n\ndef test_TwoSlopeNorm_autoscale_None_vmin():\n norm = mcolors.TwoSlopeNorm(2, vmin=0, vmax=None)\n norm.autoscale_None([1, 2, 3, 4, 5])\n assert norm(5) == 1\n assert norm.vmax == 5\n\n\ndef test_TwoSlopeNorm_autoscale_None_vmax():\n norm = mcolors.TwoSlopeNorm(2, vmin=None, vmax=10)\n norm.autoscale_None([1, 2, 3, 4, 5])\n assert norm(1) == 0\n assert norm.vmin == 1\n\n\ndef test_TwoSlopeNorm_scale():\n norm = mcolors.TwoSlopeNorm(2)\n assert norm.scaled() is False\n norm([1, 2, 3, 4])\n assert norm.scaled() is True\n\n\ndef test_TwoSlopeNorm_scaleout_center():\n # test the vmin never goes above vcenter\n norm = mcolors.TwoSlopeNorm(vcenter=0)\n norm([0, 1, 2, 3, 5])\n assert norm.vmin == -5\n assert norm.vmax == 5\n\n\ndef test_TwoSlopeNorm_scaleout_center_max():\n # test the vmax never goes below vcenter\n norm = mcolors.TwoSlopeNorm(vcenter=0)\n norm([0, -1, -2, -3, -5])\n assert norm.vmax == 5\n assert norm.vmin == -5\n\n\ndef test_TwoSlopeNorm_Even():\n norm = mcolors.TwoSlopeNorm(vmin=-1, vcenter=0, vmax=4)\n vals = np.array([-1.0, -0.5, 0.0, 1.0, 2.0, 3.0, 4.0])\n expected = np.array([0.0, 0.25, 0.5, 0.625, 0.75, 0.875, 1.0])\n assert_array_equal(norm(vals), expected)\n\n\ndef test_TwoSlopeNorm_Odd():\n norm = mcolors.TwoSlopeNorm(vmin=-2, vcenter=0, vmax=5)\n vals = np.array([-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0])\n expected = np.array([0.0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\n assert_array_equal(norm(vals), expected)\n\n\ndef test_TwoSlopeNorm_VminEqualsVcenter():\n with pytest.raises(ValueError):\n mcolors.TwoSlopeNorm(vmin=-2, vcenter=-2, vmax=2)\n\n\ndef test_TwoSlopeNorm_VmaxEqualsVcenter():\n with pytest.raises(ValueError):\n mcolors.TwoSlopeNorm(vmin=-2, vcenter=2, vmax=2)\n\n\ndef test_TwoSlopeNorm_VminGTVcenter():\n with pytest.raises(ValueError):\n mcolors.TwoSlopeNorm(vmin=10, vcenter=0, vmax=20)\n\n\ndef test_TwoSlopeNorm_TwoSlopeNorm_VminGTVmax():\n with pytest.raises(ValueError):\n mcolors.TwoSlopeNorm(vmin=10, vcenter=0, vmax=5)\n\n\ndef test_TwoSlopeNorm_VcenterGTVmax():\n with pytest.raises(ValueError):\n mcolors.TwoSlopeNorm(vmin=10, vcenter=25, vmax=20)\n\n\ndef test_TwoSlopeNorm_premature_scaling():\n norm = mcolors.TwoSlopeNorm(vcenter=2)\n with pytest.raises(ValueError):\n norm.inverse(np.array([0.1, 0.5, 0.9]))\n\n\ndef test_SymLogNorm():\n """\n Test SymLogNorm behavior\n """\n norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2, base=np.e)\n vals = np.array([-30, -1, 2, 6], dtype=float)\n normed_vals = norm(vals)\n expected = [0., 0.53980074, 0.826991, 1.02758204]\n assert_array_almost_equal(normed_vals, expected)\n _inverse_tester(norm, vals)\n _scalar_tester(norm, vals)\n _mask_tester(norm, vals)\n\n # Ensure that specifying vmin returns the same result as above\n norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2, base=np.e)\n normed_vals = norm(vals)\n assert_array_almost_equal(normed_vals, expected)\n\n # test something more easily checked.\n norm = mcolors.SymLogNorm(1, vmin=-np.e**3, vmax=np.e**3, base=np.e)\n nn = norm([-np.e**3, -np.e**2, -np.e**1, -1,\n 0, 1, np.e**1, np.e**2, np.e**3])\n xx = np.array([0., 0.109123, 0.218246, 0.32737, 0.5, 0.67263,\n 0.781754, 0.890877, 1.])\n assert_array_almost_equal(nn, xx)\n norm = mcolors.SymLogNorm(1, vmin=-10**3, vmax=10**3, base=10)\n nn = norm([-10**3, -10**2, -10**1, -1,\n 0, 1, 10**1, 10**2, 10**3])\n xx = np.array([0., 0.121622, 0.243243, 0.364865, 0.5, 0.635135,\n 0.756757, 0.878378, 1.])\n assert_array_almost_equal(nn, xx)\n\n\ndef test_SymLogNorm_colorbar():\n """\n Test un-called SymLogNorm in a colorbar.\n """\n norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1, base=np.e)\n fig = plt.figure()\n mcolorbar.ColorbarBase(fig.add_subplot(), norm=norm)\n plt.close(fig)\n\n\ndef test_SymLogNorm_single_zero():\n """\n Test SymLogNorm to ensure it is not adding sub-ticks to zero label\n """\n fig = plt.figure()\n norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1, base=np.e)\n cbar = mcolorbar.ColorbarBase(fig.add_subplot(), norm=norm)\n ticks = cbar.get_ticks()\n assert np.count_nonzero(ticks == 0) <= 1\n plt.close(fig)\n\n\nclass TestAsinhNorm:\n """\n Tests for `~.colors.AsinhNorm`\n """\n\n def test_init(self):\n norm0 = mcolors.AsinhNorm()\n assert norm0.linear_width == 1\n\n norm5 = mcolors.AsinhNorm(linear_width=5)\n assert norm5.linear_width == 5\n\n def test_norm(self):\n norm = mcolors.AsinhNorm(2, vmin=-4, vmax=4)\n vals = np.arange(-3.5, 3.5, 10)\n normed_vals = norm(vals)\n asinh2 = np.arcsinh(2)\n\n expected = (2 * np.arcsinh(vals / 2) + 2 * asinh2) / (4 * asinh2)\n assert_array_almost_equal(normed_vals, expected)\n\n\ndef _inverse_tester(norm_instance, vals):\n """\n Checks if the inverse of the given normalization is working.\n """\n assert_array_almost_equal(norm_instance.inverse(norm_instance(vals)), vals)\n\n\ndef _scalar_tester(norm_instance, vals):\n """\n Checks if scalars and arrays are handled the same way.\n Tests only for float.\n """\n scalar_result = [norm_instance(float(v)) for v in vals]\n assert_array_almost_equal(scalar_result, norm_instance(vals))\n\n\ndef _mask_tester(norm_instance, vals):\n """\n Checks mask handling\n """\n masked_array = np.ma.array(vals)\n masked_array[0] = np.ma.masked\n assert_array_equal(masked_array.mask, norm_instance(masked_array).mask)\n\n\n@image_comparison(['levels_and_colors.png'])\ndef test_cmap_and_norm_from_levels_and_colors():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n data = np.linspace(-2, 4, 49).reshape(7, 7)\n levels = [-1, 2, 2.5, 3]\n colors = ['red', 'green', 'blue', 'yellow', 'black']\n extend = 'both'\n cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend)\n\n ax = plt.axes()\n m = plt.pcolormesh(data, cmap=cmap, norm=norm)\n plt.colorbar(m)\n\n # Hide the axes labels (but not the colorbar ones, as they are useful)\n ax.tick_params(labelleft=False, labelbottom=False)\n\n\n@image_comparison(baseline_images=['boundarynorm_and_colorbar'],\n extensions=['png'], tol=1.0)\ndef test_boundarynorm_and_colorbarbase():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n # Make a figure and axes with dimensions as desired.\n fig = plt.figure()\n ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])\n ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])\n ax3 = fig.add_axes([0.05, 0.15, 0.9, 0.15])\n\n # Set the colormap and bounds\n bounds = [-1, 2, 5, 7, 12, 15]\n cmap = mpl.colormaps['viridis']\n\n # Default behavior\n norm = mcolors.BoundaryNorm(bounds, cmap.N)\n cb1 = mcolorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, extend='both',\n orientation='horizontal', spacing='uniform')\n # New behavior\n norm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both')\n cb2 = mcolorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,\n orientation='horizontal')\n\n # User can still force to any extend='' if really needed\n norm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both')\n cb3 = mcolorbar.ColorbarBase(ax3, cmap=cmap, norm=norm,\n extend='neither', orientation='horizontal')\n\n\ndef test_cmap_and_norm_from_levels_and_colors2():\n levels = [-1, 2, 2.5, 3]\n colors = ['red', (0, 1, 0), 'blue', (0.5, 0.5, 0.5), (0.0, 0.0, 0.0, 1.0)]\n clr = mcolors.to_rgba_array(colors)\n bad = (0.1, 0.1, 0.1, 0.1)\n no_color = (0.0, 0.0, 0.0, 0.0)\n masked_value = 'masked_value'\n\n # Define the test values which are of interest.\n # Note: levels are lev[i] <= v < lev[i+1]\n tests = [('both', None, {-2: clr[0],\n -1: clr[1],\n 2: clr[2],\n 2.25: clr[2],\n 3: clr[4],\n 3.5: clr[4],\n masked_value: bad}),\n\n ('min', -1, {-2: clr[0],\n -1: clr[1],\n 2: clr[2],\n 2.25: clr[2],\n 3: no_color,\n 3.5: no_color,\n masked_value: bad}),\n\n ('max', -1, {-2: no_color,\n -1: clr[0],\n 2: clr[1],\n 2.25: clr[1],\n 3: clr[3],\n 3.5: clr[3],\n masked_value: bad}),\n\n ('neither', -2, {-2: no_color,\n -1: clr[0],\n 2: clr[1],\n 2.25: clr[1],\n 3: no_color,\n 3.5: no_color,\n masked_value: bad}),\n ]\n\n for extend, i1, cases in tests:\n cmap, norm = mcolors.from_levels_and_colors(levels, colors[0:i1],\n extend=extend)\n cmap.set_bad(bad)\n for d_val, expected_color in cases.items():\n if d_val == masked_value:\n d_val = np.ma.array([1], mask=True)\n else:\n d_val = [d_val]\n assert_array_equal(expected_color, cmap(norm(d_val))[0],\n f'With extend={extend!r} and data '\n f'value={d_val!r}')\n\n with pytest.raises(ValueError):\n mcolors.from_levels_and_colors(levels, colors)\n\n\ndef test_rgb_hsv_round_trip():\n for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]:\n np.random.seed(0)\n tt = np.random.random(a_shape)\n assert_array_almost_equal(\n tt, mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt)))\n assert_array_almost_equal(\n tt, mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt)))\n\n\ndef test_autoscale_masked():\n # Test for #2336. Previously fully masked data would trigger a ValueError.\n data = np.ma.masked_all((12, 20))\n plt.pcolor(data)\n plt.draw()\n\n\n@image_comparison(['light_source_shading_topo.png'])\ndef test_light_source_topo_surface():\n """Shades a DEM using different v.e.'s and blend modes."""\n dem = cbook.get_sample_data('jacksboro_fault_dem.npz')\n elev = dem['elevation']\n dx, dy = dem['dx'], dem['dy']\n # Get the true cellsize in meters for accurate vertical exaggeration\n # Convert from decimal degrees to meters\n dx = 111320.0 * dx * np.cos(dem['ymin'])\n dy = 111320.0 * dy\n\n ls = mcolors.LightSource(315, 45)\n cmap = cm.gist_earth\n\n fig, axs = plt.subplots(nrows=3, ncols=3)\n for row, mode in zip(axs, ['hsv', 'overlay', 'soft']):\n for ax, ve in zip(row, [0.1, 1, 10]):\n rgb = ls.shade(elev, cmap, vert_exag=ve, dx=dx, dy=dy,\n blend_mode=mode)\n ax.imshow(rgb)\n ax.set(xticks=[], yticks=[])\n\n\ndef test_light_source_shading_default():\n """\n Array comparison test for the default "hsv" blend mode. Ensure the\n default result doesn't change without warning.\n """\n y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j]\n z = 10 * np.cos(x**2 + y**2)\n\n cmap = plt.cm.copper\n ls = mcolors.LightSource(315, 45)\n rgb = ls.shade(z, cmap)\n\n # Result stored transposed and rounded for more compact display...\n expect = np.array(\n [[[0.00, 0.45, 0.90, 0.90, 0.82, 0.62, 0.28, 0.00],\n [0.45, 0.94, 0.99, 1.00, 1.00, 0.96, 0.65, 0.17],\n [0.90, 0.99, 1.00, 1.00, 1.00, 1.00, 0.94, 0.35],\n [0.90, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.49],\n [0.82, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.41],\n [0.62, 0.96, 1.00, 1.00, 1.00, 1.00, 0.90, 0.07],\n [0.28, 0.65, 0.94, 1.00, 1.00, 0.90, 0.35, 0.01],\n [0.00, 0.17, 0.35, 0.49, 0.41, 0.07, 0.01, 0.00]],\n\n [[0.00, 0.28, 0.59, 0.72, 0.62, 0.40, 0.18, 0.00],\n [0.28, 0.78, 0.93, 0.92, 0.83, 0.66, 0.39, 0.11],\n [0.59, 0.93, 0.99, 1.00, 0.92, 0.75, 0.50, 0.21],\n [0.72, 0.92, 1.00, 0.99, 0.93, 0.76, 0.51, 0.18],\n [0.62, 0.83, 0.92, 0.93, 0.87, 0.68, 0.42, 0.08],\n [0.40, 0.66, 0.75, 0.76, 0.68, 0.52, 0.23, 0.02],\n [0.18, 0.39, 0.50, 0.51, 0.42, 0.23, 0.00, 0.00],\n [0.00, 0.11, 0.21, 0.18, 0.08, 0.02, 0.00, 0.00]],\n\n [[0.00, 0.18, 0.38, 0.46, 0.39, 0.26, 0.11, 0.00],\n [0.18, 0.50, 0.70, 0.75, 0.64, 0.44, 0.25, 0.07],\n [0.38, 0.70, 0.91, 0.98, 0.81, 0.51, 0.29, 0.13],\n [0.46, 0.75, 0.98, 0.96, 0.84, 0.48, 0.22, 0.12],\n [0.39, 0.64, 0.81, 0.84, 0.71, 0.31, 0.11, 0.05],\n [0.26, 0.44, 0.51, 0.48, 0.31, 0.10, 0.03, 0.01],\n [0.11, 0.25, 0.29, 0.22, 0.11, 0.03, 0.00, 0.00],\n [0.00, 0.07, 0.13, 0.12, 0.05, 0.01, 0.00, 0.00]],\n\n [[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]]\n ]).T\n\n assert_array_almost_equal(rgb, expect, decimal=2)\n\n\ndef test_light_source_shading_empty_mask():\n y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j]\n z0 = 10 * np.cos(x**2 + y**2)\n z1 = np.ma.array(z0)\n\n cmap = plt.cm.copper\n ls = mcolors.LightSource(315, 45)\n rgb0 = ls.shade(z0, cmap)\n rgb1 = ls.shade(z1, cmap)\n\n assert_array_almost_equal(rgb0, rgb1)\n\n\n# Numpy 1.9.1 fixed a bug in masked arrays which resulted in\n# additional elements being masked when calculating the gradient thus\n# the output is different with earlier numpy versions.\ndef test_light_source_masked_shading():\n """\n Array comparison test for a surface with a masked portion. Ensures that\n we don't wind up with "fringes" of odd colors around masked regions.\n """\n y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j]\n z = 10 * np.cos(x**2 + y**2)\n\n z = np.ma.masked_greater(z, 9.9)\n\n cmap = plt.cm.copper\n ls = mcolors.LightSource(315, 45)\n rgb = ls.shade(z, cmap)\n\n # Result stored transposed and rounded for more compact display...\n expect = np.array(\n [[[0.00, 0.46, 0.91, 0.91, 0.84, 0.64, 0.29, 0.00],\n [0.46, 0.96, 1.00, 1.00, 1.00, 0.97, 0.67, 0.18],\n [0.91, 1.00, 1.00, 1.00, 1.00, 1.00, 0.96, 0.36],\n [0.91, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 0.51],\n [0.84, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 0.44],\n [0.64, 0.97, 1.00, 1.00, 1.00, 1.00, 0.94, 0.09],\n [0.29, 0.67, 0.96, 1.00, 1.00, 0.94, 0.38, 0.01],\n [0.00, 0.18, 0.36, 0.51, 0.44, 0.09, 0.01, 0.00]],\n\n [[0.00, 0.29, 0.61, 0.75, 0.64, 0.41, 0.18, 0.00],\n [0.29, 0.81, 0.95, 0.93, 0.85, 0.68, 0.40, 0.11],\n [0.61, 0.95, 1.00, 0.78, 0.78, 0.77, 0.52, 0.22],\n [0.75, 0.93, 0.78, 0.00, 0.00, 0.78, 0.54, 0.19],\n [0.64, 0.85, 0.78, 0.00, 0.00, 0.78, 0.45, 0.08],\n [0.41, 0.68, 0.77, 0.78, 0.78, 0.55, 0.25, 0.02],\n [0.18, 0.40, 0.52, 0.54, 0.45, 0.25, 0.00, 0.00],\n [0.00, 0.11, 0.22, 0.19, 0.08, 0.02, 0.00, 0.00]],\n\n [[0.00, 0.19, 0.39, 0.48, 0.41, 0.26, 0.12, 0.00],\n [0.19, 0.52, 0.73, 0.78, 0.66, 0.46, 0.26, 0.07],\n [0.39, 0.73, 0.95, 0.50, 0.50, 0.53, 0.30, 0.14],\n [0.48, 0.78, 0.50, 0.00, 0.00, 0.50, 0.23, 0.12],\n [0.41, 0.66, 0.50, 0.00, 0.00, 0.50, 0.11, 0.05],\n [0.26, 0.46, 0.53, 0.50, 0.50, 0.11, 0.03, 0.01],\n [0.12, 0.26, 0.30, 0.23, 0.11, 0.03, 0.00, 0.00],\n [0.00, 0.07, 0.14, 0.12, 0.05, 0.01, 0.00, 0.00]],\n\n [[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00],\n [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]],\n ]).T\n\n assert_array_almost_equal(rgb, expect, decimal=2)\n\n\ndef test_light_source_hillshading():\n """\n Compare the current hillshading method against one that should be\n mathematically equivalent. Illuminates a cone from a range of angles.\n """\n\n def alternative_hillshade(azimuth, elev, z):\n illum = _sph2cart(*_azimuth2math(azimuth, elev))\n illum = np.array(illum)\n\n dy, dx = np.gradient(-z)\n dy = -dy\n dz = np.ones_like(dy)\n normals = np.dstack([dx, dy, dz])\n normals /= np.linalg.norm(normals, axis=2)[..., None]\n\n intensity = np.tensordot(normals, illum, axes=(2, 0))\n intensity -= intensity.min()\n intensity /= np.ptp(intensity)\n return intensity\n\n y, x = np.mgrid[5:0:-1, :5]\n z = -np.hypot(x - x.mean(), y - y.mean())\n\n for az, elev in itertools.product(range(0, 390, 30), range(0, 105, 15)):\n ls = mcolors.LightSource(az, elev)\n h1 = ls.hillshade(z)\n h2 = alternative_hillshade(az, elev, z)\n assert_array_almost_equal(h1, h2)\n\n\ndef test_light_source_planar_hillshading():\n """\n Ensure that the illumination intensity is correct for planar surfaces.\n """\n\n def plane(azimuth, elevation, x, y):\n """\n Create a plane whose normal vector is at the given azimuth and\n elevation.\n """\n theta, phi = _azimuth2math(azimuth, elevation)\n a, b, c = _sph2cart(theta, phi)\n z = -(a*x + b*y) / c\n return z\n\n def angled_plane(azimuth, elevation, angle, x, y):\n """\n Create a plane whose normal vector is at an angle from the given\n azimuth and elevation.\n """\n elevation = elevation + angle\n if elevation > 90:\n azimuth = (azimuth + 180) % 360\n elevation = (90 - elevation) % 90\n return plane(azimuth, elevation, x, y)\n\n y, x = np.mgrid[5:0:-1, :5]\n for az, elev in itertools.product(range(0, 390, 30), range(0, 105, 15)):\n ls = mcolors.LightSource(az, elev)\n\n # Make a plane at a range of angles to the illumination\n for angle in range(0, 105, 15):\n z = angled_plane(az, elev, angle, x, y)\n h = ls.hillshade(z)\n assert_array_almost_equal(h, np.cos(np.radians(angle)))\n\n\ndef test_color_names():\n assert mcolors.to_hex("blue") == "#0000ff"\n assert mcolors.to_hex("xkcd:blue") == "#0343df"\n assert mcolors.to_hex("tab:blue") == "#1f77b4"\n\n\ndef _sph2cart(theta, phi):\n x = np.cos(theta) * np.sin(phi)\n y = np.sin(theta) * np.sin(phi)\n z = np.cos(phi)\n return x, y, z\n\n\ndef _azimuth2math(azimuth, elevation):\n """\n Convert from clockwise-from-north and up-from-horizontal to mathematical\n conventions.\n """\n theta = np.radians((90 - azimuth) % 360)\n phi = np.radians(90 - elevation)\n return theta, phi\n\n\ndef test_pandas_iterable(pd):\n # Using a list or series yields equivalent\n # colormaps, i.e the series isn't seen as\n # a single color\n lst = ['red', 'blue', 'green']\n s = pd.Series(lst)\n cm1 = mcolors.ListedColormap(lst, N=5)\n cm2 = mcolors.ListedColormap(s, N=5)\n assert_array_equal(cm1.colors, cm2.colors)\n\n\n@pytest.mark.parametrize('name', sorted(mpl.colormaps()))\ndef test_colormap_reversing(name):\n """\n Check the generated _lut data of a colormap and corresponding reversed\n colormap if they are almost the same.\n """\n cmap = mpl.colormaps[name]\n cmap_r = cmap.reversed()\n if not cmap_r._isinit:\n cmap._init()\n cmap_r._init()\n assert_array_almost_equal(cmap._lut[:-3], cmap_r._lut[-4::-1])\n # Test the bad, over, under values too\n assert_array_almost_equal(cmap(-np.inf), cmap_r(np.inf))\n assert_array_almost_equal(cmap(np.inf), cmap_r(-np.inf))\n assert_array_almost_equal(cmap(np.nan), cmap_r(np.nan))\n\n\ndef test_has_alpha_channel():\n assert mcolors._has_alpha_channel((0, 0, 0, 0))\n assert mcolors._has_alpha_channel([1, 1, 1, 1])\n assert not mcolors._has_alpha_channel('blue') # 4-char string!\n assert not mcolors._has_alpha_channel('0.25')\n assert not mcolors._has_alpha_channel('r')\n assert not mcolors._has_alpha_channel((1, 0, 0))\n\n\ndef test_cn():\n matplotlib.rcParams['axes.prop_cycle'] = cycler('color',\n ['blue', 'r'])\n assert mcolors.to_hex("C0") == '#0000ff'\n assert mcolors.to_hex("C1") == '#ff0000'\n\n matplotlib.rcParams['axes.prop_cycle'] = cycler('color',\n ['xkcd:blue', 'r'])\n assert mcolors.to_hex("C0") == '#0343df'\n assert mcolors.to_hex("C1") == '#ff0000'\n assert mcolors.to_hex("C10") == '#0343df'\n assert mcolors.to_hex("C11") == '#ff0000'\n\n matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['8e4585', 'r'])\n\n assert mcolors.to_hex("C0") == '#8e4585'\n # if '8e4585' gets parsed as a float before it gets detected as a hex\n # colour it will be interpreted as a very large number.\n # this mustn't happen.\n assert mcolors.to_rgb("C0")[0] != np.inf\n\n\ndef test_conversions():\n # to_rgba_array("none") returns a (0, 4) array.\n assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4)))\n assert_array_equal(mcolors.to_rgba_array([]), np.zeros((0, 4)))\n # a list of grayscale levels, not a single color.\n assert_array_equal(\n mcolors.to_rgba_array([".2", ".5", ".8"]),\n np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]]))\n # alpha is properly set.\n assert mcolors.to_rgba((1, 1, 1), .5) == (1, 1, 1, .5)\n assert mcolors.to_rgba(".1", .5) == (.1, .1, .1, .5)\n # builtin round differs between py2 and py3.\n assert mcolors.to_hex((.7, .7, .7)) == "#b2b2b2"\n # hex roundtrip.\n hex_color = "#1234abcd"\n assert mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True) == \\n hex_color\n\n\ndef test_conversions_masked():\n x1 = np.ma.array(['k', 'b'], mask=[True, False])\n x2 = np.ma.array([[0, 0, 0, 1], [0, 0, 1, 1]])\n x2[0] = np.ma.masked\n assert mcolors.to_rgba(x1[0]) == (0, 0, 0, 0)\n assert_array_equal(mcolors.to_rgba_array(x1),\n [[0, 0, 0, 0], [0, 0, 1, 1]])\n assert_array_equal(mcolors.to_rgba_array(x2), mcolors.to_rgba_array(x1))\n\n\ndef test_to_rgba_array_single_str():\n # single color name is valid\n assert_array_equal(mcolors.to_rgba_array("red"), [(1, 0, 0, 1)])\n\n # single char color sequence is invalid\n with pytest.raises(ValueError,\n match="'rgb' is not a valid color value."):\n array = mcolors.to_rgba_array("rgb")\n\n\ndef test_to_rgba_array_2tuple_str():\n expected = np.array([[0, 0, 0, 1], [1, 1, 1, 1]])\n assert_array_equal(mcolors.to_rgba_array(("k", "w")), expected)\n\n\ndef test_to_rgba_array_alpha_array():\n with pytest.raises(ValueError, match="The number of colors must match"):\n mcolors.to_rgba_array(np.ones((5, 3), float), alpha=np.ones((2,)))\n alpha = [0.5, 0.6]\n c = mcolors.to_rgba_array(np.ones((2, 3), float), alpha=alpha)\n assert_array_equal(c[:, 3], alpha)\n c = mcolors.to_rgba_array(['r', 'g'], alpha=alpha)\n assert_array_equal(c[:, 3], alpha)\n\n\ndef test_to_rgba_array_accepts_color_alpha_tuple():\n assert_array_equal(\n mcolors.to_rgba_array(('black', 0.9)),\n [[0, 0, 0, 0.9]])\n\n\ndef test_to_rgba_array_explicit_alpha_overrides_tuple_alpha():\n assert_array_equal(\n mcolors.to_rgba_array(('black', 0.9), alpha=0.5),\n [[0, 0, 0, 0.5]])\n\n\ndef test_to_rgba_array_accepts_color_alpha_tuple_with_multiple_colors():\n color_array = np.array([[1., 1., 1., 1.], [0., 0., 1., 0.]])\n assert_array_equal(\n mcolors.to_rgba_array((color_array, 0.2)),\n [[1., 1., 1., 0.2], [0., 0., 1., 0.2]])\n\n color_sequence = [[1., 1., 1., 1.], [0., 0., 1., 0.]]\n assert_array_equal(\n mcolors.to_rgba_array((color_sequence, 0.4)),\n [[1., 1., 1., 0.4], [0., 0., 1., 0.4]])\n\n\ndef test_to_rgba_array_error_with_color_invalid_alpha_tuple():\n with pytest.raises(ValueError, match="'alpha' must be between 0 and 1,"):\n mcolors.to_rgba_array(('black', 2.0))\n\n\n@pytest.mark.parametrize('rgba_alpha',\n [('white', 0.5), ('#ffffff', 0.5), ('#ffffff00', 0.5),\n ((1.0, 1.0, 1.0, 1.0), 0.5)])\ndef test_to_rgba_accepts_color_alpha_tuple(rgba_alpha):\n assert mcolors.to_rgba(rgba_alpha) == (1, 1, 1, 0.5)\n\n\ndef test_to_rgba_explicit_alpha_overrides_tuple_alpha():\n assert mcolors.to_rgba(('red', 0.1), alpha=0.9) == (1, 0, 0, 0.9)\n\n\ndef test_to_rgba_error_with_color_invalid_alpha_tuple():\n with pytest.raises(ValueError, match="'alpha' must be between 0 and 1"):\n mcolors.to_rgba(('blue', 2.0))\n\n\n@pytest.mark.parametrize("bytes", (True, False))\ndef test_scalarmappable_to_rgba(bytes):\n sm = cm.ScalarMappable()\n alpha_1 = 255 if bytes else 1\n\n # uint8 RGBA\n x = np.ones((2, 3, 4), dtype=np.uint8)\n expected = x.copy() if bytes else x.astype(np.float32)/255\n np.testing.assert_almost_equal(sm.to_rgba(x, bytes=bytes), expected)\n # uint8 RGB\n expected[..., 3] = alpha_1\n np.testing.assert_almost_equal(sm.to_rgba(x[..., :3], bytes=bytes), expected)\n # uint8 masked RGBA\n xm = np.ma.masked_array(x, mask=np.zeros_like(x))\n xm.mask[0, 0, 0] = True\n expected = x.copy() if bytes else x.astype(np.float32)/255\n expected[0, 0, 3] = 0\n np.testing.assert_almost_equal(sm.to_rgba(xm, bytes=bytes), expected)\n # uint8 masked RGB\n expected[..., 3] = alpha_1\n expected[0, 0, 3] = 0\n np.testing.assert_almost_equal(sm.to_rgba(xm[..., :3], bytes=bytes), expected)\n\n # float RGBA\n x = np.ones((2, 3, 4), dtype=float) * 0.5\n expected = (x * 255).astype(np.uint8) if bytes else x.copy()\n np.testing.assert_almost_equal(sm.to_rgba(x, bytes=bytes), expected)\n # float RGB\n expected[..., 3] = alpha_1\n np.testing.assert_almost_equal(sm.to_rgba(x[..., :3], bytes=bytes), expected)\n # float masked RGBA\n xm = np.ma.masked_array(x, mask=np.zeros_like(x))\n xm.mask[0, 0, 0] = True\n expected = (x * 255).astype(np.uint8) if bytes else x.copy()\n expected[0, 0, 3] = 0\n np.testing.assert_almost_equal(sm.to_rgba(xm, bytes=bytes), expected)\n # float masked RGB\n expected[..., 3] = alpha_1\n expected[0, 0, 3] = 0\n np.testing.assert_almost_equal(sm.to_rgba(xm[..., :3], bytes=bytes), expected)\n\n\n@pytest.mark.parametrize("bytes", (True, False))\ndef test_scalarmappable_nan_to_rgba(bytes):\n sm = cm.ScalarMappable()\n\n # RGBA\n x = np.ones((2, 3, 4), dtype=float) * 0.5\n x[0, 0, 0] = np.nan\n expected = x.copy()\n expected[0, 0, :] = 0\n if bytes:\n expected = (expected * 255).astype(np.uint8)\n np.testing.assert_almost_equal(sm.to_rgba(x, bytes=bytes), expected)\n assert np.any(np.isnan(x)) # Input array should not be changed\n\n # RGB\n expected[..., 3] = 255 if bytes else 1\n expected[0, 0, 3] = 0\n np.testing.assert_almost_equal(sm.to_rgba(x[..., :3], bytes=bytes), expected)\n assert np.any(np.isnan(x)) # Input array should not be changed\n\n # Out-of-range fail\n x[1, 0, 0] = 42\n with pytest.raises(ValueError, match='0..1 range'):\n sm.to_rgba(x[..., :3], bytes=bytes)\n\n\ndef test_failed_conversions():\n with pytest.raises(ValueError):\n mcolors.to_rgba('5')\n with pytest.raises(ValueError):\n mcolors.to_rgba('-1')\n with pytest.raises(ValueError):\n mcolors.to_rgba('nan')\n with pytest.raises(ValueError):\n mcolors.to_rgba('unknown_color')\n with pytest.raises(ValueError):\n # Gray must be a string to distinguish 3-4 grays from RGB or RGBA.\n mcolors.to_rgba(0.4)\n\n\ndef test_grey_gray():\n color_mapping = mcolors._colors_full_map\n for k in color_mapping.keys():\n if 'grey' in k:\n assert color_mapping[k] == color_mapping[k.replace('grey', 'gray')]\n if 'gray' in k:\n assert color_mapping[k] == color_mapping[k.replace('gray', 'grey')]\n\n\ndef test_tableau_order():\n dflt_cycle = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',\n '#9467bd', '#8c564b', '#e377c2', '#7f7f7f',\n '#bcbd22', '#17becf']\n\n assert list(mcolors.TABLEAU_COLORS.values()) == dflt_cycle\n\n\ndef test_ndarray_subclass_norm():\n # Emulate an ndarray subclass that handles units\n # which objects when adding or subtracting with other\n # arrays. See #6622 and #8696\n class MyArray(np.ndarray):\n def __isub__(self, other): # type: ignore[misc]\n raise RuntimeError\n\n def __add__(self, other):\n raise RuntimeError\n\n data = np.arange(-10, 10, 1, dtype=float).reshape((10, 2))\n mydata = data.view(MyArray)\n\n for norm in [mcolors.Normalize(), mcolors.LogNorm(),\n mcolors.SymLogNorm(3, vmax=5, linscale=1, base=np.e),\n mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),\n mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max(),\n base=np.e),\n mcolors.PowerNorm(1)]:\n assert_array_equal(norm(mydata), norm(data))\n fig, ax = plt.subplots()\n ax.imshow(mydata, norm=norm)\n fig.canvas.draw() # Check that no warning is emitted.\n\n\ndef test_same_color():\n assert mcolors.same_color('k', (0, 0, 0))\n assert not mcolors.same_color('w', (1, 1, 0))\n assert mcolors.same_color(['red', 'blue'], ['r', 'b'])\n assert mcolors.same_color('none', 'none')\n assert not mcolors.same_color('none', 'red')\n with pytest.raises(ValueError):\n mcolors.same_color(['r', 'g', 'b'], ['r'])\n with pytest.raises(ValueError):\n mcolors.same_color(['red', 'green'], 'none')\n\n\ndef test_hex_shorthand_notation():\n assert mcolors.same_color("#123", "#112233")\n assert mcolors.same_color("#123a", "#112233aa")\n\n\ndef test_repr_png():\n cmap = mpl.colormaps['viridis']\n png = cmap._repr_png_()\n assert len(png) > 0\n img = Image.open(BytesIO(png))\n assert img.width > 0\n assert img.height > 0\n assert 'Title' in img.text\n assert 'Description' in img.text\n assert 'Author' in img.text\n assert 'Software' in img.text\n\n\ndef test_repr_html():\n cmap = mpl.colormaps['viridis']\n html = cmap._repr_html_()\n assert len(html) > 0\n png = cmap._repr_png_()\n assert base64.b64encode(png).decode('ascii') in html\n assert cmap.name in html\n assert html.startswith('<div')\n assert html.endswith('</div>')\n\n\ndef test_get_under_over_bad():\n cmap = mpl.colormaps['viridis']\n assert_array_equal(cmap.get_under(), cmap(-np.inf))\n assert_array_equal(cmap.get_over(), cmap(np.inf))\n assert_array_equal(cmap.get_bad(), cmap(np.nan))\n\n\n@pytest.mark.parametrize('kind', ('over', 'under', 'bad'))\ndef test_non_mutable_get_values(kind):\n cmap = copy.copy(mpl.colormaps['viridis'])\n init_value = getattr(cmap, f'get_{kind}')()\n getattr(cmap, f'set_{kind}')('k')\n black_value = getattr(cmap, f'get_{kind}')()\n assert np.all(black_value == [0, 0, 0, 1])\n assert not np.all(init_value == black_value)\n\n\ndef test_colormap_alpha_array():\n cmap = mpl.colormaps['viridis']\n vals = [-1, 0.5, 2] # under, valid, over\n with pytest.raises(ValueError, match="alpha is array-like but"):\n cmap(vals, alpha=[1, 1, 1, 1])\n alpha = np.array([0.1, 0.2, 0.3])\n c = cmap(vals, alpha=alpha)\n assert_array_equal(c[:, -1], alpha)\n c = cmap(vals, alpha=alpha, bytes=True)\n assert_array_equal(c[:, -1], (alpha * 255).astype(np.uint8))\n\n\ndef test_colormap_bad_data_with_alpha():\n cmap = mpl.colormaps['viridis']\n c = cmap(np.nan, alpha=0.5)\n assert c == (0, 0, 0, 0)\n c = cmap([0.5, np.nan], alpha=0.5)\n assert_array_equal(c[1], (0, 0, 0, 0))\n c = cmap([0.5, np.nan], alpha=[0.1, 0.2])\n assert_array_equal(c[1], (0, 0, 0, 0))\n c = cmap([[np.nan, 0.5], [0, 0]], alpha=0.5)\n assert_array_equal(c[0, 0], (0, 0, 0, 0))\n c = cmap([[np.nan, 0.5], [0, 0]], alpha=np.full((2, 2), 0.5))\n assert_array_equal(c[0, 0], (0, 0, 0, 0))\n\n\ndef test_2d_to_rgba():\n color = np.array([0.1, 0.2, 0.3])\n rgba_1d = mcolors.to_rgba(color.reshape(-1))\n rgba_2d = mcolors.to_rgba(color.reshape((1, -1)))\n assert rgba_1d == rgba_2d\n\n\ndef test_set_dict_to_rgba():\n # downstream libraries do this...\n # note we can't test this because it is not well-ordered\n # so just smoketest:\n colors = {(0, .5, 1), (1, .2, .5), (.4, 1, .2)}\n res = mcolors.to_rgba_array(colors)\n palette = {"red": (1, 0, 0), "green": (0, 1, 0), "blue": (0, 0, 1)}\n res = mcolors.to_rgba_array(palette.values())\n exp = np.eye(3)\n np.testing.assert_array_almost_equal(res[:, :-1], exp)\n\n\ndef test_norm_deepcopy():\n norm = mcolors.LogNorm()\n norm.vmin = 0.0002\n norm2 = copy.deepcopy(norm)\n assert norm2.vmin == norm.vmin\n assert isinstance(norm2._scale, mscale.LogScale)\n norm = mcolors.Normalize()\n norm.vmin = 0.0002\n norm2 = copy.deepcopy(norm)\n assert norm2._scale is None\n assert norm2.vmin == norm.vmin\n\n\ndef test_set_clim_emits_single_callback():\n data = np.array([[1, 2], [3, 4]])\n fig, ax = plt.subplots()\n image = ax.imshow(data, cmap='viridis')\n\n callback = unittest.mock.Mock()\n image.norm.callbacks.connect('changed', callback)\n\n callback.assert_not_called()\n\n # Call set_clim() to update the limits\n image.set_clim(1, 5)\n\n # Assert that only one "changed" callback is sent after calling set_clim()\n callback.assert_called_once()\n\n\ndef test_norm_callback():\n increment = unittest.mock.Mock(return_value=None)\n\n norm = mcolors.Normalize()\n norm.callbacks.connect('changed', increment)\n # Haven't updated anything, so call count should be 0\n assert increment.call_count == 0\n\n # Now change vmin and vmax to test callbacks\n norm.vmin = 1\n assert increment.call_count == 1\n norm.vmax = 5\n assert increment.call_count == 2\n # callback shouldn't be called if setting to the same value\n norm.vmin = 1\n assert increment.call_count == 2\n norm.vmax = 5\n assert increment.call_count == 2\n\n # We only want autoscale() calls to send out one update signal\n increment.call_count = 0\n norm.autoscale([0, 1, 2])\n assert increment.call_count == 1\n\n\ndef test_scalarmappable_norm_update():\n norm = mcolors.Normalize()\n sm = matplotlib.cm.ScalarMappable(norm=norm, cmap='plasma')\n # sm doesn't have a stale attribute at first, set it to False\n sm.stale = False\n # The mappable should be stale after updating vmin/vmax\n norm.vmin = 5\n assert sm.stale\n sm.stale = False\n norm.vmax = 5\n assert sm.stale\n sm.stale = False\n norm.clip = True\n assert sm.stale\n # change to the CenteredNorm and TwoSlopeNorm to test those\n # Also make sure that updating the norm directly and with\n # set_norm both update the Norm callback\n norm = mcolors.CenteredNorm()\n sm.norm = norm\n sm.stale = False\n norm.vcenter = 1\n assert sm.stale\n norm = mcolors.TwoSlopeNorm(vcenter=0, vmin=-1, vmax=1)\n sm.set_norm(norm)\n sm.stale = False\n norm.vcenter = 1\n assert sm.stale\n\n\n@check_figures_equal(extensions=['png'])\ndef test_norm_update_figs(fig_test, fig_ref):\n ax_ref = fig_ref.add_subplot()\n ax_test = fig_test.add_subplot()\n\n z = np.arange(100).reshape((10, 10))\n ax_ref.imshow(z, norm=mcolors.Normalize(10, 90))\n\n # Create the norm beforehand with different limits and then update\n # after adding to the plot\n norm = mcolors.Normalize(0, 1)\n ax_test.imshow(z, norm=norm)\n # Force initial draw to make sure it isn't already stale\n fig_test.canvas.draw()\n norm.vmin, norm.vmax = 10, 90\n\n\ndef test_make_norm_from_scale_name():\n logitnorm = mcolors.make_norm_from_scale(\n mscale.LogitScale, mcolors.Normalize)\n assert logitnorm.__name__ == logitnorm.__qualname__ == "LogitScaleNorm"\n\n\ndef test_color_sequences():\n # basic access\n assert plt.color_sequences is matplotlib.color_sequences # same registry\n assert list(plt.color_sequences) == [\n 'tab10', 'tab20', 'tab20b', 'tab20c', 'Pastel1', 'Pastel2', 'Paired',\n 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'petroff10']\n assert len(plt.color_sequences['tab10']) == 10\n assert len(plt.color_sequences['tab20']) == 20\n\n tab_colors = [\n 'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',\n 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']\n for seq_color, tab_color in zip(plt.color_sequences['tab10'], tab_colors):\n assert mcolors.same_color(seq_color, tab_color)\n\n # registering\n with pytest.raises(ValueError, match="reserved name"):\n plt.color_sequences.register('tab10', ['r', 'g', 'b'])\n with pytest.raises(ValueError, match="not a valid color specification"):\n plt.color_sequences.register('invalid', ['not a color'])\n\n rgb_colors = ['r', 'g', 'b']\n plt.color_sequences.register('rgb', rgb_colors)\n assert plt.color_sequences['rgb'] == ['r', 'g', 'b']\n # should not affect the registered sequence because input is copied\n rgb_colors.append('c')\n assert plt.color_sequences['rgb'] == ['r', 'g', 'b']\n # should not affect the registered sequence because returned list is a copy\n plt.color_sequences['rgb'].append('c')\n assert plt.color_sequences['rgb'] == ['r', 'g', 'b']\n\n # unregister\n plt.color_sequences.unregister('rgb')\n with pytest.raises(KeyError):\n plt.color_sequences['rgb'] # rgb is gone\n plt.color_sequences.unregister('rgb') # multiple unregisters are ok\n with pytest.raises(ValueError, match="Cannot unregister builtin"):\n plt.color_sequences.unregister('tab10')\n\n\ndef test_cm_set_cmap_error():\n sm = cm.ScalarMappable()\n # Pick a name we are pretty sure will never be a colormap name\n bad_cmap = 'AardvarksAreAwkward'\n with pytest.raises(ValueError, match=bad_cmap):\n sm.set_cmap(bad_cmap)\n\n\ndef test_set_cmap_mismatched_name():\n cmap = matplotlib.colormaps["viridis"].with_extremes(over='r')\n # register it with different names\n cmap.name = "test-cmap"\n matplotlib.colormaps.register(name='wrong-cmap', cmap=cmap)\n\n plt.set_cmap("wrong-cmap")\n cmap_returned = plt.get_cmap("wrong-cmap")\n assert cmap_returned == cmap\n assert cmap_returned.name == "wrong-cmap"\n\n\ndef test_cmap_alias_names():\n assert matplotlib.colormaps["gray"].name == "gray" # original\n assert matplotlib.colormaps["grey"].name == "grey" # alias\n\n\ndef test_to_rgba_array_none_color_with_alpha_param():\n # effective alpha for color "none" must always be 0 to achieve a vanishing color\n # even explicit alpha must be ignored\n c = ["blue", "none"]\n alpha = [1, 1]\n assert_array_equal(\n to_rgba_array(c, alpha), [[0., 0., 1., 1.], [0., 0., 0., 0.]]\n )\n\n\n@pytest.mark.parametrize('input, expected',\n [('red', True),\n (('red', 0.5), True),\n (('red', 2), False),\n (['red', 0.5], False),\n (('red', 'blue'), False),\n (['red', 'blue'], False),\n ('C3', True),\n (('C3', 0.5), True)])\ndef test_is_color_like(input, expected):\n assert is_color_like(input) is expected\n\n\ndef test_colorizer_vmin_vmax():\n ca = mcolorizer.Colorizer()\n assert ca.vmin is None\n assert ca.vmax is None\n ca.vmin = 1\n ca.vmax = 3\n assert ca.vmin == 1.0\n assert ca.vmax == 3.0\n assert ca.norm.vmin == 1.0\n assert ca.norm.vmax == 3.0\n | .venv\Lib\site-packages\matplotlib\tests\test_colors.py | test_colors.py | Python | 61,215 | 0.75 | 0.09502 | 0.104372 | node-utils | 944 | 2024-02-02T15:29:10.570465 | MIT | true | 0a36c65ad9f5ce664e901e6695080014 |
from pathlib import Path\nimport shutil\n\nimport pytest\nfrom pytest import approx\n\nfrom matplotlib.testing.compare import compare_images\nfrom matplotlib.testing.decorators import _image_directories\n\n\n# Tests of the image comparison algorithm.\n@pytest.mark.parametrize(\n 'im1, im2, tol, expect_rms',\n [\n # Comparison of an image and the same image with minor differences.\n # This expects the images to compare equal under normal tolerance, and\n # have a small RMS.\n ('basn3p02.png', 'basn3p02-minorchange.png', 10, None),\n # Now test with no tolerance.\n ('basn3p02.png', 'basn3p02-minorchange.png', 0, 6.50646),\n # Comparison with an image that is shifted by 1px in the X axis.\n ('basn3p02.png', 'basn3p02-1px-offset.png', 0, 90.15611),\n # Comparison with an image with half the pixels shifted by 1px in the X\n # axis.\n ('basn3p02.png', 'basn3p02-half-1px-offset.png', 0, 63.75),\n # Comparison of an image and the same image scrambled.\n # This expects the images to compare completely different, with a very\n # large RMS.\n # Note: The image has been scrambled in a specific way, by having\n # each color component of each pixel randomly placed somewhere in the\n # image. It contains exactly the same number of pixels of each color\n # value of R, G and B, but in a totally different position.\n # Test with no tolerance to make sure that we pick up even a very small\n # RMS error.\n ('basn3p02.png', 'basn3p02-scrambled.png', 0, 172.63582),\n # Comparison of an image and a slightly brighter image.\n # The two images are solid color, with the second image being exactly 1\n # color value brighter.\n # This expects the images to compare equal under normal tolerance, and\n # have an RMS of exactly 1.\n ('all127.png', 'all128.png', 0, 1),\n # Now test the reverse comparison.\n ('all128.png', 'all127.png', 0, 1),\n ])\ndef test_image_comparison_expect_rms(im1, im2, tol, expect_rms, tmp_path,\n monkeypatch):\n """\n Compare two images, expecting a particular RMS error.\n\n im1 and im2 are filenames relative to the baseline_dir directory.\n\n tol is the tolerance to pass to compare_images.\n\n expect_rms is the expected RMS value, or None. If None, the test will\n succeed if compare_images succeeds. Otherwise, the test will succeed if\n compare_images fails and returns an RMS error almost equal to this value.\n """\n # Change the working directory using monkeypatch to use a temporary\n # test specific directory\n monkeypatch.chdir(tmp_path)\n baseline_dir, result_dir = map(Path, _image_directories(lambda: "dummy"))\n # Copy "test" image to result_dir, so that compare_images writes\n # the diff to result_dir, rather than to the source tree\n result_im2 = result_dir / im1\n shutil.copyfile(baseline_dir / im2, result_im2)\n results = compare_images(\n baseline_dir / im1, result_im2, tol=tol, in_decorator=True)\n\n if expect_rms is None:\n assert results is None\n else:\n assert results is not None\n assert results['rms'] == approx(expect_rms, abs=1e-4)\n | .venv\Lib\site-packages\matplotlib\tests\test_compare_images.py | test_compare_images.py | Python | 3,260 | 0.95 | 0.054795 | 0.415385 | react-lib | 69 | 2023-08-10T11:32:48.280774 | BSD-3-Clause | true | ee8f457f96b4c521651fa6b90dfb46ac |
import gc\nimport platform\n\nimport numpy as np\nimport pytest\n\nimport matplotlib as mpl\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as mtransforms\nfrom matplotlib import gridspec, ticker\n\n\npytestmark = [\n pytest.mark.usefixtures('text_placeholders')\n]\n\n\ndef example_plot(ax, fontsize=12, nodec=False):\n ax.plot([1, 2])\n ax.locator_params(nbins=3)\n if not nodec:\n ax.set_xlabel('x-label', fontsize=fontsize)\n ax.set_ylabel('y-label', fontsize=fontsize)\n ax.set_title('Title', fontsize=fontsize)\n else:\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n\ndef example_pcolor(ax, fontsize=12):\n dx, dy = 0.6, 0.6\n y, x = np.mgrid[slice(-3, 3 + dy, dy),\n slice(-3, 3 + dx, dx)]\n z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)\n pcm = ax.pcolormesh(x, y, z[:-1, :-1], cmap='RdBu_r', vmin=-1., vmax=1.,\n rasterized=True)\n ax.set_xlabel('x-label', fontsize=fontsize)\n ax.set_ylabel('y-label', fontsize=fontsize)\n ax.set_title('Title', fontsize=fontsize)\n return pcm\n\n\n@image_comparison(['constrained_layout1.png'], style='mpl20')\ndef test_constrained_layout1():\n """Test constrained_layout for a single subplot"""\n fig = plt.figure(layout="constrained")\n ax = fig.add_subplot()\n example_plot(ax, fontsize=24)\n\n\n@image_comparison(['constrained_layout2.png'], style='mpl20')\ndef test_constrained_layout2():\n """Test constrained_layout for 2x2 subplots"""\n fig, axs = plt.subplots(2, 2, layout="constrained")\n for ax in axs.flat:\n example_plot(ax, fontsize=24)\n\n\n@image_comparison(['constrained_layout3.png'], style='mpl20')\ndef test_constrained_layout3():\n """Test constrained_layout for colorbars with subplots"""\n\n fig, axs = plt.subplots(2, 2, layout="constrained")\n for nn, ax in enumerate(axs.flat):\n pcm = example_pcolor(ax, fontsize=24)\n if nn == 3:\n pad = 0.08\n else:\n pad = 0.02 # default\n fig.colorbar(pcm, ax=ax, pad=pad)\n\n\n@image_comparison(['constrained_layout4.png'], style='mpl20')\ndef test_constrained_layout4():\n """Test constrained_layout for a single colorbar with subplots"""\n\n fig, axs = plt.subplots(2, 2, layout="constrained")\n for ax in axs.flat:\n pcm = example_pcolor(ax, fontsize=24)\n fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6)\n\n\n@image_comparison(['constrained_layout5.png'], style='mpl20')\ndef test_constrained_layout5():\n """\n Test constrained_layout for a single colorbar with subplots,\n colorbar bottom\n """\n\n fig, axs = plt.subplots(2, 2, layout="constrained")\n for ax in axs.flat:\n pcm = example_pcolor(ax, fontsize=24)\n fig.colorbar(pcm, ax=axs,\n use_gridspec=False, pad=0.01, shrink=0.6,\n location='bottom')\n\n\n@image_comparison(['constrained_layout6.png'], style='mpl20')\ndef test_constrained_layout6():\n """Test constrained_layout for nested gridspecs"""\n fig = plt.figure(layout="constrained")\n gs = fig.add_gridspec(1, 2, figure=fig)\n gsl = gs[0].subgridspec(2, 2)\n gsr = gs[1].subgridspec(1, 2)\n axsl = []\n for gs in gsl:\n ax = fig.add_subplot(gs)\n axsl += [ax]\n example_plot(ax, fontsize=12)\n ax.set_xlabel('x-label\nMultiLine')\n axsr = []\n for gs in gsr:\n ax = fig.add_subplot(gs)\n axsr += [ax]\n pcm = example_pcolor(ax, fontsize=12)\n\n fig.colorbar(pcm, ax=axsr,\n pad=0.01, shrink=0.99, location='bottom',\n ticks=ticker.MaxNLocator(nbins=5))\n\n\ndef test_identical_subgridspec():\n\n fig = plt.figure(constrained_layout=True)\n\n GS = fig.add_gridspec(2, 1)\n\n GSA = GS[0].subgridspec(1, 3)\n GSB = GS[1].subgridspec(1, 3)\n\n axa = []\n axb = []\n for i in range(3):\n axa += [fig.add_subplot(GSA[i])]\n axb += [fig.add_subplot(GSB[i])]\n\n fig.draw_without_rendering()\n # check first row above second\n assert axa[0].get_position().y0 > axb[0].get_position().y1\n\n\ndef test_constrained_layout7():\n """Test for proper warning if fig not set in GridSpec"""\n with pytest.warns(\n UserWarning, match=('There are no gridspecs with layoutgrids. '\n 'Possibly did not call parent GridSpec with '\n 'the "figure" keyword')):\n fig = plt.figure(layout="constrained")\n gs = gridspec.GridSpec(1, 2)\n gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0])\n gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1])\n for gs in gsl:\n fig.add_subplot(gs)\n # need to trigger a draw to get warning\n fig.draw_without_rendering()\n\n\n@image_comparison(['constrained_layout8.png'], style='mpl20')\ndef test_constrained_layout8():\n """Test for gridspecs that are not completely full"""\n\n fig = plt.figure(figsize=(10, 5), layout="constrained")\n gs = gridspec.GridSpec(3, 5, figure=fig)\n axs = []\n for j in [0, 1]:\n if j == 0:\n ilist = [1]\n else:\n ilist = [0, 4]\n for i in ilist:\n ax = fig.add_subplot(gs[j, i])\n axs += [ax]\n example_pcolor(ax, fontsize=9)\n if i > 0:\n ax.set_ylabel('')\n if j < 1:\n ax.set_xlabel('')\n ax.set_title('')\n ax = fig.add_subplot(gs[2, :])\n axs += [ax]\n pcm = example_pcolor(ax, fontsize=9)\n\n fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6)\n\n\n@image_comparison(['constrained_layout9.png'], style='mpl20')\ndef test_constrained_layout9():\n """Test for handling suptitle and for sharex and sharey"""\n\n fig, axs = plt.subplots(2, 2, layout="constrained",\n sharex=False, sharey=False)\n for ax in axs.flat:\n pcm = example_pcolor(ax, fontsize=24)\n ax.set_xlabel('')\n ax.set_ylabel('')\n ax.set_aspect(2.)\n fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6)\n fig.suptitle('Test Suptitle', fontsize=28)\n\n\n@image_comparison(['constrained_layout10.png'], style='mpl20',\n tol=0 if platform.machine() == 'x86_64' else 0.032)\ndef test_constrained_layout10():\n """Test for handling legend outside axis"""\n fig, axs = plt.subplots(2, 2, layout="constrained")\n for ax in axs.flat:\n ax.plot(np.arange(12), label='This is a label')\n ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5))\n\n\n@image_comparison(['constrained_layout11.png'], style='mpl20')\ndef test_constrained_layout11():\n """Test for multiple nested gridspecs"""\n\n fig = plt.figure(layout="constrained", figsize=(13, 3))\n gs0 = gridspec.GridSpec(1, 2, figure=fig)\n gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0])\n gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1])\n ax = fig.add_subplot(gs0[1])\n example_plot(ax, fontsize=9)\n axs = []\n for gs in gsl0:\n ax = fig.add_subplot(gs)\n axs += [ax]\n pcm = example_pcolor(ax, fontsize=9)\n fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.)\n ax = fig.add_subplot(gsl[0])\n example_plot(ax, fontsize=9)\n\n\n@image_comparison(['constrained_layout11rat.png'], style='mpl20')\ndef test_constrained_layout11rat():\n """Test for multiple nested gridspecs with width_ratios"""\n\n fig = plt.figure(layout="constrained", figsize=(10, 3))\n gs0 = gridspec.GridSpec(1, 2, figure=fig, width_ratios=[6, 1])\n gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0])\n gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1], height_ratios=[2, 1])\n ax = fig.add_subplot(gs0[1])\n example_plot(ax, fontsize=9)\n axs = []\n for gs in gsl0:\n ax = fig.add_subplot(gs)\n axs += [ax]\n pcm = example_pcolor(ax, fontsize=9)\n fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.)\n ax = fig.add_subplot(gsl[0])\n example_plot(ax, fontsize=9)\n\n\n@image_comparison(['constrained_layout12.png'], style='mpl20')\ndef test_constrained_layout12():\n """Test that very unbalanced labeling still works."""\n fig = plt.figure(layout="constrained", figsize=(6, 8))\n\n gs0 = gridspec.GridSpec(6, 2, figure=fig)\n\n ax1 = fig.add_subplot(gs0[:3, 1])\n ax2 = fig.add_subplot(gs0[3:, 1])\n\n example_plot(ax1, fontsize=18)\n example_plot(ax2, fontsize=18)\n\n ax = fig.add_subplot(gs0[0:2, 0])\n example_plot(ax, nodec=True)\n ax = fig.add_subplot(gs0[2:4, 0])\n example_plot(ax, nodec=True)\n ax = fig.add_subplot(gs0[4:, 0])\n example_plot(ax, nodec=True)\n ax.set_xlabel('x-label')\n\n\n@image_comparison(['constrained_layout13.png'], style='mpl20')\ndef test_constrained_layout13():\n """Test that padding works."""\n fig, axs = plt.subplots(2, 2, layout="constrained")\n for ax in axs.flat:\n pcm = example_pcolor(ax, fontsize=12)\n fig.colorbar(pcm, ax=ax, shrink=0.6, aspect=20., pad=0.02)\n with pytest.raises(TypeError):\n fig.get_layout_engine().set(wpad=1, hpad=2)\n fig.get_layout_engine().set(w_pad=24./72., h_pad=24./72.)\n\n\n@image_comparison(['constrained_layout14.png'], style='mpl20')\ndef test_constrained_layout14():\n """Test that padding works."""\n fig, axs = plt.subplots(2, 2, layout="constrained")\n for ax in axs.flat:\n pcm = example_pcolor(ax, fontsize=12)\n fig.colorbar(pcm, ax=ax, shrink=0.6, aspect=20., pad=0.02)\n fig.get_layout_engine().set(\n w_pad=3./72., h_pad=3./72.,\n hspace=0.2, wspace=0.2)\n\n\n@image_comparison(['constrained_layout15.png'], style='mpl20')\ndef test_constrained_layout15():\n """Test that rcparams work."""\n mpl.rcParams['figure.constrained_layout.use'] = True\n fig, axs = plt.subplots(2, 2)\n for ax in axs.flat:\n example_plot(ax, fontsize=12)\n\n\n@image_comparison(['constrained_layout16.png'], style='mpl20')\ndef test_constrained_layout16():\n """Test ax.set_position."""\n fig, ax = plt.subplots(layout="constrained")\n example_plot(ax, fontsize=12)\n ax2 = fig.add_axes([0.2, 0.2, 0.4, 0.4])\n\n\n@image_comparison(['constrained_layout17.png'], style='mpl20')\ndef test_constrained_layout17():\n """Test uneven gridspecs"""\n fig = plt.figure(layout="constrained")\n gs = gridspec.GridSpec(3, 3, figure=fig)\n\n ax1 = fig.add_subplot(gs[0, 0])\n ax2 = fig.add_subplot(gs[0, 1:])\n ax3 = fig.add_subplot(gs[1:, 0:2])\n ax4 = fig.add_subplot(gs[1:, -1])\n\n example_plot(ax1)\n example_plot(ax2)\n example_plot(ax3)\n example_plot(ax4)\n\n\ndef test_constrained_layout18():\n """Test twinx"""\n fig, ax = plt.subplots(layout="constrained")\n ax2 = ax.twinx()\n example_plot(ax)\n example_plot(ax2, fontsize=24)\n fig.draw_without_rendering()\n assert all(ax.get_position().extents == ax2.get_position().extents)\n\n\ndef test_constrained_layout19():\n """Test twiny"""\n fig, ax = plt.subplots(layout="constrained")\n ax2 = ax.twiny()\n example_plot(ax)\n example_plot(ax2, fontsize=24)\n ax2.set_title('')\n ax.set_title('')\n fig.draw_without_rendering()\n assert all(ax.get_position().extents == ax2.get_position().extents)\n\n\ndef test_constrained_layout20():\n """Smoke test cl does not mess up added Axes"""\n gx = np.linspace(-5, 5, 4)\n img = np.hypot(gx, gx[:, None])\n\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1])\n mesh = ax.pcolormesh(gx, gx, img[:-1, :-1])\n fig.colorbar(mesh)\n\n\ndef test_constrained_layout21():\n """#11035: repeated calls to suptitle should not alter the layout"""\n fig, ax = plt.subplots(layout="constrained")\n\n fig.suptitle("Suptitle0")\n fig.draw_without_rendering()\n extents0 = np.copy(ax.get_position().extents)\n\n fig.suptitle("Suptitle1")\n fig.draw_without_rendering()\n extents1 = np.copy(ax.get_position().extents)\n\n np.testing.assert_allclose(extents0, extents1)\n\n\ndef test_constrained_layout22():\n """#11035: suptitle should not be include in CL if manually positioned"""\n fig, ax = plt.subplots(layout="constrained")\n\n fig.draw_without_rendering()\n extents0 = np.copy(ax.get_position().extents)\n\n fig.suptitle("Suptitle", y=0.5)\n fig.draw_without_rendering()\n extents1 = np.copy(ax.get_position().extents)\n\n np.testing.assert_allclose(extents0, extents1)\n\n\ndef test_constrained_layout23():\n """\n Comment in #11035: suptitle used to cause an exception when\n reusing a figure w/ CL with ``clear=True``.\n """\n\n for i in range(2):\n fig = plt.figure(layout="constrained", clear=True, num="123")\n gs = fig.add_gridspec(1, 2)\n sub = gs[0].subgridspec(2, 2)\n fig.suptitle(f"Suptitle{i}")\n\n\n@image_comparison(['test_colorbar_location.png'],\n remove_text=True, style='mpl20')\ndef test_colorbar_location():\n """\n Test that colorbar handling is as expected for various complicated\n cases...\n """\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n fig, axs = plt.subplots(4, 5, layout="constrained")\n for ax in axs.flat:\n pcm = example_pcolor(ax)\n ax.set_xlabel('')\n ax.set_ylabel('')\n fig.colorbar(pcm, ax=axs[:, 1], shrink=0.4)\n fig.colorbar(pcm, ax=axs[-1, :2], shrink=0.5, location='bottom')\n fig.colorbar(pcm, ax=axs[0, 2:], shrink=0.5, location='bottom', pad=0.05)\n fig.colorbar(pcm, ax=axs[-2, 3:], shrink=0.5, location='top')\n fig.colorbar(pcm, ax=axs[0, 0], shrink=0.5, location='left')\n fig.colorbar(pcm, ax=axs[1:3, 2], shrink=0.5, location='right')\n\n\ndef test_hidden_axes():\n # test that if we make an Axes not visible that constrained_layout\n # still works. Note the axes still takes space in the layout\n # (as does a gridspec slot that is empty)\n fig, axs = plt.subplots(2, 2, layout="constrained")\n axs[0, 1].set_visible(False)\n fig.draw_without_rendering()\n extents1 = np.copy(axs[0, 0].get_position().extents)\n\n np.testing.assert_allclose(\n extents1, [0.046918, 0.541204, 0.477409, 0.980555], rtol=1e-5)\n\n\ndef test_colorbar_align():\n for location in ['right', 'left', 'top', 'bottom']:\n fig, axs = plt.subplots(2, 2, layout="constrained")\n cbs = []\n for nn, ax in enumerate(axs.flat):\n ax.tick_params(direction='in')\n pc = example_pcolor(ax)\n cb = fig.colorbar(pc, ax=ax, location=location, shrink=0.6,\n pad=0.04)\n cbs += [cb]\n cb.ax.tick_params(direction='in')\n if nn != 1:\n cb.ax.xaxis.set_ticks([])\n cb.ax.yaxis.set_ticks([])\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72,\n hspace=0.1, wspace=0.1)\n\n fig.draw_without_rendering()\n if location in ['left', 'right']:\n np.testing.assert_allclose(cbs[0].ax.get_position().x0,\n cbs[2].ax.get_position().x0)\n np.testing.assert_allclose(cbs[1].ax.get_position().x0,\n cbs[3].ax.get_position().x0)\n else:\n np.testing.assert_allclose(cbs[0].ax.get_position().y0,\n cbs[1].ax.get_position().y0)\n np.testing.assert_allclose(cbs[2].ax.get_position().y0,\n cbs[3].ax.get_position().y0)\n\n\n@image_comparison(['test_colorbars_no_overlapV.png'], style='mpl20')\ndef test_colorbars_no_overlapV():\n fig = plt.figure(figsize=(2, 4), layout="constrained")\n axs = fig.subplots(2, 1, sharex=True, sharey=True)\n for ax in axs:\n ax.yaxis.set_major_formatter(ticker.NullFormatter())\n ax.tick_params(axis='both', direction='in')\n im = ax.imshow([[1, 2], [3, 4]])\n fig.colorbar(im, ax=ax, orientation="vertical")\n fig.suptitle("foo")\n\n\n@image_comparison(['test_colorbars_no_overlapH.png'], style='mpl20')\ndef test_colorbars_no_overlapH():\n fig = plt.figure(figsize=(4, 2), layout="constrained")\n fig.suptitle("foo")\n axs = fig.subplots(1, 2, sharex=True, sharey=True)\n for ax in axs:\n ax.yaxis.set_major_formatter(ticker.NullFormatter())\n ax.tick_params(axis='both', direction='in')\n im = ax.imshow([[1, 2], [3, 4]])\n fig.colorbar(im, ax=ax, orientation="horizontal")\n\n\ndef test_manually_set_position():\n fig, axs = plt.subplots(1, 2, layout="constrained")\n axs[0].set_position([0.2, 0.2, 0.3, 0.3])\n fig.draw_without_rendering()\n pp = axs[0].get_position()\n np.testing.assert_allclose(pp, [[0.2, 0.2], [0.5, 0.5]])\n\n fig, axs = plt.subplots(1, 2, layout="constrained")\n axs[0].set_position([0.2, 0.2, 0.3, 0.3])\n pc = axs[0].pcolormesh(np.random.rand(20, 20))\n fig.colorbar(pc, ax=axs[0])\n fig.draw_without_rendering()\n pp = axs[0].get_position()\n np.testing.assert_allclose(pp, [[0.2, 0.2], [0.44, 0.5]])\n\n\n@image_comparison(['test_bboxtight.png'],\n remove_text=True, style='mpl20',\n savefig_kwarg={'bbox_inches': 'tight'})\ndef test_bboxtight():\n fig, ax = plt.subplots(layout="constrained")\n ax.set_aspect(1.)\n\n\n@image_comparison(['test_bbox.png'],\n remove_text=True, style='mpl20',\n savefig_kwarg={'bbox_inches':\n mtransforms.Bbox([[0.5, 0], [2.5, 2]])})\ndef test_bbox():\n fig, ax = plt.subplots(layout="constrained")\n ax.set_aspect(1.)\n\n\ndef test_align_labels():\n """\n Tests for a bug in which constrained layout and align_ylabels on\n three unevenly sized subplots, one of whose y tick labels include\n negative numbers, drives the non-negative subplots' y labels off\n the edge of the plot\n """\n fig, (ax3, ax1, ax2) = plt.subplots(3, 1, layout="constrained",\n figsize=(6.4, 8),\n gridspec_kw={"height_ratios": (1, 1,\n 0.7)})\n\n ax1.set_ylim(0, 1)\n ax1.set_ylabel("Label")\n\n ax2.set_ylim(-1.5, 1.5)\n ax2.set_ylabel("Label")\n\n ax3.set_ylim(0, 1)\n ax3.set_ylabel("Label")\n\n fig.align_ylabels(axs=(ax3, ax1, ax2))\n\n fig.draw_without_rendering()\n after_align = [ax1.yaxis.label.get_window_extent(),\n ax2.yaxis.label.get_window_extent(),\n ax3.yaxis.label.get_window_extent()]\n # ensure labels are approximately aligned\n np.testing.assert_allclose([after_align[0].x0, after_align[2].x0],\n after_align[1].x0, rtol=0, atol=1e-05)\n # ensure labels do not go off the edge\n assert after_align[0].x0 >= 1\n\n\ndef test_suplabels():\n fig, ax = plt.subplots(layout="constrained")\n fig.draw_without_rendering()\n pos0 = ax.get_tightbbox(fig.canvas.get_renderer())\n fig.supxlabel('Boo')\n fig.supylabel('Booy')\n fig.draw_without_rendering()\n pos = ax.get_tightbbox(fig.canvas.get_renderer())\n assert pos.y0 > pos0.y0 + 10.0\n assert pos.x0 > pos0.x0 + 10.0\n\n fig, ax = plt.subplots(layout="constrained")\n fig.draw_without_rendering()\n pos0 = ax.get_tightbbox(fig.canvas.get_renderer())\n # check that specifying x (y) doesn't ruin the layout\n fig.supxlabel('Boo', x=0.5)\n fig.supylabel('Boo', y=0.5)\n fig.draw_without_rendering()\n pos = ax.get_tightbbox(fig.canvas.get_renderer())\n assert pos.y0 > pos0.y0 + 10.0\n assert pos.x0 > pos0.x0 + 10.0\n\n\ndef test_gridspec_addressing():\n fig = plt.figure()\n gs = fig.add_gridspec(3, 3)\n sp = fig.add_subplot(gs[0:, 1:])\n fig.draw_without_rendering()\n\n\ndef test_discouraged_api():\n fig, ax = plt.subplots(constrained_layout=True)\n fig.draw_without_rendering()\n\n with pytest.warns(PendingDeprecationWarning,\n match="will be deprecated"):\n fig, ax = plt.subplots()\n fig.set_constrained_layout(True)\n fig.draw_without_rendering()\n\n with pytest.warns(PendingDeprecationWarning,\n match="will be deprecated"):\n fig, ax = plt.subplots()\n fig.set_constrained_layout({'w_pad': 0.02, 'h_pad': 0.02})\n fig.draw_without_rendering()\n\n\ndef test_kwargs():\n fig, ax = plt.subplots(constrained_layout={'h_pad': 0.02})\n fig.draw_without_rendering()\n\n\ndef test_rect():\n fig, ax = plt.subplots(layout='constrained')\n fig.get_layout_engine().set(rect=[0, 0, 0.5, 0.5])\n fig.draw_without_rendering()\n ppos = ax.get_position()\n assert ppos.x1 < 0.5\n assert ppos.y1 < 0.5\n\n fig, ax = plt.subplots(layout='constrained')\n fig.get_layout_engine().set(rect=[0.2, 0.2, 0.3, 0.3])\n fig.draw_without_rendering()\n ppos = ax.get_position()\n assert ppos.x1 < 0.5\n assert ppos.y1 < 0.5\n assert ppos.x0 > 0.2\n assert ppos.y0 > 0.2\n\n\ndef test_compressed1():\n fig, axs = plt.subplots(3, 2, layout='compressed',\n sharex=True, sharey=True)\n for ax in axs.flat:\n pc = ax.imshow(np.random.randn(20, 20))\n\n fig.colorbar(pc, ax=axs)\n fig.draw_without_rendering()\n\n pos = axs[0, 0].get_position()\n np.testing.assert_allclose(pos.x0, 0.2381, atol=1e-2)\n pos = axs[0, 1].get_position()\n np.testing.assert_allclose(pos.x1, 0.7024, atol=1e-3)\n\n # wider than tall\n fig, axs = plt.subplots(2, 3, layout='compressed',\n sharex=True, sharey=True, figsize=(5, 4))\n for ax in axs.flat:\n pc = ax.imshow(np.random.randn(20, 20))\n\n fig.colorbar(pc, ax=axs)\n fig.draw_without_rendering()\n\n pos = axs[0, 0].get_position()\n np.testing.assert_allclose(pos.x0, 0.05653, atol=1e-3)\n np.testing.assert_allclose(pos.y1, 0.8603, atol=1e-2)\n pos = axs[1, 2].get_position()\n np.testing.assert_allclose(pos.x1, 0.8728, atol=1e-3)\n np.testing.assert_allclose(pos.y0, 0.1808, atol=1e-2)\n\n\ndef test_compressed_suptitle():\n fig, (ax0, ax1) = plt.subplots(\n nrows=2, figsize=(4, 10), layout="compressed",\n gridspec_kw={"height_ratios": (1 / 4, 3 / 4), "hspace": 0})\n\n ax0.axis("equal")\n ax0.set_box_aspect(1/3)\n\n ax1.axis("equal")\n ax1.set_box_aspect(1)\n\n title = fig.suptitle("Title")\n fig.draw_without_rendering()\n assert title.get_position()[1] == pytest.approx(0.7491, abs=1e-3)\n\n title = fig.suptitle("Title", y=0.98)\n fig.draw_without_rendering()\n assert title.get_position()[1] == 0.98\n\n title = fig.suptitle("Title", in_layout=False)\n fig.draw_without_rendering()\n assert title.get_position()[1] == 0.98\n\n\n@pytest.mark.parametrize('arg, state', [\n (True, True),\n (False, False),\n ({}, True),\n ({'rect': None}, True)\n])\ndef test_set_constrained_layout(arg, state):\n fig, ax = plt.subplots(constrained_layout=arg)\n assert fig.get_constrained_layout() is state\n\n\ndef test_constrained_toggle():\n fig, ax = plt.subplots()\n with pytest.warns(PendingDeprecationWarning):\n fig.set_constrained_layout(True)\n assert fig.get_constrained_layout()\n fig.set_constrained_layout(False)\n assert not fig.get_constrained_layout()\n fig.set_constrained_layout(True)\n assert fig.get_constrained_layout()\n\n\ndef test_layout_leak():\n # Make sure there aren't any cyclic references when using LayoutGrid\n # GH #25853\n fig = plt.figure(constrained_layout=True, figsize=(10, 10))\n fig.add_subplot()\n fig.draw_without_rendering()\n plt.close("all")\n del fig\n gc.collect()\n assert not any(isinstance(obj, mpl._layoutgrid.LayoutGrid)\n for obj in gc.get_objects())\n | .venv\Lib\site-packages\matplotlib\tests\test_constrainedlayout.py | test_constrainedlayout.py | Python | 23,602 | 0.95 | 0.135546 | 0.020833 | vue-tools | 168 | 2025-04-23T11:44:39.112256 | Apache-2.0 | true | 0c2cbbc501320980b9e592a2a4b4cb9c |
import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef test_stem_remove():\n ax = plt.gca()\n st = ax.stem([1, 2], [1, 2])\n st.remove()\n\n\ndef test_errorbar_remove():\n\n # Regression test for a bug that caused remove to fail when using\n # fmt='none'\n\n ax = plt.gca()\n\n eb = ax.errorbar([1], [1])\n eb.remove()\n\n eb = ax.errorbar([1], [1], xerr=1)\n eb.remove()\n\n eb = ax.errorbar([1], [1], yerr=2)\n eb.remove()\n\n eb = ax.errorbar([1], [1], xerr=[2], yerr=2)\n eb.remove()\n\n eb = ax.errorbar([1], [1], fmt='none')\n eb.remove()\n\n\ndef test_nonstring_label():\n # Test for #26824\n plt.bar(np.arange(10), np.random.rand(10), label=1)\n plt.legend()\n | .venv\Lib\site-packages\matplotlib\tests\test_container.py | test_container.py | Python | 694 | 0.95 | 0.135135 | 0.125 | python-kit | 905 | 2024-02-18T19:09:00.226762 | BSD-3-Clause | true | 6172e8b71016f0fe0c0a08cef3bb017a |
import datetime\nimport platform\nimport re\nfrom unittest import mock\n\nimport contourpy\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal, assert_array_almost_equal_nulp\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt, rc_context, ticker\nfrom matplotlib.colors import LogNorm, same_color\nimport matplotlib.patches as mpatches\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\nimport pytest\n\n\ndef test_contour_shape_1d_valid():\n\n x = np.arange(10)\n y = np.arange(9)\n z = np.random.random((9, 10))\n\n fig, ax = plt.subplots()\n ax.contour(x, y, z)\n\n\ndef test_contour_shape_2d_valid():\n\n x = np.arange(10)\n y = np.arange(9)\n xg, yg = np.meshgrid(x, y)\n z = np.random.random((9, 10))\n\n fig, ax = plt.subplots()\n ax.contour(xg, yg, z)\n\n\n@pytest.mark.parametrize("args, message", [\n ((np.arange(9), np.arange(9), np.empty((9, 10))),\n 'Length of x (9) must match number of columns in z (10)'),\n ((np.arange(10), np.arange(10), np.empty((9, 10))),\n 'Length of y (10) must match number of rows in z (9)'),\n ((np.empty((10, 10)), np.arange(10), np.empty((9, 10))),\n 'Number of dimensions of x (2) and y (1) do not match'),\n ((np.arange(10), np.empty((10, 10)), np.empty((9, 10))),\n 'Number of dimensions of x (1) and y (2) do not match'),\n ((np.empty((9, 9)), np.empty((9, 10)), np.empty((9, 10))),\n 'Shapes of x (9, 9) and z (9, 10) do not match'),\n ((np.empty((9, 10)), np.empty((9, 9)), np.empty((9, 10))),\n 'Shapes of y (9, 9) and z (9, 10) do not match'),\n ((np.empty((3, 3, 3)), np.empty((3, 3, 3)), np.empty((9, 10))),\n 'Inputs x and y must be 1D or 2D, not 3D'),\n ((np.empty((3, 3, 3)), np.empty((3, 3, 3)), np.empty((3, 3, 3))),\n 'Input z must be 2D, not 3D'),\n (([[0]],), # github issue 8197\n 'Input z must be at least a (2, 2) shaped array, but has shape (1, 1)'),\n (([0], [0], [[0]]),\n 'Input z must be at least a (2, 2) shaped array, but has shape (1, 1)'),\n])\ndef test_contour_shape_error(args, message):\n fig, ax = plt.subplots()\n with pytest.raises(TypeError, match=re.escape(message)):\n ax.contour(*args)\n\n\ndef test_contour_no_valid_levels():\n fig, ax = plt.subplots()\n # no warning for empty levels.\n ax.contour(np.random.rand(9, 9), levels=[])\n # no warning if levels is given and is not within the range of z.\n cs = ax.contour(np.arange(81).reshape((9, 9)), levels=[100])\n # ... and if fmt is given.\n ax.clabel(cs, fmt={100: '%1.2f'})\n # no warning if z is uniform.\n ax.contour(np.ones((9, 9)))\n\n\ndef test_contour_Nlevels():\n # A scalar levels arg or kwarg should trigger auto level generation.\n # https://github.com/matplotlib/matplotlib/issues/11913\n z = np.arange(12).reshape((3, 4))\n fig, ax = plt.subplots()\n cs1 = ax.contour(z, 5)\n assert len(cs1.levels) > 1\n cs2 = ax.contour(z, levels=5)\n assert (cs1.levels == cs2.levels).all()\n\n\n@check_figures_equal(extensions=['png'])\ndef test_contour_set_paths(fig_test, fig_ref):\n cs_test = fig_test.subplots().contour([[0, 1], [1, 2]])\n cs_ref = fig_ref.subplots().contour([[1, 0], [2, 1]])\n\n cs_test.set_paths(cs_ref.get_paths())\n\n\n@image_comparison(['contour_manual_labels'], remove_text=True, style='mpl20', tol=0.26)\ndef test_contour_manual_labels():\n x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))\n z = np.max(np.dstack([abs(x), abs(y)]), 2)\n\n plt.figure(figsize=(6, 2), dpi=200)\n cs = plt.contour(x, y, z)\n\n pts = np.array([(1.0, 3.0), (1.0, 4.4), (1.0, 6.0)])\n plt.clabel(cs, manual=pts)\n pts = np.array([(2.0, 3.0), (2.0, 4.4), (2.0, 6.0)])\n plt.clabel(cs, manual=pts, fontsize='small', colors=('r', 'g'))\n\n\ndef test_contour_manual_moveto():\n x = np.linspace(-10, 10)\n y = np.linspace(-10, 10)\n\n X, Y = np.meshgrid(x, y)\n\n Z = X**2 * 1 / Y**2 - 1\n\n contours = plt.contour(X, Y, Z, levels=[0, 100])\n\n # This point lies on the `MOVETO` line for the 100 contour\n # but is actually closest to the 0 contour\n point = (1.3, 1)\n clabels = plt.clabel(contours, manual=[point])\n\n # Ensure that the 0 contour was chosen, not the 100 contour\n assert clabels[0].get_text() == "0"\n\n\n@image_comparison(['contour_disconnected_segments'],\n remove_text=True, style='mpl20', extensions=['png'])\ndef test_contour_label_with_disconnected_segments():\n x, y = np.mgrid[-1:1:21j, -1:1:21j]\n z = 1 / np.sqrt(0.01 + (x + 0.3) ** 2 + y ** 2)\n z += 1 / np.sqrt(0.01 + (x - 0.3) ** 2 + y ** 2)\n\n plt.figure()\n cs = plt.contour(x, y, z, levels=[7])\n cs.clabel(manual=[(0.2, 0.1)])\n\n\n@image_comparison(['contour_manual_colors_and_levels.png'], remove_text=True,\n tol=0 if platform.machine() == 'x86_64' else 0.018)\ndef test_given_colors_levels_and_extends():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n _, axs = plt.subplots(2, 4)\n\n data = np.arange(12).reshape(3, 4)\n\n colors = ['red', 'yellow', 'pink', 'blue', 'black']\n levels = [2, 4, 8, 10]\n\n for i, ax in enumerate(axs.flat):\n filled = i % 2 == 0.\n extend = ['neither', 'min', 'max', 'both'][i // 2]\n\n if filled:\n # If filled, we have 3 colors with no extension,\n # 4 colors with one extension, and 5 colors with both extensions\n first_color = 1 if extend in ['max', 'neither'] else None\n last_color = -1 if extend in ['min', 'neither'] else None\n c = ax.contourf(data, colors=colors[first_color:last_color],\n levels=levels, extend=extend)\n else:\n # If not filled, we have 4 levels and 4 colors\n c = ax.contour(data, colors=colors[:-1],\n levels=levels, extend=extend)\n\n plt.colorbar(c, ax=ax)\n\n\n@image_comparison(['contourf_hatch_colors'],\n remove_text=True, style='mpl20', extensions=['png'])\ndef test_hatch_colors():\n fig, ax = plt.subplots()\n cf = ax.contourf([[0, 1], [1, 2]], hatches=['-', '/', '\\', '//'], cmap='gray')\n cf.set_edgecolors(["blue", "grey", "yellow", "red"])\n\n\n@pytest.mark.parametrize('color, extend', [('darkred', 'neither'),\n ('darkred', 'both'),\n (('r', 0.5), 'neither'),\n ((0.1, 0.2, 0.5, 0.3), 'neither')])\ndef test_single_color_and_extend(color, extend):\n z = [[0, 1], [1, 2]]\n\n _, ax = plt.subplots()\n levels = [0.5, 0.75, 1, 1.25, 1.5]\n cs = ax.contour(z, levels=levels, colors=color, extend=extend)\n for c in cs.get_edgecolors():\n assert same_color(c, color)\n\n\n@image_comparison(['contour_log_locator.svg'], style='mpl20', remove_text=False)\ndef test_log_locator_levels():\n\n fig, ax = plt.subplots()\n\n N = 100\n x = np.linspace(-3.0, 3.0, N)\n y = np.linspace(-2.0, 2.0, N)\n\n X, Y = np.meshgrid(x, y)\n\n Z1 = np.exp(-X**2 - Y**2)\n Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)\n data = Z1 + 50 * Z2\n\n c = ax.contourf(data, locator=ticker.LogLocator())\n assert_array_almost_equal(c.levels, np.power(10.0, np.arange(-6, 3)))\n cb = fig.colorbar(c, ax=ax)\n assert_array_almost_equal(cb.ax.get_yticks(), c.levels)\n\n\n@image_comparison(['contour_datetime_axis.png'], style='mpl20')\ndef test_contour_datetime_axis():\n fig = plt.figure()\n fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)\n base = datetime.datetime(2013, 1, 1)\n x = np.array([base + datetime.timedelta(days=d) for d in range(20)])\n y = np.arange(20)\n z1, z2 = np.meshgrid(np.arange(20), np.arange(20))\n z = z1 * z2\n plt.subplot(221)\n plt.contour(x, y, z)\n plt.subplot(222)\n plt.contourf(x, y, z)\n x = np.repeat(x[np.newaxis], 20, axis=0)\n y = np.repeat(y[:, np.newaxis], 20, axis=1)\n plt.subplot(223)\n plt.contour(x, y, z)\n plt.subplot(224)\n plt.contourf(x, y, z)\n for ax in fig.get_axes():\n for label in ax.get_xticklabels():\n label.set_ha('right')\n label.set_rotation(30)\n\n\n@image_comparison(['contour_test_label_transforms.png'],\n remove_text=True, style='mpl20', tol=1.1)\ndef test_labels():\n # Adapted from pylab_examples example code: contour_demo.py\n # see issues #2475, #2843, and #2818 for explanation\n delta = 0.025\n x = np.arange(-3.0, 3.0, delta)\n y = np.arange(-2.0, 2.0, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)\n Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /\n (2 * np.pi * 0.5 * 1.5))\n\n # difference of Gaussians\n Z = 10.0 * (Z2 - Z1)\n\n fig, ax = plt.subplots(1, 1)\n CS = ax.contour(X, Y, Z)\n disp_units = [(216, 177), (359, 290), (521, 406)]\n data_units = [(-2, .5), (0, -1.5), (2.8, 1)]\n\n CS.clabel()\n\n for x, y in data_units:\n CS.add_label_near(x, y, inline=True, transform=None)\n\n for x, y in disp_units:\n CS.add_label_near(x, y, inline=True, transform=False)\n\n\ndef test_label_contour_start():\n # Set up data and figure/axes that result in automatic labelling adding the\n # label to the start of a contour\n\n _, ax = plt.subplots(dpi=100)\n lats = lons = np.linspace(-np.pi / 2, np.pi / 2, 50)\n lons, lats = np.meshgrid(lons, lats)\n wave = 0.75 * (np.sin(2 * lats) ** 8) * np.cos(4 * lons)\n mean = 0.5 * np.cos(2 * lats) * ((np.sin(2 * lats)) ** 2 + 2)\n data = wave + mean\n\n cs = ax.contour(lons, lats, data)\n\n with mock.patch.object(\n cs, '_split_path_and_get_label_rotation',\n wraps=cs._split_path_and_get_label_rotation) as mocked_splitter:\n # Smoke test that we can add the labels\n cs.clabel(fontsize=9)\n\n # Verify at least one label was added to the start of a contour. I.e. the\n # splitting method was called with idx=0 at least once.\n idxs = [cargs[0][1] for cargs in mocked_splitter.call_args_list]\n assert 0 in idxs\n\n\n@image_comparison(['contour_corner_mask_False.png', 'contour_corner_mask_True.png'],\n remove_text=True, tol=1.88)\ndef test_corner_mask():\n n = 60\n mask_level = 0.95\n noise_amp = 1.0\n np.random.seed([1])\n x, y = np.meshgrid(np.linspace(0, 2.0, n), np.linspace(0, 2.0, n))\n z = np.cos(7*x)*np.sin(8*y) + noise_amp*np.random.rand(n, n)\n mask = np.random.rand(n, n) >= mask_level\n z = np.ma.array(z, mask=mask)\n\n for corner_mask in [False, True]:\n plt.figure()\n plt.contourf(z, corner_mask=corner_mask)\n\n\ndef test_contourf_decreasing_levels():\n # github issue 5477.\n z = [[0.1, 0.3], [0.5, 0.7]]\n plt.figure()\n with pytest.raises(ValueError):\n plt.contourf(z, [1.0, 0.0])\n\n\ndef test_contourf_symmetric_locator():\n # github issue 7271\n z = np.arange(12).reshape((3, 4))\n locator = plt.MaxNLocator(nbins=4, symmetric=True)\n cs = plt.contourf(z, locator=locator)\n assert_array_almost_equal(cs.levels, np.linspace(-12, 12, 5))\n\n\ndef test_circular_contour_warning():\n # Check that almost circular contours don't throw a warning\n x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4))\n r = np.hypot(x, y)\n plt.figure()\n cs = plt.contour(x, y, r)\n plt.clabel(cs)\n\n\n@pytest.mark.parametrize("use_clabeltext, contour_zorder, clabel_zorder",\n [(True, 123, 1234), (False, 123, 1234),\n (True, 123, None), (False, 123, None)])\ndef test_clabel_zorder(use_clabeltext, contour_zorder, clabel_zorder):\n x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))\n z = np.max(np.dstack([abs(x), abs(y)]), 2)\n\n fig, (ax1, ax2) = plt.subplots(ncols=2)\n cs = ax1.contour(x, y, z, zorder=contour_zorder)\n cs_filled = ax2.contourf(x, y, z, zorder=contour_zorder)\n clabels1 = cs.clabel(zorder=clabel_zorder, use_clabeltext=use_clabeltext)\n clabels2 = cs_filled.clabel(zorder=clabel_zorder,\n use_clabeltext=use_clabeltext)\n\n if clabel_zorder is None:\n expected_clabel_zorder = 2+contour_zorder\n else:\n expected_clabel_zorder = clabel_zorder\n\n for clabel in clabels1:\n assert clabel.get_zorder() == expected_clabel_zorder\n for clabel in clabels2:\n assert clabel.get_zorder() == expected_clabel_zorder\n\n\ndef test_clabel_with_large_spacing():\n # When the inline spacing is large relative to the contour, it may cause the\n # entire contour to be removed. In current implementation, one line segment is\n # retained between the identified points.\n # This behavior may be worth reconsidering, but check to be sure we do not produce\n # an invalid path, which results in an error at clabel call time.\n # see gh-27045 for more information\n x = y = np.arange(-3.0, 3.01, 0.05)\n X, Y = np.meshgrid(x, y)\n Z = np.exp(-X**2 - Y**2)\n\n fig, ax = plt.subplots()\n contourset = ax.contour(X, Y, Z, levels=[0.01, 0.2, .5, .8])\n ax.clabel(contourset, inline_spacing=100)\n\n\n# tol because ticks happen to fall on pixel boundaries so small\n# floating point changes in tick location flip which pixel gets\n# the tick.\n@image_comparison(['contour_log_extension.png'],\n remove_text=True, style='mpl20',\n tol=1.444)\ndef test_contourf_log_extension():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n # Test that contourf with lognorm is extended correctly\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 5))\n fig.subplots_adjust(left=0.05, right=0.95)\n\n # make data set with large range e.g. between 1e-8 and 1e10\n data_exp = np.linspace(-7.5, 9.5, 1200)\n data = np.power(10, data_exp).reshape(30, 40)\n # make manual levels e.g. between 1e-4 and 1e-6\n levels_exp = np.arange(-4., 7.)\n levels = np.power(10., levels_exp)\n\n # original data\n c1 = ax1.contourf(data,\n norm=LogNorm(vmin=data.min(), vmax=data.max()))\n # just show data in levels\n c2 = ax2.contourf(data, levels=levels,\n norm=LogNorm(vmin=levels.min(), vmax=levels.max()),\n extend='neither')\n # extend data from levels\n c3 = ax3.contourf(data, levels=levels,\n norm=LogNorm(vmin=levels.min(), vmax=levels.max()),\n extend='both')\n cb = plt.colorbar(c1, ax=ax1)\n assert cb.ax.get_ylim() == (1e-8, 1e10)\n cb = plt.colorbar(c2, ax=ax2)\n assert_array_almost_equal_nulp(cb.ax.get_ylim(), np.array((1e-4, 1e6)))\n cb = plt.colorbar(c3, ax=ax3)\n\n\n@image_comparison(['contour_addlines.png'], remove_text=True, style='mpl20',\n tol=0.03 if platform.machine() == 'x86_64' else 0.15)\n# tolerance is because image changed minutely when tick finding on\n# colorbars was cleaned up...\ndef test_contour_addlines():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n fig, ax = plt.subplots()\n np.random.seed(19680812)\n X = np.random.rand(10, 10)*10000\n pcm = ax.pcolormesh(X)\n # add 1000 to make colors visible...\n cont = ax.contour(X+1000)\n cb = fig.colorbar(pcm)\n cb.add_lines(cont)\n assert_array_almost_equal(cb.ax.get_ylim(), [114.3091, 9972.30735], 3)\n\n\n@image_comparison(baseline_images=['contour_uneven'],\n extensions=['png'], remove_text=True, style='mpl20')\ndef test_contour_uneven():\n # Remove this line when this test image is regenerated.\n plt.rcParams['pcolormesh.snap'] = False\n\n z = np.arange(24).reshape(4, 6)\n fig, axs = plt.subplots(1, 2)\n ax = axs[0]\n cs = ax.contourf(z, levels=[2, 4, 6, 10, 20])\n fig.colorbar(cs, ax=ax, spacing='proportional')\n ax = axs[1]\n cs = ax.contourf(z, levels=[2, 4, 6, 10, 20])\n fig.colorbar(cs, ax=ax, spacing='uniform')\n\n\n@pytest.mark.parametrize(\n "rc_lines_linewidth, rc_contour_linewidth, call_linewidths, expected", [\n (1.23, None, None, 1.23),\n (1.23, 4.24, None, 4.24),\n (1.23, 4.24, 5.02, 5.02)\n ])\ndef test_contour_linewidth(\n rc_lines_linewidth, rc_contour_linewidth, call_linewidths, expected):\n\n with rc_context(rc={"lines.linewidth": rc_lines_linewidth,\n "contour.linewidth": rc_contour_linewidth}):\n fig, ax = plt.subplots()\n X = np.arange(4*3).reshape(4, 3)\n cs = ax.contour(X, linewidths=call_linewidths)\n assert cs.get_linewidths()[0] == expected\n\n\n@pytest.mark.backend("pdf")\ndef test_label_nonagg():\n # This should not crash even if the canvas doesn't have a get_renderer().\n plt.clabel(plt.contour([[1, 2], [3, 4]]))\n\n\n@image_comparison(baseline_images=['contour_closed_line_loop'],\n extensions=['png'], remove_text=True)\ndef test_contour_closed_line_loop():\n # github issue 19568.\n z = [[0, 0, 0], [0, 2, 0], [0, 0, 0], [2, 1, 2]]\n\n fig, ax = plt.subplots(figsize=(2, 2))\n ax.contour(z, [0.5], linewidths=[20], alpha=0.7)\n ax.set_xlim(-0.1, 2.1)\n ax.set_ylim(-0.1, 3.1)\n\n\ndef test_quadcontourset_reuse():\n # If QuadContourSet returned from one contour(f) call is passed as first\n # argument to another the underlying C++ contour generator will be reused.\n x, y = np.meshgrid([0.0, 1.0], [0.0, 1.0])\n z = x + y\n fig, ax = plt.subplots()\n qcs1 = ax.contourf(x, y, z)\n qcs2 = ax.contour(x, y, z)\n assert qcs2._contour_generator != qcs1._contour_generator\n qcs3 = ax.contour(qcs1, z)\n assert qcs3._contour_generator == qcs1._contour_generator\n\n\n@image_comparison(baseline_images=['contour_manual'],\n extensions=['png'], remove_text=True, tol=0.89)\ndef test_contour_manual():\n # Manually specifying contour lines/polygons to plot.\n from matplotlib.contour import ContourSet\n\n fig, ax = plt.subplots(figsize=(4, 4))\n cmap = 'viridis'\n\n # Segments only (no 'kind' codes).\n lines0 = [[[2, 0], [1, 2], [1, 3]]] # Single line.\n lines1 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] # Two lines.\n filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]]\n filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], # Two polygons.\n [[1, 4], [3, 4], [3, 3]]]\n ContourSet(ax, [0, 1, 2], [filled01, filled12], filled=True, cmap=cmap)\n ContourSet(ax, [1, 2], [lines0, lines1], linewidths=3, colors=['r', 'k'])\n\n # Segments and kind codes (1 = MOVETO, 2 = LINETO, 79 = CLOSEPOLY).\n segs = [[[4, 0], [7, 0], [7, 3], [4, 3], [4, 0],\n [5, 1], [5, 2], [6, 2], [6, 1], [5, 1]]]\n kinds = [[1, 2, 2, 2, 79, 1, 2, 2, 2, 79]] # Polygon containing hole.\n ContourSet(ax, [2, 3], [segs], [kinds], filled=True, cmap=cmap)\n ContourSet(ax, [2], [segs], [kinds], colors='k', linewidths=3)\n\n\n@image_comparison(baseline_images=['contour_line_start_on_corner_edge'],\n extensions=['png'], remove_text=True)\ndef test_contour_line_start_on_corner_edge():\n fig, ax = plt.subplots(figsize=(6, 5))\n\n x, y = np.meshgrid([0, 1, 2, 3, 4], [0, 1, 2])\n z = 1.2 - (x - 2)**2 + (y - 1)**2\n mask = np.zeros_like(z, dtype=bool)\n mask[1, 1] = mask[1, 3] = True\n z = np.ma.array(z, mask=mask)\n\n filled = ax.contourf(x, y, z, corner_mask=True)\n cbar = fig.colorbar(filled)\n lines = ax.contour(x, y, z, corner_mask=True, colors='k')\n cbar.add_lines(lines)\n\n\ndef test_find_nearest_contour():\n xy = np.indices((15, 15))\n img = np.exp(-np.pi * (np.sum((xy - 5)**2, 0)/5.**2))\n cs = plt.contour(img, 10)\n\n nearest_contour = cs.find_nearest_contour(1, 1, pixel=False)\n expected_nearest = (1, 0, 33, 1.965966, 1.965966, 1.866183)\n assert_array_almost_equal(nearest_contour, expected_nearest)\n\n nearest_contour = cs.find_nearest_contour(8, 1, pixel=False)\n expected_nearest = (1, 0, 5, 7.550173, 1.587542, 0.547550)\n assert_array_almost_equal(nearest_contour, expected_nearest)\n\n nearest_contour = cs.find_nearest_contour(2, 5, pixel=False)\n expected_nearest = (3, 0, 21, 1.884384, 5.023335, 0.013911)\n assert_array_almost_equal(nearest_contour, expected_nearest)\n\n nearest_contour = cs.find_nearest_contour(2, 5, indices=(5, 7), pixel=False)\n expected_nearest = (5, 0, 16, 2.628202, 5.0, 0.394638)\n assert_array_almost_equal(nearest_contour, expected_nearest)\n\n\ndef test_find_nearest_contour_no_filled():\n xy = np.indices((15, 15))\n img = np.exp(-np.pi * (np.sum((xy - 5)**2, 0)/5.**2))\n cs = plt.contourf(img, 10)\n\n with pytest.raises(ValueError, match="Method does not support filled contours"):\n cs.find_nearest_contour(1, 1, pixel=False)\n\n with pytest.raises(ValueError, match="Method does not support filled contours"):\n cs.find_nearest_contour(1, 10, indices=(5, 7), pixel=False)\n\n with pytest.raises(ValueError, match="Method does not support filled contours"):\n cs.find_nearest_contour(2, 5, indices=(2, 7), pixel=True)\n\n\n@mpl.style.context("default")\ndef test_contour_autolabel_beyond_powerlimits():\n ax = plt.figure().add_subplot()\n cs = plt.contour(np.geomspace(1e-6, 1e-4, 100).reshape(10, 10),\n levels=[.25e-5, 1e-5, 4e-5])\n ax.clabel(cs)\n # Currently, the exponent is missing, but that may be fixed in the future.\n assert {text.get_text() for text in ax.texts} == {"0.25", "1.00", "4.00"}\n\n\ndef test_contourf_legend_elements():\n from matplotlib.patches import Rectangle\n x = np.arange(1, 10)\n y = x.reshape(-1, 1)\n h = x * y\n\n cs = plt.contourf(h, levels=[10, 30, 50],\n colors=['#FFFF00', '#FF00FF', '#00FFFF'],\n extend='both')\n cs.cmap.set_over('red')\n cs.cmap.set_under('blue')\n cs.changed()\n artists, labels = cs.legend_elements()\n assert labels == ['$x \\leq -1e+250s$',\n '$10.0 < x \\leq 30.0$',\n '$30.0 < x \\leq 50.0$',\n '$x > 1e+250s$']\n expected_colors = ('blue', '#FFFF00', '#FF00FF', 'red')\n assert all(isinstance(a, Rectangle) for a in artists)\n assert all(same_color(a.get_facecolor(), c)\n for a, c in zip(artists, expected_colors))\n\n\ndef test_contour_legend_elements():\n x = np.arange(1, 10)\n y = x.reshape(-1, 1)\n h = x * y\n\n colors = ['blue', '#00FF00', 'red']\n cs = plt.contour(h, levels=[10, 30, 50],\n colors=colors,\n extend='both')\n artists, labels = cs.legend_elements()\n assert labels == ['$x = 10.0$', '$x = 30.0$', '$x = 50.0$']\n assert all(isinstance(a, mpl.lines.Line2D) for a in artists)\n assert all(same_color(a.get_color(), c)\n for a, c in zip(artists, colors))\n\n\n@pytest.mark.parametrize(\n "algorithm, klass",\n [('mpl2005', contourpy.Mpl2005ContourGenerator),\n ('mpl2014', contourpy.Mpl2014ContourGenerator),\n ('serial', contourpy.SerialContourGenerator),\n ('threaded', contourpy.ThreadedContourGenerator),\n ('invalid', None)])\ndef test_algorithm_name(algorithm, klass):\n z = np.array([[1.0, 2.0], [3.0, 4.0]])\n if klass is not None:\n cs = plt.contourf(z, algorithm=algorithm)\n assert isinstance(cs._contour_generator, klass)\n else:\n with pytest.raises(ValueError):\n plt.contourf(z, algorithm=algorithm)\n\n\n@pytest.mark.parametrize(\n "algorithm", ['mpl2005', 'mpl2014', 'serial', 'threaded'])\ndef test_algorithm_supports_corner_mask(algorithm):\n z = np.array([[1.0, 2.0], [3.0, 4.0]])\n\n # All algorithms support corner_mask=False\n plt.contourf(z, algorithm=algorithm, corner_mask=False)\n\n # Only some algorithms support corner_mask=True\n if algorithm != 'mpl2005':\n plt.contourf(z, algorithm=algorithm, corner_mask=True)\n else:\n with pytest.raises(ValueError):\n plt.contourf(z, algorithm=algorithm, corner_mask=True)\n\n\n@image_comparison(baseline_images=['contour_all_algorithms'],\n extensions=['png'], remove_text=True, tol=0.06)\ndef test_all_algorithms():\n algorithms = ['mpl2005', 'mpl2014', 'serial', 'threaded']\n\n rng = np.random.default_rng(2981)\n x, y = np.meshgrid(np.linspace(0.0, 1.0, 10), np.linspace(0.0, 1.0, 6))\n z = np.sin(15*x)*np.cos(10*y) + rng.normal(scale=0.5, size=(6, 10))\n mask = np.zeros_like(z, dtype=bool)\n mask[3, 7] = True\n z = np.ma.array(z, mask=mask)\n\n _, axs = plt.subplots(2, 2)\n for ax, algorithm in zip(axs.ravel(), algorithms):\n ax.contourf(x, y, z, algorithm=algorithm)\n ax.contour(x, y, z, algorithm=algorithm, colors='k')\n ax.set_title(algorithm)\n\n\ndef test_subfigure_clabel():\n # Smoke test for gh#23173\n delta = 0.025\n x = np.arange(-3.0, 3.0, delta)\n y = np.arange(-2.0, 2.0, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-(X**2) - Y**2)\n Z2 = np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)\n Z = (Z1 - Z2) * 2\n\n fig = plt.figure()\n figs = fig.subfigures(nrows=1, ncols=2)\n\n for f in figs:\n ax = f.subplots()\n CS = ax.contour(X, Y, Z)\n ax.clabel(CS, inline=True, fontsize=10)\n ax.set_title("Simplest default with labels")\n\n\n@pytest.mark.parametrize(\n "style", ['solid', 'dashed', 'dashdot', 'dotted'])\ndef test_linestyles(style):\n delta = 0.025\n x = np.arange(-3.0, 3.0, delta)\n y = np.arange(-2.0, 2.0, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-X**2 - Y**2)\n Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n Z = (Z1 - Z2) * 2\n\n # Positive contour defaults to solid\n fig1, ax1 = plt.subplots()\n CS1 = ax1.contour(X, Y, Z, 6, colors='k')\n ax1.clabel(CS1, fontsize=9, inline=True)\n ax1.set_title('Single color - positive contours solid (default)')\n assert CS1.linestyles is None # default\n\n # Change linestyles using linestyles kwarg\n fig2, ax2 = plt.subplots()\n CS2 = ax2.contour(X, Y, Z, 6, colors='k', linestyles=style)\n ax2.clabel(CS2, fontsize=9, inline=True)\n ax2.set_title(f'Single color - positive contours {style}')\n assert CS2.linestyles == style\n\n # Ensure linestyles do not change when negative_linestyles is defined\n fig3, ax3 = plt.subplots()\n CS3 = ax3.contour(X, Y, Z, 6, colors='k', linestyles=style,\n negative_linestyles='dashdot')\n ax3.clabel(CS3, fontsize=9, inline=True)\n ax3.set_title(f'Single color - positive contours {style}')\n assert CS3.linestyles == style\n\n\n@pytest.mark.parametrize(\n "style", ['solid', 'dashed', 'dashdot', 'dotted'])\ndef test_negative_linestyles(style):\n delta = 0.025\n x = np.arange(-3.0, 3.0, delta)\n y = np.arange(-2.0, 2.0, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-X**2 - Y**2)\n Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n Z = (Z1 - Z2) * 2\n\n # Negative contour defaults to dashed\n fig1, ax1 = plt.subplots()\n CS1 = ax1.contour(X, Y, Z, 6, colors='k')\n ax1.clabel(CS1, fontsize=9, inline=True)\n ax1.set_title('Single color - negative contours dashed (default)')\n assert CS1.negative_linestyles == 'dashed' # default\n\n # Change negative_linestyles using rcParams\n plt.rcParams['contour.negative_linestyle'] = style\n fig2, ax2 = plt.subplots()\n CS2 = ax2.contour(X, Y, Z, 6, colors='k')\n ax2.clabel(CS2, fontsize=9, inline=True)\n ax2.set_title(f'Single color - negative contours {style}'\n '(using rcParams)')\n assert CS2.negative_linestyles == style\n\n # Change negative_linestyles using negative_linestyles kwarg\n fig3, ax3 = plt.subplots()\n CS3 = ax3.contour(X, Y, Z, 6, colors='k', negative_linestyles=style)\n ax3.clabel(CS3, fontsize=9, inline=True)\n ax3.set_title(f'Single color - negative contours {style}')\n assert CS3.negative_linestyles == style\n\n # Ensure negative_linestyles do not change when linestyles is defined\n fig4, ax4 = plt.subplots()\n CS4 = ax4.contour(X, Y, Z, 6, colors='k', linestyles='dashdot',\n negative_linestyles=style)\n ax4.clabel(CS4, fontsize=9, inline=True)\n ax4.set_title(f'Single color - negative contours {style}')\n assert CS4.negative_linestyles == style\n\n\ndef test_contour_remove():\n ax = plt.figure().add_subplot()\n orig_children = ax.get_children()\n cs = ax.contour(np.arange(16).reshape((4, 4)))\n cs.clabel()\n assert ax.get_children() != orig_children\n cs.remove()\n assert ax.get_children() == orig_children\n\n\ndef test_contour_no_args():\n fig, ax = plt.subplots()\n data = [[0, 1], [1, 0]]\n with pytest.raises(TypeError, match=r"contour\(\) takes from 1 to 4"):\n ax.contour(Z=data)\n\n\ndef test_contour_clip_path():\n fig, ax = plt.subplots()\n data = [[0, 1], [1, 0]]\n circle = mpatches.Circle([0.5, 0.5], 0.5, transform=ax.transAxes)\n cs = ax.contour(data, clip_path=circle)\n assert cs.get_clip_path() is not None\n\n\ndef test_bool_autolevel():\n x, y = np.random.rand(2, 9)\n z = (np.arange(9) % 2).reshape((3, 3)).astype(bool)\n m = [[False, False, False], [False, True, False], [False, False, False]]\n assert plt.contour(z.tolist()).levels.tolist() == [.5]\n assert plt.contour(z).levels.tolist() == [.5]\n assert plt.contour(np.ma.array(z, mask=m)).levels.tolist() == [.5]\n assert plt.contourf(z.tolist()).levels.tolist() == [0, .5, 1]\n assert plt.contourf(z).levels.tolist() == [0, .5, 1]\n assert plt.contourf(np.ma.array(z, mask=m)).levels.tolist() == [0, .5, 1]\n z = z.ravel()\n assert plt.tricontour(x, y, z.tolist()).levels.tolist() == [.5]\n assert plt.tricontour(x, y, z).levels.tolist() == [.5]\n assert plt.tricontourf(x, y, z.tolist()).levels.tolist() == [0, .5, 1]\n assert plt.tricontourf(x, y, z).levels.tolist() == [0, .5, 1]\n\n\ndef test_all_nan():\n x = np.array([[np.nan, np.nan], [np.nan, np.nan]])\n assert_array_almost_equal(plt.contour(x).levels,\n [-1e-13, -7.5e-14, -5e-14, -2.4e-14, 0.0,\n 2.4e-14, 5e-14, 7.5e-14, 1e-13])\n\n\ndef test_allsegs_allkinds():\n x, y = np.meshgrid(np.arange(0, 10, 2), np.arange(0, 10, 2))\n z = np.sin(x) * np.cos(y)\n\n cs = plt.contour(x, y, z, levels=[0, 0.5])\n\n # Expect two levels, the first with 5 segments and the second with 4.\n for result in [cs.allsegs, cs.allkinds]:\n assert len(result) == 2\n assert len(result[0]) == 5\n assert len(result[1]) == 4\n | .venv\Lib\site-packages\matplotlib\tests\test_contour.py | test_contour.py | Python | 30,289 | 0.95 | 0.100119 | 0.095952 | react-lib | 384 | 2025-05-15T01:01:56.062027 | BSD-3-Clause | true | 4fe0a75f5885c398686f50f6bc82b1f2 |
import contextlib\nfrom io import StringIO\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pytest\n\nfrom cycler import cycler\n\n\ndef test_colorcycle_basic():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']))\n for _ in range(4):\n ax.plot(range(10), range(10))\n assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r']\n\n\ndef test_marker_cycle():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) +\n cycler('marker', ['.', '*', 'x']))\n for _ in range(4):\n ax.plot(range(10), range(10))\n assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r']\n assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.']\n\n\ndef test_valid_marker_cycles():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(cycler(marker=[1, "+", ".", 4]))\n\n\ndef test_marker_cycle_kwargs_arrays_iterators():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(c=np.array(['r', 'g', 'y']),\n marker=iter(['.', '*', 'x']))\n for _ in range(4):\n ax.plot(range(10), range(10))\n assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r']\n assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.']\n\n\ndef test_linestylecycle_basic():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(cycler('ls', ['-', '--', ':']))\n for _ in range(4):\n ax.plot(range(10), range(10))\n assert [l.get_linestyle() for l in ax.lines] == ['-', '--', ':', '-']\n\n\ndef test_fillcycle_basic():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) +\n cycler('hatch', ['xx', 'O', '|-']) +\n cycler('linestyle', ['-', '--', ':']))\n for _ in range(4):\n ax.fill(range(10), range(10))\n assert ([p.get_facecolor() for p in ax.patches]\n == [mpl.colors.to_rgba(c) for c in ['r', 'g', 'y', 'r']])\n assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', '|-', 'xx']\n assert [p.get_linestyle() for p in ax.patches] == ['-', '--', ':', '-']\n\n\ndef test_fillcycle_ignore():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']) +\n cycler('hatch', ['xx', 'O', '|-']) +\n cycler('marker', ['.', '*', 'D']))\n t = range(10)\n # Should not advance the cycler, even though there is an\n # unspecified property in the cycler "marker".\n # "marker" is not a Polygon property, and should be ignored.\n ax.fill(t, t, 'r', hatch='xx')\n # Allow the cycler to advance, but specify some properties\n ax.fill(t, t, hatch='O')\n ax.fill(t, t)\n ax.fill(t, t)\n assert ([p.get_facecolor() for p in ax.patches]\n == [mpl.colors.to_rgba(c) for c in ['r', 'r', 'g', 'y']])\n assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', 'O', '|-']\n\n\ndef test_property_collision_plot():\n fig, ax = plt.subplots()\n ax.set_prop_cycle('linewidth', [2, 4])\n t = range(10)\n for c in range(1, 4):\n ax.plot(t, t, lw=0.1)\n ax.plot(t, t)\n ax.plot(t, t)\n assert [l.get_linewidth() for l in ax.lines] == [0.1, 0.1, 0.1, 2, 4]\n\n\ndef test_property_collision_fill():\n fig, ax = plt.subplots()\n ax.set_prop_cycle(linewidth=[2, 3, 4, 5, 6], facecolor='bgcmy')\n t = range(10)\n for c in range(1, 4):\n ax.fill(t, t, lw=0.1)\n ax.fill(t, t)\n ax.fill(t, t)\n assert ([p.get_facecolor() for p in ax.patches]\n == [mpl.colors.to_rgba(c) for c in 'bgcmy'])\n assert [p.get_linewidth() for p in ax.patches] == [0.1, 0.1, 0.1, 5, 6]\n\n\ndef test_valid_input_forms():\n fig, ax = plt.subplots()\n # These should not raise an error.\n ax.set_prop_cycle(None)\n ax.set_prop_cycle(cycler('linewidth', [1, 2]))\n ax.set_prop_cycle('color', 'rgywkbcm')\n ax.set_prop_cycle('lw', (1, 2))\n ax.set_prop_cycle('linewidth', [1, 2])\n ax.set_prop_cycle('linewidth', iter([1, 2]))\n ax.set_prop_cycle('linewidth', np.array([1, 2]))\n ax.set_prop_cycle('color', np.array([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]]))\n ax.set_prop_cycle('dashes', [[], [13, 2], [8, 3, 1, 3]])\n ax.set_prop_cycle(lw=[1, 2], color=['k', 'w'], ls=['-', '--'])\n ax.set_prop_cycle(lw=np.array([1, 2]),\n color=np.array(['k', 'w']),\n ls=np.array(['-', '--']))\n\n\ndef test_cycle_reset():\n fig, ax = plt.subplots()\n prop0 = StringIO()\n prop1 = StringIO()\n prop2 = StringIO()\n\n with contextlib.redirect_stdout(prop0):\n plt.getp(ax.plot([1, 2], label="label")[0])\n\n ax.set_prop_cycle(linewidth=[10, 9, 4])\n with contextlib.redirect_stdout(prop1):\n plt.getp(ax.plot([1, 2], label="label")[0])\n assert prop1.getvalue() != prop0.getvalue()\n\n ax.set_prop_cycle(None)\n with contextlib.redirect_stdout(prop2):\n plt.getp(ax.plot([1, 2], label="label")[0])\n assert prop2.getvalue() == prop0.getvalue()\n\n\ndef test_invalid_input_forms():\n fig, ax = plt.subplots()\n\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle(1)\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle([1, 2])\n\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle('color', 'fish')\n\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle('linewidth', 1)\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle('linewidth', {1, 2})\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle(linewidth=1, color='r')\n\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle('foobar', [1, 2])\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle(foobar=[1, 2])\n\n with pytest.raises((TypeError, ValueError)):\n ax.set_prop_cycle(cycler(foobar=[1, 2]))\n with pytest.raises(ValueError):\n ax.set_prop_cycle(cycler(color='rgb', c='cmy'))\n | .venv\Lib\site-packages\matplotlib\tests\test_cycles.py | test_cycles.py | Python | 5,996 | 0.95 | 0.205714 | 0.035461 | vue-tools | 767 | 2025-05-20T03:44:55.599496 | BSD-3-Clause | true | b4ee9af4223b552a729bc465ce5d0c23 |
import datetime\n\nimport dateutil.tz\nimport dateutil.rrule\nimport functools\nimport numpy as np\nimport pytest\n\nfrom matplotlib import rc_context, style\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.ticker as mticker\n\n\ndef test_date_numpyx():\n # test that numpy dates work properly...\n base = datetime.datetime(2017, 1, 1)\n time = [base + datetime.timedelta(days=x) for x in range(0, 3)]\n timenp = np.array(time, dtype='datetime64[ns]')\n data = np.array([0., 2., 1.])\n fig = plt.figure(figsize=(10, 2))\n ax = fig.add_subplot(1, 1, 1)\n h, = ax.plot(time, data)\n hnp, = ax.plot(timenp, data)\n np.testing.assert_equal(h.get_xdata(orig=False), hnp.get_xdata(orig=False))\n fig = plt.figure(figsize=(10, 2))\n ax = fig.add_subplot(1, 1, 1)\n h, = ax.plot(data, time)\n hnp, = ax.plot(data, timenp)\n np.testing.assert_equal(h.get_ydata(orig=False), hnp.get_ydata(orig=False))\n\n\n@pytest.mark.parametrize('t0', [datetime.datetime(2017, 1, 1, 0, 1, 1),\n\n [datetime.datetime(2017, 1, 1, 0, 1, 1),\n datetime.datetime(2017, 1, 1, 1, 1, 1)],\n\n [[datetime.datetime(2017, 1, 1, 0, 1, 1),\n datetime.datetime(2017, 1, 1, 1, 1, 1)],\n [datetime.datetime(2017, 1, 1, 2, 1, 1),\n datetime.datetime(2017, 1, 1, 3, 1, 1)]]])\n@pytest.mark.parametrize('dtype', ['datetime64[s]',\n 'datetime64[us]',\n 'datetime64[ms]',\n 'datetime64[ns]'])\ndef test_date_date2num_numpy(t0, dtype):\n time = mdates.date2num(t0)\n tnp = np.array(t0, dtype=dtype)\n nptime = mdates.date2num(tnp)\n np.testing.assert_equal(time, nptime)\n\n\n@pytest.mark.parametrize('dtype', ['datetime64[s]',\n 'datetime64[us]',\n 'datetime64[ms]',\n 'datetime64[ns]'])\ndef test_date2num_NaT(dtype):\n t0 = datetime.datetime(2017, 1, 1, 0, 1, 1)\n tmpl = [mdates.date2num(t0), np.nan]\n tnp = np.array([t0, 'NaT'], dtype=dtype)\n nptime = mdates.date2num(tnp)\n np.testing.assert_array_equal(tmpl, nptime)\n\n\n@pytest.mark.parametrize('units', ['s', 'ms', 'us', 'ns'])\ndef test_date2num_NaT_scalar(units):\n tmpl = mdates.date2num(np.datetime64('NaT', units))\n assert np.isnan(tmpl)\n\n\ndef test_date2num_masked():\n # Without tzinfo\n base = datetime.datetime(2022, 12, 15)\n dates = np.ma.array([base + datetime.timedelta(days=(2 * i))\n for i in range(7)], mask=[0, 1, 1, 0, 0, 0, 1])\n npdates = mdates.date2num(dates)\n np.testing.assert_array_equal(np.ma.getmask(npdates),\n (False, True, True, False, False, False,\n True))\n\n # With tzinfo\n base = datetime.datetime(2022, 12, 15, tzinfo=mdates.UTC)\n dates = np.ma.array([base + datetime.timedelta(days=(2 * i))\n for i in range(7)], mask=[0, 1, 1, 0, 0, 0, 1])\n npdates = mdates.date2num(dates)\n np.testing.assert_array_equal(np.ma.getmask(npdates),\n (False, True, True, False, False, False,\n True))\n\n\ndef test_date_empty():\n # make sure we do the right thing when told to plot dates even\n # if no date data has been presented, cf\n # http://sourceforge.net/tracker/?func=detail&aid=2850075&group_id=80706&atid=560720\n fig, ax = plt.subplots()\n ax.xaxis_date()\n fig.draw_without_rendering()\n np.testing.assert_allclose(ax.get_xlim(),\n [mdates.date2num(np.datetime64('1970-01-01')),\n mdates.date2num(np.datetime64('1970-01-02'))])\n\n mdates._reset_epoch_test_example()\n mdates.set_epoch('0000-12-31')\n fig, ax = plt.subplots()\n ax.xaxis_date()\n fig.draw_without_rendering()\n np.testing.assert_allclose(ax.get_xlim(),\n [mdates.date2num(np.datetime64('1970-01-01')),\n mdates.date2num(np.datetime64('1970-01-02'))])\n mdates._reset_epoch_test_example()\n\n\ndef test_date_not_empty():\n fig = plt.figure()\n ax = fig.add_subplot()\n\n ax.plot([50, 70], [1, 2])\n ax.xaxis.axis_date()\n np.testing.assert_allclose(ax.get_xlim(), [50, 70])\n\n\ndef test_axhline():\n # make sure that axhline doesn't set the xlimits...\n fig, ax = plt.subplots()\n ax.axhline(1.5)\n ax.plot([np.datetime64('2016-01-01'), np.datetime64('2016-01-02')], [1, 2])\n np.testing.assert_allclose(ax.get_xlim(),\n [mdates.date2num(np.datetime64('2016-01-01')),\n mdates.date2num(np.datetime64('2016-01-02'))])\n\n mdates._reset_epoch_test_example()\n mdates.set_epoch('0000-12-31')\n fig, ax = plt.subplots()\n ax.axhline(1.5)\n ax.plot([np.datetime64('2016-01-01'), np.datetime64('2016-01-02')], [1, 2])\n np.testing.assert_allclose(ax.get_xlim(),\n [mdates.date2num(np.datetime64('2016-01-01')),\n mdates.date2num(np.datetime64('2016-01-02'))])\n mdates._reset_epoch_test_example()\n\n\n@image_comparison(['date_axhspan.png'])\ndef test_date_axhspan():\n # test axhspan with date inputs\n t0 = datetime.datetime(2009, 1, 20)\n tf = datetime.datetime(2009, 1, 21)\n fig, ax = plt.subplots()\n ax.axhspan(t0, tf, facecolor="blue", alpha=0.25)\n ax.set_ylim(t0 - datetime.timedelta(days=5),\n tf + datetime.timedelta(days=5))\n fig.subplots_adjust(left=0.25)\n\n\n@image_comparison(['date_axvspan.png'])\ndef test_date_axvspan():\n # test axvspan with date inputs\n t0 = datetime.datetime(2000, 1, 20)\n tf = datetime.datetime(2010, 1, 21)\n fig, ax = plt.subplots()\n ax.axvspan(t0, tf, facecolor="blue", alpha=0.25)\n ax.set_xlim(t0 - datetime.timedelta(days=720),\n tf + datetime.timedelta(days=720))\n fig.autofmt_xdate()\n\n\n@image_comparison(['date_axhline.png'])\ndef test_date_axhline():\n # test axhline with date inputs\n t0 = datetime.datetime(2009, 1, 20)\n tf = datetime.datetime(2009, 1, 31)\n fig, ax = plt.subplots()\n ax.axhline(t0, color="blue", lw=3)\n ax.set_ylim(t0 - datetime.timedelta(days=5),\n tf + datetime.timedelta(days=5))\n fig.subplots_adjust(left=0.25)\n\n\n@image_comparison(['date_axvline.png'])\ndef test_date_axvline():\n # test axvline with date inputs\n t0 = datetime.datetime(2000, 1, 20)\n tf = datetime.datetime(2000, 1, 21)\n fig, ax = plt.subplots()\n ax.axvline(t0, color="red", lw=3)\n ax.set_xlim(t0 - datetime.timedelta(days=5),\n tf + datetime.timedelta(days=5))\n fig.autofmt_xdate()\n\n\ndef test_too_many_date_ticks(caplog):\n # Attempt to test SF 2715172, see\n # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720\n # setting equal datetimes triggers and expander call in\n # transforms.nonsingular which results in too many ticks in the\n # DayLocator. This should emit a log at WARNING level.\n caplog.set_level("WARNING")\n t0 = datetime.datetime(2000, 1, 20)\n tf = datetime.datetime(2000, 1, 20)\n fig, ax = plt.subplots()\n with pytest.warns(UserWarning) as rec:\n ax.set_xlim((t0, tf), auto=True)\n assert len(rec) == 1\n assert ('Attempting to set identical low and high xlims'\n in str(rec[0].message))\n ax.plot([], [])\n ax.xaxis.set_major_locator(mdates.DayLocator())\n v = ax.xaxis.get_major_locator()()\n assert len(v) > 1000\n # The warning is emitted multiple times because the major locator is also\n # called both when placing the minor ticks (for overstriking detection) and\n # during tick label positioning.\n assert caplog.records and all(\n record.name == "matplotlib.ticker" and record.levelname == "WARNING"\n for record in caplog.records)\n assert len(caplog.records) > 0\n\n\ndef _new_epoch_decorator(thefunc):\n @functools.wraps(thefunc)\n def wrapper():\n mdates._reset_epoch_test_example()\n mdates.set_epoch('2000-01-01')\n thefunc()\n mdates._reset_epoch_test_example()\n return wrapper\n\n\n@image_comparison(['RRuleLocator_bounds.png'])\ndef test_RRuleLocator():\n import matplotlib.testing.jpl_units as units\n units.register()\n # This will cause the RRuleLocator to go out of bounds when it tries\n # to add padding to the limits, so we make sure it caps at the correct\n # boundary values.\n t0 = datetime.datetime(1000, 1, 1)\n tf = datetime.datetime(6000, 1, 1)\n\n fig = plt.figure()\n ax = plt.subplot()\n ax.set_autoscale_on(True)\n ax.plot([t0, tf], [0.0, 1.0], marker='o')\n\n rrule = mdates.rrulewrapper(dateutil.rrule.YEARLY, interval=500)\n locator = mdates.RRuleLocator(rrule)\n ax.xaxis.set_major_locator(locator)\n ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))\n\n ax.autoscale_view()\n fig.autofmt_xdate()\n\n\ndef test_RRuleLocator_dayrange():\n loc = mdates.DayLocator()\n x1 = datetime.datetime(year=1, month=1, day=1, tzinfo=mdates.UTC)\n y1 = datetime.datetime(year=1, month=1, day=16, tzinfo=mdates.UTC)\n loc.tick_values(x1, y1)\n # On success, no overflow error shall be thrown\n\n\ndef test_RRuleLocator_close_minmax():\n # if d1 and d2 are very close together, rrule cannot create\n # reasonable tick intervals; ensure that this is handled properly\n rrule = mdates.rrulewrapper(dateutil.rrule.SECONDLY, interval=5)\n loc = mdates.RRuleLocator(rrule)\n d1 = datetime.datetime(year=2020, month=1, day=1)\n d2 = datetime.datetime(year=2020, month=1, day=1, microsecond=1)\n expected = ['2020-01-01 00:00:00+00:00',\n '2020-01-01 00:00:00.000001+00:00']\n assert list(map(str, mdates.num2date(loc.tick_values(d1, d2)))) == expected\n\n\n@image_comparison(['DateFormatter_fractionalSeconds.png'])\ndef test_DateFormatter():\n import matplotlib.testing.jpl_units as units\n units.register()\n\n # Lets make sure that DateFormatter will allow us to have tick marks\n # at intervals of fractional seconds.\n\n t0 = datetime.datetime(2001, 1, 1, 0, 0, 0)\n tf = datetime.datetime(2001, 1, 1, 0, 0, 1)\n\n fig = plt.figure()\n ax = plt.subplot()\n ax.set_autoscale_on(True)\n ax.plot([t0, tf], [0.0, 1.0], marker='o')\n\n # rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 )\n # locator = mpldates.RRuleLocator( rrule )\n # ax.xaxis.set_major_locator( locator )\n # ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) )\n\n ax.autoscale_view()\n fig.autofmt_xdate()\n\n\ndef test_locator_set_formatter():\n """\n Test if setting the locator only will update the AutoDateFormatter to use\n the new locator.\n """\n plt.rcParams["date.autoformatter.minute"] = "%d %H:%M"\n t = [datetime.datetime(2018, 9, 30, 8, 0),\n datetime.datetime(2018, 9, 30, 8, 59),\n datetime.datetime(2018, 9, 30, 10, 30)]\n x = [2, 3, 1]\n\n fig, ax = plt.subplots()\n ax.plot(t, x)\n ax.xaxis.set_major_locator(mdates.MinuteLocator((0, 30)))\n fig.canvas.draw()\n ticklabels = [tl.get_text() for tl in ax.get_xticklabels()]\n expected = ['30 08:00', '30 08:30', '30 09:00',\n '30 09:30', '30 10:00', '30 10:30']\n assert ticklabels == expected\n\n ax.xaxis.set_major_locator(mticker.NullLocator())\n ax.xaxis.set_minor_locator(mdates.MinuteLocator((5, 55)))\n decoy_loc = mdates.MinuteLocator((12, 27))\n ax.xaxis.set_minor_formatter(mdates.AutoDateFormatter(decoy_loc))\n\n ax.xaxis.set_minor_locator(mdates.MinuteLocator((15, 45)))\n fig.canvas.draw()\n ticklabels = [tl.get_text() for tl in ax.get_xticklabels(which="minor")]\n expected = ['30 08:15', '30 08:45', '30 09:15', '30 09:45', '30 10:15']\n assert ticklabels == expected\n\n\ndef test_date_formatter_callable():\n\n class _Locator:\n def _get_unit(self): return -11\n\n def callable_formatting_function(dates, _):\n return [dt.strftime('%d-%m//%Y') for dt in dates]\n\n formatter = mdates.AutoDateFormatter(_Locator())\n formatter.scaled[-10] = callable_formatting_function\n assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014']\n\n\n@pytest.mark.parametrize('delta, expected', [\n (datetime.timedelta(weeks=52 * 200),\n [r'$\mathdefault{%d}$' % year for year in range(1990, 2171, 20)]),\n (datetime.timedelta(days=30),\n [r'$\mathdefault{1990{-}01{-}%02d}$' % day for day in range(1, 32, 3)]),\n (datetime.timedelta(hours=20),\n [r'$\mathdefault{01{-}01\;%02d}$' % hour for hour in range(0, 21, 2)]),\n (datetime.timedelta(minutes=10),\n [r'$\mathdefault{01\;00{:}%02d}$' % minu for minu in range(0, 11)]),\n])\ndef test_date_formatter_usetex(delta, expected):\n style.use("default")\n\n d1 = datetime.datetime(1990, 1, 1)\n d2 = d1 + delta\n\n locator = mdates.AutoDateLocator(interval_multiples=False)\n locator.create_dummy_axis()\n locator.axis.set_view_interval(mdates.date2num(d1), mdates.date2num(d2))\n\n formatter = mdates.AutoDateFormatter(locator, usetex=True)\n assert [formatter(loc) for loc in locator()] == expected\n\n\ndef test_drange():\n """\n This test should check if drange works as expected, and if all the\n rounding errors are fixed\n """\n start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)\n end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)\n delta = datetime.timedelta(hours=1)\n # We expect 24 values in drange(start, end, delta), because drange returns\n # dates from an half open interval [start, end)\n assert len(mdates.drange(start, end, delta)) == 24\n\n # Same if interval ends slightly earlier\n end = end - datetime.timedelta(microseconds=1)\n assert len(mdates.drange(start, end, delta)) == 24\n\n # if end is a little bit later, we expect the range to contain one element\n # more\n end = end + datetime.timedelta(microseconds=2)\n assert len(mdates.drange(start, end, delta)) == 25\n\n # reset end\n end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)\n\n # and tst drange with "complicated" floats:\n # 4 hours = 1/6 day, this is an "dangerous" float\n delta = datetime.timedelta(hours=4)\n daterange = mdates.drange(start, end, delta)\n assert len(daterange) == 6\n assert mdates.num2date(daterange[-1]) == (end - delta)\n\n\n@_new_epoch_decorator\ndef test_auto_date_locator():\n def _create_auto_date_locator(date1, date2):\n locator = mdates.AutoDateLocator(interval_multiples=False)\n locator.create_dummy_axis()\n locator.axis.set_view_interval(*mdates.date2num([date1, date2]))\n return locator\n\n d1 = datetime.datetime(1990, 1, 1)\n results = ([datetime.timedelta(weeks=52 * 200),\n ['1990-01-01 00:00:00+00:00', '2010-01-01 00:00:00+00:00',\n '2030-01-01 00:00:00+00:00', '2050-01-01 00:00:00+00:00',\n '2070-01-01 00:00:00+00:00', '2090-01-01 00:00:00+00:00',\n '2110-01-01 00:00:00+00:00', '2130-01-01 00:00:00+00:00',\n '2150-01-01 00:00:00+00:00', '2170-01-01 00:00:00+00:00']\n ],\n [datetime.timedelta(weeks=52),\n ['1990-01-01 00:00:00+00:00', '1990-02-01 00:00:00+00:00',\n '1990-03-01 00:00:00+00:00', '1990-04-01 00:00:00+00:00',\n '1990-05-01 00:00:00+00:00', '1990-06-01 00:00:00+00:00',\n '1990-07-01 00:00:00+00:00', '1990-08-01 00:00:00+00:00',\n '1990-09-01 00:00:00+00:00', '1990-10-01 00:00:00+00:00',\n '1990-11-01 00:00:00+00:00', '1990-12-01 00:00:00+00:00']\n ],\n [datetime.timedelta(days=141),\n ['1990-01-05 00:00:00+00:00', '1990-01-26 00:00:00+00:00',\n '1990-02-16 00:00:00+00:00', '1990-03-09 00:00:00+00:00',\n '1990-03-30 00:00:00+00:00', '1990-04-20 00:00:00+00:00',\n '1990-05-11 00:00:00+00:00']\n ],\n [datetime.timedelta(days=40),\n ['1990-01-03 00:00:00+00:00', '1990-01-10 00:00:00+00:00',\n '1990-01-17 00:00:00+00:00', '1990-01-24 00:00:00+00:00',\n '1990-01-31 00:00:00+00:00', '1990-02-07 00:00:00+00:00']\n ],\n [datetime.timedelta(hours=40),\n ['1990-01-01 00:00:00+00:00', '1990-01-01 04:00:00+00:00',\n '1990-01-01 08:00:00+00:00', '1990-01-01 12:00:00+00:00',\n '1990-01-01 16:00:00+00:00', '1990-01-01 20:00:00+00:00',\n '1990-01-02 00:00:00+00:00', '1990-01-02 04:00:00+00:00',\n '1990-01-02 08:00:00+00:00', '1990-01-02 12:00:00+00:00',\n '1990-01-02 16:00:00+00:00']\n ],\n [datetime.timedelta(minutes=20),\n ['1990-01-01 00:00:00+00:00', '1990-01-01 00:05:00+00:00',\n '1990-01-01 00:10:00+00:00', '1990-01-01 00:15:00+00:00',\n '1990-01-01 00:20:00+00:00']\n ],\n [datetime.timedelta(seconds=40),\n ['1990-01-01 00:00:00+00:00', '1990-01-01 00:00:05+00:00',\n '1990-01-01 00:00:10+00:00', '1990-01-01 00:00:15+00:00',\n '1990-01-01 00:00:20+00:00', '1990-01-01 00:00:25+00:00',\n '1990-01-01 00:00:30+00:00', '1990-01-01 00:00:35+00:00',\n '1990-01-01 00:00:40+00:00']\n ],\n [datetime.timedelta(microseconds=1500),\n ['1989-12-31 23:59:59.999500+00:00',\n '1990-01-01 00:00:00+00:00',\n '1990-01-01 00:00:00.000500+00:00',\n '1990-01-01 00:00:00.001000+00:00',\n '1990-01-01 00:00:00.001500+00:00',\n '1990-01-01 00:00:00.002000+00:00']\n ],\n )\n\n for t_delta, expected in results:\n d2 = d1 + t_delta\n locator = _create_auto_date_locator(d1, d2)\n assert list(map(str, mdates.num2date(locator()))) == expected\n\n locator = mdates.AutoDateLocator(interval_multiples=False)\n assert locator.maxticks == {0: 11, 1: 12, 3: 11, 4: 12, 5: 11, 6: 11, 7: 8}\n\n locator = mdates.AutoDateLocator(maxticks={dateutil.rrule.MONTHLY: 5})\n assert locator.maxticks == {0: 11, 1: 5, 3: 11, 4: 12, 5: 11, 6: 11, 7: 8}\n\n locator = mdates.AutoDateLocator(maxticks=5)\n assert locator.maxticks == {0: 5, 1: 5, 3: 5, 4: 5, 5: 5, 6: 5, 7: 5}\n\n\n@_new_epoch_decorator\ndef test_auto_date_locator_intmult():\n def _create_auto_date_locator(date1, date2):\n locator = mdates.AutoDateLocator(interval_multiples=True)\n locator.create_dummy_axis()\n locator.axis.set_view_interval(*mdates.date2num([date1, date2]))\n return locator\n\n results = ([datetime.timedelta(weeks=52 * 200),\n ['1980-01-01 00:00:00+00:00', '2000-01-01 00:00:00+00:00',\n '2020-01-01 00:00:00+00:00', '2040-01-01 00:00:00+00:00',\n '2060-01-01 00:00:00+00:00', '2080-01-01 00:00:00+00:00',\n '2100-01-01 00:00:00+00:00', '2120-01-01 00:00:00+00:00',\n '2140-01-01 00:00:00+00:00', '2160-01-01 00:00:00+00:00',\n '2180-01-01 00:00:00+00:00', '2200-01-01 00:00:00+00:00']\n ],\n [datetime.timedelta(weeks=52),\n ['1997-01-01 00:00:00+00:00', '1997-02-01 00:00:00+00:00',\n '1997-03-01 00:00:00+00:00', '1997-04-01 00:00:00+00:00',\n '1997-05-01 00:00:00+00:00', '1997-06-01 00:00:00+00:00',\n '1997-07-01 00:00:00+00:00', '1997-08-01 00:00:00+00:00',\n '1997-09-01 00:00:00+00:00', '1997-10-01 00:00:00+00:00',\n '1997-11-01 00:00:00+00:00', '1997-12-01 00:00:00+00:00']\n ],\n [datetime.timedelta(days=141),\n ['1997-01-01 00:00:00+00:00', '1997-01-15 00:00:00+00:00',\n '1997-02-01 00:00:00+00:00', '1997-02-15 00:00:00+00:00',\n '1997-03-01 00:00:00+00:00', '1997-03-15 00:00:00+00:00',\n '1997-04-01 00:00:00+00:00', '1997-04-15 00:00:00+00:00',\n '1997-05-01 00:00:00+00:00', '1997-05-15 00:00:00+00:00']\n ],\n [datetime.timedelta(days=40),\n ['1997-01-01 00:00:00+00:00', '1997-01-05 00:00:00+00:00',\n '1997-01-09 00:00:00+00:00', '1997-01-13 00:00:00+00:00',\n '1997-01-17 00:00:00+00:00', '1997-01-21 00:00:00+00:00',\n '1997-01-25 00:00:00+00:00', '1997-01-29 00:00:00+00:00',\n '1997-02-01 00:00:00+00:00', '1997-02-05 00:00:00+00:00',\n '1997-02-09 00:00:00+00:00']\n ],\n [datetime.timedelta(hours=40),\n ['1997-01-01 00:00:00+00:00', '1997-01-01 04:00:00+00:00',\n '1997-01-01 08:00:00+00:00', '1997-01-01 12:00:00+00:00',\n '1997-01-01 16:00:00+00:00', '1997-01-01 20:00:00+00:00',\n '1997-01-02 00:00:00+00:00', '1997-01-02 04:00:00+00:00',\n '1997-01-02 08:00:00+00:00', '1997-01-02 12:00:00+00:00',\n '1997-01-02 16:00:00+00:00']\n ],\n [datetime.timedelta(minutes=20),\n ['1997-01-01 00:00:00+00:00', '1997-01-01 00:05:00+00:00',\n '1997-01-01 00:10:00+00:00', '1997-01-01 00:15:00+00:00',\n '1997-01-01 00:20:00+00:00']\n ],\n [datetime.timedelta(seconds=40),\n ['1997-01-01 00:00:00+00:00', '1997-01-01 00:00:05+00:00',\n '1997-01-01 00:00:10+00:00', '1997-01-01 00:00:15+00:00',\n '1997-01-01 00:00:20+00:00', '1997-01-01 00:00:25+00:00',\n '1997-01-01 00:00:30+00:00', '1997-01-01 00:00:35+00:00',\n '1997-01-01 00:00:40+00:00']\n ],\n [datetime.timedelta(microseconds=1500),\n ['1996-12-31 23:59:59.999500+00:00',\n '1997-01-01 00:00:00+00:00',\n '1997-01-01 00:00:00.000500+00:00',\n '1997-01-01 00:00:00.001000+00:00',\n '1997-01-01 00:00:00.001500+00:00',\n '1997-01-01 00:00:00.002000+00:00']\n ],\n )\n\n d1 = datetime.datetime(1997, 1, 1)\n for t_delta, expected in results:\n d2 = d1 + t_delta\n locator = _create_auto_date_locator(d1, d2)\n assert list(map(str, mdates.num2date(locator()))) == expected\n\n\ndef test_concise_formatter_subsecond():\n locator = mdates.AutoDateLocator(interval_multiples=True)\n formatter = mdates.ConciseDateFormatter(locator)\n year_1996 = 9861.0\n strings = formatter.format_ticks([\n year_1996,\n year_1996 + 500 / mdates.MUSECONDS_PER_DAY,\n year_1996 + 900 / mdates.MUSECONDS_PER_DAY])\n assert strings == ['00:00', '00.0005', '00.0009']\n\n\ndef test_concise_formatter():\n def _create_auto_date_locator(date1, date2):\n fig, ax = plt.subplots()\n\n locator = mdates.AutoDateLocator(interval_multiples=True)\n formatter = mdates.ConciseDateFormatter(locator)\n ax.yaxis.set_major_locator(locator)\n ax.yaxis.set_major_formatter(formatter)\n ax.set_ylim(date1, date2)\n fig.canvas.draw()\n sts = [st.get_text() for st in ax.get_yticklabels()]\n return sts\n\n d1 = datetime.datetime(1997, 1, 1)\n results = ([datetime.timedelta(weeks=52 * 200),\n [str(t) for t in range(1980, 2201, 20)]\n ],\n [datetime.timedelta(weeks=52),\n ['1997', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',\n 'Sep', 'Oct', 'Nov', 'Dec']\n ],\n [datetime.timedelta(days=141),\n ['Jan', '15', 'Feb', '15', 'Mar', '15', 'Apr', '15',\n 'May', '15']\n ],\n [datetime.timedelta(days=40),\n ['Jan', '05', '09', '13', '17', '21', '25', '29', 'Feb',\n '05', '09']\n ],\n [datetime.timedelta(hours=40),\n ['Jan-01', '04:00', '08:00', '12:00', '16:00', '20:00',\n 'Jan-02', '04:00', '08:00', '12:00', '16:00']\n ],\n [datetime.timedelta(minutes=20),\n ['00:00', '00:05', '00:10', '00:15', '00:20']\n ],\n [datetime.timedelta(seconds=40),\n ['00:00', '05', '10', '15', '20', '25', '30', '35', '40']\n ],\n [datetime.timedelta(seconds=2),\n ['59.5', '00:00', '00.5', '01.0', '01.5', '02.0', '02.5']\n ],\n )\n for t_delta, expected in results:\n d2 = d1 + t_delta\n strings = _create_auto_date_locator(d1, d2)\n assert strings == expected\n\n\n@pytest.mark.parametrize('t_delta, expected', [\n (datetime.timedelta(seconds=0.01), '1997-Jan-01 00:00'),\n (datetime.timedelta(minutes=1), '1997-Jan-01 00:01'),\n (datetime.timedelta(hours=1), '1997-Jan-01'),\n (datetime.timedelta(days=1), '1997-Jan-02'),\n (datetime.timedelta(weeks=1), '1997-Jan'),\n (datetime.timedelta(weeks=26), ''),\n (datetime.timedelta(weeks=520), '')\n])\ndef test_concise_formatter_show_offset(t_delta, expected):\n d1 = datetime.datetime(1997, 1, 1)\n d2 = d1 + t_delta\n\n fig, ax = plt.subplots()\n locator = mdates.AutoDateLocator()\n formatter = mdates.ConciseDateFormatter(locator)\n ax.xaxis.set_major_locator(locator)\n ax.xaxis.set_major_formatter(formatter)\n\n ax.plot([d1, d2], [0, 0])\n fig.canvas.draw()\n assert formatter.get_offset() == expected\n\n\ndef test_concise_formatter_show_offset_inverted():\n # Test for github issue #28481\n d1 = datetime.datetime(1997, 1, 1)\n d2 = d1 + datetime.timedelta(days=60)\n\n fig, ax = plt.subplots()\n locator = mdates.AutoDateLocator()\n formatter = mdates.ConciseDateFormatter(locator)\n ax.xaxis.set_major_locator(locator)\n ax.xaxis.set_major_formatter(formatter)\n ax.invert_xaxis()\n\n ax.plot([d1, d2], [0, 0])\n fig.canvas.draw()\n assert formatter.get_offset() == '1997-Jan'\n\n\ndef test_concise_converter_stays():\n # This test demonstrates problems introduced by gh-23417 (reverted in gh-25278)\n # In particular, downstream libraries like Pandas had their designated converters\n # overridden by actions like setting xlim (or plotting additional points using\n # stdlib/numpy dates and string date representation, which otherwise work fine with\n # their date converters)\n # While this is a bit of a toy example that would be unusual to see it demonstrates\n # the same ideas (namely having a valid converter already applied that is desired)\n # without introducing additional subclasses.\n # See also discussion at gh-25219 for how Pandas was affected\n x = [datetime.datetime(2000, 1, 1), datetime.datetime(2020, 2, 20)]\n y = [0, 1]\n fig, ax = plt.subplots()\n ax.plot(x, y)\n # Bypass Switchable date converter\n conv = mdates.ConciseDateConverter()\n with pytest.warns(UserWarning, match="already has a converter"):\n ax.xaxis.set_converter(conv)\n assert ax.xaxis.units is None\n ax.set_xlim(*x)\n assert ax.xaxis.get_converter() == conv\n\n\ndef test_offset_changes():\n fig, ax = plt.subplots()\n\n d1 = datetime.datetime(1997, 1, 1)\n d2 = d1 + datetime.timedelta(weeks=520)\n\n locator = mdates.AutoDateLocator()\n formatter = mdates.ConciseDateFormatter(locator)\n ax.xaxis.set_major_locator(locator)\n ax.xaxis.set_major_formatter(formatter)\n\n ax.plot([d1, d2], [0, 0])\n fig.draw_without_rendering()\n assert formatter.get_offset() == ''\n ax.set_xlim(d1, d1 + datetime.timedelta(weeks=3))\n fig.draw_without_rendering()\n assert formatter.get_offset() == '1997-Jan'\n ax.set_xlim(d1 + datetime.timedelta(weeks=7),\n d1 + datetime.timedelta(weeks=30))\n fig.draw_without_rendering()\n assert formatter.get_offset() == '1997'\n ax.set_xlim(d1, d1 + datetime.timedelta(weeks=520))\n fig.draw_without_rendering()\n assert formatter.get_offset() == ''\n\n\n@pytest.mark.parametrize('t_delta, expected', [\n (datetime.timedelta(weeks=52 * 200),\n ['$\\mathdefault{%d}$' % (t, ) for t in range(1980, 2201, 20)]),\n (datetime.timedelta(days=40),\n ['Jan', '$\\mathdefault{05}$', '$\\mathdefault{09}$',\n '$\\mathdefault{13}$', '$\\mathdefault{17}$', '$\\mathdefault{21}$',\n '$\\mathdefault{25}$', '$\\mathdefault{29}$', 'Feb',\n '$\\mathdefault{05}$', '$\\mathdefault{09}$']),\n (datetime.timedelta(hours=40),\n ['Jan$\\mathdefault{{-}01}$', '$\\mathdefault{04{:}00}$',\n '$\\mathdefault{08{:}00}$', '$\\mathdefault{12{:}00}$',\n '$\\mathdefault{16{:}00}$', '$\\mathdefault{20{:}00}$',\n 'Jan$\\mathdefault{{-}02}$', '$\\mathdefault{04{:}00}$',\n '$\\mathdefault{08{:}00}$', '$\\mathdefault{12{:}00}$',\n '$\\mathdefault{16{:}00}$']),\n (datetime.timedelta(seconds=2),\n ['$\\mathdefault{59.5}$', '$\\mathdefault{00{:}00}$',\n '$\\mathdefault{00.5}$', '$\\mathdefault{01.0}$',\n '$\\mathdefault{01.5}$', '$\\mathdefault{02.0}$',\n '$\\mathdefault{02.5}$']),\n])\ndef test_concise_formatter_usetex(t_delta, expected):\n d1 = datetime.datetime(1997, 1, 1)\n d2 = d1 + t_delta\n\n locator = mdates.AutoDateLocator(interval_multiples=True)\n locator.create_dummy_axis()\n locator.axis.set_view_interval(mdates.date2num(d1), mdates.date2num(d2))\n\n formatter = mdates.ConciseDateFormatter(locator, usetex=True)\n assert formatter.format_ticks(locator()) == expected\n\n\ndef test_concise_formatter_formats():\n formats = ['%Y', '%m/%Y', 'day: %d',\n '%H hr %M min', '%H hr %M min', '%S.%f sec']\n\n def _create_auto_date_locator(date1, date2):\n fig, ax = plt.subplots()\n\n locator = mdates.AutoDateLocator(interval_multiples=True)\n formatter = mdates.ConciseDateFormatter(locator, formats=formats)\n ax.yaxis.set_major_locator(locator)\n ax.yaxis.set_major_formatter(formatter)\n ax.set_ylim(date1, date2)\n fig.canvas.draw()\n sts = [st.get_text() for st in ax.get_yticklabels()]\n return sts\n\n d1 = datetime.datetime(1997, 1, 1)\n results = (\n [datetime.timedelta(weeks=52 * 200), [str(t) for t in range(1980,\n 2201, 20)]],\n [datetime.timedelta(weeks=52), [\n '1997', '02/1997', '03/1997', '04/1997', '05/1997', '06/1997',\n '07/1997', '08/1997', '09/1997', '10/1997', '11/1997', '12/1997',\n ]],\n [datetime.timedelta(days=141), [\n '01/1997', 'day: 15', '02/1997', 'day: 15', '03/1997', 'day: 15',\n '04/1997', 'day: 15', '05/1997', 'day: 15',\n ]],\n [datetime.timedelta(days=40), [\n '01/1997', 'day: 05', 'day: 09', 'day: 13', 'day: 17', 'day: 21',\n 'day: 25', 'day: 29', '02/1997', 'day: 05', 'day: 09',\n ]],\n [datetime.timedelta(hours=40), [\n 'day: 01', '04 hr 00 min', '08 hr 00 min', '12 hr 00 min',\n '16 hr 00 min', '20 hr 00 min', 'day: 02', '04 hr 00 min',\n '08 hr 00 min', '12 hr 00 min', '16 hr 00 min',\n ]],\n [datetime.timedelta(minutes=20), ['00 hr 00 min', '00 hr 05 min',\n '00 hr 10 min', '00 hr 15 min', '00 hr 20 min']],\n [datetime.timedelta(seconds=40), [\n '00 hr 00 min', '05.000000 sec', '10.000000 sec',\n '15.000000 sec', '20.000000 sec', '25.000000 sec',\n '30.000000 sec', '35.000000 sec', '40.000000 sec',\n ]],\n [datetime.timedelta(seconds=2), [\n '59.500000 sec', '00 hr 00 min', '00.500000 sec', '01.000000 sec',\n '01.500000 sec', '02.000000 sec', '02.500000 sec',\n ]],\n )\n for t_delta, expected in results:\n d2 = d1 + t_delta\n strings = _create_auto_date_locator(d1, d2)\n assert strings == expected\n\n\ndef test_concise_formatter_zformats():\n zero_formats = ['', "'%y", '%B', '%m-%d', '%S', '%S.%f']\n\n def _create_auto_date_locator(date1, date2):\n fig, ax = plt.subplots()\n\n locator = mdates.AutoDateLocator(interval_multiples=True)\n formatter = mdates.ConciseDateFormatter(\n locator, zero_formats=zero_formats)\n ax.yaxis.set_major_locator(locator)\n ax.yaxis.set_major_formatter(formatter)\n ax.set_ylim(date1, date2)\n fig.canvas.draw()\n sts = [st.get_text() for st in ax.get_yticklabels()]\n return sts\n\n d1 = datetime.datetime(1997, 1, 1)\n results = ([datetime.timedelta(weeks=52 * 200),\n [str(t) for t in range(1980, 2201, 20)]\n ],\n [datetime.timedelta(weeks=52),\n ["'97", 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n ],\n [datetime.timedelta(days=141),\n ['January', '15', 'February', '15', 'March',\n '15', 'April', '15', 'May', '15']\n ],\n [datetime.timedelta(days=40),\n ['January', '05', '09', '13', '17', '21',\n '25', '29', 'February', '05', '09']\n ],\n [datetime.timedelta(hours=40),\n ['01-01', '04:00', '08:00', '12:00', '16:00', '20:00',\n '01-02', '04:00', '08:00', '12:00', '16:00']\n ],\n [datetime.timedelta(minutes=20),\n ['00', '00:05', '00:10', '00:15', '00:20']\n ],\n [datetime.timedelta(seconds=40),\n ['00', '05', '10', '15', '20', '25', '30', '35', '40']\n ],\n [datetime.timedelta(seconds=2),\n ['59.5', '00.0', '00.5', '01.0', '01.5', '02.0', '02.5']\n ],\n )\n for t_delta, expected in results:\n d2 = d1 + t_delta\n strings = _create_auto_date_locator(d1, d2)\n assert strings == expected\n\n\ndef test_concise_formatter_tz():\n def _create_auto_date_locator(date1, date2, tz):\n fig, ax = plt.subplots()\n\n locator = mdates.AutoDateLocator(interval_multiples=True)\n formatter = mdates.ConciseDateFormatter(locator, tz=tz)\n ax.yaxis.set_major_locator(locator)\n ax.yaxis.set_major_formatter(formatter)\n ax.set_ylim(date1, date2)\n fig.canvas.draw()\n sts = [st.get_text() for st in ax.get_yticklabels()]\n return sts, ax.yaxis.get_offset_text().get_text()\n\n d1 = datetime.datetime(1997, 1, 1).replace(tzinfo=datetime.timezone.utc)\n results = ([datetime.timedelta(hours=40),\n ['03:00', '07:00', '11:00', '15:00', '19:00', '23:00',\n '03:00', '07:00', '11:00', '15:00', '19:00'],\n "1997-Jan-02"\n ],\n [datetime.timedelta(minutes=20),\n ['03:00', '03:05', '03:10', '03:15', '03:20'],\n "1997-Jan-01"\n ],\n [datetime.timedelta(seconds=40),\n ['03:00', '05', '10', '15', '20', '25', '30', '35', '40'],\n "1997-Jan-01 03:00"\n ],\n [datetime.timedelta(seconds=2),\n ['59.5', '03:00', '00.5', '01.0', '01.5', '02.0', '02.5'],\n "1997-Jan-01 03:00"\n ],\n )\n\n new_tz = datetime.timezone(datetime.timedelta(hours=3))\n for t_delta, expected_strings, expected_offset in results:\n d2 = d1 + t_delta\n strings, offset = _create_auto_date_locator(d1, d2, new_tz)\n assert strings == expected_strings\n assert offset == expected_offset\n\n\ndef test_auto_date_locator_intmult_tz():\n def _create_auto_date_locator(date1, date2, tz):\n locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz)\n locator.create_dummy_axis()\n locator.axis.set_view_interval(*mdates.date2num([date1, date2]))\n return locator\n\n results = ([datetime.timedelta(weeks=52*200),\n ['1980-01-01 00:00:00-08:00', '2000-01-01 00:00:00-08:00',\n '2020-01-01 00:00:00-08:00', '2040-01-01 00:00:00-08:00',\n '2060-01-01 00:00:00-08:00', '2080-01-01 00:00:00-08:00',\n '2100-01-01 00:00:00-08:00', '2120-01-01 00:00:00-08:00',\n '2140-01-01 00:00:00-08:00', '2160-01-01 00:00:00-08:00',\n '2180-01-01 00:00:00-08:00', '2200-01-01 00:00:00-08:00']\n ],\n [datetime.timedelta(weeks=52),\n ['1997-01-01 00:00:00-08:00', '1997-02-01 00:00:00-08:00',\n '1997-03-01 00:00:00-08:00', '1997-04-01 00:00:00-08:00',\n '1997-05-01 00:00:00-07:00', '1997-06-01 00:00:00-07:00',\n '1997-07-01 00:00:00-07:00', '1997-08-01 00:00:00-07:00',\n '1997-09-01 00:00:00-07:00', '1997-10-01 00:00:00-07:00',\n '1997-11-01 00:00:00-08:00', '1997-12-01 00:00:00-08:00']\n ],\n [datetime.timedelta(days=141),\n ['1997-01-01 00:00:00-08:00', '1997-01-15 00:00:00-08:00',\n '1997-02-01 00:00:00-08:00', '1997-02-15 00:00:00-08:00',\n '1997-03-01 00:00:00-08:00', '1997-03-15 00:00:00-08:00',\n '1997-04-01 00:00:00-08:00', '1997-04-15 00:00:00-07:00',\n '1997-05-01 00:00:00-07:00', '1997-05-15 00:00:00-07:00']\n ],\n [datetime.timedelta(days=40),\n ['1997-01-01 00:00:00-08:00', '1997-01-05 00:00:00-08:00',\n '1997-01-09 00:00:00-08:00', '1997-01-13 00:00:00-08:00',\n '1997-01-17 00:00:00-08:00', '1997-01-21 00:00:00-08:00',\n '1997-01-25 00:00:00-08:00', '1997-01-29 00:00:00-08:00',\n '1997-02-01 00:00:00-08:00', '1997-02-05 00:00:00-08:00',\n '1997-02-09 00:00:00-08:00']\n ],\n [datetime.timedelta(hours=40),\n ['1997-01-01 00:00:00-08:00', '1997-01-01 04:00:00-08:00',\n '1997-01-01 08:00:00-08:00', '1997-01-01 12:00:00-08:00',\n '1997-01-01 16:00:00-08:00', '1997-01-01 20:00:00-08:00',\n '1997-01-02 00:00:00-08:00', '1997-01-02 04:00:00-08:00',\n '1997-01-02 08:00:00-08:00', '1997-01-02 12:00:00-08:00',\n '1997-01-02 16:00:00-08:00']\n ],\n [datetime.timedelta(minutes=20),\n ['1997-01-01 00:00:00-08:00', '1997-01-01 00:05:00-08:00',\n '1997-01-01 00:10:00-08:00', '1997-01-01 00:15:00-08:00',\n '1997-01-01 00:20:00-08:00']\n ],\n [datetime.timedelta(seconds=40),\n ['1997-01-01 00:00:00-08:00', '1997-01-01 00:00:05-08:00',\n '1997-01-01 00:00:10-08:00', '1997-01-01 00:00:15-08:00',\n '1997-01-01 00:00:20-08:00', '1997-01-01 00:00:25-08:00',\n '1997-01-01 00:00:30-08:00', '1997-01-01 00:00:35-08:00',\n '1997-01-01 00:00:40-08:00']\n ]\n )\n\n tz = dateutil.tz.gettz('Canada/Pacific')\n d1 = datetime.datetime(1997, 1, 1, tzinfo=tz)\n for t_delta, expected in results:\n with rc_context({'_internal.classic_mode': False}):\n d2 = d1 + t_delta\n locator = _create_auto_date_locator(d1, d2, tz)\n st = list(map(str, mdates.num2date(locator(), tz=tz)))\n assert st == expected\n\n\n@image_comparison(['date_inverted_limit.png'])\ndef test_date_inverted_limit():\n # test ax hline with date inputs\n t0 = datetime.datetime(2009, 1, 20)\n tf = datetime.datetime(2009, 1, 31)\n fig, ax = plt.subplots()\n ax.axhline(t0, color="blue", lw=3)\n ax.set_ylim(t0 - datetime.timedelta(days=5),\n tf + datetime.timedelta(days=5))\n ax.invert_yaxis()\n fig.subplots_adjust(left=0.25)\n\n\ndef _test_date2num_dst(date_range, tz_convert):\n # Timezones\n\n BRUSSELS = dateutil.tz.gettz('Europe/Brussels')\n UTC = mdates.UTC\n\n # Create a list of timezone-aware datetime objects in UTC\n # Interval is 0b0.0000011 days, to prevent float rounding issues\n dtstart = datetime.datetime(2014, 3, 30, 0, 0, tzinfo=UTC)\n interval = datetime.timedelta(minutes=33, seconds=45)\n interval_days = interval.seconds / 86400\n N = 8\n\n dt_utc = date_range(start=dtstart, freq=interval, periods=N)\n dt_bxl = tz_convert(dt_utc, BRUSSELS)\n t0 = 735322.0 + mdates.date2num(np.datetime64('0000-12-31'))\n expected_ordinalf = [t0 + (i * interval_days) for i in range(N)]\n actual_ordinalf = list(mdates.date2num(dt_bxl))\n\n assert actual_ordinalf == expected_ordinalf\n\n\ndef test_date2num_dst():\n # Test for github issue #3896, but in date2num around DST transitions\n # with a timezone-aware pandas date_range object.\n\n class dt_tzaware(datetime.datetime):\n """\n This bug specifically occurs because of the normalization behavior of\n pandas Timestamp objects, so in order to replicate it, we need a\n datetime-like object that applies timezone normalization after\n subtraction.\n """\n\n def __sub__(self, other):\n r = super().__sub__(other)\n tzinfo = getattr(r, 'tzinfo', None)\n\n if tzinfo is not None:\n localizer = getattr(tzinfo, 'normalize', None)\n if localizer is not None:\n r = tzinfo.normalize(r)\n\n if isinstance(r, datetime.datetime):\n r = self.mk_tzaware(r)\n\n return r\n\n def __add__(self, other):\n return self.mk_tzaware(super().__add__(other))\n\n def astimezone(self, tzinfo):\n dt = super().astimezone(tzinfo)\n return self.mk_tzaware(dt)\n\n @classmethod\n def mk_tzaware(cls, datetime_obj):\n kwargs = {}\n attrs = ('year',\n 'month',\n 'day',\n 'hour',\n 'minute',\n 'second',\n 'microsecond',\n 'tzinfo')\n\n for attr in attrs:\n val = getattr(datetime_obj, attr, None)\n if val is not None:\n kwargs[attr] = val\n\n return cls(**kwargs)\n\n # Define a date_range function similar to pandas.date_range\n def date_range(start, freq, periods):\n dtstart = dt_tzaware.mk_tzaware(start)\n\n return [dtstart + (i * freq) for i in range(periods)]\n\n # Define a tz_convert function that converts a list to a new timezone.\n def tz_convert(dt_list, tzinfo):\n return [d.astimezone(tzinfo) for d in dt_list]\n\n _test_date2num_dst(date_range, tz_convert)\n\n\ndef test_date2num_dst_pandas(pd):\n # Test for github issue #3896, but in date2num around DST transitions\n # with a timezone-aware pandas date_range object.\n\n def tz_convert(*args):\n return pd.DatetimeIndex.tz_convert(*args).astype(object)\n\n _test_date2num_dst(pd.date_range, tz_convert)\n\n\ndef _test_rrulewrapper(attach_tz, get_tz):\n SYD = get_tz('Australia/Sydney')\n\n dtstart = attach_tz(datetime.datetime(2017, 4, 1, 0), SYD)\n dtend = attach_tz(datetime.datetime(2017, 4, 4, 0), SYD)\n\n rule = mdates.rrulewrapper(freq=dateutil.rrule.DAILY, dtstart=dtstart)\n\n act = rule.between(dtstart, dtend)\n exp = [datetime.datetime(2017, 4, 1, 13, tzinfo=dateutil.tz.tzutc()),\n datetime.datetime(2017, 4, 2, 14, tzinfo=dateutil.tz.tzutc())]\n\n assert act == exp\n\n\ndef test_rrulewrapper():\n def attach_tz(dt, zi):\n return dt.replace(tzinfo=zi)\n\n _test_rrulewrapper(attach_tz, dateutil.tz.gettz)\n\n SYD = dateutil.tz.gettz('Australia/Sydney')\n dtstart = datetime.datetime(2017, 4, 1, 0)\n dtend = datetime.datetime(2017, 4, 4, 0)\n rule = mdates.rrulewrapper(freq=dateutil.rrule.DAILY, dtstart=dtstart,\n tzinfo=SYD, until=dtend)\n assert rule.after(dtstart) == datetime.datetime(2017, 4, 2, 0, 0,\n tzinfo=SYD)\n assert rule.before(dtend) == datetime.datetime(2017, 4, 3, 0, 0,\n tzinfo=SYD)\n\n # Test parts of __getattr__\n assert rule._base_tzinfo == SYD\n assert rule._interval == 1\n\n\n@pytest.mark.pytz\ndef test_rrulewrapper_pytz():\n # Test to make sure pytz zones are supported in rrules\n pytz = pytest.importorskip("pytz")\n\n def attach_tz(dt, zi):\n return zi.localize(dt)\n\n _test_rrulewrapper(attach_tz, pytz.timezone)\n\n\n@pytest.mark.pytz\ndef test_yearlocator_pytz():\n pytz = pytest.importorskip("pytz")\n\n tz = pytz.timezone('America/New_York')\n x = [tz.localize(datetime.datetime(2010, 1, 1))\n + datetime.timedelta(i) for i in range(2000)]\n locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz)\n locator.create_dummy_axis()\n locator.axis.set_view_interval(mdates.date2num(x[0])-1.0,\n mdates.date2num(x[-1])+1.0)\n t = np.array([733408.208333, 733773.208333, 734138.208333,\n 734503.208333, 734869.208333, 735234.208333, 735599.208333])\n # convert to new epoch from old...\n t = t + mdates.date2num(np.datetime64('0000-12-31'))\n np.testing.assert_allclose(t, locator())\n expected = ['2009-01-01 00:00:00-05:00',\n '2010-01-01 00:00:00-05:00', '2011-01-01 00:00:00-05:00',\n '2012-01-01 00:00:00-05:00', '2013-01-01 00:00:00-05:00',\n '2014-01-01 00:00:00-05:00', '2015-01-01 00:00:00-05:00']\n st = list(map(str, mdates.num2date(locator(), tz=tz)))\n assert st == expected\n assert np.allclose(locator.tick_values(x[0], x[1]), np.array(\n [14610.20833333, 14610.33333333, 14610.45833333, 14610.58333333,\n 14610.70833333, 14610.83333333, 14610.95833333, 14611.08333333,\n 14611.20833333]))\n assert np.allclose(locator.get_locator(x[1], x[0]).tick_values(x[0], x[1]),\n np.array(\n [14610.20833333, 14610.33333333, 14610.45833333, 14610.58333333,\n 14610.70833333, 14610.83333333, 14610.95833333, 14611.08333333,\n 14611.20833333]))\n\n\ndef test_YearLocator():\n def _create_year_locator(date1, date2, **kwargs):\n locator = mdates.YearLocator(**kwargs)\n locator.create_dummy_axis()\n locator.axis.set_view_interval(mdates.date2num(date1),\n mdates.date2num(date2))\n return locator\n\n d1 = datetime.datetime(1990, 1, 1)\n results = ([datetime.timedelta(weeks=52 * 200),\n {'base': 20, 'month': 1, 'day': 1},\n ['1980-01-01 00:00:00+00:00', '2000-01-01 00:00:00+00:00',\n '2020-01-01 00:00:00+00:00', '2040-01-01 00:00:00+00:00',\n '2060-01-01 00:00:00+00:00', '2080-01-01 00:00:00+00:00',\n '2100-01-01 00:00:00+00:00', '2120-01-01 00:00:00+00:00',\n '2140-01-01 00:00:00+00:00', '2160-01-01 00:00:00+00:00',\n '2180-01-01 00:00:00+00:00', '2200-01-01 00:00:00+00:00']\n ],\n [datetime.timedelta(weeks=52 * 200),\n {'base': 20, 'month': 5, 'day': 16},\n ['1980-05-16 00:00:00+00:00', '2000-05-16 00:00:00+00:00',\n '2020-05-16 00:00:00+00:00', '2040-05-16 00:00:00+00:00',\n '2060-05-16 00:00:00+00:00', '2080-05-16 00:00:00+00:00',\n '2100-05-16 00:00:00+00:00', '2120-05-16 00:00:00+00:00',\n '2140-05-16 00:00:00+00:00', '2160-05-16 00:00:00+00:00',\n '2180-05-16 00:00:00+00:00', '2200-05-16 00:00:00+00:00']\n ],\n [datetime.timedelta(weeks=52 * 5),\n {'base': 20, 'month': 9, 'day': 25},\n ['1980-09-25 00:00:00+00:00', '2000-09-25 00:00:00+00:00']\n ],\n )\n\n for delta, arguments, expected in results:\n d2 = d1 + delta\n locator = _create_year_locator(d1, d2, **arguments)\n assert list(map(str, mdates.num2date(locator()))) == expected\n\n\ndef test_DayLocator():\n with pytest.raises(ValueError):\n mdates.DayLocator(interval=-1)\n with pytest.raises(ValueError):\n mdates.DayLocator(interval=-1.5)\n with pytest.raises(ValueError):\n mdates.DayLocator(interval=0)\n with pytest.raises(ValueError):\n mdates.DayLocator(interval=1.3)\n mdates.DayLocator(interval=1.0)\n\n\ndef test_tz_utc():\n dt = datetime.datetime(1970, 1, 1, tzinfo=mdates.UTC)\n assert dt.tzname() == 'UTC'\n\n\n@pytest.mark.parametrize("x, tdelta",\n [(1, datetime.timedelta(days=1)),\n ([1, 1.5], [datetime.timedelta(days=1),\n datetime.timedelta(days=1.5)])])\ndef test_num2timedelta(x, tdelta):\n dt = mdates.num2timedelta(x)\n assert dt == tdelta\n\n\ndef test_datetime64_in_list():\n dt = [np.datetime64('2000-01-01'), np.datetime64('2001-01-01')]\n dn = mdates.date2num(dt)\n # convert fixed values from old to new epoch\n t = (np.array([730120., 730486.]) +\n mdates.date2num(np.datetime64('0000-12-31')))\n np.testing.assert_equal(dn, t)\n\n\ndef test_change_epoch():\n date = np.datetime64('2000-01-01')\n\n # use private method to clear the epoch and allow it to be set...\n mdates._reset_epoch_test_example()\n mdates.get_epoch() # Set default.\n\n with pytest.raises(RuntimeError):\n # this should fail here because there is a sentinel on the epoch\n # if the epoch has been used then it cannot be set.\n mdates.set_epoch('0000-01-01')\n\n mdates._reset_epoch_test_example()\n mdates.set_epoch('1970-01-01')\n dt = (date - np.datetime64('1970-01-01')).astype('datetime64[D]')\n dt = dt.astype('int')\n np.testing.assert_equal(mdates.date2num(date), float(dt))\n\n mdates._reset_epoch_test_example()\n mdates.set_epoch('0000-12-31')\n np.testing.assert_equal(mdates.date2num(date), 730120.0)\n\n mdates._reset_epoch_test_example()\n mdates.set_epoch('1970-01-01T01:00:00')\n np.testing.assert_allclose(mdates.date2num(date), dt - 1./24.)\n mdates._reset_epoch_test_example()\n mdates.set_epoch('1970-01-01T00:00:00')\n np.testing.assert_allclose(\n mdates.date2num(np.datetime64('1970-01-01T12:00:00')),\n 0.5)\n\n\ndef test_warn_notintervals():\n dates = np.arange('2001-01-10', '2001-03-04', dtype='datetime64[D]')\n locator = mdates.AutoDateLocator(interval_multiples=False)\n locator.intervald[3] = [2]\n locator.create_dummy_axis()\n locator.axis.set_view_interval(mdates.date2num(dates[0]),\n mdates.date2num(dates[-1]))\n with pytest.warns(UserWarning, match="AutoDateLocator was unable"):\n locs = locator()\n\n\ndef test_change_converter():\n plt.rcParams['date.converter'] = 'concise'\n dates = np.arange('2020-01-01', '2020-05-01', dtype='datetime64[D]')\n fig, ax = plt.subplots()\n\n ax.plot(dates, np.arange(len(dates)))\n fig.canvas.draw()\n assert ax.get_xticklabels()[0].get_text() == 'Jan'\n assert ax.get_xticklabels()[1].get_text() == '15'\n\n plt.rcParams['date.converter'] = 'auto'\n fig, ax = plt.subplots()\n\n ax.plot(dates, np.arange(len(dates)))\n fig.canvas.draw()\n assert ax.get_xticklabels()[0].get_text() == 'Jan 01 2020'\n assert ax.get_xticklabels()[1].get_text() == 'Jan 15 2020'\n with pytest.raises(ValueError):\n plt.rcParams['date.converter'] = 'boo'\n\n\ndef test_change_interval_multiples():\n plt.rcParams['date.interval_multiples'] = False\n dates = np.arange('2020-01-10', '2020-05-01', dtype='datetime64[D]')\n fig, ax = plt.subplots()\n\n ax.plot(dates, np.arange(len(dates)))\n fig.canvas.draw()\n assert ax.get_xticklabels()[0].get_text() == 'Jan 10 2020'\n assert ax.get_xticklabels()[1].get_text() == 'Jan 24 2020'\n\n plt.rcParams['date.interval_multiples'] = 'True'\n fig, ax = plt.subplots()\n\n ax.plot(dates, np.arange(len(dates)))\n fig.canvas.draw()\n assert ax.get_xticklabels()[0].get_text() == 'Jan 15 2020'\n assert ax.get_xticklabels()[1].get_text() == 'Feb 01 2020'\n\n\ndef test_DateLocator():\n locator = mdates.DateLocator()\n # Test nonsingular\n assert locator.nonsingular(0, np.inf) == (0, 1)\n assert locator.nonsingular(0, 1) == (0, 1)\n assert locator.nonsingular(1, 0) == (0, 1)\n assert locator.nonsingular(0, 0) == (-2, 2)\n locator.create_dummy_axis()\n # default values\n assert locator.datalim_to_dt() == (\n datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc),\n datetime.datetime(1970, 1, 2, 0, 0, tzinfo=datetime.timezone.utc))\n\n # Check default is UTC\n assert locator.tz == mdates.UTC\n tz_str = 'Iceland'\n iceland_tz = dateutil.tz.gettz(tz_str)\n # Check not Iceland\n assert locator.tz != iceland_tz\n # Set it to Iceland\n locator.set_tzinfo('Iceland')\n # Check now it is Iceland\n assert locator.tz == iceland_tz\n locator.create_dummy_axis()\n locator.axis.set_data_interval(*mdates.date2num(["2022-01-10",\n "2022-01-08"]))\n assert locator.datalim_to_dt() == (\n datetime.datetime(2022, 1, 8, 0, 0, tzinfo=iceland_tz),\n datetime.datetime(2022, 1, 10, 0, 0, tzinfo=iceland_tz))\n\n # Set rcParam\n plt.rcParams['timezone'] = tz_str\n\n # Create a new one in a similar way\n locator = mdates.DateLocator()\n # Check now it is Iceland\n assert locator.tz == iceland_tz\n\n # Test invalid tz values\n with pytest.raises(ValueError, match="Aiceland is not a valid timezone"):\n mdates.DateLocator(tz="Aiceland")\n with pytest.raises(TypeError,\n match="tz must be string or tzinfo subclass."):\n mdates.DateLocator(tz=1)\n\n\ndef test_datestr2num():\n assert mdates.datestr2num('2022-01-10') == 19002.0\n dt = datetime.date(year=2022, month=1, day=10)\n assert mdates.datestr2num('2022-01', default=dt) == 19002.0\n assert np.all(mdates.datestr2num(\n ['2022-01', '2022-02'], default=dt\n ) == np.array([19002., 19033.]))\n assert mdates.datestr2num([]).size == 0\n assert mdates.datestr2num([], datetime.date(year=2022,\n month=1, day=10)).size == 0\n\n\n@pytest.mark.parametrize('kwarg',\n ('formats', 'zero_formats', 'offset_formats'))\ndef test_concise_formatter_exceptions(kwarg):\n locator = mdates.AutoDateLocator()\n kwargs = {kwarg: ['', '%Y']}\n match = f"{kwarg} argument must be a list"\n with pytest.raises(ValueError, match=match):\n mdates.ConciseDateFormatter(locator, **kwargs)\n\n\ndef test_concise_formatter_call():\n locator = mdates.AutoDateLocator()\n formatter = mdates.ConciseDateFormatter(locator)\n assert formatter(19002.0) == '2022'\n assert formatter.format_data_short(19002.0) == '2022-01-10 00:00:00'\n\n\ndef test_datetime_masked():\n # make sure that all-masked data falls back to the viewlim\n # set in convert.axisinfo....\n x = np.array([datetime.datetime(2017, 1, n) for n in range(1, 6)])\n y = np.array([1, 2, 3, 4, 5])\n m = np.ma.masked_greater(y, 0)\n\n fig, ax = plt.subplots()\n ax.plot(x, m)\n assert ax.get_xlim() == (0, 1)\n\n\n@pytest.mark.parametrize('val', (-1000000, 10000000))\ndef test_num2date_error(val):\n with pytest.raises(ValueError, match=f"Date ordinal {val} converts"):\n mdates.num2date(val)\n\n\ndef test_num2date_roundoff():\n assert mdates.num2date(100000.0000578702) == datetime.datetime(\n 2243, 10, 17, 0, 0, 4, 999980, tzinfo=datetime.timezone.utc)\n # Slightly larger, steps of 20 microseconds\n assert mdates.num2date(100000.0000578703) == datetime.datetime(\n 2243, 10, 17, 0, 0, 5, tzinfo=datetime.timezone.utc)\n\n\ndef test_DateFormatter_settz():\n time = mdates.date2num(datetime.datetime(2011, 1, 1, 0, 0,\n tzinfo=mdates.UTC))\n formatter = mdates.DateFormatter('%Y-%b-%d %H:%M')\n # Default UTC\n assert formatter(time) == '2011-Jan-01 00:00'\n\n # Set tzinfo\n formatter.set_tzinfo('Pacific/Kiritimati')\n assert formatter(time) == '2011-Jan-01 14:00'\n | .venv\Lib\site-packages\matplotlib\tests\test_dates.py | test_dates.py | Python | 56,533 | 0.75 | 0.095541 | 0.06914 | react-lib | 759 | 2024-04-03T22:25:06.872291 | BSD-3-Clause | true | a5249533ab0e084dceaec92d96acc03e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.