diff --git a/.gitattributes b/.gitattributes index 198e58c7c9a05a4ac4451c95208e1cf927b37c5a..46c5e5d6ee93435193011ac7b7b7a09c5cb819fc 100644 --- a/.gitattributes +++ b/.gitattributes @@ -665,3 +665,4 @@ llava_video/lib/python3.10/site-packages/scipy/ndimage/_nd_image.cpython-310-x86 llava_video/lib/python3.10/site-packages/scipy/ndimage/_ni_label.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text llava_video/lib/python3.10/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text llava_video/lib/python3.10/site-packages/fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..96837bd9ed70a5a818227f2e1eb0db263dcd10ac --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2021-2024, ContourPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fa2550faeadd4cce0f28323321c2c212032f4481 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA @@ -0,0 +1,93 @@ +Metadata-Version: 2.1 +Name: contourpy +Version: 1.3.1 +Summary: Python library for calculating contours of 2D quadrilateral grids +Author-Email: Ian Thomas +License: BSD 3-Clause License + + Copyright (c) 2021-2024, ContourPy Developers. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Visualization +Project-URL: Homepage, https://github.com/contourpy/contourpy +Project-URL: Changelog, https://contourpy.readthedocs.io/en/latest/changelog.html +Project-URL: Documentation, https://contourpy.readthedocs.io +Project-URL: Repository, https://github.com/contourpy/contourpy +Requires-Python: >=3.10 +Requires-Dist: numpy>=1.23 +Provides-Extra: docs +Requires-Dist: furo; extra == "docs" +Requires-Dist: sphinx>=7.2; extra == "docs" +Requires-Dist: sphinx-copybutton; extra == "docs" +Provides-Extra: bokeh +Requires-Dist: bokeh; extra == "bokeh" +Requires-Dist: selenium; extra == "bokeh" +Provides-Extra: mypy +Requires-Dist: contourpy[bokeh,docs]; extra == "mypy" +Requires-Dist: docutils-stubs; extra == "mypy" +Requires-Dist: mypy==1.11.1; extra == "mypy" +Requires-Dist: types-Pillow; extra == "mypy" +Provides-Extra: test +Requires-Dist: contourpy[test-no-images]; extra == "test" +Requires-Dist: matplotlib; extra == "test" +Requires-Dist: Pillow; extra == "test" +Provides-Extra: test-no-images +Requires-Dist: pytest; extra == "test-no-images" +Requires-Dist: pytest-cov; extra == "test-no-images" +Requires-Dist: pytest-rerunfailures; extra == "test-no-images" +Requires-Dist: pytest-xdist; extra == "test-no-images" +Requires-Dist: wurlitzer; extra == "test-no-images" +Description-Content-Type: text/markdown + +ContourPy + +ContourPy is a Python library for calculating contours of 2D quadrilateral grids. It is written in C++11 and wrapped using pybind11. + +It contains the 2005 and 2014 algorithms used in Matplotlib as well as a newer algorithm that includes more features and is available in both serial and multithreaded versions. It provides an easy way for Python libraries to use contouring algorithms without having to include Matplotlib as a dependency. + + * **Documentation**: https://contourpy.readthedocs.io + * **Source code**: https://github.com/contourpy/contourpy + +| | | +| --- | --- | +| Latest release | [![PyPI version](https://img.shields.io/pypi/v/contourpy.svg?label=pypi&color=fdae61)](https://pypi.python.org/pypi/contourpy) [![conda-forge version](https://img.shields.io/conda/v/conda-forge/contourpy.svg?label=conda-forge&color=a6d96a)](https://anaconda.org/conda-forge/contourpy) | +| Downloads | [![PyPi downloads](https://img.shields.io/pypi/dm/contourpy?label=pypi&style=flat&color=fdae61)](https://pepy.tech/project/contourpy) | +| Python version | [![Platforms](https://img.shields.io/pypi/pyversions/contourpy?color=fdae61)](https://pypi.org/project/contourpy/) | +| Coverage | [![Codecov](https://img.shields.io/codecov/c/gh/contourpy/contourpy?color=fdae61&label=codecov)](https://app.codecov.io/gh/contourpy/contourpy) | diff --git a/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f4bc9005ba1d6f860f270a9cf25a1bdee9513d7e --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD @@ -0,0 +1,43 @@ +contourpy-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +contourpy-1.3.1.dist-info/LICENSE,sha256=x9ChU7_6oQQERGPrxjN5PUUXIu_TE4tf_SUntA8VBaI,1534 +contourpy-1.3.1.dist-info/METADATA,sha256=LQNae4q9MVNwpfb0FlnTCTe2tkw22GiKEJjpks9n7jk,5423 +contourpy-1.3.1.dist-info/RECORD,, +contourpy-1.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +contourpy-1.3.1.dist-info/WHEEL,sha256=sZM_NeUMz2G4fDenMf11eikcCxcLaQWiYRmjwQBavQs,137 +contourpy/__init__.py,sha256=Vi2YbtUhM9VxYPY3PBvxfu0xZYr6fBysl5gQPJEo88k,11831 +contourpy/__pycache__/__init__.cpython-310.pyc,, +contourpy/__pycache__/_version.cpython-310.pyc,, +contourpy/__pycache__/array.cpython-310.pyc,, +contourpy/__pycache__/chunk.cpython-310.pyc,, +contourpy/__pycache__/convert.cpython-310.pyc,, +contourpy/__pycache__/dechunk.cpython-310.pyc,, +contourpy/__pycache__/enum_util.cpython-310.pyc,, +contourpy/__pycache__/typecheck.cpython-310.pyc,, +contourpy/__pycache__/types.cpython-310.pyc,, +contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so,sha256=H8GWcYv0tePHkvGU0HhmBO_d_Chj3Bs_6QYgLRKjIMI,854312 +contourpy/_contourpy.pyi,sha256=fvtccxkiZwGb6qYag7Fp4E8bsFmAIjAmobf8LNxqfgc,7122 +contourpy/_version.py,sha256=-ypEJktJToAL9by62JJKWEzDo_KPCQtmE5kwFgX24z4,22 +contourpy/array.py,sha256=4WwLuiZe30rizn_raymmY13OzE6hlCsDOO8kuVFOP18,8979 +contourpy/chunk.py,sha256=8njDQqlpuD22RjaaCyA75FXQsSQDY5hZGJSrxFpvGGU,3279 +contourpy/convert.py,sha256=mhyn7prEoWCnf0igaH-VqDwlk-CegFsZ4qOy2LL-hpU,26154 +contourpy/dechunk.py,sha256=EgFL6hw5H54ccuof4tJ2ehdnktT7trgZjiZqppsH8QI,7756 +contourpy/enum_util.py,sha256=o8MItJRs08oqzwPP3IwC75BBAY9Qq95saIzjkXBXwqA,1519 +contourpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +contourpy/typecheck.py,sha256=t1nvvCuKMYva1Zx4fc30EpdKFcO0Enz3n_UFfXBsq9o,10747 +contourpy/types.py,sha256=2K4T5tJpMIjYrkkg1Lqh3C2ZKlnOhnMtYmtwz92l_y8,247 +contourpy/util/__init__.py,sha256=eVhJ_crOHL7nkG4Kb0dOo7NL4WHMy_Px665aAN_3d-8,118 +contourpy/util/__pycache__/__init__.cpython-310.pyc,, +contourpy/util/__pycache__/_build_config.cpython-310.pyc,, +contourpy/util/__pycache__/bokeh_renderer.cpython-310.pyc,, +contourpy/util/__pycache__/bokeh_util.cpython-310.pyc,, +contourpy/util/__pycache__/data.cpython-310.pyc,, +contourpy/util/__pycache__/mpl_renderer.cpython-310.pyc,, +contourpy/util/__pycache__/mpl_util.cpython-310.pyc,, +contourpy/util/__pycache__/renderer.cpython-310.pyc,, +contourpy/util/_build_config.py,sha256=jzJKkuBQpyjnX1U_eltbhIAN_i6fbzTAQXMAP1YTlG0,1848 +contourpy/util/bokeh_renderer.py,sha256=wNGBghEVA4x11wrSerb3dBbdRxX6E8kuoqlaKPoHTQ8,13769 +contourpy/util/bokeh_util.py,sha256=wc-S3ewBUYWyIkEv9jkhFySIergjLQl4Z0UEVnE0HhA,2804 +contourpy/util/data.py,sha256=-7SSGMLX_gN-1H2JzpNSEB_EcEF_uMtYdOo_ePRIcg8,2586 +contourpy/util/mpl_renderer.py,sha256=avUxO7_MQRDQM84X5PZ9GbNtGxG0EXPSVQYV00xQMvQ,20089 +contourpy/util/mpl_util.py,sha256=0Jz5f-aA9XMWlpO2pDnHbkVgxIiw4SY_ysxf_gACWEo,3452 +contourpy/util/renderer.py,sha256=8CBHzPmVsFPfqsWxqrxGBhqFpJhVeFHFeDzVXAgT8Fc,5118 diff --git a/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4e4c38ae320920b8f083b87f408214cdecd350d2 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/axis.py b/llava_video/lib/python3.10/site-packages/matplotlib/axis.py new file mode 100644 index 0000000000000000000000000000000000000000..56eeb0e4169b2c48a0e37fd1470d7e9e00539196 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/matplotlib/axis.py @@ -0,0 +1,2830 @@ +""" +Classes for the ticks and x- and y-axis. +""" + +import datetime +import functools +import logging +from numbers import Real +import warnings + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +import matplotlib.artist as martist +import matplotlib.colors as mcolors +import matplotlib.lines as mlines +import matplotlib.scale as mscale +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms +import matplotlib.units as munits + +_log = logging.getLogger(__name__) + +GRIDLINE_INTERPOLATION_STEPS = 180 + +# This list is being used for compatibility with Axes.grid, which +# allows all Line2D kwargs. +_line_inspector = martist.ArtistInspector(mlines.Line2D) +_line_param_names = _line_inspector.get_setters() +_line_param_aliases = [next(iter(d)) for d in _line_inspector.aliasd.values()] +_gridline_param_names = ['grid_' + name + for name in _line_param_names + _line_param_aliases] + + +class Tick(martist.Artist): + """ + Abstract base class for the axis ticks, grid lines and labels. + + Ticks mark a position on an Axis. They contain two lines as markers and + two labels; one each for the bottom and top positions (in case of an + `.XAxis`) or for the left and right positions (in case of a `.YAxis`). + + Attributes + ---------- + tick1line : `~matplotlib.lines.Line2D` + The left/bottom tick marker. + tick2line : `~matplotlib.lines.Line2D` + The right/top tick marker. + gridline : `~matplotlib.lines.Line2D` + The grid line associated with the label position. + label1 : `~matplotlib.text.Text` + The left/bottom tick label. + label2 : `~matplotlib.text.Text` + The right/top tick label. + + """ + def __init__( + self, axes, loc, *, + size=None, # points + width=None, + color=None, + tickdir=None, + pad=None, + labelsize=None, + labelcolor=None, + labelfontfamily=None, + zorder=None, + gridOn=None, # defaults to axes.grid depending on axes.grid.which + tick1On=True, + tick2On=True, + label1On=True, + label2On=False, + major=True, + labelrotation=0, + grid_color=None, + grid_linestyle=None, + grid_linewidth=None, + grid_alpha=None, + **kwargs, # Other Line2D kwargs applied to gridlines. + ): + """ + bbox is the Bound2D bounding box in display coords of the Axes + loc is the tick location in data coords + size is the tick size in points + """ + super().__init__() + + if gridOn is None: + which = mpl.rcParams['axes.grid.which'] + if major and (which in ('both', 'major')): + gridOn = mpl.rcParams['axes.grid'] + elif (not major) and (which in ('both', 'minor')): + gridOn = mpl.rcParams['axes.grid'] + else: + gridOn = False + + self.set_figure(axes.get_figure(root=False)) + self.axes = axes + + self._loc = loc + self._major = major + + name = self.__name__ + major_minor = "major" if major else "minor" + + if size is None: + size = mpl.rcParams[f"{name}.{major_minor}.size"] + self._size = size + + if width is None: + width = mpl.rcParams[f"{name}.{major_minor}.width"] + self._width = width + + if color is None: + color = mpl.rcParams[f"{name}.color"] + + if pad is None: + pad = mpl.rcParams[f"{name}.{major_minor}.pad"] + self._base_pad = pad + + if labelcolor is None: + labelcolor = mpl.rcParams[f"{name}.labelcolor"] + + if cbook._str_equal(labelcolor, 'inherit'): + # inherit from tick color + labelcolor = mpl.rcParams[f"{name}.color"] + + if labelsize is None: + labelsize = mpl.rcParams[f"{name}.labelsize"] + + self._set_labelrotation(labelrotation) + + if zorder is None: + if major: + zorder = mlines.Line2D.zorder + 0.01 + else: + zorder = mlines.Line2D.zorder + self._zorder = zorder + + grid_color = mpl._val_or_rc(grid_color, "grid.color") + grid_linestyle = mpl._val_or_rc(grid_linestyle, "grid.linestyle") + grid_linewidth = mpl._val_or_rc(grid_linewidth, "grid.linewidth") + if grid_alpha is None and not mcolors._has_alpha_channel(grid_color): + # alpha precedence: kwarg > color alpha > rcParams['grid.alpha'] + # Note: only resolve to rcParams if the color does not have alpha + # otherwise `grid(color=(1, 1, 1, 0.5))` would work like + # grid(color=(1, 1, 1, 0.5), alpha=rcParams['grid.alpha']) + # so the that the rcParams default would override color alpha. + grid_alpha = mpl.rcParams["grid.alpha"] + grid_kw = {k[5:]: v for k, v in kwargs.items()} + + self.tick1line = mlines.Line2D( + [], [], + color=color, linestyle="none", zorder=zorder, visible=tick1On, + markeredgecolor=color, markersize=size, markeredgewidth=width, + ) + self.tick2line = mlines.Line2D( + [], [], + color=color, linestyle="none", zorder=zorder, visible=tick2On, + markeredgecolor=color, markersize=size, markeredgewidth=width, + ) + self.gridline = mlines.Line2D( + [], [], + color=grid_color, alpha=grid_alpha, visible=gridOn, + linestyle=grid_linestyle, linewidth=grid_linewidth, marker="", + **grid_kw, + ) + self.gridline.get_path()._interpolation_steps = \ + GRIDLINE_INTERPOLATION_STEPS + self.label1 = mtext.Text( + np.nan, np.nan, + fontsize=labelsize, color=labelcolor, visible=label1On, + fontfamily=labelfontfamily, rotation=self._labelrotation[1]) + self.label2 = mtext.Text( + np.nan, np.nan, + fontsize=labelsize, color=labelcolor, visible=label2On, + fontfamily=labelfontfamily, rotation=self._labelrotation[1]) + + self._apply_tickdir(tickdir) + + for artist in [self.tick1line, self.tick2line, self.gridline, + self.label1, self.label2]: + self._set_artist_props(artist) + + self.update_position(loc) + + def _set_labelrotation(self, labelrotation): + if isinstance(labelrotation, str): + mode = labelrotation + angle = 0 + elif isinstance(labelrotation, (tuple, list)): + mode, angle = labelrotation + else: + mode = 'default' + angle = labelrotation + _api.check_in_list(['auto', 'default'], labelrotation=mode) + self._labelrotation = (mode, angle) + + @property + def _pad(self): + return self._base_pad + self.get_tick_padding() + + def _apply_tickdir(self, tickdir): + """Set tick direction. Valid values are 'out', 'in', 'inout'.""" + # This method is responsible for verifying input and, in subclasses, for setting + # the tick{1,2}line markers. From the user perspective this should always be + # called through _apply_params, which further updates ticklabel positions using + # the new pads. + if tickdir is None: + tickdir = mpl.rcParams[f'{self.__name__}.direction'] + else: + _api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir) + self._tickdir = tickdir + + def get_tickdir(self): + return self._tickdir + + def get_tick_padding(self): + """Get the length of the tick outside of the Axes.""" + padding = { + 'in': 0.0, + 'inout': 0.5, + 'out': 1.0 + } + return self._size * padding[self._tickdir] + + def get_children(self): + children = [self.tick1line, self.tick2line, + self.gridline, self.label1, self.label2] + return children + + def set_clip_path(self, path, transform=None): + # docstring inherited + super().set_clip_path(path, transform) + self.gridline.set_clip_path(path, transform) + self.stale = True + + def contains(self, mouseevent): + """ + Test whether the mouse event occurred in the Tick marks. + + This function always returns false. It is more useful to test if the + axis as a whole contains the mouse rather than the set of tick marks. + """ + return False, {} + + def set_pad(self, val): + """ + Set the tick label pad in points + + Parameters + ---------- + val : float + """ + self._apply_params(pad=val) + self.stale = True + + def get_pad(self): + """Get the value of the tick label pad in points.""" + return self._base_pad + + def get_loc(self): + """Return the tick location (data coords) as a scalar.""" + return self._loc + + @martist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + self.stale = False + return + renderer.open_group(self.__name__, gid=self.get_gid()) + for artist in [self.gridline, self.tick1line, self.tick2line, + self.label1, self.label2]: + artist.draw(renderer) + renderer.close_group(self.__name__) + self.stale = False + + def set_url(self, url): + """ + Set the url of label1 and label2. + + Parameters + ---------- + url : str + """ + super().set_url(url) + self.label1.set_url(url) + self.label2.set_url(url) + self.stale = True + + def _set_artist_props(self, a): + a.set_figure(self.get_figure(root=False)) + + def get_view_interval(self): + """ + Return the view limits ``(min, max)`` of the axis the tick belongs to. + """ + raise NotImplementedError('Derived must override') + + def _apply_params(self, **kwargs): + for name, target in [("gridOn", self.gridline), + ("tick1On", self.tick1line), + ("tick2On", self.tick2line), + ("label1On", self.label1), + ("label2On", self.label2)]: + if name in kwargs: + target.set_visible(kwargs.pop(name)) + if any(k in kwargs for k in ['size', 'width', 'pad', 'tickdir']): + self._size = kwargs.pop('size', self._size) + # Width could be handled outside this block, but it is + # convenient to leave it here. + self._width = kwargs.pop('width', self._width) + self._base_pad = kwargs.pop('pad', self._base_pad) + # _apply_tickdir uses _size and _base_pad to make _pad, and also + # sets the ticklines markers. + self._apply_tickdir(kwargs.pop('tickdir', self._tickdir)) + for line in (self.tick1line, self.tick2line): + line.set_markersize(self._size) + line.set_markeredgewidth(self._width) + # _get_text1_transform uses _pad from _apply_tickdir. + trans = self._get_text1_transform()[0] + self.label1.set_transform(trans) + trans = self._get_text2_transform()[0] + self.label2.set_transform(trans) + tick_kw = {k: v for k, v in kwargs.items() if k in ['color', 'zorder']} + if 'color' in kwargs: + tick_kw['markeredgecolor'] = kwargs['color'] + self.tick1line.set(**tick_kw) + self.tick2line.set(**tick_kw) + for k, v in tick_kw.items(): + setattr(self, '_' + k, v) + + if 'labelrotation' in kwargs: + self._set_labelrotation(kwargs.pop('labelrotation')) + self.label1.set(rotation=self._labelrotation[1]) + self.label2.set(rotation=self._labelrotation[1]) + + label_kw = {k[5:]: v for k, v in kwargs.items() + if k in ['labelsize', 'labelcolor', 'labelfontfamily']} + self.label1.set(**label_kw) + self.label2.set(**label_kw) + + grid_kw = {k[5:]: v for k, v in kwargs.items() + if k in _gridline_param_names} + self.gridline.set(**grid_kw) + + def update_position(self, loc): + """Set the location of tick in data coords with scalar *loc*.""" + raise NotImplementedError('Derived must override') + + def _get_text1_transform(self): + raise NotImplementedError('Derived must override') + + def _get_text2_transform(self): + raise NotImplementedError('Derived must override') + + +class XTick(Tick): + """ + Contains all the Artists needed to make an x tick - the tick line, + the label text and the grid line + """ + __name__ = 'xtick' + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # x in data coords, y in axes coords + ax = self.axes + self.tick1line.set( + data=([0], [0]), transform=ax.get_xaxis_transform("tick1")) + self.tick2line.set( + data=([0], [1]), transform=ax.get_xaxis_transform("tick2")) + self.gridline.set( + data=([0, 0], [0, 1]), transform=ax.get_xaxis_transform("grid")) + # the y loc is 3 points below the min of y axis + trans, va, ha = self._get_text1_transform() + self.label1.set( + x=0, y=0, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + trans, va, ha = self._get_text2_transform() + self.label2.set( + x=0, y=1, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + + def _get_text1_transform(self): + return self.axes.get_xaxis_text1_transform(self._pad) + + def _get_text2_transform(self): + return self.axes.get_xaxis_text2_transform(self._pad) + + def _apply_tickdir(self, tickdir): + # docstring inherited + super()._apply_tickdir(tickdir) + mark1, mark2 = { + 'out': (mlines.TICKDOWN, mlines.TICKUP), + 'in': (mlines.TICKUP, mlines.TICKDOWN), + 'inout': ('|', '|'), + }[self._tickdir] + self.tick1line.set_marker(mark1) + self.tick2line.set_marker(mark2) + + def update_position(self, loc): + """Set the location of tick in data coords with scalar *loc*.""" + self.tick1line.set_xdata((loc,)) + self.tick2line.set_xdata((loc,)) + self.gridline.set_xdata((loc,)) + self.label1.set_x(loc) + self.label2.set_x(loc) + self._loc = loc + self.stale = True + + def get_view_interval(self): + # docstring inherited + return self.axes.viewLim.intervalx + + +class YTick(Tick): + """ + Contains all the Artists needed to make a Y tick - the tick line, + the label text and the grid line + """ + __name__ = 'ytick' + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # x in axes coords, y in data coords + ax = self.axes + self.tick1line.set( + data=([0], [0]), transform=ax.get_yaxis_transform("tick1")) + self.tick2line.set( + data=([1], [0]), transform=ax.get_yaxis_transform("tick2")) + self.gridline.set( + data=([0, 1], [0, 0]), transform=ax.get_yaxis_transform("grid")) + # the y loc is 3 points below the min of y axis + trans, va, ha = self._get_text1_transform() + self.label1.set( + x=0, y=0, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + trans, va, ha = self._get_text2_transform() + self.label2.set( + x=1, y=0, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + + def _get_text1_transform(self): + return self.axes.get_yaxis_text1_transform(self._pad) + + def _get_text2_transform(self): + return self.axes.get_yaxis_text2_transform(self._pad) + + def _apply_tickdir(self, tickdir): + # docstring inherited + super()._apply_tickdir(tickdir) + mark1, mark2 = { + 'out': (mlines.TICKLEFT, mlines.TICKRIGHT), + 'in': (mlines.TICKRIGHT, mlines.TICKLEFT), + 'inout': ('_', '_'), + }[self._tickdir] + self.tick1line.set_marker(mark1) + self.tick2line.set_marker(mark2) + + def update_position(self, loc): + """Set the location of tick in data coords with scalar *loc*.""" + self.tick1line.set_ydata((loc,)) + self.tick2line.set_ydata((loc,)) + self.gridline.set_ydata((loc,)) + self.label1.set_y(loc) + self.label2.set_y(loc) + self._loc = loc + self.stale = True + + def get_view_interval(self): + # docstring inherited + return self.axes.viewLim.intervaly + + +class Ticker: + """ + A container for the objects defining tick position and format. + + Attributes + ---------- + locator : `~matplotlib.ticker.Locator` subclass + Determines the positions of the ticks. + formatter : `~matplotlib.ticker.Formatter` subclass + Determines the format of the tick labels. + """ + + def __init__(self): + self._locator = None + self._formatter = None + self._locator_is_default = True + self._formatter_is_default = True + + @property + def locator(self): + return self._locator + + @locator.setter + def locator(self, locator): + if not isinstance(locator, mticker.Locator): + raise TypeError('locator must be a subclass of ' + 'matplotlib.ticker.Locator') + self._locator = locator + + @property + def formatter(self): + return self._formatter + + @formatter.setter + def formatter(self, formatter): + if not isinstance(formatter, mticker.Formatter): + raise TypeError('formatter must be a subclass of ' + 'matplotlib.ticker.Formatter') + self._formatter = formatter + + +class _LazyTickList: + """ + A descriptor for lazy instantiation of tick lists. + + See comment above definition of the ``majorTicks`` and ``minorTicks`` + attributes. + """ + + def __init__(self, major): + self._major = major + + def __get__(self, instance, owner): + if instance is None: + return self + else: + # instance._get_tick() can itself try to access the majorTicks + # attribute (e.g. in certain projection classes which override + # e.g. get_xaxis_text1_transform). In order to avoid infinite + # recursion, first set the majorTicks on the instance temporarily + # to an empty lis. Then create the tick; note that _get_tick() + # may call reset_ticks(). Therefore, the final tick list is + # created and assigned afterwards. + if self._major: + instance.majorTicks = [] + tick = instance._get_tick(major=True) + instance.majorTicks = [tick] + return instance.majorTicks + else: + instance.minorTicks = [] + tick = instance._get_tick(major=False) + instance.minorTicks = [tick] + return instance.minorTicks + + +class Axis(martist.Artist): + """ + Base class for `.XAxis` and `.YAxis`. + + Attributes + ---------- + isDefault_label : bool + + axes : `~matplotlib.axes.Axes` + The `~.axes.Axes` to which the Axis belongs. + major : `~matplotlib.axis.Ticker` + Determines the major tick positions and their label format. + minor : `~matplotlib.axis.Ticker` + Determines the minor tick positions and their label format. + callbacks : `~matplotlib.cbook.CallbackRegistry` + + label : `~matplotlib.text.Text` + The axis label. + labelpad : float + The distance between the axis label and the tick labels. + Defaults to :rc:`axes.labelpad`. + offsetText : `~matplotlib.text.Text` + A `.Text` object containing the data offset of the ticks (if any). + pickradius : float + The acceptance radius for containment tests. See also `.Axis.contains`. + majorTicks : list of `.Tick` + The major ticks. + + .. warning:: + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that changes to individual ticks will not + survive if you work on the figure further (including also + panning/zooming on a displayed figure). + + Working on the individual ticks is a method of last resort. + Use `.set_tick_params` instead if possible. + + minorTicks : list of `.Tick` + The minor ticks. + """ + OFFSETTEXTPAD = 3 + # The class used in _get_tick() to create tick instances. Must either be + # overwritten in subclasses, or subclasses must reimplement _get_tick(). + _tick_class = None + converter = _api.deprecate_privatize_attribute( + "3.10", + alternative="get_converter and set_converter methods" + ) + + def __str__(self): + return "{}({},{})".format( + type(self).__name__, *self.axes.transAxes.transform((0, 0))) + + def __init__(self, axes, *, pickradius=15, clear=True): + """ + Parameters + ---------- + axes : `~matplotlib.axes.Axes` + The `~.axes.Axes` to which the created Axis belongs. + pickradius : float + The acceptance radius for containment tests. See also + `.Axis.contains`. + clear : bool, default: True + Whether to clear the Axis on creation. This is not required, e.g., when + creating an Axis as part of an Axes, as ``Axes.clear`` will call + ``Axis.clear``. + .. versionadded:: 3.8 + """ + super().__init__() + self._remove_overlapping_locs = True + + self.set_figure(axes.get_figure(root=False)) + + self.isDefault_label = True + + self.axes = axes + self.major = Ticker() + self.minor = Ticker() + self.callbacks = cbook.CallbackRegistry(signals=["units"]) + + self._autolabelpos = True + + self.label = mtext.Text( + np.nan, np.nan, + fontsize=mpl.rcParams['axes.labelsize'], + fontweight=mpl.rcParams['axes.labelweight'], + color=mpl.rcParams['axes.labelcolor'], + ) #: The `.Text` object of the axis label. + + self._set_artist_props(self.label) + self.offsetText = mtext.Text(np.nan, np.nan) + self._set_artist_props(self.offsetText) + + self.labelpad = mpl.rcParams['axes.labelpad'] + + self.pickradius = pickradius + + # Initialize here for testing; later add API + self._major_tick_kw = dict() + self._minor_tick_kw = dict() + + if clear: + self.clear() + else: + self._converter = None + self._converter_is_explicit = False + self.units = None + + self._autoscale_on = True + + @property + def isDefault_majloc(self): + return self.major._locator_is_default + + @isDefault_majloc.setter + def isDefault_majloc(self, value): + self.major._locator_is_default = value + + @property + def isDefault_majfmt(self): + return self.major._formatter_is_default + + @isDefault_majfmt.setter + def isDefault_majfmt(self, value): + self.major._formatter_is_default = value + + @property + def isDefault_minloc(self): + return self.minor._locator_is_default + + @isDefault_minloc.setter + def isDefault_minloc(self, value): + self.minor._locator_is_default = value + + @property + def isDefault_minfmt(self): + return self.minor._formatter_is_default + + @isDefault_minfmt.setter + def isDefault_minfmt(self, value): + self.minor._formatter_is_default = value + + def _get_shared_axes(self): + """Return Grouper of shared Axes for current axis.""" + return self.axes._shared_axes[ + self._get_axis_name()].get_siblings(self.axes) + + def _get_shared_axis(self): + """Return list of shared axis for current axis.""" + name = self._get_axis_name() + return [ax._axis_map[name] for ax in self._get_shared_axes()] + + def _get_axis_name(self): + """Return the axis name.""" + return next(name for name, axis in self.axes._axis_map.items() + if axis is self) + + # During initialization, Axis objects often create ticks that are later + # unused; this turns out to be a very slow step. Instead, use a custom + # descriptor to make the tick lists lazy and instantiate them as needed. + majorTicks = _LazyTickList(major=True) + minorTicks = _LazyTickList(major=False) + + def get_remove_overlapping_locs(self): + return self._remove_overlapping_locs + + def set_remove_overlapping_locs(self, val): + self._remove_overlapping_locs = bool(val) + + remove_overlapping_locs = property( + get_remove_overlapping_locs, set_remove_overlapping_locs, + doc=('If minor ticker locations that overlap with major ' + 'ticker locations should be trimmed.')) + + def set_label_coords(self, x, y, transform=None): + """ + Set the coordinates of the label. + + By default, the x coordinate of the y label and the y coordinate of the + x label are determined by the tick label bounding boxes, but this can + lead to poor alignment of multiple labels if there are multiple Axes. + + You can also specify the coordinate system of the label with the + transform. If None, the default coordinate system will be the axes + coordinate system: (0, 0) is bottom left, (0.5, 0.5) is center, etc. + """ + self._autolabelpos = False + if transform is None: + transform = self.axes.transAxes + + self.label.set_transform(transform) + self.label.set_position((x, y)) + self.stale = True + + def get_transform(self): + """Return the transform used in the Axis' scale""" + return self._scale.get_transform() + + def get_scale(self): + """Return this Axis' scale (as a str).""" + return self._scale.name + + def _set_scale(self, value, **kwargs): + if not isinstance(value, mscale.ScaleBase): + self._scale = mscale.scale_factory(value, self, **kwargs) + else: + self._scale = value + self._scale.set_default_locators_and_formatters(self) + + self.isDefault_majloc = True + self.isDefault_minloc = True + self.isDefault_majfmt = True + self.isDefault_minfmt = True + + # This method is directly wrapped by Axes.set_{x,y}scale. + def _set_axes_scale(self, value, **kwargs): + """ + Set this Axis' scale. + + Parameters + ---------- + value : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase` + The axis scale type to apply. + + **kwargs + Different keyword arguments are accepted, depending on the scale. + See the respective class keyword arguments: + + - `matplotlib.scale.LinearScale` + - `matplotlib.scale.LogScale` + - `matplotlib.scale.SymmetricalLogScale` + - `matplotlib.scale.LogitScale` + - `matplotlib.scale.FuncScale` + - `matplotlib.scale.AsinhScale` + + Notes + ----- + By default, Matplotlib supports the above-mentioned scales. + Additionally, custom scales may be registered using + `matplotlib.scale.register_scale`. These scales can then also + be used here. + """ + name = self._get_axis_name() + old_default_lims = (self.get_major_locator() + .nonsingular(-np.inf, np.inf)) + for ax in self._get_shared_axes(): + ax._axis_map[name]._set_scale(value, **kwargs) + ax._update_transScale() + ax.stale = True + new_default_lims = (self.get_major_locator() + .nonsingular(-np.inf, np.inf)) + if old_default_lims != new_default_lims: + # Force autoscaling now, to take advantage of the scale locator's + # nonsingular() before it possibly gets swapped out by the user. + self.axes.autoscale_view( + **{f"scale{k}": k == name for k in self.axes._axis_names}) + + def limit_range_for_scale(self, vmin, vmax): + """ + Return the range *vmin*, *vmax*, restricted to the domain supported by the + current scale. + """ + return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos()) + + def _get_autoscale_on(self): + """Return whether this Axis is autoscaled.""" + return self._autoscale_on + + def _set_autoscale_on(self, b): + """ + Set whether this Axis is autoscaled when drawing or by `.Axes.autoscale_view`. + + If b is None, then the value is not changed. + + Parameters + ---------- + b : bool + """ + if b is not None: + self._autoscale_on = b + + def get_children(self): + return [self.label, self.offsetText, + *self.get_major_ticks(), *self.get_minor_ticks()] + + def _reset_major_tick_kw(self): + self._major_tick_kw.clear() + self._major_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'major')) + + def _reset_minor_tick_kw(self): + self._minor_tick_kw.clear() + self._minor_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'minor')) + + def clear(self): + """ + Clear the axis. + + This resets axis properties to their default values: + + - the label + - the scale + - locators, formatters and ticks + - major and minor grid + - units + - registered callbacks + """ + self.label._reset_visual_defaults() + # The above resets the label formatting using text rcParams, + # so we then update the formatting using axes rcParams + self.label.set_color(mpl.rcParams['axes.labelcolor']) + self.label.set_fontsize(mpl.rcParams['axes.labelsize']) + self.label.set_fontweight(mpl.rcParams['axes.labelweight']) + self.offsetText._reset_visual_defaults() + self.labelpad = mpl.rcParams['axes.labelpad'] + + self._init() + + self._set_scale('linear') + + # Clear the callback registry for this axis, or it may "leak" + self.callbacks = cbook.CallbackRegistry(signals=["units"]) + + # whether the grids are on + self._major_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'major')) + self._minor_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'minor')) + self.reset_ticks() + + self._converter = None + self._converter_is_explicit = False + self.units = None + self.stale = True + + def reset_ticks(self): + """ + Re-initialize the major and minor Tick lists. + + Each list starts with a single fresh Tick. + """ + # Restore the lazy tick lists. + try: + del self.majorTicks + except AttributeError: + pass + try: + del self.minorTicks + except AttributeError: + pass + try: + self.set_clip_path(self.axes.patch) + except AttributeError: + pass + + def minorticks_on(self): + """ + Display default minor ticks on the Axis, depending on the scale + (`~.axis.Axis.get_scale`). + + Scales use specific minor locators: + + - log: `~.LogLocator` + - symlog: `~.SymmetricalLogLocator` + - asinh: `~.AsinhLocator` + - logit: `~.LogitLocator` + - default: `~.AutoMinorLocator` + + Displaying minor ticks may reduce performance; you may turn them off + using `minorticks_off()` if drawing speed is a problem. + """ + scale = self.get_scale() + if scale == 'log': + s = self._scale + self.set_minor_locator(mticker.LogLocator(s.base, s.subs)) + elif scale == 'symlog': + s = self._scale + self.set_minor_locator( + mticker.SymmetricalLogLocator(s._transform, s.subs)) + elif scale == 'asinh': + s = self._scale + self.set_minor_locator( + mticker.AsinhLocator(s.linear_width, base=s._base, + subs=s._subs)) + elif scale == 'logit': + self.set_minor_locator(mticker.LogitLocator(minor=True)) + else: + self.set_minor_locator(mticker.AutoMinorLocator()) + + def minorticks_off(self): + """Remove minor ticks from the Axis.""" + self.set_minor_locator(mticker.NullLocator()) + + def set_tick_params(self, which='major', reset=False, **kwargs): + """ + Set appearance parameters for ticks, ticklabels, and gridlines. + + For documentation of keyword arguments, see + :meth:`matplotlib.axes.Axes.tick_params`. + + See Also + -------- + .Axis.get_tick_params + View the current style settings for ticks, ticklabels, and + gridlines. + """ + _api.check_in_list(['major', 'minor', 'both'], which=which) + kwtrans = self._translate_tick_params(kwargs) + + # the kwargs are stored in self._major/minor_tick_kw so that any + # future new ticks will automatically get them + if reset: + if which in ['major', 'both']: + self._reset_major_tick_kw() + self._major_tick_kw.update(kwtrans) + if which in ['minor', 'both']: + self._reset_minor_tick_kw() + self._minor_tick_kw.update(kwtrans) + self.reset_ticks() + else: + if which in ['major', 'both']: + self._major_tick_kw.update(kwtrans) + for tick in self.majorTicks: + tick._apply_params(**kwtrans) + if which in ['minor', 'both']: + self._minor_tick_kw.update(kwtrans) + for tick in self.minorTicks: + tick._apply_params(**kwtrans) + # labelOn and labelcolor also apply to the offset text. + if 'label1On' in kwtrans or 'label2On' in kwtrans: + self.offsetText.set_visible( + self._major_tick_kw.get('label1On', False) + or self._major_tick_kw.get('label2On', False)) + if 'labelcolor' in kwtrans: + self.offsetText.set_color(kwtrans['labelcolor']) + + self.stale = True + + def get_tick_params(self, which='major'): + """ + Get appearance parameters for ticks, ticklabels, and gridlines. + + .. versionadded:: 3.7 + + Parameters + ---------- + which : {'major', 'minor'}, default: 'major' + The group of ticks for which the parameters are retrieved. + + Returns + ------- + dict + Properties for styling tick elements added to the axis. + + Notes + ----- + This method returns the appearance parameters for styling *new* + elements added to this axis and may be different from the values + on current elements if they were modified directly by the user + (e.g., via ``set_*`` methods on individual tick objects). + + Examples + -------- + :: + + >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red', + ... direction='out', which='major') + >>> ax.yaxis.get_tick_params(which='major') + {'direction': 'out', + 'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False, + 'labelsize': 30, + 'labelcolor': 'red'} + >>> ax.yaxis.get_tick_params(which='minor') + {'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False} + + + """ + _api.check_in_list(['major', 'minor'], which=which) + if which == 'major': + return self._translate_tick_params( + self._major_tick_kw, reverse=True + ) + return self._translate_tick_params(self._minor_tick_kw, reverse=True) + + @classmethod + def _translate_tick_params(cls, kw, reverse=False): + """ + Translate the kwargs supported by `.Axis.set_tick_params` to kwargs + supported by `.Tick._apply_params`. + + In particular, this maps axis specific names like 'top', 'left' + to the generic tick1, tick2 logic of the axis. Additionally, there + are some other name translations. + + Returns a new dict of translated kwargs. + + Note: Use reverse=True to translate from those supported by + `.Tick._apply_params` back to those supported by + `.Axis.set_tick_params`. + """ + kw_ = {**kw} + + # The following lists may be moved to a more accessible location. + allowed_keys = [ + 'size', 'width', 'color', 'tickdir', 'pad', + 'labelsize', 'labelcolor', 'labelfontfamily', 'zorder', 'gridOn', + 'tick1On', 'tick2On', 'label1On', 'label2On', + 'length', 'direction', 'left', 'bottom', 'right', 'top', + 'labelleft', 'labelbottom', 'labelright', 'labeltop', + 'labelrotation', + *_gridline_param_names] + + keymap = { + # tick_params key -> axis key + 'length': 'size', + 'direction': 'tickdir', + 'rotation': 'labelrotation', + 'left': 'tick1On', + 'bottom': 'tick1On', + 'right': 'tick2On', + 'top': 'tick2On', + 'labelleft': 'label1On', + 'labelbottom': 'label1On', + 'labelright': 'label2On', + 'labeltop': 'label2On', + } + if reverse: + kwtrans = {} + is_x_axis = cls.axis_name == 'x' + y_axis_keys = ['left', 'right', 'labelleft', 'labelright'] + for oldkey, newkey in keymap.items(): + if newkey in kw_: + if is_x_axis and oldkey in y_axis_keys: + continue + else: + kwtrans[oldkey] = kw_.pop(newkey) + else: + kwtrans = { + newkey: kw_.pop(oldkey) + for oldkey, newkey in keymap.items() if oldkey in kw_ + } + if 'colors' in kw_: + c = kw_.pop('colors') + kwtrans['color'] = c + kwtrans['labelcolor'] = c + # Maybe move the checking up to the caller of this method. + for key in kw_: + if key not in allowed_keys: + raise ValueError( + "keyword %s is not recognized; valid keywords are %s" + % (key, allowed_keys)) + kwtrans.update(kw_) + return kwtrans + + def set_clip_path(self, path, transform=None): + super().set_clip_path(path, transform) + for child in self.majorTicks + self.minorTicks: + child.set_clip_path(path, transform) + self.stale = True + + def get_view_interval(self): + """Return the ``(min, max)`` view limits of this axis.""" + raise NotImplementedError('Derived must override') + + def set_view_interval(self, vmin, vmax, ignore=False): + """ + Set the axis view limits. This method is for internal use; Matplotlib + users should typically use e.g. `~.Axes.set_xlim` or `~.Axes.set_ylim`. + + If *ignore* is False (the default), this method will never reduce the + preexisting view limits, only expand them if *vmin* or *vmax* are not + within them. Moreover, the order of *vmin* and *vmax* does not matter; + the orientation of the axis will not change. + + If *ignore* is True, the view limits will be set exactly to ``(vmin, + vmax)`` in that order. + """ + raise NotImplementedError('Derived must override') + + def get_data_interval(self): + """Return the ``(min, max)`` data limits of this axis.""" + raise NotImplementedError('Derived must override') + + def set_data_interval(self, vmin, vmax, ignore=False): + """ + Set the axis data limits. This method is for internal use. + + If *ignore* is False (the default), this method will never reduce the + preexisting data limits, only expand them if *vmin* or *vmax* are not + within them. Moreover, the order of *vmin* and *vmax* does not matter; + the orientation of the axis will not change. + + If *ignore* is True, the data limits will be set exactly to ``(vmin, + vmax)`` in that order. + """ + raise NotImplementedError('Derived must override') + + def get_inverted(self): + """ + Return whether this Axis is oriented in the "inverse" direction. + + The "normal" direction is increasing to the right for the x-axis and to + the top for the y-axis; the "inverse" direction is increasing to the + left for the x-axis and to the bottom for the y-axis. + """ + low, high = self.get_view_interval() + return high < low + + def set_inverted(self, inverted): + """ + Set whether this Axis is oriented in the "inverse" direction. + + The "normal" direction is increasing to the right for the x-axis and to + the top for the y-axis; the "inverse" direction is increasing to the + left for the x-axis and to the bottom for the y-axis. + """ + a, b = self.get_view_interval() + # cast to bool to avoid bad interaction between python 3.8 and np.bool_ + self._set_lim(*sorted((a, b), reverse=bool(inverted)), auto=None) + + def set_default_intervals(self): + """ + Set the default limits for the axis data and view interval if they + have not been not mutated yet. + """ + # this is mainly in support of custom object plotting. For + # example, if someone passes in a datetime object, we do not + # know automagically how to set the default min/max of the + # data and view limits. The unit conversion AxisInfo + # interface provides a hook for custom types to register + # default limits through the AxisInfo.default_limits + # attribute, and the derived code below will check for that + # and use it if it's available (else just use 0..1) + + def _set_lim(self, v0, v1, *, emit=True, auto): + """ + Set view limits. + + This method is a helper for the Axes ``set_xlim``, ``set_ylim``, and + ``set_zlim`` methods. + + Parameters + ---------- + v0, v1 : float + The view limits. (Passing *v0* as a (low, high) pair is not + supported; normalization must occur in the Axes setters.) + emit : bool, default: True + Whether to notify observers of limit change. + auto : bool or None, default: False + Whether to turn on autoscaling of the x-axis. True turns on, False + turns off, None leaves unchanged. + """ + name = self._get_axis_name() + + self.axes._process_unit_info([(name, (v0, v1))], convert=False) + v0 = self.axes._validate_converted_limits(v0, self.convert_units) + v1 = self.axes._validate_converted_limits(v1, self.convert_units) + + if v0 is None or v1 is None: + # Axes init calls set_xlim(0, 1) before get_xlim() can be called, + # so only grab the limits if we really need them. + old0, old1 = self.get_view_interval() + if v0 is None: + v0 = old0 + if v1 is None: + v1 = old1 + + if self.get_scale() == 'log' and (v0 <= 0 or v1 <= 0): + # Axes init calls set_xlim(0, 1) before get_xlim() can be called, + # so only grab the limits if we really need them. + old0, old1 = self.get_view_interval() + if v0 <= 0: + _api.warn_external(f"Attempt to set non-positive {name}lim on " + f"a log-scaled axis will be ignored.") + v0 = old0 + if v1 <= 0: + _api.warn_external(f"Attempt to set non-positive {name}lim on " + f"a log-scaled axis will be ignored.") + v1 = old1 + if v0 == v1: + _api.warn_external( + f"Attempting to set identical low and high {name}lims " + f"makes transformation singular; automatically expanding.") + reverse = bool(v0 > v1) # explicit cast needed for python3.8+np.bool_. + v0, v1 = self.get_major_locator().nonsingular(v0, v1) + v0, v1 = self.limit_range_for_scale(v0, v1) + v0, v1 = sorted([v0, v1], reverse=bool(reverse)) + + self.set_view_interval(v0, v1, ignore=True) + # Mark viewlims as no longer stale without triggering an autoscale. + for ax in self._get_shared_axes(): + ax._stale_viewlims[name] = False + self._set_autoscale_on(auto) + + if emit: + self.axes.callbacks.process(f"{name}lim_changed", self.axes) + # Call all of the other Axes that are shared with this one + for other in self._get_shared_axes(): + if other is self.axes: + continue + other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto) + if emit: + other.callbacks.process(f"{name}lim_changed", other) + if ((other_fig := other.get_figure(root=False)) != + self.get_figure(root=False)): + other_fig.canvas.draw_idle() + + self.stale = True + return v0, v1 + + def _set_artist_props(self, a): + if a is None: + return + a.set_figure(self.get_figure(root=False)) + + def _update_ticks(self): + """ + Update ticks (position and labels) using the current data interval of + the axes. Return the list of ticks that will be drawn. + """ + major_locs = self.get_majorticklocs() + major_labels = self.major.formatter.format_ticks(major_locs) + major_ticks = self.get_major_ticks(len(major_locs)) + for tick, loc, label in zip(major_ticks, major_locs, major_labels): + tick.update_position(loc) + tick.label1.set_text(label) + tick.label2.set_text(label) + minor_locs = self.get_minorticklocs() + minor_labels = self.minor.formatter.format_ticks(minor_locs) + minor_ticks = self.get_minor_ticks(len(minor_locs)) + for tick, loc, label in zip(minor_ticks, minor_locs, minor_labels): + tick.update_position(loc) + tick.label1.set_text(label) + tick.label2.set_text(label) + ticks = [*major_ticks, *minor_ticks] + + view_low, view_high = self.get_view_interval() + if view_low > view_high: + view_low, view_high = view_high, view_low + + if (hasattr(self, "axes") and self.axes.name == '3d' + and mpl.rcParams['axes3d.automargin']): + # In mpl3.8, the margin was 1/48. Due to the change in automargin + # behavior in mpl3.9, we need to adjust this to compensate for a + # zoom factor of 2/48, giving us a 23/24 modifier. So the new + # margin is 0.019965277777777776 = 1/48*23/24. + margin = 0.019965277777777776 + delta = view_high - view_low + view_high = view_high - delta * margin + view_low = view_low + delta * margin + + interval_t = self.get_transform().transform([view_low, view_high]) + + ticks_to_draw = [] + for tick in ticks: + try: + loc_t = self.get_transform().transform(tick.get_loc()) + except AssertionError: + # transforms.transform doesn't allow masked values but + # some scales might make them, so we need this try/except. + pass + else: + if mtransforms._interval_contains_close(interval_t, loc_t): + ticks_to_draw.append(tick) + + return ticks_to_draw + + def _get_ticklabel_bboxes(self, ticks, renderer=None): + """Return lists of bboxes for ticks' label1's and label2's.""" + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + return ([tick.label1.get_window_extent(renderer) + for tick in ticks if tick.label1.get_visible()], + [tick.label2.get_window_extent(renderer) + for tick in ticks if tick.label2.get_visible()]) + + def get_tightbbox(self, renderer=None, *, for_layout_only=False): + """ + Return a bounding box that encloses the axis. It only accounts + tick labels, axis label, and offsetText. + + If *for_layout_only* is True, then the width of the label (if this + is an x-axis) or the height of the label (if this is a y-axis) is + collapsed to near zero. This allows tight/constrained_layout to ignore + too-long labels when doing their layout. + """ + if not self.get_visible() or for_layout_only and not self.get_in_layout(): + return + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + ticks_to_draw = self._update_ticks() + + self._update_label_position(renderer) + + # go back to just this axis's tick labels + tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer) + + self._update_offset_text_position(tlb1, tlb2) + self.offsetText.set_text(self.major.formatter.get_offset()) + + bboxes = [ + *(a.get_window_extent(renderer) + for a in [self.offsetText] + if a.get_visible()), + *tlb1, *tlb2, + ] + # take care of label + if self.label.get_visible(): + bb = self.label.get_window_extent(renderer) + # for constrained/tight_layout, we want to ignore the label's + # width/height because the adjustments they make can't be improved. + # this code collapses the relevant direction + if for_layout_only: + if self.axis_name == "x" and bb.width > 0: + bb.x0 = (bb.x0 + bb.x1) / 2 - 0.5 + bb.x1 = bb.x0 + 1.0 + if self.axis_name == "y" and bb.height > 0: + bb.y0 = (bb.y0 + bb.y1) / 2 - 0.5 + bb.y1 = bb.y0 + 1.0 + bboxes.append(bb) + bboxes = [b for b in bboxes + if 0 < b.width < np.inf and 0 < b.height < np.inf] + if bboxes: + return mtransforms.Bbox.union(bboxes) + else: + return None + + def get_tick_padding(self): + values = [] + if len(self.majorTicks): + values.append(self.majorTicks[0].get_tick_padding()) + if len(self.minorTicks): + values.append(self.minorTicks[0].get_tick_padding()) + return max(values, default=0) + + @martist.allow_rasterization + def draw(self, renderer): + # docstring inherited + + if not self.get_visible(): + return + renderer.open_group(__name__, gid=self.get_gid()) + + ticks_to_draw = self._update_ticks() + tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer) + + for tick in ticks_to_draw: + tick.draw(renderer) + + # Shift label away from axes to avoid overlapping ticklabels. + self._update_label_position(renderer) + self.label.draw(renderer) + + self._update_offset_text_position(tlb1, tlb2) + self.offsetText.set_text(self.major.formatter.get_offset()) + self.offsetText.draw(renderer) + + renderer.close_group(__name__) + self.stale = False + + def get_gridlines(self): + r"""Return this Axis' grid lines as a list of `.Line2D`\s.""" + ticks = self.get_major_ticks() + return cbook.silent_list('Line2D gridline', + [tick.gridline for tick in ticks]) + + def set_label(self, s): + """Assigning legend labels is not supported. Raises RuntimeError.""" + raise RuntimeError( + "A legend label cannot be assigned to an Axis. Did you mean to " + "set the axis label via set_label_text()?") + + def get_label(self): + """ + Return the axis label as a Text instance. + + .. admonition:: Discouraged + + This overrides `.Artist.get_label`, which is for legend labels, with a new + semantic. It is recommended to use the attribute ``Axis.label`` instead. + """ + return self.label + + def get_offset_text(self): + """Return the axis offsetText as a Text instance.""" + return self.offsetText + + def get_pickradius(self): + """Return the depth of the axis used by the picker.""" + return self._pickradius + + def get_majorticklabels(self): + """Return this Axis' major tick labels, as a list of `~.text.Text`.""" + self._update_ticks() + ticks = self.get_major_ticks() + labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()] + labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()] + return labels1 + labels2 + + def get_minorticklabels(self): + """Return this Axis' minor tick labels, as a list of `~.text.Text`.""" + self._update_ticks() + ticks = self.get_minor_ticks() + labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()] + labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()] + return labels1 + labels2 + + def get_ticklabels(self, minor=False, which=None): + """ + Get this Axis' tick labels. + + Parameters + ---------- + minor : bool + Whether to return the minor or the major ticklabels. + + which : None, ('minor', 'major', 'both') + Overrides *minor*. + + Selects which ticklabels to return + + Returns + ------- + list of `~matplotlib.text.Text` + """ + if which is not None: + if which == 'minor': + return self.get_minorticklabels() + elif which == 'major': + return self.get_majorticklabels() + elif which == 'both': + return self.get_majorticklabels() + self.get_minorticklabels() + else: + _api.check_in_list(['major', 'minor', 'both'], which=which) + if minor: + return self.get_minorticklabels() + return self.get_majorticklabels() + + def get_majorticklines(self): + r"""Return this Axis' major tick lines as a list of `.Line2D`\s.""" + lines = [] + ticks = self.get_major_ticks() + for tick in ticks: + lines.append(tick.tick1line) + lines.append(tick.tick2line) + return cbook.silent_list('Line2D ticklines', lines) + + def get_minorticklines(self): + r"""Return this Axis' minor tick lines as a list of `.Line2D`\s.""" + lines = [] + ticks = self.get_minor_ticks() + for tick in ticks: + lines.append(tick.tick1line) + lines.append(tick.tick2line) + return cbook.silent_list('Line2D ticklines', lines) + + def get_ticklines(self, minor=False): + r"""Return this Axis' tick lines as a list of `.Line2D`\s.""" + if minor: + return self.get_minorticklines() + return self.get_majorticklines() + + def get_majorticklocs(self): + """Return this Axis' major tick locations in data coordinates.""" + return self.major.locator() + + def get_minorticklocs(self): + """Return this Axis' minor tick locations in data coordinates.""" + # Remove minor ticks duplicating major ticks. + minor_locs = np.asarray(self.minor.locator()) + if self.remove_overlapping_locs: + major_locs = self.major.locator() + transform = self._scale.get_transform() + tr_minor_locs = transform.transform(minor_locs) + tr_major_locs = transform.transform(major_locs) + lo, hi = sorted(transform.transform(self.get_view_interval())) + # Use the transformed view limits as scale. 1e-5 is the default + # rtol for np.isclose. + tol = (hi - lo) * 1e-5 + mask = np.isclose(tr_minor_locs[:, None], tr_major_locs[None, :], + atol=tol, rtol=0).any(axis=1) + minor_locs = minor_locs[~mask] + return minor_locs + + def get_ticklocs(self, *, minor=False): + """ + Return this Axis' tick locations in data coordinates. + + The locations are not clipped to the current axis limits and hence + may contain locations that are not visible in the output. + + Parameters + ---------- + minor : bool, default: False + True to return the minor tick directions, + False to return the major tick directions. + + Returns + ------- + array of tick locations + """ + return self.get_minorticklocs() if minor else self.get_majorticklocs() + + def get_ticks_direction(self, minor=False): + """ + Return an array of this Axis' tick directions. + + Parameters + ---------- + minor : bool, default: False + True to return the minor tick directions, + False to return the major tick directions. + + Returns + ------- + array of tick directions + """ + if minor: + return np.array( + [tick._tickdir for tick in self.get_minor_ticks()]) + else: + return np.array( + [tick._tickdir for tick in self.get_major_ticks()]) + + def _get_tick(self, major): + """Return the default tick instance.""" + if self._tick_class is None: + raise NotImplementedError( + f"The Axis subclass {self.__class__.__name__} must define " + "_tick_class or reimplement _get_tick()") + tick_kw = self._major_tick_kw if major else self._minor_tick_kw + return self._tick_class(self.axes, 0, major=major, **tick_kw) + + def _get_tick_label_size(self, axis_name): + """ + Return the text size of tick labels for this Axis. + + This is a convenience function to avoid having to create a `Tick` in + `.get_tick_space`, since it is expensive. + """ + tick_kw = self._major_tick_kw + size = tick_kw.get('labelsize', + mpl.rcParams[f'{axis_name}tick.labelsize']) + return mtext.FontProperties(size=size).get_size_in_points() + + def _copy_tick_props(self, src, dest): + """Copy the properties from *src* tick to *dest* tick.""" + if src is None or dest is None: + return + dest.label1.update_from(src.label1) + dest.label2.update_from(src.label2) + dest.tick1line.update_from(src.tick1line) + dest.tick2line.update_from(src.tick2line) + dest.gridline.update_from(src.gridline) + dest.update_from(src) + dest._loc = src._loc + dest._size = src._size + dest._width = src._width + dest._base_pad = src._base_pad + dest._labelrotation = src._labelrotation + dest._zorder = src._zorder + dest._tickdir = src._tickdir + + def get_label_text(self): + """Get the text of the label.""" + return self.label.get_text() + + def get_major_locator(self): + """Get the locator of the major ticker.""" + return self.major.locator + + def get_minor_locator(self): + """Get the locator of the minor ticker.""" + return self.minor.locator + + def get_major_formatter(self): + """Get the formatter of the major ticker.""" + return self.major.formatter + + def get_minor_formatter(self): + """Get the formatter of the minor ticker.""" + return self.minor.formatter + + def get_major_ticks(self, numticks=None): + r""" + Return the list of major `.Tick`\s. + + .. warning:: + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that changes to individual ticks will not + survive if you work on the figure further (including also + panning/zooming on a displayed figure). + + Working on the individual ticks is a method of last resort. + Use `.set_tick_params` instead if possible. + """ + if numticks is None: + numticks = len(self.get_majorticklocs()) + + while len(self.majorTicks) < numticks: + # Update the new tick label properties from the old. + tick = self._get_tick(major=True) + self.majorTicks.append(tick) + self._copy_tick_props(self.majorTicks[0], tick) + + return self.majorTicks[:numticks] + + def get_minor_ticks(self, numticks=None): + r""" + Return the list of minor `.Tick`\s. + + .. warning:: + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that changes to individual ticks will not + survive if you work on the figure further (including also + panning/zooming on a displayed figure). + + Working on the individual ticks is a method of last resort. + Use `.set_tick_params` instead if possible. + """ + if numticks is None: + numticks = len(self.get_minorticklocs()) + + while len(self.minorTicks) < numticks: + # Update the new tick label properties from the old. + tick = self._get_tick(major=False) + self.minorTicks.append(tick) + self._copy_tick_props(self.minorTicks[0], tick) + + return self.minorTicks[:numticks] + + def grid(self, visible=None, which='major', **kwargs): + """ + Configure the grid lines. + + Parameters + ---------- + visible : bool or None + Whether to show the grid lines. If any *kwargs* are supplied, it + is assumed you want the grid on and *visible* will be set to True. + + If *visible* is *None* and there are no *kwargs*, this toggles the + visibility of the lines. + + which : {'major', 'minor', 'both'} + The grid lines to apply the changes on. + + **kwargs : `~matplotlib.lines.Line2D` properties + Define the line properties of the grid, e.g.:: + + grid(color='r', linestyle='-', linewidth=2) + """ + if kwargs: + if visible is None: + visible = True + elif not visible: # something false-like but not None + _api.warn_external('First parameter to grid() is false, ' + 'but line properties are supplied. The ' + 'grid will be enabled.') + visible = True + which = which.lower() + _api.check_in_list(['major', 'minor', 'both'], which=which) + gridkw = {f'grid_{name}': value for name, value in kwargs.items()} + if which in ['minor', 'both']: + gridkw['gridOn'] = (not self._minor_tick_kw['gridOn'] + if visible is None else visible) + self.set_tick_params(which='minor', **gridkw) + if which in ['major', 'both']: + gridkw['gridOn'] = (not self._major_tick_kw['gridOn'] + if visible is None else visible) + self.set_tick_params(which='major', **gridkw) + self.stale = True + + def update_units(self, data): + """ + Introspect *data* for units converter and update the + ``axis.get_converter`` instance if necessary. Return *True* + if *data* is registered for unit conversion. + """ + if not self._converter_is_explicit: + converter = munits.registry.get_converter(data) + else: + converter = self._converter + + if converter is None: + return False + + neednew = self._converter != converter + self._set_converter(converter) + default = self._converter.default_units(data, self) + if default is not None and self.units is None: + self.set_units(default) + + elif neednew: + self._update_axisinfo() + self.stale = True + return True + + def _update_axisinfo(self): + """ + Check the axis converter for the stored units to see if the + axis info needs to be updated. + """ + if self._converter is None: + return + + info = self._converter.axisinfo(self.units, self) + + if info is None: + return + if info.majloc is not None and \ + self.major.locator != info.majloc and self.isDefault_majloc: + self.set_major_locator(info.majloc) + self.isDefault_majloc = True + if info.minloc is not None and \ + self.minor.locator != info.minloc and self.isDefault_minloc: + self.set_minor_locator(info.minloc) + self.isDefault_minloc = True + if info.majfmt is not None and \ + self.major.formatter != info.majfmt and self.isDefault_majfmt: + self.set_major_formatter(info.majfmt) + self.isDefault_majfmt = True + if info.minfmt is not None and \ + self.minor.formatter != info.minfmt and self.isDefault_minfmt: + self.set_minor_formatter(info.minfmt) + self.isDefault_minfmt = True + if info.label is not None and self.isDefault_label: + self.set_label_text(info.label) + self.isDefault_label = True + + self.set_default_intervals() + + def have_units(self): + return self._converter is not None or self.units is not None + + def convert_units(self, x): + # If x is natively supported by Matplotlib, doesn't need converting + if munits._is_natively_supported(x): + return x + + if self._converter is None: + self._set_converter(munits.registry.get_converter(x)) + + if self._converter is None: + return x + try: + ret = self._converter.convert(x, self.units, self) + except Exception as e: + raise munits.ConversionError('Failed to convert value(s) to axis ' + f'units: {x!r}') from e + return ret + + def get_converter(self): + """ + Get the unit converter for axis. + + Returns + ------- + `~matplotlib.units.ConversionInterface` or None + """ + return self._converter + + def set_converter(self, converter): + """ + Set the unit converter for axis. + + Parameters + ---------- + converter : `~matplotlib.units.ConversionInterface` + """ + self._set_converter(converter) + self._converter_is_explicit = True + + def _set_converter(self, converter): + if self._converter is converter or self._converter == converter: + return + if self._converter_is_explicit: + raise RuntimeError("Axis already has an explicit converter set") + elif ( + self._converter is not None and + not isinstance(converter, type(self._converter)) and + not isinstance(self._converter, type(converter)) + ): + _api.warn_external( + "This axis already has a converter set and " + "is updating to a potentially incompatible converter" + ) + self._converter = converter + + def set_units(self, u): + """ + Set the units for axis. + + Parameters + ---------- + u : units tag + + Notes + ----- + The units of any shared axis will also be updated. + """ + if u == self.units: + return + for axis in self._get_shared_axis(): + axis.units = u + axis._update_axisinfo() + axis.callbacks.process('units') + axis.stale = True + + def get_units(self): + """Return the units for axis.""" + return self.units + + def set_label_text(self, label, fontdict=None, **kwargs): + """ + Set the text value of the axis label. + + Parameters + ---------- + label : str + Text string. + fontdict : dict + Text properties. + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``set_label_text(..., **fontdict)``. + + **kwargs + Merged into fontdict. + """ + self.isDefault_label = False + self.label.set_text(label) + if fontdict is not None: + self.label.update(fontdict) + self.label.update(kwargs) + self.stale = True + return self.label + + def set_major_formatter(self, formatter): + """ + Set the formatter of the major ticker. + + In addition to a `~matplotlib.ticker.Formatter` instance, + this also accepts a ``str`` or function. + + For a ``str`` a `~matplotlib.ticker.StrMethodFormatter` is used. + The field used for the value must be labeled ``'x'`` and the field used + for the position must be labeled ``'pos'``. + See the `~matplotlib.ticker.StrMethodFormatter` documentation for + more information. + + For a function, a `~matplotlib.ticker.FuncFormatter` is used. + The function must take two inputs (a tick value ``x`` and a + position ``pos``), and return a string containing the corresponding + tick label. + See the `~matplotlib.ticker.FuncFormatter` documentation for + more information. + + Parameters + ---------- + formatter : `~matplotlib.ticker.Formatter`, ``str``, or function + """ + self._set_formatter(formatter, self.major) + + def set_minor_formatter(self, formatter): + """ + Set the formatter of the minor ticker. + + In addition to a `~matplotlib.ticker.Formatter` instance, + this also accepts a ``str`` or function. + See `.Axis.set_major_formatter` for more information. + + Parameters + ---------- + formatter : `~matplotlib.ticker.Formatter`, ``str``, or function + """ + self._set_formatter(formatter, self.minor) + + def _set_formatter(self, formatter, level): + if isinstance(formatter, str): + formatter = mticker.StrMethodFormatter(formatter) + # Don't allow any other TickHelper to avoid easy-to-make errors, + # like using a Locator instead of a Formatter. + elif (callable(formatter) and + not isinstance(formatter, mticker.TickHelper)): + formatter = mticker.FuncFormatter(formatter) + else: + _api.check_isinstance(mticker.Formatter, formatter=formatter) + + if (isinstance(formatter, mticker.FixedFormatter) + and len(formatter.seq) > 0 + and not isinstance(level.locator, mticker.FixedLocator)): + _api.warn_external('FixedFormatter should only be used together ' + 'with FixedLocator') + + if level == self.major: + self.isDefault_majfmt = False + else: + self.isDefault_minfmt = False + + level.formatter = formatter + formatter.set_axis(self) + self.stale = True + + def set_major_locator(self, locator): + """ + Set the locator of the major ticker. + + Parameters + ---------- + locator : `~matplotlib.ticker.Locator` + """ + _api.check_isinstance(mticker.Locator, locator=locator) + self.isDefault_majloc = False + self.major.locator = locator + if self.major.formatter: + self.major.formatter._set_locator(locator) + locator.set_axis(self) + self.stale = True + + def set_minor_locator(self, locator): + """ + Set the locator of the minor ticker. + + Parameters + ---------- + locator : `~matplotlib.ticker.Locator` + """ + _api.check_isinstance(mticker.Locator, locator=locator) + self.isDefault_minloc = False + self.minor.locator = locator + if self.minor.formatter: + self.minor.formatter._set_locator(locator) + locator.set_axis(self) + self.stale = True + + def set_pickradius(self, pickradius): + """ + Set the depth of the axis used by the picker. + + Parameters + ---------- + pickradius : float + The acceptance radius for containment tests. + See also `.Axis.contains`. + """ + if not isinstance(pickradius, Real) or pickradius < 0: + raise ValueError("pick radius should be a distance") + self._pickradius = pickradius + + pickradius = property( + get_pickradius, set_pickradius, doc="The acceptance radius for " + "containment tests. See also `.Axis.contains`.") + + # Helper for set_ticklabels. Defining it here makes it picklable. + @staticmethod + def _format_with_dict(tickd, x, pos): + return tickd.get(x, "") + + def set_ticklabels(self, labels, *, minor=False, fontdict=None, **kwargs): + r""" + [*Discouraged*] Set this Axis' tick labels with list of string labels. + + .. admonition:: Discouraged + + The use of this method is discouraged, because of the dependency on + tick positions. In most cases, you'll want to use + ``Axes.set_[x/y/z]ticks(positions, labels)`` or ``Axis.set_ticks`` + instead. + + If you are using this method, you should always fix the tick + positions before, e.g. by using `.Axis.set_ticks` or by explicitly + setting a `~.ticker.FixedLocator`. Otherwise, ticks are free to + move and the labels may end up in unexpected positions. + + Parameters + ---------- + labels : sequence of str or of `.Text`\s + Texts for labeling each tick location in the sequence set by + `.Axis.set_ticks`; the number of labels must match the number of locations. + The labels are used as is, via a `.FixedFormatter` (without further + formatting). + + minor : bool + If True, set minor ticks instead of major ticks. + + fontdict : dict, optional + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``set_ticklabels(..., **fontdict)``. + + A dictionary controlling the appearance of the ticklabels. + The default *fontdict* is:: + + {'fontsize': rcParams['axes.titlesize'], + 'fontweight': rcParams['axes.titleweight'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc} + + **kwargs + Text properties. + + .. warning:: + + This only sets the properties of the current ticks, which is + only sufficient for static plots. + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `.set_tick_params` instead if possible. + + Returns + ------- + list of `.Text`\s + For each tick, includes ``tick.label1`` if it is visible, then + ``tick.label2`` if it is visible, in that order. + """ + try: + labels = [t.get_text() if hasattr(t, 'get_text') else t + for t in labels] + except TypeError: + raise TypeError(f"{labels:=} must be a sequence") from None + locator = (self.get_minor_locator() if minor + else self.get_major_locator()) + if not labels: + # eg labels=[]: + formatter = mticker.NullFormatter() + elif isinstance(locator, mticker.FixedLocator): + # Passing [] as a list of labels is often used as a way to + # remove all tick labels, so only error for > 0 labels + if len(locator.locs) != len(labels) and len(labels) != 0: + raise ValueError( + "The number of FixedLocator locations" + f" ({len(locator.locs)}), usually from a call to" + " set_ticks, does not match" + f" the number of labels ({len(labels)}).") + tickd = {loc: lab for loc, lab in zip(locator.locs, labels)} + func = functools.partial(self._format_with_dict, tickd) + formatter = mticker.FuncFormatter(func) + else: + _api.warn_external( + "set_ticklabels() should only be used with a fixed number of " + "ticks, i.e. after set_ticks() or using a FixedLocator.") + formatter = mticker.FixedFormatter(labels) + + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="FixedFormatter should only be used together with FixedLocator") + if minor: + self.set_minor_formatter(formatter) + locs = self.get_minorticklocs() + ticks = self.get_minor_ticks(len(locs)) + else: + self.set_major_formatter(formatter) + locs = self.get_majorticklocs() + ticks = self.get_major_ticks(len(locs)) + + ret = [] + if fontdict is not None: + kwargs.update(fontdict) + for pos, (loc, tick) in enumerate(zip(locs, ticks)): + tick.update_position(loc) + tick_label = formatter(loc, pos) + # deal with label1 + tick.label1.set_text(tick_label) + tick.label1._internal_update(kwargs) + # deal with label2 + tick.label2.set_text(tick_label) + tick.label2._internal_update(kwargs) + # only return visible tick labels + if tick.label1.get_visible(): + ret.append(tick.label1) + if tick.label2.get_visible(): + ret.append(tick.label2) + + self.stale = True + return ret + + def _set_tick_locations(self, ticks, *, minor=False): + # see docstring of set_ticks + + # XXX if the user changes units, the information will be lost here + ticks = self.convert_units(ticks) + locator = mticker.FixedLocator(ticks) # validate ticks early. + if len(ticks): + for axis in self._get_shared_axis(): + # set_view_interval maintains any preexisting inversion. + axis.set_view_interval(min(ticks), max(ticks)) + self.axes.stale = True + if minor: + self.set_minor_locator(locator) + return self.get_minor_ticks(len(ticks)) + else: + self.set_major_locator(locator) + return self.get_major_ticks(len(ticks)) + + def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs): + """ + Set this Axis' tick locations and optionally tick labels. + + If necessary, the view limits of the Axis are expanded so that all + given ticks are visible. + + Parameters + ---------- + ticks : 1D array-like + Array of tick locations (either floats or in axis units). The axis + `.Locator` is replaced by a `~.ticker.FixedLocator`. + + Pass an empty list (``set_ticks([])``) to remove all ticks. + + Some tick formatters will not label arbitrary tick positions; + e.g. log formatters only label decade ticks by default. In + such a case you can set a formatter explicitly on the axis + using `.Axis.set_major_formatter` or provide formatted + *labels* yourself. + + labels : list of str, optional + Tick labels for each location in *ticks*; must have the same length as + *ticks*. If set, the labels are used as is, via a `.FixedFormatter`. + If not set, the labels are generated using the axis tick `.Formatter`. + + minor : bool, default: False + If ``False``, set only the major ticks; if ``True``, only the minor ticks. + + **kwargs + `.Text` properties for the labels. Using these is only allowed if + you pass *labels*. In other cases, please use `~.Axes.tick_params`. + + Notes + ----- + The mandatory expansion of the view limits is an intentional design + choice to prevent the surprise of a non-visible tick. If you need + other limits, you should set the limits explicitly after setting the + ticks. + """ + if labels is None and kwargs: + first_key = next(iter(kwargs)) + raise ValueError( + f"Incorrect use of keyword argument {first_key!r}. Keyword arguments " + "other than 'minor' modify the text labels and can only be used if " + "'labels' are passed as well.") + result = self._set_tick_locations(ticks, minor=minor) + if labels is not None: + self.set_ticklabels(labels, minor=minor, **kwargs) + return result + + def _get_tick_boxes_siblings(self, renderer): + """ + Get the bounding boxes for this `.axis` and its siblings + as set by `.Figure.align_xlabels` or `.Figure.align_ylabels`. + + By default, it just gets bboxes for *self*. + """ + # Get the Grouper keeping track of x or y label groups for this figure. + name = self._get_axis_name() + if name not in self.get_figure(root=False)._align_label_groups: + return [], [] + grouper = self.get_figure(root=False)._align_label_groups[name] + bboxes = [] + bboxes2 = [] + # If we want to align labels from other Axes: + for ax in grouper.get_siblings(self.axes): + axis = ax._axis_map[name] + ticks_to_draw = axis._update_ticks() + tlb, tlb2 = axis._get_ticklabel_bboxes(ticks_to_draw, renderer) + bboxes.extend(tlb) + bboxes2.extend(tlb2) + return bboxes, bboxes2 + + def _update_label_position(self, renderer): + """ + Update the label position based on the bounding box enclosing + all the ticklabels and axis spine. + """ + raise NotImplementedError('Derived must override') + + def _update_offset_text_position(self, bboxes, bboxes2): + """ + Update the offset text position based on the sequence of bounding + boxes of all the ticklabels. + """ + raise NotImplementedError('Derived must override') + + def axis_date(self, tz=None): + """ + Set up axis ticks and labels to treat data along this Axis as dates. + + Parameters + ---------- + tz : str or `datetime.tzinfo`, default: :rc:`timezone` + The timezone used to create date labels. + """ + # By providing a sample datetime instance with the desired timezone, + # the registered converter can be selected, and the "units" attribute, + # which is the timezone, can be set. + if isinstance(tz, str): + import dateutil.tz + tz = dateutil.tz.gettz(tz) + self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz)) + + def get_tick_space(self): + """Return the estimated number of ticks that can fit on the axis.""" + # Must be overridden in the subclass + raise NotImplementedError() + + def _get_ticks_position(self): + """ + Helper for `XAxis.get_ticks_position` and `YAxis.get_ticks_position`. + + Check the visibility of tick1line, label1, tick2line, and label2 on + the first major and the first minor ticks, and return + + - 1 if only tick1line and label1 are visible (which corresponds to + "bottom" for the x-axis and "left" for the y-axis); + - 2 if only tick2line and label2 are visible (which corresponds to + "top" for the x-axis and "right" for the y-axis); + - "default" if only tick1line, tick2line and label1 are visible; + - "unknown" otherwise. + """ + major = self.majorTicks[0] + minor = self.minorTicks[0] + if all(tick.tick1line.get_visible() + and not tick.tick2line.get_visible() + and tick.label1.get_visible() + and not tick.label2.get_visible() + for tick in [major, minor]): + return 1 + elif all(tick.tick2line.get_visible() + and not tick.tick1line.get_visible() + and tick.label2.get_visible() + and not tick.label1.get_visible() + for tick in [major, minor]): + return 2 + elif all(tick.tick1line.get_visible() + and tick.tick2line.get_visible() + and tick.label1.get_visible() + and not tick.label2.get_visible() + for tick in [major, minor]): + return "default" + else: + return "unknown" + + def get_label_position(self): + """ + Return the label position (top or bottom) + """ + return self.label_position + + def set_label_position(self, position): + """ + Set the label position (top or bottom) + + Parameters + ---------- + position : {'top', 'bottom'} + """ + raise NotImplementedError() + + def get_minpos(self): + raise NotImplementedError() + + +def _make_getset_interval(method_name, lim_name, attr_name): + """ + Helper to generate ``get_{data,view}_interval`` and + ``set_{data,view}_interval`` implementations. + """ + + def getter(self): + # docstring inherited. + return getattr(getattr(self.axes, lim_name), attr_name) + + def setter(self, vmin, vmax, ignore=False): + # docstring inherited. + if ignore: + setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax)) + else: + oldmin, oldmax = getter(self) + if oldmin < oldmax: + setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), + ignore=True) + else: + setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax), + ignore=True) + self.stale = True + + getter.__name__ = f"get_{method_name}_interval" + setter.__name__ = f"set_{method_name}_interval" + + return getter, setter + + +class XAxis(Axis): + __name__ = 'xaxis' + axis_name = 'x' #: Read-only name identifying the axis. + _tick_class = XTick + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._init() + + def _init(self): + """ + Initialize the label and offsetText instance values and + `label_position` / `offset_text_position`. + """ + # x in axes coords, y in display coords (to be updated at draw time by + # _update_label_positions and _update_offset_text_position). + self.label.set( + x=0.5, y=0, + verticalalignment='top', horizontalalignment='center', + transform=mtransforms.blended_transform_factory( + self.axes.transAxes, mtransforms.IdentityTransform()), + ) + self.label_position = 'bottom' + + if mpl.rcParams['xtick.labelcolor'] == 'inherit': + tick_color = mpl.rcParams['xtick.color'] + else: + tick_color = mpl.rcParams['xtick.labelcolor'] + + self.offsetText.set( + x=1, y=0, + verticalalignment='top', horizontalalignment='right', + transform=mtransforms.blended_transform_factory( + self.axes.transAxes, mtransforms.IdentityTransform()), + fontsize=mpl.rcParams['xtick.labelsize'], + color=tick_color + ) + self.offset_text_position = 'bottom' + + def contains(self, mouseevent): + """Test whether the mouse event occurred in the x-axis.""" + if self._different_canvas(mouseevent): + return False, {} + x, y = mouseevent.x, mouseevent.y + try: + trans = self.axes.transAxes.inverted() + xaxes, yaxes = trans.transform((x, y)) + except ValueError: + return False, {} + (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)]) + inaxis = 0 <= xaxes <= 1 and ( + b - self._pickradius < y < b or + t < y < t + self._pickradius) + return inaxis, {} + + def set_label_position(self, position): + """ + Set the label position (top or bottom) + + Parameters + ---------- + position : {'top', 'bottom'} + """ + self.label.set_verticalalignment(_api.check_getitem({ + 'top': 'baseline', 'bottom': 'top', + }, position=position)) + self.label_position = position + self.stale = True + + def _update_label_position(self, renderer): + """ + Update the label position based on the bounding box enclosing + all the ticklabels and axis spine + """ + if not self._autolabelpos: + return + + # get bounding boxes for this axis and any siblings + # that have been set by `fig.align_xlabels()` + bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer) + x, y = self.label.get_position() + + if self.label_position == 'bottom': + # Union with extents of the bottom spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes, self.axes.spines.get("bottom", self.axes).get_window_extent()]) + self.label.set_position( + (x, bbox.y0 - self.labelpad * self.get_figure(root=True).dpi / 72)) + else: + # Union with extents of the top spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes2, self.axes.spines.get("top", self.axes).get_window_extent()]) + self.label.set_position( + (x, bbox.y1 + self.labelpad * self.get_figure(root=True).dpi / 72)) + + def _update_offset_text_position(self, bboxes, bboxes2): + """ + Update the offset_text position based on the sequence of bounding + boxes of all the ticklabels + """ + x, y = self.offsetText.get_position() + if not hasattr(self, '_tick_position'): + self._tick_position = 'bottom' + if self._tick_position == 'bottom': + if not len(bboxes): + bottom = self.axes.bbox.ymin + else: + bbox = mtransforms.Bbox.union(bboxes) + bottom = bbox.y0 + y = bottom - self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72 + else: + if not len(bboxes2): + top = self.axes.bbox.ymax + else: + bbox = mtransforms.Bbox.union(bboxes2) + top = bbox.y1 + y = top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72 + self.offsetText.set_position((x, y)) + + def set_ticks_position(self, position): + """ + Set the ticks position. + + Parameters + ---------- + position : {'top', 'bottom', 'both', 'default', 'none'} + 'both' sets the ticks to appear on both positions, but does not + change the tick labels. 'default' resets the tick positions to + the default: ticks on both positions, labels at bottom. 'none' + can be used if you don't want any ticks. 'none' and 'both' + affect only the ticks, not the labels. + """ + if position == 'top': + self.set_tick_params(which='both', top=True, labeltop=True, + bottom=False, labelbottom=False) + self._tick_position = 'top' + self.offsetText.set_verticalalignment('bottom') + elif position == 'bottom': + self.set_tick_params(which='both', top=False, labeltop=False, + bottom=True, labelbottom=True) + self._tick_position = 'bottom' + self.offsetText.set_verticalalignment('top') + elif position == 'both': + self.set_tick_params(which='both', top=True, + bottom=True) + elif position == 'none': + self.set_tick_params(which='both', top=False, + bottom=False) + elif position == 'default': + self.set_tick_params(which='both', top=True, labeltop=False, + bottom=True, labelbottom=True) + self._tick_position = 'bottom' + self.offsetText.set_verticalalignment('top') + else: + _api.check_in_list(['top', 'bottom', 'both', 'default', 'none'], + position=position) + self.stale = True + + def tick_top(self): + """ + Move ticks and ticklabels (if present) to the top of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('top') + # If labels were turned off before this was called, leave them off. + self.set_tick_params(which='both', labeltop=label) + + def tick_bottom(self): + """ + Move ticks and ticklabels (if present) to the bottom of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('bottom') + # If labels were turned off before this was called, leave them off. + self.set_tick_params(which='both', labelbottom=label) + + def get_ticks_position(self): + """ + Return the ticks position ("top", "bottom", "default", or "unknown"). + """ + return {1: "bottom", 2: "top", + "default": "default", "unknown": "unknown"}[ + self._get_ticks_position()] + + get_view_interval, set_view_interval = _make_getset_interval( + "view", "viewLim", "intervalx") + get_data_interval, set_data_interval = _make_getset_interval( + "data", "dataLim", "intervalx") + + def get_minpos(self): + return self.axes.dataLim.minposx + + def set_default_intervals(self): + # docstring inherited + # only change view if dataLim has not changed and user has + # not changed the view: + if (not self.axes.dataLim.mutatedx() and + not self.axes.viewLim.mutatedx()): + if self._converter is not None: + info = self._converter.axisinfo(self.units, self) + if info.default_limits is not None: + xmin, xmax = self.convert_units(info.default_limits) + self.axes.viewLim.intervalx = xmin, xmax + self.stale = True + + def get_tick_space(self): + ends = mtransforms.Bbox.unit().transformed( + self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans) + length = ends.width * 72 + # There is a heuristic here that the aspect ratio of tick text + # is no more than 3:1 + size = self._get_tick_label_size('x') * 3 + if size > 0: + return int(np.floor(length / size)) + else: + return 2**31 - 1 + + +class YAxis(Axis): + __name__ = 'yaxis' + axis_name = 'y' #: Read-only name identifying the axis. + _tick_class = YTick + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._init() + + def _init(self): + """ + Initialize the label and offsetText instance values and + `label_position` / `offset_text_position`. + """ + # x in display coords, y in axes coords (to be updated at draw time by + # _update_label_positions and _update_offset_text_position). + self.label.set( + x=0, y=0.5, + verticalalignment='bottom', horizontalalignment='center', + rotation='vertical', rotation_mode='anchor', + transform=mtransforms.blended_transform_factory( + mtransforms.IdentityTransform(), self.axes.transAxes), + ) + self.label_position = 'left' + + if mpl.rcParams['ytick.labelcolor'] == 'inherit': + tick_color = mpl.rcParams['ytick.color'] + else: + tick_color = mpl.rcParams['ytick.labelcolor'] + + # x in axes coords, y in display coords(!). + self.offsetText.set( + x=0, y=0.5, + verticalalignment='baseline', horizontalalignment='left', + transform=mtransforms.blended_transform_factory( + self.axes.transAxes, mtransforms.IdentityTransform()), + fontsize=mpl.rcParams['ytick.labelsize'], + color=tick_color + ) + self.offset_text_position = 'left' + + def contains(self, mouseevent): + # docstring inherited + if self._different_canvas(mouseevent): + return False, {} + x, y = mouseevent.x, mouseevent.y + try: + trans = self.axes.transAxes.inverted() + xaxes, yaxes = trans.transform((x, y)) + except ValueError: + return False, {} + (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)]) + inaxis = 0 <= yaxes <= 1 and ( + l - self._pickradius < x < l or + r < x < r + self._pickradius) + return inaxis, {} + + def set_label_position(self, position): + """ + Set the label position (left or right) + + Parameters + ---------- + position : {'left', 'right'} + """ + self.label.set_rotation_mode('anchor') + self.label.set_verticalalignment(_api.check_getitem({ + 'left': 'bottom', 'right': 'top', + }, position=position)) + self.label_position = position + self.stale = True + + def _update_label_position(self, renderer): + """ + Update the label position based on the bounding box enclosing + all the ticklabels and axis spine + """ + if not self._autolabelpos: + return + + # get bounding boxes for this axis and any siblings + # that have been set by `fig.align_ylabels()` + bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer) + x, y = self.label.get_position() + + if self.label_position == 'left': + # Union with extents of the left spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes, self.axes.spines.get("left", self.axes).get_window_extent()]) + self.label.set_position( + (bbox.x0 - self.labelpad * self.get_figure(root=True).dpi / 72, y)) + else: + # Union with extents of the right spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes2, self.axes.spines.get("right", self.axes).get_window_extent()]) + self.label.set_position( + (bbox.x1 + self.labelpad * self.get_figure(root=True).dpi / 72, y)) + + def _update_offset_text_position(self, bboxes, bboxes2): + """ + Update the offset_text position based on the sequence of bounding + boxes of all the ticklabels + """ + x, _ = self.offsetText.get_position() + if 'outline' in self.axes.spines: + # Special case for colorbars: + bbox = self.axes.spines['outline'].get_window_extent() + else: + bbox = self.axes.bbox + top = bbox.ymax + self.offsetText.set_position( + (x, top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72) + ) + + def set_offset_position(self, position): + """ + Parameters + ---------- + position : {'left', 'right'} + """ + x, y = self.offsetText.get_position() + x = _api.check_getitem({'left': 0, 'right': 1}, position=position) + + self.offsetText.set_ha(position) + self.offsetText.set_position((x, y)) + self.stale = True + + def set_ticks_position(self, position): + """ + Set the ticks position. + + Parameters + ---------- + position : {'left', 'right', 'both', 'default', 'none'} + 'both' sets the ticks to appear on both positions, but does not + change the tick labels. 'default' resets the tick positions to + the default: ticks on both positions, labels at left. 'none' + can be used if you don't want any ticks. 'none' and 'both' + affect only the ticks, not the labels. + """ + if position == 'right': + self.set_tick_params(which='both', right=True, labelright=True, + left=False, labelleft=False) + self.set_offset_position(position) + elif position == 'left': + self.set_tick_params(which='both', right=False, labelright=False, + left=True, labelleft=True) + self.set_offset_position(position) + elif position == 'both': + self.set_tick_params(which='both', right=True, + left=True) + elif position == 'none': + self.set_tick_params(which='both', right=False, + left=False) + elif position == 'default': + self.set_tick_params(which='both', right=True, labelright=False, + left=True, labelleft=True) + else: + _api.check_in_list(['left', 'right', 'both', 'default', 'none'], + position=position) + self.stale = True + + def tick_right(self): + """ + Move ticks and ticklabels (if present) to the right of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('right') + # if labels were turned off before this was called + # leave them off + self.set_tick_params(which='both', labelright=label) + + def tick_left(self): + """ + Move ticks and ticklabels (if present) to the left of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('left') + # if labels were turned off before this was called + # leave them off + self.set_tick_params(which='both', labelleft=label) + + def get_ticks_position(self): + """ + Return the ticks position ("left", "right", "default", or "unknown"). + """ + return {1: "left", 2: "right", + "default": "default", "unknown": "unknown"}[ + self._get_ticks_position()] + + get_view_interval, set_view_interval = _make_getset_interval( + "view", "viewLim", "intervaly") + get_data_interval, set_data_interval = _make_getset_interval( + "data", "dataLim", "intervaly") + + def get_minpos(self): + return self.axes.dataLim.minposy + + def set_default_intervals(self): + # docstring inherited + # only change view if dataLim has not changed and user has + # not changed the view: + if (not self.axes.dataLim.mutatedy() and + not self.axes.viewLim.mutatedy()): + if self._converter is not None: + info = self._converter.axisinfo(self.units, self) + if info.default_limits is not None: + ymin, ymax = self.convert_units(info.default_limits) + self.axes.viewLim.intervaly = ymin, ymax + self.stale = True + + def get_tick_space(self): + ends = mtransforms.Bbox.unit().transformed( + self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans) + length = ends.height * 72 + # Having a spacing of at least 2 just looks good. + size = self._get_tick_label_size('y') * 2 + if size > 0: + return int(np.floor(length / size)) + else: + return 2**31 - 1 diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/collections.py b/llava_video/lib/python3.10/site-packages/matplotlib/collections.py new file mode 100644 index 0000000000000000000000000000000000000000..f18d5a4c3a8c90ec65d943e495b3928de1672689 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/matplotlib/collections.py @@ -0,0 +1,2582 @@ +""" +Classes for the efficient drawing of large collections of objects that +share most properties, e.g., a large number of line segments or +polygons. + +The classes are not meant to be as flexible as their single element +counterparts (e.g., you may not be able to select all line styles) but +they are meant to be fast for common use cases (e.g., a large set of solid +line segments). +""" + +import itertools +import functools +import math +from numbers import Number, Real +import warnings + +import numpy as np + +import matplotlib as mpl +from . import (_api, _path, artist, cbook, colorizer as mcolorizer, colors as mcolors, + _docstring, hatch as mhatch, lines as mlines, path as mpath, transforms) +from ._enums import JoinStyle, CapStyle + + +# "color" is excluded; it is a compound setter, and its docstring differs +# in LineCollection. +@_api.define_aliases({ + "antialiased": ["antialiaseds", "aa"], + "edgecolor": ["edgecolors", "ec"], + "facecolor": ["facecolors", "fc"], + "linestyle": ["linestyles", "dashes", "ls"], + "linewidth": ["linewidths", "lw"], + "offset_transform": ["transOffset"], +}) +class Collection(mcolorizer.ColorizingArtist): + r""" + Base class for Collections. Must be subclassed to be usable. + + A Collection represents a sequence of `.Patch`\es that can be drawn + more efficiently together than individually. For example, when a single + path is being drawn repeatedly at different offsets, the renderer can + typically execute a ``draw_marker()`` call much more efficiently than a + series of repeated calls to ``draw_path()`` with the offsets put in + one-by-one. + + Most properties of a collection can be configured per-element. Therefore, + Collections have "plural" versions of many of the properties of a `.Patch` + (e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are + the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties, + which can only be set globally for the whole collection. + + Besides these exceptions, all properties can be specified as single values + (applying to all elements) or sequences of values. The property of the + ``i``\th element of the collection is:: + + prop[i % len(prop)] + + Each Collection can optionally be used as its own `.ScalarMappable` by + passing the *norm* and *cmap* parameters to its constructor. If the + Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call + to `.Collection.set_array`), then at draw time this internal scalar + mappable will be used to set the ``facecolors`` and ``edgecolors``, + ignoring those that were manually passed in. + """ + #: Either a list of 3x3 arrays or an Nx3x3 array (representing N + #: transforms), suitable for the `all_transforms` argument to + #: `~matplotlib.backend_bases.RendererBase.draw_path_collection`; + #: each 3x3 array is used to initialize an + #: `~matplotlib.transforms.Affine2D` object. + #: Each kind of collection defines this based on its arguments. + _transforms = np.empty((0, 3, 3)) + + # Whether to draw an edge by default. Set on a + # subclass-by-subclass basis. + _edge_default = False + + @_docstring.interpd + def __init__(self, *, + edgecolors=None, + facecolors=None, + linewidths=None, + linestyles='solid', + capstyle=None, + joinstyle=None, + antialiaseds=None, + offsets=None, + offset_transform=None, + norm=None, # optional for ScalarMappable + cmap=None, # ditto + colorizer=None, + pickradius=5.0, + hatch=None, + urls=None, + zorder=1, + **kwargs + ): + """ + Parameters + ---------- + edgecolors : :mpltype:`color` or list of colors, default: :rc:`patch.edgecolor` + Edge color for each patch making up the collection. The special + value 'face' can be passed to make the edgecolor match the + facecolor. + facecolors : :mpltype:`color` or list of colors, default: :rc:`patch.facecolor` + Face color for each patch making up the collection. + linewidths : float or list of floats, default: :rc:`patch.linewidth` + Line width for each patch making up the collection. + linestyles : str or tuple or list thereof, default: 'solid' + Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', + '--', '-.', ':']. Dash tuples should be of the form:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink lengths + in points. For examples, see + :doc:`/gallery/lines_bars_and_markers/linestyles`. + capstyle : `.CapStyle`-like, default: 'butt' + Style to use for capping lines for all paths in the collection. + Allowed values are %(CapStyle)s. + joinstyle : `.JoinStyle`-like, default: 'round' + Style to use for joining lines for all paths in the collection. + Allowed values are %(JoinStyle)s. + antialiaseds : bool or list of bool, default: :rc:`patch.antialiased` + Whether each patch in the collection should be drawn with + antialiasing. + offsets : (float, float) or list thereof, default: (0, 0) + A vector by which to translate each patch after rendering (default + is no translation). The translation is performed in screen (pixel) + coordinates (i.e. after the Artist's transform is applied). + offset_transform : `~.Transform`, default: `.IdentityTransform` + A single transform which will be applied to each *offsets* vector + before it is used. + cmap, norm + Data normalization and colormapping parameters. See + `.ScalarMappable` for a detailed description. + hatch : str, optional + Hatching pattern to use in filled paths, if any. Valid strings are + ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See + :doc:`/gallery/shapes_and_collections/hatch_style_reference` for + the meaning of each hatch type. + pickradius : float, default: 5.0 + If ``pickradius <= 0``, then `.Collection.contains` will return + ``True`` whenever the test point is inside of one of the polygons + formed by the control points of a Path in the Collection. On the + other hand, if it is greater than 0, then we instead check if the + test point is contained in a stroke of width ``2*pickradius`` + following any of the Paths in the Collection. + urls : list of str, default: None + A URL for each patch to link to once drawn. Currently only works + for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for + examples. + zorder : float, default: 1 + The drawing order, shared by all Patches in the Collection. See + :doc:`/gallery/misc/zorder_demo` for all defaults and examples. + **kwargs + Remaining keyword arguments will be used to set properties as + ``Collection.set_{key}(val)`` for each key-value pair in *kwargs*. + """ + + super().__init__(self._get_colorizer(cmap, norm, colorizer)) + # list of un-scaled dash patterns + # this is needed scaling the dash pattern by linewidth + self._us_linestyles = [(0, None)] + # list of dash patterns + self._linestyles = [(0, None)] + # list of unbroadcast/scaled linewidths + self._us_lw = [0] + self._linewidths = [0] + + self._gapcolor = None # Currently only used by LineCollection. + + # Flags set by _set_mappable_flags: are colors from mapping an array? + self._face_is_mapped = None + self._edge_is_mapped = None + self._mapped_colors = None # calculated in update_scalarmappable + self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color']) + self._hatch_linewidth = mpl.rcParams['hatch.linewidth'] + self.set_facecolor(facecolors) + self.set_edgecolor(edgecolors) + self.set_linewidth(linewidths) + self.set_linestyle(linestyles) + self.set_antialiased(antialiaseds) + self.set_pickradius(pickradius) + self.set_urls(urls) + self.set_hatch(hatch) + self.set_zorder(zorder) + + if capstyle: + self.set_capstyle(capstyle) + else: + self._capstyle = None + + if joinstyle: + self.set_joinstyle(joinstyle) + else: + self._joinstyle = None + + if offsets is not None: + offsets = np.asanyarray(offsets, float) + # Broadcast (2,) -> (1, 2) but nothing else. + if offsets.shape == (2,): + offsets = offsets[None, :] + + self._offsets = offsets + self._offset_transform = offset_transform + + self._path_effects = None + self._internal_update(kwargs) + self._paths = None + + def get_paths(self): + return self._paths + + def set_paths(self, paths): + self._paths = paths + self.stale = True + + def get_transforms(self): + return self._transforms + + def get_offset_transform(self): + """Return the `.Transform` instance used by this artist offset.""" + if self._offset_transform is None: + self._offset_transform = transforms.IdentityTransform() + elif (not isinstance(self._offset_transform, transforms.Transform) + and hasattr(self._offset_transform, '_as_mpl_transform')): + self._offset_transform = \ + self._offset_transform._as_mpl_transform(self.axes) + return self._offset_transform + + def set_offset_transform(self, offset_transform): + """ + Set the artist offset transform. + + Parameters + ---------- + offset_transform : `.Transform` + """ + self._offset_transform = offset_transform + + def get_datalim(self, transData): + # Calculate the data limits and return them as a `.Bbox`. + # + # This operation depends on the transforms for the data in the + # collection and whether the collection has offsets: + # + # 1. offsets = None, transform child of transData: use the paths for + # the automatic limits (i.e. for LineCollection in streamline). + # 2. offsets != None: offset_transform is child of transData: + # + # a. transform is child of transData: use the path + offset for + # limits (i.e for bar). + # b. transform is not a child of transData: just use the offsets + # for the limits (i.e. for scatter) + # + # 3. otherwise return a null Bbox. + + transform = self.get_transform() + offset_trf = self.get_offset_transform() + if not (isinstance(offset_trf, transforms.IdentityTransform) + or offset_trf.contains_branch(transData)): + # if the offsets are in some coords other than data, + # then don't use them for autoscaling. + return transforms.Bbox.null() + + paths = self.get_paths() + if not len(paths): + # No paths to transform + return transforms.Bbox.null() + + if not transform.is_affine: + paths = [transform.transform_path_non_affine(p) for p in paths] + # Don't convert transform to transform.get_affine() here because + # we may have transform.contains_branch(transData) but not + # transforms.get_affine().contains_branch(transData). But later, + # be careful to only apply the affine part that remains. + + offsets = self.get_offsets() + + if any(transform.contains_branch_seperately(transData)): + # collections that are just in data units (like quiver) + # can properly have the axes limits set by their shape + + # offset. LineCollections that have no offsets can + # also use this algorithm (like streamplot). + if isinstance(offsets, np.ma.MaskedArray): + offsets = offsets.filled(np.nan) + # get_path_collection_extents handles nan but not masked arrays + return mpath.get_path_collection_extents( + transform.get_affine() - transData, paths, + self.get_transforms(), + offset_trf.transform_non_affine(offsets), + offset_trf.get_affine().frozen()) + + # NOTE: None is the default case where no offsets were passed in + if self._offsets is not None: + # this is for collections that have their paths (shapes) + # in physical, axes-relative, or figure-relative units + # (i.e. like scatter). We can't uniquely set limits based on + # those shapes, so we just set the limits based on their + # location. + offsets = (offset_trf - transData).transform(offsets) + # note A-B means A B^{-1} + offsets = np.ma.masked_invalid(offsets) + if not offsets.mask.all(): + bbox = transforms.Bbox.null() + bbox.update_from_data_xy(offsets) + return bbox + return transforms.Bbox.null() + + def get_window_extent(self, renderer=None): + # TODO: check to ensure that this does not fail for + # cases other than scatter plot legend + return self.get_datalim(transforms.IdentityTransform()) + + def _prepare_points(self): + # Helper for drawing and hit testing. + + transform = self.get_transform() + offset_trf = self.get_offset_transform() + offsets = self.get_offsets() + paths = self.get_paths() + + if self.have_units(): + paths = [] + for path in self.get_paths(): + vertices = path.vertices + xs, ys = vertices[:, 0], vertices[:, 1] + xs = self.convert_xunits(xs) + ys = self.convert_yunits(ys) + paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes)) + xs = self.convert_xunits(offsets[:, 0]) + ys = self.convert_yunits(offsets[:, 1]) + offsets = np.ma.column_stack([xs, ys]) + + if not transform.is_affine: + paths = [transform.transform_path_non_affine(path) + for path in paths] + transform = transform.get_affine() + if not offset_trf.is_affine: + offsets = offset_trf.transform_non_affine(offsets) + # This might have changed an ndarray into a masked array. + offset_trf = offset_trf.get_affine() + + if isinstance(offsets, np.ma.MaskedArray): + offsets = offsets.filled(np.nan) + # Changing from a masked array to nan-filled ndarray + # is probably most efficient at this point. + + return transform, offset_trf, offsets, paths + + @artist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + renderer.open_group(self.__class__.__name__, self.get_gid()) + + self.update_scalarmappable() + + transform, offset_trf, offsets, paths = self._prepare_points() + + gc = renderer.new_gc() + self._set_gc_clip(gc) + gc.set_snap(self.get_snap()) + + if self._hatch: + gc.set_hatch(self._hatch) + gc.set_hatch_color(self._hatch_color) + gc.set_hatch_linewidth(self._hatch_linewidth) + + if self.get_sketch_params() is not None: + gc.set_sketch_params(*self.get_sketch_params()) + + if self.get_path_effects(): + from matplotlib.patheffects import PathEffectRenderer + renderer = PathEffectRenderer(self.get_path_effects(), renderer) + + # If the collection is made up of a single shape/color/stroke, + # it can be rendered once and blitted multiple times, using + # `draw_markers` rather than `draw_path_collection`. This is + # *much* faster for Agg, and results in smaller file sizes in + # PDF/SVG/PS. + + trans = self.get_transforms() + facecolors = self.get_facecolor() + edgecolors = self.get_edgecolor() + do_single_path_optimization = False + if (len(paths) == 1 and len(trans) <= 1 and + len(facecolors) == 1 and len(edgecolors) == 1 and + len(self._linewidths) == 1 and + all(ls[1] is None for ls in self._linestyles) and + len(self._antialiaseds) == 1 and len(self._urls) == 1 and + self.get_hatch() is None): + if len(trans): + combined_transform = transforms.Affine2D(trans[0]) + transform + else: + combined_transform = transform + extents = paths[0].get_extents(combined_transform) + if (extents.width < self.get_figure(root=True).bbox.width + and extents.height < self.get_figure(root=True).bbox.height): + do_single_path_optimization = True + + if self._joinstyle: + gc.set_joinstyle(self._joinstyle) + + if self._capstyle: + gc.set_capstyle(self._capstyle) + + if do_single_path_optimization: + gc.set_foreground(tuple(edgecolors[0])) + gc.set_linewidth(self._linewidths[0]) + gc.set_dashes(*self._linestyles[0]) + gc.set_antialiased(self._antialiaseds[0]) + gc.set_url(self._urls[0]) + renderer.draw_markers( + gc, paths[0], combined_transform.frozen(), + mpath.Path(offsets), offset_trf, tuple(facecolors[0])) + else: + if self._gapcolor is not None: + # First draw paths within the gaps. + ipaths, ilinestyles = self._get_inverse_paths_linestyles() + renderer.draw_path_collection( + gc, transform.frozen(), ipaths, + self.get_transforms(), offsets, offset_trf, + [mcolors.to_rgba("none")], self._gapcolor, + self._linewidths, ilinestyles, + self._antialiaseds, self._urls, + "screen") + + renderer.draw_path_collection( + gc, transform.frozen(), paths, + self.get_transforms(), offsets, offset_trf, + self.get_facecolor(), self.get_edgecolor(), + self._linewidths, self._linestyles, + self._antialiaseds, self._urls, + "screen") # offset_position, kept for backcompat. + + gc.restore() + renderer.close_group(self.__class__.__name__) + self.stale = False + + def set_pickradius(self, pickradius): + """ + Set the pick radius used for containment tests. + + Parameters + ---------- + pickradius : float + Pick radius, in points. + """ + if not isinstance(pickradius, Real): + raise ValueError( + f"pickradius must be a real-valued number, not {pickradius!r}") + self._pickradius = pickradius + + def get_pickradius(self): + return self._pickradius + + def contains(self, mouseevent): + """ + Test whether the mouse event occurred in the collection. + + Returns ``bool, dict(ind=itemlist)``, where every item in itemlist + contains the event. + """ + if self._different_canvas(mouseevent) or not self.get_visible(): + return False, {} + pickradius = ( + float(self._picker) + if isinstance(self._picker, Number) and + self._picker is not True # the bool, not just nonzero or 1 + else self._pickradius) + if self.axes: + self.axes._unstale_viewLim() + transform, offset_trf, offsets, paths = self._prepare_points() + # Tests if the point is contained on one of the polygons formed + # by the control points of each of the paths. A point is considered + # "on" a path if it would lie within a stroke of width 2*pickradius + # following the path. If pickradius <= 0, then we instead simply check + # if the point is *inside* of the path instead. + ind = _path.point_in_path_collection( + mouseevent.x, mouseevent.y, pickradius, + transform.frozen(), paths, self.get_transforms(), + offsets, offset_trf, pickradius <= 0) + return len(ind) > 0, dict(ind=ind) + + def set_urls(self, urls): + """ + Parameters + ---------- + urls : list of str or None + + Notes + ----- + URLs are currently only implemented by the SVG backend. They are + ignored by all other backends. + """ + self._urls = urls if urls is not None else [None] + self.stale = True + + def get_urls(self): + """ + Return a list of URLs, one for each element of the collection. + + The list contains *None* for elements without a URL. See + :doc:`/gallery/misc/hyperlinks_sgskip` for an example. + """ + return self._urls + + def set_hatch(self, hatch): + r""" + Set the hatching pattern + + *hatch* can be one of:: + + / - diagonal hatching + \ - back diagonal + | - vertical + - - horizontal + + - crossed + x - crossed diagonal + o - small circle + O - large circle + . - dots + * - stars + + Letters can be combined, in which case all the specified + hatchings are done. If same letter repeats, it increases the + density of hatching of that pattern. + + Unlike other properties such as linewidth and colors, hatching + can only be specified for the collection as a whole, not separately + for each member. + + Parameters + ---------- + hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} + """ + # Use validate_hatch(list) after deprecation. + mhatch._validate_hatch_pattern(hatch) + self._hatch = hatch + self.stale = True + + def get_hatch(self): + """Return the current hatching pattern.""" + return self._hatch + + def set_hatch_linewidth(self, lw): + """Set the hatch linewidth.""" + self._hatch_linewidth = lw + + def get_hatch_linewidth(self): + """Return the hatch linewidth.""" + return self._hatch_linewidth + + def set_offsets(self, offsets): + """ + Set the offsets for the collection. + + Parameters + ---------- + offsets : (N, 2) or (2,) array-like + """ + offsets = np.asanyarray(offsets) + if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else. + offsets = offsets[None, :] + cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray) + else np.column_stack) + self._offsets = cstack( + (np.asanyarray(self.convert_xunits(offsets[:, 0]), float), + np.asanyarray(self.convert_yunits(offsets[:, 1]), float))) + self.stale = True + + def get_offsets(self): + """Return the offsets for the collection.""" + # Default to zeros in the no-offset (None) case + return np.zeros((1, 2)) if self._offsets is None else self._offsets + + def _get_default_linewidth(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.linewidth'] # validated as float + + def set_linewidth(self, lw): + """ + Set the linewidth(s) for the collection. *lw* can be a scalar + or a sequence; if it is a sequence the patches will cycle + through the sequence + + Parameters + ---------- + lw : float or list of floats + """ + if lw is None: + lw = self._get_default_linewidth() + # get the un-scaled/broadcast lw + self._us_lw = np.atleast_1d(lw) + + # scale all of the dash patterns. + self._linewidths, self._linestyles = self._bcast_lwls( + self._us_lw, self._us_linestyles) + self.stale = True + + def set_linestyle(self, ls): + """ + Set the linestyle(s) for the collection. + + =========================== ================= + linestyle description + =========================== ================= + ``'-'`` or ``'solid'`` solid line + ``'--'`` or ``'dashed'`` dashed line + ``'-.'`` or ``'dashdot'`` dash-dotted line + ``':'`` or ``'dotted'`` dotted line + =========================== ================= + + Alternatively a dash tuple of the following form can be provided:: + + (offset, onoffseq), + + where ``onoffseq`` is an even length tuple of on and off ink in points. + + Parameters + ---------- + ls : str or tuple or list thereof + Valid values for individual linestyles include {'-', '--', '-.', + ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a + complete description. + """ + try: + dashes = [mlines._get_dash_pattern(ls)] + except ValueError: + try: + dashes = [mlines._get_dash_pattern(x) for x in ls] + except ValueError as err: + emsg = f'Do not know how to convert {ls!r} to dashes' + raise ValueError(emsg) from err + + # get the list of raw 'unscaled' dash patterns + self._us_linestyles = dashes + + # broadcast and scale the lw and dash patterns + self._linewidths, self._linestyles = self._bcast_lwls( + self._us_lw, self._us_linestyles) + + @_docstring.interpd + def set_capstyle(self, cs): + """ + Set the `.CapStyle` for the collection (for all its elements). + + Parameters + ---------- + cs : `.CapStyle` or %(CapStyle)s + """ + self._capstyle = CapStyle(cs) + + @_docstring.interpd + def get_capstyle(self): + """ + Return the cap style for the collection (for all its elements). + + Returns + ------- + %(CapStyle)s or None + """ + return self._capstyle.name if self._capstyle else None + + @_docstring.interpd + def set_joinstyle(self, js): + """ + Set the `.JoinStyle` for the collection (for all its elements). + + Parameters + ---------- + js : `.JoinStyle` or %(JoinStyle)s + """ + self._joinstyle = JoinStyle(js) + + @_docstring.interpd + def get_joinstyle(self): + """ + Return the join style for the collection (for all its elements). + + Returns + ------- + %(JoinStyle)s or None + """ + return self._joinstyle.name if self._joinstyle else None + + @staticmethod + def _bcast_lwls(linewidths, dashes): + """ + Internal helper function to broadcast + scale ls/lw + + In the collection drawing code, the linewidth and linestyle are cycled + through as circular buffers (via ``v[i % len(v)]``). Thus, if we are + going to scale the dash pattern at set time (not draw time) we need to + do the broadcasting now and expand both lists to be the same length. + + Parameters + ---------- + linewidths : list + line widths of collection + dashes : list + dash specification (offset, (dash pattern tuple)) + + Returns + ------- + linewidths, dashes : list + Will be the same length, dashes are scaled by paired linewidth + """ + if mpl.rcParams['_internal.classic_mode']: + return linewidths, dashes + # make sure they are the same length so we can zip them + if len(dashes) != len(linewidths): + l_dashes = len(dashes) + l_lw = len(linewidths) + gcd = math.gcd(l_dashes, l_lw) + dashes = list(dashes) * (l_lw // gcd) + linewidths = list(linewidths) * (l_dashes // gcd) + + # scale the dash patterns + dashes = [mlines._scale_dashes(o, d, lw) + for (o, d), lw in zip(dashes, linewidths)] + + return linewidths, dashes + + def get_antialiased(self): + """ + Get the antialiasing state for rendering. + + Returns + ------- + array of bools + """ + return self._antialiaseds + + def set_antialiased(self, aa): + """ + Set the antialiasing state for rendering. + + Parameters + ---------- + aa : bool or list of bools + """ + if aa is None: + aa = self._get_default_antialiased() + self._antialiaseds = np.atleast_1d(np.asarray(aa, bool)) + self.stale = True + + def _get_default_antialiased(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.antialiased'] + + def set_color(self, c): + """ + Set both the edgecolor and the facecolor. + + Parameters + ---------- + c : :mpltype:`color` or list of RGBA tuples + + See Also + -------- + Collection.set_facecolor, Collection.set_edgecolor + For setting the edge or face color individually. + """ + self.set_facecolor(c) + self.set_edgecolor(c) + + def _get_default_facecolor(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.facecolor'] + + def _set_facecolor(self, c): + if c is None: + c = self._get_default_facecolor() + + self._facecolors = mcolors.to_rgba_array(c, self._alpha) + self.stale = True + + def set_facecolor(self, c): + """ + Set the facecolor(s) of the collection. *c* can be a color (all patches + have same color), or a sequence of colors; if it is a sequence the + patches will cycle through the sequence. + + If *c* is 'none', the patch will not be filled. + + Parameters + ---------- + c : :mpltype:`color` or list of :mpltype:`color` + """ + if isinstance(c, str) and c.lower() in ("none", "face"): + c = c.lower() + self._original_facecolor = c + self._set_facecolor(c) + + def get_facecolor(self): + return self._facecolors + + def get_edgecolor(self): + if cbook._str_equal(self._edgecolors, 'face'): + return self.get_facecolor() + else: + return self._edgecolors + + def _get_default_edgecolor(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.edgecolor'] + + def _set_edgecolor(self, c): + set_hatch_color = True + if c is None: + if (mpl.rcParams['patch.force_edgecolor'] + or self._edge_default + or cbook._str_equal(self._original_facecolor, 'none')): + c = self._get_default_edgecolor() + else: + c = 'none' + set_hatch_color = False + if cbook._str_lower_equal(c, 'face'): + self._edgecolors = 'face' + self.stale = True + return + self._edgecolors = mcolors.to_rgba_array(c, self._alpha) + if set_hatch_color and len(self._edgecolors): + self._hatch_color = tuple(self._edgecolors[0]) + self.stale = True + + def set_edgecolor(self, c): + """ + Set the edgecolor(s) of the collection. + + Parameters + ---------- + c : :mpltype:`color` or list of :mpltype:`color` or 'face' + The collection edgecolor(s). If a sequence, the patches cycle + through it. If 'face', match the facecolor. + """ + # We pass through a default value for use in LineCollection. + # This allows us to maintain None as the default indicator in + # _original_edgecolor. + if isinstance(c, str) and c.lower() in ("none", "face"): + c = c.lower() + self._original_edgecolor = c + self._set_edgecolor(c) + + def set_alpha(self, alpha): + """ + Set the transparency of the collection. + + Parameters + ---------- + alpha : float or array of float or None + If not None, *alpha* values must be between 0 and 1, inclusive. + If an array is provided, its length must match the number of + elements in the collection. Masked values and nans are not + supported. + """ + artist.Artist._set_alpha_for_array(self, alpha) + self._set_facecolor(self._original_facecolor) + self._set_edgecolor(self._original_edgecolor) + + set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__ + + def get_linewidth(self): + return self._linewidths + + def get_linestyle(self): + return self._linestyles + + def _set_mappable_flags(self): + """ + Determine whether edges and/or faces are color-mapped. + + This is a helper for update_scalarmappable. + It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'. + + Returns + ------- + mapping_change : bool + True if either flag is True, or if a flag has changed. + """ + # The flags are initialized to None to ensure this returns True + # the first time it is called. + edge0 = self._edge_is_mapped + face0 = self._face_is_mapped + # After returning, the flags must be Booleans, not None. + self._edge_is_mapped = False + self._face_is_mapped = False + if self._A is not None: + if not cbook._str_equal(self._original_facecolor, 'none'): + self._face_is_mapped = True + if cbook._str_equal(self._original_edgecolor, 'face'): + self._edge_is_mapped = True + else: + if self._original_edgecolor is None: + self._edge_is_mapped = True + + mapped = self._face_is_mapped or self._edge_is_mapped + changed = (edge0 is None or face0 is None + or self._edge_is_mapped != edge0 + or self._face_is_mapped != face0) + return mapped or changed + + def update_scalarmappable(self): + """ + Update colors from the scalar mappable array, if any. + + Assign colors to edges and faces based on the array and/or + colors that were directly set, as appropriate. + """ + if not self._set_mappable_flags(): + return + # Allow possibility to call 'self.set_array(None)'. + if self._A is not None: + # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array) + if self._A.ndim > 1 and not isinstance(self, _MeshData): + raise ValueError('Collections can only map rank 1 arrays') + if np.iterable(self._alpha): + if self._alpha.size != self._A.size: + raise ValueError( + f'Data array shape, {self._A.shape} ' + 'is incompatible with alpha array shape, ' + f'{self._alpha.shape}. ' + 'This can occur with the deprecated ' + 'behavior of the "flat" shading option, ' + 'in which a row and/or column of the data ' + 'array is dropped.') + # pcolormesh, scatter, maybe others flatten their _A + self._alpha = self._alpha.reshape(self._A.shape) + self._mapped_colors = self.to_rgba(self._A, self._alpha) + + if self._face_is_mapped: + self._facecolors = self._mapped_colors + else: + self._set_facecolor(self._original_facecolor) + if self._edge_is_mapped: + self._edgecolors = self._mapped_colors + else: + self._set_edgecolor(self._original_edgecolor) + self.stale = True + + def get_fill(self): + """Return whether face is colored.""" + return not cbook._str_lower_equal(self._original_facecolor, "none") + + def update_from(self, other): + """Copy properties from other to self.""" + + artist.Artist.update_from(self, other) + self._antialiaseds = other._antialiaseds + self._mapped_colors = other._mapped_colors + self._edge_is_mapped = other._edge_is_mapped + self._original_edgecolor = other._original_edgecolor + self._edgecolors = other._edgecolors + self._face_is_mapped = other._face_is_mapped + self._original_facecolor = other._original_facecolor + self._facecolors = other._facecolors + self._linewidths = other._linewidths + self._linestyles = other._linestyles + self._us_linestyles = other._us_linestyles + self._pickradius = other._pickradius + self._hatch = other._hatch + + # update_from for scalarmappable + self._A = other._A + self.norm = other.norm + self.cmap = other.cmap + self.stale = True + + +class _CollectionWithSizes(Collection): + """ + Base class for collections that have an array of sizes. + """ + _factor = 1.0 + + def get_sizes(self): + """ + Return the sizes ('areas') of the elements in the collection. + + Returns + ------- + array + The 'area' of each element. + """ + return self._sizes + + def set_sizes(self, sizes, dpi=72.0): + """ + Set the sizes of each member of the collection. + + Parameters + ---------- + sizes : `numpy.ndarray` or None + The size to set for each element of the collection. The + value is the 'area' of the element. + dpi : float, default: 72 + The dpi of the canvas. + """ + if sizes is None: + self._sizes = np.array([]) + self._transforms = np.empty((0, 3, 3)) + else: + self._sizes = np.asarray(sizes) + self._transforms = np.zeros((len(self._sizes), 3, 3)) + scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor + self._transforms[:, 0, 0] = scale + self._transforms[:, 1, 1] = scale + self._transforms[:, 2, 2] = 1.0 + self.stale = True + + @artist.allow_rasterization + def draw(self, renderer): + self.set_sizes(self._sizes, self.get_figure(root=True).dpi) + super().draw(renderer) + + +class PathCollection(_CollectionWithSizes): + r""" + A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`. + """ + + def __init__(self, paths, sizes=None, **kwargs): + """ + Parameters + ---------- + paths : list of `.path.Path` + The paths that will make up the `.Collection`. + sizes : array-like + The factor by which to scale each drawn `~.path.Path`. One unit + squared in the Path's data space is scaled to be ``sizes**2`` + points when rendered. + **kwargs + Forwarded to `.Collection`. + """ + + super().__init__(**kwargs) + self.set_paths(paths) + self.set_sizes(sizes) + self.stale = True + + def get_paths(self): + return self._paths + + def legend_elements(self, prop="colors", num="auto", + fmt=None, func=lambda x: x, **kwargs): + """ + Create legend handles and labels for a PathCollection. + + Each legend handle is a `.Line2D` representing the Path that was drawn, + and each label is a string that represents the Path. + + This is useful for obtaining a legend for a `~.Axes.scatter` plot; + e.g.:: + + scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3], num=None) + plt.legend(*scatter.legend_elements()) + + creates three legend elements, one for each color with the numerical + values passed to *c* as the labels. + + Also see the :ref:`automatedlegendcreation` example. + + Parameters + ---------- + prop : {"colors", "sizes"}, default: "colors" + If "colors", the legend handles will show the different colors of + the collection. If "sizes", the legend will show the different + sizes. To set both, use *kwargs* to directly edit the `.Line2D` + properties. + num : int, None, "auto" (default), array-like, or `~.ticker.Locator` + Target number of elements to create. + If None, use all unique elements of the mappable array. If an + integer, target to use *num* elements in the normed range. + If *"auto"*, try to determine which option better suits the nature + of the data. + The number of created elements may slightly deviate from *num* due + to a `~.ticker.Locator` being used to find useful locations. + If a list or array, use exactly those elements for the legend. + Finally, a `~.ticker.Locator` can be provided. + fmt : str, `~matplotlib.ticker.Formatter`, or None (default) + The format or formatter to use for the labels. If a string must be + a valid input for a `.StrMethodFormatter`. If None (the default), + use a `.ScalarFormatter`. + func : function, default: ``lambda x: x`` + Function to calculate the labels. Often the size (or color) + argument to `~.Axes.scatter` will have been pre-processed by the + user using a function ``s = f(x)`` to make the markers visible; + e.g. ``size = np.log10(x)``. Providing the inverse of this + function here allows that pre-processing to be inverted, so that + the legend labels have the correct values; e.g. ``func = lambda + x: 10**x``. + **kwargs + Allowed keyword arguments are *color* and *size*. E.g. it may be + useful to set the color of the markers if *prop="sizes"* is used; + similarly to set the size of the markers if *prop="colors"* is + used. Any further parameters are passed onto the `.Line2D` + instance. This may be useful to e.g. specify a different + *markeredgecolor* or *alpha* for the legend handles. + + Returns + ------- + handles : list of `.Line2D` + Visual representation of each element of the legend. + labels : list of str + The string labels for elements of the legend. + """ + handles = [] + labels = [] + hasarray = self.get_array() is not None + if fmt is None: + fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True) + elif isinstance(fmt, str): + fmt = mpl.ticker.StrMethodFormatter(fmt) + fmt.create_dummy_axis() + + if prop == "colors": + if not hasarray: + warnings.warn("Collection without array used. Make sure to " + "specify the values to be colormapped via the " + "`c` argument.") + return handles, labels + u = np.unique(self.get_array()) + size = kwargs.pop("size", mpl.rcParams["lines.markersize"]) + elif prop == "sizes": + u = np.unique(self.get_sizes()) + color = kwargs.pop("color", "k") + else: + raise ValueError("Valid values for `prop` are 'colors' or " + f"'sizes'. You supplied '{prop}' instead.") + + fu = func(u) + fmt.axis.set_view_interval(fu.min(), fu.max()) + fmt.axis.set_data_interval(fu.min(), fu.max()) + if num == "auto": + num = 9 + if len(u) <= num: + num = None + if num is None: + values = u + label_values = func(values) + else: + if prop == "colors": + arr = self.get_array() + elif prop == "sizes": + arr = self.get_sizes() + if isinstance(num, mpl.ticker.Locator): + loc = num + elif np.iterable(num): + loc = mpl.ticker.FixedLocator(num) + else: + num = int(num) + loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1, + steps=[1, 2, 2.5, 3, 5, 6, 8, 10]) + label_values = loc.tick_values(func(arr).min(), func(arr).max()) + cond = ((label_values >= func(arr).min()) & + (label_values <= func(arr).max())) + label_values = label_values[cond] + yarr = np.linspace(arr.min(), arr.max(), 256) + xarr = func(yarr) + ix = np.argsort(xarr) + values = np.interp(label_values, xarr[ix], yarr[ix]) + + kw = {"markeredgewidth": self.get_linewidths()[0], + "alpha": self.get_alpha(), + **kwargs} + + for val, lab in zip(values, label_values): + if prop == "colors": + color = self.cmap(self.norm(val)) + elif prop == "sizes": + size = np.sqrt(val) + if np.isclose(size, 0.0): + continue + h = mlines.Line2D([0], [0], ls="", color=color, ms=size, + marker=self.get_paths()[0], **kw) + handles.append(h) + if hasattr(fmt, "set_locs"): + fmt.set_locs(label_values) + l = fmt(lab) + labels.append(l) + + return handles, labels + + +class PolyCollection(_CollectionWithSizes): + + def __init__(self, verts, sizes=None, *, closed=True, **kwargs): + """ + Parameters + ---------- + verts : list of array-like + The sequence of polygons [*verts0*, *verts1*, ...] where each + element *verts_i* defines the vertices of polygon *i* as a 2D + array-like of shape (M, 2). + sizes : array-like, default: None + Squared scaling factors for the polygons. The coordinates of each + polygon *verts_i* are multiplied by the square-root of the + corresponding entry in *sizes* (i.e., *sizes* specify the scaling + of areas). The scaling is applied before the Artist master + transform. + closed : bool, default: True + Whether the polygon should be closed by adding a CLOSEPOLY + connection at the end. + **kwargs + Forwarded to `.Collection`. + """ + super().__init__(**kwargs) + self.set_sizes(sizes) + self.set_verts(verts, closed) + self.stale = True + + def set_verts(self, verts, closed=True): + """ + Set the vertices of the polygons. + + Parameters + ---------- + verts : list of array-like + The sequence of polygons [*verts0*, *verts1*, ...] where each + element *verts_i* defines the vertices of polygon *i* as a 2D + array-like of shape (M, 2). + closed : bool, default: True + Whether the polygon should be closed by adding a CLOSEPOLY + connection at the end. + """ + self.stale = True + if isinstance(verts, np.ma.MaskedArray): + verts = verts.astype(float).filled(np.nan) + + # No need to do anything fancy if the path isn't closed. + if not closed: + self._paths = [mpath.Path(xy) for xy in verts] + return + + # Fast path for arrays + if isinstance(verts, np.ndarray) and len(verts.shape) == 3: + verts_pad = np.concatenate((verts, verts[:, :1]), axis=1) + # Creating the codes once is much faster than having Path do it + # separately each time by passing closed=True. + codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type) + codes[:] = mpath.Path.LINETO + codes[0] = mpath.Path.MOVETO + codes[-1] = mpath.Path.CLOSEPOLY + self._paths = [mpath.Path(xy, codes) for xy in verts_pad] + return + + self._paths = [] + for xy in verts: + if len(xy): + self._paths.append(mpath.Path._create_closed(xy)) + else: + self._paths.append(mpath.Path(xy)) + + set_paths = set_verts + + def set_verts_and_codes(self, verts, codes): + """Initialize vertices with path codes.""" + if len(verts) != len(codes): + raise ValueError("'codes' must be a 1D list or array " + "with the same length of 'verts'") + self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy) + for xy, cds in zip(verts, codes)] + self.stale = True + + +class FillBetweenPolyCollection(PolyCollection): + """ + `.PolyCollection` that fills the area between two x- or y-curves. + """ + def __init__( + self, t_direction, t, f1, f2, *, + where=None, interpolate=False, step=None, **kwargs): + """ + Parameters + ---------- + t_direction : {{'x', 'y'}} + The axes on which the variable lies. + + - 'x': the curves are ``(t, f1)`` and ``(t, f2)``. + - 'y': the curves are ``(f1, t)`` and ``(f2, t)``. + + t : array (length N) + The ``t_direction`` coordinates of the nodes defining the curves. + + f1 : array (length N) or scalar + The other coordinates of the nodes defining the first curve. + + f2 : array (length N) or scalar + The other coordinates of the nodes defining the second curve. + + where : array of bool (length N), optional + Define *where* to exclude some {dir} regions from being filled. + The filled regions are defined by the coordinates ``t[where]``. + More precisely, fill between ``t[i]`` and ``t[i+1]`` if + ``where[i] and where[i+1]``. Note that this definition implies + that an isolated *True* value between two *False* values in *where* + will not result in filling. Both sides of the *True* position + remain unfilled due to the adjacent *False* values. + + interpolate : bool, default: False + This option is only relevant if *where* is used and the two curves + are crossing each other. + + Semantically, *where* is often used for *f1* > *f2* or + similar. By default, the nodes of the polygon defining the filled + region will only be placed at the positions in the *t* array. + Such a polygon cannot describe the above semantics close to the + intersection. The t-sections containing the intersection are + simply clipped. + + Setting *interpolate* to *True* will calculate the actual + intersection point and extend the filled region up to this point. + + step : {{'pre', 'post', 'mid'}}, optional + Define *step* if the filling should be a step function, + i.e. constant in between *t*. The value determines where the + step will occur: + + - 'pre': The f value is continued constantly to the left from + every *t* position, i.e. the interval ``(t[i-1], t[i]]`` has the + value ``f[i]``. + - 'post': The y value is continued constantly to the right from + every *x* position, i.e. the interval ``[t[i], t[i+1])`` has the + value ``f[i]``. + - 'mid': Steps occur half-way between the *t* positions. + + **kwargs + Forwarded to `.PolyCollection`. + + See Also + -------- + .Axes.fill_between, .Axes.fill_betweenx + """ + self.t_direction = t_direction + self._interpolate = interpolate + self._step = step + verts = self._make_verts(t, f1, f2, where) + super().__init__(verts, **kwargs) + + @staticmethod + def _f_dir_from_t(t_direction): + """The direction that is other than `t_direction`.""" + if t_direction == "x": + return "y" + elif t_direction == "y": + return "x" + else: + msg = f"t_direction must be 'x' or 'y', got {t_direction!r}" + raise ValueError(msg) + + @property + def _f_direction(self): + """The direction that is other than `self.t_direction`.""" + return self._f_dir_from_t(self.t_direction) + + def set_data(self, t, f1, f2, *, where=None): + """ + Set new values for the two bounding curves. + + Parameters + ---------- + t : array (length N) + The ``self.t_direction`` coordinates of the nodes defining the curves. + + f1 : array (length N) or scalar + The other coordinates of the nodes defining the first curve. + + f2 : array (length N) or scalar + The other coordinates of the nodes defining the second curve. + + where : array of bool (length N), optional + Define *where* to exclude some {dir} regions from being filled. + The filled regions are defined by the coordinates ``t[where]``. + More precisely, fill between ``t[i]`` and ``t[i+1]`` if + ``where[i] and where[i+1]``. Note that this definition implies + that an isolated *True* value between two *False* values in *where* + will not result in filling. Both sides of the *True* position + remain unfilled due to the adjacent *False* values. + + See Also + -------- + .PolyCollection.set_verts, .Line2D.set_data + """ + t, f1, f2 = self.axes._fill_between_process_units( + self.t_direction, self._f_direction, t, f1, f2) + + verts = self._make_verts(t, f1, f2, where) + self.set_verts(verts) + + def get_datalim(self, transData): + """Calculate the data limits and return them as a `.Bbox`.""" + datalim = transforms.Bbox.null() + datalim.update_from_data_xy((self.get_transform() - transData).transform( + np.concatenate([self._bbox, [self._bbox.minpos]]))) + return datalim + + def _make_verts(self, t, f1, f2, where): + """ + Make verts that can be forwarded to `.PolyCollection`. + """ + self._validate_shapes(self.t_direction, self._f_direction, t, f1, f2) + + where = self._get_data_mask(t, f1, f2, where) + t, f1, f2 = np.broadcast_arrays(np.atleast_1d(t), f1, f2, subok=True) + + self._bbox = transforms.Bbox.null() + self._bbox.update_from_data_xy(self._fix_pts_xy_order(np.concatenate([ + np.stack((t[where], f[where]), axis=-1) for f in (f1, f2)]))) + + return [ + self._make_verts_for_region(t, f1, f2, idx0, idx1) + for idx0, idx1 in cbook.contiguous_regions(where) + ] + + def _get_data_mask(self, t, f1, f2, where): + """ + Return a bool array, with True at all points that should eventually be rendered. + + The array is True at a point if none of the data inputs + *t*, *f1*, *f2* is masked and if the input *where* is true at that point. + """ + if where is None: + where = True + else: + where = np.asarray(where, dtype=bool) + if where.size != t.size: + msg = "where size ({}) does not match {!r} size ({})".format( + where.size, self.t_direction, t.size) + raise ValueError(msg) + return where & ~functools.reduce( + np.logical_or, map(np.ma.getmaskarray, [t, f1, f2])) + + @staticmethod + def _validate_shapes(t_dir, f_dir, t, f1, f2): + """Validate that t, f1 and f2 are 1-dimensional and have the same length.""" + names = (d + s for d, s in zip((t_dir, f_dir, f_dir), ("", "1", "2"))) + for name, array in zip(names, [t, f1, f2]): + if array.ndim > 1: + raise ValueError(f"{name!r} is not 1-dimensional") + if t.size > 1 and array.size > 1 and t.size != array.size: + msg = "{!r} has size {}, but {!r} has an unequal size of {}".format( + t_dir, t.size, name, array.size) + raise ValueError(msg) + + def _make_verts_for_region(self, t, f1, f2, idx0, idx1): + """ + Make ``verts`` for a contiguous region between ``idx0`` and ``idx1``, taking + into account ``step`` and ``interpolate``. + """ + t_slice = t[idx0:idx1] + f1_slice = f1[idx0:idx1] + f2_slice = f2[idx0:idx1] + if self._step is not None: + step_func = cbook.STEP_LOOKUP_MAP["steps-" + self._step] + t_slice, f1_slice, f2_slice = step_func(t_slice, f1_slice, f2_slice) + + if self._interpolate: + start = self._get_interpolating_points(t, f1, f2, idx0) + end = self._get_interpolating_points(t, f1, f2, idx1) + else: + # Handle scalar f2 (e.g. 0): the fill should go all + # the way down to 0 even if none of the dep1 sample points do. + start = t_slice[0], f2_slice[0] + end = t_slice[-1], f2_slice[-1] + + pts = np.concatenate(( + np.asarray([start]), + np.stack((t_slice, f1_slice), axis=-1), + np.asarray([end]), + np.stack((t_slice, f2_slice), axis=-1)[::-1])) + + return self._fix_pts_xy_order(pts) + + @classmethod + def _get_interpolating_points(cls, t, f1, f2, idx): + """Calculate interpolating points.""" + im1 = max(idx - 1, 0) + t_values = t[im1:idx+1] + diff_values = f1[im1:idx+1] - f2[im1:idx+1] + f1_values = f1[im1:idx+1] + + if len(diff_values) == 2: + if np.ma.is_masked(diff_values[1]): + return t[im1], f1[im1] + elif np.ma.is_masked(diff_values[0]): + return t[idx], f1[idx] + + diff_root_t = cls._get_diff_root(0, diff_values, t_values) + diff_root_f = cls._get_diff_root(diff_root_t, t_values, f1_values) + return diff_root_t, diff_root_f + + @staticmethod + def _get_diff_root(x, xp, fp): + """Calculate diff root.""" + order = xp.argsort() + return np.interp(x, xp[order], fp[order]) + + def _fix_pts_xy_order(self, pts): + """ + Fix pts calculation results with `self.t_direction`. + + In the workflow, it is assumed that `self.t_direction` is 'x'. If this + is not true, we need to exchange the coordinates. + """ + return pts[:, ::-1] if self.t_direction == "y" else pts + + +class RegularPolyCollection(_CollectionWithSizes): + """A collection of n-sided regular polygons.""" + + _path_generator = mpath.Path.unit_regular_polygon + _factor = np.pi ** (-1/2) + + def __init__(self, + numsides, + *, + rotation=0, + sizes=(1,), + **kwargs): + """ + Parameters + ---------- + numsides : int + The number of sides of the polygon. + rotation : float + The rotation of the polygon in radians. + sizes : tuple of float + The area of the circle circumscribing the polygon in points^2. + **kwargs + Forwarded to `.Collection`. + + Examples + -------- + See :doc:`/gallery/event_handling/lasso_demo` for a complete example:: + + offsets = np.random.rand(20, 2) + facecolors = [cm.jet(x) for x in np.random.rand(20)] + + collection = RegularPolyCollection( + numsides=5, # a pentagon + rotation=0, sizes=(50,), + facecolors=facecolors, + edgecolors=("black",), + linewidths=(1,), + offsets=offsets, + offset_transform=ax.transData, + ) + """ + super().__init__(**kwargs) + self.set_sizes(sizes) + self._numsides = numsides + self._paths = [self._path_generator(numsides)] + self._rotation = rotation + self.set_transform(transforms.IdentityTransform()) + + def get_numsides(self): + return self._numsides + + def get_rotation(self): + return self._rotation + + @artist.allow_rasterization + def draw(self, renderer): + self.set_sizes(self._sizes, self.get_figure(root=True).dpi) + self._transforms = [ + transforms.Affine2D(x).rotate(-self._rotation).get_matrix() + for x in self._transforms + ] + # Explicitly not super().draw, because set_sizes must be called before + # updating self._transforms. + Collection.draw(self, renderer) + + +class StarPolygonCollection(RegularPolyCollection): + """Draw a collection of regular stars with *numsides* points.""" + _path_generator = mpath.Path.unit_regular_star + + +class AsteriskPolygonCollection(RegularPolyCollection): + """Draw a collection of regular asterisks with *numsides* points.""" + _path_generator = mpath.Path.unit_regular_asterisk + + +class LineCollection(Collection): + r""" + Represents a sequence of `.Line2D`\s that should be drawn together. + + This class extends `.Collection` to represent a sequence of + `.Line2D`\s instead of just a sequence of `.Patch`\s. + Just as in `.Collection`, each property of a *LineCollection* may be either + a single value or a list of values. This list is then used cyclically for + each element of the LineCollection, so the property of the ``i``\th element + of the collection is:: + + prop[i % len(prop)] + + The properties of each member of a *LineCollection* default to their values + in :rc:`lines.*` instead of :rc:`patch.*`, and the property *colors* is + added in place of *edgecolors*. + """ + + _edge_default = True + + def __init__(self, segments, # Can be None. + *, + zorder=2, # Collection.zorder is 1 + **kwargs + ): + """ + Parameters + ---------- + segments : list of (N, 2) array-like + A sequence ``[line0, line1, ...]`` where each line is a (N, 2)-shape + array-like containing points:: + + line0 = [(x0, y0), (x1, y1), ...] + + Each line can contain a different number of points. + linewidths : float or list of float, default: :rc:`lines.linewidth` + The width of each line in points. + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not + allowed). + antialiaseds : bool or list of bool, default: :rc:`lines.antialiased` + Whether to use antialiasing for each line. + zorder : float, default: 2 + zorder of the lines once drawn. + + facecolors : :mpltype:`color` or list of :mpltype:`color`, default: 'none' + When setting *facecolors*, each line is interpreted as a boundary + for an area, implicitly closing the path from the last point to the + first point. The enclosed area is filled with *facecolor*. + In order to manually specify what should count as the "interior" of + each line, please use `.PathCollection` instead, where the + "interior" can be specified by appropriate usage of + `~.path.Path.CLOSEPOLY`. + + **kwargs + Forwarded to `.Collection`. + """ + # Unfortunately, mplot3d needs this explicit setting of 'facecolors'. + kwargs.setdefault('facecolors', 'none') + super().__init__( + zorder=zorder, + **kwargs) + self.set_segments(segments) + + def set_segments(self, segments): + if segments is None: + return + + self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray) + else mpath.Path(np.asarray(seg, float)) + for seg in segments] + self.stale = True + + set_verts = set_segments # for compatibility with PolyCollection + set_paths = set_segments + + def get_segments(self): + """ + Returns + ------- + list + List of segments in the LineCollection. Each list item contains an + array of vertices. + """ + segments = [] + + for path in self._paths: + vertices = [ + vertex + for vertex, _ + # Never simplify here, we want to get the data-space values + # back and there in no way to know the "right" simplification + # threshold so never try. + in path.iter_segments(simplify=False) + ] + vertices = np.asarray(vertices) + segments.append(vertices) + + return segments + + def _get_default_linewidth(self): + return mpl.rcParams['lines.linewidth'] + + def _get_default_antialiased(self): + return mpl.rcParams['lines.antialiased'] + + def _get_default_edgecolor(self): + return mpl.rcParams['lines.color'] + + def _get_default_facecolor(self): + return 'none' + + def set_alpha(self, alpha): + # docstring inherited + super().set_alpha(alpha) + if self._gapcolor is not None: + self.set_gapcolor(self._original_gapcolor) + + def set_color(self, c): + """ + Set the edgecolor(s) of the LineCollection. + + Parameters + ---------- + c : :mpltype:`color` or list of :mpltype:`color` + Single color (all lines have same color), or a + sequence of RGBA tuples; if it is a sequence the lines will + cycle through the sequence. + """ + self.set_edgecolor(c) + + set_colors = set_color + + def get_color(self): + return self._edgecolors + + get_colors = get_color # for compatibility with old versions + + def set_gapcolor(self, gapcolor): + """ + Set a color to fill the gaps in the dashed line style. + + .. note:: + + Striped lines are created by drawing two interleaved dashed lines. + There can be overlaps between those two, which may result in + artifacts when using transparency. + + This functionality is experimental and may change. + + Parameters + ---------- + gapcolor : :mpltype:`color` or list of :mpltype:`color` or None + The color with which to fill the gaps. If None, the gaps are + unfilled. + """ + self._original_gapcolor = gapcolor + self._set_gapcolor(gapcolor) + + def _set_gapcolor(self, gapcolor): + if gapcolor is not None: + gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha) + self._gapcolor = gapcolor + self.stale = True + + def get_gapcolor(self): + return self._gapcolor + + def _get_inverse_paths_linestyles(self): + """ + Returns the path and pattern for the gaps in the non-solid lines. + + This path and pattern is the inverse of the path and pattern used to + construct the non-solid lines. For solid lines, we set the inverse path + to nans to prevent drawing an inverse line. + """ + path_patterns = [ + (mpath.Path(np.full((1, 2), np.nan)), ls) + if ls == (0, None) else + (path, mlines._get_inverse_dash_pattern(*ls)) + for (path, ls) in + zip(self._paths, itertools.cycle(self._linestyles))] + + return zip(*path_patterns) + + +class EventCollection(LineCollection): + """ + A collection of locations along a single axis at which an "event" occurred. + + The events are given by a 1-dimensional array. They do not have an + amplitude and are displayed as parallel lines. + """ + + _edge_default = True + + def __init__(self, + positions, # Cannot be None. + orientation='horizontal', + *, + lineoffset=0, + linelength=1, + linewidth=None, + color=None, + linestyle='solid', + antialiased=None, + **kwargs + ): + """ + Parameters + ---------- + positions : 1D array-like + Each value is an event. + orientation : {'horizontal', 'vertical'}, default: 'horizontal' + The sequence of events is plotted along this direction. + The marker lines of the single events are along the orthogonal + direction. + lineoffset : float, default: 0 + The offset of the center of the markers from the origin, in the + direction orthogonal to *orientation*. + linelength : float, default: 1 + The total height of the marker (i.e. the marker stretches from + ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``). + linewidth : float or list thereof, default: :rc:`lines.linewidth` + The line width of the event lines, in points. + color : :mpltype:`color` or list of :mpltype:`color`, default: :rc:`lines.color` + The color of the event lines. + linestyle : str or tuple or list thereof, default: 'solid' + Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', + '-', '--', '-.', ':']. Dash tuples should be of the form:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink + in points. + antialiased : bool or list thereof, default: :rc:`lines.antialiased` + Whether to use antialiasing for drawing the lines. + **kwargs + Forwarded to `.LineCollection`. + + Examples + -------- + .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py + """ + super().__init__([], + linewidths=linewidth, linestyles=linestyle, + colors=color, antialiaseds=antialiased, + **kwargs) + self._is_horizontal = True # Initial value, may be switched below. + self._linelength = linelength + self._lineoffset = lineoffset + self.set_orientation(orientation) + self.set_positions(positions) + + def get_positions(self): + """ + Return an array containing the floating-point values of the positions. + """ + pos = 0 if self.is_horizontal() else 1 + return [segment[0, pos] for segment in self.get_segments()] + + def set_positions(self, positions): + """Set the positions of the events.""" + if positions is None: + positions = [] + if np.ndim(positions) != 1: + raise ValueError('positions must be one-dimensional') + lineoffset = self.get_lineoffset() + linelength = self.get_linelength() + pos_idx = 0 if self.is_horizontal() else 1 + segments = np.empty((len(positions), 2, 2)) + segments[:, :, pos_idx] = np.sort(positions)[:, None] + segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2 + segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2 + self.set_segments(segments) + + def add_positions(self, position): + """Add one or more events at the specified positions.""" + if position is None or (hasattr(position, 'len') and + len(position) == 0): + return + positions = self.get_positions() + positions = np.hstack([positions, np.asanyarray(position)]) + self.set_positions(positions) + extend_positions = append_positions = add_positions + + def is_horizontal(self): + """True if the eventcollection is horizontal, False if vertical.""" + return self._is_horizontal + + def get_orientation(self): + """ + Return the orientation of the event line ('horizontal' or 'vertical'). + """ + return 'horizontal' if self.is_horizontal() else 'vertical' + + def switch_orientation(self): + """ + Switch the orientation of the event line, either from vertical to + horizontal or vice versus. + """ + segments = self.get_segments() + for i, segment in enumerate(segments): + segments[i] = np.fliplr(segment) + self.set_segments(segments) + self._is_horizontal = not self.is_horizontal() + self.stale = True + + def set_orientation(self, orientation): + """ + Set the orientation of the event line. + + Parameters + ---------- + orientation : {'horizontal', 'vertical'} + """ + is_horizontal = _api.check_getitem( + {"horizontal": True, "vertical": False}, + orientation=orientation) + if is_horizontal == self.is_horizontal(): + return + self.switch_orientation() + + def get_linelength(self): + """Return the length of the lines used to mark each event.""" + return self._linelength + + def set_linelength(self, linelength): + """Set the length of the lines used to mark each event.""" + if linelength == self.get_linelength(): + return + lineoffset = self.get_lineoffset() + segments = self.get_segments() + pos = 1 if self.is_horizontal() else 0 + for segment in segments: + segment[0, pos] = lineoffset + linelength / 2. + segment[1, pos] = lineoffset - linelength / 2. + self.set_segments(segments) + self._linelength = linelength + + def get_lineoffset(self): + """Return the offset of the lines used to mark each event.""" + return self._lineoffset + + def set_lineoffset(self, lineoffset): + """Set the offset of the lines used to mark each event.""" + if lineoffset == self.get_lineoffset(): + return + linelength = self.get_linelength() + segments = self.get_segments() + pos = 1 if self.is_horizontal() else 0 + for segment in segments: + segment[0, pos] = lineoffset + linelength / 2. + segment[1, pos] = lineoffset - linelength / 2. + self.set_segments(segments) + self._lineoffset = lineoffset + + def get_linewidth(self): + """Get the width of the lines used to mark each event.""" + return super().get_linewidth()[0] + + def get_linewidths(self): + return super().get_linewidth() + + def get_color(self): + """Return the color of the lines used to mark each event.""" + return self.get_colors()[0] + + +class CircleCollection(_CollectionWithSizes): + """A collection of circles, drawn using splines.""" + + _factor = np.pi ** (-1/2) + + def __init__(self, sizes, **kwargs): + """ + Parameters + ---------- + sizes : float or array-like + The area of each circle in points^2. + **kwargs + Forwarded to `.Collection`. + """ + super().__init__(**kwargs) + self.set_sizes(sizes) + self.set_transform(transforms.IdentityTransform()) + self._paths = [mpath.Path.unit_circle()] + + +class EllipseCollection(Collection): + """A collection of ellipses, drawn using splines.""" + + def __init__(self, widths, heights, angles, *, units='points', **kwargs): + """ + Parameters + ---------- + widths : array-like + The lengths of the first axes (e.g., major axis lengths). + heights : array-like + The lengths of second axes. + angles : array-like + The angles of the first axes, degrees CCW from the x-axis. + units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'} + The units in which majors and minors are given; 'width' and + 'height' refer to the dimensions of the axes, while 'x' and 'y' + refer to the *offsets* data units. 'xy' differs from all others in + that the angle as plotted varies with the aspect ratio, and equals + the specified angle only when the aspect ratio is unity. Hence + it behaves the same as the `~.patches.Ellipse` with + ``axes.transData`` as its transform. + **kwargs + Forwarded to `Collection`. + """ + super().__init__(**kwargs) + self.set_widths(widths) + self.set_heights(heights) + self.set_angles(angles) + self._units = units + self.set_transform(transforms.IdentityTransform()) + self._transforms = np.empty((0, 3, 3)) + self._paths = [mpath.Path.unit_circle()] + + def _set_transforms(self): + """Calculate transforms immediately before drawing.""" + + ax = self.axes + fig = self.get_figure(root=False) + + if self._units == 'xy': + sc = 1 + elif self._units == 'x': + sc = ax.bbox.width / ax.viewLim.width + elif self._units == 'y': + sc = ax.bbox.height / ax.viewLim.height + elif self._units == 'inches': + sc = fig.dpi + elif self._units == 'points': + sc = fig.dpi / 72.0 + elif self._units == 'width': + sc = ax.bbox.width + elif self._units == 'height': + sc = ax.bbox.height + elif self._units == 'dots': + sc = 1.0 + else: + raise ValueError(f'Unrecognized units: {self._units!r}') + + self._transforms = np.zeros((len(self._widths), 3, 3)) + widths = self._widths * sc + heights = self._heights * sc + sin_angle = np.sin(self._angles) + cos_angle = np.cos(self._angles) + self._transforms[:, 0, 0] = widths * cos_angle + self._transforms[:, 0, 1] = heights * -sin_angle + self._transforms[:, 1, 0] = widths * sin_angle + self._transforms[:, 1, 1] = heights * cos_angle + self._transforms[:, 2, 2] = 1.0 + + _affine = transforms.Affine2D + if self._units == 'xy': + m = ax.transData.get_affine().get_matrix().copy() + m[:2, 2:] = 0 + self.set_transform(_affine(m)) + + def set_widths(self, widths): + """Set the lengths of the first axes (e.g., major axis).""" + self._widths = 0.5 * np.asarray(widths).ravel() + self.stale = True + + def set_heights(self, heights): + """Set the lengths of second axes (e.g., minor axes).""" + self._heights = 0.5 * np.asarray(heights).ravel() + self.stale = True + + def set_angles(self, angles): + """Set the angles of the first axes, degrees CCW from the x-axis.""" + self._angles = np.deg2rad(angles).ravel() + self.stale = True + + def get_widths(self): + """Get the lengths of the first axes (e.g., major axis).""" + return self._widths * 2 + + def get_heights(self): + """Set the lengths of second axes (e.g., minor axes).""" + return self._heights * 2 + + def get_angles(self): + """Get the angles of the first axes, degrees CCW from the x-axis.""" + return np.rad2deg(self._angles) + + @artist.allow_rasterization + def draw(self, renderer): + self._set_transforms() + super().draw(renderer) + + +class PatchCollection(Collection): + """ + A generic collection of patches. + + PatchCollection draws faster than a large number of equivalent individual + Patches. It also makes it easier to assign a colormap to a heterogeneous + collection of patches. + """ + + def __init__(self, patches, *, match_original=False, **kwargs): + """ + Parameters + ---------- + patches : list of `.Patch` + A sequence of Patch objects. This list may include + a heterogeneous assortment of different patch types. + + match_original : bool, default: False + If True, use the colors and linewidths of the original + patches. If False, new colors may be assigned by + providing the standard collection arguments, facecolor, + edgecolor, linewidths, norm or cmap. + + **kwargs + All other parameters are forwarded to `.Collection`. + + If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds* + are None, they default to their `.rcParams` patch setting, in + sequence form. + + Notes + ----- + The use of `~matplotlib.cm.ScalarMappable` functionality is optional. + If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via + a call to `~.ScalarMappable.set_array`), at draw time a call to scalar + mappable will be made to set the face colors. + """ + + if match_original: + def determine_facecolor(patch): + if patch.get_fill(): + return patch.get_facecolor() + return [0, 0, 0, 0] + + kwargs['facecolors'] = [determine_facecolor(p) for p in patches] + kwargs['edgecolors'] = [p.get_edgecolor() for p in patches] + kwargs['linewidths'] = [p.get_linewidth() for p in patches] + kwargs['linestyles'] = [p.get_linestyle() for p in patches] + kwargs['antialiaseds'] = [p.get_antialiased() for p in patches] + + super().__init__(**kwargs) + + self.set_paths(patches) + + def set_paths(self, patches): + paths = [p.get_transform().transform_path(p.get_path()) + for p in patches] + self._paths = paths + + +class TriMesh(Collection): + """ + Class for the efficient drawing of a triangular mesh using Gouraud shading. + + A triangular mesh is a `~matplotlib.tri.Triangulation` object. + """ + def __init__(self, triangulation, **kwargs): + super().__init__(**kwargs) + self._triangulation = triangulation + self._shading = 'gouraud' + + self._bbox = transforms.Bbox.unit() + + # Unfortunately this requires a copy, unless Triangulation + # was rewritten. + xy = np.hstack((triangulation.x.reshape(-1, 1), + triangulation.y.reshape(-1, 1))) + self._bbox.update_from_data_xy(xy) + + def get_paths(self): + if self._paths is None: + self.set_paths() + return self._paths + + def set_paths(self): + self._paths = self.convert_mesh_to_paths(self._triangulation) + + @staticmethod + def convert_mesh_to_paths(tri): + """ + Convert a given mesh into a sequence of `.Path` objects. + + This function is primarily of use to implementers of backends that do + not directly support meshes. + """ + triangles = tri.get_masked_triangles() + verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1) + return [mpath.Path(x) for x in verts] + + @artist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + renderer.open_group(self.__class__.__name__, gid=self.get_gid()) + transform = self.get_transform() + + # Get a list of triangles and the color at each vertex. + tri = self._triangulation + triangles = tri.get_masked_triangles() + + verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1) + + self.update_scalarmappable() + colors = self._facecolors[triangles] + + gc = renderer.new_gc() + self._set_gc_clip(gc) + gc.set_linewidth(self.get_linewidth()[0]) + renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen()) + gc.restore() + renderer.close_group(self.__class__.__name__) + + +class _MeshData: + r""" + Class for managing the two dimensional coordinates of Quadrilateral meshes + and the associated data with them. This class is a mixin and is intended to + be used with another collection that will implement the draw separately. + + A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are + defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is + defined by the vertices :: + + (m+1, n) ----------- (m+1, n+1) + / / + / / + / / + (m, n) -------- (m, n+1) + + The mesh need not be regular and the polygons need not be convex. + + Parameters + ---------- + coordinates : (M+1, N+1, 2) array-like + The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates + of vertex (m, n). + + shading : {'flat', 'gouraud'}, default: 'flat' + """ + def __init__(self, coordinates, *, shading='flat'): + _api.check_shape((None, None, 2), coordinates=coordinates) + self._coordinates = coordinates + self._shading = shading + + def set_array(self, A): + """ + Set the data values. + + Parameters + ---------- + A : array-like + The mesh data. Supported array shapes are: + + - (M, N) or (M*N,): a mesh with scalar data. The values are mapped + to colors using normalization and a colormap. See parameters + *norm*, *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + If the values are provided as a 2D grid, the shape must match the + coordinates grid. If the values are 1D, they are reshaped to 2D. + M, N follow from the coordinates grid, where the coordinates grid + shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat' + shading. + """ + height, width = self._coordinates.shape[0:-1] + if self._shading == 'flat': + h, w = height - 1, width - 1 + else: + h, w = height, width + ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)] + if A is not None: + shape = np.shape(A) + if shape not in ok_shapes: + raise ValueError( + f"For X ({width}) and Y ({height}) with {self._shading} " + f"shading, A should have shape " + f"{' or '.join(map(str, ok_shapes))}, not {A.shape}") + return super().set_array(A) + + def get_coordinates(self): + """ + Return the vertices of the mesh as an (M+1, N+1, 2) array. + + M, N are the number of quadrilaterals in the rows / columns of the + mesh, corresponding to (M+1, N+1) vertices. + The last dimension specifies the components (x, y). + """ + return self._coordinates + + def get_edgecolor(self): + # docstring inherited + # Note that we want to return an array of shape (N*M, 4) + # a flattened RGBA collection + return super().get_edgecolor().reshape(-1, 4) + + def get_facecolor(self): + # docstring inherited + # Note that we want to return an array of shape (N*M, 4) + # a flattened RGBA collection + return super().get_facecolor().reshape(-1, 4) + + @staticmethod + def _convert_mesh_to_paths(coordinates): + """ + Convert a given mesh into a sequence of `.Path` objects. + + This function is primarily of use to implementers of backends that do + not directly support quadmeshes. + """ + if isinstance(coordinates, np.ma.MaskedArray): + c = coordinates.data + else: + c = coordinates + points = np.concatenate([ + c[:-1, :-1], + c[:-1, 1:], + c[1:, 1:], + c[1:, :-1], + c[:-1, :-1] + ], axis=2).reshape((-1, 5, 2)) + return [mpath.Path(x) for x in points] + + def _convert_mesh_to_triangles(self, coordinates): + """ + Convert a given mesh into a sequence of triangles, each point + with its own color. The result can be used to construct a call to + `~.RendererBase.draw_gouraud_triangles`. + """ + if isinstance(coordinates, np.ma.MaskedArray): + p = coordinates.data + else: + p = coordinates + + p_a = p[:-1, :-1] + p_b = p[:-1, 1:] + p_c = p[1:, 1:] + p_d = p[1:, :-1] + p_center = (p_a + p_b + p_c + p_d) / 4.0 + triangles = np.concatenate([ + p_a, p_b, p_center, + p_b, p_c, p_center, + p_c, p_d, p_center, + p_d, p_a, p_center, + ], axis=2).reshape((-1, 3, 2)) + + c = self.get_facecolor().reshape((*coordinates.shape[:2], 4)) + z = self.get_array() + mask = z.mask if np.ma.is_masked(z) else None + if mask is not None: + c[mask, 3] = np.nan + c_a = c[:-1, :-1] + c_b = c[:-1, 1:] + c_c = c[1:, 1:] + c_d = c[1:, :-1] + c_center = (c_a + c_b + c_c + c_d) / 4.0 + colors = np.concatenate([ + c_a, c_b, c_center, + c_b, c_c, c_center, + c_c, c_d, c_center, + c_d, c_a, c_center, + ], axis=2).reshape((-1, 3, 4)) + tmask = np.isnan(colors[..., 2, 3]) + return triangles[~tmask], colors[~tmask] + + +class QuadMesh(_MeshData, Collection): + r""" + Class for the efficient drawing of a quadrilateral mesh. + + A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are + defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is + defined by the vertices :: + + (m+1, n) ----------- (m+1, n+1) + / / + / / + / / + (m, n) -------- (m, n+1) + + The mesh need not be regular and the polygons need not be convex. + + Parameters + ---------- + coordinates : (M+1, N+1, 2) array-like + The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates + of vertex (m, n). + + antialiased : bool, default: True + + shading : {'flat', 'gouraud'}, default: 'flat' + + Notes + ----- + Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0, + i.e. `~.Artist.contains` checks whether the test point is within any of the + mesh quadrilaterals. + + """ + + def __init__(self, coordinates, *, antialiased=True, shading='flat', + **kwargs): + kwargs.setdefault("pickradius", 0) + super().__init__(coordinates=coordinates, shading=shading) + Collection.__init__(self, **kwargs) + + self._antialiased = antialiased + self._bbox = transforms.Bbox.unit() + self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2)) + self.set_mouseover(False) + + def get_paths(self): + if self._paths is None: + self.set_paths() + return self._paths + + def set_paths(self): + self._paths = self._convert_mesh_to_paths(self._coordinates) + self.stale = True + + def get_datalim(self, transData): + return (self.get_transform() - transData).transform_bbox(self._bbox) + + @artist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + renderer.open_group(self.__class__.__name__, self.get_gid()) + transform = self.get_transform() + offset_trf = self.get_offset_transform() + offsets = self.get_offsets() + + if self.have_units(): + xs = self.convert_xunits(offsets[:, 0]) + ys = self.convert_yunits(offsets[:, 1]) + offsets = np.column_stack([xs, ys]) + + self.update_scalarmappable() + + if not transform.is_affine: + coordinates = self._coordinates.reshape((-1, 2)) + coordinates = transform.transform(coordinates) + coordinates = coordinates.reshape(self._coordinates.shape) + transform = transforms.IdentityTransform() + else: + coordinates = self._coordinates + + if not offset_trf.is_affine: + offsets = offset_trf.transform_non_affine(offsets) + offset_trf = offset_trf.get_affine() + + gc = renderer.new_gc() + gc.set_snap(self.get_snap()) + self._set_gc_clip(gc) + gc.set_linewidth(self.get_linewidth()[0]) + + if self._shading == 'gouraud': + triangles, colors = self._convert_mesh_to_triangles(coordinates) + renderer.draw_gouraud_triangles( + gc, triangles, colors, transform.frozen()) + else: + renderer.draw_quad_mesh( + gc, transform.frozen(), + coordinates.shape[1] - 1, coordinates.shape[0] - 1, + coordinates, offsets, offset_trf, + # Backends expect flattened rgba arrays (n*m, 4) for fc and ec + self.get_facecolor().reshape((-1, 4)), + self._antialiased, self.get_edgecolors().reshape((-1, 4))) + gc.restore() + renderer.close_group(self.__class__.__name__) + self.stale = False + + def get_cursor_data(self, event): + contained, info = self.contains(event) + if contained and self.get_array() is not None: + return self.get_array().ravel()[info["ind"]] + return None + + +class PolyQuadMesh(_MeshData, PolyCollection): + """ + Class for drawing a quadrilateral mesh as individual Polygons. + + A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are + defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is + defined by the vertices :: + + (m+1, n) ----------- (m+1, n+1) + / / + / / + / / + (m, n) -------- (m, n+1) + + The mesh need not be regular and the polygons need not be convex. + + Parameters + ---------- + coordinates : (M+1, N+1, 2) array-like + The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates + of vertex (m, n). + + Notes + ----- + Unlike `.QuadMesh`, this class will draw each cell as an individual Polygon. + This is significantly slower, but allows for more flexibility when wanting + to add additional properties to the cells, such as hatching. + + Another difference from `.QuadMesh` is that if any of the vertices or data + of a cell are masked, that Polygon will **not** be drawn and it won't be in + the list of paths returned. + """ + + def __init__(self, coordinates, **kwargs): + super().__init__(coordinates=coordinates) + PolyCollection.__init__(self, verts=[], **kwargs) + # Setting the verts updates the paths of the PolyCollection + # This is called after the initializers to make sure the kwargs + # have all been processed and available for the masking calculations + self._set_unmasked_verts() + + def _get_unmasked_polys(self): + """Get the unmasked regions using the coordinates and array""" + # mask(X) | mask(Y) + mask = np.any(np.ma.getmaskarray(self._coordinates), axis=-1) + + # We want the shape of the polygon, which is the corner of each X/Y array + mask = (mask[0:-1, 0:-1] | mask[1:, 1:] | mask[0:-1, 1:] | mask[1:, 0:-1]) + arr = self.get_array() + if arr is not None: + arr = np.ma.getmaskarray(arr) + if arr.ndim == 3: + # RGB(A) case + mask |= np.any(arr, axis=-1) + elif arr.ndim == 2: + mask |= arr + else: + mask |= arr.reshape(self._coordinates[:-1, :-1, :].shape[:2]) + return ~mask + + def _set_unmasked_verts(self): + X = self._coordinates[..., 0] + Y = self._coordinates[..., 1] + + unmask = self._get_unmasked_polys() + X1 = np.ma.filled(X[:-1, :-1])[unmask] + Y1 = np.ma.filled(Y[:-1, :-1])[unmask] + X2 = np.ma.filled(X[1:, :-1])[unmask] + Y2 = np.ma.filled(Y[1:, :-1])[unmask] + X3 = np.ma.filled(X[1:, 1:])[unmask] + Y3 = np.ma.filled(Y[1:, 1:])[unmask] + X4 = np.ma.filled(X[:-1, 1:])[unmask] + Y4 = np.ma.filled(Y[:-1, 1:])[unmask] + npoly = len(X1) + + xy = np.ma.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1) + verts = xy.reshape((npoly, 5, 2)) + self.set_verts(verts) + + def get_edgecolor(self): + # docstring inherited + # We only want to return the facecolors of the polygons + # that were drawn. + ec = super().get_edgecolor() + unmasked_polys = self._get_unmasked_polys().ravel() + if len(ec) != len(unmasked_polys): + # Mapping is off + return ec + return ec[unmasked_polys, :] + + def get_facecolor(self): + # docstring inherited + # We only want to return the facecolors of the polygons + # that were drawn. + fc = super().get_facecolor() + unmasked_polys = self._get_unmasked_polys().ravel() + if len(fc) != len(unmasked_polys): + # Mapping is off + return fc + return fc[unmasked_polys, :] + + def set_array(self, A): + # docstring inherited + prev_unmask = self._get_unmasked_polys() + super().set_array(A) + # If the mask has changed at all we need to update + # the set of Polys that we are drawing + if not np.array_equal(prev_unmask, self._get_unmasked_polys()): + self._set_unmasked_verts() diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/font_manager.py b/llava_video/lib/python3.10/site-packages/matplotlib/font_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa8dccde444b8998f34ded5cd9cfe07e7b46f6a --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/matplotlib/font_manager.py @@ -0,0 +1,1645 @@ +""" +A module for finding, managing, and using fonts across platforms. + +This module provides a single `FontManager` instance, ``fontManager``, that can +be shared across backends and platforms. The `findfont` +function returns the best TrueType (TTF) font file in the local or +system font path that matches the specified `FontProperties` +instance. The `FontManager` also handles Adobe Font Metrics +(AFM) font files for use by the PostScript backend. +The `FontManager.addfont` function adds a custom font from a file without +installing it into your operating system. + +The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1) +font specification `_. +Future versions may implement the Level 2 or 2.1 specifications. +""" + +# KNOWN ISSUES +# +# - documentation +# - font variant is untested +# - font stretch is incomplete +# - font size is incomplete +# - default font algorithm needs improvement and testing +# - setWeights function needs improvement +# - 'light' is an invalid weight value, remove it. + +from __future__ import annotations + +from base64 import b64encode +import copy +import dataclasses +from functools import lru_cache +import functools +from io import BytesIO +import json +import logging +from numbers import Number +import os +from pathlib import Path +import plistlib +import re +import subprocess +import sys +import threading + +import matplotlib as mpl +from matplotlib import _api, _afm, cbook, ft2font +from matplotlib._fontconfig_pattern import ( + parse_fontconfig_pattern, generate_fontconfig_pattern) +from matplotlib.rcsetup import _validators + +_log = logging.getLogger(__name__) + +font_scalings = { + 'xx-small': 0.579, + 'x-small': 0.694, + 'small': 0.833, + 'medium': 1.0, + 'large': 1.200, + 'x-large': 1.440, + 'xx-large': 1.728, + 'larger': 1.2, + 'smaller': 0.833, + None: 1.0, +} +stretch_dict = { + 'ultra-condensed': 100, + 'extra-condensed': 200, + 'condensed': 300, + 'semi-condensed': 400, + 'normal': 500, + 'semi-expanded': 600, + 'semi-extended': 600, + 'expanded': 700, + 'extended': 700, + 'extra-expanded': 800, + 'extra-extended': 800, + 'ultra-expanded': 900, + 'ultra-extended': 900, +} +weight_dict = { + 'ultralight': 100, + 'light': 200, + 'normal': 400, + 'regular': 400, + 'book': 400, + 'medium': 500, + 'roman': 500, + 'semibold': 600, + 'demibold': 600, + 'demi': 600, + 'bold': 700, + 'heavy': 800, + 'extra bold': 800, + 'black': 900, +} +_weight_regexes = [ + # From fontconfig's FcFreeTypeQueryFaceInternal; not the same as + # weight_dict! + ("thin", 100), + ("extralight", 200), + ("ultralight", 200), + ("demilight", 350), + ("semilight", 350), + ("light", 300), # Needs to come *after* demi/semilight! + ("book", 380), + ("regular", 400), + ("normal", 400), + ("medium", 500), + ("demibold", 600), + ("demi", 600), + ("semibold", 600), + ("extrabold", 800), + ("superbold", 800), + ("ultrabold", 800), + ("bold", 700), # Needs to come *after* extra/super/ultrabold! + ("ultrablack", 1000), + ("superblack", 1000), + ("extrablack", 1000), + (r"\bultra", 1000), + ("black", 900), # Needs to come *after* ultra/super/extrablack! + ("heavy", 900), +] +font_family_aliases = { + 'serif', + 'sans-serif', + 'sans serif', + 'cursive', + 'fantasy', + 'monospace', + 'sans', +} + +# OS Font paths +try: + _HOME = Path.home() +except Exception: # Exceptions thrown by home() are not specified... + _HOME = Path(os.devnull) # Just an arbitrary path with no children. +MSFolders = \ + r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' +MSFontDirectories = [ + r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts', + r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts'] +MSUserFontDirectories = [ + str(_HOME / 'AppData/Local/Microsoft/Windows/Fonts'), + str(_HOME / 'AppData/Roaming/Microsoft/Windows/Fonts'), +] +X11FontDirectories = [ + # an old standard installation point + "/usr/X11R6/lib/X11/fonts/TTF/", + "/usr/X11/lib/X11/fonts", + # here is the new standard location for fonts + "/usr/share/fonts/", + # documented as a good place to install new fonts + "/usr/local/share/fonts/", + # common application, not really useful + "/usr/lib/openoffice/share/fonts/truetype/", + # user fonts + str((Path(os.environ.get('XDG_DATA_HOME') or _HOME / ".local/share")) + / "fonts"), + str(_HOME / ".fonts"), +] +OSXFontDirectories = [ + "/Library/Fonts/", + "/Network/Library/Fonts/", + "/System/Library/Fonts/", + # fonts installed via MacPorts + "/opt/local/share/fonts", + # user fonts + str(_HOME / "Library/Fonts"), +] + + +def get_fontext_synonyms(fontext): + """ + Return a list of file extensions that are synonyms for + the given file extension *fileext*. + """ + return { + 'afm': ['afm'], + 'otf': ['otf', 'ttc', 'ttf'], + 'ttc': ['otf', 'ttc', 'ttf'], + 'ttf': ['otf', 'ttc', 'ttf'], + }[fontext] + + +def list_fonts(directory, extensions): + """ + Return a list of all fonts matching any of the extensions, found + recursively under the directory. + """ + extensions = ["." + ext for ext in extensions] + return [os.path.join(dirpath, filename) + # os.walk ignores access errors, unlike Path.glob. + for dirpath, _, filenames in os.walk(directory) + for filename in filenames + if Path(filename).suffix.lower() in extensions] + + +def win32FontDirectory(): + r""" + Return the user-specified font directory for Win32. This is + looked up from the registry key :: + + \\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts + + If the key is not found, ``%WINDIR%\Fonts`` will be returned. + """ # noqa: E501 + import winreg + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user: + return winreg.QueryValueEx(user, 'Fonts')[0] + except OSError: + return os.path.join(os.environ['WINDIR'], 'Fonts') + + +def _get_win32_installed_fonts(): + """List the font paths known to the Windows registry.""" + import winreg + items = set() + # Search and resolve fonts listed in the registry. + for domain, base_dirs in [ + (winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]), # System. + (winreg.HKEY_CURRENT_USER, MSUserFontDirectories), # User. + ]: + for base_dir in base_dirs: + for reg_path in MSFontDirectories: + try: + with winreg.OpenKey(domain, reg_path) as local: + for j in range(winreg.QueryInfoKey(local)[1]): + # value may contain the filename of the font or its + # absolute path. + key, value, tp = winreg.EnumValue(local, j) + if not isinstance(value, str): + continue + try: + # If value contains already an absolute path, + # then it is not changed further. + path = Path(base_dir, value).resolve() + except RuntimeError: + # Don't fail with invalid entries. + continue + items.add(path) + except (OSError, MemoryError): + continue + return items + + +@lru_cache +def _get_fontconfig_fonts(): + """Cache and list the font paths known to ``fc-list``.""" + try: + if b'--format' not in subprocess.check_output(['fc-list', '--help']): + _log.warning( # fontconfig 2.7 implemented --format. + 'Matplotlib needs fontconfig>=2.7 to query system fonts.') + return [] + out = subprocess.check_output(['fc-list', '--format=%{file}\\n']) + except (OSError, subprocess.CalledProcessError): + return [] + return [Path(os.fsdecode(fname)) for fname in out.split(b'\n')] + + +@lru_cache +def _get_macos_fonts(): + """Cache and list the font paths known to ``system_profiler SPFontsDataType``.""" + try: + d, = plistlib.loads( + subprocess.check_output(["system_profiler", "-xml", "SPFontsDataType"])) + except (OSError, subprocess.CalledProcessError, plistlib.InvalidFileException): + return [] + return [Path(entry["path"]) for entry in d["_items"]] + + +def findSystemFonts(fontpaths=None, fontext='ttf'): + """ + Search for fonts in the specified font paths. If no paths are + given, will use a standard set of system paths, as well as the + list of fonts tracked by fontconfig if fontconfig is installed and + available. A list of TrueType fonts are returned by default with + AFM fonts as an option. + """ + fontfiles = set() + fontexts = get_fontext_synonyms(fontext) + + if fontpaths is None: + if sys.platform == 'win32': + installed_fonts = _get_win32_installed_fonts() + fontpaths = [] + else: + installed_fonts = _get_fontconfig_fonts() + if sys.platform == 'darwin': + installed_fonts += _get_macos_fonts() + fontpaths = [*X11FontDirectories, *OSXFontDirectories] + else: + fontpaths = X11FontDirectories + fontfiles.update(str(path) for path in installed_fonts + if path.suffix.lower()[1:] in fontexts) + + elif isinstance(fontpaths, str): + fontpaths = [fontpaths] + + for path in fontpaths: + fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts))) + + return [fname for fname in fontfiles if os.path.exists(fname)] + + +@dataclasses.dataclass(frozen=True) +class FontEntry: + """ + A class for storing Font properties. + + It is used when populating the font lookup dictionary. + """ + + fname: str = '' + name: str = '' + style: str = 'normal' + variant: str = 'normal' + weight: str | int = 'normal' + stretch: str = 'normal' + size: str = 'medium' + + def _repr_html_(self) -> str: + png_stream = self._repr_png_() + png_b64 = b64encode(png_stream).decode() + return f"" + + def _repr_png_(self) -> bytes: + from matplotlib.figure import Figure # Circular import. + fig = Figure() + font_path = Path(self.fname) if self.fname != '' else None + fig.text(0, 0, self.name, font=font_path) + with BytesIO() as buf: + fig.savefig(buf, bbox_inches='tight', transparent=True) + return buf.getvalue() + + +def ttfFontProperty(font): + """ + Extract information from a TrueType font file. + + Parameters + ---------- + font : `.FT2Font` + The TrueType font file from which information will be extracted. + + Returns + ------- + `FontEntry` + The extracted font properties. + + """ + name = font.family_name + + # Styles are: italic, oblique, and normal (default) + + sfnt = font.get_sfnt() + mac_key = (1, # platform: macintosh + 0, # id: roman + 0) # langid: english + ms_key = (3, # platform: microsoft + 1, # id: unicode_cs + 0x0409) # langid: english_united_states + + # These tables are actually mac_roman-encoded, but mac_roman support may be + # missing in some alternative Python implementations and we are only going + # to look for ASCII substrings, where any ASCII-compatible encoding works + # - or big-endian UTF-16, since important Microsoft fonts use that. + sfnt2 = (sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or + sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower()) + sfnt4 = (sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or + sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower()) + + if sfnt4.find('oblique') >= 0: + style = 'oblique' + elif sfnt4.find('italic') >= 0: + style = 'italic' + elif sfnt2.find('regular') >= 0: + style = 'normal' + elif ft2font.StyleFlags.ITALIC in font.style_flags: + style = 'italic' + else: + style = 'normal' + + # Variants are: small-caps and normal (default) + + # !!!! Untested + if name.lower() in ['capitals', 'small-caps']: + variant = 'small-caps' + else: + variant = 'normal' + + # The weight-guessing algorithm is directly translated from fontconfig + # 2.13.1's FcFreeTypeQueryFaceInternal (fcfreetype.c). + wws_subfamily = 22 + typographic_subfamily = 16 + font_subfamily = 2 + styles = [ + sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'), + sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'), + sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'), + sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'), + sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'), + sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be'), + ] + styles = [*filter(None, styles)] or [font.style_name] + + def get_weight(): # From fontconfig's FcFreeTypeQueryFaceInternal. + # OS/2 table weight. + os2 = font.get_sfnt_table("OS/2") + if os2 and os2["version"] != 0xffff: + return os2["usWeightClass"] + # PostScript font info weight. + try: + ps_font_info_weight = ( + font.get_ps_font_info()["weight"].replace(" ", "") or "") + except ValueError: + pass + else: + for regex, weight in _weight_regexes: + if re.fullmatch(regex, ps_font_info_weight, re.I): + return weight + # Style name weight. + for style in styles: + style = style.replace(" ", "") + for regex, weight in _weight_regexes: + if re.search(regex, style, re.I): + return weight + if ft2font.StyleFlags.BOLD in font.style_flags: + return 700 # "bold" + return 500 # "medium", not "regular"! + + weight = int(get_weight()) + + # Stretch can be absolute and relative + # Absolute stretches are: ultra-condensed, extra-condensed, condensed, + # semi-condensed, normal, semi-expanded, expanded, extra-expanded, + # and ultra-expanded. + # Relative stretches are: wider, narrower + # Child value is: inherit + + if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']): + stretch = 'condensed' + elif 'demi cond' in sfnt4: + stretch = 'semi-condensed' + elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']): + stretch = 'expanded' + else: + stretch = 'normal' + + # Sizes can be absolute and relative. + # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, + # and xx-large. + # Relative sizes are: larger, smaller + # Length value is an absolute font size, e.g., 12pt + # Percentage values are in 'em's. Most robust specification. + + if not font.scalable: + raise NotImplementedError("Non-scalable fonts are not supported") + size = 'scalable' + + return FontEntry(font.fname, name, style, variant, weight, stretch, size) + + +def afmFontProperty(fontpath, font): + """ + Extract information from an AFM font file. + + Parameters + ---------- + fontpath : str + The filename corresponding to *font*. + font : AFM + The AFM font file from which information will be extracted. + + Returns + ------- + `FontEntry` + The extracted font properties. + """ + + name = font.get_familyname() + fontname = font.get_fontname().lower() + + # Styles are: italic, oblique, and normal (default) + + if font.get_angle() != 0 or 'italic' in name.lower(): + style = 'italic' + elif 'oblique' in name.lower(): + style = 'oblique' + else: + style = 'normal' + + # Variants are: small-caps and normal (default) + + # !!!! Untested + if name.lower() in ['capitals', 'small-caps']: + variant = 'small-caps' + else: + variant = 'normal' + + weight = font.get_weight().lower() + if weight not in weight_dict: + weight = 'normal' + + # Stretch can be absolute and relative + # Absolute stretches are: ultra-condensed, extra-condensed, condensed, + # semi-condensed, normal, semi-expanded, expanded, extra-expanded, + # and ultra-expanded. + # Relative stretches are: wider, narrower + # Child value is: inherit + if 'demi cond' in fontname: + stretch = 'semi-condensed' + elif any(word in fontname for word in ['narrow', 'cond']): + stretch = 'condensed' + elif any(word in fontname for word in ['wide', 'expanded', 'extended']): + stretch = 'expanded' + else: + stretch = 'normal' + + # Sizes can be absolute and relative. + # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, + # and xx-large. + # Relative sizes are: larger, smaller + # Length value is an absolute font size, e.g., 12pt + # Percentage values are in 'em's. Most robust specification. + + # All AFM fonts are apparently scalable. + + size = 'scalable' + + return FontEntry(fontpath, name, style, variant, weight, stretch, size) + + +def _cleanup_fontproperties_init(init_method): + """ + A decorator to limit the call signature to single a positional argument + or alternatively only keyword arguments. + + We still accept but deprecate all other call signatures. + + When the deprecation expires we can switch the signature to:: + + __init__(self, pattern=None, /, *, family=None, style=None, ...) + + plus a runtime check that pattern is not used alongside with the + keyword arguments. This results eventually in the two possible + call signatures:: + + FontProperties(pattern) + FontProperties(family=..., size=..., ...) + + """ + @functools.wraps(init_method) + def wrapper(self, *args, **kwargs): + # multiple args with at least some positional ones + if len(args) > 1 or len(args) == 1 and kwargs: + # Note: Both cases were previously handled as individual properties. + # Therefore, we do not mention the case of font properties here. + _api.warn_deprecated( + "3.10", + message="Passing individual properties to FontProperties() " + "positionally was deprecated in Matplotlib %(since)s and " + "will be removed in %(removal)s. Please pass all properties " + "via keyword arguments." + ) + # single non-string arg -> clearly a family not a pattern + if len(args) == 1 and not kwargs and not cbook.is_scalar_or_string(args[0]): + # Case font-family list passed as single argument + _api.warn_deprecated( + "3.10", + message="Passing family as positional argument to FontProperties() " + "was deprecated in Matplotlib %(since)s and will be removed " + "in %(removal)s. Please pass family names as keyword" + "argument." + ) + # Note on single string arg: + # This has been interpreted as pattern so far. We are already raising if a + # non-pattern compatible family string was given. Therefore, we do not need + # to warn for this case. + return init_method(self, *args, **kwargs) + + return wrapper + + +class FontProperties: + """ + A class for storing and manipulating font properties. + + The font properties are the six properties described in the + `W3C Cascading Style Sheet, Level 1 + `_ font + specification and *math_fontfamily* for math fonts: + + - family: A list of font names in decreasing order of priority. + The items may include a generic font family name, either 'sans-serif', + 'serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actual + font to be used will be looked up from the associated rcParam during the + search process in `.findfont`. Default: :rc:`font.family` + + - style: Either 'normal', 'italic' or 'oblique'. + Default: :rc:`font.style` + + - variant: Either 'normal' or 'small-caps'. + Default: :rc:`font.variant` + + - stretch: A numeric value in the range 0-1000 or one of + 'ultra-condensed', 'extra-condensed', 'condensed', + 'semi-condensed', 'normal', 'semi-expanded', 'expanded', + 'extra-expanded' or 'ultra-expanded'. Default: :rc:`font.stretch` + + - weight: A numeric value in the range 0-1000 or one of + 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', + 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', + 'extra bold', 'black'. Default: :rc:`font.weight` + + - size: Either a relative value of 'xx-small', 'x-small', + 'small', 'medium', 'large', 'x-large', 'xx-large' or an + absolute font size, e.g., 10. Default: :rc:`font.size` + + - math_fontfamily: The family of fonts used to render math text. + Supported values are: 'dejavusans', 'dejavuserif', 'cm', + 'stix', 'stixsans' and 'custom'. Default: :rc:`mathtext.fontset` + + Alternatively, a font may be specified using the absolute path to a font + file, by using the *fname* kwarg. However, in this case, it is typically + simpler to just pass the path (as a `pathlib.Path`, not a `str`) to the + *font* kwarg of the `.Text` object. + + The preferred usage of font sizes is to use the relative values, + e.g., 'large', instead of absolute font sizes, e.g., 12. This + approach allows all text sizes to be made larger or smaller based + on the font manager's default font size. + + This class accepts a single positional string as fontconfig_ pattern_, + or alternatively individual properties as keyword arguments:: + + FontProperties(pattern) + FontProperties(*, family=None, style=None, variant=None, ...) + + This support does not depend on fontconfig; we are merely borrowing its + pattern syntax for use here. + + .. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/ + .. _pattern: + https://www.freedesktop.org/software/fontconfig/fontconfig-user.html + + Note that Matplotlib's internal font manager and fontconfig use a + different algorithm to lookup fonts, so the results of the same pattern + may be different in Matplotlib than in other applications that use + fontconfig. + """ + + @_cleanup_fontproperties_init + def __init__(self, family=None, style=None, variant=None, weight=None, + stretch=None, size=None, + fname=None, # if set, it's a hardcoded filename to use + math_fontfamily=None): + self.set_family(family) + self.set_style(style) + self.set_variant(variant) + self.set_weight(weight) + self.set_stretch(stretch) + self.set_file(fname) + self.set_size(size) + self.set_math_fontfamily(math_fontfamily) + # Treat family as a fontconfig pattern if it is the only parameter + # provided. Even in that case, call the other setters first to set + # attributes not specified by the pattern to the rcParams defaults. + if (isinstance(family, str) + and style is None and variant is None and weight is None + and stretch is None and size is None and fname is None): + self.set_fontconfig_pattern(family) + + @classmethod + def _from_any(cls, arg): + """ + Generic constructor which can build a `.FontProperties` from any of the + following: + + - a `.FontProperties`: it is passed through as is; + - `None`: a `.FontProperties` using rc values is used; + - an `os.PathLike`: it is used as path to the font file; + - a `str`: it is parsed as a fontconfig pattern; + - a `dict`: it is passed as ``**kwargs`` to `.FontProperties`. + """ + if arg is None: + return cls() + elif isinstance(arg, cls): + return arg + elif isinstance(arg, os.PathLike): + return cls(fname=arg) + elif isinstance(arg, str): + return cls(arg) + else: + return cls(**arg) + + def __hash__(self): + l = (tuple(self.get_family()), + self.get_slant(), + self.get_variant(), + self.get_weight(), + self.get_stretch(), + self.get_size(), + self.get_file(), + self.get_math_fontfamily()) + return hash(l) + + def __eq__(self, other): + return hash(self) == hash(other) + + def __str__(self): + return self.get_fontconfig_pattern() + + def get_family(self): + """ + Return a list of individual font family names or generic family names. + + The font families or generic font families (which will be resolved + from their respective rcParams when searching for a matching font) in + the order of preference. + """ + return self._family + + def get_name(self): + """ + Return the name of the font that best matches the font properties. + """ + return get_font(findfont(self)).family_name + + def get_style(self): + """ + Return the font style. Values are: 'normal', 'italic' or 'oblique'. + """ + return self._slant + + def get_variant(self): + """ + Return the font variant. Values are: 'normal' or 'small-caps'. + """ + return self._variant + + def get_weight(self): + """ + Set the font weight. Options are: A numeric value in the + range 0-1000 or one of 'light', 'normal', 'regular', 'book', + 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', + 'heavy', 'extra bold', 'black' + """ + return self._weight + + def get_stretch(self): + """ + Return the font stretch or width. Options are: 'ultra-condensed', + 'extra-condensed', 'condensed', 'semi-condensed', 'normal', + 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'. + """ + return self._stretch + + def get_size(self): + """ + Return the font size. + """ + return self._size + + def get_file(self): + """ + Return the filename of the associated font. + """ + return self._file + + def get_fontconfig_pattern(self): + """ + Get a fontconfig_ pattern_ suitable for looking up the font as + specified with fontconfig's ``fc-match`` utility. + + This support does not depend on fontconfig; we are merely borrowing its + pattern syntax for use here. + """ + return generate_fontconfig_pattern(self) + + def set_family(self, family): + """ + Change the font family. Can be either an alias (generic name + is CSS parlance), such as: 'serif', 'sans-serif', 'cursive', + 'fantasy', or 'monospace', a real font name or a list of real + font names. Real font names are not supported when + :rc:`text.usetex` is `True`. Default: :rc:`font.family` + """ + if family is None: + family = mpl.rcParams['font.family'] + if isinstance(family, str): + family = [family] + self._family = family + + def set_style(self, style): + """ + Set the font style. + + Parameters + ---------- + style : {'normal', 'italic', 'oblique'}, default: :rc:`font.style` + """ + if style is None: + style = mpl.rcParams['font.style'] + _api.check_in_list(['normal', 'italic', 'oblique'], style=style) + self._slant = style + + def set_variant(self, variant): + """ + Set the font variant. + + Parameters + ---------- + variant : {'normal', 'small-caps'}, default: :rc:`font.variant` + """ + if variant is None: + variant = mpl.rcParams['font.variant'] + _api.check_in_list(['normal', 'small-caps'], variant=variant) + self._variant = variant + + def set_weight(self, weight): + """ + Set the font weight. + + Parameters + ---------- + weight : int or {'ultralight', 'light', 'normal', 'regular', 'book', \ +'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', \ +'extra bold', 'black'}, default: :rc:`font.weight` + If int, must be in the range 0-1000. + """ + if weight is None: + weight = mpl.rcParams['font.weight'] + if weight in weight_dict: + self._weight = weight + return + try: + weight = int(weight) + except ValueError: + pass + else: + if 0 <= weight <= 1000: + self._weight = weight + return + raise ValueError(f"{weight=} is invalid") + + def set_stretch(self, stretch): + """ + Set the font stretch or width. + + Parameters + ---------- + stretch : int or {'ultra-condensed', 'extra-condensed', 'condensed', \ +'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', \ +'ultra-expanded'}, default: :rc:`font.stretch` + If int, must be in the range 0-1000. + """ + if stretch is None: + stretch = mpl.rcParams['font.stretch'] + if stretch in stretch_dict: + self._stretch = stretch + return + try: + stretch = int(stretch) + except ValueError: + pass + else: + if 0 <= stretch <= 1000: + self._stretch = stretch + return + raise ValueError(f"{stretch=} is invalid") + + def set_size(self, size): + """ + Set the font size. + + Parameters + ---------- + size : float or {'xx-small', 'x-small', 'small', 'medium', \ +'large', 'x-large', 'xx-large'}, default: :rc:`font.size` + If a float, the font size in points. The string values denote + sizes relative to the default font size. + """ + if size is None: + size = mpl.rcParams['font.size'] + try: + size = float(size) + except ValueError: + try: + scale = font_scalings[size] + except KeyError as err: + raise ValueError( + "Size is invalid. Valid font size are " + + ", ".join(map(str, font_scalings))) from err + else: + size = scale * FontManager.get_default_size() + if size < 1.0: + _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. ' + 'Setting fontsize = 1 pt', size) + size = 1.0 + self._size = size + + def set_file(self, file): + """ + Set the filename of the fontfile to use. In this case, all + other properties will be ignored. + """ + self._file = os.fspath(file) if file is not None else None + + def set_fontconfig_pattern(self, pattern): + """ + Set the properties by parsing a fontconfig_ *pattern*. + + This support does not depend on fontconfig; we are merely borrowing its + pattern syntax for use here. + """ + for key, val in parse_fontconfig_pattern(pattern).items(): + if type(val) is list: + getattr(self, "set_" + key)(val[0]) + else: + getattr(self, "set_" + key)(val) + + def get_math_fontfamily(self): + """ + Return the name of the font family used for math text. + + The default font is :rc:`mathtext.fontset`. + """ + return self._math_fontfamily + + def set_math_fontfamily(self, fontfamily): + """ + Set the font family for text in math mode. + + If not set explicitly, :rc:`mathtext.fontset` will be used. + + Parameters + ---------- + fontfamily : str + The name of the font family. + + Available font families are defined in the + :ref:`default matplotlibrc file `. + + See Also + -------- + .text.Text.get_math_fontfamily + """ + if fontfamily is None: + fontfamily = mpl.rcParams['mathtext.fontset'] + else: + valid_fonts = _validators['mathtext.fontset'].valid.values() + # _check_in_list() Validates the parameter math_fontfamily as + # if it were passed to rcParams['mathtext.fontset'] + _api.check_in_list(valid_fonts, math_fontfamily=fontfamily) + self._math_fontfamily = fontfamily + + def copy(self): + """Return a copy of self.""" + return copy.copy(self) + + # Aliases + set_name = set_family + get_slant = get_style + set_slant = set_style + get_size_in_points = get_size + + +class _JSONEncoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, FontManager): + return dict(o.__dict__, __class__='FontManager') + elif isinstance(o, FontEntry): + d = dict(o.__dict__, __class__='FontEntry') + try: + # Cache paths of fonts shipped with Matplotlib relative to the + # Matplotlib data path, which helps in the presence of venvs. + d["fname"] = str(Path(d["fname"]).relative_to(mpl.get_data_path())) + except ValueError: + pass + return d + else: + return super().default(o) + + +def _json_decode(o): + cls = o.pop('__class__', None) + if cls is None: + return o + elif cls == 'FontManager': + r = FontManager.__new__(FontManager) + r.__dict__.update(o) + return r + elif cls == 'FontEntry': + if not os.path.isabs(o['fname']): + o['fname'] = os.path.join(mpl.get_data_path(), o['fname']) + r = FontEntry(**o) + return r + else: + raise ValueError("Don't know how to deserialize __class__=%s" % cls) + + +def json_dump(data, filename): + """ + Dump `FontManager` *data* as JSON to the file named *filename*. + + See Also + -------- + json_load + + Notes + ----- + File paths that are children of the Matplotlib data path (typically, fonts + shipped with Matplotlib) are stored relative to that data path (to remain + valid across virtualenvs). + + This function temporarily locks the output file to prevent multiple + processes from overwriting one another's output. + """ + try: + with cbook._lock_path(filename), open(filename, 'w') as fh: + json.dump(data, fh, cls=_JSONEncoder, indent=2) + except OSError as e: + _log.warning('Could not save font_manager cache %s', e) + + +def json_load(filename): + """ + Load a `FontManager` from the JSON file named *filename*. + + See Also + -------- + json_dump + """ + with open(filename) as fh: + return json.load(fh, object_hook=_json_decode) + + +class FontManager: + """ + On import, the `FontManager` singleton instance creates a list of ttf and + afm fonts and caches their `FontProperties`. The `FontManager.findfont` + method does a nearest neighbor search to find the font that most closely + matches the specification. If no good enough match is found, the default + font is returned. + + Fonts added with the `FontManager.addfont` method will not persist in the + cache; therefore, `addfont` will need to be called every time Matplotlib is + imported. This method should only be used if and when a font cannot be + installed on your operating system by other means. + + Notes + ----- + The `FontManager.addfont` method must be called on the global `FontManager` + instance. + + Example usage:: + + import matplotlib.pyplot as plt + from matplotlib import font_manager + + font_dirs = ["/resources/fonts"] # The path to the custom font file. + font_files = font_manager.findSystemFonts(fontpaths=font_dirs) + + for font_file in font_files: + font_manager.fontManager.addfont(font_file) + """ + # Increment this version number whenever the font cache data + # format or behavior has changed and requires an existing font + # cache files to be rebuilt. + __version__ = 390 + + def __init__(self, size=None, weight='normal'): + self._version = self.__version__ + + self.__default_weight = weight + self.default_size = size + + # Create list of font paths. + paths = [cbook._get_data_path('fonts', subdir) + for subdir in ['ttf', 'afm', 'pdfcorefonts']] + _log.debug('font search path %s', paths) + + self.defaultFamily = { + 'ttf': 'DejaVu Sans', + 'afm': 'Helvetica'} + + self.afmlist = [] + self.ttflist = [] + + # Delay the warning by 5s. + timer = threading.Timer(5, lambda: _log.warning( + 'Matplotlib is building the font cache; this may take a moment.')) + timer.start() + try: + for fontext in ["afm", "ttf"]: + for path in [*findSystemFonts(paths, fontext=fontext), + *findSystemFonts(fontext=fontext)]: + try: + self.addfont(path) + except OSError as exc: + _log.info("Failed to open font file %s: %s", path, exc) + except Exception as exc: + _log.info("Failed to extract font properties from %s: " + "%s", path, exc) + finally: + timer.cancel() + + def addfont(self, path): + """ + Cache the properties of the font at *path* to make it available to the + `FontManager`. The type of font is inferred from the path suffix. + + Parameters + ---------- + path : str or path-like + + Notes + ----- + This method is useful for adding a custom font without installing it in + your operating system. See the `FontManager` singleton instance for + usage and caveats about this function. + """ + # Convert to string in case of a path as + # afmFontProperty and FT2Font expect this + path = os.fsdecode(path) + if Path(path).suffix.lower() == ".afm": + with open(path, "rb") as fh: + font = _afm.AFM(fh) + prop = afmFontProperty(path, font) + self.afmlist.append(prop) + else: + font = ft2font.FT2Font(path) + prop = ttfFontProperty(font) + self.ttflist.append(prop) + self._findfont_cached.cache_clear() + + @property + def defaultFont(self): + # Lazily evaluated (findfont then caches the result) to avoid including + # the venv path in the json serialization. + return {ext: self.findfont(family, fontext=ext) + for ext, family in self.defaultFamily.items()} + + def get_default_weight(self): + """ + Return the default font weight. + """ + return self.__default_weight + + @staticmethod + def get_default_size(): + """ + Return the default font size. + """ + return mpl.rcParams['font.size'] + + def set_default_weight(self, weight): + """ + Set the default font weight. The initial value is 'normal'. + """ + self.__default_weight = weight + + @staticmethod + def _expand_aliases(family): + if family in ('sans', 'sans serif'): + family = 'sans-serif' + return mpl.rcParams['font.' + family] + + # Each of the scoring functions below should return a value between + # 0.0 (perfect match) and 1.0 (terrible match) + def score_family(self, families, family2): + """ + Return a match score between the list of font families in + *families* and the font family name *family2*. + + An exact match at the head of the list returns 0.0. + + A match further down the list will return between 0 and 1. + + No match will return 1.0. + """ + if not isinstance(families, (list, tuple)): + families = [families] + elif len(families) == 0: + return 1.0 + family2 = family2.lower() + step = 1 / len(families) + for i, family1 in enumerate(families): + family1 = family1.lower() + if family1 in font_family_aliases: + options = [*map(str.lower, self._expand_aliases(family1))] + if family2 in options: + idx = options.index(family2) + return (i + (idx / len(options))) * step + elif family1 == family2: + # The score should be weighted by where in the + # list the font was found. + return i * step + return 1.0 + + def score_style(self, style1, style2): + """ + Return a match score between *style1* and *style2*. + + An exact match returns 0.0. + + A match between 'italic' and 'oblique' returns 0.1. + + No match returns 1.0. + """ + if style1 == style2: + return 0.0 + elif (style1 in ('italic', 'oblique') + and style2 in ('italic', 'oblique')): + return 0.1 + return 1.0 + + def score_variant(self, variant1, variant2): + """ + Return a match score between *variant1* and *variant2*. + + An exact match returns 0.0, otherwise 1.0. + """ + if variant1 == variant2: + return 0.0 + else: + return 1.0 + + def score_stretch(self, stretch1, stretch2): + """ + Return a match score between *stretch1* and *stretch2*. + + The result is the absolute value of the difference between the + CSS numeric values of *stretch1* and *stretch2*, normalized + between 0.0 and 1.0. + """ + try: + stretchval1 = int(stretch1) + except ValueError: + stretchval1 = stretch_dict.get(stretch1, 500) + try: + stretchval2 = int(stretch2) + except ValueError: + stretchval2 = stretch_dict.get(stretch2, 500) + return abs(stretchval1 - stretchval2) / 1000.0 + + def score_weight(self, weight1, weight2): + """ + Return a match score between *weight1* and *weight2*. + + The result is 0.0 if both weight1 and weight 2 are given as strings + and have the same value. + + Otherwise, the result is the absolute value of the difference between + the CSS numeric values of *weight1* and *weight2*, normalized between + 0.05 and 1.0. + """ + # exact match of the weight names, e.g. weight1 == weight2 == "regular" + if cbook._str_equal(weight1, weight2): + return 0.0 + w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1] + w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2] + return 0.95 * (abs(w1 - w2) / 1000) + 0.05 + + def score_size(self, size1, size2): + """ + Return a match score between *size1* and *size2*. + + If *size2* (the size specified in the font file) is 'scalable', this + function always returns 0.0, since any font size can be generated. + + Otherwise, the result is the absolute distance between *size1* and + *size2*, normalized so that the usual range of font sizes (6pt - + 72pt) will lie between 0.0 and 1.0. + """ + if size2 == 'scalable': + return 0.0 + # Size value should have already been + try: + sizeval1 = float(size1) + except ValueError: + sizeval1 = self.default_size * font_scalings[size1] + try: + sizeval2 = float(size2) + except ValueError: + return 1.0 + return abs(sizeval1 - sizeval2) / 72 + + def findfont(self, prop, fontext='ttf', directory=None, + fallback_to_default=True, rebuild_if_missing=True): + """ + Find the path to the font file most closely matching the given font properties. + + Parameters + ---------- + prop : str or `~matplotlib.font_manager.FontProperties` + The font properties to search for. This can be either a + `.FontProperties` object or a string defining a + `fontconfig patterns`_. + + fontext : {'ttf', 'afm'}, default: 'ttf' + The extension of the font file: + + - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf) + - 'afm': Adobe Font Metrics (.afm) + + directory : str, optional + If given, only search this directory and its subdirectories. + + fallback_to_default : bool + If True, will fall back to the default font family (usually + "DejaVu Sans" or "Helvetica") if the first lookup hard-fails. + + rebuild_if_missing : bool + Whether to rebuild the font cache and search again if the first + match appears to point to a nonexisting font (i.e., the font cache + contains outdated entries). + + Returns + ------- + str + The filename of the best matching font. + + Notes + ----- + This performs a nearest neighbor search. Each font is given a + similarity score to the target font properties. The first font with + the highest score is returned. If no matches below a certain + threshold are found, the default font (usually DejaVu Sans) is + returned. + + The result is cached, so subsequent lookups don't have to + perform the O(n) nearest neighbor search. + + See the `W3C Cascading Style Sheet, Level 1 + `_ documentation + for a description of the font finding algorithm. + + .. _fontconfig patterns: + https://www.freedesktop.org/software/fontconfig/fontconfig-user.html + """ + # Pass the relevant rcParams (and the font manager, as `self`) to + # _findfont_cached so to prevent using a stale cache entry after an + # rcParam was changed. + rc_params = tuple(tuple(mpl.rcParams[key]) for key in [ + "font.serif", "font.sans-serif", "font.cursive", "font.fantasy", + "font.monospace"]) + ret = self._findfont_cached( + prop, fontext, directory, fallback_to_default, rebuild_if_missing, + rc_params) + if isinstance(ret, cbook._ExceptionInfo): + raise ret.to_exception() + return ret + + def get_font_names(self): + """Return the list of available fonts.""" + return list({font.name for font in self.ttflist}) + + def _find_fonts_by_props(self, prop, fontext='ttf', directory=None, + fallback_to_default=True, rebuild_if_missing=True): + """ + Find the paths to the font files most closely matching the given properties. + + Parameters + ---------- + prop : str or `~matplotlib.font_manager.FontProperties` + The font properties to search for. This can be either a + `.FontProperties` object or a string defining a + `fontconfig patterns`_. + + fontext : {'ttf', 'afm'}, default: 'ttf' + The extension of the font file: + + - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf) + - 'afm': Adobe Font Metrics (.afm) + + directory : str, optional + If given, only search this directory and its subdirectories. + + fallback_to_default : bool + If True, will fall back to the default font family (usually + "DejaVu Sans" or "Helvetica") if none of the families were found. + + rebuild_if_missing : bool + Whether to rebuild the font cache and search again if the first + match appears to point to a nonexisting font (i.e., the font cache + contains outdated entries). + + Returns + ------- + list[str] + The paths of the fonts found. + + Notes + ----- + This is an extension/wrapper of the original findfont API, which only + returns a single font for given font properties. Instead, this API + returns a list of filepaths of multiple fonts which closely match the + given font properties. Since this internally uses the original API, + there's no change to the logic of performing the nearest neighbor + search. See `findfont` for more details. + """ + + prop = FontProperties._from_any(prop) + + fpaths = [] + for family in prop.get_family(): + cprop = prop.copy() + cprop.set_family(family) # set current prop's family + + try: + fpaths.append( + self.findfont( + cprop, fontext, directory, + fallback_to_default=False, # don't fallback to default + rebuild_if_missing=rebuild_if_missing, + ) + ) + except ValueError: + if family in font_family_aliases: + _log.warning( + "findfont: Generic family %r not found because " + "none of the following families were found: %s", + family, ", ".join(self._expand_aliases(family)) + ) + else: + _log.warning("findfont: Font family %r not found.", family) + + # only add default family if no other font was found and + # fallback_to_default is enabled + if not fpaths: + if fallback_to_default: + dfamily = self.defaultFamily[fontext] + cprop = prop.copy() + cprop.set_family(dfamily) + fpaths.append( + self.findfont( + cprop, fontext, directory, + fallback_to_default=True, + rebuild_if_missing=rebuild_if_missing, + ) + ) + else: + raise ValueError("Failed to find any font, and fallback " + "to the default font was disabled") + + return fpaths + + @lru_cache(1024) + def _findfont_cached(self, prop, fontext, directory, fallback_to_default, + rebuild_if_missing, rc_params): + + prop = FontProperties._from_any(prop) + + fname = prop.get_file() + if fname is not None: + return fname + + if fontext == 'afm': + fontlist = self.afmlist + else: + fontlist = self.ttflist + + best_score = 1e64 + best_font = None + + _log.debug('findfont: Matching %s.', prop) + for font in fontlist: + if (directory is not None and + Path(directory) not in Path(font.fname).parents): + continue + # Matching family should have top priority, so multiply it by 10. + score = (self.score_family(prop.get_family(), font.name) * 10 + + self.score_style(prop.get_style(), font.style) + + self.score_variant(prop.get_variant(), font.variant) + + self.score_weight(prop.get_weight(), font.weight) + + self.score_stretch(prop.get_stretch(), font.stretch) + + self.score_size(prop.get_size(), font.size)) + _log.debug('findfont: score(%s) = %s', font, score) + if score < best_score: + best_score = score + best_font = font + if score == 0: + break + + if best_font is None or best_score >= 10.0: + if fallback_to_default: + _log.warning( + 'findfont: Font family %s not found. Falling back to %s.', + prop.get_family(), self.defaultFamily[fontext]) + for family in map(str.lower, prop.get_family()): + if family in font_family_aliases: + _log.warning( + "findfont: Generic family %r not found because " + "none of the following families were found: %s", + family, ", ".join(self._expand_aliases(family))) + default_prop = prop.copy() + default_prop.set_family(self.defaultFamily[fontext]) + return self.findfont(default_prop, fontext, directory, + fallback_to_default=False) + else: + # This return instead of raise is intentional, as we wish to + # cache that it was not found, which will not occur if it was + # actually raised. + return cbook._ExceptionInfo( + ValueError, + f"Failed to find font {prop}, and fallback to the default font was " + f"disabled" + ) + else: + _log.debug('findfont: Matching %s to %s (%r) with score of %f.', + prop, best_font.name, best_font.fname, best_score) + result = best_font.fname + + if not os.path.isfile(result): + if rebuild_if_missing: + _log.info( + 'findfont: Found a missing font file. Rebuilding cache.') + new_fm = _load_fontmanager(try_read_cache=False) + # Replace self by the new fontmanager, because users may have + # a reference to this specific instance. + # TODO: _load_fontmanager should really be (used by) a method + # modifying the instance in place. + vars(self).update(vars(new_fm)) + return self.findfont( + prop, fontext, directory, rebuild_if_missing=False) + else: + # This return instead of raise is intentional, as we wish to + # cache that it was not found, which will not occur if it was + # actually raised. + return cbook._ExceptionInfo(ValueError, "No valid font could be found") + + return _cached_realpath(result) + + +@lru_cache +def is_opentype_cff_font(filename): + """ + Return whether the given font is a Postscript Compact Font Format Font + embedded in an OpenType wrapper. Used by the PostScript and PDF backends + that cannot subset these fonts. + """ + if os.path.splitext(filename)[1].lower() == '.otf': + with open(filename, 'rb') as fd: + return fd.read(4) == b"OTTO" + else: + return False + + +@lru_cache(64) +def _get_font(font_filepaths, hinting_factor, *, _kerning_factor, thread_id): + first_fontpath, *rest = font_filepaths + return ft2font.FT2Font( + first_fontpath, hinting_factor, + _fallback_list=[ + ft2font.FT2Font( + fpath, hinting_factor, + _kerning_factor=_kerning_factor + ) + for fpath in rest + ], + _kerning_factor=_kerning_factor + ) + + +# FT2Font objects cannot be used across fork()s because they reference the same +# FT_Library object. While invalidating *all* existing FT2Fonts after a fork +# would be too complicated to be worth it, the main way FT2Fonts get reused is +# via the cache of _get_font, which we can empty upon forking (not on Windows, +# which has no fork() or register_at_fork()). +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_get_font.cache_clear) + + +@lru_cache(64) +def _cached_realpath(path): + # Resolving the path avoids embedding the font twice in pdf/ps output if a + # single font is selected using two different relative paths. + return os.path.realpath(path) + + +def get_font(font_filepaths, hinting_factor=None): + """ + Get an `.ft2font.FT2Font` object given a list of file paths. + + Parameters + ---------- + font_filepaths : Iterable[str, Path, bytes], str, Path, bytes + Relative or absolute paths to the font files to be used. + + If a single string, bytes, or `pathlib.Path`, then it will be treated + as a list with that entry only. + + If more than one filepath is passed, then the returned FT2Font object + will fall back through the fonts, in the order given, to find a needed + glyph. + + Returns + ------- + `.ft2font.FT2Font` + + """ + if isinstance(font_filepaths, (str, Path, bytes)): + paths = (_cached_realpath(font_filepaths),) + else: + paths = tuple(_cached_realpath(fname) for fname in font_filepaths) + + if hinting_factor is None: + hinting_factor = mpl.rcParams['text.hinting_factor'] + + return _get_font( + # must be a tuple to be cached + paths, + hinting_factor, + _kerning_factor=mpl.rcParams['text.kerning_factor'], + # also key on the thread ID to prevent segfaults with multi-threading + thread_id=threading.get_ident() + ) + + +def _load_fontmanager(*, try_read_cache=True): + fm_path = Path( + mpl.get_cachedir(), f"fontlist-v{FontManager.__version__}.json") + if try_read_cache: + try: + fm = json_load(fm_path) + except Exception: + pass + else: + if getattr(fm, "_version", object()) == FontManager.__version__: + _log.debug("Using fontManager instance from %s", fm_path) + return fm + fm = FontManager() + json_dump(fm, fm_path) + _log.info("generated new fontManager") + return fm + + +fontManager = _load_fontmanager() +findfont = fontManager.findfont +get_font_names = fontManager.get_font_names diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/offsetbox.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/offsetbox.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3b1520e171385a334e0b4893de6bf152c379c52a --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/matplotlib/offsetbox.pyi @@ -0,0 +1,298 @@ +import matplotlib.artist as martist +from matplotlib.backend_bases import RendererBase, Event, FigureCanvasBase +from matplotlib.colors import Colormap, Normalize +import matplotlib.text as mtext +from matplotlib.figure import Figure, SubFigure +from matplotlib.font_manager import FontProperties +from matplotlib.image import BboxImage +from matplotlib.patches import FancyArrowPatch, FancyBboxPatch +from matplotlib.transforms import Bbox, BboxBase, Transform +from matplotlib.typing import CoordsType + +import numpy as np +from numpy.typing import ArrayLike +from collections.abc import Callable, Sequence +from typing import Any, Literal, overload + +DEBUG: bool + +def _get_packed_offsets( + widths: Sequence[float], + total: float | None, + sep: float | None, + mode: Literal["fixed", "expand", "equal"] = ..., +) -> tuple[float, np.ndarray]: ... + +class OffsetBox(martist.Artist): + width: float | None + height: float | None + def __init__(self, *args, **kwargs) -> None: ... + def set_figure(self, fig: Figure | SubFigure) -> None: ... + def set_offset( + self, + xy: tuple[float, float] + | Callable[[float, float, float, float, RendererBase], tuple[float, float]], + ) -> None: ... + + @overload + def get_offset(self, bbox: Bbox, renderer: RendererBase) -> tuple[float, float]: ... + @overload + def get_offset( + self, + width: float, + height: float, + xdescent: float, + ydescent: float, + renderer: RendererBase + ) -> tuple[float, float]: ... + + def set_width(self, width: float) -> None: ... + def set_height(self, height: float) -> None: ... + def get_visible_children(self) -> list[martist.Artist]: ... + def get_children(self) -> list[martist.Artist]: ... + def get_bbox(self, renderer: RendererBase) -> Bbox: ... + def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ... + +class PackerBase(OffsetBox): + height: float | None + width: float | None + sep: float | None + pad: float | None + mode: Literal["fixed", "expand", "equal"] + align: Literal["top", "bottom", "left", "right", "center", "baseline"] + def __init__( + self, + pad: float | None = ..., + sep: float | None = ..., + width: float | None = ..., + height: float | None = ..., + align: Literal["top", "bottom", "left", "right", "center", "baseline"] = ..., + mode: Literal["fixed", "expand", "equal"] = ..., + children: list[martist.Artist] | None = ..., + ) -> None: ... + +class VPacker(PackerBase): ... +class HPacker(PackerBase): ... + +class PaddedBox(OffsetBox): + pad: float | None + patch: FancyBboxPatch + def __init__( + self, + child: martist.Artist, + pad: float | None = ..., + *, + draw_frame: bool = ..., + patch_attrs: dict[str, Any] | None = ..., + ) -> None: ... + def update_frame(self, bbox: Bbox, fontsize: float | None = ...) -> None: ... + def draw_frame(self, renderer: RendererBase) -> None: ... + +class DrawingArea(OffsetBox): + width: float + height: float + xdescent: float + ydescent: float + offset_transform: Transform + dpi_transform: Transform + def __init__( + self, + width: float, + height: float, + xdescent: float = ..., + ydescent: float = ..., + clip: bool = ..., + ) -> None: ... + @property + def clip_children(self) -> bool: ... + @clip_children.setter + def clip_children(self, val: bool) -> None: ... + def get_transform(self) -> Transform: ... + + # does not accept all options of superclass + def set_offset(self, xy: tuple[float, float]) -> None: ... # type: ignore[override] + def get_offset(self) -> tuple[float, float]: ... # type: ignore[override] + def add_artist(self, a: martist.Artist) -> None: ... + +class TextArea(OffsetBox): + offset_transform: Transform + def __init__( + self, + s: str, + *, + textprops: dict[str, Any] | None = ..., + multilinebaseline: bool = ..., + ) -> None: ... + def set_text(self, s: str) -> None: ... + def get_text(self) -> str: ... + def set_multilinebaseline(self, t: bool) -> None: ... + def get_multilinebaseline(self) -> bool: ... + + # does not accept all options of superclass + def set_offset(self, xy: tuple[float, float]) -> None: ... # type: ignore[override] + def get_offset(self) -> tuple[float, float]: ... # type: ignore[override] + +class AuxTransformBox(OffsetBox): + aux_transform: Transform + offset_transform: Transform + ref_offset_transform: Transform + def __init__(self, aux_transform: Transform) -> None: ... + def add_artist(self, a: martist.Artist) -> None: ... + def get_transform(self) -> Transform: ... + + # does not accept all options of superclass + def set_offset(self, xy: tuple[float, float]) -> None: ... # type: ignore[override] + def get_offset(self) -> tuple[float, float]: ... # type: ignore[override] + +class AnchoredOffsetbox(OffsetBox): + zorder: float + codes: dict[str, int] + loc: int + borderpad: float + pad: float + prop: FontProperties + patch: FancyBboxPatch + def __init__( + self, + loc: str, + *, + pad: float = ..., + borderpad: float = ..., + child: OffsetBox | None = ..., + prop: FontProperties | None = ..., + frameon: bool = ..., + bbox_to_anchor: BboxBase + | tuple[float, float] + | tuple[float, float, float, float] + | None = ..., + bbox_transform: Transform | None = ..., + **kwargs + ) -> None: ... + def set_child(self, child: OffsetBox | None) -> None: ... + def get_child(self) -> OffsetBox | None: ... + def get_children(self) -> list[martist.Artist]: ... + def get_bbox_to_anchor(self) -> Bbox: ... + def set_bbox_to_anchor( + self, bbox: BboxBase, transform: Transform | None = ... + ) -> None: ... + def update_frame(self, bbox: Bbox, fontsize: float | None = ...) -> None: ... + +class AnchoredText(AnchoredOffsetbox): + txt: TextArea + def __init__( + self, + s: str, + loc: str, + *, + pad: float = ..., + borderpad: float = ..., + prop: dict[str, Any] | None = ..., + **kwargs + ) -> None: ... + +class OffsetImage(OffsetBox): + image: BboxImage + def __init__( + self, + arr: ArrayLike, + *, + zoom: float = ..., + cmap: Colormap | str | None = ..., + norm: Normalize | str | None = ..., + interpolation: str | None = ..., + origin: Literal["upper", "lower"] | None = ..., + filternorm: bool = ..., + filterrad: float = ..., + resample: bool = ..., + dpi_cor: bool = ..., + **kwargs + ) -> None: ... + stale: bool + def set_data(self, arr: ArrayLike | None) -> None: ... + def get_data(self) -> ArrayLike | None: ... + def set_zoom(self, zoom: float) -> None: ... + def get_zoom(self) -> float: ... + def get_children(self) -> list[martist.Artist]: ... + def get_offset(self) -> tuple[float, float]: ... # type: ignore[override] + +class AnnotationBbox(martist.Artist, mtext._AnnotationBase): + zorder: float + offsetbox: OffsetBox + arrowprops: dict[str, Any] | None + xybox: tuple[float, float] + boxcoords: CoordsType + arrow_patch: FancyArrowPatch | None + patch: FancyBboxPatch + prop: FontProperties + def __init__( + self, + offsetbox: OffsetBox, + xy: tuple[float, float], + xybox: tuple[float, float] | None = ..., + xycoords: CoordsType = ..., + boxcoords: CoordsType | None = ..., + *, + frameon: bool = ..., + pad: float = ..., + annotation_clip: bool | None = ..., + box_alignment: tuple[float, float] = ..., + bboxprops: dict[str, Any] | None = ..., + arrowprops: dict[str, Any] | None = ..., + fontsize: float | str | None = ..., + **kwargs + ) -> None: ... + @property + def xyann(self) -> tuple[float, float]: ... + @xyann.setter + def xyann(self, xyann: tuple[float, float]) -> None: ... + @property + def anncoords( + self, + ) -> CoordsType: ... + @anncoords.setter + def anncoords( + self, + coords: CoordsType, + ) -> None: ... + def get_children(self) -> list[martist.Artist]: ... + def set_figure(self, fig: Figure | SubFigure) -> None: ... + def set_fontsize(self, s: str | float | None = ...) -> None: ... + def get_fontsize(self) -> float: ... + def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox: ... + def update_positions(self, renderer: RendererBase) -> None: ... + +class DraggableBase: + ref_artist: martist.Artist + got_artist: bool + mouse_x: int + mouse_y: int + background: Any + + @property + def canvas(self) -> FigureCanvasBase: ... + @property + def cids(self) -> list[int]: ... + + def __init__(self, ref_artist: martist.Artist, use_blit: bool = ...) -> None: ... + def on_motion(self, evt: Event) -> None: ... + def on_pick(self, evt: Event) -> None: ... + def on_release(self, event: Event) -> None: ... + def disconnect(self) -> None: ... + def save_offset(self) -> None: ... + def update_offset(self, dx: float, dy: float) -> None: ... + def finalize_offset(self) -> None: ... + +class DraggableOffsetBox(DraggableBase): + offsetbox: OffsetBox + def __init__( + self, ref_artist: martist.Artist, offsetbox: OffsetBox, use_blit: bool = ... + ) -> None: ... + def save_offset(self) -> None: ... + def update_offset(self, dx: float, dy: float) -> None: ... + def get_loc_in_canvas(self) -> tuple[float, float]: ... + +class DraggableAnnotation(DraggableBase): + annotation: mtext.Annotation + def __init__(self, annotation: mtext.Annotation, use_blit: bool = ...) -> None: ... + def save_offset(self) -> None: ... + def update_offset(self, dx: float, dy: float) -> None: ... diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/text.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/text.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d65a3dc4c7da2754b35e59f79e47318e55effa7e --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/matplotlib/text.pyi @@ -0,0 +1,181 @@ +from .artist import Artist +from .backend_bases import RendererBase +from .font_manager import FontProperties +from .offsetbox import DraggableAnnotation +from .path import Path +from .patches import FancyArrowPatch, FancyBboxPatch +from .textpath import ( # noqa: F401, reexported API + TextPath as TextPath, + TextToPath as TextToPath, +) +from .transforms import ( + Bbox, + BboxBase, + Transform, +) + +from collections.abc import Callable, Iterable +from typing import Any, Literal +from .typing import ColorType, CoordsType + +class Text(Artist): + zorder: float + def __init__( + self, + x: float = ..., + y: float = ..., + text: Any = ..., + *, + color: ColorType | None = ..., + verticalalignment: Literal[ + "bottom", "baseline", "center", "center_baseline", "top" + ] = ..., + horizontalalignment: Literal["left", "center", "right"] = ..., + multialignment: Literal["left", "center", "right"] | None = ..., + fontproperties: str | Path | FontProperties | None = ..., + rotation: float | Literal["vertical", "horizontal"] | None = ..., + linespacing: float | None = ..., + rotation_mode: Literal["default", "anchor"] | None = ..., + usetex: bool | None = ..., + wrap: bool = ..., + transform_rotates_text: bool = ..., + parse_math: bool | None = ..., + antialiased: bool | None = ..., + **kwargs + ) -> None: ... + def update(self, kwargs: dict[str, Any]) -> list[Any]: ... + def get_rotation(self) -> float: ... + def get_transform_rotates_text(self) -> bool: ... + def set_rotation_mode(self, m: None | Literal["default", "anchor"]) -> None: ... + def get_rotation_mode(self) -> Literal["default", "anchor"]: ... + def set_bbox(self, rectprops: dict[str, Any]) -> None: ... + def get_bbox_patch(self) -> None | FancyBboxPatch: ... + def update_bbox_position_size(self, renderer: RendererBase) -> None: ... + def get_wrap(self) -> bool: ... + def set_wrap(self, wrap: bool) -> None: ... + def get_color(self) -> ColorType: ... + def get_fontproperties(self) -> FontProperties: ... + def get_fontfamily(self) -> list[str]: ... + def get_fontname(self) -> str: ... + def get_fontstyle(self) -> Literal["normal", "italic", "oblique"]: ... + def get_fontsize(self) -> float | str: ... + def get_fontvariant(self) -> Literal["normal", "small-caps"]: ... + def get_fontweight(self) -> int | str: ... + def get_stretch(self) -> int | str: ... + def get_horizontalalignment(self) -> Literal["left", "center", "right"]: ... + def get_unitless_position(self) -> tuple[float, float]: ... + def get_position(self) -> tuple[float, float]: ... + def get_text(self) -> str: ... + def get_verticalalignment( + self, + ) -> Literal["bottom", "baseline", "center", "center_baseline", "top"]: ... + def get_window_extent( + self, renderer: RendererBase | None = ..., dpi: float | None = ... + ) -> Bbox: ... + def set_backgroundcolor(self, color: ColorType) -> None: ... + def set_color(self, color: ColorType) -> None: ... + def set_horizontalalignment( + self, align: Literal["left", "center", "right"] + ) -> None: ... + def set_multialignment(self, align: Literal["left", "center", "right"]) -> None: ... + def set_linespacing(self, spacing: float) -> None: ... + def set_fontfamily(self, fontname: str | Iterable[str]) -> None: ... + def set_fontvariant(self, variant: Literal["normal", "small-caps"]) -> None: ... + def set_fontstyle( + self, fontstyle: Literal["normal", "italic", "oblique"] + ) -> None: ... + def set_fontsize(self, fontsize: float | str) -> None: ... + def get_math_fontfamily(self) -> str: ... + def set_math_fontfamily(self, fontfamily: str) -> None: ... + def set_fontweight(self, weight: int | str) -> None: ... + def set_fontstretch(self, stretch: int | str) -> None: ... + def set_position(self, xy: tuple[float, float]) -> None: ... + def set_x(self, x: float) -> None: ... + def set_y(self, y: float) -> None: ... + def set_rotation(self, s: float) -> None: ... + def set_transform_rotates_text(self, t: bool) -> None: ... + def set_verticalalignment( + self, align: Literal["bottom", "baseline", "center", "center_baseline", "top"] + ) -> None: ... + def set_text(self, s: Any) -> None: ... + def set_fontproperties(self, fp: FontProperties | str | Path | None) -> None: ... + def set_usetex(self, usetex: bool | None) -> None: ... + def get_usetex(self) -> bool: ... + def set_parse_math(self, parse_math: bool) -> None: ... + def get_parse_math(self) -> bool: ... + def set_fontname(self, fontname: str | Iterable[str]) -> None: ... + def get_antialiased(self) -> bool: ... + def set_antialiased(self, antialiased: bool) -> None: ... + +class OffsetFrom: + def __init__( + self, + artist: Artist | BboxBase | Transform, + ref_coord: tuple[float, float], + unit: Literal["points", "pixels"] = ..., + ) -> None: ... + def set_unit(self, unit: Literal["points", "pixels"]) -> None: ... + def get_unit(self) -> Literal["points", "pixels"]: ... + def __call__(self, renderer: RendererBase) -> Transform: ... + +class _AnnotationBase: + xy: tuple[float, float] + xycoords: CoordsType + def __init__( + self, + xy, + xycoords: CoordsType = ..., + annotation_clip: bool | None = ..., + ) -> None: ... + def set_annotation_clip(self, b: bool | None) -> None: ... + def get_annotation_clip(self) -> bool | None: ... + def draggable( + self, state: bool | None = ..., use_blit: bool = ... + ) -> DraggableAnnotation | None: ... + +class Annotation(Text, _AnnotationBase): + arrowprops: dict[str, Any] | None + arrow_patch: FancyArrowPatch | None + def __init__( + self, + text: str, + xy: tuple[float, float], + xytext: tuple[float, float] | None = ..., + xycoords: CoordsType = ..., + textcoords: CoordsType | None = ..., + arrowprops: dict[str, Any] | None = ..., + annotation_clip: bool | None = ..., + **kwargs + ) -> None: ... + @property + def xycoords( + self, + ) -> CoordsType: ... + @xycoords.setter + def xycoords( + self, + xycoords: CoordsType, + ) -> None: ... + @property + def xyann(self) -> tuple[float, float]: ... + @xyann.setter + def xyann(self, xytext: tuple[float, float]) -> None: ... + def get_anncoords( + self, + ) -> CoordsType: ... + def set_anncoords( + self, + coords: CoordsType, + ) -> None: ... + @property + def anncoords( + self, + ) -> CoordsType: ... + @anncoords.setter + def anncoords( + self, + coords: CoordsType, + ) -> None: ... + def update_positions(self, renderer: RendererBase) -> None: ... + # Drops `dpi` parameter from superclass + def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ... # type: ignore[override] diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/textpath.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/textpath.pyi new file mode 100644 index 0000000000000000000000000000000000000000..34d4e92ac47ef45c70ab906bc3b8d1fa2bac07dd --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/matplotlib/textpath.pyi @@ -0,0 +1,74 @@ +from matplotlib.font_manager import FontProperties +from matplotlib.ft2font import FT2Font +from matplotlib.mathtext import MathTextParser, VectorParse +from matplotlib.path import Path + +import numpy as np + +from typing import Literal + +class TextToPath: + FONT_SCALE: float + DPI: float + mathtext_parser: MathTextParser[VectorParse] + def __init__(self) -> None: ... + def get_text_width_height_descent( + self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"] + ) -> tuple[float, float, float]: ... + def get_text_path( + self, prop: FontProperties, s: str, ismath: bool | Literal["TeX"] = ... + ) -> list[np.ndarray]: ... + def get_glyphs_with_font( + self, + font: FT2Font, + s: str, + glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ..., + return_new_glyphs_only: bool = ..., + ) -> tuple[ + list[tuple[str, float, float, float]], + dict[str, tuple[np.ndarray, np.ndarray]], + list[tuple[list[tuple[float, float]], list[int]]], + ]: ... + def get_glyphs_mathtext( + self, + prop: FontProperties, + s: str, + glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ..., + return_new_glyphs_only: bool = ..., + ) -> tuple[ + list[tuple[str, float, float, float]], + dict[str, tuple[np.ndarray, np.ndarray]], + list[tuple[list[tuple[float, float]], list[int]]], + ]: ... + def get_glyphs_tex( + self, + prop: FontProperties, + s: str, + glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ..., + return_new_glyphs_only: bool = ..., + ) -> tuple[ + list[tuple[str, float, float, float]], + dict[str, tuple[np.ndarray, np.ndarray]], + list[tuple[list[tuple[float, float]], list[int]]], + ]: ... + +text_to_path: TextToPath + +class TextPath(Path): + def __init__( + self, + xy: tuple[float, float], + s: str, + size: float | None = ..., + prop: FontProperties | None = ..., + _interpolation_steps: int = ..., + usetex: bool = ..., + ) -> None: ... + def set_size(self, size: float | None) -> None: ... + def get_size(self) -> float | None: ... + + # These are read only... there actually are protections in the base class, so probably can be deleted... + @property # type: ignore[misc] + def vertices(self) -> np.ndarray: ... # type: ignore[override] + @property # type: ignore[misc] + def codes(self) -> np.ndarray: ... # type: ignore[override] diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/transforms.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/transforms.pyi new file mode 100644 index 0000000000000000000000000000000000000000..551487a11c6015ba392d32fa1a86b5c7b61090e5 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/matplotlib/transforms.pyi @@ -0,0 +1,341 @@ +from .path import Path +from .patches import Patch +from .figure import Figure +import numpy as np +from numpy.typing import ArrayLike +from collections.abc import Iterable, Sequence +from typing import Literal + +DEBUG: bool + +class TransformNode: + INVALID_NON_AFFINE: int + INVALID_AFFINE: int + INVALID: int + is_bbox: bool + # Implemented as a standard attr in base class, but functionally readonly and some subclasses implement as such + @property + def is_affine(self) -> bool: ... + pass_through: bool + def __init__(self, shorthand_name: str | None = ...) -> None: ... + def __copy__(self) -> TransformNode: ... + def invalidate(self) -> None: ... + def set_children(self, *children: TransformNode) -> None: ... + def frozen(self) -> TransformNode: ... + +class BboxBase(TransformNode): + is_bbox: bool + is_affine: bool + def frozen(self) -> Bbox: ... + def __array__(self, *args, **kwargs): ... + @property + def x0(self) -> float: ... + @property + def y0(self) -> float: ... + @property + def x1(self) -> float: ... + @property + def y1(self) -> float: ... + @property + def p0(self) -> tuple[float, float]: ... + @property + def p1(self) -> tuple[float, float]: ... + @property + def xmin(self) -> float: ... + @property + def ymin(self) -> float: ... + @property + def xmax(self) -> float: ... + @property + def ymax(self) -> float: ... + @property + def min(self) -> tuple[float, float]: ... + @property + def max(self) -> tuple[float, float]: ... + @property + def intervalx(self) -> tuple[float, float]: ... + @property + def intervaly(self) -> tuple[float, float]: ... + @property + def width(self) -> float: ... + @property + def height(self) -> float: ... + @property + def size(self) -> tuple[float, float]: ... + @property + def bounds(self) -> tuple[float, float, float, float]: ... + @property + def extents(self) -> tuple[float, float, float, float]: ... + def get_points(self) -> np.ndarray: ... + def containsx(self, x: float) -> bool: ... + def containsy(self, y: float) -> bool: ... + def contains(self, x: float, y: float) -> bool: ... + def overlaps(self, other: BboxBase) -> bool: ... + def fully_containsx(self, x: float) -> bool: ... + def fully_containsy(self, y: float) -> bool: ... + def fully_contains(self, x: float, y: float) -> bool: ... + def fully_overlaps(self, other: BboxBase) -> bool: ... + def transformed(self, transform: Transform) -> Bbox: ... + coefs: dict[str, tuple[float, float]] + def anchored( + self, + c: tuple[float, float] | Literal['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'], + container: BboxBase, + ) -> Bbox: ... + def shrunk(self, mx: float, my: float) -> Bbox: ... + def shrunk_to_aspect( + self, + box_aspect: float, + container: BboxBase | None = ..., + fig_aspect: float = ..., + ) -> Bbox: ... + def splitx(self, *args: float) -> list[Bbox]: ... + def splity(self, *args: float) -> list[Bbox]: ... + def count_contains(self, vertices: ArrayLike) -> int: ... + def count_overlaps(self, bboxes: Iterable[BboxBase]) -> int: ... + def expanded(self, sw: float, sh: float) -> Bbox: ... + def padded(self, w_pad: float, h_pad: float | None = ...) -> Bbox: ... + def translated(self, tx: float, ty: float) -> Bbox: ... + def corners(self) -> np.ndarray: ... + def rotated(self, radians: float) -> Bbox: ... + @staticmethod + def union(bboxes: Sequence[BboxBase]) -> Bbox: ... + @staticmethod + def intersection(bbox1: BboxBase, bbox2: BboxBase) -> Bbox | None: ... + +class Bbox(BboxBase): + def __init__(self, points: ArrayLike, **kwargs) -> None: ... + @staticmethod + def unit() -> Bbox: ... + @staticmethod + def null() -> Bbox: ... + @staticmethod + def from_bounds(x0: float, y0: float, width: float, height: float) -> Bbox: ... + @staticmethod + def from_extents(*args: float, minpos: float | None = ...) -> Bbox: ... + def __format__(self, fmt: str) -> str: ... + def ignore(self, value: bool) -> None: ... + def update_from_path( + self, + path: Path, + ignore: bool | None = ..., + updatex: bool = ..., + updatey: bool = ..., + ) -> None: ... + def update_from_data_x(self, x: ArrayLike, ignore: bool | None = ...) -> None: ... + def update_from_data_y(self, y: ArrayLike, ignore: bool | None = ...) -> None: ... + def update_from_data_xy( + self, + xy: ArrayLike, + ignore: bool | None = ..., + updatex: bool = ..., + updatey: bool = ..., + ) -> None: ... + @property + def minpos(self) -> float: ... + @property + def minposx(self) -> float: ... + @property + def minposy(self) -> float: ... + def get_points(self) -> np.ndarray: ... + def set_points(self, points: ArrayLike) -> None: ... + def set(self, other: Bbox) -> None: ... + def mutated(self) -> bool: ... + def mutatedx(self) -> bool: ... + def mutatedy(self) -> bool: ... + +class TransformedBbox(BboxBase): + def __init__(self, bbox: Bbox, transform: Transform, **kwargs) -> None: ... + def get_points(self) -> np.ndarray: ... + +class LockableBbox(BboxBase): + def __init__( + self, + bbox: BboxBase, + x0: float | None = ..., + y0: float | None = ..., + x1: float | None = ..., + y1: float | None = ..., + **kwargs + ) -> None: ... + @property + def locked_x0(self) -> float | None: ... + @locked_x0.setter + def locked_x0(self, x0: float | None) -> None: ... + @property + def locked_y0(self) -> float | None: ... + @locked_y0.setter + def locked_y0(self, y0: float | None) -> None: ... + @property + def locked_x1(self) -> float | None: ... + @locked_x1.setter + def locked_x1(self, x1: float | None) -> None: ... + @property + def locked_y1(self) -> float | None: ... + @locked_y1.setter + def locked_y1(self, y1: float | None) -> None: ... + +class Transform(TransformNode): + + # Implemented as a standard attrs in base class, but functionally readonly and some subclasses implement as such + @property + def input_dims(self) -> int | None: ... + @property + def output_dims(self) -> int | None: ... + @property + def is_separable(self) -> bool: ... + @property + def has_inverse(self) -> bool: ... + + def __add__(self, other: Transform) -> Transform: ... + @property + def depth(self) -> int: ... + def contains_branch(self, other: Transform) -> bool: ... + def contains_branch_seperately( + self, other_transform: Transform + ) -> Sequence[bool]: ... + def __sub__(self, other: Transform) -> Transform: ... + def __array__(self, *args, **kwargs) -> np.ndarray: ... + def transform(self, values: ArrayLike) -> np.ndarray: ... + def transform_affine(self, values: ArrayLike) -> np.ndarray: ... + def transform_non_affine(self, values: ArrayLike) -> ArrayLike: ... + def transform_bbox(self, bbox: BboxBase) -> Bbox: ... + def get_affine(self) -> Transform: ... + def get_matrix(self) -> np.ndarray: ... + def transform_point(self, point: ArrayLike) -> np.ndarray: ... + def transform_path(self, path: Path) -> Path: ... + def transform_path_affine(self, path: Path) -> Path: ... + def transform_path_non_affine(self, path: Path) -> Path: ... + def transform_angles( + self, + angles: ArrayLike, + pts: ArrayLike, + radians: bool = ..., + pushoff: float = ..., + ) -> np.ndarray: ... + def inverted(self) -> Transform: ... + +class TransformWrapper(Transform): + pass_through: bool + def __init__(self, child: Transform) -> None: ... + def __eq__(self, other: object) -> bool: ... + def frozen(self) -> Transform: ... + def set(self, child: Transform) -> None: ... + +class AffineBase(Transform): + is_affine: Literal[True] + def __init__(self, *args, **kwargs) -> None: ... + def __eq__(self, other: object) -> bool: ... + +class Affine2DBase(AffineBase): + input_dims: Literal[2] + output_dims: Literal[2] + def frozen(self) -> Affine2D: ... + def to_values(self) -> tuple[float, float, float, float, float, float]: ... + +class Affine2D(Affine2DBase): + def __init__(self, matrix: ArrayLike | None = ..., **kwargs) -> None: ... + @staticmethod + def from_values( + a: float, b: float, c: float, d: float, e: float, f: float + ) -> Affine2D: ... + def set_matrix(self, mtx: ArrayLike) -> None: ... + def clear(self) -> Affine2D: ... + def rotate(self, theta: float) -> Affine2D: ... + def rotate_deg(self, degrees: float) -> Affine2D: ... + def rotate_around(self, x: float, y: float, theta: float) -> Affine2D: ... + def rotate_deg_around(self, x: float, y: float, degrees: float) -> Affine2D: ... + def translate(self, tx: float, ty: float) -> Affine2D: ... + def scale(self, sx: float, sy: float | None = ...) -> Affine2D: ... + def skew(self, xShear: float, yShear: float) -> Affine2D: ... + def skew_deg(self, xShear: float, yShear: float) -> Affine2D: ... + +class IdentityTransform(Affine2DBase): ... + +class _BlendedMixin: + def __eq__(self, other: object) -> bool: ... + def contains_branch_seperately(self, transform: Transform) -> Sequence[bool]: ... + +class BlendedGenericTransform(_BlendedMixin, Transform): + input_dims: Literal[2] + output_dims: Literal[2] + pass_through: bool + def __init__( + self, x_transform: Transform, y_transform: Transform, **kwargs + ) -> None: ... + @property + def depth(self) -> int: ... + def contains_branch(self, other: Transform) -> Literal[False]: ... + @property + def is_affine(self) -> bool: ... + +class BlendedAffine2D(_BlendedMixin, Affine2DBase): + def __init__( + self, x_transform: Transform, y_transform: Transform, **kwargs + ) -> None: ... + +def blended_transform_factory( + x_transform: Transform, y_transform: Transform +) -> BlendedGenericTransform | BlendedAffine2D: ... + +class CompositeGenericTransform(Transform): + pass_through: bool + def __init__(self, a: Transform, b: Transform, **kwargs) -> None: ... + +class CompositeAffine2D(Affine2DBase): + def __init__(self, a: Affine2DBase, b: Affine2DBase, **kwargs) -> None: ... + @property + def depth(self) -> int: ... + +def composite_transform_factory(a: Transform, b: Transform) -> Transform: ... + +class BboxTransform(Affine2DBase): + def __init__(self, boxin: BboxBase, boxout: BboxBase, **kwargs) -> None: ... + +class BboxTransformTo(Affine2DBase): + def __init__(self, boxout: BboxBase, **kwargs) -> None: ... + +class BboxTransformToMaxOnly(BboxTransformTo): ... + +class BboxTransformFrom(Affine2DBase): + def __init__(self, boxin: BboxBase, **kwargs) -> None: ... + +class ScaledTranslation(Affine2DBase): + def __init__( + self, xt: float, yt: float, scale_trans: Affine2DBase, **kwargs + ) -> None: ... + +class AffineDeltaTransform(Affine2DBase): + def __init__(self, transform: Affine2DBase, **kwargs) -> None: ... + +class TransformedPath(TransformNode): + def __init__(self, path: Path, transform: Transform) -> None: ... + def get_transformed_points_and_affine(self) -> tuple[Path, Transform]: ... + def get_transformed_path_and_affine(self) -> tuple[Path, Transform]: ... + def get_fully_transformed_path(self) -> Path: ... + def get_affine(self) -> Transform: ... + +class TransformedPatchPath(TransformedPath): + def __init__(self, patch: Patch) -> None: ... + +def nonsingular( + vmin: float, + vmax: float, + expander: float = ..., + tiny: float = ..., + increasing: bool = ..., +) -> tuple[float, float]: ... +def interval_contains(interval: tuple[float, float], val: float) -> bool: ... +def interval_contains_open(interval: tuple[float, float], val: float) -> bool: ... +def offset_copy( + trans: Transform, + fig: Figure | None = ..., + x: float = ..., + y: float = ..., + units: Literal["inches", "points", "dots"] = ..., +) -> Transform: ... + + +class _ScaledRotation(Affine2DBase): + def __init__(self, theta: float, trans_shift: Transform) -> None: ... + def get_matrix(self) -> np.ndarray: ... diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..645bdadd744b44ed0b9f3b42073526f638907e6b --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:191fd421685d609268ca1cf8363261f6cc101d545a1bc2b3ba669e28e3512464 +size 115599 diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05399a72d830191b0a08b1c9dced0962439572fa Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eda818fe6fe4637858e3e925b54918012fc2a316 Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_pkg_resources.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_pkg_resources.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..139734369dbfc2814a616c54ff803c2eb8ddbf51 Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_pkg_resources.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c513db5ec96dee613173162a116171eb99ab323 Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c982017a551fdcc0419e37556fad51df7ca7e769 Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.cfg b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip new file mode 100644 index 0000000000000000000000000000000000000000..400905eecf0385de4d3b8e50b9892e1302b2b894 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01845c437f4655e3cf9cc4fc4e49cfd607431f22675e1b611129a90239f34822 +size 1809 diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..7328e3f7d18d31422d13b4fd63a7ef746956b7db --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO @@ -0,0 +1,10 @@ +Metadata-Version: 1.0 +Name: my-test-package +Version: 1.0 +Summary: UNKNOWN +Home-page: UNKNOWN +Author: UNKNOWN +Author-email: UNKNOWN +License: UNKNOWN +Description: UNKNOWN +Platform: UNKNOWN diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt @@ -0,0 +1 @@ + diff --git a/llava_video/lib/python3.10/site-packages/pkg_resources/tests/test_working_set.py b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/test_working_set.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb84952c11395688eb2ea46e795b2523d2eef6f --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pkg_resources/tests/test_working_set.py @@ -0,0 +1,501 @@ +import functools +import inspect +import re +import textwrap + +import pytest + +import pkg_resources + +from .test_resources import Metadata + + +def strip_comments(s): + return '\n'.join( + line + for line in s.split('\n') + if line.strip() and not line.strip().startswith('#') + ) + + +def parse_distributions(s): + """ + Parse a series of distribution specs of the form: + {project_name}-{version} + [optional, indented requirements specification] + + Example: + + foo-0.2 + bar-1.0 + foo>=3.0 + [feature] + baz + + yield 2 distributions: + - project_name=foo, version=0.2 + - project_name=bar, version=1.0, + requires=['foo>=3.0', 'baz; extra=="feature"'] + """ + s = s.strip() + for spec in re.split(r'\n(?=[^\s])', s): + if not spec: + continue + fields = spec.split('\n', 1) + assert 1 <= len(fields) <= 2 + name, version = fields.pop(0).rsplit('-', 1) + if fields: + requires = textwrap.dedent(fields.pop(0)) + metadata = Metadata(('requires.txt', requires)) + else: + metadata = None + dist = pkg_resources.Distribution( + project_name=name, version=version, metadata=metadata + ) + yield dist + + +class FakeInstaller: + def __init__(self, installable_dists) -> None: + self._installable_dists = installable_dists + + def __call__(self, req): + return next( + iter(filter(lambda dist: dist in req, self._installable_dists)), None + ) + + +def parametrize_test_working_set_resolve(*test_list): + idlist = [] + argvalues = [] + for test in test_list: + ( + name, + installed_dists, + installable_dists, + requirements, + expected1, + expected2, + ) = ( + strip_comments(s.lstrip()) + for s in textwrap.dedent(test).lstrip().split('\n\n', 5) + ) + installed_dists = list(parse_distributions(installed_dists)) + installable_dists = list(parse_distributions(installable_dists)) + requirements = list(pkg_resources.parse_requirements(requirements)) + for id_, replace_conflicting, expected in ( + (name, False, expected1), + (name + '_replace_conflicting', True, expected2), + ): + idlist.append(id_) + expected = strip_comments(expected.strip()) + if re.match(r'\w+$', expected): + expected = getattr(pkg_resources, expected) + assert issubclass(expected, Exception) + else: + expected = list(parse_distributions(expected)) + argvalues.append( + pytest.param( + installed_dists, + installable_dists, + requirements, + replace_conflicting, + expected, + ) + ) + return pytest.mark.parametrize( + 'installed_dists,installable_dists,' + 'requirements,replace_conflicting,' + 'resolved_dists_or_exception', + argvalues, + ids=idlist, + ) + + +@parametrize_test_working_set_resolve( + """ + # id + noop + + # installed + + # installable + + # wanted + + # resolved + + # resolved [replace conflicting] + """, + """ + # id + already_installed + + # installed + foo-3.0 + + # installable + + # wanted + foo>=2.1,!=3.1,<4 + + # resolved + foo-3.0 + + # resolved [replace conflicting] + foo-3.0 + """, + """ + # id + installable_not_installed + + # installed + + # installable + foo-3.0 + foo-4.0 + + # wanted + foo>=2.1,!=3.1,<4 + + # resolved + foo-3.0 + + # resolved [replace conflicting] + foo-3.0 + """, + """ + # id + not_installable + + # installed + + # installable + + # wanted + foo>=2.1,!=3.1,<4 + + # resolved + DistributionNotFound + + # resolved [replace conflicting] + DistributionNotFound + """, + """ + # id + no_matching_version + + # installed + + # installable + foo-3.1 + + # wanted + foo>=2.1,!=3.1,<4 + + # resolved + DistributionNotFound + + # resolved [replace conflicting] + DistributionNotFound + """, + """ + # id + installable_with_installed_conflict + + # installed + foo-3.1 + + # installable + foo-3.5 + + # wanted + foo>=2.1,!=3.1,<4 + + # resolved + VersionConflict + + # resolved [replace conflicting] + foo-3.5 + """, + """ + # id + not_installable_with_installed_conflict + + # installed + foo-3.1 + + # installable + + # wanted + foo>=2.1,!=3.1,<4 + + # resolved + VersionConflict + + # resolved [replace conflicting] + DistributionNotFound + """, + """ + # id + installed_with_installed_require + + # installed + foo-3.9 + baz-0.1 + foo>=2.1,!=3.1,<4 + + # installable + + # wanted + baz + + # resolved + foo-3.9 + baz-0.1 + + # resolved [replace conflicting] + foo-3.9 + baz-0.1 + """, + """ + # id + installed_with_conflicting_installed_require + + # installed + foo-5 + baz-0.1 + foo>=2.1,!=3.1,<4 + + # installable + + # wanted + baz + + # resolved + VersionConflict + + # resolved [replace conflicting] + DistributionNotFound + """, + """ + # id + installed_with_installable_conflicting_require + + # installed + foo-5 + baz-0.1 + foo>=2.1,!=3.1,<4 + + # installable + foo-2.9 + + # wanted + baz + + # resolved + VersionConflict + + # resolved [replace conflicting] + baz-0.1 + foo-2.9 + """, + """ + # id + installed_with_installable_require + + # installed + baz-0.1 + foo>=2.1,!=3.1,<4 + + # installable + foo-3.9 + + # wanted + baz + + # resolved + foo-3.9 + baz-0.1 + + # resolved [replace conflicting] + foo-3.9 + baz-0.1 + """, + """ + # id + installable_with_installed_require + + # installed + foo-3.9 + + # installable + baz-0.1 + foo>=2.1,!=3.1,<4 + + # wanted + baz + + # resolved + foo-3.9 + baz-0.1 + + # resolved [replace conflicting] + foo-3.9 + baz-0.1 + """, + """ + # id + installable_with_installable_require + + # installed + + # installable + foo-3.9 + baz-0.1 + foo>=2.1,!=3.1,<4 + + # wanted + baz + + # resolved + foo-3.9 + baz-0.1 + + # resolved [replace conflicting] + foo-3.9 + baz-0.1 + """, + """ + # id + installable_with_conflicting_installable_require + + # installed + foo-5 + + # installable + foo-2.9 + baz-0.1 + foo>=2.1,!=3.1,<4 + + # wanted + baz + + # resolved + VersionConflict + + # resolved [replace conflicting] + baz-0.1 + foo-2.9 + """, + """ + # id + conflicting_installables + + # installed + + # installable + foo-2.9 + foo-5.0 + + # wanted + foo>=2.1,!=3.1,<4 + foo>=4 + + # resolved + VersionConflict + + # resolved [replace conflicting] + VersionConflict + """, + """ + # id + installables_with_conflicting_requires + + # installed + + # installable + foo-2.9 + dep==1.0 + baz-5.0 + dep==2.0 + dep-1.0 + dep-2.0 + + # wanted + foo + baz + + # resolved + VersionConflict + + # resolved [replace conflicting] + VersionConflict + """, + """ + # id + installables_with_conflicting_nested_requires + + # installed + + # installable + foo-2.9 + dep1 + dep1-1.0 + subdep<1.0 + baz-5.0 + dep2 + dep2-1.0 + subdep>1.0 + subdep-0.9 + subdep-1.1 + + # wanted + foo + baz + + # resolved + VersionConflict + + # resolved [replace conflicting] + VersionConflict + """, + """ + # id + wanted_normalized_name_installed_canonical + + # installed + foo.bar-3.6 + + # installable + + # wanted + foo-bar==3.6 + + # resolved + foo.bar-3.6 + + # resolved [replace conflicting] + foo.bar-3.6 + """, +) +def test_working_set_resolve( + installed_dists, + installable_dists, + requirements, + replace_conflicting, + resolved_dists_or_exception, +): + ws = pkg_resources.WorkingSet([]) + list(map(ws.add, installed_dists)) + resolve_call = functools.partial( + ws.resolve, + requirements, + installer=FakeInstaller(installable_dists), + replace_conflicting=replace_conflicting, + ) + if inspect.isclass(resolved_dists_or_exception): + with pytest.raises(resolved_dists_or_exception): + resolve_call() + else: + assert sorted(resolve_call()) == sorted(resolved_dists_or_exception) diff --git a/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5dec44ad6a78c0e6720d8581e3801f478350e89 Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7d868ffd13fd9eeb0b3dcfce0ba5fd59971d688 Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04749ee7ca06323be2b4d73e6a94ec10aa30257d Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae500f8feeaca66f890afba5990c0f6febeb0dbc Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e103a492d57072151b444f25a9247af944636dd4 Binary files /dev/null and b/llava_video/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc differ diff --git a/llava_video/lib/python3.10/site-packages/pybind11/_version.py b/llava_video/lib/python3.10/site-packages/pybind11/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c298836bc33beb10a672a07bd027869c6a93ba1c --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pybind11/_version.py @@ -0,0 +1,12 @@ +from __future__ import annotations + + +def _to_int(s: str) -> int | str: + try: + return int(s) + except ValueError: + return s + + +__version__ = "2.13.6" +version_info = tuple(_to_int(s) for s in __version__.split(".")) diff --git a/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h b/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h new file mode 100644 index 0000000000000000000000000000000000000000..1044db94d906ac5fcf6faab6ac7668187314598f --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h @@ -0,0 +1,690 @@ +/* + pybind11/attr.h: Infrastructure for processing custom + type and function attributes + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" +#include "cast.h" + +#include + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +/// \addtogroup annotations +/// @{ + +/// Annotation for methods +struct is_method { + handle class_; + explicit is_method(const handle &c) : class_(c) {} +}; + +/// Annotation for setters +struct is_setter {}; + +/// Annotation for operators +struct is_operator {}; + +/// Annotation for classes that cannot be subclassed +struct is_final {}; + +/// Annotation for parent scope +struct scope { + handle value; + explicit scope(const handle &s) : value(s) {} +}; + +/// Annotation for documentation +struct doc { + const char *value; + explicit doc(const char *value) : value(value) {} +}; + +/// Annotation for function names +struct name { + const char *value; + explicit name(const char *value) : value(value) {} +}; + +/// Annotation indicating that a function is an overload associated with a given "sibling" +struct sibling { + handle value; + explicit sibling(const handle &value) : value(value.ptr()) {} +}; + +/// Annotation indicating that a class derives from another given type +template +struct base { + + PYBIND11_DEPRECATED( + "base() was deprecated in favor of specifying 'T' as a template argument to class_") + base() = default; +}; + +/// Keep patient alive while nurse lives +template +struct keep_alive {}; + +/// Annotation indicating that a class is involved in a multiple inheritance relationship +struct multiple_inheritance {}; + +/// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class +struct dynamic_attr {}; + +/// Annotation which enables the buffer protocol for a type +struct buffer_protocol {}; + +/// Annotation which requests that a special metaclass is created for a type +struct metaclass { + handle value; + + PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.") + metaclass() = default; + + /// Override pybind11's default metaclass + explicit metaclass(handle value) : value(value) {} +}; + +/// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that +/// may be used to customize the Python type. +/// +/// The callback is invoked immediately before `PyType_Ready`. +/// +/// Note: This is an advanced interface, and uses of it may require changes to +/// work with later versions of pybind11. You may wish to consult the +/// implementation of `make_new_python_type` in `detail/classes.h` to understand +/// the context in which the callback will be run. +struct custom_type_setup { + using callback = std::function; + + explicit custom_type_setup(callback value) : value(std::move(value)) {} + + callback value; +}; + +/// Annotation that marks a class as local to the module: +struct module_local { + const bool value; + constexpr explicit module_local(bool v = true) : value(v) {} +}; + +/// Annotation to mark enums as an arithmetic type +struct arithmetic {}; + +/// Mark a function for addition at the beginning of the existing overload chain instead of the end +struct prepend {}; + +/** \rst + A call policy which places one or more guard variables (``Ts...``) around the function call. + + For example, this definition: + + .. code-block:: cpp + + m.def("foo", foo, py::call_guard()); + + is equivalent to the following pseudocode: + + .. code-block:: cpp + + m.def("foo", [](args...) { + T scope_guard; + return foo(args...); // forwarded arguments + }); + \endrst */ +template +struct call_guard; + +template <> +struct call_guard<> { + using type = detail::void_type; +}; + +template +struct call_guard { + static_assert(std::is_default_constructible::value, + "The guard type must be default constructible"); + + using type = T; +}; + +template +struct call_guard { + struct type { + T guard{}; // Compose multiple guard types with left-to-right default-constructor order + typename call_guard::type next{}; + }; +}; + +/// @} annotations + +PYBIND11_NAMESPACE_BEGIN(detail) +/* Forward declarations */ +enum op_id : int; +enum op_type : int; +struct undefined_t; +template +struct op_; +void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret); + +/// Internal data structure which holds metadata about a keyword argument +struct argument_record { + const char *name; ///< Argument name + const char *descr; ///< Human-readable version of the argument value + handle value; ///< Associated Python object + bool convert : 1; ///< True if the argument is allowed to convert when loading + bool none : 1; ///< True if None is allowed when loading + + argument_record(const char *name, const char *descr, handle value, bool convert, bool none) + : name(name), descr(descr), value(value), convert(convert), none(none) {} +}; + +/// Internal data structure which holds metadata about a bound function (signature, overloads, +/// etc.) +struct function_record { + function_record() + : is_constructor(false), is_new_style_constructor(false), is_stateless(false), + is_operator(false), is_method(false), is_setter(false), has_args(false), + has_kwargs(false), prepend(false) {} + + /// Function name + char *name = nullptr; /* why no C++ strings? They generate heavier code.. */ + + // User-specified documentation string + char *doc = nullptr; + + /// Human-readable version of the function signature + char *signature = nullptr; + + /// List of registered keyword arguments + std::vector args; + + /// Pointer to lambda function which converts arguments and performs the actual call + handle (*impl)(function_call &) = nullptr; + + /// Storage for the wrapped function pointer and captured data, if any + void *data[3] = {}; + + /// Pointer to custom destructor for 'data' (if needed) + void (*free_data)(function_record *ptr) = nullptr; + + /// Return value policy associated with this function + return_value_policy policy = return_value_policy::automatic; + + /// True if name == '__init__' + bool is_constructor : 1; + + /// True if this is a new-style `__init__` defined in `detail/init.h` + bool is_new_style_constructor : 1; + + /// True if this is a stateless function pointer + bool is_stateless : 1; + + /// True if this is an operator (__add__), etc. + bool is_operator : 1; + + /// True if this is a method + bool is_method : 1; + + /// True if this is a setter + bool is_setter : 1; + + /// True if the function has a '*args' argument + bool has_args : 1; + + /// True if the function has a '**kwargs' argument + bool has_kwargs : 1; + + /// True if this function is to be inserted at the beginning of the overload resolution chain + bool prepend : 1; + + /// Number of arguments (including py::args and/or py::kwargs, if present) + std::uint16_t nargs; + + /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs + /// argument or by a py::kw_only annotation. + std::uint16_t nargs_pos = 0; + + /// Number of leading arguments (counted in `nargs`) that are positional-only + std::uint16_t nargs_pos_only = 0; + + /// Python method object + PyMethodDef *def = nullptr; + + /// Python handle to the parent scope (a class or a module) + handle scope; + + /// Python handle to the sibling function representing an overload chain + handle sibling; + + /// Pointer to next overload + function_record *next = nullptr; +}; + +/// Special data structure which (temporarily) holds metadata about a bound class +struct type_record { + PYBIND11_NOINLINE type_record() + : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false), + default_holder(true), module_local(false), is_final(false) {} + + /// Handle to the parent scope + handle scope; + + /// Name of the class + const char *name = nullptr; + + // Pointer to RTTI type_info data structure + const std::type_info *type = nullptr; + + /// How large is the underlying C++ type? + size_t type_size = 0; + + /// What is the alignment of the underlying C++ type? + size_t type_align = 0; + + /// How large is the type's holder? + size_t holder_size = 0; + + /// The global operator new can be overridden with a class-specific variant + void *(*operator_new)(size_t) = nullptr; + + /// Function pointer to class_<..>::init_instance + void (*init_instance)(instance *, const void *) = nullptr; + + /// Function pointer to class_<..>::dealloc + void (*dealloc)(detail::value_and_holder &) = nullptr; + + /// List of base classes of the newly created type + list bases; + + /// Optional docstring + const char *doc = nullptr; + + /// Custom metaclass (optional) + handle metaclass; + + /// Custom type setup. + custom_type_setup::callback custom_type_setup_callback; + + /// Multiple inheritance marker + bool multiple_inheritance : 1; + + /// Does the class manage a __dict__? + bool dynamic_attr : 1; + + /// Does the class implement the buffer protocol? + bool buffer_protocol : 1; + + /// Is the default (unique_ptr) holder type used? + bool default_holder : 1; + + /// Is the class definition local to the module shared object? + bool module_local : 1; + + /// Is the class inheritable from python classes? + bool is_final : 1; + + PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) { + auto *base_info = detail::get_type_info(base, false); + if (!base_info) { + std::string tname(base.name()); + detail::clean_type_id(tname); + pybind11_fail("generic_type: type \"" + std::string(name) + + "\" referenced unknown base type \"" + tname + "\""); + } + + if (default_holder != base_info->default_holder) { + std::string tname(base.name()); + detail::clean_type_id(tname); + pybind11_fail("generic_type: type \"" + std::string(name) + "\" " + + (default_holder ? "does not have" : "has") + + " a non-default holder type while its base \"" + tname + "\" " + + (base_info->default_holder ? "does not" : "does")); + } + + bases.append((PyObject *) base_info->type); + +#if PY_VERSION_HEX < 0x030B0000 + dynamic_attr |= base_info->type->tp_dictoffset != 0; +#else + dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0; +#endif + + if (caster) { + base_info->implicit_casts.emplace_back(type, caster); + } + } +}; + +inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) { + args.reserve(f.nargs); + args_convert.reserve(f.nargs); +} + +/// Tag for a new-style `__init__` defined in `detail/init.h` +struct is_new_style_constructor {}; + +/** + * Partial template specializations to process custom attributes provided to + * cpp_function_ and class_. These are either used to initialize the respective + * fields in the type_record and function_record data structures or executed at + * runtime to deal with custom call policies (e.g. keep_alive). + */ +template +struct process_attribute; + +template +struct process_attribute_default { + /// Default implementation: do nothing + static void init(const T &, function_record *) {} + static void init(const T &, type_record *) {} + static void precall(function_call &) {} + static void postcall(function_call &, handle) {} +}; + +/// Process an attribute specifying the function's name +template <> +struct process_attribute : process_attribute_default { + static void init(const name &n, function_record *r) { r->name = const_cast(n.value); } +}; + +/// Process an attribute specifying the function's docstring +template <> +struct process_attribute : process_attribute_default { + static void init(const doc &n, function_record *r) { r->doc = const_cast(n.value); } +}; + +/// Process an attribute specifying the function's docstring (provided as a C-style string) +template <> +struct process_attribute : process_attribute_default { + static void init(const char *d, function_record *r) { r->doc = const_cast(d); } + static void init(const char *d, type_record *r) { r->doc = d; } +}; +template <> +struct process_attribute : process_attribute {}; + +/// Process an attribute indicating the function's return value policy +template <> +struct process_attribute : process_attribute_default { + static void init(const return_value_policy &p, function_record *r) { r->policy = p; } +}; + +/// Process an attribute which indicates that this is an overloaded function associated with a +/// given sibling +template <> +struct process_attribute : process_attribute_default { + static void init(const sibling &s, function_record *r) { r->sibling = s.value; } +}; + +/// Process an attribute which indicates that this function is a method +template <> +struct process_attribute : process_attribute_default { + static void init(const is_method &s, function_record *r) { + r->is_method = true; + r->scope = s.class_; + } +}; + +/// Process an attribute which indicates that this function is a setter +template <> +struct process_attribute : process_attribute_default { + static void init(const is_setter &, function_record *r) { r->is_setter = true; } +}; + +/// Process an attribute which indicates the parent scope of a method +template <> +struct process_attribute : process_attribute_default { + static void init(const scope &s, function_record *r) { r->scope = s.value; } +}; + +/// Process an attribute which indicates that this function is an operator +template <> +struct process_attribute : process_attribute_default { + static void init(const is_operator &, function_record *r) { r->is_operator = true; } +}; + +template <> +struct process_attribute + : process_attribute_default { + static void init(const is_new_style_constructor &, function_record *r) { + r->is_new_style_constructor = true; + } +}; + +inline void check_kw_only_arg(const arg &a, function_record *r) { + if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) { + pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or " + "args() argument"); + } +} + +inline void append_self_arg_if_needed(function_record *r) { + if (r->is_method && r->args.empty()) { + r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false); + } +} + +/// Process a keyword argument attribute (*without* a default value) +template <> +struct process_attribute : process_attribute_default { + static void init(const arg &a, function_record *r) { + append_self_arg_if_needed(r); + r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none); + + check_kw_only_arg(a, r); + } +}; + +/// Process a keyword argument attribute (*with* a default value) +template <> +struct process_attribute : process_attribute_default { + static void init(const arg_v &a, function_record *r) { + if (r->is_method && r->args.empty()) { + r->args.emplace_back( + "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false); + } + + if (!a.value) { +#if defined(PYBIND11_DETAILED_ERROR_MESSAGES) + std::string descr("'"); + if (a.name) { + descr += std::string(a.name) + ": "; + } + descr += a.type + "'"; + if (r->is_method) { + if (r->name) { + descr += " in method '" + (std::string) str(r->scope) + "." + + (std::string) r->name + "'"; + } else { + descr += " in method of '" + (std::string) str(r->scope) + "'"; + } + } else if (r->name) { + descr += " in function '" + (std::string) r->name + "'"; + } + pybind11_fail("arg(): could not convert default argument " + descr + + " into a Python object (type not registered yet?)"); +#else + pybind11_fail("arg(): could not convert default argument " + "into a Python object (type not registered yet?). " + "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for " + "more information."); +#endif + } + r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none); + + check_kw_only_arg(a, r); + } +}; + +/// Process a keyword-only-arguments-follow pseudo argument +template <> +struct process_attribute : process_attribute_default { + static void init(const kw_only &, function_record *r) { + append_self_arg_if_needed(r); + if (r->has_args && r->nargs_pos != static_cast(r->args.size())) { + pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative " + "argument location (or omit kw_only() entirely)"); + } + r->nargs_pos = static_cast(r->args.size()); + } +}; + +/// Process a positional-only-argument maker +template <> +struct process_attribute : process_attribute_default { + static void init(const pos_only &, function_record *r) { + append_self_arg_if_needed(r); + r->nargs_pos_only = static_cast(r->args.size()); + if (r->nargs_pos_only > r->nargs_pos) { + pybind11_fail("pos_only(): cannot follow a py::args() argument"); + } + // It also can't follow a kw_only, but a static_assert in pybind11.h checks that + } +}; + +/// Process a parent class attribute. Single inheritance only (class_ itself already guarantees +/// that) +template +struct process_attribute::value>> + : process_attribute_default { + static void init(const handle &h, type_record *r) { r->bases.append(h); } +}; + +/// Process a parent class attribute (deprecated, does not support multiple inheritance) +template +struct process_attribute> : process_attribute_default> { + static void init(const base &, type_record *r) { r->add_base(typeid(T), nullptr); } +}; + +/// Process a multiple inheritance attribute +template <> +struct process_attribute : process_attribute_default { + static void init(const multiple_inheritance &, type_record *r) { + r->multiple_inheritance = true; + } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; } +}; + +template <> +struct process_attribute { + static void init(const custom_type_setup &value, type_record *r) { + r->custom_type_setup_callback = value.value; + } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const is_final &, type_record *r) { r->is_final = true; } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; } +}; + +template <> +struct process_attribute : process_attribute_default { + static void init(const module_local &l, type_record *r) { r->module_local = l.value; } +}; + +/// Process a 'prepend' attribute, putting this at the beginning of the overload chain +template <> +struct process_attribute : process_attribute_default { + static void init(const prepend &, function_record *r) { r->prepend = true; } +}; + +/// Process an 'arithmetic' attribute for enums (does nothing here) +template <> +struct process_attribute : process_attribute_default {}; + +template +struct process_attribute> : process_attribute_default> {}; + +/** + * Process a keep_alive call policy -- invokes keep_alive_impl during the + * pre-call handler if both Nurse, Patient != 0 and use the post-call handler + * otherwise + */ +template +struct process_attribute> + : public process_attribute_default> { + template = 0> + static void precall(function_call &call) { + keep_alive_impl(Nurse, Patient, call, handle()); + } + template = 0> + static void postcall(function_call &, handle) {} + template = 0> + static void precall(function_call &) {} + template = 0> + static void postcall(function_call &call, handle ret) { + keep_alive_impl(Nurse, Patient, call, ret); + } +}; + +/// Recursively iterate over variadic template arguments +template +struct process_attributes { + static void init(const Args &...args, function_record *r) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); + using expander = int[]; + (void) expander{ + 0, ((void) process_attribute::type>::init(args, r), 0)...}; + } + static void init(const Args &...args, type_record *r) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); + using expander = int[]; + (void) expander{0, + (process_attribute::type>::init(args, r), 0)...}; + } + static void precall(function_call &call) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call); + using expander = int[]; + (void) expander{0, + (process_attribute::type>::precall(call), 0)...}; + } + static void postcall(function_call &call, handle fn_ret) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret); + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret); + using expander = int[]; + (void) expander{ + 0, (process_attribute::type>::postcall(call, fn_ret), 0)...}; + } +}; + +template +using is_call_guard = is_instantiation; + +/// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found) +template +using extract_guard_t = typename exactly_one_t, Extra...>::type; + +/// Check the number of named arguments at compile time +template ::value...), + size_t self = constexpr_sum(std::is_same::value...)> +constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) { + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs); + return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs; +} + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h b/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h new file mode 100644 index 0000000000000000000000000000000000000000..75aec0ba3092a401a73f7cdb09b0894aef85cc27 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h @@ -0,0 +1,208 @@ +/* + pybind11/buffer_info.h: Python buffer object interface + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +PYBIND11_NAMESPACE_BEGIN(detail) + +// Default, C-style strides +inline std::vector c_strides(const std::vector &shape, ssize_t itemsize) { + auto ndim = shape.size(); + std::vector strides(ndim, itemsize); + if (ndim > 0) { + for (size_t i = ndim - 1; i > 0; --i) { + strides[i - 1] = strides[i] * shape[i]; + } + } + return strides; +} + +// F-style strides; default when constructing an array_t with `ExtraFlags & f_style` +inline std::vector f_strides(const std::vector &shape, ssize_t itemsize) { + auto ndim = shape.size(); + std::vector strides(ndim, itemsize); + for (size_t i = 1; i < ndim; ++i) { + strides[i] = strides[i - 1] * shape[i - 1]; + } + return strides; +} + +template +struct compare_buffer_info; + +PYBIND11_NAMESPACE_END(detail) + +/// Information record describing a Python buffer object +struct buffer_info { + void *ptr = nullptr; // Pointer to the underlying storage + ssize_t itemsize = 0; // Size of individual items in bytes + ssize_t size = 0; // Total number of entries + std::string format; // For homogeneous buffers, this should be set to + // format_descriptor::format() + ssize_t ndim = 0; // Number of dimensions + std::vector shape; // Shape of the tensor (1 entry per dimension) + std::vector strides; // Number of bytes between adjacent entries + // (for each per dimension) + bool readonly = false; // flag to indicate if the underlying storage may be written to + + buffer_info() = default; + + buffer_info(void *ptr, + ssize_t itemsize, + const std::string &format, + ssize_t ndim, + detail::any_container shape_in, + detail::any_container strides_in, + bool readonly = false) + : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim), + shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) { + if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) { + pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length"); + } + for (size_t i = 0; i < (size_t) ndim; ++i) { + size *= shape[i]; + } + } + + template + buffer_info(T *ptr, + detail::any_container shape_in, + detail::any_container strides_in, + bool readonly = false) + : buffer_info(private_ctr_tag(), + ptr, + sizeof(T), + format_descriptor::format(), + static_cast(shape_in->size()), + std::move(shape_in), + std::move(strides_in), + readonly) {} + + buffer_info(void *ptr, + ssize_t itemsize, + const std::string &format, + ssize_t size, + bool readonly = false) + : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {} + + template + buffer_info(T *ptr, ssize_t size, bool readonly = false) + : buffer_info(ptr, sizeof(T), format_descriptor::format(), size, readonly) {} + + template + buffer_info(const T *ptr, ssize_t size, bool readonly = true) + : buffer_info( + const_cast(ptr), sizeof(T), format_descriptor::format(), size, readonly) {} + + explicit buffer_info(Py_buffer *view, bool ownview = true) + : buffer_info( + view->buf, + view->itemsize, + view->format, + view->ndim, + {view->shape, view->shape + view->ndim}, + /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects + * ignore this flag and return a view with NULL strides. + * When strides are NULL, build them manually. */ + view->strides + ? std::vector(view->strides, view->strides + view->ndim) + : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize), + (view->readonly != 0)) { + // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) + this->m_view = view; + // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) + this->ownview = ownview; + } + + buffer_info(const buffer_info &) = delete; + buffer_info &operator=(const buffer_info &) = delete; + + buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); } + + buffer_info &operator=(buffer_info &&rhs) noexcept { + ptr = rhs.ptr; + itemsize = rhs.itemsize; + size = rhs.size; + format = std::move(rhs.format); + ndim = rhs.ndim; + shape = std::move(rhs.shape); + strides = std::move(rhs.strides); + std::swap(m_view, rhs.m_view); + std::swap(ownview, rhs.ownview); + readonly = rhs.readonly; + return *this; + } + + ~buffer_info() { + if (m_view && ownview) { + PyBuffer_Release(m_view); + delete m_view; + } + } + + Py_buffer *view() const { return m_view; } + Py_buffer *&view() { return m_view; } + + /* True if the buffer item type is equivalent to `T`. */ + // To define "equivalent" by example: + // `buffer_info::item_type_is_equivalent_to(b)` and + // `buffer_info::item_type_is_equivalent_to(b)` may both be true + // on some platforms, but `int` and `unsigned` will never be equivalent. + // For the ground truth, please inspect `detail::compare_buffer_info<>`. + template + bool item_type_is_equivalent_to() const { + return detail::compare_buffer_info::compare(*this); + } + +private: + struct private_ctr_tag {}; + + buffer_info(private_ctr_tag, + void *ptr, + ssize_t itemsize, + const std::string &format, + ssize_t ndim, + detail::any_container &&shape_in, + detail::any_container &&strides_in, + bool readonly) + : buffer_info( + ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {} + + Py_buffer *m_view = nullptr; + bool ownview = false; +}; + +PYBIND11_NAMESPACE_BEGIN(detail) + +template +struct compare_buffer_info { + static bool compare(const buffer_info &b) { + // NOLINTNEXTLINE(bugprone-sizeof-expression) Needed for `PyObject *` + return b.format == format_descriptor::format() && b.itemsize == (ssize_t) sizeof(T); + } +}; + +template +struct compare_buffer_info::value>> { + static bool compare(const buffer_info &b) { + return (size_t) b.itemsize == sizeof(T) + && (b.format == format_descriptor::value + || ((sizeof(T) == sizeof(long)) + && b.format == (std::is_unsigned::value ? "L" : "l")) + || ((sizeof(T) == sizeof(size_t)) + && b.format == (std::is_unsigned::value ? "N" : "n"))); + } +}; + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h b/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h new file mode 100644 index 0000000000000000000000000000000000000000..0f3091f6869900d14d521791198d97fcccf40629 --- /dev/null +++ b/llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h @@ -0,0 +1,1855 @@ +/* + pybind11/cast.h: Partial template specializations to cast between + C++ and Python types + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" +#include "detail/descr.h" +#include "detail/type_caster_base.h" +#include "detail/typeid.h" +#include "pytypes.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +PYBIND11_WARNING_DISABLE_MSVC(4127) + +PYBIND11_NAMESPACE_BEGIN(detail) + +template +class type_caster : public type_caster_base {}; +template +using make_caster = type_caster>; + +// Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T +template +typename make_caster::template cast_op_type cast_op(make_caster &caster) { + using result_t = typename make_caster::template cast_op_type; // See PR #4893 + return caster.operator result_t(); +} +template +typename make_caster::template cast_op_type::type> +cast_op(make_caster &&caster) { + using result_t = typename make_caster::template cast_op_type< + typename std::add_rvalue_reference::type>; // See PR #4893 + return std::move(caster).operator result_t(); +} + +template +class type_caster> { +private: + using caster_t = make_caster; + caster_t subcaster; + using reference_t = type &; + using subcaster_cast_op_type = typename caster_t::template cast_op_type; + + static_assert( + std::is_same::type &, subcaster_cast_op_type>::value + || std::is_same::value, + "std::reference_wrapper caster requires T to have a caster with an " + "`operator T &()` or `operator const T &()`"); + +public: + bool load(handle src, bool convert) { return subcaster.load(src, convert); } + static constexpr auto name = caster_t::name; + static handle + cast(const std::reference_wrapper &src, return_value_policy policy, handle parent) { + // It is definitely wrong to take ownership of this pointer, so mask that rvp + if (policy == return_value_policy::take_ownership + || policy == return_value_policy::automatic) { + policy = return_value_policy::automatic_reference; + } + return caster_t::cast(&src.get(), policy, parent); + } + template + using cast_op_type = std::reference_wrapper; + explicit operator std::reference_wrapper() { return cast_op(subcaster); } +}; + +#define PYBIND11_TYPE_CASTER(type, py_name) \ +protected: \ + type value; \ + \ +public: \ + static constexpr auto name = py_name; \ + template >::value, \ + int> \ + = 0> \ + static ::pybind11::handle cast( \ + T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \ + if (!src) \ + return ::pybind11::none().release(); \ + if (policy == ::pybind11::return_value_policy::take_ownership) { \ + auto h = cast(std::move(*src), policy, parent); \ + delete src; \ + return h; \ + } \ + return cast(*src, policy, parent); \ + } \ + operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \ + operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \ + operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \ + template \ + using cast_op_type = ::pybind11::detail::movable_cast_op_type + +template +using is_std_char_type = any_of, /* std::string */ +#if defined(PYBIND11_HAS_U8STRING) + std::is_same, /* std::u8string */ +#endif + std::is_same, /* std::u16string */ + std::is_same, /* std::u32string */ + std::is_same /* std::wstring */ + >; + +template +struct type_caster::value && !is_std_char_type::value>> { + using _py_type_0 = conditional_t; + using _py_type_1 = conditional_t::value, + _py_type_0, + typename std::make_unsigned<_py_type_0>::type>; + using py_type = conditional_t::value, double, _py_type_1>; + +public: + bool load(handle src, bool convert) { + py_type py_value; + + if (!src) { + return false; + } + +#if !defined(PYPY_VERSION) + auto index_check = [](PyObject *o) { return PyIndex_Check(o); }; +#else + // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`, + // while CPython only considers the existence of `nb_index`/`__index__`. + auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); }; +#endif + + if (std::is_floating_point::value) { + if (convert || PyFloat_Check(src.ptr())) { + py_value = (py_type) PyFloat_AsDouble(src.ptr()); + } else { + return false; + } + } else if (PyFloat_Check(src.ptr()) + || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) { + return false; + } else { + handle src_or_index = src; + // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls. +#if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION) + object index; + if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr()) + index = reinterpret_steal(PyNumber_Index(src.ptr())); + if (!index) { + PyErr_Clear(); + if (!convert) + return false; + } else { + src_or_index = index; + } + } +#endif + if (std::is_unsigned::value) { + py_value = as_unsigned(src_or_index.ptr()); + } else { // signed integer: + py_value = sizeof(T) <= sizeof(long) + ? (py_type) PyLong_AsLong(src_or_index.ptr()) + : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr()); + } + } + + // Python API reported an error + bool py_err = py_value == (py_type) -1 && PyErr_Occurred(); + + // Check to see if the conversion is valid (integers should match exactly) + // Signed/unsigned checks happen elsewhere + if (py_err + || (std::is_integral::value && sizeof(py_type) != sizeof(T) + && py_value != (py_type) (T) py_value)) { + PyErr_Clear(); + if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) { + auto tmp = reinterpret_steal(std::is_floating_point::value + ? PyNumber_Float(src.ptr()) + : PyNumber_Long(src.ptr())); + PyErr_Clear(); + return load(tmp, false); + } + return false; + } + + value = (T) py_value; + return true; + } + + template + static typename std::enable_if::value, handle>::type + cast(U src, return_value_policy /* policy */, handle /* parent */) { + return PyFloat_FromDouble((double) src); + } + + template + static typename std::enable_if::value && std::is_signed::value + && (sizeof(U) <= sizeof(long)), + handle>::type + cast(U src, return_value_policy /* policy */, handle /* parent */) { + return PYBIND11_LONG_FROM_SIGNED((long) src); + } + + template + static typename std::enable_if::value && std::is_unsigned::value + && (sizeof(U) <= sizeof(unsigned long)), + handle>::type + cast(U src, return_value_policy /* policy */, handle /* parent */) { + return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src); + } + + template + static typename std::enable_if::value && std::is_signed::value + && (sizeof(U) > sizeof(long)), + handle>::type + cast(U src, return_value_policy /* policy */, handle /* parent */) { + return PyLong_FromLongLong((long long) src); + } + + template + static typename std::enable_if::value && std::is_unsigned::value + && (sizeof(U) > sizeof(unsigned long)), + handle>::type + cast(U src, return_value_policy /* policy */, handle /* parent */) { + return PyLong_FromUnsignedLongLong((unsigned long long) src); + } + + PYBIND11_TYPE_CASTER(T, const_name::value>("int", "float")); +}; + +template +struct void_caster { +public: + bool load(handle src, bool) { + if (src && src.is_none()) { + return true; + } + return false; + } + static handle cast(T, return_value_policy /* policy */, handle /* parent */) { + return none().release(); + } + PYBIND11_TYPE_CASTER(T, const_name("None")); +}; + +template <> +class type_caster : public void_caster {}; + +template <> +class type_caster : public type_caster { +public: + using type_caster::cast; + + bool load(handle h, bool) { + if (!h) { + return false; + } + if (h.is_none()) { + value = nullptr; + return true; + } + + /* Check if this is a capsule */ + if (isinstance(h)) { + value = reinterpret_borrow(h); + return true; + } + + /* Check if this is a C++ type */ + const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr()); + if (bases.size() == 1) { // Only allowing loading from a single-value type + value = values_and_holders(reinterpret_cast(h.ptr())).begin()->value_ptr(); + return true; + } + + /* Fail */ + return false; + } + + static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) { + if (ptr) { + return capsule(ptr).release(); + } + return none().release(); + } + + template + using cast_op_type = void *&; + explicit operator void *&() { return value; } + static constexpr auto name = const_name("capsule"); + +private: + void *value = nullptr; +}; + +template <> +class type_caster : public void_caster {}; + +template <> +class type_caster { +public: + bool load(handle src, bool convert) { + if (!src) { + return false; + } + if (src.ptr() == Py_True) { + value = true; + return true; + } + if (src.ptr() == Py_False) { + value = false; + return true; + } + if (convert || is_numpy_bool(src)) { + // (allow non-implicit conversion for numpy booleans), use strncmp + // since NumPy 1.x had an additional trailing underscore. + + Py_ssize_t res = -1; + if (src.is_none()) { + res = 0; // None is implicitly converted to False + } +#if defined(PYPY_VERSION) + // On PyPy, check that "__bool__" attr exists + else if (hasattr(src, PYBIND11_BOOL_ATTR)) { + res = PyObject_IsTrue(src.ptr()); + } +#else + // Alternate approach for CPython: this does the same as the above, but optimized + // using the CPython API so as to avoid an unneeded attribute lookup. + else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) { + if (PYBIND11_NB_BOOL(tp_as_number)) { + res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr()); + } + } +#endif + if (res == 0 || res == 1) { + value = (res != 0); + return true; + } + PyErr_Clear(); + } + return false; + } + static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) { + return handle(src ? Py_True : Py_False).inc_ref(); + } + PYBIND11_TYPE_CASTER(bool, const_name("bool")); + +private: + // Test if an object is a NumPy boolean (without fetching the type). + static inline bool is_numpy_bool(handle object) { + const char *type_name = Py_TYPE(object.ptr())->tp_name; + // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support + return std::strcmp("numpy.bool", type_name) == 0 + || std::strcmp("numpy.bool_", type_name) == 0; + } +}; + +// Helper class for UTF-{8,16,32} C++ stl strings: +template +struct string_caster { + using CharT = typename StringType::value_type; + + // Simplify life by being able to assume standard char sizes (the standard only guarantees + // minimums, but Python requires exact sizes) + static_assert(!std::is_same::value || sizeof(CharT) == 1, + "Unsupported char size != 1"); +#if defined(PYBIND11_HAS_U8STRING) + static_assert(!std::is_same::value || sizeof(CharT) == 1, + "Unsupported char8_t size != 1"); +#endif + static_assert(!std::is_same::value || sizeof(CharT) == 2, + "Unsupported char16_t size != 2"); + static_assert(!std::is_same::value || sizeof(CharT) == 4, + "Unsupported char32_t size != 4"); + // wchar_t can be either 16 bits (Windows) or 32 (everywhere else) + static_assert(!std::is_same::value || sizeof(CharT) == 2 || sizeof(CharT) == 4, + "Unsupported wchar_t size != 2/4"); + static constexpr size_t UTF_N = 8 * sizeof(CharT); + + bool load(handle src, bool) { + handle load_src = src; + if (!src) { + return false; + } + if (!PyUnicode_Check(load_src.ptr())) { + return load_raw(load_src); + } + + // For UTF-8 we avoid the need for a temporary `bytes` object by using + // `PyUnicode_AsUTF8AndSize`. + if (UTF_N == 8) { + Py_ssize_t size = -1; + const auto *buffer + = reinterpret_cast(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size)); + if (!buffer) { + PyErr_Clear(); + return false; + } + value = StringType(buffer, static_cast(size)); + return true; + } + + auto utfNbytes + = reinterpret_steal(PyUnicode_AsEncodedString(load_src.ptr(), + UTF_N == 8 ? "utf-8" + : UTF_N == 16 ? "utf-16" + : "utf-32", + nullptr)); + if (!utfNbytes) { + PyErr_Clear(); + return false; + } + + const auto *buffer + = reinterpret_cast(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr())); + size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT); + // Skip BOM for UTF-16/32 + if (UTF_N > 8) { + buffer++; + length--; + } + value = StringType(buffer, length); + + // If we're loading a string_view we need to keep the encoded Python object alive: + if (IsView) { + loader_life_support::add_patient(utfNbytes); + } + + return true; + } + + static handle + cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) { + const char *buffer = reinterpret_cast(src.data()); + auto nbytes = ssize_t(src.size() * sizeof(CharT)); + handle s = decode_utfN(buffer, nbytes); + if (!s) { + throw error_already_set(); + } + return s; + } + + PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME)); + +private: + static handle decode_utfN(const char *buffer, ssize_t nbytes) { +#if !defined(PYPY_VERSION) + return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) + : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) + : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr); +#else + // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as + // well), so bypass the whole thing by just passing the encoding as a string value, which + // works properly: + return PyUnicode_Decode(buffer, + nbytes, + UTF_N == 8 ? "utf-8" + : UTF_N == 16 ? "utf-16" + : "utf-32", + nullptr); +#endif + } + + // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e. + // without any encoding/decoding attempt). For other C++ char sizes this is a no-op. + // which supports loading a unicode from a str, doesn't take this path. + template + bool load_raw(enable_if_t::value, handle> src) { + if (PYBIND11_BYTES_CHECK(src.ptr())) { + // We were passed raw bytes; accept it into a std::string or char* + // without any encoding attempt. + const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr()); + if (!bytes) { + pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure."); + } + value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr())); + return true; + } + if (PyByteArray_Check(src.ptr())) { + // We were passed a bytearray; accept it into a std::string or char* + // without any encoding attempt. + const char *bytearray = PyByteArray_AsString(src.ptr()); + if (!bytearray) { + pybind11_fail("Unexpected PyByteArray_AsString() failure."); + } + value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr())); + return true; + } + + return false; + } + + template + bool load_raw(enable_if_t::value, handle>) { + return false; + } +}; + +template +struct type_caster, + enable_if_t::value>> + : string_caster> {}; + +#ifdef PYBIND11_HAS_STRING_VIEW +template +struct type_caster, + enable_if_t::value>> + : string_caster, true> {}; +#endif + +// Type caster for C-style strings. We basically use a std::string type caster, but also add the +// ability to use None as a nullptr char* (which the string caster doesn't allow). +template +struct type_caster::value>> { + using StringType = std::basic_string; + using StringCaster = make_caster; + StringCaster str_caster; + bool none = false; + CharT one_char = 0; + +public: + bool load(handle src, bool convert) { + if (!src) { + return false; + } + if (src.is_none()) { + // Defer accepting None to other overloads (if we aren't in convert mode): + if (!convert) { + return false; + } + none = true; + return true; + } + return str_caster.load(src, convert); + } + + static handle cast(const CharT *src, return_value_policy policy, handle parent) { + if (src == nullptr) { + return pybind11::none().release(); + } + return StringCaster::cast(StringType(src), policy, parent); + } + + static handle cast(CharT src, return_value_policy policy, handle parent) { + if (std::is_same::value) { + handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr); + if (!s) { + throw error_already_set(); + } + return s; + } + return StringCaster::cast(StringType(1, src), policy, parent); + } + + explicit operator CharT *() { + return none ? nullptr : const_cast(static_cast(str_caster).c_str()); + } + explicit operator CharT &() { + if (none) { + throw value_error("Cannot convert None to a character"); + } + + auto &value = static_cast(str_caster); + size_t str_len = value.size(); + if (str_len == 0) { + throw value_error("Cannot convert empty string to a character"); + } + + // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that + // is too high, and one for multiple unicode characters (caught later), so we need to + // figure out how long the first encoded character is in bytes to distinguish between these + // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as + // those can fit into a single char value. + if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) { + auto v0 = static_cast(value[0]); + // low bits only: 0-127 + // 0b110xxxxx - start of 2-byte sequence + // 0b1110xxxx - start of 3-byte sequence + // 0b11110xxx - start of 4-byte sequence + size_t char0_bytes = (v0 & 0x80) == 0 ? 1 + : (v0 & 0xE0) == 0xC0 ? 2 + : (v0 & 0xF0) == 0xE0 ? 3 + : 4; + + if (char0_bytes == str_len) { + // If we have a 128-255 value, we can decode it into a single char: + if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx + one_char = static_cast(((v0 & 3) << 6) + + (static_cast(value[1]) & 0x3F)); + return one_char; + } + // Otherwise we have a single character, but it's > U+00FF + throw value_error("Character code point not in range(0x100)"); + } + } + + // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a + // surrogate pair with total length 2 instantly indicates a range error (but not a "your + // string was too long" error). + else if (StringCaster::UTF_N == 16 && str_len == 2) { + one_char = static_cast(value[0]); + if (one_char >= 0xD800 && one_char < 0xE000) { + throw value_error("Character code point not in range(0x10000)"); + } + } + + if (str_len != 1) { + throw value_error("Expected a character, but multi-character string found"); + } + + one_char = value[0]; + return one_char; + } + + static constexpr auto name = const_name(PYBIND11_STRING_NAME); + template + using cast_op_type = pybind11::detail::cast_op_type<_T>; +}; + +// Base implementation for std::tuple and std::pair +template