diff --git a/.gitattributes b/.gitattributes index 52e78da36ec70109691ca8d6b71750ca16a551a9..14786c6cca6ba067376cb1d56428223259e2cc7a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -990,3 +990,4 @@ omnilmm/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so fil omnilmm/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops_train.so.8 filter=lfs diff=lfs merge=lfs -text omnilmm/lib/python3.10/site-packages/pandas/core/__pycache__/frame.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text omnilmm/lib/python3.10/site-packages/pandas/tests/io/__pycache__/test_sql.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER b/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE b/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..96837bd9ed70a5a818227f2e1eb0db263dcd10ac --- /dev/null +++ b/omnilmm/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/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA b/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fa2550faeadd4cce0f28323321c2c212032f4481 --- /dev/null +++ b/omnilmm/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/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD b/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f4bc9005ba1d6f860f270a9cf25a1bdee9513d7e --- /dev/null +++ b/omnilmm/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/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED b/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL b/omnilmm/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4e4c38ae320920b8f083b87f408214cdecd350d2 --- /dev/null +++ b/omnilmm/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/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0a918d5ae4a748b5261eadb14edef29f274a91b Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11bced03d27e27ed9dc3a85ed82ed25f7b3caac6 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7975b07a9ae5015cefb2b80e8cfbd640a5f59213 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..018196503e6662966b29be13cf5610ae3e9255c2 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..993888bf67e7d65adf840994fc930d8a6e565495 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8ae93f85e44391d86b1fb226793c82657564ed4 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f951b5aceeb458de08460296d4ff3247c415fa4 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d5706053783eef026939ce667767334876f199e Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a4968d2f80ba37743db1444c43221c935a75be3 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfed6812ca641ba8d0483b526595f2065b2bffe8 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e12379b9482d88d796b04a56f9a0221feb41863d Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bfc999f8d1bf0936e0d457ecb248614239dbc2e Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/__init__.py b/omnilmm/lib/python3.10/site-packages/matplotlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ae68094000fc3361d970fb91b6950cf36cb7fec6 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/__init__.py @@ -0,0 +1,1486 @@ +""" +An object-oriented plotting library. + +A procedural interface is provided by the companion pyplot module, +which may be imported directly, e.g.:: + + import matplotlib.pyplot as plt + +or using ipython:: + + ipython + +at your terminal, followed by:: + + In [1]: %matplotlib + In [2]: import matplotlib.pyplot as plt + +at the ipython shell prompt. + +For the most part, direct use of the explicit object-oriented library is +encouraged when programming; the implicit pyplot interface is primarily for +working interactively. The exceptions to this suggestion are the pyplot +functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and +`.pyplot.savefig`, which can greatly simplify scripting. See +:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit +and explicit interfaces. + +Modules include: + + :mod:`matplotlib.axes` + The `~.axes.Axes` class. Most pyplot functions are wrappers for + `~.axes.Axes` methods. The axes module is the highest level of OO + access to the library. + + :mod:`matplotlib.figure` + The `.Figure` class. + + :mod:`matplotlib.artist` + The `.Artist` base class for all classes that draw things. + + :mod:`matplotlib.lines` + The `.Line2D` class for drawing lines and markers. + + :mod:`matplotlib.patches` + Classes for drawing polygons. + + :mod:`matplotlib.text` + The `.Text` and `.Annotation` classes. + + :mod:`matplotlib.image` + The `.AxesImage` and `.FigureImage` classes. + + :mod:`matplotlib.collections` + Classes for efficient drawing of groups of lines or polygons. + + :mod:`matplotlib.colors` + Color specifications and making colormaps. + + :mod:`matplotlib.cm` + Colormaps, and the `.ScalarMappable` mixin class for providing color + mapping functionality to other classes. + + :mod:`matplotlib.ticker` + Calculation of tick mark locations and formatting of tick labels. + + :mod:`matplotlib.backends` + A subpackage with modules for various GUI libraries and output formats. + +The base matplotlib namespace includes: + + `~matplotlib.rcParams` + Default configuration settings; their defaults may be overridden using + a :file:`matplotlibrc` file. + + `~matplotlib.use` + Setting the Matplotlib backend. This should be called before any + figure is created, because it is not possible to switch between + different GUI backends after that. + +The following environment variables can be used to customize the behavior: + + :envvar:`MPLBACKEND` + This optional variable can be set to choose the Matplotlib backend. See + :ref:`what-is-a-backend`. + + :envvar:`MPLCONFIGDIR` + This is the directory used to store user customizations to + Matplotlib, as well as some caches to improve performance. If + :envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib` + and :file:`{HOME}/.cache/matplotlib` are used on Linux, and + :file:`{HOME}/.matplotlib` on other platforms, if they are + writable. Otherwise, the Python standard library's `tempfile.gettempdir` + is used to find a base directory in which the :file:`matplotlib` + subdirectory is created. + +Matplotlib was initially written by John D. Hunter (1968-2012) and is now +developed and maintained by a host of others. + +Occasionally the internal documentation (python docstrings) will refer +to MATLAB®, a registered trademark of The MathWorks, Inc. + +""" + +import atexit +from collections import namedtuple +from collections.abc import MutableMapping +import contextlib +import functools +import importlib +import inspect +from inspect import Parameter +import locale +import logging +import os +from pathlib import Path +import pprint +import re +import shutil +import subprocess +import sys +import tempfile +import warnings + +import numpy +from packaging.version import parse as parse_version + +# cbook must import matplotlib only within function +# definitions, so it is safe to import from it here. +from . import _api, _version, cbook, _docstring, rcsetup +from matplotlib.cbook import sanitize_sequence +from matplotlib._api import MatplotlibDeprecationWarning +from matplotlib.rcsetup import validate_backend, cycler + + +_log = logging.getLogger(__name__) + +__bibtex__ = r"""@Article{Hunter:2007, + Author = {Hunter, J. D.}, + Title = {Matplotlib: A 2D graphics environment}, + Journal = {Computing in Science \& Engineering}, + Volume = {9}, + Number = {3}, + Pages = {90--95}, + abstract = {Matplotlib is a 2D graphics package used for Python + for application development, interactive scripting, and + publication-quality image generation across user + interfaces and operating systems.}, + publisher = {IEEE COMPUTER SOC}, + year = 2007 +}""" + +# modelled after sys.version_info +_VersionInfo = namedtuple('_VersionInfo', + 'major, minor, micro, releaselevel, serial') + + +def _parse_to_version_info(version_str): + """ + Parse a version string to a namedtuple analogous to sys.version_info. + + See: + https://packaging.pypa.io/en/latest/version.html#packaging.version.parse + https://docs.python.org/3/library/sys.html#sys.version_info + """ + v = parse_version(version_str) + if v.pre is None and v.post is None and v.dev is None: + return _VersionInfo(v.major, v.minor, v.micro, 'final', 0) + elif v.dev is not None: + return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev) + elif v.pre is not None: + releaselevel = { + 'a': 'alpha', + 'b': 'beta', + 'rc': 'candidate'}.get(v.pre[0], 'alpha') + return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1]) + else: + # fallback for v.post: guess-next-dev scheme from setuptools_scm + return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post) + + +def _get_version(): + """Return the version string used for __version__.""" + # Only shell out to a git subprocess if really needed, i.e. when we are in + # a matplotlib git repo but not in a shallow clone, such as those used by + # CI, as the latter would trigger a warning from setuptools_scm. + root = Path(__file__).resolve().parents[2] + if ((root / ".matplotlib-repo").exists() + and (root / ".git").exists() + and not (root / ".git/shallow").exists()): + import setuptools_scm + return setuptools_scm.get_version( + root=root, + version_scheme="release-branch-semver", + local_scheme="node-and-date", + fallback_version=_version.version, + ) + else: # Get the version from the _version.py setuptools_scm file. + return _version.version + + +@_api.caching_module_getattr +class __getattr__: + __version__ = property(lambda self: _get_version()) + __version_info__ = property( + lambda self: _parse_to_version_info(self.__version__)) + + +def _check_versions(): + + # Quickfix to ensure Microsoft Visual C++ redistributable + # DLLs are loaded before importing kiwisolver + from . import ft2font + + for modname, minver in [ + ("cycler", "0.10"), + ("dateutil", "2.7"), + ("kiwisolver", "1.0.1"), + ("numpy", "1.20"), + ("pyparsing", "2.3.1"), + ]: + module = importlib.import_module(modname) + if parse_version(module.__version__) < parse_version(minver): + raise ImportError(f"Matplotlib requires {modname}>={minver}; " + f"you have {module.__version__}") + + +_check_versions() + + +# The decorator ensures this always returns the same handler (and it is only +# attached once). +@functools.lru_cache() +def _ensure_handler(): + """ + The first time this function is called, attach a `StreamHandler` using the + same format as `logging.basicConfig` to the Matplotlib root logger. + + Return this handler every time this function is called. + """ + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) + _log.addHandler(handler) + return handler + + +def set_loglevel(level): + """ + Configure Matplotlib's logging levels. + + Matplotlib uses the standard library `logging` framework under the root + logger 'matplotlib'. This is a helper function to: + + - set Matplotlib's root logger level + - set the root logger handler's level, creating the handler + if it does not exist yet + + Typically, one should call ``set_loglevel("info")`` or + ``set_loglevel("debug")`` to get additional debugging information. + + Users or applications that are installing their own logging handlers + may want to directly manipulate ``logging.getLogger('matplotlib')`` rather + than use this function. + + Parameters + ---------- + level : {"notset", "debug", "info", "warning", "error", "critical"} + The log level of the handler. + + Notes + ----- + The first time this function is called, an additional handler is attached + to Matplotlib's root handler; this handler is reused every time and this + function simply manipulates the logger and handler's level. + + """ + _log.setLevel(level.upper()) + _ensure_handler().setLevel(level.upper()) + + +def _logged_cached(fmt, func=None): + """ + Decorator that logs a function's return value, and memoizes that value. + + After :: + + @_logged_cached(fmt) + def func(): ... + + the first call to *func* will log its return value at the DEBUG level using + %-format string *fmt*, and memoize it; later calls to *func* will directly + return that value. + """ + if func is None: # Return the actual decorator. + return functools.partial(_logged_cached, fmt) + + called = False + ret = None + + @functools.wraps(func) + def wrapper(**kwargs): + nonlocal called, ret + if not called: + ret = func(**kwargs) + called = True + _log.debug(fmt, ret) + return ret + + return wrapper + + +_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version") + + +class ExecutableNotFoundError(FileNotFoundError): + """ + Error raised when an executable that Matplotlib optionally + depends on can't be found. + """ + pass + + +@functools.lru_cache() +def _get_executable_info(name): + """ + Get the version of some executable that Matplotlib optionally depends on. + + .. warning:: + The list of executables that this function supports is set according to + Matplotlib's internal needs, and may change without notice. + + Parameters + ---------- + name : str + The executable to query. The following values are currently supported: + "dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This + list is subject to change without notice. + + Returns + ------- + tuple + A namedtuple with fields ``executable`` (`str`) and ``version`` + (`packaging.Version`, or ``None`` if the version cannot be determined). + + Raises + ------ + ExecutableNotFoundError + If the executable is not found or older than the oldest version + supported by Matplotlib. For debugging purposes, it is also + possible to "hide" an executable from Matplotlib by adding it to the + :envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated + list), which must be set prior to any calls to this function. + ValueError + If the executable is not one that we know how to query. + """ + + def impl(args, regex, min_ver=None, ignore_exit_code=False): + # Execute the subprocess specified by args; capture stdout and stderr. + # Search for a regex match in the output; if the match succeeds, the + # first group of the match is the version. + # Return an _ExecInfo if the executable exists, and has a version of + # at least min_ver (if set); else, raise ExecutableNotFoundError. + try: + output = subprocess.check_output( + args, stderr=subprocess.STDOUT, + universal_newlines=True, errors="replace") + except subprocess.CalledProcessError as _cpe: + if ignore_exit_code: + output = _cpe.output + else: + raise ExecutableNotFoundError(str(_cpe)) from _cpe + except OSError as _ose: + raise ExecutableNotFoundError(str(_ose)) from _ose + match = re.search(regex, output) + if match: + raw_version = match.group(1) + version = parse_version(raw_version) + if min_ver is not None and version < parse_version(min_ver): + raise ExecutableNotFoundError( + f"You have {args[0]} version {version} but the minimum " + f"version supported by Matplotlib is {min_ver}") + return _ExecInfo(args[0], raw_version, version) + else: + raise ExecutableNotFoundError( + f"Failed to determine the version of {args[0]} from " + f"{' '.join(args)}, which output {output}") + + if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","): + raise ExecutableNotFoundError(f"{name} was hidden") + + if name == "dvipng": + return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6") + elif name == "gs": + execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex. + if sys.platform == "win32" else + ["gs"]) + for e in execs: + try: + return impl([e, "--version"], "(.*)", "9") + except ExecutableNotFoundError: + pass + message = "Failed to find a Ghostscript installation" + raise ExecutableNotFoundError(message) + elif name == "inkscape": + try: + # Try headless option first (needed for Inkscape version < 1.0): + return impl(["inkscape", "--without-gui", "-V"], + "Inkscape ([^ ]*)") + except ExecutableNotFoundError: + pass # Suppress exception chaining. + # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so + # try without it: + return impl(["inkscape", "-V"], "Inkscape ([^ ]*)") + elif name == "magick": + if sys.platform == "win32": + # Check the registry to avoid confusing ImageMagick's convert with + # Windows's builtin convert.exe. + import winreg + binpath = "" + for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]: + try: + with winreg.OpenKeyEx( + winreg.HKEY_LOCAL_MACHINE, + r"Software\Imagemagick\Current", + 0, winreg.KEY_QUERY_VALUE | flag) as hkey: + binpath = winreg.QueryValueEx(hkey, "BinPath")[0] + except OSError: + pass + path = None + if binpath: + for name in ["convert.exe", "magick.exe"]: + candidate = Path(binpath, name) + if candidate.exists(): + path = str(candidate) + break + if path is None: + raise ExecutableNotFoundError( + "Failed to find an ImageMagick installation") + else: + path = "convert" + info = impl([path, "--version"], r"^Version: ImageMagick (\S*)") + if info.raw_version == "7.0.10-34": + # https://github.com/ImageMagick/ImageMagick/issues/2720 + raise ExecutableNotFoundError( + f"You have ImageMagick {info.version}, which is unsupported") + return info + elif name == "pdftocairo": + return impl(["pdftocairo", "-v"], "pdftocairo version (.*)") + elif name == "pdftops": + info = impl(["pdftops", "-v"], "^pdftops version (.*)", + ignore_exit_code=True) + if info and not ( + 3 <= info.version.major or + # poppler version numbers. + parse_version("0.9") <= info.version < parse_version("1.0")): + raise ExecutableNotFoundError( + f"You have pdftops version {info.version} but the minimum " + f"version supported by Matplotlib is 3.0") + return info + else: + raise ValueError("Unknown executable: {!r}".format(name)) + + +@_api.deprecated("3.6", alternative="a vendored copy of this function") +def checkdep_usetex(s): + if not s: + return False + if not shutil.which("tex"): + _log.warning("usetex mode requires TeX.") + return False + try: + _get_executable_info("dvipng") + except ExecutableNotFoundError: + _log.warning("usetex mode requires dvipng.") + return False + try: + _get_executable_info("gs") + except ExecutableNotFoundError: + _log.warning("usetex mode requires ghostscript.") + return False + return True + + +def _get_xdg_config_dir(): + """ + Return the XDG configuration directory, according to the XDG base + directory spec: + + https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html + """ + return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config") + + +def _get_xdg_cache_dir(): + """ + Return the XDG cache directory, according to the XDG base directory spec: + + https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html + """ + return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache") + + +def _get_config_or_cache_dir(xdg_base_getter): + configdir = os.environ.get('MPLCONFIGDIR') + if configdir: + configdir = Path(configdir).resolve() + elif sys.platform.startswith(('linux', 'freebsd')): + # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first, + # as _xdg_base_getter can throw. + configdir = Path(xdg_base_getter(), "matplotlib") + else: + configdir = Path.home() / ".matplotlib" + try: + configdir.mkdir(parents=True, exist_ok=True) + except OSError: + pass + else: + if os.access(str(configdir), os.W_OK) and configdir.is_dir(): + return str(configdir) + # If the config or cache directory cannot be created or is not a writable + # directory, create a temporary one. + try: + tmpdir = tempfile.mkdtemp(prefix="matplotlib-") + except OSError as exc: + raise OSError( + f"Matplotlib requires access to a writable cache directory, but the " + f"default path ({configdir}) is not a writable directory, and a temporary " + f"directory could not be created; set the MPLCONFIGDIR environment " + f"variable to a writable directory") from exc + os.environ["MPLCONFIGDIR"] = tmpdir + atexit.register(shutil.rmtree, tmpdir) + _log.warning( + "Matplotlib created a temporary cache directory at %s because the default path " + "(%s) is not a writable directory; it is highly recommended to set the " + "MPLCONFIGDIR environment variable to a writable directory, in particular to " + "speed up the import of Matplotlib and to better support multiprocessing.", + tmpdir, configdir) + return tmpdir + + +@_logged_cached('CONFIGDIR=%s') +def get_configdir(): + """ + Return the string path of the configuration directory. + + The directory is chosen as follows: + + 1. If the MPLCONFIGDIR environment variable is supplied, choose that. + 2. On Linux, follow the XDG specification and look first in + ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other + platforms, choose ``$HOME/.matplotlib``. + 3. If the chosen directory exists and is writable, use that as the + configuration directory. + 4. Else, create a temporary directory, and use it as the configuration + directory. + """ + return _get_config_or_cache_dir(_get_xdg_config_dir) + + +@_logged_cached('CACHEDIR=%s') +def get_cachedir(): + """ + Return the string path of the cache directory. + + The procedure used to find the directory is the same as for + _get_config_dir, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead. + """ + return _get_config_or_cache_dir(_get_xdg_cache_dir) + + +@_logged_cached('matplotlib data path: %s') +def get_data_path(): + """Return the path to Matplotlib data.""" + return str(Path(__file__).with_name("mpl-data")) + + +def matplotlib_fname(): + """ + Get the location of the config file. + + The file location is determined in the following order + + - ``$PWD/matplotlibrc`` + - ``$MATPLOTLIBRC`` if it is not a directory + - ``$MATPLOTLIBRC/matplotlibrc`` + - ``$MPLCONFIGDIR/matplotlibrc`` + - On Linux, + - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` + is defined) + - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` + is not defined) + - On other platforms, + - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined + - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always + exist. + """ + + def gen_candidates(): + # rely on down-stream code to make absolute. This protects us + # from having to directly get the current working directory + # which can fail if the user has ended up with a cwd that is + # non-existent. + yield 'matplotlibrc' + try: + matplotlibrc = os.environ['MATPLOTLIBRC'] + except KeyError: + pass + else: + yield matplotlibrc + yield os.path.join(matplotlibrc, 'matplotlibrc') + yield os.path.join(get_configdir(), 'matplotlibrc') + yield os.path.join(get_data_path(), 'matplotlibrc') + + for fname in gen_candidates(): + if os.path.exists(fname) and not os.path.isdir(fname): + return fname + + raise RuntimeError("Could not find matplotlibrc file; your Matplotlib " + "install is broken") + + +# rcParams deprecated and automatically mapped to another key. +# Values are tuples of (version, new_name, f_old2new, f_new2old). +_deprecated_map = {} +# rcParams deprecated; some can manually be mapped to another key. +# Values are tuples of (version, new_name_or_None). +_deprecated_ignore_map = {} +# rcParams deprecated; can use None to suppress warnings; remain actually +# listed in the rcParams. +# Values are tuples of (version,) +_deprecated_remain_as_none = {} + + +@_docstring.Substitution( + "\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower))) +) +class RcParams(MutableMapping, dict): + """ + A dict-like key-value store for config parameters, including validation. + + Validating functions are defined and associated with rc parameters in + :mod:`matplotlib.rcsetup`. + + The list of rcParams is: + + %s + + See Also + -------- + :ref:`customizing-with-matplotlibrc-files` + """ + + validate = rcsetup._validators + + # validate values on the way in + def __init__(self, *args, **kwargs): + self.update(*args, **kwargs) + + def _set(self, key, val): + """ + Directly write data bypassing deprecation and validation logic. + + Notes + ----- + As end user or downstream library you almost always should use + ``rcParams[key] = val`` and not ``_set()``. + + There are only very few special cases that need direct data access. + These cases previously used ``dict.__setitem__(rcParams, key, val)``, + which is now deprecated and replaced by ``rcParams._set(key, val)``. + + Even though private, we guarantee API stability for ``rcParams._set``, + i.e. it is subject to Matplotlib's API and deprecation policy. + + :meta public: + """ + dict.__setitem__(self, key, val) + + def _get(self, key): + """ + Directly read data bypassing deprecation, backend and validation + logic. + + Notes + ----- + As end user or downstream library you almost always should use + ``val = rcParams[key]`` and not ``_get()``. + + There are only very few special cases that need direct data access. + These cases previously used ``dict.__getitem__(rcParams, key, val)``, + which is now deprecated and replaced by ``rcParams._get(key)``. + + Even though private, we guarantee API stability for ``rcParams._get``, + i.e. it is subject to Matplotlib's API and deprecation policy. + + :meta public: + """ + return dict.__getitem__(self, key) + + def __setitem__(self, key, val): + try: + if key in _deprecated_map: + version, alt_key, alt_val, inverse_alt = _deprecated_map[key] + _api.warn_deprecated( + version, name=key, obj_type="rcparam", alternative=alt_key) + key = alt_key + val = alt_val(val) + elif key in _deprecated_remain_as_none and val is not None: + version, = _deprecated_remain_as_none[key] + _api.warn_deprecated(version, name=key, obj_type="rcparam") + elif key in _deprecated_ignore_map: + version, alt_key = _deprecated_ignore_map[key] + _api.warn_deprecated( + version, name=key, obj_type="rcparam", alternative=alt_key) + return + elif key == 'backend': + if val is rcsetup._auto_backend_sentinel: + if 'backend' in self: + return + try: + cval = self.validate[key](val) + except ValueError as ve: + raise ValueError(f"Key {key}: {ve}") from None + self._set(key, cval) + except KeyError as err: + raise KeyError( + f"{key} is not a valid rc parameter (see rcParams.keys() for " + f"a list of valid parameters)") from err + + def __getitem__(self, key): + if key in _deprecated_map: + version, alt_key, alt_val, inverse_alt = _deprecated_map[key] + _api.warn_deprecated( + version, name=key, obj_type="rcparam", alternative=alt_key) + return inverse_alt(self._get(alt_key)) + + elif key in _deprecated_ignore_map: + version, alt_key = _deprecated_ignore_map[key] + _api.warn_deprecated( + version, name=key, obj_type="rcparam", alternative=alt_key) + return self._get(alt_key) if alt_key else None + + # In theory, this should only ever be used after the global rcParams + # has been set up, but better be safe e.g. in presence of breakpoints. + elif key == "backend" and self is globals().get("rcParams"): + val = self._get(key) + if val is rcsetup._auto_backend_sentinel: + from matplotlib import pyplot as plt + plt.switch_backend(rcsetup._auto_backend_sentinel) + + return self._get(key) + + def _get_backend_or_none(self): + """Get the requested backend, if any, without triggering resolution.""" + backend = self._get("backend") + return None if backend is rcsetup._auto_backend_sentinel else backend + + def __repr__(self): + class_name = self.__class__.__name__ + indent = len(class_name) + 1 + with _api.suppress_matplotlib_deprecation_warning(): + repr_split = pprint.pformat(dict(self), indent=1, + width=80 - indent).split('\n') + repr_indented = ('\n' + ' ' * indent).join(repr_split) + return '{}({})'.format(class_name, repr_indented) + + def __str__(self): + return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items()))) + + def __iter__(self): + """Yield sorted list of keys.""" + with _api.suppress_matplotlib_deprecation_warning(): + yield from sorted(dict.__iter__(self)) + + def __len__(self): + return dict.__len__(self) + + def find_all(self, pattern): + """ + Return the subset of this RcParams dictionary whose keys match, + using :func:`re.search`, the given ``pattern``. + + .. note:: + + Changes to the returned dictionary are *not* propagated to + the parent RcParams dictionary. + + """ + pattern_re = re.compile(pattern) + return RcParams((key, value) + for key, value in self.items() + if pattern_re.search(key)) + + def copy(self): + """Copy this RcParams instance.""" + rccopy = RcParams() + for k in self: # Skip deprecations and revalidation. + rccopy._set(k, self._get(k)) + return rccopy + + +def rc_params(fail_on_error=False): + """Construct a `RcParams` instance from the default Matplotlib rc file.""" + return rc_params_from_file(matplotlib_fname(), fail_on_error) + + +@functools.lru_cache() +def _get_ssl_context(): + try: + import certifi + except ImportError: + _log.debug("Could not import certifi.") + return None + import ssl + return ssl.create_default_context(cafile=certifi.where()) + + +@contextlib.contextmanager +def _open_file_or_url(fname): + if (isinstance(fname, str) + and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))): + import urllib.request + ssl_ctx = _get_ssl_context() + if ssl_ctx is None: + _log.debug( + "Could not get certifi ssl context, https may not work." + ) + with urllib.request.urlopen(fname, context=ssl_ctx) as f: + yield (line.decode('utf-8') for line in f) + else: + fname = os.path.expanduser(fname) + with open(fname, encoding='utf-8') as f: + yield f + + +def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False): + """ + Construct a `RcParams` instance from file *fname*. + + Unlike `rc_params_from_file`, the configuration class only contains the + parameters specified in the file (i.e. default values are not filled in). + + Parameters + ---------- + fname : path-like + The loaded file. + transform : callable, default: the identity function + A function called on each individual line of the file to transform it, + before further parsing. + fail_on_error : bool, default: False + Whether invalid entries should result in an exception or a warning. + """ + import matplotlib as mpl + rc_temp = {} + with _open_file_or_url(fname) as fd: + try: + for line_no, line in enumerate(fd, 1): + line = transform(line) + strippedline = cbook._strip_comment(line) + if not strippedline: + continue + tup = strippedline.split(':', 1) + if len(tup) != 2: + _log.warning('Missing colon in file %r, line %d (%r)', + fname, line_no, line.rstrip('\n')) + continue + key, val = tup + key = key.strip() + val = val.strip() + if val.startswith('"') and val.endswith('"'): + val = val[1:-1] # strip double quotes + if key in rc_temp: + _log.warning('Duplicate key in file %r, line %d (%r)', + fname, line_no, line.rstrip('\n')) + rc_temp[key] = (val, line, line_no) + except UnicodeDecodeError: + _log.warning('Cannot decode configuration file %r as utf-8.', + fname) + raise + + config = RcParams() + + for key, (val, line, line_no) in rc_temp.items(): + if key in rcsetup._validators: + if fail_on_error: + config[key] = val # try to convert to proper type or raise + else: + try: + config[key] = val # try to convert to proper type or skip + except Exception as msg: + _log.warning('Bad value in file %r, line %d (%r): %s', + fname, line_no, line.rstrip('\n'), msg) + elif key in _deprecated_ignore_map: + version, alt_key = _deprecated_ignore_map[key] + _api.warn_deprecated( + version, name=key, alternative=alt_key, obj_type='rcparam', + addendum="Please update your matplotlibrc.") + else: + # __version__ must be looked up as an attribute to trigger the + # module-level __getattr__. + version = ('main' if '.post' in mpl.__version__ + else f'v{mpl.__version__}') + _log.warning(""" +Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r) +You probably need to get an updated matplotlibrc file from +https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc +or from the matplotlib source distribution""", + dict(key=key, fname=fname, line_no=line_no, + line=line.rstrip('\n'), version=version)) + return config + + +def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): + """ + Construct a `RcParams` from file *fname*. + + Parameters + ---------- + fname : str or path-like + A file with Matplotlib rc settings. + fail_on_error : bool + If True, raise an error when the parser fails to convert a parameter. + use_default_template : bool + If True, initialize with default parameters before updating with those + in the given file. If False, the configuration class only contains the + parameters specified in the file. (Useful for updating dicts.) + """ + config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error) + + if not use_default_template: + return config_from_file + + with _api.suppress_matplotlib_deprecation_warning(): + config = RcParams({**rcParamsDefault, **config_from_file}) + + if "".join(config['text.latex.preamble']): + _log.info(""" +***************************************************************** +You have the following UNSUPPORTED LaTeX preamble customizations: +%s +Please do not ask for support with these customizations active. +***************************************************************** +""", '\n'.join(config['text.latex.preamble'])) + _log.debug('loaded rc file %s', fname) + + return config + + +# When constructing the global instances, we need to perform certain updates +# by explicitly calling the superclass (dict.update, dict.items) to avoid +# triggering resolution of _auto_backend_sentinel. +rcParamsDefault = _rc_params_in_file( + cbook._get_data_path("matplotlibrc"), + # Strip leading comment. + transform=lambda line: line[1:] if line.startswith("#") else line, + fail_on_error=True) +dict.update(rcParamsDefault, rcsetup._hardcoded_defaults) +# Normally, the default matplotlibrc file contains *no* entry for backend (the +# corresponding line starts with ##, not #; we fill on _auto_backend_sentinel +# in that case. However, packagers can set a different default backend +# (resulting in a normal `#backend: foo` line) in which case we should *not* +# fill in _auto_backend_sentinel. +dict.setdefault(rcParamsDefault, "backend", rcsetup._auto_backend_sentinel) +rcParams = RcParams() # The global instance. +dict.update(rcParams, dict.items(rcParamsDefault)) +dict.update(rcParams, _rc_params_in_file(matplotlib_fname())) +rcParamsOrig = rcParams.copy() +with _api.suppress_matplotlib_deprecation_warning(): + # This also checks that all rcParams are indeed listed in the template. + # Assigning to rcsetup.defaultParams is left only for backcompat. + defaultParams = rcsetup.defaultParams = { + # We want to resolve deprecated rcParams, but not backend... + key: [(rcsetup._auto_backend_sentinel if key == "backend" else + rcParamsDefault[key]), + validator] + for key, validator in rcsetup._validators.items()} +if rcParams['axes.formatter.use_locale']: + locale.setlocale(locale.LC_ALL, '') + + +def rc(group, **kwargs): + """ + Set the current `.rcParams`. *group* is the grouping for the rc, e.g., + for ``lines.linewidth`` the group is ``lines``, for + ``axes.facecolor``, the group is ``axes``, and so on. Group may + also be a list or tuple of group names, e.g., (*xtick*, *ytick*). + *kwargs* is a dictionary attribute name/value pairs, e.g.,:: + + rc('lines', linewidth=2, color='r') + + sets the current `.rcParams` and is equivalent to:: + + rcParams['lines.linewidth'] = 2 + rcParams['lines.color'] = 'r' + + The following aliases are available to save typing for interactive users: + + ===== ================= + Alias Property + ===== ================= + 'lw' 'linewidth' + 'ls' 'linestyle' + 'c' 'color' + 'fc' 'facecolor' + 'ec' 'edgecolor' + 'mew' 'markeredgewidth' + 'aa' 'antialiased' + ===== ================= + + Thus you could abbreviate the above call as:: + + rc('lines', lw=2, c='r') + + Note you can use python's kwargs dictionary facility to store + dictionaries of default parameters. e.g., you can customize the + font rc as follows:: + + font = {'family' : 'monospace', + 'weight' : 'bold', + 'size' : 'larger'} + rc('font', **font) # pass in the font dict as kwargs + + This enables you to easily switch between several configurations. Use + ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to + restore the default `.rcParams` after changes. + + Notes + ----- + Similar functionality is available by using the normal dict interface, i.e. + ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update`` + does not support abbreviations or grouping). + """ + + aliases = { + 'lw': 'linewidth', + 'ls': 'linestyle', + 'c': 'color', + 'fc': 'facecolor', + 'ec': 'edgecolor', + 'mew': 'markeredgewidth', + 'aa': 'antialiased', + } + + if isinstance(group, str): + group = (group,) + for g in group: + for k, v in kwargs.items(): + name = aliases.get(k) or k + key = '%s.%s' % (g, name) + try: + rcParams[key] = v + except KeyError as err: + raise KeyError(('Unrecognized key "%s" for group "%s" and ' + 'name "%s"') % (key, g, name)) from err + + +def rcdefaults(): + """ + Restore the `.rcParams` from Matplotlib's internal default style. + + Style-blacklisted `.rcParams` (defined in + ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated. + + See Also + -------- + matplotlib.rc_file_defaults + Restore the `.rcParams` from the rc file originally loaded by + Matplotlib. + matplotlib.style.use + Use a specific style file. Call ``style.use('default')`` to restore + the default style. + """ + # Deprecation warnings were already handled when creating rcParamsDefault, + # no need to reemit them here. + with _api.suppress_matplotlib_deprecation_warning(): + from .style.core import STYLE_BLACKLIST + rcParams.clear() + rcParams.update({k: v for k, v in rcParamsDefault.items() + if k not in STYLE_BLACKLIST}) + + +def rc_file_defaults(): + """ + Restore the `.rcParams` from the original rc file loaded by Matplotlib. + + Style-blacklisted `.rcParams` (defined in + ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated. + """ + # Deprecation warnings were already handled when creating rcParamsOrig, no + # need to reemit them here. + with _api.suppress_matplotlib_deprecation_warning(): + from .style.core import STYLE_BLACKLIST + rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig + if k not in STYLE_BLACKLIST}) + + +def rc_file(fname, *, use_default_template=True): + """ + Update `.rcParams` from file. + + Style-blacklisted `.rcParams` (defined in + ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated. + + Parameters + ---------- + fname : str or path-like + A file with Matplotlib rc settings. + + use_default_template : bool + If True, initialize with default parameters before updating with those + in the given file. If False, the current configuration persists + and only the parameters specified in the file are updated. + """ + # Deprecation warnings were already handled in rc_params_from_file, no need + # to reemit them here. + with _api.suppress_matplotlib_deprecation_warning(): + from .style.core import STYLE_BLACKLIST + rc_from_file = rc_params_from_file( + fname, use_default_template=use_default_template) + rcParams.update({k: rc_from_file[k] for k in rc_from_file + if k not in STYLE_BLACKLIST}) + + +@contextlib.contextmanager +def rc_context(rc=None, fname=None): + """ + Return a context manager for temporarily changing rcParams. + + The :rc:`backend` will not be reset by the context manager. + + rcParams changed both through the context manager invocation and + in the body of the context will be reset on context exit. + + Parameters + ---------- + rc : dict + The rcParams to temporarily set. + fname : str or path-like + A file with Matplotlib rc settings. If both *fname* and *rc* are given, + settings from *rc* take precedence. + + See Also + -------- + :ref:`customizing-with-matplotlibrc-files` + + Examples + -------- + Passing explicit values via a dict:: + + with mpl.rc_context({'interactive': False}): + fig, ax = plt.subplots() + ax.plot(range(3), range(3)) + fig.savefig('example.png') + plt.close(fig) + + Loading settings from a file:: + + with mpl.rc_context(fname='print.rc'): + plt.plot(x, y) # uses 'print.rc' + + Setting in the context body:: + + with mpl.rc_context(): + # will be reset + mpl.rcParams['lines.linewidth'] = 5 + plt.plot(x, y) + + """ + orig = dict(rcParams.copy()) + del orig['backend'] + try: + if fname: + rc_file(fname) + if rc: + rcParams.update(rc) + yield + finally: + dict.update(rcParams, orig) # Revert to the original rcs. + + +def use(backend, *, force=True): + """ + Select the backend used for rendering and GUI integration. + + If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used + and if the new backend is different than the current backend, all Figures + will be closed. + + Parameters + ---------- + backend : str + The backend to switch to. This can either be one of the standard + backend names, which are case-insensitive: + + - interactive backends: + GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, QtAgg, + QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo + + - non-interactive backends: + agg, cairo, pdf, pgf, ps, svg, template + + or a string of the form: ``module://my.module.name``. + + Switching to an interactive backend is not possible if an unrelated + event loop has already been started (e.g., switching to GTK3Agg if a + TkAgg window has already been opened). Switching to a non-interactive + backend is always possible. + + force : bool, default: True + If True (the default), raise an `ImportError` if the backend cannot be + set up (either because it fails to import, or because an incompatible + GUI interactive framework is already running); if False, silently + ignore the failure. + + See Also + -------- + :ref:`backends` + matplotlib.get_backend + matplotlib.pyplot.switch_backend + + """ + name = validate_backend(backend) + # don't (prematurely) resolve the "auto" backend setting + if rcParams._get_backend_or_none() == name: + # Nothing to do if the requested backend is already set + pass + else: + # if pyplot is not already imported, do not import it. Doing + # so may trigger a `plt.switch_backend` to the _default_ backend + # before we get a chance to change to the one the user just requested + plt = sys.modules.get('matplotlib.pyplot') + # if pyplot is imported, then try to change backends + if plt is not None: + try: + # we need this import check here to re-raise if the + # user does not have the libraries to support their + # chosen backend installed. + plt.switch_backend(name) + except ImportError: + if force: + raise + # if we have not imported pyplot, then we can set the rcParam + # value which will be respected when the user finally imports + # pyplot + else: + rcParams['backend'] = backend + # if the user has asked for a given backend, do not helpfully + # fallback + rcParams['backend_fallback'] = False + + +if os.environ.get('MPLBACKEND'): + rcParams['backend'] = os.environ.get('MPLBACKEND') + + +def get_backend(): + """ + Return the name of the current backend. + + See Also + -------- + matplotlib.use + """ + return rcParams['backend'] + + +def interactive(b): + """ + Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`). + """ + rcParams['interactive'] = b + + +def is_interactive(): + """ + Return whether to redraw after every plotting command. + + .. note:: + + This function is only intended for use in backends. End users should + use `.pyplot.isinteractive` instead. + """ + return rcParams['interactive'] + + +def _init_tests(): + # The version of FreeType to install locally for running the + # tests. This must match the value in `setupext.py` + LOCAL_FREETYPE_VERSION = '2.6.1' + + from matplotlib import ft2font + if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or + ft2font.__freetype_build_type__ != 'local'): + _log.warning( + f"Matplotlib is not built with the correct FreeType version to " + f"run tests. Rebuild without setting system_freetype=1 in " + f"mplsetup.cfg. Expect many image comparison failures below. " + f"Expected freetype version {LOCAL_FREETYPE_VERSION}. " + f"Found freetype version {ft2font.__freetype_version__}. " + "Freetype build type is {}local".format( + "" if ft2font.__freetype_build_type__ == 'local' else "not ")) + + +def _replacer(data, value): + """ + Either returns ``data[value]`` or passes ``data`` back, converts either to + a sequence. + """ + try: + # if key isn't a string don't bother + if isinstance(value, str): + # try to use __getitem__ + value = data[value] + except Exception: + # key does not exist, silently fall back to key + pass + return sanitize_sequence(value) + + +def _label_from_arg(y, default_name): + try: + return y.name + except AttributeError: + if isinstance(default_name, str): + return default_name + return None + + +def _add_data_doc(docstring, replace_names): + """ + Add documentation for a *data* field to the given docstring. + + Parameters + ---------- + docstring : str + The input docstring. + replace_names : list of str or None + The list of parameter names which arguments should be replaced by + ``data[name]`` (if ``data[name]`` does not throw an exception). If + None, replacement is attempted for all arguments. + + Returns + ------- + str + The augmented docstring. + """ + if (docstring is None + or replace_names is not None and len(replace_names) == 0): + return docstring + docstring = inspect.cleandoc(docstring) + + data_doc = ("""\ + If given, all parameters also accept a string ``s``, which is + interpreted as ``data[s]`` (unless this raises an exception).""" + if replace_names is None else f"""\ + If given, the following parameters also accept a string ``s``, which is + interpreted as ``data[s]`` (unless this raises an exception): + + {', '.join(map('*{}*'.format, replace_names))}""") + # using string replacement instead of formatting has the advantages + # 1) simpler indent handling + # 2) prevent problems with formatting characters '{', '%' in the docstring + if _log.level <= logging.DEBUG: + # test_data_parameter_replacement() tests against these log messages + # make sure to keep message and test in sync + if "data : indexable object, optional" not in docstring: + _log.debug("data parameter docstring error: no data parameter") + if 'DATA_PARAMETER_PLACEHOLDER' not in docstring: + _log.debug("data parameter docstring error: missing placeholder") + return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc) + + +def _preprocess_data(func=None, *, replace_names=None, label_namer=None): + """ + A decorator to add a 'data' kwarg to a function. + + When applied:: + + @_preprocess_data() + def func(ax, *args, **kwargs): ... + + the signature is modified to ``decorated(ax, *args, data=None, **kwargs)`` + with the following behavior: + + - if called with ``data=None``, forward the other arguments to ``func``; + - otherwise, *data* must be a mapping; for any argument passed in as a + string ``name``, replace the argument by ``data[name]`` (if this does not + throw an exception), then forward the arguments to ``func``. + + In either case, any argument that is a `MappingView` is also converted to a + list. + + Parameters + ---------- + replace_names : list of str or None, default: None + The list of parameter names for which lookup into *data* should be + attempted. If None, replacement is attempted for all arguments. + label_namer : str, default: None + If set e.g. to "namer" (which must be a kwarg in the function's + signature -- not as ``**kwargs``), if the *namer* argument passed in is + a (string) key of *data* and no *label* kwarg is passed, then use the + (string) value of the *namer* as *label*. :: + + @_preprocess_data(label_namer="foo") + def func(foo, label=None): ... + + func("key", data={"key": value}) + # is equivalent to + func.__wrapped__(value, label="key") + """ + + if func is None: # Return the actual decorator. + return functools.partial( + _preprocess_data, + replace_names=replace_names, label_namer=label_namer) + + sig = inspect.signature(func) + varargs_name = None + varkwargs_name = None + arg_names = [] + params = list(sig.parameters.values()) + for p in params: + if p.kind is Parameter.VAR_POSITIONAL: + varargs_name = p.name + elif p.kind is Parameter.VAR_KEYWORD: + varkwargs_name = p.name + else: + arg_names.append(p.name) + data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None) + if varkwargs_name: + params.insert(-1, data_param) + else: + params.append(data_param) + new_sig = sig.replace(parameters=params) + arg_names = arg_names[1:] # remove the first "ax" / self arg + + assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, ( + "Matplotlib internal error: invalid replace_names ({!r}) for {!r}" + .format(replace_names, func.__name__)) + assert label_namer is None or label_namer in arg_names, ( + "Matplotlib internal error: invalid label_namer ({!r}) for {!r}" + .format(label_namer, func.__name__)) + + @functools.wraps(func) + def inner(ax, *args, data=None, **kwargs): + if data is None: + return func(ax, *map(sanitize_sequence, args), **kwargs) + + bound = new_sig.bind(ax, *args, **kwargs) + auto_label = (bound.arguments.get(label_namer) + or bound.kwargs.get(label_namer)) + + for k, v in bound.arguments.items(): + if k == varkwargs_name: + for k1, v1 in v.items(): + if replace_names is None or k1 in replace_names: + v[k1] = _replacer(data, v1) + elif k == varargs_name: + if replace_names is None: + bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v) + else: + if replace_names is None or k in replace_names: + bound.arguments[k] = _replacer(data, v) + + new_args = bound.args + new_kwargs = bound.kwargs + + args_and_kwargs = {**bound.arguments, **bound.kwargs} + if label_namer and "label" not in args_and_kwargs: + new_kwargs["label"] = _label_from_arg( + args_and_kwargs.get(label_namer), auto_label) + + return func(*new_args, **new_kwargs) + + inner.__doc__ = _add_data_doc(inner.__doc__, replace_names) + inner.__signature__ = new_sig + return inner + + +_log.debug('interactive is %s', is_interactive()) +_log.debug('platform is %s', sys.platform) + + +# workaround: we must defer colormaps import to after loading rcParams, because +# colormap creation depends on rcParams +from matplotlib.cm import _colormaps as colormaps +from matplotlib.colors import _color_sequences as color_sequences diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/_afm.py b/omnilmm/lib/python3.10/site-packages/matplotlib/_afm.py new file mode 100644 index 0000000000000000000000000000000000000000..3d02d7f9c1d6cdcfc0410ea5e8cba13665163d0e --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/_afm.py @@ -0,0 +1,532 @@ +""" +A python interface to Adobe Font Metrics Files. + +Although a number of other Python implementations exist, and may be more +complete than this, it was decided not to go with them because they were +either: + +1) copyrighted or used a non-BSD compatible license +2) had too many dependencies and a free standing lib was needed +3) did more than needed and it was easier to write afresh rather than + figure out how to get just what was needed. + +It is pretty easy to use, and has no external dependencies: + +>>> import matplotlib as mpl +>>> from pathlib import Path +>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm') +>>> +>>> from matplotlib.afm import AFM +>>> with afm_path.open('rb') as fh: +... afm = AFM(fh) +>>> afm.string_width_height('What the heck?') +(6220.0, 694) +>>> afm.get_fontname() +'Times-Roman' +>>> afm.get_kern_dist('A', 'f') +0 +>>> afm.get_kern_dist('A', 'y') +-92.0 +>>> afm.get_bbox_char('!') +[130, -9, 238, 676] + +As in the Adobe Font Metrics File Format Specification, all dimensions +are given in units of 1/1000 of the scale factor (point size) of the font +being used. +""" + +from collections import namedtuple +import logging +import re + +from ._mathtext_data import uni2type1 + + +_log = logging.getLogger(__name__) + + +def _to_int(x): + # Some AFM files have floats where we are expecting ints -- there is + # probably a better way to handle this (support floats, round rather than + # truncate). But I don't know what the best approach is now and this + # change to _to_int should at least prevent Matplotlib from crashing on + # these. JDH (2009-11-06) + return int(float(x)) + + +def _to_float(x): + # Some AFM files use "," instead of "." as decimal separator -- this + # shouldn't be ambiguous (unless someone is wicked enough to use "," as + # thousands separator...). + if isinstance(x, bytes): + # Encoding doesn't really matter -- if we have codepoints >127 the call + # to float() will error anyways. + x = x.decode('latin-1') + return float(x.replace(',', '.')) + + +def _to_str(x): + return x.decode('utf8') + + +def _to_list_of_ints(s): + s = s.replace(b',', b' ') + return [_to_int(val) for val in s.split()] + + +def _to_list_of_floats(s): + return [_to_float(val) for val in s.split()] + + +def _to_bool(s): + if s.lower().strip() in (b'false', b'0', b'no'): + return False + else: + return True + + +def _parse_header(fh): + """ + Read the font metrics header (up to the char metrics) and returns + a dictionary mapping *key* to *val*. *val* will be converted to the + appropriate python type as necessary; e.g.: + + * 'False'->False + * '0'->0 + * '-168 -218 1000 898'-> [-168, -218, 1000, 898] + + Dictionary keys are + + StartFontMetrics, FontName, FullName, FamilyName, Weight, + ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition, + UnderlineThickness, Version, Notice, EncodingScheme, CapHeight, + XHeight, Ascender, Descender, StartCharMetrics + """ + header_converters = { + b'StartFontMetrics': _to_float, + b'FontName': _to_str, + b'FullName': _to_str, + b'FamilyName': _to_str, + b'Weight': _to_str, + b'ItalicAngle': _to_float, + b'IsFixedPitch': _to_bool, + b'FontBBox': _to_list_of_ints, + b'UnderlinePosition': _to_float, + b'UnderlineThickness': _to_float, + b'Version': _to_str, + # Some AFM files have non-ASCII characters (which are not allowed by + # the spec). Given that there is actually no public API to even access + # this field, just return it as straight bytes. + b'Notice': lambda x: x, + b'EncodingScheme': _to_str, + b'CapHeight': _to_float, # Is the second version a mistake, or + b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS + b'XHeight': _to_float, + b'Ascender': _to_float, + b'Descender': _to_float, + b'StdHW': _to_float, + b'StdVW': _to_float, + b'StartCharMetrics': _to_int, + b'CharacterSet': _to_str, + b'Characters': _to_int, + } + d = {} + first_line = True + for line in fh: + line = line.rstrip() + if line.startswith(b'Comment'): + continue + lst = line.split(b' ', 1) + key = lst[0] + if first_line: + # AFM spec, Section 4: The StartFontMetrics keyword + # [followed by a version number] must be the first line in + # the file, and the EndFontMetrics keyword must be the + # last non-empty line in the file. We just check the + # first header entry. + if key != b'StartFontMetrics': + raise RuntimeError('Not an AFM file') + first_line = False + if len(lst) == 2: + val = lst[1] + else: + val = b'' + try: + converter = header_converters[key] + except KeyError: + _log.error('Found an unknown keyword in AFM header (was %r)' % key) + continue + try: + d[key] = converter(val) + except ValueError: + _log.error('Value error parsing header in AFM: %s, %s', key, val) + continue + if key == b'StartCharMetrics': + break + else: + raise RuntimeError('Bad parse') + return d + + +CharMetrics = namedtuple('CharMetrics', 'width, name, bbox') +CharMetrics.__doc__ = """ + Represents the character metrics of a single character. + + Notes + ----- + The fields do currently only describe a subset of character metrics + information defined in the AFM standard. + """ +CharMetrics.width.__doc__ = """The character width (WX).""" +CharMetrics.name.__doc__ = """The character name (N).""" +CharMetrics.bbox.__doc__ = """ + The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*).""" + + +def _parse_char_metrics(fh): + """ + Parse the given filehandle for character metrics information and return + the information as dicts. + + It is assumed that the file cursor is on the line behind + 'StartCharMetrics'. + + Returns + ------- + ascii_d : dict + A mapping "ASCII num of the character" to `.CharMetrics`. + name_d : dict + A mapping "character name" to `.CharMetrics`. + + Notes + ----- + This function is incomplete per the standard, but thus far parses + all the sample afm files tried. + """ + required_keys = {'C', 'WX', 'N', 'B'} + + ascii_d = {} + name_d = {} + for line in fh: + # We are defensively letting values be utf8. The spec requires + # ascii, but there are non-compliant fonts in circulation + line = _to_str(line.rstrip()) # Convert from byte-literal + if line.startswith('EndCharMetrics'): + return ascii_d, name_d + # Split the metric line into a dictionary, keyed by metric identifiers + vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s) + # There may be other metrics present, but only these are needed + if not required_keys.issubset(vals): + raise RuntimeError('Bad char metrics line: %s' % line) + num = _to_int(vals['C']) + wx = _to_float(vals['WX']) + name = vals['N'] + bbox = _to_list_of_floats(vals['B']) + bbox = list(map(int, bbox)) + metrics = CharMetrics(wx, name, bbox) + # Workaround: If the character name is 'Euro', give it the + # corresponding character code, according to WinAnsiEncoding (see PDF + # Reference). + if name == 'Euro': + num = 128 + elif name == 'minus': + num = ord("\N{MINUS SIGN}") # 0x2212 + if num != -1: + ascii_d[num] = metrics + name_d[name] = metrics + raise RuntimeError('Bad parse') + + +def _parse_kern_pairs(fh): + """ + Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and + values are the kern pair value. For example, a kern pairs line like + ``KPX A y -50`` + + will be represented as:: + + d[ ('A', 'y') ] = -50 + + """ + + line = next(fh) + if not line.startswith(b'StartKernPairs'): + raise RuntimeError('Bad start of kern pairs data: %s' % line) + + d = {} + for line in fh: + line = line.rstrip() + if not line: + continue + if line.startswith(b'EndKernPairs'): + next(fh) # EndKernData + return d + vals = line.split() + if len(vals) != 4 or vals[0] != b'KPX': + raise RuntimeError('Bad kern pairs line: %s' % line) + c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3]) + d[(c1, c2)] = val + raise RuntimeError('Bad kern pairs parse') + + +CompositePart = namedtuple('CompositePart', 'name, dx, dy') +CompositePart.__doc__ = """ + Represents the information on a composite element of a composite char.""" +CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'.""" +CompositePart.dx.__doc__ = """x-displacement of the part from the origin.""" +CompositePart.dy.__doc__ = """y-displacement of the part from the origin.""" + + +def _parse_composites(fh): + """ + Parse the given filehandle for composites information return them as a + dict. + + It is assumed that the file cursor is on the line behind 'StartComposites'. + + Returns + ------- + dict + A dict mapping composite character names to a parts list. The parts + list is a list of `.CompositePart` entries describing the parts of + the composite. + + Examples + -------- + A composite definition line:: + + CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ; + + will be represented as:: + + composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0), + CompositePart(name='acute', dx=160, dy=170)] + + """ + composites = {} + for line in fh: + line = line.rstrip() + if not line: + continue + if line.startswith(b'EndComposites'): + return composites + vals = line.split(b';') + cc = vals[0].split() + name, _num_parts = cc[1], _to_int(cc[2]) + pccParts = [] + for s in vals[1:-1]: + pcc = s.split() + part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3])) + pccParts.append(part) + composites[name] = pccParts + + raise RuntimeError('Bad composites parse') + + +def _parse_optional(fh): + """ + Parse the optional fields for kern pair data and composites. + + Returns + ------- + kern_data : dict + A dict containing kerning information. May be empty. + See `._parse_kern_pairs`. + composites : dict + A dict containing composite information. May be empty. + See `._parse_composites`. + """ + optional = { + b'StartKernData': _parse_kern_pairs, + b'StartComposites': _parse_composites, + } + + d = {b'StartKernData': {}, + b'StartComposites': {}} + for line in fh: + line = line.rstrip() + if not line: + continue + key = line.split()[0] + + if key in optional: + d[key] = optional[key](fh) + + return d[b'StartKernData'], d[b'StartComposites'] + + +class AFM: + + def __init__(self, fh): + """Parse the AFM file in file object *fh*.""" + self._header = _parse_header(fh) + self._metrics, self._metrics_by_name = _parse_char_metrics(fh) + self._kern, self._composite = _parse_optional(fh) + + def get_bbox_char(self, c, isord=False): + if not isord: + c = ord(c) + return self._metrics[c].bbox + + def string_width_height(self, s): + """ + Return the string width (including kerning) and string height + as a (*w*, *h*) tuple. + """ + if not len(s): + return 0, 0 + total_width = 0 + namelast = None + miny = 1e9 + maxy = 0 + for c in s: + if c == '\n': + continue + wx, name, bbox = self._metrics[ord(c)] + + total_width += wx + self._kern.get((namelast, name), 0) + l, b, w, h = bbox + miny = min(miny, b) + maxy = max(maxy, b + h) + + namelast = name + + return total_width, maxy - miny + + def get_str_bbox_and_descent(self, s): + """Return the string bounding box and the maximal descent.""" + if not len(s): + return 0, 0, 0, 0, 0 + total_width = 0 + namelast = None + miny = 1e9 + maxy = 0 + left = 0 + if not isinstance(s, str): + s = _to_str(s) + for c in s: + if c == '\n': + continue + name = uni2type1.get(ord(c), f"uni{ord(c):04X}") + try: + wx, _, bbox = self._metrics_by_name[name] + except KeyError: + name = 'question' + wx, _, bbox = self._metrics_by_name[name] + total_width += wx + self._kern.get((namelast, name), 0) + l, b, w, h = bbox + left = min(left, l) + miny = min(miny, b) + maxy = max(maxy, b + h) + + namelast = name + + return left, miny, total_width, maxy - miny, -miny + + def get_str_bbox(self, s): + """Return the string bounding box.""" + return self.get_str_bbox_and_descent(s)[:4] + + def get_name_char(self, c, isord=False): + """Get the name of the character, i.e., ';' is 'semicolon'.""" + if not isord: + c = ord(c) + return self._metrics[c].name + + def get_width_char(self, c, isord=False): + """ + Get the width of the character from the character metric WX field. + """ + if not isord: + c = ord(c) + return self._metrics[c].width + + def get_width_from_char_name(self, name): + """Get the width of the character from a type1 character name.""" + return self._metrics_by_name[name].width + + def get_height_char(self, c, isord=False): + """Get the bounding box (ink) height of character *c* (space is 0).""" + if not isord: + c = ord(c) + return self._metrics[c].bbox[-1] + + def get_kern_dist(self, c1, c2): + """ + Return the kerning pair distance (possibly 0) for chars *c1* and *c2*. + """ + name1, name2 = self.get_name_char(c1), self.get_name_char(c2) + return self.get_kern_dist_from_name(name1, name2) + + def get_kern_dist_from_name(self, name1, name2): + """ + Return the kerning pair distance (possibly 0) for chars + *name1* and *name2*. + """ + return self._kern.get((name1, name2), 0) + + def get_fontname(self): + """Return the font name, e.g., 'Times-Roman'.""" + return self._header[b'FontName'] + + @property + def postscript_name(self): # For consistency with FT2Font. + return self.get_fontname() + + def get_fullname(self): + """Return the font full name, e.g., 'Times-Roman'.""" + name = self._header.get(b'FullName') + if name is None: # use FontName as a substitute + name = self._header[b'FontName'] + return name + + def get_familyname(self): + """Return the font family name, e.g., 'Times'.""" + name = self._header.get(b'FamilyName') + if name is not None: + return name + + # FamilyName not specified so we'll make a guess + name = self.get_fullname() + extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|' + r'light|ultralight|extra|condensed))+$') + return re.sub(extras, '', name) + + @property + def family_name(self): + """The font family name, e.g., 'Times'.""" + return self.get_familyname() + + def get_weight(self): + """Return the font weight, e.g., 'Bold' or 'Roman'.""" + return self._header[b'Weight'] + + def get_angle(self): + """Return the fontangle as float.""" + return self._header[b'ItalicAngle'] + + def get_capheight(self): + """Return the cap height as float.""" + return self._header[b'CapHeight'] + + def get_xheight(self): + """Return the xheight as float.""" + return self._header[b'XHeight'] + + def get_underline_thickness(self): + """Return the underline thickness as float.""" + return self._header[b'UnderlineThickness'] + + def get_horizontal_stem_width(self): + """ + Return the standard horizontal stem width as float, or *None* if + not specified in AFM file. + """ + return self._header.get(b'StdHW', None) + + def get_vertical_stem_width(self): + """ + Return the standard vertical stem width as float, or *None* if + not specified in AFM file. + """ + return self._header.get(b'StdVW', None) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3e0ef09969243000be062b5beef08d56060c67f4 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py b/omnilmm/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ed155c2d62fe6f6bb8f3a4b7ae63056790dbed --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/_fontconfig_pattern.py @@ -0,0 +1,120 @@ +""" +A module for parsing and generating `fontconfig patterns`_. + +.. _fontconfig patterns: + https://www.freedesktop.org/software/fontconfig/fontconfig-user.html +""" + +# This class logically belongs in `matplotlib.font_manager`, but placing it +# there would have created cyclical dependency problems, because it also needs +# to be available from `matplotlib.rcsetup` (for parsing matplotlibrc files). + +from functools import lru_cache, partial +import re + +from pyparsing import ( + Group, Optional, ParseException, Regex, StringEnd, Suppress, ZeroOrMore) + +from matplotlib import _api + + +_family_punc = r'\\\-:,' +_family_unescape = partial(re.compile(r'\\(?=[%s])' % _family_punc).sub, '') +_family_escape = partial(re.compile(r'(?=[%s])' % _family_punc).sub, r'\\') +_value_punc = r'\\=_:,' +_value_unescape = partial(re.compile(r'\\(?=[%s])' % _value_punc).sub, '') +_value_escape = partial(re.compile(r'(?=[%s])' % _value_punc).sub, r'\\') + + +_CONSTANTS = { + 'thin': ('weight', 'light'), + 'extralight': ('weight', 'light'), + 'ultralight': ('weight', 'light'), + 'light': ('weight', 'light'), + 'book': ('weight', 'book'), + 'regular': ('weight', 'regular'), + 'normal': ('weight', 'normal'), + 'medium': ('weight', 'medium'), + 'demibold': ('weight', 'demibold'), + 'semibold': ('weight', 'semibold'), + 'bold': ('weight', 'bold'), + 'extrabold': ('weight', 'extra bold'), + 'black': ('weight', 'black'), + 'heavy': ('weight', 'heavy'), + 'roman': ('slant', 'normal'), + 'italic': ('slant', 'italic'), + 'oblique': ('slant', 'oblique'), + 'ultracondensed': ('width', 'ultra-condensed'), + 'extracondensed': ('width', 'extra-condensed'), + 'condensed': ('width', 'condensed'), + 'semicondensed': ('width', 'semi-condensed'), + 'expanded': ('width', 'expanded'), + 'extraexpanded': ('width', 'extra-expanded'), + 'ultraexpanded': ('width', 'ultra-expanded'), +} + + +@lru_cache # The parser instance is a singleton. +def _make_fontconfig_parser(): + def comma_separated(elem): + return elem + ZeroOrMore(Suppress(",") + elem) + + family = Regex(r"([^%s]|(\\[%s]))*" % (_family_punc, _family_punc)) + size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)") + name = Regex(r"[a-z]+") + value = Regex(r"([^%s]|(\\[%s]))*" % (_value_punc, _value_punc)) + # replace trailing `| name` by oneOf(_CONSTANTS) in mpl 3.9. + prop = Group((name + Suppress("=") + comma_separated(value)) | name) + return ( + Optional(comma_separated(family)("families")) + + Optional("-" + comma_separated(size)("sizes")) + + ZeroOrMore(":" + prop("properties*")) + + StringEnd() + ) + + +# `parse_fontconfig_pattern` is a bottleneck during the tests because it is +# repeatedly called when the rcParams are reset (to validate the default +# fonts). In practice, the cache size doesn't grow beyond a few dozen entries +# during the test suite. +@lru_cache +def parse_fontconfig_pattern(pattern): + """ + Parse a fontconfig *pattern* into a dict that can initialize a + `.font_manager.FontProperties` object. + """ + parser = _make_fontconfig_parser() + try: + parse = parser.parseString(pattern) + except ParseException as err: + # explain becomes a plain method on pyparsing 3 (err.explain(0)). + raise ValueError("\n" + ParseException.explain(err, 0)) from None + parser.resetCache() + props = {} + if "families" in parse: + props["family"] = [*map(_family_unescape, parse["families"])] + if "sizes" in parse: + props["size"] = [*parse["sizes"]] + for prop in parse.get("properties", []): + if len(prop) == 1: + if prop[0] not in _CONSTANTS: + _api.warn_deprecated( + "3.7", message=f"Support for unknown constants " + f"({prop[0]!r}) is deprecated since %(since)s and " + f"will be removed %(removal)s.") + continue + prop = _CONSTANTS[prop[0]] + k, *v = prop + props.setdefault(k, []).extend(map(_value_unescape, v)) + return props + + +def generate_fontconfig_pattern(d): + """Convert a `.FontProperties` to a fontconfig pattern string.""" + kvs = [(k, getattr(d, f"get_{k}")()) + for k in ["style", "variant", "weight", "stretch", "file", "size"]] + # Families is given first without a leading keyword. Other entries (which + # are necessarily scalar) are given as key=value, skipping Nones. + return (",".join(_family_escape(f) for f in d.get_family()) + + "".join(f":{k}={_value_escape(str(v))}" + for k, v in kvs if v is not None)) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/_internal_utils.py b/omnilmm/lib/python3.10/site-packages/matplotlib/_internal_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0223aa593bb2cb20b58f2b9e41bdc0dfa5ceed35 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/_internal_utils.py @@ -0,0 +1,64 @@ +""" +Internal debugging utilities, that are not expected to be used in the rest of +the codebase. + +WARNING: Code in this module may change without prior notice! +""" + +from io import StringIO +from pathlib import Path +import subprocess + +from matplotlib.transforms import TransformNode + + +def graphviz_dump_transform(transform, dest, *, highlight=None): + """ + Generate a graphical representation of the transform tree for *transform* + using the :program:`dot` program (which this function depends on). The + output format (png, dot, etc.) is determined from the suffix of *dest*. + + Parameters + ---------- + transform : `~matplotlib.transform.Transform` + The represented transform. + dest : str + Output filename. The extension must be one of the formats supported + by :program:`dot`, e.g. png, svg, dot, ... + (see https://www.graphviz.org/doc/info/output.html). + highlight : list of `~matplotlib.transform.Transform` or None + The transforms in the tree to be drawn in bold. + If *None*, *transform* is highlighted. + """ + + if highlight is None: + highlight = [transform] + seen = set() + + def recurse(root, buf): + if id(root) in seen: + return + seen.add(id(root)) + props = {} + label = type(root).__name__ + if root._invalid: + label = f'[{label}]' + if root in highlight: + props['style'] = 'bold' + props['shape'] = 'box' + props['label'] = '"%s"' % label + props = ' '.join(map('{0[0]}={0[1]}'.format, props.items())) + buf.write(f'{id(root)} [{props}];\n') + for key, val in vars(root).items(): + if isinstance(val, TransformNode) and id(root) in val._parents: + buf.write(f'"{id(root)}" -> "{id(val)}" ' + f'[label="{key}", fontsize=10];\n') + recurse(val, buf) + + buf = StringIO() + buf.write('digraph G {\n') + recurse(transform, buf) + buf.write('}\n') + subprocess.run( + ['dot', '-T', Path(dest).suffix[1:], '-o', dest], + input=buf.getvalue().encode('utf-8'), check=True) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/_layoutgrid.py b/omnilmm/lib/python3.10/site-packages/matplotlib/_layoutgrid.py new file mode 100644 index 0000000000000000000000000000000000000000..8bef9283112c249a716807f162a1be89ed13a3e8 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/_layoutgrid.py @@ -0,0 +1,547 @@ +""" +A layoutgrid is a nrows by ncols set of boxes, meant to be used by +`._constrained_layout`, each box is analogous to a subplotspec element of +a gridspec. + +Each box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows], +and by two editable margins for each side. The main margin gets its value +set by the size of ticklabels, titles, etc on each axes that is in the figure. +The outer margin is the padding around the axes, and space for any +colorbars. + +The "inner" widths and heights of these boxes are then constrained to be the +same (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`). + +The layoutgrid is then constrained to be contained within a parent layoutgrid, +its column(s) and row(s) specified when it is created. +""" + +import itertools +import kiwisolver as kiwi +import logging +import numpy as np + +import matplotlib as mpl +import matplotlib.patches as mpatches +from matplotlib.transforms import Bbox + +_log = logging.getLogger(__name__) + + +class LayoutGrid: + """ + Analogous to a gridspec, and contained in another LayoutGrid. + """ + + def __init__(self, parent=None, parent_pos=(0, 0), + parent_inner=False, name='', ncols=1, nrows=1, + h_pad=None, w_pad=None, width_ratios=None, + height_ratios=None): + Variable = kiwi.Variable + self.parent_pos = parent_pos + self.parent_inner = parent_inner + self.name = name + seq_id() + if isinstance(parent, LayoutGrid): + self.name = f'{parent.name}.{self.name}' + self.nrows = nrows + self.ncols = ncols + self.height_ratios = np.atleast_1d(height_ratios) + if height_ratios is None: + self.height_ratios = np.ones(nrows) + self.width_ratios = np.atleast_1d(width_ratios) + if width_ratios is None: + self.width_ratios = np.ones(ncols) + + sn = self.name + '_' + if not isinstance(parent, LayoutGrid): + # parent can be a rect if not a LayoutGrid + # allows specifying a rectangle to contain the layout. + self.solver = kiwi.Solver() + else: + parent.add_child(self, *parent_pos) + self.solver = parent.solver + # keep track of artist associated w/ this layout. Can be none + self.artists = np.empty((nrows, ncols), dtype=object) + self.children = np.empty((nrows, ncols), dtype=object) + + self.margins = {} + self.margin_vals = {} + # all the boxes in each column share the same left/right margins: + for todo in ['left', 'right', 'leftcb', 'rightcb']: + # track the value so we can change only if a margin is larger + # than the current value + self.margin_vals[todo] = np.zeros(ncols) + + sol = self.solver + + self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)] + self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)] + for todo in ['left', 'right', 'leftcb', 'rightcb']: + self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]') + for i in range(ncols)] + for i in range(ncols): + sol.addEditVariable(self.margins[todo][i], 'strong') + + for todo in ['bottom', 'top', 'bottomcb', 'topcb']: + self.margins[todo] = np.empty((nrows), dtype=object) + self.margin_vals[todo] = np.zeros(nrows) + + self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)] + self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)] + for todo in ['bottom', 'top', 'bottomcb', 'topcb']: + self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]') + for i in range(nrows)] + for i in range(nrows): + sol.addEditVariable(self.margins[todo][i], 'strong') + + # set these margins to zero by default. They will be edited as + # children are filled. + self.reset_margins() + self.add_constraints(parent) + + self.h_pad = h_pad + self.w_pad = w_pad + + def __repr__(self): + str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n' + for i in range(self.nrows): + for j in range(self.ncols): + str += f'{i}, {j}: '\ + f'L{self.lefts[j].value():1.3f}, ' \ + f'B{self.bottoms[i].value():1.3f}, ' \ + f'R{self.rights[j].value():1.3f}, ' \ + f'T{self.tops[i].value():1.3f}, ' \ + f'ML{self.margins["left"][j].value():1.3f}, ' \ + f'MR{self.margins["right"][j].value():1.3f}, ' \ + f'MB{self.margins["bottom"][i].value():1.3f}, ' \ + f'MT{self.margins["top"][i].value():1.3f}, \n' + return str + + def reset_margins(self): + """ + Reset all the margins to zero. Must do this after changing + figure size, for instance, because the relative size of the + axes labels etc changes. + """ + for todo in ['left', 'right', 'bottom', 'top', + 'leftcb', 'rightcb', 'bottomcb', 'topcb']: + self.edit_margins(todo, 0.0) + + def add_constraints(self, parent): + # define self-consistent constraints + self.hard_constraints() + # define relationship with parent layoutgrid: + self.parent_constraints(parent) + # define relative widths of the grid cells to each other + # and stack horizontally and vertically. + self.grid_constraints() + + def hard_constraints(self): + """ + These are the redundant constraints, plus ones that make the + rest of the code easier. + """ + for i in range(self.ncols): + hc = [self.rights[i] >= self.lefts[i], + (self.rights[i] - self.margins['right'][i] - + self.margins['rightcb'][i] >= + self.lefts[i] - self.margins['left'][i] - + self.margins['leftcb'][i]) + ] + for c in hc: + self.solver.addConstraint(c | 'required') + + for i in range(self.nrows): + hc = [self.tops[i] >= self.bottoms[i], + (self.tops[i] - self.margins['top'][i] - + self.margins['topcb'][i] >= + self.bottoms[i] - self.margins['bottom'][i] - + self.margins['bottomcb'][i]) + ] + for c in hc: + self.solver.addConstraint(c | 'required') + + def add_child(self, child, i=0, j=0): + # np.ix_ returns the cross product of i and j indices + self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child + + def parent_constraints(self, parent): + # constraints that are due to the parent... + # i.e. the first column's left is equal to the + # parent's left, the last column right equal to the + # parent's right... + if not isinstance(parent, LayoutGrid): + # specify a rectangle in figure coordinates + hc = [self.lefts[0] == parent[0], + self.rights[-1] == parent[0] + parent[2], + # top and bottom reversed order... + self.tops[0] == parent[1] + parent[3], + self.bottoms[-1] == parent[1]] + else: + rows, cols = self.parent_pos + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + left = parent.lefts[cols[0]] + right = parent.rights[cols[-1]] + top = parent.tops[rows[0]] + bottom = parent.bottoms[rows[-1]] + if self.parent_inner: + # the layout grid is contained inside the inner + # grid of the parent. + left += parent.margins['left'][cols[0]] + left += parent.margins['leftcb'][cols[0]] + right -= parent.margins['right'][cols[-1]] + right -= parent.margins['rightcb'][cols[-1]] + top -= parent.margins['top'][rows[0]] + top -= parent.margins['topcb'][rows[0]] + bottom += parent.margins['bottom'][rows[-1]] + bottom += parent.margins['bottomcb'][rows[-1]] + hc = [self.lefts[0] == left, + self.rights[-1] == right, + # from top to bottom + self.tops[0] == top, + self.bottoms[-1] == bottom] + for c in hc: + self.solver.addConstraint(c | 'required') + + def grid_constraints(self): + # constrain the ratio of the inner part of the grids + # to be the same (relative to width_ratios) + + # constrain widths: + w = (self.rights[0] - self.margins['right'][0] - + self.margins['rightcb'][0]) + w = (w - self.lefts[0] - self.margins['left'][0] - + self.margins['leftcb'][0]) + w0 = w / self.width_ratios[0] + # from left to right + for i in range(1, self.ncols): + w = (self.rights[i] - self.margins['right'][i] - + self.margins['rightcb'][i]) + w = (w - self.lefts[i] - self.margins['left'][i] - + self.margins['leftcb'][i]) + c = (w == w0 * self.width_ratios[i]) + self.solver.addConstraint(c | 'strong') + # constrain the grid cells to be directly next to each other. + c = (self.rights[i - 1] == self.lefts[i]) + self.solver.addConstraint(c | 'strong') + + # constrain heights: + h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0] + h = (h - self.bottoms[0] - self.margins['bottom'][0] - + self.margins['bottomcb'][0]) + h0 = h / self.height_ratios[0] + # from top to bottom: + for i in range(1, self.nrows): + h = (self.tops[i] - self.margins['top'][i] - + self.margins['topcb'][i]) + h = (h - self.bottoms[i] - self.margins['bottom'][i] - + self.margins['bottomcb'][i]) + c = (h == h0 * self.height_ratios[i]) + self.solver.addConstraint(c | 'strong') + # constrain the grid cells to be directly above each other. + c = (self.bottoms[i - 1] == self.tops[i]) + self.solver.addConstraint(c | 'strong') + + # Margin editing: The margins are variable and meant to + # contain things of a fixed size like axes labels, tick labels, titles + # etc + def edit_margin(self, todo, size, cell): + """ + Change the size of the margin for one cell. + + Parameters + ---------- + todo : string (one of 'left', 'right', 'bottom', 'top') + margin to alter. + + size : float + Size of the margin. If it is larger than the existing minimum it + updates the margin size. Fraction of figure size. + + cell : int + Cell column or row to edit. + """ + self.solver.suggestValue(self.margins[todo][cell], size) + self.margin_vals[todo][cell] = size + + def edit_margin_min(self, todo, size, cell=0): + """ + Change the minimum size of the margin for one cell. + + Parameters + ---------- + todo : string (one of 'left', 'right', 'bottom', 'top') + margin to alter. + + size : float + Minimum size of the margin . If it is larger than the + existing minimum it updates the margin size. Fraction of + figure size. + + cell : int + Cell column or row to edit. + """ + + if size > self.margin_vals[todo][cell]: + self.edit_margin(todo, size, cell) + + def edit_margins(self, todo, size): + """ + Change the size of all the margin of all the cells in the layout grid. + + Parameters + ---------- + todo : string (one of 'left', 'right', 'bottom', 'top') + margin to alter. + + size : float + Size to set the margins. Fraction of figure size. + """ + + for i in range(len(self.margin_vals[todo])): + self.edit_margin(todo, size, i) + + def edit_all_margins_min(self, todo, size): + """ + Change the minimum size of all the margin of all + the cells in the layout grid. + + Parameters + ---------- + todo : {'left', 'right', 'bottom', 'top'} + The margin to alter. + + size : float + Minimum size of the margin. If it is larger than the + existing minimum it updates the margin size. Fraction of + figure size. + """ + + for i in range(len(self.margin_vals[todo])): + self.edit_margin_min(todo, size, i) + + def edit_outer_margin_mins(self, margin, ss): + """ + Edit all four margin minimums in one statement. + + Parameters + ---------- + margin : dict + size of margins in a dict with keys 'left', 'right', 'bottom', + 'top' + + ss : SubplotSpec + defines the subplotspec these margins should be applied to + """ + + self.edit_margin_min('left', margin['left'], ss.colspan.start) + self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start) + self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1) + self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1) + # rows are from the top down: + self.edit_margin_min('top', margin['top'], ss.rowspan.start) + self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start) + self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1) + self.edit_margin_min('bottomcb', margin['bottomcb'], + ss.rowspan.stop - 1) + + def get_margins(self, todo, col): + """Return the margin at this position""" + return self.margin_vals[todo][col] + + def get_outer_bbox(self, rows=0, cols=0): + """ + Return the outer bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + self.lefts[cols[0]].value(), + self.bottoms[rows[-1]].value(), + self.rights[cols[-1]].value(), + self.tops[rows[0]].value()) + return bbox + + def get_inner_bbox(self, rows=0, cols=0): + """ + Return the inner bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value() + + self.margins['left'][cols[0]].value() + + self.margins['leftcb'][cols[0]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottom'][rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value()), + (self.rights[cols[-1]].value() - + self.margins['right'][cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.tops[rows[0]].value() - + self.margins['top'][rows[0]].value() - + self.margins['topcb'][rows[0]].value()) + ) + return bbox + + def get_bbox_for_cb(self, rows=0, cols=0): + """ + Return the bounding box that includes the + decorations but, *not* the colorbar... + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value() + + self.margins['leftcb'][cols[0]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value()), + (self.rights[cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.tops[rows[0]].value() - + self.margins['topcb'][rows[0]].value()) + ) + return bbox + + def get_left_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value() + + self.margins['leftcb'][cols[0]].value()), + (self.bottoms[rows[-1]].value()), + (self.lefts[cols[0]].value() + + self.margins['leftcb'][cols[0]].value() + + self.margins['left'][cols[0]].value()), + (self.tops[rows[0]].value())) + return bbox + + def get_bottom_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value()), + (self.rights[cols[-1]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottom'][rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value() + )) + return bbox + + def get_right_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.rights[cols[-1]].value() - + self.margins['right'][cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.bottoms[rows[-1]].value()), + (self.rights[cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.tops[rows[0]].value())) + return bbox + + def get_top_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value()), + (self.tops[rows[0]].value() - + self.margins['topcb'][rows[0]].value()), + (self.rights[cols[-1]].value()), + (self.tops[rows[0]].value() - + self.margins['topcb'][rows[0]].value() - + self.margins['top'][rows[0]].value())) + return bbox + + def update_variables(self): + """ + Update the variables for the solver attached to this layoutgrid. + """ + self.solver.updateVariables() + +_layoutboxobjnum = itertools.count() + + +def seq_id(): + """Generate a short sequential id for layoutbox objects.""" + return '%06d' % next(_layoutboxobjnum) + + +def plot_children(fig, lg=None, level=0): + """Simple plotting to show where boxes are.""" + if lg is None: + _layoutgrids = fig.get_layout_engine().execute(fig) + lg = _layoutgrids[fig] + colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"] + col = colors[level] + for i in range(lg.nrows): + for j in range(lg.ncols): + bb = lg.get_outer_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1, + edgecolor='0.7', facecolor='0.7', + alpha=0.2, transform=fig.transFigure, + zorder=-3)) + bbi = lg.get_inner_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2, + edgecolor=col, facecolor='none', + transform=fig.transFigure, zorder=-2)) + + bbi = lg.get_left_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.5, 0.7, 0.5], + transform=fig.transFigure, zorder=-2)) + bbi = lg.get_right_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.7, 0.5, 0.5], + transform=fig.transFigure, zorder=-2)) + bbi = lg.get_bottom_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.5, 0.5, 0.7], + transform=fig.transFigure, zorder=-2)) + bbi = lg.get_top_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.7, 0.2, 0.7], + transform=fig.transFigure, zorder=-2)) + for ch in lg.children.flat: + if ch is not None: + plot_children(fig, ch, level=level+1) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/_text_helpers.py b/omnilmm/lib/python3.10/site-packages/matplotlib/_text_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..18bfb550c90bd86fc6c79dbdd7bb0602dc040993 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/_text_helpers.py @@ -0,0 +1,74 @@ +""" +Low-level text helper utilities. +""" + +import dataclasses + +from . import _api +from .ft2font import KERNING_DEFAULT, LOAD_NO_HINTING + + +LayoutItem = dataclasses.make_dataclass( + "LayoutItem", ["ft_object", "char", "glyph_idx", "x", "prev_kern"]) + + +def warn_on_missing_glyph(codepoint): + _api.warn_external( + "Glyph {} ({}) missing from current font.".format( + codepoint, + chr(codepoint).encode("ascii", "namereplace").decode("ascii"))) + block = ("Hebrew" if 0x0590 <= codepoint <= 0x05ff else + "Arabic" if 0x0600 <= codepoint <= 0x06ff else + "Devanagari" if 0x0900 <= codepoint <= 0x097f else + "Bengali" if 0x0980 <= codepoint <= 0x09ff else + "Gurmukhi" if 0x0a00 <= codepoint <= 0x0a7f else + "Gujarati" if 0x0a80 <= codepoint <= 0x0aff else + "Oriya" if 0x0b00 <= codepoint <= 0x0b7f else + "Tamil" if 0x0b80 <= codepoint <= 0x0bff else + "Telugu" if 0x0c00 <= codepoint <= 0x0c7f else + "Kannada" if 0x0c80 <= codepoint <= 0x0cff else + "Malayalam" if 0x0d00 <= codepoint <= 0x0d7f else + "Sinhala" if 0x0d80 <= codepoint <= 0x0dff else + None) + if block: + _api.warn_external( + f"Matplotlib currently does not support {block} natively.") + + +def layout(string, font, *, kern_mode=KERNING_DEFAULT): + """ + Render *string* with *font*. For each character in *string*, yield a + (glyph-index, x-position) pair. When such a pair is yielded, the font's + glyph is set to the corresponding character. + + Parameters + ---------- + string : str + The string to be rendered. + font : FT2Font + The font. + kern_mode : int + A FreeType kerning mode. + + Yields + ------ + glyph_index : int + x_position : float + """ + x = 0 + prev_glyph_idx = None + char_to_font = font._get_fontmap(string) + base_font = font + for char in string: + # This has done the fallback logic + font = char_to_font.get(char, base_font) + glyph_idx = font.get_char_index(ord(char)) + kern = ( + base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64 + if prev_glyph_idx is not None else 0. + ) + x += kern + glyph = font.load_glyph(glyph_idx, flags=LOAD_NO_HINTING) + yield LayoutItem(font, char, glyph_idx, x, kern) + x += glyph.linearHoriAdvance / 65536 + prev_glyph_idx = glyph_idx diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/_tight_bbox.py b/omnilmm/lib/python3.10/site-packages/matplotlib/_tight_bbox.py new file mode 100644 index 0000000000000000000000000000000000000000..db72bbdff020680dfd833229cac41e9b33e428ee --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/_tight_bbox.py @@ -0,0 +1,84 @@ +""" +Helper module for the *bbox_inches* parameter in `.Figure.savefig`. +""" + +from matplotlib.transforms import Bbox, TransformedBbox, Affine2D + + +def adjust_bbox(fig, bbox_inches, fixed_dpi=None): + """ + Temporarily adjust the figure so that only the specified area + (bbox_inches) is saved. + + It modifies fig.bbox, fig.bbox_inches, + fig.transFigure._boxout, and fig.patch. While the figure size + changes, the scale of the original figure is conserved. A + function which restores the original values are returned. + """ + origBbox = fig.bbox + origBboxInches = fig.bbox_inches + _boxout = fig.transFigure._boxout + + old_aspect = [] + locator_list = [] + sentinel = object() + for ax in fig.axes: + locator = ax.get_axes_locator() + if locator is not None: + ax.apply_aspect(locator(ax, None)) + locator_list.append(locator) + current_pos = ax.get_position(original=False).frozen() + ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos) + # override the method that enforces the aspect ratio on the Axes + if 'apply_aspect' in ax.__dict__: + old_aspect.append(ax.apply_aspect) + else: + old_aspect.append(sentinel) + ax.apply_aspect = lambda pos=None: None + + def restore_bbox(): + for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect): + ax.set_axes_locator(loc) + if aspect is sentinel: + # delete our no-op function which un-hides the original method + del ax.apply_aspect + else: + ax.apply_aspect = aspect + + fig.bbox = origBbox + fig.bbox_inches = origBboxInches + fig.transFigure._boxout = _boxout + fig.transFigure.invalidate() + fig.patch.set_bounds(0, 0, 1, 1) + + if fixed_dpi is None: + fixed_dpi = fig.dpi + tr = Affine2D().scale(fixed_dpi) + dpi_scale = fixed_dpi / fig.dpi + + fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size) + x0, y0 = tr.transform(bbox_inches.p0) + w1, h1 = fig.bbox.size * dpi_scale + fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) + fig.transFigure.invalidate() + + fig.bbox = TransformedBbox(fig.bbox_inches, tr) + + fig.patch.set_bounds(x0 / w1, y0 / h1, + fig.bbox.width / w1, fig.bbox.height / h1) + + return restore_bbox + + +def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): + """ + A function that needs to be called when figure dpi changes during the + drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with + the new dpi. + """ + + bbox_inches, restore_bbox = bbox_inches_restore + restore_bbox() + r = adjust_bbox(fig, bbox_inches, fixed_dpi) + + return bbox_inches, r diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/animation.py b/omnilmm/lib/python3.10/site-packages/matplotlib/animation.py new file mode 100644 index 0000000000000000000000000000000000000000..2d8156a51599bdf766541365b0da38657dd95bd4 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/animation.py @@ -0,0 +1,1790 @@ +# TODO: +# * Documentation -- this will need a new section of the User's Guide. +# Both for Animations and just timers. +# - Also need to update +# https://scipy-cookbook.readthedocs.io/items/Matplotlib_Animations.html +# * Blit +# * Currently broken with Qt4 for widgets that don't start on screen +# * Still a few edge cases that aren't working correctly +# * Can this integrate better with existing matplotlib animation artist flag? +# - If animated removes from default draw(), perhaps we could use this to +# simplify initial draw. +# * Example +# * Frameless animation - pure procedural with no loop +# * Need example that uses something like inotify or subprocess +# * Complex syncing examples +# * Movies +# * Can blit be enabled for movies? +# * Need to consider event sources to allow clicking through multiple figures + + +import abc +import base64 +import contextlib +from io import BytesIO, TextIOWrapper +import itertools +import logging +from pathlib import Path +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory +import uuid +import warnings + +import numpy as np +from PIL import Image + +import matplotlib as mpl +from matplotlib._animation_data import ( + DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE) +from matplotlib import _api, cbook +import matplotlib.colors as mcolors + +_log = logging.getLogger(__name__) + +# Process creation flag for subprocess to prevent it raising a terminal +# window. See for example https://stackoverflow.com/q/24130623/ +subprocess_creation_flags = ( + subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0) + +# Other potential writing methods: +# * http://pymedia.org/ +# * libming (produces swf) python wrappers: https://github.com/libming/libming +# * Wrap x264 API: + +# (https://stackoverflow.com/q/2940671/) + + +def adjusted_figsize(w, h, dpi, n): + """ + Compute figure size so that pixels are a multiple of n. + + Parameters + ---------- + w, h : float + Size in inches. + + dpi : float + The dpi. + + n : int + The target multiple. + + Returns + ------- + wnew, hnew : float + The new figure size in inches. + """ + + # this maybe simplified if / when we adopt consistent rounding for + # pixel size across the whole library + def correct_roundoff(x, dpi, n): + if int(x*dpi) % n != 0: + if int(np.nextafter(x, np.inf)*dpi) % n == 0: + x = np.nextafter(x, np.inf) + elif int(np.nextafter(x, -np.inf)*dpi) % n == 0: + x = np.nextafter(x, -np.inf) + return x + + wnew = int(w * dpi / n) * n / dpi + hnew = int(h * dpi / n) * n / dpi + return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n) + + +class MovieWriterRegistry: + """Registry of available writer classes by human readable name.""" + + def __init__(self): + self._registered = dict() + + def register(self, name): + """ + Decorator for registering a class under a name. + + Example use:: + + @registry.register(name) + class Foo: + pass + """ + def wrapper(writer_cls): + self._registered[name] = writer_cls + return writer_cls + return wrapper + + def is_available(self, name): + """ + Check if given writer is available by name. + + Parameters + ---------- + name : str + + Returns + ------- + bool + """ + try: + cls = self._registered[name] + except KeyError: + return False + return cls.isAvailable() + + def __iter__(self): + """Iterate over names of available writer class.""" + for name in self._registered: + if self.is_available(name): + yield name + + def list(self): + """Get a list of available MovieWriters.""" + return [*self] + + def __getitem__(self, name): + """Get an available writer class from its name.""" + if self.is_available(name): + return self._registered[name] + raise RuntimeError(f"Requested MovieWriter ({name}) not available") + + +writers = MovieWriterRegistry() + + +class AbstractMovieWriter(abc.ABC): + """ + Abstract base class for writing movies, providing a way to grab frames by + calling `~AbstractMovieWriter.grab_frame`. + + `setup` is called to start the process and `finish` is called afterwards. + `saving` is provided as a context manager to facilitate this process as :: + + with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100): + # Iterate over frames + moviewriter.grab_frame(**savefig_kwargs) + + The use of the context manager ensures that `setup` and `finish` are + performed as necessary. + + An instance of a concrete subclass of this class can be given as the + ``writer`` argument of `Animation.save()`. + """ + + def __init__(self, fps=5, metadata=None, codec=None, bitrate=None): + self.fps = fps + self.metadata = metadata if metadata is not None else {} + self.codec = ( + mpl.rcParams['animation.codec'] if codec is None else codec) + self.bitrate = ( + mpl.rcParams['animation.bitrate'] if bitrate is None else bitrate) + + @abc.abstractmethod + def setup(self, fig, outfile, dpi=None): + """ + Setup for writing the movie file. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The figure object that contains the information for frames. + outfile : str + The filename of the resulting movie file. + dpi : float, default: ``fig.dpi`` + The DPI (or resolution) for the file. This controls the size + in pixels of the resulting movie file. + """ + # Check that path is valid + Path(outfile).parent.resolve(strict=True) + self.outfile = outfile + self.fig = fig + if dpi is None: + dpi = self.fig.dpi + self.dpi = dpi + + @property + def frame_size(self): + """A tuple ``(width, height)`` in pixels of a movie frame.""" + w, h = self.fig.get_size_inches() + return int(w * self.dpi), int(h * self.dpi) + + @abc.abstractmethod + def grab_frame(self, **savefig_kwargs): + """ + Grab the image information from the figure and save as a movie frame. + + All keyword arguments in *savefig_kwargs* are passed on to the + `~.Figure.savefig` call that saves the figure. + """ + + @abc.abstractmethod + def finish(self): + """Finish any processing for writing the movie.""" + + @contextlib.contextmanager + def saving(self, fig, outfile, dpi, *args, **kwargs): + """ + Context manager to facilitate writing the movie file. + + ``*args, **kw`` are any parameters that should be passed to `setup`. + """ + # This particular sequence is what contextlib.contextmanager wants + self.setup(fig, outfile, dpi, *args, **kwargs) + try: + yield self + finally: + self.finish() + + +class MovieWriter(AbstractMovieWriter): + """ + Base class for writing movies. + + This is a base class for MovieWriter subclasses that write a movie frame + data to a pipe. You cannot instantiate this class directly. + See examples for how to use its subclasses. + + Attributes + ---------- + frame_format : str + The format used in writing frame data, defaults to 'rgba'. + fig : `~matplotlib.figure.Figure` + The figure to capture data from. + This must be provided by the subclasses. + """ + + # Builtin writer subclasses additionally define the _exec_key and _args_key + # attributes, which indicate the rcParams entries where the path to the + # executable and additional command-line arguments to the executable are + # stored. Third-party writers cannot meaningfully set these as they cannot + # extend rcParams with new keys. + + # Pipe-based writers only support RGBA, but file-based ones support more + # formats. + supported_formats = ["rgba"] + + def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None, + metadata=None): + """ + Parameters + ---------- + fps : int, default: 5 + Movie frame rate (per second). + codec : str or None, default: :rc:`animation.codec` + The codec to use. + bitrate : int, default: :rc:`animation.bitrate` + The bitrate of the movie, in kilobits per second. Higher values + means higher quality movies, but increase the file size. A value + of -1 lets the underlying movie encoder select the bitrate. + extra_args : list of str or None, optional + Extra command-line arguments passed to the underlying movie + encoder. The default, None, means to use + :rc:`animation.[name-of-encoder]_args` for the builtin writers. + metadata : dict[str, str], default: {} + A dictionary of keys and values for metadata to include in the + output file. Some keys that may be of use include: + title, artist, genre, subject, copyright, srcform, comment. + """ + if type(self) is MovieWriter: + # TODO MovieWriter is still an abstract class and needs to be + # extended with a mixin. This should be clearer in naming + # and description. For now, just give a reasonable error + # message to users. + raise TypeError( + 'MovieWriter cannot be instantiated directly. Please use one ' + 'of its subclasses.') + + super().__init__(fps=fps, metadata=metadata, codec=codec, + bitrate=bitrate) + self.frame_format = self.supported_formats[0] + self.extra_args = extra_args + + def _adjust_frame_size(self): + if self.codec == 'h264': + wo, ho = self.fig.get_size_inches() + w, h = adjusted_figsize(wo, ho, self.dpi, 2) + if (wo, ho) != (w, h): + self.fig.set_size_inches(w, h, forward=True) + _log.info('figure size in inches has been adjusted ' + 'from %s x %s to %s x %s', wo, ho, w, h) + else: + w, h = self.fig.get_size_inches() + _log.debug('frame size in pixels is %s x %s', *self.frame_size) + return w, h + + def setup(self, fig, outfile, dpi=None): + # docstring inherited + super().setup(fig, outfile, dpi=dpi) + self._w, self._h = self._adjust_frame_size() + # Run here so that grab_frame() can write the data to a pipe. This + # eliminates the need for temp files. + self._run() + + def _run(self): + # Uses subprocess to call the program for assembling frames into a + # movie file. *args* returns the sequence of command line arguments + # from a few configuration options. + command = self._args() + _log.info('MovieWriter._run: running command: %s', + cbook._pformat_subprocess(command)) + PIPE = subprocess.PIPE + self._proc = subprocess.Popen( + command, stdin=PIPE, stdout=PIPE, stderr=PIPE, + creationflags=subprocess_creation_flags) + + def finish(self): + """Finish any processing for writing the movie.""" + out, err = self._proc.communicate() + # Use the encoding/errors that universal_newlines would use. + out = TextIOWrapper(BytesIO(out)).read() + err = TextIOWrapper(BytesIO(err)).read() + if out: + _log.log( + logging.WARNING if self._proc.returncode else logging.DEBUG, + "MovieWriter stdout:\n%s", out) + if err: + _log.log( + logging.WARNING if self._proc.returncode else logging.DEBUG, + "MovieWriter stderr:\n%s", err) + if self._proc.returncode: + raise subprocess.CalledProcessError( + self._proc.returncode, self._proc.args, out, err) + + def grab_frame(self, **savefig_kwargs): + # docstring inherited + _log.debug('MovieWriter.grab_frame: Grabbing frame.') + # Readjust the figure size in case it has been changed by the user. + # All frames must have the same size to save the movie correctly. + self.fig.set_size_inches(self._w, self._h) + # Save the figure data to the sink, using the frame format and dpi. + self.fig.savefig(self._proc.stdin, format=self.frame_format, + dpi=self.dpi, **savefig_kwargs) + + def _args(self): + """Assemble list of encoder-specific command-line arguments.""" + return NotImplementedError("args needs to be implemented by subclass.") + + @classmethod + def bin_path(cls): + """ + Return the binary path to the commandline tool used by a specific + subclass. This is a class method so that the tool can be looked for + before making a particular MovieWriter subclass available. + """ + return str(mpl.rcParams[cls._exec_key]) + + @classmethod + def isAvailable(cls): + """Return whether a MovieWriter subclass is actually available.""" + return shutil.which(cls.bin_path()) is not None + + +class FileMovieWriter(MovieWriter): + """ + `MovieWriter` for writing to individual files and stitching at the end. + + This must be sub-classed to be useful. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.frame_format = mpl.rcParams['animation.frame_format'] + + def setup(self, fig, outfile, dpi=None, frame_prefix=None): + """ + Setup for writing the movie file. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The figure to grab the rendered frames from. + outfile : str + The filename of the resulting movie file. + dpi : float, default: ``fig.dpi`` + The dpi of the output file. This, with the figure size, + controls the size in pixels of the resulting movie file. + frame_prefix : str, optional + The filename prefix to use for temporary files. If *None* (the + default), files are written to a temporary directory which is + deleted by `finish`; if not *None*, no temporary files are + deleted. + """ + # Check that path is valid + Path(outfile).parent.resolve(strict=True) + self.fig = fig + self.outfile = outfile + if dpi is None: + dpi = self.fig.dpi + self.dpi = dpi + self._adjust_frame_size() + + if frame_prefix is None: + self._tmpdir = TemporaryDirectory() + self.temp_prefix = str(Path(self._tmpdir.name, 'tmp')) + else: + self._tmpdir = None + self.temp_prefix = frame_prefix + self._frame_counter = 0 # used for generating sequential file names + self._temp_paths = list() + self.fname_format_str = '%s%%07d.%s' + + def __del__(self): + if hasattr(self, '_tmpdir') and self._tmpdir: + self._tmpdir.cleanup() + + @property + def frame_format(self): + """ + Format (png, jpeg, etc.) to use for saving the frames, which can be + decided by the individual subclasses. + """ + return self._frame_format + + @frame_format.setter + def frame_format(self, frame_format): + if frame_format in self.supported_formats: + self._frame_format = frame_format + else: + _api.warn_external( + f"Ignoring file format {frame_format!r} which is not " + f"supported by {type(self).__name__}; using " + f"{self.supported_formats[0]} instead.") + self._frame_format = self.supported_formats[0] + + def _base_temp_name(self): + # Generates a template name (without number) given the frame format + # for extension and the prefix. + return self.fname_format_str % (self.temp_prefix, self.frame_format) + + def grab_frame(self, **savefig_kwargs): + # docstring inherited + # Creates a filename for saving using basename and counter. + path = Path(self._base_temp_name() % self._frame_counter) + self._temp_paths.append(path) # Record the filename for later use. + self._frame_counter += 1 # Ensures each created name is unique. + _log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s', + self._frame_counter, path) + with open(path, 'wb') as sink: # Save figure to the sink. + self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi, + **savefig_kwargs) + + def finish(self): + # Call run here now that all frame grabbing is done. All temp files + # are available to be assembled. + try: + self._run() + super().finish() + finally: + if self._tmpdir: + _log.debug( + 'MovieWriter: clearing temporary path=%s', self._tmpdir + ) + self._tmpdir.cleanup() + + +@writers.register('pillow') +class PillowWriter(AbstractMovieWriter): + @classmethod + def isAvailable(cls): + return True + + def setup(self, fig, outfile, dpi=None): + super().setup(fig, outfile, dpi=dpi) + self._frames = [] + + def grab_frame(self, **savefig_kwargs): + buf = BytesIO() + self.fig.savefig( + buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi}) + self._frames.append(Image.frombuffer( + "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)) + + def finish(self): + self._frames[0].save( + self.outfile, save_all=True, append_images=self._frames[1:], + duration=int(1000 / self.fps), loop=0) + + +# Base class of ffmpeg information. Has the config keys and the common set +# of arguments that controls the *output* side of things. +class FFMpegBase: + """ + Mixin class for FFMpeg output. + + This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter` + classes. + """ + + _exec_key = 'animation.ffmpeg_path' + _args_key = 'animation.ffmpeg_args' + + @property + def output_args(self): + args = [] + if Path(self.outfile).suffix == '.gif': + self.codec = 'gif' + else: + args.extend(['-vcodec', self.codec]) + extra_args = (self.extra_args if self.extra_args is not None + else mpl.rcParams[self._args_key]) + # For h264, the default format is yuv444p, which is not compatible + # with quicktime (and others). Specifying yuv420p fixes playback on + # iOS, as well as HTML5 video in firefox and safari (on both Win and + # OSX). Also fixes internet explorer. This is as of 2015/10/29. + if self.codec == 'h264' and '-pix_fmt' not in extra_args: + args.extend(['-pix_fmt', 'yuv420p']) + # For GIF, we're telling FFMPEG to split the video stream, to generate + # a palette, and then use it for encoding. + elif self.codec == 'gif' and '-filter_complex' not in extra_args: + args.extend(['-filter_complex', + 'split [a][b];[a] palettegen [p];[b][p] paletteuse']) + if self.bitrate > 0: + args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps. + args.extend(extra_args) + for k, v in self.metadata.items(): + args.extend(['-metadata', '%s=%s' % (k, v)]) + + return args + ['-y', self.outfile] + + +# Combine FFMpeg options with pipe-based writing +@writers.register('ffmpeg') +class FFMpegWriter(FFMpegBase, MovieWriter): + """ + Pipe-based ffmpeg writer. + + Frames are streamed directly to ffmpeg via a pipe and written in a single + pass. + """ + def _args(self): + # Returns the command line parameters for subprocess to use + # ffmpeg to create a movie using a pipe. + args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo', + '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format, + '-r', str(self.fps)] + # Logging is quieted because subprocess.PIPE has limited buffer size. + # If you have a lot of frames in your animation and set logging to + # DEBUG, you will have a buffer overrun. + if _log.getEffectiveLevel() > logging.DEBUG: + args += ['-loglevel', 'error'] + args += ['-i', 'pipe:'] + self.output_args + return args + + +# Combine FFMpeg options with temp file-based writing +@writers.register('ffmpeg_file') +class FFMpegFileWriter(FFMpegBase, FileMovieWriter): + """ + File-based ffmpeg writer. + + Frames are written to temporary files on disk and then stitched + together at the end. + """ + supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba'] + + def _args(self): + # Returns the command line parameters for subprocess to use + # ffmpeg to create a movie using a collection of temp images + args = [] + # For raw frames, we need to explicitly tell ffmpeg the metadata. + if self.frame_format in {'raw', 'rgba'}: + args += [ + '-f', 'image2', '-vcodec', 'rawvideo', + '-video_size', '%dx%d' % self.frame_size, + '-pixel_format', 'rgba', + '-framerate', str(self.fps), + ] + args += ['-r', str(self.fps), '-i', self._base_temp_name(), + '-vframes', str(self._frame_counter)] + # Logging is quieted because subprocess.PIPE has limited buffer size. + # If you have a lot of frames in your animation and set logging to + # DEBUG, you will have a buffer overrun. + if _log.getEffectiveLevel() > logging.DEBUG: + args += ['-loglevel', 'error'] + return [self.bin_path(), *args, *self.output_args] + + +# Base class for animated GIFs with ImageMagick +class ImageMagickBase: + """ + Mixin class for ImageMagick output. + + This is a base class for the concrete `ImageMagickWriter` and + `ImageMagickFileWriter` classes, which define an ``input_names`` attribute + (or property) specifying the input names passed to ImageMagick. + """ + + _exec_key = 'animation.convert_path' + _args_key = 'animation.convert_args' + + @_api.deprecated("3.6") + @property + def delay(self): + return 100. / self.fps + + @_api.deprecated("3.6") + @property + def output_args(self): + extra_args = (self.extra_args if self.extra_args is not None + else mpl.rcParams[self._args_key]) + return [*extra_args, self.outfile] + + def _args(self): + # ImageMagick does not recognize "raw". + fmt = "rgba" if self.frame_format == "raw" else self.frame_format + extra_args = (self.extra_args if self.extra_args is not None + else mpl.rcParams[self._args_key]) + return [ + self.bin_path(), + "-size", "%ix%i" % self.frame_size, + "-depth", "8", + "-delay", str(100 / self.fps), + "-loop", "0", + f"{fmt}:{self.input_names}", + *extra_args, + self.outfile, + ] + + @classmethod + def bin_path(cls): + binpath = super().bin_path() + if binpath == 'convert': + binpath = mpl._get_executable_info('magick').executable + return binpath + + @classmethod + def isAvailable(cls): + try: + return super().isAvailable() + except mpl.ExecutableNotFoundError as _enf: + # May be raised by get_executable_info. + _log.debug('ImageMagick unavailable due to: %s', _enf) + return False + + +# Combine ImageMagick options with pipe-based writing +@writers.register('imagemagick') +class ImageMagickWriter(ImageMagickBase, MovieWriter): + """ + Pipe-based animated gif writer. + + Frames are streamed directly to ImageMagick via a pipe and written + in a single pass. + """ + + input_names = "-" # stdin + + +# Combine ImageMagick options with temp file-based writing +@writers.register('imagemagick_file') +class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter): + """ + File-based animated gif writer. + + Frames are written to temporary files on disk and then stitched + together at the end. + """ + + supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba'] + input_names = property( + lambda self: f'{self.temp_prefix}*.{self.frame_format}') + + +# Taken directly from jakevdp's JSAnimation package at +# http://github.com/jakevdp/JSAnimation +def _included_frames(frame_count, frame_format, frame_dir): + return INCLUDED_FRAMES.format(Nframes=frame_count, + frame_dir=frame_dir, + frame_format=frame_format) + + +def _embedded_frames(frame_list, frame_format): + """frame_list should be a list of base64-encoded png files""" + if frame_format == 'svg': + # Fix MIME type for svg + frame_format = 'svg+xml' + template = ' frames[{0}] = "data:image/{1};base64,{2}"\n' + return "\n" + "".join( + template.format(i, frame_format, frame_data.replace('\n', '\\\n')) + for i, frame_data in enumerate(frame_list)) + + +@writers.register('html') +class HTMLWriter(FileMovieWriter): + """Writer for JavaScript-based HTML movies.""" + + supported_formats = ['png', 'jpeg', 'tiff', 'svg'] + + @classmethod + def isAvailable(cls): + return True + + def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None, + metadata=None, embed_frames=False, default_mode='loop', + embed_limit=None): + + if extra_args: + _log.warning("HTMLWriter ignores 'extra_args'") + extra_args = () # Don't lookup nonexistent rcParam[args_key]. + self.embed_frames = embed_frames + self.default_mode = default_mode.lower() + _api.check_in_list(['loop', 'once', 'reflect'], + default_mode=self.default_mode) + + # Save embed limit, which is given in MB + if embed_limit is None: + self._bytes_limit = mpl.rcParams['animation.embed_limit'] + else: + self._bytes_limit = embed_limit + # Convert from MB to bytes + self._bytes_limit *= 1024 * 1024 + + super().__init__(fps, codec, bitrate, extra_args, metadata) + + def setup(self, fig, outfile, dpi=None, frame_dir=None): + outfile = Path(outfile) + _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix) + + self._saved_frames = [] + self._total_bytes = 0 + self._hit_limit = False + + if not self.embed_frames: + if frame_dir is None: + frame_dir = outfile.with_name(outfile.stem + '_frames') + frame_dir.mkdir(parents=True, exist_ok=True) + frame_prefix = frame_dir / 'frame' + else: + frame_prefix = None + + super().setup(fig, outfile, dpi, frame_prefix) + self._clear_temp = False + + def grab_frame(self, **savefig_kwargs): + if self.embed_frames: + # Just stop processing if we hit the limit + if self._hit_limit: + return + f = BytesIO() + self.fig.savefig(f, format=self.frame_format, + dpi=self.dpi, **savefig_kwargs) + imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii') + self._total_bytes += len(imgdata64) + if self._total_bytes >= self._bytes_limit: + _log.warning( + "Animation size has reached %s bytes, exceeding the limit " + "of %s. If you're sure you want a larger animation " + "embedded, set the animation.embed_limit rc parameter to " + "a larger value (in MB). This and further frames will be " + "dropped.", self._total_bytes, self._bytes_limit) + self._hit_limit = True + else: + self._saved_frames.append(imgdata64) + else: + return super().grab_frame(**savefig_kwargs) + + def finish(self): + # save the frames to an html file + if self.embed_frames: + fill_frames = _embedded_frames(self._saved_frames, + self.frame_format) + frame_count = len(self._saved_frames) + else: + # temp names is filled by FileMovieWriter + frame_count = len(self._temp_paths) + fill_frames = _included_frames( + frame_count, self.frame_format, + self._temp_paths[0].parent.relative_to(self.outfile.parent)) + mode_dict = dict(once_checked='', + loop_checked='', + reflect_checked='') + mode_dict[self.default_mode + '_checked'] = 'checked' + + interval = 1000 // self.fps + + with open(self.outfile, 'w') as of: + of.write(JS_INCLUDE + STYLE_INCLUDE) + of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex, + Nframes=frame_count, + fill_frames=fill_frames, + interval=interval, + **mode_dict)) + + # Duplicate the temporary file clean up logic from + # FileMovieWriter.finish. We can not call the inherited version of + # finish because it assumes that there is a subprocess that we either + # need to call to merge many frames together or that there is a + # subprocess call that we need to clean up. + if self._tmpdir: + _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir) + self._tmpdir.cleanup() + + +class Animation: + """ + A base class for Animations. + + This class is not usable as is, and should be subclassed to provide needed + behavior. + + .. note:: + + You must store the created Animation in a variable that lives as long + as the animation should run. Otherwise, the Animation object will be + garbage-collected and the animation stops. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The figure object used to get needed events, such as draw or resize. + + event_source : object, optional + A class that can run a callback when desired events + are generated, as well as be stopped and started. + + Examples include timers (see `TimedAnimation`) and file + system notifications. + + blit : bool, default: False + Whether blitting is used to optimize drawing. If the backend does not + support blitting, then this parameter has no effect. + + See Also + -------- + FuncAnimation, ArtistAnimation + """ + + def __init__(self, fig, event_source=None, blit=False): + self._draw_was_started = False + + self._fig = fig + # Disables blitting for backends that don't support it. This + # allows users to request it if available, but still have a + # fallback that works if it is not. + self._blit = blit and fig.canvas.supports_blit + + # These are the basics of the animation. The frame sequence represents + # information for each frame of the animation and depends on how the + # drawing is handled by the subclasses. The event source fires events + # that cause the frame sequence to be iterated. + self.frame_seq = self.new_frame_seq() + self.event_source = event_source + + # Instead of starting the event source now, we connect to the figure's + # draw_event, so that we only start once the figure has been drawn. + self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start) + + # Connect to the figure's close_event so that we don't continue to + # fire events and try to draw to a deleted figure. + self._close_id = self._fig.canvas.mpl_connect('close_event', + self._stop) + if self._blit: + self._setup_blit() + + def __del__(self): + if not getattr(self, '_draw_was_started', True): + warnings.warn( + 'Animation was deleted without rendering anything. This is ' + 'most likely not intended. To prevent deletion, assign the ' + 'Animation to a variable, e.g. `anim`, that exists until you ' + 'output the Animation using `plt.show()` or ' + '`anim.save()`.' + ) + + def _start(self, *args): + """ + Starts interactive animation. Adds the draw frame command to the GUI + handler, calls show to start the event loop. + """ + # Do not start the event source if saving() it. + if self._fig.canvas.is_saving(): + return + # First disconnect our draw event handler + self._fig.canvas.mpl_disconnect(self._first_draw_id) + + # Now do any initial draw + self._init_draw() + + # Add our callback for stepping the animation and + # actually start the event_source. + self.event_source.add_callback(self._step) + self.event_source.start() + + def _stop(self, *args): + # On stop we disconnect all of our events. + if self._blit: + self._fig.canvas.mpl_disconnect(self._resize_id) + self._fig.canvas.mpl_disconnect(self._close_id) + self.event_source.remove_callback(self._step) + self.event_source = None + + def save(self, filename, writer=None, fps=None, dpi=None, codec=None, + bitrate=None, extra_args=None, metadata=None, extra_anim=None, + savefig_kwargs=None, *, progress_callback=None): + """ + Save the animation as a movie file by drawing every frame. + + Parameters + ---------- + filename : str + The output filename, e.g., :file:`mymovie.mp4`. + + writer : `MovieWriter` or str, default: :rc:`animation.writer` + A `MovieWriter` instance to use or a key that identifies a + class to use, such as 'ffmpeg'. + + fps : int, optional + Movie frame rate (per second). If not set, the frame rate from the + animation's frame interval. + + dpi : float, default: :rc:`savefig.dpi` + Controls the dots per inch for the movie frames. Together with + the figure's size in inches, this controls the size of the movie. + + codec : str, default: :rc:`animation.codec`. + The video codec to use. Not all codecs are supported by a given + `MovieWriter`. + + bitrate : int, default: :rc:`animation.bitrate` + The bitrate of the movie, in kilobits per second. Higher values + means higher quality movies, but increase the file size. A value + of -1 lets the underlying movie encoder select the bitrate. + + extra_args : list of str or None, optional + Extra command-line arguments passed to the underlying movie + encoder. The default, None, means to use + :rc:`animation.[name-of-encoder]_args` for the builtin writers. + + metadata : dict[str, str], default: {} + Dictionary of keys and values for metadata to include in + the output file. Some keys that may be of use include: + title, artist, genre, subject, copyright, srcform, comment. + + extra_anim : list, default: [] + Additional `Animation` objects that should be included + in the saved movie file. These need to be from the same + `.Figure` instance. Also, animation frames will + just be simply combined, so there should be a 1:1 correspondence + between the frames from the different animations. + + savefig_kwargs : dict, default: {} + Keyword arguments passed to each `~.Figure.savefig` call used to + save the individual frames. + + progress_callback : function, optional + A callback function that will be called for every frame to notify + the saving progress. It must have the signature :: + + def func(current_frame: int, total_frames: int) -> Any + + where *current_frame* is the current frame number and + *total_frames* is the total number of frames to be saved. + *total_frames* is set to None, if the total number of frames can + not be determined. Return values may exist but are ignored. + + Example code to write the progress to stdout:: + + progress_callback = lambda i, n: print(f'Saving frame {i}/{n}') + + Notes + ----- + *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to + construct a `.MovieWriter` instance and can only be passed if + *writer* is a string. If they are passed as non-*None* and *writer* + is a `.MovieWriter`, a `RuntimeError` will be raised. + """ + + all_anim = [self] + if extra_anim is not None: + all_anim.extend(anim for anim in extra_anim + if anim._fig is self._fig) + + # Disable "Animation was deleted without rendering" warning. + for anim in all_anim: + anim._draw_was_started = True + + if writer is None: + writer = mpl.rcParams['animation.writer'] + elif (not isinstance(writer, str) and + any(arg is not None + for arg in (fps, codec, bitrate, extra_args, metadata))): + raise RuntimeError('Passing in values for arguments ' + 'fps, codec, bitrate, extra_args, or metadata ' + 'is not supported when writer is an existing ' + 'MovieWriter instance. These should instead be ' + 'passed as arguments when creating the ' + 'MovieWriter instance.') + + if savefig_kwargs is None: + savefig_kwargs = {} + else: + # we are going to mutate this below + savefig_kwargs = dict(savefig_kwargs) + + if fps is None and hasattr(self, '_interval'): + # Convert interval in ms to frames per second + fps = 1000. / self._interval + + # Re-use the savefig DPI for ours if none is given + if dpi is None: + dpi = mpl.rcParams['savefig.dpi'] + if dpi == 'figure': + dpi = self._fig.dpi + + writer_kwargs = {} + if codec is not None: + writer_kwargs['codec'] = codec + if bitrate is not None: + writer_kwargs['bitrate'] = bitrate + if extra_args is not None: + writer_kwargs['extra_args'] = extra_args + if metadata is not None: + writer_kwargs['metadata'] = metadata + + # If we have the name of a writer, instantiate an instance of the + # registered class. + if isinstance(writer, str): + try: + writer_cls = writers[writer] + except RuntimeError: # Raised if not available. + writer_cls = PillowWriter # Always available. + _log.warning("MovieWriter %s unavailable; using Pillow " + "instead.", writer) + writer = writer_cls(fps, **writer_kwargs) + _log.info('Animation.save using %s', type(writer)) + + if 'bbox_inches' in savefig_kwargs: + _log.warning("Warning: discarding the 'bbox_inches' argument in " + "'savefig_kwargs' as it may cause frame size " + "to vary, which is inappropriate for animation.") + savefig_kwargs.pop('bbox_inches') + + # Create a new sequence of frames for saved data. This is different + # from new_frame_seq() to give the ability to save 'live' generated + # frame information to be saved later. + # TODO: Right now, after closing the figure, saving a movie won't work + # since GUI widgets are gone. Either need to remove extra code to + # allow for this non-existent use case or find a way to make it work. + if mpl.rcParams['savefig.bbox'] == 'tight': + _log.info("Disabling savefig.bbox = 'tight', as it may cause " + "frame size to vary, which is inappropriate for " + "animation.") + + facecolor = savefig_kwargs.get('facecolor', + mpl.rcParams['savefig.facecolor']) + if facecolor == 'auto': + facecolor = self._fig.get_facecolor() + + def _pre_composite_to_white(color): + r, g, b, a = mcolors.to_rgba(color) + return a * np.array([r, g, b]) + 1 - a + + savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor) + savefig_kwargs['transparent'] = False # just to be safe! + # canvas._is_saving = True makes the draw_event animation-starting + # callback a no-op; canvas.manager = None prevents resizing the GUI + # widget (both are likewise done in savefig()). + with mpl.rc_context({'savefig.bbox': None}), \ + writer.saving(self._fig, filename, dpi), \ + cbook._setattr_cm(self._fig.canvas, + _is_saving=True, manager=None): + for anim in all_anim: + anim._init_draw() # Clear the initial frame + frame_number = 0 + # TODO: Currently only FuncAnimation has a save_count + # attribute. Can we generalize this to all Animations? + save_count_list = [getattr(a, '_save_count', None) + for a in all_anim] + if None in save_count_list: + total_frames = None + else: + total_frames = sum(save_count_list) + for data in zip(*[a.new_saved_frame_seq() for a in all_anim]): + for anim, d in zip(all_anim, data): + # TODO: See if turning off blit is really necessary + anim._draw_next_frame(d, blit=False) + if progress_callback is not None: + progress_callback(frame_number, total_frames) + frame_number += 1 + writer.grab_frame(**savefig_kwargs) + + def _step(self, *args): + """ + Handler for getting events. By default, gets the next frame in the + sequence and hands the data off to be drawn. + """ + # Returns True to indicate that the event source should continue to + # call _step, until the frame sequence reaches the end of iteration, + # at which point False will be returned. + try: + framedata = next(self.frame_seq) + self._draw_next_frame(framedata, self._blit) + return True + except StopIteration: + return False + + def new_frame_seq(self): + """Return a new sequence of frame information.""" + # Default implementation is just an iterator over self._framedata + return iter(self._framedata) + + def new_saved_frame_seq(self): + """Return a new sequence of saved/cached frame information.""" + # Default is the same as the regular frame sequence + return self.new_frame_seq() + + def _draw_next_frame(self, framedata, blit): + # Breaks down the drawing of the next frame into steps of pre- and + # post- draw, as well as the drawing of the frame itself. + self._pre_draw(framedata, blit) + self._draw_frame(framedata) + self._post_draw(framedata, blit) + + def _init_draw(self): + # Initial draw to clear the frame. Also used by the blitting code + # when a clean base is required. + self._draw_was_started = True + + def _pre_draw(self, framedata, blit): + # Perform any cleaning or whatnot before the drawing of the frame. + # This default implementation allows blit to clear the frame. + if blit: + self._blit_clear(self._drawn_artists) + + def _draw_frame(self, framedata): + # Performs actual drawing of the frame. + raise NotImplementedError('Needs to be implemented by subclasses to' + ' actually make an animation.') + + def _post_draw(self, framedata, blit): + # After the frame is rendered, this handles the actual flushing of + # the draw, which can be a direct draw_idle() or make use of the + # blitting. + if blit and self._drawn_artists: + self._blit_draw(self._drawn_artists) + else: + self._fig.canvas.draw_idle() + + # The rest of the code in this class is to facilitate easy blitting + def _blit_draw(self, artists): + # Handles blitted drawing, which renders only the artists given instead + # of the entire figure. + updated_ax = {a.axes for a in artists} + # Enumerate artists to cache Axes backgrounds. We do not draw + # artists yet to not cache foreground from plots with shared axes + for ax in updated_ax: + # If we haven't cached the background for the current view of this + # Axes object, do so now. This might not always be reliable, but + # it's an attempt to automate the process. + cur_view = ax._get_view() + view, bg = self._blit_cache.get(ax, (object(), None)) + if cur_view != view: + self._blit_cache[ax] = ( + cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox)) + # Make a separate pass to draw foreground. + for a in artists: + a.axes.draw_artist(a) + # After rendering all the needed artists, blit each Axes individually. + for ax in updated_ax: + ax.figure.canvas.blit(ax.bbox) + + def _blit_clear(self, artists): + # Get a list of the Axes that need clearing from the artists that + # have been drawn. Grab the appropriate saved background from the + # cache and restore. + axes = {a.axes for a in artists} + for ax in axes: + try: + view, bg = self._blit_cache[ax] + except KeyError: + continue + if ax._get_view() == view: + ax.figure.canvas.restore_region(bg) + else: + self._blit_cache.pop(ax) + + def _setup_blit(self): + # Setting up the blit requires: a cache of the background for the Axes + self._blit_cache = dict() + self._drawn_artists = [] + # _post_draw needs to be called first to initialize the renderer + self._post_draw(None, self._blit) + # Then we need to clear the Frame for the initial draw + # This is typically handled in _on_resize because QT and Tk + # emit a resize event on launch, but the macosx backend does not, + # thus we force it here for everyone for consistency + self._init_draw() + # Connect to future resize events + self._resize_id = self._fig.canvas.mpl_connect('resize_event', + self._on_resize) + + def _on_resize(self, event): + # On resize, we need to disable the resize event handling so we don't + # get too many events. Also stop the animation events, so that + # we're paused. Reset the cache and re-init. Set up an event handler + # to catch once the draw has actually taken place. + self._fig.canvas.mpl_disconnect(self._resize_id) + self.event_source.stop() + self._blit_cache.clear() + self._init_draw() + self._resize_id = self._fig.canvas.mpl_connect('draw_event', + self._end_redraw) + + def _end_redraw(self, event): + # Now that the redraw has happened, do the post draw flushing and + # blit handling. Then re-enable all of the original events. + self._post_draw(None, False) + self.event_source.start() + self._fig.canvas.mpl_disconnect(self._resize_id) + self._resize_id = self._fig.canvas.mpl_connect('resize_event', + self._on_resize) + + def to_html5_video(self, embed_limit=None): + """ + Convert the animation to an HTML5 ``