Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_spfuncs.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc +0 -0
- moondream/lib/python3.10/site-packages/matplotlib/__init__.py +1576 -0
- moondream/lib/python3.10/site-packages/matplotlib/_afm.py +532 -0
- moondream/lib/python3.10/site-packages/matplotlib/_animation_data.py +262 -0
- moondream/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi +8 -0
- moondream/lib/python3.10/site-packages/matplotlib/_color_data.pyi +6 -0
- moondream/lib/python3.10/site-packages/matplotlib/_constrained_layout.py +801 -0
- moondream/lib/python3.10/site-packages/matplotlib/_docstring.pyi +34 -0
- moondream/lib/python3.10/site-packages/matplotlib/_enums.py +187 -0
- moondream/lib/python3.10/site-packages/matplotlib/_mathtext_data.py +1742 -0
- moondream/lib/python3.10/site-packages/matplotlib/_path.pyi +9 -0
- moondream/lib/python3.10/site-packages/matplotlib/_qhull.pyi +0 -0
- moondream/lib/python3.10/site-packages/matplotlib/_tight_bbox.py +84 -0
- moondream/lib/python3.10/site-packages/matplotlib/animation.py +1823 -0
- moondream/lib/python3.10/site-packages/matplotlib/animation.pyi +217 -0
- moondream/lib/python3.10/site-packages/matplotlib/artist.py +1855 -0
- moondream/lib/python3.10/site-packages/matplotlib/backend_bases.pyi +482 -0
- moondream/lib/python3.10/site-packages/matplotlib/backend_managers.py +387 -0
- moondream/lib/python3.10/site-packages/matplotlib/backend_tools.pyi +121 -0
- moondream/lib/python3.10/site-packages/matplotlib/bezier.pyi +74 -0
- moondream/lib/python3.10/site-packages/matplotlib/colorbar.pyi +139 -0
- moondream/lib/python3.10/site-packages/matplotlib/contour.py +1709 -0
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc
ADDED
|
Binary file (23.5 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc
ADDED
|
Binary file (37.2 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc
ADDED
|
Binary file (43.3 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc
ADDED
|
Binary file (48.6 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc
ADDED
|
Binary file (18.3 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc
ADDED
|
Binary file (5.08 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc
ADDED
|
Binary file (19.2 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc
ADDED
|
Binary file (5.65 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc
ADDED
|
Binary file (5.31 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_spfuncs.cpython-310.pyc
ADDED
|
Binary file (1.82 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc
ADDED
|
Binary file (18.5 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc
ADDED
|
Binary file (778 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc
ADDED
|
Binary file (779 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc
ADDED
|
Binary file (942 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc
ADDED
|
Binary file (851 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc
ADDED
|
Binary file (806 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc
ADDED
|
Binary file (643 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc
ADDED
|
Binary file (680 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc
ADDED
|
Binary file (619 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc
ADDED
|
Binary file (699 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc
ADDED
|
Binary file (725 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc
ADDED
|
Binary file (614 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc
ADDED
|
Binary file (640 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc
ADDED
|
Binary file (628 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (7.54 kB). View file
|
|
|
moondream/lib/python3.10/site-packages/matplotlib/__init__.py
ADDED
|
@@ -0,0 +1,1576 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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::
|
| 6 |
+
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
|
| 9 |
+
or using ipython::
|
| 10 |
+
|
| 11 |
+
ipython
|
| 12 |
+
|
| 13 |
+
at your terminal, followed by::
|
| 14 |
+
|
| 15 |
+
In [1]: %matplotlib
|
| 16 |
+
In [2]: import matplotlib.pyplot as plt
|
| 17 |
+
|
| 18 |
+
at the ipython shell prompt.
|
| 19 |
+
|
| 20 |
+
For the most part, direct use of the explicit object-oriented library is
|
| 21 |
+
encouraged when programming; the implicit pyplot interface is primarily for
|
| 22 |
+
working interactively. The exceptions to this suggestion are the pyplot
|
| 23 |
+
functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and
|
| 24 |
+
`.pyplot.savefig`, which can greatly simplify scripting. See
|
| 25 |
+
:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit
|
| 26 |
+
and explicit interfaces.
|
| 27 |
+
|
| 28 |
+
Modules include:
|
| 29 |
+
|
| 30 |
+
:mod:`matplotlib.axes`
|
| 31 |
+
The `~.axes.Axes` class. Most pyplot functions are wrappers for
|
| 32 |
+
`~.axes.Axes` methods. The axes module is the highest level of OO
|
| 33 |
+
access to the library.
|
| 34 |
+
|
| 35 |
+
:mod:`matplotlib.figure`
|
| 36 |
+
The `.Figure` class.
|
| 37 |
+
|
| 38 |
+
:mod:`matplotlib.artist`
|
| 39 |
+
The `.Artist` base class for all classes that draw things.
|
| 40 |
+
|
| 41 |
+
:mod:`matplotlib.lines`
|
| 42 |
+
The `.Line2D` class for drawing lines and markers.
|
| 43 |
+
|
| 44 |
+
:mod:`matplotlib.patches`
|
| 45 |
+
Classes for drawing polygons.
|
| 46 |
+
|
| 47 |
+
:mod:`matplotlib.text`
|
| 48 |
+
The `.Text` and `.Annotation` classes.
|
| 49 |
+
|
| 50 |
+
:mod:`matplotlib.image`
|
| 51 |
+
The `.AxesImage` and `.FigureImage` classes.
|
| 52 |
+
|
| 53 |
+
:mod:`matplotlib.collections`
|
| 54 |
+
Classes for efficient drawing of groups of lines or polygons.
|
| 55 |
+
|
| 56 |
+
:mod:`matplotlib.colors`
|
| 57 |
+
Color specifications and making colormaps.
|
| 58 |
+
|
| 59 |
+
:mod:`matplotlib.cm`
|
| 60 |
+
Colormaps, and the `.ScalarMappable` mixin class for providing color
|
| 61 |
+
mapping functionality to other classes.
|
| 62 |
+
|
| 63 |
+
:mod:`matplotlib.ticker`
|
| 64 |
+
Calculation of tick mark locations and formatting of tick labels.
|
| 65 |
+
|
| 66 |
+
:mod:`matplotlib.backends`
|
| 67 |
+
A subpackage with modules for various GUI libraries and output formats.
|
| 68 |
+
|
| 69 |
+
The base matplotlib namespace includes:
|
| 70 |
+
|
| 71 |
+
`~matplotlib.rcParams`
|
| 72 |
+
Default configuration settings; their defaults may be overridden using
|
| 73 |
+
a :file:`matplotlibrc` file.
|
| 74 |
+
|
| 75 |
+
`~matplotlib.use`
|
| 76 |
+
Setting the Matplotlib backend. This should be called before any
|
| 77 |
+
figure is created, because it is not possible to switch between
|
| 78 |
+
different GUI backends after that.
|
| 79 |
+
|
| 80 |
+
The following environment variables can be used to customize the behavior:
|
| 81 |
+
|
| 82 |
+
:envvar:`MPLBACKEND`
|
| 83 |
+
This optional variable can be set to choose the Matplotlib backend. See
|
| 84 |
+
:ref:`what-is-a-backend`.
|
| 85 |
+
|
| 86 |
+
:envvar:`MPLCONFIGDIR`
|
| 87 |
+
This is the directory used to store user customizations to
|
| 88 |
+
Matplotlib, as well as some caches to improve performance. If
|
| 89 |
+
:envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`
|
| 90 |
+
and :file:`{HOME}/.cache/matplotlib` are used on Linux, and
|
| 91 |
+
:file:`{HOME}/.matplotlib` on other platforms, if they are
|
| 92 |
+
writable. Otherwise, the Python standard library's `tempfile.gettempdir`
|
| 93 |
+
is used to find a base directory in which the :file:`matplotlib`
|
| 94 |
+
subdirectory is created.
|
| 95 |
+
|
| 96 |
+
Matplotlib was initially written by John D. Hunter (1968-2012) and is now
|
| 97 |
+
developed and maintained by a host of others.
|
| 98 |
+
|
| 99 |
+
Occasionally the internal documentation (python docstrings) will refer
|
| 100 |
+
to MATLAB®, a registered trademark of The MathWorks, Inc.
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
__all__ = [
|
| 105 |
+
"__bibtex__",
|
| 106 |
+
"__version__",
|
| 107 |
+
"__version_info__",
|
| 108 |
+
"set_loglevel",
|
| 109 |
+
"ExecutableNotFoundError",
|
| 110 |
+
"get_configdir",
|
| 111 |
+
"get_cachedir",
|
| 112 |
+
"get_data_path",
|
| 113 |
+
"matplotlib_fname",
|
| 114 |
+
"MatplotlibDeprecationWarning",
|
| 115 |
+
"RcParams",
|
| 116 |
+
"rc_params",
|
| 117 |
+
"rc_params_from_file",
|
| 118 |
+
"rcParamsDefault",
|
| 119 |
+
"rcParams",
|
| 120 |
+
"rcParamsOrig",
|
| 121 |
+
"defaultParams",
|
| 122 |
+
"rc",
|
| 123 |
+
"rcdefaults",
|
| 124 |
+
"rc_file_defaults",
|
| 125 |
+
"rc_file",
|
| 126 |
+
"rc_context",
|
| 127 |
+
"use",
|
| 128 |
+
"get_backend",
|
| 129 |
+
"interactive",
|
| 130 |
+
"is_interactive",
|
| 131 |
+
"colormaps",
|
| 132 |
+
"multivar_colormaps",
|
| 133 |
+
"bivar_colormaps",
|
| 134 |
+
"color_sequences",
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
import atexit
|
| 139 |
+
from collections import namedtuple
|
| 140 |
+
from collections.abc import MutableMapping
|
| 141 |
+
import contextlib
|
| 142 |
+
import functools
|
| 143 |
+
import importlib
|
| 144 |
+
import inspect
|
| 145 |
+
from inspect import Parameter
|
| 146 |
+
import locale
|
| 147 |
+
import logging
|
| 148 |
+
import os
|
| 149 |
+
from pathlib import Path
|
| 150 |
+
import pprint
|
| 151 |
+
import re
|
| 152 |
+
import shutil
|
| 153 |
+
import subprocess
|
| 154 |
+
import sys
|
| 155 |
+
import tempfile
|
| 156 |
+
|
| 157 |
+
from packaging.version import parse as parse_version
|
| 158 |
+
|
| 159 |
+
# cbook must import matplotlib only within function
|
| 160 |
+
# definitions, so it is safe to import from it here.
|
| 161 |
+
from . import _api, _version, cbook, _docstring, rcsetup
|
| 162 |
+
from matplotlib._api import MatplotlibDeprecationWarning
|
| 163 |
+
from matplotlib.rcsetup import cycler # noqa: F401
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
_log = logging.getLogger(__name__)
|
| 167 |
+
|
| 168 |
+
__bibtex__ = r"""@Article{Hunter:2007,
|
| 169 |
+
Author = {Hunter, J. D.},
|
| 170 |
+
Title = {Matplotlib: A 2D graphics environment},
|
| 171 |
+
Journal = {Computing in Science \& Engineering},
|
| 172 |
+
Volume = {9},
|
| 173 |
+
Number = {3},
|
| 174 |
+
Pages = {90--95},
|
| 175 |
+
abstract = {Matplotlib is a 2D graphics package used for Python
|
| 176 |
+
for application development, interactive scripting, and
|
| 177 |
+
publication-quality image generation across user
|
| 178 |
+
interfaces and operating systems.},
|
| 179 |
+
publisher = {IEEE COMPUTER SOC},
|
| 180 |
+
year = 2007
|
| 181 |
+
}"""
|
| 182 |
+
|
| 183 |
+
# modelled after sys.version_info
|
| 184 |
+
_VersionInfo = namedtuple('_VersionInfo',
|
| 185 |
+
'major, minor, micro, releaselevel, serial')
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _parse_to_version_info(version_str):
|
| 189 |
+
"""
|
| 190 |
+
Parse a version string to a namedtuple analogous to sys.version_info.
|
| 191 |
+
|
| 192 |
+
See:
|
| 193 |
+
https://packaging.pypa.io/en/latest/version.html#packaging.version.parse
|
| 194 |
+
https://docs.python.org/3/library/sys.html#sys.version_info
|
| 195 |
+
"""
|
| 196 |
+
v = parse_version(version_str)
|
| 197 |
+
if v.pre is None and v.post is None and v.dev is None:
|
| 198 |
+
return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)
|
| 199 |
+
elif v.dev is not None:
|
| 200 |
+
return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)
|
| 201 |
+
elif v.pre is not None:
|
| 202 |
+
releaselevel = {
|
| 203 |
+
'a': 'alpha',
|
| 204 |
+
'b': 'beta',
|
| 205 |
+
'rc': 'candidate'}.get(v.pre[0], 'alpha')
|
| 206 |
+
return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])
|
| 207 |
+
else:
|
| 208 |
+
# fallback for v.post: guess-next-dev scheme from setuptools_scm
|
| 209 |
+
return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _get_version():
|
| 213 |
+
"""Return the version string used for __version__."""
|
| 214 |
+
# Only shell out to a git subprocess if really needed, i.e. when we are in
|
| 215 |
+
# a matplotlib git repo but not in a shallow clone, such as those used by
|
| 216 |
+
# CI, as the latter would trigger a warning from setuptools_scm.
|
| 217 |
+
root = Path(__file__).resolve().parents[2]
|
| 218 |
+
if ((root / ".matplotlib-repo").exists()
|
| 219 |
+
and (root / ".git").exists()
|
| 220 |
+
and not (root / ".git/shallow").exists()):
|
| 221 |
+
try:
|
| 222 |
+
import setuptools_scm
|
| 223 |
+
except ImportError:
|
| 224 |
+
pass
|
| 225 |
+
else:
|
| 226 |
+
return setuptools_scm.get_version(
|
| 227 |
+
root=root,
|
| 228 |
+
dist_name="matplotlib",
|
| 229 |
+
version_scheme="release-branch-semver",
|
| 230 |
+
local_scheme="node-and-date",
|
| 231 |
+
fallback_version=_version.version,
|
| 232 |
+
)
|
| 233 |
+
# Get the version from the _version.py file if not in repo or setuptools_scm is
|
| 234 |
+
# unavailable.
|
| 235 |
+
return _version.version
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@_api.caching_module_getattr
|
| 239 |
+
class __getattr__:
|
| 240 |
+
__version__ = property(lambda self: _get_version())
|
| 241 |
+
__version_info__ = property(
|
| 242 |
+
lambda self: _parse_to_version_info(self.__version__))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _check_versions():
|
| 246 |
+
|
| 247 |
+
# Quickfix to ensure Microsoft Visual C++ redistributable
|
| 248 |
+
# DLLs are loaded before importing kiwisolver
|
| 249 |
+
from . import ft2font # noqa: F401
|
| 250 |
+
|
| 251 |
+
for modname, minver in [
|
| 252 |
+
("cycler", "0.10"),
|
| 253 |
+
("dateutil", "2.7"),
|
| 254 |
+
("kiwisolver", "1.3.1"),
|
| 255 |
+
("numpy", "1.23"),
|
| 256 |
+
("pyparsing", "2.3.1"),
|
| 257 |
+
]:
|
| 258 |
+
module = importlib.import_module(modname)
|
| 259 |
+
if parse_version(module.__version__) < parse_version(minver):
|
| 260 |
+
raise ImportError(f"Matplotlib requires {modname}>={minver}; "
|
| 261 |
+
f"you have {module.__version__}")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
_check_versions()
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# The decorator ensures this always returns the same handler (and it is only
|
| 268 |
+
# attached once).
|
| 269 |
+
@functools.cache
|
| 270 |
+
def _ensure_handler():
|
| 271 |
+
"""
|
| 272 |
+
The first time this function is called, attach a `StreamHandler` using the
|
| 273 |
+
same format as `logging.basicConfig` to the Matplotlib root logger.
|
| 274 |
+
|
| 275 |
+
Return this handler every time this function is called.
|
| 276 |
+
"""
|
| 277 |
+
handler = logging.StreamHandler()
|
| 278 |
+
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
|
| 279 |
+
_log.addHandler(handler)
|
| 280 |
+
return handler
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def set_loglevel(level):
|
| 284 |
+
"""
|
| 285 |
+
Configure Matplotlib's logging levels.
|
| 286 |
+
|
| 287 |
+
Matplotlib uses the standard library `logging` framework under the root
|
| 288 |
+
logger 'matplotlib'. This is a helper function to:
|
| 289 |
+
|
| 290 |
+
- set Matplotlib's root logger level
|
| 291 |
+
- set the root logger handler's level, creating the handler
|
| 292 |
+
if it does not exist yet
|
| 293 |
+
|
| 294 |
+
Typically, one should call ``set_loglevel("info")`` or
|
| 295 |
+
``set_loglevel("debug")`` to get additional debugging information.
|
| 296 |
+
|
| 297 |
+
Users or applications that are installing their own logging handlers
|
| 298 |
+
may want to directly manipulate ``logging.getLogger('matplotlib')`` rather
|
| 299 |
+
than use this function.
|
| 300 |
+
|
| 301 |
+
Parameters
|
| 302 |
+
----------
|
| 303 |
+
level : {"notset", "debug", "info", "warning", "error", "critical"}
|
| 304 |
+
The log level of the handler.
|
| 305 |
+
|
| 306 |
+
Notes
|
| 307 |
+
-----
|
| 308 |
+
The first time this function is called, an additional handler is attached
|
| 309 |
+
to Matplotlib's root handler; this handler is reused every time and this
|
| 310 |
+
function simply manipulates the logger and handler's level.
|
| 311 |
+
|
| 312 |
+
"""
|
| 313 |
+
_log.setLevel(level.upper())
|
| 314 |
+
_ensure_handler().setLevel(level.upper())
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _logged_cached(fmt, func=None):
|
| 318 |
+
"""
|
| 319 |
+
Decorator that logs a function's return value, and memoizes that value.
|
| 320 |
+
|
| 321 |
+
After ::
|
| 322 |
+
|
| 323 |
+
@_logged_cached(fmt)
|
| 324 |
+
def func(): ...
|
| 325 |
+
|
| 326 |
+
the first call to *func* will log its return value at the DEBUG level using
|
| 327 |
+
%-format string *fmt*, and memoize it; later calls to *func* will directly
|
| 328 |
+
return that value.
|
| 329 |
+
"""
|
| 330 |
+
if func is None: # Return the actual decorator.
|
| 331 |
+
return functools.partial(_logged_cached, fmt)
|
| 332 |
+
|
| 333 |
+
called = False
|
| 334 |
+
ret = None
|
| 335 |
+
|
| 336 |
+
@functools.wraps(func)
|
| 337 |
+
def wrapper(**kwargs):
|
| 338 |
+
nonlocal called, ret
|
| 339 |
+
if not called:
|
| 340 |
+
ret = func(**kwargs)
|
| 341 |
+
called = True
|
| 342 |
+
_log.debug(fmt, ret)
|
| 343 |
+
return ret
|
| 344 |
+
|
| 345 |
+
return wrapper
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class ExecutableNotFoundError(FileNotFoundError):
|
| 352 |
+
"""
|
| 353 |
+
Error raised when an executable that Matplotlib optionally
|
| 354 |
+
depends on can't be found.
|
| 355 |
+
"""
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@functools.cache
|
| 360 |
+
def _get_executable_info(name):
|
| 361 |
+
"""
|
| 362 |
+
Get the version of some executable that Matplotlib optionally depends on.
|
| 363 |
+
|
| 364 |
+
.. warning::
|
| 365 |
+
The list of executables that this function supports is set according to
|
| 366 |
+
Matplotlib's internal needs, and may change without notice.
|
| 367 |
+
|
| 368 |
+
Parameters
|
| 369 |
+
----------
|
| 370 |
+
name : str
|
| 371 |
+
The executable to query. The following values are currently supported:
|
| 372 |
+
"dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This
|
| 373 |
+
list is subject to change without notice.
|
| 374 |
+
|
| 375 |
+
Returns
|
| 376 |
+
-------
|
| 377 |
+
tuple
|
| 378 |
+
A namedtuple with fields ``executable`` (`str`) and ``version``
|
| 379 |
+
(`packaging.Version`, or ``None`` if the version cannot be determined).
|
| 380 |
+
|
| 381 |
+
Raises
|
| 382 |
+
------
|
| 383 |
+
ExecutableNotFoundError
|
| 384 |
+
If the executable is not found or older than the oldest version
|
| 385 |
+
supported by Matplotlib. For debugging purposes, it is also
|
| 386 |
+
possible to "hide" an executable from Matplotlib by adding it to the
|
| 387 |
+
:envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated
|
| 388 |
+
list), which must be set prior to any calls to this function.
|
| 389 |
+
ValueError
|
| 390 |
+
If the executable is not one that we know how to query.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
def impl(args, regex, min_ver=None, ignore_exit_code=False):
|
| 394 |
+
# Execute the subprocess specified by args; capture stdout and stderr.
|
| 395 |
+
# Search for a regex match in the output; if the match succeeds, the
|
| 396 |
+
# first group of the match is the version.
|
| 397 |
+
# Return an _ExecInfo if the executable exists, and has a version of
|
| 398 |
+
# at least min_ver (if set); else, raise ExecutableNotFoundError.
|
| 399 |
+
try:
|
| 400 |
+
output = subprocess.check_output(
|
| 401 |
+
args, stderr=subprocess.STDOUT,
|
| 402 |
+
text=True, errors="replace")
|
| 403 |
+
except subprocess.CalledProcessError as _cpe:
|
| 404 |
+
if ignore_exit_code:
|
| 405 |
+
output = _cpe.output
|
| 406 |
+
else:
|
| 407 |
+
raise ExecutableNotFoundError(str(_cpe)) from _cpe
|
| 408 |
+
except OSError as _ose:
|
| 409 |
+
raise ExecutableNotFoundError(str(_ose)) from _ose
|
| 410 |
+
match = re.search(regex, output)
|
| 411 |
+
if match:
|
| 412 |
+
raw_version = match.group(1)
|
| 413 |
+
version = parse_version(raw_version)
|
| 414 |
+
if min_ver is not None and version < parse_version(min_ver):
|
| 415 |
+
raise ExecutableNotFoundError(
|
| 416 |
+
f"You have {args[0]} version {version} but the minimum "
|
| 417 |
+
f"version supported by Matplotlib is {min_ver}")
|
| 418 |
+
return _ExecInfo(args[0], raw_version, version)
|
| 419 |
+
else:
|
| 420 |
+
raise ExecutableNotFoundError(
|
| 421 |
+
f"Failed to determine the version of {args[0]} from "
|
| 422 |
+
f"{' '.join(args)}, which output {output}")
|
| 423 |
+
|
| 424 |
+
if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):
|
| 425 |
+
raise ExecutableNotFoundError(f"{name} was hidden")
|
| 426 |
+
|
| 427 |
+
if name == "dvipng":
|
| 428 |
+
return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
|
| 429 |
+
elif name == "gs":
|
| 430 |
+
execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
|
| 431 |
+
if sys.platform == "win32" else
|
| 432 |
+
["gs"])
|
| 433 |
+
for e in execs:
|
| 434 |
+
try:
|
| 435 |
+
return impl([e, "--version"], "(.*)", "9")
|
| 436 |
+
except ExecutableNotFoundError:
|
| 437 |
+
pass
|
| 438 |
+
message = "Failed to find a Ghostscript installation"
|
| 439 |
+
raise ExecutableNotFoundError(message)
|
| 440 |
+
elif name == "inkscape":
|
| 441 |
+
try:
|
| 442 |
+
# Try headless option first (needed for Inkscape version < 1.0):
|
| 443 |
+
return impl(["inkscape", "--without-gui", "-V"],
|
| 444 |
+
"Inkscape ([^ ]*)")
|
| 445 |
+
except ExecutableNotFoundError:
|
| 446 |
+
pass # Suppress exception chaining.
|
| 447 |
+
# If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
|
| 448 |
+
# try without it:
|
| 449 |
+
return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
|
| 450 |
+
elif name == "magick":
|
| 451 |
+
if sys.platform == "win32":
|
| 452 |
+
# Check the registry to avoid confusing ImageMagick's convert with
|
| 453 |
+
# Windows's builtin convert.exe.
|
| 454 |
+
import winreg
|
| 455 |
+
binpath = ""
|
| 456 |
+
for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
|
| 457 |
+
try:
|
| 458 |
+
with winreg.OpenKeyEx(
|
| 459 |
+
winreg.HKEY_LOCAL_MACHINE,
|
| 460 |
+
r"Software\Imagemagick\Current",
|
| 461 |
+
0, winreg.KEY_QUERY_VALUE | flag) as hkey:
|
| 462 |
+
binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
|
| 463 |
+
except OSError:
|
| 464 |
+
pass
|
| 465 |
+
path = None
|
| 466 |
+
if binpath:
|
| 467 |
+
for name in ["convert.exe", "magick.exe"]:
|
| 468 |
+
candidate = Path(binpath, name)
|
| 469 |
+
if candidate.exists():
|
| 470 |
+
path = str(candidate)
|
| 471 |
+
break
|
| 472 |
+
if path is None:
|
| 473 |
+
raise ExecutableNotFoundError(
|
| 474 |
+
"Failed to find an ImageMagick installation")
|
| 475 |
+
else:
|
| 476 |
+
path = "convert"
|
| 477 |
+
info = impl([path, "--version"], r"^Version: ImageMagick (\S*)")
|
| 478 |
+
if info.raw_version == "7.0.10-34":
|
| 479 |
+
# https://github.com/ImageMagick/ImageMagick/issues/2720
|
| 480 |
+
raise ExecutableNotFoundError(
|
| 481 |
+
f"You have ImageMagick {info.version}, which is unsupported")
|
| 482 |
+
return info
|
| 483 |
+
elif name == "pdftocairo":
|
| 484 |
+
return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")
|
| 485 |
+
elif name == "pdftops":
|
| 486 |
+
info = impl(["pdftops", "-v"], "^pdftops version (.*)",
|
| 487 |
+
ignore_exit_code=True)
|
| 488 |
+
if info and not (
|
| 489 |
+
3 <= info.version.major or
|
| 490 |
+
# poppler version numbers.
|
| 491 |
+
parse_version("0.9") <= info.version < parse_version("1.0")):
|
| 492 |
+
raise ExecutableNotFoundError(
|
| 493 |
+
f"You have pdftops version {info.version} but the minimum "
|
| 494 |
+
f"version supported by Matplotlib is 3.0")
|
| 495 |
+
return info
|
| 496 |
+
else:
|
| 497 |
+
raise ValueError(f"Unknown executable: {name!r}")
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _get_xdg_config_dir():
|
| 501 |
+
"""
|
| 502 |
+
Return the XDG configuration directory, according to the XDG base
|
| 503 |
+
directory spec:
|
| 504 |
+
|
| 505 |
+
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
| 506 |
+
"""
|
| 507 |
+
return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def _get_xdg_cache_dir():
|
| 511 |
+
"""
|
| 512 |
+
Return the XDG cache directory, according to the XDG base directory spec:
|
| 513 |
+
|
| 514 |
+
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
| 515 |
+
"""
|
| 516 |
+
return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _get_config_or_cache_dir(xdg_base_getter):
|
| 520 |
+
configdir = os.environ.get('MPLCONFIGDIR')
|
| 521 |
+
if configdir:
|
| 522 |
+
configdir = Path(configdir)
|
| 523 |
+
elif sys.platform.startswith(('linux', 'freebsd')):
|
| 524 |
+
# Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,
|
| 525 |
+
# as _xdg_base_getter can throw.
|
| 526 |
+
configdir = Path(xdg_base_getter(), "matplotlib")
|
| 527 |
+
else:
|
| 528 |
+
configdir = Path.home() / ".matplotlib"
|
| 529 |
+
# Resolve the path to handle potential issues with inaccessible symlinks.
|
| 530 |
+
configdir = configdir.resolve()
|
| 531 |
+
try:
|
| 532 |
+
configdir.mkdir(parents=True, exist_ok=True)
|
| 533 |
+
except OSError as exc:
|
| 534 |
+
_log.warning("mkdir -p failed for path %s: %s", configdir, exc)
|
| 535 |
+
else:
|
| 536 |
+
if os.access(str(configdir), os.W_OK) and configdir.is_dir():
|
| 537 |
+
return str(configdir)
|
| 538 |
+
_log.warning("%s is not a writable directory", configdir)
|
| 539 |
+
# If the config or cache directory cannot be created or is not a writable
|
| 540 |
+
# directory, create a temporary one.
|
| 541 |
+
try:
|
| 542 |
+
tmpdir = tempfile.mkdtemp(prefix="matplotlib-")
|
| 543 |
+
except OSError as exc:
|
| 544 |
+
raise OSError(
|
| 545 |
+
f"Matplotlib requires access to a writable cache directory, but there "
|
| 546 |
+
f"was an issue with the default path ({configdir}), and a temporary "
|
| 547 |
+
f"directory could not be created; set the MPLCONFIGDIR environment "
|
| 548 |
+
f"variable to a writable directory") from exc
|
| 549 |
+
os.environ["MPLCONFIGDIR"] = tmpdir
|
| 550 |
+
atexit.register(shutil.rmtree, tmpdir)
|
| 551 |
+
_log.warning(
|
| 552 |
+
"Matplotlib created a temporary cache directory at %s because there was "
|
| 553 |
+
"an issue with the default path (%s); it is highly recommended to set the "
|
| 554 |
+
"MPLCONFIGDIR environment variable to a writable directory, in particular to "
|
| 555 |
+
"speed up the import of Matplotlib and to better support multiprocessing.",
|
| 556 |
+
tmpdir, configdir)
|
| 557 |
+
return tmpdir
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
@_logged_cached('CONFIGDIR=%s')
|
| 561 |
+
def get_configdir():
|
| 562 |
+
"""
|
| 563 |
+
Return the string path of the configuration directory.
|
| 564 |
+
|
| 565 |
+
The directory is chosen as follows:
|
| 566 |
+
|
| 567 |
+
1. If the MPLCONFIGDIR environment variable is supplied, choose that.
|
| 568 |
+
2. On Linux, follow the XDG specification and look first in
|
| 569 |
+
``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other
|
| 570 |
+
platforms, choose ``$HOME/.matplotlib``.
|
| 571 |
+
3. If the chosen directory exists and is writable, use that as the
|
| 572 |
+
configuration directory.
|
| 573 |
+
4. Else, create a temporary directory, and use it as the configuration
|
| 574 |
+
directory.
|
| 575 |
+
"""
|
| 576 |
+
return _get_config_or_cache_dir(_get_xdg_config_dir)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
@_logged_cached('CACHEDIR=%s')
|
| 580 |
+
def get_cachedir():
|
| 581 |
+
"""
|
| 582 |
+
Return the string path of the cache directory.
|
| 583 |
+
|
| 584 |
+
The procedure used to find the directory is the same as for
|
| 585 |
+
`get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.
|
| 586 |
+
"""
|
| 587 |
+
return _get_config_or_cache_dir(_get_xdg_cache_dir)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
@_logged_cached('matplotlib data path: %s')
|
| 591 |
+
def get_data_path():
|
| 592 |
+
"""Return the path to Matplotlib data."""
|
| 593 |
+
return str(Path(__file__).with_name("mpl-data"))
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def matplotlib_fname():
|
| 597 |
+
"""
|
| 598 |
+
Get the location of the config file.
|
| 599 |
+
|
| 600 |
+
The file location is determined in the following order
|
| 601 |
+
|
| 602 |
+
- ``$PWD/matplotlibrc``
|
| 603 |
+
- ``$MATPLOTLIBRC`` if it is not a directory
|
| 604 |
+
- ``$MATPLOTLIBRC/matplotlibrc``
|
| 605 |
+
- ``$MPLCONFIGDIR/matplotlibrc``
|
| 606 |
+
- On Linux,
|
| 607 |
+
- ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
|
| 608 |
+
is defined)
|
| 609 |
+
- or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
|
| 610 |
+
is not defined)
|
| 611 |
+
- On other platforms,
|
| 612 |
+
- ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
|
| 613 |
+
- Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
|
| 614 |
+
exist.
|
| 615 |
+
"""
|
| 616 |
+
|
| 617 |
+
def gen_candidates():
|
| 618 |
+
# rely on down-stream code to make absolute. This protects us
|
| 619 |
+
# from having to directly get the current working directory
|
| 620 |
+
# which can fail if the user has ended up with a cwd that is
|
| 621 |
+
# non-existent.
|
| 622 |
+
yield 'matplotlibrc'
|
| 623 |
+
try:
|
| 624 |
+
matplotlibrc = os.environ['MATPLOTLIBRC']
|
| 625 |
+
except KeyError:
|
| 626 |
+
pass
|
| 627 |
+
else:
|
| 628 |
+
yield matplotlibrc
|
| 629 |
+
yield os.path.join(matplotlibrc, 'matplotlibrc')
|
| 630 |
+
yield os.path.join(get_configdir(), 'matplotlibrc')
|
| 631 |
+
yield os.path.join(get_data_path(), 'matplotlibrc')
|
| 632 |
+
|
| 633 |
+
for fname in gen_candidates():
|
| 634 |
+
if os.path.exists(fname) and not os.path.isdir(fname):
|
| 635 |
+
return fname
|
| 636 |
+
|
| 637 |
+
raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
|
| 638 |
+
"install is broken")
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
# rcParams deprecated and automatically mapped to another key.
|
| 642 |
+
# Values are tuples of (version, new_name, f_old2new, f_new2old).
|
| 643 |
+
_deprecated_map = {}
|
| 644 |
+
# rcParams deprecated; some can manually be mapped to another key.
|
| 645 |
+
# Values are tuples of (version, new_name_or_None).
|
| 646 |
+
_deprecated_ignore_map = {}
|
| 647 |
+
# rcParams deprecated; can use None to suppress warnings; remain actually
|
| 648 |
+
# listed in the rcParams.
|
| 649 |
+
# Values are tuples of (version,)
|
| 650 |
+
_deprecated_remain_as_none = {}
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
@_docstring.Substitution(
|
| 654 |
+
"\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))
|
| 655 |
+
)
|
| 656 |
+
class RcParams(MutableMapping, dict):
|
| 657 |
+
"""
|
| 658 |
+
A dict-like key-value store for config parameters, including validation.
|
| 659 |
+
|
| 660 |
+
Validating functions are defined and associated with rc parameters in
|
| 661 |
+
:mod:`matplotlib.rcsetup`.
|
| 662 |
+
|
| 663 |
+
The list of rcParams is:
|
| 664 |
+
|
| 665 |
+
%s
|
| 666 |
+
|
| 667 |
+
See Also
|
| 668 |
+
--------
|
| 669 |
+
:ref:`customizing-with-matplotlibrc-files`
|
| 670 |
+
"""
|
| 671 |
+
|
| 672 |
+
validate = rcsetup._validators
|
| 673 |
+
|
| 674 |
+
# validate values on the way in
|
| 675 |
+
def __init__(self, *args, **kwargs):
|
| 676 |
+
self.update(*args, **kwargs)
|
| 677 |
+
|
| 678 |
+
def _set(self, key, val):
|
| 679 |
+
"""
|
| 680 |
+
Directly write data bypassing deprecation and validation logic.
|
| 681 |
+
|
| 682 |
+
Notes
|
| 683 |
+
-----
|
| 684 |
+
As end user or downstream library you almost always should use
|
| 685 |
+
``rcParams[key] = val`` and not ``_set()``.
|
| 686 |
+
|
| 687 |
+
There are only very few special cases that need direct data access.
|
| 688 |
+
These cases previously used ``dict.__setitem__(rcParams, key, val)``,
|
| 689 |
+
which is now deprecated and replaced by ``rcParams._set(key, val)``.
|
| 690 |
+
|
| 691 |
+
Even though private, we guarantee API stability for ``rcParams._set``,
|
| 692 |
+
i.e. it is subject to Matplotlib's API and deprecation policy.
|
| 693 |
+
|
| 694 |
+
:meta public:
|
| 695 |
+
"""
|
| 696 |
+
dict.__setitem__(self, key, val)
|
| 697 |
+
|
| 698 |
+
def _get(self, key):
|
| 699 |
+
"""
|
| 700 |
+
Directly read data bypassing deprecation, backend and validation
|
| 701 |
+
logic.
|
| 702 |
+
|
| 703 |
+
Notes
|
| 704 |
+
-----
|
| 705 |
+
As end user or downstream library you almost always should use
|
| 706 |
+
``val = rcParams[key]`` and not ``_get()``.
|
| 707 |
+
|
| 708 |
+
There are only very few special cases that need direct data access.
|
| 709 |
+
These cases previously used ``dict.__getitem__(rcParams, key, val)``,
|
| 710 |
+
which is now deprecated and replaced by ``rcParams._get(key)``.
|
| 711 |
+
|
| 712 |
+
Even though private, we guarantee API stability for ``rcParams._get``,
|
| 713 |
+
i.e. it is subject to Matplotlib's API and deprecation policy.
|
| 714 |
+
|
| 715 |
+
:meta public:
|
| 716 |
+
"""
|
| 717 |
+
return dict.__getitem__(self, key)
|
| 718 |
+
|
| 719 |
+
def _update_raw(self, other_params):
|
| 720 |
+
"""
|
| 721 |
+
Directly update the data from *other_params*, bypassing deprecation,
|
| 722 |
+
backend and validation logic on both sides.
|
| 723 |
+
|
| 724 |
+
This ``rcParams._update_raw(params)`` replaces the previous pattern
|
| 725 |
+
``dict.update(rcParams, params)``.
|
| 726 |
+
|
| 727 |
+
Parameters
|
| 728 |
+
----------
|
| 729 |
+
other_params : dict or `.RcParams`
|
| 730 |
+
The input mapping from which to update.
|
| 731 |
+
"""
|
| 732 |
+
if isinstance(other_params, RcParams):
|
| 733 |
+
other_params = dict.items(other_params)
|
| 734 |
+
dict.update(self, other_params)
|
| 735 |
+
|
| 736 |
+
def _ensure_has_backend(self):
|
| 737 |
+
"""
|
| 738 |
+
Ensure that a "backend" entry exists.
|
| 739 |
+
|
| 740 |
+
Normally, the default matplotlibrc file contains *no* entry for "backend" (the
|
| 741 |
+
corresponding line starts with ##, not #; we fill in _auto_backend_sentinel
|
| 742 |
+
in that case. However, packagers can set a different default backend
|
| 743 |
+
(resulting in a normal `#backend: foo` line) in which case we should *not*
|
| 744 |
+
fill in _auto_backend_sentinel.
|
| 745 |
+
"""
|
| 746 |
+
dict.setdefault(self, "backend", rcsetup._auto_backend_sentinel)
|
| 747 |
+
|
| 748 |
+
def __setitem__(self, key, val):
|
| 749 |
+
try:
|
| 750 |
+
if key in _deprecated_map:
|
| 751 |
+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
|
| 752 |
+
_api.warn_deprecated(
|
| 753 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 754 |
+
key = alt_key
|
| 755 |
+
val = alt_val(val)
|
| 756 |
+
elif key in _deprecated_remain_as_none and val is not None:
|
| 757 |
+
version, = _deprecated_remain_as_none[key]
|
| 758 |
+
_api.warn_deprecated(version, name=key, obj_type="rcparam")
|
| 759 |
+
elif key in _deprecated_ignore_map:
|
| 760 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 761 |
+
_api.warn_deprecated(
|
| 762 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 763 |
+
return
|
| 764 |
+
elif key == 'backend':
|
| 765 |
+
if val is rcsetup._auto_backend_sentinel:
|
| 766 |
+
if 'backend' in self:
|
| 767 |
+
return
|
| 768 |
+
try:
|
| 769 |
+
cval = self.validate[key](val)
|
| 770 |
+
except ValueError as ve:
|
| 771 |
+
raise ValueError(f"Key {key}: {ve}") from None
|
| 772 |
+
self._set(key, cval)
|
| 773 |
+
except KeyError as err:
|
| 774 |
+
raise KeyError(
|
| 775 |
+
f"{key} is not a valid rc parameter (see rcParams.keys() for "
|
| 776 |
+
f"a list of valid parameters)") from err
|
| 777 |
+
|
| 778 |
+
def __getitem__(self, key):
|
| 779 |
+
if key in _deprecated_map:
|
| 780 |
+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
|
| 781 |
+
_api.warn_deprecated(
|
| 782 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 783 |
+
return inverse_alt(self._get(alt_key))
|
| 784 |
+
|
| 785 |
+
elif key in _deprecated_ignore_map:
|
| 786 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 787 |
+
_api.warn_deprecated(
|
| 788 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 789 |
+
return self._get(alt_key) if alt_key else None
|
| 790 |
+
|
| 791 |
+
# In theory, this should only ever be used after the global rcParams
|
| 792 |
+
# has been set up, but better be safe e.g. in presence of breakpoints.
|
| 793 |
+
elif key == "backend" and self is globals().get("rcParams"):
|
| 794 |
+
val = self._get(key)
|
| 795 |
+
if val is rcsetup._auto_backend_sentinel:
|
| 796 |
+
from matplotlib import pyplot as plt
|
| 797 |
+
plt.switch_backend(rcsetup._auto_backend_sentinel)
|
| 798 |
+
|
| 799 |
+
return self._get(key)
|
| 800 |
+
|
| 801 |
+
def _get_backend_or_none(self):
|
| 802 |
+
"""Get the requested backend, if any, without triggering resolution."""
|
| 803 |
+
backend = self._get("backend")
|
| 804 |
+
return None if backend is rcsetup._auto_backend_sentinel else backend
|
| 805 |
+
|
| 806 |
+
def __repr__(self):
|
| 807 |
+
class_name = self.__class__.__name__
|
| 808 |
+
indent = len(class_name) + 1
|
| 809 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 810 |
+
repr_split = pprint.pformat(dict(self), indent=1,
|
| 811 |
+
width=80 - indent).split('\n')
|
| 812 |
+
repr_indented = ('\n' + ' ' * indent).join(repr_split)
|
| 813 |
+
return f'{class_name}({repr_indented})'
|
| 814 |
+
|
| 815 |
+
def __str__(self):
|
| 816 |
+
return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
|
| 817 |
+
|
| 818 |
+
def __iter__(self):
|
| 819 |
+
"""Yield sorted list of keys."""
|
| 820 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 821 |
+
yield from sorted(dict.__iter__(self))
|
| 822 |
+
|
| 823 |
+
def __len__(self):
|
| 824 |
+
return dict.__len__(self)
|
| 825 |
+
|
| 826 |
+
def find_all(self, pattern):
|
| 827 |
+
"""
|
| 828 |
+
Return the subset of this RcParams dictionary whose keys match,
|
| 829 |
+
using :func:`re.search`, the given ``pattern``.
|
| 830 |
+
|
| 831 |
+
.. note::
|
| 832 |
+
|
| 833 |
+
Changes to the returned dictionary are *not* propagated to
|
| 834 |
+
the parent RcParams dictionary.
|
| 835 |
+
|
| 836 |
+
"""
|
| 837 |
+
pattern_re = re.compile(pattern)
|
| 838 |
+
return RcParams((key, value)
|
| 839 |
+
for key, value in self.items()
|
| 840 |
+
if pattern_re.search(key))
|
| 841 |
+
|
| 842 |
+
def copy(self):
|
| 843 |
+
"""Copy this RcParams instance."""
|
| 844 |
+
rccopy = RcParams()
|
| 845 |
+
for k in self: # Skip deprecations and revalidation.
|
| 846 |
+
rccopy._set(k, self._get(k))
|
| 847 |
+
return rccopy
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
def rc_params(fail_on_error=False):
|
| 851 |
+
"""Construct a `RcParams` instance from the default Matplotlib rc file."""
|
| 852 |
+
return rc_params_from_file(matplotlib_fname(), fail_on_error)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
@functools.cache
|
| 856 |
+
def _get_ssl_context():
|
| 857 |
+
try:
|
| 858 |
+
import certifi
|
| 859 |
+
except ImportError:
|
| 860 |
+
_log.debug("Could not import certifi.")
|
| 861 |
+
return None
|
| 862 |
+
import ssl
|
| 863 |
+
return ssl.create_default_context(cafile=certifi.where())
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
@contextlib.contextmanager
|
| 867 |
+
def _open_file_or_url(fname):
|
| 868 |
+
if (isinstance(fname, str)
|
| 869 |
+
and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):
|
| 870 |
+
import urllib.request
|
| 871 |
+
ssl_ctx = _get_ssl_context()
|
| 872 |
+
if ssl_ctx is None:
|
| 873 |
+
_log.debug(
|
| 874 |
+
"Could not get certifi ssl context, https may not work."
|
| 875 |
+
)
|
| 876 |
+
with urllib.request.urlopen(fname, context=ssl_ctx) as f:
|
| 877 |
+
yield (line.decode('utf-8') for line in f)
|
| 878 |
+
else:
|
| 879 |
+
fname = os.path.expanduser(fname)
|
| 880 |
+
with open(fname, encoding='utf-8') as f:
|
| 881 |
+
yield f
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
|
| 885 |
+
"""
|
| 886 |
+
Construct a `RcParams` instance from file *fname*.
|
| 887 |
+
|
| 888 |
+
Unlike `rc_params_from_file`, the configuration class only contains the
|
| 889 |
+
parameters specified in the file (i.e. default values are not filled in).
|
| 890 |
+
|
| 891 |
+
Parameters
|
| 892 |
+
----------
|
| 893 |
+
fname : path-like
|
| 894 |
+
The loaded file.
|
| 895 |
+
transform : callable, default: the identity function
|
| 896 |
+
A function called on each individual line of the file to transform it,
|
| 897 |
+
before further parsing.
|
| 898 |
+
fail_on_error : bool, default: False
|
| 899 |
+
Whether invalid entries should result in an exception or a warning.
|
| 900 |
+
"""
|
| 901 |
+
import matplotlib as mpl
|
| 902 |
+
rc_temp = {}
|
| 903 |
+
with _open_file_or_url(fname) as fd:
|
| 904 |
+
try:
|
| 905 |
+
for line_no, line in enumerate(fd, 1):
|
| 906 |
+
line = transform(line)
|
| 907 |
+
strippedline = cbook._strip_comment(line)
|
| 908 |
+
if not strippedline:
|
| 909 |
+
continue
|
| 910 |
+
tup = strippedline.split(':', 1)
|
| 911 |
+
if len(tup) != 2:
|
| 912 |
+
_log.warning('Missing colon in file %r, line %d (%r)',
|
| 913 |
+
fname, line_no, line.rstrip('\n'))
|
| 914 |
+
continue
|
| 915 |
+
key, val = tup
|
| 916 |
+
key = key.strip()
|
| 917 |
+
val = val.strip()
|
| 918 |
+
if val.startswith('"') and val.endswith('"'):
|
| 919 |
+
val = val[1:-1] # strip double quotes
|
| 920 |
+
if key in rc_temp:
|
| 921 |
+
_log.warning('Duplicate key in file %r, line %d (%r)',
|
| 922 |
+
fname, line_no, line.rstrip('\n'))
|
| 923 |
+
rc_temp[key] = (val, line, line_no)
|
| 924 |
+
except UnicodeDecodeError:
|
| 925 |
+
_log.warning('Cannot decode configuration file %r as utf-8.',
|
| 926 |
+
fname)
|
| 927 |
+
raise
|
| 928 |
+
|
| 929 |
+
config = RcParams()
|
| 930 |
+
|
| 931 |
+
for key, (val, line, line_no) in rc_temp.items():
|
| 932 |
+
if key in rcsetup._validators:
|
| 933 |
+
if fail_on_error:
|
| 934 |
+
config[key] = val # try to convert to proper type or raise
|
| 935 |
+
else:
|
| 936 |
+
try:
|
| 937 |
+
config[key] = val # try to convert to proper type or skip
|
| 938 |
+
except Exception as msg:
|
| 939 |
+
_log.warning('Bad value in file %r, line %d (%r): %s',
|
| 940 |
+
fname, line_no, line.rstrip('\n'), msg)
|
| 941 |
+
elif key in _deprecated_ignore_map:
|
| 942 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 943 |
+
_api.warn_deprecated(
|
| 944 |
+
version, name=key, alternative=alt_key, obj_type='rcparam',
|
| 945 |
+
addendum="Please update your matplotlibrc.")
|
| 946 |
+
else:
|
| 947 |
+
# __version__ must be looked up as an attribute to trigger the
|
| 948 |
+
# module-level __getattr__.
|
| 949 |
+
version = ('main' if '.post' in mpl.__version__
|
| 950 |
+
else f'v{mpl.__version__}')
|
| 951 |
+
_log.warning("""
|
| 952 |
+
Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
|
| 953 |
+
You probably need to get an updated matplotlibrc file from
|
| 954 |
+
https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc
|
| 955 |
+
or from the matplotlib source distribution""",
|
| 956 |
+
dict(key=key, fname=fname, line_no=line_no,
|
| 957 |
+
line=line.rstrip('\n'), version=version))
|
| 958 |
+
return config
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
|
| 962 |
+
"""
|
| 963 |
+
Construct a `RcParams` from file *fname*.
|
| 964 |
+
|
| 965 |
+
Parameters
|
| 966 |
+
----------
|
| 967 |
+
fname : str or path-like
|
| 968 |
+
A file with Matplotlib rc settings.
|
| 969 |
+
fail_on_error : bool
|
| 970 |
+
If True, raise an error when the parser fails to convert a parameter.
|
| 971 |
+
use_default_template : bool
|
| 972 |
+
If True, initialize with default parameters before updating with those
|
| 973 |
+
in the given file. If False, the configuration class only contains the
|
| 974 |
+
parameters specified in the file. (Useful for updating dicts.)
|
| 975 |
+
"""
|
| 976 |
+
config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
|
| 977 |
+
|
| 978 |
+
if not use_default_template:
|
| 979 |
+
return config_from_file
|
| 980 |
+
|
| 981 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 982 |
+
config = RcParams({**rcParamsDefault, **config_from_file})
|
| 983 |
+
|
| 984 |
+
if "".join(config['text.latex.preamble']):
|
| 985 |
+
_log.info("""
|
| 986 |
+
*****************************************************************
|
| 987 |
+
You have the following UNSUPPORTED LaTeX preamble customizations:
|
| 988 |
+
%s
|
| 989 |
+
Please do not ask for support with these customizations active.
|
| 990 |
+
*****************************************************************
|
| 991 |
+
""", '\n'.join(config['text.latex.preamble']))
|
| 992 |
+
_log.debug('loaded rc file %s', fname)
|
| 993 |
+
|
| 994 |
+
return config
|
| 995 |
+
|
| 996 |
+
|
| 997 |
+
rcParamsDefault = _rc_params_in_file(
|
| 998 |
+
cbook._get_data_path("matplotlibrc"),
|
| 999 |
+
# Strip leading comment.
|
| 1000 |
+
transform=lambda line: line[1:] if line.startswith("#") else line,
|
| 1001 |
+
fail_on_error=True)
|
| 1002 |
+
rcParamsDefault._update_raw(rcsetup._hardcoded_defaults)
|
| 1003 |
+
rcParamsDefault._ensure_has_backend()
|
| 1004 |
+
|
| 1005 |
+
rcParams = RcParams() # The global instance.
|
| 1006 |
+
rcParams._update_raw(rcParamsDefault)
|
| 1007 |
+
rcParams._update_raw(_rc_params_in_file(matplotlib_fname()))
|
| 1008 |
+
rcParamsOrig = rcParams.copy()
|
| 1009 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1010 |
+
# This also checks that all rcParams are indeed listed in the template.
|
| 1011 |
+
# Assigning to rcsetup.defaultParams is left only for backcompat.
|
| 1012 |
+
defaultParams = rcsetup.defaultParams = {
|
| 1013 |
+
# We want to resolve deprecated rcParams, but not backend...
|
| 1014 |
+
key: [(rcsetup._auto_backend_sentinel if key == "backend" else
|
| 1015 |
+
rcParamsDefault[key]),
|
| 1016 |
+
validator]
|
| 1017 |
+
for key, validator in rcsetup._validators.items()}
|
| 1018 |
+
if rcParams['axes.formatter.use_locale']:
|
| 1019 |
+
locale.setlocale(locale.LC_ALL, '')
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
def rc(group, **kwargs):
|
| 1023 |
+
"""
|
| 1024 |
+
Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
|
| 1025 |
+
for ``lines.linewidth`` the group is ``lines``, for
|
| 1026 |
+
``axes.facecolor``, the group is ``axes``, and so on. Group may
|
| 1027 |
+
also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
|
| 1028 |
+
*kwargs* is a dictionary attribute name/value pairs, e.g.,::
|
| 1029 |
+
|
| 1030 |
+
rc('lines', linewidth=2, color='r')
|
| 1031 |
+
|
| 1032 |
+
sets the current `.rcParams` and is equivalent to::
|
| 1033 |
+
|
| 1034 |
+
rcParams['lines.linewidth'] = 2
|
| 1035 |
+
rcParams['lines.color'] = 'r'
|
| 1036 |
+
|
| 1037 |
+
The following aliases are available to save typing for interactive users:
|
| 1038 |
+
|
| 1039 |
+
===== =================
|
| 1040 |
+
Alias Property
|
| 1041 |
+
===== =================
|
| 1042 |
+
'lw' 'linewidth'
|
| 1043 |
+
'ls' 'linestyle'
|
| 1044 |
+
'c' 'color'
|
| 1045 |
+
'fc' 'facecolor'
|
| 1046 |
+
'ec' 'edgecolor'
|
| 1047 |
+
'mew' 'markeredgewidth'
|
| 1048 |
+
'aa' 'antialiased'
|
| 1049 |
+
===== =================
|
| 1050 |
+
|
| 1051 |
+
Thus you could abbreviate the above call as::
|
| 1052 |
+
|
| 1053 |
+
rc('lines', lw=2, c='r')
|
| 1054 |
+
|
| 1055 |
+
Note you can use python's kwargs dictionary facility to store
|
| 1056 |
+
dictionaries of default parameters. e.g., you can customize the
|
| 1057 |
+
font rc as follows::
|
| 1058 |
+
|
| 1059 |
+
font = {'family' : 'monospace',
|
| 1060 |
+
'weight' : 'bold',
|
| 1061 |
+
'size' : 'larger'}
|
| 1062 |
+
rc('font', **font) # pass in the font dict as kwargs
|
| 1063 |
+
|
| 1064 |
+
This enables you to easily switch between several configurations. Use
|
| 1065 |
+
``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
|
| 1066 |
+
restore the default `.rcParams` after changes.
|
| 1067 |
+
|
| 1068 |
+
Notes
|
| 1069 |
+
-----
|
| 1070 |
+
Similar functionality is available by using the normal dict interface, i.e.
|
| 1071 |
+
``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
|
| 1072 |
+
does not support abbreviations or grouping).
|
| 1073 |
+
"""
|
| 1074 |
+
|
| 1075 |
+
aliases = {
|
| 1076 |
+
'lw': 'linewidth',
|
| 1077 |
+
'ls': 'linestyle',
|
| 1078 |
+
'c': 'color',
|
| 1079 |
+
'fc': 'facecolor',
|
| 1080 |
+
'ec': 'edgecolor',
|
| 1081 |
+
'mew': 'markeredgewidth',
|
| 1082 |
+
'aa': 'antialiased',
|
| 1083 |
+
}
|
| 1084 |
+
|
| 1085 |
+
if isinstance(group, str):
|
| 1086 |
+
group = (group,)
|
| 1087 |
+
for g in group:
|
| 1088 |
+
for k, v in kwargs.items():
|
| 1089 |
+
name = aliases.get(k) or k
|
| 1090 |
+
key = f'{g}.{name}'
|
| 1091 |
+
try:
|
| 1092 |
+
rcParams[key] = v
|
| 1093 |
+
except KeyError as err:
|
| 1094 |
+
raise KeyError(('Unrecognized key "%s" for group "%s" and '
|
| 1095 |
+
'name "%s"') % (key, g, name)) from err
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
def rcdefaults():
|
| 1099 |
+
"""
|
| 1100 |
+
Restore the `.rcParams` from Matplotlib's internal default style.
|
| 1101 |
+
|
| 1102 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1103 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1104 |
+
|
| 1105 |
+
See Also
|
| 1106 |
+
--------
|
| 1107 |
+
matplotlib.rc_file_defaults
|
| 1108 |
+
Restore the `.rcParams` from the rc file originally loaded by
|
| 1109 |
+
Matplotlib.
|
| 1110 |
+
matplotlib.style.use
|
| 1111 |
+
Use a specific style file. Call ``style.use('default')`` to restore
|
| 1112 |
+
the default style.
|
| 1113 |
+
"""
|
| 1114 |
+
# Deprecation warnings were already handled when creating rcParamsDefault,
|
| 1115 |
+
# no need to reemit them here.
|
| 1116 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1117 |
+
from .style.core import STYLE_BLACKLIST
|
| 1118 |
+
rcParams.clear()
|
| 1119 |
+
rcParams.update({k: v for k, v in rcParamsDefault.items()
|
| 1120 |
+
if k not in STYLE_BLACKLIST})
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
def rc_file_defaults():
|
| 1124 |
+
"""
|
| 1125 |
+
Restore the `.rcParams` from the original rc file loaded by Matplotlib.
|
| 1126 |
+
|
| 1127 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1128 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1129 |
+
"""
|
| 1130 |
+
# Deprecation warnings were already handled when creating rcParamsOrig, no
|
| 1131 |
+
# need to reemit them here.
|
| 1132 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1133 |
+
from .style.core import STYLE_BLACKLIST
|
| 1134 |
+
rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
|
| 1135 |
+
if k not in STYLE_BLACKLIST})
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
def rc_file(fname, *, use_default_template=True):
|
| 1139 |
+
"""
|
| 1140 |
+
Update `.rcParams` from file.
|
| 1141 |
+
|
| 1142 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1143 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1144 |
+
|
| 1145 |
+
Parameters
|
| 1146 |
+
----------
|
| 1147 |
+
fname : str or path-like
|
| 1148 |
+
A file with Matplotlib rc settings.
|
| 1149 |
+
|
| 1150 |
+
use_default_template : bool
|
| 1151 |
+
If True, initialize with default parameters before updating with those
|
| 1152 |
+
in the given file. If False, the current configuration persists
|
| 1153 |
+
and only the parameters specified in the file are updated.
|
| 1154 |
+
"""
|
| 1155 |
+
# Deprecation warnings were already handled in rc_params_from_file, no need
|
| 1156 |
+
# to reemit them here.
|
| 1157 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1158 |
+
from .style.core import STYLE_BLACKLIST
|
| 1159 |
+
rc_from_file = rc_params_from_file(
|
| 1160 |
+
fname, use_default_template=use_default_template)
|
| 1161 |
+
rcParams.update({k: rc_from_file[k] for k in rc_from_file
|
| 1162 |
+
if k not in STYLE_BLACKLIST})
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
@contextlib.contextmanager
|
| 1166 |
+
def rc_context(rc=None, fname=None):
|
| 1167 |
+
"""
|
| 1168 |
+
Return a context manager for temporarily changing rcParams.
|
| 1169 |
+
|
| 1170 |
+
The :rc:`backend` will not be reset by the context manager.
|
| 1171 |
+
|
| 1172 |
+
rcParams changed both through the context manager invocation and
|
| 1173 |
+
in the body of the context will be reset on context exit.
|
| 1174 |
+
|
| 1175 |
+
Parameters
|
| 1176 |
+
----------
|
| 1177 |
+
rc : dict
|
| 1178 |
+
The rcParams to temporarily set.
|
| 1179 |
+
fname : str or path-like
|
| 1180 |
+
A file with Matplotlib rc settings. If both *fname* and *rc* are given,
|
| 1181 |
+
settings from *rc* take precedence.
|
| 1182 |
+
|
| 1183 |
+
See Also
|
| 1184 |
+
--------
|
| 1185 |
+
:ref:`customizing-with-matplotlibrc-files`
|
| 1186 |
+
|
| 1187 |
+
Examples
|
| 1188 |
+
--------
|
| 1189 |
+
Passing explicit values via a dict::
|
| 1190 |
+
|
| 1191 |
+
with mpl.rc_context({'interactive': False}):
|
| 1192 |
+
fig, ax = plt.subplots()
|
| 1193 |
+
ax.plot(range(3), range(3))
|
| 1194 |
+
fig.savefig('example.png')
|
| 1195 |
+
plt.close(fig)
|
| 1196 |
+
|
| 1197 |
+
Loading settings from a file::
|
| 1198 |
+
|
| 1199 |
+
with mpl.rc_context(fname='print.rc'):
|
| 1200 |
+
plt.plot(x, y) # uses 'print.rc'
|
| 1201 |
+
|
| 1202 |
+
Setting in the context body::
|
| 1203 |
+
|
| 1204 |
+
with mpl.rc_context():
|
| 1205 |
+
# will be reset
|
| 1206 |
+
mpl.rcParams['lines.linewidth'] = 5
|
| 1207 |
+
plt.plot(x, y)
|
| 1208 |
+
|
| 1209 |
+
"""
|
| 1210 |
+
orig = dict(rcParams.copy())
|
| 1211 |
+
del orig['backend']
|
| 1212 |
+
try:
|
| 1213 |
+
if fname:
|
| 1214 |
+
rc_file(fname)
|
| 1215 |
+
if rc:
|
| 1216 |
+
rcParams.update(rc)
|
| 1217 |
+
yield
|
| 1218 |
+
finally:
|
| 1219 |
+
rcParams._update_raw(orig) # Revert to the original rcs.
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
def use(backend, *, force=True):
|
| 1223 |
+
"""
|
| 1224 |
+
Select the backend used for rendering and GUI integration.
|
| 1225 |
+
|
| 1226 |
+
If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used
|
| 1227 |
+
and if the new backend is different than the current backend, all Figures
|
| 1228 |
+
will be closed.
|
| 1229 |
+
|
| 1230 |
+
Parameters
|
| 1231 |
+
----------
|
| 1232 |
+
backend : str
|
| 1233 |
+
The backend to switch to. This can either be one of the standard
|
| 1234 |
+
backend names, which are case-insensitive:
|
| 1235 |
+
|
| 1236 |
+
- interactive backends:
|
| 1237 |
+
GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg,
|
| 1238 |
+
QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo
|
| 1239 |
+
|
| 1240 |
+
- non-interactive backends:
|
| 1241 |
+
agg, cairo, pdf, pgf, ps, svg, template
|
| 1242 |
+
|
| 1243 |
+
or a string of the form: ``module://my.module.name``.
|
| 1244 |
+
|
| 1245 |
+
notebook is a synonym for nbAgg.
|
| 1246 |
+
|
| 1247 |
+
Switching to an interactive backend is not possible if an unrelated
|
| 1248 |
+
event loop has already been started (e.g., switching to GTK3Agg if a
|
| 1249 |
+
TkAgg window has already been opened). Switching to a non-interactive
|
| 1250 |
+
backend is always possible.
|
| 1251 |
+
|
| 1252 |
+
force : bool, default: True
|
| 1253 |
+
If True (the default), raise an `ImportError` if the backend cannot be
|
| 1254 |
+
set up (either because it fails to import, or because an incompatible
|
| 1255 |
+
GUI interactive framework is already running); if False, silently
|
| 1256 |
+
ignore the failure.
|
| 1257 |
+
|
| 1258 |
+
See Also
|
| 1259 |
+
--------
|
| 1260 |
+
:ref:`backends`
|
| 1261 |
+
matplotlib.get_backend
|
| 1262 |
+
matplotlib.pyplot.switch_backend
|
| 1263 |
+
|
| 1264 |
+
"""
|
| 1265 |
+
name = rcsetup.validate_backend(backend)
|
| 1266 |
+
# don't (prematurely) resolve the "auto" backend setting
|
| 1267 |
+
if rcParams._get_backend_or_none() == name:
|
| 1268 |
+
# Nothing to do if the requested backend is already set
|
| 1269 |
+
pass
|
| 1270 |
+
else:
|
| 1271 |
+
# if pyplot is not already imported, do not import it. Doing
|
| 1272 |
+
# so may trigger a `plt.switch_backend` to the _default_ backend
|
| 1273 |
+
# before we get a chance to change to the one the user just requested
|
| 1274 |
+
plt = sys.modules.get('matplotlib.pyplot')
|
| 1275 |
+
# if pyplot is imported, then try to change backends
|
| 1276 |
+
if plt is not None:
|
| 1277 |
+
try:
|
| 1278 |
+
# we need this import check here to re-raise if the
|
| 1279 |
+
# user does not have the libraries to support their
|
| 1280 |
+
# chosen backend installed.
|
| 1281 |
+
plt.switch_backend(name)
|
| 1282 |
+
except ImportError:
|
| 1283 |
+
if force:
|
| 1284 |
+
raise
|
| 1285 |
+
# if we have not imported pyplot, then we can set the rcParam
|
| 1286 |
+
# value which will be respected when the user finally imports
|
| 1287 |
+
# pyplot
|
| 1288 |
+
else:
|
| 1289 |
+
rcParams['backend'] = backend
|
| 1290 |
+
# if the user has asked for a given backend, do not helpfully
|
| 1291 |
+
# fallback
|
| 1292 |
+
rcParams['backend_fallback'] = False
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
if os.environ.get('MPLBACKEND'):
|
| 1296 |
+
rcParams['backend'] = os.environ.get('MPLBACKEND')
|
| 1297 |
+
|
| 1298 |
+
|
| 1299 |
+
def get_backend(*, auto_select=True):
|
| 1300 |
+
"""
|
| 1301 |
+
Return the name of the current backend.
|
| 1302 |
+
|
| 1303 |
+
Parameters
|
| 1304 |
+
----------
|
| 1305 |
+
auto_select : bool, default: True
|
| 1306 |
+
Whether to trigger backend resolution if no backend has been
|
| 1307 |
+
selected so far. If True, this ensures that a valid backend
|
| 1308 |
+
is returned. If False, this returns None if no backend has been
|
| 1309 |
+
selected so far.
|
| 1310 |
+
|
| 1311 |
+
.. versionadded:: 3.10
|
| 1312 |
+
|
| 1313 |
+
.. admonition:: Provisional
|
| 1314 |
+
|
| 1315 |
+
The *auto_select* flag is provisional. It may be changed or removed
|
| 1316 |
+
without prior warning.
|
| 1317 |
+
|
| 1318 |
+
See Also
|
| 1319 |
+
--------
|
| 1320 |
+
matplotlib.use
|
| 1321 |
+
"""
|
| 1322 |
+
if auto_select:
|
| 1323 |
+
return rcParams['backend']
|
| 1324 |
+
else:
|
| 1325 |
+
backend = rcParams._get('backend')
|
| 1326 |
+
if backend is rcsetup._auto_backend_sentinel:
|
| 1327 |
+
return None
|
| 1328 |
+
else:
|
| 1329 |
+
return backend
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
def interactive(b):
|
| 1333 |
+
"""
|
| 1334 |
+
Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).
|
| 1335 |
+
"""
|
| 1336 |
+
rcParams['interactive'] = b
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
def is_interactive():
|
| 1340 |
+
"""
|
| 1341 |
+
Return whether to redraw after every plotting command.
|
| 1342 |
+
|
| 1343 |
+
.. note::
|
| 1344 |
+
|
| 1345 |
+
This function is only intended for use in backends. End users should
|
| 1346 |
+
use `.pyplot.isinteractive` instead.
|
| 1347 |
+
"""
|
| 1348 |
+
return rcParams['interactive']
|
| 1349 |
+
|
| 1350 |
+
|
| 1351 |
+
def _val_or_rc(val, rc_name):
|
| 1352 |
+
"""
|
| 1353 |
+
If *val* is None, return ``mpl.rcParams[rc_name]``, otherwise return val.
|
| 1354 |
+
"""
|
| 1355 |
+
return val if val is not None else rcParams[rc_name]
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def _init_tests():
|
| 1359 |
+
# The version of FreeType to install locally for running the tests. This must match
|
| 1360 |
+
# the value in `meson.build`.
|
| 1361 |
+
LOCAL_FREETYPE_VERSION = '2.6.1'
|
| 1362 |
+
|
| 1363 |
+
from matplotlib import ft2font
|
| 1364 |
+
if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
|
| 1365 |
+
ft2font.__freetype_build_type__ != 'local'):
|
| 1366 |
+
_log.warning(
|
| 1367 |
+
"Matplotlib is not built with the correct FreeType version to run tests. "
|
| 1368 |
+
"Rebuild without setting system-freetype=true in Meson setup options. "
|
| 1369 |
+
"Expect many image comparison failures below. "
|
| 1370 |
+
"Expected freetype version %s. "
|
| 1371 |
+
"Found freetype version %s. "
|
| 1372 |
+
"Freetype build type is %slocal.",
|
| 1373 |
+
LOCAL_FREETYPE_VERSION,
|
| 1374 |
+
ft2font.__freetype_version__,
|
| 1375 |
+
"" if ft2font.__freetype_build_type__ == 'local' else "not ")
|
| 1376 |
+
|
| 1377 |
+
|
| 1378 |
+
def _replacer(data, value):
|
| 1379 |
+
"""
|
| 1380 |
+
Either returns ``data[value]`` or passes ``data`` back, converts either to
|
| 1381 |
+
a sequence.
|
| 1382 |
+
"""
|
| 1383 |
+
try:
|
| 1384 |
+
# if key isn't a string don't bother
|
| 1385 |
+
if isinstance(value, str):
|
| 1386 |
+
# try to use __getitem__
|
| 1387 |
+
value = data[value]
|
| 1388 |
+
except Exception:
|
| 1389 |
+
# key does not exist, silently fall back to key
|
| 1390 |
+
pass
|
| 1391 |
+
return cbook.sanitize_sequence(value)
|
| 1392 |
+
|
| 1393 |
+
|
| 1394 |
+
def _label_from_arg(y, default_name):
|
| 1395 |
+
try:
|
| 1396 |
+
return y.name
|
| 1397 |
+
except AttributeError:
|
| 1398 |
+
if isinstance(default_name, str):
|
| 1399 |
+
return default_name
|
| 1400 |
+
return None
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
def _add_data_doc(docstring, replace_names):
|
| 1404 |
+
"""
|
| 1405 |
+
Add documentation for a *data* field to the given docstring.
|
| 1406 |
+
|
| 1407 |
+
Parameters
|
| 1408 |
+
----------
|
| 1409 |
+
docstring : str
|
| 1410 |
+
The input docstring.
|
| 1411 |
+
replace_names : list of str or None
|
| 1412 |
+
The list of parameter names which arguments should be replaced by
|
| 1413 |
+
``data[name]`` (if ``data[name]`` does not throw an exception). If
|
| 1414 |
+
None, replacement is attempted for all arguments.
|
| 1415 |
+
|
| 1416 |
+
Returns
|
| 1417 |
+
-------
|
| 1418 |
+
str
|
| 1419 |
+
The augmented docstring.
|
| 1420 |
+
"""
|
| 1421 |
+
if (docstring is None
|
| 1422 |
+
or replace_names is not None and len(replace_names) == 0):
|
| 1423 |
+
return docstring
|
| 1424 |
+
docstring = inspect.cleandoc(docstring)
|
| 1425 |
+
|
| 1426 |
+
data_doc = ("""\
|
| 1427 |
+
If given, all parameters also accept a string ``s``, which is
|
| 1428 |
+
interpreted as ``data[s]`` if ``s`` is a key in ``data``."""
|
| 1429 |
+
if replace_names is None else f"""\
|
| 1430 |
+
If given, the following parameters also accept a string ``s``, which is
|
| 1431 |
+
interpreted as ``data[s]`` if ``s`` is a key in ``data``:
|
| 1432 |
+
|
| 1433 |
+
{', '.join(map('*{}*'.format, replace_names))}""")
|
| 1434 |
+
# using string replacement instead of formatting has the advantages
|
| 1435 |
+
# 1) simpler indent handling
|
| 1436 |
+
# 2) prevent problems with formatting characters '{', '%' in the docstring
|
| 1437 |
+
if _log.level <= logging.DEBUG:
|
| 1438 |
+
# test_data_parameter_replacement() tests against these log messages
|
| 1439 |
+
# make sure to keep message and test in sync
|
| 1440 |
+
if "data : indexable object, optional" not in docstring:
|
| 1441 |
+
_log.debug("data parameter docstring error: no data parameter")
|
| 1442 |
+
if 'DATA_PARAMETER_PLACEHOLDER' not in docstring:
|
| 1443 |
+
_log.debug("data parameter docstring error: missing placeholder")
|
| 1444 |
+
return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc)
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
|
| 1448 |
+
"""
|
| 1449 |
+
A decorator to add a 'data' kwarg to a function.
|
| 1450 |
+
|
| 1451 |
+
When applied::
|
| 1452 |
+
|
| 1453 |
+
@_preprocess_data()
|
| 1454 |
+
def func(ax, *args, **kwargs): ...
|
| 1455 |
+
|
| 1456 |
+
the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``
|
| 1457 |
+
with the following behavior:
|
| 1458 |
+
|
| 1459 |
+
- if called with ``data=None``, forward the other arguments to ``func``;
|
| 1460 |
+
- otherwise, *data* must be a mapping; for any argument passed in as a
|
| 1461 |
+
string ``name``, replace the argument by ``data[name]`` (if this does not
|
| 1462 |
+
throw an exception), then forward the arguments to ``func``.
|
| 1463 |
+
|
| 1464 |
+
In either case, any argument that is a `MappingView` is also converted to a
|
| 1465 |
+
list.
|
| 1466 |
+
|
| 1467 |
+
Parameters
|
| 1468 |
+
----------
|
| 1469 |
+
replace_names : list of str or None, default: None
|
| 1470 |
+
The list of parameter names for which lookup into *data* should be
|
| 1471 |
+
attempted. If None, replacement is attempted for all arguments.
|
| 1472 |
+
label_namer : str, default: None
|
| 1473 |
+
If set e.g. to "namer" (which must be a kwarg in the function's
|
| 1474 |
+
signature -- not as ``**kwargs``), if the *namer* argument passed in is
|
| 1475 |
+
a (string) key of *data* and no *label* kwarg is passed, then use the
|
| 1476 |
+
(string) value of the *namer* as *label*. ::
|
| 1477 |
+
|
| 1478 |
+
@_preprocess_data(label_namer="foo")
|
| 1479 |
+
def func(foo, label=None): ...
|
| 1480 |
+
|
| 1481 |
+
func("key", data={"key": value})
|
| 1482 |
+
# is equivalent to
|
| 1483 |
+
func.__wrapped__(value, label="key")
|
| 1484 |
+
"""
|
| 1485 |
+
|
| 1486 |
+
if func is None: # Return the actual decorator.
|
| 1487 |
+
return functools.partial(
|
| 1488 |
+
_preprocess_data,
|
| 1489 |
+
replace_names=replace_names, label_namer=label_namer)
|
| 1490 |
+
|
| 1491 |
+
sig = inspect.signature(func)
|
| 1492 |
+
varargs_name = None
|
| 1493 |
+
varkwargs_name = None
|
| 1494 |
+
arg_names = []
|
| 1495 |
+
params = list(sig.parameters.values())
|
| 1496 |
+
for p in params:
|
| 1497 |
+
if p.kind is Parameter.VAR_POSITIONAL:
|
| 1498 |
+
varargs_name = p.name
|
| 1499 |
+
elif p.kind is Parameter.VAR_KEYWORD:
|
| 1500 |
+
varkwargs_name = p.name
|
| 1501 |
+
else:
|
| 1502 |
+
arg_names.append(p.name)
|
| 1503 |
+
data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
|
| 1504 |
+
if varkwargs_name:
|
| 1505 |
+
params.insert(-1, data_param)
|
| 1506 |
+
else:
|
| 1507 |
+
params.append(data_param)
|
| 1508 |
+
new_sig = sig.replace(parameters=params)
|
| 1509 |
+
arg_names = arg_names[1:] # remove the first "ax" / self arg
|
| 1510 |
+
|
| 1511 |
+
assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
|
| 1512 |
+
"Matplotlib internal error: invalid replace_names "
|
| 1513 |
+
f"({replace_names!r}) for {func.__name__!r}")
|
| 1514 |
+
assert label_namer is None or label_namer in arg_names, (
|
| 1515 |
+
"Matplotlib internal error: invalid label_namer "
|
| 1516 |
+
f"({label_namer!r}) for {func.__name__!r}")
|
| 1517 |
+
|
| 1518 |
+
@functools.wraps(func)
|
| 1519 |
+
def inner(ax, *args, data=None, **kwargs):
|
| 1520 |
+
if data is None:
|
| 1521 |
+
return func(
|
| 1522 |
+
ax,
|
| 1523 |
+
*map(cbook.sanitize_sequence, args),
|
| 1524 |
+
**{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
|
| 1525 |
+
|
| 1526 |
+
bound = new_sig.bind(ax, *args, **kwargs)
|
| 1527 |
+
auto_label = (bound.arguments.get(label_namer)
|
| 1528 |
+
or bound.kwargs.get(label_namer))
|
| 1529 |
+
|
| 1530 |
+
for k, v in bound.arguments.items():
|
| 1531 |
+
if k == varkwargs_name:
|
| 1532 |
+
for k1, v1 in v.items():
|
| 1533 |
+
if replace_names is None or k1 in replace_names:
|
| 1534 |
+
v[k1] = _replacer(data, v1)
|
| 1535 |
+
elif k == varargs_name:
|
| 1536 |
+
if replace_names is None:
|
| 1537 |
+
bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
|
| 1538 |
+
else:
|
| 1539 |
+
if replace_names is None or k in replace_names:
|
| 1540 |
+
bound.arguments[k] = _replacer(data, v)
|
| 1541 |
+
|
| 1542 |
+
new_args = bound.args
|
| 1543 |
+
new_kwargs = bound.kwargs
|
| 1544 |
+
|
| 1545 |
+
args_and_kwargs = {**bound.arguments, **bound.kwargs}
|
| 1546 |
+
if label_namer and "label" not in args_and_kwargs:
|
| 1547 |
+
new_kwargs["label"] = _label_from_arg(
|
| 1548 |
+
args_and_kwargs.get(label_namer), auto_label)
|
| 1549 |
+
|
| 1550 |
+
return func(*new_args, **new_kwargs)
|
| 1551 |
+
|
| 1552 |
+
inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
|
| 1553 |
+
inner.__signature__ = new_sig
|
| 1554 |
+
return inner
|
| 1555 |
+
|
| 1556 |
+
|
| 1557 |
+
_log.debug('interactive is %s', is_interactive())
|
| 1558 |
+
_log.debug('platform is %s', sys.platform)
|
| 1559 |
+
|
| 1560 |
+
|
| 1561 |
+
@_api.deprecated("3.10", alternative="matplotlib.cbook.sanitize_sequence")
|
| 1562 |
+
def sanitize_sequence(data):
|
| 1563 |
+
return cbook.sanitize_sequence(data)
|
| 1564 |
+
|
| 1565 |
+
|
| 1566 |
+
@_api.deprecated("3.10", alternative="matplotlib.rcsetup.validate_backend")
|
| 1567 |
+
def validate_backend(s):
|
| 1568 |
+
return rcsetup.validate_backend(s)
|
| 1569 |
+
|
| 1570 |
+
|
| 1571 |
+
# workaround: we must defer colormaps import to after loading rcParams, because
|
| 1572 |
+
# colormap creation depends on rcParams
|
| 1573 |
+
from matplotlib.cm import _colormaps as colormaps # noqa: E402
|
| 1574 |
+
from matplotlib.cm import _multivar_colormaps as multivar_colormaps # noqa: E402
|
| 1575 |
+
from matplotlib.cm import _bivar_colormaps as bivar_colormaps # noqa: E402
|
| 1576 |
+
from matplotlib.colors import _color_sequences as color_sequences # noqa: E402
|
moondream/lib/python3.10/site-packages/matplotlib/_afm.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A python interface to Adobe Font Metrics Files.
|
| 3 |
+
|
| 4 |
+
Although a number of other Python implementations exist, and may be more
|
| 5 |
+
complete than this, it was decided not to go with them because they were
|
| 6 |
+
either:
|
| 7 |
+
|
| 8 |
+
1) copyrighted or used a non-BSD compatible license
|
| 9 |
+
2) had too many dependencies and a free standing lib was needed
|
| 10 |
+
3) did more than needed and it was easier to write afresh rather than
|
| 11 |
+
figure out how to get just what was needed.
|
| 12 |
+
|
| 13 |
+
It is pretty easy to use, and has no external dependencies:
|
| 14 |
+
|
| 15 |
+
>>> import matplotlib as mpl
|
| 16 |
+
>>> from pathlib import Path
|
| 17 |
+
>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm')
|
| 18 |
+
>>>
|
| 19 |
+
>>> from matplotlib.afm import AFM
|
| 20 |
+
>>> with afm_path.open('rb') as fh:
|
| 21 |
+
... afm = AFM(fh)
|
| 22 |
+
>>> afm.string_width_height('What the heck?')
|
| 23 |
+
(6220.0, 694)
|
| 24 |
+
>>> afm.get_fontname()
|
| 25 |
+
'Times-Roman'
|
| 26 |
+
>>> afm.get_kern_dist('A', 'f')
|
| 27 |
+
0
|
| 28 |
+
>>> afm.get_kern_dist('A', 'y')
|
| 29 |
+
-92.0
|
| 30 |
+
>>> afm.get_bbox_char('!')
|
| 31 |
+
[130, -9, 238, 676]
|
| 32 |
+
|
| 33 |
+
As in the Adobe Font Metrics File Format Specification, all dimensions
|
| 34 |
+
are given in units of 1/1000 of the scale factor (point size) of the font
|
| 35 |
+
being used.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from collections import namedtuple
|
| 39 |
+
import logging
|
| 40 |
+
import re
|
| 41 |
+
|
| 42 |
+
from ._mathtext_data import uni2type1
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
_log = logging.getLogger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _to_int(x):
|
| 49 |
+
# Some AFM files have floats where we are expecting ints -- there is
|
| 50 |
+
# probably a better way to handle this (support floats, round rather than
|
| 51 |
+
# truncate). But I don't know what the best approach is now and this
|
| 52 |
+
# change to _to_int should at least prevent Matplotlib from crashing on
|
| 53 |
+
# these. JDH (2009-11-06)
|
| 54 |
+
return int(float(x))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _to_float(x):
|
| 58 |
+
# Some AFM files use "," instead of "." as decimal separator -- this
|
| 59 |
+
# shouldn't be ambiguous (unless someone is wicked enough to use "," as
|
| 60 |
+
# thousands separator...).
|
| 61 |
+
if isinstance(x, bytes):
|
| 62 |
+
# Encoding doesn't really matter -- if we have codepoints >127 the call
|
| 63 |
+
# to float() will error anyways.
|
| 64 |
+
x = x.decode('latin-1')
|
| 65 |
+
return float(x.replace(',', '.'))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _to_str(x):
|
| 69 |
+
return x.decode('utf8')
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _to_list_of_ints(s):
|
| 73 |
+
s = s.replace(b',', b' ')
|
| 74 |
+
return [_to_int(val) for val in s.split()]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _to_list_of_floats(s):
|
| 78 |
+
return [_to_float(val) for val in s.split()]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _to_bool(s):
|
| 82 |
+
if s.lower().strip() in (b'false', b'0', b'no'):
|
| 83 |
+
return False
|
| 84 |
+
else:
|
| 85 |
+
return True
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _parse_header(fh):
|
| 89 |
+
"""
|
| 90 |
+
Read the font metrics header (up to the char metrics) and returns
|
| 91 |
+
a dictionary mapping *key* to *val*. *val* will be converted to the
|
| 92 |
+
appropriate python type as necessary; e.g.:
|
| 93 |
+
|
| 94 |
+
* 'False'->False
|
| 95 |
+
* '0'->0
|
| 96 |
+
* '-168 -218 1000 898'-> [-168, -218, 1000, 898]
|
| 97 |
+
|
| 98 |
+
Dictionary keys are
|
| 99 |
+
|
| 100 |
+
StartFontMetrics, FontName, FullName, FamilyName, Weight,
|
| 101 |
+
ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
|
| 102 |
+
UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
|
| 103 |
+
XHeight, Ascender, Descender, StartCharMetrics
|
| 104 |
+
"""
|
| 105 |
+
header_converters = {
|
| 106 |
+
b'StartFontMetrics': _to_float,
|
| 107 |
+
b'FontName': _to_str,
|
| 108 |
+
b'FullName': _to_str,
|
| 109 |
+
b'FamilyName': _to_str,
|
| 110 |
+
b'Weight': _to_str,
|
| 111 |
+
b'ItalicAngle': _to_float,
|
| 112 |
+
b'IsFixedPitch': _to_bool,
|
| 113 |
+
b'FontBBox': _to_list_of_ints,
|
| 114 |
+
b'UnderlinePosition': _to_float,
|
| 115 |
+
b'UnderlineThickness': _to_float,
|
| 116 |
+
b'Version': _to_str,
|
| 117 |
+
# Some AFM files have non-ASCII characters (which are not allowed by
|
| 118 |
+
# the spec). Given that there is actually no public API to even access
|
| 119 |
+
# this field, just return it as straight bytes.
|
| 120 |
+
b'Notice': lambda x: x,
|
| 121 |
+
b'EncodingScheme': _to_str,
|
| 122 |
+
b'CapHeight': _to_float, # Is the second version a mistake, or
|
| 123 |
+
b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS
|
| 124 |
+
b'XHeight': _to_float,
|
| 125 |
+
b'Ascender': _to_float,
|
| 126 |
+
b'Descender': _to_float,
|
| 127 |
+
b'StdHW': _to_float,
|
| 128 |
+
b'StdVW': _to_float,
|
| 129 |
+
b'StartCharMetrics': _to_int,
|
| 130 |
+
b'CharacterSet': _to_str,
|
| 131 |
+
b'Characters': _to_int,
|
| 132 |
+
}
|
| 133 |
+
d = {}
|
| 134 |
+
first_line = True
|
| 135 |
+
for line in fh:
|
| 136 |
+
line = line.rstrip()
|
| 137 |
+
if line.startswith(b'Comment'):
|
| 138 |
+
continue
|
| 139 |
+
lst = line.split(b' ', 1)
|
| 140 |
+
key = lst[0]
|
| 141 |
+
if first_line:
|
| 142 |
+
# AFM spec, Section 4: The StartFontMetrics keyword
|
| 143 |
+
# [followed by a version number] must be the first line in
|
| 144 |
+
# the file, and the EndFontMetrics keyword must be the
|
| 145 |
+
# last non-empty line in the file. We just check the
|
| 146 |
+
# first header entry.
|
| 147 |
+
if key != b'StartFontMetrics':
|
| 148 |
+
raise RuntimeError('Not an AFM file')
|
| 149 |
+
first_line = False
|
| 150 |
+
if len(lst) == 2:
|
| 151 |
+
val = lst[1]
|
| 152 |
+
else:
|
| 153 |
+
val = b''
|
| 154 |
+
try:
|
| 155 |
+
converter = header_converters[key]
|
| 156 |
+
except KeyError:
|
| 157 |
+
_log.error("Found an unknown keyword in AFM header (was %r)", key)
|
| 158 |
+
continue
|
| 159 |
+
try:
|
| 160 |
+
d[key] = converter(val)
|
| 161 |
+
except ValueError:
|
| 162 |
+
_log.error('Value error parsing header in AFM: %s, %s', key, val)
|
| 163 |
+
continue
|
| 164 |
+
if key == b'StartCharMetrics':
|
| 165 |
+
break
|
| 166 |
+
else:
|
| 167 |
+
raise RuntimeError('Bad parse')
|
| 168 |
+
return d
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
CharMetrics = namedtuple('CharMetrics', 'width, name, bbox')
|
| 172 |
+
CharMetrics.__doc__ = """
|
| 173 |
+
Represents the character metrics of a single character.
|
| 174 |
+
|
| 175 |
+
Notes
|
| 176 |
+
-----
|
| 177 |
+
The fields do currently only describe a subset of character metrics
|
| 178 |
+
information defined in the AFM standard.
|
| 179 |
+
"""
|
| 180 |
+
CharMetrics.width.__doc__ = """The character width (WX)."""
|
| 181 |
+
CharMetrics.name.__doc__ = """The character name (N)."""
|
| 182 |
+
CharMetrics.bbox.__doc__ = """
|
| 183 |
+
The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*)."""
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _parse_char_metrics(fh):
|
| 187 |
+
"""
|
| 188 |
+
Parse the given filehandle for character metrics information and return
|
| 189 |
+
the information as dicts.
|
| 190 |
+
|
| 191 |
+
It is assumed that the file cursor is on the line behind
|
| 192 |
+
'StartCharMetrics'.
|
| 193 |
+
|
| 194 |
+
Returns
|
| 195 |
+
-------
|
| 196 |
+
ascii_d : dict
|
| 197 |
+
A mapping "ASCII num of the character" to `.CharMetrics`.
|
| 198 |
+
name_d : dict
|
| 199 |
+
A mapping "character name" to `.CharMetrics`.
|
| 200 |
+
|
| 201 |
+
Notes
|
| 202 |
+
-----
|
| 203 |
+
This function is incomplete per the standard, but thus far parses
|
| 204 |
+
all the sample afm files tried.
|
| 205 |
+
"""
|
| 206 |
+
required_keys = {'C', 'WX', 'N', 'B'}
|
| 207 |
+
|
| 208 |
+
ascii_d = {}
|
| 209 |
+
name_d = {}
|
| 210 |
+
for line in fh:
|
| 211 |
+
# We are defensively letting values be utf8. The spec requires
|
| 212 |
+
# ascii, but there are non-compliant fonts in circulation
|
| 213 |
+
line = _to_str(line.rstrip()) # Convert from byte-literal
|
| 214 |
+
if line.startswith('EndCharMetrics'):
|
| 215 |
+
return ascii_d, name_d
|
| 216 |
+
# Split the metric line into a dictionary, keyed by metric identifiers
|
| 217 |
+
vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s)
|
| 218 |
+
# There may be other metrics present, but only these are needed
|
| 219 |
+
if not required_keys.issubset(vals):
|
| 220 |
+
raise RuntimeError('Bad char metrics line: %s' % line)
|
| 221 |
+
num = _to_int(vals['C'])
|
| 222 |
+
wx = _to_float(vals['WX'])
|
| 223 |
+
name = vals['N']
|
| 224 |
+
bbox = _to_list_of_floats(vals['B'])
|
| 225 |
+
bbox = list(map(int, bbox))
|
| 226 |
+
metrics = CharMetrics(wx, name, bbox)
|
| 227 |
+
# Workaround: If the character name is 'Euro', give it the
|
| 228 |
+
# corresponding character code, according to WinAnsiEncoding (see PDF
|
| 229 |
+
# Reference).
|
| 230 |
+
if name == 'Euro':
|
| 231 |
+
num = 128
|
| 232 |
+
elif name == 'minus':
|
| 233 |
+
num = ord("\N{MINUS SIGN}") # 0x2212
|
| 234 |
+
if num != -1:
|
| 235 |
+
ascii_d[num] = metrics
|
| 236 |
+
name_d[name] = metrics
|
| 237 |
+
raise RuntimeError('Bad parse')
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _parse_kern_pairs(fh):
|
| 241 |
+
"""
|
| 242 |
+
Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
|
| 243 |
+
values are the kern pair value. For example, a kern pairs line like
|
| 244 |
+
``KPX A y -50``
|
| 245 |
+
|
| 246 |
+
will be represented as::
|
| 247 |
+
|
| 248 |
+
d[ ('A', 'y') ] = -50
|
| 249 |
+
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
line = next(fh)
|
| 253 |
+
if not line.startswith(b'StartKernPairs'):
|
| 254 |
+
raise RuntimeError('Bad start of kern pairs data: %s' % line)
|
| 255 |
+
|
| 256 |
+
d = {}
|
| 257 |
+
for line in fh:
|
| 258 |
+
line = line.rstrip()
|
| 259 |
+
if not line:
|
| 260 |
+
continue
|
| 261 |
+
if line.startswith(b'EndKernPairs'):
|
| 262 |
+
next(fh) # EndKernData
|
| 263 |
+
return d
|
| 264 |
+
vals = line.split()
|
| 265 |
+
if len(vals) != 4 or vals[0] != b'KPX':
|
| 266 |
+
raise RuntimeError('Bad kern pairs line: %s' % line)
|
| 267 |
+
c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3])
|
| 268 |
+
d[(c1, c2)] = val
|
| 269 |
+
raise RuntimeError('Bad kern pairs parse')
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
CompositePart = namedtuple('CompositePart', 'name, dx, dy')
|
| 273 |
+
CompositePart.__doc__ = """
|
| 274 |
+
Represents the information on a composite element of a composite char."""
|
| 275 |
+
CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'."""
|
| 276 |
+
CompositePart.dx.__doc__ = """x-displacement of the part from the origin."""
|
| 277 |
+
CompositePart.dy.__doc__ = """y-displacement of the part from the origin."""
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _parse_composites(fh):
|
| 281 |
+
"""
|
| 282 |
+
Parse the given filehandle for composites information return them as a
|
| 283 |
+
dict.
|
| 284 |
+
|
| 285 |
+
It is assumed that the file cursor is on the line behind 'StartComposites'.
|
| 286 |
+
|
| 287 |
+
Returns
|
| 288 |
+
-------
|
| 289 |
+
dict
|
| 290 |
+
A dict mapping composite character names to a parts list. The parts
|
| 291 |
+
list is a list of `.CompositePart` entries describing the parts of
|
| 292 |
+
the composite.
|
| 293 |
+
|
| 294 |
+
Examples
|
| 295 |
+
--------
|
| 296 |
+
A composite definition line::
|
| 297 |
+
|
| 298 |
+
CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
|
| 299 |
+
|
| 300 |
+
will be represented as::
|
| 301 |
+
|
| 302 |
+
composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
|
| 303 |
+
CompositePart(name='acute', dx=160, dy=170)]
|
| 304 |
+
|
| 305 |
+
"""
|
| 306 |
+
composites = {}
|
| 307 |
+
for line in fh:
|
| 308 |
+
line = line.rstrip()
|
| 309 |
+
if not line:
|
| 310 |
+
continue
|
| 311 |
+
if line.startswith(b'EndComposites'):
|
| 312 |
+
return composites
|
| 313 |
+
vals = line.split(b';')
|
| 314 |
+
cc = vals[0].split()
|
| 315 |
+
name, _num_parts = cc[1], _to_int(cc[2])
|
| 316 |
+
pccParts = []
|
| 317 |
+
for s in vals[1:-1]:
|
| 318 |
+
pcc = s.split()
|
| 319 |
+
part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3]))
|
| 320 |
+
pccParts.append(part)
|
| 321 |
+
composites[name] = pccParts
|
| 322 |
+
|
| 323 |
+
raise RuntimeError('Bad composites parse')
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _parse_optional(fh):
|
| 327 |
+
"""
|
| 328 |
+
Parse the optional fields for kern pair data and composites.
|
| 329 |
+
|
| 330 |
+
Returns
|
| 331 |
+
-------
|
| 332 |
+
kern_data : dict
|
| 333 |
+
A dict containing kerning information. May be empty.
|
| 334 |
+
See `._parse_kern_pairs`.
|
| 335 |
+
composites : dict
|
| 336 |
+
A dict containing composite information. May be empty.
|
| 337 |
+
See `._parse_composites`.
|
| 338 |
+
"""
|
| 339 |
+
optional = {
|
| 340 |
+
b'StartKernData': _parse_kern_pairs,
|
| 341 |
+
b'StartComposites': _parse_composites,
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
d = {b'StartKernData': {},
|
| 345 |
+
b'StartComposites': {}}
|
| 346 |
+
for line in fh:
|
| 347 |
+
line = line.rstrip()
|
| 348 |
+
if not line:
|
| 349 |
+
continue
|
| 350 |
+
key = line.split()[0]
|
| 351 |
+
|
| 352 |
+
if key in optional:
|
| 353 |
+
d[key] = optional[key](fh)
|
| 354 |
+
|
| 355 |
+
return d[b'StartKernData'], d[b'StartComposites']
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class AFM:
|
| 359 |
+
|
| 360 |
+
def __init__(self, fh):
|
| 361 |
+
"""Parse the AFM file in file object *fh*."""
|
| 362 |
+
self._header = _parse_header(fh)
|
| 363 |
+
self._metrics, self._metrics_by_name = _parse_char_metrics(fh)
|
| 364 |
+
self._kern, self._composite = _parse_optional(fh)
|
| 365 |
+
|
| 366 |
+
def get_bbox_char(self, c, isord=False):
|
| 367 |
+
if not isord:
|
| 368 |
+
c = ord(c)
|
| 369 |
+
return self._metrics[c].bbox
|
| 370 |
+
|
| 371 |
+
def string_width_height(self, s):
|
| 372 |
+
"""
|
| 373 |
+
Return the string width (including kerning) and string height
|
| 374 |
+
as a (*w*, *h*) tuple.
|
| 375 |
+
"""
|
| 376 |
+
if not len(s):
|
| 377 |
+
return 0, 0
|
| 378 |
+
total_width = 0
|
| 379 |
+
namelast = None
|
| 380 |
+
miny = 1e9
|
| 381 |
+
maxy = 0
|
| 382 |
+
for c in s:
|
| 383 |
+
if c == '\n':
|
| 384 |
+
continue
|
| 385 |
+
wx, name, bbox = self._metrics[ord(c)]
|
| 386 |
+
|
| 387 |
+
total_width += wx + self._kern.get((namelast, name), 0)
|
| 388 |
+
l, b, w, h = bbox
|
| 389 |
+
miny = min(miny, b)
|
| 390 |
+
maxy = max(maxy, b + h)
|
| 391 |
+
|
| 392 |
+
namelast = name
|
| 393 |
+
|
| 394 |
+
return total_width, maxy - miny
|
| 395 |
+
|
| 396 |
+
def get_str_bbox_and_descent(self, s):
|
| 397 |
+
"""Return the string bounding box and the maximal descent."""
|
| 398 |
+
if not len(s):
|
| 399 |
+
return 0, 0, 0, 0, 0
|
| 400 |
+
total_width = 0
|
| 401 |
+
namelast = None
|
| 402 |
+
miny = 1e9
|
| 403 |
+
maxy = 0
|
| 404 |
+
left = 0
|
| 405 |
+
if not isinstance(s, str):
|
| 406 |
+
s = _to_str(s)
|
| 407 |
+
for c in s:
|
| 408 |
+
if c == '\n':
|
| 409 |
+
continue
|
| 410 |
+
name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
|
| 411 |
+
try:
|
| 412 |
+
wx, _, bbox = self._metrics_by_name[name]
|
| 413 |
+
except KeyError:
|
| 414 |
+
name = 'question'
|
| 415 |
+
wx, _, bbox = self._metrics_by_name[name]
|
| 416 |
+
total_width += wx + self._kern.get((namelast, name), 0)
|
| 417 |
+
l, b, w, h = bbox
|
| 418 |
+
left = min(left, l)
|
| 419 |
+
miny = min(miny, b)
|
| 420 |
+
maxy = max(maxy, b + h)
|
| 421 |
+
|
| 422 |
+
namelast = name
|
| 423 |
+
|
| 424 |
+
return left, miny, total_width, maxy - miny, -miny
|
| 425 |
+
|
| 426 |
+
def get_str_bbox(self, s):
|
| 427 |
+
"""Return the string bounding box."""
|
| 428 |
+
return self.get_str_bbox_and_descent(s)[:4]
|
| 429 |
+
|
| 430 |
+
def get_name_char(self, c, isord=False):
|
| 431 |
+
"""Get the name of the character, i.e., ';' is 'semicolon'."""
|
| 432 |
+
if not isord:
|
| 433 |
+
c = ord(c)
|
| 434 |
+
return self._metrics[c].name
|
| 435 |
+
|
| 436 |
+
def get_width_char(self, c, isord=False):
|
| 437 |
+
"""
|
| 438 |
+
Get the width of the character from the character metric WX field.
|
| 439 |
+
"""
|
| 440 |
+
if not isord:
|
| 441 |
+
c = ord(c)
|
| 442 |
+
return self._metrics[c].width
|
| 443 |
+
|
| 444 |
+
def get_width_from_char_name(self, name):
|
| 445 |
+
"""Get the width of the character from a type1 character name."""
|
| 446 |
+
return self._metrics_by_name[name].width
|
| 447 |
+
|
| 448 |
+
def get_height_char(self, c, isord=False):
|
| 449 |
+
"""Get the bounding box (ink) height of character *c* (space is 0)."""
|
| 450 |
+
if not isord:
|
| 451 |
+
c = ord(c)
|
| 452 |
+
return self._metrics[c].bbox[-1]
|
| 453 |
+
|
| 454 |
+
def get_kern_dist(self, c1, c2):
|
| 455 |
+
"""
|
| 456 |
+
Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
|
| 457 |
+
"""
|
| 458 |
+
name1, name2 = self.get_name_char(c1), self.get_name_char(c2)
|
| 459 |
+
return self.get_kern_dist_from_name(name1, name2)
|
| 460 |
+
|
| 461 |
+
def get_kern_dist_from_name(self, name1, name2):
|
| 462 |
+
"""
|
| 463 |
+
Return the kerning pair distance (possibly 0) for chars
|
| 464 |
+
*name1* and *name2*.
|
| 465 |
+
"""
|
| 466 |
+
return self._kern.get((name1, name2), 0)
|
| 467 |
+
|
| 468 |
+
def get_fontname(self):
|
| 469 |
+
"""Return the font name, e.g., 'Times-Roman'."""
|
| 470 |
+
return self._header[b'FontName']
|
| 471 |
+
|
| 472 |
+
@property
|
| 473 |
+
def postscript_name(self): # For consistency with FT2Font.
|
| 474 |
+
return self.get_fontname()
|
| 475 |
+
|
| 476 |
+
def get_fullname(self):
|
| 477 |
+
"""Return the font full name, e.g., 'Times-Roman'."""
|
| 478 |
+
name = self._header.get(b'FullName')
|
| 479 |
+
if name is None: # use FontName as a substitute
|
| 480 |
+
name = self._header[b'FontName']
|
| 481 |
+
return name
|
| 482 |
+
|
| 483 |
+
def get_familyname(self):
|
| 484 |
+
"""Return the font family name, e.g., 'Times'."""
|
| 485 |
+
name = self._header.get(b'FamilyName')
|
| 486 |
+
if name is not None:
|
| 487 |
+
return name
|
| 488 |
+
|
| 489 |
+
# FamilyName not specified so we'll make a guess
|
| 490 |
+
name = self.get_fullname()
|
| 491 |
+
extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
|
| 492 |
+
r'light|ultralight|extra|condensed))+$')
|
| 493 |
+
return re.sub(extras, '', name)
|
| 494 |
+
|
| 495 |
+
@property
|
| 496 |
+
def family_name(self):
|
| 497 |
+
"""The font family name, e.g., 'Times'."""
|
| 498 |
+
return self.get_familyname()
|
| 499 |
+
|
| 500 |
+
def get_weight(self):
|
| 501 |
+
"""Return the font weight, e.g., 'Bold' or 'Roman'."""
|
| 502 |
+
return self._header[b'Weight']
|
| 503 |
+
|
| 504 |
+
def get_angle(self):
|
| 505 |
+
"""Return the fontangle as float."""
|
| 506 |
+
return self._header[b'ItalicAngle']
|
| 507 |
+
|
| 508 |
+
def get_capheight(self):
|
| 509 |
+
"""Return the cap height as float."""
|
| 510 |
+
return self._header[b'CapHeight']
|
| 511 |
+
|
| 512 |
+
def get_xheight(self):
|
| 513 |
+
"""Return the xheight as float."""
|
| 514 |
+
return self._header[b'XHeight']
|
| 515 |
+
|
| 516 |
+
def get_underline_thickness(self):
|
| 517 |
+
"""Return the underline thickness as float."""
|
| 518 |
+
return self._header[b'UnderlineThickness']
|
| 519 |
+
|
| 520 |
+
def get_horizontal_stem_width(self):
|
| 521 |
+
"""
|
| 522 |
+
Return the standard horizontal stem width as float, or *None* if
|
| 523 |
+
not specified in AFM file.
|
| 524 |
+
"""
|
| 525 |
+
return self._header.get(b'StdHW', None)
|
| 526 |
+
|
| 527 |
+
def get_vertical_stem_width(self):
|
| 528 |
+
"""
|
| 529 |
+
Return the standard vertical stem width as float, or *None* if
|
| 530 |
+
not specified in AFM file.
|
| 531 |
+
"""
|
| 532 |
+
return self._header.get(b'StdVW', None)
|
moondream/lib/python3.10/site-packages/matplotlib/_animation_data.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# JavaScript template for HTMLWriter
|
| 2 |
+
JS_INCLUDE = """
|
| 3 |
+
<link rel="stylesheet"
|
| 4 |
+
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
|
| 5 |
+
<script language="javascript">
|
| 6 |
+
function isInternetExplorer() {
|
| 7 |
+
ua = navigator.userAgent;
|
| 8 |
+
/* MSIE used to detect old browsers and Trident used to newer ones*/
|
| 9 |
+
return ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
/* Define the Animation class */
|
| 13 |
+
function Animation(frames, img_id, slider_id, interval, loop_select_id){
|
| 14 |
+
this.img_id = img_id;
|
| 15 |
+
this.slider_id = slider_id;
|
| 16 |
+
this.loop_select_id = loop_select_id;
|
| 17 |
+
this.interval = interval;
|
| 18 |
+
this.current_frame = 0;
|
| 19 |
+
this.direction = 0;
|
| 20 |
+
this.timer = null;
|
| 21 |
+
this.frames = new Array(frames.length);
|
| 22 |
+
|
| 23 |
+
for (var i=0; i<frames.length; i++)
|
| 24 |
+
{
|
| 25 |
+
this.frames[i] = new Image();
|
| 26 |
+
this.frames[i].src = frames[i];
|
| 27 |
+
}
|
| 28 |
+
var slider = document.getElementById(this.slider_id);
|
| 29 |
+
slider.max = this.frames.length - 1;
|
| 30 |
+
if (isInternetExplorer()) {
|
| 31 |
+
// switch from oninput to onchange because IE <= 11 does not conform
|
| 32 |
+
// with W3C specification. It ignores oninput and onchange behaves
|
| 33 |
+
// like oninput. In contrast, Microsoft Edge behaves correctly.
|
| 34 |
+
slider.setAttribute('onchange', slider.getAttribute('oninput'));
|
| 35 |
+
slider.setAttribute('oninput', null);
|
| 36 |
+
}
|
| 37 |
+
this.set_frame(this.current_frame);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
Animation.prototype.get_loop_state = function(){
|
| 41 |
+
var button_group = document[this.loop_select_id].state;
|
| 42 |
+
for (var i = 0; i < button_group.length; i++) {
|
| 43 |
+
var button = button_group[i];
|
| 44 |
+
if (button.checked) {
|
| 45 |
+
return button.value;
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
return undefined;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
Animation.prototype.set_frame = function(frame){
|
| 52 |
+
this.current_frame = frame;
|
| 53 |
+
document.getElementById(this.img_id).src =
|
| 54 |
+
this.frames[this.current_frame].src;
|
| 55 |
+
document.getElementById(this.slider_id).value = this.current_frame;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
Animation.prototype.next_frame = function()
|
| 59 |
+
{
|
| 60 |
+
this.set_frame(Math.min(this.frames.length - 1, this.current_frame + 1));
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
Animation.prototype.previous_frame = function()
|
| 64 |
+
{
|
| 65 |
+
this.set_frame(Math.max(0, this.current_frame - 1));
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
Animation.prototype.first_frame = function()
|
| 69 |
+
{
|
| 70 |
+
this.set_frame(0);
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
Animation.prototype.last_frame = function()
|
| 74 |
+
{
|
| 75 |
+
this.set_frame(this.frames.length - 1);
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
Animation.prototype.slower = function()
|
| 79 |
+
{
|
| 80 |
+
this.interval /= 0.7;
|
| 81 |
+
if(this.direction > 0){this.play_animation();}
|
| 82 |
+
else if(this.direction < 0){this.reverse_animation();}
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
Animation.prototype.faster = function()
|
| 86 |
+
{
|
| 87 |
+
this.interval *= 0.7;
|
| 88 |
+
if(this.direction > 0){this.play_animation();}
|
| 89 |
+
else if(this.direction < 0){this.reverse_animation();}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
Animation.prototype.anim_step_forward = function()
|
| 93 |
+
{
|
| 94 |
+
this.current_frame += 1;
|
| 95 |
+
if(this.current_frame < this.frames.length){
|
| 96 |
+
this.set_frame(this.current_frame);
|
| 97 |
+
}else{
|
| 98 |
+
var loop_state = this.get_loop_state();
|
| 99 |
+
if(loop_state == "loop"){
|
| 100 |
+
this.first_frame();
|
| 101 |
+
}else if(loop_state == "reflect"){
|
| 102 |
+
this.last_frame();
|
| 103 |
+
this.reverse_animation();
|
| 104 |
+
}else{
|
| 105 |
+
this.pause_animation();
|
| 106 |
+
this.last_frame();
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
Animation.prototype.anim_step_reverse = function()
|
| 112 |
+
{
|
| 113 |
+
this.current_frame -= 1;
|
| 114 |
+
if(this.current_frame >= 0){
|
| 115 |
+
this.set_frame(this.current_frame);
|
| 116 |
+
}else{
|
| 117 |
+
var loop_state = this.get_loop_state();
|
| 118 |
+
if(loop_state == "loop"){
|
| 119 |
+
this.last_frame();
|
| 120 |
+
}else if(loop_state == "reflect"){
|
| 121 |
+
this.first_frame();
|
| 122 |
+
this.play_animation();
|
| 123 |
+
}else{
|
| 124 |
+
this.pause_animation();
|
| 125 |
+
this.first_frame();
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
Animation.prototype.pause_animation = function()
|
| 131 |
+
{
|
| 132 |
+
this.direction = 0;
|
| 133 |
+
if (this.timer){
|
| 134 |
+
clearInterval(this.timer);
|
| 135 |
+
this.timer = null;
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
Animation.prototype.play_animation = function()
|
| 140 |
+
{
|
| 141 |
+
this.pause_animation();
|
| 142 |
+
this.direction = 1;
|
| 143 |
+
var t = this;
|
| 144 |
+
if (!this.timer) this.timer = setInterval(function() {
|
| 145 |
+
t.anim_step_forward();
|
| 146 |
+
}, this.interval);
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
Animation.prototype.reverse_animation = function()
|
| 150 |
+
{
|
| 151 |
+
this.pause_animation();
|
| 152 |
+
this.direction = -1;
|
| 153 |
+
var t = this;
|
| 154 |
+
if (!this.timer) this.timer = setInterval(function() {
|
| 155 |
+
t.anim_step_reverse();
|
| 156 |
+
}, this.interval);
|
| 157 |
+
}
|
| 158 |
+
</script>
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# Style definitions for the HTML template
|
| 163 |
+
STYLE_INCLUDE = """
|
| 164 |
+
<style>
|
| 165 |
+
.animation {
|
| 166 |
+
display: inline-block;
|
| 167 |
+
text-align: center;
|
| 168 |
+
}
|
| 169 |
+
input[type=range].anim-slider {
|
| 170 |
+
width: 374px;
|
| 171 |
+
margin-left: auto;
|
| 172 |
+
margin-right: auto;
|
| 173 |
+
}
|
| 174 |
+
.anim-buttons {
|
| 175 |
+
margin: 8px 0px;
|
| 176 |
+
}
|
| 177 |
+
.anim-buttons button {
|
| 178 |
+
padding: 0;
|
| 179 |
+
width: 36px;
|
| 180 |
+
}
|
| 181 |
+
.anim-state label {
|
| 182 |
+
margin-right: 8px;
|
| 183 |
+
}
|
| 184 |
+
.anim-state input {
|
| 185 |
+
margin: 0;
|
| 186 |
+
vertical-align: middle;
|
| 187 |
+
}
|
| 188 |
+
</style>
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# HTML template for HTMLWriter
|
| 193 |
+
DISPLAY_TEMPLATE = """
|
| 194 |
+
<div class="animation">
|
| 195 |
+
<img id="_anim_img{id}">
|
| 196 |
+
<div class="anim-controls">
|
| 197 |
+
<input id="_anim_slider{id}" type="range" class="anim-slider"
|
| 198 |
+
name="points" min="0" max="1" step="1" value="0"
|
| 199 |
+
oninput="anim{id}.set_frame(parseInt(this.value));">
|
| 200 |
+
<div class="anim-buttons">
|
| 201 |
+
<button title="Decrease speed" aria-label="Decrease speed" onclick="anim{id}.slower()">
|
| 202 |
+
<i class="fa fa-minus"></i></button>
|
| 203 |
+
<button title="First frame" aria-label="First frame" onclick="anim{id}.first_frame()">
|
| 204 |
+
<i class="fa fa-fast-backward"></i></button>
|
| 205 |
+
<button title="Previous frame" aria-label="Previous frame" onclick="anim{id}.previous_frame()">
|
| 206 |
+
<i class="fa fa-step-backward"></i></button>
|
| 207 |
+
<button title="Play backwards" aria-label="Play backwards" onclick="anim{id}.reverse_animation()">
|
| 208 |
+
<i class="fa fa-play fa-flip-horizontal"></i></button>
|
| 209 |
+
<button title="Pause" aria-label="Pause" onclick="anim{id}.pause_animation()">
|
| 210 |
+
<i class="fa fa-pause"></i></button>
|
| 211 |
+
<button title="Play" aria-label="Play" onclick="anim{id}.play_animation()">
|
| 212 |
+
<i class="fa fa-play"></i></button>
|
| 213 |
+
<button title="Next frame" aria-label="Next frame" onclick="anim{id}.next_frame()">
|
| 214 |
+
<i class="fa fa-step-forward"></i></button>
|
| 215 |
+
<button title="Last frame" aria-label="Last frame" onclick="anim{id}.last_frame()">
|
| 216 |
+
<i class="fa fa-fast-forward"></i></button>
|
| 217 |
+
<button title="Increase speed" aria-label="Increase speed" onclick="anim{id}.faster()">
|
| 218 |
+
<i class="fa fa-plus"></i></button>
|
| 219 |
+
</div>
|
| 220 |
+
<form title="Repetition mode" aria-label="Repetition mode" action="#n" name="_anim_loop_select{id}"
|
| 221 |
+
class="anim-state">
|
| 222 |
+
<input type="radio" name="state" value="once" id="_anim_radio1_{id}"
|
| 223 |
+
{once_checked}>
|
| 224 |
+
<label for="_anim_radio1_{id}">Once</label>
|
| 225 |
+
<input type="radio" name="state" value="loop" id="_anim_radio2_{id}"
|
| 226 |
+
{loop_checked}>
|
| 227 |
+
<label for="_anim_radio2_{id}">Loop</label>
|
| 228 |
+
<input type="radio" name="state" value="reflect" id="_anim_radio3_{id}"
|
| 229 |
+
{reflect_checked}>
|
| 230 |
+
<label for="_anim_radio3_{id}">Reflect</label>
|
| 231 |
+
</form>
|
| 232 |
+
</div>
|
| 233 |
+
</div>
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
<script language="javascript">
|
| 237 |
+
/* Instantiate the Animation class. */
|
| 238 |
+
/* The IDs given should match those used in the template above. */
|
| 239 |
+
(function() {{
|
| 240 |
+
var img_id = "_anim_img{id}";
|
| 241 |
+
var slider_id = "_anim_slider{id}";
|
| 242 |
+
var loop_select_id = "_anim_loop_select{id}";
|
| 243 |
+
var frames = new Array({Nframes});
|
| 244 |
+
{fill_frames}
|
| 245 |
+
|
| 246 |
+
/* set a timeout to make sure all the above elements are created before
|
| 247 |
+
the object is initialized. */
|
| 248 |
+
setTimeout(function() {{
|
| 249 |
+
anim{id} = new Animation(frames, img_id, slider_id, {interval},
|
| 250 |
+
loop_select_id);
|
| 251 |
+
}}, 0);
|
| 252 |
+
}})()
|
| 253 |
+
</script>
|
| 254 |
+
""" # noqa: E501
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
INCLUDED_FRAMES = """
|
| 258 |
+
for (var i=0; i<{Nframes}; i++){{
|
| 259 |
+
frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) +
|
| 260 |
+
".{frame_format}";
|
| 261 |
+
}}
|
| 262 |
+
"""
|
moondream/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def display_is_valid() -> bool: ...
|
| 2 |
+
def xdisplay_is_valid() -> bool: ...
|
| 3 |
+
|
| 4 |
+
def Win32_GetForegroundWindow() -> int | None: ...
|
| 5 |
+
def Win32_SetForegroundWindow(hwnd: int) -> None: ...
|
| 6 |
+
def Win32_SetProcessDpiAwareness_max() -> None: ...
|
| 7 |
+
def Win32_SetCurrentProcessExplicitAppUserModelID(appid: str) -> None: ...
|
| 8 |
+
def Win32_GetCurrentProcessExplicitAppUserModelID() -> str | None: ...
|
moondream/lib/python3.10/site-packages/matplotlib/_color_data.pyi
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .typing import ColorType
|
| 2 |
+
|
| 3 |
+
BASE_COLORS: dict[str, ColorType]
|
| 4 |
+
TABLEAU_COLORS: dict[str, ColorType]
|
| 5 |
+
XKCD_COLORS: dict[str, ColorType]
|
| 6 |
+
CSS4_COLORS: dict[str, ColorType]
|
moondream/lib/python3.10/site-packages/matplotlib/_constrained_layout.py
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adjust subplot layouts so that there are no overlapping Axes or Axes
|
| 3 |
+
decorations. All Axes decorations are dealt with (labels, ticks, titles,
|
| 4 |
+
ticklabels) and some dependent artists are also dealt with (colorbar,
|
| 5 |
+
suptitle).
|
| 6 |
+
|
| 7 |
+
Layout is done via `~matplotlib.gridspec`, with one constraint per gridspec,
|
| 8 |
+
so it is possible to have overlapping Axes if the gridspecs overlap (i.e.
|
| 9 |
+
using `~matplotlib.gridspec.GridSpecFromSubplotSpec`). Axes placed using
|
| 10 |
+
``figure.subplots()`` or ``figure.add_subplots()`` will participate in the
|
| 11 |
+
layout. Axes manually placed via ``figure.add_axes()`` will not.
|
| 12 |
+
|
| 13 |
+
See Tutorial: :ref:`constrainedlayout_guide`
|
| 14 |
+
|
| 15 |
+
General idea:
|
| 16 |
+
-------------
|
| 17 |
+
|
| 18 |
+
First, a figure has a gridspec that divides the figure into nrows and ncols,
|
| 19 |
+
with heights and widths set by ``height_ratios`` and ``width_ratios``,
|
| 20 |
+
often just set to 1 for an equal grid.
|
| 21 |
+
|
| 22 |
+
Subplotspecs that are derived from this gridspec can contain either a
|
| 23 |
+
``SubPanel``, a ``GridSpecFromSubplotSpec``, or an ``Axes``. The ``SubPanel``
|
| 24 |
+
and ``GridSpecFromSubplotSpec`` are dealt with recursively and each contain an
|
| 25 |
+
analogous layout.
|
| 26 |
+
|
| 27 |
+
Each ``GridSpec`` has a ``_layoutgrid`` attached to it. The ``_layoutgrid``
|
| 28 |
+
has the same logical layout as the ``GridSpec``. Each row of the grid spec
|
| 29 |
+
has a top and bottom "margin" and each column has a left and right "margin".
|
| 30 |
+
The "inner" height of each row is constrained to be the same (or as modified
|
| 31 |
+
by ``height_ratio``), and the "inner" width of each column is
|
| 32 |
+
constrained to be the same (as modified by ``width_ratio``), where "inner"
|
| 33 |
+
is the width or height of each column/row minus the size of the margins.
|
| 34 |
+
|
| 35 |
+
Then the size of the margins for each row and column are determined as the
|
| 36 |
+
max width of the decorators on each Axes that has decorators in that margin.
|
| 37 |
+
For instance, a normal Axes would have a left margin that includes the
|
| 38 |
+
left ticklabels, and the ylabel if it exists. The right margin may include a
|
| 39 |
+
colorbar, the bottom margin the xaxis decorations, and the top margin the
|
| 40 |
+
title.
|
| 41 |
+
|
| 42 |
+
With these constraints, the solver then finds appropriate bounds for the
|
| 43 |
+
columns and rows. It's possible that the margins take up the whole figure,
|
| 44 |
+
in which case the algorithm is not applied and a warning is raised.
|
| 45 |
+
|
| 46 |
+
See the tutorial :ref:`constrainedlayout_guide`
|
| 47 |
+
for more discussion of the algorithm with examples.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
import logging
|
| 51 |
+
|
| 52 |
+
import numpy as np
|
| 53 |
+
|
| 54 |
+
from matplotlib import _api, artist as martist
|
| 55 |
+
import matplotlib.transforms as mtransforms
|
| 56 |
+
import matplotlib._layoutgrid as mlayoutgrid
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
_log = logging.getLogger(__name__)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
######################################################
|
| 63 |
+
def do_constrained_layout(fig, h_pad, w_pad,
|
| 64 |
+
hspace=None, wspace=None, rect=(0, 0, 1, 1),
|
| 65 |
+
compress=False):
|
| 66 |
+
"""
|
| 67 |
+
Do the constrained_layout. Called at draw time in
|
| 68 |
+
``figure.constrained_layout()``
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
fig : `~matplotlib.figure.Figure`
|
| 73 |
+
`.Figure` instance to do the layout in.
|
| 74 |
+
|
| 75 |
+
h_pad, w_pad : float
|
| 76 |
+
Padding around the Axes elements in figure-normalized units.
|
| 77 |
+
|
| 78 |
+
hspace, wspace : float
|
| 79 |
+
Fraction of the figure to dedicate to space between the
|
| 80 |
+
Axes. These are evenly spread between the gaps between the Axes.
|
| 81 |
+
A value of 0.2 for a three-column layout would have a space
|
| 82 |
+
of 0.1 of the figure width between each column.
|
| 83 |
+
If h/wspace < h/w_pad, then the pads are used instead.
|
| 84 |
+
|
| 85 |
+
rect : tuple of 4 floats
|
| 86 |
+
Rectangle in figure coordinates to perform constrained layout in
|
| 87 |
+
[left, bottom, width, height], each from 0-1.
|
| 88 |
+
|
| 89 |
+
compress : bool
|
| 90 |
+
Whether to shift Axes so that white space in between them is
|
| 91 |
+
removed. This is useful for simple grids of fixed-aspect Axes (e.g.
|
| 92 |
+
a grid of images).
|
| 93 |
+
|
| 94 |
+
Returns
|
| 95 |
+
-------
|
| 96 |
+
layoutgrid : private debugging structure
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
renderer = fig._get_renderer()
|
| 100 |
+
# make layoutgrid tree...
|
| 101 |
+
layoutgrids = make_layoutgrids(fig, None, rect=rect)
|
| 102 |
+
if not layoutgrids['hasgrids']:
|
| 103 |
+
_api.warn_external('There are no gridspecs with layoutgrids. '
|
| 104 |
+
'Possibly did not call parent GridSpec with the'
|
| 105 |
+
' "figure" keyword')
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
for _ in range(2):
|
| 109 |
+
# do the algorithm twice. This has to be done because decorations
|
| 110 |
+
# change size after the first re-position (i.e. x/yticklabels get
|
| 111 |
+
# larger/smaller). This second reposition tends to be much milder,
|
| 112 |
+
# so doing twice makes things work OK.
|
| 113 |
+
|
| 114 |
+
# make margins for all the Axes and subfigures in the
|
| 115 |
+
# figure. Add margins for colorbars...
|
| 116 |
+
make_layout_margins(layoutgrids, fig, renderer, h_pad=h_pad,
|
| 117 |
+
w_pad=w_pad, hspace=hspace, wspace=wspace)
|
| 118 |
+
make_margin_suptitles(layoutgrids, fig, renderer, h_pad=h_pad,
|
| 119 |
+
w_pad=w_pad)
|
| 120 |
+
|
| 121 |
+
# if a layout is such that a columns (or rows) margin has no
|
| 122 |
+
# constraints, we need to make all such instances in the grid
|
| 123 |
+
# match in margin size.
|
| 124 |
+
match_submerged_margins(layoutgrids, fig)
|
| 125 |
+
|
| 126 |
+
# update all the variables in the layout.
|
| 127 |
+
layoutgrids[fig].update_variables()
|
| 128 |
+
|
| 129 |
+
warn_collapsed = ('constrained_layout not applied because '
|
| 130 |
+
'axes sizes collapsed to zero. Try making '
|
| 131 |
+
'figure larger or Axes decorations smaller.')
|
| 132 |
+
if check_no_collapsed_axes(layoutgrids, fig):
|
| 133 |
+
reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad,
|
| 134 |
+
w_pad=w_pad, hspace=hspace, wspace=wspace)
|
| 135 |
+
if compress:
|
| 136 |
+
layoutgrids = compress_fixed_aspect(layoutgrids, fig)
|
| 137 |
+
layoutgrids[fig].update_variables()
|
| 138 |
+
if check_no_collapsed_axes(layoutgrids, fig):
|
| 139 |
+
reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad,
|
| 140 |
+
w_pad=w_pad, hspace=hspace, wspace=wspace)
|
| 141 |
+
else:
|
| 142 |
+
_api.warn_external(warn_collapsed)
|
| 143 |
+
|
| 144 |
+
if ((suptitle := fig._suptitle) is not None and
|
| 145 |
+
suptitle.get_in_layout() and suptitle._autopos):
|
| 146 |
+
x, _ = suptitle.get_position()
|
| 147 |
+
suptitle.set_position(
|
| 148 |
+
(x, layoutgrids[fig].get_inner_bbox().y1 + h_pad))
|
| 149 |
+
suptitle.set_verticalalignment('bottom')
|
| 150 |
+
else:
|
| 151 |
+
_api.warn_external(warn_collapsed)
|
| 152 |
+
reset_margins(layoutgrids, fig)
|
| 153 |
+
return layoutgrids
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def make_layoutgrids(fig, layoutgrids, rect=(0, 0, 1, 1)):
|
| 157 |
+
"""
|
| 158 |
+
Make the layoutgrid tree.
|
| 159 |
+
|
| 160 |
+
(Sub)Figures get a layoutgrid so we can have figure margins.
|
| 161 |
+
|
| 162 |
+
Gridspecs that are attached to Axes get a layoutgrid so Axes
|
| 163 |
+
can have margins.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
if layoutgrids is None:
|
| 167 |
+
layoutgrids = dict()
|
| 168 |
+
layoutgrids['hasgrids'] = False
|
| 169 |
+
if not hasattr(fig, '_parent'):
|
| 170 |
+
# top figure; pass rect as parent to allow user-specified
|
| 171 |
+
# margins
|
| 172 |
+
layoutgrids[fig] = mlayoutgrid.LayoutGrid(parent=rect, name='figlb')
|
| 173 |
+
else:
|
| 174 |
+
# subfigure
|
| 175 |
+
gs = fig._subplotspec.get_gridspec()
|
| 176 |
+
# it is possible the gridspec containing this subfigure hasn't
|
| 177 |
+
# been added to the tree yet:
|
| 178 |
+
layoutgrids = make_layoutgrids_gs(layoutgrids, gs)
|
| 179 |
+
# add the layoutgrid for the subfigure:
|
| 180 |
+
parentlb = layoutgrids[gs]
|
| 181 |
+
layoutgrids[fig] = mlayoutgrid.LayoutGrid(
|
| 182 |
+
parent=parentlb,
|
| 183 |
+
name='panellb',
|
| 184 |
+
parent_inner=True,
|
| 185 |
+
nrows=1, ncols=1,
|
| 186 |
+
parent_pos=(fig._subplotspec.rowspan,
|
| 187 |
+
fig._subplotspec.colspan))
|
| 188 |
+
# recursively do all subfigures in this figure...
|
| 189 |
+
for sfig in fig.subfigs:
|
| 190 |
+
layoutgrids = make_layoutgrids(sfig, layoutgrids)
|
| 191 |
+
|
| 192 |
+
# for each Axes at the local level add its gridspec:
|
| 193 |
+
for ax in fig._localaxes:
|
| 194 |
+
gs = ax.get_gridspec()
|
| 195 |
+
if gs is not None:
|
| 196 |
+
layoutgrids = make_layoutgrids_gs(layoutgrids, gs)
|
| 197 |
+
|
| 198 |
+
return layoutgrids
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def make_layoutgrids_gs(layoutgrids, gs):
|
| 202 |
+
"""
|
| 203 |
+
Make the layoutgrid for a gridspec (and anything nested in the gridspec)
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
if gs in layoutgrids or gs.figure is None:
|
| 207 |
+
return layoutgrids
|
| 208 |
+
# in order to do constrained_layout there has to be at least *one*
|
| 209 |
+
# gridspec in the tree:
|
| 210 |
+
layoutgrids['hasgrids'] = True
|
| 211 |
+
if not hasattr(gs, '_subplot_spec'):
|
| 212 |
+
# normal gridspec
|
| 213 |
+
parent = layoutgrids[gs.figure]
|
| 214 |
+
layoutgrids[gs] = mlayoutgrid.LayoutGrid(
|
| 215 |
+
parent=parent,
|
| 216 |
+
parent_inner=True,
|
| 217 |
+
name='gridspec',
|
| 218 |
+
ncols=gs._ncols, nrows=gs._nrows,
|
| 219 |
+
width_ratios=gs.get_width_ratios(),
|
| 220 |
+
height_ratios=gs.get_height_ratios())
|
| 221 |
+
else:
|
| 222 |
+
# this is a gridspecfromsubplotspec:
|
| 223 |
+
subplot_spec = gs._subplot_spec
|
| 224 |
+
parentgs = subplot_spec.get_gridspec()
|
| 225 |
+
# if a nested gridspec it is possible the parent is not in there yet:
|
| 226 |
+
if parentgs not in layoutgrids:
|
| 227 |
+
layoutgrids = make_layoutgrids_gs(layoutgrids, parentgs)
|
| 228 |
+
subspeclb = layoutgrids[parentgs]
|
| 229 |
+
# gridspecfromsubplotspec need an outer container:
|
| 230 |
+
# get a unique representation:
|
| 231 |
+
rep = (gs, 'top')
|
| 232 |
+
if rep not in layoutgrids:
|
| 233 |
+
layoutgrids[rep] = mlayoutgrid.LayoutGrid(
|
| 234 |
+
parent=subspeclb,
|
| 235 |
+
name='top',
|
| 236 |
+
nrows=1, ncols=1,
|
| 237 |
+
parent_pos=(subplot_spec.rowspan, subplot_spec.colspan))
|
| 238 |
+
layoutgrids[gs] = mlayoutgrid.LayoutGrid(
|
| 239 |
+
parent=layoutgrids[rep],
|
| 240 |
+
name='gridspec',
|
| 241 |
+
nrows=gs._nrows, ncols=gs._ncols,
|
| 242 |
+
width_ratios=gs.get_width_ratios(),
|
| 243 |
+
height_ratios=gs.get_height_ratios())
|
| 244 |
+
return layoutgrids
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def check_no_collapsed_axes(layoutgrids, fig):
|
| 248 |
+
"""
|
| 249 |
+
Check that no Axes have collapsed to zero size.
|
| 250 |
+
"""
|
| 251 |
+
for sfig in fig.subfigs:
|
| 252 |
+
ok = check_no_collapsed_axes(layoutgrids, sfig)
|
| 253 |
+
if not ok:
|
| 254 |
+
return False
|
| 255 |
+
for ax in fig.axes:
|
| 256 |
+
gs = ax.get_gridspec()
|
| 257 |
+
if gs in layoutgrids: # also implies gs is not None.
|
| 258 |
+
lg = layoutgrids[gs]
|
| 259 |
+
for i in range(gs.nrows):
|
| 260 |
+
for j in range(gs.ncols):
|
| 261 |
+
bb = lg.get_inner_bbox(i, j)
|
| 262 |
+
if bb.width <= 0 or bb.height <= 0:
|
| 263 |
+
return False
|
| 264 |
+
return True
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def compress_fixed_aspect(layoutgrids, fig):
|
| 268 |
+
gs = None
|
| 269 |
+
for ax in fig.axes:
|
| 270 |
+
if ax.get_subplotspec() is None:
|
| 271 |
+
continue
|
| 272 |
+
ax.apply_aspect()
|
| 273 |
+
sub = ax.get_subplotspec()
|
| 274 |
+
_gs = sub.get_gridspec()
|
| 275 |
+
if gs is None:
|
| 276 |
+
gs = _gs
|
| 277 |
+
extraw = np.zeros(gs.ncols)
|
| 278 |
+
extrah = np.zeros(gs.nrows)
|
| 279 |
+
elif _gs != gs:
|
| 280 |
+
raise ValueError('Cannot do compressed layout if Axes are not'
|
| 281 |
+
'all from the same gridspec')
|
| 282 |
+
orig = ax.get_position(original=True)
|
| 283 |
+
actual = ax.get_position(original=False)
|
| 284 |
+
dw = orig.width - actual.width
|
| 285 |
+
if dw > 0:
|
| 286 |
+
extraw[sub.colspan] = np.maximum(extraw[sub.colspan], dw)
|
| 287 |
+
dh = orig.height - actual.height
|
| 288 |
+
if dh > 0:
|
| 289 |
+
extrah[sub.rowspan] = np.maximum(extrah[sub.rowspan], dh)
|
| 290 |
+
|
| 291 |
+
if gs is None:
|
| 292 |
+
raise ValueError('Cannot do compressed layout if no Axes '
|
| 293 |
+
'are part of a gridspec.')
|
| 294 |
+
w = np.sum(extraw) / 2
|
| 295 |
+
layoutgrids[fig].edit_margin_min('left', w)
|
| 296 |
+
layoutgrids[fig].edit_margin_min('right', w)
|
| 297 |
+
|
| 298 |
+
h = np.sum(extrah) / 2
|
| 299 |
+
layoutgrids[fig].edit_margin_min('top', h)
|
| 300 |
+
layoutgrids[fig].edit_margin_min('bottom', h)
|
| 301 |
+
return layoutgrids
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def get_margin_from_padding(obj, *, w_pad=0, h_pad=0,
|
| 305 |
+
hspace=0, wspace=0):
|
| 306 |
+
|
| 307 |
+
ss = obj._subplotspec
|
| 308 |
+
gs = ss.get_gridspec()
|
| 309 |
+
|
| 310 |
+
if hasattr(gs, 'hspace'):
|
| 311 |
+
_hspace = (gs.hspace if gs.hspace is not None else hspace)
|
| 312 |
+
_wspace = (gs.wspace if gs.wspace is not None else wspace)
|
| 313 |
+
else:
|
| 314 |
+
_hspace = (gs._hspace if gs._hspace is not None else hspace)
|
| 315 |
+
_wspace = (gs._wspace if gs._wspace is not None else wspace)
|
| 316 |
+
|
| 317 |
+
_wspace = _wspace / 2
|
| 318 |
+
_hspace = _hspace / 2
|
| 319 |
+
|
| 320 |
+
nrows, ncols = gs.get_geometry()
|
| 321 |
+
# there are two margins for each direction. The "cb"
|
| 322 |
+
# margins are for pads and colorbars, the non-"cb" are
|
| 323 |
+
# for the Axes decorations (labels etc).
|
| 324 |
+
margin = {'leftcb': w_pad, 'rightcb': w_pad,
|
| 325 |
+
'bottomcb': h_pad, 'topcb': h_pad,
|
| 326 |
+
'left': 0, 'right': 0,
|
| 327 |
+
'top': 0, 'bottom': 0}
|
| 328 |
+
if _wspace / ncols > w_pad:
|
| 329 |
+
if ss.colspan.start > 0:
|
| 330 |
+
margin['leftcb'] = _wspace / ncols
|
| 331 |
+
if ss.colspan.stop < ncols:
|
| 332 |
+
margin['rightcb'] = _wspace / ncols
|
| 333 |
+
if _hspace / nrows > h_pad:
|
| 334 |
+
if ss.rowspan.stop < nrows:
|
| 335 |
+
margin['bottomcb'] = _hspace / nrows
|
| 336 |
+
if ss.rowspan.start > 0:
|
| 337 |
+
margin['topcb'] = _hspace / nrows
|
| 338 |
+
|
| 339 |
+
return margin
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
|
| 343 |
+
hspace=0, wspace=0):
|
| 344 |
+
"""
|
| 345 |
+
For each Axes, make a margin between the *pos* layoutbox and the
|
| 346 |
+
*axes* layoutbox be a minimum size that can accommodate the
|
| 347 |
+
decorations on the axis.
|
| 348 |
+
|
| 349 |
+
Then make room for colorbars.
|
| 350 |
+
|
| 351 |
+
Parameters
|
| 352 |
+
----------
|
| 353 |
+
layoutgrids : dict
|
| 354 |
+
fig : `~matplotlib.figure.Figure`
|
| 355 |
+
`.Figure` instance to do the layout in.
|
| 356 |
+
renderer : `~matplotlib.backend_bases.RendererBase` subclass.
|
| 357 |
+
The renderer to use.
|
| 358 |
+
w_pad, h_pad : float, default: 0
|
| 359 |
+
Width and height padding (in fraction of figure).
|
| 360 |
+
hspace, wspace : float, default: 0
|
| 361 |
+
Width and height padding as fraction of figure size divided by
|
| 362 |
+
number of columns or rows.
|
| 363 |
+
"""
|
| 364 |
+
for sfig in fig.subfigs: # recursively make child panel margins
|
| 365 |
+
ss = sfig._subplotspec
|
| 366 |
+
gs = ss.get_gridspec()
|
| 367 |
+
|
| 368 |
+
make_layout_margins(layoutgrids, sfig, renderer,
|
| 369 |
+
w_pad=w_pad, h_pad=h_pad,
|
| 370 |
+
hspace=hspace, wspace=wspace)
|
| 371 |
+
|
| 372 |
+
margins = get_margin_from_padding(sfig, w_pad=0, h_pad=0,
|
| 373 |
+
hspace=hspace, wspace=wspace)
|
| 374 |
+
layoutgrids[gs].edit_outer_margin_mins(margins, ss)
|
| 375 |
+
|
| 376 |
+
for ax in fig._localaxes:
|
| 377 |
+
if not ax.get_subplotspec() or not ax.get_in_layout():
|
| 378 |
+
continue
|
| 379 |
+
|
| 380 |
+
ss = ax.get_subplotspec()
|
| 381 |
+
gs = ss.get_gridspec()
|
| 382 |
+
|
| 383 |
+
if gs not in layoutgrids:
|
| 384 |
+
return
|
| 385 |
+
|
| 386 |
+
margin = get_margin_from_padding(ax, w_pad=w_pad, h_pad=h_pad,
|
| 387 |
+
hspace=hspace, wspace=wspace)
|
| 388 |
+
pos, bbox = get_pos_and_bbox(ax, renderer)
|
| 389 |
+
# the margin is the distance between the bounding box of the Axes
|
| 390 |
+
# and its position (plus the padding from above)
|
| 391 |
+
margin['left'] += pos.x0 - bbox.x0
|
| 392 |
+
margin['right'] += bbox.x1 - pos.x1
|
| 393 |
+
# remember that rows are ordered from top:
|
| 394 |
+
margin['bottom'] += pos.y0 - bbox.y0
|
| 395 |
+
margin['top'] += bbox.y1 - pos.y1
|
| 396 |
+
|
| 397 |
+
# make margin for colorbars. These margins go in the
|
| 398 |
+
# padding margin, versus the margin for Axes decorators.
|
| 399 |
+
for cbax in ax._colorbars:
|
| 400 |
+
# note pad is a fraction of the parent width...
|
| 401 |
+
pad = colorbar_get_pad(layoutgrids, cbax)
|
| 402 |
+
# colorbars can be child of more than one subplot spec:
|
| 403 |
+
cbp_rspan, cbp_cspan = get_cb_parent_spans(cbax)
|
| 404 |
+
loc = cbax._colorbar_info['location']
|
| 405 |
+
cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)
|
| 406 |
+
if loc == 'right':
|
| 407 |
+
if cbp_cspan.stop == ss.colspan.stop:
|
| 408 |
+
# only increase if the colorbar is on the right edge
|
| 409 |
+
margin['rightcb'] += cbbbox.width + pad
|
| 410 |
+
elif loc == 'left':
|
| 411 |
+
if cbp_cspan.start == ss.colspan.start:
|
| 412 |
+
# only increase if the colorbar is on the left edge
|
| 413 |
+
margin['leftcb'] += cbbbox.width + pad
|
| 414 |
+
elif loc == 'top':
|
| 415 |
+
if cbp_rspan.start == ss.rowspan.start:
|
| 416 |
+
margin['topcb'] += cbbbox.height + pad
|
| 417 |
+
else:
|
| 418 |
+
if cbp_rspan.stop == ss.rowspan.stop:
|
| 419 |
+
margin['bottomcb'] += cbbbox.height + pad
|
| 420 |
+
# If the colorbars are wider than the parent box in the
|
| 421 |
+
# cross direction
|
| 422 |
+
if loc in ['top', 'bottom']:
|
| 423 |
+
if (cbp_cspan.start == ss.colspan.start and
|
| 424 |
+
cbbbox.x0 < bbox.x0):
|
| 425 |
+
margin['left'] += bbox.x0 - cbbbox.x0
|
| 426 |
+
if (cbp_cspan.stop == ss.colspan.stop and
|
| 427 |
+
cbbbox.x1 > bbox.x1):
|
| 428 |
+
margin['right'] += cbbbox.x1 - bbox.x1
|
| 429 |
+
# or taller:
|
| 430 |
+
if loc in ['left', 'right']:
|
| 431 |
+
if (cbp_rspan.stop == ss.rowspan.stop and
|
| 432 |
+
cbbbox.y0 < bbox.y0):
|
| 433 |
+
margin['bottom'] += bbox.y0 - cbbbox.y0
|
| 434 |
+
if (cbp_rspan.start == ss.rowspan.start and
|
| 435 |
+
cbbbox.y1 > bbox.y1):
|
| 436 |
+
margin['top'] += cbbbox.y1 - bbox.y1
|
| 437 |
+
# pass the new margins down to the layout grid for the solution...
|
| 438 |
+
layoutgrids[gs].edit_outer_margin_mins(margin, ss)
|
| 439 |
+
|
| 440 |
+
# make margins for figure-level legends:
|
| 441 |
+
for leg in fig.legends:
|
| 442 |
+
inv_trans_fig = None
|
| 443 |
+
if leg._outside_loc and leg._bbox_to_anchor is None:
|
| 444 |
+
if inv_trans_fig is None:
|
| 445 |
+
inv_trans_fig = fig.transFigure.inverted().transform_bbox
|
| 446 |
+
bbox = inv_trans_fig(leg.get_tightbbox(renderer))
|
| 447 |
+
w = bbox.width + 2 * w_pad
|
| 448 |
+
h = bbox.height + 2 * h_pad
|
| 449 |
+
legendloc = leg._outside_loc
|
| 450 |
+
if legendloc == 'lower':
|
| 451 |
+
layoutgrids[fig].edit_margin_min('bottom', h)
|
| 452 |
+
elif legendloc == 'upper':
|
| 453 |
+
layoutgrids[fig].edit_margin_min('top', h)
|
| 454 |
+
if legendloc == 'right':
|
| 455 |
+
layoutgrids[fig].edit_margin_min('right', w)
|
| 456 |
+
elif legendloc == 'left':
|
| 457 |
+
layoutgrids[fig].edit_margin_min('left', w)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0):
|
| 461 |
+
# Figure out how large the suptitle is and make the
|
| 462 |
+
# top level figure margin larger.
|
| 463 |
+
|
| 464 |
+
inv_trans_fig = fig.transFigure.inverted().transform_bbox
|
| 465 |
+
# get the h_pad and w_pad as distances in the local subfigure coordinates:
|
| 466 |
+
padbox = mtransforms.Bbox([[0, 0], [w_pad, h_pad]])
|
| 467 |
+
padbox = (fig.transFigure -
|
| 468 |
+
fig.transSubfigure).transform_bbox(padbox)
|
| 469 |
+
h_pad_local = padbox.height
|
| 470 |
+
w_pad_local = padbox.width
|
| 471 |
+
|
| 472 |
+
for sfig in fig.subfigs:
|
| 473 |
+
make_margin_suptitles(layoutgrids, sfig, renderer,
|
| 474 |
+
w_pad=w_pad, h_pad=h_pad)
|
| 475 |
+
|
| 476 |
+
if fig._suptitle is not None and fig._suptitle.get_in_layout():
|
| 477 |
+
p = fig._suptitle.get_position()
|
| 478 |
+
if getattr(fig._suptitle, '_autopos', False):
|
| 479 |
+
fig._suptitle.set_position((p[0], 1 - h_pad_local))
|
| 480 |
+
bbox = inv_trans_fig(fig._suptitle.get_tightbbox(renderer))
|
| 481 |
+
layoutgrids[fig].edit_margin_min('top', bbox.height + 2 * h_pad)
|
| 482 |
+
|
| 483 |
+
if fig._supxlabel is not None and fig._supxlabel.get_in_layout():
|
| 484 |
+
p = fig._supxlabel.get_position()
|
| 485 |
+
if getattr(fig._supxlabel, '_autopos', False):
|
| 486 |
+
fig._supxlabel.set_position((p[0], h_pad_local))
|
| 487 |
+
bbox = inv_trans_fig(fig._supxlabel.get_tightbbox(renderer))
|
| 488 |
+
layoutgrids[fig].edit_margin_min('bottom',
|
| 489 |
+
bbox.height + 2 * h_pad)
|
| 490 |
+
|
| 491 |
+
if fig._supylabel is not None and fig._supylabel.get_in_layout():
|
| 492 |
+
p = fig._supylabel.get_position()
|
| 493 |
+
if getattr(fig._supylabel, '_autopos', False):
|
| 494 |
+
fig._supylabel.set_position((w_pad_local, p[1]))
|
| 495 |
+
bbox = inv_trans_fig(fig._supylabel.get_tightbbox(renderer))
|
| 496 |
+
layoutgrids[fig].edit_margin_min('left', bbox.width + 2 * w_pad)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def match_submerged_margins(layoutgrids, fig):
|
| 500 |
+
"""
|
| 501 |
+
Make the margins that are submerged inside an Axes the same size.
|
| 502 |
+
|
| 503 |
+
This allows Axes that span two columns (or rows) that are offset
|
| 504 |
+
from one another to have the same size.
|
| 505 |
+
|
| 506 |
+
This gives the proper layout for something like::
|
| 507 |
+
fig = plt.figure(constrained_layout=True)
|
| 508 |
+
axs = fig.subplot_mosaic("AAAB\nCCDD")
|
| 509 |
+
|
| 510 |
+
Without this routine, the Axes D will be wider than C, because the
|
| 511 |
+
margin width between the two columns in C has no width by default,
|
| 512 |
+
whereas the margins between the two columns of D are set by the
|
| 513 |
+
width of the margin between A and B. However, obviously the user would
|
| 514 |
+
like C and D to be the same size, so we need to add constraints to these
|
| 515 |
+
"submerged" margins.
|
| 516 |
+
|
| 517 |
+
This routine makes all the interior margins the same, and the spacing
|
| 518 |
+
between the three columns in A and the two column in C are all set to the
|
| 519 |
+
margins between the two columns of D.
|
| 520 |
+
|
| 521 |
+
See test_constrained_layout::test_constrained_layout12 for an example.
|
| 522 |
+
"""
|
| 523 |
+
|
| 524 |
+
for sfig in fig.subfigs:
|
| 525 |
+
match_submerged_margins(layoutgrids, sfig)
|
| 526 |
+
|
| 527 |
+
axs = [a for a in fig.get_axes()
|
| 528 |
+
if a.get_subplotspec() is not None and a.get_in_layout()]
|
| 529 |
+
|
| 530 |
+
for ax1 in axs:
|
| 531 |
+
ss1 = ax1.get_subplotspec()
|
| 532 |
+
if ss1.get_gridspec() not in layoutgrids:
|
| 533 |
+
axs.remove(ax1)
|
| 534 |
+
continue
|
| 535 |
+
lg1 = layoutgrids[ss1.get_gridspec()]
|
| 536 |
+
|
| 537 |
+
# interior columns:
|
| 538 |
+
if len(ss1.colspan) > 1:
|
| 539 |
+
maxsubl = np.max(
|
| 540 |
+
lg1.margin_vals['left'][ss1.colspan[1:]] +
|
| 541 |
+
lg1.margin_vals['leftcb'][ss1.colspan[1:]]
|
| 542 |
+
)
|
| 543 |
+
maxsubr = np.max(
|
| 544 |
+
lg1.margin_vals['right'][ss1.colspan[:-1]] +
|
| 545 |
+
lg1.margin_vals['rightcb'][ss1.colspan[:-1]]
|
| 546 |
+
)
|
| 547 |
+
for ax2 in axs:
|
| 548 |
+
ss2 = ax2.get_subplotspec()
|
| 549 |
+
lg2 = layoutgrids[ss2.get_gridspec()]
|
| 550 |
+
if lg2 is not None and len(ss2.colspan) > 1:
|
| 551 |
+
maxsubl2 = np.max(
|
| 552 |
+
lg2.margin_vals['left'][ss2.colspan[1:]] +
|
| 553 |
+
lg2.margin_vals['leftcb'][ss2.colspan[1:]])
|
| 554 |
+
if maxsubl2 > maxsubl:
|
| 555 |
+
maxsubl = maxsubl2
|
| 556 |
+
maxsubr2 = np.max(
|
| 557 |
+
lg2.margin_vals['right'][ss2.colspan[:-1]] +
|
| 558 |
+
lg2.margin_vals['rightcb'][ss2.colspan[:-1]])
|
| 559 |
+
if maxsubr2 > maxsubr:
|
| 560 |
+
maxsubr = maxsubr2
|
| 561 |
+
for i in ss1.colspan[1:]:
|
| 562 |
+
lg1.edit_margin_min('left', maxsubl, cell=i)
|
| 563 |
+
for i in ss1.colspan[:-1]:
|
| 564 |
+
lg1.edit_margin_min('right', maxsubr, cell=i)
|
| 565 |
+
|
| 566 |
+
# interior rows:
|
| 567 |
+
if len(ss1.rowspan) > 1:
|
| 568 |
+
maxsubt = np.max(
|
| 569 |
+
lg1.margin_vals['top'][ss1.rowspan[1:]] +
|
| 570 |
+
lg1.margin_vals['topcb'][ss1.rowspan[1:]]
|
| 571 |
+
)
|
| 572 |
+
maxsubb = np.max(
|
| 573 |
+
lg1.margin_vals['bottom'][ss1.rowspan[:-1]] +
|
| 574 |
+
lg1.margin_vals['bottomcb'][ss1.rowspan[:-1]]
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
for ax2 in axs:
|
| 578 |
+
ss2 = ax2.get_subplotspec()
|
| 579 |
+
lg2 = layoutgrids[ss2.get_gridspec()]
|
| 580 |
+
if lg2 is not None:
|
| 581 |
+
if len(ss2.rowspan) > 1:
|
| 582 |
+
maxsubt = np.max([np.max(
|
| 583 |
+
lg2.margin_vals['top'][ss2.rowspan[1:]] +
|
| 584 |
+
lg2.margin_vals['topcb'][ss2.rowspan[1:]]
|
| 585 |
+
), maxsubt])
|
| 586 |
+
maxsubb = np.max([np.max(
|
| 587 |
+
lg2.margin_vals['bottom'][ss2.rowspan[:-1]] +
|
| 588 |
+
lg2.margin_vals['bottomcb'][ss2.rowspan[:-1]]
|
| 589 |
+
), maxsubb])
|
| 590 |
+
for i in ss1.rowspan[1:]:
|
| 591 |
+
lg1.edit_margin_min('top', maxsubt, cell=i)
|
| 592 |
+
for i in ss1.rowspan[:-1]:
|
| 593 |
+
lg1.edit_margin_min('bottom', maxsubb, cell=i)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def get_cb_parent_spans(cbax):
|
| 597 |
+
"""
|
| 598 |
+
Figure out which subplotspecs this colorbar belongs to.
|
| 599 |
+
|
| 600 |
+
Parameters
|
| 601 |
+
----------
|
| 602 |
+
cbax : `~matplotlib.axes.Axes`
|
| 603 |
+
Axes for the colorbar.
|
| 604 |
+
"""
|
| 605 |
+
rowstart = np.inf
|
| 606 |
+
rowstop = -np.inf
|
| 607 |
+
colstart = np.inf
|
| 608 |
+
colstop = -np.inf
|
| 609 |
+
for parent in cbax._colorbar_info['parents']:
|
| 610 |
+
ss = parent.get_subplotspec()
|
| 611 |
+
rowstart = min(ss.rowspan.start, rowstart)
|
| 612 |
+
rowstop = max(ss.rowspan.stop, rowstop)
|
| 613 |
+
colstart = min(ss.colspan.start, colstart)
|
| 614 |
+
colstop = max(ss.colspan.stop, colstop)
|
| 615 |
+
|
| 616 |
+
rowspan = range(rowstart, rowstop)
|
| 617 |
+
colspan = range(colstart, colstop)
|
| 618 |
+
return rowspan, colspan
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def get_pos_and_bbox(ax, renderer):
|
| 622 |
+
"""
|
| 623 |
+
Get the position and the bbox for the Axes.
|
| 624 |
+
|
| 625 |
+
Parameters
|
| 626 |
+
----------
|
| 627 |
+
ax : `~matplotlib.axes.Axes`
|
| 628 |
+
renderer : `~matplotlib.backend_bases.RendererBase` subclass.
|
| 629 |
+
|
| 630 |
+
Returns
|
| 631 |
+
-------
|
| 632 |
+
pos : `~matplotlib.transforms.Bbox`
|
| 633 |
+
Position in figure coordinates.
|
| 634 |
+
bbox : `~matplotlib.transforms.Bbox`
|
| 635 |
+
Tight bounding box in figure coordinates.
|
| 636 |
+
"""
|
| 637 |
+
fig = ax.get_figure(root=False)
|
| 638 |
+
pos = ax.get_position(original=True)
|
| 639 |
+
# pos is in panel co-ords, but we need in figure for the layout
|
| 640 |
+
pos = pos.transformed(fig.transSubfigure - fig.transFigure)
|
| 641 |
+
tightbbox = martist._get_tightbbox_for_layout_only(ax, renderer)
|
| 642 |
+
if tightbbox is None:
|
| 643 |
+
bbox = pos
|
| 644 |
+
else:
|
| 645 |
+
bbox = tightbbox.transformed(fig.transFigure.inverted())
|
| 646 |
+
return pos, bbox
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def reposition_axes(layoutgrids, fig, renderer, *,
|
| 650 |
+
w_pad=0, h_pad=0, hspace=0, wspace=0):
|
| 651 |
+
"""
|
| 652 |
+
Reposition all the Axes based on the new inner bounding box.
|
| 653 |
+
"""
|
| 654 |
+
trans_fig_to_subfig = fig.transFigure - fig.transSubfigure
|
| 655 |
+
for sfig in fig.subfigs:
|
| 656 |
+
bbox = layoutgrids[sfig].get_outer_bbox()
|
| 657 |
+
sfig._redo_transform_rel_fig(
|
| 658 |
+
bbox=bbox.transformed(trans_fig_to_subfig))
|
| 659 |
+
reposition_axes(layoutgrids, sfig, renderer,
|
| 660 |
+
w_pad=w_pad, h_pad=h_pad,
|
| 661 |
+
wspace=wspace, hspace=hspace)
|
| 662 |
+
|
| 663 |
+
for ax in fig._localaxes:
|
| 664 |
+
if ax.get_subplotspec() is None or not ax.get_in_layout():
|
| 665 |
+
continue
|
| 666 |
+
|
| 667 |
+
# grid bbox is in Figure coordinates, but we specify in panel
|
| 668 |
+
# coordinates...
|
| 669 |
+
ss = ax.get_subplotspec()
|
| 670 |
+
gs = ss.get_gridspec()
|
| 671 |
+
if gs not in layoutgrids:
|
| 672 |
+
return
|
| 673 |
+
|
| 674 |
+
bbox = layoutgrids[gs].get_inner_bbox(rows=ss.rowspan,
|
| 675 |
+
cols=ss.colspan)
|
| 676 |
+
|
| 677 |
+
# transform from figure to panel for set_position:
|
| 678 |
+
newbbox = trans_fig_to_subfig.transform_bbox(bbox)
|
| 679 |
+
ax._set_position(newbbox)
|
| 680 |
+
|
| 681 |
+
# move the colorbars:
|
| 682 |
+
# we need to keep track of oldw and oldh if there is more than
|
| 683 |
+
# one colorbar:
|
| 684 |
+
offset = {'left': 0, 'right': 0, 'bottom': 0, 'top': 0}
|
| 685 |
+
for nn, cbax in enumerate(ax._colorbars[::-1]):
|
| 686 |
+
if ax == cbax._colorbar_info['parents'][0]:
|
| 687 |
+
reposition_colorbar(layoutgrids, cbax, renderer,
|
| 688 |
+
offset=offset)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None):
|
| 692 |
+
"""
|
| 693 |
+
Place the colorbar in its new place.
|
| 694 |
+
|
| 695 |
+
Parameters
|
| 696 |
+
----------
|
| 697 |
+
layoutgrids : dict
|
| 698 |
+
cbax : `~matplotlib.axes.Axes`
|
| 699 |
+
Axes for the colorbar.
|
| 700 |
+
renderer : `~matplotlib.backend_bases.RendererBase` subclass.
|
| 701 |
+
The renderer to use.
|
| 702 |
+
offset : array-like
|
| 703 |
+
Offset the colorbar needs to be pushed to in order to
|
| 704 |
+
account for multiple colorbars.
|
| 705 |
+
"""
|
| 706 |
+
|
| 707 |
+
parents = cbax._colorbar_info['parents']
|
| 708 |
+
gs = parents[0].get_gridspec()
|
| 709 |
+
fig = cbax.get_figure(root=False)
|
| 710 |
+
trans_fig_to_subfig = fig.transFigure - fig.transSubfigure
|
| 711 |
+
|
| 712 |
+
cb_rspans, cb_cspans = get_cb_parent_spans(cbax)
|
| 713 |
+
bboxparent = layoutgrids[gs].get_bbox_for_cb(rows=cb_rspans,
|
| 714 |
+
cols=cb_cspans)
|
| 715 |
+
pb = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans)
|
| 716 |
+
|
| 717 |
+
location = cbax._colorbar_info['location']
|
| 718 |
+
anchor = cbax._colorbar_info['anchor']
|
| 719 |
+
fraction = cbax._colorbar_info['fraction']
|
| 720 |
+
aspect = cbax._colorbar_info['aspect']
|
| 721 |
+
shrink = cbax._colorbar_info['shrink']
|
| 722 |
+
|
| 723 |
+
cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)
|
| 724 |
+
|
| 725 |
+
# Colorbar gets put at extreme edge of outer bbox of the subplotspec
|
| 726 |
+
# It needs to be moved in by: 1) a pad 2) its "margin" 3) by
|
| 727 |
+
# any colorbars already added at this location:
|
| 728 |
+
cbpad = colorbar_get_pad(layoutgrids, cbax)
|
| 729 |
+
if location in ('left', 'right'):
|
| 730 |
+
# fraction and shrink are fractions of parent
|
| 731 |
+
pbcb = pb.shrunk(fraction, shrink).anchored(anchor, pb)
|
| 732 |
+
# The colorbar is at the left side of the parent. Need
|
| 733 |
+
# to translate to right (or left)
|
| 734 |
+
if location == 'right':
|
| 735 |
+
lmargin = cbpos.x0 - cbbbox.x0
|
| 736 |
+
dx = bboxparent.x1 - pbcb.x0 + offset['right']
|
| 737 |
+
dx += cbpad + lmargin
|
| 738 |
+
offset['right'] += cbbbox.width + cbpad
|
| 739 |
+
pbcb = pbcb.translated(dx, 0)
|
| 740 |
+
else:
|
| 741 |
+
lmargin = cbpos.x0 - cbbbox.x0
|
| 742 |
+
dx = bboxparent.x0 - pbcb.x0 # edge of parent
|
| 743 |
+
dx += -cbbbox.width - cbpad + lmargin - offset['left']
|
| 744 |
+
offset['left'] += cbbbox.width + cbpad
|
| 745 |
+
pbcb = pbcb.translated(dx, 0)
|
| 746 |
+
else: # horizontal axes:
|
| 747 |
+
pbcb = pb.shrunk(shrink, fraction).anchored(anchor, pb)
|
| 748 |
+
if location == 'top':
|
| 749 |
+
bmargin = cbpos.y0 - cbbbox.y0
|
| 750 |
+
dy = bboxparent.y1 - pbcb.y0 + offset['top']
|
| 751 |
+
dy += cbpad + bmargin
|
| 752 |
+
offset['top'] += cbbbox.height + cbpad
|
| 753 |
+
pbcb = pbcb.translated(0, dy)
|
| 754 |
+
else:
|
| 755 |
+
bmargin = cbpos.y0 - cbbbox.y0
|
| 756 |
+
dy = bboxparent.y0 - pbcb.y0
|
| 757 |
+
dy += -cbbbox.height - cbpad + bmargin - offset['bottom']
|
| 758 |
+
offset['bottom'] += cbbbox.height + cbpad
|
| 759 |
+
pbcb = pbcb.translated(0, dy)
|
| 760 |
+
|
| 761 |
+
pbcb = trans_fig_to_subfig.transform_bbox(pbcb)
|
| 762 |
+
cbax.set_transform(fig.transSubfigure)
|
| 763 |
+
cbax._set_position(pbcb)
|
| 764 |
+
cbax.set_anchor(anchor)
|
| 765 |
+
if location in ['bottom', 'top']:
|
| 766 |
+
aspect = 1 / aspect
|
| 767 |
+
cbax.set_box_aspect(aspect)
|
| 768 |
+
cbax.set_aspect('auto')
|
| 769 |
+
return offset
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def reset_margins(layoutgrids, fig):
|
| 773 |
+
"""
|
| 774 |
+
Reset the margins in the layoutboxes of *fig*.
|
| 775 |
+
|
| 776 |
+
Margins are usually set as a minimum, so if the figure gets smaller
|
| 777 |
+
the minimum needs to be zero in order for it to grow again.
|
| 778 |
+
"""
|
| 779 |
+
for sfig in fig.subfigs:
|
| 780 |
+
reset_margins(layoutgrids, sfig)
|
| 781 |
+
for ax in fig.axes:
|
| 782 |
+
if ax.get_in_layout():
|
| 783 |
+
gs = ax.get_gridspec()
|
| 784 |
+
if gs in layoutgrids: # also implies gs is not None.
|
| 785 |
+
layoutgrids[gs].reset_margins()
|
| 786 |
+
layoutgrids[fig].reset_margins()
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def colorbar_get_pad(layoutgrids, cax):
|
| 790 |
+
parents = cax._colorbar_info['parents']
|
| 791 |
+
gs = parents[0].get_gridspec()
|
| 792 |
+
|
| 793 |
+
cb_rspans, cb_cspans = get_cb_parent_spans(cax)
|
| 794 |
+
bboxouter = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans)
|
| 795 |
+
|
| 796 |
+
if cax._colorbar_info['location'] in ['right', 'left']:
|
| 797 |
+
size = bboxouter.width
|
| 798 |
+
else:
|
| 799 |
+
size = bboxouter.height
|
| 800 |
+
|
| 801 |
+
return cax._colorbar_info['pad'] * size
|
moondream/lib/python3.10/site-packages/matplotlib/_docstring.pyi
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
from typing import Any, TypeVar, overload
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
_T = TypeVar('_T')
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def kwarg_doc(text: str) -> Callable[[_T], _T]: ...
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Substitution:
|
| 12 |
+
@overload
|
| 13 |
+
def __init__(self, *args: str): ...
|
| 14 |
+
@overload
|
| 15 |
+
def __init__(self, **kwargs: str): ...
|
| 16 |
+
def __call__(self, func: _T) -> _T: ...
|
| 17 |
+
def update(self, *args, **kwargs): ... # type: ignore[no-untyped-def]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class _ArtistKwdocLoader(dict[str, str]):
|
| 21 |
+
def __missing__(self, key: str) -> str: ...
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _ArtistPropertiesSubstitution:
|
| 25 |
+
def __init__(self) -> None: ...
|
| 26 |
+
def register(self, **kwargs) -> None: ...
|
| 27 |
+
def __call__(self, obj: _T) -> _T: ...
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def copy(source: Any) -> Callable[[_T], _T]: ...
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
dedent_interpd: _ArtistPropertiesSubstitution
|
| 34 |
+
interpd: _ArtistPropertiesSubstitution
|
moondream/lib/python3.10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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Enums representing sets of strings that Matplotlib uses as input parameters.
|
| 3 |
+
|
| 4 |
+
Matplotlib often uses simple data types like strings or tuples to define a
|
| 5 |
+
concept; e.g. the line capstyle can be specified as one of 'butt', 'round',
|
| 6 |
+
or 'projecting'. The classes in this module are used internally and serve to
|
| 7 |
+
document these concepts formally.
|
| 8 |
+
|
| 9 |
+
As an end-user you will not use these classes directly, but only the values
|
| 10 |
+
they define.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from enum import Enum, auto
|
| 14 |
+
from matplotlib import _docstring
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _AutoStringNameEnum(Enum):
|
| 18 |
+
"""Automate the ``name = 'name'`` part of making a (str, Enum)."""
|
| 19 |
+
|
| 20 |
+
def _generate_next_value_(name, start, count, last_values):
|
| 21 |
+
return name
|
| 22 |
+
|
| 23 |
+
def __hash__(self):
|
| 24 |
+
return str(self).__hash__()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class JoinStyle(str, _AutoStringNameEnum):
|
| 28 |
+
"""
|
| 29 |
+
Define how the connection between two line segments is drawn.
|
| 30 |
+
|
| 31 |
+
For a visual impression of each *JoinStyle*, `view these docs online
|
| 32 |
+
<JoinStyle>`, or run `JoinStyle.demo`.
|
| 33 |
+
|
| 34 |
+
Lines in Matplotlib are typically defined by a 1D `~.path.Path` and a
|
| 35 |
+
finite ``linewidth``, where the underlying 1D `~.path.Path` represents the
|
| 36 |
+
center of the stroked line.
|
| 37 |
+
|
| 38 |
+
By default, `~.backend_bases.GraphicsContextBase` defines the boundaries of
|
| 39 |
+
a stroked line to simply be every point within some radius,
|
| 40 |
+
``linewidth/2``, away from any point of the center line. However, this
|
| 41 |
+
results in corners appearing "rounded", which may not be the desired
|
| 42 |
+
behavior if you are drawing, for example, a polygon or pointed star.
|
| 43 |
+
|
| 44 |
+
**Supported values:**
|
| 45 |
+
|
| 46 |
+
.. rst-class:: value-list
|
| 47 |
+
|
| 48 |
+
'miter'
|
| 49 |
+
the "arrow-tip" style. Each boundary of the filled-in area will
|
| 50 |
+
extend in a straight line parallel to the tangent vector of the
|
| 51 |
+
centerline at the point it meets the corner, until they meet in a
|
| 52 |
+
sharp point.
|
| 53 |
+
'round'
|
| 54 |
+
stokes every point within a radius of ``linewidth/2`` of the center
|
| 55 |
+
lines.
|
| 56 |
+
'bevel'
|
| 57 |
+
the "squared-off" style. It can be thought of as a rounded corner
|
| 58 |
+
where the "circular" part of the corner has been cut off.
|
| 59 |
+
|
| 60 |
+
.. note::
|
| 61 |
+
|
| 62 |
+
Very long miter tips are cut off (to form a *bevel*) after a
|
| 63 |
+
backend-dependent limit called the "miter limit", which specifies the
|
| 64 |
+
maximum allowed ratio of miter length to line width. For example, the
|
| 65 |
+
PDF backend uses the default value of 10 specified by the PDF standard,
|
| 66 |
+
while the SVG backend does not even specify the miter limit, resulting
|
| 67 |
+
in a default value of 4 per the SVG specification. Matplotlib does not
|
| 68 |
+
currently allow the user to adjust this parameter.
|
| 69 |
+
|
| 70 |
+
A more detailed description of the effect of a miter limit can be found
|
| 71 |
+
in the `Mozilla Developer Docs
|
| 72 |
+
<https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit>`_
|
| 73 |
+
|
| 74 |
+
.. plot::
|
| 75 |
+
:alt: Demo of possible JoinStyle's
|
| 76 |
+
|
| 77 |
+
from matplotlib._enums import JoinStyle
|
| 78 |
+
JoinStyle.demo()
|
| 79 |
+
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
miter = auto()
|
| 83 |
+
round = auto()
|
| 84 |
+
bevel = auto()
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
def demo():
|
| 88 |
+
"""Demonstrate how each JoinStyle looks for various join angles."""
|
| 89 |
+
import numpy as np
|
| 90 |
+
import matplotlib.pyplot as plt
|
| 91 |
+
|
| 92 |
+
def plot_angle(ax, x, y, angle, style):
|
| 93 |
+
phi = np.radians(angle)
|
| 94 |
+
xx = [x + .5, x, x + .5*np.cos(phi)]
|
| 95 |
+
yy = [y, y, y + .5*np.sin(phi)]
|
| 96 |
+
ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style)
|
| 97 |
+
ax.plot(xx, yy, lw=1, color='black')
|
| 98 |
+
ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3)
|
| 99 |
+
|
| 100 |
+
fig, ax = plt.subplots(figsize=(5, 4), constrained_layout=True)
|
| 101 |
+
ax.set_title('Join style')
|
| 102 |
+
for x, style in enumerate(['miter', 'round', 'bevel']):
|
| 103 |
+
ax.text(x, 5, style)
|
| 104 |
+
for y, angle in enumerate([20, 45, 60, 90, 120]):
|
| 105 |
+
plot_angle(ax, x, y, angle, style)
|
| 106 |
+
if x == 0:
|
| 107 |
+
ax.text(-1.3, y, f'{angle} degrees')
|
| 108 |
+
ax.set_xlim(-1.5, 2.75)
|
| 109 |
+
ax.set_ylim(-.5, 5.5)
|
| 110 |
+
ax.set_axis_off()
|
| 111 |
+
fig.show()
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
JoinStyle.input_description = "{" \
|
| 115 |
+
+ ", ".join([f"'{js.name}'" for js in JoinStyle]) \
|
| 116 |
+
+ "}"
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class CapStyle(str, _AutoStringNameEnum):
|
| 120 |
+
r"""
|
| 121 |
+
Define how the two endpoints (caps) of an unclosed line are drawn.
|
| 122 |
+
|
| 123 |
+
How to draw the start and end points of lines that represent a closed curve
|
| 124 |
+
(i.e. that end in a `~.path.Path.CLOSEPOLY`) is controlled by the line's
|
| 125 |
+
`JoinStyle`. For all other lines, how the start and end points are drawn is
|
| 126 |
+
controlled by the *CapStyle*.
|
| 127 |
+
|
| 128 |
+
For a visual impression of each *CapStyle*, `view these docs online
|
| 129 |
+
<CapStyle>` or run `CapStyle.demo`.
|
| 130 |
+
|
| 131 |
+
By default, `~.backend_bases.GraphicsContextBase` draws a stroked line as
|
| 132 |
+
squared off at its endpoints.
|
| 133 |
+
|
| 134 |
+
**Supported values:**
|
| 135 |
+
|
| 136 |
+
.. rst-class:: value-list
|
| 137 |
+
|
| 138 |
+
'butt'
|
| 139 |
+
the line is squared off at its endpoint.
|
| 140 |
+
'projecting'
|
| 141 |
+
the line is squared off as in *butt*, but the filled in area
|
| 142 |
+
extends beyond the endpoint a distance of ``linewidth/2``.
|
| 143 |
+
'round'
|
| 144 |
+
like *butt*, but a semicircular cap is added to the end of the
|
| 145 |
+
line, of radius ``linewidth/2``.
|
| 146 |
+
|
| 147 |
+
.. plot::
|
| 148 |
+
:alt: Demo of possible CapStyle's
|
| 149 |
+
|
| 150 |
+
from matplotlib._enums import CapStyle
|
| 151 |
+
CapStyle.demo()
|
| 152 |
+
|
| 153 |
+
"""
|
| 154 |
+
butt = auto()
|
| 155 |
+
projecting = auto()
|
| 156 |
+
round = auto()
|
| 157 |
+
|
| 158 |
+
@staticmethod
|
| 159 |
+
def demo():
|
| 160 |
+
"""Demonstrate how each CapStyle looks for a thick line segment."""
|
| 161 |
+
import matplotlib.pyplot as plt
|
| 162 |
+
|
| 163 |
+
fig = plt.figure(figsize=(4, 1.2))
|
| 164 |
+
ax = fig.add_axes([0, 0, 1, 0.8])
|
| 165 |
+
ax.set_title('Cap style')
|
| 166 |
+
|
| 167 |
+
for x, style in enumerate(['butt', 'round', 'projecting']):
|
| 168 |
+
ax.text(x+0.25, 0.85, style, ha='center')
|
| 169 |
+
xx = [x, x+0.5]
|
| 170 |
+
yy = [0, 0]
|
| 171 |
+
ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style)
|
| 172 |
+
ax.plot(xx, yy, lw=1, color='black')
|
| 173 |
+
ax.plot(xx, yy, 'o', color='tab:red', markersize=3)
|
| 174 |
+
|
| 175 |
+
ax.set_ylim(-.5, 1.5)
|
| 176 |
+
ax.set_axis_off()
|
| 177 |
+
fig.show()
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
CapStyle.input_description = "{" \
|
| 181 |
+
+ ", ".join([f"'{cs.name}'" for cs in CapStyle]) \
|
| 182 |
+
+ "}"
|
| 183 |
+
|
| 184 |
+
_docstring.interpd.register(
|
| 185 |
+
JoinStyle=JoinStyle.input_description,
|
| 186 |
+
CapStyle=CapStyle.input_description,
|
| 187 |
+
)
|
moondream/lib/python3.10/site-packages/matplotlib/_mathtext_data.py
ADDED
|
@@ -0,0 +1,1742 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
font data tables for truetype and afm computer modern fonts
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
from typing import overload
|
| 7 |
+
|
| 8 |
+
latex_to_bakoma = {
|
| 9 |
+
'\\__sqrt__' : ('cmex10', 0x70),
|
| 10 |
+
'\\bigcap' : ('cmex10', 0x5c),
|
| 11 |
+
'\\bigcup' : ('cmex10', 0x5b),
|
| 12 |
+
'\\bigodot' : ('cmex10', 0x4b),
|
| 13 |
+
'\\bigoplus' : ('cmex10', 0x4d),
|
| 14 |
+
'\\bigotimes' : ('cmex10', 0x4f),
|
| 15 |
+
'\\biguplus' : ('cmex10', 0x5d),
|
| 16 |
+
'\\bigvee' : ('cmex10', 0x5f),
|
| 17 |
+
'\\bigwedge' : ('cmex10', 0x5e),
|
| 18 |
+
'\\coprod' : ('cmex10', 0x61),
|
| 19 |
+
'\\int' : ('cmex10', 0x5a),
|
| 20 |
+
'\\langle' : ('cmex10', 0xad),
|
| 21 |
+
'\\leftangle' : ('cmex10', 0xad),
|
| 22 |
+
'\\leftbrace' : ('cmex10', 0xa9),
|
| 23 |
+
'\\oint' : ('cmex10', 0x49),
|
| 24 |
+
'\\prod' : ('cmex10', 0x59),
|
| 25 |
+
'\\rangle' : ('cmex10', 0xae),
|
| 26 |
+
'\\rightangle' : ('cmex10', 0xae),
|
| 27 |
+
'\\rightbrace' : ('cmex10', 0xaa),
|
| 28 |
+
'\\sum' : ('cmex10', 0x58),
|
| 29 |
+
'\\widehat' : ('cmex10', 0x62),
|
| 30 |
+
'\\widetilde' : ('cmex10', 0x65),
|
| 31 |
+
'\\{' : ('cmex10', 0xa9),
|
| 32 |
+
'\\}' : ('cmex10', 0xaa),
|
| 33 |
+
'{' : ('cmex10', 0xa9),
|
| 34 |
+
'}' : ('cmex10', 0xaa),
|
| 35 |
+
|
| 36 |
+
',' : ('cmmi10', 0x3b),
|
| 37 |
+
'.' : ('cmmi10', 0x3a),
|
| 38 |
+
'/' : ('cmmi10', 0x3d),
|
| 39 |
+
'<' : ('cmmi10', 0x3c),
|
| 40 |
+
'>' : ('cmmi10', 0x3e),
|
| 41 |
+
'\\alpha' : ('cmmi10', 0xae),
|
| 42 |
+
'\\beta' : ('cmmi10', 0xaf),
|
| 43 |
+
'\\chi' : ('cmmi10', 0xc2),
|
| 44 |
+
'\\combiningrightarrowabove' : ('cmmi10', 0x7e),
|
| 45 |
+
'\\delta' : ('cmmi10', 0xb1),
|
| 46 |
+
'\\ell' : ('cmmi10', 0x60),
|
| 47 |
+
'\\epsilon' : ('cmmi10', 0xb2),
|
| 48 |
+
'\\eta' : ('cmmi10', 0xb4),
|
| 49 |
+
'\\flat' : ('cmmi10', 0x5b),
|
| 50 |
+
'\\frown' : ('cmmi10', 0x5f),
|
| 51 |
+
'\\gamma' : ('cmmi10', 0xb0),
|
| 52 |
+
'\\imath' : ('cmmi10', 0x7b),
|
| 53 |
+
'\\iota' : ('cmmi10', 0xb6),
|
| 54 |
+
'\\jmath' : ('cmmi10', 0x7c),
|
| 55 |
+
'\\kappa' : ('cmmi10', 0x2219),
|
| 56 |
+
'\\lambda' : ('cmmi10', 0xb8),
|
| 57 |
+
'\\leftharpoondown' : ('cmmi10', 0x29),
|
| 58 |
+
'\\leftharpoonup' : ('cmmi10', 0x28),
|
| 59 |
+
'\\mu' : ('cmmi10', 0xb9),
|
| 60 |
+
'\\natural' : ('cmmi10', 0x5c),
|
| 61 |
+
'\\nu' : ('cmmi10', 0xba),
|
| 62 |
+
'\\omega' : ('cmmi10', 0x21),
|
| 63 |
+
'\\phi' : ('cmmi10', 0xc1),
|
| 64 |
+
'\\pi' : ('cmmi10', 0xbc),
|
| 65 |
+
'\\psi' : ('cmmi10', 0xc3),
|
| 66 |
+
'\\rho' : ('cmmi10', 0xbd),
|
| 67 |
+
'\\rightharpoondown' : ('cmmi10', 0x2b),
|
| 68 |
+
'\\rightharpoonup' : ('cmmi10', 0x2a),
|
| 69 |
+
'\\sharp' : ('cmmi10', 0x5d),
|
| 70 |
+
'\\sigma' : ('cmmi10', 0xbe),
|
| 71 |
+
'\\smile' : ('cmmi10', 0x5e),
|
| 72 |
+
'\\tau' : ('cmmi10', 0xbf),
|
| 73 |
+
'\\theta' : ('cmmi10', 0xb5),
|
| 74 |
+
'\\triangleleft' : ('cmmi10', 0x2f),
|
| 75 |
+
'\\triangleright' : ('cmmi10', 0x2e),
|
| 76 |
+
'\\upsilon' : ('cmmi10', 0xc0),
|
| 77 |
+
'\\varepsilon' : ('cmmi10', 0x22),
|
| 78 |
+
'\\varphi' : ('cmmi10', 0x27),
|
| 79 |
+
'\\varrho' : ('cmmi10', 0x25),
|
| 80 |
+
'\\varsigma' : ('cmmi10', 0x26),
|
| 81 |
+
'\\vartheta' : ('cmmi10', 0x23),
|
| 82 |
+
'\\wp' : ('cmmi10', 0x7d),
|
| 83 |
+
'\\xi' : ('cmmi10', 0xbb),
|
| 84 |
+
'\\zeta' : ('cmmi10', 0xb3),
|
| 85 |
+
|
| 86 |
+
'!' : ('cmr10', 0x21),
|
| 87 |
+
'%' : ('cmr10', 0x25),
|
| 88 |
+
'&' : ('cmr10', 0x26),
|
| 89 |
+
'(' : ('cmr10', 0x28),
|
| 90 |
+
')' : ('cmr10', 0x29),
|
| 91 |
+
'+' : ('cmr10', 0x2b),
|
| 92 |
+
'0' : ('cmr10', 0x30),
|
| 93 |
+
'1' : ('cmr10', 0x31),
|
| 94 |
+
'2' : ('cmr10', 0x32),
|
| 95 |
+
'3' : ('cmr10', 0x33),
|
| 96 |
+
'4' : ('cmr10', 0x34),
|
| 97 |
+
'5' : ('cmr10', 0x35),
|
| 98 |
+
'6' : ('cmr10', 0x36),
|
| 99 |
+
'7' : ('cmr10', 0x37),
|
| 100 |
+
'8' : ('cmr10', 0x38),
|
| 101 |
+
'9' : ('cmr10', 0x39),
|
| 102 |
+
':' : ('cmr10', 0x3a),
|
| 103 |
+
';' : ('cmr10', 0x3b),
|
| 104 |
+
'=' : ('cmr10', 0x3d),
|
| 105 |
+
'?' : ('cmr10', 0x3f),
|
| 106 |
+
'@' : ('cmr10', 0x40),
|
| 107 |
+
'[' : ('cmr10', 0x5b),
|
| 108 |
+
'\\#' : ('cmr10', 0x23),
|
| 109 |
+
'\\$' : ('cmr10', 0x24),
|
| 110 |
+
'\\%' : ('cmr10', 0x25),
|
| 111 |
+
'\\Delta' : ('cmr10', 0xa2),
|
| 112 |
+
'\\Gamma' : ('cmr10', 0xa1),
|
| 113 |
+
'\\Lambda' : ('cmr10', 0xa4),
|
| 114 |
+
'\\Omega' : ('cmr10', 0xad),
|
| 115 |
+
'\\Phi' : ('cmr10', 0xa9),
|
| 116 |
+
'\\Pi' : ('cmr10', 0xa6),
|
| 117 |
+
'\\Psi' : ('cmr10', 0xaa),
|
| 118 |
+
'\\Sigma' : ('cmr10', 0xa7),
|
| 119 |
+
'\\Theta' : ('cmr10', 0xa3),
|
| 120 |
+
'\\Upsilon' : ('cmr10', 0xa8),
|
| 121 |
+
'\\Xi' : ('cmr10', 0xa5),
|
| 122 |
+
'\\circumflexaccent' : ('cmr10', 0x5e),
|
| 123 |
+
'\\combiningacuteaccent' : ('cmr10', 0xb6),
|
| 124 |
+
'\\combiningbreve' : ('cmr10', 0xb8),
|
| 125 |
+
'\\combiningdiaeresis' : ('cmr10', 0xc4),
|
| 126 |
+
'\\combiningdotabove' : ('cmr10', 0x5f),
|
| 127 |
+
'\\combininggraveaccent' : ('cmr10', 0xb5),
|
| 128 |
+
'\\combiningoverline' : ('cmr10', 0xb9),
|
| 129 |
+
'\\combiningtilde' : ('cmr10', 0x7e),
|
| 130 |
+
'\\leftbracket' : ('cmr10', 0x5b),
|
| 131 |
+
'\\leftparen' : ('cmr10', 0x28),
|
| 132 |
+
'\\rightbracket' : ('cmr10', 0x5d),
|
| 133 |
+
'\\rightparen' : ('cmr10', 0x29),
|
| 134 |
+
'\\widebar' : ('cmr10', 0xb9),
|
| 135 |
+
']' : ('cmr10', 0x5d),
|
| 136 |
+
|
| 137 |
+
'*' : ('cmsy10', 0xa4),
|
| 138 |
+
'\N{MINUS SIGN}' : ('cmsy10', 0xa1),
|
| 139 |
+
'\\Downarrow' : ('cmsy10', 0x2b),
|
| 140 |
+
'\\Im' : ('cmsy10', 0x3d),
|
| 141 |
+
'\\Leftarrow' : ('cmsy10', 0x28),
|
| 142 |
+
'\\Leftrightarrow' : ('cmsy10', 0x2c),
|
| 143 |
+
'\\P' : ('cmsy10', 0x7b),
|
| 144 |
+
'\\Re' : ('cmsy10', 0x3c),
|
| 145 |
+
'\\Rightarrow' : ('cmsy10', 0x29),
|
| 146 |
+
'\\S' : ('cmsy10', 0x78),
|
| 147 |
+
'\\Uparrow' : ('cmsy10', 0x2a),
|
| 148 |
+
'\\Updownarrow' : ('cmsy10', 0x6d),
|
| 149 |
+
'\\Vert' : ('cmsy10', 0x6b),
|
| 150 |
+
'\\aleph' : ('cmsy10', 0x40),
|
| 151 |
+
'\\approx' : ('cmsy10', 0xbc),
|
| 152 |
+
'\\ast' : ('cmsy10', 0xa4),
|
| 153 |
+
'\\asymp' : ('cmsy10', 0xb3),
|
| 154 |
+
'\\backslash' : ('cmsy10', 0x6e),
|
| 155 |
+
'\\bigcirc' : ('cmsy10', 0xb0),
|
| 156 |
+
'\\bigtriangledown' : ('cmsy10', 0x35),
|
| 157 |
+
'\\bigtriangleup' : ('cmsy10', 0x34),
|
| 158 |
+
'\\bot' : ('cmsy10', 0x3f),
|
| 159 |
+
'\\bullet' : ('cmsy10', 0xb2),
|
| 160 |
+
'\\cap' : ('cmsy10', 0x5c),
|
| 161 |
+
'\\cdot' : ('cmsy10', 0xa2),
|
| 162 |
+
'\\circ' : ('cmsy10', 0xb1),
|
| 163 |
+
'\\clubsuit' : ('cmsy10', 0x7c),
|
| 164 |
+
'\\cup' : ('cmsy10', 0x5b),
|
| 165 |
+
'\\dag' : ('cmsy10', 0x79),
|
| 166 |
+
'\\dashv' : ('cmsy10', 0x61),
|
| 167 |
+
'\\ddag' : ('cmsy10', 0x7a),
|
| 168 |
+
'\\diamond' : ('cmsy10', 0xa6),
|
| 169 |
+
'\\diamondsuit' : ('cmsy10', 0x7d),
|
| 170 |
+
'\\div' : ('cmsy10', 0xa5),
|
| 171 |
+
'\\downarrow' : ('cmsy10', 0x23),
|
| 172 |
+
'\\emptyset' : ('cmsy10', 0x3b),
|
| 173 |
+
'\\equiv' : ('cmsy10', 0xb4),
|
| 174 |
+
'\\exists' : ('cmsy10', 0x39),
|
| 175 |
+
'\\forall' : ('cmsy10', 0x38),
|
| 176 |
+
'\\geq' : ('cmsy10', 0xb8),
|
| 177 |
+
'\\gg' : ('cmsy10', 0xc0),
|
| 178 |
+
'\\heartsuit' : ('cmsy10', 0x7e),
|
| 179 |
+
'\\in' : ('cmsy10', 0x32),
|
| 180 |
+
'\\infty' : ('cmsy10', 0x31),
|
| 181 |
+
'\\lbrace' : ('cmsy10', 0x66),
|
| 182 |
+
'\\lceil' : ('cmsy10', 0x64),
|
| 183 |
+
'\\leftarrow' : ('cmsy10', 0xc3),
|
| 184 |
+
'\\leftrightarrow' : ('cmsy10', 0x24),
|
| 185 |
+
'\\leq' : ('cmsy10', 0x2219),
|
| 186 |
+
'\\lfloor' : ('cmsy10', 0x62),
|
| 187 |
+
'\\ll' : ('cmsy10', 0xbf),
|
| 188 |
+
'\\mid' : ('cmsy10', 0x6a),
|
| 189 |
+
'\\mp' : ('cmsy10', 0xa8),
|
| 190 |
+
'\\nabla' : ('cmsy10', 0x72),
|
| 191 |
+
'\\nearrow' : ('cmsy10', 0x25),
|
| 192 |
+
'\\neg' : ('cmsy10', 0x3a),
|
| 193 |
+
'\\ni' : ('cmsy10', 0x33),
|
| 194 |
+
'\\nwarrow' : ('cmsy10', 0x2d),
|
| 195 |
+
'\\odot' : ('cmsy10', 0xaf),
|
| 196 |
+
'\\ominus' : ('cmsy10', 0xaa),
|
| 197 |
+
'\\oplus' : ('cmsy10', 0xa9),
|
| 198 |
+
'\\oslash' : ('cmsy10', 0xae),
|
| 199 |
+
'\\otimes' : ('cmsy10', 0xad),
|
| 200 |
+
'\\pm' : ('cmsy10', 0xa7),
|
| 201 |
+
'\\prec' : ('cmsy10', 0xc1),
|
| 202 |
+
'\\preceq' : ('cmsy10', 0xb9),
|
| 203 |
+
'\\prime' : ('cmsy10', 0x30),
|
| 204 |
+
'\\propto' : ('cmsy10', 0x2f),
|
| 205 |
+
'\\rbrace' : ('cmsy10', 0x67),
|
| 206 |
+
'\\rceil' : ('cmsy10', 0x65),
|
| 207 |
+
'\\rfloor' : ('cmsy10', 0x63),
|
| 208 |
+
'\\rightarrow' : ('cmsy10', 0x21),
|
| 209 |
+
'\\searrow' : ('cmsy10', 0x26),
|
| 210 |
+
'\\sim' : ('cmsy10', 0xbb),
|
| 211 |
+
'\\simeq' : ('cmsy10', 0x27),
|
| 212 |
+
'\\slash' : ('cmsy10', 0x36),
|
| 213 |
+
'\\spadesuit' : ('cmsy10', 0xc4),
|
| 214 |
+
'\\sqcap' : ('cmsy10', 0x75),
|
| 215 |
+
'\\sqcup' : ('cmsy10', 0x74),
|
| 216 |
+
'\\sqsubseteq' : ('cmsy10', 0x76),
|
| 217 |
+
'\\sqsupseteq' : ('cmsy10', 0x77),
|
| 218 |
+
'\\subset' : ('cmsy10', 0xbd),
|
| 219 |
+
'\\subseteq' : ('cmsy10', 0xb5),
|
| 220 |
+
'\\succ' : ('cmsy10', 0xc2),
|
| 221 |
+
'\\succeq' : ('cmsy10', 0xba),
|
| 222 |
+
'\\supset' : ('cmsy10', 0xbe),
|
| 223 |
+
'\\supseteq' : ('cmsy10', 0xb6),
|
| 224 |
+
'\\swarrow' : ('cmsy10', 0x2e),
|
| 225 |
+
'\\times' : ('cmsy10', 0xa3),
|
| 226 |
+
'\\to' : ('cmsy10', 0x21),
|
| 227 |
+
'\\top' : ('cmsy10', 0x3e),
|
| 228 |
+
'\\uparrow' : ('cmsy10', 0x22),
|
| 229 |
+
'\\updownarrow' : ('cmsy10', 0x6c),
|
| 230 |
+
'\\uplus' : ('cmsy10', 0x5d),
|
| 231 |
+
'\\vdash' : ('cmsy10', 0x60),
|
| 232 |
+
'\\vee' : ('cmsy10', 0x5f),
|
| 233 |
+
'\\vert' : ('cmsy10', 0x6a),
|
| 234 |
+
'\\wedge' : ('cmsy10', 0x5e),
|
| 235 |
+
'\\wr' : ('cmsy10', 0x6f),
|
| 236 |
+
'\\|' : ('cmsy10', 0x6b),
|
| 237 |
+
'|' : ('cmsy10', 0x6a),
|
| 238 |
+
|
| 239 |
+
'\\_' : ('cmtt10', 0x5f)
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
# Automatically generated.
|
| 243 |
+
|
| 244 |
+
type12uni = {
|
| 245 |
+
'aring' : 229,
|
| 246 |
+
'quotedblright' : 8221,
|
| 247 |
+
'V' : 86,
|
| 248 |
+
'dollar' : 36,
|
| 249 |
+
'four' : 52,
|
| 250 |
+
'Yacute' : 221,
|
| 251 |
+
'P' : 80,
|
| 252 |
+
'underscore' : 95,
|
| 253 |
+
'p' : 112,
|
| 254 |
+
'Otilde' : 213,
|
| 255 |
+
'perthousand' : 8240,
|
| 256 |
+
'zero' : 48,
|
| 257 |
+
'dotlessi' : 305,
|
| 258 |
+
'Scaron' : 352,
|
| 259 |
+
'zcaron' : 382,
|
| 260 |
+
'egrave' : 232,
|
| 261 |
+
'section' : 167,
|
| 262 |
+
'Icircumflex' : 206,
|
| 263 |
+
'ntilde' : 241,
|
| 264 |
+
'ampersand' : 38,
|
| 265 |
+
'dotaccent' : 729,
|
| 266 |
+
'degree' : 176,
|
| 267 |
+
'K' : 75,
|
| 268 |
+
'acircumflex' : 226,
|
| 269 |
+
'Aring' : 197,
|
| 270 |
+
'k' : 107,
|
| 271 |
+
'smalltilde' : 732,
|
| 272 |
+
'Agrave' : 192,
|
| 273 |
+
'divide' : 247,
|
| 274 |
+
'ocircumflex' : 244,
|
| 275 |
+
'asciitilde' : 126,
|
| 276 |
+
'two' : 50,
|
| 277 |
+
'E' : 69,
|
| 278 |
+
'scaron' : 353,
|
| 279 |
+
'F' : 70,
|
| 280 |
+
'bracketleft' : 91,
|
| 281 |
+
'asciicircum' : 94,
|
| 282 |
+
'f' : 102,
|
| 283 |
+
'ordmasculine' : 186,
|
| 284 |
+
'mu' : 181,
|
| 285 |
+
'paragraph' : 182,
|
| 286 |
+
'nine' : 57,
|
| 287 |
+
'v' : 118,
|
| 288 |
+
'guilsinglleft' : 8249,
|
| 289 |
+
'backslash' : 92,
|
| 290 |
+
'six' : 54,
|
| 291 |
+
'A' : 65,
|
| 292 |
+
'icircumflex' : 238,
|
| 293 |
+
'a' : 97,
|
| 294 |
+
'ogonek' : 731,
|
| 295 |
+
'q' : 113,
|
| 296 |
+
'oacute' : 243,
|
| 297 |
+
'ograve' : 242,
|
| 298 |
+
'edieresis' : 235,
|
| 299 |
+
'comma' : 44,
|
| 300 |
+
'otilde' : 245,
|
| 301 |
+
'guillemotright' : 187,
|
| 302 |
+
'ecircumflex' : 234,
|
| 303 |
+
'greater' : 62,
|
| 304 |
+
'uacute' : 250,
|
| 305 |
+
'L' : 76,
|
| 306 |
+
'bullet' : 8226,
|
| 307 |
+
'cedilla' : 184,
|
| 308 |
+
'ydieresis' : 255,
|
| 309 |
+
'l' : 108,
|
| 310 |
+
'logicalnot' : 172,
|
| 311 |
+
'exclamdown' : 161,
|
| 312 |
+
'endash' : 8211,
|
| 313 |
+
'agrave' : 224,
|
| 314 |
+
'Adieresis' : 196,
|
| 315 |
+
'germandbls' : 223,
|
| 316 |
+
'Odieresis' : 214,
|
| 317 |
+
'space' : 32,
|
| 318 |
+
'quoteright' : 8217,
|
| 319 |
+
'ucircumflex' : 251,
|
| 320 |
+
'G' : 71,
|
| 321 |
+
'quoteleft' : 8216,
|
| 322 |
+
'W' : 87,
|
| 323 |
+
'Q' : 81,
|
| 324 |
+
'g' : 103,
|
| 325 |
+
'w' : 119,
|
| 326 |
+
'question' : 63,
|
| 327 |
+
'one' : 49,
|
| 328 |
+
'ring' : 730,
|
| 329 |
+
'figuredash' : 8210,
|
| 330 |
+
'B' : 66,
|
| 331 |
+
'iacute' : 237,
|
| 332 |
+
'Ydieresis' : 376,
|
| 333 |
+
'R' : 82,
|
| 334 |
+
'b' : 98,
|
| 335 |
+
'r' : 114,
|
| 336 |
+
'Ccedilla' : 199,
|
| 337 |
+
'minus' : 8722,
|
| 338 |
+
'Lslash' : 321,
|
| 339 |
+
'Uacute' : 218,
|
| 340 |
+
'yacute' : 253,
|
| 341 |
+
'Ucircumflex' : 219,
|
| 342 |
+
'quotedbl' : 34,
|
| 343 |
+
'onehalf' : 189,
|
| 344 |
+
'Thorn' : 222,
|
| 345 |
+
'M' : 77,
|
| 346 |
+
'eight' : 56,
|
| 347 |
+
'multiply' : 215,
|
| 348 |
+
'grave' : 96,
|
| 349 |
+
'Ocircumflex' : 212,
|
| 350 |
+
'm' : 109,
|
| 351 |
+
'Ugrave' : 217,
|
| 352 |
+
'guilsinglright' : 8250,
|
| 353 |
+
'Ntilde' : 209,
|
| 354 |
+
'questiondown' : 191,
|
| 355 |
+
'Atilde' : 195,
|
| 356 |
+
'ccedilla' : 231,
|
| 357 |
+
'Z' : 90,
|
| 358 |
+
'copyright' : 169,
|
| 359 |
+
'yen' : 165,
|
| 360 |
+
'Eacute' : 201,
|
| 361 |
+
'H' : 72,
|
| 362 |
+
'X' : 88,
|
| 363 |
+
'Idieresis' : 207,
|
| 364 |
+
'bar' : 124,
|
| 365 |
+
'h' : 104,
|
| 366 |
+
'x' : 120,
|
| 367 |
+
'udieresis' : 252,
|
| 368 |
+
'ordfeminine' : 170,
|
| 369 |
+
'braceleft' : 123,
|
| 370 |
+
'macron' : 175,
|
| 371 |
+
'atilde' : 227,
|
| 372 |
+
'Acircumflex' : 194,
|
| 373 |
+
'Oslash' : 216,
|
| 374 |
+
'C' : 67,
|
| 375 |
+
'quotedblleft' : 8220,
|
| 376 |
+
'S' : 83,
|
| 377 |
+
'exclam' : 33,
|
| 378 |
+
'Zcaron' : 381,
|
| 379 |
+
'equal' : 61,
|
| 380 |
+
's' : 115,
|
| 381 |
+
'eth' : 240,
|
| 382 |
+
'Egrave' : 200,
|
| 383 |
+
'hyphen' : 45,
|
| 384 |
+
'period' : 46,
|
| 385 |
+
'igrave' : 236,
|
| 386 |
+
'colon' : 58,
|
| 387 |
+
'Ecircumflex' : 202,
|
| 388 |
+
'trademark' : 8482,
|
| 389 |
+
'Aacute' : 193,
|
| 390 |
+
'cent' : 162,
|
| 391 |
+
'lslash' : 322,
|
| 392 |
+
'c' : 99,
|
| 393 |
+
'N' : 78,
|
| 394 |
+
'breve' : 728,
|
| 395 |
+
'Oacute' : 211,
|
| 396 |
+
'guillemotleft' : 171,
|
| 397 |
+
'n' : 110,
|
| 398 |
+
'idieresis' : 239,
|
| 399 |
+
'braceright' : 125,
|
| 400 |
+
'seven' : 55,
|
| 401 |
+
'brokenbar' : 166,
|
| 402 |
+
'ugrave' : 249,
|
| 403 |
+
'periodcentered' : 183,
|
| 404 |
+
'sterling' : 163,
|
| 405 |
+
'I' : 73,
|
| 406 |
+
'Y' : 89,
|
| 407 |
+
'Eth' : 208,
|
| 408 |
+
'emdash' : 8212,
|
| 409 |
+
'i' : 105,
|
| 410 |
+
'daggerdbl' : 8225,
|
| 411 |
+
'y' : 121,
|
| 412 |
+
'plusminus' : 177,
|
| 413 |
+
'less' : 60,
|
| 414 |
+
'Udieresis' : 220,
|
| 415 |
+
'D' : 68,
|
| 416 |
+
'five' : 53,
|
| 417 |
+
'T' : 84,
|
| 418 |
+
'oslash' : 248,
|
| 419 |
+
'acute' : 180,
|
| 420 |
+
'd' : 100,
|
| 421 |
+
'OE' : 338,
|
| 422 |
+
'Igrave' : 204,
|
| 423 |
+
't' : 116,
|
| 424 |
+
'parenright' : 41,
|
| 425 |
+
'adieresis' : 228,
|
| 426 |
+
'quotesingle' : 39,
|
| 427 |
+
'twodotenleader' : 8229,
|
| 428 |
+
'slash' : 47,
|
| 429 |
+
'ellipsis' : 8230,
|
| 430 |
+
'numbersign' : 35,
|
| 431 |
+
'odieresis' : 246,
|
| 432 |
+
'O' : 79,
|
| 433 |
+
'oe' : 339,
|
| 434 |
+
'o' : 111,
|
| 435 |
+
'Edieresis' : 203,
|
| 436 |
+
'plus' : 43,
|
| 437 |
+
'dagger' : 8224,
|
| 438 |
+
'three' : 51,
|
| 439 |
+
'hungarumlaut' : 733,
|
| 440 |
+
'parenleft' : 40,
|
| 441 |
+
'fraction' : 8260,
|
| 442 |
+
'registered' : 174,
|
| 443 |
+
'J' : 74,
|
| 444 |
+
'dieresis' : 168,
|
| 445 |
+
'Ograve' : 210,
|
| 446 |
+
'j' : 106,
|
| 447 |
+
'z' : 122,
|
| 448 |
+
'ae' : 230,
|
| 449 |
+
'semicolon' : 59,
|
| 450 |
+
'at' : 64,
|
| 451 |
+
'Iacute' : 205,
|
| 452 |
+
'percent' : 37,
|
| 453 |
+
'bracketright' : 93,
|
| 454 |
+
'AE' : 198,
|
| 455 |
+
'asterisk' : 42,
|
| 456 |
+
'aacute' : 225,
|
| 457 |
+
'U' : 85,
|
| 458 |
+
'eacute' : 233,
|
| 459 |
+
'e' : 101,
|
| 460 |
+
'thorn' : 254,
|
| 461 |
+
'u' : 117,
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
uni2type1 = {v: k for k, v in type12uni.items()}
|
| 465 |
+
|
| 466 |
+
# The script below is to sort and format the tex2uni dict
|
| 467 |
+
|
| 468 |
+
## For decimal values: int(hex(v), 16)
|
| 469 |
+
# newtex = {k: hex(v) for k, v in tex2uni.items()}
|
| 470 |
+
# sd = dict(sorted(newtex.items(), key=lambda item: item[0]))
|
| 471 |
+
#
|
| 472 |
+
## For formatting the sorted dictionary with proper spacing
|
| 473 |
+
## the value '24' comes from finding the longest string in
|
| 474 |
+
## the newtex keys with len(max(newtex, key=len))
|
| 475 |
+
# for key in sd:
|
| 476 |
+
# print("{0:24} : {1: <s},".format("'" + key + "'", sd[key]))
|
| 477 |
+
|
| 478 |
+
tex2uni = {
|
| 479 |
+
'#' : 0x23,
|
| 480 |
+
'$' : 0x24,
|
| 481 |
+
'%' : 0x25,
|
| 482 |
+
'AA' : 0xc5,
|
| 483 |
+
'AE' : 0xc6,
|
| 484 |
+
'BbbC' : 0x2102,
|
| 485 |
+
'BbbN' : 0x2115,
|
| 486 |
+
'BbbP' : 0x2119,
|
| 487 |
+
'BbbQ' : 0x211a,
|
| 488 |
+
'BbbR' : 0x211d,
|
| 489 |
+
'BbbZ' : 0x2124,
|
| 490 |
+
'Bumpeq' : 0x224e,
|
| 491 |
+
'Cap' : 0x22d2,
|
| 492 |
+
'Colon' : 0x2237,
|
| 493 |
+
'Cup' : 0x22d3,
|
| 494 |
+
'DH' : 0xd0,
|
| 495 |
+
'Delta' : 0x394,
|
| 496 |
+
'Doteq' : 0x2251,
|
| 497 |
+
'Downarrow' : 0x21d3,
|
| 498 |
+
'Equiv' : 0x2263,
|
| 499 |
+
'Finv' : 0x2132,
|
| 500 |
+
'Game' : 0x2141,
|
| 501 |
+
'Gamma' : 0x393,
|
| 502 |
+
'H' : 0x30b,
|
| 503 |
+
'Im' : 0x2111,
|
| 504 |
+
'Join' : 0x2a1d,
|
| 505 |
+
'L' : 0x141,
|
| 506 |
+
'Lambda' : 0x39b,
|
| 507 |
+
'Ldsh' : 0x21b2,
|
| 508 |
+
'Leftarrow' : 0x21d0,
|
| 509 |
+
'Leftrightarrow' : 0x21d4,
|
| 510 |
+
'Lleftarrow' : 0x21da,
|
| 511 |
+
'Longleftarrow' : 0x27f8,
|
| 512 |
+
'Longleftrightarrow' : 0x27fa,
|
| 513 |
+
'Longrightarrow' : 0x27f9,
|
| 514 |
+
'Lsh' : 0x21b0,
|
| 515 |
+
'Nearrow' : 0x21d7,
|
| 516 |
+
'Nwarrow' : 0x21d6,
|
| 517 |
+
'O' : 0xd8,
|
| 518 |
+
'OE' : 0x152,
|
| 519 |
+
'Omega' : 0x3a9,
|
| 520 |
+
'P' : 0xb6,
|
| 521 |
+
'Phi' : 0x3a6,
|
| 522 |
+
'Pi' : 0x3a0,
|
| 523 |
+
'Psi' : 0x3a8,
|
| 524 |
+
'QED' : 0x220e,
|
| 525 |
+
'Rdsh' : 0x21b3,
|
| 526 |
+
'Re' : 0x211c,
|
| 527 |
+
'Rightarrow' : 0x21d2,
|
| 528 |
+
'Rrightarrow' : 0x21db,
|
| 529 |
+
'Rsh' : 0x21b1,
|
| 530 |
+
'S' : 0xa7,
|
| 531 |
+
'Searrow' : 0x21d8,
|
| 532 |
+
'Sigma' : 0x3a3,
|
| 533 |
+
'Subset' : 0x22d0,
|
| 534 |
+
'Supset' : 0x22d1,
|
| 535 |
+
'Swarrow' : 0x21d9,
|
| 536 |
+
'Theta' : 0x398,
|
| 537 |
+
'Thorn' : 0xde,
|
| 538 |
+
'Uparrow' : 0x21d1,
|
| 539 |
+
'Updownarrow' : 0x21d5,
|
| 540 |
+
'Upsilon' : 0x3a5,
|
| 541 |
+
'Vdash' : 0x22a9,
|
| 542 |
+
'Vert' : 0x2016,
|
| 543 |
+
'Vvdash' : 0x22aa,
|
| 544 |
+
'Xi' : 0x39e,
|
| 545 |
+
'_' : 0x5f,
|
| 546 |
+
'__sqrt__' : 0x221a,
|
| 547 |
+
'aa' : 0xe5,
|
| 548 |
+
'ac' : 0x223e,
|
| 549 |
+
'acute' : 0x301,
|
| 550 |
+
'acwopencirclearrow' : 0x21ba,
|
| 551 |
+
'adots' : 0x22f0,
|
| 552 |
+
'ae' : 0xe6,
|
| 553 |
+
'aleph' : 0x2135,
|
| 554 |
+
'alpha' : 0x3b1,
|
| 555 |
+
'amalg' : 0x2a3f,
|
| 556 |
+
'angle' : 0x2220,
|
| 557 |
+
'approx' : 0x2248,
|
| 558 |
+
'approxeq' : 0x224a,
|
| 559 |
+
'approxident' : 0x224b,
|
| 560 |
+
'arceq' : 0x2258,
|
| 561 |
+
'ast' : 0x2217,
|
| 562 |
+
'asterisk' : 0x2a,
|
| 563 |
+
'asymp' : 0x224d,
|
| 564 |
+
'backcong' : 0x224c,
|
| 565 |
+
'backepsilon' : 0x3f6,
|
| 566 |
+
'backprime' : 0x2035,
|
| 567 |
+
'backsim' : 0x223d,
|
| 568 |
+
'backsimeq' : 0x22cd,
|
| 569 |
+
'backslash' : 0x5c,
|
| 570 |
+
'bagmember' : 0x22ff,
|
| 571 |
+
'bar' : 0x304,
|
| 572 |
+
'barleftarrow' : 0x21e4,
|
| 573 |
+
'barvee' : 0x22bd,
|
| 574 |
+
'barwedge' : 0x22bc,
|
| 575 |
+
'because' : 0x2235,
|
| 576 |
+
'beta' : 0x3b2,
|
| 577 |
+
'beth' : 0x2136,
|
| 578 |
+
'between' : 0x226c,
|
| 579 |
+
'bigcap' : 0x22c2,
|
| 580 |
+
'bigcirc' : 0x25cb,
|
| 581 |
+
'bigcup' : 0x22c3,
|
| 582 |
+
'bigodot' : 0x2a00,
|
| 583 |
+
'bigoplus' : 0x2a01,
|
| 584 |
+
'bigotimes' : 0x2a02,
|
| 585 |
+
'bigsqcup' : 0x2a06,
|
| 586 |
+
'bigstar' : 0x2605,
|
| 587 |
+
'bigtriangledown' : 0x25bd,
|
| 588 |
+
'bigtriangleup' : 0x25b3,
|
| 589 |
+
'biguplus' : 0x2a04,
|
| 590 |
+
'bigvee' : 0x22c1,
|
| 591 |
+
'bigwedge' : 0x22c0,
|
| 592 |
+
'blacksquare' : 0x25a0,
|
| 593 |
+
'blacktriangle' : 0x25b4,
|
| 594 |
+
'blacktriangledown' : 0x25be,
|
| 595 |
+
'blacktriangleleft' : 0x25c0,
|
| 596 |
+
'blacktriangleright' : 0x25b6,
|
| 597 |
+
'bot' : 0x22a5,
|
| 598 |
+
'bowtie' : 0x22c8,
|
| 599 |
+
'boxbar' : 0x25eb,
|
| 600 |
+
'boxdot' : 0x22a1,
|
| 601 |
+
'boxminus' : 0x229f,
|
| 602 |
+
'boxplus' : 0x229e,
|
| 603 |
+
'boxtimes' : 0x22a0,
|
| 604 |
+
'breve' : 0x306,
|
| 605 |
+
'bullet' : 0x2219,
|
| 606 |
+
'bumpeq' : 0x224f,
|
| 607 |
+
'c' : 0x327,
|
| 608 |
+
'candra' : 0x310,
|
| 609 |
+
'cap' : 0x2229,
|
| 610 |
+
'carriagereturn' : 0x21b5,
|
| 611 |
+
'cdot' : 0x22c5,
|
| 612 |
+
'cdotp' : 0xb7,
|
| 613 |
+
'cdots' : 0x22ef,
|
| 614 |
+
'cent' : 0xa2,
|
| 615 |
+
'check' : 0x30c,
|
| 616 |
+
'checkmark' : 0x2713,
|
| 617 |
+
'chi' : 0x3c7,
|
| 618 |
+
'circ' : 0x2218,
|
| 619 |
+
'circeq' : 0x2257,
|
| 620 |
+
'circlearrowleft' : 0x21ba,
|
| 621 |
+
'circlearrowright' : 0x21bb,
|
| 622 |
+
'circledR' : 0xae,
|
| 623 |
+
'circledS' : 0x24c8,
|
| 624 |
+
'circledast' : 0x229b,
|
| 625 |
+
'circledcirc' : 0x229a,
|
| 626 |
+
'circleddash' : 0x229d,
|
| 627 |
+
'circumflexaccent' : 0x302,
|
| 628 |
+
'clubsuit' : 0x2663,
|
| 629 |
+
'clubsuitopen' : 0x2667,
|
| 630 |
+
'colon' : 0x3a,
|
| 631 |
+
'coloneq' : 0x2254,
|
| 632 |
+
'combiningacuteaccent' : 0x301,
|
| 633 |
+
'combiningbreve' : 0x306,
|
| 634 |
+
'combiningdiaeresis' : 0x308,
|
| 635 |
+
'combiningdotabove' : 0x307,
|
| 636 |
+
'combiningfourdotsabove' : 0x20dc,
|
| 637 |
+
'combininggraveaccent' : 0x300,
|
| 638 |
+
'combiningoverline' : 0x304,
|
| 639 |
+
'combiningrightarrowabove' : 0x20d7,
|
| 640 |
+
'combiningthreedotsabove' : 0x20db,
|
| 641 |
+
'combiningtilde' : 0x303,
|
| 642 |
+
'complement' : 0x2201,
|
| 643 |
+
'cong' : 0x2245,
|
| 644 |
+
'coprod' : 0x2210,
|
| 645 |
+
'copyright' : 0xa9,
|
| 646 |
+
'cup' : 0x222a,
|
| 647 |
+
'cupdot' : 0x228d,
|
| 648 |
+
'cupleftarrow' : 0x228c,
|
| 649 |
+
'curlyeqprec' : 0x22de,
|
| 650 |
+
'curlyeqsucc' : 0x22df,
|
| 651 |
+
'curlyvee' : 0x22ce,
|
| 652 |
+
'curlywedge' : 0x22cf,
|
| 653 |
+
'curvearrowleft' : 0x21b6,
|
| 654 |
+
'curvearrowright' : 0x21b7,
|
| 655 |
+
'cwopencirclearrow' : 0x21bb,
|
| 656 |
+
'd' : 0x323,
|
| 657 |
+
'dag' : 0x2020,
|
| 658 |
+
'dagger' : 0x2020,
|
| 659 |
+
'daleth' : 0x2138,
|
| 660 |
+
'danger' : 0x2621,
|
| 661 |
+
'dashleftarrow' : 0x290e,
|
| 662 |
+
'dashrightarrow' : 0x290f,
|
| 663 |
+
'dashv' : 0x22a3,
|
| 664 |
+
'ddag' : 0x2021,
|
| 665 |
+
'ddagger' : 0x2021,
|
| 666 |
+
'ddddot' : 0x20dc,
|
| 667 |
+
'dddot' : 0x20db,
|
| 668 |
+
'ddot' : 0x308,
|
| 669 |
+
'ddots' : 0x22f1,
|
| 670 |
+
'degree' : 0xb0,
|
| 671 |
+
'delta' : 0x3b4,
|
| 672 |
+
'dh' : 0xf0,
|
| 673 |
+
'diamond' : 0x22c4,
|
| 674 |
+
'diamondsuit' : 0x2662,
|
| 675 |
+
'digamma' : 0x3dd,
|
| 676 |
+
'disin' : 0x22f2,
|
| 677 |
+
'div' : 0xf7,
|
| 678 |
+
'divideontimes' : 0x22c7,
|
| 679 |
+
'dot' : 0x307,
|
| 680 |
+
'doteq' : 0x2250,
|
| 681 |
+
'doteqdot' : 0x2251,
|
| 682 |
+
'dotminus' : 0x2238,
|
| 683 |
+
'dotplus' : 0x2214,
|
| 684 |
+
'dots' : 0x2026,
|
| 685 |
+
'dotsminusdots' : 0x223a,
|
| 686 |
+
'doublebarwedge' : 0x2306,
|
| 687 |
+
'downarrow' : 0x2193,
|
| 688 |
+
'downdownarrows' : 0x21ca,
|
| 689 |
+
'downharpoonleft' : 0x21c3,
|
| 690 |
+
'downharpoonright' : 0x21c2,
|
| 691 |
+
'downzigzagarrow' : 0x21af,
|
| 692 |
+
'ell' : 0x2113,
|
| 693 |
+
'emdash' : 0x2014,
|
| 694 |
+
'emptyset' : 0x2205,
|
| 695 |
+
'endash' : 0x2013,
|
| 696 |
+
'epsilon' : 0x3b5,
|
| 697 |
+
'eqcirc' : 0x2256,
|
| 698 |
+
'eqcolon' : 0x2255,
|
| 699 |
+
'eqdef' : 0x225d,
|
| 700 |
+
'eqgtr' : 0x22dd,
|
| 701 |
+
'eqless' : 0x22dc,
|
| 702 |
+
'eqsim' : 0x2242,
|
| 703 |
+
'eqslantgtr' : 0x2a96,
|
| 704 |
+
'eqslantless' : 0x2a95,
|
| 705 |
+
'equal' : 0x3d,
|
| 706 |
+
'equalparallel' : 0x22d5,
|
| 707 |
+
'equiv' : 0x2261,
|
| 708 |
+
'eta' : 0x3b7,
|
| 709 |
+
'eth' : 0xf0,
|
| 710 |
+
'exists' : 0x2203,
|
| 711 |
+
'fallingdotseq' : 0x2252,
|
| 712 |
+
'flat' : 0x266d,
|
| 713 |
+
'forall' : 0x2200,
|
| 714 |
+
'frakC' : 0x212d,
|
| 715 |
+
'frakZ' : 0x2128,
|
| 716 |
+
'frown' : 0x2322,
|
| 717 |
+
'gamma' : 0x3b3,
|
| 718 |
+
'geq' : 0x2265,
|
| 719 |
+
'geqq' : 0x2267,
|
| 720 |
+
'geqslant' : 0x2a7e,
|
| 721 |
+
'gg' : 0x226b,
|
| 722 |
+
'ggg' : 0x22d9,
|
| 723 |
+
'gimel' : 0x2137,
|
| 724 |
+
'gnapprox' : 0x2a8a,
|
| 725 |
+
'gneqq' : 0x2269,
|
| 726 |
+
'gnsim' : 0x22e7,
|
| 727 |
+
'grave' : 0x300,
|
| 728 |
+
'greater' : 0x3e,
|
| 729 |
+
'gtrapprox' : 0x2a86,
|
| 730 |
+
'gtrdot' : 0x22d7,
|
| 731 |
+
'gtreqless' : 0x22db,
|
| 732 |
+
'gtreqqless' : 0x2a8c,
|
| 733 |
+
'gtrless' : 0x2277,
|
| 734 |
+
'gtrsim' : 0x2273,
|
| 735 |
+
'guillemotleft' : 0xab,
|
| 736 |
+
'guillemotright' : 0xbb,
|
| 737 |
+
'guilsinglleft' : 0x2039,
|
| 738 |
+
'guilsinglright' : 0x203a,
|
| 739 |
+
'hat' : 0x302,
|
| 740 |
+
'hbar' : 0x127,
|
| 741 |
+
'heartsuit' : 0x2661,
|
| 742 |
+
'hermitmatrix' : 0x22b9,
|
| 743 |
+
'hookleftarrow' : 0x21a9,
|
| 744 |
+
'hookrightarrow' : 0x21aa,
|
| 745 |
+
'hslash' : 0x210f,
|
| 746 |
+
'i' : 0x131,
|
| 747 |
+
'iiiint' : 0x2a0c,
|
| 748 |
+
'iiint' : 0x222d,
|
| 749 |
+
'iint' : 0x222c,
|
| 750 |
+
'imageof' : 0x22b7,
|
| 751 |
+
'imath' : 0x131,
|
| 752 |
+
'in' : 0x2208,
|
| 753 |
+
'increment' : 0x2206,
|
| 754 |
+
'infty' : 0x221e,
|
| 755 |
+
'int' : 0x222b,
|
| 756 |
+
'intercal' : 0x22ba,
|
| 757 |
+
'invnot' : 0x2310,
|
| 758 |
+
'iota' : 0x3b9,
|
| 759 |
+
'isinE' : 0x22f9,
|
| 760 |
+
'isindot' : 0x22f5,
|
| 761 |
+
'isinobar' : 0x22f7,
|
| 762 |
+
'isins' : 0x22f4,
|
| 763 |
+
'isinvb' : 0x22f8,
|
| 764 |
+
'jmath' : 0x237,
|
| 765 |
+
'k' : 0x328,
|
| 766 |
+
'kappa' : 0x3ba,
|
| 767 |
+
'kernelcontraction' : 0x223b,
|
| 768 |
+
'l' : 0x142,
|
| 769 |
+
'lambda' : 0x3bb,
|
| 770 |
+
'lambdabar' : 0x19b,
|
| 771 |
+
'langle' : 0x27e8,
|
| 772 |
+
'lasp' : 0x2bd,
|
| 773 |
+
'lbrace' : 0x7b,
|
| 774 |
+
'lbrack' : 0x5b,
|
| 775 |
+
'lceil' : 0x2308,
|
| 776 |
+
'ldots' : 0x2026,
|
| 777 |
+
'leadsto' : 0x21dd,
|
| 778 |
+
'leftarrow' : 0x2190,
|
| 779 |
+
'leftarrowtail' : 0x21a2,
|
| 780 |
+
'leftbrace' : 0x7b,
|
| 781 |
+
'leftharpoonaccent' : 0x20d0,
|
| 782 |
+
'leftharpoondown' : 0x21bd,
|
| 783 |
+
'leftharpoonup' : 0x21bc,
|
| 784 |
+
'leftleftarrows' : 0x21c7,
|
| 785 |
+
'leftparen' : 0x28,
|
| 786 |
+
'leftrightarrow' : 0x2194,
|
| 787 |
+
'leftrightarrows' : 0x21c6,
|
| 788 |
+
'leftrightharpoons' : 0x21cb,
|
| 789 |
+
'leftrightsquigarrow' : 0x21ad,
|
| 790 |
+
'leftsquigarrow' : 0x219c,
|
| 791 |
+
'leftthreetimes' : 0x22cb,
|
| 792 |
+
'leq' : 0x2264,
|
| 793 |
+
'leqq' : 0x2266,
|
| 794 |
+
'leqslant' : 0x2a7d,
|
| 795 |
+
'less' : 0x3c,
|
| 796 |
+
'lessapprox' : 0x2a85,
|
| 797 |
+
'lessdot' : 0x22d6,
|
| 798 |
+
'lesseqgtr' : 0x22da,
|
| 799 |
+
'lesseqqgtr' : 0x2a8b,
|
| 800 |
+
'lessgtr' : 0x2276,
|
| 801 |
+
'lesssim' : 0x2272,
|
| 802 |
+
'lfloor' : 0x230a,
|
| 803 |
+
'lgroup' : 0x27ee,
|
| 804 |
+
'lhd' : 0x25c1,
|
| 805 |
+
'll' : 0x226a,
|
| 806 |
+
'llcorner' : 0x231e,
|
| 807 |
+
'lll' : 0x22d8,
|
| 808 |
+
'lnapprox' : 0x2a89,
|
| 809 |
+
'lneqq' : 0x2268,
|
| 810 |
+
'lnsim' : 0x22e6,
|
| 811 |
+
'longleftarrow' : 0x27f5,
|
| 812 |
+
'longleftrightarrow' : 0x27f7,
|
| 813 |
+
'longmapsto' : 0x27fc,
|
| 814 |
+
'longrightarrow' : 0x27f6,
|
| 815 |
+
'looparrowleft' : 0x21ab,
|
| 816 |
+
'looparrowright' : 0x21ac,
|
| 817 |
+
'lq' : 0x2018,
|
| 818 |
+
'lrcorner' : 0x231f,
|
| 819 |
+
'ltimes' : 0x22c9,
|
| 820 |
+
'macron' : 0xaf,
|
| 821 |
+
'maltese' : 0x2720,
|
| 822 |
+
'mapsdown' : 0x21a7,
|
| 823 |
+
'mapsfrom' : 0x21a4,
|
| 824 |
+
'mapsto' : 0x21a6,
|
| 825 |
+
'mapsup' : 0x21a5,
|
| 826 |
+
'measeq' : 0x225e,
|
| 827 |
+
'measuredangle' : 0x2221,
|
| 828 |
+
'measuredrightangle' : 0x22be,
|
| 829 |
+
'merge' : 0x2a55,
|
| 830 |
+
'mho' : 0x2127,
|
| 831 |
+
'mid' : 0x2223,
|
| 832 |
+
'minus' : 0x2212,
|
| 833 |
+
'minuscolon' : 0x2239,
|
| 834 |
+
'models' : 0x22a7,
|
| 835 |
+
'mp' : 0x2213,
|
| 836 |
+
'mu' : 0x3bc,
|
| 837 |
+
'multimap' : 0x22b8,
|
| 838 |
+
'nLeftarrow' : 0x21cd,
|
| 839 |
+
'nLeftrightarrow' : 0x21ce,
|
| 840 |
+
'nRightarrow' : 0x21cf,
|
| 841 |
+
'nVDash' : 0x22af,
|
| 842 |
+
'nVdash' : 0x22ae,
|
| 843 |
+
'nabla' : 0x2207,
|
| 844 |
+
'napprox' : 0x2249,
|
| 845 |
+
'natural' : 0x266e,
|
| 846 |
+
'ncong' : 0x2247,
|
| 847 |
+
'ne' : 0x2260,
|
| 848 |
+
'nearrow' : 0x2197,
|
| 849 |
+
'neg' : 0xac,
|
| 850 |
+
'neq' : 0x2260,
|
| 851 |
+
'nequiv' : 0x2262,
|
| 852 |
+
'nexists' : 0x2204,
|
| 853 |
+
'ngeq' : 0x2271,
|
| 854 |
+
'ngtr' : 0x226f,
|
| 855 |
+
'ngtrless' : 0x2279,
|
| 856 |
+
'ngtrsim' : 0x2275,
|
| 857 |
+
'ni' : 0x220b,
|
| 858 |
+
'niobar' : 0x22fe,
|
| 859 |
+
'nis' : 0x22fc,
|
| 860 |
+
'nisd' : 0x22fa,
|
| 861 |
+
'nleftarrow' : 0x219a,
|
| 862 |
+
'nleftrightarrow' : 0x21ae,
|
| 863 |
+
'nleq' : 0x2270,
|
| 864 |
+
'nless' : 0x226e,
|
| 865 |
+
'nlessgtr' : 0x2278,
|
| 866 |
+
'nlesssim' : 0x2274,
|
| 867 |
+
'nmid' : 0x2224,
|
| 868 |
+
'not' : 0x338,
|
| 869 |
+
'notin' : 0x2209,
|
| 870 |
+
'notsmallowns' : 0x220c,
|
| 871 |
+
'nparallel' : 0x2226,
|
| 872 |
+
'nprec' : 0x2280,
|
| 873 |
+
'npreccurlyeq' : 0x22e0,
|
| 874 |
+
'nrightarrow' : 0x219b,
|
| 875 |
+
'nsim' : 0x2241,
|
| 876 |
+
'nsimeq' : 0x2244,
|
| 877 |
+
'nsqsubseteq' : 0x22e2,
|
| 878 |
+
'nsqsupseteq' : 0x22e3,
|
| 879 |
+
'nsubset' : 0x2284,
|
| 880 |
+
'nsubseteq' : 0x2288,
|
| 881 |
+
'nsucc' : 0x2281,
|
| 882 |
+
'nsucccurlyeq' : 0x22e1,
|
| 883 |
+
'nsupset' : 0x2285,
|
| 884 |
+
'nsupseteq' : 0x2289,
|
| 885 |
+
'ntriangleleft' : 0x22ea,
|
| 886 |
+
'ntrianglelefteq' : 0x22ec,
|
| 887 |
+
'ntriangleright' : 0x22eb,
|
| 888 |
+
'ntrianglerighteq' : 0x22ed,
|
| 889 |
+
'nu' : 0x3bd,
|
| 890 |
+
'nvDash' : 0x22ad,
|
| 891 |
+
'nvdash' : 0x22ac,
|
| 892 |
+
'nwarrow' : 0x2196,
|
| 893 |
+
'o' : 0xf8,
|
| 894 |
+
'obar' : 0x233d,
|
| 895 |
+
'ocirc' : 0x30a,
|
| 896 |
+
'odot' : 0x2299,
|
| 897 |
+
'oe' : 0x153,
|
| 898 |
+
'oequal' : 0x229c,
|
| 899 |
+
'oiiint' : 0x2230,
|
| 900 |
+
'oiint' : 0x222f,
|
| 901 |
+
'oint' : 0x222e,
|
| 902 |
+
'omega' : 0x3c9,
|
| 903 |
+
'ominus' : 0x2296,
|
| 904 |
+
'oplus' : 0x2295,
|
| 905 |
+
'origof' : 0x22b6,
|
| 906 |
+
'oslash' : 0x2298,
|
| 907 |
+
'otimes' : 0x2297,
|
| 908 |
+
'overarc' : 0x311,
|
| 909 |
+
'overleftarrow' : 0x20d6,
|
| 910 |
+
'overleftrightarrow' : 0x20e1,
|
| 911 |
+
'parallel' : 0x2225,
|
| 912 |
+
'partial' : 0x2202,
|
| 913 |
+
'perp' : 0x27c2,
|
| 914 |
+
'perthousand' : 0x2030,
|
| 915 |
+
'phi' : 0x3d5,
|
| 916 |
+
'pi' : 0x3c0,
|
| 917 |
+
'pitchfork' : 0x22d4,
|
| 918 |
+
'plus' : 0x2b,
|
| 919 |
+
'pm' : 0xb1,
|
| 920 |
+
'prec' : 0x227a,
|
| 921 |
+
'precapprox' : 0x2ab7,
|
| 922 |
+
'preccurlyeq' : 0x227c,
|
| 923 |
+
'preceq' : 0x227c,
|
| 924 |
+
'precnapprox' : 0x2ab9,
|
| 925 |
+
'precnsim' : 0x22e8,
|
| 926 |
+
'precsim' : 0x227e,
|
| 927 |
+
'prime' : 0x2032,
|
| 928 |
+
'prod' : 0x220f,
|
| 929 |
+
'propto' : 0x221d,
|
| 930 |
+
'prurel' : 0x22b0,
|
| 931 |
+
'psi' : 0x3c8,
|
| 932 |
+
'quad' : 0x2003,
|
| 933 |
+
'questeq' : 0x225f,
|
| 934 |
+
'rangle' : 0x27e9,
|
| 935 |
+
'rasp' : 0x2bc,
|
| 936 |
+
'ratio' : 0x2236,
|
| 937 |
+
'rbrace' : 0x7d,
|
| 938 |
+
'rbrack' : 0x5d,
|
| 939 |
+
'rceil' : 0x2309,
|
| 940 |
+
'rfloor' : 0x230b,
|
| 941 |
+
'rgroup' : 0x27ef,
|
| 942 |
+
'rhd' : 0x25b7,
|
| 943 |
+
'rho' : 0x3c1,
|
| 944 |
+
'rightModels' : 0x22ab,
|
| 945 |
+
'rightangle' : 0x221f,
|
| 946 |
+
'rightarrow' : 0x2192,
|
| 947 |
+
'rightarrowbar' : 0x21e5,
|
| 948 |
+
'rightarrowtail' : 0x21a3,
|
| 949 |
+
'rightassert' : 0x22a6,
|
| 950 |
+
'rightbrace' : 0x7d,
|
| 951 |
+
'rightharpoonaccent' : 0x20d1,
|
| 952 |
+
'rightharpoondown' : 0x21c1,
|
| 953 |
+
'rightharpoonup' : 0x21c0,
|
| 954 |
+
'rightleftarrows' : 0x21c4,
|
| 955 |
+
'rightleftharpoons' : 0x21cc,
|
| 956 |
+
'rightparen' : 0x29,
|
| 957 |
+
'rightrightarrows' : 0x21c9,
|
| 958 |
+
'rightsquigarrow' : 0x219d,
|
| 959 |
+
'rightthreetimes' : 0x22cc,
|
| 960 |
+
'rightzigzagarrow' : 0x21dd,
|
| 961 |
+
'ring' : 0x2da,
|
| 962 |
+
'risingdotseq' : 0x2253,
|
| 963 |
+
'rq' : 0x2019,
|
| 964 |
+
'rtimes' : 0x22ca,
|
| 965 |
+
'scrB' : 0x212c,
|
| 966 |
+
'scrE' : 0x2130,
|
| 967 |
+
'scrF' : 0x2131,
|
| 968 |
+
'scrH' : 0x210b,
|
| 969 |
+
'scrI' : 0x2110,
|
| 970 |
+
'scrL' : 0x2112,
|
| 971 |
+
'scrM' : 0x2133,
|
| 972 |
+
'scrR' : 0x211b,
|
| 973 |
+
'scre' : 0x212f,
|
| 974 |
+
'scrg' : 0x210a,
|
| 975 |
+
'scro' : 0x2134,
|
| 976 |
+
'scurel' : 0x22b1,
|
| 977 |
+
'searrow' : 0x2198,
|
| 978 |
+
'setminus' : 0x2216,
|
| 979 |
+
'sharp' : 0x266f,
|
| 980 |
+
'sigma' : 0x3c3,
|
| 981 |
+
'sim' : 0x223c,
|
| 982 |
+
'simeq' : 0x2243,
|
| 983 |
+
'simneqq' : 0x2246,
|
| 984 |
+
'sinewave' : 0x223f,
|
| 985 |
+
'slash' : 0x2215,
|
| 986 |
+
'smallin' : 0x220a,
|
| 987 |
+
'smallintclockwise' : 0x2231,
|
| 988 |
+
'smallointctrcclockwise' : 0x2233,
|
| 989 |
+
'smallowns' : 0x220d,
|
| 990 |
+
'smallsetminus' : 0x2216,
|
| 991 |
+
'smallvarointclockwise' : 0x2232,
|
| 992 |
+
'smile' : 0x2323,
|
| 993 |
+
'solbar' : 0x233f,
|
| 994 |
+
'spadesuit' : 0x2660,
|
| 995 |
+
'spadesuitopen' : 0x2664,
|
| 996 |
+
'sphericalangle' : 0x2222,
|
| 997 |
+
'sqcap' : 0x2293,
|
| 998 |
+
'sqcup' : 0x2294,
|
| 999 |
+
'sqsubset' : 0x228f,
|
| 1000 |
+
'sqsubseteq' : 0x2291,
|
| 1001 |
+
'sqsubsetneq' : 0x22e4,
|
| 1002 |
+
'sqsupset' : 0x2290,
|
| 1003 |
+
'sqsupseteq' : 0x2292,
|
| 1004 |
+
'sqsupsetneq' : 0x22e5,
|
| 1005 |
+
'ss' : 0xdf,
|
| 1006 |
+
'star' : 0x22c6,
|
| 1007 |
+
'stareq' : 0x225b,
|
| 1008 |
+
'sterling' : 0xa3,
|
| 1009 |
+
'subset' : 0x2282,
|
| 1010 |
+
'subseteq' : 0x2286,
|
| 1011 |
+
'subseteqq' : 0x2ac5,
|
| 1012 |
+
'subsetneq' : 0x228a,
|
| 1013 |
+
'subsetneqq' : 0x2acb,
|
| 1014 |
+
'succ' : 0x227b,
|
| 1015 |
+
'succapprox' : 0x2ab8,
|
| 1016 |
+
'succcurlyeq' : 0x227d,
|
| 1017 |
+
'succeq' : 0x227d,
|
| 1018 |
+
'succnapprox' : 0x2aba,
|
| 1019 |
+
'succnsim' : 0x22e9,
|
| 1020 |
+
'succsim' : 0x227f,
|
| 1021 |
+
'sum' : 0x2211,
|
| 1022 |
+
'supset' : 0x2283,
|
| 1023 |
+
'supseteq' : 0x2287,
|
| 1024 |
+
'supseteqq' : 0x2ac6,
|
| 1025 |
+
'supsetneq' : 0x228b,
|
| 1026 |
+
'supsetneqq' : 0x2acc,
|
| 1027 |
+
'swarrow' : 0x2199,
|
| 1028 |
+
't' : 0x361,
|
| 1029 |
+
'tau' : 0x3c4,
|
| 1030 |
+
'textasciiacute' : 0xb4,
|
| 1031 |
+
'textasciicircum' : 0x5e,
|
| 1032 |
+
'textasciigrave' : 0x60,
|
| 1033 |
+
'textasciitilde' : 0x7e,
|
| 1034 |
+
'textexclamdown' : 0xa1,
|
| 1035 |
+
'textquestiondown' : 0xbf,
|
| 1036 |
+
'textquotedblleft' : 0x201c,
|
| 1037 |
+
'textquotedblright' : 0x201d,
|
| 1038 |
+
'therefore' : 0x2234,
|
| 1039 |
+
'theta' : 0x3b8,
|
| 1040 |
+
'thickspace' : 0x2005,
|
| 1041 |
+
'thorn' : 0xfe,
|
| 1042 |
+
'tilde' : 0x303,
|
| 1043 |
+
'times' : 0xd7,
|
| 1044 |
+
'to' : 0x2192,
|
| 1045 |
+
'top' : 0x22a4,
|
| 1046 |
+
'triangle' : 0x25b3,
|
| 1047 |
+
'triangledown' : 0x25bf,
|
| 1048 |
+
'triangleeq' : 0x225c,
|
| 1049 |
+
'triangleleft' : 0x25c1,
|
| 1050 |
+
'trianglelefteq' : 0x22b4,
|
| 1051 |
+
'triangleq' : 0x225c,
|
| 1052 |
+
'triangleright' : 0x25b7,
|
| 1053 |
+
'trianglerighteq' : 0x22b5,
|
| 1054 |
+
'turnednot' : 0x2319,
|
| 1055 |
+
'twoheaddownarrow' : 0x21a1,
|
| 1056 |
+
'twoheadleftarrow' : 0x219e,
|
| 1057 |
+
'twoheadrightarrow' : 0x21a0,
|
| 1058 |
+
'twoheaduparrow' : 0x219f,
|
| 1059 |
+
'ulcorner' : 0x231c,
|
| 1060 |
+
'underbar' : 0x331,
|
| 1061 |
+
'unlhd' : 0x22b4,
|
| 1062 |
+
'unrhd' : 0x22b5,
|
| 1063 |
+
'uparrow' : 0x2191,
|
| 1064 |
+
'updownarrow' : 0x2195,
|
| 1065 |
+
'updownarrowbar' : 0x21a8,
|
| 1066 |
+
'updownarrows' : 0x21c5,
|
| 1067 |
+
'upharpoonleft' : 0x21bf,
|
| 1068 |
+
'upharpoonright' : 0x21be,
|
| 1069 |
+
'uplus' : 0x228e,
|
| 1070 |
+
'upsilon' : 0x3c5,
|
| 1071 |
+
'upuparrows' : 0x21c8,
|
| 1072 |
+
'urcorner' : 0x231d,
|
| 1073 |
+
'vDash' : 0x22a8,
|
| 1074 |
+
'varepsilon' : 0x3b5,
|
| 1075 |
+
'varisinobar' : 0x22f6,
|
| 1076 |
+
'varisins' : 0x22f3,
|
| 1077 |
+
'varkappa' : 0x3f0,
|
| 1078 |
+
'varlrtriangle' : 0x22bf,
|
| 1079 |
+
'varniobar' : 0x22fd,
|
| 1080 |
+
'varnis' : 0x22fb,
|
| 1081 |
+
'varnothing' : 0x2205,
|
| 1082 |
+
'varphi' : 0x3c6,
|
| 1083 |
+
'varpi' : 0x3d6,
|
| 1084 |
+
'varpropto' : 0x221d,
|
| 1085 |
+
'varrho' : 0x3f1,
|
| 1086 |
+
'varsigma' : 0x3c2,
|
| 1087 |
+
'vartheta' : 0x3d1,
|
| 1088 |
+
'vartriangle' : 0x25b5,
|
| 1089 |
+
'vartriangleleft' : 0x22b2,
|
| 1090 |
+
'vartriangleright' : 0x22b3,
|
| 1091 |
+
'vdash' : 0x22a2,
|
| 1092 |
+
'vdots' : 0x22ee,
|
| 1093 |
+
'vec' : 0x20d7,
|
| 1094 |
+
'vee' : 0x2228,
|
| 1095 |
+
'veebar' : 0x22bb,
|
| 1096 |
+
'veeeq' : 0x225a,
|
| 1097 |
+
'vert' : 0x7c,
|
| 1098 |
+
'wedge' : 0x2227,
|
| 1099 |
+
'wedgeq' : 0x2259,
|
| 1100 |
+
'widebar' : 0x305,
|
| 1101 |
+
'widehat' : 0x302,
|
| 1102 |
+
'widetilde' : 0x303,
|
| 1103 |
+
'wp' : 0x2118,
|
| 1104 |
+
'wr' : 0x2240,
|
| 1105 |
+
'xi' : 0x3be,
|
| 1106 |
+
'yen' : 0xa5,
|
| 1107 |
+
'zeta' : 0x3b6,
|
| 1108 |
+
'{' : 0x7b,
|
| 1109 |
+
'|' : 0x2016,
|
| 1110 |
+
'}' : 0x7d,
|
| 1111 |
+
}
|
| 1112 |
+
|
| 1113 |
+
# Each element is a 4-tuple of the form:
|
| 1114 |
+
# src_start, src_end, dst_font, dst_start
|
| 1115 |
+
|
| 1116 |
+
_EntryTypeIn = tuple[str, str, str, str | int]
|
| 1117 |
+
_EntryTypeOut = tuple[int, int, str, int]
|
| 1118 |
+
|
| 1119 |
+
_stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeIn]] | list[_EntryTypeIn]] = {
|
| 1120 |
+
'bb': {
|
| 1121 |
+
"rm": [
|
| 1122 |
+
("\N{DIGIT ZERO}",
|
| 1123 |
+
"\N{DIGIT NINE}",
|
| 1124 |
+
"rm",
|
| 1125 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}"),
|
| 1126 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1127 |
+
"\N{LATIN CAPITAL LETTER B}",
|
| 1128 |
+
"rm",
|
| 1129 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL A}"),
|
| 1130 |
+
("\N{LATIN CAPITAL LETTER C}",
|
| 1131 |
+
"\N{LATIN CAPITAL LETTER C}",
|
| 1132 |
+
"rm",
|
| 1133 |
+
"\N{DOUBLE-STRUCK CAPITAL C}"),
|
| 1134 |
+
("\N{LATIN CAPITAL LETTER D}",
|
| 1135 |
+
"\N{LATIN CAPITAL LETTER G}",
|
| 1136 |
+
"rm",
|
| 1137 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL D}"),
|
| 1138 |
+
("\N{LATIN CAPITAL LETTER H}",
|
| 1139 |
+
"\N{LATIN CAPITAL LETTER H}",
|
| 1140 |
+
"rm",
|
| 1141 |
+
"\N{DOUBLE-STRUCK CAPITAL H}"),
|
| 1142 |
+
("\N{LATIN CAPITAL LETTER I}",
|
| 1143 |
+
"\N{LATIN CAPITAL LETTER M}",
|
| 1144 |
+
"rm",
|
| 1145 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}"),
|
| 1146 |
+
("\N{LATIN CAPITAL LETTER N}",
|
| 1147 |
+
"\N{LATIN CAPITAL LETTER N}",
|
| 1148 |
+
"rm",
|
| 1149 |
+
"\N{DOUBLE-STRUCK CAPITAL N}"),
|
| 1150 |
+
("\N{LATIN CAPITAL LETTER O}",
|
| 1151 |
+
"\N{LATIN CAPITAL LETTER O}",
|
| 1152 |
+
"rm",
|
| 1153 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL O}"),
|
| 1154 |
+
("\N{LATIN CAPITAL LETTER P}",
|
| 1155 |
+
"\N{LATIN CAPITAL LETTER Q}",
|
| 1156 |
+
"rm",
|
| 1157 |
+
"\N{DOUBLE-STRUCK CAPITAL P}"),
|
| 1158 |
+
("\N{LATIN CAPITAL LETTER R}",
|
| 1159 |
+
"\N{LATIN CAPITAL LETTER R}",
|
| 1160 |
+
"rm",
|
| 1161 |
+
"\N{DOUBLE-STRUCK CAPITAL R}"),
|
| 1162 |
+
("\N{LATIN CAPITAL LETTER S}",
|
| 1163 |
+
"\N{LATIN CAPITAL LETTER Y}",
|
| 1164 |
+
"rm",
|
| 1165 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL S}"),
|
| 1166 |
+
("\N{LATIN CAPITAL LETTER Z}",
|
| 1167 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1168 |
+
"rm",
|
| 1169 |
+
"\N{DOUBLE-STRUCK CAPITAL Z}"),
|
| 1170 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1171 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1172 |
+
"rm",
|
| 1173 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK SMALL A}"),
|
| 1174 |
+
("\N{GREEK CAPITAL LETTER GAMMA}",
|
| 1175 |
+
"\N{GREEK CAPITAL LETTER GAMMA}",
|
| 1176 |
+
"rm",
|
| 1177 |
+
"\N{DOUBLE-STRUCK CAPITAL GAMMA}"),
|
| 1178 |
+
("\N{GREEK CAPITAL LETTER PI}",
|
| 1179 |
+
"\N{GREEK CAPITAL LETTER PI}",
|
| 1180 |
+
"rm",
|
| 1181 |
+
"\N{DOUBLE-STRUCK CAPITAL PI}"),
|
| 1182 |
+
("\N{GREEK CAPITAL LETTER SIGMA}",
|
| 1183 |
+
"\N{GREEK CAPITAL LETTER SIGMA}",
|
| 1184 |
+
"rm",
|
| 1185 |
+
"\N{DOUBLE-STRUCK N-ARY SUMMATION}"),
|
| 1186 |
+
("\N{GREEK SMALL LETTER GAMMA}",
|
| 1187 |
+
"\N{GREEK SMALL LETTER GAMMA}",
|
| 1188 |
+
"rm",
|
| 1189 |
+
"\N{DOUBLE-STRUCK SMALL GAMMA}"),
|
| 1190 |
+
("\N{GREEK SMALL LETTER PI}",
|
| 1191 |
+
"\N{GREEK SMALL LETTER PI}",
|
| 1192 |
+
"rm",
|
| 1193 |
+
"\N{DOUBLE-STRUCK SMALL PI}"),
|
| 1194 |
+
],
|
| 1195 |
+
"it": [
|
| 1196 |
+
("\N{DIGIT ZERO}",
|
| 1197 |
+
"\N{DIGIT NINE}",
|
| 1198 |
+
"rm",
|
| 1199 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}"),
|
| 1200 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1201 |
+
"\N{LATIN CAPITAL LETTER B}",
|
| 1202 |
+
"it",
|
| 1203 |
+
0xe154),
|
| 1204 |
+
("\N{LATIN CAPITAL LETTER C}",
|
| 1205 |
+
"\N{LATIN CAPITAL LETTER C}",
|
| 1206 |
+
"it",
|
| 1207 |
+
"\N{DOUBLE-STRUCK CAPITAL C}"),
|
| 1208 |
+
("\N{LATIN CAPITAL LETTER D}",
|
| 1209 |
+
"\N{LATIN CAPITAL LETTER D}",
|
| 1210 |
+
"it",
|
| 1211 |
+
"\N{DOUBLE-STRUCK ITALIC CAPITAL D}"),
|
| 1212 |
+
("\N{LATIN CAPITAL LETTER E}",
|
| 1213 |
+
"\N{LATIN CAPITAL LETTER G}",
|
| 1214 |
+
"it",
|
| 1215 |
+
0xe156),
|
| 1216 |
+
("\N{LATIN CAPITAL LETTER H}",
|
| 1217 |
+
"\N{LATIN CAPITAL LETTER H}",
|
| 1218 |
+
"it",
|
| 1219 |
+
"\N{DOUBLE-STRUCK CAPITAL H}"),
|
| 1220 |
+
("\N{LATIN CAPITAL LETTER I}",
|
| 1221 |
+
"\N{LATIN CAPITAL LETTER M}",
|
| 1222 |
+
"it",
|
| 1223 |
+
0xe159),
|
| 1224 |
+
("\N{LATIN CAPITAL LETTER N}",
|
| 1225 |
+
"\N{LATIN CAPITAL LETTER N}",
|
| 1226 |
+
"it",
|
| 1227 |
+
"\N{DOUBLE-STRUCK CAPITAL N}"),
|
| 1228 |
+
("\N{LATIN CAPITAL LETTER O}",
|
| 1229 |
+
"\N{LATIN CAPITAL LETTER O}",
|
| 1230 |
+
"it",
|
| 1231 |
+
0xe15e),
|
| 1232 |
+
("\N{LATIN CAPITAL LETTER P}",
|
| 1233 |
+
"\N{LATIN CAPITAL LETTER Q}",
|
| 1234 |
+
"it",
|
| 1235 |
+
"\N{DOUBLE-STRUCK CAPITAL P}"),
|
| 1236 |
+
("\N{LATIN CAPITAL LETTER R}",
|
| 1237 |
+
"\N{LATIN CAPITAL LETTER R}",
|
| 1238 |
+
"it",
|
| 1239 |
+
"\N{DOUBLE-STRUCK CAPITAL R}"),
|
| 1240 |
+
("\N{LATIN CAPITAL LETTER S}",
|
| 1241 |
+
"\N{LATIN CAPITAL LETTER Y}",
|
| 1242 |
+
"it",
|
| 1243 |
+
0xe15f),
|
| 1244 |
+
("\N{LATIN CAPITAL LETTER Z}",
|
| 1245 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1246 |
+
"it",
|
| 1247 |
+
"\N{DOUBLE-STRUCK CAPITAL Z}"),
|
| 1248 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1249 |
+
"\N{LATIN SMALL LETTER C}",
|
| 1250 |
+
"it",
|
| 1251 |
+
0xe166),
|
| 1252 |
+
("\N{LATIN SMALL LETTER D}",
|
| 1253 |
+
"\N{LATIN SMALL LETTER E}",
|
| 1254 |
+
"it",
|
| 1255 |
+
"\N{DOUBLE-STRUCK ITALIC SMALL D}"),
|
| 1256 |
+
("\N{LATIN SMALL LETTER F}",
|
| 1257 |
+
"\N{LATIN SMALL LETTER H}",
|
| 1258 |
+
"it",
|
| 1259 |
+
0xe169),
|
| 1260 |
+
("\N{LATIN SMALL LETTER I}",
|
| 1261 |
+
"\N{LATIN SMALL LETTER J}",
|
| 1262 |
+
"it",
|
| 1263 |
+
"\N{DOUBLE-STRUCK ITALIC SMALL I}"),
|
| 1264 |
+
("\N{LATIN SMALL LETTER K}",
|
| 1265 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1266 |
+
"it",
|
| 1267 |
+
0xe16c),
|
| 1268 |
+
("\N{GREEK CAPITAL LETTER GAMMA}",
|
| 1269 |
+
"\N{GREEK CAPITAL LETTER GAMMA}",
|
| 1270 |
+
"it",
|
| 1271 |
+
"\N{DOUBLE-STRUCK CAPITAL GAMMA}"), # \Gamma (not in beta STIX fonts)
|
| 1272 |
+
("\N{GREEK CAPITAL LETTER PI}",
|
| 1273 |
+
"\N{GREEK CAPITAL LETTER PI}",
|
| 1274 |
+
"it",
|
| 1275 |
+
"\N{DOUBLE-STRUCK CAPITAL PI}"),
|
| 1276 |
+
("\N{GREEK CAPITAL LETTER SIGMA}",
|
| 1277 |
+
"\N{GREEK CAPITAL LETTER SIGMA}",
|
| 1278 |
+
"it",
|
| 1279 |
+
"\N{DOUBLE-STRUCK N-ARY SUMMATION}"), # \Sigma (not in beta STIX fonts)
|
| 1280 |
+
("\N{GREEK SMALL LETTER GAMMA}",
|
| 1281 |
+
"\N{GREEK SMALL LETTER GAMMA}",
|
| 1282 |
+
"it",
|
| 1283 |
+
"\N{DOUBLE-STRUCK SMALL GAMMA}"), # \gamma (not in beta STIX fonts)
|
| 1284 |
+
("\N{GREEK SMALL LETTER PI}",
|
| 1285 |
+
"\N{GREEK SMALL LETTER PI}",
|
| 1286 |
+
"it",
|
| 1287 |
+
"\N{DOUBLE-STRUCK SMALL PI}"),
|
| 1288 |
+
],
|
| 1289 |
+
"bf": [
|
| 1290 |
+
("\N{DIGIT ZERO}",
|
| 1291 |
+
"\N{DIGIT NINE}",
|
| 1292 |
+
"rm",
|
| 1293 |
+
"\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}"),
|
| 1294 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1295 |
+
"\N{LATIN CAPITAL LETTER B}",
|
| 1296 |
+
"bf",
|
| 1297 |
+
0xe38a),
|
| 1298 |
+
("\N{LATIN CAPITAL LETTER C}",
|
| 1299 |
+
"\N{LATIN CAPITAL LETTER C}",
|
| 1300 |
+
"bf",
|
| 1301 |
+
"\N{DOUBLE-STRUCK CAPITAL C}"),
|
| 1302 |
+
("\N{LATIN CAPITAL LETTER D}",
|
| 1303 |
+
"\N{LATIN CAPITAL LETTER D}",
|
| 1304 |
+
"bf",
|
| 1305 |
+
"\N{DOUBLE-STRUCK ITALIC CAPITAL D}"),
|
| 1306 |
+
("\N{LATIN CAPITAL LETTER E}",
|
| 1307 |
+
"\N{LATIN CAPITAL LETTER G}",
|
| 1308 |
+
"bf",
|
| 1309 |
+
0xe38d),
|
| 1310 |
+
("\N{LATIN CAPITAL LETTER H}",
|
| 1311 |
+
"\N{LATIN CAPITAL LETTER H}",
|
| 1312 |
+
"bf",
|
| 1313 |
+
"\N{DOUBLE-STRUCK CAPITAL H}"),
|
| 1314 |
+
("\N{LATIN CAPITAL LETTER I}",
|
| 1315 |
+
"\N{LATIN CAPITAL LETTER M}",
|
| 1316 |
+
"bf",
|
| 1317 |
+
0xe390),
|
| 1318 |
+
("\N{LATIN CAPITAL LETTER N}",
|
| 1319 |
+
"\N{LATIN CAPITAL LETTER N}",
|
| 1320 |
+
"bf",
|
| 1321 |
+
"\N{DOUBLE-STRUCK CAPITAL N}"),
|
| 1322 |
+
("\N{LATIN CAPITAL LETTER O}",
|
| 1323 |
+
"\N{LATIN CAPITAL LETTER O}",
|
| 1324 |
+
"bf",
|
| 1325 |
+
0xe395),
|
| 1326 |
+
("\N{LATIN CAPITAL LETTER P}",
|
| 1327 |
+
"\N{LATIN CAPITAL LETTER Q}",
|
| 1328 |
+
"bf",
|
| 1329 |
+
"\N{DOUBLE-STRUCK CAPITAL P}"),
|
| 1330 |
+
("\N{LATIN CAPITAL LETTER R}",
|
| 1331 |
+
"\N{LATIN CAPITAL LETTER R}",
|
| 1332 |
+
"bf",
|
| 1333 |
+
"\N{DOUBLE-STRUCK CAPITAL R}"),
|
| 1334 |
+
("\N{LATIN CAPITAL LETTER S}",
|
| 1335 |
+
"\N{LATIN CAPITAL LETTER Y}",
|
| 1336 |
+
"bf",
|
| 1337 |
+
0xe396),
|
| 1338 |
+
("\N{LATIN CAPITAL LETTER Z}",
|
| 1339 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1340 |
+
"bf",
|
| 1341 |
+
"\N{DOUBLE-STRUCK CAPITAL Z}"),
|
| 1342 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1343 |
+
"\N{LATIN SMALL LETTER C}",
|
| 1344 |
+
"bf",
|
| 1345 |
+
0xe39d),
|
| 1346 |
+
("\N{LATIN SMALL LETTER D}",
|
| 1347 |
+
"\N{LATIN SMALL LETTER E}",
|
| 1348 |
+
"bf",
|
| 1349 |
+
"\N{DOUBLE-STRUCK ITALIC SMALL D}"),
|
| 1350 |
+
("\N{LATIN SMALL LETTER F}",
|
| 1351 |
+
"\N{LATIN SMALL LETTER H}",
|
| 1352 |
+
"bf",
|
| 1353 |
+
0xe3a2),
|
| 1354 |
+
("\N{LATIN SMALL LETTER I}",
|
| 1355 |
+
"\N{LATIN SMALL LETTER J}",
|
| 1356 |
+
"bf",
|
| 1357 |
+
"\N{DOUBLE-STRUCK ITALIC SMALL I}"),
|
| 1358 |
+
("\N{LATIN SMALL LETTER K}",
|
| 1359 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1360 |
+
"bf",
|
| 1361 |
+
0xe3a7),
|
| 1362 |
+
("\N{GREEK CAPITAL LETTER GAMMA}",
|
| 1363 |
+
"\N{GREEK CAPITAL LETTER GAMMA}",
|
| 1364 |
+
"bf",
|
| 1365 |
+
"\N{DOUBLE-STRUCK CAPITAL GAMMA}"),
|
| 1366 |
+
("\N{GREEK CAPITAL LETTER PI}",
|
| 1367 |
+
"\N{GREEK CAPITAL LETTER PI}",
|
| 1368 |
+
"bf",
|
| 1369 |
+
"\N{DOUBLE-STRUCK CAPITAL PI}"),
|
| 1370 |
+
("\N{GREEK CAPITAL LETTER SIGMA}",
|
| 1371 |
+
"\N{GREEK CAPITAL LETTER SIGMA}",
|
| 1372 |
+
"bf",
|
| 1373 |
+
"\N{DOUBLE-STRUCK N-ARY SUMMATION}"),
|
| 1374 |
+
("\N{GREEK SMALL LETTER GAMMA}",
|
| 1375 |
+
"\N{GREEK SMALL LETTER GAMMA}",
|
| 1376 |
+
"bf",
|
| 1377 |
+
"\N{DOUBLE-STRUCK SMALL GAMMA}"),
|
| 1378 |
+
("\N{GREEK SMALL LETTER PI}",
|
| 1379 |
+
"\N{GREEK SMALL LETTER PI}",
|
| 1380 |
+
"bf",
|
| 1381 |
+
"\N{DOUBLE-STRUCK SMALL PI}"),
|
| 1382 |
+
],
|
| 1383 |
+
},
|
| 1384 |
+
'cal': [
|
| 1385 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1386 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1387 |
+
"it",
|
| 1388 |
+
0xe22d),
|
| 1389 |
+
],
|
| 1390 |
+
'frak': {
|
| 1391 |
+
"rm": [
|
| 1392 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1393 |
+
"\N{LATIN CAPITAL LETTER B}",
|
| 1394 |
+
"rm",
|
| 1395 |
+
"\N{MATHEMATICAL FRAKTUR CAPITAL A}"),
|
| 1396 |
+
("\N{LATIN CAPITAL LETTER C}",
|
| 1397 |
+
"\N{LATIN CAPITAL LETTER C}",
|
| 1398 |
+
"rm",
|
| 1399 |
+
"\N{BLACK-LETTER CAPITAL C}"),
|
| 1400 |
+
("\N{LATIN CAPITAL LETTER D}",
|
| 1401 |
+
"\N{LATIN CAPITAL LETTER G}",
|
| 1402 |
+
"rm",
|
| 1403 |
+
"\N{MATHEMATICAL FRAKTUR CAPITAL D}"),
|
| 1404 |
+
("\N{LATIN CAPITAL LETTER H}",
|
| 1405 |
+
"\N{LATIN CAPITAL LETTER H}",
|
| 1406 |
+
"rm",
|
| 1407 |
+
"\N{BLACK-LETTER CAPITAL H}"),
|
| 1408 |
+
("\N{LATIN CAPITAL LETTER I}",
|
| 1409 |
+
"\N{LATIN CAPITAL LETTER I}",
|
| 1410 |
+
"rm",
|
| 1411 |
+
"\N{BLACK-LETTER CAPITAL I}"),
|
| 1412 |
+
("\N{LATIN CAPITAL LETTER J}",
|
| 1413 |
+
"\N{LATIN CAPITAL LETTER Q}",
|
| 1414 |
+
"rm",
|
| 1415 |
+
"\N{MATHEMATICAL FRAKTUR CAPITAL J}"),
|
| 1416 |
+
("\N{LATIN CAPITAL LETTER R}",
|
| 1417 |
+
"\N{LATIN CAPITAL LETTER R}",
|
| 1418 |
+
"rm",
|
| 1419 |
+
"\N{BLACK-LETTER CAPITAL R}"),
|
| 1420 |
+
("\N{LATIN CAPITAL LETTER S}",
|
| 1421 |
+
"\N{LATIN CAPITAL LETTER Y}",
|
| 1422 |
+
"rm",
|
| 1423 |
+
"\N{MATHEMATICAL FRAKTUR CAPITAL S}"),
|
| 1424 |
+
("\N{LATIN CAPITAL LETTER Z}",
|
| 1425 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1426 |
+
"rm",
|
| 1427 |
+
"\N{BLACK-LETTER CAPITAL Z}"),
|
| 1428 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1429 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1430 |
+
"rm",
|
| 1431 |
+
"\N{MATHEMATICAL FRAKTUR SMALL A}"),
|
| 1432 |
+
],
|
| 1433 |
+
"bf": [
|
| 1434 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1435 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1436 |
+
"bf",
|
| 1437 |
+
"\N{MATHEMATICAL BOLD FRAKTUR CAPITAL A}"),
|
| 1438 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1439 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1440 |
+
"bf",
|
| 1441 |
+
"\N{MATHEMATICAL BOLD FRAKTUR SMALL A}"),
|
| 1442 |
+
],
|
| 1443 |
+
},
|
| 1444 |
+
'scr': [
|
| 1445 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1446 |
+
"\N{LATIN CAPITAL LETTER A}",
|
| 1447 |
+
"it",
|
| 1448 |
+
"\N{MATHEMATICAL SCRIPT CAPITAL A}"),
|
| 1449 |
+
("\N{LATIN CAPITAL LETTER B}",
|
| 1450 |
+
"\N{LATIN CAPITAL LETTER B}",
|
| 1451 |
+
"it",
|
| 1452 |
+
"\N{SCRIPT CAPITAL B}"),
|
| 1453 |
+
("\N{LATIN CAPITAL LETTER C}",
|
| 1454 |
+
"\N{LATIN CAPITAL LETTER D}",
|
| 1455 |
+
"it",
|
| 1456 |
+
"\N{MATHEMATICAL SCRIPT CAPITAL C}"),
|
| 1457 |
+
("\N{LATIN CAPITAL LETTER E}",
|
| 1458 |
+
"\N{LATIN CAPITAL LETTER F}",
|
| 1459 |
+
"it",
|
| 1460 |
+
"\N{SCRIPT CAPITAL E}"),
|
| 1461 |
+
("\N{LATIN CAPITAL LETTER G}",
|
| 1462 |
+
"\N{LATIN CAPITAL LETTER G}",
|
| 1463 |
+
"it",
|
| 1464 |
+
"\N{MATHEMATICAL SCRIPT CAPITAL G}"),
|
| 1465 |
+
("\N{LATIN CAPITAL LETTER H}",
|
| 1466 |
+
"\N{LATIN CAPITAL LETTER H}",
|
| 1467 |
+
"it",
|
| 1468 |
+
"\N{SCRIPT CAPITAL H}"),
|
| 1469 |
+
("\N{LATIN CAPITAL LETTER I}",
|
| 1470 |
+
"\N{LATIN CAPITAL LETTER I}",
|
| 1471 |
+
"it",
|
| 1472 |
+
"\N{SCRIPT CAPITAL I}"),
|
| 1473 |
+
("\N{LATIN CAPITAL LETTER J}",
|
| 1474 |
+
"\N{LATIN CAPITAL LETTER K}",
|
| 1475 |
+
"it",
|
| 1476 |
+
"\N{MATHEMATICAL SCRIPT CAPITAL J}"),
|
| 1477 |
+
("\N{LATIN CAPITAL LETTER L}",
|
| 1478 |
+
"\N{LATIN CAPITAL LETTER L}",
|
| 1479 |
+
"it",
|
| 1480 |
+
"\N{SCRIPT CAPITAL L}"),
|
| 1481 |
+
("\N{LATIN CAPITAL LETTER M}",
|
| 1482 |
+
"\N{LATIN CAPITAL LETTER M}",
|
| 1483 |
+
"it",
|
| 1484 |
+
"\N{SCRIPT CAPITAL M}"),
|
| 1485 |
+
("\N{LATIN CAPITAL LETTER N}",
|
| 1486 |
+
"\N{LATIN CAPITAL LETTER Q}",
|
| 1487 |
+
"it",
|
| 1488 |
+
"\N{MATHEMATICAL SCRIPT CAPITAL N}"),
|
| 1489 |
+
("\N{LATIN CAPITAL LETTER R}",
|
| 1490 |
+
"\N{LATIN CAPITAL LETTER R}",
|
| 1491 |
+
"it",
|
| 1492 |
+
"\N{SCRIPT CAPITAL R}"),
|
| 1493 |
+
("\N{LATIN CAPITAL LETTER S}",
|
| 1494 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1495 |
+
"it",
|
| 1496 |
+
"\N{MATHEMATICAL SCRIPT CAPITAL S}"),
|
| 1497 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1498 |
+
"\N{LATIN SMALL LETTER D}",
|
| 1499 |
+
"it",
|
| 1500 |
+
"\N{MATHEMATICAL SCRIPT SMALL A}"),
|
| 1501 |
+
("\N{LATIN SMALL LETTER E}",
|
| 1502 |
+
"\N{LATIN SMALL LETTER E}",
|
| 1503 |
+
"it",
|
| 1504 |
+
"\N{SCRIPT SMALL E}"),
|
| 1505 |
+
("\N{LATIN SMALL LETTER F}",
|
| 1506 |
+
"\N{LATIN SMALL LETTER F}",
|
| 1507 |
+
"it",
|
| 1508 |
+
"\N{MATHEMATICAL SCRIPT SMALL F}"),
|
| 1509 |
+
("\N{LATIN SMALL LETTER G}",
|
| 1510 |
+
"\N{LATIN SMALL LETTER G}",
|
| 1511 |
+
"it",
|
| 1512 |
+
"\N{SCRIPT SMALL G}"),
|
| 1513 |
+
("\N{LATIN SMALL LETTER H}",
|
| 1514 |
+
"\N{LATIN SMALL LETTER N}",
|
| 1515 |
+
"it",
|
| 1516 |
+
"\N{MATHEMATICAL SCRIPT SMALL H}"),
|
| 1517 |
+
("\N{LATIN SMALL LETTER O}",
|
| 1518 |
+
"\N{LATIN SMALL LETTER O}",
|
| 1519 |
+
"it",
|
| 1520 |
+
"\N{SCRIPT SMALL O}"),
|
| 1521 |
+
("\N{LATIN SMALL LETTER P}",
|
| 1522 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1523 |
+
"it",
|
| 1524 |
+
"\N{MATHEMATICAL SCRIPT SMALL P}"),
|
| 1525 |
+
],
|
| 1526 |
+
'sf': {
|
| 1527 |
+
"rm": [
|
| 1528 |
+
("\N{DIGIT ZERO}",
|
| 1529 |
+
"\N{DIGIT NINE}",
|
| 1530 |
+
"rm",
|
| 1531 |
+
"\N{MATHEMATICAL SANS-SERIF DIGIT ZERO}"),
|
| 1532 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1533 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1534 |
+
"rm",
|
| 1535 |
+
"\N{MATHEMATICAL SANS-SERIF CAPITAL A}"),
|
| 1536 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1537 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1538 |
+
"rm",
|
| 1539 |
+
"\N{MATHEMATICAL SANS-SERIF SMALL A}"),
|
| 1540 |
+
("\N{GREEK CAPITAL LETTER ALPHA}",
|
| 1541 |
+
"\N{GREEK CAPITAL LETTER OMEGA}",
|
| 1542 |
+
"rm",
|
| 1543 |
+
0xe17d),
|
| 1544 |
+
("\N{GREEK SMALL LETTER ALPHA}",
|
| 1545 |
+
"\N{GREEK SMALL LETTER OMEGA}",
|
| 1546 |
+
"rm",
|
| 1547 |
+
0xe196),
|
| 1548 |
+
("\N{GREEK THETA SYMBOL}",
|
| 1549 |
+
"\N{GREEK THETA SYMBOL}",
|
| 1550 |
+
"rm",
|
| 1551 |
+
0xe1b0),
|
| 1552 |
+
("\N{GREEK PHI SYMBOL}",
|
| 1553 |
+
"\N{GREEK PHI SYMBOL}",
|
| 1554 |
+
"rm",
|
| 1555 |
+
0xe1b1),
|
| 1556 |
+
("\N{GREEK PI SYMBOL}",
|
| 1557 |
+
"\N{GREEK PI SYMBOL}",
|
| 1558 |
+
"rm",
|
| 1559 |
+
0xe1b3),
|
| 1560 |
+
("\N{GREEK RHO SYMBOL}",
|
| 1561 |
+
"\N{GREEK RHO SYMBOL}",
|
| 1562 |
+
"rm",
|
| 1563 |
+
0xe1b2),
|
| 1564 |
+
("\N{GREEK LUNATE EPSILON SYMBOL}",
|
| 1565 |
+
"\N{GREEK LUNATE EPSILON SYMBOL}",
|
| 1566 |
+
"rm",
|
| 1567 |
+
0xe1af),
|
| 1568 |
+
("\N{PARTIAL DIFFERENTIAL}",
|
| 1569 |
+
"\N{PARTIAL DIFFERENTIAL}",
|
| 1570 |
+
"rm",
|
| 1571 |
+
0xe17c),
|
| 1572 |
+
],
|
| 1573 |
+
"it": [
|
| 1574 |
+
# These numerals are actually upright. We don't actually
|
| 1575 |
+
# want italic numerals ever.
|
| 1576 |
+
("\N{DIGIT ZERO}",
|
| 1577 |
+
"\N{DIGIT NINE}",
|
| 1578 |
+
"rm",
|
| 1579 |
+
"\N{MATHEMATICAL SANS-SERIF DIGIT ZERO}"),
|
| 1580 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1581 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1582 |
+
"it",
|
| 1583 |
+
"\N{MATHEMATICAL SANS-SERIF ITALIC CAPITAL A}"),
|
| 1584 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1585 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1586 |
+
"it",
|
| 1587 |
+
"\N{MATHEMATICAL SANS-SERIF ITALIC SMALL A}"),
|
| 1588 |
+
("\N{GREEK CAPITAL LETTER ALPHA}",
|
| 1589 |
+
"\N{GREEK CAPITAL LETTER OMEGA}",
|
| 1590 |
+
"rm",
|
| 1591 |
+
0xe17d),
|
| 1592 |
+
("\N{GREEK SMALL LETTER ALPHA}",
|
| 1593 |
+
"\N{GREEK SMALL LETTER OMEGA}",
|
| 1594 |
+
"it",
|
| 1595 |
+
0xe1d8),
|
| 1596 |
+
("\N{GREEK THETA SYMBOL}",
|
| 1597 |
+
"\N{GREEK THETA SYMBOL}",
|
| 1598 |
+
"it",
|
| 1599 |
+
0xe1f2),
|
| 1600 |
+
("\N{GREEK PHI SYMBOL}",
|
| 1601 |
+
"\N{GREEK PHI SYMBOL}",
|
| 1602 |
+
"it",
|
| 1603 |
+
0xe1f3),
|
| 1604 |
+
("\N{GREEK PI SYMBOL}",
|
| 1605 |
+
"\N{GREEK PI SYMBOL}",
|
| 1606 |
+
"it",
|
| 1607 |
+
0xe1f5),
|
| 1608 |
+
("\N{GREEK RHO SYMBOL}",
|
| 1609 |
+
"\N{GREEK RHO SYMBOL}",
|
| 1610 |
+
"it",
|
| 1611 |
+
0xe1f4),
|
| 1612 |
+
("\N{GREEK LUNATE EPSILON SYMBOL}",
|
| 1613 |
+
"\N{GREEK LUNATE EPSILON SYMBOL}",
|
| 1614 |
+
"it",
|
| 1615 |
+
0xe1f1),
|
| 1616 |
+
],
|
| 1617 |
+
"bf": [
|
| 1618 |
+
("\N{DIGIT ZERO}",
|
| 1619 |
+
"\N{DIGIT NINE}",
|
| 1620 |
+
"bf",
|
| 1621 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD DIGIT ZERO}"),
|
| 1622 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1623 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1624 |
+
"bf",
|
| 1625 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD CAPITAL A}"),
|
| 1626 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1627 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1628 |
+
"bf",
|
| 1629 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD SMALL A}"),
|
| 1630 |
+
("\N{GREEK CAPITAL LETTER ALPHA}",
|
| 1631 |
+
"\N{GREEK CAPITAL LETTER OMEGA}",
|
| 1632 |
+
"bf",
|
| 1633 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD CAPITAL ALPHA}"),
|
| 1634 |
+
("\N{GREEK SMALL LETTER ALPHA}",
|
| 1635 |
+
"\N{GREEK SMALL LETTER OMEGA}",
|
| 1636 |
+
"bf",
|
| 1637 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA}"),
|
| 1638 |
+
("\N{GREEK THETA SYMBOL}",
|
| 1639 |
+
"\N{GREEK THETA SYMBOL}",
|
| 1640 |
+
"bf",
|
| 1641 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD THETA SYMBOL}"),
|
| 1642 |
+
("\N{GREEK PHI SYMBOL}",
|
| 1643 |
+
"\N{GREEK PHI SYMBOL}",
|
| 1644 |
+
"bf",
|
| 1645 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD PHI SYMBOL}"),
|
| 1646 |
+
("\N{GREEK PI SYMBOL}",
|
| 1647 |
+
"\N{GREEK PI SYMBOL}",
|
| 1648 |
+
"bf",
|
| 1649 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD PI SYMBOL}"),
|
| 1650 |
+
("\N{GREEK KAPPA SYMBOL}",
|
| 1651 |
+
"\N{GREEK KAPPA SYMBOL}",
|
| 1652 |
+
"bf",
|
| 1653 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD KAPPA SYMBOL}"),
|
| 1654 |
+
("\N{GREEK RHO SYMBOL}",
|
| 1655 |
+
"\N{GREEK RHO SYMBOL}",
|
| 1656 |
+
"bf",
|
| 1657 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD RHO SYMBOL}"),
|
| 1658 |
+
("\N{GREEK LUNATE EPSILON SYMBOL}",
|
| 1659 |
+
"\N{GREEK LUNATE EPSILON SYMBOL}",
|
| 1660 |
+
"bf",
|
| 1661 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL}"),
|
| 1662 |
+
("\N{PARTIAL DIFFERENTIAL}",
|
| 1663 |
+
"\N{PARTIAL DIFFERENTIAL}",
|
| 1664 |
+
"bf",
|
| 1665 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL}"),
|
| 1666 |
+
("\N{NABLA}",
|
| 1667 |
+
"\N{NABLA}",
|
| 1668 |
+
"bf",
|
| 1669 |
+
"\N{MATHEMATICAL SANS-SERIF BOLD NABLA}"),
|
| 1670 |
+
],
|
| 1671 |
+
"bfit": [
|
| 1672 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1673 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1674 |
+
"bfit",
|
| 1675 |
+
"\N{MATHEMATICAL BOLD ITALIC CAPITAL A}"),
|
| 1676 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1677 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1678 |
+
"bfit",
|
| 1679 |
+
"\N{MATHEMATICAL BOLD ITALIC SMALL A}"),
|
| 1680 |
+
("\N{GREEK CAPITAL LETTER GAMMA}",
|
| 1681 |
+
"\N{GREEK CAPITAL LETTER OMEGA}",
|
| 1682 |
+
"bfit",
|
| 1683 |
+
"\N{MATHEMATICAL BOLD ITALIC CAPITAL GAMMA}"),
|
| 1684 |
+
("\N{GREEK SMALL LETTER ALPHA}",
|
| 1685 |
+
"\N{GREEK SMALL LETTER OMEGA}",
|
| 1686 |
+
"bfit",
|
| 1687 |
+
"\N{MATHEMATICAL BOLD ITALIC SMALL ALPHA}"),
|
| 1688 |
+
],
|
| 1689 |
+
},
|
| 1690 |
+
'tt': [
|
| 1691 |
+
("\N{DIGIT ZERO}",
|
| 1692 |
+
"\N{DIGIT NINE}",
|
| 1693 |
+
"rm",
|
| 1694 |
+
"\N{MATHEMATICAL MONOSPACE DIGIT ZERO}"),
|
| 1695 |
+
("\N{LATIN CAPITAL LETTER A}",
|
| 1696 |
+
"\N{LATIN CAPITAL LETTER Z}",
|
| 1697 |
+
"rm",
|
| 1698 |
+
"\N{MATHEMATICAL MONOSPACE CAPITAL A}"),
|
| 1699 |
+
("\N{LATIN SMALL LETTER A}",
|
| 1700 |
+
"\N{LATIN SMALL LETTER Z}",
|
| 1701 |
+
"rm",
|
| 1702 |
+
"\N{MATHEMATICAL MONOSPACE SMALL A}")
|
| 1703 |
+
],
|
| 1704 |
+
}
|
| 1705 |
+
|
| 1706 |
+
|
| 1707 |
+
@overload
|
| 1708 |
+
def _normalize_stix_fontcodes(d: _EntryTypeIn) -> _EntryTypeOut: ...
|
| 1709 |
+
|
| 1710 |
+
|
| 1711 |
+
@overload
|
| 1712 |
+
def _normalize_stix_fontcodes(d: list[_EntryTypeIn]) -> list[_EntryTypeOut]: ...
|
| 1713 |
+
|
| 1714 |
+
|
| 1715 |
+
@overload
|
| 1716 |
+
def _normalize_stix_fontcodes(d: dict[str, list[_EntryTypeIn] |
|
| 1717 |
+
dict[str, list[_EntryTypeIn]]]
|
| 1718 |
+
) -> dict[str, list[_EntryTypeOut] |
|
| 1719 |
+
dict[str, list[_EntryTypeOut]]]: ...
|
| 1720 |
+
|
| 1721 |
+
|
| 1722 |
+
def _normalize_stix_fontcodes(d):
|
| 1723 |
+
if isinstance(d, tuple):
|
| 1724 |
+
return tuple(ord(x) if isinstance(x, str) and len(x) == 1 else x for x in d)
|
| 1725 |
+
elif isinstance(d, list):
|
| 1726 |
+
return [_normalize_stix_fontcodes(x) for x in d]
|
| 1727 |
+
elif isinstance(d, dict):
|
| 1728 |
+
return {k: _normalize_stix_fontcodes(v) for k, v in d.items()}
|
| 1729 |
+
|
| 1730 |
+
|
| 1731 |
+
stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeOut]] | list[_EntryTypeOut]]
|
| 1732 |
+
stix_virtual_fonts = _normalize_stix_fontcodes(_stix_virtual_fonts)
|
| 1733 |
+
|
| 1734 |
+
# Free redundant list now that it has been normalized
|
| 1735 |
+
del _stix_virtual_fonts
|
| 1736 |
+
|
| 1737 |
+
# Fix some incorrect glyphs.
|
| 1738 |
+
stix_glyph_fixes = {
|
| 1739 |
+
# Cap and Cup glyphs are swapped.
|
| 1740 |
+
0x22d2: 0x22d3,
|
| 1741 |
+
0x22d3: 0x22d2,
|
| 1742 |
+
}
|
moondream/lib/python3.10/site-packages/matplotlib/_path.pyi
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from .transforms import BboxBase
|
| 6 |
+
|
| 7 |
+
def affine_transform(points: np.ndarray, trans: np.ndarray) -> np.ndarray: ...
|
| 8 |
+
def count_bboxes_overlapping_bbox(bbox: BboxBase, bboxes: Sequence[BboxBase]) -> int: ...
|
| 9 |
+
def update_path_extents(path, trans, rect, minpos, ignore): ...
|
moondream/lib/python3.10/site-packages/matplotlib/_qhull.pyi
ADDED
|
File without changes
|
moondream/lib/python3.10/site-packages/matplotlib/_tight_bbox.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Helper module for the *bbox_inches* parameter in `.Figure.savefig`.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
|
| 9 |
+
"""
|
| 10 |
+
Temporarily adjust the figure so that only the specified area
|
| 11 |
+
(bbox_inches) is saved.
|
| 12 |
+
|
| 13 |
+
It modifies fig.bbox, fig.bbox_inches,
|
| 14 |
+
fig.transFigure._boxout, and fig.patch. While the figure size
|
| 15 |
+
changes, the scale of the original figure is conserved. A
|
| 16 |
+
function which restores the original values are returned.
|
| 17 |
+
"""
|
| 18 |
+
origBbox = fig.bbox
|
| 19 |
+
origBboxInches = fig.bbox_inches
|
| 20 |
+
_boxout = fig.transFigure._boxout
|
| 21 |
+
|
| 22 |
+
old_aspect = []
|
| 23 |
+
locator_list = []
|
| 24 |
+
sentinel = object()
|
| 25 |
+
for ax in fig.axes:
|
| 26 |
+
locator = ax.get_axes_locator()
|
| 27 |
+
if locator is not None:
|
| 28 |
+
ax.apply_aspect(locator(ax, None))
|
| 29 |
+
locator_list.append(locator)
|
| 30 |
+
current_pos = ax.get_position(original=False).frozen()
|
| 31 |
+
ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos)
|
| 32 |
+
# override the method that enforces the aspect ratio on the Axes
|
| 33 |
+
if 'apply_aspect' in ax.__dict__:
|
| 34 |
+
old_aspect.append(ax.apply_aspect)
|
| 35 |
+
else:
|
| 36 |
+
old_aspect.append(sentinel)
|
| 37 |
+
ax.apply_aspect = lambda pos=None: None
|
| 38 |
+
|
| 39 |
+
def restore_bbox():
|
| 40 |
+
for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect):
|
| 41 |
+
ax.set_axes_locator(loc)
|
| 42 |
+
if aspect is sentinel:
|
| 43 |
+
# delete our no-op function which un-hides the original method
|
| 44 |
+
del ax.apply_aspect
|
| 45 |
+
else:
|
| 46 |
+
ax.apply_aspect = aspect
|
| 47 |
+
|
| 48 |
+
fig.bbox = origBbox
|
| 49 |
+
fig.bbox_inches = origBboxInches
|
| 50 |
+
fig.transFigure._boxout = _boxout
|
| 51 |
+
fig.transFigure.invalidate()
|
| 52 |
+
fig.patch.set_bounds(0, 0, 1, 1)
|
| 53 |
+
|
| 54 |
+
if fixed_dpi is None:
|
| 55 |
+
fixed_dpi = fig.dpi
|
| 56 |
+
tr = Affine2D().scale(fixed_dpi)
|
| 57 |
+
dpi_scale = fixed_dpi / fig.dpi
|
| 58 |
+
|
| 59 |
+
fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size)
|
| 60 |
+
x0, y0 = tr.transform(bbox_inches.p0)
|
| 61 |
+
w1, h1 = fig.bbox.size * dpi_scale
|
| 62 |
+
fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
|
| 63 |
+
fig.transFigure.invalidate()
|
| 64 |
+
|
| 65 |
+
fig.bbox = TransformedBbox(fig.bbox_inches, tr)
|
| 66 |
+
|
| 67 |
+
fig.patch.set_bounds(x0 / w1, y0 / h1,
|
| 68 |
+
fig.bbox.width / w1, fig.bbox.height / h1)
|
| 69 |
+
|
| 70 |
+
return restore_bbox
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None):
|
| 74 |
+
"""
|
| 75 |
+
A function that needs to be called when figure dpi changes during the
|
| 76 |
+
drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with
|
| 77 |
+
the new dpi.
|
| 78 |
+
"""
|
| 79 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|
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
from tempfile import TemporaryDirectory
|
| 12 |
+
import uuid
|
| 13 |
+
import warnings
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
import matplotlib as mpl
|
| 19 |
+
from matplotlib._animation_data import (
|
| 20 |
+
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
|
| 21 |
+
from matplotlib import _api, cbook
|
| 22 |
+
import matplotlib.colors as mcolors
|
| 23 |
+
|
| 24 |
+
_log = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
# Process creation flag for subprocess to prevent it raising a terminal
|
| 27 |
+
# window. See for example https://stackoverflow.com/q/24130623/
|
| 28 |
+
subprocess_creation_flags = (
|
| 29 |
+
subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def adjusted_figsize(w, h, dpi, n):
|
| 33 |
+
"""
|
| 34 |
+
Compute figure size so that pixels are a multiple of n.
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
----------
|
| 38 |
+
w, h : float
|
| 39 |
+
Size in inches.
|
| 40 |
+
|
| 41 |
+
dpi : float
|
| 42 |
+
The dpi.
|
| 43 |
+
|
| 44 |
+
n : int
|
| 45 |
+
The target multiple.
|
| 46 |
+
|
| 47 |
+
Returns
|
| 48 |
+
-------
|
| 49 |
+
wnew, hnew : float
|
| 50 |
+
The new figure size in inches.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
# this maybe simplified if / when we adopt consistent rounding for
|
| 54 |
+
# pixel size across the whole library
|
| 55 |
+
def correct_roundoff(x, dpi, n):
|
| 56 |
+
if int(x*dpi) % n != 0:
|
| 57 |
+
if int(np.nextafter(x, np.inf)*dpi) % n == 0:
|
| 58 |
+
x = np.nextafter(x, np.inf)
|
| 59 |
+
elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
|
| 60 |
+
x = np.nextafter(x, -np.inf)
|
| 61 |
+
return x
|
| 62 |
+
|
| 63 |
+
wnew = int(w * dpi / n) * n / dpi
|
| 64 |
+
hnew = int(h * dpi / n) * n / dpi
|
| 65 |
+
return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class MovieWriterRegistry:
|
| 69 |
+
"""Registry of available writer classes by human readable name."""
|
| 70 |
+
|
| 71 |
+
def __init__(self):
|
| 72 |
+
self._registered = dict()
|
| 73 |
+
|
| 74 |
+
def register(self, name):
|
| 75 |
+
"""
|
| 76 |
+
Decorator for registering a class under a name.
|
| 77 |
+
|
| 78 |
+
Example use::
|
| 79 |
+
|
| 80 |
+
@registry.register(name)
|
| 81 |
+
class Foo:
|
| 82 |
+
pass
|
| 83 |
+
"""
|
| 84 |
+
def wrapper(writer_cls):
|
| 85 |
+
self._registered[name] = writer_cls
|
| 86 |
+
return writer_cls
|
| 87 |
+
return wrapper
|
| 88 |
+
|
| 89 |
+
def is_available(self, name):
|
| 90 |
+
"""
|
| 91 |
+
Check if given writer is available by name.
|
| 92 |
+
|
| 93 |
+
Parameters
|
| 94 |
+
----------
|
| 95 |
+
name : str
|
| 96 |
+
|
| 97 |
+
Returns
|
| 98 |
+
-------
|
| 99 |
+
bool
|
| 100 |
+
"""
|
| 101 |
+
try:
|
| 102 |
+
cls = self._registered[name]
|
| 103 |
+
except KeyError:
|
| 104 |
+
return False
|
| 105 |
+
return cls.isAvailable()
|
| 106 |
+
|
| 107 |
+
def __iter__(self):
|
| 108 |
+
"""Iterate over names of available writer class."""
|
| 109 |
+
for name in self._registered:
|
| 110 |
+
if self.is_available(name):
|
| 111 |
+
yield name
|
| 112 |
+
|
| 113 |
+
def list(self):
|
| 114 |
+
"""Get a list of available MovieWriters."""
|
| 115 |
+
return [*self]
|
| 116 |
+
|
| 117 |
+
def __getitem__(self, name):
|
| 118 |
+
"""Get an available writer class from its name."""
|
| 119 |
+
if self.is_available(name):
|
| 120 |
+
return self._registered[name]
|
| 121 |
+
raise RuntimeError(f"Requested MovieWriter ({name}) not available")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
writers = MovieWriterRegistry()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class AbstractMovieWriter(abc.ABC):
|
| 128 |
+
"""
|
| 129 |
+
Abstract base class for writing movies, providing a way to grab frames by
|
| 130 |
+
calling `~AbstractMovieWriter.grab_frame`.
|
| 131 |
+
|
| 132 |
+
`setup` is called to start the process and `finish` is called afterwards.
|
| 133 |
+
`saving` is provided as a context manager to facilitate this process as ::
|
| 134 |
+
|
| 135 |
+
with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
|
| 136 |
+
# Iterate over frames
|
| 137 |
+
moviewriter.grab_frame(**savefig_kwargs)
|
| 138 |
+
|
| 139 |
+
The use of the context manager ensures that `setup` and `finish` are
|
| 140 |
+
performed as necessary.
|
| 141 |
+
|
| 142 |
+
An instance of a concrete subclass of this class can be given as the
|
| 143 |
+
``writer`` argument of `Animation.save()`.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
|
| 147 |
+
self.fps = fps
|
| 148 |
+
self.metadata = metadata if metadata is not None else {}
|
| 149 |
+
self.codec = mpl._val_or_rc(codec, 'animation.codec')
|
| 150 |
+
self.bitrate = mpl._val_or_rc(bitrate, 'animation.bitrate')
|
| 151 |
+
|
| 152 |
+
@abc.abstractmethod
|
| 153 |
+
def setup(self, fig, outfile, dpi=None):
|
| 154 |
+
"""
|
| 155 |
+
Setup for writing the movie file.
|
| 156 |
+
|
| 157 |
+
Parameters
|
| 158 |
+
----------
|
| 159 |
+
fig : `~matplotlib.figure.Figure`
|
| 160 |
+
The figure object that contains the information for frames.
|
| 161 |
+
outfile : str
|
| 162 |
+
The filename of the resulting movie file.
|
| 163 |
+
dpi : float, default: ``fig.dpi``
|
| 164 |
+
The DPI (or resolution) for the file. This controls the size
|
| 165 |
+
in pixels of the resulting movie file.
|
| 166 |
+
"""
|
| 167 |
+
# Check that path is valid
|
| 168 |
+
Path(outfile).parent.resolve(strict=True)
|
| 169 |
+
self.outfile = outfile
|
| 170 |
+
self.fig = fig
|
| 171 |
+
if dpi is None:
|
| 172 |
+
dpi = self.fig.dpi
|
| 173 |
+
self.dpi = dpi
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def frame_size(self):
|
| 177 |
+
"""A tuple ``(width, height)`` in pixels of a movie frame."""
|
| 178 |
+
w, h = self.fig.get_size_inches()
|
| 179 |
+
return int(w * self.dpi), int(h * self.dpi)
|
| 180 |
+
|
| 181 |
+
def _supports_transparency(self):
|
| 182 |
+
"""
|
| 183 |
+
Whether this writer supports transparency.
|
| 184 |
+
|
| 185 |
+
Writers may consult output file type and codec to determine this at runtime.
|
| 186 |
+
"""
|
| 187 |
+
return False
|
| 188 |
+
|
| 189 |
+
@abc.abstractmethod
|
| 190 |
+
def grab_frame(self, **savefig_kwargs):
|
| 191 |
+
"""
|
| 192 |
+
Grab the image information from the figure and save as a movie frame.
|
| 193 |
+
|
| 194 |
+
All keyword arguments in *savefig_kwargs* are passed on to the
|
| 195 |
+
`~.Figure.savefig` call that saves the figure. However, several
|
| 196 |
+
keyword arguments that are supported by `~.Figure.savefig` may not be
|
| 197 |
+
passed as they are controlled by the MovieWriter:
|
| 198 |
+
|
| 199 |
+
- *dpi*, *bbox_inches*: These may not be passed because each frame of the
|
| 200 |
+
animation much be exactly the same size in pixels.
|
| 201 |
+
- *format*: This is controlled by the MovieWriter.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
@abc.abstractmethod
|
| 205 |
+
def finish(self):
|
| 206 |
+
"""Finish any processing for writing the movie."""
|
| 207 |
+
|
| 208 |
+
@contextlib.contextmanager
|
| 209 |
+
def saving(self, fig, outfile, dpi, *args, **kwargs):
|
| 210 |
+
"""
|
| 211 |
+
Context manager to facilitate writing the movie file.
|
| 212 |
+
|
| 213 |
+
``*args, **kw`` are any parameters that should be passed to `setup`.
|
| 214 |
+
"""
|
| 215 |
+
if mpl.rcParams['savefig.bbox'] == 'tight':
|
| 216 |
+
_log.info("Disabling savefig.bbox = 'tight', as it may cause "
|
| 217 |
+
"frame size to vary, which is inappropriate for "
|
| 218 |
+
"animation.")
|
| 219 |
+
|
| 220 |
+
# This particular sequence is what contextlib.contextmanager wants
|
| 221 |
+
self.setup(fig, outfile, dpi, *args, **kwargs)
|
| 222 |
+
with mpl.rc_context({'savefig.bbox': None}):
|
| 223 |
+
try:
|
| 224 |
+
yield self
|
| 225 |
+
finally:
|
| 226 |
+
self.finish()
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class MovieWriter(AbstractMovieWriter):
|
| 230 |
+
"""
|
| 231 |
+
Base class for writing movies.
|
| 232 |
+
|
| 233 |
+
This is a base class for MovieWriter subclasses that write a movie frame
|
| 234 |
+
data to a pipe. You cannot instantiate this class directly.
|
| 235 |
+
See examples for how to use its subclasses.
|
| 236 |
+
|
| 237 |
+
Attributes
|
| 238 |
+
----------
|
| 239 |
+
frame_format : str
|
| 240 |
+
The format used in writing frame data, defaults to 'rgba'.
|
| 241 |
+
fig : `~matplotlib.figure.Figure`
|
| 242 |
+
The figure to capture data from.
|
| 243 |
+
This must be provided by the subclasses.
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
# Builtin writer subclasses additionally define the _exec_key and _args_key
|
| 247 |
+
# attributes, which indicate the rcParams entries where the path to the
|
| 248 |
+
# executable and additional command-line arguments to the executable are
|
| 249 |
+
# stored. Third-party writers cannot meaningfully set these as they cannot
|
| 250 |
+
# extend rcParams with new keys.
|
| 251 |
+
|
| 252 |
+
# Pipe-based writers only support RGBA, but file-based ones support more
|
| 253 |
+
# formats.
|
| 254 |
+
supported_formats = ["rgba"]
|
| 255 |
+
|
| 256 |
+
def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
|
| 257 |
+
metadata=None):
|
| 258 |
+
"""
|
| 259 |
+
Parameters
|
| 260 |
+
----------
|
| 261 |
+
fps : int, default: 5
|
| 262 |
+
Movie frame rate (per second).
|
| 263 |
+
codec : str or None, default: :rc:`animation.codec`
|
| 264 |
+
The codec to use.
|
| 265 |
+
bitrate : int, default: :rc:`animation.bitrate`
|
| 266 |
+
The bitrate of the movie, in kilobits per second. Higher values
|
| 267 |
+
means higher quality movies, but increase the file size. A value
|
| 268 |
+
of -1 lets the underlying movie encoder select the bitrate.
|
| 269 |
+
extra_args : list of str or None, optional
|
| 270 |
+
Extra command-line arguments passed to the underlying movie encoder. These
|
| 271 |
+
arguments are passed last to the encoder, just before the filename. The
|
| 272 |
+
default, None, means to use :rc:`animation.[name-of-encoder]_args` for the
|
| 273 |
+
builtin writers.
|
| 274 |
+
metadata : dict[str, str], default: {}
|
| 275 |
+
A dictionary of keys and values for metadata to include in the
|
| 276 |
+
output file. Some keys that may be of use include:
|
| 277 |
+
title, artist, genre, subject, copyright, srcform, comment.
|
| 278 |
+
"""
|
| 279 |
+
if type(self) is MovieWriter:
|
| 280 |
+
# TODO MovieWriter is still an abstract class and needs to be
|
| 281 |
+
# extended with a mixin. This should be clearer in naming
|
| 282 |
+
# and description. For now, just give a reasonable error
|
| 283 |
+
# message to users.
|
| 284 |
+
raise TypeError(
|
| 285 |
+
'MovieWriter cannot be instantiated directly. Please use one '
|
| 286 |
+
'of its subclasses.')
|
| 287 |
+
|
| 288 |
+
super().__init__(fps=fps, metadata=metadata, codec=codec,
|
| 289 |
+
bitrate=bitrate)
|
| 290 |
+
self.frame_format = self.supported_formats[0]
|
| 291 |
+
self.extra_args = extra_args
|
| 292 |
+
|
| 293 |
+
def _adjust_frame_size(self):
|
| 294 |
+
if self.codec == 'h264':
|
| 295 |
+
wo, ho = self.fig.get_size_inches()
|
| 296 |
+
w, h = adjusted_figsize(wo, ho, self.dpi, 2)
|
| 297 |
+
if (wo, ho) != (w, h):
|
| 298 |
+
self.fig.set_size_inches(w, h, forward=True)
|
| 299 |
+
_log.info('figure size in inches has been adjusted '
|
| 300 |
+
'from %s x %s to %s x %s', wo, ho, w, h)
|
| 301 |
+
else:
|
| 302 |
+
w, h = self.fig.get_size_inches()
|
| 303 |
+
_log.debug('frame size in pixels is %s x %s', *self.frame_size)
|
| 304 |
+
return w, h
|
| 305 |
+
|
| 306 |
+
def setup(self, fig, outfile, dpi=None):
|
| 307 |
+
# docstring inherited
|
| 308 |
+
super().setup(fig, outfile, dpi=dpi)
|
| 309 |
+
self._w, self._h = self._adjust_frame_size()
|
| 310 |
+
# Run here so that grab_frame() can write the data to a pipe. This
|
| 311 |
+
# eliminates the need for temp files.
|
| 312 |
+
self._run()
|
| 313 |
+
|
| 314 |
+
def _run(self):
|
| 315 |
+
# Uses subprocess to call the program for assembling frames into a
|
| 316 |
+
# movie file. *args* returns the sequence of command line arguments
|
| 317 |
+
# from a few configuration options.
|
| 318 |
+
command = self._args()
|
| 319 |
+
_log.info('MovieWriter._run: running command: %s',
|
| 320 |
+
cbook._pformat_subprocess(command))
|
| 321 |
+
PIPE = subprocess.PIPE
|
| 322 |
+
self._proc = subprocess.Popen(
|
| 323 |
+
command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
|
| 324 |
+
creationflags=subprocess_creation_flags)
|
| 325 |
+
|
| 326 |
+
def finish(self):
|
| 327 |
+
"""Finish any processing for writing the movie."""
|
| 328 |
+
out, err = self._proc.communicate()
|
| 329 |
+
# Use the encoding/errors that universal_newlines would use.
|
| 330 |
+
out = TextIOWrapper(BytesIO(out)).read()
|
| 331 |
+
err = TextIOWrapper(BytesIO(err)).read()
|
| 332 |
+
if out:
|
| 333 |
+
_log.log(
|
| 334 |
+
logging.WARNING if self._proc.returncode else logging.DEBUG,
|
| 335 |
+
"MovieWriter stdout:\n%s", out)
|
| 336 |
+
if err:
|
| 337 |
+
_log.log(
|
| 338 |
+
logging.WARNING if self._proc.returncode else logging.DEBUG,
|
| 339 |
+
"MovieWriter stderr:\n%s", err)
|
| 340 |
+
if self._proc.returncode:
|
| 341 |
+
raise subprocess.CalledProcessError(
|
| 342 |
+
self._proc.returncode, self._proc.args, out, err)
|
| 343 |
+
|
| 344 |
+
def grab_frame(self, **savefig_kwargs):
|
| 345 |
+
# docstring inherited
|
| 346 |
+
_validate_grabframe_kwargs(savefig_kwargs)
|
| 347 |
+
_log.debug('MovieWriter.grab_frame: Grabbing frame.')
|
| 348 |
+
# Readjust the figure size in case it has been changed by the user.
|
| 349 |
+
# All frames must have the same size to save the movie correctly.
|
| 350 |
+
self.fig.set_size_inches(self._w, self._h)
|
| 351 |
+
# Save the figure data to the sink, using the frame format and dpi.
|
| 352 |
+
self.fig.savefig(self._proc.stdin, format=self.frame_format,
|
| 353 |
+
dpi=self.dpi, **savefig_kwargs)
|
| 354 |
+
|
| 355 |
+
def _args(self):
|
| 356 |
+
"""Assemble list of encoder-specific command-line arguments."""
|
| 357 |
+
return NotImplementedError("args needs to be implemented by subclass.")
|
| 358 |
+
|
| 359 |
+
@classmethod
|
| 360 |
+
def bin_path(cls):
|
| 361 |
+
"""
|
| 362 |
+
Return the binary path to the commandline tool used by a specific
|
| 363 |
+
subclass. This is a class method so that the tool can be looked for
|
| 364 |
+
before making a particular MovieWriter subclass available.
|
| 365 |
+
"""
|
| 366 |
+
return str(mpl.rcParams[cls._exec_key])
|
| 367 |
+
|
| 368 |
+
@classmethod
|
| 369 |
+
def isAvailable(cls):
|
| 370 |
+
"""Return whether a MovieWriter subclass is actually available."""
|
| 371 |
+
return shutil.which(cls.bin_path()) is not None
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class FileMovieWriter(MovieWriter):
|
| 375 |
+
"""
|
| 376 |
+
`MovieWriter` for writing to individual files and stitching at the end.
|
| 377 |
+
|
| 378 |
+
This must be sub-classed to be useful.
|
| 379 |
+
"""
|
| 380 |
+
def __init__(self, *args, **kwargs):
|
| 381 |
+
super().__init__(*args, **kwargs)
|
| 382 |
+
self.frame_format = mpl.rcParams['animation.frame_format']
|
| 383 |
+
|
| 384 |
+
def setup(self, fig, outfile, dpi=None, frame_prefix=None):
|
| 385 |
+
"""
|
| 386 |
+
Setup for writing the movie file.
|
| 387 |
+
|
| 388 |
+
Parameters
|
| 389 |
+
----------
|
| 390 |
+
fig : `~matplotlib.figure.Figure`
|
| 391 |
+
The figure to grab the rendered frames from.
|
| 392 |
+
outfile : str
|
| 393 |
+
The filename of the resulting movie file.
|
| 394 |
+
dpi : float, default: ``fig.dpi``
|
| 395 |
+
The dpi of the output file. This, with the figure size,
|
| 396 |
+
controls the size in pixels of the resulting movie file.
|
| 397 |
+
frame_prefix : str, optional
|
| 398 |
+
The filename prefix to use for temporary files. If *None* (the
|
| 399 |
+
default), files are written to a temporary directory which is
|
| 400 |
+
deleted by `finish`; if not *None*, no temporary files are
|
| 401 |
+
deleted.
|
| 402 |
+
"""
|
| 403 |
+
# Check that path is valid
|
| 404 |
+
Path(outfile).parent.resolve(strict=True)
|
| 405 |
+
self.fig = fig
|
| 406 |
+
self.outfile = outfile
|
| 407 |
+
if dpi is None:
|
| 408 |
+
dpi = self.fig.dpi
|
| 409 |
+
self.dpi = dpi
|
| 410 |
+
self._adjust_frame_size()
|
| 411 |
+
|
| 412 |
+
if frame_prefix is None:
|
| 413 |
+
self._tmpdir = TemporaryDirectory()
|
| 414 |
+
self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
|
| 415 |
+
else:
|
| 416 |
+
self._tmpdir = None
|
| 417 |
+
self.temp_prefix = frame_prefix
|
| 418 |
+
self._frame_counter = 0 # used for generating sequential file names
|
| 419 |
+
self._temp_paths = list()
|
| 420 |
+
self.fname_format_str = '%s%%07d.%s'
|
| 421 |
+
|
| 422 |
+
def __del__(self):
|
| 423 |
+
if hasattr(self, '_tmpdir') and self._tmpdir:
|
| 424 |
+
self._tmpdir.cleanup()
|
| 425 |
+
|
| 426 |
+
@property
|
| 427 |
+
def frame_format(self):
|
| 428 |
+
"""
|
| 429 |
+
Format (png, jpeg, etc.) to use for saving the frames, which can be
|
| 430 |
+
decided by the individual subclasses.
|
| 431 |
+
"""
|
| 432 |
+
return self._frame_format
|
| 433 |
+
|
| 434 |
+
@frame_format.setter
|
| 435 |
+
def frame_format(self, frame_format):
|
| 436 |
+
if frame_format in self.supported_formats:
|
| 437 |
+
self._frame_format = frame_format
|
| 438 |
+
else:
|
| 439 |
+
_api.warn_external(
|
| 440 |
+
f"Ignoring file format {frame_format!r} which is not "
|
| 441 |
+
f"supported by {type(self).__name__}; using "
|
| 442 |
+
f"{self.supported_formats[0]} instead.")
|
| 443 |
+
self._frame_format = self.supported_formats[0]
|
| 444 |
+
|
| 445 |
+
def _base_temp_name(self):
|
| 446 |
+
# Generates a template name (without number) given the frame format
|
| 447 |
+
# for extension and the prefix.
|
| 448 |
+
return self.fname_format_str % (self.temp_prefix, self.frame_format)
|
| 449 |
+
|
| 450 |
+
def grab_frame(self, **savefig_kwargs):
|
| 451 |
+
# docstring inherited
|
| 452 |
+
# Creates a filename for saving using basename and counter.
|
| 453 |
+
_validate_grabframe_kwargs(savefig_kwargs)
|
| 454 |
+
path = Path(self._base_temp_name() % self._frame_counter)
|
| 455 |
+
self._temp_paths.append(path) # Record the filename for later use.
|
| 456 |
+
self._frame_counter += 1 # Ensures each created name is unique.
|
| 457 |
+
_log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s',
|
| 458 |
+
self._frame_counter, path)
|
| 459 |
+
with open(path, 'wb') as sink: # Save figure to the sink.
|
| 460 |
+
self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi,
|
| 461 |
+
**savefig_kwargs)
|
| 462 |
+
|
| 463 |
+
def finish(self):
|
| 464 |
+
# Call run here now that all frame grabbing is done. All temp files
|
| 465 |
+
# are available to be assembled.
|
| 466 |
+
try:
|
| 467 |
+
self._run()
|
| 468 |
+
super().finish()
|
| 469 |
+
finally:
|
| 470 |
+
if self._tmpdir:
|
| 471 |
+
_log.debug(
|
| 472 |
+
'MovieWriter: clearing temporary path=%s', self._tmpdir
|
| 473 |
+
)
|
| 474 |
+
self._tmpdir.cleanup()
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
@writers.register('pillow')
|
| 478 |
+
class PillowWriter(AbstractMovieWriter):
|
| 479 |
+
def _supports_transparency(self):
|
| 480 |
+
return True
|
| 481 |
+
|
| 482 |
+
@classmethod
|
| 483 |
+
def isAvailable(cls):
|
| 484 |
+
return True
|
| 485 |
+
|
| 486 |
+
def setup(self, fig, outfile, dpi=None):
|
| 487 |
+
super().setup(fig, outfile, dpi=dpi)
|
| 488 |
+
self._frames = []
|
| 489 |
+
|
| 490 |
+
def grab_frame(self, **savefig_kwargs):
|
| 491 |
+
_validate_grabframe_kwargs(savefig_kwargs)
|
| 492 |
+
buf = BytesIO()
|
| 493 |
+
self.fig.savefig(
|
| 494 |
+
buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
|
| 495 |
+
im = Image.frombuffer(
|
| 496 |
+
"RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)
|
| 497 |
+
if im.getextrema()[3][0] < 255:
|
| 498 |
+
# This frame has transparency, so we'll just add it as is.
|
| 499 |
+
self._frame.append(im)
|
| 500 |
+
else:
|
| 501 |
+
# Without transparency, we switch to RGB mode, which converts to P mode a
|
| 502 |
+
# little better if needed (specifically, this helps with GIF output.)
|
| 503 |
+
self._frames.append(im.convert("RGB"))
|
| 504 |
+
|
| 505 |
+
def finish(self):
|
| 506 |
+
self._frames[0].save(
|
| 507 |
+
self.outfile, save_all=True, append_images=self._frames[1:],
|
| 508 |
+
duration=int(1000 / self.fps), loop=0)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# Base class of ffmpeg information. Has the config keys and the common set
|
| 512 |
+
# of arguments that controls the *output* side of things.
|
| 513 |
+
class FFMpegBase:
|
| 514 |
+
"""
|
| 515 |
+
Mixin class for FFMpeg output.
|
| 516 |
+
|
| 517 |
+
This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter`
|
| 518 |
+
classes.
|
| 519 |
+
"""
|
| 520 |
+
|
| 521 |
+
_exec_key = 'animation.ffmpeg_path'
|
| 522 |
+
_args_key = 'animation.ffmpeg_args'
|
| 523 |
+
|
| 524 |
+
def _supports_transparency(self):
|
| 525 |
+
suffix = Path(self.outfile).suffix
|
| 526 |
+
if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
|
| 527 |
+
return True
|
| 528 |
+
# This list was found by going through `ffmpeg -codecs` for video encoders,
|
| 529 |
+
# running them with _support_transparency() forced to True, and checking that
|
| 530 |
+
# the "Pixel format" in Kdenlive included alpha. Note this is not a guarantee
|
| 531 |
+
# that transparency will work; you may also need to pass `-pix_fmt`, but we
|
| 532 |
+
# trust the user has done so if they are asking for these formats.
|
| 533 |
+
return self.codec in {
|
| 534 |
+
'apng', 'avrp', 'bmp', 'cfhd', 'dpx', 'ffv1', 'ffvhuff', 'gif', 'huffyuv',
|
| 535 |
+
'jpeg2000', 'ljpeg', 'png', 'prores', 'prores_aw', 'prores_ks', 'qtrle',
|
| 536 |
+
'rawvideo', 'targa', 'tiff', 'utvideo', 'v408', }
|
| 537 |
+
|
| 538 |
+
@property
|
| 539 |
+
def output_args(self):
|
| 540 |
+
args = []
|
| 541 |
+
suffix = Path(self.outfile).suffix
|
| 542 |
+
if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
|
| 543 |
+
self.codec = suffix[1:]
|
| 544 |
+
else:
|
| 545 |
+
args.extend(['-vcodec', self.codec])
|
| 546 |
+
extra_args = (self.extra_args if self.extra_args is not None
|
| 547 |
+
else mpl.rcParams[self._args_key])
|
| 548 |
+
# For h264, the default format is yuv444p, which is not compatible
|
| 549 |
+
# with quicktime (and others). Specifying yuv420p fixes playback on
|
| 550 |
+
# iOS, as well as HTML5 video in firefox and safari (on both Windows and
|
| 551 |
+
# macOS). Also fixes internet explorer. This is as of 2015/10/29.
|
| 552 |
+
if self.codec == 'h264' and '-pix_fmt' not in extra_args:
|
| 553 |
+
args.extend(['-pix_fmt', 'yuv420p'])
|
| 554 |
+
# For GIF, we're telling FFmpeg to split the video stream, to generate
|
| 555 |
+
# a palette, and then use it for encoding.
|
| 556 |
+
elif self.codec == 'gif' and '-filter_complex' not in extra_args:
|
| 557 |
+
args.extend(['-filter_complex',
|
| 558 |
+
'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
|
| 559 |
+
# For AVIF, we're telling FFmpeg to split the video stream, extract the alpha,
|
| 560 |
+
# in order to place it in a secondary stream, as needed by AVIF-in-FFmpeg.
|
| 561 |
+
elif self.codec == 'avif' and '-filter_complex' not in extra_args:
|
| 562 |
+
args.extend(['-filter_complex',
|
| 563 |
+
'split [rgb][rgba]; [rgba] alphaextract [alpha]',
|
| 564 |
+
'-map', '[rgb]', '-map', '[alpha]'])
|
| 565 |
+
if self.bitrate > 0:
|
| 566 |
+
args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
|
| 567 |
+
for k, v in self.metadata.items():
|
| 568 |
+
args.extend(['-metadata', f'{k}={v}'])
|
| 569 |
+
args.extend(extra_args)
|
| 570 |
+
|
| 571 |
+
return args + ['-y', self.outfile]
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
# Combine FFMpeg options with pipe-based writing
|
| 575 |
+
@writers.register('ffmpeg')
|
| 576 |
+
class FFMpegWriter(FFMpegBase, MovieWriter):
|
| 577 |
+
"""
|
| 578 |
+
Pipe-based ffmpeg writer.
|
| 579 |
+
|
| 580 |
+
Frames are streamed directly to ffmpeg via a pipe and written in a single pass.
|
| 581 |
+
|
| 582 |
+
This effectively works as a slideshow input to ffmpeg with the fps passed as
|
| 583 |
+
``-framerate``, so see also `their notes on frame rates`_ for further details.
|
| 584 |
+
|
| 585 |
+
.. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
|
| 586 |
+
"""
|
| 587 |
+
def _args(self):
|
| 588 |
+
# Returns the command line parameters for subprocess to use
|
| 589 |
+
# ffmpeg to create a movie using a pipe.
|
| 590 |
+
args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
|
| 591 |
+
'-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
|
| 592 |
+
'-framerate', str(self.fps)]
|
| 593 |
+
# Logging is quieted because subprocess.PIPE has limited buffer size.
|
| 594 |
+
# If you have a lot of frames in your animation and set logging to
|
| 595 |
+
# DEBUG, you will have a buffer overrun.
|
| 596 |
+
if _log.getEffectiveLevel() > logging.DEBUG:
|
| 597 |
+
args += ['-loglevel', 'error']
|
| 598 |
+
args += ['-i', 'pipe:'] + self.output_args
|
| 599 |
+
return args
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# Combine FFMpeg options with temp file-based writing
|
| 603 |
+
@writers.register('ffmpeg_file')
|
| 604 |
+
class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
|
| 605 |
+
"""
|
| 606 |
+
File-based ffmpeg writer.
|
| 607 |
+
|
| 608 |
+
Frames are written to temporary files on disk and then stitched together at the end.
|
| 609 |
+
|
| 610 |
+
This effectively works as a slideshow input to ffmpeg with the fps passed as
|
| 611 |
+
``-framerate``, so see also `their notes on frame rates`_ for further details.
|
| 612 |
+
|
| 613 |
+
.. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
|
| 614 |
+
"""
|
| 615 |
+
supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
|
| 616 |
+
|
| 617 |
+
def _args(self):
|
| 618 |
+
# Returns the command line parameters for subprocess to use
|
| 619 |
+
# ffmpeg to create a movie using a collection of temp images
|
| 620 |
+
args = []
|
| 621 |
+
# For raw frames, we need to explicitly tell ffmpeg the metadata.
|
| 622 |
+
if self.frame_format in {'raw', 'rgba'}:
|
| 623 |
+
args += [
|
| 624 |
+
'-f', 'image2', '-vcodec', 'rawvideo',
|
| 625 |
+
'-video_size', '%dx%d' % self.frame_size,
|
| 626 |
+
'-pixel_format', 'rgba',
|
| 627 |
+
]
|
| 628 |
+
args += ['-framerate', str(self.fps), '-i', self._base_temp_name()]
|
| 629 |
+
if not self._tmpdir:
|
| 630 |
+
args += ['-frames:v', str(self._frame_counter)]
|
| 631 |
+
# Logging is quieted because subprocess.PIPE has limited buffer size.
|
| 632 |
+
# If you have a lot of frames in your animation and set logging to
|
| 633 |
+
# DEBUG, you will have a buffer overrun.
|
| 634 |
+
if _log.getEffectiveLevel() > logging.DEBUG:
|
| 635 |
+
args += ['-loglevel', 'error']
|
| 636 |
+
return [self.bin_path(), *args, *self.output_args]
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
# Base class for animated GIFs with ImageMagick
|
| 640 |
+
class ImageMagickBase:
|
| 641 |
+
"""
|
| 642 |
+
Mixin class for ImageMagick output.
|
| 643 |
+
|
| 644 |
+
This is a base class for the concrete `ImageMagickWriter` and
|
| 645 |
+
`ImageMagickFileWriter` classes, which define an ``input_names`` attribute
|
| 646 |
+
(or property) specifying the input names passed to ImageMagick.
|
| 647 |
+
"""
|
| 648 |
+
|
| 649 |
+
_exec_key = 'animation.convert_path'
|
| 650 |
+
_args_key = 'animation.convert_args'
|
| 651 |
+
|
| 652 |
+
def _supports_transparency(self):
|
| 653 |
+
suffix = Path(self.outfile).suffix
|
| 654 |
+
return suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}
|
| 655 |
+
|
| 656 |
+
def _args(self):
|
| 657 |
+
# ImageMagick does not recognize "raw".
|
| 658 |
+
fmt = "rgba" if self.frame_format == "raw" else self.frame_format
|
| 659 |
+
extra_args = (self.extra_args if self.extra_args is not None
|
| 660 |
+
else mpl.rcParams[self._args_key])
|
| 661 |
+
return [
|
| 662 |
+
self.bin_path(),
|
| 663 |
+
"-size", "%ix%i" % self.frame_size,
|
| 664 |
+
"-depth", "8",
|
| 665 |
+
"-delay", str(100 / self.fps),
|
| 666 |
+
"-loop", "0",
|
| 667 |
+
f"{fmt}:{self.input_names}",
|
| 668 |
+
*extra_args,
|
| 669 |
+
self.outfile,
|
| 670 |
+
]
|
| 671 |
+
|
| 672 |
+
@classmethod
|
| 673 |
+
def bin_path(cls):
|
| 674 |
+
binpath = super().bin_path()
|
| 675 |
+
if binpath == 'convert':
|
| 676 |
+
binpath = mpl._get_executable_info('magick').executable
|
| 677 |
+
return binpath
|
| 678 |
+
|
| 679 |
+
@classmethod
|
| 680 |
+
def isAvailable(cls):
|
| 681 |
+
try:
|
| 682 |
+
return super().isAvailable()
|
| 683 |
+
except mpl.ExecutableNotFoundError as _enf:
|
| 684 |
+
# May be raised by get_executable_info.
|
| 685 |
+
_log.debug('ImageMagick unavailable due to: %s', _enf)
|
| 686 |
+
return False
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
# Combine ImageMagick options with pipe-based writing
|
| 690 |
+
@writers.register('imagemagick')
|
| 691 |
+
class ImageMagickWriter(ImageMagickBase, MovieWriter):
|
| 692 |
+
"""
|
| 693 |
+
Pipe-based animated gif writer.
|
| 694 |
+
|
| 695 |
+
Frames are streamed directly to ImageMagick via a pipe and written
|
| 696 |
+
in a single pass.
|
| 697 |
+
"""
|
| 698 |
+
|
| 699 |
+
input_names = "-" # stdin
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
# Combine ImageMagick options with temp file-based writing
|
| 703 |
+
@writers.register('imagemagick_file')
|
| 704 |
+
class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
|
| 705 |
+
"""
|
| 706 |
+
File-based animated gif writer.
|
| 707 |
+
|
| 708 |
+
Frames are written to temporary files on disk and then stitched
|
| 709 |
+
together at the end.
|
| 710 |
+
"""
|
| 711 |
+
|
| 712 |
+
supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
|
| 713 |
+
input_names = property(
|
| 714 |
+
lambda self: f'{self.temp_prefix}*.{self.frame_format}')
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
# Taken directly from jakevdp's JSAnimation package at
|
| 718 |
+
# http://github.com/jakevdp/JSAnimation
|
| 719 |
+
def _included_frames(frame_count, frame_format, frame_dir):
|
| 720 |
+
return INCLUDED_FRAMES.format(Nframes=frame_count,
|
| 721 |
+
frame_dir=frame_dir,
|
| 722 |
+
frame_format=frame_format)
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _embedded_frames(frame_list, frame_format):
|
| 726 |
+
"""frame_list should be a list of base64-encoded png files"""
|
| 727 |
+
if frame_format == 'svg':
|
| 728 |
+
# Fix MIME type for svg
|
| 729 |
+
frame_format = 'svg+xml'
|
| 730 |
+
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
|
| 731 |
+
return "\n" + "".join(
|
| 732 |
+
template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
|
| 733 |
+
for i, frame_data in enumerate(frame_list))
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
@writers.register('html')
|
| 737 |
+
class HTMLWriter(FileMovieWriter):
|
| 738 |
+
"""Writer for JavaScript-based HTML movies."""
|
| 739 |
+
|
| 740 |
+
supported_formats = ['png', 'jpeg', 'tiff', 'svg']
|
| 741 |
+
|
| 742 |
+
@classmethod
|
| 743 |
+
def isAvailable(cls):
|
| 744 |
+
return True
|
| 745 |
+
|
| 746 |
+
def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
|
| 747 |
+
metadata=None, embed_frames=False, default_mode='loop',
|
| 748 |
+
embed_limit=None):
|
| 749 |
+
|
| 750 |
+
if extra_args:
|
| 751 |
+
_log.warning("HTMLWriter ignores 'extra_args'")
|
| 752 |
+
extra_args = () # Don't lookup nonexistent rcParam[args_key].
|
| 753 |
+
self.embed_frames = embed_frames
|
| 754 |
+
self.default_mode = default_mode.lower()
|
| 755 |
+
_api.check_in_list(['loop', 'once', 'reflect'],
|
| 756 |
+
default_mode=self.default_mode)
|
| 757 |
+
|
| 758 |
+
# Save embed limit, which is given in MB
|
| 759 |
+
self._bytes_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
|
| 760 |
+
# Convert from MB to bytes
|
| 761 |
+
self._bytes_limit *= 1024 * 1024
|
| 762 |
+
|
| 763 |
+
super().__init__(fps, codec, bitrate, extra_args, metadata)
|
| 764 |
+
|
| 765 |
+
def setup(self, fig, outfile, dpi=None, frame_dir=None):
|
| 766 |
+
outfile = Path(outfile)
|
| 767 |
+
_api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
|
| 768 |
+
|
| 769 |
+
self._saved_frames = []
|
| 770 |
+
self._total_bytes = 0
|
| 771 |
+
self._hit_limit = False
|
| 772 |
+
|
| 773 |
+
if not self.embed_frames:
|
| 774 |
+
if frame_dir is None:
|
| 775 |
+
frame_dir = outfile.with_name(outfile.stem + '_frames')
|
| 776 |
+
frame_dir.mkdir(parents=True, exist_ok=True)
|
| 777 |
+
frame_prefix = frame_dir / 'frame'
|
| 778 |
+
else:
|
| 779 |
+
frame_prefix = None
|
| 780 |
+
|
| 781 |
+
super().setup(fig, outfile, dpi, frame_prefix)
|
| 782 |
+
self._clear_temp = False
|
| 783 |
+
|
| 784 |
+
def grab_frame(self, **savefig_kwargs):
|
| 785 |
+
_validate_grabframe_kwargs(savefig_kwargs)
|
| 786 |
+
if self.embed_frames:
|
| 787 |
+
# Just stop processing if we hit the limit
|
| 788 |
+
if self._hit_limit:
|
| 789 |
+
return
|
| 790 |
+
f = BytesIO()
|
| 791 |
+
self.fig.savefig(f, format=self.frame_format,
|
| 792 |
+
dpi=self.dpi, **savefig_kwargs)
|
| 793 |
+
imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
|
| 794 |
+
self._total_bytes += len(imgdata64)
|
| 795 |
+
if self._total_bytes >= self._bytes_limit:
|
| 796 |
+
_log.warning(
|
| 797 |
+
"Animation size has reached %s bytes, exceeding the limit "
|
| 798 |
+
"of %s. If you're sure you want a larger animation "
|
| 799 |
+
"embedded, set the animation.embed_limit rc parameter to "
|
| 800 |
+
"a larger value (in MB). This and further frames will be "
|
| 801 |
+
"dropped.", self._total_bytes, self._bytes_limit)
|
| 802 |
+
self._hit_limit = True
|
| 803 |
+
else:
|
| 804 |
+
self._saved_frames.append(imgdata64)
|
| 805 |
+
else:
|
| 806 |
+
return super().grab_frame(**savefig_kwargs)
|
| 807 |
+
|
| 808 |
+
def finish(self):
|
| 809 |
+
# save the frames to an html file
|
| 810 |
+
if self.embed_frames:
|
| 811 |
+
fill_frames = _embedded_frames(self._saved_frames,
|
| 812 |
+
self.frame_format)
|
| 813 |
+
frame_count = len(self._saved_frames)
|
| 814 |
+
else:
|
| 815 |
+
# temp names is filled by FileMovieWriter
|
| 816 |
+
frame_count = len(self._temp_paths)
|
| 817 |
+
fill_frames = _included_frames(
|
| 818 |
+
frame_count, self.frame_format,
|
| 819 |
+
self._temp_paths[0].parent.relative_to(self.outfile.parent))
|
| 820 |
+
mode_dict = dict(once_checked='',
|
| 821 |
+
loop_checked='',
|
| 822 |
+
reflect_checked='')
|
| 823 |
+
mode_dict[self.default_mode + '_checked'] = 'checked'
|
| 824 |
+
|
| 825 |
+
interval = 1000 // self.fps
|
| 826 |
+
|
| 827 |
+
with open(self.outfile, 'w') as of:
|
| 828 |
+
of.write(JS_INCLUDE + STYLE_INCLUDE)
|
| 829 |
+
of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
|
| 830 |
+
Nframes=frame_count,
|
| 831 |
+
fill_frames=fill_frames,
|
| 832 |
+
interval=interval,
|
| 833 |
+
**mode_dict))
|
| 834 |
+
|
| 835 |
+
# Duplicate the temporary file clean up logic from
|
| 836 |
+
# FileMovieWriter.finish. We cannot call the inherited version of
|
| 837 |
+
# finish because it assumes that there is a subprocess that we either
|
| 838 |
+
# need to call to merge many frames together or that there is a
|
| 839 |
+
# subprocess call that we need to clean up.
|
| 840 |
+
if self._tmpdir:
|
| 841 |
+
_log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
|
| 842 |
+
self._tmpdir.cleanup()
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
class Animation:
|
| 846 |
+
"""
|
| 847 |
+
A base class for Animations.
|
| 848 |
+
|
| 849 |
+
This class is not usable as is, and should be subclassed to provide needed
|
| 850 |
+
behavior.
|
| 851 |
+
|
| 852 |
+
.. note::
|
| 853 |
+
|
| 854 |
+
You must store the created Animation in a variable that lives as long
|
| 855 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 856 |
+
garbage-collected and the animation stops.
|
| 857 |
+
|
| 858 |
+
Parameters
|
| 859 |
+
----------
|
| 860 |
+
fig : `~matplotlib.figure.Figure`
|
| 861 |
+
The figure object used to get needed events, such as draw or resize.
|
| 862 |
+
|
| 863 |
+
event_source : object, optional
|
| 864 |
+
A class that can run a callback when desired events
|
| 865 |
+
are generated, as well as be stopped and started.
|
| 866 |
+
|
| 867 |
+
Examples include timers (see `TimedAnimation`) and file
|
| 868 |
+
system notifications.
|
| 869 |
+
|
| 870 |
+
blit : bool, default: False
|
| 871 |
+
Whether blitting is used to optimize drawing. If the backend does not
|
| 872 |
+
support blitting, then this parameter has no effect.
|
| 873 |
+
|
| 874 |
+
See Also
|
| 875 |
+
--------
|
| 876 |
+
FuncAnimation, ArtistAnimation
|
| 877 |
+
"""
|
| 878 |
+
|
| 879 |
+
def __init__(self, fig, event_source=None, blit=False):
|
| 880 |
+
self._draw_was_started = False
|
| 881 |
+
|
| 882 |
+
self._fig = fig
|
| 883 |
+
# Disables blitting for backends that don't support it. This
|
| 884 |
+
# allows users to request it if available, but still have a
|
| 885 |
+
# fallback that works if it is not.
|
| 886 |
+
self._blit = blit and fig.canvas.supports_blit
|
| 887 |
+
|
| 888 |
+
# These are the basics of the animation. The frame sequence represents
|
| 889 |
+
# information for each frame of the animation and depends on how the
|
| 890 |
+
# drawing is handled by the subclasses. The event source fires events
|
| 891 |
+
# that cause the frame sequence to be iterated.
|
| 892 |
+
self.frame_seq = self.new_frame_seq()
|
| 893 |
+
self.event_source = event_source
|
| 894 |
+
|
| 895 |
+
# Instead of starting the event source now, we connect to the figure's
|
| 896 |
+
# draw_event, so that we only start once the figure has been drawn.
|
| 897 |
+
self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
|
| 898 |
+
|
| 899 |
+
# Connect to the figure's close_event so that we don't continue to
|
| 900 |
+
# fire events and try to draw to a deleted figure.
|
| 901 |
+
self._close_id = self._fig.canvas.mpl_connect('close_event',
|
| 902 |
+
self._stop)
|
| 903 |
+
if self._blit:
|
| 904 |
+
self._setup_blit()
|
| 905 |
+
|
| 906 |
+
def __del__(self):
|
| 907 |
+
if not getattr(self, '_draw_was_started', True):
|
| 908 |
+
warnings.warn(
|
| 909 |
+
'Animation was deleted without rendering anything. This is '
|
| 910 |
+
'most likely not intended. To prevent deletion, assign the '
|
| 911 |
+
'Animation to a variable, e.g. `anim`, that exists until you '
|
| 912 |
+
'output the Animation using `plt.show()` or '
|
| 913 |
+
'`anim.save()`.'
|
| 914 |
+
)
|
| 915 |
+
|
| 916 |
+
def _start(self, *args):
|
| 917 |
+
"""
|
| 918 |
+
Starts interactive animation. Adds the draw frame command to the GUI
|
| 919 |
+
handler, calls show to start the event loop.
|
| 920 |
+
"""
|
| 921 |
+
# Do not start the event source if saving() it.
|
| 922 |
+
if self._fig.canvas.is_saving():
|
| 923 |
+
return
|
| 924 |
+
# First disconnect our draw event handler
|
| 925 |
+
self._fig.canvas.mpl_disconnect(self._first_draw_id)
|
| 926 |
+
|
| 927 |
+
# Now do any initial draw
|
| 928 |
+
self._init_draw()
|
| 929 |
+
|
| 930 |
+
# Add our callback for stepping the animation and
|
| 931 |
+
# actually start the event_source.
|
| 932 |
+
self.event_source.add_callback(self._step)
|
| 933 |
+
self.event_source.start()
|
| 934 |
+
|
| 935 |
+
def _stop(self, *args):
|
| 936 |
+
# On stop we disconnect all of our events.
|
| 937 |
+
if self._blit:
|
| 938 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 939 |
+
self._fig.canvas.mpl_disconnect(self._close_id)
|
| 940 |
+
self.event_source.remove_callback(self._step)
|
| 941 |
+
self.event_source = None
|
| 942 |
+
|
| 943 |
+
def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
|
| 944 |
+
bitrate=None, extra_args=None, metadata=None, extra_anim=None,
|
| 945 |
+
savefig_kwargs=None, *, progress_callback=None):
|
| 946 |
+
"""
|
| 947 |
+
Save the animation as a movie file by drawing every frame.
|
| 948 |
+
|
| 949 |
+
Parameters
|
| 950 |
+
----------
|
| 951 |
+
filename : str
|
| 952 |
+
The output filename, e.g., :file:`mymovie.mp4`.
|
| 953 |
+
|
| 954 |
+
writer : `MovieWriter` or str, default: :rc:`animation.writer`
|
| 955 |
+
A `MovieWriter` instance to use or a key that identifies a
|
| 956 |
+
class to use, such as 'ffmpeg'.
|
| 957 |
+
|
| 958 |
+
fps : int, optional
|
| 959 |
+
Movie frame rate (per second). If not set, the frame rate from the
|
| 960 |
+
animation's frame interval.
|
| 961 |
+
|
| 962 |
+
dpi : float, default: :rc:`savefig.dpi`
|
| 963 |
+
Controls the dots per inch for the movie frames. Together with
|
| 964 |
+
the figure's size in inches, this controls the size of the movie.
|
| 965 |
+
|
| 966 |
+
codec : str, default: :rc:`animation.codec`.
|
| 967 |
+
The video codec to use. Not all codecs are supported by a given
|
| 968 |
+
`MovieWriter`.
|
| 969 |
+
|
| 970 |
+
bitrate : int, default: :rc:`animation.bitrate`
|
| 971 |
+
The bitrate of the movie, in kilobits per second. Higher values
|
| 972 |
+
means higher quality movies, but increase the file size. A value
|
| 973 |
+
of -1 lets the underlying movie encoder select the bitrate.
|
| 974 |
+
|
| 975 |
+
extra_args : list of str or None, optional
|
| 976 |
+
Extra command-line arguments passed to the underlying movie encoder. These
|
| 977 |
+
arguments are passed last to the encoder, just before the output filename.
|
| 978 |
+
The default, None, means to use :rc:`animation.[name-of-encoder]_args` for
|
| 979 |
+
the builtin writers.
|
| 980 |
+
|
| 981 |
+
metadata : dict[str, str], default: {}
|
| 982 |
+
Dictionary of keys and values for metadata to include in
|
| 983 |
+
the output file. Some keys that may be of use include:
|
| 984 |
+
title, artist, genre, subject, copyright, srcform, comment.
|
| 985 |
+
|
| 986 |
+
extra_anim : list, default: []
|
| 987 |
+
Additional `Animation` objects that should be included
|
| 988 |
+
in the saved movie file. These need to be from the same
|
| 989 |
+
`.Figure` instance. Also, animation frames will
|
| 990 |
+
just be simply combined, so there should be a 1:1 correspondence
|
| 991 |
+
between the frames from the different animations.
|
| 992 |
+
|
| 993 |
+
savefig_kwargs : dict, default: {}
|
| 994 |
+
Keyword arguments passed to each `~.Figure.savefig` call used to
|
| 995 |
+
save the individual frames.
|
| 996 |
+
|
| 997 |
+
progress_callback : function, optional
|
| 998 |
+
A callback function that will be called for every frame to notify
|
| 999 |
+
the saving progress. It must have the signature ::
|
| 1000 |
+
|
| 1001 |
+
def func(current_frame: int, total_frames: int) -> Any
|
| 1002 |
+
|
| 1003 |
+
where *current_frame* is the current frame number and *total_frames* is the
|
| 1004 |
+
total number of frames to be saved. *total_frames* is set to None, if the
|
| 1005 |
+
total number of frames cannot be determined. Return values may exist but are
|
| 1006 |
+
ignored.
|
| 1007 |
+
|
| 1008 |
+
Example code to write the progress to stdout::
|
| 1009 |
+
|
| 1010 |
+
progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
|
| 1011 |
+
|
| 1012 |
+
Notes
|
| 1013 |
+
-----
|
| 1014 |
+
*fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
|
| 1015 |
+
construct a `.MovieWriter` instance and can only be passed if
|
| 1016 |
+
*writer* is a string. If they are passed as non-*None* and *writer*
|
| 1017 |
+
is a `.MovieWriter`, a `RuntimeError` will be raised.
|
| 1018 |
+
"""
|
| 1019 |
+
|
| 1020 |
+
all_anim = [self]
|
| 1021 |
+
if extra_anim is not None:
|
| 1022 |
+
all_anim.extend(anim for anim in extra_anim
|
| 1023 |
+
if anim._fig is self._fig)
|
| 1024 |
+
|
| 1025 |
+
# Disable "Animation was deleted without rendering" warning.
|
| 1026 |
+
for anim in all_anim:
|
| 1027 |
+
anim._draw_was_started = True
|
| 1028 |
+
|
| 1029 |
+
if writer is None:
|
| 1030 |
+
writer = mpl.rcParams['animation.writer']
|
| 1031 |
+
elif (not isinstance(writer, str) and
|
| 1032 |
+
any(arg is not None
|
| 1033 |
+
for arg in (fps, codec, bitrate, extra_args, metadata))):
|
| 1034 |
+
raise RuntimeError('Passing in values for arguments '
|
| 1035 |
+
'fps, codec, bitrate, extra_args, or metadata '
|
| 1036 |
+
'is not supported when writer is an existing '
|
| 1037 |
+
'MovieWriter instance. These should instead be '
|
| 1038 |
+
'passed as arguments when creating the '
|
| 1039 |
+
'MovieWriter instance.')
|
| 1040 |
+
|
| 1041 |
+
if savefig_kwargs is None:
|
| 1042 |
+
savefig_kwargs = {}
|
| 1043 |
+
else:
|
| 1044 |
+
# we are going to mutate this below
|
| 1045 |
+
savefig_kwargs = dict(savefig_kwargs)
|
| 1046 |
+
|
| 1047 |
+
if fps is None and hasattr(self, '_interval'):
|
| 1048 |
+
# Convert interval in ms to frames per second
|
| 1049 |
+
fps = 1000. / self._interval
|
| 1050 |
+
|
| 1051 |
+
# Reuse the savefig DPI for ours if none is given.
|
| 1052 |
+
dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
|
| 1053 |
+
if dpi == 'figure':
|
| 1054 |
+
dpi = self._fig.dpi
|
| 1055 |
+
|
| 1056 |
+
writer_kwargs = {}
|
| 1057 |
+
if codec is not None:
|
| 1058 |
+
writer_kwargs['codec'] = codec
|
| 1059 |
+
if bitrate is not None:
|
| 1060 |
+
writer_kwargs['bitrate'] = bitrate
|
| 1061 |
+
if extra_args is not None:
|
| 1062 |
+
writer_kwargs['extra_args'] = extra_args
|
| 1063 |
+
if metadata is not None:
|
| 1064 |
+
writer_kwargs['metadata'] = metadata
|
| 1065 |
+
|
| 1066 |
+
# If we have the name of a writer, instantiate an instance of the
|
| 1067 |
+
# registered class.
|
| 1068 |
+
if isinstance(writer, str):
|
| 1069 |
+
try:
|
| 1070 |
+
writer_cls = writers[writer]
|
| 1071 |
+
except RuntimeError: # Raised if not available.
|
| 1072 |
+
writer_cls = PillowWriter # Always available.
|
| 1073 |
+
_log.warning("MovieWriter %s unavailable; using Pillow "
|
| 1074 |
+
"instead.", writer)
|
| 1075 |
+
writer = writer_cls(fps, **writer_kwargs)
|
| 1076 |
+
_log.info('Animation.save using %s', type(writer))
|
| 1077 |
+
|
| 1078 |
+
if 'bbox_inches' in savefig_kwargs:
|
| 1079 |
+
_log.warning("Warning: discarding the 'bbox_inches' argument in "
|
| 1080 |
+
"'savefig_kwargs' as it may cause frame size "
|
| 1081 |
+
"to vary, which is inappropriate for animation.")
|
| 1082 |
+
savefig_kwargs.pop('bbox_inches')
|
| 1083 |
+
|
| 1084 |
+
# Create a new sequence of frames for saved data. This is different
|
| 1085 |
+
# from new_frame_seq() to give the ability to save 'live' generated
|
| 1086 |
+
# frame information to be saved later.
|
| 1087 |
+
# TODO: Right now, after closing the figure, saving a movie won't work
|
| 1088 |
+
# since GUI widgets are gone. Either need to remove extra code to
|
| 1089 |
+
# allow for this non-existent use case or find a way to make it work.
|
| 1090 |
+
|
| 1091 |
+
def _pre_composite_to_white(color):
|
| 1092 |
+
r, g, b, a = mcolors.to_rgba(color)
|
| 1093 |
+
return a * np.array([r, g, b]) + 1 - a
|
| 1094 |
+
|
| 1095 |
+
# canvas._is_saving = True makes the draw_event animation-starting
|
| 1096 |
+
# callback a no-op; canvas.manager = None prevents resizing the GUI
|
| 1097 |
+
# widget (both are likewise done in savefig()).
|
| 1098 |
+
with (writer.saving(self._fig, filename, dpi),
|
| 1099 |
+
cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None)):
|
| 1100 |
+
if not writer._supports_transparency():
|
| 1101 |
+
facecolor = savefig_kwargs.get('facecolor',
|
| 1102 |
+
mpl.rcParams['savefig.facecolor'])
|
| 1103 |
+
if facecolor == 'auto':
|
| 1104 |
+
facecolor = self._fig.get_facecolor()
|
| 1105 |
+
savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor)
|
| 1106 |
+
savefig_kwargs['transparent'] = False # just to be safe!
|
| 1107 |
+
|
| 1108 |
+
for anim in all_anim:
|
| 1109 |
+
anim._init_draw() # Clear the initial frame
|
| 1110 |
+
frame_number = 0
|
| 1111 |
+
# TODO: Currently only FuncAnimation has a save_count
|
| 1112 |
+
# attribute. Can we generalize this to all Animations?
|
| 1113 |
+
save_count_list = [getattr(a, '_save_count', None)
|
| 1114 |
+
for a in all_anim]
|
| 1115 |
+
if None in save_count_list:
|
| 1116 |
+
total_frames = None
|
| 1117 |
+
else:
|
| 1118 |
+
total_frames = sum(save_count_list)
|
| 1119 |
+
for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
|
| 1120 |
+
for anim, d in zip(all_anim, data):
|
| 1121 |
+
# TODO: See if turning off blit is really necessary
|
| 1122 |
+
anim._draw_next_frame(d, blit=False)
|
| 1123 |
+
if progress_callback is not None:
|
| 1124 |
+
progress_callback(frame_number, total_frames)
|
| 1125 |
+
frame_number += 1
|
| 1126 |
+
writer.grab_frame(**savefig_kwargs)
|
| 1127 |
+
|
| 1128 |
+
def _step(self, *args):
|
| 1129 |
+
"""
|
| 1130 |
+
Handler for getting events. By default, gets the next frame in the
|
| 1131 |
+
sequence and hands the data off to be drawn.
|
| 1132 |
+
"""
|
| 1133 |
+
# Returns True to indicate that the event source should continue to
|
| 1134 |
+
# call _step, until the frame sequence reaches the end of iteration,
|
| 1135 |
+
# at which point False will be returned.
|
| 1136 |
+
try:
|
| 1137 |
+
framedata = next(self.frame_seq)
|
| 1138 |
+
self._draw_next_frame(framedata, self._blit)
|
| 1139 |
+
return True
|
| 1140 |
+
except StopIteration:
|
| 1141 |
+
return False
|
| 1142 |
+
|
| 1143 |
+
def new_frame_seq(self):
|
| 1144 |
+
"""Return a new sequence of frame information."""
|
| 1145 |
+
# Default implementation is just an iterator over self._framedata
|
| 1146 |
+
return iter(self._framedata)
|
| 1147 |
+
|
| 1148 |
+
def new_saved_frame_seq(self):
|
| 1149 |
+
"""Return a new sequence of saved/cached frame information."""
|
| 1150 |
+
# Default is the same as the regular frame sequence
|
| 1151 |
+
return self.new_frame_seq()
|
| 1152 |
+
|
| 1153 |
+
def _draw_next_frame(self, framedata, blit):
|
| 1154 |
+
# Breaks down the drawing of the next frame into steps of pre- and
|
| 1155 |
+
# post- draw, as well as the drawing of the frame itself.
|
| 1156 |
+
self._pre_draw(framedata, blit)
|
| 1157 |
+
self._draw_frame(framedata)
|
| 1158 |
+
self._post_draw(framedata, blit)
|
| 1159 |
+
|
| 1160 |
+
def _init_draw(self):
|
| 1161 |
+
# Initial draw to clear the frame. Also used by the blitting code
|
| 1162 |
+
# when a clean base is required.
|
| 1163 |
+
self._draw_was_started = True
|
| 1164 |
+
|
| 1165 |
+
def _pre_draw(self, framedata, blit):
|
| 1166 |
+
# Perform any cleaning or whatnot before the drawing of the frame.
|
| 1167 |
+
# This default implementation allows blit to clear the frame.
|
| 1168 |
+
if blit:
|
| 1169 |
+
self._blit_clear(self._drawn_artists)
|
| 1170 |
+
|
| 1171 |
+
def _draw_frame(self, framedata):
|
| 1172 |
+
# Performs actual drawing of the frame.
|
| 1173 |
+
raise NotImplementedError('Needs to be implemented by subclasses to'
|
| 1174 |
+
' actually make an animation.')
|
| 1175 |
+
|
| 1176 |
+
def _post_draw(self, framedata, blit):
|
| 1177 |
+
# After the frame is rendered, this handles the actual flushing of
|
| 1178 |
+
# the draw, which can be a direct draw_idle() or make use of the
|
| 1179 |
+
# blitting.
|
| 1180 |
+
if blit and self._drawn_artists:
|
| 1181 |
+
self._blit_draw(self._drawn_artists)
|
| 1182 |
+
else:
|
| 1183 |
+
self._fig.canvas.draw_idle()
|
| 1184 |
+
|
| 1185 |
+
# The rest of the code in this class is to facilitate easy blitting
|
| 1186 |
+
def _blit_draw(self, artists):
|
| 1187 |
+
# Handles blitted drawing, which renders only the artists given instead
|
| 1188 |
+
# of the entire figure.
|
| 1189 |
+
updated_ax = {a.axes for a in artists}
|
| 1190 |
+
# Enumerate artists to cache Axes backgrounds. We do not draw
|
| 1191 |
+
# artists yet to not cache foreground from plots with shared Axes
|
| 1192 |
+
for ax in updated_ax:
|
| 1193 |
+
# If we haven't cached the background for the current view of this
|
| 1194 |
+
# Axes object, do so now. This might not always be reliable, but
|
| 1195 |
+
# it's an attempt to automate the process.
|
| 1196 |
+
cur_view = ax._get_view()
|
| 1197 |
+
view, bg = self._blit_cache.get(ax, (object(), None))
|
| 1198 |
+
if cur_view != view:
|
| 1199 |
+
self._blit_cache[ax] = (
|
| 1200 |
+
cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox))
|
| 1201 |
+
# Make a separate pass to draw foreground.
|
| 1202 |
+
for a in artists:
|
| 1203 |
+
a.axes.draw_artist(a)
|
| 1204 |
+
# After rendering all the needed artists, blit each Axes individually.
|
| 1205 |
+
for ax in updated_ax:
|
| 1206 |
+
ax.figure.canvas.blit(ax.bbox)
|
| 1207 |
+
|
| 1208 |
+
def _blit_clear(self, artists):
|
| 1209 |
+
# Get a list of the Axes that need clearing from the artists that
|
| 1210 |
+
# have been drawn. Grab the appropriate saved background from the
|
| 1211 |
+
# cache and restore.
|
| 1212 |
+
axes = {a.axes for a in artists}
|
| 1213 |
+
for ax in axes:
|
| 1214 |
+
try:
|
| 1215 |
+
view, bg = self._blit_cache[ax]
|
| 1216 |
+
except KeyError:
|
| 1217 |
+
continue
|
| 1218 |
+
if ax._get_view() == view:
|
| 1219 |
+
ax.figure.canvas.restore_region(bg)
|
| 1220 |
+
else:
|
| 1221 |
+
self._blit_cache.pop(ax)
|
| 1222 |
+
|
| 1223 |
+
def _setup_blit(self):
|
| 1224 |
+
# Setting up the blit requires: a cache of the background for the Axes
|
| 1225 |
+
self._blit_cache = dict()
|
| 1226 |
+
self._drawn_artists = []
|
| 1227 |
+
# _post_draw needs to be called first to initialize the renderer
|
| 1228 |
+
self._post_draw(None, self._blit)
|
| 1229 |
+
# Then we need to clear the Frame for the initial draw
|
| 1230 |
+
# This is typically handled in _on_resize because QT and Tk
|
| 1231 |
+
# emit a resize event on launch, but the macosx backend does not,
|
| 1232 |
+
# thus we force it here for everyone for consistency
|
| 1233 |
+
self._init_draw()
|
| 1234 |
+
# Connect to future resize events
|
| 1235 |
+
self._resize_id = self._fig.canvas.mpl_connect('resize_event',
|
| 1236 |
+
self._on_resize)
|
| 1237 |
+
|
| 1238 |
+
def _on_resize(self, event):
|
| 1239 |
+
# On resize, we need to disable the resize event handling so we don't
|
| 1240 |
+
# get too many events. Also stop the animation events, so that
|
| 1241 |
+
# we're paused. Reset the cache and re-init. Set up an event handler
|
| 1242 |
+
# to catch once the draw has actually taken place.
|
| 1243 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 1244 |
+
self.event_source.stop()
|
| 1245 |
+
self._blit_cache.clear()
|
| 1246 |
+
self._init_draw()
|
| 1247 |
+
self._resize_id = self._fig.canvas.mpl_connect('draw_event',
|
| 1248 |
+
self._end_redraw)
|
| 1249 |
+
|
| 1250 |
+
def _end_redraw(self, event):
|
| 1251 |
+
# Now that the redraw has happened, do the post draw flushing and
|
| 1252 |
+
# blit handling. Then re-enable all of the original events.
|
| 1253 |
+
self._post_draw(None, False)
|
| 1254 |
+
self.event_source.start()
|
| 1255 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 1256 |
+
self._resize_id = self._fig.canvas.mpl_connect('resize_event',
|
| 1257 |
+
self._on_resize)
|
| 1258 |
+
|
| 1259 |
+
def to_html5_video(self, embed_limit=None):
|
| 1260 |
+
"""
|
| 1261 |
+
Convert the animation to an HTML5 ``<video>`` tag.
|
| 1262 |
+
|
| 1263 |
+
This saves the animation as an h264 video, encoded in base64
|
| 1264 |
+
directly into the HTML5 video tag. This respects :rc:`animation.writer`
|
| 1265 |
+
and :rc:`animation.bitrate`. This also makes use of the
|
| 1266 |
+
*interval* to control the speed, and uses the *repeat*
|
| 1267 |
+
parameter to decide whether to loop.
|
| 1268 |
+
|
| 1269 |
+
Parameters
|
| 1270 |
+
----------
|
| 1271 |
+
embed_limit : float, optional
|
| 1272 |
+
Limit, in MB, of the returned animation. No animation is created
|
| 1273 |
+
if the limit is exceeded.
|
| 1274 |
+
Defaults to :rc:`animation.embed_limit` = 20.0.
|
| 1275 |
+
|
| 1276 |
+
Returns
|
| 1277 |
+
-------
|
| 1278 |
+
str
|
| 1279 |
+
An HTML5 video tag with the animation embedded as base64 encoded
|
| 1280 |
+
h264 video.
|
| 1281 |
+
If the *embed_limit* is exceeded, this returns the string
|
| 1282 |
+
"Video too large to embed."
|
| 1283 |
+
"""
|
| 1284 |
+
VIDEO_TAG = r'''<video {size} {options}>
|
| 1285 |
+
<source type="video/mp4" src="data:video/mp4;base64,{video}">
|
| 1286 |
+
Your browser does not support the video tag.
|
| 1287 |
+
</video>'''
|
| 1288 |
+
# Cache the rendering of the video as HTML
|
| 1289 |
+
if not hasattr(self, '_base64_video'):
|
| 1290 |
+
# Save embed limit, which is given in MB
|
| 1291 |
+
embed_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
|
| 1292 |
+
|
| 1293 |
+
# Convert from MB to bytes
|
| 1294 |
+
embed_limit *= 1024 * 1024
|
| 1295 |
+
|
| 1296 |
+
# Can't open a NamedTemporaryFile twice on Windows, so use a
|
| 1297 |
+
# TemporaryDirectory instead.
|
| 1298 |
+
with TemporaryDirectory() as tmpdir:
|
| 1299 |
+
path = Path(tmpdir, "temp.m4v")
|
| 1300 |
+
# We create a writer manually so that we can get the
|
| 1301 |
+
# appropriate size for the tag
|
| 1302 |
+
Writer = writers[mpl.rcParams['animation.writer']]
|
| 1303 |
+
writer = Writer(codec='h264',
|
| 1304 |
+
bitrate=mpl.rcParams['animation.bitrate'],
|
| 1305 |
+
fps=1000. / self._interval)
|
| 1306 |
+
self.save(str(path), writer=writer)
|
| 1307 |
+
# Now open and base64 encode.
|
| 1308 |
+
vid64 = base64.encodebytes(path.read_bytes())
|
| 1309 |
+
|
| 1310 |
+
vid_len = len(vid64)
|
| 1311 |
+
if vid_len >= embed_limit:
|
| 1312 |
+
_log.warning(
|
| 1313 |
+
"Animation movie is %s bytes, exceeding the limit of %s. "
|
| 1314 |
+
"If you're sure you want a large animation embedded, set "
|
| 1315 |
+
"the animation.embed_limit rc parameter to a larger value "
|
| 1316 |
+
"(in MB).", vid_len, embed_limit)
|
| 1317 |
+
else:
|
| 1318 |
+
self._base64_video = vid64.decode('ascii')
|
| 1319 |
+
self._video_size = 'width="{}" height="{}"'.format(
|
| 1320 |
+
*writer.frame_size)
|
| 1321 |
+
|
| 1322 |
+
# If we exceeded the size, this attribute won't exist
|
| 1323 |
+
if hasattr(self, '_base64_video'):
|
| 1324 |
+
# Default HTML5 options are to autoplay and display video controls
|
| 1325 |
+
options = ['controls', 'autoplay']
|
| 1326 |
+
|
| 1327 |
+
# If we're set to repeat, make it loop
|
| 1328 |
+
if getattr(self, '_repeat', False):
|
| 1329 |
+
options.append('loop')
|
| 1330 |
+
|
| 1331 |
+
return VIDEO_TAG.format(video=self._base64_video,
|
| 1332 |
+
size=self._video_size,
|
| 1333 |
+
options=' '.join(options))
|
| 1334 |
+
else:
|
| 1335 |
+
return 'Video too large to embed.'
|
| 1336 |
+
|
| 1337 |
+
def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
|
| 1338 |
+
"""
|
| 1339 |
+
Generate HTML representation of the animation.
|
| 1340 |
+
|
| 1341 |
+
Parameters
|
| 1342 |
+
----------
|
| 1343 |
+
fps : int, optional
|
| 1344 |
+
Movie frame rate (per second). If not set, the frame rate from
|
| 1345 |
+
the animation's frame interval.
|
| 1346 |
+
embed_frames : bool, optional
|
| 1347 |
+
default_mode : str, optional
|
| 1348 |
+
What to do when the animation ends. Must be one of ``{'loop',
|
| 1349 |
+
'once', 'reflect'}``. Defaults to ``'loop'`` if the *repeat*
|
| 1350 |
+
parameter is True, otherwise ``'once'``.
|
| 1351 |
+
|
| 1352 |
+
Returns
|
| 1353 |
+
-------
|
| 1354 |
+
str
|
| 1355 |
+
An HTML representation of the animation embedded as a js object as
|
| 1356 |
+
produced with the `.HTMLWriter`.
|
| 1357 |
+
"""
|
| 1358 |
+
if fps is None and hasattr(self, '_interval'):
|
| 1359 |
+
# Convert interval in ms to frames per second
|
| 1360 |
+
fps = 1000 / self._interval
|
| 1361 |
+
|
| 1362 |
+
# If we're not given a default mode, choose one base on the value of
|
| 1363 |
+
# the _repeat attribute
|
| 1364 |
+
if default_mode is None:
|
| 1365 |
+
default_mode = 'loop' if getattr(self, '_repeat',
|
| 1366 |
+
False) else 'once'
|
| 1367 |
+
|
| 1368 |
+
if not hasattr(self, "_html_representation"):
|
| 1369 |
+
# Can't open a NamedTemporaryFile twice on Windows, so use a
|
| 1370 |
+
# TemporaryDirectory instead.
|
| 1371 |
+
with TemporaryDirectory() as tmpdir:
|
| 1372 |
+
path = Path(tmpdir, "temp.html")
|
| 1373 |
+
writer = HTMLWriter(fps=fps,
|
| 1374 |
+
embed_frames=embed_frames,
|
| 1375 |
+
default_mode=default_mode)
|
| 1376 |
+
self.save(str(path), writer=writer)
|
| 1377 |
+
self._html_representation = path.read_text()
|
| 1378 |
+
|
| 1379 |
+
return self._html_representation
|
| 1380 |
+
|
| 1381 |
+
def _repr_html_(self):
|
| 1382 |
+
"""IPython display hook for rendering."""
|
| 1383 |
+
fmt = mpl.rcParams['animation.html']
|
| 1384 |
+
if fmt == 'html5':
|
| 1385 |
+
return self.to_html5_video()
|
| 1386 |
+
elif fmt == 'jshtml':
|
| 1387 |
+
return self.to_jshtml()
|
| 1388 |
+
|
| 1389 |
+
def pause(self):
|
| 1390 |
+
"""Pause the animation."""
|
| 1391 |
+
self.event_source.stop()
|
| 1392 |
+
if self._blit:
|
| 1393 |
+
for artist in self._drawn_artists:
|
| 1394 |
+
artist.set_animated(False)
|
| 1395 |
+
|
| 1396 |
+
def resume(self):
|
| 1397 |
+
"""Resume the animation."""
|
| 1398 |
+
self.event_source.start()
|
| 1399 |
+
if self._blit:
|
| 1400 |
+
for artist in self._drawn_artists:
|
| 1401 |
+
artist.set_animated(True)
|
| 1402 |
+
|
| 1403 |
+
|
| 1404 |
+
class TimedAnimation(Animation):
|
| 1405 |
+
"""
|
| 1406 |
+
`Animation` subclass for time-based animation.
|
| 1407 |
+
|
| 1408 |
+
A new frame is drawn every *interval* milliseconds.
|
| 1409 |
+
|
| 1410 |
+
.. note::
|
| 1411 |
+
|
| 1412 |
+
You must store the created Animation in a variable that lives as long
|
| 1413 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 1414 |
+
garbage-collected and the animation stops.
|
| 1415 |
+
|
| 1416 |
+
Parameters
|
| 1417 |
+
----------
|
| 1418 |
+
fig : `~matplotlib.figure.Figure`
|
| 1419 |
+
The figure object used to get needed events, such as draw or resize.
|
| 1420 |
+
interval : int, default: 200
|
| 1421 |
+
Delay between frames in milliseconds.
|
| 1422 |
+
repeat_delay : int, default: 0
|
| 1423 |
+
The delay in milliseconds between consecutive animation runs, if
|
| 1424 |
+
*repeat* is True.
|
| 1425 |
+
repeat : bool, default: True
|
| 1426 |
+
Whether the animation repeats when the sequence of frames is completed.
|
| 1427 |
+
blit : bool, default: False
|
| 1428 |
+
Whether blitting is used to optimize drawing.
|
| 1429 |
+
"""
|
| 1430 |
+
def __init__(self, fig, interval=200, repeat_delay=0, repeat=True,
|
| 1431 |
+
event_source=None, *args, **kwargs):
|
| 1432 |
+
self._interval = interval
|
| 1433 |
+
# Undocumented support for repeat_delay = None as backcompat.
|
| 1434 |
+
self._repeat_delay = repeat_delay if repeat_delay is not None else 0
|
| 1435 |
+
self._repeat = repeat
|
| 1436 |
+
# If we're not given an event source, create a new timer. This permits
|
| 1437 |
+
# sharing timers between animation objects for syncing animations.
|
| 1438 |
+
if event_source is None:
|
| 1439 |
+
event_source = fig.canvas.new_timer(interval=self._interval)
|
| 1440 |
+
super().__init__(fig, event_source=event_source, *args, **kwargs)
|
| 1441 |
+
|
| 1442 |
+
def _step(self, *args):
|
| 1443 |
+
"""Handler for getting events."""
|
| 1444 |
+
# Extends the _step() method for the Animation class. If
|
| 1445 |
+
# Animation._step signals that it reached the end and we want to
|
| 1446 |
+
# repeat, we refresh the frame sequence and return True. If
|
| 1447 |
+
# _repeat_delay is set, change the event_source's interval to our loop
|
| 1448 |
+
# delay and set the callback to one which will then set the interval
|
| 1449 |
+
# back.
|
| 1450 |
+
still_going = super()._step(*args)
|
| 1451 |
+
if not still_going:
|
| 1452 |
+
if self._repeat:
|
| 1453 |
+
# Restart the draw loop
|
| 1454 |
+
self._init_draw()
|
| 1455 |
+
self.frame_seq = self.new_frame_seq()
|
| 1456 |
+
self.event_source.interval = self._repeat_delay
|
| 1457 |
+
return True
|
| 1458 |
+
else:
|
| 1459 |
+
# We are done with the animation. Call pause to remove
|
| 1460 |
+
# animated flags from artists that were using blitting
|
| 1461 |
+
self.pause()
|
| 1462 |
+
if self._blit:
|
| 1463 |
+
# Remove the resize callback if we were blitting
|
| 1464 |
+
self._fig.canvas.mpl_disconnect(self._resize_id)
|
| 1465 |
+
self._fig.canvas.mpl_disconnect(self._close_id)
|
| 1466 |
+
self.event_source = None
|
| 1467 |
+
return False
|
| 1468 |
+
|
| 1469 |
+
self.event_source.interval = self._interval
|
| 1470 |
+
return True
|
| 1471 |
+
|
| 1472 |
+
|
| 1473 |
+
class ArtistAnimation(TimedAnimation):
|
| 1474 |
+
"""
|
| 1475 |
+
`TimedAnimation` subclass that creates an animation by using a fixed
|
| 1476 |
+
set of `.Artist` objects.
|
| 1477 |
+
|
| 1478 |
+
Before creating an instance, all plotting should have taken place
|
| 1479 |
+
and the relevant artists saved.
|
| 1480 |
+
|
| 1481 |
+
.. note::
|
| 1482 |
+
|
| 1483 |
+
You must store the created Animation in a variable that lives as long
|
| 1484 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 1485 |
+
garbage-collected and the animation stops.
|
| 1486 |
+
|
| 1487 |
+
Parameters
|
| 1488 |
+
----------
|
| 1489 |
+
fig : `~matplotlib.figure.Figure`
|
| 1490 |
+
The figure object used to get needed events, such as draw or resize.
|
| 1491 |
+
artists : list
|
| 1492 |
+
Each list entry is a collection of `.Artist` objects that are made
|
| 1493 |
+
visible on the corresponding frame. Other artists are made invisible.
|
| 1494 |
+
interval : int, default: 200
|
| 1495 |
+
Delay between frames in milliseconds.
|
| 1496 |
+
repeat_delay : int, default: 0
|
| 1497 |
+
The delay in milliseconds between consecutive animation runs, if
|
| 1498 |
+
*repeat* is True.
|
| 1499 |
+
repeat : bool, default: True
|
| 1500 |
+
Whether the animation repeats when the sequence of frames is completed.
|
| 1501 |
+
blit : bool, default: False
|
| 1502 |
+
Whether blitting is used to optimize drawing.
|
| 1503 |
+
"""
|
| 1504 |
+
|
| 1505 |
+
def __init__(self, fig, artists, *args, **kwargs):
|
| 1506 |
+
# Internal list of artists drawn in the most recent frame.
|
| 1507 |
+
self._drawn_artists = []
|
| 1508 |
+
|
| 1509 |
+
# Use the list of artists as the framedata, which will be iterated
|
| 1510 |
+
# over by the machinery.
|
| 1511 |
+
self._framedata = artists
|
| 1512 |
+
super().__init__(fig, *args, **kwargs)
|
| 1513 |
+
|
| 1514 |
+
def _init_draw(self):
|
| 1515 |
+
super()._init_draw()
|
| 1516 |
+
# Make all the artists involved in *any* frame invisible
|
| 1517 |
+
figs = set()
|
| 1518 |
+
for f in self.new_frame_seq():
|
| 1519 |
+
for artist in f:
|
| 1520 |
+
artist.set_visible(False)
|
| 1521 |
+
artist.set_animated(self._blit)
|
| 1522 |
+
# Assemble a list of unique figures that need flushing
|
| 1523 |
+
if artist.get_figure() not in figs:
|
| 1524 |
+
figs.add(artist.get_figure())
|
| 1525 |
+
|
| 1526 |
+
# Flush the needed figures
|
| 1527 |
+
for fig in figs:
|
| 1528 |
+
fig.canvas.draw_idle()
|
| 1529 |
+
|
| 1530 |
+
def _pre_draw(self, framedata, blit):
|
| 1531 |
+
"""Clears artists from the last frame."""
|
| 1532 |
+
if blit:
|
| 1533 |
+
# Let blit handle clearing
|
| 1534 |
+
self._blit_clear(self._drawn_artists)
|
| 1535 |
+
else:
|
| 1536 |
+
# Otherwise, make all the artists from the previous frame invisible
|
| 1537 |
+
for artist in self._drawn_artists:
|
| 1538 |
+
artist.set_visible(False)
|
| 1539 |
+
|
| 1540 |
+
def _draw_frame(self, artists):
|
| 1541 |
+
# Save the artists that were passed in as framedata for the other
|
| 1542 |
+
# steps (esp. blitting) to use.
|
| 1543 |
+
self._drawn_artists = artists
|
| 1544 |
+
|
| 1545 |
+
# Make all the artists from the current frame visible
|
| 1546 |
+
for artist in artists:
|
| 1547 |
+
artist.set_visible(True)
|
| 1548 |
+
|
| 1549 |
+
|
| 1550 |
+
class FuncAnimation(TimedAnimation):
|
| 1551 |
+
"""
|
| 1552 |
+
`TimedAnimation` subclass that makes an animation by repeatedly calling
|
| 1553 |
+
a function *func*.
|
| 1554 |
+
|
| 1555 |
+
.. note::
|
| 1556 |
+
|
| 1557 |
+
You must store the created Animation in a variable that lives as long
|
| 1558 |
+
as the animation should run. Otherwise, the Animation object will be
|
| 1559 |
+
garbage-collected and the animation stops.
|
| 1560 |
+
|
| 1561 |
+
Parameters
|
| 1562 |
+
----------
|
| 1563 |
+
fig : `~matplotlib.figure.Figure`
|
| 1564 |
+
The figure object used to get needed events, such as draw or resize.
|
| 1565 |
+
|
| 1566 |
+
func : callable
|
| 1567 |
+
The function to call at each frame. The first argument will
|
| 1568 |
+
be the next value in *frames*. Any additional positional
|
| 1569 |
+
arguments can be supplied using `functools.partial` or via the *fargs*
|
| 1570 |
+
parameter.
|
| 1571 |
+
|
| 1572 |
+
The required signature is::
|
| 1573 |
+
|
| 1574 |
+
def func(frame, *fargs) -> iterable_of_artists
|
| 1575 |
+
|
| 1576 |
+
It is often more convenient to provide the arguments using
|
| 1577 |
+
`functools.partial`. In this way it is also possible to pass keyword
|
| 1578 |
+
arguments. To pass a function with both positional and keyword
|
| 1579 |
+
arguments, set all arguments as keyword arguments, just leaving the
|
| 1580 |
+
*frame* argument unset::
|
| 1581 |
+
|
| 1582 |
+
def func(frame, art, *, y=None):
|
| 1583 |
+
...
|
| 1584 |
+
|
| 1585 |
+
ani = FuncAnimation(fig, partial(func, art=ln, y='foo'))
|
| 1586 |
+
|
| 1587 |
+
If ``blit == True``, *func* must return an iterable of all artists
|
| 1588 |
+
that were modified or created. This information is used by the blitting
|
| 1589 |
+
algorithm to determine which parts of the figure have to be updated.
|
| 1590 |
+
The return value is unused if ``blit == False`` and may be omitted in
|
| 1591 |
+
that case.
|
| 1592 |
+
|
| 1593 |
+
frames : iterable, int, generator function, or None, optional
|
| 1594 |
+
Source of data to pass *func* and each frame of the animation
|
| 1595 |
+
|
| 1596 |
+
- If an iterable, then simply use the values provided. If the
|
| 1597 |
+
iterable has a length, it will override the *save_count* kwarg.
|
| 1598 |
+
|
| 1599 |
+
- If an integer, then equivalent to passing ``range(frames)``
|
| 1600 |
+
|
| 1601 |
+
- If a generator function, then must have the signature::
|
| 1602 |
+
|
| 1603 |
+
def gen_function() -> obj
|
| 1604 |
+
|
| 1605 |
+
- If *None*, then equivalent to passing ``itertools.count``.
|
| 1606 |
+
|
| 1607 |
+
In all of these cases, the values in *frames* is simply passed through
|
| 1608 |
+
to the user-supplied *func* and thus can be of any type.
|
| 1609 |
+
|
| 1610 |
+
init_func : callable, optional
|
| 1611 |
+
A function used to draw a clear frame. If not given, the results of
|
| 1612 |
+
drawing from the first item in the frames sequence will be used. This
|
| 1613 |
+
function will be called once before the first frame.
|
| 1614 |
+
|
| 1615 |
+
The required signature is::
|
| 1616 |
+
|
| 1617 |
+
def init_func() -> iterable_of_artists
|
| 1618 |
+
|
| 1619 |
+
If ``blit == True``, *init_func* must return an iterable of artists
|
| 1620 |
+
to be re-drawn. This information is used by the blitting algorithm to
|
| 1621 |
+
determine which parts of the figure have to be updated. The return
|
| 1622 |
+
value is unused if ``blit == False`` and may be omitted in that case.
|
| 1623 |
+
|
| 1624 |
+
fargs : tuple or None, optional
|
| 1625 |
+
Additional arguments to pass to each call to *func*. Note: the use of
|
| 1626 |
+
`functools.partial` is preferred over *fargs*. See *func* for details.
|
| 1627 |
+
|
| 1628 |
+
save_count : int, optional
|
| 1629 |
+
Fallback for the number of values from *frames* to cache. This is
|
| 1630 |
+
only used if the number of frames cannot be inferred from *frames*,
|
| 1631 |
+
i.e. when it's an iterator without length or a generator.
|
| 1632 |
+
|
| 1633 |
+
interval : int, default: 200
|
| 1634 |
+
Delay between frames in milliseconds.
|
| 1635 |
+
|
| 1636 |
+
repeat_delay : int, default: 0
|
| 1637 |
+
The delay in milliseconds between consecutive animation runs, if
|
| 1638 |
+
*repeat* is True.
|
| 1639 |
+
|
| 1640 |
+
repeat : bool, default: True
|
| 1641 |
+
Whether the animation repeats when the sequence of frames is completed.
|
| 1642 |
+
|
| 1643 |
+
blit : bool, default: False
|
| 1644 |
+
Whether blitting is used to optimize drawing. Note: when using
|
| 1645 |
+
blitting, any animated artists will be drawn according to their zorder;
|
| 1646 |
+
however, they will be drawn on top of any previous artists, regardless
|
| 1647 |
+
of their zorder.
|
| 1648 |
+
|
| 1649 |
+
cache_frame_data : bool, default: True
|
| 1650 |
+
Whether frame data is cached. Disabling cache might be helpful when
|
| 1651 |
+
frames contain large objects.
|
| 1652 |
+
"""
|
| 1653 |
+
def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
|
| 1654 |
+
save_count=None, *, cache_frame_data=True, **kwargs):
|
| 1655 |
+
if fargs:
|
| 1656 |
+
self._args = fargs
|
| 1657 |
+
else:
|
| 1658 |
+
self._args = ()
|
| 1659 |
+
self._func = func
|
| 1660 |
+
self._init_func = init_func
|
| 1661 |
+
|
| 1662 |
+
# Amount of framedata to keep around for saving movies. This is only
|
| 1663 |
+
# used if we don't know how many frames there will be: in the case
|
| 1664 |
+
# of no generator or in the case of a callable.
|
| 1665 |
+
self._save_count = save_count
|
| 1666 |
+
# Set up a function that creates a new iterable when needed. If nothing
|
| 1667 |
+
# is passed in for frames, just use itertools.count, which will just
|
| 1668 |
+
# keep counting from 0. A callable passed in for frames is assumed to
|
| 1669 |
+
# be a generator. An iterable will be used as is, and anything else
|
| 1670 |
+
# will be treated as a number of frames.
|
| 1671 |
+
if frames is None:
|
| 1672 |
+
self._iter_gen = itertools.count
|
| 1673 |
+
elif callable(frames):
|
| 1674 |
+
self._iter_gen = frames
|
| 1675 |
+
elif np.iterable(frames):
|
| 1676 |
+
if kwargs.get('repeat', True):
|
| 1677 |
+
self._tee_from = frames
|
| 1678 |
+
def iter_frames(frames=frames):
|
| 1679 |
+
this, self._tee_from = itertools.tee(self._tee_from, 2)
|
| 1680 |
+
yield from this
|
| 1681 |
+
self._iter_gen = iter_frames
|
| 1682 |
+
else:
|
| 1683 |
+
self._iter_gen = lambda: iter(frames)
|
| 1684 |
+
if hasattr(frames, '__len__'):
|
| 1685 |
+
self._save_count = len(frames)
|
| 1686 |
+
if save_count is not None:
|
| 1687 |
+
_api.warn_external(
|
| 1688 |
+
f"You passed in an explicit {save_count=} "
|
| 1689 |
+
"which is being ignored in favor of "
|
| 1690 |
+
f"{len(frames)=}."
|
| 1691 |
+
)
|
| 1692 |
+
else:
|
| 1693 |
+
self._iter_gen = lambda: iter(range(frames))
|
| 1694 |
+
self._save_count = frames
|
| 1695 |
+
if save_count is not None:
|
| 1696 |
+
_api.warn_external(
|
| 1697 |
+
f"You passed in an explicit {save_count=} which is being "
|
| 1698 |
+
f"ignored in favor of {frames=}."
|
| 1699 |
+
)
|
| 1700 |
+
if self._save_count is None and cache_frame_data:
|
| 1701 |
+
_api.warn_external(
|
| 1702 |
+
f"{frames=!r} which we can infer the length of, "
|
| 1703 |
+
"did not pass an explicit *save_count* "
|
| 1704 |
+
f"and passed {cache_frame_data=}. To avoid a possibly "
|
| 1705 |
+
"unbounded cache, frame data caching has been disabled. "
|
| 1706 |
+
"To suppress this warning either pass "
|
| 1707 |
+
"`cache_frame_data=False` or `save_count=MAX_FRAMES`."
|
| 1708 |
+
)
|
| 1709 |
+
cache_frame_data = False
|
| 1710 |
+
|
| 1711 |
+
self._cache_frame_data = cache_frame_data
|
| 1712 |
+
|
| 1713 |
+
# Needs to be initialized so the draw functions work without checking
|
| 1714 |
+
self._save_seq = []
|
| 1715 |
+
|
| 1716 |
+
super().__init__(fig, **kwargs)
|
| 1717 |
+
|
| 1718 |
+
# Need to reset the saved seq, since right now it will contain data
|
| 1719 |
+
# for a single frame from init, which is not what we want.
|
| 1720 |
+
self._save_seq = []
|
| 1721 |
+
|
| 1722 |
+
def new_frame_seq(self):
|
| 1723 |
+
# Use the generating function to generate a new frame sequence
|
| 1724 |
+
return self._iter_gen()
|
| 1725 |
+
|
| 1726 |
+
def new_saved_frame_seq(self):
|
| 1727 |
+
# Generate an iterator for the sequence of saved data. If there are
|
| 1728 |
+
# no saved frames, generate a new frame sequence and take the first
|
| 1729 |
+
# save_count entries in it.
|
| 1730 |
+
if self._save_seq:
|
| 1731 |
+
# While iterating we are going to update _save_seq
|
| 1732 |
+
# so make a copy to safely iterate over
|
| 1733 |
+
self._old_saved_seq = list(self._save_seq)
|
| 1734 |
+
return iter(self._old_saved_seq)
|
| 1735 |
+
else:
|
| 1736 |
+
if self._save_count is None:
|
| 1737 |
+
frame_seq = self.new_frame_seq()
|
| 1738 |
+
|
| 1739 |
+
def gen():
|
| 1740 |
+
try:
|
| 1741 |
+
while True:
|
| 1742 |
+
yield next(frame_seq)
|
| 1743 |
+
except StopIteration:
|
| 1744 |
+
pass
|
| 1745 |
+
return gen()
|
| 1746 |
+
else:
|
| 1747 |
+
return itertools.islice(self.new_frame_seq(), self._save_count)
|
| 1748 |
+
|
| 1749 |
+
def _init_draw(self):
|
| 1750 |
+
super()._init_draw()
|
| 1751 |
+
# Initialize the drawing either using the given init_func or by
|
| 1752 |
+
# calling the draw function with the first item of the frame sequence.
|
| 1753 |
+
# For blitting, the init_func should return a sequence of modified
|
| 1754 |
+
# artists.
|
| 1755 |
+
if self._init_func is None:
|
| 1756 |
+
try:
|
| 1757 |
+
frame_data = next(self.new_frame_seq())
|
| 1758 |
+
except StopIteration:
|
| 1759 |
+
# we can't start the iteration, it may have already been
|
| 1760 |
+
# exhausted by a previous save or just be 0 length.
|
| 1761 |
+
# warn and bail.
|
| 1762 |
+
warnings.warn(
|
| 1763 |
+
"Can not start iterating the frames for the initial draw. "
|
| 1764 |
+
"This can be caused by passing in a 0 length sequence "
|
| 1765 |
+
"for *frames*.\n\n"
|
| 1766 |
+
"If you passed *frames* as a generator "
|
| 1767 |
+
"it may be exhausted due to a previous display or save."
|
| 1768 |
+
)
|
| 1769 |
+
return
|
| 1770 |
+
self._draw_frame(frame_data)
|
| 1771 |
+
else:
|
| 1772 |
+
self._drawn_artists = self._init_func()
|
| 1773 |
+
if self._blit:
|
| 1774 |
+
if self._drawn_artists is None:
|
| 1775 |
+
raise RuntimeError('The init_func must return a '
|
| 1776 |
+
'sequence of Artist objects.')
|
| 1777 |
+
for a in self._drawn_artists:
|
| 1778 |
+
a.set_animated(self._blit)
|
| 1779 |
+
self._save_seq = []
|
| 1780 |
+
|
| 1781 |
+
def _draw_frame(self, framedata):
|
| 1782 |
+
if self._cache_frame_data:
|
| 1783 |
+
# Save the data for potential saving of movies.
|
| 1784 |
+
self._save_seq.append(framedata)
|
| 1785 |
+
self._save_seq = self._save_seq[-self._save_count:]
|
| 1786 |
+
|
| 1787 |
+
# Call the func with framedata and args. If blitting is desired,
|
| 1788 |
+
# func needs to return a sequence of any artists that were modified.
|
| 1789 |
+
self._drawn_artists = self._func(framedata, *self._args)
|
| 1790 |
+
|
| 1791 |
+
if self._blit:
|
| 1792 |
+
|
| 1793 |
+
err = RuntimeError('The animation function must return a sequence '
|
| 1794 |
+
'of Artist objects.')
|
| 1795 |
+
try:
|
| 1796 |
+
# check if a sequence
|
| 1797 |
+
iter(self._drawn_artists)
|
| 1798 |
+
except TypeError:
|
| 1799 |
+
raise err from None
|
| 1800 |
+
|
| 1801 |
+
# check each item if it's artist
|
| 1802 |
+
for i in self._drawn_artists:
|
| 1803 |
+
if not isinstance(i, mpl.artist.Artist):
|
| 1804 |
+
raise err
|
| 1805 |
+
|
| 1806 |
+
self._drawn_artists = sorted(self._drawn_artists,
|
| 1807 |
+
key=lambda x: x.get_zorder())
|
| 1808 |
+
|
| 1809 |
+
for a in self._drawn_artists:
|
| 1810 |
+
a.set_animated(self._blit)
|
| 1811 |
+
|
| 1812 |
+
|
| 1813 |
+
def _validate_grabframe_kwargs(savefig_kwargs):
|
| 1814 |
+
if mpl.rcParams['savefig.bbox'] == 'tight':
|
| 1815 |
+
raise ValueError(
|
| 1816 |
+
f"{mpl.rcParams['savefig.bbox']=} must not be 'tight' as it "
|
| 1817 |
+
"may cause frame size to vary, which is inappropriate for animation."
|
| 1818 |
+
)
|
| 1819 |
+
for k in ('dpi', 'bbox_inches', 'format'):
|
| 1820 |
+
if k in savefig_kwargs:
|
| 1821 |
+
raise TypeError(
|
| 1822 |
+
f"grab_frame got an unexpected keyword argument {k!r}"
|
| 1823 |
+
)
|
moondream/lib/python3.10/site-packages/matplotlib/animation.pyi
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
from collections.abc import Callable, Collection, Iterable, Sequence, Generator
|
| 3 |
+
import contextlib
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from matplotlib.artist import Artist
|
| 6 |
+
from matplotlib.backend_bases import TimerBase
|
| 7 |
+
from matplotlib.figure import Figure
|
| 8 |
+
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
subprocess_creation_flags: int
|
| 12 |
+
|
| 13 |
+
def adjusted_figsize(w: float, h: float, dpi: float, n: int) -> tuple[float, float]: ...
|
| 14 |
+
|
| 15 |
+
class MovieWriterRegistry:
|
| 16 |
+
def __init__(self) -> None: ...
|
| 17 |
+
def register(
|
| 18 |
+
self, name: str
|
| 19 |
+
) -> Callable[[type[AbstractMovieWriter]], type[AbstractMovieWriter]]: ...
|
| 20 |
+
def is_available(self, name: str) -> bool: ...
|
| 21 |
+
def __iter__(self) -> Generator[str, None, None]: ...
|
| 22 |
+
def list(self) -> list[str]: ...
|
| 23 |
+
def __getitem__(self, name: str) -> type[AbstractMovieWriter]: ...
|
| 24 |
+
|
| 25 |
+
writers: MovieWriterRegistry
|
| 26 |
+
|
| 27 |
+
class AbstractMovieWriter(abc.ABC, metaclass=abc.ABCMeta):
|
| 28 |
+
fps: int
|
| 29 |
+
metadata: dict[str, str]
|
| 30 |
+
codec: str
|
| 31 |
+
bitrate: int
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
fps: int = ...,
|
| 35 |
+
metadata: dict[str, str] | None = ...,
|
| 36 |
+
codec: str | None = ...,
|
| 37 |
+
bitrate: int | None = ...,
|
| 38 |
+
) -> None: ...
|
| 39 |
+
outfile: str | Path
|
| 40 |
+
fig: Figure
|
| 41 |
+
dpi: float
|
| 42 |
+
|
| 43 |
+
@abc.abstractmethod
|
| 44 |
+
def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
|
| 45 |
+
@property
|
| 46 |
+
def frame_size(self) -> tuple[int, int]: ...
|
| 47 |
+
@abc.abstractmethod
|
| 48 |
+
def grab_frame(self, **savefig_kwargs) -> None: ...
|
| 49 |
+
@abc.abstractmethod
|
| 50 |
+
def finish(self) -> None: ...
|
| 51 |
+
@contextlib.contextmanager
|
| 52 |
+
def saving(
|
| 53 |
+
self, fig: Figure, outfile: str | Path, dpi: float | None, *args, **kwargs
|
| 54 |
+
) -> Generator[AbstractMovieWriter, None, None]: ...
|
| 55 |
+
|
| 56 |
+
class MovieWriter(AbstractMovieWriter):
|
| 57 |
+
supported_formats: list[str]
|
| 58 |
+
frame_format: str
|
| 59 |
+
extra_args: list[str] | None
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
fps: int = ...,
|
| 63 |
+
codec: str | None = ...,
|
| 64 |
+
bitrate: int | None = ...,
|
| 65 |
+
extra_args: list[str] | None = ...,
|
| 66 |
+
metadata: dict[str, str] | None = ...,
|
| 67 |
+
) -> None: ...
|
| 68 |
+
def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
|
| 69 |
+
def grab_frame(self, **savefig_kwargs) -> None: ...
|
| 70 |
+
def finish(self) -> None: ...
|
| 71 |
+
@classmethod
|
| 72 |
+
def bin_path(cls) -> str: ...
|
| 73 |
+
@classmethod
|
| 74 |
+
def isAvailable(cls) -> bool: ...
|
| 75 |
+
|
| 76 |
+
class FileMovieWriter(MovieWriter):
|
| 77 |
+
fig: Figure
|
| 78 |
+
outfile: str | Path
|
| 79 |
+
dpi: float
|
| 80 |
+
temp_prefix: str
|
| 81 |
+
fname_format_str: str
|
| 82 |
+
def setup(
|
| 83 |
+
self,
|
| 84 |
+
fig: Figure,
|
| 85 |
+
outfile: str | Path,
|
| 86 |
+
dpi: float | None = ...,
|
| 87 |
+
frame_prefix: str | Path | None = ...,
|
| 88 |
+
) -> None: ...
|
| 89 |
+
def __del__(self) -> None: ...
|
| 90 |
+
@property
|
| 91 |
+
def frame_format(self) -> str: ...
|
| 92 |
+
@frame_format.setter
|
| 93 |
+
def frame_format(self, frame_format: str) -> None: ...
|
| 94 |
+
|
| 95 |
+
class PillowWriter(AbstractMovieWriter):
|
| 96 |
+
@classmethod
|
| 97 |
+
def isAvailable(cls) -> bool: ...
|
| 98 |
+
def setup(
|
| 99 |
+
self, fig: Figure, outfile: str | Path, dpi: float | None = ...
|
| 100 |
+
) -> None: ...
|
| 101 |
+
def grab_frame(self, **savefig_kwargs) -> None: ...
|
| 102 |
+
def finish(self) -> None: ...
|
| 103 |
+
|
| 104 |
+
class FFMpegBase:
|
| 105 |
+
codec: str
|
| 106 |
+
@property
|
| 107 |
+
def output_args(self) -> list[str]: ...
|
| 108 |
+
|
| 109 |
+
class FFMpegWriter(FFMpegBase, MovieWriter): ...
|
| 110 |
+
|
| 111 |
+
class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
|
| 112 |
+
supported_formats: list[str]
|
| 113 |
+
|
| 114 |
+
class ImageMagickBase:
|
| 115 |
+
@classmethod
|
| 116 |
+
def bin_path(cls) -> str: ...
|
| 117 |
+
@classmethod
|
| 118 |
+
def isAvailable(cls) -> bool: ...
|
| 119 |
+
|
| 120 |
+
class ImageMagickWriter(ImageMagickBase, MovieWriter):
|
| 121 |
+
input_names: str
|
| 122 |
+
|
| 123 |
+
class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
|
| 124 |
+
supported_formats: list[str]
|
| 125 |
+
@property
|
| 126 |
+
def input_names(self) -> str: ...
|
| 127 |
+
|
| 128 |
+
class HTMLWriter(FileMovieWriter):
|
| 129 |
+
supported_formats: list[str]
|
| 130 |
+
@classmethod
|
| 131 |
+
def isAvailable(cls) -> bool: ...
|
| 132 |
+
embed_frames: bool
|
| 133 |
+
default_mode: str
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
fps: int = ...,
|
| 137 |
+
codec: str | None = ...,
|
| 138 |
+
bitrate: int | None = ...,
|
| 139 |
+
extra_args: list[str] | None = ...,
|
| 140 |
+
metadata: dict[str, str] | None = ...,
|
| 141 |
+
embed_frames: bool = ...,
|
| 142 |
+
default_mode: str = ...,
|
| 143 |
+
embed_limit: float | None = ...,
|
| 144 |
+
) -> None: ...
|
| 145 |
+
def setup(
|
| 146 |
+
self,
|
| 147 |
+
fig: Figure,
|
| 148 |
+
outfile: str | Path,
|
| 149 |
+
dpi: float | None = ...,
|
| 150 |
+
frame_dir: str | Path | None = ...,
|
| 151 |
+
) -> None: ...
|
| 152 |
+
def grab_frame(self, **savefig_kwargs): ...
|
| 153 |
+
def finish(self) -> None: ...
|
| 154 |
+
|
| 155 |
+
class Animation:
|
| 156 |
+
frame_seq: Iterable[Artist]
|
| 157 |
+
event_source: Any
|
| 158 |
+
def __init__(
|
| 159 |
+
self, fig: Figure, event_source: Any | None = ..., blit: bool = ...
|
| 160 |
+
) -> None: ...
|
| 161 |
+
def __del__(self) -> None: ...
|
| 162 |
+
def save(
|
| 163 |
+
self,
|
| 164 |
+
filename: str | Path,
|
| 165 |
+
writer: AbstractMovieWriter | str | None = ...,
|
| 166 |
+
fps: int | None = ...,
|
| 167 |
+
dpi: float | None = ...,
|
| 168 |
+
codec: str | None = ...,
|
| 169 |
+
bitrate: int | None = ...,
|
| 170 |
+
extra_args: list[str] | None = ...,
|
| 171 |
+
metadata: dict[str, str] | None = ...,
|
| 172 |
+
extra_anim: list[Animation] | None = ...,
|
| 173 |
+
savefig_kwargs: dict[str, Any] | None = ...,
|
| 174 |
+
*,
|
| 175 |
+
progress_callback: Callable[[int, int], Any] | None = ...
|
| 176 |
+
) -> None: ...
|
| 177 |
+
def new_frame_seq(self) -> Iterable[Artist]: ...
|
| 178 |
+
def new_saved_frame_seq(self) -> Iterable[Artist]: ...
|
| 179 |
+
def to_html5_video(self, embed_limit: float | None = ...) -> str: ...
|
| 180 |
+
def to_jshtml(
|
| 181 |
+
self,
|
| 182 |
+
fps: int | None = ...,
|
| 183 |
+
embed_frames: bool = ...,
|
| 184 |
+
default_mode: str | None = ...,
|
| 185 |
+
) -> str: ...
|
| 186 |
+
def _repr_html_(self) -> str: ...
|
| 187 |
+
def pause(self) -> None: ...
|
| 188 |
+
def resume(self) -> None: ...
|
| 189 |
+
|
| 190 |
+
class TimedAnimation(Animation):
|
| 191 |
+
def __init__(
|
| 192 |
+
self,
|
| 193 |
+
fig: Figure,
|
| 194 |
+
interval: int = ...,
|
| 195 |
+
repeat_delay: int = ...,
|
| 196 |
+
repeat: bool = ...,
|
| 197 |
+
event_source: TimerBase | None = ...,
|
| 198 |
+
*args,
|
| 199 |
+
**kwargs
|
| 200 |
+
) -> None: ...
|
| 201 |
+
|
| 202 |
+
class ArtistAnimation(TimedAnimation):
|
| 203 |
+
def __init__(self, fig: Figure, artists: Sequence[Collection[Artist]], *args, **kwargs) -> None: ...
|
| 204 |
+
|
| 205 |
+
class FuncAnimation(TimedAnimation):
|
| 206 |
+
def __init__(
|
| 207 |
+
self,
|
| 208 |
+
fig: Figure,
|
| 209 |
+
func: Callable[..., Iterable[Artist]],
|
| 210 |
+
frames: Iterable | int | Callable[[], Generator] | None = ...,
|
| 211 |
+
init_func: Callable[[], Iterable[Artist]] | None = ...,
|
| 212 |
+
fargs: tuple[Any, ...] | None = ...,
|
| 213 |
+
save_count: int | None = ...,
|
| 214 |
+
*,
|
| 215 |
+
cache_frame_data: bool = ...,
|
| 216 |
+
**kwargs
|
| 217 |
+
) -> None: ...
|
moondream/lib/python3.10/site-packages/matplotlib/artist.py
ADDED
|
@@ -0,0 +1,1855 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
import contextlib
|
| 3 |
+
from functools import cache, reduce, wraps
|
| 4 |
+
import inspect
|
| 5 |
+
from inspect import Signature, Parameter
|
| 6 |
+
import logging
|
| 7 |
+
from numbers import Number, Real
|
| 8 |
+
import operator
|
| 9 |
+
import re
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
import matplotlib as mpl
|
| 15 |
+
from . import _api, cbook
|
| 16 |
+
from .path import Path
|
| 17 |
+
from .transforms import (BboxBase, Bbox, IdentityTransform, Transform, TransformedBbox,
|
| 18 |
+
TransformedPatchPath, TransformedPath)
|
| 19 |
+
|
| 20 |
+
_log = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _prevent_rasterization(draw):
|
| 24 |
+
# We assume that by default artists are not allowed to rasterize (unless
|
| 25 |
+
# its draw method is explicitly decorated). If it is being drawn after a
|
| 26 |
+
# rasterized artist and it has reached a raster_depth of 0, we stop
|
| 27 |
+
# rasterization so that it does not affect the behavior of normal artist
|
| 28 |
+
# (e.g., change in dpi).
|
| 29 |
+
|
| 30 |
+
@wraps(draw)
|
| 31 |
+
def draw_wrapper(artist, renderer, *args, **kwargs):
|
| 32 |
+
if renderer._raster_depth == 0 and renderer._rasterizing:
|
| 33 |
+
# Only stop when we are not in a rasterized parent
|
| 34 |
+
# and something has been rasterized since last stop.
|
| 35 |
+
renderer.stop_rasterizing()
|
| 36 |
+
renderer._rasterizing = False
|
| 37 |
+
|
| 38 |
+
return draw(artist, renderer, *args, **kwargs)
|
| 39 |
+
|
| 40 |
+
draw_wrapper._supports_rasterization = False
|
| 41 |
+
return draw_wrapper
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def allow_rasterization(draw):
|
| 45 |
+
"""
|
| 46 |
+
Decorator for Artist.draw method. Provides routines
|
| 47 |
+
that run before and after the draw call. The before and after functions
|
| 48 |
+
are useful for changing artist-dependent renderer attributes or making
|
| 49 |
+
other setup function calls, such as starting and flushing a mixed-mode
|
| 50 |
+
renderer.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
@wraps(draw)
|
| 54 |
+
def draw_wrapper(artist, renderer):
|
| 55 |
+
try:
|
| 56 |
+
if artist.get_rasterized():
|
| 57 |
+
if renderer._raster_depth == 0 and not renderer._rasterizing:
|
| 58 |
+
renderer.start_rasterizing()
|
| 59 |
+
renderer._rasterizing = True
|
| 60 |
+
renderer._raster_depth += 1
|
| 61 |
+
else:
|
| 62 |
+
if renderer._raster_depth == 0 and renderer._rasterizing:
|
| 63 |
+
# Only stop when we are not in a rasterized parent
|
| 64 |
+
# and something has be rasterized since last stop
|
| 65 |
+
renderer.stop_rasterizing()
|
| 66 |
+
renderer._rasterizing = False
|
| 67 |
+
|
| 68 |
+
if artist.get_agg_filter() is not None:
|
| 69 |
+
renderer.start_filter()
|
| 70 |
+
|
| 71 |
+
return draw(artist, renderer)
|
| 72 |
+
finally:
|
| 73 |
+
if artist.get_agg_filter() is not None:
|
| 74 |
+
renderer.stop_filter(artist.get_agg_filter())
|
| 75 |
+
if artist.get_rasterized():
|
| 76 |
+
renderer._raster_depth -= 1
|
| 77 |
+
if (renderer._rasterizing and (fig := artist.get_figure(root=True)) and
|
| 78 |
+
fig.suppressComposite):
|
| 79 |
+
# restart rasterizing to prevent merging
|
| 80 |
+
renderer.stop_rasterizing()
|
| 81 |
+
renderer.start_rasterizing()
|
| 82 |
+
|
| 83 |
+
draw_wrapper._supports_rasterization = True
|
| 84 |
+
return draw_wrapper
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _finalize_rasterization(draw):
|
| 88 |
+
"""
|
| 89 |
+
Decorator for Artist.draw method. Needed on the outermost artist, i.e.
|
| 90 |
+
Figure, to finish up if the render is still in rasterized mode.
|
| 91 |
+
"""
|
| 92 |
+
@wraps(draw)
|
| 93 |
+
def draw_wrapper(artist, renderer, *args, **kwargs):
|
| 94 |
+
result = draw(artist, renderer, *args, **kwargs)
|
| 95 |
+
if renderer._rasterizing:
|
| 96 |
+
renderer.stop_rasterizing()
|
| 97 |
+
renderer._rasterizing = False
|
| 98 |
+
return result
|
| 99 |
+
return draw_wrapper
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _stale_axes_callback(self, val):
|
| 103 |
+
if self.axes:
|
| 104 |
+
self.axes.stale = val
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
_XYPair = namedtuple("_XYPair", "x y")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class _Unset:
|
| 111 |
+
def __repr__(self):
|
| 112 |
+
return "<UNSET>"
|
| 113 |
+
_UNSET = _Unset()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Artist:
|
| 117 |
+
"""
|
| 118 |
+
Abstract base class for objects that render into a FigureCanvas.
|
| 119 |
+
|
| 120 |
+
Typically, all visible elements in a figure are subclasses of Artist.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
zorder = 0
|
| 124 |
+
|
| 125 |
+
def __init_subclass__(cls):
|
| 126 |
+
|
| 127 |
+
# Decorate draw() method so that all artists are able to stop
|
| 128 |
+
# rastrization when necessary. If the artist's draw method is already
|
| 129 |
+
# decorated (has a `_supports_rasterization` attribute), it won't be
|
| 130 |
+
# decorated.
|
| 131 |
+
|
| 132 |
+
if not hasattr(cls.draw, "_supports_rasterization"):
|
| 133 |
+
cls.draw = _prevent_rasterization(cls.draw)
|
| 134 |
+
|
| 135 |
+
# Inject custom set() methods into the subclass with signature and
|
| 136 |
+
# docstring based on the subclasses' properties.
|
| 137 |
+
|
| 138 |
+
if not hasattr(cls.set, '_autogenerated_signature'):
|
| 139 |
+
# Don't overwrite cls.set if the subclass or one of its parents
|
| 140 |
+
# has defined a set method set itself.
|
| 141 |
+
# If there was no explicit definition, cls.set is inherited from
|
| 142 |
+
# the hierarchy of auto-generated set methods, which hold the
|
| 143 |
+
# flag _autogenerated_signature.
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
cls.set = lambda self, **kwargs: Artist.set(self, **kwargs)
|
| 147 |
+
cls.set.__name__ = "set"
|
| 148 |
+
cls.set.__qualname__ = f"{cls.__qualname__}.set"
|
| 149 |
+
cls._update_set_signature_and_docstring()
|
| 150 |
+
|
| 151 |
+
_PROPERTIES_EXCLUDED_FROM_SET = [
|
| 152 |
+
'navigate_mode', # not a user-facing function
|
| 153 |
+
'figure', # changing the figure is such a profound operation
|
| 154 |
+
# that we don't want this in set()
|
| 155 |
+
'3d_properties', # cannot be used as a keyword due to leading digit
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def _update_set_signature_and_docstring(cls):
|
| 160 |
+
"""
|
| 161 |
+
Update the signature of the set function to list all properties
|
| 162 |
+
as keyword arguments.
|
| 163 |
+
|
| 164 |
+
Property aliases are not listed in the signature for brevity, but
|
| 165 |
+
are still accepted as keyword arguments.
|
| 166 |
+
"""
|
| 167 |
+
cls.set.__signature__ = Signature(
|
| 168 |
+
[Parameter("self", Parameter.POSITIONAL_OR_KEYWORD),
|
| 169 |
+
*[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET)
|
| 170 |
+
for prop in ArtistInspector(cls).get_setters()
|
| 171 |
+
if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]])
|
| 172 |
+
cls.set._autogenerated_signature = True
|
| 173 |
+
|
| 174 |
+
cls.set.__doc__ = (
|
| 175 |
+
"Set multiple properties at once.\n\n"
|
| 176 |
+
"Supported properties are\n\n"
|
| 177 |
+
+ kwdoc(cls))
|
| 178 |
+
|
| 179 |
+
def __init__(self):
|
| 180 |
+
self._stale = True
|
| 181 |
+
self.stale_callback = None
|
| 182 |
+
self._axes = None
|
| 183 |
+
self._parent_figure = None
|
| 184 |
+
|
| 185 |
+
self._transform = None
|
| 186 |
+
self._transformSet = False
|
| 187 |
+
self._visible = True
|
| 188 |
+
self._animated = False
|
| 189 |
+
self._alpha = None
|
| 190 |
+
self.clipbox = None
|
| 191 |
+
self._clippath = None
|
| 192 |
+
self._clipon = True
|
| 193 |
+
self._label = ''
|
| 194 |
+
self._picker = None
|
| 195 |
+
self._rasterized = False
|
| 196 |
+
self._agg_filter = None
|
| 197 |
+
# Normally, artist classes need to be queried for mouseover info if and
|
| 198 |
+
# only if they override get_cursor_data.
|
| 199 |
+
self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data
|
| 200 |
+
self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
|
| 201 |
+
try:
|
| 202 |
+
self.axes = None
|
| 203 |
+
except AttributeError:
|
| 204 |
+
# Handle self.axes as a read-only property, as in Figure.
|
| 205 |
+
pass
|
| 206 |
+
self._remove_method = None
|
| 207 |
+
self._url = None
|
| 208 |
+
self._gid = None
|
| 209 |
+
self._snap = None
|
| 210 |
+
self._sketch = mpl.rcParams['path.sketch']
|
| 211 |
+
self._path_effects = mpl.rcParams['path.effects']
|
| 212 |
+
self._sticky_edges = _XYPair([], [])
|
| 213 |
+
self._in_layout = True
|
| 214 |
+
|
| 215 |
+
def __getstate__(self):
|
| 216 |
+
d = self.__dict__.copy()
|
| 217 |
+
d['stale_callback'] = None
|
| 218 |
+
return d
|
| 219 |
+
|
| 220 |
+
def remove(self):
|
| 221 |
+
"""
|
| 222 |
+
Remove the artist from the figure if possible.
|
| 223 |
+
|
| 224 |
+
The effect will not be visible until the figure is redrawn, e.g.,
|
| 225 |
+
with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to
|
| 226 |
+
update the Axes limits if desired.
|
| 227 |
+
|
| 228 |
+
Note: `~.axes.Axes.relim` will not see collections even if the
|
| 229 |
+
collection was added to the Axes with *autolim* = True.
|
| 230 |
+
|
| 231 |
+
Note: there is no support for removing the artist's legend entry.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
# There is no method to set the callback. Instead, the parent should
|
| 235 |
+
# set the _remove_method attribute directly. This would be a
|
| 236 |
+
# protected attribute if Python supported that sort of thing. The
|
| 237 |
+
# callback has one parameter, which is the child to be removed.
|
| 238 |
+
if self._remove_method is not None:
|
| 239 |
+
self._remove_method(self)
|
| 240 |
+
# clear stale callback
|
| 241 |
+
self.stale_callback = None
|
| 242 |
+
_ax_flag = False
|
| 243 |
+
if hasattr(self, 'axes') and self.axes:
|
| 244 |
+
# remove from the mouse hit list
|
| 245 |
+
self.axes._mouseover_set.discard(self)
|
| 246 |
+
self.axes.stale = True
|
| 247 |
+
self.axes = None # decouple the artist from the Axes
|
| 248 |
+
_ax_flag = True
|
| 249 |
+
|
| 250 |
+
if (fig := self.get_figure(root=False)) is not None:
|
| 251 |
+
if not _ax_flag:
|
| 252 |
+
fig.stale = True
|
| 253 |
+
self._parent_figure = None
|
| 254 |
+
|
| 255 |
+
else:
|
| 256 |
+
raise NotImplementedError('cannot remove artist')
|
| 257 |
+
# TODO: the fix for the collections relim problem is to move the
|
| 258 |
+
# limits calculation into the artist itself, including the property of
|
| 259 |
+
# whether or not the artist should affect the limits. Then there will
|
| 260 |
+
# be no distinction between axes.add_line, axes.add_patch, etc.
|
| 261 |
+
# TODO: add legend support
|
| 262 |
+
|
| 263 |
+
def have_units(self):
|
| 264 |
+
"""Return whether units are set on any axis."""
|
| 265 |
+
ax = self.axes
|
| 266 |
+
return ax and any(axis.have_units() for axis in ax._axis_map.values())
|
| 267 |
+
|
| 268 |
+
def convert_xunits(self, x):
|
| 269 |
+
"""
|
| 270 |
+
Convert *x* using the unit type of the xaxis.
|
| 271 |
+
|
| 272 |
+
If the artist is not contained in an Axes or if the xaxis does not
|
| 273 |
+
have units, *x* itself is returned.
|
| 274 |
+
"""
|
| 275 |
+
ax = getattr(self, 'axes', None)
|
| 276 |
+
if ax is None or ax.xaxis is None:
|
| 277 |
+
return x
|
| 278 |
+
return ax.xaxis.convert_units(x)
|
| 279 |
+
|
| 280 |
+
def convert_yunits(self, y):
|
| 281 |
+
"""
|
| 282 |
+
Convert *y* using the unit type of the yaxis.
|
| 283 |
+
|
| 284 |
+
If the artist is not contained in an Axes or if the yaxis does not
|
| 285 |
+
have units, *y* itself is returned.
|
| 286 |
+
"""
|
| 287 |
+
ax = getattr(self, 'axes', None)
|
| 288 |
+
if ax is None or ax.yaxis is None:
|
| 289 |
+
return y
|
| 290 |
+
return ax.yaxis.convert_units(y)
|
| 291 |
+
|
| 292 |
+
@property
|
| 293 |
+
def axes(self):
|
| 294 |
+
"""The `~.axes.Axes` instance the artist resides in, or *None*."""
|
| 295 |
+
return self._axes
|
| 296 |
+
|
| 297 |
+
@axes.setter
|
| 298 |
+
def axes(self, new_axes):
|
| 299 |
+
if (new_axes is not None and self._axes is not None
|
| 300 |
+
and new_axes != self._axes):
|
| 301 |
+
raise ValueError("Can not reset the Axes. You are probably trying to reuse "
|
| 302 |
+
"an artist in more than one Axes which is not supported")
|
| 303 |
+
self._axes = new_axes
|
| 304 |
+
if new_axes is not None and new_axes is not self:
|
| 305 |
+
self.stale_callback = _stale_axes_callback
|
| 306 |
+
|
| 307 |
+
@property
|
| 308 |
+
def stale(self):
|
| 309 |
+
"""
|
| 310 |
+
Whether the artist is 'stale' and needs to be re-drawn for the output
|
| 311 |
+
to match the internal state of the artist.
|
| 312 |
+
"""
|
| 313 |
+
return self._stale
|
| 314 |
+
|
| 315 |
+
@stale.setter
|
| 316 |
+
def stale(self, val):
|
| 317 |
+
self._stale = val
|
| 318 |
+
|
| 319 |
+
# if the artist is animated it does not take normal part in the
|
| 320 |
+
# draw stack and is not expected to be drawn as part of the normal
|
| 321 |
+
# draw loop (when not saving) so do not propagate this change
|
| 322 |
+
if self._animated:
|
| 323 |
+
return
|
| 324 |
+
|
| 325 |
+
if val and self.stale_callback is not None:
|
| 326 |
+
self.stale_callback(self, val)
|
| 327 |
+
|
| 328 |
+
def get_window_extent(self, renderer=None):
|
| 329 |
+
"""
|
| 330 |
+
Get the artist's bounding box in display space.
|
| 331 |
+
|
| 332 |
+
The bounding box' width and height are nonnegative.
|
| 333 |
+
|
| 334 |
+
Subclasses should override for inclusion in the bounding box
|
| 335 |
+
"tight" calculation. Default is to return an empty bounding
|
| 336 |
+
box at 0, 0.
|
| 337 |
+
|
| 338 |
+
Be careful when using this function, the results will not update
|
| 339 |
+
if the artist window extent of the artist changes. The extent
|
| 340 |
+
can change due to any changes in the transform stack, such as
|
| 341 |
+
changing the Axes limits, the figure size, or the canvas used
|
| 342 |
+
(as is done when saving a figure). This can lead to unexpected
|
| 343 |
+
behavior where interactive figures will look fine on the screen,
|
| 344 |
+
but will save incorrectly.
|
| 345 |
+
"""
|
| 346 |
+
return Bbox([[0, 0], [0, 0]])
|
| 347 |
+
|
| 348 |
+
def get_tightbbox(self, renderer=None):
|
| 349 |
+
"""
|
| 350 |
+
Like `.Artist.get_window_extent`, but includes any clipping.
|
| 351 |
+
|
| 352 |
+
Parameters
|
| 353 |
+
----------
|
| 354 |
+
renderer : `~matplotlib.backend_bases.RendererBase` subclass, optional
|
| 355 |
+
renderer that will be used to draw the figures (i.e.
|
| 356 |
+
``fig.canvas.get_renderer()``)
|
| 357 |
+
|
| 358 |
+
Returns
|
| 359 |
+
-------
|
| 360 |
+
`.Bbox` or None
|
| 361 |
+
The enclosing bounding box (in figure pixel coordinates).
|
| 362 |
+
Returns None if clipping results in no intersection.
|
| 363 |
+
"""
|
| 364 |
+
bbox = self.get_window_extent(renderer)
|
| 365 |
+
if self.get_clip_on():
|
| 366 |
+
clip_box = self.get_clip_box()
|
| 367 |
+
if clip_box is not None:
|
| 368 |
+
bbox = Bbox.intersection(bbox, clip_box)
|
| 369 |
+
clip_path = self.get_clip_path()
|
| 370 |
+
if clip_path is not None and bbox is not None:
|
| 371 |
+
clip_path = clip_path.get_fully_transformed_path()
|
| 372 |
+
bbox = Bbox.intersection(bbox, clip_path.get_extents())
|
| 373 |
+
return bbox
|
| 374 |
+
|
| 375 |
+
def add_callback(self, func):
|
| 376 |
+
"""
|
| 377 |
+
Add a callback function that will be called whenever one of the
|
| 378 |
+
`.Artist`'s properties changes.
|
| 379 |
+
|
| 380 |
+
Parameters
|
| 381 |
+
----------
|
| 382 |
+
func : callable
|
| 383 |
+
The callback function. It must have the signature::
|
| 384 |
+
|
| 385 |
+
def func(artist: Artist) -> Any
|
| 386 |
+
|
| 387 |
+
where *artist* is the calling `.Artist`. Return values may exist
|
| 388 |
+
but are ignored.
|
| 389 |
+
|
| 390 |
+
Returns
|
| 391 |
+
-------
|
| 392 |
+
int
|
| 393 |
+
The observer id associated with the callback. This id can be
|
| 394 |
+
used for removing the callback with `.remove_callback` later.
|
| 395 |
+
|
| 396 |
+
See Also
|
| 397 |
+
--------
|
| 398 |
+
remove_callback
|
| 399 |
+
"""
|
| 400 |
+
# Wrapping func in a lambda ensures it can be connected multiple times
|
| 401 |
+
# and never gets weakref-gc'ed.
|
| 402 |
+
return self._callbacks.connect("pchanged", lambda: func(self))
|
| 403 |
+
|
| 404 |
+
def remove_callback(self, oid):
|
| 405 |
+
"""
|
| 406 |
+
Remove a callback based on its observer id.
|
| 407 |
+
|
| 408 |
+
See Also
|
| 409 |
+
--------
|
| 410 |
+
add_callback
|
| 411 |
+
"""
|
| 412 |
+
self._callbacks.disconnect(oid)
|
| 413 |
+
|
| 414 |
+
def pchanged(self):
|
| 415 |
+
"""
|
| 416 |
+
Call all of the registered callbacks.
|
| 417 |
+
|
| 418 |
+
This function is triggered internally when a property is changed.
|
| 419 |
+
|
| 420 |
+
See Also
|
| 421 |
+
--------
|
| 422 |
+
add_callback
|
| 423 |
+
remove_callback
|
| 424 |
+
"""
|
| 425 |
+
self._callbacks.process("pchanged")
|
| 426 |
+
|
| 427 |
+
def is_transform_set(self):
|
| 428 |
+
"""
|
| 429 |
+
Return whether the Artist has an explicitly set transform.
|
| 430 |
+
|
| 431 |
+
This is *True* after `.set_transform` has been called.
|
| 432 |
+
"""
|
| 433 |
+
return self._transformSet
|
| 434 |
+
|
| 435 |
+
def set_transform(self, t):
|
| 436 |
+
"""
|
| 437 |
+
Set the artist transform.
|
| 438 |
+
|
| 439 |
+
Parameters
|
| 440 |
+
----------
|
| 441 |
+
t : `~matplotlib.transforms.Transform`
|
| 442 |
+
"""
|
| 443 |
+
self._transform = t
|
| 444 |
+
self._transformSet = True
|
| 445 |
+
self.pchanged()
|
| 446 |
+
self.stale = True
|
| 447 |
+
|
| 448 |
+
def get_transform(self):
|
| 449 |
+
"""Return the `.Transform` instance used by this artist."""
|
| 450 |
+
if self._transform is None:
|
| 451 |
+
self._transform = IdentityTransform()
|
| 452 |
+
elif (not isinstance(self._transform, Transform)
|
| 453 |
+
and hasattr(self._transform, '_as_mpl_transform')):
|
| 454 |
+
self._transform = self._transform._as_mpl_transform(self.axes)
|
| 455 |
+
return self._transform
|
| 456 |
+
|
| 457 |
+
def get_children(self):
|
| 458 |
+
r"""Return a list of the child `.Artist`\s of this `.Artist`."""
|
| 459 |
+
return []
|
| 460 |
+
|
| 461 |
+
def _different_canvas(self, event):
|
| 462 |
+
"""
|
| 463 |
+
Check whether an *event* occurred on a canvas other that this artist's canvas.
|
| 464 |
+
|
| 465 |
+
If this method returns True, the event definitely occurred on a different
|
| 466 |
+
canvas; if it returns False, either it occurred on the same canvas, or we may
|
| 467 |
+
not have enough information to know.
|
| 468 |
+
|
| 469 |
+
Subclasses should start their definition of `contains` as follows::
|
| 470 |
+
|
| 471 |
+
if self._different_canvas(mouseevent):
|
| 472 |
+
return False, {}
|
| 473 |
+
# subclass-specific implementation follows
|
| 474 |
+
"""
|
| 475 |
+
return (getattr(event, "canvas", None) is not None
|
| 476 |
+
and (fig := self.get_figure(root=True)) is not None
|
| 477 |
+
and event.canvas is not fig.canvas)
|
| 478 |
+
|
| 479 |
+
def contains(self, mouseevent):
|
| 480 |
+
"""
|
| 481 |
+
Test whether the artist contains the mouse event.
|
| 482 |
+
|
| 483 |
+
Parameters
|
| 484 |
+
----------
|
| 485 |
+
mouseevent : `~matplotlib.backend_bases.MouseEvent`
|
| 486 |
+
|
| 487 |
+
Returns
|
| 488 |
+
-------
|
| 489 |
+
contains : bool
|
| 490 |
+
Whether any values are within the radius.
|
| 491 |
+
details : dict
|
| 492 |
+
An artist-specific dictionary of details of the event context,
|
| 493 |
+
such as which points are contained in the pick radius. See the
|
| 494 |
+
individual Artist subclasses for details.
|
| 495 |
+
"""
|
| 496 |
+
_log.warning("%r needs 'contains' method", self.__class__.__name__)
|
| 497 |
+
return False, {}
|
| 498 |
+
|
| 499 |
+
def pickable(self):
|
| 500 |
+
"""
|
| 501 |
+
Return whether the artist is pickable.
|
| 502 |
+
|
| 503 |
+
See Also
|
| 504 |
+
--------
|
| 505 |
+
.Artist.set_picker, .Artist.get_picker, .Artist.pick
|
| 506 |
+
"""
|
| 507 |
+
return self.get_figure(root=False) is not None and self._picker is not None
|
| 508 |
+
|
| 509 |
+
def pick(self, mouseevent):
|
| 510 |
+
"""
|
| 511 |
+
Process a pick event.
|
| 512 |
+
|
| 513 |
+
Each child artist will fire a pick event if *mouseevent* is over
|
| 514 |
+
the artist and the artist has picker set.
|
| 515 |
+
|
| 516 |
+
See Also
|
| 517 |
+
--------
|
| 518 |
+
.Artist.set_picker, .Artist.get_picker, .Artist.pickable
|
| 519 |
+
"""
|
| 520 |
+
from .backend_bases import PickEvent # Circular import.
|
| 521 |
+
# Pick self
|
| 522 |
+
if self.pickable():
|
| 523 |
+
picker = self.get_picker()
|
| 524 |
+
if callable(picker):
|
| 525 |
+
inside, prop = picker(self, mouseevent)
|
| 526 |
+
else:
|
| 527 |
+
inside, prop = self.contains(mouseevent)
|
| 528 |
+
if inside:
|
| 529 |
+
PickEvent("pick_event", self.get_figure(root=True).canvas,
|
| 530 |
+
mouseevent, self, **prop)._process()
|
| 531 |
+
|
| 532 |
+
# Pick children
|
| 533 |
+
for a in self.get_children():
|
| 534 |
+
# make sure the event happened in the same Axes
|
| 535 |
+
ax = getattr(a, 'axes', None)
|
| 536 |
+
if (isinstance(a, mpl.figure.SubFigure)
|
| 537 |
+
or mouseevent.inaxes is None or ax is None
|
| 538 |
+
or mouseevent.inaxes == ax):
|
| 539 |
+
# we need to check if mouseevent.inaxes is None
|
| 540 |
+
# because some objects associated with an Axes (e.g., a
|
| 541 |
+
# tick label) can be outside the bounding box of the
|
| 542 |
+
# Axes and inaxes will be None
|
| 543 |
+
# also check that ax is None so that it traverse objects
|
| 544 |
+
# which do not have an axes property but children might
|
| 545 |
+
a.pick(mouseevent)
|
| 546 |
+
|
| 547 |
+
def set_picker(self, picker):
|
| 548 |
+
"""
|
| 549 |
+
Define the picking behavior of the artist.
|
| 550 |
+
|
| 551 |
+
Parameters
|
| 552 |
+
----------
|
| 553 |
+
picker : None or bool or float or callable
|
| 554 |
+
This can be one of the following:
|
| 555 |
+
|
| 556 |
+
- *None*: Picking is disabled for this artist (default).
|
| 557 |
+
|
| 558 |
+
- A boolean: If *True* then picking will be enabled and the
|
| 559 |
+
artist will fire a pick event if the mouse event is over
|
| 560 |
+
the artist.
|
| 561 |
+
|
| 562 |
+
- A float: If picker is a number it is interpreted as an
|
| 563 |
+
epsilon tolerance in points and the artist will fire
|
| 564 |
+
off an event if its data is within epsilon of the mouse
|
| 565 |
+
event. For some artists like lines and patch collections,
|
| 566 |
+
the artist may provide additional data to the pick event
|
| 567 |
+
that is generated, e.g., the indices of the data within
|
| 568 |
+
epsilon of the pick event
|
| 569 |
+
|
| 570 |
+
- A function: If picker is callable, it is a user supplied
|
| 571 |
+
function which determines whether the artist is hit by the
|
| 572 |
+
mouse event::
|
| 573 |
+
|
| 574 |
+
hit, props = picker(artist, mouseevent)
|
| 575 |
+
|
| 576 |
+
to determine the hit test. if the mouse event is over the
|
| 577 |
+
artist, return *hit=True* and props is a dictionary of
|
| 578 |
+
properties you want added to the PickEvent attributes.
|
| 579 |
+
"""
|
| 580 |
+
self._picker = picker
|
| 581 |
+
|
| 582 |
+
def get_picker(self):
|
| 583 |
+
"""
|
| 584 |
+
Return the picking behavior of the artist.
|
| 585 |
+
|
| 586 |
+
The possible values are described in `.Artist.set_picker`.
|
| 587 |
+
|
| 588 |
+
See Also
|
| 589 |
+
--------
|
| 590 |
+
.Artist.set_picker, .Artist.pickable, .Artist.pick
|
| 591 |
+
"""
|
| 592 |
+
return self._picker
|
| 593 |
+
|
| 594 |
+
def get_url(self):
|
| 595 |
+
"""Return the url."""
|
| 596 |
+
return self._url
|
| 597 |
+
|
| 598 |
+
def set_url(self, url):
|
| 599 |
+
"""
|
| 600 |
+
Set the url for the artist.
|
| 601 |
+
|
| 602 |
+
Parameters
|
| 603 |
+
----------
|
| 604 |
+
url : str
|
| 605 |
+
"""
|
| 606 |
+
self._url = url
|
| 607 |
+
|
| 608 |
+
def get_gid(self):
|
| 609 |
+
"""Return the group id."""
|
| 610 |
+
return self._gid
|
| 611 |
+
|
| 612 |
+
def set_gid(self, gid):
|
| 613 |
+
"""
|
| 614 |
+
Set the (group) id for the artist.
|
| 615 |
+
|
| 616 |
+
Parameters
|
| 617 |
+
----------
|
| 618 |
+
gid : str
|
| 619 |
+
"""
|
| 620 |
+
self._gid = gid
|
| 621 |
+
|
| 622 |
+
def get_snap(self):
|
| 623 |
+
"""
|
| 624 |
+
Return the snap setting.
|
| 625 |
+
|
| 626 |
+
See `.set_snap` for details.
|
| 627 |
+
"""
|
| 628 |
+
if mpl.rcParams['path.snap']:
|
| 629 |
+
return self._snap
|
| 630 |
+
else:
|
| 631 |
+
return False
|
| 632 |
+
|
| 633 |
+
def set_snap(self, snap):
|
| 634 |
+
"""
|
| 635 |
+
Set the snapping behavior.
|
| 636 |
+
|
| 637 |
+
Snapping aligns positions with the pixel grid, which results in
|
| 638 |
+
clearer images. For example, if a black line of 1px width was
|
| 639 |
+
defined at a position in between two pixels, the resulting image
|
| 640 |
+
would contain the interpolated value of that line in the pixel grid,
|
| 641 |
+
which would be a grey value on both adjacent pixel positions. In
|
| 642 |
+
contrast, snapping will move the line to the nearest integer pixel
|
| 643 |
+
value, so that the resulting image will really contain a 1px wide
|
| 644 |
+
black line.
|
| 645 |
+
|
| 646 |
+
Snapping is currently only supported by the Agg and MacOSX backends.
|
| 647 |
+
|
| 648 |
+
Parameters
|
| 649 |
+
----------
|
| 650 |
+
snap : bool or None
|
| 651 |
+
Possible values:
|
| 652 |
+
|
| 653 |
+
- *True*: Snap vertices to the nearest pixel center.
|
| 654 |
+
- *False*: Do not modify vertex positions.
|
| 655 |
+
- *None*: (auto) If the path contains only rectilinear line
|
| 656 |
+
segments, round to the nearest pixel center.
|
| 657 |
+
"""
|
| 658 |
+
self._snap = snap
|
| 659 |
+
self.stale = True
|
| 660 |
+
|
| 661 |
+
def get_sketch_params(self):
|
| 662 |
+
"""
|
| 663 |
+
Return the sketch parameters for the artist.
|
| 664 |
+
|
| 665 |
+
Returns
|
| 666 |
+
-------
|
| 667 |
+
tuple or None
|
| 668 |
+
|
| 669 |
+
A 3-tuple with the following elements:
|
| 670 |
+
|
| 671 |
+
- *scale*: The amplitude of the wiggle perpendicular to the
|
| 672 |
+
source line.
|
| 673 |
+
- *length*: The length of the wiggle along the line.
|
| 674 |
+
- *randomness*: The scale factor by which the length is
|
| 675 |
+
shrunken or expanded.
|
| 676 |
+
|
| 677 |
+
Returns *None* if no sketch parameters were set.
|
| 678 |
+
"""
|
| 679 |
+
return self._sketch
|
| 680 |
+
|
| 681 |
+
def set_sketch_params(self, scale=None, length=None, randomness=None):
|
| 682 |
+
"""
|
| 683 |
+
Set the sketch parameters.
|
| 684 |
+
|
| 685 |
+
Parameters
|
| 686 |
+
----------
|
| 687 |
+
scale : float, optional
|
| 688 |
+
The amplitude of the wiggle perpendicular to the source
|
| 689 |
+
line, in pixels. If scale is `None`, or not provided, no
|
| 690 |
+
sketch filter will be provided.
|
| 691 |
+
length : float, optional
|
| 692 |
+
The length of the wiggle along the line, in pixels
|
| 693 |
+
(default 128.0)
|
| 694 |
+
randomness : float, optional
|
| 695 |
+
The scale factor by which the length is shrunken or
|
| 696 |
+
expanded (default 16.0)
|
| 697 |
+
|
| 698 |
+
The PGF backend uses this argument as an RNG seed and not as
|
| 699 |
+
described above. Using the same seed yields the same random shape.
|
| 700 |
+
|
| 701 |
+
.. ACCEPTS: (scale: float, length: float, randomness: float)
|
| 702 |
+
"""
|
| 703 |
+
if scale is None:
|
| 704 |
+
self._sketch = None
|
| 705 |
+
else:
|
| 706 |
+
self._sketch = (scale, length or 128.0, randomness or 16.0)
|
| 707 |
+
self.stale = True
|
| 708 |
+
|
| 709 |
+
def set_path_effects(self, path_effects):
|
| 710 |
+
"""
|
| 711 |
+
Set the path effects.
|
| 712 |
+
|
| 713 |
+
Parameters
|
| 714 |
+
----------
|
| 715 |
+
path_effects : list of `.AbstractPathEffect`
|
| 716 |
+
"""
|
| 717 |
+
self._path_effects = path_effects
|
| 718 |
+
self.stale = True
|
| 719 |
+
|
| 720 |
+
def get_path_effects(self):
|
| 721 |
+
return self._path_effects
|
| 722 |
+
|
| 723 |
+
def get_figure(self, root=False):
|
| 724 |
+
"""
|
| 725 |
+
Return the `.Figure` or `.SubFigure` instance the artist belongs to.
|
| 726 |
+
|
| 727 |
+
Parameters
|
| 728 |
+
----------
|
| 729 |
+
root : bool, default=False
|
| 730 |
+
If False, return the (Sub)Figure this artist is on. If True,
|
| 731 |
+
return the root Figure for a nested tree of SubFigures.
|
| 732 |
+
"""
|
| 733 |
+
if root and self._parent_figure is not None:
|
| 734 |
+
return self._parent_figure.get_figure(root=True)
|
| 735 |
+
|
| 736 |
+
return self._parent_figure
|
| 737 |
+
|
| 738 |
+
def set_figure(self, fig):
|
| 739 |
+
"""
|
| 740 |
+
Set the `.Figure` or `.SubFigure` instance the artist belongs to.
|
| 741 |
+
|
| 742 |
+
Parameters
|
| 743 |
+
----------
|
| 744 |
+
fig : `~matplotlib.figure.Figure` or `~matplotlib.figure.SubFigure`
|
| 745 |
+
"""
|
| 746 |
+
# if this is a no-op just return
|
| 747 |
+
if self._parent_figure is fig:
|
| 748 |
+
return
|
| 749 |
+
# if we currently have a figure (the case of both `self.figure`
|
| 750 |
+
# and *fig* being none is taken care of above) we then user is
|
| 751 |
+
# trying to change the figure an artist is associated with which
|
| 752 |
+
# is not allowed for the same reason as adding the same instance
|
| 753 |
+
# to more than one Axes
|
| 754 |
+
if self._parent_figure is not None:
|
| 755 |
+
raise RuntimeError("Can not put single artist in "
|
| 756 |
+
"more than one figure")
|
| 757 |
+
self._parent_figure = fig
|
| 758 |
+
if self._parent_figure and self._parent_figure is not self:
|
| 759 |
+
self.pchanged()
|
| 760 |
+
self.stale = True
|
| 761 |
+
|
| 762 |
+
figure = property(get_figure, set_figure,
|
| 763 |
+
doc=("The (Sub)Figure that the artist is on. For more "
|
| 764 |
+
"control, use the `get_figure` method."))
|
| 765 |
+
|
| 766 |
+
def set_clip_box(self, clipbox):
|
| 767 |
+
"""
|
| 768 |
+
Set the artist's clip `.Bbox`.
|
| 769 |
+
|
| 770 |
+
Parameters
|
| 771 |
+
----------
|
| 772 |
+
clipbox : `~matplotlib.transforms.BboxBase` or None
|
| 773 |
+
Will typically be created from a `.TransformedBbox`. For instance,
|
| 774 |
+
``TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes)`` is the default
|
| 775 |
+
clipping for an artist added to an Axes.
|
| 776 |
+
|
| 777 |
+
"""
|
| 778 |
+
_api.check_isinstance((BboxBase, None), clipbox=clipbox)
|
| 779 |
+
if clipbox != self.clipbox:
|
| 780 |
+
self.clipbox = clipbox
|
| 781 |
+
self.pchanged()
|
| 782 |
+
self.stale = True
|
| 783 |
+
|
| 784 |
+
def set_clip_path(self, path, transform=None):
|
| 785 |
+
"""
|
| 786 |
+
Set the artist's clip path.
|
| 787 |
+
|
| 788 |
+
Parameters
|
| 789 |
+
----------
|
| 790 |
+
path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath` or None
|
| 791 |
+
The clip path. If given a `.Path`, *transform* must be provided as
|
| 792 |
+
well. If *None*, a previously set clip path is removed.
|
| 793 |
+
transform : `~matplotlib.transforms.Transform`, optional
|
| 794 |
+
Only used if *path* is a `.Path`, in which case the given `.Path`
|
| 795 |
+
is converted to a `.TransformedPath` using *transform*.
|
| 796 |
+
|
| 797 |
+
Notes
|
| 798 |
+
-----
|
| 799 |
+
For efficiency, if *path* is a `.Rectangle` this method will set the
|
| 800 |
+
clipping box to the corresponding rectangle and set the clipping path
|
| 801 |
+
to ``None``.
|
| 802 |
+
|
| 803 |
+
For technical reasons (support of `~.Artist.set`), a tuple
|
| 804 |
+
(*path*, *transform*) is also accepted as a single positional
|
| 805 |
+
parameter.
|
| 806 |
+
|
| 807 |
+
.. ACCEPTS: Patch or (Path, Transform) or None
|
| 808 |
+
"""
|
| 809 |
+
from matplotlib.patches import Patch, Rectangle
|
| 810 |
+
|
| 811 |
+
success = False
|
| 812 |
+
if transform is None:
|
| 813 |
+
if isinstance(path, Rectangle):
|
| 814 |
+
self.clipbox = TransformedBbox(Bbox.unit(),
|
| 815 |
+
path.get_transform())
|
| 816 |
+
self._clippath = None
|
| 817 |
+
success = True
|
| 818 |
+
elif isinstance(path, Patch):
|
| 819 |
+
self._clippath = TransformedPatchPath(path)
|
| 820 |
+
success = True
|
| 821 |
+
elif isinstance(path, tuple):
|
| 822 |
+
path, transform = path
|
| 823 |
+
|
| 824 |
+
if path is None:
|
| 825 |
+
self._clippath = None
|
| 826 |
+
success = True
|
| 827 |
+
elif isinstance(path, Path):
|
| 828 |
+
self._clippath = TransformedPath(path, transform)
|
| 829 |
+
success = True
|
| 830 |
+
elif isinstance(path, TransformedPatchPath):
|
| 831 |
+
self._clippath = path
|
| 832 |
+
success = True
|
| 833 |
+
elif isinstance(path, TransformedPath):
|
| 834 |
+
self._clippath = path
|
| 835 |
+
success = True
|
| 836 |
+
|
| 837 |
+
if not success:
|
| 838 |
+
raise TypeError(
|
| 839 |
+
"Invalid arguments to set_clip_path, of type "
|
| 840 |
+
f"{type(path).__name__} and {type(transform).__name__}")
|
| 841 |
+
# This may result in the callbacks being hit twice, but guarantees they
|
| 842 |
+
# will be hit at least once.
|
| 843 |
+
self.pchanged()
|
| 844 |
+
self.stale = True
|
| 845 |
+
|
| 846 |
+
def get_alpha(self):
|
| 847 |
+
"""
|
| 848 |
+
Return the alpha value used for blending - not supported on all
|
| 849 |
+
backends.
|
| 850 |
+
"""
|
| 851 |
+
return self._alpha
|
| 852 |
+
|
| 853 |
+
def get_visible(self):
|
| 854 |
+
"""Return the visibility."""
|
| 855 |
+
return self._visible
|
| 856 |
+
|
| 857 |
+
def get_animated(self):
|
| 858 |
+
"""Return whether the artist is animated."""
|
| 859 |
+
return self._animated
|
| 860 |
+
|
| 861 |
+
def get_in_layout(self):
|
| 862 |
+
"""
|
| 863 |
+
Return boolean flag, ``True`` if artist is included in layout
|
| 864 |
+
calculations.
|
| 865 |
+
|
| 866 |
+
E.g. :ref:`constrainedlayout_guide`,
|
| 867 |
+
`.Figure.tight_layout()`, and
|
| 868 |
+
``fig.savefig(fname, bbox_inches='tight')``.
|
| 869 |
+
"""
|
| 870 |
+
return self._in_layout
|
| 871 |
+
|
| 872 |
+
def _fully_clipped_to_axes(self):
|
| 873 |
+
"""
|
| 874 |
+
Return a boolean flag, ``True`` if the artist is clipped to the Axes
|
| 875 |
+
and can thus be skipped in layout calculations. Requires `get_clip_on`
|
| 876 |
+
is True, one of `clip_box` or `clip_path` is set, ``clip_box.extents``
|
| 877 |
+
is equivalent to ``ax.bbox.extents`` (if set), and ``clip_path._patch``
|
| 878 |
+
is equivalent to ``ax.patch`` (if set).
|
| 879 |
+
"""
|
| 880 |
+
# Note that ``clip_path.get_fully_transformed_path().get_extents()``
|
| 881 |
+
# cannot be directly compared to ``axes.bbox.extents`` because the
|
| 882 |
+
# extents may be undefined (i.e. equivalent to ``Bbox.null()``)
|
| 883 |
+
# before the associated artist is drawn, and this method is meant
|
| 884 |
+
# to determine whether ``axes.get_tightbbox()`` may bypass drawing
|
| 885 |
+
clip_box = self.get_clip_box()
|
| 886 |
+
clip_path = self.get_clip_path()
|
| 887 |
+
return (self.axes is not None
|
| 888 |
+
and self.get_clip_on()
|
| 889 |
+
and (clip_box is not None or clip_path is not None)
|
| 890 |
+
and (clip_box is None
|
| 891 |
+
or np.all(clip_box.extents == self.axes.bbox.extents))
|
| 892 |
+
and (clip_path is None
|
| 893 |
+
or isinstance(clip_path, TransformedPatchPath)
|
| 894 |
+
and clip_path._patch is self.axes.patch))
|
| 895 |
+
|
| 896 |
+
def get_clip_on(self):
|
| 897 |
+
"""Return whether the artist uses clipping."""
|
| 898 |
+
return self._clipon
|
| 899 |
+
|
| 900 |
+
def get_clip_box(self):
|
| 901 |
+
"""Return the clipbox."""
|
| 902 |
+
return self.clipbox
|
| 903 |
+
|
| 904 |
+
def get_clip_path(self):
|
| 905 |
+
"""Return the clip path."""
|
| 906 |
+
return self._clippath
|
| 907 |
+
|
| 908 |
+
def get_transformed_clip_path_and_affine(self):
|
| 909 |
+
"""
|
| 910 |
+
Return the clip path with the non-affine part of its
|
| 911 |
+
transformation applied, and the remaining affine part of its
|
| 912 |
+
transformation.
|
| 913 |
+
"""
|
| 914 |
+
if self._clippath is not None:
|
| 915 |
+
return self._clippath.get_transformed_path_and_affine()
|
| 916 |
+
return None, None
|
| 917 |
+
|
| 918 |
+
def set_clip_on(self, b):
|
| 919 |
+
"""
|
| 920 |
+
Set whether the artist uses clipping.
|
| 921 |
+
|
| 922 |
+
When False, artists will be visible outside the Axes which
|
| 923 |
+
can lead to unexpected results.
|
| 924 |
+
|
| 925 |
+
Parameters
|
| 926 |
+
----------
|
| 927 |
+
b : bool
|
| 928 |
+
"""
|
| 929 |
+
self._clipon = b
|
| 930 |
+
# This may result in the callbacks being hit twice, but ensures they
|
| 931 |
+
# are hit at least once
|
| 932 |
+
self.pchanged()
|
| 933 |
+
self.stale = True
|
| 934 |
+
|
| 935 |
+
def _set_gc_clip(self, gc):
|
| 936 |
+
"""Set the clip properly for the gc."""
|
| 937 |
+
if self._clipon:
|
| 938 |
+
if self.clipbox is not None:
|
| 939 |
+
gc.set_clip_rectangle(self.clipbox)
|
| 940 |
+
gc.set_clip_path(self._clippath)
|
| 941 |
+
else:
|
| 942 |
+
gc.set_clip_rectangle(None)
|
| 943 |
+
gc.set_clip_path(None)
|
| 944 |
+
|
| 945 |
+
def get_rasterized(self):
|
| 946 |
+
"""Return whether the artist is to be rasterized."""
|
| 947 |
+
return self._rasterized
|
| 948 |
+
|
| 949 |
+
def set_rasterized(self, rasterized):
|
| 950 |
+
"""
|
| 951 |
+
Force rasterized (bitmap) drawing for vector graphics output.
|
| 952 |
+
|
| 953 |
+
Rasterized drawing is not supported by all artists. If you try to
|
| 954 |
+
enable this on an artist that does not support it, the command has no
|
| 955 |
+
effect and a warning will be issued.
|
| 956 |
+
|
| 957 |
+
This setting is ignored for pixel-based output.
|
| 958 |
+
|
| 959 |
+
See also :doc:`/gallery/misc/rasterization_demo`.
|
| 960 |
+
|
| 961 |
+
Parameters
|
| 962 |
+
----------
|
| 963 |
+
rasterized : bool
|
| 964 |
+
"""
|
| 965 |
+
supports_rasterization = getattr(self.draw,
|
| 966 |
+
"_supports_rasterization", False)
|
| 967 |
+
if rasterized and not supports_rasterization:
|
| 968 |
+
_api.warn_external(f"Rasterization of '{self}' will be ignored")
|
| 969 |
+
|
| 970 |
+
self._rasterized = rasterized
|
| 971 |
+
|
| 972 |
+
def get_agg_filter(self):
|
| 973 |
+
"""Return filter function to be used for agg filter."""
|
| 974 |
+
return self._agg_filter
|
| 975 |
+
|
| 976 |
+
def set_agg_filter(self, filter_func):
|
| 977 |
+
"""
|
| 978 |
+
Set the agg filter.
|
| 979 |
+
|
| 980 |
+
Parameters
|
| 981 |
+
----------
|
| 982 |
+
filter_func : callable
|
| 983 |
+
A filter function, which takes a (m, n, depth) float array
|
| 984 |
+
and a dpi value, and returns a (m, n, depth) array and two
|
| 985 |
+
offsets from the bottom left corner of the image
|
| 986 |
+
|
| 987 |
+
.. ACCEPTS: a filter function, which takes a (m, n, 3) float array
|
| 988 |
+
and a dpi value, and returns a (m, n, 3) array and two offsets
|
| 989 |
+
from the bottom left corner of the image
|
| 990 |
+
"""
|
| 991 |
+
self._agg_filter = filter_func
|
| 992 |
+
self.stale = True
|
| 993 |
+
|
| 994 |
+
def draw(self, renderer):
|
| 995 |
+
"""
|
| 996 |
+
Draw the Artist (and its children) using the given renderer.
|
| 997 |
+
|
| 998 |
+
This has no effect if the artist is not visible (`.Artist.get_visible`
|
| 999 |
+
returns False).
|
| 1000 |
+
|
| 1001 |
+
Parameters
|
| 1002 |
+
----------
|
| 1003 |
+
renderer : `~matplotlib.backend_bases.RendererBase` subclass.
|
| 1004 |
+
|
| 1005 |
+
Notes
|
| 1006 |
+
-----
|
| 1007 |
+
This method is overridden in the Artist subclasses.
|
| 1008 |
+
"""
|
| 1009 |
+
if not self.get_visible():
|
| 1010 |
+
return
|
| 1011 |
+
self.stale = False
|
| 1012 |
+
|
| 1013 |
+
def set_alpha(self, alpha):
|
| 1014 |
+
"""
|
| 1015 |
+
Set the alpha value used for blending - not supported on all backends.
|
| 1016 |
+
|
| 1017 |
+
Parameters
|
| 1018 |
+
----------
|
| 1019 |
+
alpha : scalar or None
|
| 1020 |
+
*alpha* must be within the 0-1 range, inclusive.
|
| 1021 |
+
"""
|
| 1022 |
+
if alpha is not None and not isinstance(alpha, Real):
|
| 1023 |
+
raise TypeError(
|
| 1024 |
+
f'alpha must be numeric or None, not {type(alpha)}')
|
| 1025 |
+
if alpha is not None and not (0 <= alpha <= 1):
|
| 1026 |
+
raise ValueError(f'alpha ({alpha}) is outside 0-1 range')
|
| 1027 |
+
if alpha != self._alpha:
|
| 1028 |
+
self._alpha = alpha
|
| 1029 |
+
self.pchanged()
|
| 1030 |
+
self.stale = True
|
| 1031 |
+
|
| 1032 |
+
def _set_alpha_for_array(self, alpha):
|
| 1033 |
+
"""
|
| 1034 |
+
Set the alpha value used for blending - not supported on all backends.
|
| 1035 |
+
|
| 1036 |
+
Parameters
|
| 1037 |
+
----------
|
| 1038 |
+
alpha : array-like or scalar or None
|
| 1039 |
+
All values must be within the 0-1 range, inclusive.
|
| 1040 |
+
Masked values and nans are not supported.
|
| 1041 |
+
"""
|
| 1042 |
+
if isinstance(alpha, str):
|
| 1043 |
+
raise TypeError("alpha must be numeric or None, not a string")
|
| 1044 |
+
if not np.iterable(alpha):
|
| 1045 |
+
Artist.set_alpha(self, alpha)
|
| 1046 |
+
return
|
| 1047 |
+
alpha = np.asarray(alpha)
|
| 1048 |
+
if not (0 <= alpha.min() and alpha.max() <= 1):
|
| 1049 |
+
raise ValueError('alpha must be between 0 and 1, inclusive, '
|
| 1050 |
+
f'but min is {alpha.min()}, max is {alpha.max()}')
|
| 1051 |
+
self._alpha = alpha
|
| 1052 |
+
self.pchanged()
|
| 1053 |
+
self.stale = True
|
| 1054 |
+
|
| 1055 |
+
def set_visible(self, b):
|
| 1056 |
+
"""
|
| 1057 |
+
Set the artist's visibility.
|
| 1058 |
+
|
| 1059 |
+
Parameters
|
| 1060 |
+
----------
|
| 1061 |
+
b : bool
|
| 1062 |
+
"""
|
| 1063 |
+
if b != self._visible:
|
| 1064 |
+
self._visible = b
|
| 1065 |
+
self.pchanged()
|
| 1066 |
+
self.stale = True
|
| 1067 |
+
|
| 1068 |
+
def set_animated(self, b):
|
| 1069 |
+
"""
|
| 1070 |
+
Set whether the artist is intended to be used in an animation.
|
| 1071 |
+
|
| 1072 |
+
If True, the artist is excluded from regular drawing of the figure.
|
| 1073 |
+
You have to call `.Figure.draw_artist` / `.Axes.draw_artist`
|
| 1074 |
+
explicitly on the artist. This approach is used to speed up animations
|
| 1075 |
+
using blitting.
|
| 1076 |
+
|
| 1077 |
+
See also `matplotlib.animation` and
|
| 1078 |
+
:ref:`blitting`.
|
| 1079 |
+
|
| 1080 |
+
Parameters
|
| 1081 |
+
----------
|
| 1082 |
+
b : bool
|
| 1083 |
+
"""
|
| 1084 |
+
if self._animated != b:
|
| 1085 |
+
self._animated = b
|
| 1086 |
+
self.pchanged()
|
| 1087 |
+
|
| 1088 |
+
def set_in_layout(self, in_layout):
|
| 1089 |
+
"""
|
| 1090 |
+
Set if artist is to be included in layout calculations,
|
| 1091 |
+
E.g. :ref:`constrainedlayout_guide`,
|
| 1092 |
+
`.Figure.tight_layout()`, and
|
| 1093 |
+
``fig.savefig(fname, bbox_inches='tight')``.
|
| 1094 |
+
|
| 1095 |
+
Parameters
|
| 1096 |
+
----------
|
| 1097 |
+
in_layout : bool
|
| 1098 |
+
"""
|
| 1099 |
+
self._in_layout = in_layout
|
| 1100 |
+
|
| 1101 |
+
def get_label(self):
|
| 1102 |
+
"""Return the label used for this artist in the legend."""
|
| 1103 |
+
return self._label
|
| 1104 |
+
|
| 1105 |
+
def set_label(self, s):
|
| 1106 |
+
"""
|
| 1107 |
+
Set a label that will be displayed in the legend.
|
| 1108 |
+
|
| 1109 |
+
Parameters
|
| 1110 |
+
----------
|
| 1111 |
+
s : object
|
| 1112 |
+
*s* will be converted to a string by calling `str`.
|
| 1113 |
+
"""
|
| 1114 |
+
label = str(s) if s is not None else None
|
| 1115 |
+
if label != self._label:
|
| 1116 |
+
self._label = label
|
| 1117 |
+
self.pchanged()
|
| 1118 |
+
self.stale = True
|
| 1119 |
+
|
| 1120 |
+
def get_zorder(self):
|
| 1121 |
+
"""Return the artist's zorder."""
|
| 1122 |
+
return self.zorder
|
| 1123 |
+
|
| 1124 |
+
def set_zorder(self, level):
|
| 1125 |
+
"""
|
| 1126 |
+
Set the zorder for the artist. Artists with lower zorder
|
| 1127 |
+
values are drawn first.
|
| 1128 |
+
|
| 1129 |
+
Parameters
|
| 1130 |
+
----------
|
| 1131 |
+
level : float
|
| 1132 |
+
"""
|
| 1133 |
+
if level is None:
|
| 1134 |
+
level = self.__class__.zorder
|
| 1135 |
+
if level != self.zorder:
|
| 1136 |
+
self.zorder = level
|
| 1137 |
+
self.pchanged()
|
| 1138 |
+
self.stale = True
|
| 1139 |
+
|
| 1140 |
+
@property
|
| 1141 |
+
def sticky_edges(self):
|
| 1142 |
+
"""
|
| 1143 |
+
``x`` and ``y`` sticky edge lists for autoscaling.
|
| 1144 |
+
|
| 1145 |
+
When performing autoscaling, if a data limit coincides with a value in
|
| 1146 |
+
the corresponding sticky_edges list, then no margin will be added--the
|
| 1147 |
+
view limit "sticks" to the edge. A typical use case is histograms,
|
| 1148 |
+
where one usually expects no margin on the bottom edge (0) of the
|
| 1149 |
+
histogram.
|
| 1150 |
+
|
| 1151 |
+
Moreover, margin expansion "bumps" against sticky edges and cannot
|
| 1152 |
+
cross them. For example, if the upper data limit is 1.0, the upper
|
| 1153 |
+
view limit computed by simple margin application is 1.2, but there is a
|
| 1154 |
+
sticky edge at 1.1, then the actual upper view limit will be 1.1.
|
| 1155 |
+
|
| 1156 |
+
This attribute cannot be assigned to; however, the ``x`` and ``y``
|
| 1157 |
+
lists can be modified in place as needed.
|
| 1158 |
+
|
| 1159 |
+
Examples
|
| 1160 |
+
--------
|
| 1161 |
+
>>> artist.sticky_edges.x[:] = (xmin, xmax)
|
| 1162 |
+
>>> artist.sticky_edges.y[:] = (ymin, ymax)
|
| 1163 |
+
|
| 1164 |
+
"""
|
| 1165 |
+
return self._sticky_edges
|
| 1166 |
+
|
| 1167 |
+
def update_from(self, other):
|
| 1168 |
+
"""Copy properties from *other* to *self*."""
|
| 1169 |
+
self._transform = other._transform
|
| 1170 |
+
self._transformSet = other._transformSet
|
| 1171 |
+
self._visible = other._visible
|
| 1172 |
+
self._alpha = other._alpha
|
| 1173 |
+
self.clipbox = other.clipbox
|
| 1174 |
+
self._clipon = other._clipon
|
| 1175 |
+
self._clippath = other._clippath
|
| 1176 |
+
self._label = other._label
|
| 1177 |
+
self._sketch = other._sketch
|
| 1178 |
+
self._path_effects = other._path_effects
|
| 1179 |
+
self.sticky_edges.x[:] = other.sticky_edges.x.copy()
|
| 1180 |
+
self.sticky_edges.y[:] = other.sticky_edges.y.copy()
|
| 1181 |
+
self.pchanged()
|
| 1182 |
+
self.stale = True
|
| 1183 |
+
|
| 1184 |
+
def properties(self):
|
| 1185 |
+
"""Return a dictionary of all the properties of the artist."""
|
| 1186 |
+
return ArtistInspector(self).properties()
|
| 1187 |
+
|
| 1188 |
+
def _update_props(self, props, errfmt):
|
| 1189 |
+
"""
|
| 1190 |
+
Helper for `.Artist.set` and `.Artist.update`.
|
| 1191 |
+
|
| 1192 |
+
*errfmt* is used to generate error messages for invalid property
|
| 1193 |
+
names; it gets formatted with ``type(self)`` for "{cls}" and the
|
| 1194 |
+
property name for "{prop_name}".
|
| 1195 |
+
"""
|
| 1196 |
+
ret = []
|
| 1197 |
+
with cbook._setattr_cm(self, eventson=False):
|
| 1198 |
+
for k, v in props.items():
|
| 1199 |
+
# Allow attributes we want to be able to update through
|
| 1200 |
+
# art.update, art.set, setp.
|
| 1201 |
+
if k == "axes":
|
| 1202 |
+
ret.append(setattr(self, k, v))
|
| 1203 |
+
else:
|
| 1204 |
+
func = getattr(self, f"set_{k}", None)
|
| 1205 |
+
if not callable(func):
|
| 1206 |
+
raise AttributeError(
|
| 1207 |
+
errfmt.format(cls=type(self), prop_name=k),
|
| 1208 |
+
name=k)
|
| 1209 |
+
ret.append(func(v))
|
| 1210 |
+
if ret:
|
| 1211 |
+
self.pchanged()
|
| 1212 |
+
self.stale = True
|
| 1213 |
+
return ret
|
| 1214 |
+
|
| 1215 |
+
def update(self, props):
|
| 1216 |
+
"""
|
| 1217 |
+
Update this artist's properties from the dict *props*.
|
| 1218 |
+
|
| 1219 |
+
Parameters
|
| 1220 |
+
----------
|
| 1221 |
+
props : dict
|
| 1222 |
+
"""
|
| 1223 |
+
return self._update_props(
|
| 1224 |
+
props, "{cls.__name__!r} object has no property {prop_name!r}")
|
| 1225 |
+
|
| 1226 |
+
def _internal_update(self, kwargs):
|
| 1227 |
+
"""
|
| 1228 |
+
Update artist properties without prenormalizing them, but generating
|
| 1229 |
+
errors as if calling `set`.
|
| 1230 |
+
|
| 1231 |
+
The lack of prenormalization is to maintain backcompatibility.
|
| 1232 |
+
"""
|
| 1233 |
+
return self._update_props(
|
| 1234 |
+
kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
|
| 1235 |
+
"{prop_name!r}")
|
| 1236 |
+
|
| 1237 |
+
def set(self, **kwargs):
|
| 1238 |
+
# docstring and signature are auto-generated via
|
| 1239 |
+
# Artist._update_set_signature_and_docstring() at the end of the
|
| 1240 |
+
# module.
|
| 1241 |
+
return self._internal_update(cbook.normalize_kwargs(kwargs, self))
|
| 1242 |
+
|
| 1243 |
+
@contextlib.contextmanager
|
| 1244 |
+
def _cm_set(self, **kwargs):
|
| 1245 |
+
"""
|
| 1246 |
+
`.Artist.set` context-manager that restores original values at exit.
|
| 1247 |
+
"""
|
| 1248 |
+
orig_vals = {k: getattr(self, f"get_{k}")() for k in kwargs}
|
| 1249 |
+
try:
|
| 1250 |
+
self.set(**kwargs)
|
| 1251 |
+
yield
|
| 1252 |
+
finally:
|
| 1253 |
+
self.set(**orig_vals)
|
| 1254 |
+
|
| 1255 |
+
def findobj(self, match=None, include_self=True):
|
| 1256 |
+
"""
|
| 1257 |
+
Find artist objects.
|
| 1258 |
+
|
| 1259 |
+
Recursively find all `.Artist` instances contained in the artist.
|
| 1260 |
+
|
| 1261 |
+
Parameters
|
| 1262 |
+
----------
|
| 1263 |
+
match
|
| 1264 |
+
A filter criterion for the matches. This can be
|
| 1265 |
+
|
| 1266 |
+
- *None*: Return all objects contained in artist.
|
| 1267 |
+
- A function with signature ``def match(artist: Artist) -> bool``.
|
| 1268 |
+
The result will only contain artists for which the function
|
| 1269 |
+
returns *True*.
|
| 1270 |
+
- A class instance: e.g., `.Line2D`. The result will only contain
|
| 1271 |
+
artists of this class or its subclasses (``isinstance`` check).
|
| 1272 |
+
|
| 1273 |
+
include_self : bool
|
| 1274 |
+
Include *self* in the list to be checked for a match.
|
| 1275 |
+
|
| 1276 |
+
Returns
|
| 1277 |
+
-------
|
| 1278 |
+
list of `.Artist`
|
| 1279 |
+
|
| 1280 |
+
"""
|
| 1281 |
+
if match is None: # always return True
|
| 1282 |
+
def matchfunc(x):
|
| 1283 |
+
return True
|
| 1284 |
+
elif isinstance(match, type) and issubclass(match, Artist):
|
| 1285 |
+
def matchfunc(x):
|
| 1286 |
+
return isinstance(x, match)
|
| 1287 |
+
elif callable(match):
|
| 1288 |
+
matchfunc = match
|
| 1289 |
+
else:
|
| 1290 |
+
raise ValueError('match must be None, a matplotlib.artist.Artist '
|
| 1291 |
+
'subclass, or a callable')
|
| 1292 |
+
|
| 1293 |
+
artists = reduce(operator.iadd,
|
| 1294 |
+
[c.findobj(matchfunc) for c in self.get_children()], [])
|
| 1295 |
+
if include_self and matchfunc(self):
|
| 1296 |
+
artists.append(self)
|
| 1297 |
+
return artists
|
| 1298 |
+
|
| 1299 |
+
def get_cursor_data(self, event):
|
| 1300 |
+
"""
|
| 1301 |
+
Return the cursor data for a given event.
|
| 1302 |
+
|
| 1303 |
+
.. note::
|
| 1304 |
+
This method is intended to be overridden by artist subclasses.
|
| 1305 |
+
As an end-user of Matplotlib you will most likely not call this
|
| 1306 |
+
method yourself.
|
| 1307 |
+
|
| 1308 |
+
Cursor data can be used by Artists to provide additional context
|
| 1309 |
+
information for a given event. The default implementation just returns
|
| 1310 |
+
*None*.
|
| 1311 |
+
|
| 1312 |
+
Subclasses can override the method and return arbitrary data. However,
|
| 1313 |
+
when doing so, they must ensure that `.format_cursor_data` can convert
|
| 1314 |
+
the data to a string representation.
|
| 1315 |
+
|
| 1316 |
+
The only current use case is displaying the z-value of an `.AxesImage`
|
| 1317 |
+
in the status bar of a plot window, while moving the mouse.
|
| 1318 |
+
|
| 1319 |
+
Parameters
|
| 1320 |
+
----------
|
| 1321 |
+
event : `~matplotlib.backend_bases.MouseEvent`
|
| 1322 |
+
|
| 1323 |
+
See Also
|
| 1324 |
+
--------
|
| 1325 |
+
format_cursor_data
|
| 1326 |
+
|
| 1327 |
+
"""
|
| 1328 |
+
return None
|
| 1329 |
+
|
| 1330 |
+
def format_cursor_data(self, data):
|
| 1331 |
+
"""
|
| 1332 |
+
Return a string representation of *data*.
|
| 1333 |
+
|
| 1334 |
+
.. note::
|
| 1335 |
+
This method is intended to be overridden by artist subclasses.
|
| 1336 |
+
As an end-user of Matplotlib you will most likely not call this
|
| 1337 |
+
method yourself.
|
| 1338 |
+
|
| 1339 |
+
The default implementation converts ints and floats and arrays of ints
|
| 1340 |
+
and floats into a comma-separated string enclosed in square brackets,
|
| 1341 |
+
unless the artist has an associated colorbar, in which case scalar
|
| 1342 |
+
values are formatted using the colorbar's formatter.
|
| 1343 |
+
|
| 1344 |
+
See Also
|
| 1345 |
+
--------
|
| 1346 |
+
get_cursor_data
|
| 1347 |
+
"""
|
| 1348 |
+
if np.ndim(data) == 0 and hasattr(self, "_format_cursor_data_override"):
|
| 1349 |
+
# workaround for ScalarMappable to be able to define its own
|
| 1350 |
+
# format_cursor_data(). See ScalarMappable._format_cursor_data_override
|
| 1351 |
+
# for details.
|
| 1352 |
+
return self._format_cursor_data_override(data)
|
| 1353 |
+
else:
|
| 1354 |
+
try:
|
| 1355 |
+
data[0]
|
| 1356 |
+
except (TypeError, IndexError):
|
| 1357 |
+
data = [data]
|
| 1358 |
+
data_str = ', '.join(f'{item:0.3g}' for item in data
|
| 1359 |
+
if isinstance(item, Number))
|
| 1360 |
+
return "[" + data_str + "]"
|
| 1361 |
+
|
| 1362 |
+
def get_mouseover(self):
|
| 1363 |
+
"""
|
| 1364 |
+
Return whether this artist is queried for custom context information
|
| 1365 |
+
when the mouse cursor moves over it.
|
| 1366 |
+
"""
|
| 1367 |
+
return self._mouseover
|
| 1368 |
+
|
| 1369 |
+
def set_mouseover(self, mouseover):
|
| 1370 |
+
"""
|
| 1371 |
+
Set whether this artist is queried for custom context information when
|
| 1372 |
+
the mouse cursor moves over it.
|
| 1373 |
+
|
| 1374 |
+
Parameters
|
| 1375 |
+
----------
|
| 1376 |
+
mouseover : bool
|
| 1377 |
+
|
| 1378 |
+
See Also
|
| 1379 |
+
--------
|
| 1380 |
+
get_cursor_data
|
| 1381 |
+
.ToolCursorPosition
|
| 1382 |
+
.NavigationToolbar2
|
| 1383 |
+
"""
|
| 1384 |
+
self._mouseover = bool(mouseover)
|
| 1385 |
+
ax = self.axes
|
| 1386 |
+
if ax:
|
| 1387 |
+
if self._mouseover:
|
| 1388 |
+
ax._mouseover_set.add(self)
|
| 1389 |
+
else:
|
| 1390 |
+
ax._mouseover_set.discard(self)
|
| 1391 |
+
|
| 1392 |
+
mouseover = property(get_mouseover, set_mouseover) # backcompat.
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
def _get_tightbbox_for_layout_only(obj, *args, **kwargs):
|
| 1396 |
+
"""
|
| 1397 |
+
Matplotlib's `.Axes.get_tightbbox` and `.Axis.get_tightbbox` support a
|
| 1398 |
+
*for_layout_only* kwarg; this helper tries to use the kwarg but skips it
|
| 1399 |
+
when encountering third-party subclasses that do not support it.
|
| 1400 |
+
"""
|
| 1401 |
+
try:
|
| 1402 |
+
return obj.get_tightbbox(*args, **{**kwargs, "for_layout_only": True})
|
| 1403 |
+
except TypeError:
|
| 1404 |
+
return obj.get_tightbbox(*args, **kwargs)
|
| 1405 |
+
|
| 1406 |
+
|
| 1407 |
+
class ArtistInspector:
|
| 1408 |
+
"""
|
| 1409 |
+
A helper class to inspect an `~matplotlib.artist.Artist` and return
|
| 1410 |
+
information about its settable properties and their current values.
|
| 1411 |
+
"""
|
| 1412 |
+
|
| 1413 |
+
def __init__(self, o):
|
| 1414 |
+
r"""
|
| 1415 |
+
Initialize the artist inspector with an `Artist` or an iterable of
|
| 1416 |
+
`Artist`\s. If an iterable is used, we assume it is a homogeneous
|
| 1417 |
+
sequence (all `Artist`\s are of the same type) and it is your
|
| 1418 |
+
responsibility to make sure this is so.
|
| 1419 |
+
"""
|
| 1420 |
+
if not isinstance(o, Artist):
|
| 1421 |
+
if np.iterable(o):
|
| 1422 |
+
o = list(o)
|
| 1423 |
+
if len(o):
|
| 1424 |
+
o = o[0]
|
| 1425 |
+
|
| 1426 |
+
self.oorig = o
|
| 1427 |
+
if not isinstance(o, type):
|
| 1428 |
+
o = type(o)
|
| 1429 |
+
self.o = o
|
| 1430 |
+
|
| 1431 |
+
self.aliasd = self.get_aliases()
|
| 1432 |
+
|
| 1433 |
+
def get_aliases(self):
|
| 1434 |
+
"""
|
| 1435 |
+
Get a dict mapping property fullnames to sets of aliases for each alias
|
| 1436 |
+
in the :class:`~matplotlib.artist.ArtistInspector`.
|
| 1437 |
+
|
| 1438 |
+
e.g., for lines::
|
| 1439 |
+
|
| 1440 |
+
{'markerfacecolor': {'mfc'},
|
| 1441 |
+
'linewidth' : {'lw'},
|
| 1442 |
+
}
|
| 1443 |
+
"""
|
| 1444 |
+
names = [name for name in dir(self.o)
|
| 1445 |
+
if name.startswith(('set_', 'get_'))
|
| 1446 |
+
and callable(getattr(self.o, name))]
|
| 1447 |
+
aliases = {}
|
| 1448 |
+
for name in names:
|
| 1449 |
+
func = getattr(self.o, name)
|
| 1450 |
+
if not self.is_alias(func):
|
| 1451 |
+
continue
|
| 1452 |
+
propname = re.search(f"`({name[:4]}.*)`", # get_.*/set_.*
|
| 1453 |
+
inspect.getdoc(func)).group(1)
|
| 1454 |
+
aliases.setdefault(propname[4:], set()).add(name[4:])
|
| 1455 |
+
return aliases
|
| 1456 |
+
|
| 1457 |
+
_get_valid_values_regex = re.compile(
|
| 1458 |
+
r"\n\s*(?:\.\.\s+)?ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))"
|
| 1459 |
+
)
|
| 1460 |
+
|
| 1461 |
+
def get_valid_values(self, attr):
|
| 1462 |
+
"""
|
| 1463 |
+
Get the legal arguments for the setter associated with *attr*.
|
| 1464 |
+
|
| 1465 |
+
This is done by querying the docstring of the setter for a line that
|
| 1466 |
+
begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a
|
| 1467 |
+
numpydoc-style documentation for the setter's first argument.
|
| 1468 |
+
"""
|
| 1469 |
+
|
| 1470 |
+
name = 'set_%s' % attr
|
| 1471 |
+
if not hasattr(self.o, name):
|
| 1472 |
+
raise AttributeError(f'{self.o} has no function {name}')
|
| 1473 |
+
func = getattr(self.o, name)
|
| 1474 |
+
|
| 1475 |
+
if hasattr(func, '_kwarg_doc'):
|
| 1476 |
+
return func._kwarg_doc
|
| 1477 |
+
|
| 1478 |
+
docstring = inspect.getdoc(func)
|
| 1479 |
+
if docstring is None:
|
| 1480 |
+
return 'unknown'
|
| 1481 |
+
|
| 1482 |
+
if docstring.startswith('Alias for '):
|
| 1483 |
+
return None
|
| 1484 |
+
|
| 1485 |
+
match = self._get_valid_values_regex.search(docstring)
|
| 1486 |
+
if match is not None:
|
| 1487 |
+
return re.sub("\n *", " ", match.group(1))
|
| 1488 |
+
|
| 1489 |
+
# Much faster than list(inspect.signature(func).parameters)[1],
|
| 1490 |
+
# although barely relevant wrt. matplotlib's total import time.
|
| 1491 |
+
param_name = func.__code__.co_varnames[1]
|
| 1492 |
+
# We could set the presence * based on whether the parameter is a
|
| 1493 |
+
# varargs (it can't be a varkwargs) but it's not really worth it.
|
| 1494 |
+
match = re.search(fr"(?m)^ *\*?{param_name} : (.+)", docstring)
|
| 1495 |
+
if match:
|
| 1496 |
+
return match.group(1)
|
| 1497 |
+
|
| 1498 |
+
return 'unknown'
|
| 1499 |
+
|
| 1500 |
+
def _replace_path(self, source_class):
|
| 1501 |
+
"""
|
| 1502 |
+
Changes the full path to the public API path that is used
|
| 1503 |
+
in sphinx. This is needed for links to work.
|
| 1504 |
+
"""
|
| 1505 |
+
replace_dict = {'_base._AxesBase': 'Axes',
|
| 1506 |
+
'_axes.Axes': 'Axes'}
|
| 1507 |
+
for key, value in replace_dict.items():
|
| 1508 |
+
source_class = source_class.replace(key, value)
|
| 1509 |
+
return source_class
|
| 1510 |
+
|
| 1511 |
+
def get_setters(self):
|
| 1512 |
+
"""
|
| 1513 |
+
Get the attribute strings with setters for object.
|
| 1514 |
+
|
| 1515 |
+
For example, for a line, return ``['markerfacecolor', 'linewidth',
|
| 1516 |
+
....]``.
|
| 1517 |
+
"""
|
| 1518 |
+
setters = []
|
| 1519 |
+
for name in dir(self.o):
|
| 1520 |
+
if not name.startswith('set_'):
|
| 1521 |
+
continue
|
| 1522 |
+
func = getattr(self.o, name)
|
| 1523 |
+
if (not callable(func)
|
| 1524 |
+
or self.number_of_parameters(func) < 2
|
| 1525 |
+
or self.is_alias(func)):
|
| 1526 |
+
continue
|
| 1527 |
+
setters.append(name[4:])
|
| 1528 |
+
return setters
|
| 1529 |
+
|
| 1530 |
+
@staticmethod
|
| 1531 |
+
@cache
|
| 1532 |
+
def number_of_parameters(func):
|
| 1533 |
+
"""Return number of parameters of the callable *func*."""
|
| 1534 |
+
return len(inspect.signature(func).parameters)
|
| 1535 |
+
|
| 1536 |
+
@staticmethod
|
| 1537 |
+
@cache
|
| 1538 |
+
def is_alias(method):
|
| 1539 |
+
"""
|
| 1540 |
+
Return whether the object *method* is an alias for another method.
|
| 1541 |
+
"""
|
| 1542 |
+
|
| 1543 |
+
ds = inspect.getdoc(method)
|
| 1544 |
+
if ds is None:
|
| 1545 |
+
return False
|
| 1546 |
+
|
| 1547 |
+
return ds.startswith('Alias for ')
|
| 1548 |
+
|
| 1549 |
+
def aliased_name(self, s):
|
| 1550 |
+
"""
|
| 1551 |
+
Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'.
|
| 1552 |
+
|
| 1553 |
+
For example, for the line markerfacecolor property, which has an
|
| 1554 |
+
alias, return 'markerfacecolor or mfc' and for the transform
|
| 1555 |
+
property, which does not, return 'transform'.
|
| 1556 |
+
"""
|
| 1557 |
+
aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, [])))
|
| 1558 |
+
return s + aliases
|
| 1559 |
+
|
| 1560 |
+
_NOT_LINKABLE = {
|
| 1561 |
+
# A set of property setter methods that are not available in our
|
| 1562 |
+
# current docs. This is a workaround used to prevent trying to link
|
| 1563 |
+
# these setters which would lead to "target reference not found"
|
| 1564 |
+
# warnings during doc build.
|
| 1565 |
+
'matplotlib.image._ImageBase.set_alpha',
|
| 1566 |
+
'matplotlib.image._ImageBase.set_array',
|
| 1567 |
+
'matplotlib.image._ImageBase.set_data',
|
| 1568 |
+
'matplotlib.image._ImageBase.set_filternorm',
|
| 1569 |
+
'matplotlib.image._ImageBase.set_filterrad',
|
| 1570 |
+
'matplotlib.image._ImageBase.set_interpolation',
|
| 1571 |
+
'matplotlib.image._ImageBase.set_interpolation_stage',
|
| 1572 |
+
'matplotlib.image._ImageBase.set_resample',
|
| 1573 |
+
'matplotlib.text._AnnotationBase.set_annotation_clip',
|
| 1574 |
+
}
|
| 1575 |
+
|
| 1576 |
+
def aliased_name_rest(self, s, target):
|
| 1577 |
+
"""
|
| 1578 |
+
Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME',
|
| 1579 |
+
formatted for reST.
|
| 1580 |
+
|
| 1581 |
+
For example, for the line markerfacecolor property, which has an
|
| 1582 |
+
alias, return 'markerfacecolor or mfc' and for the transform
|
| 1583 |
+
property, which does not, return 'transform'.
|
| 1584 |
+
"""
|
| 1585 |
+
# workaround to prevent "reference target not found"
|
| 1586 |
+
if target in self._NOT_LINKABLE:
|
| 1587 |
+
return f'``{s}``'
|
| 1588 |
+
|
| 1589 |
+
aliases = ''.join(
|
| 1590 |
+
f' or :meth:`{a} <{target}>`' for a in sorted(self.aliasd.get(s, [])))
|
| 1591 |
+
return f':meth:`{s} <{target}>`{aliases}'
|
| 1592 |
+
|
| 1593 |
+
def pprint_setters(self, prop=None, leadingspace=2):
|
| 1594 |
+
"""
|
| 1595 |
+
If *prop* is *None*, return a list of strings of all settable
|
| 1596 |
+
properties and their valid values.
|
| 1597 |
+
|
| 1598 |
+
If *prop* is not *None*, it is a valid property name and that
|
| 1599 |
+
property will be returned as a string of property : valid
|
| 1600 |
+
values.
|
| 1601 |
+
"""
|
| 1602 |
+
if leadingspace:
|
| 1603 |
+
pad = ' ' * leadingspace
|
| 1604 |
+
else:
|
| 1605 |
+
pad = ''
|
| 1606 |
+
if prop is not None:
|
| 1607 |
+
accepts = self.get_valid_values(prop)
|
| 1608 |
+
return f'{pad}{prop}: {accepts}'
|
| 1609 |
+
|
| 1610 |
+
lines = []
|
| 1611 |
+
for prop in sorted(self.get_setters()):
|
| 1612 |
+
accepts = self.get_valid_values(prop)
|
| 1613 |
+
name = self.aliased_name(prop)
|
| 1614 |
+
lines.append(f'{pad}{name}: {accepts}')
|
| 1615 |
+
return lines
|
| 1616 |
+
|
| 1617 |
+
def pprint_setters_rest(self, prop=None, leadingspace=4):
|
| 1618 |
+
"""
|
| 1619 |
+
If *prop* is *None*, return a list of reST-formatted strings of all
|
| 1620 |
+
settable properties and their valid values.
|
| 1621 |
+
|
| 1622 |
+
If *prop* is not *None*, it is a valid property name and that
|
| 1623 |
+
property will be returned as a string of "property : valid"
|
| 1624 |
+
values.
|
| 1625 |
+
"""
|
| 1626 |
+
if leadingspace:
|
| 1627 |
+
pad = ' ' * leadingspace
|
| 1628 |
+
else:
|
| 1629 |
+
pad = ''
|
| 1630 |
+
if prop is not None:
|
| 1631 |
+
accepts = self.get_valid_values(prop)
|
| 1632 |
+
return f'{pad}{prop}: {accepts}'
|
| 1633 |
+
|
| 1634 |
+
prop_and_qualnames = []
|
| 1635 |
+
for prop in sorted(self.get_setters()):
|
| 1636 |
+
# Find the parent method which actually provides the docstring.
|
| 1637 |
+
for cls in self.o.__mro__:
|
| 1638 |
+
method = getattr(cls, f"set_{prop}", None)
|
| 1639 |
+
if method and method.__doc__ is not None:
|
| 1640 |
+
break
|
| 1641 |
+
else: # No docstring available.
|
| 1642 |
+
method = getattr(self.o, f"set_{prop}")
|
| 1643 |
+
prop_and_qualnames.append(
|
| 1644 |
+
(prop, f"{method.__module__}.{method.__qualname__}"))
|
| 1645 |
+
|
| 1646 |
+
names = [self.aliased_name_rest(prop, target)
|
| 1647 |
+
.replace('_base._AxesBase', 'Axes')
|
| 1648 |
+
.replace('_axes.Axes', 'Axes')
|
| 1649 |
+
for prop, target in prop_and_qualnames]
|
| 1650 |
+
accepts = [self.get_valid_values(prop)
|
| 1651 |
+
for prop, _ in prop_and_qualnames]
|
| 1652 |
+
|
| 1653 |
+
col0_len = max(len(n) for n in names)
|
| 1654 |
+
col1_len = max(len(a) for a in accepts)
|
| 1655 |
+
table_formatstr = pad + ' ' + '=' * col0_len + ' ' + '=' * col1_len
|
| 1656 |
+
|
| 1657 |
+
return [
|
| 1658 |
+
'',
|
| 1659 |
+
pad + '.. table::',
|
| 1660 |
+
pad + ' :class: property-table',
|
| 1661 |
+
'',
|
| 1662 |
+
table_formatstr,
|
| 1663 |
+
pad + ' ' + 'Property'.ljust(col0_len)
|
| 1664 |
+
+ ' ' + 'Description'.ljust(col1_len),
|
| 1665 |
+
table_formatstr,
|
| 1666 |
+
*[pad + ' ' + n.ljust(col0_len) + ' ' + a.ljust(col1_len)
|
| 1667 |
+
for n, a in zip(names, accepts)],
|
| 1668 |
+
table_formatstr,
|
| 1669 |
+
'',
|
| 1670 |
+
]
|
| 1671 |
+
|
| 1672 |
+
def properties(self):
|
| 1673 |
+
"""Return a dictionary mapping property name -> value."""
|
| 1674 |
+
o = self.oorig
|
| 1675 |
+
getters = [name for name in dir(o)
|
| 1676 |
+
if name.startswith('get_') and callable(getattr(o, name))]
|
| 1677 |
+
getters.sort()
|
| 1678 |
+
d = {}
|
| 1679 |
+
for name in getters:
|
| 1680 |
+
func = getattr(o, name)
|
| 1681 |
+
if self.is_alias(func):
|
| 1682 |
+
continue
|
| 1683 |
+
try:
|
| 1684 |
+
with warnings.catch_warnings():
|
| 1685 |
+
warnings.simplefilter('ignore')
|
| 1686 |
+
val = func()
|
| 1687 |
+
except Exception:
|
| 1688 |
+
continue
|
| 1689 |
+
else:
|
| 1690 |
+
d[name[4:]] = val
|
| 1691 |
+
return d
|
| 1692 |
+
|
| 1693 |
+
def pprint_getters(self):
|
| 1694 |
+
"""Return the getters and actual values as list of strings."""
|
| 1695 |
+
lines = []
|
| 1696 |
+
for name, val in sorted(self.properties().items()):
|
| 1697 |
+
if getattr(val, 'shape', ()) != () and len(val) > 6:
|
| 1698 |
+
s = str(val[:6]) + '...'
|
| 1699 |
+
else:
|
| 1700 |
+
s = str(val)
|
| 1701 |
+
s = s.replace('\n', ' ')
|
| 1702 |
+
if len(s) > 50:
|
| 1703 |
+
s = s[:50] + '...'
|
| 1704 |
+
name = self.aliased_name(name)
|
| 1705 |
+
lines.append(f' {name} = {s}')
|
| 1706 |
+
return lines
|
| 1707 |
+
|
| 1708 |
+
|
| 1709 |
+
def getp(obj, property=None):
|
| 1710 |
+
"""
|
| 1711 |
+
Return the value of an `.Artist`'s *property*, or print all of them.
|
| 1712 |
+
|
| 1713 |
+
Parameters
|
| 1714 |
+
----------
|
| 1715 |
+
obj : `~matplotlib.artist.Artist`
|
| 1716 |
+
The queried artist; e.g., a `.Line2D`, a `.Text`, or an `~.axes.Axes`.
|
| 1717 |
+
|
| 1718 |
+
property : str or None, default: None
|
| 1719 |
+
If *property* is 'somename', this function returns
|
| 1720 |
+
``obj.get_somename()``.
|
| 1721 |
+
|
| 1722 |
+
If it's None (or unset), it *prints* all gettable properties from
|
| 1723 |
+
*obj*. Many properties have aliases for shorter typing, e.g. 'lw' is
|
| 1724 |
+
an alias for 'linewidth'. In the output, aliases and full property
|
| 1725 |
+
names will be listed as:
|
| 1726 |
+
|
| 1727 |
+
property or alias = value
|
| 1728 |
+
|
| 1729 |
+
e.g.:
|
| 1730 |
+
|
| 1731 |
+
linewidth or lw = 2
|
| 1732 |
+
|
| 1733 |
+
See Also
|
| 1734 |
+
--------
|
| 1735 |
+
setp
|
| 1736 |
+
"""
|
| 1737 |
+
if property is None:
|
| 1738 |
+
insp = ArtistInspector(obj)
|
| 1739 |
+
ret = insp.pprint_getters()
|
| 1740 |
+
print('\n'.join(ret))
|
| 1741 |
+
return
|
| 1742 |
+
return getattr(obj, 'get_' + property)()
|
| 1743 |
+
|
| 1744 |
+
# alias
|
| 1745 |
+
get = getp
|
| 1746 |
+
|
| 1747 |
+
|
| 1748 |
+
def setp(obj, *args, file=None, **kwargs):
|
| 1749 |
+
"""
|
| 1750 |
+
Set one or more properties on an `.Artist`, or list allowed values.
|
| 1751 |
+
|
| 1752 |
+
Parameters
|
| 1753 |
+
----------
|
| 1754 |
+
obj : `~matplotlib.artist.Artist` or list of `.Artist`
|
| 1755 |
+
The artist(s) whose properties are being set or queried. When setting
|
| 1756 |
+
properties, all artists are affected; when querying the allowed values,
|
| 1757 |
+
only the first instance in the sequence is queried.
|
| 1758 |
+
|
| 1759 |
+
For example, two lines can be made thicker and red with a single call:
|
| 1760 |
+
|
| 1761 |
+
>>> x = arange(0, 1, 0.01)
|
| 1762 |
+
>>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x))
|
| 1763 |
+
>>> setp(lines, linewidth=2, color='r')
|
| 1764 |
+
|
| 1765 |
+
file : file-like, default: `sys.stdout`
|
| 1766 |
+
Where `setp` writes its output when asked to list allowed values.
|
| 1767 |
+
|
| 1768 |
+
>>> with open('output.log') as file:
|
| 1769 |
+
... setp(line, file=file)
|
| 1770 |
+
|
| 1771 |
+
The default, ``None``, means `sys.stdout`.
|
| 1772 |
+
|
| 1773 |
+
*args, **kwargs
|
| 1774 |
+
The properties to set. The following combinations are supported:
|
| 1775 |
+
|
| 1776 |
+
- Set the linestyle of a line to be dashed:
|
| 1777 |
+
|
| 1778 |
+
>>> line, = plot([1, 2, 3])
|
| 1779 |
+
>>> setp(line, linestyle='--')
|
| 1780 |
+
|
| 1781 |
+
- Set multiple properties at once:
|
| 1782 |
+
|
| 1783 |
+
>>> setp(line, linewidth=2, color='r')
|
| 1784 |
+
|
| 1785 |
+
- List allowed values for a line's linestyle:
|
| 1786 |
+
|
| 1787 |
+
>>> setp(line, 'linestyle')
|
| 1788 |
+
linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
|
| 1789 |
+
|
| 1790 |
+
- List all properties that can be set, and their allowed values:
|
| 1791 |
+
|
| 1792 |
+
>>> setp(line)
|
| 1793 |
+
agg_filter: a filter function, ...
|
| 1794 |
+
[long output listing omitted]
|
| 1795 |
+
|
| 1796 |
+
`setp` also supports MATLAB style string/value pairs. For example, the
|
| 1797 |
+
following are equivalent:
|
| 1798 |
+
|
| 1799 |
+
>>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style
|
| 1800 |
+
>>> setp(lines, linewidth=2, color='r') # Python style
|
| 1801 |
+
|
| 1802 |
+
See Also
|
| 1803 |
+
--------
|
| 1804 |
+
getp
|
| 1805 |
+
"""
|
| 1806 |
+
|
| 1807 |
+
if isinstance(obj, Artist):
|
| 1808 |
+
objs = [obj]
|
| 1809 |
+
else:
|
| 1810 |
+
objs = list(cbook.flatten(obj))
|
| 1811 |
+
|
| 1812 |
+
if not objs:
|
| 1813 |
+
return
|
| 1814 |
+
|
| 1815 |
+
insp = ArtistInspector(objs[0])
|
| 1816 |
+
|
| 1817 |
+
if not kwargs and len(args) < 2:
|
| 1818 |
+
if args:
|
| 1819 |
+
print(insp.pprint_setters(prop=args[0]), file=file)
|
| 1820 |
+
else:
|
| 1821 |
+
print('\n'.join(insp.pprint_setters()), file=file)
|
| 1822 |
+
return
|
| 1823 |
+
|
| 1824 |
+
if len(args) % 2:
|
| 1825 |
+
raise ValueError('The set args must be string, value pairs')
|
| 1826 |
+
|
| 1827 |
+
funcvals = dict(zip(args[::2], args[1::2]))
|
| 1828 |
+
ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs]
|
| 1829 |
+
return list(cbook.flatten(ret))
|
| 1830 |
+
|
| 1831 |
+
|
| 1832 |
+
def kwdoc(artist):
|
| 1833 |
+
r"""
|
| 1834 |
+
Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and
|
| 1835 |
+
return information about its settable properties and their current values.
|
| 1836 |
+
|
| 1837 |
+
Parameters
|
| 1838 |
+
----------
|
| 1839 |
+
artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s
|
| 1840 |
+
|
| 1841 |
+
Returns
|
| 1842 |
+
-------
|
| 1843 |
+
str
|
| 1844 |
+
The settable properties of *artist*, as plain text if
|
| 1845 |
+
:rc:`docstring.hardcopy` is False and as a rst table (intended for
|
| 1846 |
+
use in Sphinx) if it is True.
|
| 1847 |
+
"""
|
| 1848 |
+
ai = ArtistInspector(artist)
|
| 1849 |
+
return ('\n'.join(ai.pprint_setters_rest(leadingspace=4))
|
| 1850 |
+
if mpl.rcParams['docstring.hardcopy'] else
|
| 1851 |
+
'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4)))
|
| 1852 |
+
|
| 1853 |
+
# We defer this to the end of them module, because it needs ArtistInspector
|
| 1854 |
+
# to be defined.
|
| 1855 |
+
Artist._update_set_signature_and_docstring()
|
moondream/lib/python3.10/site-packages/matplotlib/backend_bases.pyi
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum, IntEnum
|
| 2 |
+
import os
|
| 3 |
+
from matplotlib import (
|
| 4 |
+
cbook,
|
| 5 |
+
transforms,
|
| 6 |
+
widgets,
|
| 7 |
+
_api,
|
| 8 |
+
)
|
| 9 |
+
from matplotlib.artist import Artist
|
| 10 |
+
from matplotlib.axes import Axes
|
| 11 |
+
from matplotlib.backend_managers import ToolManager
|
| 12 |
+
from matplotlib.backend_tools import Cursors, ToolBase
|
| 13 |
+
from matplotlib.colorbar import Colorbar
|
| 14 |
+
from matplotlib.figure import Figure
|
| 15 |
+
from matplotlib.font_manager import FontProperties
|
| 16 |
+
from matplotlib.path import Path
|
| 17 |
+
from matplotlib.texmanager import TexManager
|
| 18 |
+
from matplotlib.text import Text
|
| 19 |
+
from matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 22 |
+
from typing import Any, IO, Literal, NamedTuple, TypeVar
|
| 23 |
+
from numpy.typing import ArrayLike
|
| 24 |
+
from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
|
| 25 |
+
|
| 26 |
+
def register_backend(
|
| 27 |
+
format: str, backend: str | type[FigureCanvasBase], description: str | None = ...
|
| 28 |
+
) -> None: ...
|
| 29 |
+
def get_registered_canvas_class(format: str) -> type[FigureCanvasBase]: ...
|
| 30 |
+
|
| 31 |
+
class RendererBase:
|
| 32 |
+
def __init__(self) -> None: ...
|
| 33 |
+
def open_group(self, s: str, gid: str | None = ...) -> None: ...
|
| 34 |
+
def close_group(self, s: str) -> None: ...
|
| 35 |
+
def draw_path(
|
| 36 |
+
self,
|
| 37 |
+
gc: GraphicsContextBase,
|
| 38 |
+
path: Path,
|
| 39 |
+
transform: Transform,
|
| 40 |
+
rgbFace: ColorType | None = ...,
|
| 41 |
+
) -> None: ...
|
| 42 |
+
def draw_markers(
|
| 43 |
+
self,
|
| 44 |
+
gc: GraphicsContextBase,
|
| 45 |
+
marker_path: Path,
|
| 46 |
+
marker_trans: Transform,
|
| 47 |
+
path: Path,
|
| 48 |
+
trans: Transform,
|
| 49 |
+
rgbFace: ColorType | None = ...,
|
| 50 |
+
) -> None: ...
|
| 51 |
+
def draw_path_collection(
|
| 52 |
+
self,
|
| 53 |
+
gc: GraphicsContextBase,
|
| 54 |
+
master_transform: Transform,
|
| 55 |
+
paths: Sequence[Path],
|
| 56 |
+
all_transforms: Sequence[ArrayLike],
|
| 57 |
+
offsets: ArrayLike | Sequence[ArrayLike],
|
| 58 |
+
offset_trans: Transform,
|
| 59 |
+
facecolors: ColorType | Sequence[ColorType],
|
| 60 |
+
edgecolors: ColorType | Sequence[ColorType],
|
| 61 |
+
linewidths: float | Sequence[float],
|
| 62 |
+
linestyles: LineStyleType | Sequence[LineStyleType],
|
| 63 |
+
antialiaseds: bool | Sequence[bool],
|
| 64 |
+
urls: str | Sequence[str],
|
| 65 |
+
offset_position: Any,
|
| 66 |
+
) -> None: ...
|
| 67 |
+
def draw_quad_mesh(
|
| 68 |
+
self,
|
| 69 |
+
gc: GraphicsContextBase,
|
| 70 |
+
master_transform: Transform,
|
| 71 |
+
meshWidth,
|
| 72 |
+
meshHeight,
|
| 73 |
+
coordinates: ArrayLike,
|
| 74 |
+
offsets: ArrayLike | Sequence[ArrayLike],
|
| 75 |
+
offsetTrans: Transform,
|
| 76 |
+
facecolors: Sequence[ColorType],
|
| 77 |
+
antialiased: bool,
|
| 78 |
+
edgecolors: Sequence[ColorType] | ColorType | None,
|
| 79 |
+
) -> None: ...
|
| 80 |
+
def draw_gouraud_triangles(
|
| 81 |
+
self,
|
| 82 |
+
gc: GraphicsContextBase,
|
| 83 |
+
triangles_array: ArrayLike,
|
| 84 |
+
colors_array: ArrayLike,
|
| 85 |
+
transform: Transform,
|
| 86 |
+
) -> None: ...
|
| 87 |
+
def get_image_magnification(self) -> float: ...
|
| 88 |
+
def draw_image(
|
| 89 |
+
self,
|
| 90 |
+
gc: GraphicsContextBase,
|
| 91 |
+
x: float,
|
| 92 |
+
y: float,
|
| 93 |
+
im: ArrayLike,
|
| 94 |
+
transform: transforms.Affine2DBase | None = ...,
|
| 95 |
+
) -> None: ...
|
| 96 |
+
def option_image_nocomposite(self) -> bool: ...
|
| 97 |
+
def option_scale_image(self) -> bool: ...
|
| 98 |
+
def draw_tex(
|
| 99 |
+
self,
|
| 100 |
+
gc: GraphicsContextBase,
|
| 101 |
+
x: float,
|
| 102 |
+
y: float,
|
| 103 |
+
s: str,
|
| 104 |
+
prop: FontProperties,
|
| 105 |
+
angle: float,
|
| 106 |
+
*,
|
| 107 |
+
mtext: Text | None = ...
|
| 108 |
+
) -> None: ...
|
| 109 |
+
def draw_text(
|
| 110 |
+
self,
|
| 111 |
+
gc: GraphicsContextBase,
|
| 112 |
+
x: float,
|
| 113 |
+
y: float,
|
| 114 |
+
s: str,
|
| 115 |
+
prop: FontProperties,
|
| 116 |
+
angle: float,
|
| 117 |
+
ismath: bool | Literal["TeX"] = ...,
|
| 118 |
+
mtext: Text | None = ...,
|
| 119 |
+
) -> None: ...
|
| 120 |
+
def get_text_width_height_descent(
|
| 121 |
+
self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"]
|
| 122 |
+
) -> tuple[float, float, float]: ...
|
| 123 |
+
def flipy(self) -> bool: ...
|
| 124 |
+
def get_canvas_width_height(self) -> tuple[float, float]: ...
|
| 125 |
+
def get_texmanager(self) -> TexManager: ...
|
| 126 |
+
def new_gc(self) -> GraphicsContextBase: ...
|
| 127 |
+
def points_to_pixels(self, points: ArrayLike) -> ArrayLike: ...
|
| 128 |
+
def start_rasterizing(self) -> None: ...
|
| 129 |
+
def stop_rasterizing(self) -> None: ...
|
| 130 |
+
def start_filter(self) -> None: ...
|
| 131 |
+
def stop_filter(self, filter_func) -> None: ...
|
| 132 |
+
|
| 133 |
+
class GraphicsContextBase:
|
| 134 |
+
def __init__(self) -> None: ...
|
| 135 |
+
def copy_properties(self, gc: GraphicsContextBase) -> None: ...
|
| 136 |
+
def restore(self) -> None: ...
|
| 137 |
+
def get_alpha(self) -> float: ...
|
| 138 |
+
def get_antialiased(self) -> int: ...
|
| 139 |
+
def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
|
| 140 |
+
def get_clip_rectangle(self) -> Bbox | None: ...
|
| 141 |
+
def get_clip_path(
|
| 142 |
+
self,
|
| 143 |
+
) -> tuple[TransformedPath, Transform] | tuple[None, None]: ...
|
| 144 |
+
def get_dashes(self) -> tuple[float, ArrayLike | None]: ...
|
| 145 |
+
def get_forced_alpha(self) -> bool: ...
|
| 146 |
+
def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
|
| 147 |
+
def get_linewidth(self) -> float: ...
|
| 148 |
+
def get_rgb(self) -> tuple[float, float, float, float]: ...
|
| 149 |
+
def get_url(self) -> str | None: ...
|
| 150 |
+
def get_gid(self) -> int | None: ...
|
| 151 |
+
def get_snap(self) -> bool | None: ...
|
| 152 |
+
def set_alpha(self, alpha: float) -> None: ...
|
| 153 |
+
def set_antialiased(self, b: bool) -> None: ...
|
| 154 |
+
def set_capstyle(self, cs: CapStyleType) -> None: ...
|
| 155 |
+
def set_clip_rectangle(self, rectangle: Bbox | None) -> None: ...
|
| 156 |
+
def set_clip_path(self, path: TransformedPath | None) -> None: ...
|
| 157 |
+
def set_dashes(self, dash_offset: float, dash_list: ArrayLike | None) -> None: ...
|
| 158 |
+
def set_foreground(self, fg: ColorType, isRGBA: bool = ...) -> None: ...
|
| 159 |
+
def set_joinstyle(self, js: JoinStyleType) -> None: ...
|
| 160 |
+
def set_linewidth(self, w: float) -> None: ...
|
| 161 |
+
def set_url(self, url: str | None) -> None: ...
|
| 162 |
+
def set_gid(self, id: int | None) -> None: ...
|
| 163 |
+
def set_snap(self, snap: bool | None) -> None: ...
|
| 164 |
+
def set_hatch(self, hatch: str | None) -> None: ...
|
| 165 |
+
def get_hatch(self) -> str | None: ...
|
| 166 |
+
def get_hatch_path(self, density: float = ...) -> Path: ...
|
| 167 |
+
def get_hatch_color(self) -> ColorType: ...
|
| 168 |
+
def set_hatch_color(self, hatch_color: ColorType) -> None: ...
|
| 169 |
+
def get_hatch_linewidth(self) -> float: ...
|
| 170 |
+
def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ...
|
| 171 |
+
def get_sketch_params(self) -> tuple[float, float, float] | None: ...
|
| 172 |
+
def set_sketch_params(
|
| 173 |
+
self,
|
| 174 |
+
scale: float | None = ...,
|
| 175 |
+
length: float | None = ...,
|
| 176 |
+
randomness: float | None = ...,
|
| 177 |
+
) -> None: ...
|
| 178 |
+
|
| 179 |
+
class TimerBase:
|
| 180 |
+
callbacks: list[tuple[Callable, tuple, dict[str, Any]]]
|
| 181 |
+
def __init__(
|
| 182 |
+
self,
|
| 183 |
+
interval: int | None = ...,
|
| 184 |
+
callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
|
| 185 |
+
) -> None: ...
|
| 186 |
+
def __del__(self) -> None: ...
|
| 187 |
+
def start(self, interval: int | None = ...) -> None: ...
|
| 188 |
+
def stop(self) -> None: ...
|
| 189 |
+
@property
|
| 190 |
+
def interval(self) -> int: ...
|
| 191 |
+
@interval.setter
|
| 192 |
+
def interval(self, interval: int) -> None: ...
|
| 193 |
+
@property
|
| 194 |
+
def single_shot(self) -> bool: ...
|
| 195 |
+
@single_shot.setter
|
| 196 |
+
def single_shot(self, ss: bool) -> None: ...
|
| 197 |
+
def add_callback(self, func: Callable, *args, **kwargs) -> Callable: ...
|
| 198 |
+
def remove_callback(self, func: Callable, *args, **kwargs) -> None: ...
|
| 199 |
+
|
| 200 |
+
class Event:
|
| 201 |
+
name: str
|
| 202 |
+
canvas: FigureCanvasBase
|
| 203 |
+
guiEvent: Any
|
| 204 |
+
def __init__(
|
| 205 |
+
self, name: str, canvas: FigureCanvasBase, guiEvent: Any | None = ...
|
| 206 |
+
) -> None: ...
|
| 207 |
+
|
| 208 |
+
class DrawEvent(Event):
|
| 209 |
+
renderer: RendererBase
|
| 210 |
+
def __init__(
|
| 211 |
+
self, name: str, canvas: FigureCanvasBase, renderer: RendererBase
|
| 212 |
+
) -> None: ...
|
| 213 |
+
|
| 214 |
+
class ResizeEvent(Event):
|
| 215 |
+
width: int
|
| 216 |
+
height: int
|
| 217 |
+
def __init__(self, name: str, canvas: FigureCanvasBase) -> None: ...
|
| 218 |
+
|
| 219 |
+
class CloseEvent(Event): ...
|
| 220 |
+
|
| 221 |
+
class LocationEvent(Event):
|
| 222 |
+
x: int
|
| 223 |
+
y: int
|
| 224 |
+
inaxes: Axes | None
|
| 225 |
+
xdata: float | None
|
| 226 |
+
ydata: float | None
|
| 227 |
+
def __init__(
|
| 228 |
+
self,
|
| 229 |
+
name: str,
|
| 230 |
+
canvas: FigureCanvasBase,
|
| 231 |
+
x: int,
|
| 232 |
+
y: int,
|
| 233 |
+
guiEvent: Any | None = ...,
|
| 234 |
+
*,
|
| 235 |
+
modifiers: Iterable[str] | None = ...,
|
| 236 |
+
) -> None: ...
|
| 237 |
+
|
| 238 |
+
class MouseButton(IntEnum):
|
| 239 |
+
LEFT: int
|
| 240 |
+
MIDDLE: int
|
| 241 |
+
RIGHT: int
|
| 242 |
+
BACK: int
|
| 243 |
+
FORWARD: int
|
| 244 |
+
|
| 245 |
+
class MouseEvent(LocationEvent):
|
| 246 |
+
button: MouseButton | Literal["up", "down"] | None
|
| 247 |
+
key: str | None
|
| 248 |
+
step: float
|
| 249 |
+
dblclick: bool
|
| 250 |
+
def __init__(
|
| 251 |
+
self,
|
| 252 |
+
name: str,
|
| 253 |
+
canvas: FigureCanvasBase,
|
| 254 |
+
x: int,
|
| 255 |
+
y: int,
|
| 256 |
+
button: MouseButton | Literal["up", "down"] | None = ...,
|
| 257 |
+
key: str | None = ...,
|
| 258 |
+
step: float = ...,
|
| 259 |
+
dblclick: bool = ...,
|
| 260 |
+
guiEvent: Any | None = ...,
|
| 261 |
+
*,
|
| 262 |
+
buttons: Iterable[MouseButton] | None = ...,
|
| 263 |
+
modifiers: Iterable[str] | None = ...,
|
| 264 |
+
) -> None: ...
|
| 265 |
+
|
| 266 |
+
class PickEvent(Event):
|
| 267 |
+
mouseevent: MouseEvent
|
| 268 |
+
artist: Artist
|
| 269 |
+
def __init__(
|
| 270 |
+
self,
|
| 271 |
+
name: str,
|
| 272 |
+
canvas: FigureCanvasBase,
|
| 273 |
+
mouseevent: MouseEvent,
|
| 274 |
+
artist: Artist,
|
| 275 |
+
guiEvent: Any | None = ...,
|
| 276 |
+
**kwargs
|
| 277 |
+
) -> None: ...
|
| 278 |
+
|
| 279 |
+
class KeyEvent(LocationEvent):
|
| 280 |
+
key: str | None
|
| 281 |
+
def __init__(
|
| 282 |
+
self,
|
| 283 |
+
name: str,
|
| 284 |
+
canvas: FigureCanvasBase,
|
| 285 |
+
key: str | None,
|
| 286 |
+
x: int = ...,
|
| 287 |
+
y: int = ...,
|
| 288 |
+
guiEvent: Any | None = ...,
|
| 289 |
+
) -> None: ...
|
| 290 |
+
|
| 291 |
+
class FigureCanvasBase:
|
| 292 |
+
required_interactive_framework: str | None
|
| 293 |
+
|
| 294 |
+
@_api.classproperty
|
| 295 |
+
def manager_class(cls) -> type[FigureManagerBase]: ...
|
| 296 |
+
events: list[str]
|
| 297 |
+
fixed_dpi: None | float
|
| 298 |
+
filetypes: dict[str, str]
|
| 299 |
+
|
| 300 |
+
@_api.classproperty
|
| 301 |
+
def supports_blit(cls) -> bool: ...
|
| 302 |
+
|
| 303 |
+
figure: Figure
|
| 304 |
+
manager: None | FigureManagerBase
|
| 305 |
+
widgetlock: widgets.LockDraw
|
| 306 |
+
mouse_grabber: None | Axes
|
| 307 |
+
toolbar: None | NavigationToolbar2
|
| 308 |
+
def __init__(self, figure: Figure | None = ...) -> None: ...
|
| 309 |
+
@property
|
| 310 |
+
def callbacks(self) -> cbook.CallbackRegistry: ...
|
| 311 |
+
@property
|
| 312 |
+
def button_pick_id(self) -> int: ...
|
| 313 |
+
@property
|
| 314 |
+
def scroll_pick_id(self) -> int: ...
|
| 315 |
+
@classmethod
|
| 316 |
+
def new_manager(cls, figure: Figure, num: int | str) -> FigureManagerBase: ...
|
| 317 |
+
def is_saving(self) -> bool: ...
|
| 318 |
+
def blit(self, bbox: BboxBase | None = ...) -> None: ...
|
| 319 |
+
def inaxes(self, xy: tuple[float, float]) -> Axes | None: ...
|
| 320 |
+
def grab_mouse(self, ax: Axes) -> None: ...
|
| 321 |
+
def release_mouse(self, ax: Axes) -> None: ...
|
| 322 |
+
def set_cursor(self, cursor: Cursors) -> None: ...
|
| 323 |
+
def draw(self, *args, **kwargs) -> None: ...
|
| 324 |
+
def draw_idle(self, *args, **kwargs) -> None: ...
|
| 325 |
+
@property
|
| 326 |
+
def device_pixel_ratio(self) -> float: ...
|
| 327 |
+
def get_width_height(self, *, physical: bool = ...) -> tuple[int, int]: ...
|
| 328 |
+
@classmethod
|
| 329 |
+
def get_supported_filetypes(cls) -> dict[str, str]: ...
|
| 330 |
+
@classmethod
|
| 331 |
+
def get_supported_filetypes_grouped(cls) -> dict[str, list[str]]: ...
|
| 332 |
+
def print_figure(
|
| 333 |
+
self,
|
| 334 |
+
filename: str | os.PathLike | IO,
|
| 335 |
+
dpi: float | None = ...,
|
| 336 |
+
facecolor: ColorType | Literal["auto"] | None = ...,
|
| 337 |
+
edgecolor: ColorType | Literal["auto"] | None = ...,
|
| 338 |
+
orientation: str = ...,
|
| 339 |
+
format: str | None = ...,
|
| 340 |
+
*,
|
| 341 |
+
bbox_inches: Literal["tight"] | Bbox | None = ...,
|
| 342 |
+
pad_inches: float | None = ...,
|
| 343 |
+
bbox_extra_artists: list[Artist] | None = ...,
|
| 344 |
+
backend: str | None = ...,
|
| 345 |
+
**kwargs
|
| 346 |
+
) -> Any: ...
|
| 347 |
+
@classmethod
|
| 348 |
+
def get_default_filetype(cls) -> str: ...
|
| 349 |
+
def get_default_filename(self) -> str: ...
|
| 350 |
+
_T = TypeVar("_T", bound=FigureCanvasBase)
|
| 351 |
+
def mpl_connect(self, s: str, func: Callable[[Event], Any]) -> int: ...
|
| 352 |
+
def mpl_disconnect(self, cid: int) -> None: ...
|
| 353 |
+
def new_timer(
|
| 354 |
+
self,
|
| 355 |
+
interval: int | None = ...,
|
| 356 |
+
callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
|
| 357 |
+
) -> TimerBase: ...
|
| 358 |
+
def flush_events(self) -> None: ...
|
| 359 |
+
def start_event_loop(self, timeout: float = ...) -> None: ...
|
| 360 |
+
def stop_event_loop(self) -> None: ...
|
| 361 |
+
|
| 362 |
+
def key_press_handler(
|
| 363 |
+
event: KeyEvent,
|
| 364 |
+
canvas: FigureCanvasBase | None = ...,
|
| 365 |
+
toolbar: NavigationToolbar2 | None = ...,
|
| 366 |
+
) -> None: ...
|
| 367 |
+
def button_press_handler(
|
| 368 |
+
event: MouseEvent,
|
| 369 |
+
canvas: FigureCanvasBase | None = ...,
|
| 370 |
+
toolbar: NavigationToolbar2 | None = ...,
|
| 371 |
+
) -> None: ...
|
| 372 |
+
|
| 373 |
+
class NonGuiException(Exception): ...
|
| 374 |
+
|
| 375 |
+
class FigureManagerBase:
|
| 376 |
+
canvas: FigureCanvasBase
|
| 377 |
+
num: int | str
|
| 378 |
+
key_press_handler_id: int | None
|
| 379 |
+
button_press_handler_id: int | None
|
| 380 |
+
toolmanager: ToolManager | None
|
| 381 |
+
toolbar: NavigationToolbar2 | ToolContainerBase | None
|
| 382 |
+
def __init__(self, canvas: FigureCanvasBase, num: int | str) -> None: ...
|
| 383 |
+
@classmethod
|
| 384 |
+
def create_with_canvas(
|
| 385 |
+
cls, canvas_class: type[FigureCanvasBase], figure: Figure, num: int | str
|
| 386 |
+
) -> FigureManagerBase: ...
|
| 387 |
+
@classmethod
|
| 388 |
+
def start_main_loop(cls) -> None: ...
|
| 389 |
+
@classmethod
|
| 390 |
+
def pyplot_show(cls, *, block: bool | None = ...) -> None: ...
|
| 391 |
+
def show(self) -> None: ...
|
| 392 |
+
def destroy(self) -> None: ...
|
| 393 |
+
def full_screen_toggle(self) -> None: ...
|
| 394 |
+
def resize(self, w: int, h: int) -> None: ...
|
| 395 |
+
def get_window_title(self) -> str: ...
|
| 396 |
+
def set_window_title(self, title: str) -> None: ...
|
| 397 |
+
|
| 398 |
+
cursors = Cursors
|
| 399 |
+
|
| 400 |
+
class _Mode(str, Enum):
|
| 401 |
+
NONE: str
|
| 402 |
+
PAN: str
|
| 403 |
+
ZOOM: str
|
| 404 |
+
|
| 405 |
+
class NavigationToolbar2:
|
| 406 |
+
toolitems: tuple[tuple[str, ...] | tuple[None, ...], ...]
|
| 407 |
+
UNKNOWN_SAVED_STATUS: object
|
| 408 |
+
canvas: FigureCanvasBase
|
| 409 |
+
mode: _Mode
|
| 410 |
+
def __init__(self, canvas: FigureCanvasBase) -> None: ...
|
| 411 |
+
def set_message(self, s: str) -> None: ...
|
| 412 |
+
def draw_rubberband(
|
| 413 |
+
self, event: Event, x0: float, y0: float, x1: float, y1: float
|
| 414 |
+
) -> None: ...
|
| 415 |
+
def remove_rubberband(self) -> None: ...
|
| 416 |
+
def home(self, *args) -> None: ...
|
| 417 |
+
def back(self, *args) -> None: ...
|
| 418 |
+
def forward(self, *args) -> None: ...
|
| 419 |
+
def mouse_move(self, event: MouseEvent) -> None: ...
|
| 420 |
+
def pan(self, *args) -> None: ...
|
| 421 |
+
|
| 422 |
+
class _PanInfo(NamedTuple):
|
| 423 |
+
button: MouseButton
|
| 424 |
+
axes: list[Axes]
|
| 425 |
+
cid: int
|
| 426 |
+
def press_pan(self, event: Event) -> None: ...
|
| 427 |
+
def drag_pan(self, event: Event) -> None: ...
|
| 428 |
+
def release_pan(self, event: Event) -> None: ...
|
| 429 |
+
def zoom(self, *args) -> None: ...
|
| 430 |
+
|
| 431 |
+
class _ZoomInfo(NamedTuple):
|
| 432 |
+
direction: Literal["in", "out"]
|
| 433 |
+
start_xy: tuple[float, float]
|
| 434 |
+
axes: list[Axes]
|
| 435 |
+
cid: int
|
| 436 |
+
cbar: Colorbar
|
| 437 |
+
def press_zoom(self, event: Event) -> None: ...
|
| 438 |
+
def drag_zoom(self, event: Event) -> None: ...
|
| 439 |
+
def release_zoom(self, event: Event) -> None: ...
|
| 440 |
+
def push_current(self) -> None: ...
|
| 441 |
+
subplot_tool: widgets.SubplotTool
|
| 442 |
+
def configure_subplots(self, *args): ...
|
| 443 |
+
def save_figure(self, *args) -> str | None | object: ...
|
| 444 |
+
def update(self) -> None: ...
|
| 445 |
+
def set_history_buttons(self) -> None: ...
|
| 446 |
+
|
| 447 |
+
class ToolContainerBase:
|
| 448 |
+
toolmanager: ToolManager
|
| 449 |
+
def __init__(self, toolmanager: ToolManager) -> None: ...
|
| 450 |
+
def add_tool(self, tool: ToolBase, group: str, position: int = ...) -> None: ...
|
| 451 |
+
def trigger_tool(self, name: str) -> None: ...
|
| 452 |
+
def add_toolitem(
|
| 453 |
+
self,
|
| 454 |
+
name: str,
|
| 455 |
+
group: str,
|
| 456 |
+
position: int,
|
| 457 |
+
image: str,
|
| 458 |
+
description: str,
|
| 459 |
+
toggle: bool,
|
| 460 |
+
) -> None: ...
|
| 461 |
+
def toggle_toolitem(self, name: str, toggled: bool) -> None: ...
|
| 462 |
+
def remove_toolitem(self, name: str) -> None: ...
|
| 463 |
+
def set_message(self, s: str) -> None: ...
|
| 464 |
+
|
| 465 |
+
class _Backend:
|
| 466 |
+
backend_version: str
|
| 467 |
+
FigureCanvas: type[FigureCanvasBase] | None
|
| 468 |
+
FigureManager: type[FigureManagerBase]
|
| 469 |
+
mainloop: None | Callable[[], Any]
|
| 470 |
+
@classmethod
|
| 471 |
+
def new_figure_manager(cls, num: int | str, *args, **kwargs) -> FigureManagerBase: ...
|
| 472 |
+
@classmethod
|
| 473 |
+
def new_figure_manager_given_figure(cls, num: int | str, figure: Figure) -> FigureManagerBase: ...
|
| 474 |
+
@classmethod
|
| 475 |
+
def draw_if_interactive(cls) -> None: ...
|
| 476 |
+
@classmethod
|
| 477 |
+
def show(cls, *, block: bool | None = ...) -> None: ...
|
| 478 |
+
@staticmethod
|
| 479 |
+
def export(cls) -> type[_Backend]: ...
|
| 480 |
+
|
| 481 |
+
class ShowBase(_Backend):
|
| 482 |
+
def __call__(self, block: bool | None = ...) -> None: ...
|
moondream/lib/python3.10/site-packages/matplotlib/backend_managers.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib import _api, backend_tools, cbook, widgets
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ToolEvent:
|
| 5 |
+
"""Event for tool manipulation (add/remove)."""
|
| 6 |
+
def __init__(self, name, sender, tool, data=None):
|
| 7 |
+
self.name = name
|
| 8 |
+
self.sender = sender
|
| 9 |
+
self.tool = tool
|
| 10 |
+
self.data = data
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ToolTriggerEvent(ToolEvent):
|
| 14 |
+
"""Event to inform that a tool has been triggered."""
|
| 15 |
+
def __init__(self, name, sender, tool, canvasevent=None, data=None):
|
| 16 |
+
super().__init__(name, sender, tool, data)
|
| 17 |
+
self.canvasevent = canvasevent
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ToolManagerMessageEvent:
|
| 21 |
+
"""
|
| 22 |
+
Event carrying messages from toolmanager.
|
| 23 |
+
|
| 24 |
+
Messages usually get displayed to the user by the toolbar.
|
| 25 |
+
"""
|
| 26 |
+
def __init__(self, name, sender, message):
|
| 27 |
+
self.name = name
|
| 28 |
+
self.sender = sender
|
| 29 |
+
self.message = message
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ToolManager:
|
| 33 |
+
"""
|
| 34 |
+
Manager for actions triggered by user interactions (key press, toolbar
|
| 35 |
+
clicks, ...) on a Figure.
|
| 36 |
+
|
| 37 |
+
Attributes
|
| 38 |
+
----------
|
| 39 |
+
figure : `.Figure`
|
| 40 |
+
keypresslock : `~matplotlib.widgets.LockDraw`
|
| 41 |
+
`.LockDraw` object to know if the `canvas` key_press_event is locked.
|
| 42 |
+
messagelock : `~matplotlib.widgets.LockDraw`
|
| 43 |
+
`.LockDraw` object to know if the message is available to write.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, figure=None):
|
| 47 |
+
|
| 48 |
+
self._key_press_handler_id = None
|
| 49 |
+
|
| 50 |
+
self._tools = {}
|
| 51 |
+
self._keys = {}
|
| 52 |
+
self._toggled = {}
|
| 53 |
+
self._callbacks = cbook.CallbackRegistry()
|
| 54 |
+
|
| 55 |
+
# to process keypress event
|
| 56 |
+
self.keypresslock = widgets.LockDraw()
|
| 57 |
+
self.messagelock = widgets.LockDraw()
|
| 58 |
+
|
| 59 |
+
self._figure = None
|
| 60 |
+
self.set_figure(figure)
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def canvas(self):
|
| 64 |
+
"""Canvas managed by FigureManager."""
|
| 65 |
+
if not self._figure:
|
| 66 |
+
return None
|
| 67 |
+
return self._figure.canvas
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def figure(self):
|
| 71 |
+
"""Figure that holds the canvas."""
|
| 72 |
+
return self._figure
|
| 73 |
+
|
| 74 |
+
@figure.setter
|
| 75 |
+
def figure(self, figure):
|
| 76 |
+
self.set_figure(figure)
|
| 77 |
+
|
| 78 |
+
def set_figure(self, figure, update_tools=True):
|
| 79 |
+
"""
|
| 80 |
+
Bind the given figure to the tools.
|
| 81 |
+
|
| 82 |
+
Parameters
|
| 83 |
+
----------
|
| 84 |
+
figure : `.Figure`
|
| 85 |
+
update_tools : bool, default: True
|
| 86 |
+
Force tools to update figure.
|
| 87 |
+
"""
|
| 88 |
+
if self._key_press_handler_id:
|
| 89 |
+
self.canvas.mpl_disconnect(self._key_press_handler_id)
|
| 90 |
+
self._figure = figure
|
| 91 |
+
if figure:
|
| 92 |
+
self._key_press_handler_id = self.canvas.mpl_connect(
|
| 93 |
+
'key_press_event', self._key_press)
|
| 94 |
+
if update_tools:
|
| 95 |
+
for tool in self._tools.values():
|
| 96 |
+
tool.figure = figure
|
| 97 |
+
|
| 98 |
+
def toolmanager_connect(self, s, func):
|
| 99 |
+
"""
|
| 100 |
+
Connect event with string *s* to *func*.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
s : str
|
| 105 |
+
The name of the event. The following events are recognized:
|
| 106 |
+
|
| 107 |
+
- 'tool_message_event'
|
| 108 |
+
- 'tool_removed_event'
|
| 109 |
+
- 'tool_added_event'
|
| 110 |
+
|
| 111 |
+
For every tool added a new event is created
|
| 112 |
+
|
| 113 |
+
- 'tool_trigger_TOOLNAME', where TOOLNAME is the id of the tool.
|
| 114 |
+
|
| 115 |
+
func : callable
|
| 116 |
+
Callback function for the toolmanager event with signature::
|
| 117 |
+
|
| 118 |
+
def func(event: ToolEvent) -> Any
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
cid
|
| 123 |
+
The callback id for the connection. This can be used in
|
| 124 |
+
`.toolmanager_disconnect`.
|
| 125 |
+
"""
|
| 126 |
+
return self._callbacks.connect(s, func)
|
| 127 |
+
|
| 128 |
+
def toolmanager_disconnect(self, cid):
|
| 129 |
+
"""
|
| 130 |
+
Disconnect callback id *cid*.
|
| 131 |
+
|
| 132 |
+
Example usage::
|
| 133 |
+
|
| 134 |
+
cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress)
|
| 135 |
+
#...later
|
| 136 |
+
toolmanager.toolmanager_disconnect(cid)
|
| 137 |
+
"""
|
| 138 |
+
return self._callbacks.disconnect(cid)
|
| 139 |
+
|
| 140 |
+
def message_event(self, message, sender=None):
|
| 141 |
+
"""Emit a `ToolManagerMessageEvent`."""
|
| 142 |
+
if sender is None:
|
| 143 |
+
sender = self
|
| 144 |
+
|
| 145 |
+
s = 'tool_message_event'
|
| 146 |
+
event = ToolManagerMessageEvent(s, sender, message)
|
| 147 |
+
self._callbacks.process(s, event)
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def active_toggle(self):
|
| 151 |
+
"""Currently toggled tools."""
|
| 152 |
+
return self._toggled
|
| 153 |
+
|
| 154 |
+
def get_tool_keymap(self, name):
|
| 155 |
+
"""
|
| 156 |
+
Return the keymap associated with the specified tool.
|
| 157 |
+
|
| 158 |
+
Parameters
|
| 159 |
+
----------
|
| 160 |
+
name : str
|
| 161 |
+
Name of the Tool.
|
| 162 |
+
|
| 163 |
+
Returns
|
| 164 |
+
-------
|
| 165 |
+
list of str
|
| 166 |
+
List of keys associated with the tool.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
keys = [k for k, i in self._keys.items() if i == name]
|
| 170 |
+
return keys
|
| 171 |
+
|
| 172 |
+
def _remove_keys(self, name):
|
| 173 |
+
for k in self.get_tool_keymap(name):
|
| 174 |
+
del self._keys[k]
|
| 175 |
+
|
| 176 |
+
def update_keymap(self, name, key):
|
| 177 |
+
"""
|
| 178 |
+
Set the keymap to associate with the specified tool.
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
name : str
|
| 183 |
+
Name of the Tool.
|
| 184 |
+
key : str or list of str
|
| 185 |
+
Keys to associate with the tool.
|
| 186 |
+
"""
|
| 187 |
+
if name not in self._tools:
|
| 188 |
+
raise KeyError(f'{name!r} not in Tools')
|
| 189 |
+
self._remove_keys(name)
|
| 190 |
+
if isinstance(key, str):
|
| 191 |
+
key = [key]
|
| 192 |
+
for k in key:
|
| 193 |
+
if k in self._keys:
|
| 194 |
+
_api.warn_external(
|
| 195 |
+
f'Key {k} changed from {self._keys[k]} to {name}')
|
| 196 |
+
self._keys[k] = name
|
| 197 |
+
|
| 198 |
+
def remove_tool(self, name):
|
| 199 |
+
"""
|
| 200 |
+
Remove tool named *name*.
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
----------
|
| 204 |
+
name : str
|
| 205 |
+
Name of the tool.
|
| 206 |
+
"""
|
| 207 |
+
tool = self.get_tool(name)
|
| 208 |
+
if getattr(tool, 'toggled', False): # If it's a toggled toggle tool, untoggle
|
| 209 |
+
self.trigger_tool(tool, 'toolmanager')
|
| 210 |
+
self._remove_keys(name)
|
| 211 |
+
event = ToolEvent('tool_removed_event', self, tool)
|
| 212 |
+
self._callbacks.process(event.name, event)
|
| 213 |
+
del self._tools[name]
|
| 214 |
+
|
| 215 |
+
def add_tool(self, name, tool, *args, **kwargs):
|
| 216 |
+
"""
|
| 217 |
+
Add *tool* to `ToolManager`.
|
| 218 |
+
|
| 219 |
+
If successful, adds a new event ``tool_trigger_{name}`` where
|
| 220 |
+
``{name}`` is the *name* of the tool; the event is fired every time the
|
| 221 |
+
tool is triggered.
|
| 222 |
+
|
| 223 |
+
Parameters
|
| 224 |
+
----------
|
| 225 |
+
name : str
|
| 226 |
+
Name of the tool, treated as the ID, has to be unique.
|
| 227 |
+
tool : type
|
| 228 |
+
Class of the tool to be added. A subclass will be used
|
| 229 |
+
instead if one was registered for the current canvas class.
|
| 230 |
+
*args, **kwargs
|
| 231 |
+
Passed to the *tool*'s constructor.
|
| 232 |
+
|
| 233 |
+
See Also
|
| 234 |
+
--------
|
| 235 |
+
matplotlib.backend_tools.ToolBase : The base class for tools.
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
tool_cls = backend_tools._find_tool_class(type(self.canvas), tool)
|
| 239 |
+
if not tool_cls:
|
| 240 |
+
raise ValueError('Impossible to find class for %s' % str(tool))
|
| 241 |
+
|
| 242 |
+
if name in self._tools:
|
| 243 |
+
_api.warn_external('A "Tool class" with the same name already '
|
| 244 |
+
'exists, not added')
|
| 245 |
+
return self._tools[name]
|
| 246 |
+
|
| 247 |
+
tool_obj = tool_cls(self, name, *args, **kwargs)
|
| 248 |
+
self._tools[name] = tool_obj
|
| 249 |
+
|
| 250 |
+
if tool_obj.default_keymap is not None:
|
| 251 |
+
self.update_keymap(name, tool_obj.default_keymap)
|
| 252 |
+
|
| 253 |
+
# For toggle tools init the radio_group in self._toggled
|
| 254 |
+
if isinstance(tool_obj, backend_tools.ToolToggleBase):
|
| 255 |
+
# None group is not mutually exclusive, a set is used to keep track
|
| 256 |
+
# of all toggled tools in this group
|
| 257 |
+
if tool_obj.radio_group is None:
|
| 258 |
+
self._toggled.setdefault(None, set())
|
| 259 |
+
else:
|
| 260 |
+
self._toggled.setdefault(tool_obj.radio_group, None)
|
| 261 |
+
|
| 262 |
+
# If initially toggled
|
| 263 |
+
if tool_obj.toggled:
|
| 264 |
+
self._handle_toggle(tool_obj, None, None)
|
| 265 |
+
tool_obj.set_figure(self.figure)
|
| 266 |
+
|
| 267 |
+
event = ToolEvent('tool_added_event', self, tool_obj)
|
| 268 |
+
self._callbacks.process(event.name, event)
|
| 269 |
+
|
| 270 |
+
return tool_obj
|
| 271 |
+
|
| 272 |
+
def _handle_toggle(self, tool, canvasevent, data):
|
| 273 |
+
"""
|
| 274 |
+
Toggle tools, need to untoggle prior to using other Toggle tool.
|
| 275 |
+
Called from trigger_tool.
|
| 276 |
+
|
| 277 |
+
Parameters
|
| 278 |
+
----------
|
| 279 |
+
tool : `.ToolBase`
|
| 280 |
+
canvasevent : Event
|
| 281 |
+
Original Canvas event or None.
|
| 282 |
+
data : object
|
| 283 |
+
Extra data to pass to the tool when triggering.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
radio_group = tool.radio_group
|
| 287 |
+
# radio_group None is not mutually exclusive
|
| 288 |
+
# just keep track of toggled tools in this group
|
| 289 |
+
if radio_group is None:
|
| 290 |
+
if tool.name in self._toggled[None]:
|
| 291 |
+
self._toggled[None].remove(tool.name)
|
| 292 |
+
else:
|
| 293 |
+
self._toggled[None].add(tool.name)
|
| 294 |
+
return
|
| 295 |
+
|
| 296 |
+
# If the tool already has a toggled state, untoggle it
|
| 297 |
+
if self._toggled[radio_group] == tool.name:
|
| 298 |
+
toggled = None
|
| 299 |
+
# If no tool was toggled in the radio_group
|
| 300 |
+
# toggle it
|
| 301 |
+
elif self._toggled[radio_group] is None:
|
| 302 |
+
toggled = tool.name
|
| 303 |
+
# Other tool in the radio_group is toggled
|
| 304 |
+
else:
|
| 305 |
+
# Untoggle previously toggled tool
|
| 306 |
+
self.trigger_tool(self._toggled[radio_group],
|
| 307 |
+
self,
|
| 308 |
+
canvasevent,
|
| 309 |
+
data)
|
| 310 |
+
toggled = tool.name
|
| 311 |
+
|
| 312 |
+
# Keep track of the toggled tool in the radio_group
|
| 313 |
+
self._toggled[radio_group] = toggled
|
| 314 |
+
|
| 315 |
+
def trigger_tool(self, name, sender=None, canvasevent=None, data=None):
|
| 316 |
+
"""
|
| 317 |
+
Trigger a tool and emit the ``tool_trigger_{name}`` event.
|
| 318 |
+
|
| 319 |
+
Parameters
|
| 320 |
+
----------
|
| 321 |
+
name : str
|
| 322 |
+
Name of the tool.
|
| 323 |
+
sender : object
|
| 324 |
+
Object that wishes to trigger the tool.
|
| 325 |
+
canvasevent : Event
|
| 326 |
+
Original Canvas event or None.
|
| 327 |
+
data : object
|
| 328 |
+
Extra data to pass to the tool when triggering.
|
| 329 |
+
"""
|
| 330 |
+
tool = self.get_tool(name)
|
| 331 |
+
if tool is None:
|
| 332 |
+
return
|
| 333 |
+
|
| 334 |
+
if sender is None:
|
| 335 |
+
sender = self
|
| 336 |
+
|
| 337 |
+
if isinstance(tool, backend_tools.ToolToggleBase):
|
| 338 |
+
self._handle_toggle(tool, canvasevent, data)
|
| 339 |
+
|
| 340 |
+
tool.trigger(sender, canvasevent, data) # Actually trigger Tool.
|
| 341 |
+
|
| 342 |
+
s = 'tool_trigger_%s' % name
|
| 343 |
+
event = ToolTriggerEvent(s, sender, tool, canvasevent, data)
|
| 344 |
+
self._callbacks.process(s, event)
|
| 345 |
+
|
| 346 |
+
def _key_press(self, event):
|
| 347 |
+
if event.key is None or self.keypresslock.locked():
|
| 348 |
+
return
|
| 349 |
+
|
| 350 |
+
name = self._keys.get(event.key, None)
|
| 351 |
+
if name is None:
|
| 352 |
+
return
|
| 353 |
+
self.trigger_tool(name, canvasevent=event)
|
| 354 |
+
|
| 355 |
+
@property
|
| 356 |
+
def tools(self):
|
| 357 |
+
"""A dict mapping tool name -> controlled tool."""
|
| 358 |
+
return self._tools
|
| 359 |
+
|
| 360 |
+
def get_tool(self, name, warn=True):
|
| 361 |
+
"""
|
| 362 |
+
Return the tool object with the given name.
|
| 363 |
+
|
| 364 |
+
For convenience, this passes tool objects through.
|
| 365 |
+
|
| 366 |
+
Parameters
|
| 367 |
+
----------
|
| 368 |
+
name : str or `.ToolBase`
|
| 369 |
+
Name of the tool, or the tool itself.
|
| 370 |
+
warn : bool, default: True
|
| 371 |
+
Whether a warning should be emitted it no tool with the given name
|
| 372 |
+
exists.
|
| 373 |
+
|
| 374 |
+
Returns
|
| 375 |
+
-------
|
| 376 |
+
`.ToolBase` or None
|
| 377 |
+
The tool or None if no tool with the given name exists.
|
| 378 |
+
"""
|
| 379 |
+
if (isinstance(name, backend_tools.ToolBase)
|
| 380 |
+
and name.name in self._tools):
|
| 381 |
+
return name
|
| 382 |
+
if name not in self._tools:
|
| 383 |
+
if warn:
|
| 384 |
+
_api.warn_external(
|
| 385 |
+
f"ToolManager does not control tool {name!r}")
|
| 386 |
+
return None
|
| 387 |
+
return self._tools[name]
|
moondream/lib/python3.10/site-packages/matplotlib/backend_tools.pyi
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
from matplotlib import cbook
|
| 3 |
+
from matplotlib.axes import Axes
|
| 4 |
+
from matplotlib.backend_bases import ToolContainerBase, FigureCanvasBase
|
| 5 |
+
from matplotlib.backend_managers import ToolManager, ToolEvent
|
| 6 |
+
from matplotlib.figure import Figure
|
| 7 |
+
from matplotlib.scale import ScaleBase
|
| 8 |
+
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
class Cursors(enum.IntEnum):
|
| 12 |
+
POINTER: int
|
| 13 |
+
HAND: int
|
| 14 |
+
SELECT_REGION: int
|
| 15 |
+
MOVE: int
|
| 16 |
+
WAIT: int
|
| 17 |
+
RESIZE_HORIZONTAL: int
|
| 18 |
+
RESIZE_VERTICAL: int
|
| 19 |
+
|
| 20 |
+
cursors = Cursors
|
| 21 |
+
|
| 22 |
+
class ToolBase:
|
| 23 |
+
@property
|
| 24 |
+
def default_keymap(self) -> list[str] | None: ...
|
| 25 |
+
description: str | None
|
| 26 |
+
image: str | None
|
| 27 |
+
def __init__(self, toolmanager: ToolManager, name: str) -> None: ...
|
| 28 |
+
@property
|
| 29 |
+
def name(self) -> str: ...
|
| 30 |
+
@property
|
| 31 |
+
def toolmanager(self) -> ToolManager: ...
|
| 32 |
+
@property
|
| 33 |
+
def canvas(self) -> FigureCanvasBase | None: ...
|
| 34 |
+
@property
|
| 35 |
+
def figure(self) -> Figure | None: ...
|
| 36 |
+
@figure.setter
|
| 37 |
+
def figure(self, figure: Figure | None) -> None: ...
|
| 38 |
+
def set_figure(self, figure: Figure | None) -> None: ...
|
| 39 |
+
def trigger(self, sender: Any, event: ToolEvent, data: Any = ...) -> None: ...
|
| 40 |
+
|
| 41 |
+
class ToolToggleBase(ToolBase):
|
| 42 |
+
radio_group: str | None
|
| 43 |
+
cursor: Cursors | None
|
| 44 |
+
default_toggled: bool
|
| 45 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 46 |
+
def enable(self, event: ToolEvent | None = ...) -> None: ...
|
| 47 |
+
def disable(self, event: ToolEvent | None = ...) -> None: ...
|
| 48 |
+
@property
|
| 49 |
+
def toggled(self) -> bool: ...
|
| 50 |
+
def set_figure(self, figure: Figure | None) -> None: ...
|
| 51 |
+
|
| 52 |
+
class ToolSetCursor(ToolBase): ...
|
| 53 |
+
|
| 54 |
+
class ToolCursorPosition(ToolBase):
|
| 55 |
+
def send_message(self, event: ToolEvent) -> None: ...
|
| 56 |
+
|
| 57 |
+
class RubberbandBase(ToolBase):
|
| 58 |
+
def draw_rubberband(self, *data) -> None: ...
|
| 59 |
+
def remove_rubberband(self) -> None: ...
|
| 60 |
+
|
| 61 |
+
class ToolQuit(ToolBase): ...
|
| 62 |
+
class ToolQuitAll(ToolBase): ...
|
| 63 |
+
class ToolGrid(ToolBase): ...
|
| 64 |
+
class ToolMinorGrid(ToolBase): ...
|
| 65 |
+
class ToolFullScreen(ToolBase): ...
|
| 66 |
+
|
| 67 |
+
class AxisScaleBase(ToolToggleBase):
|
| 68 |
+
def enable(self, event: ToolEvent | None = ...) -> None: ...
|
| 69 |
+
def disable(self, event: ToolEvent | None = ...) -> None: ...
|
| 70 |
+
|
| 71 |
+
class ToolYScale(AxisScaleBase):
|
| 72 |
+
def set_scale(self, ax: Axes, scale: str | ScaleBase) -> None: ...
|
| 73 |
+
|
| 74 |
+
class ToolXScale(AxisScaleBase):
|
| 75 |
+
def set_scale(self, ax, scale: str | ScaleBase) -> None: ...
|
| 76 |
+
|
| 77 |
+
class ToolViewsPositions(ToolBase):
|
| 78 |
+
views: dict[Figure | Axes, cbook._Stack]
|
| 79 |
+
positions: dict[Figure | Axes, cbook._Stack]
|
| 80 |
+
home_views: dict[Figure, dict[Axes, tuple[float, float, float, float]]]
|
| 81 |
+
def add_figure(self, figure: Figure) -> None: ...
|
| 82 |
+
def clear(self, figure: Figure) -> None: ...
|
| 83 |
+
def update_view(self) -> None: ...
|
| 84 |
+
def push_current(self, figure: Figure | None = ...) -> None: ...
|
| 85 |
+
def update_home_views(self, figure: Figure | None = ...) -> None: ...
|
| 86 |
+
def home(self) -> None: ...
|
| 87 |
+
def back(self) -> None: ...
|
| 88 |
+
def forward(self) -> None: ...
|
| 89 |
+
|
| 90 |
+
class ViewsPositionsBase(ToolBase): ...
|
| 91 |
+
class ToolHome(ViewsPositionsBase): ...
|
| 92 |
+
class ToolBack(ViewsPositionsBase): ...
|
| 93 |
+
class ToolForward(ViewsPositionsBase): ...
|
| 94 |
+
class ConfigureSubplotsBase(ToolBase): ...
|
| 95 |
+
class SaveFigureBase(ToolBase): ...
|
| 96 |
+
|
| 97 |
+
class ZoomPanBase(ToolToggleBase):
|
| 98 |
+
base_scale: float
|
| 99 |
+
scrollthresh: float
|
| 100 |
+
lastscroll: float
|
| 101 |
+
def __init__(self, *args) -> None: ...
|
| 102 |
+
def enable(self, event: ToolEvent | None = ...) -> None: ...
|
| 103 |
+
def disable(self, event: ToolEvent | None = ...) -> None: ...
|
| 104 |
+
def scroll_zoom(self, event: ToolEvent) -> None: ...
|
| 105 |
+
|
| 106 |
+
class ToolZoom(ZoomPanBase): ...
|
| 107 |
+
class ToolPan(ZoomPanBase): ...
|
| 108 |
+
|
| 109 |
+
class ToolHelpBase(ToolBase):
|
| 110 |
+
@staticmethod
|
| 111 |
+
def format_shortcut(key_sequence: str) -> str: ...
|
| 112 |
+
|
| 113 |
+
class ToolCopyToClipboardBase(ToolBase): ...
|
| 114 |
+
|
| 115 |
+
default_tools: dict[str, ToolBase]
|
| 116 |
+
default_toolbar_tools: list[list[str | list[str]]]
|
| 117 |
+
|
| 118 |
+
def add_tools_to_manager(
|
| 119 |
+
toolmanager: ToolManager, tools: dict[str, type[ToolBase]] = ...
|
| 120 |
+
) -> None: ...
|
| 121 |
+
def add_tools_to_container(container: ToolContainerBase, tools: list[Any] = ...) -> None: ...
|
moondream/lib/python3.10/site-packages/matplotlib/bezier.pyi
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.typing import ArrayLike
|
| 6 |
+
|
| 7 |
+
from .path import Path
|
| 8 |
+
|
| 9 |
+
class NonIntersectingPathException(ValueError): ...
|
| 10 |
+
|
| 11 |
+
def get_intersection(
|
| 12 |
+
cx1: float,
|
| 13 |
+
cy1: float,
|
| 14 |
+
cos_t1: float,
|
| 15 |
+
sin_t1: float,
|
| 16 |
+
cx2: float,
|
| 17 |
+
cy2: float,
|
| 18 |
+
cos_t2: float,
|
| 19 |
+
sin_t2: float,
|
| 20 |
+
) -> tuple[float, float]: ...
|
| 21 |
+
def get_normal_points(
|
| 22 |
+
cx: float, cy: float, cos_t: float, sin_t: float, length: float
|
| 23 |
+
) -> tuple[float, float, float, float]: ...
|
| 24 |
+
def split_de_casteljau(beta: ArrayLike, t: float) -> tuple[np.ndarray, np.ndarray]: ...
|
| 25 |
+
def find_bezier_t_intersecting_with_closedpath(
|
| 26 |
+
bezier_point_at_t: Callable[[float], tuple[float, float]],
|
| 27 |
+
inside_closedpath: Callable[[tuple[float, float]], bool],
|
| 28 |
+
t0: float = ...,
|
| 29 |
+
t1: float = ...,
|
| 30 |
+
tolerance: float = ...,
|
| 31 |
+
) -> tuple[float, float]: ...
|
| 32 |
+
|
| 33 |
+
# TODO make generic over d, the dimension? ndarraydim
|
| 34 |
+
class BezierSegment:
|
| 35 |
+
def __init__(self, control_points: ArrayLike) -> None: ...
|
| 36 |
+
def __call__(self, t: ArrayLike) -> np.ndarray: ...
|
| 37 |
+
def point_at_t(self, t: float) -> tuple[float, ...]: ...
|
| 38 |
+
@property
|
| 39 |
+
def control_points(self) -> np.ndarray: ...
|
| 40 |
+
@property
|
| 41 |
+
def dimension(self) -> int: ...
|
| 42 |
+
@property
|
| 43 |
+
def degree(self) -> int: ...
|
| 44 |
+
@property
|
| 45 |
+
def polynomial_coefficients(self) -> np.ndarray: ...
|
| 46 |
+
def axis_aligned_extrema(self) -> tuple[np.ndarray, np.ndarray]: ...
|
| 47 |
+
|
| 48 |
+
def split_bezier_intersecting_with_closedpath(
|
| 49 |
+
bezier: ArrayLike,
|
| 50 |
+
inside_closedpath: Callable[[tuple[float, float]], bool],
|
| 51 |
+
tolerance: float = ...,
|
| 52 |
+
) -> tuple[np.ndarray, np.ndarray]: ...
|
| 53 |
+
def split_path_inout(
|
| 54 |
+
path: Path,
|
| 55 |
+
inside: Callable[[tuple[float, float]], bool],
|
| 56 |
+
tolerance: float = ...,
|
| 57 |
+
reorder_inout: bool = ...,
|
| 58 |
+
) -> tuple[Path, Path]: ...
|
| 59 |
+
def inside_circle(
|
| 60 |
+
cx: float, cy: float, r: float
|
| 61 |
+
) -> Callable[[tuple[float, float]], bool]: ...
|
| 62 |
+
def get_cos_sin(x0: float, y0: float, x1: float, y1: float) -> tuple[float, float]: ...
|
| 63 |
+
def check_if_parallel(
|
| 64 |
+
dx1: float, dy1: float, dx2: float, dy2: float, tolerance: float = ...
|
| 65 |
+
) -> Literal[-1, False, 1]: ...
|
| 66 |
+
def get_parallels(
|
| 67 |
+
bezier2: ArrayLike, width: float
|
| 68 |
+
) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]: ...
|
| 69 |
+
def find_control_points(
|
| 70 |
+
c1x: float, c1y: float, mmx: float, mmy: float, c2x: float, c2y: float
|
| 71 |
+
) -> list[tuple[float, float]]: ...
|
| 72 |
+
def make_wedged_bezier2(
|
| 73 |
+
bezier2: ArrayLike, width: float, w1: float = ..., wm: float = ..., w2: float = ...
|
| 74 |
+
) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]: ...
|
moondream/lib/python3.10/site-packages/matplotlib/colorbar.pyi
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib.spines as mspines
|
| 2 |
+
from matplotlib import cm, collections, colors, contour, colorizer
|
| 3 |
+
from matplotlib.axes import Axes
|
| 4 |
+
from matplotlib.axis import Axis
|
| 5 |
+
from matplotlib.backend_bases import RendererBase
|
| 6 |
+
from matplotlib.patches import Patch
|
| 7 |
+
from matplotlib.ticker import Locator, Formatter
|
| 8 |
+
from matplotlib.transforms import Bbox
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from numpy.typing import ArrayLike
|
| 12 |
+
from collections.abc import Sequence
|
| 13 |
+
from typing import Any, Literal, overload
|
| 14 |
+
from .typing import ColorType
|
| 15 |
+
|
| 16 |
+
class _ColorbarSpine(mspines.Spines):
|
| 17 |
+
def __init__(self, axes: Axes): ...
|
| 18 |
+
def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox:...
|
| 19 |
+
def set_xy(self, xy: ArrayLike) -> None: ...
|
| 20 |
+
def draw(self, renderer: RendererBase | None) -> None:...
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Colorbar:
|
| 24 |
+
n_rasterize: int
|
| 25 |
+
mappable: cm.ScalarMappable | colorizer.ColorizingArtist
|
| 26 |
+
ax: Axes
|
| 27 |
+
alpha: float | None
|
| 28 |
+
cmap: colors.Colormap
|
| 29 |
+
norm: colors.Normalize
|
| 30 |
+
values: Sequence[float] | None
|
| 31 |
+
boundaries: Sequence[float] | None
|
| 32 |
+
extend: Literal["neither", "both", "min", "max"]
|
| 33 |
+
spacing: Literal["uniform", "proportional"]
|
| 34 |
+
orientation: Literal["vertical", "horizontal"]
|
| 35 |
+
drawedges: bool
|
| 36 |
+
extendfrac: Literal["auto"] | float | Sequence[float] | None
|
| 37 |
+
extendrect: bool
|
| 38 |
+
solids: None | collections.QuadMesh
|
| 39 |
+
solids_patches: list[Patch]
|
| 40 |
+
lines: list[collections.LineCollection]
|
| 41 |
+
outline: _ColorbarSpine
|
| 42 |
+
dividers: collections.LineCollection
|
| 43 |
+
ticklocation: Literal["left", "right", "top", "bottom"]
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
ax: Axes,
|
| 47 |
+
mappable: cm.ScalarMappable | colorizer.ColorizingArtist | None = ...,
|
| 48 |
+
*,
|
| 49 |
+
cmap: str | colors.Colormap | None = ...,
|
| 50 |
+
norm: colors.Normalize | None = ...,
|
| 51 |
+
alpha: float | None = ...,
|
| 52 |
+
values: Sequence[float] | None = ...,
|
| 53 |
+
boundaries: Sequence[float] | None = ...,
|
| 54 |
+
orientation: Literal["vertical", "horizontal"] | None = ...,
|
| 55 |
+
ticklocation: Literal["auto", "left", "right", "top", "bottom"] = ...,
|
| 56 |
+
extend: Literal["neither", "both", "min", "max"] | None = ...,
|
| 57 |
+
spacing: Literal["uniform", "proportional"] = ...,
|
| 58 |
+
ticks: Sequence[float] | Locator | None = ...,
|
| 59 |
+
format: str | Formatter | None = ...,
|
| 60 |
+
drawedges: bool = ...,
|
| 61 |
+
extendfrac: Literal["auto"] | float | Sequence[float] | None = ...,
|
| 62 |
+
extendrect: bool = ...,
|
| 63 |
+
label: str = ...,
|
| 64 |
+
location: Literal["left", "right", "top", "bottom"] | None = ...
|
| 65 |
+
) -> None: ...
|
| 66 |
+
@property
|
| 67 |
+
def long_axis(self) -> Axis: ...
|
| 68 |
+
@property
|
| 69 |
+
def locator(self) -> Locator: ...
|
| 70 |
+
@locator.setter
|
| 71 |
+
def locator(self, loc: Locator) -> None: ...
|
| 72 |
+
@property
|
| 73 |
+
def minorlocator(self) -> Locator: ...
|
| 74 |
+
@minorlocator.setter
|
| 75 |
+
def minorlocator(self, loc: Locator) -> None: ...
|
| 76 |
+
@property
|
| 77 |
+
def formatter(self) -> Formatter: ...
|
| 78 |
+
@formatter.setter
|
| 79 |
+
def formatter(self, fmt: Formatter) -> None: ...
|
| 80 |
+
@property
|
| 81 |
+
def minorformatter(self) -> Formatter: ...
|
| 82 |
+
@minorformatter.setter
|
| 83 |
+
def minorformatter(self, fmt: Formatter) -> None: ...
|
| 84 |
+
def update_normal(self, mappable: cm.ScalarMappable | None = ...) -> None: ...
|
| 85 |
+
@overload
|
| 86 |
+
def add_lines(self, CS: contour.ContourSet, erase: bool = ...) -> None: ...
|
| 87 |
+
@overload
|
| 88 |
+
def add_lines(
|
| 89 |
+
self,
|
| 90 |
+
levels: ArrayLike,
|
| 91 |
+
colors: ColorType | Sequence[ColorType],
|
| 92 |
+
linewidths: float | ArrayLike,
|
| 93 |
+
erase: bool = ...,
|
| 94 |
+
) -> None: ...
|
| 95 |
+
def update_ticks(self) -> None: ...
|
| 96 |
+
def set_ticks(
|
| 97 |
+
self,
|
| 98 |
+
ticks: Sequence[float] | Locator,
|
| 99 |
+
*,
|
| 100 |
+
labels: Sequence[str] | None = ...,
|
| 101 |
+
minor: bool = ...,
|
| 102 |
+
**kwargs
|
| 103 |
+
) -> None: ...
|
| 104 |
+
def get_ticks(self, minor: bool = ...) -> np.ndarray: ...
|
| 105 |
+
def set_ticklabels(
|
| 106 |
+
self,
|
| 107 |
+
ticklabels: Sequence[str],
|
| 108 |
+
*,
|
| 109 |
+
minor: bool = ...,
|
| 110 |
+
**kwargs
|
| 111 |
+
) -> None: ...
|
| 112 |
+
def minorticks_on(self) -> None: ...
|
| 113 |
+
def minorticks_off(self) -> None: ...
|
| 114 |
+
def set_label(self, label: str, *, loc: str | None = ..., **kwargs) -> None: ...
|
| 115 |
+
def set_alpha(self, alpha: float | np.ndarray) -> None: ...
|
| 116 |
+
def remove(self) -> None: ...
|
| 117 |
+
def drag_pan(self, button: Any, key: Any, x: float, y: float) -> None: ...
|
| 118 |
+
|
| 119 |
+
ColorbarBase = Colorbar
|
| 120 |
+
|
| 121 |
+
def make_axes(
|
| 122 |
+
parents: Axes | list[Axes] | np.ndarray,
|
| 123 |
+
location: Literal["left", "right", "top", "bottom"] | None = ...,
|
| 124 |
+
orientation: Literal["vertical", "horizontal"] | None = ...,
|
| 125 |
+
fraction: float = ...,
|
| 126 |
+
shrink: float = ...,
|
| 127 |
+
aspect: float = ...,
|
| 128 |
+
**kwargs
|
| 129 |
+
) -> tuple[Axes, dict[str, Any]]: ...
|
| 130 |
+
def make_axes_gridspec(
|
| 131 |
+
parent: Axes,
|
| 132 |
+
*,
|
| 133 |
+
location: Literal["left", "right", "top", "bottom"] | None = ...,
|
| 134 |
+
orientation: Literal["vertical", "horizontal"] | None = ...,
|
| 135 |
+
fraction: float = ...,
|
| 136 |
+
shrink: float = ...,
|
| 137 |
+
aspect: float = ...,
|
| 138 |
+
**kwargs
|
| 139 |
+
) -> tuple[Axes, dict[str, Any]]: ...
|
moondream/lib/python3.10/site-packages/matplotlib/contour.py
ADDED
|
@@ -0,0 +1,1709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Classes to support contour plotting and labelling for the Axes class.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from contextlib import ExitStack
|
| 6 |
+
import functools
|
| 7 |
+
import math
|
| 8 |
+
from numbers import Integral
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from numpy import ma
|
| 12 |
+
|
| 13 |
+
import matplotlib as mpl
|
| 14 |
+
from matplotlib import _api, _docstring
|
| 15 |
+
from matplotlib.backend_bases import MouseButton
|
| 16 |
+
from matplotlib.lines import Line2D
|
| 17 |
+
from matplotlib.path import Path
|
| 18 |
+
from matplotlib.text import Text
|
| 19 |
+
import matplotlib.ticker as ticker
|
| 20 |
+
import matplotlib.cm as cm
|
| 21 |
+
import matplotlib.colors as mcolors
|
| 22 |
+
import matplotlib.collections as mcoll
|
| 23 |
+
import matplotlib.font_manager as font_manager
|
| 24 |
+
import matplotlib.cbook as cbook
|
| 25 |
+
import matplotlib.patches as mpatches
|
| 26 |
+
import matplotlib.transforms as mtransforms
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _contour_labeler_event_handler(cs, inline, inline_spacing, event):
|
| 30 |
+
canvas = cs.axes.get_figure(root=True).canvas
|
| 31 |
+
is_button = event.name == "button_press_event"
|
| 32 |
+
is_key = event.name == "key_press_event"
|
| 33 |
+
# Quit (even if not in infinite mode; this is consistent with
|
| 34 |
+
# MATLAB and sometimes quite useful, but will require the user to
|
| 35 |
+
# test how many points were actually returned before using data).
|
| 36 |
+
if (is_button and event.button == MouseButton.MIDDLE
|
| 37 |
+
or is_key and event.key in ["escape", "enter"]):
|
| 38 |
+
canvas.stop_event_loop()
|
| 39 |
+
# Pop last click.
|
| 40 |
+
elif (is_button and event.button == MouseButton.RIGHT
|
| 41 |
+
or is_key and event.key in ["backspace", "delete"]):
|
| 42 |
+
# Unfortunately, if one is doing inline labels, then there is currently
|
| 43 |
+
# no way to fix the broken contour - once humpty-dumpty is broken, he
|
| 44 |
+
# can't be put back together. In inline mode, this does nothing.
|
| 45 |
+
if not inline:
|
| 46 |
+
cs.pop_label()
|
| 47 |
+
canvas.draw()
|
| 48 |
+
# Add new click.
|
| 49 |
+
elif (is_button and event.button == MouseButton.LEFT
|
| 50 |
+
# On macOS/gtk, some keys return None.
|
| 51 |
+
or is_key and event.key is not None):
|
| 52 |
+
if cs.axes.contains(event)[0]:
|
| 53 |
+
cs.add_label_near(event.x, event.y, transform=False,
|
| 54 |
+
inline=inline, inline_spacing=inline_spacing)
|
| 55 |
+
canvas.draw()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ContourLabeler:
|
| 59 |
+
"""Mixin to provide labelling capability to `.ContourSet`."""
|
| 60 |
+
|
| 61 |
+
def clabel(self, levels=None, *,
|
| 62 |
+
fontsize=None, inline=True, inline_spacing=5, fmt=None,
|
| 63 |
+
colors=None, use_clabeltext=False, manual=False,
|
| 64 |
+
rightside_up=True, zorder=None):
|
| 65 |
+
"""
|
| 66 |
+
Label a contour plot.
|
| 67 |
+
|
| 68 |
+
Adds labels to line contours in this `.ContourSet` (which inherits from
|
| 69 |
+
this mixin class).
|
| 70 |
+
|
| 71 |
+
Parameters
|
| 72 |
+
----------
|
| 73 |
+
levels : array-like, optional
|
| 74 |
+
A list of level values, that should be labeled. The list must be
|
| 75 |
+
a subset of ``cs.levels``. If not given, all levels are labeled.
|
| 76 |
+
|
| 77 |
+
fontsize : str or float, default: :rc:`font.size`
|
| 78 |
+
Size in points or relative size e.g., 'smaller', 'x-large'.
|
| 79 |
+
See `.Text.set_size` for accepted string values.
|
| 80 |
+
|
| 81 |
+
colors : :mpltype:`color` or colors or None, default: None
|
| 82 |
+
The label colors:
|
| 83 |
+
|
| 84 |
+
- If *None*, the color of each label matches the color of
|
| 85 |
+
the corresponding contour.
|
| 86 |
+
|
| 87 |
+
- If one string color, e.g., *colors* = 'r' or *colors* =
|
| 88 |
+
'red', all labels will be plotted in this color.
|
| 89 |
+
|
| 90 |
+
- If a tuple of colors (string, float, RGB, etc), different labels
|
| 91 |
+
will be plotted in different colors in the order specified.
|
| 92 |
+
|
| 93 |
+
inline : bool, default: True
|
| 94 |
+
If ``True`` the underlying contour is removed where the label is
|
| 95 |
+
placed.
|
| 96 |
+
|
| 97 |
+
inline_spacing : float, default: 5
|
| 98 |
+
Space in pixels to leave on each side of label when placing inline.
|
| 99 |
+
|
| 100 |
+
This spacing will be exact for labels at locations where the
|
| 101 |
+
contour is straight, less so for labels on curved contours.
|
| 102 |
+
|
| 103 |
+
fmt : `.Formatter` or str or callable or dict, optional
|
| 104 |
+
How the levels are formatted:
|
| 105 |
+
|
| 106 |
+
- If a `.Formatter`, it is used to format all levels at once, using
|
| 107 |
+
its `.Formatter.format_ticks` method.
|
| 108 |
+
- If a str, it is interpreted as a %-style format string.
|
| 109 |
+
- If a callable, it is called with one level at a time and should
|
| 110 |
+
return the corresponding label.
|
| 111 |
+
- If a dict, it should directly map levels to labels.
|
| 112 |
+
|
| 113 |
+
The default is to use a standard `.ScalarFormatter`.
|
| 114 |
+
|
| 115 |
+
manual : bool or iterable, default: False
|
| 116 |
+
If ``True``, contour labels will be placed manually using
|
| 117 |
+
mouse clicks. Click the first button near a contour to
|
| 118 |
+
add a label, click the second button (or potentially both
|
| 119 |
+
mouse buttons at once) to finish adding labels. The third
|
| 120 |
+
button can be used to remove the last label added, but
|
| 121 |
+
only if labels are not inline. Alternatively, the keyboard
|
| 122 |
+
can be used to select label locations (enter to end label
|
| 123 |
+
placement, delete or backspace act like the third mouse button,
|
| 124 |
+
and any other key will select a label location).
|
| 125 |
+
|
| 126 |
+
*manual* can also be an iterable object of (x, y) tuples.
|
| 127 |
+
Contour labels will be created as if mouse is clicked at each
|
| 128 |
+
(x, y) position.
|
| 129 |
+
|
| 130 |
+
rightside_up : bool, default: True
|
| 131 |
+
If ``True``, label rotations will always be plus
|
| 132 |
+
or minus 90 degrees from level.
|
| 133 |
+
|
| 134 |
+
use_clabeltext : bool, default: False
|
| 135 |
+
If ``True``, use `.Text.set_transform_rotates_text` to ensure that
|
| 136 |
+
label rotation is updated whenever the Axes aspect changes.
|
| 137 |
+
|
| 138 |
+
zorder : float or None, default: ``(2 + contour.get_zorder())``
|
| 139 |
+
zorder of the contour labels.
|
| 140 |
+
|
| 141 |
+
Returns
|
| 142 |
+
-------
|
| 143 |
+
labels
|
| 144 |
+
A list of `.Text` instances for the labels.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
# Based on the input arguments, clabel() adds a list of "label
|
| 148 |
+
# specific" attributes to the ContourSet object. These attributes are
|
| 149 |
+
# all of the form label* and names should be fairly self explanatory.
|
| 150 |
+
#
|
| 151 |
+
# Once these attributes are set, clabel passes control to the labels()
|
| 152 |
+
# method (for automatic label placement) or blocking_input_loop and
|
| 153 |
+
# _contour_labeler_event_handler (for manual label placement).
|
| 154 |
+
|
| 155 |
+
if fmt is None:
|
| 156 |
+
fmt = ticker.ScalarFormatter(useOffset=False)
|
| 157 |
+
fmt.create_dummy_axis()
|
| 158 |
+
self.labelFmt = fmt
|
| 159 |
+
self._use_clabeltext = use_clabeltext
|
| 160 |
+
self.labelManual = manual
|
| 161 |
+
self.rightside_up = rightside_up
|
| 162 |
+
self._clabel_zorder = 2 + self.get_zorder() if zorder is None else zorder
|
| 163 |
+
|
| 164 |
+
if levels is None:
|
| 165 |
+
levels = self.levels
|
| 166 |
+
indices = list(range(len(self.cvalues)))
|
| 167 |
+
else:
|
| 168 |
+
levlabs = list(levels)
|
| 169 |
+
indices, levels = [], []
|
| 170 |
+
for i, lev in enumerate(self.levels):
|
| 171 |
+
if lev in levlabs:
|
| 172 |
+
indices.append(i)
|
| 173 |
+
levels.append(lev)
|
| 174 |
+
if len(levels) < len(levlabs):
|
| 175 |
+
raise ValueError(f"Specified levels {levlabs} don't match "
|
| 176 |
+
f"available levels {self.levels}")
|
| 177 |
+
self.labelLevelList = levels
|
| 178 |
+
self.labelIndiceList = indices
|
| 179 |
+
|
| 180 |
+
self._label_font_props = font_manager.FontProperties(size=fontsize)
|
| 181 |
+
|
| 182 |
+
if colors is None:
|
| 183 |
+
self.labelMappable = self
|
| 184 |
+
self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
|
| 185 |
+
else:
|
| 186 |
+
cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
|
| 187 |
+
self.labelCValueList = list(range(len(self.labelLevelList)))
|
| 188 |
+
self.labelMappable = cm.ScalarMappable(cmap=cmap,
|
| 189 |
+
norm=mcolors.NoNorm())
|
| 190 |
+
|
| 191 |
+
self.labelXYs = []
|
| 192 |
+
|
| 193 |
+
if np.iterable(manual):
|
| 194 |
+
for x, y in manual:
|
| 195 |
+
self.add_label_near(x, y, inline, inline_spacing)
|
| 196 |
+
elif manual:
|
| 197 |
+
print('Select label locations manually using first mouse button.')
|
| 198 |
+
print('End manual selection with second mouse button.')
|
| 199 |
+
if not inline:
|
| 200 |
+
print('Remove last label by clicking third mouse button.')
|
| 201 |
+
mpl._blocking_input.blocking_input_loop(
|
| 202 |
+
self.axes.get_figure(root=True),
|
| 203 |
+
["button_press_event", "key_press_event"],
|
| 204 |
+
timeout=-1, handler=functools.partial(
|
| 205 |
+
_contour_labeler_event_handler,
|
| 206 |
+
self, inline, inline_spacing))
|
| 207 |
+
else:
|
| 208 |
+
self.labels(inline, inline_spacing)
|
| 209 |
+
|
| 210 |
+
return cbook.silent_list('text.Text', self.labelTexts)
|
| 211 |
+
|
| 212 |
+
def print_label(self, linecontour, labelwidth):
|
| 213 |
+
"""Return whether a contour is long enough to hold a label."""
|
| 214 |
+
return (len(linecontour) > 10 * labelwidth
|
| 215 |
+
or (len(linecontour)
|
| 216 |
+
and (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()))
|
| 217 |
+
|
| 218 |
+
def too_close(self, x, y, lw):
|
| 219 |
+
"""Return whether a label is already near this location."""
|
| 220 |
+
thresh = (1.2 * lw) ** 2
|
| 221 |
+
return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
|
| 222 |
+
for loc in self.labelXYs)
|
| 223 |
+
|
| 224 |
+
def _get_nth_label_width(self, nth):
|
| 225 |
+
"""Return the width of the *nth* label, in pixels."""
|
| 226 |
+
fig = self.axes.get_figure(root=False)
|
| 227 |
+
renderer = fig.get_figure(root=True)._get_renderer()
|
| 228 |
+
return (Text(0, 0,
|
| 229 |
+
self.get_text(self.labelLevelList[nth], self.labelFmt),
|
| 230 |
+
figure=fig, fontproperties=self._label_font_props)
|
| 231 |
+
.get_window_extent(renderer).width)
|
| 232 |
+
|
| 233 |
+
def get_text(self, lev, fmt):
|
| 234 |
+
"""Get the text of the label."""
|
| 235 |
+
if isinstance(lev, str):
|
| 236 |
+
return lev
|
| 237 |
+
elif isinstance(fmt, dict):
|
| 238 |
+
return fmt.get(lev, '%1.3f')
|
| 239 |
+
elif callable(getattr(fmt, "format_ticks", None)):
|
| 240 |
+
return fmt.format_ticks([*self.labelLevelList, lev])[-1]
|
| 241 |
+
elif callable(fmt):
|
| 242 |
+
return fmt(lev)
|
| 243 |
+
else:
|
| 244 |
+
return fmt % lev
|
| 245 |
+
|
| 246 |
+
def locate_label(self, linecontour, labelwidth):
|
| 247 |
+
"""
|
| 248 |
+
Find good place to draw a label (relatively flat part of the contour).
|
| 249 |
+
"""
|
| 250 |
+
ctr_size = len(linecontour)
|
| 251 |
+
n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1
|
| 252 |
+
block_size = ctr_size if n_blocks == 1 else int(labelwidth)
|
| 253 |
+
# Split contour into blocks of length ``block_size``, filling the last
|
| 254 |
+
# block by cycling the contour start (per `np.resize` semantics). (Due
|
| 255 |
+
# to cycling, the index returned is taken modulo ctr_size.)
|
| 256 |
+
xx = np.resize(linecontour[:, 0], (n_blocks, block_size))
|
| 257 |
+
yy = np.resize(linecontour[:, 1], (n_blocks, block_size))
|
| 258 |
+
yfirst = yy[:, :1]
|
| 259 |
+
ylast = yy[:, -1:]
|
| 260 |
+
xfirst = xx[:, :1]
|
| 261 |
+
xlast = xx[:, -1:]
|
| 262 |
+
s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst)
|
| 263 |
+
l = np.hypot(xlast - xfirst, ylast - yfirst)
|
| 264 |
+
# Ignore warning that divide by zero throws, as this is a valid option
|
| 265 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
| 266 |
+
distances = (abs(s) / l).sum(axis=-1)
|
| 267 |
+
# Labels are drawn in the middle of the block (``hbsize``) where the
|
| 268 |
+
# contour is the closest (per ``distances``) to a straight line, but
|
| 269 |
+
# not `too_close()` to a preexisting label.
|
| 270 |
+
hbsize = block_size // 2
|
| 271 |
+
adist = np.argsort(distances)
|
| 272 |
+
# If all candidates are `too_close()`, go back to the straightest part
|
| 273 |
+
# (``adist[0]``).
|
| 274 |
+
for idx in np.append(adist, adist[0]):
|
| 275 |
+
x, y = xx[idx, hbsize], yy[idx, hbsize]
|
| 276 |
+
if not self.too_close(x, y, labelwidth):
|
| 277 |
+
break
|
| 278 |
+
return x, y, (idx * block_size + hbsize) % ctr_size
|
| 279 |
+
|
| 280 |
+
def _split_path_and_get_label_rotation(self, path, idx, screen_pos, lw, spacing=5):
|
| 281 |
+
"""
|
| 282 |
+
Prepare for insertion of a label at index *idx* of *path*.
|
| 283 |
+
|
| 284 |
+
Parameters
|
| 285 |
+
----------
|
| 286 |
+
path : Path
|
| 287 |
+
The path where the label will be inserted, in data space.
|
| 288 |
+
idx : int
|
| 289 |
+
The vertex index after which the label will be inserted.
|
| 290 |
+
screen_pos : (float, float)
|
| 291 |
+
The position where the label will be inserted, in screen space.
|
| 292 |
+
lw : float
|
| 293 |
+
The label width, in screen space.
|
| 294 |
+
spacing : float
|
| 295 |
+
Extra spacing around the label, in screen space.
|
| 296 |
+
|
| 297 |
+
Returns
|
| 298 |
+
-------
|
| 299 |
+
path : Path
|
| 300 |
+
The path, broken so that the label can be drawn over it.
|
| 301 |
+
angle : float
|
| 302 |
+
The rotation of the label.
|
| 303 |
+
|
| 304 |
+
Notes
|
| 305 |
+
-----
|
| 306 |
+
Both tasks are done together to avoid calculating path lengths multiple times,
|
| 307 |
+
which is relatively costly.
|
| 308 |
+
|
| 309 |
+
The method used here involves computing the path length along the contour in
|
| 310 |
+
pixel coordinates and then looking (label width / 2) away from central point to
|
| 311 |
+
determine rotation and then to break contour if desired. The extra spacing is
|
| 312 |
+
taken into account when breaking the path, but not when computing the angle.
|
| 313 |
+
"""
|
| 314 |
+
xys = path.vertices
|
| 315 |
+
codes = path.codes
|
| 316 |
+
|
| 317 |
+
# Insert a vertex at idx/pos (converting back to data space), if there isn't yet
|
| 318 |
+
# a vertex there. With infinite precision one could also always insert the
|
| 319 |
+
# extra vertex (it will get masked out by the label below anyways), but floating
|
| 320 |
+
# point inaccuracies (the point can have undergone a data->screen->data
|
| 321 |
+
# transform loop) can slightly shift the point and e.g. shift the angle computed
|
| 322 |
+
# below from exactly zero to nonzero.
|
| 323 |
+
pos = self.get_transform().inverted().transform(screen_pos)
|
| 324 |
+
if not np.allclose(pos, xys[idx]):
|
| 325 |
+
xys = np.insert(xys, idx, pos, axis=0)
|
| 326 |
+
codes = np.insert(codes, idx, Path.LINETO)
|
| 327 |
+
|
| 328 |
+
# Find the connected component where the label will be inserted. Note that a
|
| 329 |
+
# path always starts with a MOVETO, and we consider there's an implicit
|
| 330 |
+
# MOVETO (closing the last path) at the end.
|
| 331 |
+
movetos = (codes == Path.MOVETO).nonzero()[0]
|
| 332 |
+
start = movetos[movetos <= idx][-1]
|
| 333 |
+
try:
|
| 334 |
+
stop = movetos[movetos > idx][0]
|
| 335 |
+
except IndexError:
|
| 336 |
+
stop = len(codes)
|
| 337 |
+
|
| 338 |
+
# Restrict ourselves to the connected component.
|
| 339 |
+
cc_xys = xys[start:stop]
|
| 340 |
+
idx -= start
|
| 341 |
+
|
| 342 |
+
# If the path is closed, rotate it s.t. it starts at the label.
|
| 343 |
+
is_closed_path = codes[stop - 1] == Path.CLOSEPOLY
|
| 344 |
+
if is_closed_path:
|
| 345 |
+
cc_xys = np.concatenate([cc_xys[idx:-1], cc_xys[:idx+1]])
|
| 346 |
+
idx = 0
|
| 347 |
+
|
| 348 |
+
# Like np.interp, but additionally vectorized over fp.
|
| 349 |
+
def interp_vec(x, xp, fp): return [np.interp(x, xp, col) for col in fp.T]
|
| 350 |
+
|
| 351 |
+
# Use cumulative path lengths ("cpl") as curvilinear coordinate along contour.
|
| 352 |
+
screen_xys = self.get_transform().transform(cc_xys)
|
| 353 |
+
path_cpls = np.insert(
|
| 354 |
+
np.cumsum(np.hypot(*np.diff(screen_xys, axis=0).T)), 0, 0)
|
| 355 |
+
path_cpls -= path_cpls[idx]
|
| 356 |
+
|
| 357 |
+
# Use linear interpolation to get end coordinates of label.
|
| 358 |
+
target_cpls = np.array([-lw/2, lw/2])
|
| 359 |
+
if is_closed_path: # For closed paths, target from the other end.
|
| 360 |
+
target_cpls[0] += (path_cpls[-1] - path_cpls[0])
|
| 361 |
+
(sx0, sx1), (sy0, sy1) = interp_vec(target_cpls, path_cpls, screen_xys)
|
| 362 |
+
angle = np.rad2deg(np.arctan2(sy1 - sy0, sx1 - sx0)) # Screen space.
|
| 363 |
+
if self.rightside_up: # Fix angle so text is never upside-down
|
| 364 |
+
angle = (angle + 90) % 180 - 90
|
| 365 |
+
|
| 366 |
+
target_cpls += [-spacing, +spacing] # Expand range by spacing.
|
| 367 |
+
|
| 368 |
+
# Get indices near points of interest; use -1 as out of bounds marker.
|
| 369 |
+
i0, i1 = np.interp(target_cpls, path_cpls, range(len(path_cpls)),
|
| 370 |
+
left=-1, right=-1)
|
| 371 |
+
i0 = math.floor(i0)
|
| 372 |
+
i1 = math.ceil(i1)
|
| 373 |
+
(x0, x1), (y0, y1) = interp_vec(target_cpls, path_cpls, cc_xys)
|
| 374 |
+
|
| 375 |
+
# Actually break contours (dropping zero-len parts).
|
| 376 |
+
new_xy_blocks = []
|
| 377 |
+
new_code_blocks = []
|
| 378 |
+
if is_closed_path:
|
| 379 |
+
if i0 != -1 and i1 != -1:
|
| 380 |
+
# This is probably wrong in the case that the entire contour would
|
| 381 |
+
# be discarded, but ensures that a valid path is returned and is
|
| 382 |
+
# consistent with behavior of mpl <3.8
|
| 383 |
+
points = cc_xys[i1:i0+1]
|
| 384 |
+
new_xy_blocks.extend([[(x1, y1)], points, [(x0, y0)]])
|
| 385 |
+
nlines = len(points) + 1
|
| 386 |
+
new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * nlines])
|
| 387 |
+
else:
|
| 388 |
+
if i0 != -1:
|
| 389 |
+
new_xy_blocks.extend([cc_xys[:i0 + 1], [(x0, y0)]])
|
| 390 |
+
new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * (i0 + 1)])
|
| 391 |
+
if i1 != -1:
|
| 392 |
+
new_xy_blocks.extend([[(x1, y1)], cc_xys[i1:]])
|
| 393 |
+
new_code_blocks.extend([
|
| 394 |
+
[Path.MOVETO], [Path.LINETO] * (len(cc_xys) - i1)])
|
| 395 |
+
|
| 396 |
+
# Back to the full path.
|
| 397 |
+
xys = np.concatenate([xys[:start], *new_xy_blocks, xys[stop:]])
|
| 398 |
+
codes = np.concatenate([codes[:start], *new_code_blocks, codes[stop:]])
|
| 399 |
+
|
| 400 |
+
return angle, Path(xys, codes)
|
| 401 |
+
|
| 402 |
+
def add_label(self, x, y, rotation, lev, cvalue):
|
| 403 |
+
"""Add a contour label, respecting whether *use_clabeltext* was set."""
|
| 404 |
+
data_x, data_y = self.axes.transData.inverted().transform((x, y))
|
| 405 |
+
t = Text(
|
| 406 |
+
data_x, data_y,
|
| 407 |
+
text=self.get_text(lev, self.labelFmt),
|
| 408 |
+
rotation=rotation,
|
| 409 |
+
horizontalalignment='center', verticalalignment='center',
|
| 410 |
+
zorder=self._clabel_zorder,
|
| 411 |
+
color=self.labelMappable.to_rgba(cvalue, alpha=self.get_alpha()),
|
| 412 |
+
fontproperties=self._label_font_props,
|
| 413 |
+
clip_box=self.axes.bbox)
|
| 414 |
+
if self._use_clabeltext:
|
| 415 |
+
data_rotation, = self.axes.transData.inverted().transform_angles(
|
| 416 |
+
[rotation], [[x, y]])
|
| 417 |
+
t.set(rotation=data_rotation, transform_rotates_text=True)
|
| 418 |
+
self.labelTexts.append(t)
|
| 419 |
+
self.labelCValues.append(cvalue)
|
| 420 |
+
self.labelXYs.append((x, y))
|
| 421 |
+
# Add label to plot here - useful for manual mode label selection
|
| 422 |
+
self.axes.add_artist(t)
|
| 423 |
+
|
| 424 |
+
def add_label_near(self, x, y, inline=True, inline_spacing=5,
|
| 425 |
+
transform=None):
|
| 426 |
+
"""
|
| 427 |
+
Add a label near the point ``(x, y)``.
|
| 428 |
+
|
| 429 |
+
Parameters
|
| 430 |
+
----------
|
| 431 |
+
x, y : float
|
| 432 |
+
The approximate location of the label.
|
| 433 |
+
inline : bool, default: True
|
| 434 |
+
If *True* remove the segment of the contour beneath the label.
|
| 435 |
+
inline_spacing : int, default: 5
|
| 436 |
+
Space in pixels to leave on each side of label when placing
|
| 437 |
+
inline. This spacing will be exact for labels at locations where
|
| 438 |
+
the contour is straight, less so for labels on curved contours.
|
| 439 |
+
transform : `.Transform` or `False`, default: ``self.axes.transData``
|
| 440 |
+
A transform applied to ``(x, y)`` before labeling. The default
|
| 441 |
+
causes ``(x, y)`` to be interpreted as data coordinates. `False`
|
| 442 |
+
is a synonym for `.IdentityTransform`; i.e. ``(x, y)`` should be
|
| 443 |
+
interpreted as display coordinates.
|
| 444 |
+
"""
|
| 445 |
+
|
| 446 |
+
if transform is None:
|
| 447 |
+
transform = self.axes.transData
|
| 448 |
+
if transform:
|
| 449 |
+
x, y = transform.transform((x, y))
|
| 450 |
+
|
| 451 |
+
idx_level_min, idx_vtx_min, proj = self._find_nearest_contour(
|
| 452 |
+
(x, y), self.labelIndiceList)
|
| 453 |
+
path = self._paths[idx_level_min]
|
| 454 |
+
level = self.labelIndiceList.index(idx_level_min)
|
| 455 |
+
label_width = self._get_nth_label_width(level)
|
| 456 |
+
rotation, path = self._split_path_and_get_label_rotation(
|
| 457 |
+
path, idx_vtx_min, proj, label_width, inline_spacing)
|
| 458 |
+
self.add_label(*proj, rotation, self.labelLevelList[idx_level_min],
|
| 459 |
+
self.labelCValueList[idx_level_min])
|
| 460 |
+
|
| 461 |
+
if inline:
|
| 462 |
+
self._paths[idx_level_min] = path
|
| 463 |
+
|
| 464 |
+
def pop_label(self, index=-1):
|
| 465 |
+
"""Defaults to removing last label, but any index can be supplied"""
|
| 466 |
+
self.labelCValues.pop(index)
|
| 467 |
+
t = self.labelTexts.pop(index)
|
| 468 |
+
t.remove()
|
| 469 |
+
|
| 470 |
+
def labels(self, inline, inline_spacing):
|
| 471 |
+
for idx, (icon, lev, cvalue) in enumerate(zip(
|
| 472 |
+
self.labelIndiceList,
|
| 473 |
+
self.labelLevelList,
|
| 474 |
+
self.labelCValueList,
|
| 475 |
+
)):
|
| 476 |
+
trans = self.get_transform()
|
| 477 |
+
label_width = self._get_nth_label_width(idx)
|
| 478 |
+
additions = []
|
| 479 |
+
for subpath in self._paths[icon]._iter_connected_components():
|
| 480 |
+
screen_xys = trans.transform(subpath.vertices)
|
| 481 |
+
# Check if long enough for a label
|
| 482 |
+
if self.print_label(screen_xys, label_width):
|
| 483 |
+
x, y, idx = self.locate_label(screen_xys, label_width)
|
| 484 |
+
rotation, path = self._split_path_and_get_label_rotation(
|
| 485 |
+
subpath, idx, (x, y),
|
| 486 |
+
label_width, inline_spacing)
|
| 487 |
+
self.add_label(x, y, rotation, lev, cvalue) # Really add label.
|
| 488 |
+
if inline: # If inline, add new contours
|
| 489 |
+
additions.append(path)
|
| 490 |
+
else: # If not adding label, keep old path
|
| 491 |
+
additions.append(subpath)
|
| 492 |
+
# After looping over all segments on a contour, replace old path by new one
|
| 493 |
+
# if inlining.
|
| 494 |
+
if inline:
|
| 495 |
+
self._paths[icon] = Path.make_compound_path(*additions)
|
| 496 |
+
|
| 497 |
+
def remove(self):
|
| 498 |
+
super().remove()
|
| 499 |
+
for text in self.labelTexts:
|
| 500 |
+
text.remove()
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def _find_closest_point_on_path(xys, p):
|
| 504 |
+
"""
|
| 505 |
+
Parameters
|
| 506 |
+
----------
|
| 507 |
+
xys : (N, 2) array-like
|
| 508 |
+
Coordinates of vertices.
|
| 509 |
+
p : (float, float)
|
| 510 |
+
Coordinates of point.
|
| 511 |
+
|
| 512 |
+
Returns
|
| 513 |
+
-------
|
| 514 |
+
d2min : float
|
| 515 |
+
Minimum square distance of *p* to *xys*.
|
| 516 |
+
proj : (float, float)
|
| 517 |
+
Projection of *p* onto *xys*.
|
| 518 |
+
imin : (int, int)
|
| 519 |
+
Consecutive indices of vertices of segment in *xys* where *proj* is.
|
| 520 |
+
Segments are considered as including their end-points; i.e. if the
|
| 521 |
+
closest point on the path is a node in *xys* with index *i*, this
|
| 522 |
+
returns ``(i-1, i)``. For the special case where *xys* is a single
|
| 523 |
+
point, this returns ``(0, 0)``.
|
| 524 |
+
"""
|
| 525 |
+
if len(xys) == 1:
|
| 526 |
+
return (((p - xys[0]) ** 2).sum(), xys[0], (0, 0))
|
| 527 |
+
dxys = xys[1:] - xys[:-1] # Individual segment vectors.
|
| 528 |
+
norms = (dxys ** 2).sum(axis=1)
|
| 529 |
+
norms[norms == 0] = 1 # For zero-length segment, replace 0/0 by 0/1.
|
| 530 |
+
rel_projs = np.clip( # Project onto each segment in relative 0-1 coords.
|
| 531 |
+
((p - xys[:-1]) * dxys).sum(axis=1) / norms,
|
| 532 |
+
0, 1)[:, None]
|
| 533 |
+
projs = xys[:-1] + rel_projs * dxys # Projs. onto each segment, in (x, y).
|
| 534 |
+
d2s = ((projs - p) ** 2).sum(axis=1) # Squared distances.
|
| 535 |
+
imin = np.argmin(d2s)
|
| 536 |
+
return (d2s[imin], projs[imin], (imin, imin+1))
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
_docstring.interpd.register(contour_set_attributes=r"""
|
| 540 |
+
Attributes
|
| 541 |
+
----------
|
| 542 |
+
ax : `~matplotlib.axes.Axes`
|
| 543 |
+
The Axes object in which the contours are drawn.
|
| 544 |
+
|
| 545 |
+
collections : `.silent_list` of `.PathCollection`\s
|
| 546 |
+
The `.Artist`\s representing the contour. This is a list of
|
| 547 |
+
`.PathCollection`\s for both line and filled contours.
|
| 548 |
+
|
| 549 |
+
levels : array
|
| 550 |
+
The values of the contour levels.
|
| 551 |
+
|
| 552 |
+
layers : array
|
| 553 |
+
Same as levels for line contours; half-way between
|
| 554 |
+
levels for filled contours. See ``ContourSet._process_colors``.
|
| 555 |
+
""")
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
@_docstring.interpd
|
| 559 |
+
class ContourSet(ContourLabeler, mcoll.Collection):
|
| 560 |
+
"""
|
| 561 |
+
Store a set of contour lines or filled regions.
|
| 562 |
+
|
| 563 |
+
User-callable method: `~.Axes.clabel`
|
| 564 |
+
|
| 565 |
+
Parameters
|
| 566 |
+
----------
|
| 567 |
+
ax : `~matplotlib.axes.Axes`
|
| 568 |
+
|
| 569 |
+
levels : [level0, level1, ..., leveln]
|
| 570 |
+
A list of floating point numbers indicating the contour levels.
|
| 571 |
+
|
| 572 |
+
allsegs : [level0segs, level1segs, ...]
|
| 573 |
+
List of all the polygon segments for all the *levels*.
|
| 574 |
+
For contour lines ``len(allsegs) == len(levels)``, and for
|
| 575 |
+
filled contour regions ``len(allsegs) = len(levels)-1``. The lists
|
| 576 |
+
should look like ::
|
| 577 |
+
|
| 578 |
+
level0segs = [polygon0, polygon1, ...]
|
| 579 |
+
polygon0 = [[x0, y0], [x1, y1], ...]
|
| 580 |
+
|
| 581 |
+
allkinds : ``None`` or [level0kinds, level1kinds, ...]
|
| 582 |
+
Optional list of all the polygon vertex kinds (code types), as
|
| 583 |
+
described and used in Path. This is used to allow multiply-
|
| 584 |
+
connected paths such as holes within filled polygons.
|
| 585 |
+
If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
|
| 586 |
+
should look like ::
|
| 587 |
+
|
| 588 |
+
level0kinds = [polygon0kinds, ...]
|
| 589 |
+
polygon0kinds = [vertexcode0, vertexcode1, ...]
|
| 590 |
+
|
| 591 |
+
If *allkinds* is not ``None``, usually all polygons for a
|
| 592 |
+
particular contour level are grouped together so that
|
| 593 |
+
``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
|
| 594 |
+
|
| 595 |
+
**kwargs
|
| 596 |
+
Keyword arguments are as described in the docstring of
|
| 597 |
+
`~.Axes.contour`.
|
| 598 |
+
|
| 599 |
+
%(contour_set_attributes)s
|
| 600 |
+
"""
|
| 601 |
+
|
| 602 |
+
def __init__(self, ax, *args,
|
| 603 |
+
levels=None, filled=False, linewidths=None, linestyles=None,
|
| 604 |
+
hatches=(None,), alpha=None, origin=None, extent=None,
|
| 605 |
+
cmap=None, colors=None, norm=None, vmin=None, vmax=None,
|
| 606 |
+
colorizer=None, extend='neither', antialiased=None, nchunk=0,
|
| 607 |
+
locator=None, transform=None, negative_linestyles=None, clip_path=None,
|
| 608 |
+
**kwargs):
|
| 609 |
+
"""
|
| 610 |
+
Draw contour lines or filled regions, depending on
|
| 611 |
+
whether keyword arg *filled* is ``False`` (default) or ``True``.
|
| 612 |
+
|
| 613 |
+
Call signature::
|
| 614 |
+
|
| 615 |
+
ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
|
| 616 |
+
|
| 617 |
+
Parameters
|
| 618 |
+
----------
|
| 619 |
+
ax : `~matplotlib.axes.Axes`
|
| 620 |
+
The `~.axes.Axes` object to draw on.
|
| 621 |
+
|
| 622 |
+
levels : [level0, level1, ..., leveln]
|
| 623 |
+
A list of floating point numbers indicating the contour
|
| 624 |
+
levels.
|
| 625 |
+
|
| 626 |
+
allsegs : [level0segs, level1segs, ...]
|
| 627 |
+
List of all the polygon segments for all the *levels*.
|
| 628 |
+
For contour lines ``len(allsegs) == len(levels)``, and for
|
| 629 |
+
filled contour regions ``len(allsegs) = len(levels)-1``. The lists
|
| 630 |
+
should look like ::
|
| 631 |
+
|
| 632 |
+
level0segs = [polygon0, polygon1, ...]
|
| 633 |
+
polygon0 = [[x0, y0], [x1, y1], ...]
|
| 634 |
+
|
| 635 |
+
allkinds : [level0kinds, level1kinds, ...], optional
|
| 636 |
+
Optional list of all the polygon vertex kinds (code types), as
|
| 637 |
+
described and used in Path. This is used to allow multiply-
|
| 638 |
+
connected paths such as holes within filled polygons.
|
| 639 |
+
If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
|
| 640 |
+
should look like ::
|
| 641 |
+
|
| 642 |
+
level0kinds = [polygon0kinds, ...]
|
| 643 |
+
polygon0kinds = [vertexcode0, vertexcode1, ...]
|
| 644 |
+
|
| 645 |
+
If *allkinds* is not ``None``, usually all polygons for a
|
| 646 |
+
particular contour level are grouped together so that
|
| 647 |
+
``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
|
| 648 |
+
|
| 649 |
+
**kwargs
|
| 650 |
+
Keyword arguments are as described in the docstring of
|
| 651 |
+
`~.Axes.contour`.
|
| 652 |
+
"""
|
| 653 |
+
if antialiased is None and filled:
|
| 654 |
+
# Eliminate artifacts; we are not stroking the boundaries.
|
| 655 |
+
antialiased = False
|
| 656 |
+
# The default for line contours will be taken from the
|
| 657 |
+
# LineCollection default, which uses :rc:`lines.antialiased`.
|
| 658 |
+
super().__init__(
|
| 659 |
+
antialiaseds=antialiased,
|
| 660 |
+
alpha=alpha,
|
| 661 |
+
clip_path=clip_path,
|
| 662 |
+
transform=transform,
|
| 663 |
+
colorizer=colorizer,
|
| 664 |
+
)
|
| 665 |
+
self.axes = ax
|
| 666 |
+
self.levels = levels
|
| 667 |
+
self.filled = filled
|
| 668 |
+
self.hatches = hatches
|
| 669 |
+
self.origin = origin
|
| 670 |
+
self.extent = extent
|
| 671 |
+
self.colors = colors
|
| 672 |
+
self.extend = extend
|
| 673 |
+
|
| 674 |
+
self.nchunk = nchunk
|
| 675 |
+
self.locator = locator
|
| 676 |
+
|
| 677 |
+
if colorizer:
|
| 678 |
+
self._set_colorizer_check_keywords(colorizer, cmap=cmap,
|
| 679 |
+
norm=norm, vmin=vmin,
|
| 680 |
+
vmax=vmax, colors=colors)
|
| 681 |
+
norm = colorizer.norm
|
| 682 |
+
cmap = colorizer.cmap
|
| 683 |
+
if (isinstance(norm, mcolors.LogNorm)
|
| 684 |
+
or isinstance(self.locator, ticker.LogLocator)):
|
| 685 |
+
self.logscale = True
|
| 686 |
+
if norm is None:
|
| 687 |
+
norm = mcolors.LogNorm()
|
| 688 |
+
else:
|
| 689 |
+
self.logscale = False
|
| 690 |
+
|
| 691 |
+
_api.check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
|
| 692 |
+
if self.extent is not None and len(self.extent) != 4:
|
| 693 |
+
raise ValueError(
|
| 694 |
+
"If given, 'extent' must be None or (x0, x1, y0, y1)")
|
| 695 |
+
if self.colors is not None and cmap is not None:
|
| 696 |
+
raise ValueError('Either colors or cmap must be None')
|
| 697 |
+
if self.origin == 'image':
|
| 698 |
+
self.origin = mpl.rcParams['image.origin']
|
| 699 |
+
|
| 700 |
+
self._orig_linestyles = linestyles # Only kept for user access.
|
| 701 |
+
self.negative_linestyles = negative_linestyles
|
| 702 |
+
# If negative_linestyles was not defined as a keyword argument, define
|
| 703 |
+
# negative_linestyles with rcParams
|
| 704 |
+
if self.negative_linestyles is None:
|
| 705 |
+
self.negative_linestyles = \
|
| 706 |
+
mpl.rcParams['contour.negative_linestyle']
|
| 707 |
+
|
| 708 |
+
kwargs = self._process_args(*args, **kwargs)
|
| 709 |
+
self._process_levels()
|
| 710 |
+
|
| 711 |
+
self._extend_min = self.extend in ['min', 'both']
|
| 712 |
+
self._extend_max = self.extend in ['max', 'both']
|
| 713 |
+
if self.colors is not None:
|
| 714 |
+
if mcolors.is_color_like(self.colors):
|
| 715 |
+
color_sequence = [self.colors]
|
| 716 |
+
else:
|
| 717 |
+
color_sequence = self.colors
|
| 718 |
+
|
| 719 |
+
ncolors = len(self.levels)
|
| 720 |
+
if self.filled:
|
| 721 |
+
ncolors -= 1
|
| 722 |
+
i0 = 0
|
| 723 |
+
|
| 724 |
+
# Handle the case where colors are given for the extended
|
| 725 |
+
# parts of the contour.
|
| 726 |
+
|
| 727 |
+
use_set_under_over = False
|
| 728 |
+
# if we are extending the lower end, and we've been given enough
|
| 729 |
+
# colors then skip the first color in the resulting cmap. For the
|
| 730 |
+
# extend_max case we don't need to worry about passing more colors
|
| 731 |
+
# than ncolors as ListedColormap will clip.
|
| 732 |
+
total_levels = (ncolors +
|
| 733 |
+
int(self._extend_min) +
|
| 734 |
+
int(self._extend_max))
|
| 735 |
+
if (len(color_sequence) == total_levels and
|
| 736 |
+
(self._extend_min or self._extend_max)):
|
| 737 |
+
use_set_under_over = True
|
| 738 |
+
if self._extend_min:
|
| 739 |
+
i0 = 1
|
| 740 |
+
|
| 741 |
+
cmap = mcolors.ListedColormap(color_sequence[i0:None], N=ncolors)
|
| 742 |
+
|
| 743 |
+
if use_set_under_over:
|
| 744 |
+
if self._extend_min:
|
| 745 |
+
cmap.set_under(color_sequence[0])
|
| 746 |
+
if self._extend_max:
|
| 747 |
+
cmap.set_over(color_sequence[-1])
|
| 748 |
+
|
| 749 |
+
# label lists must be initialized here
|
| 750 |
+
self.labelTexts = []
|
| 751 |
+
self.labelCValues = []
|
| 752 |
+
|
| 753 |
+
self.set_cmap(cmap)
|
| 754 |
+
if norm is not None:
|
| 755 |
+
self.set_norm(norm)
|
| 756 |
+
with self.norm.callbacks.blocked(signal="changed"):
|
| 757 |
+
if vmin is not None:
|
| 758 |
+
self.norm.vmin = vmin
|
| 759 |
+
if vmax is not None:
|
| 760 |
+
self.norm.vmax = vmax
|
| 761 |
+
self.norm._changed()
|
| 762 |
+
self._process_colors()
|
| 763 |
+
|
| 764 |
+
if self._paths is None:
|
| 765 |
+
self._paths = self._make_paths_from_contour_generator()
|
| 766 |
+
|
| 767 |
+
if self.filled:
|
| 768 |
+
if linewidths is not None:
|
| 769 |
+
_api.warn_external('linewidths is ignored by contourf')
|
| 770 |
+
# Lower and upper contour levels.
|
| 771 |
+
lowers, uppers = self._get_lowers_and_uppers()
|
| 772 |
+
self.set(
|
| 773 |
+
edgecolor="none",
|
| 774 |
+
# Default zorder taken from Collection
|
| 775 |
+
zorder=kwargs.pop("zorder", 1),
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
else:
|
| 779 |
+
self.set(
|
| 780 |
+
facecolor="none",
|
| 781 |
+
linewidths=self._process_linewidths(linewidths),
|
| 782 |
+
linestyle=self._process_linestyles(linestyles),
|
| 783 |
+
# Default zorder taken from LineCollection, which is higher
|
| 784 |
+
# than for filled contours so that lines are displayed on top.
|
| 785 |
+
zorder=kwargs.pop("zorder", 2),
|
| 786 |
+
label="_nolegend_",
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
self.axes.add_collection(self, autolim=False)
|
| 790 |
+
self.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
|
| 791 |
+
self.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
|
| 792 |
+
self.axes.update_datalim([self._mins, self._maxs])
|
| 793 |
+
self.axes.autoscale_view(tight=True)
|
| 794 |
+
|
| 795 |
+
self.changed() # set the colors
|
| 796 |
+
|
| 797 |
+
if kwargs:
|
| 798 |
+
_api.warn_external(
|
| 799 |
+
'The following kwargs were not used by contour: ' +
|
| 800 |
+
", ".join(map(repr, kwargs))
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
allsegs = property(lambda self: [
|
| 804 |
+
[subp.vertices for subp in p._iter_connected_components()]
|
| 805 |
+
for p in self.get_paths()])
|
| 806 |
+
allkinds = property(lambda self: [
|
| 807 |
+
[subp.codes for subp in p._iter_connected_components()]
|
| 808 |
+
for p in self.get_paths()])
|
| 809 |
+
alpha = property(lambda self: self.get_alpha())
|
| 810 |
+
linestyles = property(lambda self: self._orig_linestyles)
|
| 811 |
+
|
| 812 |
+
def get_transform(self):
|
| 813 |
+
"""Return the `.Transform` instance used by this ContourSet."""
|
| 814 |
+
if self._transform is None:
|
| 815 |
+
self._transform = self.axes.transData
|
| 816 |
+
elif (not isinstance(self._transform, mtransforms.Transform)
|
| 817 |
+
and hasattr(self._transform, '_as_mpl_transform')):
|
| 818 |
+
self._transform = self._transform._as_mpl_transform(self.axes)
|
| 819 |
+
return self._transform
|
| 820 |
+
|
| 821 |
+
def __getstate__(self):
|
| 822 |
+
state = self.__dict__.copy()
|
| 823 |
+
# the C object _contour_generator cannot currently be pickled. This
|
| 824 |
+
# isn't a big issue as it is not actually used once the contour has
|
| 825 |
+
# been calculated.
|
| 826 |
+
state['_contour_generator'] = None
|
| 827 |
+
return state
|
| 828 |
+
|
| 829 |
+
def legend_elements(self, variable_name='x', str_format=str):
|
| 830 |
+
"""
|
| 831 |
+
Return a list of artists and labels suitable for passing through
|
| 832 |
+
to `~.Axes.legend` which represent this ContourSet.
|
| 833 |
+
|
| 834 |
+
The labels have the form "0 < x <= 1" stating the data ranges which
|
| 835 |
+
the artists represent.
|
| 836 |
+
|
| 837 |
+
Parameters
|
| 838 |
+
----------
|
| 839 |
+
variable_name : str
|
| 840 |
+
The string used inside the inequality used on the labels.
|
| 841 |
+
str_format : function: float -> str
|
| 842 |
+
Function used to format the numbers in the labels.
|
| 843 |
+
|
| 844 |
+
Returns
|
| 845 |
+
-------
|
| 846 |
+
artists : list[`.Artist`]
|
| 847 |
+
A list of the artists.
|
| 848 |
+
labels : list[str]
|
| 849 |
+
A list of the labels.
|
| 850 |
+
"""
|
| 851 |
+
artists = []
|
| 852 |
+
labels = []
|
| 853 |
+
|
| 854 |
+
if self.filled:
|
| 855 |
+
lowers, uppers = self._get_lowers_and_uppers()
|
| 856 |
+
n_levels = len(self._paths)
|
| 857 |
+
for idx in range(n_levels):
|
| 858 |
+
artists.append(mpatches.Rectangle(
|
| 859 |
+
(0, 0), 1, 1,
|
| 860 |
+
facecolor=self.get_facecolor()[idx],
|
| 861 |
+
hatch=self.hatches[idx % len(self.hatches)],
|
| 862 |
+
))
|
| 863 |
+
lower = str_format(lowers[idx])
|
| 864 |
+
upper = str_format(uppers[idx])
|
| 865 |
+
if idx == 0 and self.extend in ('min', 'both'):
|
| 866 |
+
labels.append(fr'${variable_name} \leq {lower}s$')
|
| 867 |
+
elif idx == n_levels - 1 and self.extend in ('max', 'both'):
|
| 868 |
+
labels.append(fr'${variable_name} > {upper}s$')
|
| 869 |
+
else:
|
| 870 |
+
labels.append(fr'${lower} < {variable_name} \leq {upper}$')
|
| 871 |
+
else:
|
| 872 |
+
for idx, level in enumerate(self.levels):
|
| 873 |
+
artists.append(Line2D(
|
| 874 |
+
[], [],
|
| 875 |
+
color=self.get_edgecolor()[idx],
|
| 876 |
+
linewidth=self.get_linewidths()[idx],
|
| 877 |
+
linestyle=self.get_linestyles()[idx],
|
| 878 |
+
))
|
| 879 |
+
labels.append(fr'${variable_name} = {str_format(level)}$')
|
| 880 |
+
|
| 881 |
+
return artists, labels
|
| 882 |
+
|
| 883 |
+
def _process_args(self, *args, **kwargs):
|
| 884 |
+
"""
|
| 885 |
+
Process *args* and *kwargs*; override in derived classes.
|
| 886 |
+
|
| 887 |
+
Must set self.levels, self.zmin and self.zmax, and update Axes limits.
|
| 888 |
+
"""
|
| 889 |
+
self.levels = args[0]
|
| 890 |
+
allsegs = args[1]
|
| 891 |
+
allkinds = args[2] if len(args) > 2 else None
|
| 892 |
+
self.zmax = np.max(self.levels)
|
| 893 |
+
self.zmin = np.min(self.levels)
|
| 894 |
+
|
| 895 |
+
if allkinds is None:
|
| 896 |
+
allkinds = [[None] * len(segs) for segs in allsegs]
|
| 897 |
+
|
| 898 |
+
# Check lengths of levels and allsegs.
|
| 899 |
+
if self.filled:
|
| 900 |
+
if len(allsegs) != len(self.levels) - 1:
|
| 901 |
+
raise ValueError('must be one less number of segments as '
|
| 902 |
+
'levels')
|
| 903 |
+
else:
|
| 904 |
+
if len(allsegs) != len(self.levels):
|
| 905 |
+
raise ValueError('must be same number of segments as levels')
|
| 906 |
+
|
| 907 |
+
# Check length of allkinds.
|
| 908 |
+
if len(allkinds) != len(allsegs):
|
| 909 |
+
raise ValueError('allkinds has different length to allsegs')
|
| 910 |
+
|
| 911 |
+
# Determine x, y bounds and update axes data limits.
|
| 912 |
+
flatseglist = [s for seg in allsegs for s in seg]
|
| 913 |
+
points = np.concatenate(flatseglist, axis=0)
|
| 914 |
+
self._mins = points.min(axis=0)
|
| 915 |
+
self._maxs = points.max(axis=0)
|
| 916 |
+
|
| 917 |
+
# Each entry in (allsegs, allkinds) is a list of (segs, kinds): segs is a list
|
| 918 |
+
# of (N, 2) arrays of xy coordinates, kinds is a list of arrays of corresponding
|
| 919 |
+
# pathcodes. However, kinds can also be None; in which case all paths in that
|
| 920 |
+
# list are codeless (this case is normalized above). These lists are used to
|
| 921 |
+
# construct paths, which then get concatenated.
|
| 922 |
+
self._paths = [Path.make_compound_path(*map(Path, segs, kinds))
|
| 923 |
+
for segs, kinds in zip(allsegs, allkinds)]
|
| 924 |
+
|
| 925 |
+
return kwargs
|
| 926 |
+
|
| 927 |
+
def _make_paths_from_contour_generator(self):
|
| 928 |
+
"""Compute ``paths`` using C extension."""
|
| 929 |
+
if self._paths is not None:
|
| 930 |
+
return self._paths
|
| 931 |
+
cg = self._contour_generator
|
| 932 |
+
empty_path = Path(np.empty((0, 2)))
|
| 933 |
+
vertices_and_codes = (
|
| 934 |
+
map(cg.create_filled_contour, *self._get_lowers_and_uppers())
|
| 935 |
+
if self.filled else
|
| 936 |
+
map(cg.create_contour, self.levels))
|
| 937 |
+
return [Path(np.concatenate(vs), np.concatenate(cs)) if len(vs) else empty_path
|
| 938 |
+
for vs, cs in vertices_and_codes]
|
| 939 |
+
|
| 940 |
+
def _get_lowers_and_uppers(self):
|
| 941 |
+
"""
|
| 942 |
+
Return ``(lowers, uppers)`` for filled contours.
|
| 943 |
+
"""
|
| 944 |
+
lowers = self._levels[:-1]
|
| 945 |
+
if self.zmin == lowers[0]:
|
| 946 |
+
# Include minimum values in lowest interval
|
| 947 |
+
lowers = lowers.copy() # so we don't change self._levels
|
| 948 |
+
if self.logscale:
|
| 949 |
+
lowers[0] = 0.99 * self.zmin
|
| 950 |
+
else:
|
| 951 |
+
lowers[0] -= 1
|
| 952 |
+
uppers = self._levels[1:]
|
| 953 |
+
return (lowers, uppers)
|
| 954 |
+
|
| 955 |
+
def changed(self):
|
| 956 |
+
if not hasattr(self, "cvalues"):
|
| 957 |
+
self._process_colors() # Sets cvalues.
|
| 958 |
+
# Force an autoscale immediately because self.to_rgba() calls
|
| 959 |
+
# autoscale_None() internally with the data passed to it,
|
| 960 |
+
# so if vmin/vmax are not set yet, this would override them with
|
| 961 |
+
# content from *cvalues* rather than levels like we want
|
| 962 |
+
self.norm.autoscale_None(self.levels)
|
| 963 |
+
self.set_array(self.cvalues)
|
| 964 |
+
self.update_scalarmappable()
|
| 965 |
+
alphas = np.broadcast_to(self.get_alpha(), len(self.cvalues))
|
| 966 |
+
for label, cv, alpha in zip(self.labelTexts, self.labelCValues, alphas):
|
| 967 |
+
label.set_alpha(alpha)
|
| 968 |
+
label.set_color(self.labelMappable.to_rgba(cv))
|
| 969 |
+
super().changed()
|
| 970 |
+
|
| 971 |
+
def _autolev(self, N):
|
| 972 |
+
"""
|
| 973 |
+
Select contour levels to span the data.
|
| 974 |
+
|
| 975 |
+
The target number of levels, *N*, is used only when the
|
| 976 |
+
scale is not log and default locator is used.
|
| 977 |
+
|
| 978 |
+
We need two more levels for filled contours than for
|
| 979 |
+
line contours, because for the latter we need to specify
|
| 980 |
+
the lower and upper boundary of each range. For example,
|
| 981 |
+
a single contour boundary, say at z = 0, requires only
|
| 982 |
+
one contour line, but two filled regions, and therefore
|
| 983 |
+
three levels to provide boundaries for both regions.
|
| 984 |
+
"""
|
| 985 |
+
if self.locator is None:
|
| 986 |
+
if self.logscale:
|
| 987 |
+
self.locator = ticker.LogLocator()
|
| 988 |
+
else:
|
| 989 |
+
self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
|
| 990 |
+
|
| 991 |
+
lev = self.locator.tick_values(self.zmin, self.zmax)
|
| 992 |
+
|
| 993 |
+
try:
|
| 994 |
+
if self.locator._symmetric:
|
| 995 |
+
return lev
|
| 996 |
+
except AttributeError:
|
| 997 |
+
pass
|
| 998 |
+
|
| 999 |
+
# Trim excess levels the locator may have supplied.
|
| 1000 |
+
under = np.nonzero(lev < self.zmin)[0]
|
| 1001 |
+
i0 = under[-1] if len(under) else 0
|
| 1002 |
+
over = np.nonzero(lev > self.zmax)[0]
|
| 1003 |
+
i1 = over[0] + 1 if len(over) else len(lev)
|
| 1004 |
+
if self.extend in ('min', 'both'):
|
| 1005 |
+
i0 += 1
|
| 1006 |
+
if self.extend in ('max', 'both'):
|
| 1007 |
+
i1 -= 1
|
| 1008 |
+
|
| 1009 |
+
if i1 - i0 < 3:
|
| 1010 |
+
i0, i1 = 0, len(lev)
|
| 1011 |
+
|
| 1012 |
+
return lev[i0:i1]
|
| 1013 |
+
|
| 1014 |
+
def _process_contour_level_args(self, args, z_dtype):
|
| 1015 |
+
"""
|
| 1016 |
+
Determine the contour levels and store in self.levels.
|
| 1017 |
+
"""
|
| 1018 |
+
if self.levels is None:
|
| 1019 |
+
if args:
|
| 1020 |
+
levels_arg = args[0]
|
| 1021 |
+
elif np.issubdtype(z_dtype, bool):
|
| 1022 |
+
if self.filled:
|
| 1023 |
+
levels_arg = [0, .5, 1]
|
| 1024 |
+
else:
|
| 1025 |
+
levels_arg = [.5]
|
| 1026 |
+
else:
|
| 1027 |
+
levels_arg = 7 # Default, hard-wired.
|
| 1028 |
+
else:
|
| 1029 |
+
levels_arg = self.levels
|
| 1030 |
+
if isinstance(levels_arg, Integral):
|
| 1031 |
+
self.levels = self._autolev(levels_arg)
|
| 1032 |
+
else:
|
| 1033 |
+
self.levels = np.asarray(levels_arg, np.float64)
|
| 1034 |
+
if self.filled and len(self.levels) < 2:
|
| 1035 |
+
raise ValueError("Filled contours require at least 2 levels.")
|
| 1036 |
+
if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
|
| 1037 |
+
raise ValueError("Contour levels must be increasing")
|
| 1038 |
+
|
| 1039 |
+
def _process_levels(self):
|
| 1040 |
+
"""
|
| 1041 |
+
Assign values to :attr:`layers` based on :attr:`levels`,
|
| 1042 |
+
adding extended layers as needed if contours are filled.
|
| 1043 |
+
|
| 1044 |
+
For line contours, layers simply coincide with levels;
|
| 1045 |
+
a line is a thin layer. No extended levels are needed
|
| 1046 |
+
with line contours.
|
| 1047 |
+
"""
|
| 1048 |
+
# Make a private _levels to include extended regions; we
|
| 1049 |
+
# want to leave the original levels attribute unchanged.
|
| 1050 |
+
# (Colorbar needs this even for line contours.)
|
| 1051 |
+
self._levels = list(self.levels)
|
| 1052 |
+
|
| 1053 |
+
if self.logscale:
|
| 1054 |
+
lower, upper = 1e-250, 1e250
|
| 1055 |
+
else:
|
| 1056 |
+
lower, upper = -1e250, 1e250
|
| 1057 |
+
|
| 1058 |
+
if self.extend in ('both', 'min'):
|
| 1059 |
+
self._levels.insert(0, lower)
|
| 1060 |
+
if self.extend in ('both', 'max'):
|
| 1061 |
+
self._levels.append(upper)
|
| 1062 |
+
self._levels = np.asarray(self._levels)
|
| 1063 |
+
|
| 1064 |
+
if not self.filled:
|
| 1065 |
+
self.layers = self.levels
|
| 1066 |
+
return
|
| 1067 |
+
|
| 1068 |
+
# Layer values are mid-way between levels in screen space.
|
| 1069 |
+
if self.logscale:
|
| 1070 |
+
# Avoid overflow by taking sqrt before multiplying.
|
| 1071 |
+
self.layers = (np.sqrt(self._levels[:-1])
|
| 1072 |
+
* np.sqrt(self._levels[1:]))
|
| 1073 |
+
else:
|
| 1074 |
+
self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
|
| 1075 |
+
|
| 1076 |
+
def _process_colors(self):
|
| 1077 |
+
"""
|
| 1078 |
+
Color argument processing for contouring.
|
| 1079 |
+
|
| 1080 |
+
Note that we base the colormapping on the contour levels
|
| 1081 |
+
and layers, not on the actual range of the Z values. This
|
| 1082 |
+
means we don't have to worry about bad values in Z, and we
|
| 1083 |
+
always have the full dynamic range available for the selected
|
| 1084 |
+
levels.
|
| 1085 |
+
|
| 1086 |
+
The color is based on the midpoint of the layer, except for
|
| 1087 |
+
extended end layers. By default, the norm vmin and vmax
|
| 1088 |
+
are the extreme values of the non-extended levels. Hence,
|
| 1089 |
+
the layer color extremes are not the extreme values of
|
| 1090 |
+
the colormap itself, but approach those values as the number
|
| 1091 |
+
of levels increases. An advantage of this scheme is that
|
| 1092 |
+
line contours, when added to filled contours, take on
|
| 1093 |
+
colors that are consistent with those of the filled regions;
|
| 1094 |
+
for example, a contour line on the boundary between two
|
| 1095 |
+
regions will have a color intermediate between those
|
| 1096 |
+
of the regions.
|
| 1097 |
+
|
| 1098 |
+
"""
|
| 1099 |
+
self.monochrome = self.cmap.monochrome
|
| 1100 |
+
if self.colors is not None:
|
| 1101 |
+
# Generate integers for direct indexing.
|
| 1102 |
+
i0, i1 = 0, len(self.levels)
|
| 1103 |
+
if self.filled:
|
| 1104 |
+
i1 -= 1
|
| 1105 |
+
# Out of range indices for over and under:
|
| 1106 |
+
if self.extend in ('both', 'min'):
|
| 1107 |
+
i0 -= 1
|
| 1108 |
+
if self.extend in ('both', 'max'):
|
| 1109 |
+
i1 += 1
|
| 1110 |
+
self.cvalues = list(range(i0, i1))
|
| 1111 |
+
self.set_norm(mcolors.NoNorm())
|
| 1112 |
+
else:
|
| 1113 |
+
self.cvalues = self.layers
|
| 1114 |
+
self.norm.autoscale_None(self.levels)
|
| 1115 |
+
self.set_array(self.cvalues)
|
| 1116 |
+
self.update_scalarmappable()
|
| 1117 |
+
if self.extend in ('both', 'max', 'min'):
|
| 1118 |
+
self.norm.clip = False
|
| 1119 |
+
|
| 1120 |
+
def _process_linewidths(self, linewidths):
|
| 1121 |
+
Nlev = len(self.levels)
|
| 1122 |
+
if linewidths is None:
|
| 1123 |
+
default_linewidth = mpl.rcParams['contour.linewidth']
|
| 1124 |
+
if default_linewidth is None:
|
| 1125 |
+
default_linewidth = mpl.rcParams['lines.linewidth']
|
| 1126 |
+
return [default_linewidth] * Nlev
|
| 1127 |
+
elif not np.iterable(linewidths):
|
| 1128 |
+
return [linewidths] * Nlev
|
| 1129 |
+
else:
|
| 1130 |
+
linewidths = list(linewidths)
|
| 1131 |
+
return (linewidths * math.ceil(Nlev / len(linewidths)))[:Nlev]
|
| 1132 |
+
|
| 1133 |
+
def _process_linestyles(self, linestyles):
|
| 1134 |
+
Nlev = len(self.levels)
|
| 1135 |
+
if linestyles is None:
|
| 1136 |
+
tlinestyles = ['solid'] * Nlev
|
| 1137 |
+
if self.monochrome:
|
| 1138 |
+
eps = - (self.zmax - self.zmin) * 1e-15
|
| 1139 |
+
for i, lev in enumerate(self.levels):
|
| 1140 |
+
if lev < eps:
|
| 1141 |
+
tlinestyles[i] = self.negative_linestyles
|
| 1142 |
+
else:
|
| 1143 |
+
if isinstance(linestyles, str):
|
| 1144 |
+
tlinestyles = [linestyles] * Nlev
|
| 1145 |
+
elif np.iterable(linestyles):
|
| 1146 |
+
tlinestyles = list(linestyles)
|
| 1147 |
+
if len(tlinestyles) < Nlev:
|
| 1148 |
+
nreps = int(np.ceil(Nlev / len(linestyles)))
|
| 1149 |
+
tlinestyles = tlinestyles * nreps
|
| 1150 |
+
if len(tlinestyles) > Nlev:
|
| 1151 |
+
tlinestyles = tlinestyles[:Nlev]
|
| 1152 |
+
else:
|
| 1153 |
+
raise ValueError("Unrecognized type for linestyles kwarg")
|
| 1154 |
+
return tlinestyles
|
| 1155 |
+
|
| 1156 |
+
def _find_nearest_contour(self, xy, indices=None):
|
| 1157 |
+
"""
|
| 1158 |
+
Find the point in the unfilled contour plot that is closest (in screen
|
| 1159 |
+
space) to point *xy*.
|
| 1160 |
+
|
| 1161 |
+
Parameters
|
| 1162 |
+
----------
|
| 1163 |
+
xy : tuple[float, float]
|
| 1164 |
+
The reference point (in screen space).
|
| 1165 |
+
indices : list of int or None, default: None
|
| 1166 |
+
Indices of contour levels to consider. If None (the default), all levels
|
| 1167 |
+
are considered.
|
| 1168 |
+
|
| 1169 |
+
Returns
|
| 1170 |
+
-------
|
| 1171 |
+
idx_level_min : int
|
| 1172 |
+
The index of the contour level closest to *xy*.
|
| 1173 |
+
idx_vtx_min : int
|
| 1174 |
+
The index of the `.Path` segment closest to *xy* (at that level).
|
| 1175 |
+
proj : (float, float)
|
| 1176 |
+
The point in the contour plot closest to *xy*.
|
| 1177 |
+
"""
|
| 1178 |
+
|
| 1179 |
+
# Convert each contour segment to pixel coordinates and then compare the given
|
| 1180 |
+
# point to those coordinates for each contour. This is fast enough in normal
|
| 1181 |
+
# cases, but speedups may be possible.
|
| 1182 |
+
|
| 1183 |
+
if self.filled:
|
| 1184 |
+
raise ValueError("Method does not support filled contours")
|
| 1185 |
+
|
| 1186 |
+
if indices is None:
|
| 1187 |
+
indices = range(len(self._paths))
|
| 1188 |
+
|
| 1189 |
+
d2min = np.inf
|
| 1190 |
+
idx_level_min = idx_vtx_min = proj_min = None
|
| 1191 |
+
|
| 1192 |
+
for idx_level in indices:
|
| 1193 |
+
path = self._paths[idx_level]
|
| 1194 |
+
idx_vtx_start = 0
|
| 1195 |
+
for subpath in path._iter_connected_components():
|
| 1196 |
+
if not len(subpath.vertices):
|
| 1197 |
+
continue
|
| 1198 |
+
lc = self.get_transform().transform(subpath.vertices)
|
| 1199 |
+
d2, proj, leg = _find_closest_point_on_path(lc, xy)
|
| 1200 |
+
if d2 < d2min:
|
| 1201 |
+
d2min = d2
|
| 1202 |
+
idx_level_min = idx_level
|
| 1203 |
+
idx_vtx_min = leg[1] + idx_vtx_start
|
| 1204 |
+
proj_min = proj
|
| 1205 |
+
idx_vtx_start += len(subpath)
|
| 1206 |
+
|
| 1207 |
+
return idx_level_min, idx_vtx_min, proj_min
|
| 1208 |
+
|
| 1209 |
+
def find_nearest_contour(self, x, y, indices=None, pixel=True):
|
| 1210 |
+
"""
|
| 1211 |
+
Find the point in the contour plot that is closest to ``(x, y)``.
|
| 1212 |
+
|
| 1213 |
+
This method does not support filled contours.
|
| 1214 |
+
|
| 1215 |
+
Parameters
|
| 1216 |
+
----------
|
| 1217 |
+
x, y : float
|
| 1218 |
+
The reference point.
|
| 1219 |
+
indices : list of int or None, default: None
|
| 1220 |
+
Indices of contour levels to consider. If None (the default), all
|
| 1221 |
+
levels are considered.
|
| 1222 |
+
pixel : bool, default: True
|
| 1223 |
+
If *True*, measure distance in pixel (screen) space, which is
|
| 1224 |
+
useful for manual contour labeling; else, measure distance in axes
|
| 1225 |
+
space.
|
| 1226 |
+
|
| 1227 |
+
Returns
|
| 1228 |
+
-------
|
| 1229 |
+
path : int
|
| 1230 |
+
The index of the path that is closest to ``(x, y)``. Each path corresponds
|
| 1231 |
+
to one contour level.
|
| 1232 |
+
subpath : int
|
| 1233 |
+
The index within that closest path of the subpath that is closest to
|
| 1234 |
+
``(x, y)``. Each subpath corresponds to one unbroken contour line.
|
| 1235 |
+
index : int
|
| 1236 |
+
The index of the vertices within that subpath that are closest to
|
| 1237 |
+
``(x, y)``.
|
| 1238 |
+
xmin, ymin : float
|
| 1239 |
+
The point in the contour plot that is closest to ``(x, y)``.
|
| 1240 |
+
d2 : float
|
| 1241 |
+
The squared distance from ``(xmin, ymin)`` to ``(x, y)``.
|
| 1242 |
+
"""
|
| 1243 |
+
segment = index = d2 = None
|
| 1244 |
+
|
| 1245 |
+
with ExitStack() as stack:
|
| 1246 |
+
if not pixel:
|
| 1247 |
+
# _find_nearest_contour works in pixel space. We want axes space, so
|
| 1248 |
+
# effectively disable the transformation here by setting to identity.
|
| 1249 |
+
stack.enter_context(self._cm_set(
|
| 1250 |
+
transform=mtransforms.IdentityTransform()))
|
| 1251 |
+
|
| 1252 |
+
i_level, i_vtx, (xmin, ymin) = self._find_nearest_contour((x, y), indices)
|
| 1253 |
+
|
| 1254 |
+
if i_level is not None:
|
| 1255 |
+
cc_cumlens = np.cumsum(
|
| 1256 |
+
[*map(len, self._paths[i_level]._iter_connected_components())])
|
| 1257 |
+
segment = cc_cumlens.searchsorted(i_vtx, "right")
|
| 1258 |
+
index = i_vtx if segment == 0 else i_vtx - cc_cumlens[segment - 1]
|
| 1259 |
+
d2 = (xmin-x)**2 + (ymin-y)**2
|
| 1260 |
+
|
| 1261 |
+
return (i_level, segment, index, xmin, ymin, d2)
|
| 1262 |
+
|
| 1263 |
+
def draw(self, renderer):
|
| 1264 |
+
paths = self._paths
|
| 1265 |
+
n_paths = len(paths)
|
| 1266 |
+
if not self.filled or all(hatch is None for hatch in self.hatches):
|
| 1267 |
+
super().draw(renderer)
|
| 1268 |
+
return
|
| 1269 |
+
# In presence of hatching, draw contours one at a time.
|
| 1270 |
+
edgecolors = self.get_edgecolors()
|
| 1271 |
+
if edgecolors.size == 0:
|
| 1272 |
+
edgecolors = ("none",)
|
| 1273 |
+
for idx in range(n_paths):
|
| 1274 |
+
with cbook._setattr_cm(self, _paths=[paths[idx]]), self._cm_set(
|
| 1275 |
+
hatch=self.hatches[idx % len(self.hatches)],
|
| 1276 |
+
array=[self.get_array()[idx]],
|
| 1277 |
+
linewidths=[self.get_linewidths()[idx % len(self.get_linewidths())]],
|
| 1278 |
+
linestyles=[self.get_linestyles()[idx % len(self.get_linestyles())]],
|
| 1279 |
+
edgecolors=edgecolors[idx % len(edgecolors)],
|
| 1280 |
+
):
|
| 1281 |
+
super().draw(renderer)
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
@_docstring.interpd
|
| 1285 |
+
class QuadContourSet(ContourSet):
|
| 1286 |
+
"""
|
| 1287 |
+
Create and store a set of contour lines or filled regions.
|
| 1288 |
+
|
| 1289 |
+
This class is typically not instantiated directly by the user but by
|
| 1290 |
+
`~.Axes.contour` and `~.Axes.contourf`.
|
| 1291 |
+
|
| 1292 |
+
%(contour_set_attributes)s
|
| 1293 |
+
"""
|
| 1294 |
+
|
| 1295 |
+
def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs):
|
| 1296 |
+
"""
|
| 1297 |
+
Process args and kwargs.
|
| 1298 |
+
"""
|
| 1299 |
+
if args and isinstance(args[0], QuadContourSet):
|
| 1300 |
+
if self.levels is None:
|
| 1301 |
+
self.levels = args[0].levels
|
| 1302 |
+
self.zmin = args[0].zmin
|
| 1303 |
+
self.zmax = args[0].zmax
|
| 1304 |
+
self._corner_mask = args[0]._corner_mask
|
| 1305 |
+
contour_generator = args[0]._contour_generator
|
| 1306 |
+
self._mins = args[0]._mins
|
| 1307 |
+
self._maxs = args[0]._maxs
|
| 1308 |
+
self._algorithm = args[0]._algorithm
|
| 1309 |
+
else:
|
| 1310 |
+
import contourpy
|
| 1311 |
+
|
| 1312 |
+
if algorithm is None:
|
| 1313 |
+
algorithm = mpl.rcParams['contour.algorithm']
|
| 1314 |
+
mpl.rcParams.validate["contour.algorithm"](algorithm)
|
| 1315 |
+
self._algorithm = algorithm
|
| 1316 |
+
|
| 1317 |
+
if corner_mask is None:
|
| 1318 |
+
if self._algorithm == "mpl2005":
|
| 1319 |
+
# mpl2005 does not support corner_mask=True so if not
|
| 1320 |
+
# specifically requested then disable it.
|
| 1321 |
+
corner_mask = False
|
| 1322 |
+
else:
|
| 1323 |
+
corner_mask = mpl.rcParams['contour.corner_mask']
|
| 1324 |
+
self._corner_mask = corner_mask
|
| 1325 |
+
|
| 1326 |
+
x, y, z = self._contour_args(args, kwargs)
|
| 1327 |
+
|
| 1328 |
+
contour_generator = contourpy.contour_generator(
|
| 1329 |
+
x, y, z, name=self._algorithm, corner_mask=self._corner_mask,
|
| 1330 |
+
line_type=contourpy.LineType.SeparateCode,
|
| 1331 |
+
fill_type=contourpy.FillType.OuterCode,
|
| 1332 |
+
chunk_size=self.nchunk)
|
| 1333 |
+
|
| 1334 |
+
t = self.get_transform()
|
| 1335 |
+
|
| 1336 |
+
# if the transform is not trans data, and some part of it
|
| 1337 |
+
# contains transData, transform the xs and ys to data coordinates
|
| 1338 |
+
if (t != self.axes.transData and
|
| 1339 |
+
any(t.contains_branch_seperately(self.axes.transData))):
|
| 1340 |
+
trans_to_data = t - self.axes.transData
|
| 1341 |
+
pts = np.vstack([x.flat, y.flat]).T
|
| 1342 |
+
transformed_pts = trans_to_data.transform(pts)
|
| 1343 |
+
x = transformed_pts[..., 0]
|
| 1344 |
+
y = transformed_pts[..., 1]
|
| 1345 |
+
|
| 1346 |
+
self._mins = [ma.min(x), ma.min(y)]
|
| 1347 |
+
self._maxs = [ma.max(x), ma.max(y)]
|
| 1348 |
+
|
| 1349 |
+
self._contour_generator = contour_generator
|
| 1350 |
+
|
| 1351 |
+
return kwargs
|
| 1352 |
+
|
| 1353 |
+
def _contour_args(self, args, kwargs):
|
| 1354 |
+
if self.filled:
|
| 1355 |
+
fn = 'contourf'
|
| 1356 |
+
else:
|
| 1357 |
+
fn = 'contour'
|
| 1358 |
+
nargs = len(args)
|
| 1359 |
+
|
| 1360 |
+
if 0 < nargs <= 2:
|
| 1361 |
+
z, *args = args
|
| 1362 |
+
z = ma.asarray(z)
|
| 1363 |
+
x, y = self._initialize_x_y(z)
|
| 1364 |
+
elif 2 < nargs <= 4:
|
| 1365 |
+
x, y, z_orig, *args = args
|
| 1366 |
+
x, y, z = self._check_xyz(x, y, z_orig, kwargs)
|
| 1367 |
+
|
| 1368 |
+
else:
|
| 1369 |
+
raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)
|
| 1370 |
+
z = ma.masked_invalid(z, copy=False)
|
| 1371 |
+
self.zmax = z.max().astype(float)
|
| 1372 |
+
self.zmin = z.min().astype(float)
|
| 1373 |
+
if self.logscale and self.zmin <= 0:
|
| 1374 |
+
z = ma.masked_where(z <= 0, z)
|
| 1375 |
+
_api.warn_external('Log scale: values of z <= 0 have been masked')
|
| 1376 |
+
self.zmin = z.min().astype(float)
|
| 1377 |
+
self._process_contour_level_args(args, z.dtype)
|
| 1378 |
+
return (x, y, z)
|
| 1379 |
+
|
| 1380 |
+
def _check_xyz(self, x, y, z, kwargs):
|
| 1381 |
+
"""
|
| 1382 |
+
Check that the shapes of the input arrays match; if x and y are 1D,
|
| 1383 |
+
convert them to 2D using meshgrid.
|
| 1384 |
+
"""
|
| 1385 |
+
x, y = self.axes._process_unit_info([("x", x), ("y", y)], kwargs)
|
| 1386 |
+
|
| 1387 |
+
x = np.asarray(x, dtype=np.float64)
|
| 1388 |
+
y = np.asarray(y, dtype=np.float64)
|
| 1389 |
+
z = ma.asarray(z)
|
| 1390 |
+
|
| 1391 |
+
if z.ndim != 2:
|
| 1392 |
+
raise TypeError(f"Input z must be 2D, not {z.ndim}D")
|
| 1393 |
+
if z.shape[0] < 2 or z.shape[1] < 2:
|
| 1394 |
+
raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
|
| 1395 |
+
f"but has shape {z.shape}")
|
| 1396 |
+
Ny, Nx = z.shape
|
| 1397 |
+
|
| 1398 |
+
if x.ndim != y.ndim:
|
| 1399 |
+
raise TypeError(f"Number of dimensions of x ({x.ndim}) and y "
|
| 1400 |
+
f"({y.ndim}) do not match")
|
| 1401 |
+
if x.ndim == 1:
|
| 1402 |
+
nx, = x.shape
|
| 1403 |
+
ny, = y.shape
|
| 1404 |
+
if nx != Nx:
|
| 1405 |
+
raise TypeError(f"Length of x ({nx}) must match number of "
|
| 1406 |
+
f"columns in z ({Nx})")
|
| 1407 |
+
if ny != Ny:
|
| 1408 |
+
raise TypeError(f"Length of y ({ny}) must match number of "
|
| 1409 |
+
f"rows in z ({Ny})")
|
| 1410 |
+
x, y = np.meshgrid(x, y)
|
| 1411 |
+
elif x.ndim == 2:
|
| 1412 |
+
if x.shape != z.shape:
|
| 1413 |
+
raise TypeError(
|
| 1414 |
+
f"Shapes of x {x.shape} and z {z.shape} do not match")
|
| 1415 |
+
if y.shape != z.shape:
|
| 1416 |
+
raise TypeError(
|
| 1417 |
+
f"Shapes of y {y.shape} and z {z.shape} do not match")
|
| 1418 |
+
else:
|
| 1419 |
+
raise TypeError(f"Inputs x and y must be 1D or 2D, not {x.ndim}D")
|
| 1420 |
+
|
| 1421 |
+
return x, y, z
|
| 1422 |
+
|
| 1423 |
+
def _initialize_x_y(self, z):
|
| 1424 |
+
"""
|
| 1425 |
+
Return X, Y arrays such that contour(Z) will match imshow(Z)
|
| 1426 |
+
if origin is not None.
|
| 1427 |
+
The center of pixel Z[i, j] depends on origin:
|
| 1428 |
+
if origin is None, x = j, y = i;
|
| 1429 |
+
if origin is 'lower', x = j + 0.5, y = i + 0.5;
|
| 1430 |
+
if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
|
| 1431 |
+
If extent is not None, x and y will be scaled to match,
|
| 1432 |
+
as in imshow.
|
| 1433 |
+
If origin is None and extent is not None, then extent
|
| 1434 |
+
will give the minimum and maximum values of x and y.
|
| 1435 |
+
"""
|
| 1436 |
+
if z.ndim != 2:
|
| 1437 |
+
raise TypeError(f"Input z must be 2D, not {z.ndim}D")
|
| 1438 |
+
elif z.shape[0] < 2 or z.shape[1] < 2:
|
| 1439 |
+
raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
|
| 1440 |
+
f"but has shape {z.shape}")
|
| 1441 |
+
else:
|
| 1442 |
+
Ny, Nx = z.shape
|
| 1443 |
+
if self.origin is None: # Not for image-matching.
|
| 1444 |
+
if self.extent is None:
|
| 1445 |
+
return np.meshgrid(np.arange(Nx), np.arange(Ny))
|
| 1446 |
+
else:
|
| 1447 |
+
x0, x1, y0, y1 = self.extent
|
| 1448 |
+
x = np.linspace(x0, x1, Nx)
|
| 1449 |
+
y = np.linspace(y0, y1, Ny)
|
| 1450 |
+
return np.meshgrid(x, y)
|
| 1451 |
+
# Match image behavior:
|
| 1452 |
+
if self.extent is None:
|
| 1453 |
+
x0, x1, y0, y1 = (0, Nx, 0, Ny)
|
| 1454 |
+
else:
|
| 1455 |
+
x0, x1, y0, y1 = self.extent
|
| 1456 |
+
dx = (x1 - x0) / Nx
|
| 1457 |
+
dy = (y1 - y0) / Ny
|
| 1458 |
+
x = x0 + (np.arange(Nx) + 0.5) * dx
|
| 1459 |
+
y = y0 + (np.arange(Ny) + 0.5) * dy
|
| 1460 |
+
if self.origin == 'upper':
|
| 1461 |
+
y = y[::-1]
|
| 1462 |
+
return np.meshgrid(x, y)
|
| 1463 |
+
|
| 1464 |
+
|
| 1465 |
+
_docstring.interpd.register(contour_doc="""
|
| 1466 |
+
`.contour` and `.contourf` draw contour lines and filled contours,
|
| 1467 |
+
respectively. Except as noted, function signatures and return values
|
| 1468 |
+
are the same for both versions.
|
| 1469 |
+
|
| 1470 |
+
Parameters
|
| 1471 |
+
----------
|
| 1472 |
+
X, Y : array-like, optional
|
| 1473 |
+
The coordinates of the values in *Z*.
|
| 1474 |
+
|
| 1475 |
+
*X* and *Y* must both be 2D with the same shape as *Z* (e.g.
|
| 1476 |
+
created via `numpy.meshgrid`), or they must both be 1-D such
|
| 1477 |
+
that ``len(X) == N`` is the number of columns in *Z* and
|
| 1478 |
+
``len(Y) == M`` is the number of rows in *Z*.
|
| 1479 |
+
|
| 1480 |
+
*X* and *Y* must both be ordered monotonically.
|
| 1481 |
+
|
| 1482 |
+
If not given, they are assumed to be integer indices, i.e.
|
| 1483 |
+
``X = range(N)``, ``Y = range(M)``.
|
| 1484 |
+
|
| 1485 |
+
Z : (M, N) array-like
|
| 1486 |
+
The height values over which the contour is drawn. Color-mapping is
|
| 1487 |
+
controlled by *cmap*, *norm*, *vmin*, and *vmax*.
|
| 1488 |
+
|
| 1489 |
+
levels : int or array-like, optional
|
| 1490 |
+
Determines the number and positions of the contour lines / regions.
|
| 1491 |
+
|
| 1492 |
+
If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries
|
| 1493 |
+
to automatically choose no more than *n+1* "nice" contour levels
|
| 1494 |
+
between minimum and maximum numeric values of *Z*.
|
| 1495 |
+
|
| 1496 |
+
If array-like, draw contour lines at the specified levels.
|
| 1497 |
+
The values must be in increasing order.
|
| 1498 |
+
|
| 1499 |
+
Returns
|
| 1500 |
+
-------
|
| 1501 |
+
`~.contour.QuadContourSet`
|
| 1502 |
+
|
| 1503 |
+
Other Parameters
|
| 1504 |
+
----------------
|
| 1505 |
+
corner_mask : bool, default: :rc:`contour.corner_mask`
|
| 1506 |
+
Enable/disable corner masking, which only has an effect if *Z* is
|
| 1507 |
+
a masked array. If ``False``, any quad touching a masked point is
|
| 1508 |
+
masked out. If ``True``, only the triangular corners of quads
|
| 1509 |
+
nearest those points are always masked out, other triangular
|
| 1510 |
+
corners comprising three unmasked points are contoured as usual.
|
| 1511 |
+
|
| 1512 |
+
colors : :mpltype:`color` or list of :mpltype:`color`, optional
|
| 1513 |
+
The colors of the levels, i.e. the lines for `.contour` and the
|
| 1514 |
+
areas for `.contourf`.
|
| 1515 |
+
|
| 1516 |
+
The sequence is cycled for the levels in ascending order. If the
|
| 1517 |
+
sequence is shorter than the number of levels, it's repeated.
|
| 1518 |
+
|
| 1519 |
+
As a shortcut, a single color may be used in place of one-element lists, i.e.
|
| 1520 |
+
``'red'`` instead of ``['red']`` to color all levels with the same color.
|
| 1521 |
+
|
| 1522 |
+
.. versionchanged:: 3.10
|
| 1523 |
+
Previously a single color had to be expressed as a string, but now any
|
| 1524 |
+
valid color format may be passed.
|
| 1525 |
+
|
| 1526 |
+
By default (value *None*), the colormap specified by *cmap*
|
| 1527 |
+
will be used.
|
| 1528 |
+
|
| 1529 |
+
alpha : float, default: 1
|
| 1530 |
+
The alpha blending value, between 0 (transparent) and 1 (opaque).
|
| 1531 |
+
|
| 1532 |
+
%(cmap_doc)s
|
| 1533 |
+
|
| 1534 |
+
This parameter is ignored if *colors* is set.
|
| 1535 |
+
|
| 1536 |
+
%(norm_doc)s
|
| 1537 |
+
|
| 1538 |
+
This parameter is ignored if *colors* is set.
|
| 1539 |
+
|
| 1540 |
+
%(vmin_vmax_doc)s
|
| 1541 |
+
|
| 1542 |
+
If *vmin* or *vmax* are not given, the default color scaling is based on
|
| 1543 |
+
*levels*.
|
| 1544 |
+
|
| 1545 |
+
This parameter is ignored if *colors* is set.
|
| 1546 |
+
|
| 1547 |
+
%(colorizer_doc)s
|
| 1548 |
+
|
| 1549 |
+
This parameter is ignored if *colors* is set.
|
| 1550 |
+
|
| 1551 |
+
origin : {*None*, 'upper', 'lower', 'image'}, default: None
|
| 1552 |
+
Determines the orientation and exact position of *Z* by specifying
|
| 1553 |
+
the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*
|
| 1554 |
+
are not given.
|
| 1555 |
+
|
| 1556 |
+
- *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
|
| 1557 |
+
- 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
|
| 1558 |
+
- 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
|
| 1559 |
+
corner.
|
| 1560 |
+
- 'image': Use the value from :rc:`image.origin`.
|
| 1561 |
+
|
| 1562 |
+
extent : (x0, x1, y0, y1), optional
|
| 1563 |
+
If *origin* is not *None*, then *extent* is interpreted as in
|
| 1564 |
+
`.imshow`: it gives the outer pixel boundaries. In this case, the
|
| 1565 |
+
position of Z[0, 0] is the center of the pixel, not a corner. If
|
| 1566 |
+
*origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],
|
| 1567 |
+
and (*x1*, *y1*) is the position of Z[-1, -1].
|
| 1568 |
+
|
| 1569 |
+
This argument is ignored if *X* and *Y* are specified in the call
|
| 1570 |
+
to contour.
|
| 1571 |
+
|
| 1572 |
+
locator : ticker.Locator subclass, optional
|
| 1573 |
+
The locator is used to determine the contour levels if they
|
| 1574 |
+
are not given explicitly via *levels*.
|
| 1575 |
+
Defaults to `~.ticker.MaxNLocator`.
|
| 1576 |
+
|
| 1577 |
+
extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
|
| 1578 |
+
Determines the ``contourf``-coloring of values that are outside the
|
| 1579 |
+
*levels* range.
|
| 1580 |
+
|
| 1581 |
+
If 'neither', values outside the *levels* range are not colored.
|
| 1582 |
+
If 'min', 'max' or 'both', color the values below, above or below
|
| 1583 |
+
and above the *levels* range.
|
| 1584 |
+
|
| 1585 |
+
Values below ``min(levels)`` and above ``max(levels)`` are mapped
|
| 1586 |
+
to the under/over values of the `.Colormap`. Note that most
|
| 1587 |
+
colormaps do not have dedicated colors for these by default, so
|
| 1588 |
+
that the over and under values are the edge values of the colormap.
|
| 1589 |
+
You may want to set these values explicitly using
|
| 1590 |
+
`.Colormap.set_under` and `.Colormap.set_over`.
|
| 1591 |
+
|
| 1592 |
+
.. note::
|
| 1593 |
+
|
| 1594 |
+
An existing `.QuadContourSet` does not get notified if
|
| 1595 |
+
properties of its colormap are changed. Therefore, an explicit
|
| 1596 |
+
call `~.ContourSet.changed()` is needed after modifying the
|
| 1597 |
+
colormap. The explicit call can be left out, if a colorbar is
|
| 1598 |
+
assigned to the `.QuadContourSet` because it internally calls
|
| 1599 |
+
`~.ContourSet.changed()`.
|
| 1600 |
+
|
| 1601 |
+
Example::
|
| 1602 |
+
|
| 1603 |
+
x = np.arange(1, 10)
|
| 1604 |
+
y = x.reshape(-1, 1)
|
| 1605 |
+
h = x * y
|
| 1606 |
+
|
| 1607 |
+
cs = plt.contourf(h, levels=[10, 30, 50],
|
| 1608 |
+
colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
|
| 1609 |
+
cs.cmap.set_over('red')
|
| 1610 |
+
cs.cmap.set_under('blue')
|
| 1611 |
+
cs.changed()
|
| 1612 |
+
|
| 1613 |
+
xunits, yunits : registered units, optional
|
| 1614 |
+
Override axis units by specifying an instance of a
|
| 1615 |
+
:class:`matplotlib.units.ConversionInterface`.
|
| 1616 |
+
|
| 1617 |
+
antialiased : bool, optional
|
| 1618 |
+
Enable antialiasing, overriding the defaults. For
|
| 1619 |
+
filled contours, the default is *False*. For line contours,
|
| 1620 |
+
it is taken from :rc:`lines.antialiased`.
|
| 1621 |
+
|
| 1622 |
+
nchunk : int >= 0, optional
|
| 1623 |
+
If 0, no subdivision of the domain. Specify a positive integer to
|
| 1624 |
+
divide the domain into subdomains of *nchunk* by *nchunk* quads.
|
| 1625 |
+
Chunking reduces the maximum length of polygons generated by the
|
| 1626 |
+
contouring algorithm which reduces the rendering workload passed
|
| 1627 |
+
on to the backend and also requires slightly less RAM. It can
|
| 1628 |
+
however introduce rendering artifacts at chunk boundaries depending
|
| 1629 |
+
on the backend, the *antialiased* flag and value of *alpha*.
|
| 1630 |
+
|
| 1631 |
+
linewidths : float or array-like, default: :rc:`contour.linewidth`
|
| 1632 |
+
*Only applies to* `.contour`.
|
| 1633 |
+
|
| 1634 |
+
The line width of the contour lines.
|
| 1635 |
+
|
| 1636 |
+
If a number, all levels will be plotted with this linewidth.
|
| 1637 |
+
|
| 1638 |
+
If a sequence, the levels in ascending order will be plotted with
|
| 1639 |
+
the linewidths in the order specified.
|
| 1640 |
+
|
| 1641 |
+
If None, this falls back to :rc:`lines.linewidth`.
|
| 1642 |
+
|
| 1643 |
+
linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
|
| 1644 |
+
*Only applies to* `.contour`.
|
| 1645 |
+
|
| 1646 |
+
If *linestyles* is *None*, the default is 'solid' unless the lines are
|
| 1647 |
+
monochrome. In that case, negative contours will instead take their
|
| 1648 |
+
linestyle from the *negative_linestyles* argument.
|
| 1649 |
+
|
| 1650 |
+
*linestyles* can also be an iterable of the above strings specifying a set
|
| 1651 |
+
of linestyles to be used. If this iterable is shorter than the number of
|
| 1652 |
+
contour levels it will be repeated as necessary.
|
| 1653 |
+
|
| 1654 |
+
negative_linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, \
|
| 1655 |
+
optional
|
| 1656 |
+
*Only applies to* `.contour`.
|
| 1657 |
+
|
| 1658 |
+
If *linestyles* is *None* and the lines are monochrome, this argument
|
| 1659 |
+
specifies the line style for negative contours.
|
| 1660 |
+
|
| 1661 |
+
If *negative_linestyles* is *None*, the default is taken from
|
| 1662 |
+
:rc:`contour.negative_linestyle`.
|
| 1663 |
+
|
| 1664 |
+
*negative_linestyles* can also be an iterable of the above strings
|
| 1665 |
+
specifying a set of linestyles to be used. If this iterable is shorter than
|
| 1666 |
+
the number of contour levels it will be repeated as necessary.
|
| 1667 |
+
|
| 1668 |
+
hatches : list[str], optional
|
| 1669 |
+
*Only applies to* `.contourf`.
|
| 1670 |
+
|
| 1671 |
+
A list of cross hatch patterns to use on the filled areas.
|
| 1672 |
+
If None, no hatching will be added to the contour.
|
| 1673 |
+
|
| 1674 |
+
algorithm : {'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional
|
| 1675 |
+
Which contouring algorithm to use to calculate the contour lines and
|
| 1676 |
+
polygons. The algorithms are implemented in
|
| 1677 |
+
`ContourPy <https://github.com/contourpy/contourpy>`_, consult the
|
| 1678 |
+
`ContourPy documentation <https://contourpy.readthedocs.io>`_ for
|
| 1679 |
+
further information.
|
| 1680 |
+
|
| 1681 |
+
The default is taken from :rc:`contour.algorithm`.
|
| 1682 |
+
|
| 1683 |
+
clip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`
|
| 1684 |
+
Set the clip path. See `~matplotlib.artist.Artist.set_clip_path`.
|
| 1685 |
+
|
| 1686 |
+
.. versionadded:: 3.8
|
| 1687 |
+
|
| 1688 |
+
data : indexable object, optional
|
| 1689 |
+
DATA_PARAMETER_PLACEHOLDER
|
| 1690 |
+
|
| 1691 |
+
Notes
|
| 1692 |
+
-----
|
| 1693 |
+
1. `.contourf` differs from the MATLAB version in that it does not draw
|
| 1694 |
+
the polygon edges. To draw edges, add line contours with calls to
|
| 1695 |
+
`.contour`.
|
| 1696 |
+
|
| 1697 |
+
2. `.contourf` fills intervals that are closed at the top; that is, for
|
| 1698 |
+
boundaries *z1* and *z2*, the filled region is::
|
| 1699 |
+
|
| 1700 |
+
z1 < Z <= z2
|
| 1701 |
+
|
| 1702 |
+
except for the lowest interval, which is closed on both sides (i.e.
|
| 1703 |
+
it includes the lowest value).
|
| 1704 |
+
|
| 1705 |
+
3. `.contour` and `.contourf` use a `marching squares
|
| 1706 |
+
<https://en.wikipedia.org/wiki/Marching_squares>`_ algorithm to
|
| 1707 |
+
compute contour locations. More information can be found in
|
| 1708 |
+
`ContourPy documentation <https://contourpy.readthedocs.io>`_.
|
| 1709 |
+
""" % _docstring.interpd.params)
|