diff --git a/.gitattributes b/.gitattributes
index 46c5e5d6ee93435193011ac7b7b7a09c5cb819fc..f545650f193623d52120bec4809664804dbf5031 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -666,3 +666,7 @@ llava_video/lib/python3.10/site-packages/scipy/ndimage/_ni_label.cpython-310-x86
llava_video/lib/python3.10/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
llava_video/lib/python3.10/site-packages/fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
+llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+llava_video/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+llava_video/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+llava_video/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/__init__.py b/llava_video/lib/python3.10/site-packages/matplotlib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f964e0b34dea11f572136a3bb6e3d9968ebe754
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/__init__.py
@@ -0,0 +1,1576 @@
+"""
+An object-oriented plotting library.
+
+A procedural interface is provided by the companion pyplot module,
+which may be imported directly, e.g.::
+
+ import matplotlib.pyplot as plt
+
+or using ipython::
+
+ ipython
+
+at your terminal, followed by::
+
+ In [1]: %matplotlib
+ In [2]: import matplotlib.pyplot as plt
+
+at the ipython shell prompt.
+
+For the most part, direct use of the explicit object-oriented library is
+encouraged when programming; the implicit pyplot interface is primarily for
+working interactively. The exceptions to this suggestion are the pyplot
+functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and
+`.pyplot.savefig`, which can greatly simplify scripting. See
+:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit
+and explicit interfaces.
+
+Modules include:
+
+:mod:`matplotlib.axes`
+ The `~.axes.Axes` class. Most pyplot functions are wrappers for
+ `~.axes.Axes` methods. The axes module is the highest level of OO
+ access to the library.
+
+:mod:`matplotlib.figure`
+ The `.Figure` class.
+
+:mod:`matplotlib.artist`
+ The `.Artist` base class for all classes that draw things.
+
+:mod:`matplotlib.lines`
+ The `.Line2D` class for drawing lines and markers.
+
+:mod:`matplotlib.patches`
+ Classes for drawing polygons.
+
+:mod:`matplotlib.text`
+ The `.Text` and `.Annotation` classes.
+
+:mod:`matplotlib.image`
+ The `.AxesImage` and `.FigureImage` classes.
+
+:mod:`matplotlib.collections`
+ Classes for efficient drawing of groups of lines or polygons.
+
+:mod:`matplotlib.colors`
+ Color specifications and making colormaps.
+
+:mod:`matplotlib.cm`
+ Colormaps, and the `.ScalarMappable` mixin class for providing color
+ mapping functionality to other classes.
+
+:mod:`matplotlib.ticker`
+ Calculation of tick mark locations and formatting of tick labels.
+
+:mod:`matplotlib.backends`
+ A subpackage with modules for various GUI libraries and output formats.
+
+The base matplotlib namespace includes:
+
+`~matplotlib.rcParams`
+ Default configuration settings; their defaults may be overridden using
+ a :file:`matplotlibrc` file.
+
+`~matplotlib.use`
+ Setting the Matplotlib backend. This should be called before any
+ figure is created, because it is not possible to switch between
+ different GUI backends after that.
+
+The following environment variables can be used to customize the behavior:
+
+:envvar:`MPLBACKEND`
+ This optional variable can be set to choose the Matplotlib backend. See
+ :ref:`what-is-a-backend`.
+
+:envvar:`MPLCONFIGDIR`
+ This is the directory used to store user customizations to
+ Matplotlib, as well as some caches to improve performance. If
+ :envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`
+ and :file:`{HOME}/.cache/matplotlib` are used on Linux, and
+ :file:`{HOME}/.matplotlib` on other platforms, if they are
+ writable. Otherwise, the Python standard library's `tempfile.gettempdir`
+ is used to find a base directory in which the :file:`matplotlib`
+ subdirectory is created.
+
+Matplotlib was initially written by John D. Hunter (1968-2012) and is now
+developed and maintained by a host of others.
+
+Occasionally the internal documentation (python docstrings) will refer
+to MATLAB®, a registered trademark of The MathWorks, Inc.
+
+"""
+
+__all__ = [
+ "__bibtex__",
+ "__version__",
+ "__version_info__",
+ "set_loglevel",
+ "ExecutableNotFoundError",
+ "get_configdir",
+ "get_cachedir",
+ "get_data_path",
+ "matplotlib_fname",
+ "MatplotlibDeprecationWarning",
+ "RcParams",
+ "rc_params",
+ "rc_params_from_file",
+ "rcParamsDefault",
+ "rcParams",
+ "rcParamsOrig",
+ "defaultParams",
+ "rc",
+ "rcdefaults",
+ "rc_file_defaults",
+ "rc_file",
+ "rc_context",
+ "use",
+ "get_backend",
+ "interactive",
+ "is_interactive",
+ "colormaps",
+ "multivar_colormaps",
+ "bivar_colormaps",
+ "color_sequences",
+]
+
+
+import atexit
+from collections import namedtuple
+from collections.abc import MutableMapping
+import contextlib
+import functools
+import importlib
+import inspect
+from inspect import Parameter
+import locale
+import logging
+import os
+from pathlib import Path
+import pprint
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+from packaging.version import parse as parse_version
+
+# cbook must import matplotlib only within function
+# definitions, so it is safe to import from it here.
+from . import _api, _version, cbook, _docstring, rcsetup
+from matplotlib._api import MatplotlibDeprecationWarning
+from matplotlib.rcsetup import cycler # noqa: F401
+
+
+_log = logging.getLogger(__name__)
+
+__bibtex__ = r"""@Article{Hunter:2007,
+ Author = {Hunter, J. D.},
+ Title = {Matplotlib: A 2D graphics environment},
+ Journal = {Computing in Science \& Engineering},
+ Volume = {9},
+ Number = {3},
+ Pages = {90--95},
+ abstract = {Matplotlib is a 2D graphics package used for Python
+ for application development, interactive scripting, and
+ publication-quality image generation across user
+ interfaces and operating systems.},
+ publisher = {IEEE COMPUTER SOC},
+ year = 2007
+}"""
+
+# modelled after sys.version_info
+_VersionInfo = namedtuple('_VersionInfo',
+ 'major, minor, micro, releaselevel, serial')
+
+
+def _parse_to_version_info(version_str):
+ """
+ Parse a version string to a namedtuple analogous to sys.version_info.
+
+ See:
+ https://packaging.pypa.io/en/latest/version.html#packaging.version.parse
+ https://docs.python.org/3/library/sys.html#sys.version_info
+ """
+ v = parse_version(version_str)
+ if v.pre is None and v.post is None and v.dev is None:
+ return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)
+ elif v.dev is not None:
+ return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)
+ elif v.pre is not None:
+ releaselevel = {
+ 'a': 'alpha',
+ 'b': 'beta',
+ 'rc': 'candidate'}.get(v.pre[0], 'alpha')
+ return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])
+ else:
+ # fallback for v.post: guess-next-dev scheme from setuptools_scm
+ return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)
+
+
+def _get_version():
+ """Return the version string used for __version__."""
+ # Only shell out to a git subprocess if really needed, i.e. when we are in
+ # a matplotlib git repo but not in a shallow clone, such as those used by
+ # CI, as the latter would trigger a warning from setuptools_scm.
+ root = Path(__file__).resolve().parents[2]
+ if ((root / ".matplotlib-repo").exists()
+ and (root / ".git").exists()
+ and not (root / ".git/shallow").exists()):
+ try:
+ import setuptools_scm
+ except ImportError:
+ pass
+ else:
+ return setuptools_scm.get_version(
+ root=root,
+ dist_name="matplotlib",
+ version_scheme="release-branch-semver",
+ local_scheme="node-and-date",
+ fallback_version=_version.version,
+ )
+ # Get the version from the _version.py file if not in repo or setuptools_scm is
+ # unavailable.
+ return _version.version
+
+
+@_api.caching_module_getattr
+class __getattr__:
+ __version__ = property(lambda self: _get_version())
+ __version_info__ = property(
+ lambda self: _parse_to_version_info(self.__version__))
+
+
+def _check_versions():
+
+ # Quickfix to ensure Microsoft Visual C++ redistributable
+ # DLLs are loaded before importing kiwisolver
+ from . import ft2font # noqa: F401
+
+ for modname, minver in [
+ ("cycler", "0.10"),
+ ("dateutil", "2.7"),
+ ("kiwisolver", "1.3.1"),
+ ("numpy", "1.23"),
+ ("pyparsing", "2.3.1"),
+ ]:
+ module = importlib.import_module(modname)
+ if parse_version(module.__version__) < parse_version(minver):
+ raise ImportError(f"Matplotlib requires {modname}>={minver}; "
+ f"you have {module.__version__}")
+
+
+_check_versions()
+
+
+# The decorator ensures this always returns the same handler (and it is only
+# attached once).
+@functools.cache
+def _ensure_handler():
+ """
+ The first time this function is called, attach a `StreamHandler` using the
+ same format as `logging.basicConfig` to the Matplotlib root logger.
+
+ Return this handler every time this function is called.
+ """
+ handler = logging.StreamHandler()
+ handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
+ _log.addHandler(handler)
+ return handler
+
+
+def set_loglevel(level):
+ """
+ Configure Matplotlib's logging levels.
+
+ Matplotlib uses the standard library `logging` framework under the root
+ logger 'matplotlib'. This is a helper function to:
+
+ - set Matplotlib's root logger level
+ - set the root logger handler's level, creating the handler
+ if it does not exist yet
+
+ Typically, one should call ``set_loglevel("info")`` or
+ ``set_loglevel("debug")`` to get additional debugging information.
+
+ Users or applications that are installing their own logging handlers
+ may want to directly manipulate ``logging.getLogger('matplotlib')`` rather
+ than use this function.
+
+ Parameters
+ ----------
+ level : {"notset", "debug", "info", "warning", "error", "critical"}
+ The log level of the handler.
+
+ Notes
+ -----
+ The first time this function is called, an additional handler is attached
+ to Matplotlib's root handler; this handler is reused every time and this
+ function simply manipulates the logger and handler's level.
+
+ """
+ _log.setLevel(level.upper())
+ _ensure_handler().setLevel(level.upper())
+
+
+def _logged_cached(fmt, func=None):
+ """
+ Decorator that logs a function's return value, and memoizes that value.
+
+ After ::
+
+ @_logged_cached(fmt)
+ def func(): ...
+
+ the first call to *func* will log its return value at the DEBUG level using
+ %-format string *fmt*, and memoize it; later calls to *func* will directly
+ return that value.
+ """
+ if func is None: # Return the actual decorator.
+ return functools.partial(_logged_cached, fmt)
+
+ called = False
+ ret = None
+
+ @functools.wraps(func)
+ def wrapper(**kwargs):
+ nonlocal called, ret
+ if not called:
+ ret = func(**kwargs)
+ called = True
+ _log.debug(fmt, ret)
+ return ret
+
+ return wrapper
+
+
+_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")
+
+
+class ExecutableNotFoundError(FileNotFoundError):
+ """
+ Error raised when an executable that Matplotlib optionally
+ depends on can't be found.
+ """
+ pass
+
+
+@functools.cache
+def _get_executable_info(name):
+ """
+ Get the version of some executable that Matplotlib optionally depends on.
+
+ .. warning::
+ The list of executables that this function supports is set according to
+ Matplotlib's internal needs, and may change without notice.
+
+ Parameters
+ ----------
+ name : str
+ The executable to query. The following values are currently supported:
+ "dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This
+ list is subject to change without notice.
+
+ Returns
+ -------
+ tuple
+ A namedtuple with fields ``executable`` (`str`) and ``version``
+ (`packaging.Version`, or ``None`` if the version cannot be determined).
+
+ Raises
+ ------
+ ExecutableNotFoundError
+ If the executable is not found or older than the oldest version
+ supported by Matplotlib. For debugging purposes, it is also
+ possible to "hide" an executable from Matplotlib by adding it to the
+ :envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated
+ list), which must be set prior to any calls to this function.
+ ValueError
+ If the executable is not one that we know how to query.
+ """
+
+ def impl(args, regex, min_ver=None, ignore_exit_code=False):
+ # Execute the subprocess specified by args; capture stdout and stderr.
+ # Search for a regex match in the output; if the match succeeds, the
+ # first group of the match is the version.
+ # Return an _ExecInfo if the executable exists, and has a version of
+ # at least min_ver (if set); else, raise ExecutableNotFoundError.
+ try:
+ output = subprocess.check_output(
+ args, stderr=subprocess.STDOUT,
+ text=True, errors="replace")
+ except subprocess.CalledProcessError as _cpe:
+ if ignore_exit_code:
+ output = _cpe.output
+ else:
+ raise ExecutableNotFoundError(str(_cpe)) from _cpe
+ except OSError as _ose:
+ raise ExecutableNotFoundError(str(_ose)) from _ose
+ match = re.search(regex, output)
+ if match:
+ raw_version = match.group(1)
+ version = parse_version(raw_version)
+ if min_ver is not None and version < parse_version(min_ver):
+ raise ExecutableNotFoundError(
+ f"You have {args[0]} version {version} but the minimum "
+ f"version supported by Matplotlib is {min_ver}")
+ return _ExecInfo(args[0], raw_version, version)
+ else:
+ raise ExecutableNotFoundError(
+ f"Failed to determine the version of {args[0]} from "
+ f"{' '.join(args)}, which output {output}")
+
+ if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):
+ raise ExecutableNotFoundError(f"{name} was hidden")
+
+ if name == "dvipng":
+ return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
+ elif name == "gs":
+ execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
+ if sys.platform == "win32" else
+ ["gs"])
+ for e in execs:
+ try:
+ return impl([e, "--version"], "(.*)", "9")
+ except ExecutableNotFoundError:
+ pass
+ message = "Failed to find a Ghostscript installation"
+ raise ExecutableNotFoundError(message)
+ elif name == "inkscape":
+ try:
+ # Try headless option first (needed for Inkscape version < 1.0):
+ return impl(["inkscape", "--without-gui", "-V"],
+ "Inkscape ([^ ]*)")
+ except ExecutableNotFoundError:
+ pass # Suppress exception chaining.
+ # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
+ # try without it:
+ return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
+ elif name == "magick":
+ if sys.platform == "win32":
+ # Check the registry to avoid confusing ImageMagick's convert with
+ # Windows's builtin convert.exe.
+ import winreg
+ binpath = ""
+ for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
+ try:
+ with winreg.OpenKeyEx(
+ winreg.HKEY_LOCAL_MACHINE,
+ r"Software\Imagemagick\Current",
+ 0, winreg.KEY_QUERY_VALUE | flag) as hkey:
+ binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
+ except OSError:
+ pass
+ path = None
+ if binpath:
+ for name in ["convert.exe", "magick.exe"]:
+ candidate = Path(binpath, name)
+ if candidate.exists():
+ path = str(candidate)
+ break
+ if path is None:
+ raise ExecutableNotFoundError(
+ "Failed to find an ImageMagick installation")
+ else:
+ path = "convert"
+ info = impl([path, "--version"], r"^Version: ImageMagick (\S*)")
+ if info.raw_version == "7.0.10-34":
+ # https://github.com/ImageMagick/ImageMagick/issues/2720
+ raise ExecutableNotFoundError(
+ f"You have ImageMagick {info.version}, which is unsupported")
+ return info
+ elif name == "pdftocairo":
+ return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")
+ elif name == "pdftops":
+ info = impl(["pdftops", "-v"], "^pdftops version (.*)",
+ ignore_exit_code=True)
+ if info and not (
+ 3 <= info.version.major or
+ # poppler version numbers.
+ parse_version("0.9") <= info.version < parse_version("1.0")):
+ raise ExecutableNotFoundError(
+ f"You have pdftops version {info.version} but the minimum "
+ f"version supported by Matplotlib is 3.0")
+ return info
+ else:
+ raise ValueError(f"Unknown executable: {name!r}")
+
+
+def _get_xdg_config_dir():
+ """
+ Return the XDG configuration directory, according to the XDG base
+ directory spec:
+
+ https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+ """
+ return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
+
+
+def _get_xdg_cache_dir():
+ """
+ Return the XDG cache directory, according to the XDG base directory spec:
+
+ https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+ """
+ return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
+
+
+def _get_config_or_cache_dir(xdg_base_getter):
+ configdir = os.environ.get('MPLCONFIGDIR')
+ if configdir:
+ configdir = Path(configdir)
+ elif sys.platform.startswith(('linux', 'freebsd')):
+ # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,
+ # as _xdg_base_getter can throw.
+ configdir = Path(xdg_base_getter(), "matplotlib")
+ else:
+ configdir = Path.home() / ".matplotlib"
+ # Resolve the path to handle potential issues with inaccessible symlinks.
+ configdir = configdir.resolve()
+ try:
+ configdir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ _log.warning("mkdir -p failed for path %s: %s", configdir, exc)
+ else:
+ if os.access(str(configdir), os.W_OK) and configdir.is_dir():
+ return str(configdir)
+ _log.warning("%s is not a writable directory", configdir)
+ # If the config or cache directory cannot be created or is not a writable
+ # directory, create a temporary one.
+ try:
+ tmpdir = tempfile.mkdtemp(prefix="matplotlib-")
+ except OSError as exc:
+ raise OSError(
+ f"Matplotlib requires access to a writable cache directory, but there "
+ f"was an issue with the default path ({configdir}), and a temporary "
+ f"directory could not be created; set the MPLCONFIGDIR environment "
+ f"variable to a writable directory") from exc
+ os.environ["MPLCONFIGDIR"] = tmpdir
+ atexit.register(shutil.rmtree, tmpdir)
+ _log.warning(
+ "Matplotlib created a temporary cache directory at %s because there was "
+ "an issue with the default path (%s); it is highly recommended to set the "
+ "MPLCONFIGDIR environment variable to a writable directory, in particular to "
+ "speed up the import of Matplotlib and to better support multiprocessing.",
+ tmpdir, configdir)
+ return tmpdir
+
+
+@_logged_cached('CONFIGDIR=%s')
+def get_configdir():
+ """
+ Return the string path of the configuration directory.
+
+ The directory is chosen as follows:
+
+ 1. If the MPLCONFIGDIR environment variable is supplied, choose that.
+ 2. On Linux, follow the XDG specification and look first in
+ ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other
+ platforms, choose ``$HOME/.matplotlib``.
+ 3. If the chosen directory exists and is writable, use that as the
+ configuration directory.
+ 4. Else, create a temporary directory, and use it as the configuration
+ directory.
+ """
+ return _get_config_or_cache_dir(_get_xdg_config_dir)
+
+
+@_logged_cached('CACHEDIR=%s')
+def get_cachedir():
+ """
+ Return the string path of the cache directory.
+
+ The procedure used to find the directory is the same as for
+ `get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.
+ """
+ return _get_config_or_cache_dir(_get_xdg_cache_dir)
+
+
+@_logged_cached('matplotlib data path: %s')
+def get_data_path():
+ """Return the path to Matplotlib data."""
+ return str(Path(__file__).with_name("mpl-data"))
+
+
+def matplotlib_fname():
+ """
+ Get the location of the config file.
+
+ The file location is determined in the following order
+
+ - ``$PWD/matplotlibrc``
+ - ``$MATPLOTLIBRC`` if it is not a directory
+ - ``$MATPLOTLIBRC/matplotlibrc``
+ - ``$MPLCONFIGDIR/matplotlibrc``
+ - On Linux,
+ - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
+ is defined)
+ - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
+ is not defined)
+ - On other platforms,
+ - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
+ - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
+ exist.
+ """
+
+ def gen_candidates():
+ # rely on down-stream code to make absolute. This protects us
+ # from having to directly get the current working directory
+ # which can fail if the user has ended up with a cwd that is
+ # non-existent.
+ yield 'matplotlibrc'
+ try:
+ matplotlibrc = os.environ['MATPLOTLIBRC']
+ except KeyError:
+ pass
+ else:
+ yield matplotlibrc
+ yield os.path.join(matplotlibrc, 'matplotlibrc')
+ yield os.path.join(get_configdir(), 'matplotlibrc')
+ yield os.path.join(get_data_path(), 'matplotlibrc')
+
+ for fname in gen_candidates():
+ if os.path.exists(fname) and not os.path.isdir(fname):
+ return fname
+
+ raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
+ "install is broken")
+
+
+# rcParams deprecated and automatically mapped to another key.
+# Values are tuples of (version, new_name, f_old2new, f_new2old).
+_deprecated_map = {}
+# rcParams deprecated; some can manually be mapped to another key.
+# Values are tuples of (version, new_name_or_None).
+_deprecated_ignore_map = {}
+# rcParams deprecated; can use None to suppress warnings; remain actually
+# listed in the rcParams.
+# Values are tuples of (version,)
+_deprecated_remain_as_none = {}
+
+
+@_docstring.Substitution(
+ "\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))
+)
+class RcParams(MutableMapping, dict):
+ """
+ A dict-like key-value store for config parameters, including validation.
+
+ Validating functions are defined and associated with rc parameters in
+ :mod:`matplotlib.rcsetup`.
+
+ The list of rcParams is:
+
+ %s
+
+ See Also
+ --------
+ :ref:`customizing-with-matplotlibrc-files`
+ """
+
+ validate = rcsetup._validators
+
+ # validate values on the way in
+ def __init__(self, *args, **kwargs):
+ self.update(*args, **kwargs)
+
+ def _set(self, key, val):
+ """
+ Directly write data bypassing deprecation and validation logic.
+
+ Notes
+ -----
+ As end user or downstream library you almost always should use
+ ``rcParams[key] = val`` and not ``_set()``.
+
+ There are only very few special cases that need direct data access.
+ These cases previously used ``dict.__setitem__(rcParams, key, val)``,
+ which is now deprecated and replaced by ``rcParams._set(key, val)``.
+
+ Even though private, we guarantee API stability for ``rcParams._set``,
+ i.e. it is subject to Matplotlib's API and deprecation policy.
+
+ :meta public:
+ """
+ dict.__setitem__(self, key, val)
+
+ def _get(self, key):
+ """
+ Directly read data bypassing deprecation, backend and validation
+ logic.
+
+ Notes
+ -----
+ As end user or downstream library you almost always should use
+ ``val = rcParams[key]`` and not ``_get()``.
+
+ There are only very few special cases that need direct data access.
+ These cases previously used ``dict.__getitem__(rcParams, key, val)``,
+ which is now deprecated and replaced by ``rcParams._get(key)``.
+
+ Even though private, we guarantee API stability for ``rcParams._get``,
+ i.e. it is subject to Matplotlib's API and deprecation policy.
+
+ :meta public:
+ """
+ return dict.__getitem__(self, key)
+
+ def _update_raw(self, other_params):
+ """
+ Directly update the data from *other_params*, bypassing deprecation,
+ backend and validation logic on both sides.
+
+ This ``rcParams._update_raw(params)`` replaces the previous pattern
+ ``dict.update(rcParams, params)``.
+
+ Parameters
+ ----------
+ other_params : dict or `.RcParams`
+ The input mapping from which to update.
+ """
+ if isinstance(other_params, RcParams):
+ other_params = dict.items(other_params)
+ dict.update(self, other_params)
+
+ def _ensure_has_backend(self):
+ """
+ Ensure that a "backend" entry exists.
+
+ Normally, the default matplotlibrc file contains *no* entry for "backend" (the
+ corresponding line starts with ##, not #; we fill in _auto_backend_sentinel
+ in that case. However, packagers can set a different default backend
+ (resulting in a normal `#backend: foo` line) in which case we should *not*
+ fill in _auto_backend_sentinel.
+ """
+ dict.setdefault(self, "backend", rcsetup._auto_backend_sentinel)
+
+ def __setitem__(self, key, val):
+ try:
+ if key in _deprecated_map:
+ version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ key = alt_key
+ val = alt_val(val)
+ elif key in _deprecated_remain_as_none and val is not None:
+ version, = _deprecated_remain_as_none[key]
+ _api.warn_deprecated(version, name=key, obj_type="rcparam")
+ elif key in _deprecated_ignore_map:
+ version, alt_key = _deprecated_ignore_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ return
+ elif key == 'backend':
+ if val is rcsetup._auto_backend_sentinel:
+ if 'backend' in self:
+ return
+ try:
+ cval = self.validate[key](val)
+ except ValueError as ve:
+ raise ValueError(f"Key {key}: {ve}") from None
+ self._set(key, cval)
+ except KeyError as err:
+ raise KeyError(
+ f"{key} is not a valid rc parameter (see rcParams.keys() for "
+ f"a list of valid parameters)") from err
+
+ def __getitem__(self, key):
+ if key in _deprecated_map:
+ version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ return inverse_alt(self._get(alt_key))
+
+ elif key in _deprecated_ignore_map:
+ version, alt_key = _deprecated_ignore_map[key]
+ _api.warn_deprecated(
+ version, name=key, obj_type="rcparam", alternative=alt_key)
+ return self._get(alt_key) if alt_key else None
+
+ # In theory, this should only ever be used after the global rcParams
+ # has been set up, but better be safe e.g. in presence of breakpoints.
+ elif key == "backend" and self is globals().get("rcParams"):
+ val = self._get(key)
+ if val is rcsetup._auto_backend_sentinel:
+ from matplotlib import pyplot as plt
+ plt.switch_backend(rcsetup._auto_backend_sentinel)
+
+ return self._get(key)
+
+ def _get_backend_or_none(self):
+ """Get the requested backend, if any, without triggering resolution."""
+ backend = self._get("backend")
+ return None if backend is rcsetup._auto_backend_sentinel else backend
+
+ def __repr__(self):
+ class_name = self.__class__.__name__
+ indent = len(class_name) + 1
+ with _api.suppress_matplotlib_deprecation_warning():
+ repr_split = pprint.pformat(dict(self), indent=1,
+ width=80 - indent).split('\n')
+ repr_indented = ('\n' + ' ' * indent).join(repr_split)
+ return f'{class_name}({repr_indented})'
+
+ def __str__(self):
+ return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
+
+ def __iter__(self):
+ """Yield sorted list of keys."""
+ with _api.suppress_matplotlib_deprecation_warning():
+ yield from sorted(dict.__iter__(self))
+
+ def __len__(self):
+ return dict.__len__(self)
+
+ def find_all(self, pattern):
+ """
+ Return the subset of this RcParams dictionary whose keys match,
+ using :func:`re.search`, the given ``pattern``.
+
+ .. note::
+
+ Changes to the returned dictionary are *not* propagated to
+ the parent RcParams dictionary.
+
+ """
+ pattern_re = re.compile(pattern)
+ return RcParams((key, value)
+ for key, value in self.items()
+ if pattern_re.search(key))
+
+ def copy(self):
+ """Copy this RcParams instance."""
+ rccopy = RcParams()
+ for k in self: # Skip deprecations and revalidation.
+ rccopy._set(k, self._get(k))
+ return rccopy
+
+
+def rc_params(fail_on_error=False):
+ """Construct a `RcParams` instance from the default Matplotlib rc file."""
+ return rc_params_from_file(matplotlib_fname(), fail_on_error)
+
+
+@functools.cache
+def _get_ssl_context():
+ try:
+ import certifi
+ except ImportError:
+ _log.debug("Could not import certifi.")
+ return None
+ import ssl
+ return ssl.create_default_context(cafile=certifi.where())
+
+
+@contextlib.contextmanager
+def _open_file_or_url(fname):
+ if (isinstance(fname, str)
+ and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):
+ import urllib.request
+ ssl_ctx = _get_ssl_context()
+ if ssl_ctx is None:
+ _log.debug(
+ "Could not get certifi ssl context, https may not work."
+ )
+ with urllib.request.urlopen(fname, context=ssl_ctx) as f:
+ yield (line.decode('utf-8') for line in f)
+ else:
+ fname = os.path.expanduser(fname)
+ with open(fname, encoding='utf-8') as f:
+ yield f
+
+
+def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
+ """
+ Construct a `RcParams` instance from file *fname*.
+
+ Unlike `rc_params_from_file`, the configuration class only contains the
+ parameters specified in the file (i.e. default values are not filled in).
+
+ Parameters
+ ----------
+ fname : path-like
+ The loaded file.
+ transform : callable, default: the identity function
+ A function called on each individual line of the file to transform it,
+ before further parsing.
+ fail_on_error : bool, default: False
+ Whether invalid entries should result in an exception or a warning.
+ """
+ import matplotlib as mpl
+ rc_temp = {}
+ with _open_file_or_url(fname) as fd:
+ try:
+ for line_no, line in enumerate(fd, 1):
+ line = transform(line)
+ strippedline = cbook._strip_comment(line)
+ if not strippedline:
+ continue
+ tup = strippedline.split(':', 1)
+ if len(tup) != 2:
+ _log.warning('Missing colon in file %r, line %d (%r)',
+ fname, line_no, line.rstrip('\n'))
+ continue
+ key, val = tup
+ key = key.strip()
+ val = val.strip()
+ if val.startswith('"') and val.endswith('"'):
+ val = val[1:-1] # strip double quotes
+ if key in rc_temp:
+ _log.warning('Duplicate key in file %r, line %d (%r)',
+ fname, line_no, line.rstrip('\n'))
+ rc_temp[key] = (val, line, line_no)
+ except UnicodeDecodeError:
+ _log.warning('Cannot decode configuration file %r as utf-8.',
+ fname)
+ raise
+
+ config = RcParams()
+
+ for key, (val, line, line_no) in rc_temp.items():
+ if key in rcsetup._validators:
+ if fail_on_error:
+ config[key] = val # try to convert to proper type or raise
+ else:
+ try:
+ config[key] = val # try to convert to proper type or skip
+ except Exception as msg:
+ _log.warning('Bad value in file %r, line %d (%r): %s',
+ fname, line_no, line.rstrip('\n'), msg)
+ elif key in _deprecated_ignore_map:
+ version, alt_key = _deprecated_ignore_map[key]
+ _api.warn_deprecated(
+ version, name=key, alternative=alt_key, obj_type='rcparam',
+ addendum="Please update your matplotlibrc.")
+ else:
+ # __version__ must be looked up as an attribute to trigger the
+ # module-level __getattr__.
+ version = ('main' if '.post' in mpl.__version__
+ else f'v{mpl.__version__}')
+ _log.warning("""
+Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
+You probably need to get an updated matplotlibrc file from
+https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc
+or from the matplotlib source distribution""",
+ dict(key=key, fname=fname, line_no=line_no,
+ line=line.rstrip('\n'), version=version))
+ return config
+
+
+def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
+ """
+ Construct a `RcParams` from file *fname*.
+
+ Parameters
+ ----------
+ fname : str or path-like
+ A file with Matplotlib rc settings.
+ fail_on_error : bool
+ If True, raise an error when the parser fails to convert a parameter.
+ use_default_template : bool
+ If True, initialize with default parameters before updating with those
+ in the given file. If False, the configuration class only contains the
+ parameters specified in the file. (Useful for updating dicts.)
+ """
+ config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
+
+ if not use_default_template:
+ return config_from_file
+
+ with _api.suppress_matplotlib_deprecation_warning():
+ config = RcParams({**rcParamsDefault, **config_from_file})
+
+ if "".join(config['text.latex.preamble']):
+ _log.info("""
+*****************************************************************
+You have the following UNSUPPORTED LaTeX preamble customizations:
+%s
+Please do not ask for support with these customizations active.
+*****************************************************************
+""", '\n'.join(config['text.latex.preamble']))
+ _log.debug('loaded rc file %s', fname)
+
+ return config
+
+
+rcParamsDefault = _rc_params_in_file(
+ cbook._get_data_path("matplotlibrc"),
+ # Strip leading comment.
+ transform=lambda line: line[1:] if line.startswith("#") else line,
+ fail_on_error=True)
+rcParamsDefault._update_raw(rcsetup._hardcoded_defaults)
+rcParamsDefault._ensure_has_backend()
+
+rcParams = RcParams() # The global instance.
+rcParams._update_raw(rcParamsDefault)
+rcParams._update_raw(_rc_params_in_file(matplotlib_fname()))
+rcParamsOrig = rcParams.copy()
+with _api.suppress_matplotlib_deprecation_warning():
+ # This also checks that all rcParams are indeed listed in the template.
+ # Assigning to rcsetup.defaultParams is left only for backcompat.
+ defaultParams = rcsetup.defaultParams = {
+ # We want to resolve deprecated rcParams, but not backend...
+ key: [(rcsetup._auto_backend_sentinel if key == "backend" else
+ rcParamsDefault[key]),
+ validator]
+ for key, validator in rcsetup._validators.items()}
+if rcParams['axes.formatter.use_locale']:
+ locale.setlocale(locale.LC_ALL, '')
+
+
+def rc(group, **kwargs):
+ """
+ Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
+ for ``lines.linewidth`` the group is ``lines``, for
+ ``axes.facecolor``, the group is ``axes``, and so on. Group may
+ also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
+ *kwargs* is a dictionary attribute name/value pairs, e.g.,::
+
+ rc('lines', linewidth=2, color='r')
+
+ sets the current `.rcParams` and is equivalent to::
+
+ rcParams['lines.linewidth'] = 2
+ rcParams['lines.color'] = 'r'
+
+ The following aliases are available to save typing for interactive users:
+
+ ===== =================
+ Alias Property
+ ===== =================
+ 'lw' 'linewidth'
+ 'ls' 'linestyle'
+ 'c' 'color'
+ 'fc' 'facecolor'
+ 'ec' 'edgecolor'
+ 'mew' 'markeredgewidth'
+ 'aa' 'antialiased'
+ ===== =================
+
+ Thus you could abbreviate the above call as::
+
+ rc('lines', lw=2, c='r')
+
+ Note you can use python's kwargs dictionary facility to store
+ dictionaries of default parameters. e.g., you can customize the
+ font rc as follows::
+
+ font = {'family' : 'monospace',
+ 'weight' : 'bold',
+ 'size' : 'larger'}
+ rc('font', **font) # pass in the font dict as kwargs
+
+ This enables you to easily switch between several configurations. Use
+ ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
+ restore the default `.rcParams` after changes.
+
+ Notes
+ -----
+ Similar functionality is available by using the normal dict interface, i.e.
+ ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
+ does not support abbreviations or grouping).
+ """
+
+ aliases = {
+ 'lw': 'linewidth',
+ 'ls': 'linestyle',
+ 'c': 'color',
+ 'fc': 'facecolor',
+ 'ec': 'edgecolor',
+ 'mew': 'markeredgewidth',
+ 'aa': 'antialiased',
+ }
+
+ if isinstance(group, str):
+ group = (group,)
+ for g in group:
+ for k, v in kwargs.items():
+ name = aliases.get(k) or k
+ key = f'{g}.{name}'
+ try:
+ rcParams[key] = v
+ except KeyError as err:
+ raise KeyError(('Unrecognized key "%s" for group "%s" and '
+ 'name "%s"') % (key, g, name)) from err
+
+
+def rcdefaults():
+ """
+ Restore the `.rcParams` from Matplotlib's internal default style.
+
+ Style-blacklisted `.rcParams` (defined in
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
+
+ See Also
+ --------
+ matplotlib.rc_file_defaults
+ Restore the `.rcParams` from the rc file originally loaded by
+ Matplotlib.
+ matplotlib.style.use
+ Use a specific style file. Call ``style.use('default')`` to restore
+ the default style.
+ """
+ # Deprecation warnings were already handled when creating rcParamsDefault,
+ # no need to reemit them here.
+ with _api.suppress_matplotlib_deprecation_warning():
+ from .style.core import STYLE_BLACKLIST
+ rcParams.clear()
+ rcParams.update({k: v for k, v in rcParamsDefault.items()
+ if k not in STYLE_BLACKLIST})
+
+
+def rc_file_defaults():
+ """
+ Restore the `.rcParams` from the original rc file loaded by Matplotlib.
+
+ Style-blacklisted `.rcParams` (defined in
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
+ """
+ # Deprecation warnings were already handled when creating rcParamsOrig, no
+ # need to reemit them here.
+ with _api.suppress_matplotlib_deprecation_warning():
+ from .style.core import STYLE_BLACKLIST
+ rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
+ if k not in STYLE_BLACKLIST})
+
+
+def rc_file(fname, *, use_default_template=True):
+ """
+ Update `.rcParams` from file.
+
+ Style-blacklisted `.rcParams` (defined in
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
+
+ Parameters
+ ----------
+ fname : str or path-like
+ A file with Matplotlib rc settings.
+
+ use_default_template : bool
+ If True, initialize with default parameters before updating with those
+ in the given file. If False, the current configuration persists
+ and only the parameters specified in the file are updated.
+ """
+ # Deprecation warnings were already handled in rc_params_from_file, no need
+ # to reemit them here.
+ with _api.suppress_matplotlib_deprecation_warning():
+ from .style.core import STYLE_BLACKLIST
+ rc_from_file = rc_params_from_file(
+ fname, use_default_template=use_default_template)
+ rcParams.update({k: rc_from_file[k] for k in rc_from_file
+ if k not in STYLE_BLACKLIST})
+
+
+@contextlib.contextmanager
+def rc_context(rc=None, fname=None):
+ """
+ Return a context manager for temporarily changing rcParams.
+
+ The :rc:`backend` will not be reset by the context manager.
+
+ rcParams changed both through the context manager invocation and
+ in the body of the context will be reset on context exit.
+
+ Parameters
+ ----------
+ rc : dict
+ The rcParams to temporarily set.
+ fname : str or path-like
+ A file with Matplotlib rc settings. If both *fname* and *rc* are given,
+ settings from *rc* take precedence.
+
+ See Also
+ --------
+ :ref:`customizing-with-matplotlibrc-files`
+
+ Examples
+ --------
+ Passing explicit values via a dict::
+
+ with mpl.rc_context({'interactive': False}):
+ fig, ax = plt.subplots()
+ ax.plot(range(3), range(3))
+ fig.savefig('example.png')
+ plt.close(fig)
+
+ Loading settings from a file::
+
+ with mpl.rc_context(fname='print.rc'):
+ plt.plot(x, y) # uses 'print.rc'
+
+ Setting in the context body::
+
+ with mpl.rc_context():
+ # will be reset
+ mpl.rcParams['lines.linewidth'] = 5
+ plt.plot(x, y)
+
+ """
+ orig = dict(rcParams.copy())
+ del orig['backend']
+ try:
+ if fname:
+ rc_file(fname)
+ if rc:
+ rcParams.update(rc)
+ yield
+ finally:
+ rcParams._update_raw(orig) # Revert to the original rcs.
+
+
+def use(backend, *, force=True):
+ """
+ Select the backend used for rendering and GUI integration.
+
+ If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used
+ and if the new backend is different than the current backend, all Figures
+ will be closed.
+
+ Parameters
+ ----------
+ backend : str
+ The backend to switch to. This can either be one of the standard
+ backend names, which are case-insensitive:
+
+ - interactive backends:
+ GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg,
+ QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo
+
+ - non-interactive backends:
+ agg, cairo, pdf, pgf, ps, svg, template
+
+ or a string of the form: ``module://my.module.name``.
+
+ notebook is a synonym for nbAgg.
+
+ Switching to an interactive backend is not possible if an unrelated
+ event loop has already been started (e.g., switching to GTK3Agg if a
+ TkAgg window has already been opened). Switching to a non-interactive
+ backend is always possible.
+
+ force : bool, default: True
+ If True (the default), raise an `ImportError` if the backend cannot be
+ set up (either because it fails to import, or because an incompatible
+ GUI interactive framework is already running); if False, silently
+ ignore the failure.
+
+ See Also
+ --------
+ :ref:`backends`
+ matplotlib.get_backend
+ matplotlib.pyplot.switch_backend
+
+ """
+ name = rcsetup.validate_backend(backend)
+ # don't (prematurely) resolve the "auto" backend setting
+ if rcParams._get_backend_or_none() == name:
+ # Nothing to do if the requested backend is already set
+ pass
+ else:
+ # if pyplot is not already imported, do not import it. Doing
+ # so may trigger a `plt.switch_backend` to the _default_ backend
+ # before we get a chance to change to the one the user just requested
+ plt = sys.modules.get('matplotlib.pyplot')
+ # if pyplot is imported, then try to change backends
+ if plt is not None:
+ try:
+ # we need this import check here to re-raise if the
+ # user does not have the libraries to support their
+ # chosen backend installed.
+ plt.switch_backend(name)
+ except ImportError:
+ if force:
+ raise
+ # if we have not imported pyplot, then we can set the rcParam
+ # value which will be respected when the user finally imports
+ # pyplot
+ else:
+ rcParams['backend'] = backend
+ # if the user has asked for a given backend, do not helpfully
+ # fallback
+ rcParams['backend_fallback'] = False
+
+
+if os.environ.get('MPLBACKEND'):
+ rcParams['backend'] = os.environ.get('MPLBACKEND')
+
+
+def get_backend(*, auto_select=True):
+ """
+ Return the name of the current backend.
+
+ Parameters
+ ----------
+ auto_select : bool, default: True
+ Whether to trigger backend resolution if no backend has been
+ selected so far. If True, this ensures that a valid backend
+ is returned. If False, this returns None if no backend has been
+ selected so far.
+
+ .. versionadded:: 3.10
+
+ .. admonition:: Provisional
+
+ The *auto_select* flag is provisional. It may be changed or removed
+ without prior warning.
+
+ See Also
+ --------
+ matplotlib.use
+ """
+ if auto_select:
+ return rcParams['backend']
+ else:
+ backend = rcParams._get('backend')
+ if backend is rcsetup._auto_backend_sentinel:
+ return None
+ else:
+ return backend
+
+
+def interactive(b):
+ """
+ Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).
+ """
+ rcParams['interactive'] = b
+
+
+def is_interactive():
+ """
+ Return whether to redraw after every plotting command.
+
+ .. note::
+
+ This function is only intended for use in backends. End users should
+ use `.pyplot.isinteractive` instead.
+ """
+ return rcParams['interactive']
+
+
+def _val_or_rc(val, rc_name):
+ """
+ If *val* is None, return ``mpl.rcParams[rc_name]``, otherwise return val.
+ """
+ return val if val is not None else rcParams[rc_name]
+
+
+def _init_tests():
+ # The version of FreeType to install locally for running the tests. This must match
+ # the value in `meson.build`.
+ LOCAL_FREETYPE_VERSION = '2.6.1'
+
+ from matplotlib import ft2font
+ if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
+ ft2font.__freetype_build_type__ != 'local'):
+ _log.warning(
+ "Matplotlib is not built with the correct FreeType version to run tests. "
+ "Rebuild without setting system-freetype=true in Meson setup options. "
+ "Expect many image comparison failures below. "
+ "Expected freetype version %s. "
+ "Found freetype version %s. "
+ "Freetype build type is %slocal.",
+ LOCAL_FREETYPE_VERSION,
+ ft2font.__freetype_version__,
+ "" if ft2font.__freetype_build_type__ == 'local' else "not ")
+
+
+def _replacer(data, value):
+ """
+ Either returns ``data[value]`` or passes ``data`` back, converts either to
+ a sequence.
+ """
+ try:
+ # if key isn't a string don't bother
+ if isinstance(value, str):
+ # try to use __getitem__
+ value = data[value]
+ except Exception:
+ # key does not exist, silently fall back to key
+ pass
+ return cbook.sanitize_sequence(value)
+
+
+def _label_from_arg(y, default_name):
+ try:
+ return y.name
+ except AttributeError:
+ if isinstance(default_name, str):
+ return default_name
+ return None
+
+
+def _add_data_doc(docstring, replace_names):
+ """
+ Add documentation for a *data* field to the given docstring.
+
+ Parameters
+ ----------
+ docstring : str
+ The input docstring.
+ replace_names : list of str or None
+ The list of parameter names which arguments should be replaced by
+ ``data[name]`` (if ``data[name]`` does not throw an exception). If
+ None, replacement is attempted for all arguments.
+
+ Returns
+ -------
+ str
+ The augmented docstring.
+ """
+ if (docstring is None
+ or replace_names is not None and len(replace_names) == 0):
+ return docstring
+ docstring = inspect.cleandoc(docstring)
+
+ data_doc = ("""\
+ If given, all parameters also accept a string ``s``, which is
+ interpreted as ``data[s]`` if ``s`` is a key in ``data``."""
+ if replace_names is None else f"""\
+ If given, the following parameters also accept a string ``s``, which is
+ interpreted as ``data[s]`` if ``s`` is a key in ``data``:
+
+ {', '.join(map('*{}*'.format, replace_names))}""")
+ # using string replacement instead of formatting has the advantages
+ # 1) simpler indent handling
+ # 2) prevent problems with formatting characters '{', '%' in the docstring
+ if _log.level <= logging.DEBUG:
+ # test_data_parameter_replacement() tests against these log messages
+ # make sure to keep message and test in sync
+ if "data : indexable object, optional" not in docstring:
+ _log.debug("data parameter docstring error: no data parameter")
+ if 'DATA_PARAMETER_PLACEHOLDER' not in docstring:
+ _log.debug("data parameter docstring error: missing placeholder")
+ return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc)
+
+
+def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
+ """
+ A decorator to add a 'data' kwarg to a function.
+
+ When applied::
+
+ @_preprocess_data()
+ def func(ax, *args, **kwargs): ...
+
+ the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``
+ with the following behavior:
+
+ - if called with ``data=None``, forward the other arguments to ``func``;
+ - otherwise, *data* must be a mapping; for any argument passed in as a
+ string ``name``, replace the argument by ``data[name]`` (if this does not
+ throw an exception), then forward the arguments to ``func``.
+
+ In either case, any argument that is a `MappingView` is also converted to a
+ list.
+
+ Parameters
+ ----------
+ replace_names : list of str or None, default: None
+ The list of parameter names for which lookup into *data* should be
+ attempted. If None, replacement is attempted for all arguments.
+ label_namer : str, default: None
+ If set e.g. to "namer" (which must be a kwarg in the function's
+ signature -- not as ``**kwargs``), if the *namer* argument passed in is
+ a (string) key of *data* and no *label* kwarg is passed, then use the
+ (string) value of the *namer* as *label*. ::
+
+ @_preprocess_data(label_namer="foo")
+ def func(foo, label=None): ...
+
+ func("key", data={"key": value})
+ # is equivalent to
+ func.__wrapped__(value, label="key")
+ """
+
+ if func is None: # Return the actual decorator.
+ return functools.partial(
+ _preprocess_data,
+ replace_names=replace_names, label_namer=label_namer)
+
+ sig = inspect.signature(func)
+ varargs_name = None
+ varkwargs_name = None
+ arg_names = []
+ params = list(sig.parameters.values())
+ for p in params:
+ if p.kind is Parameter.VAR_POSITIONAL:
+ varargs_name = p.name
+ elif p.kind is Parameter.VAR_KEYWORD:
+ varkwargs_name = p.name
+ else:
+ arg_names.append(p.name)
+ data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
+ if varkwargs_name:
+ params.insert(-1, data_param)
+ else:
+ params.append(data_param)
+ new_sig = sig.replace(parameters=params)
+ arg_names = arg_names[1:] # remove the first "ax" / self arg
+
+ assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
+ "Matplotlib internal error: invalid replace_names "
+ f"({replace_names!r}) for {func.__name__!r}")
+ assert label_namer is None or label_namer in arg_names, (
+ "Matplotlib internal error: invalid label_namer "
+ f"({label_namer!r}) for {func.__name__!r}")
+
+ @functools.wraps(func)
+ def inner(ax, *args, data=None, **kwargs):
+ if data is None:
+ return func(
+ ax,
+ *map(cbook.sanitize_sequence, args),
+ **{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
+
+ bound = new_sig.bind(ax, *args, **kwargs)
+ auto_label = (bound.arguments.get(label_namer)
+ or bound.kwargs.get(label_namer))
+
+ for k, v in bound.arguments.items():
+ if k == varkwargs_name:
+ for k1, v1 in v.items():
+ if replace_names is None or k1 in replace_names:
+ v[k1] = _replacer(data, v1)
+ elif k == varargs_name:
+ if replace_names is None:
+ bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
+ else:
+ if replace_names is None or k in replace_names:
+ bound.arguments[k] = _replacer(data, v)
+
+ new_args = bound.args
+ new_kwargs = bound.kwargs
+
+ args_and_kwargs = {**bound.arguments, **bound.kwargs}
+ if label_namer and "label" not in args_and_kwargs:
+ new_kwargs["label"] = _label_from_arg(
+ args_and_kwargs.get(label_namer), auto_label)
+
+ return func(*new_args, **new_kwargs)
+
+ inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
+ inner.__signature__ = new_sig
+ return inner
+
+
+_log.debug('interactive is %s', is_interactive())
+_log.debug('platform is %s', sys.platform)
+
+
+@_api.deprecated("3.10", alternative="matplotlib.cbook.sanitize_sequence")
+def sanitize_sequence(data):
+ return cbook.sanitize_sequence(data)
+
+
+@_api.deprecated("3.10", alternative="matplotlib.rcsetup.validate_backend")
+def validate_backend(s):
+ return rcsetup.validate_backend(s)
+
+
+# workaround: we must defer colormaps import to after loading rcParams, because
+# colormap creation depends on rcParams
+from matplotlib.cm import _colormaps as colormaps # noqa: E402
+from matplotlib.cm import _multivar_colormaps as multivar_colormaps # noqa: E402
+from matplotlib.cm import _bivar_colormaps as bivar_colormaps # noqa: E402
+from matplotlib.colors import _color_sequences as color_sequences # noqa: E402
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_afm.py b/llava_video/lib/python3.10/site-packages/matplotlib/_afm.py
new file mode 100644
index 0000000000000000000000000000000000000000..558efe16392f7d386f642c86a8b028d10a778f25
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_afm.py
@@ -0,0 +1,532 @@
+"""
+A python interface to Adobe Font Metrics Files.
+
+Although a number of other Python implementations exist, and may be more
+complete than this, it was decided not to go with them because they were
+either:
+
+1) copyrighted or used a non-BSD compatible license
+2) had too many dependencies and a free standing lib was needed
+3) did more than needed and it was easier to write afresh rather than
+ figure out how to get just what was needed.
+
+It is pretty easy to use, and has no external dependencies:
+
+>>> import matplotlib as mpl
+>>> from pathlib import Path
+>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm')
+>>>
+>>> from matplotlib.afm import AFM
+>>> with afm_path.open('rb') as fh:
+... afm = AFM(fh)
+>>> afm.string_width_height('What the heck?')
+(6220.0, 694)
+>>> afm.get_fontname()
+'Times-Roman'
+>>> afm.get_kern_dist('A', 'f')
+0
+>>> afm.get_kern_dist('A', 'y')
+-92.0
+>>> afm.get_bbox_char('!')
+[130, -9, 238, 676]
+
+As in the Adobe Font Metrics File Format Specification, all dimensions
+are given in units of 1/1000 of the scale factor (point size) of the font
+being used.
+"""
+
+from collections import namedtuple
+import logging
+import re
+
+from ._mathtext_data import uni2type1
+
+
+_log = logging.getLogger(__name__)
+
+
+def _to_int(x):
+ # Some AFM files have floats where we are expecting ints -- there is
+ # probably a better way to handle this (support floats, round rather than
+ # truncate). But I don't know what the best approach is now and this
+ # change to _to_int should at least prevent Matplotlib from crashing on
+ # these. JDH (2009-11-06)
+ return int(float(x))
+
+
+def _to_float(x):
+ # Some AFM files use "," instead of "." as decimal separator -- this
+ # shouldn't be ambiguous (unless someone is wicked enough to use "," as
+ # thousands separator...).
+ if isinstance(x, bytes):
+ # Encoding doesn't really matter -- if we have codepoints >127 the call
+ # to float() will error anyways.
+ x = x.decode('latin-1')
+ return float(x.replace(',', '.'))
+
+
+def _to_str(x):
+ return x.decode('utf8')
+
+
+def _to_list_of_ints(s):
+ s = s.replace(b',', b' ')
+ return [_to_int(val) for val in s.split()]
+
+
+def _to_list_of_floats(s):
+ return [_to_float(val) for val in s.split()]
+
+
+def _to_bool(s):
+ if s.lower().strip() in (b'false', b'0', b'no'):
+ return False
+ else:
+ return True
+
+
+def _parse_header(fh):
+ """
+ Read the font metrics header (up to the char metrics) and returns
+ a dictionary mapping *key* to *val*. *val* will be converted to the
+ appropriate python type as necessary; e.g.:
+
+ * 'False'->False
+ * '0'->0
+ * '-168 -218 1000 898'-> [-168, -218, 1000, 898]
+
+ Dictionary keys are
+
+ StartFontMetrics, FontName, FullName, FamilyName, Weight,
+ ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
+ UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
+ XHeight, Ascender, Descender, StartCharMetrics
+ """
+ header_converters = {
+ b'StartFontMetrics': _to_float,
+ b'FontName': _to_str,
+ b'FullName': _to_str,
+ b'FamilyName': _to_str,
+ b'Weight': _to_str,
+ b'ItalicAngle': _to_float,
+ b'IsFixedPitch': _to_bool,
+ b'FontBBox': _to_list_of_ints,
+ b'UnderlinePosition': _to_float,
+ b'UnderlineThickness': _to_float,
+ b'Version': _to_str,
+ # Some AFM files have non-ASCII characters (which are not allowed by
+ # the spec). Given that there is actually no public API to even access
+ # this field, just return it as straight bytes.
+ b'Notice': lambda x: x,
+ b'EncodingScheme': _to_str,
+ b'CapHeight': _to_float, # Is the second version a mistake, or
+ b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS
+ b'XHeight': _to_float,
+ b'Ascender': _to_float,
+ b'Descender': _to_float,
+ b'StdHW': _to_float,
+ b'StdVW': _to_float,
+ b'StartCharMetrics': _to_int,
+ b'CharacterSet': _to_str,
+ b'Characters': _to_int,
+ }
+ d = {}
+ first_line = True
+ for line in fh:
+ line = line.rstrip()
+ if line.startswith(b'Comment'):
+ continue
+ lst = line.split(b' ', 1)
+ key = lst[0]
+ if first_line:
+ # AFM spec, Section 4: The StartFontMetrics keyword
+ # [followed by a version number] must be the first line in
+ # the file, and the EndFontMetrics keyword must be the
+ # last non-empty line in the file. We just check the
+ # first header entry.
+ if key != b'StartFontMetrics':
+ raise RuntimeError('Not an AFM file')
+ first_line = False
+ if len(lst) == 2:
+ val = lst[1]
+ else:
+ val = b''
+ try:
+ converter = header_converters[key]
+ except KeyError:
+ _log.error("Found an unknown keyword in AFM header (was %r)", key)
+ continue
+ try:
+ d[key] = converter(val)
+ except ValueError:
+ _log.error('Value error parsing header in AFM: %s, %s', key, val)
+ continue
+ if key == b'StartCharMetrics':
+ break
+ else:
+ raise RuntimeError('Bad parse')
+ return d
+
+
+CharMetrics = namedtuple('CharMetrics', 'width, name, bbox')
+CharMetrics.__doc__ = """
+ Represents the character metrics of a single character.
+
+ Notes
+ -----
+ The fields do currently only describe a subset of character metrics
+ information defined in the AFM standard.
+ """
+CharMetrics.width.__doc__ = """The character width (WX)."""
+CharMetrics.name.__doc__ = """The character name (N)."""
+CharMetrics.bbox.__doc__ = """
+ The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*)."""
+
+
+def _parse_char_metrics(fh):
+ """
+ Parse the given filehandle for character metrics information and return
+ the information as dicts.
+
+ It is assumed that the file cursor is on the line behind
+ 'StartCharMetrics'.
+
+ Returns
+ -------
+ ascii_d : dict
+ A mapping "ASCII num of the character" to `.CharMetrics`.
+ name_d : dict
+ A mapping "character name" to `.CharMetrics`.
+
+ Notes
+ -----
+ This function is incomplete per the standard, but thus far parses
+ all the sample afm files tried.
+ """
+ required_keys = {'C', 'WX', 'N', 'B'}
+
+ ascii_d = {}
+ name_d = {}
+ for line in fh:
+ # We are defensively letting values be utf8. The spec requires
+ # ascii, but there are non-compliant fonts in circulation
+ line = _to_str(line.rstrip()) # Convert from byte-literal
+ if line.startswith('EndCharMetrics'):
+ return ascii_d, name_d
+ # Split the metric line into a dictionary, keyed by metric identifiers
+ vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s)
+ # There may be other metrics present, but only these are needed
+ if not required_keys.issubset(vals):
+ raise RuntimeError('Bad char metrics line: %s' % line)
+ num = _to_int(vals['C'])
+ wx = _to_float(vals['WX'])
+ name = vals['N']
+ bbox = _to_list_of_floats(vals['B'])
+ bbox = list(map(int, bbox))
+ metrics = CharMetrics(wx, name, bbox)
+ # Workaround: If the character name is 'Euro', give it the
+ # corresponding character code, according to WinAnsiEncoding (see PDF
+ # Reference).
+ if name == 'Euro':
+ num = 128
+ elif name == 'minus':
+ num = ord("\N{MINUS SIGN}") # 0x2212
+ if num != -1:
+ ascii_d[num] = metrics
+ name_d[name] = metrics
+ raise RuntimeError('Bad parse')
+
+
+def _parse_kern_pairs(fh):
+ """
+ Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
+ values are the kern pair value. For example, a kern pairs line like
+ ``KPX A y -50``
+
+ will be represented as::
+
+ d[ ('A', 'y') ] = -50
+
+ """
+
+ line = next(fh)
+ if not line.startswith(b'StartKernPairs'):
+ raise RuntimeError('Bad start of kern pairs data: %s' % line)
+
+ d = {}
+ for line in fh:
+ line = line.rstrip()
+ if not line:
+ continue
+ if line.startswith(b'EndKernPairs'):
+ next(fh) # EndKernData
+ return d
+ vals = line.split()
+ if len(vals) != 4 or vals[0] != b'KPX':
+ raise RuntimeError('Bad kern pairs line: %s' % line)
+ c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3])
+ d[(c1, c2)] = val
+ raise RuntimeError('Bad kern pairs parse')
+
+
+CompositePart = namedtuple('CompositePart', 'name, dx, dy')
+CompositePart.__doc__ = """
+ Represents the information on a composite element of a composite char."""
+CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'."""
+CompositePart.dx.__doc__ = """x-displacement of the part from the origin."""
+CompositePart.dy.__doc__ = """y-displacement of the part from the origin."""
+
+
+def _parse_composites(fh):
+ """
+ Parse the given filehandle for composites information return them as a
+ dict.
+
+ It is assumed that the file cursor is on the line behind 'StartComposites'.
+
+ Returns
+ -------
+ dict
+ A dict mapping composite character names to a parts list. The parts
+ list is a list of `.CompositePart` entries describing the parts of
+ the composite.
+
+ Examples
+ --------
+ A composite definition line::
+
+ CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
+
+ will be represented as::
+
+ composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
+ CompositePart(name='acute', dx=160, dy=170)]
+
+ """
+ composites = {}
+ for line in fh:
+ line = line.rstrip()
+ if not line:
+ continue
+ if line.startswith(b'EndComposites'):
+ return composites
+ vals = line.split(b';')
+ cc = vals[0].split()
+ name, _num_parts = cc[1], _to_int(cc[2])
+ pccParts = []
+ for s in vals[1:-1]:
+ pcc = s.split()
+ part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3]))
+ pccParts.append(part)
+ composites[name] = pccParts
+
+ raise RuntimeError('Bad composites parse')
+
+
+def _parse_optional(fh):
+ """
+ Parse the optional fields for kern pair data and composites.
+
+ Returns
+ -------
+ kern_data : dict
+ A dict containing kerning information. May be empty.
+ See `._parse_kern_pairs`.
+ composites : dict
+ A dict containing composite information. May be empty.
+ See `._parse_composites`.
+ """
+ optional = {
+ b'StartKernData': _parse_kern_pairs,
+ b'StartComposites': _parse_composites,
+ }
+
+ d = {b'StartKernData': {},
+ b'StartComposites': {}}
+ for line in fh:
+ line = line.rstrip()
+ if not line:
+ continue
+ key = line.split()[0]
+
+ if key in optional:
+ d[key] = optional[key](fh)
+
+ return d[b'StartKernData'], d[b'StartComposites']
+
+
+class AFM:
+
+ def __init__(self, fh):
+ """Parse the AFM file in file object *fh*."""
+ self._header = _parse_header(fh)
+ self._metrics, self._metrics_by_name = _parse_char_metrics(fh)
+ self._kern, self._composite = _parse_optional(fh)
+
+ def get_bbox_char(self, c, isord=False):
+ if not isord:
+ c = ord(c)
+ return self._metrics[c].bbox
+
+ def string_width_height(self, s):
+ """
+ Return the string width (including kerning) and string height
+ as a (*w*, *h*) tuple.
+ """
+ if not len(s):
+ return 0, 0
+ total_width = 0
+ namelast = None
+ miny = 1e9
+ maxy = 0
+ for c in s:
+ if c == '\n':
+ continue
+ wx, name, bbox = self._metrics[ord(c)]
+
+ total_width += wx + self._kern.get((namelast, name), 0)
+ l, b, w, h = bbox
+ miny = min(miny, b)
+ maxy = max(maxy, b + h)
+
+ namelast = name
+
+ return total_width, maxy - miny
+
+ def get_str_bbox_and_descent(self, s):
+ """Return the string bounding box and the maximal descent."""
+ if not len(s):
+ return 0, 0, 0, 0, 0
+ total_width = 0
+ namelast = None
+ miny = 1e9
+ maxy = 0
+ left = 0
+ if not isinstance(s, str):
+ s = _to_str(s)
+ for c in s:
+ if c == '\n':
+ continue
+ name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
+ try:
+ wx, _, bbox = self._metrics_by_name[name]
+ except KeyError:
+ name = 'question'
+ wx, _, bbox = self._metrics_by_name[name]
+ total_width += wx + self._kern.get((namelast, name), 0)
+ l, b, w, h = bbox
+ left = min(left, l)
+ miny = min(miny, b)
+ maxy = max(maxy, b + h)
+
+ namelast = name
+
+ return left, miny, total_width, maxy - miny, -miny
+
+ def get_str_bbox(self, s):
+ """Return the string bounding box."""
+ return self.get_str_bbox_and_descent(s)[:4]
+
+ def get_name_char(self, c, isord=False):
+ """Get the name of the character, i.e., ';' is 'semicolon'."""
+ if not isord:
+ c = ord(c)
+ return self._metrics[c].name
+
+ def get_width_char(self, c, isord=False):
+ """
+ Get the width of the character from the character metric WX field.
+ """
+ if not isord:
+ c = ord(c)
+ return self._metrics[c].width
+
+ def get_width_from_char_name(self, name):
+ """Get the width of the character from a type1 character name."""
+ return self._metrics_by_name[name].width
+
+ def get_height_char(self, c, isord=False):
+ """Get the bounding box (ink) height of character *c* (space is 0)."""
+ if not isord:
+ c = ord(c)
+ return self._metrics[c].bbox[-1]
+
+ def get_kern_dist(self, c1, c2):
+ """
+ Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
+ """
+ name1, name2 = self.get_name_char(c1), self.get_name_char(c2)
+ return self.get_kern_dist_from_name(name1, name2)
+
+ def get_kern_dist_from_name(self, name1, name2):
+ """
+ Return the kerning pair distance (possibly 0) for chars
+ *name1* and *name2*.
+ """
+ return self._kern.get((name1, name2), 0)
+
+ def get_fontname(self):
+ """Return the font name, e.g., 'Times-Roman'."""
+ return self._header[b'FontName']
+
+ @property
+ def postscript_name(self): # For consistency with FT2Font.
+ return self.get_fontname()
+
+ def get_fullname(self):
+ """Return the font full name, e.g., 'Times-Roman'."""
+ name = self._header.get(b'FullName')
+ if name is None: # use FontName as a substitute
+ name = self._header[b'FontName']
+ return name
+
+ def get_familyname(self):
+ """Return the font family name, e.g., 'Times'."""
+ name = self._header.get(b'FamilyName')
+ if name is not None:
+ return name
+
+ # FamilyName not specified so we'll make a guess
+ name = self.get_fullname()
+ extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
+ r'light|ultralight|extra|condensed))+$')
+ return re.sub(extras, '', name)
+
+ @property
+ def family_name(self):
+ """The font family name, e.g., 'Times'."""
+ return self.get_familyname()
+
+ def get_weight(self):
+ """Return the font weight, e.g., 'Bold' or 'Roman'."""
+ return self._header[b'Weight']
+
+ def get_angle(self):
+ """Return the fontangle as float."""
+ return self._header[b'ItalicAngle']
+
+ def get_capheight(self):
+ """Return the cap height as float."""
+ return self._header[b'CapHeight']
+
+ def get_xheight(self):
+ """Return the xheight as float."""
+ return self._header[b'XHeight']
+
+ def get_underline_thickness(self):
+ """Return the underline thickness as float."""
+ return self._header[b'UnderlineThickness']
+
+ def get_horizontal_stem_width(self):
+ """
+ Return the standard horizontal stem width as float, or *None* if
+ not specified in AFM file.
+ """
+ return self._header.get(b'StdHW', None)
+
+ def get_vertical_stem_width(self):
+ """
+ Return the standard vertical stem width as float, or *None* if
+ not specified in AFM file.
+ """
+ return self._header.get(b'StdVW', None)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_animation_data.py b/llava_video/lib/python3.10/site-packages/matplotlib/_animation_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cbd312d8f142d8b4ec3a3ad3e005a14f380ec13
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_animation_data.py
@@ -0,0 +1,262 @@
+# JavaScript template for HTMLWriter
+JS_INCLUDE = """
+
+
+"""
+
+
+# Style definitions for the HTML template
+STYLE_INCLUDE = """
+
+"""
+
+
+# HTML template for HTMLWriter
+DISPLAY_TEMPLATE = """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+""" # noqa: E501
+
+
+INCLUDED_FRAMES = """
+ for (var i=0; i<{Nframes}; i++){{
+ frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) +
+ ".{frame_format}";
+ }}
+"""
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so b/llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..03718036c23f393f29019779998c8d162ac44c33
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:643c208f3cb14042e0b6f3d82aa31fb094fc56f61beecee0aab0001cc44580ab
+size 251392
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ccc172cde27a35ad930cc618b86fdf5c8d44728e
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi
@@ -0,0 +1,8 @@
+def display_is_valid() -> bool: ...
+def xdisplay_is_valid() -> bool: ...
+
+def Win32_GetForegroundWindow() -> int | None: ...
+def Win32_SetForegroundWindow(hwnd: int) -> None: ...
+def Win32_SetProcessDpiAwareness_max() -> None: ...
+def Win32_SetCurrentProcessExplicitAppUserModelID(appid: str) -> None: ...
+def Win32_GetCurrentProcessExplicitAppUserModelID() -> str | None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_cm_multivar.py b/llava_video/lib/python3.10/site-packages/matplotlib/_cm_multivar.py
new file mode 100644
index 0000000000000000000000000000000000000000..610d7c40935b0999fe7de38515f316ce816023f7
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_cm_multivar.py
@@ -0,0 +1,166 @@
+# auto-generated by https://github.com/trygvrad/multivariate_colormaps
+# date: 2024-05-28
+
+from .colors import LinearSegmentedColormap, MultivarColormap
+import matplotlib as mpl
+_LUTSIZE = mpl.rcParams['image.lut']
+
+_2VarAddA0_data = [[0.000, 0.000, 0.000],
+ [0.020, 0.026, 0.031],
+ [0.049, 0.068, 0.085],
+ [0.075, 0.107, 0.135],
+ [0.097, 0.144, 0.183],
+ [0.116, 0.178, 0.231],
+ [0.133, 0.212, 0.279],
+ [0.148, 0.244, 0.326],
+ [0.161, 0.276, 0.374],
+ [0.173, 0.308, 0.422],
+ [0.182, 0.339, 0.471],
+ [0.190, 0.370, 0.521],
+ [0.197, 0.400, 0.572],
+ [0.201, 0.431, 0.623],
+ [0.204, 0.461, 0.675],
+ [0.204, 0.491, 0.728],
+ [0.202, 0.520, 0.783],
+ [0.197, 0.549, 0.838],
+ [0.187, 0.577, 0.895]]
+
+_2VarAddA1_data = [[0.000, 0.000, 0.000],
+ [0.030, 0.023, 0.018],
+ [0.079, 0.060, 0.043],
+ [0.125, 0.093, 0.065],
+ [0.170, 0.123, 0.083],
+ [0.213, 0.151, 0.098],
+ [0.255, 0.177, 0.110],
+ [0.298, 0.202, 0.120],
+ [0.341, 0.226, 0.128],
+ [0.384, 0.249, 0.134],
+ [0.427, 0.271, 0.138],
+ [0.472, 0.292, 0.141],
+ [0.517, 0.313, 0.142],
+ [0.563, 0.333, 0.141],
+ [0.610, 0.353, 0.139],
+ [0.658, 0.372, 0.134],
+ [0.708, 0.390, 0.127],
+ [0.759, 0.407, 0.118],
+ [0.813, 0.423, 0.105]]
+
+_2VarSubA0_data = [[1.000, 1.000, 1.000],
+ [0.959, 0.973, 0.986],
+ [0.916, 0.948, 0.974],
+ [0.874, 0.923, 0.965],
+ [0.832, 0.899, 0.956],
+ [0.790, 0.875, 0.948],
+ [0.748, 0.852, 0.940],
+ [0.707, 0.829, 0.934],
+ [0.665, 0.806, 0.927],
+ [0.624, 0.784, 0.921],
+ [0.583, 0.762, 0.916],
+ [0.541, 0.740, 0.910],
+ [0.500, 0.718, 0.905],
+ [0.457, 0.697, 0.901],
+ [0.414, 0.675, 0.896],
+ [0.369, 0.652, 0.892],
+ [0.320, 0.629, 0.888],
+ [0.266, 0.604, 0.884],
+ [0.199, 0.574, 0.881]]
+
+_2VarSubA1_data = [[1.000, 1.000, 1.000],
+ [0.982, 0.967, 0.955],
+ [0.966, 0.935, 0.908],
+ [0.951, 0.902, 0.860],
+ [0.937, 0.870, 0.813],
+ [0.923, 0.838, 0.765],
+ [0.910, 0.807, 0.718],
+ [0.898, 0.776, 0.671],
+ [0.886, 0.745, 0.624],
+ [0.874, 0.714, 0.577],
+ [0.862, 0.683, 0.530],
+ [0.851, 0.653, 0.483],
+ [0.841, 0.622, 0.435],
+ [0.831, 0.592, 0.388],
+ [0.822, 0.561, 0.340],
+ [0.813, 0.530, 0.290],
+ [0.806, 0.498, 0.239],
+ [0.802, 0.464, 0.184],
+ [0.801, 0.426, 0.119]]
+
+_3VarAddA0_data = [[0.000, 0.000, 0.000],
+ [0.018, 0.023, 0.028],
+ [0.040, 0.056, 0.071],
+ [0.059, 0.087, 0.110],
+ [0.074, 0.114, 0.147],
+ [0.086, 0.139, 0.183],
+ [0.095, 0.163, 0.219],
+ [0.101, 0.187, 0.255],
+ [0.105, 0.209, 0.290],
+ [0.107, 0.230, 0.326],
+ [0.105, 0.251, 0.362],
+ [0.101, 0.271, 0.398],
+ [0.091, 0.291, 0.434],
+ [0.075, 0.309, 0.471],
+ [0.046, 0.325, 0.507],
+ [0.021, 0.341, 0.546],
+ [0.021, 0.363, 0.584],
+ [0.022, 0.385, 0.622],
+ [0.023, 0.408, 0.661]]
+
+_3VarAddA1_data = [[0.000, 0.000, 0.000],
+ [0.020, 0.024, 0.016],
+ [0.047, 0.058, 0.034],
+ [0.072, 0.088, 0.048],
+ [0.093, 0.116, 0.059],
+ [0.113, 0.142, 0.067],
+ [0.131, 0.167, 0.071],
+ [0.149, 0.190, 0.074],
+ [0.166, 0.213, 0.074],
+ [0.182, 0.235, 0.072],
+ [0.198, 0.256, 0.068],
+ [0.215, 0.276, 0.061],
+ [0.232, 0.296, 0.051],
+ [0.249, 0.314, 0.037],
+ [0.270, 0.330, 0.018],
+ [0.288, 0.347, 0.000],
+ [0.302, 0.369, 0.000],
+ [0.315, 0.391, 0.000],
+ [0.328, 0.414, 0.000]]
+
+_3VarAddA2_data = [[0.000, 0.000, 0.000],
+ [0.029, 0.020, 0.023],
+ [0.072, 0.045, 0.055],
+ [0.111, 0.067, 0.084],
+ [0.148, 0.085, 0.109],
+ [0.184, 0.101, 0.133],
+ [0.219, 0.115, 0.155],
+ [0.254, 0.127, 0.176],
+ [0.289, 0.138, 0.195],
+ [0.323, 0.147, 0.214],
+ [0.358, 0.155, 0.232],
+ [0.393, 0.161, 0.250],
+ [0.429, 0.166, 0.267],
+ [0.467, 0.169, 0.283],
+ [0.507, 0.168, 0.298],
+ [0.546, 0.168, 0.313],
+ [0.580, 0.172, 0.328],
+ [0.615, 0.175, 0.341],
+ [0.649, 0.178, 0.355]]
+
+cmaps = {
+ name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for name, data in [
+ ('2VarAddA0', _2VarAddA0_data),
+ ('2VarAddA1', _2VarAddA1_data),
+ ('2VarSubA0', _2VarSubA0_data),
+ ('2VarSubA1', _2VarSubA1_data),
+ ('3VarAddA0', _3VarAddA0_data),
+ ('3VarAddA1', _3VarAddA1_data),
+ ('3VarAddA2', _3VarAddA2_data),
+ ]}
+
+cmap_families = {
+ '2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)],
+ 'sRGB_add', name='2VarAddA'),
+ '2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)],
+ 'sRGB_sub', name='2VarSubA'),
+ '3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)],
+ 'sRGB_add', name='3VarAddA'),
+}
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_color_data.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/_color_data.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..feb3de9c3043d55910e2649804352ae96ccbd1ec
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_color_data.pyi
@@ -0,0 +1,6 @@
+from .typing import ColorType
+
+BASE_COLORS: dict[str, ColorType]
+TABLEAU_COLORS: dict[str, ColorType]
+XKCD_COLORS: dict[str, ColorType]
+CSS4_COLORS: dict[str, ColorType]
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_constrained_layout.py b/llava_video/lib/python3.10/site-packages/matplotlib/_constrained_layout.py
new file mode 100644
index 0000000000000000000000000000000000000000..5623e12a3c41d0d0d35041fd1dd9fb23e9938e51
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_constrained_layout.py
@@ -0,0 +1,801 @@
+"""
+Adjust subplot layouts so that there are no overlapping Axes or Axes
+decorations. All Axes decorations are dealt with (labels, ticks, titles,
+ticklabels) and some dependent artists are also dealt with (colorbar,
+suptitle).
+
+Layout is done via `~matplotlib.gridspec`, with one constraint per gridspec,
+so it is possible to have overlapping Axes if the gridspecs overlap (i.e.
+using `~matplotlib.gridspec.GridSpecFromSubplotSpec`). Axes placed using
+``figure.subplots()`` or ``figure.add_subplots()`` will participate in the
+layout. Axes manually placed via ``figure.add_axes()`` will not.
+
+See Tutorial: :ref:`constrainedlayout_guide`
+
+General idea:
+-------------
+
+First, a figure has a gridspec that divides the figure into nrows and ncols,
+with heights and widths set by ``height_ratios`` and ``width_ratios``,
+often just set to 1 for an equal grid.
+
+Subplotspecs that are derived from this gridspec can contain either a
+``SubPanel``, a ``GridSpecFromSubplotSpec``, or an ``Axes``. The ``SubPanel``
+and ``GridSpecFromSubplotSpec`` are dealt with recursively and each contain an
+analogous layout.
+
+Each ``GridSpec`` has a ``_layoutgrid`` attached to it. The ``_layoutgrid``
+has the same logical layout as the ``GridSpec``. Each row of the grid spec
+has a top and bottom "margin" and each column has a left and right "margin".
+The "inner" height of each row is constrained to be the same (or as modified
+by ``height_ratio``), and the "inner" width of each column is
+constrained to be the same (as modified by ``width_ratio``), where "inner"
+is the width or height of each column/row minus the size of the margins.
+
+Then the size of the margins for each row and column are determined as the
+max width of the decorators on each Axes that has decorators in that margin.
+For instance, a normal Axes would have a left margin that includes the
+left ticklabels, and the ylabel if it exists. The right margin may include a
+colorbar, the bottom margin the xaxis decorations, and the top margin the
+title.
+
+With these constraints, the solver then finds appropriate bounds for the
+columns and rows. It's possible that the margins take up the whole figure,
+in which case the algorithm is not applied and a warning is raised.
+
+See the tutorial :ref:`constrainedlayout_guide`
+for more discussion of the algorithm with examples.
+"""
+
+import logging
+
+import numpy as np
+
+from matplotlib import _api, artist as martist
+import matplotlib.transforms as mtransforms
+import matplotlib._layoutgrid as mlayoutgrid
+
+
+_log = logging.getLogger(__name__)
+
+
+######################################################
+def do_constrained_layout(fig, h_pad, w_pad,
+ hspace=None, wspace=None, rect=(0, 0, 1, 1),
+ compress=False):
+ """
+ Do the constrained_layout. Called at draw time in
+ ``figure.constrained_layout()``
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ `.Figure` instance to do the layout in.
+
+ h_pad, w_pad : float
+ Padding around the Axes elements in figure-normalized units.
+
+ hspace, wspace : float
+ Fraction of the figure to dedicate to space between the
+ Axes. These are evenly spread between the gaps between the Axes.
+ A value of 0.2 for a three-column layout would have a space
+ of 0.1 of the figure width between each column.
+ If h/wspace < h/w_pad, then the pads are used instead.
+
+ rect : tuple of 4 floats
+ Rectangle in figure coordinates to perform constrained layout in
+ [left, bottom, width, height], each from 0-1.
+
+ compress : bool
+ Whether to shift Axes so that white space in between them is
+ removed. This is useful for simple grids of fixed-aspect Axes (e.g.
+ a grid of images).
+
+ Returns
+ -------
+ layoutgrid : private debugging structure
+ """
+
+ renderer = fig._get_renderer()
+ # make layoutgrid tree...
+ layoutgrids = make_layoutgrids(fig, None, rect=rect)
+ if not layoutgrids['hasgrids']:
+ _api.warn_external('There are no gridspecs with layoutgrids. '
+ 'Possibly did not call parent GridSpec with the'
+ ' "figure" keyword')
+ return
+
+ for _ in range(2):
+ # do the algorithm twice. This has to be done because decorations
+ # change size after the first re-position (i.e. x/yticklabels get
+ # larger/smaller). This second reposition tends to be much milder,
+ # so doing twice makes things work OK.
+
+ # make margins for all the Axes and subfigures in the
+ # figure. Add margins for colorbars...
+ make_layout_margins(layoutgrids, fig, renderer, h_pad=h_pad,
+ w_pad=w_pad, hspace=hspace, wspace=wspace)
+ make_margin_suptitles(layoutgrids, fig, renderer, h_pad=h_pad,
+ w_pad=w_pad)
+
+ # if a layout is such that a columns (or rows) margin has no
+ # constraints, we need to make all such instances in the grid
+ # match in margin size.
+ match_submerged_margins(layoutgrids, fig)
+
+ # update all the variables in the layout.
+ layoutgrids[fig].update_variables()
+
+ warn_collapsed = ('constrained_layout not applied because '
+ 'axes sizes collapsed to zero. Try making '
+ 'figure larger or Axes decorations smaller.')
+ if check_no_collapsed_axes(layoutgrids, fig):
+ reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad,
+ w_pad=w_pad, hspace=hspace, wspace=wspace)
+ if compress:
+ layoutgrids = compress_fixed_aspect(layoutgrids, fig)
+ layoutgrids[fig].update_variables()
+ if check_no_collapsed_axes(layoutgrids, fig):
+ reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad,
+ w_pad=w_pad, hspace=hspace, wspace=wspace)
+ else:
+ _api.warn_external(warn_collapsed)
+
+ if ((suptitle := fig._suptitle) is not None and
+ suptitle.get_in_layout() and suptitle._autopos):
+ x, _ = suptitle.get_position()
+ suptitle.set_position(
+ (x, layoutgrids[fig].get_inner_bbox().y1 + h_pad))
+ suptitle.set_verticalalignment('bottom')
+ else:
+ _api.warn_external(warn_collapsed)
+ reset_margins(layoutgrids, fig)
+ return layoutgrids
+
+
+def make_layoutgrids(fig, layoutgrids, rect=(0, 0, 1, 1)):
+ """
+ Make the layoutgrid tree.
+
+ (Sub)Figures get a layoutgrid so we can have figure margins.
+
+ Gridspecs that are attached to Axes get a layoutgrid so Axes
+ can have margins.
+ """
+
+ if layoutgrids is None:
+ layoutgrids = dict()
+ layoutgrids['hasgrids'] = False
+ if not hasattr(fig, '_parent'):
+ # top figure; pass rect as parent to allow user-specified
+ # margins
+ layoutgrids[fig] = mlayoutgrid.LayoutGrid(parent=rect, name='figlb')
+ else:
+ # subfigure
+ gs = fig._subplotspec.get_gridspec()
+ # it is possible the gridspec containing this subfigure hasn't
+ # been added to the tree yet:
+ layoutgrids = make_layoutgrids_gs(layoutgrids, gs)
+ # add the layoutgrid for the subfigure:
+ parentlb = layoutgrids[gs]
+ layoutgrids[fig] = mlayoutgrid.LayoutGrid(
+ parent=parentlb,
+ name='panellb',
+ parent_inner=True,
+ nrows=1, ncols=1,
+ parent_pos=(fig._subplotspec.rowspan,
+ fig._subplotspec.colspan))
+ # recursively do all subfigures in this figure...
+ for sfig in fig.subfigs:
+ layoutgrids = make_layoutgrids(sfig, layoutgrids)
+
+ # for each Axes at the local level add its gridspec:
+ for ax in fig._localaxes:
+ gs = ax.get_gridspec()
+ if gs is not None:
+ layoutgrids = make_layoutgrids_gs(layoutgrids, gs)
+
+ return layoutgrids
+
+
+def make_layoutgrids_gs(layoutgrids, gs):
+ """
+ Make the layoutgrid for a gridspec (and anything nested in the gridspec)
+ """
+
+ if gs in layoutgrids or gs.figure is None:
+ return layoutgrids
+ # in order to do constrained_layout there has to be at least *one*
+ # gridspec in the tree:
+ layoutgrids['hasgrids'] = True
+ if not hasattr(gs, '_subplot_spec'):
+ # normal gridspec
+ parent = layoutgrids[gs.figure]
+ layoutgrids[gs] = mlayoutgrid.LayoutGrid(
+ parent=parent,
+ parent_inner=True,
+ name='gridspec',
+ ncols=gs._ncols, nrows=gs._nrows,
+ width_ratios=gs.get_width_ratios(),
+ height_ratios=gs.get_height_ratios())
+ else:
+ # this is a gridspecfromsubplotspec:
+ subplot_spec = gs._subplot_spec
+ parentgs = subplot_spec.get_gridspec()
+ # if a nested gridspec it is possible the parent is not in there yet:
+ if parentgs not in layoutgrids:
+ layoutgrids = make_layoutgrids_gs(layoutgrids, parentgs)
+ subspeclb = layoutgrids[parentgs]
+ # gridspecfromsubplotspec need an outer container:
+ # get a unique representation:
+ rep = (gs, 'top')
+ if rep not in layoutgrids:
+ layoutgrids[rep] = mlayoutgrid.LayoutGrid(
+ parent=subspeclb,
+ name='top',
+ nrows=1, ncols=1,
+ parent_pos=(subplot_spec.rowspan, subplot_spec.colspan))
+ layoutgrids[gs] = mlayoutgrid.LayoutGrid(
+ parent=layoutgrids[rep],
+ name='gridspec',
+ nrows=gs._nrows, ncols=gs._ncols,
+ width_ratios=gs.get_width_ratios(),
+ height_ratios=gs.get_height_ratios())
+ return layoutgrids
+
+
+def check_no_collapsed_axes(layoutgrids, fig):
+ """
+ Check that no Axes have collapsed to zero size.
+ """
+ for sfig in fig.subfigs:
+ ok = check_no_collapsed_axes(layoutgrids, sfig)
+ if not ok:
+ return False
+ for ax in fig.axes:
+ gs = ax.get_gridspec()
+ if gs in layoutgrids: # also implies gs is not None.
+ lg = layoutgrids[gs]
+ for i in range(gs.nrows):
+ for j in range(gs.ncols):
+ bb = lg.get_inner_bbox(i, j)
+ if bb.width <= 0 or bb.height <= 0:
+ return False
+ return True
+
+
+def compress_fixed_aspect(layoutgrids, fig):
+ gs = None
+ for ax in fig.axes:
+ if ax.get_subplotspec() is None:
+ continue
+ ax.apply_aspect()
+ sub = ax.get_subplotspec()
+ _gs = sub.get_gridspec()
+ if gs is None:
+ gs = _gs
+ extraw = np.zeros(gs.ncols)
+ extrah = np.zeros(gs.nrows)
+ elif _gs != gs:
+ raise ValueError('Cannot do compressed layout if Axes are not'
+ 'all from the same gridspec')
+ orig = ax.get_position(original=True)
+ actual = ax.get_position(original=False)
+ dw = orig.width - actual.width
+ if dw > 0:
+ extraw[sub.colspan] = np.maximum(extraw[sub.colspan], dw)
+ dh = orig.height - actual.height
+ if dh > 0:
+ extrah[sub.rowspan] = np.maximum(extrah[sub.rowspan], dh)
+
+ if gs is None:
+ raise ValueError('Cannot do compressed layout if no Axes '
+ 'are part of a gridspec.')
+ w = np.sum(extraw) / 2
+ layoutgrids[fig].edit_margin_min('left', w)
+ layoutgrids[fig].edit_margin_min('right', w)
+
+ h = np.sum(extrah) / 2
+ layoutgrids[fig].edit_margin_min('top', h)
+ layoutgrids[fig].edit_margin_min('bottom', h)
+ return layoutgrids
+
+
+def get_margin_from_padding(obj, *, w_pad=0, h_pad=0,
+ hspace=0, wspace=0):
+
+ ss = obj._subplotspec
+ gs = ss.get_gridspec()
+
+ if hasattr(gs, 'hspace'):
+ _hspace = (gs.hspace if gs.hspace is not None else hspace)
+ _wspace = (gs.wspace if gs.wspace is not None else wspace)
+ else:
+ _hspace = (gs._hspace if gs._hspace is not None else hspace)
+ _wspace = (gs._wspace if gs._wspace is not None else wspace)
+
+ _wspace = _wspace / 2
+ _hspace = _hspace / 2
+
+ nrows, ncols = gs.get_geometry()
+ # there are two margins for each direction. The "cb"
+ # margins are for pads and colorbars, the non-"cb" are
+ # for the Axes decorations (labels etc).
+ margin = {'leftcb': w_pad, 'rightcb': w_pad,
+ 'bottomcb': h_pad, 'topcb': h_pad,
+ 'left': 0, 'right': 0,
+ 'top': 0, 'bottom': 0}
+ if _wspace / ncols > w_pad:
+ if ss.colspan.start > 0:
+ margin['leftcb'] = _wspace / ncols
+ if ss.colspan.stop < ncols:
+ margin['rightcb'] = _wspace / ncols
+ if _hspace / nrows > h_pad:
+ if ss.rowspan.stop < nrows:
+ margin['bottomcb'] = _hspace / nrows
+ if ss.rowspan.start > 0:
+ margin['topcb'] = _hspace / nrows
+
+ return margin
+
+
+def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
+ hspace=0, wspace=0):
+ """
+ For each Axes, make a margin between the *pos* layoutbox and the
+ *axes* layoutbox be a minimum size that can accommodate the
+ decorations on the axis.
+
+ Then make room for colorbars.
+
+ Parameters
+ ----------
+ layoutgrids : dict
+ fig : `~matplotlib.figure.Figure`
+ `.Figure` instance to do the layout in.
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass.
+ The renderer to use.
+ w_pad, h_pad : float, default: 0
+ Width and height padding (in fraction of figure).
+ hspace, wspace : float, default: 0
+ Width and height padding as fraction of figure size divided by
+ number of columns or rows.
+ """
+ for sfig in fig.subfigs: # recursively make child panel margins
+ ss = sfig._subplotspec
+ gs = ss.get_gridspec()
+
+ make_layout_margins(layoutgrids, sfig, renderer,
+ w_pad=w_pad, h_pad=h_pad,
+ hspace=hspace, wspace=wspace)
+
+ margins = get_margin_from_padding(sfig, w_pad=0, h_pad=0,
+ hspace=hspace, wspace=wspace)
+ layoutgrids[gs].edit_outer_margin_mins(margins, ss)
+
+ for ax in fig._localaxes:
+ if not ax.get_subplotspec() or not ax.get_in_layout():
+ continue
+
+ ss = ax.get_subplotspec()
+ gs = ss.get_gridspec()
+
+ if gs not in layoutgrids:
+ return
+
+ margin = get_margin_from_padding(ax, w_pad=w_pad, h_pad=h_pad,
+ hspace=hspace, wspace=wspace)
+ pos, bbox = get_pos_and_bbox(ax, renderer)
+ # the margin is the distance between the bounding box of the Axes
+ # and its position (plus the padding from above)
+ margin['left'] += pos.x0 - bbox.x0
+ margin['right'] += bbox.x1 - pos.x1
+ # remember that rows are ordered from top:
+ margin['bottom'] += pos.y0 - bbox.y0
+ margin['top'] += bbox.y1 - pos.y1
+
+ # make margin for colorbars. These margins go in the
+ # padding margin, versus the margin for Axes decorators.
+ for cbax in ax._colorbars:
+ # note pad is a fraction of the parent width...
+ pad = colorbar_get_pad(layoutgrids, cbax)
+ # colorbars can be child of more than one subplot spec:
+ cbp_rspan, cbp_cspan = get_cb_parent_spans(cbax)
+ loc = cbax._colorbar_info['location']
+ cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)
+ if loc == 'right':
+ if cbp_cspan.stop == ss.colspan.stop:
+ # only increase if the colorbar is on the right edge
+ margin['rightcb'] += cbbbox.width + pad
+ elif loc == 'left':
+ if cbp_cspan.start == ss.colspan.start:
+ # only increase if the colorbar is on the left edge
+ margin['leftcb'] += cbbbox.width + pad
+ elif loc == 'top':
+ if cbp_rspan.start == ss.rowspan.start:
+ margin['topcb'] += cbbbox.height + pad
+ else:
+ if cbp_rspan.stop == ss.rowspan.stop:
+ margin['bottomcb'] += cbbbox.height + pad
+ # If the colorbars are wider than the parent box in the
+ # cross direction
+ if loc in ['top', 'bottom']:
+ if (cbp_cspan.start == ss.colspan.start and
+ cbbbox.x0 < bbox.x0):
+ margin['left'] += bbox.x0 - cbbbox.x0
+ if (cbp_cspan.stop == ss.colspan.stop and
+ cbbbox.x1 > bbox.x1):
+ margin['right'] += cbbbox.x1 - bbox.x1
+ # or taller:
+ if loc in ['left', 'right']:
+ if (cbp_rspan.stop == ss.rowspan.stop and
+ cbbbox.y0 < bbox.y0):
+ margin['bottom'] += bbox.y0 - cbbbox.y0
+ if (cbp_rspan.start == ss.rowspan.start and
+ cbbbox.y1 > bbox.y1):
+ margin['top'] += cbbbox.y1 - bbox.y1
+ # pass the new margins down to the layout grid for the solution...
+ layoutgrids[gs].edit_outer_margin_mins(margin, ss)
+
+ # make margins for figure-level legends:
+ for leg in fig.legends:
+ inv_trans_fig = None
+ if leg._outside_loc and leg._bbox_to_anchor is None:
+ if inv_trans_fig is None:
+ inv_trans_fig = fig.transFigure.inverted().transform_bbox
+ bbox = inv_trans_fig(leg.get_tightbbox(renderer))
+ w = bbox.width + 2 * w_pad
+ h = bbox.height + 2 * h_pad
+ legendloc = leg._outside_loc
+ if legendloc == 'lower':
+ layoutgrids[fig].edit_margin_min('bottom', h)
+ elif legendloc == 'upper':
+ layoutgrids[fig].edit_margin_min('top', h)
+ if legendloc == 'right':
+ layoutgrids[fig].edit_margin_min('right', w)
+ elif legendloc == 'left':
+ layoutgrids[fig].edit_margin_min('left', w)
+
+
+def make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0):
+ # Figure out how large the suptitle is and make the
+ # top level figure margin larger.
+
+ inv_trans_fig = fig.transFigure.inverted().transform_bbox
+ # get the h_pad and w_pad as distances in the local subfigure coordinates:
+ padbox = mtransforms.Bbox([[0, 0], [w_pad, h_pad]])
+ padbox = (fig.transFigure -
+ fig.transSubfigure).transform_bbox(padbox)
+ h_pad_local = padbox.height
+ w_pad_local = padbox.width
+
+ for sfig in fig.subfigs:
+ make_margin_suptitles(layoutgrids, sfig, renderer,
+ w_pad=w_pad, h_pad=h_pad)
+
+ if fig._suptitle is not None and fig._suptitle.get_in_layout():
+ p = fig._suptitle.get_position()
+ if getattr(fig._suptitle, '_autopos', False):
+ fig._suptitle.set_position((p[0], 1 - h_pad_local))
+ bbox = inv_trans_fig(fig._suptitle.get_tightbbox(renderer))
+ layoutgrids[fig].edit_margin_min('top', bbox.height + 2 * h_pad)
+
+ if fig._supxlabel is not None and fig._supxlabel.get_in_layout():
+ p = fig._supxlabel.get_position()
+ if getattr(fig._supxlabel, '_autopos', False):
+ fig._supxlabel.set_position((p[0], h_pad_local))
+ bbox = inv_trans_fig(fig._supxlabel.get_tightbbox(renderer))
+ layoutgrids[fig].edit_margin_min('bottom',
+ bbox.height + 2 * h_pad)
+
+ if fig._supylabel is not None and fig._supylabel.get_in_layout():
+ p = fig._supylabel.get_position()
+ if getattr(fig._supylabel, '_autopos', False):
+ fig._supylabel.set_position((w_pad_local, p[1]))
+ bbox = inv_trans_fig(fig._supylabel.get_tightbbox(renderer))
+ layoutgrids[fig].edit_margin_min('left', bbox.width + 2 * w_pad)
+
+
+def match_submerged_margins(layoutgrids, fig):
+ """
+ Make the margins that are submerged inside an Axes the same size.
+
+ This allows Axes that span two columns (or rows) that are offset
+ from one another to have the same size.
+
+ This gives the proper layout for something like::
+ fig = plt.figure(constrained_layout=True)
+ axs = fig.subplot_mosaic("AAAB\nCCDD")
+
+ Without this routine, the Axes D will be wider than C, because the
+ margin width between the two columns in C has no width by default,
+ whereas the margins between the two columns of D are set by the
+ width of the margin between A and B. However, obviously the user would
+ like C and D to be the same size, so we need to add constraints to these
+ "submerged" margins.
+
+ This routine makes all the interior margins the same, and the spacing
+ between the three columns in A and the two column in C are all set to the
+ margins between the two columns of D.
+
+ See test_constrained_layout::test_constrained_layout12 for an example.
+ """
+
+ for sfig in fig.subfigs:
+ match_submerged_margins(layoutgrids, sfig)
+
+ axs = [a for a in fig.get_axes()
+ if a.get_subplotspec() is not None and a.get_in_layout()]
+
+ for ax1 in axs:
+ ss1 = ax1.get_subplotspec()
+ if ss1.get_gridspec() not in layoutgrids:
+ axs.remove(ax1)
+ continue
+ lg1 = layoutgrids[ss1.get_gridspec()]
+
+ # interior columns:
+ if len(ss1.colspan) > 1:
+ maxsubl = np.max(
+ lg1.margin_vals['left'][ss1.colspan[1:]] +
+ lg1.margin_vals['leftcb'][ss1.colspan[1:]]
+ )
+ maxsubr = np.max(
+ lg1.margin_vals['right'][ss1.colspan[:-1]] +
+ lg1.margin_vals['rightcb'][ss1.colspan[:-1]]
+ )
+ for ax2 in axs:
+ ss2 = ax2.get_subplotspec()
+ lg2 = layoutgrids[ss2.get_gridspec()]
+ if lg2 is not None and len(ss2.colspan) > 1:
+ maxsubl2 = np.max(
+ lg2.margin_vals['left'][ss2.colspan[1:]] +
+ lg2.margin_vals['leftcb'][ss2.colspan[1:]])
+ if maxsubl2 > maxsubl:
+ maxsubl = maxsubl2
+ maxsubr2 = np.max(
+ lg2.margin_vals['right'][ss2.colspan[:-1]] +
+ lg2.margin_vals['rightcb'][ss2.colspan[:-1]])
+ if maxsubr2 > maxsubr:
+ maxsubr = maxsubr2
+ for i in ss1.colspan[1:]:
+ lg1.edit_margin_min('left', maxsubl, cell=i)
+ for i in ss1.colspan[:-1]:
+ lg1.edit_margin_min('right', maxsubr, cell=i)
+
+ # interior rows:
+ if len(ss1.rowspan) > 1:
+ maxsubt = np.max(
+ lg1.margin_vals['top'][ss1.rowspan[1:]] +
+ lg1.margin_vals['topcb'][ss1.rowspan[1:]]
+ )
+ maxsubb = np.max(
+ lg1.margin_vals['bottom'][ss1.rowspan[:-1]] +
+ lg1.margin_vals['bottomcb'][ss1.rowspan[:-1]]
+ )
+
+ for ax2 in axs:
+ ss2 = ax2.get_subplotspec()
+ lg2 = layoutgrids[ss2.get_gridspec()]
+ if lg2 is not None:
+ if len(ss2.rowspan) > 1:
+ maxsubt = np.max([np.max(
+ lg2.margin_vals['top'][ss2.rowspan[1:]] +
+ lg2.margin_vals['topcb'][ss2.rowspan[1:]]
+ ), maxsubt])
+ maxsubb = np.max([np.max(
+ lg2.margin_vals['bottom'][ss2.rowspan[:-1]] +
+ lg2.margin_vals['bottomcb'][ss2.rowspan[:-1]]
+ ), maxsubb])
+ for i in ss1.rowspan[1:]:
+ lg1.edit_margin_min('top', maxsubt, cell=i)
+ for i in ss1.rowspan[:-1]:
+ lg1.edit_margin_min('bottom', maxsubb, cell=i)
+
+
+def get_cb_parent_spans(cbax):
+ """
+ Figure out which subplotspecs this colorbar belongs to.
+
+ Parameters
+ ----------
+ cbax : `~matplotlib.axes.Axes`
+ Axes for the colorbar.
+ """
+ rowstart = np.inf
+ rowstop = -np.inf
+ colstart = np.inf
+ colstop = -np.inf
+ for parent in cbax._colorbar_info['parents']:
+ ss = parent.get_subplotspec()
+ rowstart = min(ss.rowspan.start, rowstart)
+ rowstop = max(ss.rowspan.stop, rowstop)
+ colstart = min(ss.colspan.start, colstart)
+ colstop = max(ss.colspan.stop, colstop)
+
+ rowspan = range(rowstart, rowstop)
+ colspan = range(colstart, colstop)
+ return rowspan, colspan
+
+
+def get_pos_and_bbox(ax, renderer):
+ """
+ Get the position and the bbox for the Axes.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass.
+
+ Returns
+ -------
+ pos : `~matplotlib.transforms.Bbox`
+ Position in figure coordinates.
+ bbox : `~matplotlib.transforms.Bbox`
+ Tight bounding box in figure coordinates.
+ """
+ fig = ax.get_figure(root=False)
+ pos = ax.get_position(original=True)
+ # pos is in panel co-ords, but we need in figure for the layout
+ pos = pos.transformed(fig.transSubfigure - fig.transFigure)
+ tightbbox = martist._get_tightbbox_for_layout_only(ax, renderer)
+ if tightbbox is None:
+ bbox = pos
+ else:
+ bbox = tightbbox.transformed(fig.transFigure.inverted())
+ return pos, bbox
+
+
+def reposition_axes(layoutgrids, fig, renderer, *,
+ w_pad=0, h_pad=0, hspace=0, wspace=0):
+ """
+ Reposition all the Axes based on the new inner bounding box.
+ """
+ trans_fig_to_subfig = fig.transFigure - fig.transSubfigure
+ for sfig in fig.subfigs:
+ bbox = layoutgrids[sfig].get_outer_bbox()
+ sfig._redo_transform_rel_fig(
+ bbox=bbox.transformed(trans_fig_to_subfig))
+ reposition_axes(layoutgrids, sfig, renderer,
+ w_pad=w_pad, h_pad=h_pad,
+ wspace=wspace, hspace=hspace)
+
+ for ax in fig._localaxes:
+ if ax.get_subplotspec() is None or not ax.get_in_layout():
+ continue
+
+ # grid bbox is in Figure coordinates, but we specify in panel
+ # coordinates...
+ ss = ax.get_subplotspec()
+ gs = ss.get_gridspec()
+ if gs not in layoutgrids:
+ return
+
+ bbox = layoutgrids[gs].get_inner_bbox(rows=ss.rowspan,
+ cols=ss.colspan)
+
+ # transform from figure to panel for set_position:
+ newbbox = trans_fig_to_subfig.transform_bbox(bbox)
+ ax._set_position(newbbox)
+
+ # move the colorbars:
+ # we need to keep track of oldw and oldh if there is more than
+ # one colorbar:
+ offset = {'left': 0, 'right': 0, 'bottom': 0, 'top': 0}
+ for nn, cbax in enumerate(ax._colorbars[::-1]):
+ if ax == cbax._colorbar_info['parents'][0]:
+ reposition_colorbar(layoutgrids, cbax, renderer,
+ offset=offset)
+
+
+def reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None):
+ """
+ Place the colorbar in its new place.
+
+ Parameters
+ ----------
+ layoutgrids : dict
+ cbax : `~matplotlib.axes.Axes`
+ Axes for the colorbar.
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass.
+ The renderer to use.
+ offset : array-like
+ Offset the colorbar needs to be pushed to in order to
+ account for multiple colorbars.
+ """
+
+ parents = cbax._colorbar_info['parents']
+ gs = parents[0].get_gridspec()
+ fig = cbax.get_figure(root=False)
+ trans_fig_to_subfig = fig.transFigure - fig.transSubfigure
+
+ cb_rspans, cb_cspans = get_cb_parent_spans(cbax)
+ bboxparent = layoutgrids[gs].get_bbox_for_cb(rows=cb_rspans,
+ cols=cb_cspans)
+ pb = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans)
+
+ location = cbax._colorbar_info['location']
+ anchor = cbax._colorbar_info['anchor']
+ fraction = cbax._colorbar_info['fraction']
+ aspect = cbax._colorbar_info['aspect']
+ shrink = cbax._colorbar_info['shrink']
+
+ cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)
+
+ # Colorbar gets put at extreme edge of outer bbox of the subplotspec
+ # It needs to be moved in by: 1) a pad 2) its "margin" 3) by
+ # any colorbars already added at this location:
+ cbpad = colorbar_get_pad(layoutgrids, cbax)
+ if location in ('left', 'right'):
+ # fraction and shrink are fractions of parent
+ pbcb = pb.shrunk(fraction, shrink).anchored(anchor, pb)
+ # The colorbar is at the left side of the parent. Need
+ # to translate to right (or left)
+ if location == 'right':
+ lmargin = cbpos.x0 - cbbbox.x0
+ dx = bboxparent.x1 - pbcb.x0 + offset['right']
+ dx += cbpad + lmargin
+ offset['right'] += cbbbox.width + cbpad
+ pbcb = pbcb.translated(dx, 0)
+ else:
+ lmargin = cbpos.x0 - cbbbox.x0
+ dx = bboxparent.x0 - pbcb.x0 # edge of parent
+ dx += -cbbbox.width - cbpad + lmargin - offset['left']
+ offset['left'] += cbbbox.width + cbpad
+ pbcb = pbcb.translated(dx, 0)
+ else: # horizontal axes:
+ pbcb = pb.shrunk(shrink, fraction).anchored(anchor, pb)
+ if location == 'top':
+ bmargin = cbpos.y0 - cbbbox.y0
+ dy = bboxparent.y1 - pbcb.y0 + offset['top']
+ dy += cbpad + bmargin
+ offset['top'] += cbbbox.height + cbpad
+ pbcb = pbcb.translated(0, dy)
+ else:
+ bmargin = cbpos.y0 - cbbbox.y0
+ dy = bboxparent.y0 - pbcb.y0
+ dy += -cbbbox.height - cbpad + bmargin - offset['bottom']
+ offset['bottom'] += cbbbox.height + cbpad
+ pbcb = pbcb.translated(0, dy)
+
+ pbcb = trans_fig_to_subfig.transform_bbox(pbcb)
+ cbax.set_transform(fig.transSubfigure)
+ cbax._set_position(pbcb)
+ cbax.set_anchor(anchor)
+ if location in ['bottom', 'top']:
+ aspect = 1 / aspect
+ cbax.set_box_aspect(aspect)
+ cbax.set_aspect('auto')
+ return offset
+
+
+def reset_margins(layoutgrids, fig):
+ """
+ Reset the margins in the layoutboxes of *fig*.
+
+ Margins are usually set as a minimum, so if the figure gets smaller
+ the minimum needs to be zero in order for it to grow again.
+ """
+ for sfig in fig.subfigs:
+ reset_margins(layoutgrids, sfig)
+ for ax in fig.axes:
+ if ax.get_in_layout():
+ gs = ax.get_gridspec()
+ if gs in layoutgrids: # also implies gs is not None.
+ layoutgrids[gs].reset_margins()
+ layoutgrids[fig].reset_margins()
+
+
+def colorbar_get_pad(layoutgrids, cax):
+ parents = cax._colorbar_info['parents']
+ gs = parents[0].get_gridspec()
+
+ cb_rspans, cb_cspans = get_cb_parent_spans(cax)
+ bboxouter = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans)
+
+ if cax._colorbar_info['location'] in ['right', 'left']:
+ size = bboxouter.width
+ else:
+ size = bboxouter.height
+
+ return cax._colorbar_info['pad'] * size
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_docstring.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/_docstring.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..fb52d084612399f399e6bcd3f07bca85bb010ba0
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_docstring.pyi
@@ -0,0 +1,34 @@
+from collections.abc import Callable
+from typing import Any, TypeVar, overload
+
+
+_T = TypeVar('_T')
+
+
+def kwarg_doc(text: str) -> Callable[[_T], _T]: ...
+
+
+class Substitution:
+ @overload
+ def __init__(self, *args: str): ...
+ @overload
+ def __init__(self, **kwargs: str): ...
+ def __call__(self, func: _T) -> _T: ...
+ def update(self, *args, **kwargs): ... # type: ignore[no-untyped-def]
+
+
+class _ArtistKwdocLoader(dict[str, str]):
+ def __missing__(self, key: str) -> str: ...
+
+
+class _ArtistPropertiesSubstitution:
+ def __init__(self) -> None: ...
+ def register(self, **kwargs) -> None: ...
+ def __call__(self, obj: _T) -> _T: ...
+
+
+def copy(source: Any) -> Callable[[_T], _T]: ...
+
+
+dedent_interpd: _ArtistPropertiesSubstitution
+interpd: _ArtistPropertiesSubstitution
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_enums.py b/llava_video/lib/python3.10/site-packages/matplotlib/_enums.py
new file mode 100644
index 0000000000000000000000000000000000000000..773011d36bf6f17d0dba073eef6db95924a3d11c
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_enums.py
@@ -0,0 +1,187 @@
+"""
+Enums representing sets of strings that Matplotlib uses as input parameters.
+
+Matplotlib often uses simple data types like strings or tuples to define a
+concept; e.g. the line capstyle can be specified as one of 'butt', 'round',
+or 'projecting'. The classes in this module are used internally and serve to
+document these concepts formally.
+
+As an end-user you will not use these classes directly, but only the values
+they define.
+"""
+
+from enum import Enum, auto
+from matplotlib import _docstring
+
+
+class _AutoStringNameEnum(Enum):
+ """Automate the ``name = 'name'`` part of making a (str, Enum)."""
+
+ def _generate_next_value_(name, start, count, last_values):
+ return name
+
+ def __hash__(self):
+ return str(self).__hash__()
+
+
+class JoinStyle(str, _AutoStringNameEnum):
+ """
+ Define how the connection between two line segments is drawn.
+
+ For a visual impression of each *JoinStyle*, `view these docs online
+ `, or run `JoinStyle.demo`.
+
+ Lines in Matplotlib are typically defined by a 1D `~.path.Path` and a
+ finite ``linewidth``, where the underlying 1D `~.path.Path` represents the
+ center of the stroked line.
+
+ By default, `~.backend_bases.GraphicsContextBase` defines the boundaries of
+ a stroked line to simply be every point within some radius,
+ ``linewidth/2``, away from any point of the center line. However, this
+ results in corners appearing "rounded", which may not be the desired
+ behavior if you are drawing, for example, a polygon or pointed star.
+
+ **Supported values:**
+
+ .. rst-class:: value-list
+
+ 'miter'
+ the "arrow-tip" style. Each boundary of the filled-in area will
+ extend in a straight line parallel to the tangent vector of the
+ centerline at the point it meets the corner, until they meet in a
+ sharp point.
+ 'round'
+ stokes every point within a radius of ``linewidth/2`` of the center
+ lines.
+ 'bevel'
+ the "squared-off" style. It can be thought of as a rounded corner
+ where the "circular" part of the corner has been cut off.
+
+ .. note::
+
+ Very long miter tips are cut off (to form a *bevel*) after a
+ backend-dependent limit called the "miter limit", which specifies the
+ maximum allowed ratio of miter length to line width. For example, the
+ PDF backend uses the default value of 10 specified by the PDF standard,
+ while the SVG backend does not even specify the miter limit, resulting
+ in a default value of 4 per the SVG specification. Matplotlib does not
+ currently allow the user to adjust this parameter.
+
+ A more detailed description of the effect of a miter limit can be found
+ in the `Mozilla Developer Docs
+ `_
+
+ .. plot::
+ :alt: Demo of possible JoinStyle's
+
+ from matplotlib._enums import JoinStyle
+ JoinStyle.demo()
+
+ """
+
+ miter = auto()
+ round = auto()
+ bevel = auto()
+
+ @staticmethod
+ def demo():
+ """Demonstrate how each JoinStyle looks for various join angles."""
+ import numpy as np
+ import matplotlib.pyplot as plt
+
+ def plot_angle(ax, x, y, angle, style):
+ phi = np.radians(angle)
+ xx = [x + .5, x, x + .5*np.cos(phi)]
+ yy = [y, y, y + .5*np.sin(phi)]
+ ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style)
+ ax.plot(xx, yy, lw=1, color='black')
+ ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3)
+
+ fig, ax = plt.subplots(figsize=(5, 4), constrained_layout=True)
+ ax.set_title('Join style')
+ for x, style in enumerate(['miter', 'round', 'bevel']):
+ ax.text(x, 5, style)
+ for y, angle in enumerate([20, 45, 60, 90, 120]):
+ plot_angle(ax, x, y, angle, style)
+ if x == 0:
+ ax.text(-1.3, y, f'{angle} degrees')
+ ax.set_xlim(-1.5, 2.75)
+ ax.set_ylim(-.5, 5.5)
+ ax.set_axis_off()
+ fig.show()
+
+
+JoinStyle.input_description = "{" \
+ + ", ".join([f"'{js.name}'" for js in JoinStyle]) \
+ + "}"
+
+
+class CapStyle(str, _AutoStringNameEnum):
+ r"""
+ Define how the two endpoints (caps) of an unclosed line are drawn.
+
+ How to draw the start and end points of lines that represent a closed curve
+ (i.e. that end in a `~.path.Path.CLOSEPOLY`) is controlled by the line's
+ `JoinStyle`. For all other lines, how the start and end points are drawn is
+ controlled by the *CapStyle*.
+
+ For a visual impression of each *CapStyle*, `view these docs online
+ ` or run `CapStyle.demo`.
+
+ By default, `~.backend_bases.GraphicsContextBase` draws a stroked line as
+ squared off at its endpoints.
+
+ **Supported values:**
+
+ .. rst-class:: value-list
+
+ 'butt'
+ the line is squared off at its endpoint.
+ 'projecting'
+ the line is squared off as in *butt*, but the filled in area
+ extends beyond the endpoint a distance of ``linewidth/2``.
+ 'round'
+ like *butt*, but a semicircular cap is added to the end of the
+ line, of radius ``linewidth/2``.
+
+ .. plot::
+ :alt: Demo of possible CapStyle's
+
+ from matplotlib._enums import CapStyle
+ CapStyle.demo()
+
+ """
+ butt = auto()
+ projecting = auto()
+ round = auto()
+
+ @staticmethod
+ def demo():
+ """Demonstrate how each CapStyle looks for a thick line segment."""
+ import matplotlib.pyplot as plt
+
+ fig = plt.figure(figsize=(4, 1.2))
+ ax = fig.add_axes([0, 0, 1, 0.8])
+ ax.set_title('Cap style')
+
+ for x, style in enumerate(['butt', 'round', 'projecting']):
+ ax.text(x+0.25, 0.85, style, ha='center')
+ xx = [x, x+0.5]
+ yy = [0, 0]
+ ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style)
+ ax.plot(xx, yy, lw=1, color='black')
+ ax.plot(xx, yy, 'o', color='tab:red', markersize=3)
+
+ ax.set_ylim(-.5, 1.5)
+ ax.set_axis_off()
+ fig.show()
+
+
+CapStyle.input_description = "{" \
+ + ", ".join([f"'{cs.name}'" for cs in CapStyle]) \
+ + "}"
+
+_docstring.interpd.register(
+ JoinStyle=JoinStyle.input_description,
+ CapStyle=CapStyle.input_description,
+)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so b/llava_video/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..889540ceb1096e5290a091f61ea013557bc2c25e
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d4f3443d50b91c2f8722796f76e9b816440151bb78367173091c9fab480a24da
+size 555016
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_internal_utils.py b/llava_video/lib/python3.10/site-packages/matplotlib/_internal_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0223aa593bb2cb20b58f2b9e41bdc0dfa5ceed35
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_internal_utils.py
@@ -0,0 +1,64 @@
+"""
+Internal debugging utilities, that are not expected to be used in the rest of
+the codebase.
+
+WARNING: Code in this module may change without prior notice!
+"""
+
+from io import StringIO
+from pathlib import Path
+import subprocess
+
+from matplotlib.transforms import TransformNode
+
+
+def graphviz_dump_transform(transform, dest, *, highlight=None):
+ """
+ Generate a graphical representation of the transform tree for *transform*
+ using the :program:`dot` program (which this function depends on). The
+ output format (png, dot, etc.) is determined from the suffix of *dest*.
+
+ Parameters
+ ----------
+ transform : `~matplotlib.transform.Transform`
+ The represented transform.
+ dest : str
+ Output filename. The extension must be one of the formats supported
+ by :program:`dot`, e.g. png, svg, dot, ...
+ (see https://www.graphviz.org/doc/info/output.html).
+ highlight : list of `~matplotlib.transform.Transform` or None
+ The transforms in the tree to be drawn in bold.
+ If *None*, *transform* is highlighted.
+ """
+
+ if highlight is None:
+ highlight = [transform]
+ seen = set()
+
+ def recurse(root, buf):
+ if id(root) in seen:
+ return
+ seen.add(id(root))
+ props = {}
+ label = type(root).__name__
+ if root._invalid:
+ label = f'[{label}]'
+ if root in highlight:
+ props['style'] = 'bold'
+ props['shape'] = 'box'
+ props['label'] = '"%s"' % label
+ props = ' '.join(map('{0[0]}={0[1]}'.format, props.items()))
+ buf.write(f'{id(root)} [{props}];\n')
+ for key, val in vars(root).items():
+ if isinstance(val, TransformNode) and id(root) in val._parents:
+ buf.write(f'"{id(root)}" -> "{id(val)}" '
+ f'[label="{key}", fontsize=10];\n')
+ recurse(val, buf)
+
+ buf = StringIO()
+ buf.write('digraph G {\n')
+ recurse(transform, buf)
+ buf.write('}\n')
+ subprocess.run(
+ ['dot', '-T', Path(dest).suffix[1:], '-o', dest],
+ input=buf.getvalue().encode('utf-8'), check=True)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_layoutgrid.py b/llava_video/lib/python3.10/site-packages/matplotlib/_layoutgrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f81b14765b68fa1f7480c3d34ba74245e39b84f
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_layoutgrid.py
@@ -0,0 +1,547 @@
+"""
+A layoutgrid is a nrows by ncols set of boxes, meant to be used by
+`._constrained_layout`, each box is analogous to a subplotspec element of
+a gridspec.
+
+Each box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows],
+and by two editable margins for each side. The main margin gets its value
+set by the size of ticklabels, titles, etc on each Axes that is in the figure.
+The outer margin is the padding around the Axes, and space for any
+colorbars.
+
+The "inner" widths and heights of these boxes are then constrained to be the
+same (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`).
+
+The layoutgrid is then constrained to be contained within a parent layoutgrid,
+its column(s) and row(s) specified when it is created.
+"""
+
+import itertools
+import kiwisolver as kiwi
+import logging
+import numpy as np
+
+import matplotlib as mpl
+import matplotlib.patches as mpatches
+from matplotlib.transforms import Bbox
+
+_log = logging.getLogger(__name__)
+
+
+class LayoutGrid:
+ """
+ Analogous to a gridspec, and contained in another LayoutGrid.
+ """
+
+ def __init__(self, parent=None, parent_pos=(0, 0),
+ parent_inner=False, name='', ncols=1, nrows=1,
+ h_pad=None, w_pad=None, width_ratios=None,
+ height_ratios=None):
+ Variable = kiwi.Variable
+ self.parent_pos = parent_pos
+ self.parent_inner = parent_inner
+ self.name = name + seq_id()
+ if isinstance(parent, LayoutGrid):
+ self.name = f'{parent.name}.{self.name}'
+ self.nrows = nrows
+ self.ncols = ncols
+ self.height_ratios = np.atleast_1d(height_ratios)
+ if height_ratios is None:
+ self.height_ratios = np.ones(nrows)
+ self.width_ratios = np.atleast_1d(width_ratios)
+ if width_ratios is None:
+ self.width_ratios = np.ones(ncols)
+
+ sn = self.name + '_'
+ if not isinstance(parent, LayoutGrid):
+ # parent can be a rect if not a LayoutGrid
+ # allows specifying a rectangle to contain the layout.
+ self.solver = kiwi.Solver()
+ else:
+ parent.add_child(self, *parent_pos)
+ self.solver = parent.solver
+ # keep track of artist associated w/ this layout. Can be none
+ self.artists = np.empty((nrows, ncols), dtype=object)
+ self.children = np.empty((nrows, ncols), dtype=object)
+
+ self.margins = {}
+ self.margin_vals = {}
+ # all the boxes in each column share the same left/right margins:
+ for todo in ['left', 'right', 'leftcb', 'rightcb']:
+ # track the value so we can change only if a margin is larger
+ # than the current value
+ self.margin_vals[todo] = np.zeros(ncols)
+
+ sol = self.solver
+
+ self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)]
+ self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)]
+ for todo in ['left', 'right', 'leftcb', 'rightcb']:
+ self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
+ for i in range(ncols)]
+ for i in range(ncols):
+ sol.addEditVariable(self.margins[todo][i], 'strong')
+
+ for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
+ self.margins[todo] = np.empty((nrows), dtype=object)
+ self.margin_vals[todo] = np.zeros(nrows)
+
+ self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)]
+ self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)]
+ for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
+ self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
+ for i in range(nrows)]
+ for i in range(nrows):
+ sol.addEditVariable(self.margins[todo][i], 'strong')
+
+ # set these margins to zero by default. They will be edited as
+ # children are filled.
+ self.reset_margins()
+ self.add_constraints(parent)
+
+ self.h_pad = h_pad
+ self.w_pad = w_pad
+
+ def __repr__(self):
+ str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n'
+ for i in range(self.nrows):
+ for j in range(self.ncols):
+ str += f'{i}, {j}: '\
+ f'L{self.lefts[j].value():1.3f}, ' \
+ f'B{self.bottoms[i].value():1.3f}, ' \
+ f'R{self.rights[j].value():1.3f}, ' \
+ f'T{self.tops[i].value():1.3f}, ' \
+ f'ML{self.margins["left"][j].value():1.3f}, ' \
+ f'MR{self.margins["right"][j].value():1.3f}, ' \
+ f'MB{self.margins["bottom"][i].value():1.3f}, ' \
+ f'MT{self.margins["top"][i].value():1.3f}, \n'
+ return str
+
+ def reset_margins(self):
+ """
+ Reset all the margins to zero. Must do this after changing
+ figure size, for instance, because the relative size of the
+ axes labels etc changes.
+ """
+ for todo in ['left', 'right', 'bottom', 'top',
+ 'leftcb', 'rightcb', 'bottomcb', 'topcb']:
+ self.edit_margins(todo, 0.0)
+
+ def add_constraints(self, parent):
+ # define self-consistent constraints
+ self.hard_constraints()
+ # define relationship with parent layoutgrid:
+ self.parent_constraints(parent)
+ # define relative widths of the grid cells to each other
+ # and stack horizontally and vertically.
+ self.grid_constraints()
+
+ def hard_constraints(self):
+ """
+ These are the redundant constraints, plus ones that make the
+ rest of the code easier.
+ """
+ for i in range(self.ncols):
+ hc = [self.rights[i] >= self.lefts[i],
+ (self.rights[i] - self.margins['right'][i] -
+ self.margins['rightcb'][i] >=
+ self.lefts[i] - self.margins['left'][i] -
+ self.margins['leftcb'][i])
+ ]
+ for c in hc:
+ self.solver.addConstraint(c | 'required')
+
+ for i in range(self.nrows):
+ hc = [self.tops[i] >= self.bottoms[i],
+ (self.tops[i] - self.margins['top'][i] -
+ self.margins['topcb'][i] >=
+ self.bottoms[i] - self.margins['bottom'][i] -
+ self.margins['bottomcb'][i])
+ ]
+ for c in hc:
+ self.solver.addConstraint(c | 'required')
+
+ def add_child(self, child, i=0, j=0):
+ # np.ix_ returns the cross product of i and j indices
+ self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child
+
+ def parent_constraints(self, parent):
+ # constraints that are due to the parent...
+ # i.e. the first column's left is equal to the
+ # parent's left, the last column right equal to the
+ # parent's right...
+ if not isinstance(parent, LayoutGrid):
+ # specify a rectangle in figure coordinates
+ hc = [self.lefts[0] == parent[0],
+ self.rights[-1] == parent[0] + parent[2],
+ # top and bottom reversed order...
+ self.tops[0] == parent[1] + parent[3],
+ self.bottoms[-1] == parent[1]]
+ else:
+ rows, cols = self.parent_pos
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ left = parent.lefts[cols[0]]
+ right = parent.rights[cols[-1]]
+ top = parent.tops[rows[0]]
+ bottom = parent.bottoms[rows[-1]]
+ if self.parent_inner:
+ # the layout grid is contained inside the inner
+ # grid of the parent.
+ left += parent.margins['left'][cols[0]]
+ left += parent.margins['leftcb'][cols[0]]
+ right -= parent.margins['right'][cols[-1]]
+ right -= parent.margins['rightcb'][cols[-1]]
+ top -= parent.margins['top'][rows[0]]
+ top -= parent.margins['topcb'][rows[0]]
+ bottom += parent.margins['bottom'][rows[-1]]
+ bottom += parent.margins['bottomcb'][rows[-1]]
+ hc = [self.lefts[0] == left,
+ self.rights[-1] == right,
+ # from top to bottom
+ self.tops[0] == top,
+ self.bottoms[-1] == bottom]
+ for c in hc:
+ self.solver.addConstraint(c | 'required')
+
+ def grid_constraints(self):
+ # constrain the ratio of the inner part of the grids
+ # to be the same (relative to width_ratios)
+
+ # constrain widths:
+ w = (self.rights[0] - self.margins['right'][0] -
+ self.margins['rightcb'][0])
+ w = (w - self.lefts[0] - self.margins['left'][0] -
+ self.margins['leftcb'][0])
+ w0 = w / self.width_ratios[0]
+ # from left to right
+ for i in range(1, self.ncols):
+ w = (self.rights[i] - self.margins['right'][i] -
+ self.margins['rightcb'][i])
+ w = (w - self.lefts[i] - self.margins['left'][i] -
+ self.margins['leftcb'][i])
+ c = (w == w0 * self.width_ratios[i])
+ self.solver.addConstraint(c | 'strong')
+ # constrain the grid cells to be directly next to each other.
+ c = (self.rights[i - 1] == self.lefts[i])
+ self.solver.addConstraint(c | 'strong')
+
+ # constrain heights:
+ h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0]
+ h = (h - self.bottoms[0] - self.margins['bottom'][0] -
+ self.margins['bottomcb'][0])
+ h0 = h / self.height_ratios[0]
+ # from top to bottom:
+ for i in range(1, self.nrows):
+ h = (self.tops[i] - self.margins['top'][i] -
+ self.margins['topcb'][i])
+ h = (h - self.bottoms[i] - self.margins['bottom'][i] -
+ self.margins['bottomcb'][i])
+ c = (h == h0 * self.height_ratios[i])
+ self.solver.addConstraint(c | 'strong')
+ # constrain the grid cells to be directly above each other.
+ c = (self.bottoms[i - 1] == self.tops[i])
+ self.solver.addConstraint(c | 'strong')
+
+ # Margin editing: The margins are variable and meant to
+ # contain things of a fixed size like axes labels, tick labels, titles
+ # etc
+ def edit_margin(self, todo, size, cell):
+ """
+ Change the size of the margin for one cell.
+
+ Parameters
+ ----------
+ todo : string (one of 'left', 'right', 'bottom', 'top')
+ margin to alter.
+
+ size : float
+ Size of the margin. If it is larger than the existing minimum it
+ updates the margin size. Fraction of figure size.
+
+ cell : int
+ Cell column or row to edit.
+ """
+ self.solver.suggestValue(self.margins[todo][cell], size)
+ self.margin_vals[todo][cell] = size
+
+ def edit_margin_min(self, todo, size, cell=0):
+ """
+ Change the minimum size of the margin for one cell.
+
+ Parameters
+ ----------
+ todo : string (one of 'left', 'right', 'bottom', 'top')
+ margin to alter.
+
+ size : float
+ Minimum size of the margin . If it is larger than the
+ existing minimum it updates the margin size. Fraction of
+ figure size.
+
+ cell : int
+ Cell column or row to edit.
+ """
+
+ if size > self.margin_vals[todo][cell]:
+ self.edit_margin(todo, size, cell)
+
+ def edit_margins(self, todo, size):
+ """
+ Change the size of all the margin of all the cells in the layout grid.
+
+ Parameters
+ ----------
+ todo : string (one of 'left', 'right', 'bottom', 'top')
+ margin to alter.
+
+ size : float
+ Size to set the margins. Fraction of figure size.
+ """
+
+ for i in range(len(self.margin_vals[todo])):
+ self.edit_margin(todo, size, i)
+
+ def edit_all_margins_min(self, todo, size):
+ """
+ Change the minimum size of all the margin of all
+ the cells in the layout grid.
+
+ Parameters
+ ----------
+ todo : {'left', 'right', 'bottom', 'top'}
+ The margin to alter.
+
+ size : float
+ Minimum size of the margin. If it is larger than the
+ existing minimum it updates the margin size. Fraction of
+ figure size.
+ """
+
+ for i in range(len(self.margin_vals[todo])):
+ self.edit_margin_min(todo, size, i)
+
+ def edit_outer_margin_mins(self, margin, ss):
+ """
+ Edit all four margin minimums in one statement.
+
+ Parameters
+ ----------
+ margin : dict
+ size of margins in a dict with keys 'left', 'right', 'bottom',
+ 'top'
+
+ ss : SubplotSpec
+ defines the subplotspec these margins should be applied to
+ """
+
+ self.edit_margin_min('left', margin['left'], ss.colspan.start)
+ self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start)
+ self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1)
+ self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1)
+ # rows are from the top down:
+ self.edit_margin_min('top', margin['top'], ss.rowspan.start)
+ self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start)
+ self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1)
+ self.edit_margin_min('bottomcb', margin['bottomcb'],
+ ss.rowspan.stop - 1)
+
+ def get_margins(self, todo, col):
+ """Return the margin at this position"""
+ return self.margin_vals[todo][col]
+
+ def get_outer_bbox(self, rows=0, cols=0):
+ """
+ Return the outer bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ self.lefts[cols[0]].value(),
+ self.bottoms[rows[-1]].value(),
+ self.rights[cols[-1]].value(),
+ self.tops[rows[0]].value())
+ return bbox
+
+ def get_inner_bbox(self, rows=0, cols=0):
+ """
+ Return the inner bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value() +
+ self.margins['left'][cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottom'][rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()),
+ (self.rights[cols[-1]].value() -
+ self.margins['right'][cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['top'][rows[0]].value() -
+ self.margins['topcb'][rows[0]].value())
+ )
+ return bbox
+
+ def get_bbox_for_cb(self, rows=0, cols=0):
+ """
+ Return the bounding box that includes the
+ decorations but, *not* the colorbar...
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()),
+ (self.rights[cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['topcb'][rows[0]].value())
+ )
+ return bbox
+
+ def get_left_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value()),
+ (self.bottoms[rows[-1]].value()),
+ (self.lefts[cols[0]].value() +
+ self.margins['leftcb'][cols[0]].value() +
+ self.margins['left'][cols[0]].value()),
+ (self.tops[rows[0]].value()))
+ return bbox
+
+ def get_bottom_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()),
+ (self.rights[cols[-1]].value()),
+ (self.bottoms[rows[-1]].value() +
+ self.margins['bottom'][rows[-1]].value() +
+ self.margins['bottomcb'][rows[-1]].value()
+ ))
+ return bbox
+
+ def get_right_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.rights[cols[-1]].value() -
+ self.margins['right'][cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.bottoms[rows[-1]].value()),
+ (self.rights[cols[-1]].value() -
+ self.margins['rightcb'][cols[-1]].value()),
+ (self.tops[rows[0]].value()))
+ return bbox
+
+ def get_top_margin_bbox(self, rows=0, cols=0):
+ """
+ Return the left margin bounding box of the subplot specs
+ given by rows and cols. rows and cols can be spans.
+ """
+ rows = np.atleast_1d(rows)
+ cols = np.atleast_1d(cols)
+
+ bbox = Bbox.from_extents(
+ (self.lefts[cols[0]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['topcb'][rows[0]].value()),
+ (self.rights[cols[-1]].value()),
+ (self.tops[rows[0]].value() -
+ self.margins['topcb'][rows[0]].value() -
+ self.margins['top'][rows[0]].value()))
+ return bbox
+
+ def update_variables(self):
+ """
+ Update the variables for the solver attached to this layoutgrid.
+ """
+ self.solver.updateVariables()
+
+_layoutboxobjnum = itertools.count()
+
+
+def seq_id():
+ """Generate a short sequential id for layoutbox objects."""
+ return '%06d' % next(_layoutboxobjnum)
+
+
+def plot_children(fig, lg=None, level=0):
+ """Simple plotting to show where boxes are."""
+ if lg is None:
+ _layoutgrids = fig.get_layout_engine().execute(fig)
+ lg = _layoutgrids[fig]
+ colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"]
+ col = colors[level]
+ for i in range(lg.nrows):
+ for j in range(lg.ncols):
+ bb = lg.get_outer_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1,
+ edgecolor='0.7', facecolor='0.7',
+ alpha=0.2, transform=fig.transFigure,
+ zorder=-3))
+ bbi = lg.get_inner_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2,
+ edgecolor=col, facecolor='none',
+ transform=fig.transFigure, zorder=-2))
+
+ bbi = lg.get_left_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.5, 0.7, 0.5],
+ transform=fig.transFigure, zorder=-2))
+ bbi = lg.get_right_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.7, 0.5, 0.5],
+ transform=fig.transFigure, zorder=-2))
+ bbi = lg.get_bottom_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.5, 0.5, 0.7],
+ transform=fig.transFigure, zorder=-2))
+ bbi = lg.get_top_margin_bbox(rows=i, cols=j)
+ fig.add_artist(
+ mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
+ edgecolor='none', alpha=0.2,
+ facecolor=[0.7, 0.2, 0.7],
+ transform=fig.transFigure, zorder=-2))
+ for ch in lg.children.flat:
+ if ch is not None:
+ plot_children(fig, ch, level=level+1)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_mathtext_data.py b/llava_video/lib/python3.10/site-packages/matplotlib/_mathtext_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..5819ee7430447f9ef5f6e760b65cdd5933ef9395
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_mathtext_data.py
@@ -0,0 +1,1742 @@
+"""
+font data tables for truetype and afm computer modern fonts
+"""
+
+from __future__ import annotations
+from typing import overload
+
+latex_to_bakoma = {
+ '\\__sqrt__' : ('cmex10', 0x70),
+ '\\bigcap' : ('cmex10', 0x5c),
+ '\\bigcup' : ('cmex10', 0x5b),
+ '\\bigodot' : ('cmex10', 0x4b),
+ '\\bigoplus' : ('cmex10', 0x4d),
+ '\\bigotimes' : ('cmex10', 0x4f),
+ '\\biguplus' : ('cmex10', 0x5d),
+ '\\bigvee' : ('cmex10', 0x5f),
+ '\\bigwedge' : ('cmex10', 0x5e),
+ '\\coprod' : ('cmex10', 0x61),
+ '\\int' : ('cmex10', 0x5a),
+ '\\langle' : ('cmex10', 0xad),
+ '\\leftangle' : ('cmex10', 0xad),
+ '\\leftbrace' : ('cmex10', 0xa9),
+ '\\oint' : ('cmex10', 0x49),
+ '\\prod' : ('cmex10', 0x59),
+ '\\rangle' : ('cmex10', 0xae),
+ '\\rightangle' : ('cmex10', 0xae),
+ '\\rightbrace' : ('cmex10', 0xaa),
+ '\\sum' : ('cmex10', 0x58),
+ '\\widehat' : ('cmex10', 0x62),
+ '\\widetilde' : ('cmex10', 0x65),
+ '\\{' : ('cmex10', 0xa9),
+ '\\}' : ('cmex10', 0xaa),
+ '{' : ('cmex10', 0xa9),
+ '}' : ('cmex10', 0xaa),
+
+ ',' : ('cmmi10', 0x3b),
+ '.' : ('cmmi10', 0x3a),
+ '/' : ('cmmi10', 0x3d),
+ '<' : ('cmmi10', 0x3c),
+ '>' : ('cmmi10', 0x3e),
+ '\\alpha' : ('cmmi10', 0xae),
+ '\\beta' : ('cmmi10', 0xaf),
+ '\\chi' : ('cmmi10', 0xc2),
+ '\\combiningrightarrowabove' : ('cmmi10', 0x7e),
+ '\\delta' : ('cmmi10', 0xb1),
+ '\\ell' : ('cmmi10', 0x60),
+ '\\epsilon' : ('cmmi10', 0xb2),
+ '\\eta' : ('cmmi10', 0xb4),
+ '\\flat' : ('cmmi10', 0x5b),
+ '\\frown' : ('cmmi10', 0x5f),
+ '\\gamma' : ('cmmi10', 0xb0),
+ '\\imath' : ('cmmi10', 0x7b),
+ '\\iota' : ('cmmi10', 0xb6),
+ '\\jmath' : ('cmmi10', 0x7c),
+ '\\kappa' : ('cmmi10', 0x2219),
+ '\\lambda' : ('cmmi10', 0xb8),
+ '\\leftharpoondown' : ('cmmi10', 0x29),
+ '\\leftharpoonup' : ('cmmi10', 0x28),
+ '\\mu' : ('cmmi10', 0xb9),
+ '\\natural' : ('cmmi10', 0x5c),
+ '\\nu' : ('cmmi10', 0xba),
+ '\\omega' : ('cmmi10', 0x21),
+ '\\phi' : ('cmmi10', 0xc1),
+ '\\pi' : ('cmmi10', 0xbc),
+ '\\psi' : ('cmmi10', 0xc3),
+ '\\rho' : ('cmmi10', 0xbd),
+ '\\rightharpoondown' : ('cmmi10', 0x2b),
+ '\\rightharpoonup' : ('cmmi10', 0x2a),
+ '\\sharp' : ('cmmi10', 0x5d),
+ '\\sigma' : ('cmmi10', 0xbe),
+ '\\smile' : ('cmmi10', 0x5e),
+ '\\tau' : ('cmmi10', 0xbf),
+ '\\theta' : ('cmmi10', 0xb5),
+ '\\triangleleft' : ('cmmi10', 0x2f),
+ '\\triangleright' : ('cmmi10', 0x2e),
+ '\\upsilon' : ('cmmi10', 0xc0),
+ '\\varepsilon' : ('cmmi10', 0x22),
+ '\\varphi' : ('cmmi10', 0x27),
+ '\\varrho' : ('cmmi10', 0x25),
+ '\\varsigma' : ('cmmi10', 0x26),
+ '\\vartheta' : ('cmmi10', 0x23),
+ '\\wp' : ('cmmi10', 0x7d),
+ '\\xi' : ('cmmi10', 0xbb),
+ '\\zeta' : ('cmmi10', 0xb3),
+
+ '!' : ('cmr10', 0x21),
+ '%' : ('cmr10', 0x25),
+ '&' : ('cmr10', 0x26),
+ '(' : ('cmr10', 0x28),
+ ')' : ('cmr10', 0x29),
+ '+' : ('cmr10', 0x2b),
+ '0' : ('cmr10', 0x30),
+ '1' : ('cmr10', 0x31),
+ '2' : ('cmr10', 0x32),
+ '3' : ('cmr10', 0x33),
+ '4' : ('cmr10', 0x34),
+ '5' : ('cmr10', 0x35),
+ '6' : ('cmr10', 0x36),
+ '7' : ('cmr10', 0x37),
+ '8' : ('cmr10', 0x38),
+ '9' : ('cmr10', 0x39),
+ ':' : ('cmr10', 0x3a),
+ ';' : ('cmr10', 0x3b),
+ '=' : ('cmr10', 0x3d),
+ '?' : ('cmr10', 0x3f),
+ '@' : ('cmr10', 0x40),
+ '[' : ('cmr10', 0x5b),
+ '\\#' : ('cmr10', 0x23),
+ '\\$' : ('cmr10', 0x24),
+ '\\%' : ('cmr10', 0x25),
+ '\\Delta' : ('cmr10', 0xa2),
+ '\\Gamma' : ('cmr10', 0xa1),
+ '\\Lambda' : ('cmr10', 0xa4),
+ '\\Omega' : ('cmr10', 0xad),
+ '\\Phi' : ('cmr10', 0xa9),
+ '\\Pi' : ('cmr10', 0xa6),
+ '\\Psi' : ('cmr10', 0xaa),
+ '\\Sigma' : ('cmr10', 0xa7),
+ '\\Theta' : ('cmr10', 0xa3),
+ '\\Upsilon' : ('cmr10', 0xa8),
+ '\\Xi' : ('cmr10', 0xa5),
+ '\\circumflexaccent' : ('cmr10', 0x5e),
+ '\\combiningacuteaccent' : ('cmr10', 0xb6),
+ '\\combiningbreve' : ('cmr10', 0xb8),
+ '\\combiningdiaeresis' : ('cmr10', 0xc4),
+ '\\combiningdotabove' : ('cmr10', 0x5f),
+ '\\combininggraveaccent' : ('cmr10', 0xb5),
+ '\\combiningoverline' : ('cmr10', 0xb9),
+ '\\combiningtilde' : ('cmr10', 0x7e),
+ '\\leftbracket' : ('cmr10', 0x5b),
+ '\\leftparen' : ('cmr10', 0x28),
+ '\\rightbracket' : ('cmr10', 0x5d),
+ '\\rightparen' : ('cmr10', 0x29),
+ '\\widebar' : ('cmr10', 0xb9),
+ ']' : ('cmr10', 0x5d),
+
+ '*' : ('cmsy10', 0xa4),
+ '\N{MINUS SIGN}' : ('cmsy10', 0xa1),
+ '\\Downarrow' : ('cmsy10', 0x2b),
+ '\\Im' : ('cmsy10', 0x3d),
+ '\\Leftarrow' : ('cmsy10', 0x28),
+ '\\Leftrightarrow' : ('cmsy10', 0x2c),
+ '\\P' : ('cmsy10', 0x7b),
+ '\\Re' : ('cmsy10', 0x3c),
+ '\\Rightarrow' : ('cmsy10', 0x29),
+ '\\S' : ('cmsy10', 0x78),
+ '\\Uparrow' : ('cmsy10', 0x2a),
+ '\\Updownarrow' : ('cmsy10', 0x6d),
+ '\\Vert' : ('cmsy10', 0x6b),
+ '\\aleph' : ('cmsy10', 0x40),
+ '\\approx' : ('cmsy10', 0xbc),
+ '\\ast' : ('cmsy10', 0xa4),
+ '\\asymp' : ('cmsy10', 0xb3),
+ '\\backslash' : ('cmsy10', 0x6e),
+ '\\bigcirc' : ('cmsy10', 0xb0),
+ '\\bigtriangledown' : ('cmsy10', 0x35),
+ '\\bigtriangleup' : ('cmsy10', 0x34),
+ '\\bot' : ('cmsy10', 0x3f),
+ '\\bullet' : ('cmsy10', 0xb2),
+ '\\cap' : ('cmsy10', 0x5c),
+ '\\cdot' : ('cmsy10', 0xa2),
+ '\\circ' : ('cmsy10', 0xb1),
+ '\\clubsuit' : ('cmsy10', 0x7c),
+ '\\cup' : ('cmsy10', 0x5b),
+ '\\dag' : ('cmsy10', 0x79),
+ '\\dashv' : ('cmsy10', 0x61),
+ '\\ddag' : ('cmsy10', 0x7a),
+ '\\diamond' : ('cmsy10', 0xa6),
+ '\\diamondsuit' : ('cmsy10', 0x7d),
+ '\\div' : ('cmsy10', 0xa5),
+ '\\downarrow' : ('cmsy10', 0x23),
+ '\\emptyset' : ('cmsy10', 0x3b),
+ '\\equiv' : ('cmsy10', 0xb4),
+ '\\exists' : ('cmsy10', 0x39),
+ '\\forall' : ('cmsy10', 0x38),
+ '\\geq' : ('cmsy10', 0xb8),
+ '\\gg' : ('cmsy10', 0xc0),
+ '\\heartsuit' : ('cmsy10', 0x7e),
+ '\\in' : ('cmsy10', 0x32),
+ '\\infty' : ('cmsy10', 0x31),
+ '\\lbrace' : ('cmsy10', 0x66),
+ '\\lceil' : ('cmsy10', 0x64),
+ '\\leftarrow' : ('cmsy10', 0xc3),
+ '\\leftrightarrow' : ('cmsy10', 0x24),
+ '\\leq' : ('cmsy10', 0x2219),
+ '\\lfloor' : ('cmsy10', 0x62),
+ '\\ll' : ('cmsy10', 0xbf),
+ '\\mid' : ('cmsy10', 0x6a),
+ '\\mp' : ('cmsy10', 0xa8),
+ '\\nabla' : ('cmsy10', 0x72),
+ '\\nearrow' : ('cmsy10', 0x25),
+ '\\neg' : ('cmsy10', 0x3a),
+ '\\ni' : ('cmsy10', 0x33),
+ '\\nwarrow' : ('cmsy10', 0x2d),
+ '\\odot' : ('cmsy10', 0xaf),
+ '\\ominus' : ('cmsy10', 0xaa),
+ '\\oplus' : ('cmsy10', 0xa9),
+ '\\oslash' : ('cmsy10', 0xae),
+ '\\otimes' : ('cmsy10', 0xad),
+ '\\pm' : ('cmsy10', 0xa7),
+ '\\prec' : ('cmsy10', 0xc1),
+ '\\preceq' : ('cmsy10', 0xb9),
+ '\\prime' : ('cmsy10', 0x30),
+ '\\propto' : ('cmsy10', 0x2f),
+ '\\rbrace' : ('cmsy10', 0x67),
+ '\\rceil' : ('cmsy10', 0x65),
+ '\\rfloor' : ('cmsy10', 0x63),
+ '\\rightarrow' : ('cmsy10', 0x21),
+ '\\searrow' : ('cmsy10', 0x26),
+ '\\sim' : ('cmsy10', 0xbb),
+ '\\simeq' : ('cmsy10', 0x27),
+ '\\slash' : ('cmsy10', 0x36),
+ '\\spadesuit' : ('cmsy10', 0xc4),
+ '\\sqcap' : ('cmsy10', 0x75),
+ '\\sqcup' : ('cmsy10', 0x74),
+ '\\sqsubseteq' : ('cmsy10', 0x76),
+ '\\sqsupseteq' : ('cmsy10', 0x77),
+ '\\subset' : ('cmsy10', 0xbd),
+ '\\subseteq' : ('cmsy10', 0xb5),
+ '\\succ' : ('cmsy10', 0xc2),
+ '\\succeq' : ('cmsy10', 0xba),
+ '\\supset' : ('cmsy10', 0xbe),
+ '\\supseteq' : ('cmsy10', 0xb6),
+ '\\swarrow' : ('cmsy10', 0x2e),
+ '\\times' : ('cmsy10', 0xa3),
+ '\\to' : ('cmsy10', 0x21),
+ '\\top' : ('cmsy10', 0x3e),
+ '\\uparrow' : ('cmsy10', 0x22),
+ '\\updownarrow' : ('cmsy10', 0x6c),
+ '\\uplus' : ('cmsy10', 0x5d),
+ '\\vdash' : ('cmsy10', 0x60),
+ '\\vee' : ('cmsy10', 0x5f),
+ '\\vert' : ('cmsy10', 0x6a),
+ '\\wedge' : ('cmsy10', 0x5e),
+ '\\wr' : ('cmsy10', 0x6f),
+ '\\|' : ('cmsy10', 0x6b),
+ '|' : ('cmsy10', 0x6a),
+
+ '\\_' : ('cmtt10', 0x5f)
+}
+
+# Automatically generated.
+
+type12uni = {
+ 'aring' : 229,
+ 'quotedblright' : 8221,
+ 'V' : 86,
+ 'dollar' : 36,
+ 'four' : 52,
+ 'Yacute' : 221,
+ 'P' : 80,
+ 'underscore' : 95,
+ 'p' : 112,
+ 'Otilde' : 213,
+ 'perthousand' : 8240,
+ 'zero' : 48,
+ 'dotlessi' : 305,
+ 'Scaron' : 352,
+ 'zcaron' : 382,
+ 'egrave' : 232,
+ 'section' : 167,
+ 'Icircumflex' : 206,
+ 'ntilde' : 241,
+ 'ampersand' : 38,
+ 'dotaccent' : 729,
+ 'degree' : 176,
+ 'K' : 75,
+ 'acircumflex' : 226,
+ 'Aring' : 197,
+ 'k' : 107,
+ 'smalltilde' : 732,
+ 'Agrave' : 192,
+ 'divide' : 247,
+ 'ocircumflex' : 244,
+ 'asciitilde' : 126,
+ 'two' : 50,
+ 'E' : 69,
+ 'scaron' : 353,
+ 'F' : 70,
+ 'bracketleft' : 91,
+ 'asciicircum' : 94,
+ 'f' : 102,
+ 'ordmasculine' : 186,
+ 'mu' : 181,
+ 'paragraph' : 182,
+ 'nine' : 57,
+ 'v' : 118,
+ 'guilsinglleft' : 8249,
+ 'backslash' : 92,
+ 'six' : 54,
+ 'A' : 65,
+ 'icircumflex' : 238,
+ 'a' : 97,
+ 'ogonek' : 731,
+ 'q' : 113,
+ 'oacute' : 243,
+ 'ograve' : 242,
+ 'edieresis' : 235,
+ 'comma' : 44,
+ 'otilde' : 245,
+ 'guillemotright' : 187,
+ 'ecircumflex' : 234,
+ 'greater' : 62,
+ 'uacute' : 250,
+ 'L' : 76,
+ 'bullet' : 8226,
+ 'cedilla' : 184,
+ 'ydieresis' : 255,
+ 'l' : 108,
+ 'logicalnot' : 172,
+ 'exclamdown' : 161,
+ 'endash' : 8211,
+ 'agrave' : 224,
+ 'Adieresis' : 196,
+ 'germandbls' : 223,
+ 'Odieresis' : 214,
+ 'space' : 32,
+ 'quoteright' : 8217,
+ 'ucircumflex' : 251,
+ 'G' : 71,
+ 'quoteleft' : 8216,
+ 'W' : 87,
+ 'Q' : 81,
+ 'g' : 103,
+ 'w' : 119,
+ 'question' : 63,
+ 'one' : 49,
+ 'ring' : 730,
+ 'figuredash' : 8210,
+ 'B' : 66,
+ 'iacute' : 237,
+ 'Ydieresis' : 376,
+ 'R' : 82,
+ 'b' : 98,
+ 'r' : 114,
+ 'Ccedilla' : 199,
+ 'minus' : 8722,
+ 'Lslash' : 321,
+ 'Uacute' : 218,
+ 'yacute' : 253,
+ 'Ucircumflex' : 219,
+ 'quotedbl' : 34,
+ 'onehalf' : 189,
+ 'Thorn' : 222,
+ 'M' : 77,
+ 'eight' : 56,
+ 'multiply' : 215,
+ 'grave' : 96,
+ 'Ocircumflex' : 212,
+ 'm' : 109,
+ 'Ugrave' : 217,
+ 'guilsinglright' : 8250,
+ 'Ntilde' : 209,
+ 'questiondown' : 191,
+ 'Atilde' : 195,
+ 'ccedilla' : 231,
+ 'Z' : 90,
+ 'copyright' : 169,
+ 'yen' : 165,
+ 'Eacute' : 201,
+ 'H' : 72,
+ 'X' : 88,
+ 'Idieresis' : 207,
+ 'bar' : 124,
+ 'h' : 104,
+ 'x' : 120,
+ 'udieresis' : 252,
+ 'ordfeminine' : 170,
+ 'braceleft' : 123,
+ 'macron' : 175,
+ 'atilde' : 227,
+ 'Acircumflex' : 194,
+ 'Oslash' : 216,
+ 'C' : 67,
+ 'quotedblleft' : 8220,
+ 'S' : 83,
+ 'exclam' : 33,
+ 'Zcaron' : 381,
+ 'equal' : 61,
+ 's' : 115,
+ 'eth' : 240,
+ 'Egrave' : 200,
+ 'hyphen' : 45,
+ 'period' : 46,
+ 'igrave' : 236,
+ 'colon' : 58,
+ 'Ecircumflex' : 202,
+ 'trademark' : 8482,
+ 'Aacute' : 193,
+ 'cent' : 162,
+ 'lslash' : 322,
+ 'c' : 99,
+ 'N' : 78,
+ 'breve' : 728,
+ 'Oacute' : 211,
+ 'guillemotleft' : 171,
+ 'n' : 110,
+ 'idieresis' : 239,
+ 'braceright' : 125,
+ 'seven' : 55,
+ 'brokenbar' : 166,
+ 'ugrave' : 249,
+ 'periodcentered' : 183,
+ 'sterling' : 163,
+ 'I' : 73,
+ 'Y' : 89,
+ 'Eth' : 208,
+ 'emdash' : 8212,
+ 'i' : 105,
+ 'daggerdbl' : 8225,
+ 'y' : 121,
+ 'plusminus' : 177,
+ 'less' : 60,
+ 'Udieresis' : 220,
+ 'D' : 68,
+ 'five' : 53,
+ 'T' : 84,
+ 'oslash' : 248,
+ 'acute' : 180,
+ 'd' : 100,
+ 'OE' : 338,
+ 'Igrave' : 204,
+ 't' : 116,
+ 'parenright' : 41,
+ 'adieresis' : 228,
+ 'quotesingle' : 39,
+ 'twodotenleader' : 8229,
+ 'slash' : 47,
+ 'ellipsis' : 8230,
+ 'numbersign' : 35,
+ 'odieresis' : 246,
+ 'O' : 79,
+ 'oe' : 339,
+ 'o' : 111,
+ 'Edieresis' : 203,
+ 'plus' : 43,
+ 'dagger' : 8224,
+ 'three' : 51,
+ 'hungarumlaut' : 733,
+ 'parenleft' : 40,
+ 'fraction' : 8260,
+ 'registered' : 174,
+ 'J' : 74,
+ 'dieresis' : 168,
+ 'Ograve' : 210,
+ 'j' : 106,
+ 'z' : 122,
+ 'ae' : 230,
+ 'semicolon' : 59,
+ 'at' : 64,
+ 'Iacute' : 205,
+ 'percent' : 37,
+ 'bracketright' : 93,
+ 'AE' : 198,
+ 'asterisk' : 42,
+ 'aacute' : 225,
+ 'U' : 85,
+ 'eacute' : 233,
+ 'e' : 101,
+ 'thorn' : 254,
+ 'u' : 117,
+}
+
+uni2type1 = {v: k for k, v in type12uni.items()}
+
+# The script below is to sort and format the tex2uni dict
+
+## For decimal values: int(hex(v), 16)
+# newtex = {k: hex(v) for k, v in tex2uni.items()}
+# sd = dict(sorted(newtex.items(), key=lambda item: item[0]))
+#
+## For formatting the sorted dictionary with proper spacing
+## the value '24' comes from finding the longest string in
+## the newtex keys with len(max(newtex, key=len))
+# for key in sd:
+# print("{0:24} : {1: _EntryTypeOut: ...
+
+
+@overload
+def _normalize_stix_fontcodes(d: list[_EntryTypeIn]) -> list[_EntryTypeOut]: ...
+
+
+@overload
+def _normalize_stix_fontcodes(d: dict[str, list[_EntryTypeIn] |
+ dict[str, list[_EntryTypeIn]]]
+ ) -> dict[str, list[_EntryTypeOut] |
+ dict[str, list[_EntryTypeOut]]]: ...
+
+
+def _normalize_stix_fontcodes(d):
+ if isinstance(d, tuple):
+ return tuple(ord(x) if isinstance(x, str) and len(x) == 1 else x for x in d)
+ elif isinstance(d, list):
+ return [_normalize_stix_fontcodes(x) for x in d]
+ elif isinstance(d, dict):
+ return {k: _normalize_stix_fontcodes(v) for k, v in d.items()}
+
+
+stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeOut]] | list[_EntryTypeOut]]
+stix_virtual_fonts = _normalize_stix_fontcodes(_stix_virtual_fonts)
+
+# Free redundant list now that it has been normalized
+del _stix_virtual_fonts
+
+# Fix some incorrect glyphs.
+stix_glyph_fixes = {
+ # Cap and Cup glyphs are swapped.
+ 0x22d2: 0x22d3,
+ 0x22d3: 0x22d2,
+}
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so b/llava_video/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..eed83acff1dc8adbe29d1e751cb5e22c6f280e38
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6a28a124af2791c5ebdeb7360abcb1d9bc1a701a63e042b8d215e68ff25ae555
+size 486904
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_path.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/_path.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..456905528b28e0f4eea31ec9d86433fb43767b85
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_path.pyi
@@ -0,0 +1,9 @@
+from collections.abc import Sequence
+
+import numpy as np
+
+from .transforms import BboxBase
+
+def affine_transform(points: np.ndarray, trans: np.ndarray) -> np.ndarray: ...
+def count_bboxes_overlapping_bbox(bbox: BboxBase, bboxes: Sequence[BboxBase]) -> int: ...
+def update_path_extents(path, trans, rect, minpos, ignore): ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_qhull.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/_qhull.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_text_helpers.py b/llava_video/lib/python3.10/site-packages/matplotlib/_text_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9603b114bc245ecf32da926573ddb4157210c7a
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_text_helpers.py
@@ -0,0 +1,82 @@
+"""
+Low-level text helper utilities.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+
+from . import _api
+from .ft2font import FT2Font, Kerning, LoadFlags
+
+
+@dataclasses.dataclass(frozen=True)
+class LayoutItem:
+ ft_object: FT2Font
+ char: str
+ glyph_idx: int
+ x: float
+ prev_kern: float
+
+
+def warn_on_missing_glyph(codepoint, fontnames):
+ _api.warn_external(
+ f"Glyph {codepoint} "
+ f"({chr(codepoint).encode('ascii', 'namereplace').decode('ascii')}) "
+ f"missing from font(s) {fontnames}.")
+
+ block = ("Hebrew" if 0x0590 <= codepoint <= 0x05ff else
+ "Arabic" if 0x0600 <= codepoint <= 0x06ff else
+ "Devanagari" if 0x0900 <= codepoint <= 0x097f else
+ "Bengali" if 0x0980 <= codepoint <= 0x09ff else
+ "Gurmukhi" if 0x0a00 <= codepoint <= 0x0a7f else
+ "Gujarati" if 0x0a80 <= codepoint <= 0x0aff else
+ "Oriya" if 0x0b00 <= codepoint <= 0x0b7f else
+ "Tamil" if 0x0b80 <= codepoint <= 0x0bff else
+ "Telugu" if 0x0c00 <= codepoint <= 0x0c7f else
+ "Kannada" if 0x0c80 <= codepoint <= 0x0cff else
+ "Malayalam" if 0x0d00 <= codepoint <= 0x0d7f else
+ "Sinhala" if 0x0d80 <= codepoint <= 0x0dff else
+ None)
+ if block:
+ _api.warn_external(
+ f"Matplotlib currently does not support {block} natively.")
+
+
+def layout(string, font, *, kern_mode=Kerning.DEFAULT):
+ """
+ Render *string* with *font*.
+
+ For each character in *string*, yield a LayoutItem instance. When such an instance
+ is yielded, the font's glyph is set to the corresponding character.
+
+ Parameters
+ ----------
+ string : str
+ The string to be rendered.
+ font : FT2Font
+ The font.
+ kern_mode : Kerning
+ A FreeType kerning mode.
+
+ Yields
+ ------
+ LayoutItem
+ """
+ x = 0
+ prev_glyph_idx = None
+ char_to_font = font._get_fontmap(string)
+ base_font = font
+ for char in string:
+ # This has done the fallback logic
+ font = char_to_font.get(char, base_font)
+ glyph_idx = font.get_char_index(ord(char))
+ kern = (
+ base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64
+ if prev_glyph_idx is not None else 0.
+ )
+ x += kern
+ glyph = font.load_glyph(glyph_idx, flags=LoadFlags.NO_HINTING)
+ yield LayoutItem(font, char, glyph_idx, x, kern)
+ x += glyph.linearHoriAdvance / 65536
+ prev_glyph_idx = glyph_idx
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_tight_bbox.py b/llava_video/lib/python3.10/site-packages/matplotlib/_tight_bbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..db72bbdff020680dfd833229cac41e9b33e428ee
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_tight_bbox.py
@@ -0,0 +1,84 @@
+"""
+Helper module for the *bbox_inches* parameter in `.Figure.savefig`.
+"""
+
+from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
+
+
+def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
+ """
+ Temporarily adjust the figure so that only the specified area
+ (bbox_inches) is saved.
+
+ It modifies fig.bbox, fig.bbox_inches,
+ fig.transFigure._boxout, and fig.patch. While the figure size
+ changes, the scale of the original figure is conserved. A
+ function which restores the original values are returned.
+ """
+ origBbox = fig.bbox
+ origBboxInches = fig.bbox_inches
+ _boxout = fig.transFigure._boxout
+
+ old_aspect = []
+ locator_list = []
+ sentinel = object()
+ for ax in fig.axes:
+ locator = ax.get_axes_locator()
+ if locator is not None:
+ ax.apply_aspect(locator(ax, None))
+ locator_list.append(locator)
+ current_pos = ax.get_position(original=False).frozen()
+ ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos)
+ # override the method that enforces the aspect ratio on the Axes
+ if 'apply_aspect' in ax.__dict__:
+ old_aspect.append(ax.apply_aspect)
+ else:
+ old_aspect.append(sentinel)
+ ax.apply_aspect = lambda pos=None: None
+
+ def restore_bbox():
+ for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect):
+ ax.set_axes_locator(loc)
+ if aspect is sentinel:
+ # delete our no-op function which un-hides the original method
+ del ax.apply_aspect
+ else:
+ ax.apply_aspect = aspect
+
+ fig.bbox = origBbox
+ fig.bbox_inches = origBboxInches
+ fig.transFigure._boxout = _boxout
+ fig.transFigure.invalidate()
+ fig.patch.set_bounds(0, 0, 1, 1)
+
+ if fixed_dpi is None:
+ fixed_dpi = fig.dpi
+ tr = Affine2D().scale(fixed_dpi)
+ dpi_scale = fixed_dpi / fig.dpi
+
+ fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size)
+ x0, y0 = tr.transform(bbox_inches.p0)
+ w1, h1 = fig.bbox.size * dpi_scale
+ fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
+ fig.transFigure.invalidate()
+
+ fig.bbox = TransformedBbox(fig.bbox_inches, tr)
+
+ fig.patch.set_bounds(x0 / w1, y0 / h1,
+ fig.bbox.width / w1, fig.bbox.height / h1)
+
+ return restore_bbox
+
+
+def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None):
+ """
+ A function that needs to be called when figure dpi changes during the
+ drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with
+ the new dpi.
+ """
+
+ bbox_inches, restore_bbox = bbox_inches_restore
+ restore_bbox()
+ r = adjust_bbox(fig, bbox_inches, fixed_dpi)
+
+ return bbox_inches, r
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so b/llava_video/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..2022275c4dfbe74929ff6e463ce4d7682725ccb2
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5ec117a7bee59ea2cf47311cc05170252bbdc1b64851ee15fd80da777fc3550a
+size 411008
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/animation.py b/llava_video/lib/python3.10/site-packages/matplotlib/animation.py
new file mode 100644
index 0000000000000000000000000000000000000000..2be61284073a67f1c063b41729ac51b903b563e1
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/animation.py
@@ -0,0 +1,1823 @@
+import abc
+import base64
+import contextlib
+from io import BytesIO, TextIOWrapper
+import itertools
+import logging
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+from tempfile import TemporaryDirectory
+import uuid
+import warnings
+
+import numpy as np
+from PIL import Image
+
+import matplotlib as mpl
+from matplotlib._animation_data import (
+ DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
+from matplotlib import _api, cbook
+import matplotlib.colors as mcolors
+
+_log = logging.getLogger(__name__)
+
+# Process creation flag for subprocess to prevent it raising a terminal
+# window. See for example https://stackoverflow.com/q/24130623/
+subprocess_creation_flags = (
+ subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0)
+
+
+def adjusted_figsize(w, h, dpi, n):
+ """
+ Compute figure size so that pixels are a multiple of n.
+
+ Parameters
+ ----------
+ w, h : float
+ Size in inches.
+
+ dpi : float
+ The dpi.
+
+ n : int
+ The target multiple.
+
+ Returns
+ -------
+ wnew, hnew : float
+ The new figure size in inches.
+ """
+
+ # this maybe simplified if / when we adopt consistent rounding for
+ # pixel size across the whole library
+ def correct_roundoff(x, dpi, n):
+ if int(x*dpi) % n != 0:
+ if int(np.nextafter(x, np.inf)*dpi) % n == 0:
+ x = np.nextafter(x, np.inf)
+ elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
+ x = np.nextafter(x, -np.inf)
+ return x
+
+ wnew = int(w * dpi / n) * n / dpi
+ hnew = int(h * dpi / n) * n / dpi
+ return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
+
+
+class MovieWriterRegistry:
+ """Registry of available writer classes by human readable name."""
+
+ def __init__(self):
+ self._registered = dict()
+
+ def register(self, name):
+ """
+ Decorator for registering a class under a name.
+
+ Example use::
+
+ @registry.register(name)
+ class Foo:
+ pass
+ """
+ def wrapper(writer_cls):
+ self._registered[name] = writer_cls
+ return writer_cls
+ return wrapper
+
+ def is_available(self, name):
+ """
+ Check if given writer is available by name.
+
+ Parameters
+ ----------
+ name : str
+
+ Returns
+ -------
+ bool
+ """
+ try:
+ cls = self._registered[name]
+ except KeyError:
+ return False
+ return cls.isAvailable()
+
+ def __iter__(self):
+ """Iterate over names of available writer class."""
+ for name in self._registered:
+ if self.is_available(name):
+ yield name
+
+ def list(self):
+ """Get a list of available MovieWriters."""
+ return [*self]
+
+ def __getitem__(self, name):
+ """Get an available writer class from its name."""
+ if self.is_available(name):
+ return self._registered[name]
+ raise RuntimeError(f"Requested MovieWriter ({name}) not available")
+
+
+writers = MovieWriterRegistry()
+
+
+class AbstractMovieWriter(abc.ABC):
+ """
+ Abstract base class for writing movies, providing a way to grab frames by
+ calling `~AbstractMovieWriter.grab_frame`.
+
+ `setup` is called to start the process and `finish` is called afterwards.
+ `saving` is provided as a context manager to facilitate this process as ::
+
+ with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
+ # Iterate over frames
+ moviewriter.grab_frame(**savefig_kwargs)
+
+ The use of the context manager ensures that `setup` and `finish` are
+ performed as necessary.
+
+ An instance of a concrete subclass of this class can be given as the
+ ``writer`` argument of `Animation.save()`.
+ """
+
+ def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
+ self.fps = fps
+ self.metadata = metadata if metadata is not None else {}
+ self.codec = mpl._val_or_rc(codec, 'animation.codec')
+ self.bitrate = mpl._val_or_rc(bitrate, 'animation.bitrate')
+
+ @abc.abstractmethod
+ def setup(self, fig, outfile, dpi=None):
+ """
+ Setup for writing the movie file.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object that contains the information for frames.
+ outfile : str
+ The filename of the resulting movie file.
+ dpi : float, default: ``fig.dpi``
+ The DPI (or resolution) for the file. This controls the size
+ in pixels of the resulting movie file.
+ """
+ # Check that path is valid
+ Path(outfile).parent.resolve(strict=True)
+ self.outfile = outfile
+ self.fig = fig
+ if dpi is None:
+ dpi = self.fig.dpi
+ self.dpi = dpi
+
+ @property
+ def frame_size(self):
+ """A tuple ``(width, height)`` in pixels of a movie frame."""
+ w, h = self.fig.get_size_inches()
+ return int(w * self.dpi), int(h * self.dpi)
+
+ def _supports_transparency(self):
+ """
+ Whether this writer supports transparency.
+
+ Writers may consult output file type and codec to determine this at runtime.
+ """
+ return False
+
+ @abc.abstractmethod
+ def grab_frame(self, **savefig_kwargs):
+ """
+ Grab the image information from the figure and save as a movie frame.
+
+ All keyword arguments in *savefig_kwargs* are passed on to the
+ `~.Figure.savefig` call that saves the figure. However, several
+ keyword arguments that are supported by `~.Figure.savefig` may not be
+ passed as they are controlled by the MovieWriter:
+
+ - *dpi*, *bbox_inches*: These may not be passed because each frame of the
+ animation much be exactly the same size in pixels.
+ - *format*: This is controlled by the MovieWriter.
+ """
+
+ @abc.abstractmethod
+ def finish(self):
+ """Finish any processing for writing the movie."""
+
+ @contextlib.contextmanager
+ def saving(self, fig, outfile, dpi, *args, **kwargs):
+ """
+ Context manager to facilitate writing the movie file.
+
+ ``*args, **kw`` are any parameters that should be passed to `setup`.
+ """
+ if mpl.rcParams['savefig.bbox'] == 'tight':
+ _log.info("Disabling savefig.bbox = 'tight', as it may cause "
+ "frame size to vary, which is inappropriate for "
+ "animation.")
+
+ # This particular sequence is what contextlib.contextmanager wants
+ self.setup(fig, outfile, dpi, *args, **kwargs)
+ with mpl.rc_context({'savefig.bbox': None}):
+ try:
+ yield self
+ finally:
+ self.finish()
+
+
+class MovieWriter(AbstractMovieWriter):
+ """
+ Base class for writing movies.
+
+ This is a base class for MovieWriter subclasses that write a movie frame
+ data to a pipe. You cannot instantiate this class directly.
+ See examples for how to use its subclasses.
+
+ Attributes
+ ----------
+ frame_format : str
+ The format used in writing frame data, defaults to 'rgba'.
+ fig : `~matplotlib.figure.Figure`
+ The figure to capture data from.
+ This must be provided by the subclasses.
+ """
+
+ # Builtin writer subclasses additionally define the _exec_key and _args_key
+ # attributes, which indicate the rcParams entries where the path to the
+ # executable and additional command-line arguments to the executable are
+ # stored. Third-party writers cannot meaningfully set these as they cannot
+ # extend rcParams with new keys.
+
+ # Pipe-based writers only support RGBA, but file-based ones support more
+ # formats.
+ supported_formats = ["rgba"]
+
+ def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
+ metadata=None):
+ """
+ Parameters
+ ----------
+ fps : int, default: 5
+ Movie frame rate (per second).
+ codec : str or None, default: :rc:`animation.codec`
+ The codec to use.
+ bitrate : int, default: :rc:`animation.bitrate`
+ The bitrate of the movie, in kilobits per second. Higher values
+ means higher quality movies, but increase the file size. A value
+ of -1 lets the underlying movie encoder select the bitrate.
+ extra_args : list of str or None, optional
+ Extra command-line arguments passed to the underlying movie encoder. These
+ arguments are passed last to the encoder, just before the filename. The
+ default, None, means to use :rc:`animation.[name-of-encoder]_args` for the
+ builtin writers.
+ metadata : dict[str, str], default: {}
+ A dictionary of keys and values for metadata to include in the
+ output file. Some keys that may be of use include:
+ title, artist, genre, subject, copyright, srcform, comment.
+ """
+ if type(self) is MovieWriter:
+ # TODO MovieWriter is still an abstract class and needs to be
+ # extended with a mixin. This should be clearer in naming
+ # and description. For now, just give a reasonable error
+ # message to users.
+ raise TypeError(
+ 'MovieWriter cannot be instantiated directly. Please use one '
+ 'of its subclasses.')
+
+ super().__init__(fps=fps, metadata=metadata, codec=codec,
+ bitrate=bitrate)
+ self.frame_format = self.supported_formats[0]
+ self.extra_args = extra_args
+
+ def _adjust_frame_size(self):
+ if self.codec == 'h264':
+ wo, ho = self.fig.get_size_inches()
+ w, h = adjusted_figsize(wo, ho, self.dpi, 2)
+ if (wo, ho) != (w, h):
+ self.fig.set_size_inches(w, h, forward=True)
+ _log.info('figure size in inches has been adjusted '
+ 'from %s x %s to %s x %s', wo, ho, w, h)
+ else:
+ w, h = self.fig.get_size_inches()
+ _log.debug('frame size in pixels is %s x %s', *self.frame_size)
+ return w, h
+
+ def setup(self, fig, outfile, dpi=None):
+ # docstring inherited
+ super().setup(fig, outfile, dpi=dpi)
+ self._w, self._h = self._adjust_frame_size()
+ # Run here so that grab_frame() can write the data to a pipe. This
+ # eliminates the need for temp files.
+ self._run()
+
+ def _run(self):
+ # Uses subprocess to call the program for assembling frames into a
+ # movie file. *args* returns the sequence of command line arguments
+ # from a few configuration options.
+ command = self._args()
+ _log.info('MovieWriter._run: running command: %s',
+ cbook._pformat_subprocess(command))
+ PIPE = subprocess.PIPE
+ self._proc = subprocess.Popen(
+ command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
+ creationflags=subprocess_creation_flags)
+
+ def finish(self):
+ """Finish any processing for writing the movie."""
+ out, err = self._proc.communicate()
+ # Use the encoding/errors that universal_newlines would use.
+ out = TextIOWrapper(BytesIO(out)).read()
+ err = TextIOWrapper(BytesIO(err)).read()
+ if out:
+ _log.log(
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
+ "MovieWriter stdout:\n%s", out)
+ if err:
+ _log.log(
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
+ "MovieWriter stderr:\n%s", err)
+ if self._proc.returncode:
+ raise subprocess.CalledProcessError(
+ self._proc.returncode, self._proc.args, out, err)
+
+ def grab_frame(self, **savefig_kwargs):
+ # docstring inherited
+ _validate_grabframe_kwargs(savefig_kwargs)
+ _log.debug('MovieWriter.grab_frame: Grabbing frame.')
+ # Readjust the figure size in case it has been changed by the user.
+ # All frames must have the same size to save the movie correctly.
+ self.fig.set_size_inches(self._w, self._h)
+ # Save the figure data to the sink, using the frame format and dpi.
+ self.fig.savefig(self._proc.stdin, format=self.frame_format,
+ dpi=self.dpi, **savefig_kwargs)
+
+ def _args(self):
+ """Assemble list of encoder-specific command-line arguments."""
+ return NotImplementedError("args needs to be implemented by subclass.")
+
+ @classmethod
+ def bin_path(cls):
+ """
+ Return the binary path to the commandline tool used by a specific
+ subclass. This is a class method so that the tool can be looked for
+ before making a particular MovieWriter subclass available.
+ """
+ return str(mpl.rcParams[cls._exec_key])
+
+ @classmethod
+ def isAvailable(cls):
+ """Return whether a MovieWriter subclass is actually available."""
+ return shutil.which(cls.bin_path()) is not None
+
+
+class FileMovieWriter(MovieWriter):
+ """
+ `MovieWriter` for writing to individual files and stitching at the end.
+
+ This must be sub-classed to be useful.
+ """
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.frame_format = mpl.rcParams['animation.frame_format']
+
+ def setup(self, fig, outfile, dpi=None, frame_prefix=None):
+ """
+ Setup for writing the movie file.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure to grab the rendered frames from.
+ outfile : str
+ The filename of the resulting movie file.
+ dpi : float, default: ``fig.dpi``
+ The dpi of the output file. This, with the figure size,
+ controls the size in pixels of the resulting movie file.
+ frame_prefix : str, optional
+ The filename prefix to use for temporary files. If *None* (the
+ default), files are written to a temporary directory which is
+ deleted by `finish`; if not *None*, no temporary files are
+ deleted.
+ """
+ # Check that path is valid
+ Path(outfile).parent.resolve(strict=True)
+ self.fig = fig
+ self.outfile = outfile
+ if dpi is None:
+ dpi = self.fig.dpi
+ self.dpi = dpi
+ self._adjust_frame_size()
+
+ if frame_prefix is None:
+ self._tmpdir = TemporaryDirectory()
+ self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
+ else:
+ self._tmpdir = None
+ self.temp_prefix = frame_prefix
+ self._frame_counter = 0 # used for generating sequential file names
+ self._temp_paths = list()
+ self.fname_format_str = '%s%%07d.%s'
+
+ def __del__(self):
+ if hasattr(self, '_tmpdir') and self._tmpdir:
+ self._tmpdir.cleanup()
+
+ @property
+ def frame_format(self):
+ """
+ Format (png, jpeg, etc.) to use for saving the frames, which can be
+ decided by the individual subclasses.
+ """
+ return self._frame_format
+
+ @frame_format.setter
+ def frame_format(self, frame_format):
+ if frame_format in self.supported_formats:
+ self._frame_format = frame_format
+ else:
+ _api.warn_external(
+ f"Ignoring file format {frame_format!r} which is not "
+ f"supported by {type(self).__name__}; using "
+ f"{self.supported_formats[0]} instead.")
+ self._frame_format = self.supported_formats[0]
+
+ def _base_temp_name(self):
+ # Generates a template name (without number) given the frame format
+ # for extension and the prefix.
+ return self.fname_format_str % (self.temp_prefix, self.frame_format)
+
+ def grab_frame(self, **savefig_kwargs):
+ # docstring inherited
+ # Creates a filename for saving using basename and counter.
+ _validate_grabframe_kwargs(savefig_kwargs)
+ path = Path(self._base_temp_name() % self._frame_counter)
+ self._temp_paths.append(path) # Record the filename for later use.
+ self._frame_counter += 1 # Ensures each created name is unique.
+ _log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s',
+ self._frame_counter, path)
+ with open(path, 'wb') as sink: # Save figure to the sink.
+ self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi,
+ **savefig_kwargs)
+
+ def finish(self):
+ # Call run here now that all frame grabbing is done. All temp files
+ # are available to be assembled.
+ try:
+ self._run()
+ super().finish()
+ finally:
+ if self._tmpdir:
+ _log.debug(
+ 'MovieWriter: clearing temporary path=%s', self._tmpdir
+ )
+ self._tmpdir.cleanup()
+
+
+@writers.register('pillow')
+class PillowWriter(AbstractMovieWriter):
+ def _supports_transparency(self):
+ return True
+
+ @classmethod
+ def isAvailable(cls):
+ return True
+
+ def setup(self, fig, outfile, dpi=None):
+ super().setup(fig, outfile, dpi=dpi)
+ self._frames = []
+
+ def grab_frame(self, **savefig_kwargs):
+ _validate_grabframe_kwargs(savefig_kwargs)
+ buf = BytesIO()
+ self.fig.savefig(
+ buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
+ im = Image.frombuffer(
+ "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)
+ if im.getextrema()[3][0] < 255:
+ # This frame has transparency, so we'll just add it as is.
+ self._frame.append(im)
+ else:
+ # Without transparency, we switch to RGB mode, which converts to P mode a
+ # little better if needed (specifically, this helps with GIF output.)
+ self._frames.append(im.convert("RGB"))
+
+ def finish(self):
+ self._frames[0].save(
+ self.outfile, save_all=True, append_images=self._frames[1:],
+ duration=int(1000 / self.fps), loop=0)
+
+
+# Base class of ffmpeg information. Has the config keys and the common set
+# of arguments that controls the *output* side of things.
+class FFMpegBase:
+ """
+ Mixin class for FFMpeg output.
+
+ This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter`
+ classes.
+ """
+
+ _exec_key = 'animation.ffmpeg_path'
+ _args_key = 'animation.ffmpeg_args'
+
+ def _supports_transparency(self):
+ suffix = Path(self.outfile).suffix
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
+ return True
+ # This list was found by going through `ffmpeg -codecs` for video encoders,
+ # running them with _support_transparency() forced to True, and checking that
+ # the "Pixel format" in Kdenlive included alpha. Note this is not a guarantee
+ # that transparency will work; you may also need to pass `-pix_fmt`, but we
+ # trust the user has done so if they are asking for these formats.
+ return self.codec in {
+ 'apng', 'avrp', 'bmp', 'cfhd', 'dpx', 'ffv1', 'ffvhuff', 'gif', 'huffyuv',
+ 'jpeg2000', 'ljpeg', 'png', 'prores', 'prores_aw', 'prores_ks', 'qtrle',
+ 'rawvideo', 'targa', 'tiff', 'utvideo', 'v408', }
+
+ @property
+ def output_args(self):
+ args = []
+ suffix = Path(self.outfile).suffix
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
+ self.codec = suffix[1:]
+ else:
+ args.extend(['-vcodec', self.codec])
+ extra_args = (self.extra_args if self.extra_args is not None
+ else mpl.rcParams[self._args_key])
+ # For h264, the default format is yuv444p, which is not compatible
+ # with quicktime (and others). Specifying yuv420p fixes playback on
+ # iOS, as well as HTML5 video in firefox and safari (on both Windows and
+ # macOS). Also fixes internet explorer. This is as of 2015/10/29.
+ if self.codec == 'h264' and '-pix_fmt' not in extra_args:
+ args.extend(['-pix_fmt', 'yuv420p'])
+ # For GIF, we're telling FFmpeg to split the video stream, to generate
+ # a palette, and then use it for encoding.
+ elif self.codec == 'gif' and '-filter_complex' not in extra_args:
+ args.extend(['-filter_complex',
+ 'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
+ # For AVIF, we're telling FFmpeg to split the video stream, extract the alpha,
+ # in order to place it in a secondary stream, as needed by AVIF-in-FFmpeg.
+ elif self.codec == 'avif' and '-filter_complex' not in extra_args:
+ args.extend(['-filter_complex',
+ 'split [rgb][rgba]; [rgba] alphaextract [alpha]',
+ '-map', '[rgb]', '-map', '[alpha]'])
+ if self.bitrate > 0:
+ args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
+ for k, v in self.metadata.items():
+ args.extend(['-metadata', f'{k}={v}'])
+ args.extend(extra_args)
+
+ return args + ['-y', self.outfile]
+
+
+# Combine FFMpeg options with pipe-based writing
+@writers.register('ffmpeg')
+class FFMpegWriter(FFMpegBase, MovieWriter):
+ """
+ Pipe-based ffmpeg writer.
+
+ Frames are streamed directly to ffmpeg via a pipe and written in a single pass.
+
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
+
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
+ """
+ def _args(self):
+ # Returns the command line parameters for subprocess to use
+ # ffmpeg to create a movie using a pipe.
+ args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
+ '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
+ '-framerate', str(self.fps)]
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
+ # If you have a lot of frames in your animation and set logging to
+ # DEBUG, you will have a buffer overrun.
+ if _log.getEffectiveLevel() > logging.DEBUG:
+ args += ['-loglevel', 'error']
+ args += ['-i', 'pipe:'] + self.output_args
+ return args
+
+
+# Combine FFMpeg options with temp file-based writing
+@writers.register('ffmpeg_file')
+class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
+ """
+ File-based ffmpeg writer.
+
+ Frames are written to temporary files on disk and then stitched together at the end.
+
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
+
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
+ """
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
+
+ def _args(self):
+ # Returns the command line parameters for subprocess to use
+ # ffmpeg to create a movie using a collection of temp images
+ args = []
+ # For raw frames, we need to explicitly tell ffmpeg the metadata.
+ if self.frame_format in {'raw', 'rgba'}:
+ args += [
+ '-f', 'image2', '-vcodec', 'rawvideo',
+ '-video_size', '%dx%d' % self.frame_size,
+ '-pixel_format', 'rgba',
+ ]
+ args += ['-framerate', str(self.fps), '-i', self._base_temp_name()]
+ if not self._tmpdir:
+ args += ['-frames:v', str(self._frame_counter)]
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
+ # If you have a lot of frames in your animation and set logging to
+ # DEBUG, you will have a buffer overrun.
+ if _log.getEffectiveLevel() > logging.DEBUG:
+ args += ['-loglevel', 'error']
+ return [self.bin_path(), *args, *self.output_args]
+
+
+# Base class for animated GIFs with ImageMagick
+class ImageMagickBase:
+ """
+ Mixin class for ImageMagick output.
+
+ This is a base class for the concrete `ImageMagickWriter` and
+ `ImageMagickFileWriter` classes, which define an ``input_names`` attribute
+ (or property) specifying the input names passed to ImageMagick.
+ """
+
+ _exec_key = 'animation.convert_path'
+ _args_key = 'animation.convert_args'
+
+ def _supports_transparency(self):
+ suffix = Path(self.outfile).suffix
+ return suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}
+
+ def _args(self):
+ # ImageMagick does not recognize "raw".
+ fmt = "rgba" if self.frame_format == "raw" else self.frame_format
+ extra_args = (self.extra_args if self.extra_args is not None
+ else mpl.rcParams[self._args_key])
+ return [
+ self.bin_path(),
+ "-size", "%ix%i" % self.frame_size,
+ "-depth", "8",
+ "-delay", str(100 / self.fps),
+ "-loop", "0",
+ f"{fmt}:{self.input_names}",
+ *extra_args,
+ self.outfile,
+ ]
+
+ @classmethod
+ def bin_path(cls):
+ binpath = super().bin_path()
+ if binpath == 'convert':
+ binpath = mpl._get_executable_info('magick').executable
+ return binpath
+
+ @classmethod
+ def isAvailable(cls):
+ try:
+ return super().isAvailable()
+ except mpl.ExecutableNotFoundError as _enf:
+ # May be raised by get_executable_info.
+ _log.debug('ImageMagick unavailable due to: %s', _enf)
+ return False
+
+
+# Combine ImageMagick options with pipe-based writing
+@writers.register('imagemagick')
+class ImageMagickWriter(ImageMagickBase, MovieWriter):
+ """
+ Pipe-based animated gif writer.
+
+ Frames are streamed directly to ImageMagick via a pipe and written
+ in a single pass.
+ """
+
+ input_names = "-" # stdin
+
+
+# Combine ImageMagick options with temp file-based writing
+@writers.register('imagemagick_file')
+class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
+ """
+ File-based animated gif writer.
+
+ Frames are written to temporary files on disk and then stitched
+ together at the end.
+ """
+
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
+ input_names = property(
+ lambda self: f'{self.temp_prefix}*.{self.frame_format}')
+
+
+# Taken directly from jakevdp's JSAnimation package at
+# http://github.com/jakevdp/JSAnimation
+def _included_frames(frame_count, frame_format, frame_dir):
+ return INCLUDED_FRAMES.format(Nframes=frame_count,
+ frame_dir=frame_dir,
+ frame_format=frame_format)
+
+
+def _embedded_frames(frame_list, frame_format):
+ """frame_list should be a list of base64-encoded png files"""
+ if frame_format == 'svg':
+ # Fix MIME type for svg
+ frame_format = 'svg+xml'
+ template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
+ return "\n" + "".join(
+ template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
+ for i, frame_data in enumerate(frame_list))
+
+
+@writers.register('html')
+class HTMLWriter(FileMovieWriter):
+ """Writer for JavaScript-based HTML movies."""
+
+ supported_formats = ['png', 'jpeg', 'tiff', 'svg']
+
+ @classmethod
+ def isAvailable(cls):
+ return True
+
+ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
+ metadata=None, embed_frames=False, default_mode='loop',
+ embed_limit=None):
+
+ if extra_args:
+ _log.warning("HTMLWriter ignores 'extra_args'")
+ extra_args = () # Don't lookup nonexistent rcParam[args_key].
+ self.embed_frames = embed_frames
+ self.default_mode = default_mode.lower()
+ _api.check_in_list(['loop', 'once', 'reflect'],
+ default_mode=self.default_mode)
+
+ # Save embed limit, which is given in MB
+ self._bytes_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
+ # Convert from MB to bytes
+ self._bytes_limit *= 1024 * 1024
+
+ super().__init__(fps, codec, bitrate, extra_args, metadata)
+
+ def setup(self, fig, outfile, dpi=None, frame_dir=None):
+ outfile = Path(outfile)
+ _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
+
+ self._saved_frames = []
+ self._total_bytes = 0
+ self._hit_limit = False
+
+ if not self.embed_frames:
+ if frame_dir is None:
+ frame_dir = outfile.with_name(outfile.stem + '_frames')
+ frame_dir.mkdir(parents=True, exist_ok=True)
+ frame_prefix = frame_dir / 'frame'
+ else:
+ frame_prefix = None
+
+ super().setup(fig, outfile, dpi, frame_prefix)
+ self._clear_temp = False
+
+ def grab_frame(self, **savefig_kwargs):
+ _validate_grabframe_kwargs(savefig_kwargs)
+ if self.embed_frames:
+ # Just stop processing if we hit the limit
+ if self._hit_limit:
+ return
+ f = BytesIO()
+ self.fig.savefig(f, format=self.frame_format,
+ dpi=self.dpi, **savefig_kwargs)
+ imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
+ self._total_bytes += len(imgdata64)
+ if self._total_bytes >= self._bytes_limit:
+ _log.warning(
+ "Animation size has reached %s bytes, exceeding the limit "
+ "of %s. If you're sure you want a larger animation "
+ "embedded, set the animation.embed_limit rc parameter to "
+ "a larger value (in MB). This and further frames will be "
+ "dropped.", self._total_bytes, self._bytes_limit)
+ self._hit_limit = True
+ else:
+ self._saved_frames.append(imgdata64)
+ else:
+ return super().grab_frame(**savefig_kwargs)
+
+ def finish(self):
+ # save the frames to an html file
+ if self.embed_frames:
+ fill_frames = _embedded_frames(self._saved_frames,
+ self.frame_format)
+ frame_count = len(self._saved_frames)
+ else:
+ # temp names is filled by FileMovieWriter
+ frame_count = len(self._temp_paths)
+ fill_frames = _included_frames(
+ frame_count, self.frame_format,
+ self._temp_paths[0].parent.relative_to(self.outfile.parent))
+ mode_dict = dict(once_checked='',
+ loop_checked='',
+ reflect_checked='')
+ mode_dict[self.default_mode + '_checked'] = 'checked'
+
+ interval = 1000 // self.fps
+
+ with open(self.outfile, 'w') as of:
+ of.write(JS_INCLUDE + STYLE_INCLUDE)
+ of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
+ Nframes=frame_count,
+ fill_frames=fill_frames,
+ interval=interval,
+ **mode_dict))
+
+ # Duplicate the temporary file clean up logic from
+ # FileMovieWriter.finish. We cannot call the inherited version of
+ # finish because it assumes that there is a subprocess that we either
+ # need to call to merge many frames together or that there is a
+ # subprocess call that we need to clean up.
+ if self._tmpdir:
+ _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
+ self._tmpdir.cleanup()
+
+
+class Animation:
+ """
+ A base class for Animations.
+
+ This class is not usable as is, and should be subclassed to provide needed
+ behavior.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+
+ event_source : object, optional
+ A class that can run a callback when desired events
+ are generated, as well as be stopped and started.
+
+ Examples include timers (see `TimedAnimation`) and file
+ system notifications.
+
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing. If the backend does not
+ support blitting, then this parameter has no effect.
+
+ See Also
+ --------
+ FuncAnimation, ArtistAnimation
+ """
+
+ def __init__(self, fig, event_source=None, blit=False):
+ self._draw_was_started = False
+
+ self._fig = fig
+ # Disables blitting for backends that don't support it. This
+ # allows users to request it if available, but still have a
+ # fallback that works if it is not.
+ self._blit = blit and fig.canvas.supports_blit
+
+ # These are the basics of the animation. The frame sequence represents
+ # information for each frame of the animation and depends on how the
+ # drawing is handled by the subclasses. The event source fires events
+ # that cause the frame sequence to be iterated.
+ self.frame_seq = self.new_frame_seq()
+ self.event_source = event_source
+
+ # Instead of starting the event source now, we connect to the figure's
+ # draw_event, so that we only start once the figure has been drawn.
+ self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
+
+ # Connect to the figure's close_event so that we don't continue to
+ # fire events and try to draw to a deleted figure.
+ self._close_id = self._fig.canvas.mpl_connect('close_event',
+ self._stop)
+ if self._blit:
+ self._setup_blit()
+
+ def __del__(self):
+ if not getattr(self, '_draw_was_started', True):
+ warnings.warn(
+ 'Animation was deleted without rendering anything. This is '
+ 'most likely not intended. To prevent deletion, assign the '
+ 'Animation to a variable, e.g. `anim`, that exists until you '
+ 'output the Animation using `plt.show()` or '
+ '`anim.save()`.'
+ )
+
+ def _start(self, *args):
+ """
+ Starts interactive animation. Adds the draw frame command to the GUI
+ handler, calls show to start the event loop.
+ """
+ # Do not start the event source if saving() it.
+ if self._fig.canvas.is_saving():
+ return
+ # First disconnect our draw event handler
+ self._fig.canvas.mpl_disconnect(self._first_draw_id)
+
+ # Now do any initial draw
+ self._init_draw()
+
+ # Add our callback for stepping the animation and
+ # actually start the event_source.
+ self.event_source.add_callback(self._step)
+ self.event_source.start()
+
+ def _stop(self, *args):
+ # On stop we disconnect all of our events.
+ if self._blit:
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self._fig.canvas.mpl_disconnect(self._close_id)
+ self.event_source.remove_callback(self._step)
+ self.event_source = None
+
+ def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
+ bitrate=None, extra_args=None, metadata=None, extra_anim=None,
+ savefig_kwargs=None, *, progress_callback=None):
+ """
+ Save the animation as a movie file by drawing every frame.
+
+ Parameters
+ ----------
+ filename : str
+ The output filename, e.g., :file:`mymovie.mp4`.
+
+ writer : `MovieWriter` or str, default: :rc:`animation.writer`
+ A `MovieWriter` instance to use or a key that identifies a
+ class to use, such as 'ffmpeg'.
+
+ fps : int, optional
+ Movie frame rate (per second). If not set, the frame rate from the
+ animation's frame interval.
+
+ dpi : float, default: :rc:`savefig.dpi`
+ Controls the dots per inch for the movie frames. Together with
+ the figure's size in inches, this controls the size of the movie.
+
+ codec : str, default: :rc:`animation.codec`.
+ The video codec to use. Not all codecs are supported by a given
+ `MovieWriter`.
+
+ bitrate : int, default: :rc:`animation.bitrate`
+ The bitrate of the movie, in kilobits per second. Higher values
+ means higher quality movies, but increase the file size. A value
+ of -1 lets the underlying movie encoder select the bitrate.
+
+ extra_args : list of str or None, optional
+ Extra command-line arguments passed to the underlying movie encoder. These
+ arguments are passed last to the encoder, just before the output filename.
+ The default, None, means to use :rc:`animation.[name-of-encoder]_args` for
+ the builtin writers.
+
+ metadata : dict[str, str], default: {}
+ Dictionary of keys and values for metadata to include in
+ the output file. Some keys that may be of use include:
+ title, artist, genre, subject, copyright, srcform, comment.
+
+ extra_anim : list, default: []
+ Additional `Animation` objects that should be included
+ in the saved movie file. These need to be from the same
+ `.Figure` instance. Also, animation frames will
+ just be simply combined, so there should be a 1:1 correspondence
+ between the frames from the different animations.
+
+ savefig_kwargs : dict, default: {}
+ Keyword arguments passed to each `~.Figure.savefig` call used to
+ save the individual frames.
+
+ progress_callback : function, optional
+ A callback function that will be called for every frame to notify
+ the saving progress. It must have the signature ::
+
+ def func(current_frame: int, total_frames: int) -> Any
+
+ where *current_frame* is the current frame number and *total_frames* is the
+ total number of frames to be saved. *total_frames* is set to None, if the
+ total number of frames cannot be determined. Return values may exist but are
+ ignored.
+
+ Example code to write the progress to stdout::
+
+ progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
+
+ Notes
+ -----
+ *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
+ construct a `.MovieWriter` instance and can only be passed if
+ *writer* is a string. If they are passed as non-*None* and *writer*
+ is a `.MovieWriter`, a `RuntimeError` will be raised.
+ """
+
+ all_anim = [self]
+ if extra_anim is not None:
+ all_anim.extend(anim for anim in extra_anim
+ if anim._fig is self._fig)
+
+ # Disable "Animation was deleted without rendering" warning.
+ for anim in all_anim:
+ anim._draw_was_started = True
+
+ if writer is None:
+ writer = mpl.rcParams['animation.writer']
+ elif (not isinstance(writer, str) and
+ any(arg is not None
+ for arg in (fps, codec, bitrate, extra_args, metadata))):
+ raise RuntimeError('Passing in values for arguments '
+ 'fps, codec, bitrate, extra_args, or metadata '
+ 'is not supported when writer is an existing '
+ 'MovieWriter instance. These should instead be '
+ 'passed as arguments when creating the '
+ 'MovieWriter instance.')
+
+ if savefig_kwargs is None:
+ savefig_kwargs = {}
+ else:
+ # we are going to mutate this below
+ savefig_kwargs = dict(savefig_kwargs)
+
+ if fps is None and hasattr(self, '_interval'):
+ # Convert interval in ms to frames per second
+ fps = 1000. / self._interval
+
+ # Reuse the savefig DPI for ours if none is given.
+ dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
+ if dpi == 'figure':
+ dpi = self._fig.dpi
+
+ writer_kwargs = {}
+ if codec is not None:
+ writer_kwargs['codec'] = codec
+ if bitrate is not None:
+ writer_kwargs['bitrate'] = bitrate
+ if extra_args is not None:
+ writer_kwargs['extra_args'] = extra_args
+ if metadata is not None:
+ writer_kwargs['metadata'] = metadata
+
+ # If we have the name of a writer, instantiate an instance of the
+ # registered class.
+ if isinstance(writer, str):
+ try:
+ writer_cls = writers[writer]
+ except RuntimeError: # Raised if not available.
+ writer_cls = PillowWriter # Always available.
+ _log.warning("MovieWriter %s unavailable; using Pillow "
+ "instead.", writer)
+ writer = writer_cls(fps, **writer_kwargs)
+ _log.info('Animation.save using %s', type(writer))
+
+ if 'bbox_inches' in savefig_kwargs:
+ _log.warning("Warning: discarding the 'bbox_inches' argument in "
+ "'savefig_kwargs' as it may cause frame size "
+ "to vary, which is inappropriate for animation.")
+ savefig_kwargs.pop('bbox_inches')
+
+ # Create a new sequence of frames for saved data. This is different
+ # from new_frame_seq() to give the ability to save 'live' generated
+ # frame information to be saved later.
+ # TODO: Right now, after closing the figure, saving a movie won't work
+ # since GUI widgets are gone. Either need to remove extra code to
+ # allow for this non-existent use case or find a way to make it work.
+
+ def _pre_composite_to_white(color):
+ r, g, b, a = mcolors.to_rgba(color)
+ return a * np.array([r, g, b]) + 1 - a
+
+ # canvas._is_saving = True makes the draw_event animation-starting
+ # callback a no-op; canvas.manager = None prevents resizing the GUI
+ # widget (both are likewise done in savefig()).
+ with (writer.saving(self._fig, filename, dpi),
+ cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None)):
+ if not writer._supports_transparency():
+ facecolor = savefig_kwargs.get('facecolor',
+ mpl.rcParams['savefig.facecolor'])
+ if facecolor == 'auto':
+ facecolor = self._fig.get_facecolor()
+ savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor)
+ savefig_kwargs['transparent'] = False # just to be safe!
+
+ for anim in all_anim:
+ anim._init_draw() # Clear the initial frame
+ frame_number = 0
+ # TODO: Currently only FuncAnimation has a save_count
+ # attribute. Can we generalize this to all Animations?
+ save_count_list = [getattr(a, '_save_count', None)
+ for a in all_anim]
+ if None in save_count_list:
+ total_frames = None
+ else:
+ total_frames = sum(save_count_list)
+ for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
+ for anim, d in zip(all_anim, data):
+ # TODO: See if turning off blit is really necessary
+ anim._draw_next_frame(d, blit=False)
+ if progress_callback is not None:
+ progress_callback(frame_number, total_frames)
+ frame_number += 1
+ writer.grab_frame(**savefig_kwargs)
+
+ def _step(self, *args):
+ """
+ Handler for getting events. By default, gets the next frame in the
+ sequence and hands the data off to be drawn.
+ """
+ # Returns True to indicate that the event source should continue to
+ # call _step, until the frame sequence reaches the end of iteration,
+ # at which point False will be returned.
+ try:
+ framedata = next(self.frame_seq)
+ self._draw_next_frame(framedata, self._blit)
+ return True
+ except StopIteration:
+ return False
+
+ def new_frame_seq(self):
+ """Return a new sequence of frame information."""
+ # Default implementation is just an iterator over self._framedata
+ return iter(self._framedata)
+
+ def new_saved_frame_seq(self):
+ """Return a new sequence of saved/cached frame information."""
+ # Default is the same as the regular frame sequence
+ return self.new_frame_seq()
+
+ def _draw_next_frame(self, framedata, blit):
+ # Breaks down the drawing of the next frame into steps of pre- and
+ # post- draw, as well as the drawing of the frame itself.
+ self._pre_draw(framedata, blit)
+ self._draw_frame(framedata)
+ self._post_draw(framedata, blit)
+
+ def _init_draw(self):
+ # Initial draw to clear the frame. Also used by the blitting code
+ # when a clean base is required.
+ self._draw_was_started = True
+
+ def _pre_draw(self, framedata, blit):
+ # Perform any cleaning or whatnot before the drawing of the frame.
+ # This default implementation allows blit to clear the frame.
+ if blit:
+ self._blit_clear(self._drawn_artists)
+
+ def _draw_frame(self, framedata):
+ # Performs actual drawing of the frame.
+ raise NotImplementedError('Needs to be implemented by subclasses to'
+ ' actually make an animation.')
+
+ def _post_draw(self, framedata, blit):
+ # After the frame is rendered, this handles the actual flushing of
+ # the draw, which can be a direct draw_idle() or make use of the
+ # blitting.
+ if blit and self._drawn_artists:
+ self._blit_draw(self._drawn_artists)
+ else:
+ self._fig.canvas.draw_idle()
+
+ # The rest of the code in this class is to facilitate easy blitting
+ def _blit_draw(self, artists):
+ # Handles blitted drawing, which renders only the artists given instead
+ # of the entire figure.
+ updated_ax = {a.axes for a in artists}
+ # Enumerate artists to cache Axes backgrounds. We do not draw
+ # artists yet to not cache foreground from plots with shared Axes
+ for ax in updated_ax:
+ # If we haven't cached the background for the current view of this
+ # Axes object, do so now. This might not always be reliable, but
+ # it's an attempt to automate the process.
+ cur_view = ax._get_view()
+ view, bg = self._blit_cache.get(ax, (object(), None))
+ if cur_view != view:
+ self._blit_cache[ax] = (
+ cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox))
+ # Make a separate pass to draw foreground.
+ for a in artists:
+ a.axes.draw_artist(a)
+ # After rendering all the needed artists, blit each Axes individually.
+ for ax in updated_ax:
+ ax.figure.canvas.blit(ax.bbox)
+
+ def _blit_clear(self, artists):
+ # Get a list of the Axes that need clearing from the artists that
+ # have been drawn. Grab the appropriate saved background from the
+ # cache and restore.
+ axes = {a.axes for a in artists}
+ for ax in axes:
+ try:
+ view, bg = self._blit_cache[ax]
+ except KeyError:
+ continue
+ if ax._get_view() == view:
+ ax.figure.canvas.restore_region(bg)
+ else:
+ self._blit_cache.pop(ax)
+
+ def _setup_blit(self):
+ # Setting up the blit requires: a cache of the background for the Axes
+ self._blit_cache = dict()
+ self._drawn_artists = []
+ # _post_draw needs to be called first to initialize the renderer
+ self._post_draw(None, self._blit)
+ # Then we need to clear the Frame for the initial draw
+ # This is typically handled in _on_resize because QT and Tk
+ # emit a resize event on launch, but the macosx backend does not,
+ # thus we force it here for everyone for consistency
+ self._init_draw()
+ # Connect to future resize events
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
+ self._on_resize)
+
+ def _on_resize(self, event):
+ # On resize, we need to disable the resize event handling so we don't
+ # get too many events. Also stop the animation events, so that
+ # we're paused. Reset the cache and re-init. Set up an event handler
+ # to catch once the draw has actually taken place.
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self.event_source.stop()
+ self._blit_cache.clear()
+ self._init_draw()
+ self._resize_id = self._fig.canvas.mpl_connect('draw_event',
+ self._end_redraw)
+
+ def _end_redraw(self, event):
+ # Now that the redraw has happened, do the post draw flushing and
+ # blit handling. Then re-enable all of the original events.
+ self._post_draw(None, False)
+ self.event_source.start()
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
+ self._on_resize)
+
+ def to_html5_video(self, embed_limit=None):
+ """
+ Convert the animation to an HTML5 ```` tag.
+
+ This saves the animation as an h264 video, encoded in base64
+ directly into the HTML5 video tag. This respects :rc:`animation.writer`
+ and :rc:`animation.bitrate`. This also makes use of the
+ *interval* to control the speed, and uses the *repeat*
+ parameter to decide whether to loop.
+
+ Parameters
+ ----------
+ embed_limit : float, optional
+ Limit, in MB, of the returned animation. No animation is created
+ if the limit is exceeded.
+ Defaults to :rc:`animation.embed_limit` = 20.0.
+
+ Returns
+ -------
+ str
+ An HTML5 video tag with the animation embedded as base64 encoded
+ h264 video.
+ If the *embed_limit* is exceeded, this returns the string
+ "Video too large to embed."
+ """
+ VIDEO_TAG = r'''
+
+ Your browser does not support the video tag.
+ '''
+ # Cache the rendering of the video as HTML
+ if not hasattr(self, '_base64_video'):
+ # Save embed limit, which is given in MB
+ embed_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
+
+ # Convert from MB to bytes
+ embed_limit *= 1024 * 1024
+
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
+ # TemporaryDirectory instead.
+ with TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir, "temp.m4v")
+ # We create a writer manually so that we can get the
+ # appropriate size for the tag
+ Writer = writers[mpl.rcParams['animation.writer']]
+ writer = Writer(codec='h264',
+ bitrate=mpl.rcParams['animation.bitrate'],
+ fps=1000. / self._interval)
+ self.save(str(path), writer=writer)
+ # Now open and base64 encode.
+ vid64 = base64.encodebytes(path.read_bytes())
+
+ vid_len = len(vid64)
+ if vid_len >= embed_limit:
+ _log.warning(
+ "Animation movie is %s bytes, exceeding the limit of %s. "
+ "If you're sure you want a large animation embedded, set "
+ "the animation.embed_limit rc parameter to a larger value "
+ "(in MB).", vid_len, embed_limit)
+ else:
+ self._base64_video = vid64.decode('ascii')
+ self._video_size = 'width="{}" height="{}"'.format(
+ *writer.frame_size)
+
+ # If we exceeded the size, this attribute won't exist
+ if hasattr(self, '_base64_video'):
+ # Default HTML5 options are to autoplay and display video controls
+ options = ['controls', 'autoplay']
+
+ # If we're set to repeat, make it loop
+ if getattr(self, '_repeat', False):
+ options.append('loop')
+
+ return VIDEO_TAG.format(video=self._base64_video,
+ size=self._video_size,
+ options=' '.join(options))
+ else:
+ return 'Video too large to embed.'
+
+ def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
+ """
+ Generate HTML representation of the animation.
+
+ Parameters
+ ----------
+ fps : int, optional
+ Movie frame rate (per second). If not set, the frame rate from
+ the animation's frame interval.
+ embed_frames : bool, optional
+ default_mode : str, optional
+ What to do when the animation ends. Must be one of ``{'loop',
+ 'once', 'reflect'}``. Defaults to ``'loop'`` if the *repeat*
+ parameter is True, otherwise ``'once'``.
+
+ Returns
+ -------
+ str
+ An HTML representation of the animation embedded as a js object as
+ produced with the `.HTMLWriter`.
+ """
+ if fps is None and hasattr(self, '_interval'):
+ # Convert interval in ms to frames per second
+ fps = 1000 / self._interval
+
+ # If we're not given a default mode, choose one base on the value of
+ # the _repeat attribute
+ if default_mode is None:
+ default_mode = 'loop' if getattr(self, '_repeat',
+ False) else 'once'
+
+ if not hasattr(self, "_html_representation"):
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
+ # TemporaryDirectory instead.
+ with TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir, "temp.html")
+ writer = HTMLWriter(fps=fps,
+ embed_frames=embed_frames,
+ default_mode=default_mode)
+ self.save(str(path), writer=writer)
+ self._html_representation = path.read_text()
+
+ return self._html_representation
+
+ def _repr_html_(self):
+ """IPython display hook for rendering."""
+ fmt = mpl.rcParams['animation.html']
+ if fmt == 'html5':
+ return self.to_html5_video()
+ elif fmt == 'jshtml':
+ return self.to_jshtml()
+
+ def pause(self):
+ """Pause the animation."""
+ self.event_source.stop()
+ if self._blit:
+ for artist in self._drawn_artists:
+ artist.set_animated(False)
+
+ def resume(self):
+ """Resume the animation."""
+ self.event_source.start()
+ if self._blit:
+ for artist in self._drawn_artists:
+ artist.set_animated(True)
+
+
+class TimedAnimation(Animation):
+ """
+ `Animation` subclass for time-based animation.
+
+ A new frame is drawn every *interval* milliseconds.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+ interval : int, default: 200
+ Delay between frames in milliseconds.
+ repeat_delay : int, default: 0
+ The delay in milliseconds between consecutive animation runs, if
+ *repeat* is True.
+ repeat : bool, default: True
+ Whether the animation repeats when the sequence of frames is completed.
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing.
+ """
+ def __init__(self, fig, interval=200, repeat_delay=0, repeat=True,
+ event_source=None, *args, **kwargs):
+ self._interval = interval
+ # Undocumented support for repeat_delay = None as backcompat.
+ self._repeat_delay = repeat_delay if repeat_delay is not None else 0
+ self._repeat = repeat
+ # If we're not given an event source, create a new timer. This permits
+ # sharing timers between animation objects for syncing animations.
+ if event_source is None:
+ event_source = fig.canvas.new_timer(interval=self._interval)
+ super().__init__(fig, event_source=event_source, *args, **kwargs)
+
+ def _step(self, *args):
+ """Handler for getting events."""
+ # Extends the _step() method for the Animation class. If
+ # Animation._step signals that it reached the end and we want to
+ # repeat, we refresh the frame sequence and return True. If
+ # _repeat_delay is set, change the event_source's interval to our loop
+ # delay and set the callback to one which will then set the interval
+ # back.
+ still_going = super()._step(*args)
+ if not still_going:
+ if self._repeat:
+ # Restart the draw loop
+ self._init_draw()
+ self.frame_seq = self.new_frame_seq()
+ self.event_source.interval = self._repeat_delay
+ return True
+ else:
+ # We are done with the animation. Call pause to remove
+ # animated flags from artists that were using blitting
+ self.pause()
+ if self._blit:
+ # Remove the resize callback if we were blitting
+ self._fig.canvas.mpl_disconnect(self._resize_id)
+ self._fig.canvas.mpl_disconnect(self._close_id)
+ self.event_source = None
+ return False
+
+ self.event_source.interval = self._interval
+ return True
+
+
+class ArtistAnimation(TimedAnimation):
+ """
+ `TimedAnimation` subclass that creates an animation by using a fixed
+ set of `.Artist` objects.
+
+ Before creating an instance, all plotting should have taken place
+ and the relevant artists saved.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+ artists : list
+ Each list entry is a collection of `.Artist` objects that are made
+ visible on the corresponding frame. Other artists are made invisible.
+ interval : int, default: 200
+ Delay between frames in milliseconds.
+ repeat_delay : int, default: 0
+ The delay in milliseconds between consecutive animation runs, if
+ *repeat* is True.
+ repeat : bool, default: True
+ Whether the animation repeats when the sequence of frames is completed.
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing.
+ """
+
+ def __init__(self, fig, artists, *args, **kwargs):
+ # Internal list of artists drawn in the most recent frame.
+ self._drawn_artists = []
+
+ # Use the list of artists as the framedata, which will be iterated
+ # over by the machinery.
+ self._framedata = artists
+ super().__init__(fig, *args, **kwargs)
+
+ def _init_draw(self):
+ super()._init_draw()
+ # Make all the artists involved in *any* frame invisible
+ figs = set()
+ for f in self.new_frame_seq():
+ for artist in f:
+ artist.set_visible(False)
+ artist.set_animated(self._blit)
+ # Assemble a list of unique figures that need flushing
+ if artist.get_figure() not in figs:
+ figs.add(artist.get_figure())
+
+ # Flush the needed figures
+ for fig in figs:
+ fig.canvas.draw_idle()
+
+ def _pre_draw(self, framedata, blit):
+ """Clears artists from the last frame."""
+ if blit:
+ # Let blit handle clearing
+ self._blit_clear(self._drawn_artists)
+ else:
+ # Otherwise, make all the artists from the previous frame invisible
+ for artist in self._drawn_artists:
+ artist.set_visible(False)
+
+ def _draw_frame(self, artists):
+ # Save the artists that were passed in as framedata for the other
+ # steps (esp. blitting) to use.
+ self._drawn_artists = artists
+
+ # Make all the artists from the current frame visible
+ for artist in artists:
+ artist.set_visible(True)
+
+
+class FuncAnimation(TimedAnimation):
+ """
+ `TimedAnimation` subclass that makes an animation by repeatedly calling
+ a function *func*.
+
+ .. note::
+
+ You must store the created Animation in a variable that lives as long
+ as the animation should run. Otherwise, the Animation object will be
+ garbage-collected and the animation stops.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure object used to get needed events, such as draw or resize.
+
+ func : callable
+ The function to call at each frame. The first argument will
+ be the next value in *frames*. Any additional positional
+ arguments can be supplied using `functools.partial` or via the *fargs*
+ parameter.
+
+ The required signature is::
+
+ def func(frame, *fargs) -> iterable_of_artists
+
+ It is often more convenient to provide the arguments using
+ `functools.partial`. In this way it is also possible to pass keyword
+ arguments. To pass a function with both positional and keyword
+ arguments, set all arguments as keyword arguments, just leaving the
+ *frame* argument unset::
+
+ def func(frame, art, *, y=None):
+ ...
+
+ ani = FuncAnimation(fig, partial(func, art=ln, y='foo'))
+
+ If ``blit == True``, *func* must return an iterable of all artists
+ that were modified or created. This information is used by the blitting
+ algorithm to determine which parts of the figure have to be updated.
+ The return value is unused if ``blit == False`` and may be omitted in
+ that case.
+
+ frames : iterable, int, generator function, or None, optional
+ Source of data to pass *func* and each frame of the animation
+
+ - If an iterable, then simply use the values provided. If the
+ iterable has a length, it will override the *save_count* kwarg.
+
+ - If an integer, then equivalent to passing ``range(frames)``
+
+ - If a generator function, then must have the signature::
+
+ def gen_function() -> obj
+
+ - If *None*, then equivalent to passing ``itertools.count``.
+
+ In all of these cases, the values in *frames* is simply passed through
+ to the user-supplied *func* and thus can be of any type.
+
+ init_func : callable, optional
+ A function used to draw a clear frame. If not given, the results of
+ drawing from the first item in the frames sequence will be used. This
+ function will be called once before the first frame.
+
+ The required signature is::
+
+ def init_func() -> iterable_of_artists
+
+ If ``blit == True``, *init_func* must return an iterable of artists
+ to be re-drawn. This information is used by the blitting algorithm to
+ determine which parts of the figure have to be updated. The return
+ value is unused if ``blit == False`` and may be omitted in that case.
+
+ fargs : tuple or None, optional
+ Additional arguments to pass to each call to *func*. Note: the use of
+ `functools.partial` is preferred over *fargs*. See *func* for details.
+
+ save_count : int, optional
+ Fallback for the number of values from *frames* to cache. This is
+ only used if the number of frames cannot be inferred from *frames*,
+ i.e. when it's an iterator without length or a generator.
+
+ interval : int, default: 200
+ Delay between frames in milliseconds.
+
+ repeat_delay : int, default: 0
+ The delay in milliseconds between consecutive animation runs, if
+ *repeat* is True.
+
+ repeat : bool, default: True
+ Whether the animation repeats when the sequence of frames is completed.
+
+ blit : bool, default: False
+ Whether blitting is used to optimize drawing. Note: when using
+ blitting, any animated artists will be drawn according to their zorder;
+ however, they will be drawn on top of any previous artists, regardless
+ of their zorder.
+
+ cache_frame_data : bool, default: True
+ Whether frame data is cached. Disabling cache might be helpful when
+ frames contain large objects.
+ """
+ def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
+ save_count=None, *, cache_frame_data=True, **kwargs):
+ if fargs:
+ self._args = fargs
+ else:
+ self._args = ()
+ self._func = func
+ self._init_func = init_func
+
+ # Amount of framedata to keep around for saving movies. This is only
+ # used if we don't know how many frames there will be: in the case
+ # of no generator or in the case of a callable.
+ self._save_count = save_count
+ # Set up a function that creates a new iterable when needed. If nothing
+ # is passed in for frames, just use itertools.count, which will just
+ # keep counting from 0. A callable passed in for frames is assumed to
+ # be a generator. An iterable will be used as is, and anything else
+ # will be treated as a number of frames.
+ if frames is None:
+ self._iter_gen = itertools.count
+ elif callable(frames):
+ self._iter_gen = frames
+ elif np.iterable(frames):
+ if kwargs.get('repeat', True):
+ self._tee_from = frames
+ def iter_frames(frames=frames):
+ this, self._tee_from = itertools.tee(self._tee_from, 2)
+ yield from this
+ self._iter_gen = iter_frames
+ else:
+ self._iter_gen = lambda: iter(frames)
+ if hasattr(frames, '__len__'):
+ self._save_count = len(frames)
+ if save_count is not None:
+ _api.warn_external(
+ f"You passed in an explicit {save_count=} "
+ "which is being ignored in favor of "
+ f"{len(frames)=}."
+ )
+ else:
+ self._iter_gen = lambda: iter(range(frames))
+ self._save_count = frames
+ if save_count is not None:
+ _api.warn_external(
+ f"You passed in an explicit {save_count=} which is being "
+ f"ignored in favor of {frames=}."
+ )
+ if self._save_count is None and cache_frame_data:
+ _api.warn_external(
+ f"{frames=!r} which we can infer the length of, "
+ "did not pass an explicit *save_count* "
+ f"and passed {cache_frame_data=}. To avoid a possibly "
+ "unbounded cache, frame data caching has been disabled. "
+ "To suppress this warning either pass "
+ "`cache_frame_data=False` or `save_count=MAX_FRAMES`."
+ )
+ cache_frame_data = False
+
+ self._cache_frame_data = cache_frame_data
+
+ # Needs to be initialized so the draw functions work without checking
+ self._save_seq = []
+
+ super().__init__(fig, **kwargs)
+
+ # Need to reset the saved seq, since right now it will contain data
+ # for a single frame from init, which is not what we want.
+ self._save_seq = []
+
+ def new_frame_seq(self):
+ # Use the generating function to generate a new frame sequence
+ return self._iter_gen()
+
+ def new_saved_frame_seq(self):
+ # Generate an iterator for the sequence of saved data. If there are
+ # no saved frames, generate a new frame sequence and take the first
+ # save_count entries in it.
+ if self._save_seq:
+ # While iterating we are going to update _save_seq
+ # so make a copy to safely iterate over
+ self._old_saved_seq = list(self._save_seq)
+ return iter(self._old_saved_seq)
+ else:
+ if self._save_count is None:
+ frame_seq = self.new_frame_seq()
+
+ def gen():
+ try:
+ while True:
+ yield next(frame_seq)
+ except StopIteration:
+ pass
+ return gen()
+ else:
+ return itertools.islice(self.new_frame_seq(), self._save_count)
+
+ def _init_draw(self):
+ super()._init_draw()
+ # Initialize the drawing either using the given init_func or by
+ # calling the draw function with the first item of the frame sequence.
+ # For blitting, the init_func should return a sequence of modified
+ # artists.
+ if self._init_func is None:
+ try:
+ frame_data = next(self.new_frame_seq())
+ except StopIteration:
+ # we can't start the iteration, it may have already been
+ # exhausted by a previous save or just be 0 length.
+ # warn and bail.
+ warnings.warn(
+ "Can not start iterating the frames for the initial draw. "
+ "This can be caused by passing in a 0 length sequence "
+ "for *frames*.\n\n"
+ "If you passed *frames* as a generator "
+ "it may be exhausted due to a previous display or save."
+ )
+ return
+ self._draw_frame(frame_data)
+ else:
+ self._drawn_artists = self._init_func()
+ if self._blit:
+ if self._drawn_artists is None:
+ raise RuntimeError('The init_func must return a '
+ 'sequence of Artist objects.')
+ for a in self._drawn_artists:
+ a.set_animated(self._blit)
+ self._save_seq = []
+
+ def _draw_frame(self, framedata):
+ if self._cache_frame_data:
+ # Save the data for potential saving of movies.
+ self._save_seq.append(framedata)
+ self._save_seq = self._save_seq[-self._save_count:]
+
+ # Call the func with framedata and args. If blitting is desired,
+ # func needs to return a sequence of any artists that were modified.
+ self._drawn_artists = self._func(framedata, *self._args)
+
+ if self._blit:
+
+ err = RuntimeError('The animation function must return a sequence '
+ 'of Artist objects.')
+ try:
+ # check if a sequence
+ iter(self._drawn_artists)
+ except TypeError:
+ raise err from None
+
+ # check each item if it's artist
+ for i in self._drawn_artists:
+ if not isinstance(i, mpl.artist.Artist):
+ raise err
+
+ self._drawn_artists = sorted(self._drawn_artists,
+ key=lambda x: x.get_zorder())
+
+ for a in self._drawn_artists:
+ a.set_animated(self._blit)
+
+
+def _validate_grabframe_kwargs(savefig_kwargs):
+ if mpl.rcParams['savefig.bbox'] == 'tight':
+ raise ValueError(
+ f"{mpl.rcParams['savefig.bbox']=} must not be 'tight' as it "
+ "may cause frame size to vary, which is inappropriate for animation."
+ )
+ for k in ('dpi', 'bbox_inches', 'format'):
+ if k in savefig_kwargs:
+ raise TypeError(
+ f"grab_frame got an unexpected keyword argument {k!r}"
+ )
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/animation.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/animation.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..345e3c6dbe61f1b3c99eba4c9e77edb0c51cff3e
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/animation.pyi
@@ -0,0 +1,217 @@
+import abc
+from collections.abc import Callable, Collection, Iterable, Sequence, Generator
+import contextlib
+from pathlib import Path
+from matplotlib.artist import Artist
+from matplotlib.backend_bases import TimerBase
+from matplotlib.figure import Figure
+
+from typing import Any
+
+subprocess_creation_flags: int
+
+def adjusted_figsize(w: float, h: float, dpi: float, n: int) -> tuple[float, float]: ...
+
+class MovieWriterRegistry:
+ def __init__(self) -> None: ...
+ def register(
+ self, name: str
+ ) -> Callable[[type[AbstractMovieWriter]], type[AbstractMovieWriter]]: ...
+ def is_available(self, name: str) -> bool: ...
+ def __iter__(self) -> Generator[str, None, None]: ...
+ def list(self) -> list[str]: ...
+ def __getitem__(self, name: str) -> type[AbstractMovieWriter]: ...
+
+writers: MovieWriterRegistry
+
+class AbstractMovieWriter(abc.ABC, metaclass=abc.ABCMeta):
+ fps: int
+ metadata: dict[str, str]
+ codec: str
+ bitrate: int
+ def __init__(
+ self,
+ fps: int = ...,
+ metadata: dict[str, str] | None = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ ) -> None: ...
+ outfile: str | Path
+ fig: Figure
+ dpi: float
+
+ @abc.abstractmethod
+ def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
+ @property
+ def frame_size(self) -> tuple[int, int]: ...
+ @abc.abstractmethod
+ def grab_frame(self, **savefig_kwargs) -> None: ...
+ @abc.abstractmethod
+ def finish(self) -> None: ...
+ @contextlib.contextmanager
+ def saving(
+ self, fig: Figure, outfile: str | Path, dpi: float | None, *args, **kwargs
+ ) -> Generator[AbstractMovieWriter, None, None]: ...
+
+class MovieWriter(AbstractMovieWriter):
+ supported_formats: list[str]
+ frame_format: str
+ extra_args: list[str] | None
+ def __init__(
+ self,
+ fps: int = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ extra_args: list[str] | None = ...,
+ metadata: dict[str, str] | None = ...,
+ ) -> None: ...
+ def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
+ def grab_frame(self, **savefig_kwargs) -> None: ...
+ def finish(self) -> None: ...
+ @classmethod
+ def bin_path(cls) -> str: ...
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+
+class FileMovieWriter(MovieWriter):
+ fig: Figure
+ outfile: str | Path
+ dpi: float
+ temp_prefix: str
+ fname_format_str: str
+ def setup(
+ self,
+ fig: Figure,
+ outfile: str | Path,
+ dpi: float | None = ...,
+ frame_prefix: str | Path | None = ...,
+ ) -> None: ...
+ def __del__(self) -> None: ...
+ @property
+ def frame_format(self) -> str: ...
+ @frame_format.setter
+ def frame_format(self, frame_format: str) -> None: ...
+
+class PillowWriter(AbstractMovieWriter):
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+ def setup(
+ self, fig: Figure, outfile: str | Path, dpi: float | None = ...
+ ) -> None: ...
+ def grab_frame(self, **savefig_kwargs) -> None: ...
+ def finish(self) -> None: ...
+
+class FFMpegBase:
+ codec: str
+ @property
+ def output_args(self) -> list[str]: ...
+
+class FFMpegWriter(FFMpegBase, MovieWriter): ...
+
+class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
+ supported_formats: list[str]
+
+class ImageMagickBase:
+ @classmethod
+ def bin_path(cls) -> str: ...
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+
+class ImageMagickWriter(ImageMagickBase, MovieWriter):
+ input_names: str
+
+class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
+ supported_formats: list[str]
+ @property
+ def input_names(self) -> str: ...
+
+class HTMLWriter(FileMovieWriter):
+ supported_formats: list[str]
+ @classmethod
+ def isAvailable(cls) -> bool: ...
+ embed_frames: bool
+ default_mode: str
+ def __init__(
+ self,
+ fps: int = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ extra_args: list[str] | None = ...,
+ metadata: dict[str, str] | None = ...,
+ embed_frames: bool = ...,
+ default_mode: str = ...,
+ embed_limit: float | None = ...,
+ ) -> None: ...
+ def setup(
+ self,
+ fig: Figure,
+ outfile: str | Path,
+ dpi: float | None = ...,
+ frame_dir: str | Path | None = ...,
+ ) -> None: ...
+ def grab_frame(self, **savefig_kwargs): ...
+ def finish(self) -> None: ...
+
+class Animation:
+ frame_seq: Iterable[Artist]
+ event_source: Any
+ def __init__(
+ self, fig: Figure, event_source: Any | None = ..., blit: bool = ...
+ ) -> None: ...
+ def __del__(self) -> None: ...
+ def save(
+ self,
+ filename: str | Path,
+ writer: AbstractMovieWriter | str | None = ...,
+ fps: int | None = ...,
+ dpi: float | None = ...,
+ codec: str | None = ...,
+ bitrate: int | None = ...,
+ extra_args: list[str] | None = ...,
+ metadata: dict[str, str] | None = ...,
+ extra_anim: list[Animation] | None = ...,
+ savefig_kwargs: dict[str, Any] | None = ...,
+ *,
+ progress_callback: Callable[[int, int], Any] | None = ...
+ ) -> None: ...
+ def new_frame_seq(self) -> Iterable[Artist]: ...
+ def new_saved_frame_seq(self) -> Iterable[Artist]: ...
+ def to_html5_video(self, embed_limit: float | None = ...) -> str: ...
+ def to_jshtml(
+ self,
+ fps: int | None = ...,
+ embed_frames: bool = ...,
+ default_mode: str | None = ...,
+ ) -> str: ...
+ def _repr_html_(self) -> str: ...
+ def pause(self) -> None: ...
+ def resume(self) -> None: ...
+
+class TimedAnimation(Animation):
+ def __init__(
+ self,
+ fig: Figure,
+ interval: int = ...,
+ repeat_delay: int = ...,
+ repeat: bool = ...,
+ event_source: TimerBase | None = ...,
+ *args,
+ **kwargs
+ ) -> None: ...
+
+class ArtistAnimation(TimedAnimation):
+ def __init__(self, fig: Figure, artists: Sequence[Collection[Artist]], *args, **kwargs) -> None: ...
+
+class FuncAnimation(TimedAnimation):
+ def __init__(
+ self,
+ fig: Figure,
+ func: Callable[..., Iterable[Artist]],
+ frames: Iterable | int | Callable[[], Generator] | None = ...,
+ init_func: Callable[[], Iterable[Artist]] | None = ...,
+ fargs: tuple[Any, ...] | None = ...,
+ save_count: int | None = ...,
+ *,
+ cache_frame_data: bool = ...,
+ **kwargs
+ ) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/artist.py b/llava_video/lib/python3.10/site-packages/matplotlib/artist.py
new file mode 100644
index 0000000000000000000000000000000000000000..17724c8b027af6f7c16d4ad97e0c6559cc119232
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/artist.py
@@ -0,0 +1,1855 @@
+from collections import namedtuple
+import contextlib
+from functools import cache, reduce, wraps
+import inspect
+from inspect import Signature, Parameter
+import logging
+from numbers import Number, Real
+import operator
+import re
+import warnings
+
+import numpy as np
+
+import matplotlib as mpl
+from . import _api, cbook
+from .path import Path
+from .transforms import (BboxBase, Bbox, IdentityTransform, Transform, TransformedBbox,
+ TransformedPatchPath, TransformedPath)
+
+_log = logging.getLogger(__name__)
+
+
+def _prevent_rasterization(draw):
+ # We assume that by default artists are not allowed to rasterize (unless
+ # its draw method is explicitly decorated). If it is being drawn after a
+ # rasterized artist and it has reached a raster_depth of 0, we stop
+ # rasterization so that it does not affect the behavior of normal artist
+ # (e.g., change in dpi).
+
+ @wraps(draw)
+ def draw_wrapper(artist, renderer, *args, **kwargs):
+ if renderer._raster_depth == 0 and renderer._rasterizing:
+ # Only stop when we are not in a rasterized parent
+ # and something has been rasterized since last stop.
+ renderer.stop_rasterizing()
+ renderer._rasterizing = False
+
+ return draw(artist, renderer, *args, **kwargs)
+
+ draw_wrapper._supports_rasterization = False
+ return draw_wrapper
+
+
+def allow_rasterization(draw):
+ """
+ Decorator for Artist.draw method. Provides routines
+ that run before and after the draw call. The before and after functions
+ are useful for changing artist-dependent renderer attributes or making
+ other setup function calls, such as starting and flushing a mixed-mode
+ renderer.
+ """
+
+ @wraps(draw)
+ def draw_wrapper(artist, renderer):
+ try:
+ if artist.get_rasterized():
+ if renderer._raster_depth == 0 and not renderer._rasterizing:
+ renderer.start_rasterizing()
+ renderer._rasterizing = True
+ renderer._raster_depth += 1
+ else:
+ if renderer._raster_depth == 0 and renderer._rasterizing:
+ # Only stop when we are not in a rasterized parent
+ # and something has be rasterized since last stop
+ renderer.stop_rasterizing()
+ renderer._rasterizing = False
+
+ if artist.get_agg_filter() is not None:
+ renderer.start_filter()
+
+ return draw(artist, renderer)
+ finally:
+ if artist.get_agg_filter() is not None:
+ renderer.stop_filter(artist.get_agg_filter())
+ if artist.get_rasterized():
+ renderer._raster_depth -= 1
+ if (renderer._rasterizing and (fig := artist.get_figure(root=True)) and
+ fig.suppressComposite):
+ # restart rasterizing to prevent merging
+ renderer.stop_rasterizing()
+ renderer.start_rasterizing()
+
+ draw_wrapper._supports_rasterization = True
+ return draw_wrapper
+
+
+def _finalize_rasterization(draw):
+ """
+ Decorator for Artist.draw method. Needed on the outermost artist, i.e.
+ Figure, to finish up if the render is still in rasterized mode.
+ """
+ @wraps(draw)
+ def draw_wrapper(artist, renderer, *args, **kwargs):
+ result = draw(artist, renderer, *args, **kwargs)
+ if renderer._rasterizing:
+ renderer.stop_rasterizing()
+ renderer._rasterizing = False
+ return result
+ return draw_wrapper
+
+
+def _stale_axes_callback(self, val):
+ if self.axes:
+ self.axes.stale = val
+
+
+_XYPair = namedtuple("_XYPair", "x y")
+
+
+class _Unset:
+ def __repr__(self):
+ return ""
+_UNSET = _Unset()
+
+
+class Artist:
+ """
+ Abstract base class for objects that render into a FigureCanvas.
+
+ Typically, all visible elements in a figure are subclasses of Artist.
+ """
+
+ zorder = 0
+
+ def __init_subclass__(cls):
+
+ # Decorate draw() method so that all artists are able to stop
+ # rastrization when necessary. If the artist's draw method is already
+ # decorated (has a `_supports_rasterization` attribute), it won't be
+ # decorated.
+
+ if not hasattr(cls.draw, "_supports_rasterization"):
+ cls.draw = _prevent_rasterization(cls.draw)
+
+ # Inject custom set() methods into the subclass with signature and
+ # docstring based on the subclasses' properties.
+
+ if not hasattr(cls.set, '_autogenerated_signature'):
+ # Don't overwrite cls.set if the subclass or one of its parents
+ # has defined a set method set itself.
+ # If there was no explicit definition, cls.set is inherited from
+ # the hierarchy of auto-generated set methods, which hold the
+ # flag _autogenerated_signature.
+ return
+
+ cls.set = lambda self, **kwargs: Artist.set(self, **kwargs)
+ cls.set.__name__ = "set"
+ cls.set.__qualname__ = f"{cls.__qualname__}.set"
+ cls._update_set_signature_and_docstring()
+
+ _PROPERTIES_EXCLUDED_FROM_SET = [
+ 'navigate_mode', # not a user-facing function
+ 'figure', # changing the figure is such a profound operation
+ # that we don't want this in set()
+ '3d_properties', # cannot be used as a keyword due to leading digit
+ ]
+
+ @classmethod
+ def _update_set_signature_and_docstring(cls):
+ """
+ Update the signature of the set function to list all properties
+ as keyword arguments.
+
+ Property aliases are not listed in the signature for brevity, but
+ are still accepted as keyword arguments.
+ """
+ cls.set.__signature__ = Signature(
+ [Parameter("self", Parameter.POSITIONAL_OR_KEYWORD),
+ *[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET)
+ for prop in ArtistInspector(cls).get_setters()
+ if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]])
+ cls.set._autogenerated_signature = True
+
+ cls.set.__doc__ = (
+ "Set multiple properties at once.\n\n"
+ "Supported properties are\n\n"
+ + kwdoc(cls))
+
+ def __init__(self):
+ self._stale = True
+ self.stale_callback = None
+ self._axes = None
+ self._parent_figure = None
+
+ self._transform = None
+ self._transformSet = False
+ self._visible = True
+ self._animated = False
+ self._alpha = None
+ self.clipbox = None
+ self._clippath = None
+ self._clipon = True
+ self._label = ''
+ self._picker = None
+ self._rasterized = False
+ self._agg_filter = None
+ # Normally, artist classes need to be queried for mouseover info if and
+ # only if they override get_cursor_data.
+ self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data
+ self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
+ try:
+ self.axes = None
+ except AttributeError:
+ # Handle self.axes as a read-only property, as in Figure.
+ pass
+ self._remove_method = None
+ self._url = None
+ self._gid = None
+ self._snap = None
+ self._sketch = mpl.rcParams['path.sketch']
+ self._path_effects = mpl.rcParams['path.effects']
+ self._sticky_edges = _XYPair([], [])
+ self._in_layout = True
+
+ def __getstate__(self):
+ d = self.__dict__.copy()
+ d['stale_callback'] = None
+ return d
+
+ def remove(self):
+ """
+ Remove the artist from the figure if possible.
+
+ The effect will not be visible until the figure is redrawn, e.g.,
+ with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to
+ update the Axes limits if desired.
+
+ Note: `~.axes.Axes.relim` will not see collections even if the
+ collection was added to the Axes with *autolim* = True.
+
+ Note: there is no support for removing the artist's legend entry.
+ """
+
+ # There is no method to set the callback. Instead, the parent should
+ # set the _remove_method attribute directly. This would be a
+ # protected attribute if Python supported that sort of thing. The
+ # callback has one parameter, which is the child to be removed.
+ if self._remove_method is not None:
+ self._remove_method(self)
+ # clear stale callback
+ self.stale_callback = None
+ _ax_flag = False
+ if hasattr(self, 'axes') and self.axes:
+ # remove from the mouse hit list
+ self.axes._mouseover_set.discard(self)
+ self.axes.stale = True
+ self.axes = None # decouple the artist from the Axes
+ _ax_flag = True
+
+ if (fig := self.get_figure(root=False)) is not None:
+ if not _ax_flag:
+ fig.stale = True
+ self._parent_figure = None
+
+ else:
+ raise NotImplementedError('cannot remove artist')
+ # TODO: the fix for the collections relim problem is to move the
+ # limits calculation into the artist itself, including the property of
+ # whether or not the artist should affect the limits. Then there will
+ # be no distinction between axes.add_line, axes.add_patch, etc.
+ # TODO: add legend support
+
+ def have_units(self):
+ """Return whether units are set on any axis."""
+ ax = self.axes
+ return ax and any(axis.have_units() for axis in ax._axis_map.values())
+
+ def convert_xunits(self, x):
+ """
+ Convert *x* using the unit type of the xaxis.
+
+ If the artist is not contained in an Axes or if the xaxis does not
+ have units, *x* itself is returned.
+ """
+ ax = getattr(self, 'axes', None)
+ if ax is None or ax.xaxis is None:
+ return x
+ return ax.xaxis.convert_units(x)
+
+ def convert_yunits(self, y):
+ """
+ Convert *y* using the unit type of the yaxis.
+
+ If the artist is not contained in an Axes or if the yaxis does not
+ have units, *y* itself is returned.
+ """
+ ax = getattr(self, 'axes', None)
+ if ax is None or ax.yaxis is None:
+ return y
+ return ax.yaxis.convert_units(y)
+
+ @property
+ def axes(self):
+ """The `~.axes.Axes` instance the artist resides in, or *None*."""
+ return self._axes
+
+ @axes.setter
+ def axes(self, new_axes):
+ if (new_axes is not None and self._axes is not None
+ and new_axes != self._axes):
+ raise ValueError("Can not reset the Axes. You are probably trying to reuse "
+ "an artist in more than one Axes which is not supported")
+ self._axes = new_axes
+ if new_axes is not None and new_axes is not self:
+ self.stale_callback = _stale_axes_callback
+
+ @property
+ def stale(self):
+ """
+ Whether the artist is 'stale' and needs to be re-drawn for the output
+ to match the internal state of the artist.
+ """
+ return self._stale
+
+ @stale.setter
+ def stale(self, val):
+ self._stale = val
+
+ # if the artist is animated it does not take normal part in the
+ # draw stack and is not expected to be drawn as part of the normal
+ # draw loop (when not saving) so do not propagate this change
+ if self._animated:
+ return
+
+ if val and self.stale_callback is not None:
+ self.stale_callback(self, val)
+
+ def get_window_extent(self, renderer=None):
+ """
+ Get the artist's bounding box in display space.
+
+ The bounding box' width and height are nonnegative.
+
+ Subclasses should override for inclusion in the bounding box
+ "tight" calculation. Default is to return an empty bounding
+ box at 0, 0.
+
+ Be careful when using this function, the results will not update
+ if the artist window extent of the artist changes. The extent
+ can change due to any changes in the transform stack, such as
+ changing the Axes limits, the figure size, or the canvas used
+ (as is done when saving a figure). This can lead to unexpected
+ behavior where interactive figures will look fine on the screen,
+ but will save incorrectly.
+ """
+ return Bbox([[0, 0], [0, 0]])
+
+ def get_tightbbox(self, renderer=None):
+ """
+ Like `.Artist.get_window_extent`, but includes any clipping.
+
+ Parameters
+ ----------
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass, optional
+ renderer that will be used to draw the figures (i.e.
+ ``fig.canvas.get_renderer()``)
+
+ Returns
+ -------
+ `.Bbox` or None
+ The enclosing bounding box (in figure pixel coordinates).
+ Returns None if clipping results in no intersection.
+ """
+ bbox = self.get_window_extent(renderer)
+ if self.get_clip_on():
+ clip_box = self.get_clip_box()
+ if clip_box is not None:
+ bbox = Bbox.intersection(bbox, clip_box)
+ clip_path = self.get_clip_path()
+ if clip_path is not None and bbox is not None:
+ clip_path = clip_path.get_fully_transformed_path()
+ bbox = Bbox.intersection(bbox, clip_path.get_extents())
+ return bbox
+
+ def add_callback(self, func):
+ """
+ Add a callback function that will be called whenever one of the
+ `.Artist`'s properties changes.
+
+ Parameters
+ ----------
+ func : callable
+ The callback function. It must have the signature::
+
+ def func(artist: Artist) -> Any
+
+ where *artist* is the calling `.Artist`. Return values may exist
+ but are ignored.
+
+ Returns
+ -------
+ int
+ The observer id associated with the callback. This id can be
+ used for removing the callback with `.remove_callback` later.
+
+ See Also
+ --------
+ remove_callback
+ """
+ # Wrapping func in a lambda ensures it can be connected multiple times
+ # and never gets weakref-gc'ed.
+ return self._callbacks.connect("pchanged", lambda: func(self))
+
+ def remove_callback(self, oid):
+ """
+ Remove a callback based on its observer id.
+
+ See Also
+ --------
+ add_callback
+ """
+ self._callbacks.disconnect(oid)
+
+ def pchanged(self):
+ """
+ Call all of the registered callbacks.
+
+ This function is triggered internally when a property is changed.
+
+ See Also
+ --------
+ add_callback
+ remove_callback
+ """
+ self._callbacks.process("pchanged")
+
+ def is_transform_set(self):
+ """
+ Return whether the Artist has an explicitly set transform.
+
+ This is *True* after `.set_transform` has been called.
+ """
+ return self._transformSet
+
+ def set_transform(self, t):
+ """
+ Set the artist transform.
+
+ Parameters
+ ----------
+ t : `~matplotlib.transforms.Transform`
+ """
+ self._transform = t
+ self._transformSet = True
+ self.pchanged()
+ self.stale = True
+
+ def get_transform(self):
+ """Return the `.Transform` instance used by this artist."""
+ if self._transform is None:
+ self._transform = IdentityTransform()
+ elif (not isinstance(self._transform, Transform)
+ and hasattr(self._transform, '_as_mpl_transform')):
+ self._transform = self._transform._as_mpl_transform(self.axes)
+ return self._transform
+
+ def get_children(self):
+ r"""Return a list of the child `.Artist`\s of this `.Artist`."""
+ return []
+
+ def _different_canvas(self, event):
+ """
+ Check whether an *event* occurred on a canvas other that this artist's canvas.
+
+ If this method returns True, the event definitely occurred on a different
+ canvas; if it returns False, either it occurred on the same canvas, or we may
+ not have enough information to know.
+
+ Subclasses should start their definition of `contains` as follows::
+
+ if self._different_canvas(mouseevent):
+ return False, {}
+ # subclass-specific implementation follows
+ """
+ return (getattr(event, "canvas", None) is not None
+ and (fig := self.get_figure(root=True)) is not None
+ and event.canvas is not fig.canvas)
+
+ def contains(self, mouseevent):
+ """
+ Test whether the artist contains the mouse event.
+
+ Parameters
+ ----------
+ mouseevent : `~matplotlib.backend_bases.MouseEvent`
+
+ Returns
+ -------
+ contains : bool
+ Whether any values are within the radius.
+ details : dict
+ An artist-specific dictionary of details of the event context,
+ such as which points are contained in the pick radius. See the
+ individual Artist subclasses for details.
+ """
+ _log.warning("%r needs 'contains' method", self.__class__.__name__)
+ return False, {}
+
+ def pickable(self):
+ """
+ Return whether the artist is pickable.
+
+ See Also
+ --------
+ .Artist.set_picker, .Artist.get_picker, .Artist.pick
+ """
+ return self.get_figure(root=False) is not None and self._picker is not None
+
+ def pick(self, mouseevent):
+ """
+ Process a pick event.
+
+ Each child artist will fire a pick event if *mouseevent* is over
+ the artist and the artist has picker set.
+
+ See Also
+ --------
+ .Artist.set_picker, .Artist.get_picker, .Artist.pickable
+ """
+ from .backend_bases import PickEvent # Circular import.
+ # Pick self
+ if self.pickable():
+ picker = self.get_picker()
+ if callable(picker):
+ inside, prop = picker(self, mouseevent)
+ else:
+ inside, prop = self.contains(mouseevent)
+ if inside:
+ PickEvent("pick_event", self.get_figure(root=True).canvas,
+ mouseevent, self, **prop)._process()
+
+ # Pick children
+ for a in self.get_children():
+ # make sure the event happened in the same Axes
+ ax = getattr(a, 'axes', None)
+ if (isinstance(a, mpl.figure.SubFigure)
+ or mouseevent.inaxes is None or ax is None
+ or mouseevent.inaxes == ax):
+ # we need to check if mouseevent.inaxes is None
+ # because some objects associated with an Axes (e.g., a
+ # tick label) can be outside the bounding box of the
+ # Axes and inaxes will be None
+ # also check that ax is None so that it traverse objects
+ # which do not have an axes property but children might
+ a.pick(mouseevent)
+
+ def set_picker(self, picker):
+ """
+ Define the picking behavior of the artist.
+
+ Parameters
+ ----------
+ picker : None or bool or float or callable
+ This can be one of the following:
+
+ - *None*: Picking is disabled for this artist (default).
+
+ - A boolean: If *True* then picking will be enabled and the
+ artist will fire a pick event if the mouse event is over
+ the artist.
+
+ - A float: If picker is a number it is interpreted as an
+ epsilon tolerance in points and the artist will fire
+ off an event if its data is within epsilon of the mouse
+ event. For some artists like lines and patch collections,
+ the artist may provide additional data to the pick event
+ that is generated, e.g., the indices of the data within
+ epsilon of the pick event
+
+ - A function: If picker is callable, it is a user supplied
+ function which determines whether the artist is hit by the
+ mouse event::
+
+ hit, props = picker(artist, mouseevent)
+
+ to determine the hit test. if the mouse event is over the
+ artist, return *hit=True* and props is a dictionary of
+ properties you want added to the PickEvent attributes.
+ """
+ self._picker = picker
+
+ def get_picker(self):
+ """
+ Return the picking behavior of the artist.
+
+ The possible values are described in `.Artist.set_picker`.
+
+ See Also
+ --------
+ .Artist.set_picker, .Artist.pickable, .Artist.pick
+ """
+ return self._picker
+
+ def get_url(self):
+ """Return the url."""
+ return self._url
+
+ def set_url(self, url):
+ """
+ Set the url for the artist.
+
+ Parameters
+ ----------
+ url : str
+ """
+ self._url = url
+
+ def get_gid(self):
+ """Return the group id."""
+ return self._gid
+
+ def set_gid(self, gid):
+ """
+ Set the (group) id for the artist.
+
+ Parameters
+ ----------
+ gid : str
+ """
+ self._gid = gid
+
+ def get_snap(self):
+ """
+ Return the snap setting.
+
+ See `.set_snap` for details.
+ """
+ if mpl.rcParams['path.snap']:
+ return self._snap
+ else:
+ return False
+
+ def set_snap(self, snap):
+ """
+ Set the snapping behavior.
+
+ Snapping aligns positions with the pixel grid, which results in
+ clearer images. For example, if a black line of 1px width was
+ defined at a position in between two pixels, the resulting image
+ would contain the interpolated value of that line in the pixel grid,
+ which would be a grey value on both adjacent pixel positions. In
+ contrast, snapping will move the line to the nearest integer pixel
+ value, so that the resulting image will really contain a 1px wide
+ black line.
+
+ Snapping is currently only supported by the Agg and MacOSX backends.
+
+ Parameters
+ ----------
+ snap : bool or None
+ Possible values:
+
+ - *True*: Snap vertices to the nearest pixel center.
+ - *False*: Do not modify vertex positions.
+ - *None*: (auto) If the path contains only rectilinear line
+ segments, round to the nearest pixel center.
+ """
+ self._snap = snap
+ self.stale = True
+
+ def get_sketch_params(self):
+ """
+ Return the sketch parameters for the artist.
+
+ Returns
+ -------
+ tuple or None
+
+ A 3-tuple with the following elements:
+
+ - *scale*: The amplitude of the wiggle perpendicular to the
+ source line.
+ - *length*: The length of the wiggle along the line.
+ - *randomness*: The scale factor by which the length is
+ shrunken or expanded.
+
+ Returns *None* if no sketch parameters were set.
+ """
+ return self._sketch
+
+ def set_sketch_params(self, scale=None, length=None, randomness=None):
+ """
+ Set the sketch parameters.
+
+ Parameters
+ ----------
+ scale : float, optional
+ The amplitude of the wiggle perpendicular to the source
+ line, in pixels. If scale is `None`, or not provided, no
+ sketch filter will be provided.
+ length : float, optional
+ The length of the wiggle along the line, in pixels
+ (default 128.0)
+ randomness : float, optional
+ The scale factor by which the length is shrunken or
+ expanded (default 16.0)
+
+ The PGF backend uses this argument as an RNG seed and not as
+ described above. Using the same seed yields the same random shape.
+
+ .. ACCEPTS: (scale: float, length: float, randomness: float)
+ """
+ if scale is None:
+ self._sketch = None
+ else:
+ self._sketch = (scale, length or 128.0, randomness or 16.0)
+ self.stale = True
+
+ def set_path_effects(self, path_effects):
+ """
+ Set the path effects.
+
+ Parameters
+ ----------
+ path_effects : list of `.AbstractPathEffect`
+ """
+ self._path_effects = path_effects
+ self.stale = True
+
+ def get_path_effects(self):
+ return self._path_effects
+
+ def get_figure(self, root=False):
+ """
+ Return the `.Figure` or `.SubFigure` instance the artist belongs to.
+
+ Parameters
+ ----------
+ root : bool, default=False
+ If False, return the (Sub)Figure this artist is on. If True,
+ return the root Figure for a nested tree of SubFigures.
+ """
+ if root and self._parent_figure is not None:
+ return self._parent_figure.get_figure(root=True)
+
+ return self._parent_figure
+
+ def set_figure(self, fig):
+ """
+ Set the `.Figure` or `.SubFigure` instance the artist belongs to.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure` or `~matplotlib.figure.SubFigure`
+ """
+ # if this is a no-op just return
+ if self._parent_figure is fig:
+ return
+ # if we currently have a figure (the case of both `self.figure`
+ # and *fig* being none is taken care of above) we then user is
+ # trying to change the figure an artist is associated with which
+ # is not allowed for the same reason as adding the same instance
+ # to more than one Axes
+ if self._parent_figure is not None:
+ raise RuntimeError("Can not put single artist in "
+ "more than one figure")
+ self._parent_figure = fig
+ if self._parent_figure and self._parent_figure is not self:
+ self.pchanged()
+ self.stale = True
+
+ figure = property(get_figure, set_figure,
+ doc=("The (Sub)Figure that the artist is on. For more "
+ "control, use the `get_figure` method."))
+
+ def set_clip_box(self, clipbox):
+ """
+ Set the artist's clip `.Bbox`.
+
+ Parameters
+ ----------
+ clipbox : `~matplotlib.transforms.BboxBase` or None
+ Will typically be created from a `.TransformedBbox`. For instance,
+ ``TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes)`` is the default
+ clipping for an artist added to an Axes.
+
+ """
+ _api.check_isinstance((BboxBase, None), clipbox=clipbox)
+ if clipbox != self.clipbox:
+ self.clipbox = clipbox
+ self.pchanged()
+ self.stale = True
+
+ def set_clip_path(self, path, transform=None):
+ """
+ Set the artist's clip path.
+
+ Parameters
+ ----------
+ path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath` or None
+ The clip path. If given a `.Path`, *transform* must be provided as
+ well. If *None*, a previously set clip path is removed.
+ transform : `~matplotlib.transforms.Transform`, optional
+ Only used if *path* is a `.Path`, in which case the given `.Path`
+ is converted to a `.TransformedPath` using *transform*.
+
+ Notes
+ -----
+ For efficiency, if *path* is a `.Rectangle` this method will set the
+ clipping box to the corresponding rectangle and set the clipping path
+ to ``None``.
+
+ For technical reasons (support of `~.Artist.set`), a tuple
+ (*path*, *transform*) is also accepted as a single positional
+ parameter.
+
+ .. ACCEPTS: Patch or (Path, Transform) or None
+ """
+ from matplotlib.patches import Patch, Rectangle
+
+ success = False
+ if transform is None:
+ if isinstance(path, Rectangle):
+ self.clipbox = TransformedBbox(Bbox.unit(),
+ path.get_transform())
+ self._clippath = None
+ success = True
+ elif isinstance(path, Patch):
+ self._clippath = TransformedPatchPath(path)
+ success = True
+ elif isinstance(path, tuple):
+ path, transform = path
+
+ if path is None:
+ self._clippath = None
+ success = True
+ elif isinstance(path, Path):
+ self._clippath = TransformedPath(path, transform)
+ success = True
+ elif isinstance(path, TransformedPatchPath):
+ self._clippath = path
+ success = True
+ elif isinstance(path, TransformedPath):
+ self._clippath = path
+ success = True
+
+ if not success:
+ raise TypeError(
+ "Invalid arguments to set_clip_path, of type "
+ f"{type(path).__name__} and {type(transform).__name__}")
+ # This may result in the callbacks being hit twice, but guarantees they
+ # will be hit at least once.
+ self.pchanged()
+ self.stale = True
+
+ def get_alpha(self):
+ """
+ Return the alpha value used for blending - not supported on all
+ backends.
+ """
+ return self._alpha
+
+ def get_visible(self):
+ """Return the visibility."""
+ return self._visible
+
+ def get_animated(self):
+ """Return whether the artist is animated."""
+ return self._animated
+
+ def get_in_layout(self):
+ """
+ Return boolean flag, ``True`` if artist is included in layout
+ calculations.
+
+ E.g. :ref:`constrainedlayout_guide`,
+ `.Figure.tight_layout()`, and
+ ``fig.savefig(fname, bbox_inches='tight')``.
+ """
+ return self._in_layout
+
+ def _fully_clipped_to_axes(self):
+ """
+ Return a boolean flag, ``True`` if the artist is clipped to the Axes
+ and can thus be skipped in layout calculations. Requires `get_clip_on`
+ is True, one of `clip_box` or `clip_path` is set, ``clip_box.extents``
+ is equivalent to ``ax.bbox.extents`` (if set), and ``clip_path._patch``
+ is equivalent to ``ax.patch`` (if set).
+ """
+ # Note that ``clip_path.get_fully_transformed_path().get_extents()``
+ # cannot be directly compared to ``axes.bbox.extents`` because the
+ # extents may be undefined (i.e. equivalent to ``Bbox.null()``)
+ # before the associated artist is drawn, and this method is meant
+ # to determine whether ``axes.get_tightbbox()`` may bypass drawing
+ clip_box = self.get_clip_box()
+ clip_path = self.get_clip_path()
+ return (self.axes is not None
+ and self.get_clip_on()
+ and (clip_box is not None or clip_path is not None)
+ and (clip_box is None
+ or np.all(clip_box.extents == self.axes.bbox.extents))
+ and (clip_path is None
+ or isinstance(clip_path, TransformedPatchPath)
+ and clip_path._patch is self.axes.patch))
+
+ def get_clip_on(self):
+ """Return whether the artist uses clipping."""
+ return self._clipon
+
+ def get_clip_box(self):
+ """Return the clipbox."""
+ return self.clipbox
+
+ def get_clip_path(self):
+ """Return the clip path."""
+ return self._clippath
+
+ def get_transformed_clip_path_and_affine(self):
+ """
+ Return the clip path with the non-affine part of its
+ transformation applied, and the remaining affine part of its
+ transformation.
+ """
+ if self._clippath is not None:
+ return self._clippath.get_transformed_path_and_affine()
+ return None, None
+
+ def set_clip_on(self, b):
+ """
+ Set whether the artist uses clipping.
+
+ When False, artists will be visible outside the Axes which
+ can lead to unexpected results.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ self._clipon = b
+ # This may result in the callbacks being hit twice, but ensures they
+ # are hit at least once
+ self.pchanged()
+ self.stale = True
+
+ def _set_gc_clip(self, gc):
+ """Set the clip properly for the gc."""
+ if self._clipon:
+ if self.clipbox is not None:
+ gc.set_clip_rectangle(self.clipbox)
+ gc.set_clip_path(self._clippath)
+ else:
+ gc.set_clip_rectangle(None)
+ gc.set_clip_path(None)
+
+ def get_rasterized(self):
+ """Return whether the artist is to be rasterized."""
+ return self._rasterized
+
+ def set_rasterized(self, rasterized):
+ """
+ Force rasterized (bitmap) drawing for vector graphics output.
+
+ Rasterized drawing is not supported by all artists. If you try to
+ enable this on an artist that does not support it, the command has no
+ effect and a warning will be issued.
+
+ This setting is ignored for pixel-based output.
+
+ See also :doc:`/gallery/misc/rasterization_demo`.
+
+ Parameters
+ ----------
+ rasterized : bool
+ """
+ supports_rasterization = getattr(self.draw,
+ "_supports_rasterization", False)
+ if rasterized and not supports_rasterization:
+ _api.warn_external(f"Rasterization of '{self}' will be ignored")
+
+ self._rasterized = rasterized
+
+ def get_agg_filter(self):
+ """Return filter function to be used for agg filter."""
+ return self._agg_filter
+
+ def set_agg_filter(self, filter_func):
+ """
+ Set the agg filter.
+
+ Parameters
+ ----------
+ filter_func : callable
+ A filter function, which takes a (m, n, depth) float array
+ and a dpi value, and returns a (m, n, depth) array and two
+ offsets from the bottom left corner of the image
+
+ .. ACCEPTS: a filter function, which takes a (m, n, 3) float array
+ and a dpi value, and returns a (m, n, 3) array and two offsets
+ from the bottom left corner of the image
+ """
+ self._agg_filter = filter_func
+ self.stale = True
+
+ def draw(self, renderer):
+ """
+ Draw the Artist (and its children) using the given renderer.
+
+ This has no effect if the artist is not visible (`.Artist.get_visible`
+ returns False).
+
+ Parameters
+ ----------
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass.
+
+ Notes
+ -----
+ This method is overridden in the Artist subclasses.
+ """
+ if not self.get_visible():
+ return
+ self.stale = False
+
+ def set_alpha(self, alpha):
+ """
+ Set the alpha value used for blending - not supported on all backends.
+
+ Parameters
+ ----------
+ alpha : scalar or None
+ *alpha* must be within the 0-1 range, inclusive.
+ """
+ if alpha is not None and not isinstance(alpha, Real):
+ raise TypeError(
+ f'alpha must be numeric or None, not {type(alpha)}')
+ if alpha is not None and not (0 <= alpha <= 1):
+ raise ValueError(f'alpha ({alpha}) is outside 0-1 range')
+ if alpha != self._alpha:
+ self._alpha = alpha
+ self.pchanged()
+ self.stale = True
+
+ def _set_alpha_for_array(self, alpha):
+ """
+ Set the alpha value used for blending - not supported on all backends.
+
+ Parameters
+ ----------
+ alpha : array-like or scalar or None
+ All values must be within the 0-1 range, inclusive.
+ Masked values and nans are not supported.
+ """
+ if isinstance(alpha, str):
+ raise TypeError("alpha must be numeric or None, not a string")
+ if not np.iterable(alpha):
+ Artist.set_alpha(self, alpha)
+ return
+ alpha = np.asarray(alpha)
+ if not (0 <= alpha.min() and alpha.max() <= 1):
+ raise ValueError('alpha must be between 0 and 1, inclusive, '
+ f'but min is {alpha.min()}, max is {alpha.max()}')
+ self._alpha = alpha
+ self.pchanged()
+ self.stale = True
+
+ def set_visible(self, b):
+ """
+ Set the artist's visibility.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ if b != self._visible:
+ self._visible = b
+ self.pchanged()
+ self.stale = True
+
+ def set_animated(self, b):
+ """
+ Set whether the artist is intended to be used in an animation.
+
+ If True, the artist is excluded from regular drawing of the figure.
+ You have to call `.Figure.draw_artist` / `.Axes.draw_artist`
+ explicitly on the artist. This approach is used to speed up animations
+ using blitting.
+
+ See also `matplotlib.animation` and
+ :ref:`blitting`.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ if self._animated != b:
+ self._animated = b
+ self.pchanged()
+
+ def set_in_layout(self, in_layout):
+ """
+ Set if artist is to be included in layout calculations,
+ E.g. :ref:`constrainedlayout_guide`,
+ `.Figure.tight_layout()`, and
+ ``fig.savefig(fname, bbox_inches='tight')``.
+
+ Parameters
+ ----------
+ in_layout : bool
+ """
+ self._in_layout = in_layout
+
+ def get_label(self):
+ """Return the label used for this artist in the legend."""
+ return self._label
+
+ def set_label(self, s):
+ """
+ Set a label that will be displayed in the legend.
+
+ Parameters
+ ----------
+ s : object
+ *s* will be converted to a string by calling `str`.
+ """
+ label = str(s) if s is not None else None
+ if label != self._label:
+ self._label = label
+ self.pchanged()
+ self.stale = True
+
+ def get_zorder(self):
+ """Return the artist's zorder."""
+ return self.zorder
+
+ def set_zorder(self, level):
+ """
+ Set the zorder for the artist. Artists with lower zorder
+ values are drawn first.
+
+ Parameters
+ ----------
+ level : float
+ """
+ if level is None:
+ level = self.__class__.zorder
+ if level != self.zorder:
+ self.zorder = level
+ self.pchanged()
+ self.stale = True
+
+ @property
+ def sticky_edges(self):
+ """
+ ``x`` and ``y`` sticky edge lists for autoscaling.
+
+ When performing autoscaling, if a data limit coincides with a value in
+ the corresponding sticky_edges list, then no margin will be added--the
+ view limit "sticks" to the edge. A typical use case is histograms,
+ where one usually expects no margin on the bottom edge (0) of the
+ histogram.
+
+ Moreover, margin expansion "bumps" against sticky edges and cannot
+ cross them. For example, if the upper data limit is 1.0, the upper
+ view limit computed by simple margin application is 1.2, but there is a
+ sticky edge at 1.1, then the actual upper view limit will be 1.1.
+
+ This attribute cannot be assigned to; however, the ``x`` and ``y``
+ lists can be modified in place as needed.
+
+ Examples
+ --------
+ >>> artist.sticky_edges.x[:] = (xmin, xmax)
+ >>> artist.sticky_edges.y[:] = (ymin, ymax)
+
+ """
+ return self._sticky_edges
+
+ def update_from(self, other):
+ """Copy properties from *other* to *self*."""
+ self._transform = other._transform
+ self._transformSet = other._transformSet
+ self._visible = other._visible
+ self._alpha = other._alpha
+ self.clipbox = other.clipbox
+ self._clipon = other._clipon
+ self._clippath = other._clippath
+ self._label = other._label
+ self._sketch = other._sketch
+ self._path_effects = other._path_effects
+ self.sticky_edges.x[:] = other.sticky_edges.x.copy()
+ self.sticky_edges.y[:] = other.sticky_edges.y.copy()
+ self.pchanged()
+ self.stale = True
+
+ def properties(self):
+ """Return a dictionary of all the properties of the artist."""
+ return ArtistInspector(self).properties()
+
+ def _update_props(self, props, errfmt):
+ """
+ Helper for `.Artist.set` and `.Artist.update`.
+
+ *errfmt* is used to generate error messages for invalid property
+ names; it gets formatted with ``type(self)`` for "{cls}" and the
+ property name for "{prop_name}".
+ """
+ ret = []
+ with cbook._setattr_cm(self, eventson=False):
+ for k, v in props.items():
+ # Allow attributes we want to be able to update through
+ # art.update, art.set, setp.
+ if k == "axes":
+ ret.append(setattr(self, k, v))
+ else:
+ func = getattr(self, f"set_{k}", None)
+ if not callable(func):
+ raise AttributeError(
+ errfmt.format(cls=type(self), prop_name=k),
+ name=k)
+ ret.append(func(v))
+ if ret:
+ self.pchanged()
+ self.stale = True
+ return ret
+
+ def update(self, props):
+ """
+ Update this artist's properties from the dict *props*.
+
+ Parameters
+ ----------
+ props : dict
+ """
+ return self._update_props(
+ props, "{cls.__name__!r} object has no property {prop_name!r}")
+
+ def _internal_update(self, kwargs):
+ """
+ Update artist properties without prenormalizing them, but generating
+ errors as if calling `set`.
+
+ The lack of prenormalization is to maintain backcompatibility.
+ """
+ return self._update_props(
+ kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
+ "{prop_name!r}")
+
+ def set(self, **kwargs):
+ # docstring and signature are auto-generated via
+ # Artist._update_set_signature_and_docstring() at the end of the
+ # module.
+ return self._internal_update(cbook.normalize_kwargs(kwargs, self))
+
+ @contextlib.contextmanager
+ def _cm_set(self, **kwargs):
+ """
+ `.Artist.set` context-manager that restores original values at exit.
+ """
+ orig_vals = {k: getattr(self, f"get_{k}")() for k in kwargs}
+ try:
+ self.set(**kwargs)
+ yield
+ finally:
+ self.set(**orig_vals)
+
+ def findobj(self, match=None, include_self=True):
+ """
+ Find artist objects.
+
+ Recursively find all `.Artist` instances contained in the artist.
+
+ Parameters
+ ----------
+ match
+ A filter criterion for the matches. This can be
+
+ - *None*: Return all objects contained in artist.
+ - A function with signature ``def match(artist: Artist) -> bool``.
+ The result will only contain artists for which the function
+ returns *True*.
+ - A class instance: e.g., `.Line2D`. The result will only contain
+ artists of this class or its subclasses (``isinstance`` check).
+
+ include_self : bool
+ Include *self* in the list to be checked for a match.
+
+ Returns
+ -------
+ list of `.Artist`
+
+ """
+ if match is None: # always return True
+ def matchfunc(x):
+ return True
+ elif isinstance(match, type) and issubclass(match, Artist):
+ def matchfunc(x):
+ return isinstance(x, match)
+ elif callable(match):
+ matchfunc = match
+ else:
+ raise ValueError('match must be None, a matplotlib.artist.Artist '
+ 'subclass, or a callable')
+
+ artists = reduce(operator.iadd,
+ [c.findobj(matchfunc) for c in self.get_children()], [])
+ if include_self and matchfunc(self):
+ artists.append(self)
+ return artists
+
+ def get_cursor_data(self, event):
+ """
+ Return the cursor data for a given event.
+
+ .. note::
+ This method is intended to be overridden by artist subclasses.
+ As an end-user of Matplotlib you will most likely not call this
+ method yourself.
+
+ Cursor data can be used by Artists to provide additional context
+ information for a given event. The default implementation just returns
+ *None*.
+
+ Subclasses can override the method and return arbitrary data. However,
+ when doing so, they must ensure that `.format_cursor_data` can convert
+ the data to a string representation.
+
+ The only current use case is displaying the z-value of an `.AxesImage`
+ in the status bar of a plot window, while moving the mouse.
+
+ Parameters
+ ----------
+ event : `~matplotlib.backend_bases.MouseEvent`
+
+ See Also
+ --------
+ format_cursor_data
+
+ """
+ return None
+
+ def format_cursor_data(self, data):
+ """
+ Return a string representation of *data*.
+
+ .. note::
+ This method is intended to be overridden by artist subclasses.
+ As an end-user of Matplotlib you will most likely not call this
+ method yourself.
+
+ The default implementation converts ints and floats and arrays of ints
+ and floats into a comma-separated string enclosed in square brackets,
+ unless the artist has an associated colorbar, in which case scalar
+ values are formatted using the colorbar's formatter.
+
+ See Also
+ --------
+ get_cursor_data
+ """
+ if np.ndim(data) == 0 and hasattr(self, "_format_cursor_data_override"):
+ # workaround for ScalarMappable to be able to define its own
+ # format_cursor_data(). See ScalarMappable._format_cursor_data_override
+ # for details.
+ return self._format_cursor_data_override(data)
+ else:
+ try:
+ data[0]
+ except (TypeError, IndexError):
+ data = [data]
+ data_str = ', '.join(f'{item:0.3g}' for item in data
+ if isinstance(item, Number))
+ return "[" + data_str + "]"
+
+ def get_mouseover(self):
+ """
+ Return whether this artist is queried for custom context information
+ when the mouse cursor moves over it.
+ """
+ return self._mouseover
+
+ def set_mouseover(self, mouseover):
+ """
+ Set whether this artist is queried for custom context information when
+ the mouse cursor moves over it.
+
+ Parameters
+ ----------
+ mouseover : bool
+
+ See Also
+ --------
+ get_cursor_data
+ .ToolCursorPosition
+ .NavigationToolbar2
+ """
+ self._mouseover = bool(mouseover)
+ ax = self.axes
+ if ax:
+ if self._mouseover:
+ ax._mouseover_set.add(self)
+ else:
+ ax._mouseover_set.discard(self)
+
+ mouseover = property(get_mouseover, set_mouseover) # backcompat.
+
+
+def _get_tightbbox_for_layout_only(obj, *args, **kwargs):
+ """
+ Matplotlib's `.Axes.get_tightbbox` and `.Axis.get_tightbbox` support a
+ *for_layout_only* kwarg; this helper tries to use the kwarg but skips it
+ when encountering third-party subclasses that do not support it.
+ """
+ try:
+ return obj.get_tightbbox(*args, **{**kwargs, "for_layout_only": True})
+ except TypeError:
+ return obj.get_tightbbox(*args, **kwargs)
+
+
+class ArtistInspector:
+ """
+ A helper class to inspect an `~matplotlib.artist.Artist` and return
+ information about its settable properties and their current values.
+ """
+
+ def __init__(self, o):
+ r"""
+ Initialize the artist inspector with an `Artist` or an iterable of
+ `Artist`\s. If an iterable is used, we assume it is a homogeneous
+ sequence (all `Artist`\s are of the same type) and it is your
+ responsibility to make sure this is so.
+ """
+ if not isinstance(o, Artist):
+ if np.iterable(o):
+ o = list(o)
+ if len(o):
+ o = o[0]
+
+ self.oorig = o
+ if not isinstance(o, type):
+ o = type(o)
+ self.o = o
+
+ self.aliasd = self.get_aliases()
+
+ def get_aliases(self):
+ """
+ Get a dict mapping property fullnames to sets of aliases for each alias
+ in the :class:`~matplotlib.artist.ArtistInspector`.
+
+ e.g., for lines::
+
+ {'markerfacecolor': {'mfc'},
+ 'linewidth' : {'lw'},
+ }
+ """
+ names = [name for name in dir(self.o)
+ if name.startswith(('set_', 'get_'))
+ and callable(getattr(self.o, name))]
+ aliases = {}
+ for name in names:
+ func = getattr(self.o, name)
+ if not self.is_alias(func):
+ continue
+ propname = re.search(f"`({name[:4]}.*)`", # get_.*/set_.*
+ inspect.getdoc(func)).group(1)
+ aliases.setdefault(propname[4:], set()).add(name[4:])
+ return aliases
+
+ _get_valid_values_regex = re.compile(
+ r"\n\s*(?:\.\.\s+)?ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))"
+ )
+
+ def get_valid_values(self, attr):
+ """
+ Get the legal arguments for the setter associated with *attr*.
+
+ This is done by querying the docstring of the setter for a line that
+ begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a
+ numpydoc-style documentation for the setter's first argument.
+ """
+
+ name = 'set_%s' % attr
+ if not hasattr(self.o, name):
+ raise AttributeError(f'{self.o} has no function {name}')
+ func = getattr(self.o, name)
+
+ if hasattr(func, '_kwarg_doc'):
+ return func._kwarg_doc
+
+ docstring = inspect.getdoc(func)
+ if docstring is None:
+ return 'unknown'
+
+ if docstring.startswith('Alias for '):
+ return None
+
+ match = self._get_valid_values_regex.search(docstring)
+ if match is not None:
+ return re.sub("\n *", " ", match.group(1))
+
+ # Much faster than list(inspect.signature(func).parameters)[1],
+ # although barely relevant wrt. matplotlib's total import time.
+ param_name = func.__code__.co_varnames[1]
+ # We could set the presence * based on whether the parameter is a
+ # varargs (it can't be a varkwargs) but it's not really worth it.
+ match = re.search(fr"(?m)^ *\*?{param_name} : (.+)", docstring)
+ if match:
+ return match.group(1)
+
+ return 'unknown'
+
+ def _replace_path(self, source_class):
+ """
+ Changes the full path to the public API path that is used
+ in sphinx. This is needed for links to work.
+ """
+ replace_dict = {'_base._AxesBase': 'Axes',
+ '_axes.Axes': 'Axes'}
+ for key, value in replace_dict.items():
+ source_class = source_class.replace(key, value)
+ return source_class
+
+ def get_setters(self):
+ """
+ Get the attribute strings with setters for object.
+
+ For example, for a line, return ``['markerfacecolor', 'linewidth',
+ ....]``.
+ """
+ setters = []
+ for name in dir(self.o):
+ if not name.startswith('set_'):
+ continue
+ func = getattr(self.o, name)
+ if (not callable(func)
+ or self.number_of_parameters(func) < 2
+ or self.is_alias(func)):
+ continue
+ setters.append(name[4:])
+ return setters
+
+ @staticmethod
+ @cache
+ def number_of_parameters(func):
+ """Return number of parameters of the callable *func*."""
+ return len(inspect.signature(func).parameters)
+
+ @staticmethod
+ @cache
+ def is_alias(method):
+ """
+ Return whether the object *method* is an alias for another method.
+ """
+
+ ds = inspect.getdoc(method)
+ if ds is None:
+ return False
+
+ return ds.startswith('Alias for ')
+
+ def aliased_name(self, s):
+ """
+ Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'.
+
+ For example, for the line markerfacecolor property, which has an
+ alias, return 'markerfacecolor or mfc' and for the transform
+ property, which does not, return 'transform'.
+ """
+ aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, [])))
+ return s + aliases
+
+ _NOT_LINKABLE = {
+ # A set of property setter methods that are not available in our
+ # current docs. This is a workaround used to prevent trying to link
+ # these setters which would lead to "target reference not found"
+ # warnings during doc build.
+ 'matplotlib.image._ImageBase.set_alpha',
+ 'matplotlib.image._ImageBase.set_array',
+ 'matplotlib.image._ImageBase.set_data',
+ 'matplotlib.image._ImageBase.set_filternorm',
+ 'matplotlib.image._ImageBase.set_filterrad',
+ 'matplotlib.image._ImageBase.set_interpolation',
+ 'matplotlib.image._ImageBase.set_interpolation_stage',
+ 'matplotlib.image._ImageBase.set_resample',
+ 'matplotlib.text._AnnotationBase.set_annotation_clip',
+ }
+
+ def aliased_name_rest(self, s, target):
+ """
+ Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME',
+ formatted for reST.
+
+ For example, for the line markerfacecolor property, which has an
+ alias, return 'markerfacecolor or mfc' and for the transform
+ property, which does not, return 'transform'.
+ """
+ # workaround to prevent "reference target not found"
+ if target in self._NOT_LINKABLE:
+ return f'``{s}``'
+
+ aliases = ''.join(
+ f' or :meth:`{a} <{target}>`' for a in sorted(self.aliasd.get(s, [])))
+ return f':meth:`{s} <{target}>`{aliases}'
+
+ def pprint_setters(self, prop=None, leadingspace=2):
+ """
+ If *prop* is *None*, return a list of strings of all settable
+ properties and their valid values.
+
+ If *prop* is not *None*, it is a valid property name and that
+ property will be returned as a string of property : valid
+ values.
+ """
+ if leadingspace:
+ pad = ' ' * leadingspace
+ else:
+ pad = ''
+ if prop is not None:
+ accepts = self.get_valid_values(prop)
+ return f'{pad}{prop}: {accepts}'
+
+ lines = []
+ for prop in sorted(self.get_setters()):
+ accepts = self.get_valid_values(prop)
+ name = self.aliased_name(prop)
+ lines.append(f'{pad}{name}: {accepts}')
+ return lines
+
+ def pprint_setters_rest(self, prop=None, leadingspace=4):
+ """
+ If *prop* is *None*, return a list of reST-formatted strings of all
+ settable properties and their valid values.
+
+ If *prop* is not *None*, it is a valid property name and that
+ property will be returned as a string of "property : valid"
+ values.
+ """
+ if leadingspace:
+ pad = ' ' * leadingspace
+ else:
+ pad = ''
+ if prop is not None:
+ accepts = self.get_valid_values(prop)
+ return f'{pad}{prop}: {accepts}'
+
+ prop_and_qualnames = []
+ for prop in sorted(self.get_setters()):
+ # Find the parent method which actually provides the docstring.
+ for cls in self.o.__mro__:
+ method = getattr(cls, f"set_{prop}", None)
+ if method and method.__doc__ is not None:
+ break
+ else: # No docstring available.
+ method = getattr(self.o, f"set_{prop}")
+ prop_and_qualnames.append(
+ (prop, f"{method.__module__}.{method.__qualname__}"))
+
+ names = [self.aliased_name_rest(prop, target)
+ .replace('_base._AxesBase', 'Axes')
+ .replace('_axes.Axes', 'Axes')
+ for prop, target in prop_and_qualnames]
+ accepts = [self.get_valid_values(prop)
+ for prop, _ in prop_and_qualnames]
+
+ col0_len = max(len(n) for n in names)
+ col1_len = max(len(a) for a in accepts)
+ table_formatstr = pad + ' ' + '=' * col0_len + ' ' + '=' * col1_len
+
+ return [
+ '',
+ pad + '.. table::',
+ pad + ' :class: property-table',
+ '',
+ table_formatstr,
+ pad + ' ' + 'Property'.ljust(col0_len)
+ + ' ' + 'Description'.ljust(col1_len),
+ table_formatstr,
+ *[pad + ' ' + n.ljust(col0_len) + ' ' + a.ljust(col1_len)
+ for n, a in zip(names, accepts)],
+ table_formatstr,
+ '',
+ ]
+
+ def properties(self):
+ """Return a dictionary mapping property name -> value."""
+ o = self.oorig
+ getters = [name for name in dir(o)
+ if name.startswith('get_') and callable(getattr(o, name))]
+ getters.sort()
+ d = {}
+ for name in getters:
+ func = getattr(o, name)
+ if self.is_alias(func):
+ continue
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore')
+ val = func()
+ except Exception:
+ continue
+ else:
+ d[name[4:]] = val
+ return d
+
+ def pprint_getters(self):
+ """Return the getters and actual values as list of strings."""
+ lines = []
+ for name, val in sorted(self.properties().items()):
+ if getattr(val, 'shape', ()) != () and len(val) > 6:
+ s = str(val[:6]) + '...'
+ else:
+ s = str(val)
+ s = s.replace('\n', ' ')
+ if len(s) > 50:
+ s = s[:50] + '...'
+ name = self.aliased_name(name)
+ lines.append(f' {name} = {s}')
+ return lines
+
+
+def getp(obj, property=None):
+ """
+ Return the value of an `.Artist`'s *property*, or print all of them.
+
+ Parameters
+ ----------
+ obj : `~matplotlib.artist.Artist`
+ The queried artist; e.g., a `.Line2D`, a `.Text`, or an `~.axes.Axes`.
+
+ property : str or None, default: None
+ If *property* is 'somename', this function returns
+ ``obj.get_somename()``.
+
+ If it's None (or unset), it *prints* all gettable properties from
+ *obj*. Many properties have aliases for shorter typing, e.g. 'lw' is
+ an alias for 'linewidth'. In the output, aliases and full property
+ names will be listed as:
+
+ property or alias = value
+
+ e.g.:
+
+ linewidth or lw = 2
+
+ See Also
+ --------
+ setp
+ """
+ if property is None:
+ insp = ArtistInspector(obj)
+ ret = insp.pprint_getters()
+ print('\n'.join(ret))
+ return
+ return getattr(obj, 'get_' + property)()
+
+# alias
+get = getp
+
+
+def setp(obj, *args, file=None, **kwargs):
+ """
+ Set one or more properties on an `.Artist`, or list allowed values.
+
+ Parameters
+ ----------
+ obj : `~matplotlib.artist.Artist` or list of `.Artist`
+ The artist(s) whose properties are being set or queried. When setting
+ properties, all artists are affected; when querying the allowed values,
+ only the first instance in the sequence is queried.
+
+ For example, two lines can be made thicker and red with a single call:
+
+ >>> x = arange(0, 1, 0.01)
+ >>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x))
+ >>> setp(lines, linewidth=2, color='r')
+
+ file : file-like, default: `sys.stdout`
+ Where `setp` writes its output when asked to list allowed values.
+
+ >>> with open('output.log') as file:
+ ... setp(line, file=file)
+
+ The default, ``None``, means `sys.stdout`.
+
+ *args, **kwargs
+ The properties to set. The following combinations are supported:
+
+ - Set the linestyle of a line to be dashed:
+
+ >>> line, = plot([1, 2, 3])
+ >>> setp(line, linestyle='--')
+
+ - Set multiple properties at once:
+
+ >>> setp(line, linewidth=2, color='r')
+
+ - List allowed values for a line's linestyle:
+
+ >>> setp(line, 'linestyle')
+ linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
+
+ - List all properties that can be set, and their allowed values:
+
+ >>> setp(line)
+ agg_filter: a filter function, ...
+ [long output listing omitted]
+
+ `setp` also supports MATLAB style string/value pairs. For example, the
+ following are equivalent:
+
+ >>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style
+ >>> setp(lines, linewidth=2, color='r') # Python style
+
+ See Also
+ --------
+ getp
+ """
+
+ if isinstance(obj, Artist):
+ objs = [obj]
+ else:
+ objs = list(cbook.flatten(obj))
+
+ if not objs:
+ return
+
+ insp = ArtistInspector(objs[0])
+
+ if not kwargs and len(args) < 2:
+ if args:
+ print(insp.pprint_setters(prop=args[0]), file=file)
+ else:
+ print('\n'.join(insp.pprint_setters()), file=file)
+ return
+
+ if len(args) % 2:
+ raise ValueError('The set args must be string, value pairs')
+
+ funcvals = dict(zip(args[::2], args[1::2]))
+ ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs]
+ return list(cbook.flatten(ret))
+
+
+def kwdoc(artist):
+ r"""
+ Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and
+ return information about its settable properties and their current values.
+
+ Parameters
+ ----------
+ artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s
+
+ Returns
+ -------
+ str
+ The settable properties of *artist*, as plain text if
+ :rc:`docstring.hardcopy` is False and as a rst table (intended for
+ use in Sphinx) if it is True.
+ """
+ ai = ArtistInspector(artist)
+ return ('\n'.join(ai.pprint_setters_rest(leadingspace=4))
+ if mpl.rcParams['docstring.hardcopy'] else
+ 'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4)))
+
+# We defer this to the end of them module, because it needs ArtistInspector
+# to be defined.
+Artist._update_set_signature_and_docstring()
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/artist.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/artist.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..be23f69d44a6df19fef57131eadede93bf4875bc
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/artist.pyi
@@ -0,0 +1,199 @@
+from .axes._base import _AxesBase
+from .backend_bases import RendererBase, MouseEvent
+from .figure import Figure, SubFigure
+from .path import Path
+from .patches import Patch
+from .patheffects import AbstractPathEffect
+from .transforms import (
+ BboxBase,
+ Bbox,
+ Transform,
+ TransformedPatchPath,
+ TransformedPath,
+)
+
+import numpy as np
+
+from collections.abc import Callable, Iterable
+from typing import Any, Literal, NamedTuple, TextIO, overload, TypeVar
+from numpy.typing import ArrayLike
+
+_T_Artist = TypeVar("_T_Artist", bound=Artist)
+
+def allow_rasterization(draw): ...
+
+class _XYPair(NamedTuple):
+ x: ArrayLike
+ y: ArrayLike
+
+class _Unset: ...
+
+class Artist:
+ zorder: float
+ stale_callback: Callable[[Artist, bool], None] | None
+ @property
+ def figure(self) -> Figure | SubFigure: ...
+ clipbox: BboxBase | None
+ def __init__(self) -> None: ...
+ def remove(self) -> None: ...
+ def have_units(self) -> bool: ...
+ # TODO units
+ def convert_xunits(self, x): ...
+ def convert_yunits(self, y): ...
+ @property
+ def axes(self) -> _AxesBase | None: ...
+ @axes.setter
+ def axes(self, new_axes: _AxesBase | None) -> None: ...
+ @property
+ def stale(self) -> bool: ...
+ @stale.setter
+ def stale(self, val: bool) -> None: ...
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
+ def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox | None: ...
+ def add_callback(self, func: Callable[[Artist], Any]) -> int: ...
+ def remove_callback(self, oid: int) -> None: ...
+ def pchanged(self) -> None: ...
+ def is_transform_set(self) -> bool: ...
+ def set_transform(self, t: Transform | None) -> None: ...
+ def get_transform(self) -> Transform: ...
+ def get_children(self) -> list[Artist]: ...
+ # TODO can these dicts be type narrowed? e.g. str keys
+ def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ...
+ def pickable(self) -> bool: ...
+ def pick(self, mouseevent: MouseEvent) -> None: ...
+ def set_picker(
+ self,
+ picker: None
+ | bool
+ | float
+ | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]],
+ ) -> None: ...
+ def get_picker(
+ self,
+ ) -> None | bool | float | Callable[
+ [Artist, MouseEvent], tuple[bool, dict[Any, Any]]
+ ]: ...
+ def get_url(self) -> str | None: ...
+ def set_url(self, url: str | None) -> None: ...
+ def get_gid(self) -> str | None: ...
+ def set_gid(self, gid: str | None) -> None: ...
+ def get_snap(self) -> bool | None: ...
+ def set_snap(self, snap: bool | None) -> None: ...
+ def get_sketch_params(self) -> tuple[float, float, float] | None: ...
+ def set_sketch_params(
+ self,
+ scale: float | None = ...,
+ length: float | None = ...,
+ randomness: float | None = ...,
+ ) -> None: ...
+ def set_path_effects(self, path_effects: list[AbstractPathEffect]) -> None: ...
+ def get_path_effects(self) -> list[AbstractPathEffect]: ...
+ @overload
+ def get_figure(self, root: Literal[True]) -> Figure | None: ...
+ @overload
+ def get_figure(self, root: Literal[False]) -> Figure | SubFigure | None: ...
+ @overload
+ def get_figure(self, root: bool = ...) -> Figure | SubFigure | None: ...
+ def set_figure(self, fig: Figure | SubFigure) -> None: ...
+ def set_clip_box(self, clipbox: BboxBase | None) -> None: ...
+ def set_clip_path(
+ self,
+ path: Patch | Path | TransformedPath | TransformedPatchPath | None,
+ transform: Transform | None = ...,
+ ) -> None: ...
+ def get_alpha(self) -> float | None: ...
+ def get_visible(self) -> bool: ...
+ def get_animated(self) -> bool: ...
+ def get_in_layout(self) -> bool: ...
+ def get_clip_on(self) -> bool: ...
+ def get_clip_box(self) -> Bbox | None: ...
+ def get_clip_path(
+ self,
+ ) -> Patch | Path | TransformedPath | TransformedPatchPath | None: ...
+ def get_transformed_clip_path_and_affine(
+ self,
+ ) -> tuple[None, None] | tuple[Path, Transform]: ...
+ def set_clip_on(self, b: bool) -> None: ...
+ def get_rasterized(self) -> bool: ...
+ def set_rasterized(self, rasterized: bool) -> None: ...
+ def get_agg_filter(self) -> Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None: ...
+ def set_agg_filter(
+ self, filter_func: Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None
+ ) -> None: ...
+ def draw(self, renderer: RendererBase) -> None: ...
+ def set_alpha(self, alpha: float | None) -> None: ...
+ def set_visible(self, b: bool) -> None: ...
+ def set_animated(self, b: bool) -> None: ...
+ def set_in_layout(self, in_layout: bool) -> None: ...
+ def get_label(self) -> object: ...
+ def set_label(self, s: object) -> None: ...
+ def get_zorder(self) -> float: ...
+ def set_zorder(self, level: float) -> None: ...
+ @property
+ def sticky_edges(self) -> _XYPair: ...
+ def update_from(self, other: Artist) -> None: ...
+ def properties(self) -> dict[str, Any]: ...
+ def update(self, props: dict[str, Any]) -> list[Any]: ...
+ def _internal_update(self, kwargs: Any) -> list[Any]: ...
+ def set(self, **kwargs: Any) -> list[Any]: ...
+
+ @overload
+ def findobj(
+ self,
+ match: None | Callable[[Artist], bool] = ...,
+ include_self: bool = ...,
+ ) -> list[Artist]: ...
+
+ @overload
+ def findobj(
+ self,
+ match: type[_T_Artist],
+ include_self: bool = ...,
+ ) -> list[_T_Artist]: ...
+
+ def get_cursor_data(self, event: MouseEvent) -> Any: ...
+ def format_cursor_data(self, data: Any) -> str: ...
+ def get_mouseover(self) -> bool: ...
+ def set_mouseover(self, mouseover: bool) -> None: ...
+ @property
+ def mouseover(self) -> bool: ...
+ @mouseover.setter
+ def mouseover(self, mouseover: bool) -> None: ...
+
+class ArtistInspector:
+ oorig: Artist | type[Artist]
+ o: type[Artist]
+ aliasd: dict[str, set[str]]
+ def __init__(
+ self, o: Artist | type[Artist] | Iterable[Artist | type[Artist]]
+ ) -> None: ...
+ def get_aliases(self) -> dict[str, set[str]]: ...
+ def get_valid_values(self, attr: str) -> str | None: ...
+ def get_setters(self) -> list[str]: ...
+ @staticmethod
+ def number_of_parameters(func: Callable) -> int: ...
+ @staticmethod
+ def is_alias(method: Callable) -> bool: ...
+ def aliased_name(self, s: str) -> str: ...
+ def aliased_name_rest(self, s: str, target: str) -> str: ...
+ @overload
+ def pprint_setters(
+ self, prop: None = ..., leadingspace: int = ...
+ ) -> list[str]: ...
+ @overload
+ def pprint_setters(self, prop: str, leadingspace: int = ...) -> str: ...
+ @overload
+ def pprint_setters_rest(
+ self, prop: None = ..., leadingspace: int = ...
+ ) -> list[str]: ...
+ @overload
+ def pprint_setters_rest(self, prop: str, leadingspace: int = ...) -> str: ...
+ def properties(self) -> dict[str, Any]: ...
+ def pprint_getters(self) -> list[str]: ...
+
+def getp(obj: Artist, property: str | None = ...) -> Any: ...
+
+get = getp
+
+def setp(obj: Artist, *args, file: TextIO | None = ..., **kwargs) -> list[Any] | None: ...
+def kwdoc(artist: Artist | type[Artist] | Iterable[Artist | type[Artist]]) -> str: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/backend_bases.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/backend_bases.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..8089bb49e5974664d0cab6587c7c2070eb787fb2
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/backend_bases.pyi
@@ -0,0 +1,482 @@
+from enum import Enum, IntEnum
+import os
+from matplotlib import (
+ cbook,
+ transforms,
+ widgets,
+ _api,
+)
+from matplotlib.artist import Artist
+from matplotlib.axes import Axes
+from matplotlib.backend_managers import ToolManager
+from matplotlib.backend_tools import Cursors, ToolBase
+from matplotlib.colorbar import Colorbar
+from matplotlib.figure import Figure
+from matplotlib.font_manager import FontProperties
+from matplotlib.path import Path
+from matplotlib.texmanager import TexManager
+from matplotlib.text import Text
+from matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath
+
+from collections.abc import Callable, Iterable, Sequence
+from typing import Any, IO, Literal, NamedTuple, TypeVar
+from numpy.typing import ArrayLike
+from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
+
+def register_backend(
+ format: str, backend: str | type[FigureCanvasBase], description: str | None = ...
+) -> None: ...
+def get_registered_canvas_class(format: str) -> type[FigureCanvasBase]: ...
+
+class RendererBase:
+ def __init__(self) -> None: ...
+ def open_group(self, s: str, gid: str | None = ...) -> None: ...
+ def close_group(self, s: str) -> None: ...
+ def draw_path(
+ self,
+ gc: GraphicsContextBase,
+ path: Path,
+ transform: Transform,
+ rgbFace: ColorType | None = ...,
+ ) -> None: ...
+ def draw_markers(
+ self,
+ gc: GraphicsContextBase,
+ marker_path: Path,
+ marker_trans: Transform,
+ path: Path,
+ trans: Transform,
+ rgbFace: ColorType | None = ...,
+ ) -> None: ...
+ def draw_path_collection(
+ self,
+ gc: GraphicsContextBase,
+ master_transform: Transform,
+ paths: Sequence[Path],
+ all_transforms: Sequence[ArrayLike],
+ offsets: ArrayLike | Sequence[ArrayLike],
+ offset_trans: Transform,
+ facecolors: ColorType | Sequence[ColorType],
+ edgecolors: ColorType | Sequence[ColorType],
+ linewidths: float | Sequence[float],
+ linestyles: LineStyleType | Sequence[LineStyleType],
+ antialiaseds: bool | Sequence[bool],
+ urls: str | Sequence[str],
+ offset_position: Any,
+ ) -> None: ...
+ def draw_quad_mesh(
+ self,
+ gc: GraphicsContextBase,
+ master_transform: Transform,
+ meshWidth,
+ meshHeight,
+ coordinates: ArrayLike,
+ offsets: ArrayLike | Sequence[ArrayLike],
+ offsetTrans: Transform,
+ facecolors: Sequence[ColorType],
+ antialiased: bool,
+ edgecolors: Sequence[ColorType] | ColorType | None,
+ ) -> None: ...
+ def draw_gouraud_triangles(
+ self,
+ gc: GraphicsContextBase,
+ triangles_array: ArrayLike,
+ colors_array: ArrayLike,
+ transform: Transform,
+ ) -> None: ...
+ def get_image_magnification(self) -> float: ...
+ def draw_image(
+ self,
+ gc: GraphicsContextBase,
+ x: float,
+ y: float,
+ im: ArrayLike,
+ transform: transforms.Affine2DBase | None = ...,
+ ) -> None: ...
+ def option_image_nocomposite(self) -> bool: ...
+ def option_scale_image(self) -> bool: ...
+ def draw_tex(
+ self,
+ gc: GraphicsContextBase,
+ x: float,
+ y: float,
+ s: str,
+ prop: FontProperties,
+ angle: float,
+ *,
+ mtext: Text | None = ...
+ ) -> None: ...
+ def draw_text(
+ self,
+ gc: GraphicsContextBase,
+ x: float,
+ y: float,
+ s: str,
+ prop: FontProperties,
+ angle: float,
+ ismath: bool | Literal["TeX"] = ...,
+ mtext: Text | None = ...,
+ ) -> None: ...
+ def get_text_width_height_descent(
+ self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"]
+ ) -> tuple[float, float, float]: ...
+ def flipy(self) -> bool: ...
+ def get_canvas_width_height(self) -> tuple[float, float]: ...
+ def get_texmanager(self) -> TexManager: ...
+ def new_gc(self) -> GraphicsContextBase: ...
+ def points_to_pixels(self, points: ArrayLike) -> ArrayLike: ...
+ def start_rasterizing(self) -> None: ...
+ def stop_rasterizing(self) -> None: ...
+ def start_filter(self) -> None: ...
+ def stop_filter(self, filter_func) -> None: ...
+
+class GraphicsContextBase:
+ def __init__(self) -> None: ...
+ def copy_properties(self, gc: GraphicsContextBase) -> None: ...
+ def restore(self) -> None: ...
+ def get_alpha(self) -> float: ...
+ def get_antialiased(self) -> int: ...
+ def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
+ def get_clip_rectangle(self) -> Bbox | None: ...
+ def get_clip_path(
+ self,
+ ) -> tuple[TransformedPath, Transform] | tuple[None, None]: ...
+ def get_dashes(self) -> tuple[float, ArrayLike | None]: ...
+ def get_forced_alpha(self) -> bool: ...
+ def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
+ def get_linewidth(self) -> float: ...
+ def get_rgb(self) -> tuple[float, float, float, float]: ...
+ def get_url(self) -> str | None: ...
+ def get_gid(self) -> int | None: ...
+ def get_snap(self) -> bool | None: ...
+ def set_alpha(self, alpha: float) -> None: ...
+ def set_antialiased(self, b: bool) -> None: ...
+ def set_capstyle(self, cs: CapStyleType) -> None: ...
+ def set_clip_rectangle(self, rectangle: Bbox | None) -> None: ...
+ def set_clip_path(self, path: TransformedPath | None) -> None: ...
+ def set_dashes(self, dash_offset: float, dash_list: ArrayLike | None) -> None: ...
+ def set_foreground(self, fg: ColorType, isRGBA: bool = ...) -> None: ...
+ def set_joinstyle(self, js: JoinStyleType) -> None: ...
+ def set_linewidth(self, w: float) -> None: ...
+ def set_url(self, url: str | None) -> None: ...
+ def set_gid(self, id: int | None) -> None: ...
+ def set_snap(self, snap: bool | None) -> None: ...
+ def set_hatch(self, hatch: str | None) -> None: ...
+ def get_hatch(self) -> str | None: ...
+ def get_hatch_path(self, density: float = ...) -> Path: ...
+ def get_hatch_color(self) -> ColorType: ...
+ def set_hatch_color(self, hatch_color: ColorType) -> None: ...
+ def get_hatch_linewidth(self) -> float: ...
+ def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ...
+ def get_sketch_params(self) -> tuple[float, float, float] | None: ...
+ def set_sketch_params(
+ self,
+ scale: float | None = ...,
+ length: float | None = ...,
+ randomness: float | None = ...,
+ ) -> None: ...
+
+class TimerBase:
+ callbacks: list[tuple[Callable, tuple, dict[str, Any]]]
+ def __init__(
+ self,
+ interval: int | None = ...,
+ callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
+ ) -> None: ...
+ def __del__(self) -> None: ...
+ def start(self, interval: int | None = ...) -> None: ...
+ def stop(self) -> None: ...
+ @property
+ def interval(self) -> int: ...
+ @interval.setter
+ def interval(self, interval: int) -> None: ...
+ @property
+ def single_shot(self) -> bool: ...
+ @single_shot.setter
+ def single_shot(self, ss: bool) -> None: ...
+ def add_callback(self, func: Callable, *args, **kwargs) -> Callable: ...
+ def remove_callback(self, func: Callable, *args, **kwargs) -> None: ...
+
+class Event:
+ name: str
+ canvas: FigureCanvasBase
+ guiEvent: Any
+ def __init__(
+ self, name: str, canvas: FigureCanvasBase, guiEvent: Any | None = ...
+ ) -> None: ...
+
+class DrawEvent(Event):
+ renderer: RendererBase
+ def __init__(
+ self, name: str, canvas: FigureCanvasBase, renderer: RendererBase
+ ) -> None: ...
+
+class ResizeEvent(Event):
+ width: int
+ height: int
+ def __init__(self, name: str, canvas: FigureCanvasBase) -> None: ...
+
+class CloseEvent(Event): ...
+
+class LocationEvent(Event):
+ x: int
+ y: int
+ inaxes: Axes | None
+ xdata: float | None
+ ydata: float | None
+ def __init__(
+ self,
+ name: str,
+ canvas: FigureCanvasBase,
+ x: int,
+ y: int,
+ guiEvent: Any | None = ...,
+ *,
+ modifiers: Iterable[str] | None = ...,
+ ) -> None: ...
+
+class MouseButton(IntEnum):
+ LEFT: int
+ MIDDLE: int
+ RIGHT: int
+ BACK: int
+ FORWARD: int
+
+class MouseEvent(LocationEvent):
+ button: MouseButton | Literal["up", "down"] | None
+ key: str | None
+ step: float
+ dblclick: bool
+ def __init__(
+ self,
+ name: str,
+ canvas: FigureCanvasBase,
+ x: int,
+ y: int,
+ button: MouseButton | Literal["up", "down"] | None = ...,
+ key: str | None = ...,
+ step: float = ...,
+ dblclick: bool = ...,
+ guiEvent: Any | None = ...,
+ *,
+ buttons: Iterable[MouseButton] | None = ...,
+ modifiers: Iterable[str] | None = ...,
+ ) -> None: ...
+
+class PickEvent(Event):
+ mouseevent: MouseEvent
+ artist: Artist
+ def __init__(
+ self,
+ name: str,
+ canvas: FigureCanvasBase,
+ mouseevent: MouseEvent,
+ artist: Artist,
+ guiEvent: Any | None = ...,
+ **kwargs
+ ) -> None: ...
+
+class KeyEvent(LocationEvent):
+ key: str | None
+ def __init__(
+ self,
+ name: str,
+ canvas: FigureCanvasBase,
+ key: str | None,
+ x: int = ...,
+ y: int = ...,
+ guiEvent: Any | None = ...,
+ ) -> None: ...
+
+class FigureCanvasBase:
+ required_interactive_framework: str | None
+
+ @_api.classproperty
+ def manager_class(cls) -> type[FigureManagerBase]: ...
+ events: list[str]
+ fixed_dpi: None | float
+ filetypes: dict[str, str]
+
+ @_api.classproperty
+ def supports_blit(cls) -> bool: ...
+
+ figure: Figure
+ manager: None | FigureManagerBase
+ widgetlock: widgets.LockDraw
+ mouse_grabber: None | Axes
+ toolbar: None | NavigationToolbar2
+ def __init__(self, figure: Figure | None = ...) -> None: ...
+ @property
+ def callbacks(self) -> cbook.CallbackRegistry: ...
+ @property
+ def button_pick_id(self) -> int: ...
+ @property
+ def scroll_pick_id(self) -> int: ...
+ @classmethod
+ def new_manager(cls, figure: Figure, num: int | str) -> FigureManagerBase: ...
+ def is_saving(self) -> bool: ...
+ def blit(self, bbox: BboxBase | None = ...) -> None: ...
+ def inaxes(self, xy: tuple[float, float]) -> Axes | None: ...
+ def grab_mouse(self, ax: Axes) -> None: ...
+ def release_mouse(self, ax: Axes) -> None: ...
+ def set_cursor(self, cursor: Cursors) -> None: ...
+ def draw(self, *args, **kwargs) -> None: ...
+ def draw_idle(self, *args, **kwargs) -> None: ...
+ @property
+ def device_pixel_ratio(self) -> float: ...
+ def get_width_height(self, *, physical: bool = ...) -> tuple[int, int]: ...
+ @classmethod
+ def get_supported_filetypes(cls) -> dict[str, str]: ...
+ @classmethod
+ def get_supported_filetypes_grouped(cls) -> dict[str, list[str]]: ...
+ def print_figure(
+ self,
+ filename: str | os.PathLike | IO,
+ dpi: float | None = ...,
+ facecolor: ColorType | Literal["auto"] | None = ...,
+ edgecolor: ColorType | Literal["auto"] | None = ...,
+ orientation: str = ...,
+ format: str | None = ...,
+ *,
+ bbox_inches: Literal["tight"] | Bbox | None = ...,
+ pad_inches: float | None = ...,
+ bbox_extra_artists: list[Artist] | None = ...,
+ backend: str | None = ...,
+ **kwargs
+ ) -> Any: ...
+ @classmethod
+ def get_default_filetype(cls) -> str: ...
+ def get_default_filename(self) -> str: ...
+ _T = TypeVar("_T", bound=FigureCanvasBase)
+ def mpl_connect(self, s: str, func: Callable[[Event], Any]) -> int: ...
+ def mpl_disconnect(self, cid: int) -> None: ...
+ def new_timer(
+ self,
+ interval: int | None = ...,
+ callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
+ ) -> TimerBase: ...
+ def flush_events(self) -> None: ...
+ def start_event_loop(self, timeout: float = ...) -> None: ...
+ def stop_event_loop(self) -> None: ...
+
+def key_press_handler(
+ event: KeyEvent,
+ canvas: FigureCanvasBase | None = ...,
+ toolbar: NavigationToolbar2 | None = ...,
+) -> None: ...
+def button_press_handler(
+ event: MouseEvent,
+ canvas: FigureCanvasBase | None = ...,
+ toolbar: NavigationToolbar2 | None = ...,
+) -> None: ...
+
+class NonGuiException(Exception): ...
+
+class FigureManagerBase:
+ canvas: FigureCanvasBase
+ num: int | str
+ key_press_handler_id: int | None
+ button_press_handler_id: int | None
+ toolmanager: ToolManager | None
+ toolbar: NavigationToolbar2 | ToolContainerBase | None
+ def __init__(self, canvas: FigureCanvasBase, num: int | str) -> None: ...
+ @classmethod
+ def create_with_canvas(
+ cls, canvas_class: type[FigureCanvasBase], figure: Figure, num: int | str
+ ) -> FigureManagerBase: ...
+ @classmethod
+ def start_main_loop(cls) -> None: ...
+ @classmethod
+ def pyplot_show(cls, *, block: bool | None = ...) -> None: ...
+ def show(self) -> None: ...
+ def destroy(self) -> None: ...
+ def full_screen_toggle(self) -> None: ...
+ def resize(self, w: int, h: int) -> None: ...
+ def get_window_title(self) -> str: ...
+ def set_window_title(self, title: str) -> None: ...
+
+cursors = Cursors
+
+class _Mode(str, Enum):
+ NONE: str
+ PAN: str
+ ZOOM: str
+
+class NavigationToolbar2:
+ toolitems: tuple[tuple[str, ...] | tuple[None, ...], ...]
+ UNKNOWN_SAVED_STATUS: object
+ canvas: FigureCanvasBase
+ mode: _Mode
+ def __init__(self, canvas: FigureCanvasBase) -> None: ...
+ def set_message(self, s: str) -> None: ...
+ def draw_rubberband(
+ self, event: Event, x0: float, y0: float, x1: float, y1: float
+ ) -> None: ...
+ def remove_rubberband(self) -> None: ...
+ def home(self, *args) -> None: ...
+ def back(self, *args) -> None: ...
+ def forward(self, *args) -> None: ...
+ def mouse_move(self, event: MouseEvent) -> None: ...
+ def pan(self, *args) -> None: ...
+
+ class _PanInfo(NamedTuple):
+ button: MouseButton
+ axes: list[Axes]
+ cid: int
+ def press_pan(self, event: Event) -> None: ...
+ def drag_pan(self, event: Event) -> None: ...
+ def release_pan(self, event: Event) -> None: ...
+ def zoom(self, *args) -> None: ...
+
+ class _ZoomInfo(NamedTuple):
+ direction: Literal["in", "out"]
+ start_xy: tuple[float, float]
+ axes: list[Axes]
+ cid: int
+ cbar: Colorbar
+ def press_zoom(self, event: Event) -> None: ...
+ def drag_zoom(self, event: Event) -> None: ...
+ def release_zoom(self, event: Event) -> None: ...
+ def push_current(self) -> None: ...
+ subplot_tool: widgets.SubplotTool
+ def configure_subplots(self, *args): ...
+ def save_figure(self, *args) -> str | None | object: ...
+ def update(self) -> None: ...
+ def set_history_buttons(self) -> None: ...
+
+class ToolContainerBase:
+ toolmanager: ToolManager
+ def __init__(self, toolmanager: ToolManager) -> None: ...
+ def add_tool(self, tool: ToolBase, group: str, position: int = ...) -> None: ...
+ def trigger_tool(self, name: str) -> None: ...
+ def add_toolitem(
+ self,
+ name: str,
+ group: str,
+ position: int,
+ image: str,
+ description: str,
+ toggle: bool,
+ ) -> None: ...
+ def toggle_toolitem(self, name: str, toggled: bool) -> None: ...
+ def remove_toolitem(self, name: str) -> None: ...
+ def set_message(self, s: str) -> None: ...
+
+class _Backend:
+ backend_version: str
+ FigureCanvas: type[FigureCanvasBase] | None
+ FigureManager: type[FigureManagerBase]
+ mainloop: None | Callable[[], Any]
+ @classmethod
+ def new_figure_manager(cls, num: int | str, *args, **kwargs) -> FigureManagerBase: ...
+ @classmethod
+ def new_figure_manager_given_figure(cls, num: int | str, figure: Figure) -> FigureManagerBase: ...
+ @classmethod
+ def draw_if_interactive(cls) -> None: ...
+ @classmethod
+ def show(cls, *, block: bool | None = ...) -> None: ...
+ @staticmethod
+ def export(cls) -> type[_Backend]: ...
+
+class ShowBase(_Backend):
+ def __call__(self, block: bool | None = ...) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/backend_managers.py b/llava_video/lib/python3.10/site-packages/matplotlib/backend_managers.py
new file mode 100644
index 0000000000000000000000000000000000000000..76f15030bcc5e2c112b9aa72ca9cbf18334599e2
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/backend_managers.py
@@ -0,0 +1,387 @@
+from matplotlib import _api, backend_tools, cbook, widgets
+
+
+class ToolEvent:
+ """Event for tool manipulation (add/remove)."""
+ def __init__(self, name, sender, tool, data=None):
+ self.name = name
+ self.sender = sender
+ self.tool = tool
+ self.data = data
+
+
+class ToolTriggerEvent(ToolEvent):
+ """Event to inform that a tool has been triggered."""
+ def __init__(self, name, sender, tool, canvasevent=None, data=None):
+ super().__init__(name, sender, tool, data)
+ self.canvasevent = canvasevent
+
+
+class ToolManagerMessageEvent:
+ """
+ Event carrying messages from toolmanager.
+
+ Messages usually get displayed to the user by the toolbar.
+ """
+ def __init__(self, name, sender, message):
+ self.name = name
+ self.sender = sender
+ self.message = message
+
+
+class ToolManager:
+ """
+ Manager for actions triggered by user interactions (key press, toolbar
+ clicks, ...) on a Figure.
+
+ Attributes
+ ----------
+ figure : `.Figure`
+ keypresslock : `~matplotlib.widgets.LockDraw`
+ `.LockDraw` object to know if the `canvas` key_press_event is locked.
+ messagelock : `~matplotlib.widgets.LockDraw`
+ `.LockDraw` object to know if the message is available to write.
+ """
+
+ def __init__(self, figure=None):
+
+ self._key_press_handler_id = None
+
+ self._tools = {}
+ self._keys = {}
+ self._toggled = {}
+ self._callbacks = cbook.CallbackRegistry()
+
+ # to process keypress event
+ self.keypresslock = widgets.LockDraw()
+ self.messagelock = widgets.LockDraw()
+
+ self._figure = None
+ self.set_figure(figure)
+
+ @property
+ def canvas(self):
+ """Canvas managed by FigureManager."""
+ if not self._figure:
+ return None
+ return self._figure.canvas
+
+ @property
+ def figure(self):
+ """Figure that holds the canvas."""
+ return self._figure
+
+ @figure.setter
+ def figure(self, figure):
+ self.set_figure(figure)
+
+ def set_figure(self, figure, update_tools=True):
+ """
+ Bind the given figure to the tools.
+
+ Parameters
+ ----------
+ figure : `.Figure`
+ update_tools : bool, default: True
+ Force tools to update figure.
+ """
+ if self._key_press_handler_id:
+ self.canvas.mpl_disconnect(self._key_press_handler_id)
+ self._figure = figure
+ if figure:
+ self._key_press_handler_id = self.canvas.mpl_connect(
+ 'key_press_event', self._key_press)
+ if update_tools:
+ for tool in self._tools.values():
+ tool.figure = figure
+
+ def toolmanager_connect(self, s, func):
+ """
+ Connect event with string *s* to *func*.
+
+ Parameters
+ ----------
+ s : str
+ The name of the event. The following events are recognized:
+
+ - 'tool_message_event'
+ - 'tool_removed_event'
+ - 'tool_added_event'
+
+ For every tool added a new event is created
+
+ - 'tool_trigger_TOOLNAME', where TOOLNAME is the id of the tool.
+
+ func : callable
+ Callback function for the toolmanager event with signature::
+
+ def func(event: ToolEvent) -> Any
+
+ Returns
+ -------
+ cid
+ The callback id for the connection. This can be used in
+ `.toolmanager_disconnect`.
+ """
+ return self._callbacks.connect(s, func)
+
+ def toolmanager_disconnect(self, cid):
+ """
+ Disconnect callback id *cid*.
+
+ Example usage::
+
+ cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress)
+ #...later
+ toolmanager.toolmanager_disconnect(cid)
+ """
+ return self._callbacks.disconnect(cid)
+
+ def message_event(self, message, sender=None):
+ """Emit a `ToolManagerMessageEvent`."""
+ if sender is None:
+ sender = self
+
+ s = 'tool_message_event'
+ event = ToolManagerMessageEvent(s, sender, message)
+ self._callbacks.process(s, event)
+
+ @property
+ def active_toggle(self):
+ """Currently toggled tools."""
+ return self._toggled
+
+ def get_tool_keymap(self, name):
+ """
+ Return the keymap associated with the specified tool.
+
+ Parameters
+ ----------
+ name : str
+ Name of the Tool.
+
+ Returns
+ -------
+ list of str
+ List of keys associated with the tool.
+ """
+
+ keys = [k for k, i in self._keys.items() if i == name]
+ return keys
+
+ def _remove_keys(self, name):
+ for k in self.get_tool_keymap(name):
+ del self._keys[k]
+
+ def update_keymap(self, name, key):
+ """
+ Set the keymap to associate with the specified tool.
+
+ Parameters
+ ----------
+ name : str
+ Name of the Tool.
+ key : str or list of str
+ Keys to associate with the tool.
+ """
+ if name not in self._tools:
+ raise KeyError(f'{name!r} not in Tools')
+ self._remove_keys(name)
+ if isinstance(key, str):
+ key = [key]
+ for k in key:
+ if k in self._keys:
+ _api.warn_external(
+ f'Key {k} changed from {self._keys[k]} to {name}')
+ self._keys[k] = name
+
+ def remove_tool(self, name):
+ """
+ Remove tool named *name*.
+
+ Parameters
+ ----------
+ name : str
+ Name of the tool.
+ """
+ tool = self.get_tool(name)
+ if getattr(tool, 'toggled', False): # If it's a toggled toggle tool, untoggle
+ self.trigger_tool(tool, 'toolmanager')
+ self._remove_keys(name)
+ event = ToolEvent('tool_removed_event', self, tool)
+ self._callbacks.process(event.name, event)
+ del self._tools[name]
+
+ def add_tool(self, name, tool, *args, **kwargs):
+ """
+ Add *tool* to `ToolManager`.
+
+ If successful, adds a new event ``tool_trigger_{name}`` where
+ ``{name}`` is the *name* of the tool; the event is fired every time the
+ tool is triggered.
+
+ Parameters
+ ----------
+ name : str
+ Name of the tool, treated as the ID, has to be unique.
+ tool : type
+ Class of the tool to be added. A subclass will be used
+ instead if one was registered for the current canvas class.
+ *args, **kwargs
+ Passed to the *tool*'s constructor.
+
+ See Also
+ --------
+ matplotlib.backend_tools.ToolBase : The base class for tools.
+ """
+
+ tool_cls = backend_tools._find_tool_class(type(self.canvas), tool)
+ if not tool_cls:
+ raise ValueError('Impossible to find class for %s' % str(tool))
+
+ if name in self._tools:
+ _api.warn_external('A "Tool class" with the same name already '
+ 'exists, not added')
+ return self._tools[name]
+
+ tool_obj = tool_cls(self, name, *args, **kwargs)
+ self._tools[name] = tool_obj
+
+ if tool_obj.default_keymap is not None:
+ self.update_keymap(name, tool_obj.default_keymap)
+
+ # For toggle tools init the radio_group in self._toggled
+ if isinstance(tool_obj, backend_tools.ToolToggleBase):
+ # None group is not mutually exclusive, a set is used to keep track
+ # of all toggled tools in this group
+ if tool_obj.radio_group is None:
+ self._toggled.setdefault(None, set())
+ else:
+ self._toggled.setdefault(tool_obj.radio_group, None)
+
+ # If initially toggled
+ if tool_obj.toggled:
+ self._handle_toggle(tool_obj, None, None)
+ tool_obj.set_figure(self.figure)
+
+ event = ToolEvent('tool_added_event', self, tool_obj)
+ self._callbacks.process(event.name, event)
+
+ return tool_obj
+
+ def _handle_toggle(self, tool, canvasevent, data):
+ """
+ Toggle tools, need to untoggle prior to using other Toggle tool.
+ Called from trigger_tool.
+
+ Parameters
+ ----------
+ tool : `.ToolBase`
+ canvasevent : Event
+ Original Canvas event or None.
+ data : object
+ Extra data to pass to the tool when triggering.
+ """
+
+ radio_group = tool.radio_group
+ # radio_group None is not mutually exclusive
+ # just keep track of toggled tools in this group
+ if radio_group is None:
+ if tool.name in self._toggled[None]:
+ self._toggled[None].remove(tool.name)
+ else:
+ self._toggled[None].add(tool.name)
+ return
+
+ # If the tool already has a toggled state, untoggle it
+ if self._toggled[radio_group] == tool.name:
+ toggled = None
+ # If no tool was toggled in the radio_group
+ # toggle it
+ elif self._toggled[radio_group] is None:
+ toggled = tool.name
+ # Other tool in the radio_group is toggled
+ else:
+ # Untoggle previously toggled tool
+ self.trigger_tool(self._toggled[radio_group],
+ self,
+ canvasevent,
+ data)
+ toggled = tool.name
+
+ # Keep track of the toggled tool in the radio_group
+ self._toggled[radio_group] = toggled
+
+ def trigger_tool(self, name, sender=None, canvasevent=None, data=None):
+ """
+ Trigger a tool and emit the ``tool_trigger_{name}`` event.
+
+ Parameters
+ ----------
+ name : str
+ Name of the tool.
+ sender : object
+ Object that wishes to trigger the tool.
+ canvasevent : Event
+ Original Canvas event or None.
+ data : object
+ Extra data to pass to the tool when triggering.
+ """
+ tool = self.get_tool(name)
+ if tool is None:
+ return
+
+ if sender is None:
+ sender = self
+
+ if isinstance(tool, backend_tools.ToolToggleBase):
+ self._handle_toggle(tool, canvasevent, data)
+
+ tool.trigger(sender, canvasevent, data) # Actually trigger Tool.
+
+ s = 'tool_trigger_%s' % name
+ event = ToolTriggerEvent(s, sender, tool, canvasevent, data)
+ self._callbacks.process(s, event)
+
+ def _key_press(self, event):
+ if event.key is None or self.keypresslock.locked():
+ return
+
+ name = self._keys.get(event.key, None)
+ if name is None:
+ return
+ self.trigger_tool(name, canvasevent=event)
+
+ @property
+ def tools(self):
+ """A dict mapping tool name -> controlled tool."""
+ return self._tools
+
+ def get_tool(self, name, warn=True):
+ """
+ Return the tool object with the given name.
+
+ For convenience, this passes tool objects through.
+
+ Parameters
+ ----------
+ name : str or `.ToolBase`
+ Name of the tool, or the tool itself.
+ warn : bool, default: True
+ Whether a warning should be emitted it no tool with the given name
+ exists.
+
+ Returns
+ -------
+ `.ToolBase` or None
+ The tool or None if no tool with the given name exists.
+ """
+ if (isinstance(name, backend_tools.ToolBase)
+ and name.name in self._tools):
+ return name
+ if name not in self._tools:
+ if warn:
+ _api.warn_external(
+ f"ToolManager does not control tool {name!r}")
+ return None
+ return self._tools[name]
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/backend_managers.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/backend_managers.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..9e59acb14eda98b25e2dcb3f6e2004ca99d0ae5e
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/backend_managers.pyi
@@ -0,0 +1,64 @@
+from matplotlib import backend_tools, widgets
+from matplotlib.backend_bases import FigureCanvasBase
+from matplotlib.figure import Figure
+
+from collections.abc import Callable, Iterable
+from typing import Any, TypeVar
+
+class ToolEvent:
+ name: str
+ sender: Any
+ tool: backend_tools.ToolBase
+ data: Any
+ def __init__(self, name, sender, tool, data: Any | None = ...) -> None: ...
+
+class ToolTriggerEvent(ToolEvent):
+ canvasevent: ToolEvent
+ def __init__(
+ self,
+ name,
+ sender,
+ tool,
+ canvasevent: ToolEvent | None = ...,
+ data: Any | None = ...,
+ ) -> None: ...
+
+class ToolManagerMessageEvent:
+ name: str
+ sender: Any
+ message: str
+ def __init__(self, name: str, sender: Any, message: str) -> None: ...
+
+class ToolManager:
+ keypresslock: widgets.LockDraw
+ messagelock: widgets.LockDraw
+ def __init__(self, figure: Figure | None = ...) -> None: ...
+ @property
+ def canvas(self) -> FigureCanvasBase | None: ...
+ @property
+ def figure(self) -> Figure | None: ...
+ @figure.setter
+ def figure(self, figure: Figure) -> None: ...
+ def set_figure(self, figure: Figure, update_tools: bool = ...) -> None: ...
+ def toolmanager_connect(self, s: str, func: Callable[[ToolEvent], Any]) -> int: ...
+ def toolmanager_disconnect(self, cid: int) -> None: ...
+ def message_event(self, message: str, sender: Any | None = ...) -> None: ...
+ @property
+ def active_toggle(self) -> dict[str | None, list[str] | str]: ...
+ def get_tool_keymap(self, name: str) -> list[str]: ...
+ def update_keymap(self, name: str, key: str | Iterable[str]) -> None: ...
+ def remove_tool(self, name: str) -> None: ...
+ _T = TypeVar("_T", bound=backend_tools.ToolBase)
+ def add_tool(self, name: str, tool: type[_T], *args, **kwargs) -> _T: ...
+ def trigger_tool(
+ self,
+ name: str | backend_tools.ToolBase,
+ sender: Any | None = ...,
+ canvasevent: ToolEvent | None = ...,
+ data: Any | None = ...,
+ ) -> None: ...
+ @property
+ def tools(self) -> dict[str, backend_tools.ToolBase]: ...
+ def get_tool(
+ self, name: str | backend_tools.ToolBase, warn: bool = ...
+ ) -> backend_tools.ToolBase | None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/backend_tools.py b/llava_video/lib/python3.10/site-packages/matplotlib/backend_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ed794022a0eee732da01ac9627b84020c83013
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/backend_tools.py
@@ -0,0 +1,998 @@
+"""
+Abstract base classes define the primitives for Tools.
+These tools are used by `matplotlib.backend_managers.ToolManager`
+
+:class:`ToolBase`
+ Simple stateless tool
+
+:class:`ToolToggleBase`
+ Tool that has two states, only one Toggle tool can be
+ active at any given time for the same
+ `matplotlib.backend_managers.ToolManager`
+"""
+
+import enum
+import functools
+import re
+import time
+from types import SimpleNamespace
+import uuid
+from weakref import WeakKeyDictionary
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib._pylab_helpers import Gcf
+from matplotlib import _api, cbook
+
+
+class Cursors(enum.IntEnum): # Must subclass int for the macOS backend.
+ """Backend-independent cursor types."""
+ POINTER = enum.auto()
+ HAND = enum.auto()
+ SELECT_REGION = enum.auto()
+ MOVE = enum.auto()
+ WAIT = enum.auto()
+ RESIZE_HORIZONTAL = enum.auto()
+ RESIZE_VERTICAL = enum.auto()
+cursors = Cursors # Backcompat.
+
+
+# _tool_registry, _register_tool_class, and _find_tool_class implement a
+# mechanism through which ToolManager.add_tool can determine whether a subclass
+# of the requested tool class has been registered (either for the current
+# canvas class or for a parent class), in which case that tool subclass will be
+# instantiated instead. This is the mechanism used e.g. to allow different
+# GUI backends to implement different specializations for ConfigureSubplots.
+
+
+_tool_registry = set()
+
+
+def _register_tool_class(canvas_cls, tool_cls=None):
+ """Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
+ if tool_cls is None:
+ return functools.partial(_register_tool_class, canvas_cls)
+ _tool_registry.add((canvas_cls, tool_cls))
+ return tool_cls
+
+
+def _find_tool_class(canvas_cls, tool_cls):
+ """Find a subclass of *tool_cls* registered for *canvas_cls*."""
+ for canvas_parent in canvas_cls.__mro__:
+ for tool_child in _api.recursive_subclasses(tool_cls):
+ if (canvas_parent, tool_child) in _tool_registry:
+ return tool_child
+ return tool_cls
+
+
+# Views positions tool
+_views_positions = 'viewpos'
+
+
+class ToolBase:
+ """
+ Base tool class.
+
+ A base tool, only implements `trigger` method or no method at all.
+ The tool is instantiated by `matplotlib.backend_managers.ToolManager`.
+ """
+
+ default_keymap = None
+ """
+ Keymap to associate with this tool.
+
+ ``list[str]``: List of keys that will trigger this tool when a keypress
+ event is emitted on ``self.figure.canvas``. Note that this attribute is
+ looked up on the instance, and can therefore be a property (this is used
+ e.g. by the built-in tools to load the rcParams at instantiation time).
+ """
+
+ description = None
+ """
+ Description of the Tool.
+
+ `str`: Tooltip used if the Tool is included in a Toolbar.
+ """
+
+ image = None
+ """
+ Icon filename.
+
+ ``str | None``: Filename of the Toolbar icon; either absolute, or relative to the
+ directory containing the Python source file where the ``Tool.image`` class attribute
+ is defined (in the latter case, this cannot be defined as an instance attribute).
+ In either case, the extension is optional; leaving it off lets individual backends
+ select the icon format they prefer. If None, the *name* is used as a label in the
+ toolbar button.
+ """
+
+ def __init__(self, toolmanager, name):
+ self._name = name
+ self._toolmanager = toolmanager
+ self._figure = None
+
+ name = property(
+ lambda self: self._name,
+ doc="The tool id (str, must be unique among tools of a tool manager).")
+ toolmanager = property(
+ lambda self: self._toolmanager,
+ doc="The `.ToolManager` that controls this tool.")
+ canvas = property(
+ lambda self: self._figure.canvas if self._figure is not None else None,
+ doc="The canvas of the figure affected by this tool, or None.")
+
+ def set_figure(self, figure):
+ self._figure = figure
+
+ figure = property(
+ lambda self: self._figure,
+ # The setter must explicitly call self.set_figure so that subclasses can
+ # meaningfully override it.
+ lambda self, figure: self.set_figure(figure),
+ doc="The Figure affected by this tool, or None.")
+
+ def _make_classic_style_pseudo_toolbar(self):
+ """
+ Return a placeholder object with a single `canvas` attribute.
+
+ This is useful to reuse the implementations of tools already provided
+ by the classic Toolbars.
+ """
+ return SimpleNamespace(canvas=self.canvas)
+
+ def trigger(self, sender, event, data=None):
+ """
+ Called when this tool gets used.
+
+ This method is called by `.ToolManager.trigger_tool`.
+
+ Parameters
+ ----------
+ event : `.Event`
+ The canvas event that caused this tool to be called.
+ sender : object
+ Object that requested the tool to be triggered.
+ data : object
+ Extra data.
+ """
+ pass
+
+
+class ToolToggleBase(ToolBase):
+ """
+ Toggleable tool.
+
+ Every time it is triggered, it switches between enable and disable.
+
+ Parameters
+ ----------
+ ``*args``
+ Variable length argument to be used by the Tool.
+ ``**kwargs``
+ `toggled` if present and True, sets the initial state of the Tool
+ Arbitrary keyword arguments to be consumed by the Tool
+ """
+
+ radio_group = None
+ """
+ Attribute to group 'radio' like tools (mutually exclusive).
+
+ `str` that identifies the group or **None** if not belonging to a group.
+ """
+
+ cursor = None
+ """Cursor to use when the tool is active."""
+
+ default_toggled = False
+ """Default of toggled state."""
+
+ def __init__(self, *args, **kwargs):
+ self._toggled = kwargs.pop('toggled', self.default_toggled)
+ super().__init__(*args, **kwargs)
+
+ def trigger(self, sender, event, data=None):
+ """Calls `enable` or `disable` based on `toggled` value."""
+ if self._toggled:
+ self.disable(event)
+ else:
+ self.enable(event)
+ self._toggled = not self._toggled
+
+ def enable(self, event=None):
+ """
+ Enable the toggle tool.
+
+ `trigger` calls this method when `toggled` is False.
+ """
+ pass
+
+ def disable(self, event=None):
+ """
+ Disable the toggle tool.
+
+ `trigger` call this method when `toggled` is True.
+
+ This can happen in different circumstances.
+
+ * Click on the toolbar tool button.
+ * Call to `matplotlib.backend_managers.ToolManager.trigger_tool`.
+ * Another `ToolToggleBase` derived tool is triggered
+ (from the same `.ToolManager`).
+ """
+ pass
+
+ @property
+ def toggled(self):
+ """State of the toggled tool."""
+ return self._toggled
+
+ def set_figure(self, figure):
+ toggled = self.toggled
+ if toggled:
+ if self.figure:
+ self.trigger(self, None)
+ else:
+ # if no figure the internal state is not changed
+ # we change it here so next call to trigger will change it back
+ self._toggled = False
+ super().set_figure(figure)
+ if toggled:
+ if figure:
+ self.trigger(self, None)
+ else:
+ # if there is no figure, trigger won't change the internal
+ # state we change it back
+ self._toggled = True
+
+
+class ToolSetCursor(ToolBase):
+ """
+ Change to the current cursor while inaxes.
+
+ This tool, keeps track of all `ToolToggleBase` derived tools, and updates
+ the cursor when a tool gets triggered.
+ """
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._id_drag = None
+ self._current_tool = None
+ self._default_cursor = cursors.POINTER
+ self._last_cursor = self._default_cursor
+ self.toolmanager.toolmanager_connect('tool_added_event',
+ self._add_tool_cbk)
+ for tool in self.toolmanager.tools.values(): # process current tools
+ self._add_tool_cbk(mpl.backend_managers.ToolEvent(
+ 'tool_added_event', self.toolmanager, tool))
+
+ def set_figure(self, figure):
+ if self._id_drag:
+ self.canvas.mpl_disconnect(self._id_drag)
+ super().set_figure(figure)
+ if figure:
+ self._id_drag = self.canvas.mpl_connect(
+ 'motion_notify_event', self._set_cursor_cbk)
+
+ def _add_tool_cbk(self, event):
+ """Process every newly added tool."""
+ if getattr(event.tool, 'cursor', None) is not None:
+ self.toolmanager.toolmanager_connect(
+ f'tool_trigger_{event.tool.name}', self._tool_trigger_cbk)
+
+ def _tool_trigger_cbk(self, event):
+ self._current_tool = event.tool if event.tool.toggled else None
+ self._set_cursor_cbk(event.canvasevent)
+
+ def _set_cursor_cbk(self, event):
+ if not event or not self.canvas:
+ return
+ if (self._current_tool and getattr(event, "inaxes", None)
+ and event.inaxes.get_navigate()):
+ if self._last_cursor != self._current_tool.cursor:
+ self.canvas.set_cursor(self._current_tool.cursor)
+ self._last_cursor = self._current_tool.cursor
+ elif self._last_cursor != self._default_cursor:
+ self.canvas.set_cursor(self._default_cursor)
+ self._last_cursor = self._default_cursor
+
+
+class ToolCursorPosition(ToolBase):
+ """
+ Send message with the current pointer position.
+
+ This tool runs in the background reporting the position of the cursor.
+ """
+ def __init__(self, *args, **kwargs):
+ self._id_drag = None
+ super().__init__(*args, **kwargs)
+
+ def set_figure(self, figure):
+ if self._id_drag:
+ self.canvas.mpl_disconnect(self._id_drag)
+ super().set_figure(figure)
+ if figure:
+ self._id_drag = self.canvas.mpl_connect(
+ 'motion_notify_event', self.send_message)
+
+ def send_message(self, event):
+ """Call `matplotlib.backend_managers.ToolManager.message_event`."""
+ if self.toolmanager.messagelock.locked():
+ return
+
+ from matplotlib.backend_bases import NavigationToolbar2
+ message = NavigationToolbar2._mouse_event_to_message(event)
+ self.toolmanager.message_event(message, self)
+
+
+class RubberbandBase(ToolBase):
+ """Draw and remove a rubberband."""
+ def trigger(self, sender, event, data=None):
+ """Call `draw_rubberband` or `remove_rubberband` based on data."""
+ if not self.figure.canvas.widgetlock.available(sender):
+ return
+ if data is not None:
+ self.draw_rubberband(*data)
+ else:
+ self.remove_rubberband()
+
+ def draw_rubberband(self, *data):
+ """
+ Draw rubberband.
+
+ This method must get implemented per backend.
+ """
+ raise NotImplementedError
+
+ def remove_rubberband(self):
+ """
+ Remove rubberband.
+
+ This method should get implemented per backend.
+ """
+ pass
+
+
+class ToolQuit(ToolBase):
+ """Tool to call the figure manager destroy method."""
+
+ description = 'Quit the figure'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.quit'])
+
+ def trigger(self, sender, event, data=None):
+ Gcf.destroy_fig(self.figure)
+
+
+class ToolQuitAll(ToolBase):
+ """Tool to call the figure manager destroy method."""
+
+ description = 'Quit all figures'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all'])
+
+ def trigger(self, sender, event, data=None):
+ Gcf.destroy_all()
+
+
+class ToolGrid(ToolBase):
+ """Tool to toggle the major grids of the figure."""
+
+ description = 'Toggle major grids'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
+
+ def trigger(self, sender, event, data=None):
+ sentinel = str(uuid.uuid4())
+ # Trigger grid switching by temporarily setting :rc:`keymap.grid`
+ # to a unique key and sending an appropriate event.
+ with (cbook._setattr_cm(event, key=sentinel),
+ mpl.rc_context({'keymap.grid': sentinel})):
+ mpl.backend_bases.key_press_handler(event, self.figure.canvas)
+
+
+class ToolMinorGrid(ToolBase):
+ """Tool to toggle the major and minor grids of the figure."""
+
+ description = 'Toggle major and minor grids'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor'])
+
+ def trigger(self, sender, event, data=None):
+ sentinel = str(uuid.uuid4())
+ # Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
+ # to a unique key and sending an appropriate event.
+ with (cbook._setattr_cm(event, key=sentinel),
+ mpl.rc_context({'keymap.grid_minor': sentinel})):
+ mpl.backend_bases.key_press_handler(event, self.figure.canvas)
+
+
+class ToolFullScreen(ToolBase):
+ """Tool to toggle full screen."""
+
+ description = 'Toggle fullscreen mode'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen'])
+
+ def trigger(self, sender, event, data=None):
+ self.figure.canvas.manager.full_screen_toggle()
+
+
+class AxisScaleBase(ToolToggleBase):
+ """Base Tool to toggle between linear and logarithmic."""
+
+ def trigger(self, sender, event, data=None):
+ if event.inaxes is None:
+ return
+ super().trigger(sender, event, data)
+
+ def enable(self, event=None):
+ self.set_scale(event.inaxes, 'log')
+ self.figure.canvas.draw_idle()
+
+ def disable(self, event=None):
+ self.set_scale(event.inaxes, 'linear')
+ self.figure.canvas.draw_idle()
+
+
+class ToolYScale(AxisScaleBase):
+ """Tool to toggle between linear and logarithmic scales on the Y axis."""
+
+ description = 'Toggle scale Y axis'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.yscale'])
+
+ def set_scale(self, ax, scale):
+ ax.set_yscale(scale)
+
+
+class ToolXScale(AxisScaleBase):
+ """Tool to toggle between linear and logarithmic scales on the X axis."""
+
+ description = 'Toggle scale X axis'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
+
+ def set_scale(self, ax, scale):
+ ax.set_xscale(scale)
+
+
+class ToolViewsPositions(ToolBase):
+ """
+ Auxiliary Tool to handle changes in views and positions.
+
+ Runs in the background and should get used by all the tools that
+ need to access the figure's history of views and positions, e.g.
+
+ * `ToolZoom`
+ * `ToolPan`
+ * `ToolHome`
+ * `ToolBack`
+ * `ToolForward`
+ """
+
+ def __init__(self, *args, **kwargs):
+ self.views = WeakKeyDictionary()
+ self.positions = WeakKeyDictionary()
+ self.home_views = WeakKeyDictionary()
+ super().__init__(*args, **kwargs)
+
+ def add_figure(self, figure):
+ """Add the current figure to the stack of views and positions."""
+
+ if figure not in self.views:
+ self.views[figure] = cbook._Stack()
+ self.positions[figure] = cbook._Stack()
+ self.home_views[figure] = WeakKeyDictionary()
+ # Define Home
+ self.push_current(figure)
+ # Make sure we add a home view for new Axes as they're added
+ figure.add_axobserver(lambda fig: self.update_home_views(fig))
+
+ def clear(self, figure):
+ """Reset the Axes stack."""
+ if figure in self.views:
+ self.views[figure].clear()
+ self.positions[figure].clear()
+ self.home_views[figure].clear()
+ self.update_home_views()
+
+ def update_view(self):
+ """
+ Update the view limits and position for each Axes from the current
+ stack position. If any Axes are present in the figure that aren't in
+ the current stack position, use the home view limits for those Axes and
+ don't update *any* positions.
+ """
+
+ views = self.views[self.figure]()
+ if views is None:
+ return
+ pos = self.positions[self.figure]()
+ if pos is None:
+ return
+ home_views = self.home_views[self.figure]
+ all_axes = self.figure.get_axes()
+ for a in all_axes:
+ if a in views:
+ cur_view = views[a]
+ else:
+ cur_view = home_views[a]
+ a._set_view(cur_view)
+
+ if set(all_axes).issubset(pos):
+ for a in all_axes:
+ # Restore both the original and modified positions
+ a._set_position(pos[a][0], 'original')
+ a._set_position(pos[a][1], 'active')
+
+ self.figure.canvas.draw_idle()
+
+ def push_current(self, figure=None):
+ """
+ Push the current view limits and position onto their respective stacks.
+ """
+ if not figure:
+ figure = self.figure
+ views = WeakKeyDictionary()
+ pos = WeakKeyDictionary()
+ for a in figure.get_axes():
+ views[a] = a._get_view()
+ pos[a] = self._axes_pos(a)
+ self.views[figure].push(views)
+ self.positions[figure].push(pos)
+
+ def _axes_pos(self, ax):
+ """
+ Return the original and modified positions for the specified Axes.
+
+ Parameters
+ ----------
+ ax : matplotlib.axes.Axes
+ The `.Axes` to get the positions for.
+
+ Returns
+ -------
+ original_position, modified_position
+ A tuple of the original and modified positions.
+ """
+
+ return (ax.get_position(True).frozen(),
+ ax.get_position().frozen())
+
+ def update_home_views(self, figure=None):
+ """
+ Make sure that ``self.home_views`` has an entry for all Axes present
+ in the figure.
+ """
+
+ if not figure:
+ figure = self.figure
+ for a in figure.get_axes():
+ if a not in self.home_views[figure]:
+ self.home_views[figure][a] = a._get_view()
+
+ def home(self):
+ """Recall the first view and position from the stack."""
+ self.views[self.figure].home()
+ self.positions[self.figure].home()
+
+ def back(self):
+ """Back one step in the stack of views and positions."""
+ self.views[self.figure].back()
+ self.positions[self.figure].back()
+
+ def forward(self):
+ """Forward one step in the stack of views and positions."""
+ self.views[self.figure].forward()
+ self.positions[self.figure].forward()
+
+
+class ViewsPositionsBase(ToolBase):
+ """Base class for `ToolHome`, `ToolBack` and `ToolForward`."""
+
+ _on_trigger = None
+
+ def trigger(self, sender, event, data=None):
+ self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
+ getattr(self.toolmanager.get_tool(_views_positions),
+ self._on_trigger)()
+ self.toolmanager.get_tool(_views_positions).update_view()
+
+
+class ToolHome(ViewsPositionsBase):
+ """Restore the original view limits."""
+
+ description = 'Reset original view'
+ image = 'mpl-data/images/home'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.home'])
+ _on_trigger = 'home'
+
+
+class ToolBack(ViewsPositionsBase):
+ """Move back up the view limits stack."""
+
+ description = 'Back to previous view'
+ image = 'mpl-data/images/back'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.back'])
+ _on_trigger = 'back'
+
+
+class ToolForward(ViewsPositionsBase):
+ """Move forward in the view lim stack."""
+
+ description = 'Forward to next view'
+ image = 'mpl-data/images/forward'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.forward'])
+ _on_trigger = 'forward'
+
+
+class ConfigureSubplotsBase(ToolBase):
+ """Base tool for the configuration of subplots."""
+
+ description = 'Configure subplots'
+ image = 'mpl-data/images/subplots'
+
+
+class SaveFigureBase(ToolBase):
+ """Base tool for figure saving."""
+
+ description = 'Save the figure'
+ image = 'mpl-data/images/filesave'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.save'])
+
+
+class ZoomPanBase(ToolToggleBase):
+ """Base class for `ToolZoom` and `ToolPan`."""
+ def __init__(self, *args):
+ super().__init__(*args)
+ self._button_pressed = None
+ self._xypress = None
+ self._idPress = None
+ self._idRelease = None
+ self._idScroll = None
+ self.base_scale = 2.
+ self.scrollthresh = .5 # .5 second scroll threshold
+ self.lastscroll = time.time()-self.scrollthresh
+
+ def enable(self, event=None):
+ """Connect press/release events and lock the canvas."""
+ self.figure.canvas.widgetlock(self)
+ self._idPress = self.figure.canvas.mpl_connect(
+ 'button_press_event', self._press)
+ self._idRelease = self.figure.canvas.mpl_connect(
+ 'button_release_event', self._release)
+ self._idScroll = self.figure.canvas.mpl_connect(
+ 'scroll_event', self.scroll_zoom)
+
+ def disable(self, event=None):
+ """Release the canvas and disconnect press/release events."""
+ self._cancel_action()
+ self.figure.canvas.widgetlock.release(self)
+ self.figure.canvas.mpl_disconnect(self._idPress)
+ self.figure.canvas.mpl_disconnect(self._idRelease)
+ self.figure.canvas.mpl_disconnect(self._idScroll)
+
+ def trigger(self, sender, event, data=None):
+ self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
+ super().trigger(sender, event, data)
+ new_navigate_mode = self.name.upper() if self.toggled else None
+ for ax in self.figure.axes:
+ ax.set_navigate_mode(new_navigate_mode)
+
+ def scroll_zoom(self, event):
+ # https://gist.github.com/tacaswell/3144287
+ if event.inaxes is None:
+ return
+
+ if event.button == 'up':
+ # deal with zoom in
+ scl = self.base_scale
+ elif event.button == 'down':
+ # deal with zoom out
+ scl = 1/self.base_scale
+ else:
+ # deal with something that should never happen
+ scl = 1
+
+ ax = event.inaxes
+ ax._set_view_from_bbox([event.x, event.y, scl])
+
+ # If last scroll was done within the timing threshold, delete the
+ # previous view
+ if (time.time()-self.lastscroll) < self.scrollthresh:
+ self.toolmanager.get_tool(_views_positions).back()
+
+ self.figure.canvas.draw_idle() # force re-draw
+
+ self.lastscroll = time.time()
+ self.toolmanager.get_tool(_views_positions).push_current()
+
+
+class ToolZoom(ZoomPanBase):
+ """A Tool for zooming using a rectangle selector."""
+
+ description = 'Zoom to rectangle'
+ image = 'mpl-data/images/zoom_to_rect'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.zoom'])
+ cursor = cursors.SELECT_REGION
+ radio_group = 'default'
+
+ def __init__(self, *args):
+ super().__init__(*args)
+ self._ids_zoom = []
+
+ def _cancel_action(self):
+ for zoom_id in self._ids_zoom:
+ self.figure.canvas.mpl_disconnect(zoom_id)
+ self.toolmanager.trigger_tool('rubberband', self)
+ self.figure.canvas.draw_idle()
+ self._xypress = None
+ self._button_pressed = None
+ self._ids_zoom = []
+ return
+
+ def _press(self, event):
+ """Callback for mouse button presses in zoom-to-rectangle mode."""
+
+ # If we're already in the middle of a zoom, pressing another
+ # button works to "cancel"
+ if self._ids_zoom:
+ self._cancel_action()
+
+ if event.button == 1:
+ self._button_pressed = 1
+ elif event.button == 3:
+ self._button_pressed = 3
+ else:
+ self._cancel_action()
+ return
+
+ x, y = event.x, event.y
+
+ self._xypress = []
+ for i, a in enumerate(self.figure.get_axes()):
+ if (x is not None and y is not None and a.in_axes(event) and
+ a.get_navigate() and a.can_zoom()):
+ self._xypress.append((x, y, a, i, a._get_view()))
+
+ id1 = self.figure.canvas.mpl_connect(
+ 'motion_notify_event', self._mouse_move)
+ id2 = self.figure.canvas.mpl_connect(
+ 'key_press_event', self._switch_on_zoom_mode)
+ id3 = self.figure.canvas.mpl_connect(
+ 'key_release_event', self._switch_off_zoom_mode)
+
+ self._ids_zoom = id1, id2, id3
+ self._zoom_mode = event.key
+
+ def _switch_on_zoom_mode(self, event):
+ self._zoom_mode = event.key
+ self._mouse_move(event)
+
+ def _switch_off_zoom_mode(self, event):
+ self._zoom_mode = None
+ self._mouse_move(event)
+
+ def _mouse_move(self, event):
+ """Callback for mouse moves in zoom-to-rectangle mode."""
+
+ if self._xypress:
+ x, y = event.x, event.y
+ lastx, lasty, a, ind, view = self._xypress[0]
+ (x1, y1), (x2, y2) = np.clip(
+ [[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
+ if self._zoom_mode == "x":
+ y1, y2 = a.bbox.intervaly
+ elif self._zoom_mode == "y":
+ x1, x2 = a.bbox.intervalx
+ self.toolmanager.trigger_tool(
+ 'rubberband', self, data=(x1, y1, x2, y2))
+
+ def _release(self, event):
+ """Callback for mouse button releases in zoom-to-rectangle mode."""
+
+ for zoom_id in self._ids_zoom:
+ self.figure.canvas.mpl_disconnect(zoom_id)
+ self._ids_zoom = []
+
+ if not self._xypress:
+ self._cancel_action()
+ return
+
+ done_ax = []
+
+ for cur_xypress in self._xypress:
+ x, y = event.x, event.y
+ lastx, lasty, a, _ind, view = cur_xypress
+ # ignore singular clicks - 5 pixels is a threshold
+ if abs(x - lastx) < 5 or abs(y - lasty) < 5:
+ self._cancel_action()
+ return
+
+ # detect twinx, twiny Axes and avoid double zooming
+ twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)
+ twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)
+ done_ax.append(a)
+
+ if self._button_pressed == 1:
+ direction = 'in'
+ elif self._button_pressed == 3:
+ direction = 'out'
+ else:
+ continue
+
+ a._set_view_from_bbox((lastx, lasty, x, y), direction,
+ self._zoom_mode, twinx, twiny)
+
+ self._zoom_mode = None
+ self.toolmanager.get_tool(_views_positions).push_current()
+ self._cancel_action()
+
+
+class ToolPan(ZoomPanBase):
+ """Pan Axes with left mouse, zoom with right."""
+
+ default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
+ description = 'Pan axes with left mouse, zoom with right'
+ image = 'mpl-data/images/move'
+ cursor = cursors.MOVE
+ radio_group = 'default'
+
+ def __init__(self, *args):
+ super().__init__(*args)
+ self._id_drag = None
+
+ def _cancel_action(self):
+ self._button_pressed = None
+ self._xypress = []
+ self.figure.canvas.mpl_disconnect(self._id_drag)
+ self.toolmanager.messagelock.release(self)
+ self.figure.canvas.draw_idle()
+
+ def _press(self, event):
+ if event.button == 1:
+ self._button_pressed = 1
+ elif event.button == 3:
+ self._button_pressed = 3
+ else:
+ self._cancel_action()
+ return
+
+ x, y = event.x, event.y
+
+ self._xypress = []
+ for i, a in enumerate(self.figure.get_axes()):
+ if (x is not None and y is not None and a.in_axes(event) and
+ a.get_navigate() and a.can_pan()):
+ a.start_pan(x, y, event.button)
+ self._xypress.append((a, i))
+ self.toolmanager.messagelock(self)
+ self._id_drag = self.figure.canvas.mpl_connect(
+ 'motion_notify_event', self._mouse_move)
+
+ def _release(self, event):
+ if self._button_pressed is None:
+ self._cancel_action()
+ return
+
+ self.figure.canvas.mpl_disconnect(self._id_drag)
+ self.toolmanager.messagelock.release(self)
+
+ for a, _ind in self._xypress:
+ a.end_pan()
+ if not self._xypress:
+ self._cancel_action()
+ return
+
+ self.toolmanager.get_tool(_views_positions).push_current()
+ self._cancel_action()
+
+ def _mouse_move(self, event):
+ for a, _ind in self._xypress:
+ # safer to use the recorded button at the _press than current
+ # button: # multiple button can get pressed during motion...
+ a.drag_pan(self._button_pressed, event.key, event.x, event.y)
+ self.toolmanager.canvas.draw_idle()
+
+
+class ToolHelpBase(ToolBase):
+ description = 'Print tool list, shortcuts and description'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.help'])
+ image = 'mpl-data/images/help'
+
+ @staticmethod
+ def format_shortcut(key_sequence):
+ """
+ Convert a shortcut string from the notation used in rc config to the
+ standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
+ """
+ return (key_sequence if len(key_sequence) == 1 else
+ re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
+
+ def _format_tool_keymap(self, name):
+ keymaps = self.toolmanager.get_tool_keymap(name)
+ return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
+
+ def _get_help_entries(self):
+ return [(name, self._format_tool_keymap(name), tool.description)
+ for name, tool in sorted(self.toolmanager.tools.items())
+ if tool.description]
+
+ def _get_help_text(self):
+ entries = self._get_help_entries()
+ entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
+ return "\n".join(entries)
+
+ def _get_help_html(self):
+ fmt = "{} {} {} "
+ rows = [fmt.format(
+ "Action ", "Shortcuts ", "Description ")]
+ rows += [fmt.format(*row) for row in self._get_help_entries()]
+ return (""
+ "" + rows[0] + " "
+ "".join(rows[1:]) + "
")
+
+
+class ToolCopyToClipboardBase(ToolBase):
+ """Tool to copy the figure to the clipboard."""
+
+ description = 'Copy the canvas figure to clipboard'
+ default_keymap = property(lambda self: mpl.rcParams['keymap.copy'])
+
+ def trigger(self, *args, **kwargs):
+ message = "Copy tool is not available"
+ self.toolmanager.message_event(message, self)
+
+
+default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
+ 'zoom': ToolZoom, 'pan': ToolPan,
+ 'subplots': ConfigureSubplotsBase,
+ 'save': SaveFigureBase,
+ 'grid': ToolGrid,
+ 'grid_minor': ToolMinorGrid,
+ 'fullscreen': ToolFullScreen,
+ 'quit': ToolQuit,
+ 'quit_all': ToolQuitAll,
+ 'xscale': ToolXScale,
+ 'yscale': ToolYScale,
+ 'position': ToolCursorPosition,
+ _views_positions: ToolViewsPositions,
+ 'cursor': ToolSetCursor,
+ 'rubberband': RubberbandBase,
+ 'help': ToolHelpBase,
+ 'copy': ToolCopyToClipboardBase,
+ }
+
+default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
+ ['zoompan', ['pan', 'zoom', 'subplots']],
+ ['io', ['save', 'help']]]
+
+
+def add_tools_to_manager(toolmanager, tools=default_tools):
+ """
+ Add multiple tools to a `.ToolManager`.
+
+ Parameters
+ ----------
+ toolmanager : `.backend_managers.ToolManager`
+ Manager to which the tools are added.
+ tools : {str: class_like}, optional
+ The tools to add in a {name: tool} dict, see
+ `.backend_managers.ToolManager.add_tool` for more info.
+ """
+
+ for name, tool in tools.items():
+ toolmanager.add_tool(name, tool)
+
+
+def add_tools_to_container(container, tools=default_toolbar_tools):
+ """
+ Add multiple tools to the container.
+
+ Parameters
+ ----------
+ container : Container
+ `.backend_bases.ToolContainerBase` object that will get the tools
+ added.
+ tools : list, optional
+ List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
+ where the tools ``[tool1, tool2, ...]`` will display in group1.
+ See `.backend_bases.ToolContainerBase.add_tool` for details.
+ """
+
+ for group, grouptools in tools:
+ for position, tool in enumerate(grouptools):
+ container.add_tool(tool, group, position)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/backend_tools.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/backend_tools.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..f86a207c754554d2918584fdec680e72713f61aa
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/backend_tools.pyi
@@ -0,0 +1,121 @@
+import enum
+from matplotlib import cbook
+from matplotlib.axes import Axes
+from matplotlib.backend_bases import ToolContainerBase, FigureCanvasBase
+from matplotlib.backend_managers import ToolManager, ToolEvent
+from matplotlib.figure import Figure
+from matplotlib.scale import ScaleBase
+
+from typing import Any
+
+class Cursors(enum.IntEnum):
+ POINTER: int
+ HAND: int
+ SELECT_REGION: int
+ MOVE: int
+ WAIT: int
+ RESIZE_HORIZONTAL: int
+ RESIZE_VERTICAL: int
+
+cursors = Cursors
+
+class ToolBase:
+ @property
+ def default_keymap(self) -> list[str] | None: ...
+ description: str | None
+ image: str | None
+ def __init__(self, toolmanager: ToolManager, name: str) -> None: ...
+ @property
+ def name(self) -> str: ...
+ @property
+ def toolmanager(self) -> ToolManager: ...
+ @property
+ def canvas(self) -> FigureCanvasBase | None: ...
+ @property
+ def figure(self) -> Figure | None: ...
+ @figure.setter
+ def figure(self, figure: Figure | None) -> None: ...
+ def set_figure(self, figure: Figure | None) -> None: ...
+ def trigger(self, sender: Any, event: ToolEvent, data: Any = ...) -> None: ...
+
+class ToolToggleBase(ToolBase):
+ radio_group: str | None
+ cursor: Cursors | None
+ default_toggled: bool
+ def __init__(self, *args, **kwargs) -> None: ...
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
+ @property
+ def toggled(self) -> bool: ...
+ def set_figure(self, figure: Figure | None) -> None: ...
+
+class ToolSetCursor(ToolBase): ...
+
+class ToolCursorPosition(ToolBase):
+ def send_message(self, event: ToolEvent) -> None: ...
+
+class RubberbandBase(ToolBase):
+ def draw_rubberband(self, *data) -> None: ...
+ def remove_rubberband(self) -> None: ...
+
+class ToolQuit(ToolBase): ...
+class ToolQuitAll(ToolBase): ...
+class ToolGrid(ToolBase): ...
+class ToolMinorGrid(ToolBase): ...
+class ToolFullScreen(ToolBase): ...
+
+class AxisScaleBase(ToolToggleBase):
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
+
+class ToolYScale(AxisScaleBase):
+ def set_scale(self, ax: Axes, scale: str | ScaleBase) -> None: ...
+
+class ToolXScale(AxisScaleBase):
+ def set_scale(self, ax, scale: str | ScaleBase) -> None: ...
+
+class ToolViewsPositions(ToolBase):
+ views: dict[Figure | Axes, cbook._Stack]
+ positions: dict[Figure | Axes, cbook._Stack]
+ home_views: dict[Figure, dict[Axes, tuple[float, float, float, float]]]
+ def add_figure(self, figure: Figure) -> None: ...
+ def clear(self, figure: Figure) -> None: ...
+ def update_view(self) -> None: ...
+ def push_current(self, figure: Figure | None = ...) -> None: ...
+ def update_home_views(self, figure: Figure | None = ...) -> None: ...
+ def home(self) -> None: ...
+ def back(self) -> None: ...
+ def forward(self) -> None: ...
+
+class ViewsPositionsBase(ToolBase): ...
+class ToolHome(ViewsPositionsBase): ...
+class ToolBack(ViewsPositionsBase): ...
+class ToolForward(ViewsPositionsBase): ...
+class ConfigureSubplotsBase(ToolBase): ...
+class SaveFigureBase(ToolBase): ...
+
+class ZoomPanBase(ToolToggleBase):
+ base_scale: float
+ scrollthresh: float
+ lastscroll: float
+ def __init__(self, *args) -> None: ...
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
+ def scroll_zoom(self, event: ToolEvent) -> None: ...
+
+class ToolZoom(ZoomPanBase): ...
+class ToolPan(ZoomPanBase): ...
+
+class ToolHelpBase(ToolBase):
+ @staticmethod
+ def format_shortcut(key_sequence: str) -> str: ...
+
+class ToolCopyToClipboardBase(ToolBase): ...
+
+default_tools: dict[str, ToolBase]
+default_toolbar_tools: list[list[str | list[str]]]
+
+def add_tools_to_manager(
+ toolmanager: ToolManager, tools: dict[str, type[ToolBase]] = ...
+) -> None: ...
+def add_tools_to_container(container: ToolContainerBase, tools: list[Any] = ...) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/bezier.py b/llava_video/lib/python3.10/site-packages/matplotlib/bezier.py
new file mode 100644
index 0000000000000000000000000000000000000000..42a6b478d729f3b2837e11e6767b84ac5972654d
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/bezier.py
@@ -0,0 +1,602 @@
+"""
+A module providing some utility functions regarding Bézier path manipulation.
+"""
+
+from functools import lru_cache
+import math
+import warnings
+
+import numpy as np
+
+from matplotlib import _api
+
+
+# same algorithm as 3.8's math.comb
+@np.vectorize
+@lru_cache(maxsize=128)
+def _comb(n, k):
+ if k > n:
+ return 0
+ k = min(k, n - k)
+ i = np.arange(1, k + 1)
+ return np.prod((n + 1 - i)/i).astype(int)
+
+
+class NonIntersectingPathException(ValueError):
+ pass
+
+
+# some functions
+
+
+def get_intersection(cx1, cy1, cos_t1, sin_t1,
+ cx2, cy2, cos_t2, sin_t2):
+ """
+ Return the intersection between the line through (*cx1*, *cy1*) at angle
+ *t1* and the line through (*cx2*, *cy2*) at angle *t2*.
+ """
+
+ # line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0.
+ # line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1
+
+ line1_rhs = sin_t1 * cx1 - cos_t1 * cy1
+ line2_rhs = sin_t2 * cx2 - cos_t2 * cy2
+
+ # rhs matrix
+ a, b = sin_t1, -cos_t1
+ c, d = sin_t2, -cos_t2
+
+ ad_bc = a * d - b * c
+ if abs(ad_bc) < 1e-12:
+ raise ValueError("Given lines do not intersect. Please verify that "
+ "the angles are not equal or differ by 180 degrees.")
+
+ # rhs_inverse
+ a_, b_ = d, -b
+ c_, d_ = -c, a
+ a_, b_, c_, d_ = (k / ad_bc for k in [a_, b_, c_, d_])
+
+ x = a_ * line1_rhs + b_ * line2_rhs
+ y = c_ * line1_rhs + d_ * line2_rhs
+
+ return x, y
+
+
+def get_normal_points(cx, cy, cos_t, sin_t, length):
+ """
+ For a line passing through (*cx*, *cy*) and having an angle *t*, return
+ locations of the two points located along its perpendicular line at the
+ distance of *length*.
+ """
+
+ if length == 0.:
+ return cx, cy, cx, cy
+
+ cos_t1, sin_t1 = sin_t, -cos_t
+ cos_t2, sin_t2 = -sin_t, cos_t
+
+ x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy
+ x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy
+
+ return x1, y1, x2, y2
+
+
+# BEZIER routines
+
+# subdividing bezier curve
+# http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html
+
+
+def _de_casteljau1(beta, t):
+ next_beta = beta[:-1] * (1 - t) + beta[1:] * t
+ return next_beta
+
+
+def split_de_casteljau(beta, t):
+ """
+ Split a Bézier segment defined by its control points *beta* into two
+ separate segments divided at *t* and return their control points.
+ """
+ beta = np.asarray(beta)
+ beta_list = [beta]
+ while True:
+ beta = _de_casteljau1(beta, t)
+ beta_list.append(beta)
+ if len(beta) == 1:
+ break
+ left_beta = [beta[0] for beta in beta_list]
+ right_beta = [beta[-1] for beta in reversed(beta_list)]
+
+ return left_beta, right_beta
+
+
+def find_bezier_t_intersecting_with_closedpath(
+ bezier_point_at_t, inside_closedpath, t0=0., t1=1., tolerance=0.01):
+ """
+ Find the intersection of the Bézier curve with a closed path.
+
+ The intersection point *t* is approximated by two parameters *t0*, *t1*
+ such that *t0* <= *t* <= *t1*.
+
+ Search starts from *t0* and *t1* and uses a simple bisecting algorithm
+ therefore one of the end points must be inside the path while the other
+ doesn't. The search stops when the distance of the points parametrized by
+ *t0* and *t1* gets smaller than the given *tolerance*.
+
+ Parameters
+ ----------
+ bezier_point_at_t : callable
+ A function returning x, y coordinates of the Bézier at parameter *t*.
+ It must have the signature::
+
+ bezier_point_at_t(t: float) -> tuple[float, float]
+
+ inside_closedpath : callable
+ A function returning True if a given point (x, y) is inside the
+ closed path. It must have the signature::
+
+ inside_closedpath(point: tuple[float, float]) -> bool
+
+ t0, t1 : float
+ Start parameters for the search.
+
+ tolerance : float
+ Maximal allowed distance between the final points.
+
+ Returns
+ -------
+ t0, t1 : float
+ The Bézier path parameters.
+ """
+ start = bezier_point_at_t(t0)
+ end = bezier_point_at_t(t1)
+
+ start_inside = inside_closedpath(start)
+ end_inside = inside_closedpath(end)
+
+ if start_inside == end_inside and start != end:
+ raise NonIntersectingPathException(
+ "Both points are on the same side of the closed path")
+
+ while True:
+
+ # return if the distance is smaller than the tolerance
+ if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerance:
+ return t0, t1
+
+ # calculate the middle point
+ middle_t = 0.5 * (t0 + t1)
+ middle = bezier_point_at_t(middle_t)
+ middle_inside = inside_closedpath(middle)
+
+ if start_inside ^ middle_inside:
+ t1 = middle_t
+ if end == middle:
+ # Edge case where infinite loop is possible
+ # Caused by large numbers relative to tolerance
+ return t0, t1
+ end = middle
+ else:
+ t0 = middle_t
+ if start == middle:
+ # Edge case where infinite loop is possible
+ # Caused by large numbers relative to tolerance
+ return t0, t1
+ start = middle
+ start_inside = middle_inside
+
+
+class BezierSegment:
+ """
+ A d-dimensional Bézier segment.
+
+ Parameters
+ ----------
+ control_points : (N, d) array
+ Location of the *N* control points.
+ """
+
+ def __init__(self, control_points):
+ self._cpoints = np.asarray(control_points)
+ self._N, self._d = self._cpoints.shape
+ self._orders = np.arange(self._N)
+ coeff = [math.factorial(self._N - 1)
+ // (math.factorial(i) * math.factorial(self._N - 1 - i))
+ for i in range(self._N)]
+ self._px = (self._cpoints.T * coeff).T
+
+ def __call__(self, t):
+ """
+ Evaluate the Bézier curve at point(s) *t* in [0, 1].
+
+ Parameters
+ ----------
+ t : (k,) array-like
+ Points at which to evaluate the curve.
+
+ Returns
+ -------
+ (k, d) array
+ Value of the curve for each point in *t*.
+ """
+ t = np.asarray(t)
+ return (np.power.outer(1 - t, self._orders[::-1])
+ * np.power.outer(t, self._orders)) @ self._px
+
+ def point_at_t(self, t):
+ """
+ Evaluate the curve at a single point, returning a tuple of *d* floats.
+ """
+ return tuple(self(t))
+
+ @property
+ def control_points(self):
+ """The control points of the curve."""
+ return self._cpoints
+
+ @property
+ def dimension(self):
+ """The dimension of the curve."""
+ return self._d
+
+ @property
+ def degree(self):
+ """Degree of the polynomial. One less the number of control points."""
+ return self._N - 1
+
+ @property
+ def polynomial_coefficients(self):
+ r"""
+ The polynomial coefficients of the Bézier curve.
+
+ .. warning:: Follows opposite convention from `numpy.polyval`.
+
+ Returns
+ -------
+ (n+1, d) array
+ Coefficients after expanding in polynomial basis, where :math:`n`
+ is the degree of the Bézier curve and :math:`d` its dimension.
+ These are the numbers (:math:`C_j`) such that the curve can be
+ written :math:`\sum_{j=0}^n C_j t^j`.
+
+ Notes
+ -----
+ The coefficients are calculated as
+
+ .. math::
+
+ {n \choose j} \sum_{i=0}^j (-1)^{i+j} {j \choose i} P_i
+
+ where :math:`P_i` are the control points of the curve.
+ """
+ n = self.degree
+ # matplotlib uses n <= 4. overflow plausible starting around n = 15.
+ if n > 10:
+ warnings.warn("Polynomial coefficients formula unstable for high "
+ "order Bezier curves!", RuntimeWarning)
+ P = self.control_points
+ j = np.arange(n+1)[:, None]
+ i = np.arange(n+1)[None, :] # _comb is non-zero for i <= j
+ prefactor = (-1)**(i + j) * _comb(j, i) # j on axis 0, i on axis 1
+ return _comb(n, j) * prefactor @ P # j on axis 0, self.dimension on 1
+
+ def axis_aligned_extrema(self):
+ """
+ Return the dimension and location of the curve's interior extrema.
+
+ The extrema are the points along the curve where one of its partial
+ derivatives is zero.
+
+ Returns
+ -------
+ dims : array of int
+ Index :math:`i` of the partial derivative which is zero at each
+ interior extrema.
+ dzeros : array of float
+ Of same size as dims. The :math:`t` such that :math:`d/dx_i B(t) =
+ 0`
+ """
+ n = self.degree
+ if n <= 1:
+ return np.array([]), np.array([])
+ Cj = self.polynomial_coefficients
+ dCj = np.arange(1, n+1)[:, None] * Cj[1:]
+ dims = []
+ roots = []
+ for i, pi in enumerate(dCj.T):
+ r = np.roots(pi[::-1])
+ roots.append(r)
+ dims.append(np.full_like(r, i))
+ roots = np.concatenate(roots)
+ dims = np.concatenate(dims)
+ in_range = np.isreal(roots) & (roots >= 0) & (roots <= 1)
+ return dims[in_range], np.real(roots)[in_range]
+
+
+def split_bezier_intersecting_with_closedpath(
+ bezier, inside_closedpath, tolerance=0.01):
+ """
+ Split a Bézier curve into two at the intersection with a closed path.
+
+ Parameters
+ ----------
+ bezier : (N, 2) array-like
+ Control points of the Bézier segment. See `.BezierSegment`.
+ inside_closedpath : callable
+ A function returning True if a given point (x, y) is inside the
+ closed path. See also `.find_bezier_t_intersecting_with_closedpath`.
+ tolerance : float
+ The tolerance for the intersection. See also
+ `.find_bezier_t_intersecting_with_closedpath`.
+
+ Returns
+ -------
+ left, right
+ Lists of control points for the two Bézier segments.
+ """
+
+ bz = BezierSegment(bezier)
+ bezier_point_at_t = bz.point_at_t
+
+ t0, t1 = find_bezier_t_intersecting_with_closedpath(
+ bezier_point_at_t, inside_closedpath, tolerance=tolerance)
+
+ _left, _right = split_de_casteljau(bezier, (t0 + t1) / 2.)
+ return _left, _right
+
+
+# matplotlib specific
+
+
+def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False):
+ """
+ Divide a path into two segments at the point where ``inside(x, y)`` becomes
+ False.
+ """
+ from .path import Path
+ path_iter = path.iter_segments()
+
+ ctl_points, command = next(path_iter)
+ begin_inside = inside(ctl_points[-2:]) # true if begin point is inside
+
+ ctl_points_old = ctl_points
+
+ iold = 0
+ i = 1
+
+ for ctl_points, command in path_iter:
+ iold = i
+ i += len(ctl_points) // 2
+ if inside(ctl_points[-2:]) != begin_inside:
+ bezier_path = np.concatenate([ctl_points_old[-2:], ctl_points])
+ break
+ ctl_points_old = ctl_points
+ else:
+ raise ValueError("The path does not intersect with the patch")
+
+ bp = bezier_path.reshape((-1, 2))
+ left, right = split_bezier_intersecting_with_closedpath(
+ bp, inside, tolerance)
+ if len(left) == 2:
+ codes_left = [Path.LINETO]
+ codes_right = [Path.MOVETO, Path.LINETO]
+ elif len(left) == 3:
+ codes_left = [Path.CURVE3, Path.CURVE3]
+ codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
+ elif len(left) == 4:
+ codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4]
+ codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
+ else:
+ raise AssertionError("This should never be reached")
+
+ verts_left = left[1:]
+ verts_right = right[:]
+
+ if path.codes is None:
+ path_in = Path(np.concatenate([path.vertices[:i], verts_left]))
+ path_out = Path(np.concatenate([verts_right, path.vertices[i:]]))
+
+ else:
+ path_in = Path(np.concatenate([path.vertices[:iold], verts_left]),
+ np.concatenate([path.codes[:iold], codes_left]))
+
+ path_out = Path(np.concatenate([verts_right, path.vertices[i:]]),
+ np.concatenate([codes_right, path.codes[i:]]))
+
+ if reorder_inout and not begin_inside:
+ path_in, path_out = path_out, path_in
+
+ return path_in, path_out
+
+
+def inside_circle(cx, cy, r):
+ """
+ Return a function that checks whether a point is in a circle with center
+ (*cx*, *cy*) and radius *r*.
+
+ The returned function has the signature::
+
+ f(xy: tuple[float, float]) -> bool
+ """
+ r2 = r ** 2
+
+ def _f(xy):
+ x, y = xy
+ return (x - cx) ** 2 + (y - cy) ** 2 < r2
+ return _f
+
+
+# quadratic Bezier lines
+
+def get_cos_sin(x0, y0, x1, y1):
+ dx, dy = x1 - x0, y1 - y0
+ d = (dx * dx + dy * dy) ** .5
+ # Account for divide by zero
+ if d == 0:
+ return 0.0, 0.0
+ return dx / d, dy / d
+
+
+def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1.e-5):
+ """
+ Check if two lines are parallel.
+
+ Parameters
+ ----------
+ dx1, dy1, dx2, dy2 : float
+ The gradients *dy*/*dx* of the two lines.
+ tolerance : float
+ The angular tolerance in radians up to which the lines are considered
+ parallel.
+
+ Returns
+ -------
+ is_parallel
+ - 1 if two lines are parallel in same direction.
+ - -1 if two lines are parallel in opposite direction.
+ - False otherwise.
+ """
+ theta1 = np.arctan2(dx1, dy1)
+ theta2 = np.arctan2(dx2, dy2)
+ dtheta = abs(theta1 - theta2)
+ if dtheta < tolerance:
+ return 1
+ elif abs(dtheta - np.pi) < tolerance:
+ return -1
+ else:
+ return False
+
+
+def get_parallels(bezier2, width):
+ """
+ Given the quadratic Bézier control points *bezier2*, returns
+ control points of quadratic Bézier lines roughly parallel to given
+ one separated by *width*.
+ """
+
+ # The parallel Bezier lines are constructed by following ways.
+ # c1 and c2 are control points representing the start and end of the
+ # Bezier line.
+ # cm is the middle point
+
+ c1x, c1y = bezier2[0]
+ cmx, cmy = bezier2[1]
+ c2x, c2y = bezier2[2]
+
+ parallel_test = check_if_parallel(c1x - cmx, c1y - cmy,
+ cmx - c2x, cmy - c2y)
+
+ if parallel_test == -1:
+ _api.warn_external(
+ "Lines do not intersect. A straight line is used instead.")
+ cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y)
+ cos_t2, sin_t2 = cos_t1, sin_t1
+ else:
+ # t1 and t2 is the angle between c1 and cm, cm, c2. They are
+ # also an angle of the tangential line of the path at c1 and c2
+ cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
+ cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y)
+
+ # find c1_left, c1_right which are located along the lines
+ # through c1 and perpendicular to the tangential lines of the
+ # Bezier path at a distance of width. Same thing for c2_left and
+ # c2_right with respect to c2.
+ c1x_left, c1y_left, c1x_right, c1y_right = (
+ get_normal_points(c1x, c1y, cos_t1, sin_t1, width)
+ )
+ c2x_left, c2y_left, c2x_right, c2y_right = (
+ get_normal_points(c2x, c2y, cos_t2, sin_t2, width)
+ )
+
+ # find cm_left which is the intersecting point of a line through
+ # c1_left with angle t1 and a line through c2_left with angle
+ # t2. Same with cm_right.
+ try:
+ cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1,
+ sin_t1, c2x_left, c2y_left,
+ cos_t2, sin_t2)
+ cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1,
+ sin_t1, c2x_right, c2y_right,
+ cos_t2, sin_t2)
+ except ValueError:
+ # Special case straight lines, i.e., angle between two lines is
+ # less than the threshold used by get_intersection (we don't use
+ # check_if_parallel as the threshold is not the same).
+ cmx_left, cmy_left = (
+ 0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left)
+ )
+ cmx_right, cmy_right = (
+ 0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right)
+ )
+
+ # the parallel Bezier lines are created with control points of
+ # [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right]
+ path_left = [(c1x_left, c1y_left),
+ (cmx_left, cmy_left),
+ (c2x_left, c2y_left)]
+ path_right = [(c1x_right, c1y_right),
+ (cmx_right, cmy_right),
+ (c2x_right, c2y_right)]
+
+ return path_left, path_right
+
+
+def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y):
+ """
+ Find control points of the Bézier curve passing through (*c1x*, *c1y*),
+ (*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1.
+ """
+ cmx = .5 * (4 * mmx - (c1x + c2x))
+ cmy = .5 * (4 * mmy - (c1y + c2y))
+ return [(c1x, c1y), (cmx, cmy), (c2x, c2y)]
+
+
+def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.):
+ """
+ Being similar to `get_parallels`, returns control points of two quadratic
+ Bézier lines having a width roughly parallel to given one separated by
+ *width*.
+ """
+
+ # c1, cm, c2
+ c1x, c1y = bezier2[0]
+ cmx, cmy = bezier2[1]
+ c3x, c3y = bezier2[2]
+
+ # t1 and t2 is the angle between c1 and cm, cm, c3.
+ # They are also an angle of the tangential line of the path at c1 and c3
+ cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
+ cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y)
+
+ # find c1_left, c1_right which are located along the lines
+ # through c1 and perpendicular to the tangential lines of the
+ # Bezier path at a distance of width. Same thing for c3_left and
+ # c3_right with respect to c3.
+ c1x_left, c1y_left, c1x_right, c1y_right = (
+ get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1)
+ )
+ c3x_left, c3y_left, c3x_right, c3y_right = (
+ get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2)
+ )
+
+ # find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and
+ # c12-c23
+ c12x, c12y = (c1x + cmx) * .5, (c1y + cmy) * .5
+ c23x, c23y = (cmx + c3x) * .5, (cmy + c3y) * .5
+ c123x, c123y = (c12x + c23x) * .5, (c12y + c23y) * .5
+
+ # tangential angle of c123 (angle between c12 and c23)
+ cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y)
+
+ c123x_left, c123y_left, c123x_right, c123y_right = (
+ get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm)
+ )
+
+ path_left = find_control_points(c1x_left, c1y_left,
+ c123x_left, c123y_left,
+ c3x_left, c3y_left)
+ path_right = find_control_points(c1x_right, c1y_right,
+ c123x_right, c123y_right,
+ c3x_right, c3y_right)
+
+ return path_left, path_right
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/bezier.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/bezier.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ad82b873affd3902290347be2fae3a3b754f35da
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/bezier.pyi
@@ -0,0 +1,74 @@
+from collections.abc import Callable
+from typing import Literal
+
+import numpy as np
+from numpy.typing import ArrayLike
+
+from .path import Path
+
+class NonIntersectingPathException(ValueError): ...
+
+def get_intersection(
+ cx1: float,
+ cy1: float,
+ cos_t1: float,
+ sin_t1: float,
+ cx2: float,
+ cy2: float,
+ cos_t2: float,
+ sin_t2: float,
+) -> tuple[float, float]: ...
+def get_normal_points(
+ cx: float, cy: float, cos_t: float, sin_t: float, length: float
+) -> tuple[float, float, float, float]: ...
+def split_de_casteljau(beta: ArrayLike, t: float) -> tuple[np.ndarray, np.ndarray]: ...
+def find_bezier_t_intersecting_with_closedpath(
+ bezier_point_at_t: Callable[[float], tuple[float, float]],
+ inside_closedpath: Callable[[tuple[float, float]], bool],
+ t0: float = ...,
+ t1: float = ...,
+ tolerance: float = ...,
+) -> tuple[float, float]: ...
+
+# TODO make generic over d, the dimension? ndarraydim
+class BezierSegment:
+ def __init__(self, control_points: ArrayLike) -> None: ...
+ def __call__(self, t: ArrayLike) -> np.ndarray: ...
+ def point_at_t(self, t: float) -> tuple[float, ...]: ...
+ @property
+ def control_points(self) -> np.ndarray: ...
+ @property
+ def dimension(self) -> int: ...
+ @property
+ def degree(self) -> int: ...
+ @property
+ def polynomial_coefficients(self) -> np.ndarray: ...
+ def axis_aligned_extrema(self) -> tuple[np.ndarray, np.ndarray]: ...
+
+def split_bezier_intersecting_with_closedpath(
+ bezier: ArrayLike,
+ inside_closedpath: Callable[[tuple[float, float]], bool],
+ tolerance: float = ...,
+) -> tuple[np.ndarray, np.ndarray]: ...
+def split_path_inout(
+ path: Path,
+ inside: Callable[[tuple[float, float]], bool],
+ tolerance: float = ...,
+ reorder_inout: bool = ...,
+) -> tuple[Path, Path]: ...
+def inside_circle(
+ cx: float, cy: float, r: float
+) -> Callable[[tuple[float, float]], bool]: ...
+def get_cos_sin(x0: float, y0: float, x1: float, y1: float) -> tuple[float, float]: ...
+def check_if_parallel(
+ dx1: float, dy1: float, dx2: float, dy2: float, tolerance: float = ...
+) -> Literal[-1, False, 1]: ...
+def get_parallels(
+ bezier2: ArrayLike, width: float
+) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]: ...
+def find_control_points(
+ c1x: float, c1y: float, mmx: float, mmy: float, c2x: float, c2y: float
+) -> list[tuple[float, float]]: ...
+def make_wedged_bezier2(
+ bezier2: ArrayLike, width: float, w1: float = ..., wm: float = ..., w2: float = ...
+) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/category.py b/llava_video/lib/python3.10/site-packages/matplotlib/category.py
new file mode 100644
index 0000000000000000000000000000000000000000..225c837006f726aa97b990c82a3265ec06e55df3
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/category.py
@@ -0,0 +1,235 @@
+"""
+Plotting of string "category" data: ``plot(['d', 'f', 'a'], [1, 2, 3])`` will
+plot three points with x-axis values of 'd', 'f', 'a'.
+
+See :doc:`/gallery/lines_bars_and_markers/categorical_variables` for an
+example.
+
+The module uses Matplotlib's `matplotlib.units` mechanism to convert from
+strings to integers and provides a tick locator, a tick formatter, and the
+`.UnitData` class that creates and stores the string-to-integer mapping.
+"""
+
+from collections import OrderedDict
+import dateutil.parser
+import itertools
+import logging
+
+import numpy as np
+
+from matplotlib import _api, cbook, ticker, units
+
+
+_log = logging.getLogger(__name__)
+
+
+class StrCategoryConverter(units.ConversionInterface):
+ @staticmethod
+ def convert(value, unit, axis):
+ """
+ Convert strings in *value* to floats using mapping information stored
+ in the *unit* object.
+
+ Parameters
+ ----------
+ value : str or iterable
+ Value or list of values to be converted.
+ unit : `.UnitData`
+ An object mapping strings to integers.
+ axis : `~matplotlib.axis.Axis`
+ The axis on which the converted value is plotted.
+
+ .. note:: *axis* is unused.
+
+ Returns
+ -------
+ float or `~numpy.ndarray` of float
+ """
+ if unit is None:
+ raise ValueError(
+ 'Missing category information for StrCategoryConverter; '
+ 'this might be caused by unintendedly mixing categorical and '
+ 'numeric data')
+ StrCategoryConverter._validate_unit(unit)
+ # dtype = object preserves numerical pass throughs
+ values = np.atleast_1d(np.array(value, dtype=object))
+ # force an update so it also does type checking
+ unit.update(values)
+ s = np.vectorize(unit._mapping.__getitem__, otypes=[float])(values)
+ return s if not cbook.is_scalar_or_string(value) else s[0]
+
+ @staticmethod
+ def axisinfo(unit, axis):
+ """
+ Set the default axis ticks and labels.
+
+ Parameters
+ ----------
+ unit : `.UnitData`
+ object string unit information for value
+ axis : `~matplotlib.axis.Axis`
+ axis for which information is being set
+
+ .. note:: *axis* is not used
+
+ Returns
+ -------
+ `~matplotlib.units.AxisInfo`
+ Information to support default tick labeling
+
+ """
+ StrCategoryConverter._validate_unit(unit)
+ # locator and formatter take mapping dict because
+ # args need to be pass by reference for updates
+ majloc = StrCategoryLocator(unit._mapping)
+ majfmt = StrCategoryFormatter(unit._mapping)
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt)
+
+ @staticmethod
+ def default_units(data, axis):
+ """
+ Set and update the `~matplotlib.axis.Axis` units.
+
+ Parameters
+ ----------
+ data : str or iterable of str
+ axis : `~matplotlib.axis.Axis`
+ axis on which the data is plotted
+
+ Returns
+ -------
+ `.UnitData`
+ object storing string to integer mapping
+ """
+ # the conversion call stack is default_units -> axis_info -> convert
+ if axis.units is None:
+ axis.set_units(UnitData(data))
+ else:
+ axis.units.update(data)
+ return axis.units
+
+ @staticmethod
+ def _validate_unit(unit):
+ if not hasattr(unit, '_mapping'):
+ raise ValueError(
+ f'Provided unit "{unit}" is not valid for a categorical '
+ 'converter, as it does not have a _mapping attribute.')
+
+
+class StrCategoryLocator(ticker.Locator):
+ """Tick at every integer mapping of the string data."""
+ def __init__(self, units_mapping):
+ """
+ Parameters
+ ----------
+ units_mapping : dict
+ Mapping of category names (str) to indices (int).
+ """
+ self._units = units_mapping
+
+ def __call__(self):
+ # docstring inherited
+ return list(self._units.values())
+
+ def tick_values(self, vmin, vmax):
+ # docstring inherited
+ return self()
+
+
+class StrCategoryFormatter(ticker.Formatter):
+ """String representation of the data at every tick."""
+ def __init__(self, units_mapping):
+ """
+ Parameters
+ ----------
+ units_mapping : dict
+ Mapping of category names (str) to indices (int).
+ """
+ self._units = units_mapping
+
+ def __call__(self, x, pos=None):
+ # docstring inherited
+ return self.format_ticks([x])[0]
+
+ def format_ticks(self, values):
+ # docstring inherited
+ r_mapping = {v: self._text(k) for k, v in self._units.items()}
+ return [r_mapping.get(round(val), '') for val in values]
+
+ @staticmethod
+ def _text(value):
+ """Convert text values into utf-8 or ascii strings."""
+ if isinstance(value, bytes):
+ value = value.decode(encoding='utf-8')
+ elif not isinstance(value, str):
+ value = str(value)
+ return value
+
+
+class UnitData:
+ def __init__(self, data=None):
+ """
+ Create mapping between unique categorical values and integer ids.
+
+ Parameters
+ ----------
+ data : iterable
+ sequence of string values
+ """
+ self._mapping = OrderedDict()
+ self._counter = itertools.count()
+ if data is not None:
+ self.update(data)
+
+ @staticmethod
+ def _str_is_convertible(val):
+ """
+ Helper method to check whether a string can be parsed as float or date.
+ """
+ try:
+ float(val)
+ except ValueError:
+ try:
+ dateutil.parser.parse(val)
+ except (ValueError, TypeError):
+ # TypeError if dateutil >= 2.8.1 else ValueError
+ return False
+ return True
+
+ def update(self, data):
+ """
+ Map new values to integer identifiers.
+
+ Parameters
+ ----------
+ data : iterable of str or bytes
+
+ Raises
+ ------
+ TypeError
+ If elements in *data* are neither str nor bytes.
+ """
+ data = np.atleast_1d(np.array(data, dtype=object))
+ # check if convertible to number:
+ convertible = True
+ for val in OrderedDict.fromkeys(data):
+ # OrderedDict just iterates over unique values in data.
+ _api.check_isinstance((str, bytes), value=val)
+ if convertible:
+ # this will only be called so long as convertible is True.
+ convertible = self._str_is_convertible(val)
+ if val not in self._mapping:
+ self._mapping[val] = next(self._counter)
+ if data.size and convertible:
+ _log.info('Using categorical units to plot a list of strings '
+ 'that are all parsable as floats or dates. If these '
+ 'strings should be plotted as numbers, cast to the '
+ 'appropriate data type before plotting.')
+
+
+# Register the converter with Matplotlib's unit framework
+# Intentionally set to a single instance
+units.registry[str] = \
+ units.registry[np.str_] = \
+ units.registry[bytes] = \
+ units.registry[np.bytes_] = StrCategoryConverter()
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/cbook.py b/llava_video/lib/python3.10/site-packages/matplotlib/cbook.py
new file mode 100644
index 0000000000000000000000000000000000000000..da7a122b09688721522e6fec4b2963b7be79db1e
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/cbook.py
@@ -0,0 +1,2405 @@
+"""
+A collection of utility functions and classes. Originally, many
+(but not all) were from the Python Cookbook -- hence the name cbook.
+"""
+
+import collections
+import collections.abc
+import contextlib
+import functools
+import gzip
+import itertools
+import math
+import operator
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import sys
+import time
+import traceback
+import types
+import weakref
+
+import numpy as np
+
+try:
+ from numpy.exceptions import VisibleDeprecationWarning # numpy >= 1.25
+except ImportError:
+ from numpy import VisibleDeprecationWarning
+
+import matplotlib
+from matplotlib import _api, _c_internal_utils
+
+
+class _ExceptionInfo:
+ """
+ A class to carry exception information around.
+
+ This is used to store and later raise exceptions. It's an alternative to
+ directly storing Exception instances that circumvents traceback-related
+ issues: caching tracebacks can keep user's objects in local namespaces
+ alive indefinitely, which can lead to very surprising memory issues for
+ users and result in incorrect tracebacks.
+ """
+
+ def __init__(self, cls, *args):
+ self._cls = cls
+ self._args = args
+
+ @classmethod
+ def from_exception(cls, exc):
+ return cls(type(exc), *exc.args)
+
+ def to_exception(self):
+ return self._cls(*self._args)
+
+
+def _get_running_interactive_framework():
+ """
+ Return the interactive framework whose event loop is currently running, if
+ any, or "headless" if no event loop can be started, or None.
+
+ Returns
+ -------
+ Optional[str]
+ One of the following values: "qt", "gtk3", "gtk4", "wx", "tk",
+ "macosx", "headless", ``None``.
+ """
+ # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
+ # entries can also have been explicitly set to None.
+ QtWidgets = (
+ sys.modules.get("PyQt6.QtWidgets")
+ or sys.modules.get("PySide6.QtWidgets")
+ or sys.modules.get("PyQt5.QtWidgets")
+ or sys.modules.get("PySide2.QtWidgets")
+ )
+ if QtWidgets and QtWidgets.QApplication.instance():
+ return "qt"
+ Gtk = sys.modules.get("gi.repository.Gtk")
+ if Gtk:
+ if Gtk.MAJOR_VERSION == 4:
+ from gi.repository import GLib
+ if GLib.main_depth():
+ return "gtk4"
+ if Gtk.MAJOR_VERSION == 3 and Gtk.main_level():
+ return "gtk3"
+ wx = sys.modules.get("wx")
+ if wx and wx.GetApp():
+ return "wx"
+ tkinter = sys.modules.get("tkinter")
+ if tkinter:
+ codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
+ for frame in sys._current_frames().values():
+ while frame:
+ if frame.f_code in codes:
+ return "tk"
+ frame = frame.f_back
+ # Preemptively break reference cycle between locals and the frame.
+ del frame
+ macosx = sys.modules.get("matplotlib.backends._macosx")
+ if macosx and macosx.event_loop_is_running():
+ return "macosx"
+ if not _c_internal_utils.display_is_valid():
+ return "headless"
+ return None
+
+
+def _exception_printer(exc):
+ if _get_running_interactive_framework() in ["headless", None]:
+ raise exc
+ else:
+ traceback.print_exc()
+
+
+class _StrongRef:
+ """
+ Wrapper similar to a weakref, but keeping a strong reference to the object.
+ """
+
+ def __init__(self, obj):
+ self._obj = obj
+
+ def __call__(self):
+ return self._obj
+
+ def __eq__(self, other):
+ return isinstance(other, _StrongRef) and self._obj == other._obj
+
+ def __hash__(self):
+ return hash(self._obj)
+
+
+def _weak_or_strong_ref(func, callback):
+ """
+ Return a `WeakMethod` wrapping *func* if possible, else a `_StrongRef`.
+ """
+ try:
+ return weakref.WeakMethod(func, callback)
+ except TypeError:
+ return _StrongRef(func)
+
+
+class _UnhashDict:
+ """
+ A minimal dict-like class that also supports unhashable keys, storing them
+ in a list of key-value pairs.
+
+ This class only implements the interface needed for `CallbackRegistry`, and
+ tries to minimize the overhead for the hashable case.
+ """
+
+ def __init__(self, pairs):
+ self._dict = {}
+ self._pairs = []
+ for k, v in pairs:
+ self[k] = v
+
+ def __setitem__(self, key, value):
+ try:
+ self._dict[key] = value
+ except TypeError:
+ for i, (k, v) in enumerate(self._pairs):
+ if k == key:
+ self._pairs[i] = (key, value)
+ break
+ else:
+ self._pairs.append((key, value))
+
+ def __getitem__(self, key):
+ try:
+ return self._dict[key]
+ except TypeError:
+ pass
+ for k, v in self._pairs:
+ if k == key:
+ return v
+ raise KeyError(key)
+
+ def pop(self, key, *args):
+ try:
+ if key in self._dict:
+ return self._dict.pop(key)
+ except TypeError:
+ for i, (k, v) in enumerate(self._pairs):
+ if k == key:
+ del self._pairs[i]
+ return v
+ if args:
+ return args[0]
+ raise KeyError(key)
+
+ def __iter__(self):
+ yield from self._dict
+ for k, v in self._pairs:
+ yield k
+
+
+class CallbackRegistry:
+ """
+ Handle registering, processing, blocking, and disconnecting
+ for a set of signals and callbacks:
+
+ >>> def oneat(x):
+ ... print('eat', x)
+ >>> def ondrink(x):
+ ... print('drink', x)
+
+ >>> from matplotlib.cbook import CallbackRegistry
+ >>> callbacks = CallbackRegistry()
+
+ >>> id_eat = callbacks.connect('eat', oneat)
+ >>> id_drink = callbacks.connect('drink', ondrink)
+
+ >>> callbacks.process('drink', 123)
+ drink 123
+ >>> callbacks.process('eat', 456)
+ eat 456
+ >>> callbacks.process('be merry', 456) # nothing will be called
+
+ >>> callbacks.disconnect(id_eat)
+ >>> callbacks.process('eat', 456) # nothing will be called
+
+ >>> with callbacks.blocked(signal='drink'):
+ ... callbacks.process('drink', 123) # nothing will be called
+ >>> callbacks.process('drink', 123)
+ drink 123
+
+ In practice, one should always disconnect all callbacks when they are
+ no longer needed to avoid dangling references (and thus memory leaks).
+ However, real code in Matplotlib rarely does so, and due to its design,
+ it is rather difficult to place this kind of code. To get around this,
+ and prevent this class of memory leaks, we instead store weak references
+ to bound methods only, so when the destination object needs to die, the
+ CallbackRegistry won't keep it alive.
+
+ Parameters
+ ----------
+ exception_handler : callable, optional
+ If not None, *exception_handler* must be a function that takes an
+ `Exception` as single parameter. It gets called with any `Exception`
+ raised by the callbacks during `CallbackRegistry.process`, and may
+ either re-raise the exception or handle it in another manner.
+
+ The default handler prints the exception (with `traceback.print_exc`) if
+ an interactive event loop is running; it re-raises the exception if no
+ interactive event loop is running.
+
+ signals : list, optional
+ If not None, *signals* is a list of signals that this registry handles:
+ attempting to `process` or to `connect` to a signal not in the list
+ throws a `ValueError`. The default, None, does not restrict the
+ handled signals.
+ """
+
+ # We maintain two mappings:
+ # callbacks: signal -> {cid -> weakref-to-callback}
+ # _func_cid_map: {(signal, weakref-to-callback) -> cid}
+
+ def __init__(self, exception_handler=_exception_printer, *, signals=None):
+ self._signals = None if signals is None else list(signals) # Copy it.
+ self.exception_handler = exception_handler
+ self.callbacks = {}
+ self._cid_gen = itertools.count()
+ self._func_cid_map = _UnhashDict([])
+ # A hidden variable that marks cids that need to be pickled.
+ self._pickled_cids = set()
+
+ def __getstate__(self):
+ return {
+ **vars(self),
+ # In general, callbacks may not be pickled, so we just drop them,
+ # unless directed otherwise by self._pickled_cids.
+ "callbacks": {s: {cid: proxy() for cid, proxy in d.items()
+ if cid in self._pickled_cids}
+ for s, d in self.callbacks.items()},
+ # It is simpler to reconstruct this from callbacks in __setstate__.
+ "_func_cid_map": None,
+ "_cid_gen": next(self._cid_gen)
+ }
+
+ def __setstate__(self, state):
+ cid_count = state.pop('_cid_gen')
+ vars(self).update(state)
+ self.callbacks = {
+ s: {cid: _weak_or_strong_ref(func, functools.partial(self._remove_proxy, s))
+ for cid, func in d.items()}
+ for s, d in self.callbacks.items()}
+ self._func_cid_map = _UnhashDict(
+ ((s, proxy), cid)
+ for s, d in self.callbacks.items() for cid, proxy in d.items())
+ self._cid_gen = itertools.count(cid_count)
+
+ def connect(self, signal, func):
+ """Register *func* to be called when signal *signal* is generated."""
+ if self._signals is not None:
+ _api.check_in_list(self._signals, signal=signal)
+ proxy = _weak_or_strong_ref(func, functools.partial(self._remove_proxy, signal))
+ try:
+ return self._func_cid_map[signal, proxy]
+ except KeyError:
+ cid = self._func_cid_map[signal, proxy] = next(self._cid_gen)
+ self.callbacks.setdefault(signal, {})[cid] = proxy
+ return cid
+
+ def _connect_picklable(self, signal, func):
+ """
+ Like `.connect`, but the callback is kept when pickling/unpickling.
+
+ Currently internal-use only.
+ """
+ cid = self.connect(signal, func)
+ self._pickled_cids.add(cid)
+ return cid
+
+ # Keep a reference to sys.is_finalizing, as sys may have been cleared out
+ # at that point.
+ def _remove_proxy(self, signal, proxy, *, _is_finalizing=sys.is_finalizing):
+ if _is_finalizing():
+ # Weakrefs can't be properly torn down at that point anymore.
+ return
+ cid = self._func_cid_map.pop((signal, proxy), None)
+ if cid is not None:
+ del self.callbacks[signal][cid]
+ self._pickled_cids.discard(cid)
+ else: # Not found
+ return
+ if len(self.callbacks[signal]) == 0: # Clean up empty dicts
+ del self.callbacks[signal]
+
+ def disconnect(self, cid):
+ """
+ Disconnect the callback registered with callback id *cid*.
+
+ No error is raised if such a callback does not exist.
+ """
+ self._pickled_cids.discard(cid)
+ for signal, proxy in self._func_cid_map:
+ if self._func_cid_map[signal, proxy] == cid:
+ break
+ else: # Not found
+ return
+ assert self.callbacks[signal][cid] == proxy
+ del self.callbacks[signal][cid]
+ self._func_cid_map.pop((signal, proxy))
+ if len(self.callbacks[signal]) == 0: # Clean up empty dicts
+ del self.callbacks[signal]
+
+ def process(self, s, *args, **kwargs):
+ """
+ Process signal *s*.
+
+ All of the functions registered to receive callbacks on *s* will be
+ called with ``*args`` and ``**kwargs``.
+ """
+ if self._signals is not None:
+ _api.check_in_list(self._signals, signal=s)
+ for ref in list(self.callbacks.get(s, {}).values()):
+ func = ref()
+ if func is not None:
+ try:
+ func(*args, **kwargs)
+ # this does not capture KeyboardInterrupt, SystemExit,
+ # and GeneratorExit
+ except Exception as exc:
+ if self.exception_handler is not None:
+ self.exception_handler(exc)
+ else:
+ raise
+
+ @contextlib.contextmanager
+ def blocked(self, *, signal=None):
+ """
+ Block callback signals from being processed.
+
+ A context manager to temporarily block/disable callback signals
+ from being processed by the registered listeners.
+
+ Parameters
+ ----------
+ signal : str, optional
+ The callback signal to block. The default is to block all signals.
+ """
+ orig = self.callbacks
+ try:
+ if signal is None:
+ # Empty out the callbacks
+ self.callbacks = {}
+ else:
+ # Only remove the specific signal
+ self.callbacks = {k: orig[k] for k in orig if k != signal}
+ yield
+ finally:
+ self.callbacks = orig
+
+
+class silent_list(list):
+ """
+ A list with a short ``repr()``.
+
+ This is meant to be used for a homogeneous list of artists, so that they
+ don't cause long, meaningless output.
+
+ Instead of ::
+
+ [,
+ ,
+ ]
+
+ one will get ::
+
+
+
+ If ``self.type`` is None, the type name is obtained from the first item in
+ the list (if any).
+ """
+
+ def __init__(self, type, seq=None):
+ self.type = type
+ if seq is not None:
+ self.extend(seq)
+
+ def __repr__(self):
+ if self.type is not None or len(self) != 0:
+ tp = self.type if self.type is not None else type(self[0]).__name__
+ return f" "
+ else:
+ return ""
+
+
+def _local_over_kwdict(
+ local_var, kwargs, *keys,
+ warning_cls=_api.MatplotlibDeprecationWarning):
+ out = local_var
+ for key in keys:
+ kwarg_val = kwargs.pop(key, None)
+ if kwarg_val is not None:
+ if out is None:
+ out = kwarg_val
+ else:
+ _api.warn_external(f'"{key}" keyword argument will be ignored',
+ warning_cls)
+ return out
+
+
+def strip_math(s):
+ """
+ Remove latex formatting from mathtext.
+
+ Only handles fully math and fully non-math strings.
+ """
+ if len(s) >= 2 and s[0] == s[-1] == "$":
+ s = s[1:-1]
+ for tex, plain in [
+ (r"\times", "x"), # Specifically for Formatter support.
+ (r"\mathdefault", ""),
+ (r"\rm", ""),
+ (r"\cal", ""),
+ (r"\tt", ""),
+ (r"\it", ""),
+ ("\\", ""),
+ ("{", ""),
+ ("}", ""),
+ ]:
+ s = s.replace(tex, plain)
+ return s
+
+
+def _strip_comment(s):
+ """Strip everything from the first unquoted #."""
+ pos = 0
+ while True:
+ quote_pos = s.find('"', pos)
+ hash_pos = s.find('#', pos)
+ if quote_pos < 0:
+ without_comment = s if hash_pos < 0 else s[:hash_pos]
+ return without_comment.strip()
+ elif 0 <= hash_pos < quote_pos:
+ return s[:hash_pos].strip()
+ else:
+ closing_quote_pos = s.find('"', quote_pos + 1)
+ if closing_quote_pos < 0:
+ raise ValueError(
+ f"Missing closing quote in: {s!r}. If you need a double-"
+ 'quote inside a string, use escaping: e.g. "the \" char"')
+ pos = closing_quote_pos + 1 # behind closing quote
+
+
+def is_writable_file_like(obj):
+ """Return whether *obj* looks like a file object with a *write* method."""
+ return callable(getattr(obj, 'write', None))
+
+
+def file_requires_unicode(x):
+ """
+ Return whether the given writable file-like object requires Unicode to be
+ written to it.
+ """
+ try:
+ x.write(b'')
+ except TypeError:
+ return True
+ else:
+ return False
+
+
+def to_filehandle(fname, flag='r', return_opened=False, encoding=None):
+ """
+ Convert a path to an open file handle or pass-through a file-like object.
+
+ Consider using `open_file_cm` instead, as it allows one to properly close
+ newly created file objects more easily.
+
+ Parameters
+ ----------
+ fname : str or path-like or file-like
+ If `str` or `os.PathLike`, the file is opened using the flags specified
+ by *flag* and *encoding*. If a file-like object, it is passed through.
+ flag : str, default: 'r'
+ Passed as the *mode* argument to `open` when *fname* is `str` or
+ `os.PathLike`; ignored if *fname* is file-like.
+ return_opened : bool, default: False
+ If True, return both the file object and a boolean indicating whether
+ this was a new file (that the caller needs to close). If False, return
+ only the new file.
+ encoding : str or None, default: None
+ Passed as the *mode* argument to `open` when *fname* is `str` or
+ `os.PathLike`; ignored if *fname* is file-like.
+
+ Returns
+ -------
+ fh : file-like
+ opened : bool
+ *opened* is only returned if *return_opened* is True.
+ """
+ if isinstance(fname, os.PathLike):
+ fname = os.fspath(fname)
+ if isinstance(fname, str):
+ if fname.endswith('.gz'):
+ fh = gzip.open(fname, flag)
+ elif fname.endswith('.bz2'):
+ # python may not be compiled with bz2 support,
+ # bury import until we need it
+ import bz2
+ fh = bz2.BZ2File(fname, flag)
+ else:
+ fh = open(fname, flag, encoding=encoding)
+ opened = True
+ elif hasattr(fname, 'seek'):
+ fh = fname
+ opened = False
+ else:
+ raise ValueError('fname must be a PathLike or file handle')
+ if return_opened:
+ return fh, opened
+ return fh
+
+
+def open_file_cm(path_or_file, mode="r", encoding=None):
+ r"""Pass through file objects and context-manage path-likes."""
+ fh, opened = to_filehandle(path_or_file, mode, True, encoding)
+ return fh if opened else contextlib.nullcontext(fh)
+
+
+def is_scalar_or_string(val):
+ """Return whether the given object is a scalar or string like."""
+ return isinstance(val, str) or not np.iterable(val)
+
+
+def get_sample_data(fname, asfileobj=True):
+ """
+ Return a sample data file. *fname* is a path relative to the
+ :file:`mpl-data/sample_data` directory. If *asfileobj* is `True`
+ return a file object, otherwise just a file path.
+
+ Sample data files are stored in the 'mpl-data/sample_data' directory within
+ the Matplotlib package.
+
+ If the filename ends in .gz, the file is implicitly ungzipped. If the
+ filename ends with .npy or .npz, and *asfileobj* is `True`, the file is
+ loaded with `numpy.load`.
+ """
+ path = _get_data_path('sample_data', fname)
+ if asfileobj:
+ suffix = path.suffix.lower()
+ if suffix == '.gz':
+ return gzip.open(path)
+ elif suffix in ['.npy', '.npz']:
+ return np.load(path)
+ elif suffix in ['.csv', '.xrc', '.txt']:
+ return path.open('r')
+ else:
+ return path.open('rb')
+ else:
+ return str(path)
+
+
+def _get_data_path(*args):
+ """
+ Return the `pathlib.Path` to a resource file provided by Matplotlib.
+
+ ``*args`` specify a path relative to the base data path.
+ """
+ return Path(matplotlib.get_data_path(), *args)
+
+
+def flatten(seq, scalarp=is_scalar_or_string):
+ """
+ Return a generator of flattened nested containers.
+
+ For example:
+
+ >>> from matplotlib.cbook import flatten
+ >>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
+ >>> print(list(flatten(l)))
+ ['John', 'Hunter', 1, 23, 42, 5, 23]
+
+ By: Composite of Holger Krekel and Luther Blissett
+ From: https://code.activestate.com/recipes/121294-simple-generator-for-flattening-nested-containers/
+ and Recipe 1.12 in cookbook
+ """ # noqa: E501
+ for item in seq:
+ if scalarp(item) or item is None:
+ yield item
+ else:
+ yield from flatten(item, scalarp)
+
+
+class _Stack:
+ """
+ Stack of elements with a movable cursor.
+
+ Mimics home/back/forward in a web browser.
+ """
+
+ def __init__(self):
+ self._pos = -1
+ self._elements = []
+
+ def clear(self):
+ """Empty the stack."""
+ self._pos = -1
+ self._elements = []
+
+ def __call__(self):
+ """Return the current element, or None."""
+ return self._elements[self._pos] if self._elements else None
+
+ def __len__(self):
+ return len(self._elements)
+
+ def __getitem__(self, ind):
+ return self._elements[ind]
+
+ def forward(self):
+ """Move the position forward and return the current element."""
+ self._pos = min(self._pos + 1, len(self._elements) - 1)
+ return self()
+
+ def back(self):
+ """Move the position back and return the current element."""
+ self._pos = max(self._pos - 1, 0)
+ return self()
+
+ def push(self, o):
+ """
+ Push *o* to the stack after the current position, and return *o*.
+
+ Discard all later elements.
+ """
+ self._elements[self._pos + 1:] = [o]
+ self._pos = len(self._elements) - 1
+ return o
+
+ def home(self):
+ """
+ Push the first element onto the top of the stack.
+
+ The first element is returned.
+ """
+ return self.push(self._elements[0]) if self._elements else None
+
+
+def safe_masked_invalid(x, copy=False):
+ x = np.array(x, subok=True, copy=copy)
+ if not x.dtype.isnative:
+ # If we have already made a copy, do the byteswap in place, else make a
+ # copy with the byte order swapped.
+ # Swap to native order.
+ x = x.byteswap(inplace=copy).view(x.dtype.newbyteorder('N'))
+ try:
+ xm = np.ma.masked_where(~(np.isfinite(x)), x, copy=False)
+ except TypeError:
+ return x
+ return xm
+
+
+def print_cycles(objects, outstream=sys.stdout, show_progress=False):
+ """
+ Print loops of cyclic references in the given *objects*.
+
+ It is often useful to pass in ``gc.garbage`` to find the cycles that are
+ preventing some objects from being garbage collected.
+
+ Parameters
+ ----------
+ objects
+ A list of objects to find cycles in.
+ outstream
+ The stream for output.
+ show_progress : bool
+ If True, print the number of objects reached as they are found.
+ """
+ import gc
+
+ def print_path(path):
+ for i, step in enumerate(path):
+ # next "wraps around"
+ next = path[(i + 1) % len(path)]
+
+ outstream.write(" %s -- " % type(step))
+ if isinstance(step, dict):
+ for key, val in step.items():
+ if val is next:
+ outstream.write(f"[{key!r}]")
+ break
+ if key is next:
+ outstream.write(f"[key] = {val!r}")
+ break
+ elif isinstance(step, list):
+ outstream.write("[%d]" % step.index(next))
+ elif isinstance(step, tuple):
+ outstream.write("( tuple )")
+ else:
+ outstream.write(repr(step))
+ outstream.write(" ->\n")
+ outstream.write("\n")
+
+ def recurse(obj, start, all, current_path):
+ if show_progress:
+ outstream.write("%d\r" % len(all))
+
+ all[id(obj)] = None
+
+ referents = gc.get_referents(obj)
+ for referent in referents:
+ # If we've found our way back to the start, this is
+ # a cycle, so print it out
+ if referent is start:
+ print_path(current_path)
+
+ # Don't go back through the original list of objects, or
+ # through temporary references to the object, since those
+ # are just an artifact of the cycle detector itself.
+ elif referent is objects or isinstance(referent, types.FrameType):
+ continue
+
+ # We haven't seen this object before, so recurse
+ elif id(referent) not in all:
+ recurse(referent, start, all, current_path + [obj])
+
+ for obj in objects:
+ outstream.write(f"Examining: {obj!r}\n")
+ recurse(obj, obj, {}, [])
+
+
+class Grouper:
+ """
+ A disjoint-set data structure.
+
+ Objects can be joined using :meth:`join`, tested for connectedness
+ using :meth:`joined`, and all disjoint sets can be retrieved by
+ using the object as an iterator.
+
+ The objects being joined must be hashable and weak-referenceable.
+
+ Examples
+ --------
+ >>> from matplotlib.cbook import Grouper
+ >>> class Foo:
+ ... def __init__(self, s):
+ ... self.s = s
+ ... def __repr__(self):
+ ... return self.s
+ ...
+ >>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
+ >>> grp = Grouper()
+ >>> grp.join(a, b)
+ >>> grp.join(b, c)
+ >>> grp.join(d, e)
+ >>> list(grp)
+ [[a, b, c], [d, e]]
+ >>> grp.joined(a, b)
+ True
+ >>> grp.joined(a, c)
+ True
+ >>> grp.joined(a, d)
+ False
+ """
+
+ def __init__(self, init=()):
+ self._mapping = weakref.WeakKeyDictionary(
+ {x: weakref.WeakSet([x]) for x in init})
+ self._ordering = weakref.WeakKeyDictionary()
+ for x in init:
+ if x not in self._ordering:
+ self._ordering[x] = len(self._ordering)
+ self._next_order = len(self._ordering) # Plain int to simplify pickling.
+
+ def __getstate__(self):
+ return {
+ **vars(self),
+ # Convert weak refs to strong ones.
+ "_mapping": {k: set(v) for k, v in self._mapping.items()},
+ "_ordering": {**self._ordering},
+ }
+
+ def __setstate__(self, state):
+ vars(self).update(state)
+ # Convert strong refs to weak ones.
+ self._mapping = weakref.WeakKeyDictionary(
+ {k: weakref.WeakSet(v) for k, v in self._mapping.items()})
+ self._ordering = weakref.WeakKeyDictionary(self._ordering)
+
+ def __contains__(self, item):
+ return item in self._mapping
+
+ def join(self, a, *args):
+ """
+ Join given arguments into the same set. Accepts one or more arguments.
+ """
+ mapping = self._mapping
+ try:
+ set_a = mapping[a]
+ except KeyError:
+ set_a = mapping[a] = weakref.WeakSet([a])
+ self._ordering[a] = self._next_order
+ self._next_order += 1
+ for arg in args:
+ try:
+ set_b = mapping[arg]
+ except KeyError:
+ set_b = mapping[arg] = weakref.WeakSet([arg])
+ self._ordering[arg] = self._next_order
+ self._next_order += 1
+ if set_b is not set_a:
+ if len(set_b) > len(set_a):
+ set_a, set_b = set_b, set_a
+ set_a.update(set_b)
+ for elem in set_b:
+ mapping[elem] = set_a
+
+ def joined(self, a, b):
+ """Return whether *a* and *b* are members of the same set."""
+ return (self._mapping.get(a, object()) is self._mapping.get(b))
+
+ def remove(self, a):
+ """Remove *a* from the grouper, doing nothing if it is not there."""
+ self._mapping.pop(a, {a}).remove(a)
+ self._ordering.pop(a, None)
+
+ def __iter__(self):
+ """
+ Iterate over each of the disjoint sets as a list.
+
+ The iterator is invalid if interleaved with calls to join().
+ """
+ unique_groups = {id(group): group for group in self._mapping.values()}
+ for group in unique_groups.values():
+ yield sorted(group, key=self._ordering.__getitem__)
+
+ def get_siblings(self, a):
+ """Return all of the items joined with *a*, including itself."""
+ siblings = self._mapping.get(a, [a])
+ return sorted(siblings, key=self._ordering.get)
+
+
+class GrouperView:
+ """Immutable view over a `.Grouper`."""
+
+ def __init__(self, grouper): self._grouper = grouper
+ def __contains__(self, item): return item in self._grouper
+ def __iter__(self): return iter(self._grouper)
+ def joined(self, a, b): return self._grouper.joined(a, b)
+ def get_siblings(self, a): return self._grouper.get_siblings(a)
+
+
+def simple_linear_interpolation(a, steps):
+ """
+ Resample an array with ``steps - 1`` points between original point pairs.
+
+ Along each column of *a*, ``(steps - 1)`` points are introduced between
+ each original values; the values are linearly interpolated.
+
+ Parameters
+ ----------
+ a : array, shape (n, ...)
+ steps : int
+
+ Returns
+ -------
+ array
+ shape ``((n - 1) * steps + 1, ...)``
+ """
+ fps = a.reshape((len(a), -1))
+ xp = np.arange(len(a)) * steps
+ x = np.arange((len(a) - 1) * steps + 1)
+ return (np.column_stack([np.interp(x, xp, fp) for fp in fps.T])
+ .reshape((len(x),) + a.shape[1:]))
+
+
+def delete_masked_points(*args):
+ """
+ Find all masked and/or non-finite points in a set of arguments,
+ and return the arguments with only the unmasked points remaining.
+
+ Arguments can be in any of 5 categories:
+
+ 1) 1-D masked arrays
+ 2) 1-D ndarrays
+ 3) ndarrays with more than one dimension
+ 4) other non-string iterables
+ 5) anything else
+
+ The first argument must be in one of the first four categories;
+ any argument with a length differing from that of the first
+ argument (and hence anything in category 5) then will be
+ passed through unchanged.
+
+ Masks are obtained from all arguments of the correct length
+ in categories 1, 2, and 4; a point is bad if masked in a masked
+ array or if it is a nan or inf. No attempt is made to
+ extract a mask from categories 2, 3, and 4 if `numpy.isfinite`
+ does not yield a Boolean array.
+
+ All input arguments that are not passed unchanged are returned
+ as ndarrays after removing the points or rows corresponding to
+ masks in any of the arguments.
+
+ A vastly simpler version of this function was originally
+ written as a helper for Axes.scatter().
+
+ """
+ if not len(args):
+ return ()
+ if is_scalar_or_string(args[0]):
+ raise ValueError("First argument must be a sequence")
+ nrecs = len(args[0])
+ margs = []
+ seqlist = [False] * len(args)
+ for i, x in enumerate(args):
+ if not isinstance(x, str) and np.iterable(x) and len(x) == nrecs:
+ seqlist[i] = True
+ if isinstance(x, np.ma.MaskedArray):
+ if x.ndim > 1:
+ raise ValueError("Masked arrays must be 1-D")
+ else:
+ x = np.asarray(x)
+ margs.append(x)
+ masks = [] # List of masks that are True where good.
+ for i, x in enumerate(margs):
+ if seqlist[i]:
+ if x.ndim > 1:
+ continue # Don't try to get nan locations unless 1-D.
+ if isinstance(x, np.ma.MaskedArray):
+ masks.append(~np.ma.getmaskarray(x)) # invert the mask
+ xd = x.data
+ else:
+ xd = x
+ try:
+ mask = np.isfinite(xd)
+ if isinstance(mask, np.ndarray):
+ masks.append(mask)
+ except Exception: # Fixme: put in tuple of possible exceptions?
+ pass
+ if len(masks):
+ mask = np.logical_and.reduce(masks)
+ igood = mask.nonzero()[0]
+ if len(igood) < nrecs:
+ for i, x in enumerate(margs):
+ if seqlist[i]:
+ margs[i] = x[igood]
+ for i, x in enumerate(margs):
+ if seqlist[i] and isinstance(x, np.ma.MaskedArray):
+ margs[i] = x.filled()
+ return margs
+
+
+def _combine_masks(*args):
+ """
+ Find all masked and/or non-finite points in a set of arguments,
+ and return the arguments as masked arrays with a common mask.
+
+ Arguments can be in any of 5 categories:
+
+ 1) 1-D masked arrays
+ 2) 1-D ndarrays
+ 3) ndarrays with more than one dimension
+ 4) other non-string iterables
+ 5) anything else
+
+ The first argument must be in one of the first four categories;
+ any argument with a length differing from that of the first
+ argument (and hence anything in category 5) then will be
+ passed through unchanged.
+
+ Masks are obtained from all arguments of the correct length
+ in categories 1, 2, and 4; a point is bad if masked in a masked
+ array or if it is a nan or inf. No attempt is made to
+ extract a mask from categories 2 and 4 if `numpy.isfinite`
+ does not yield a Boolean array. Category 3 is included to
+ support RGB or RGBA ndarrays, which are assumed to have only
+ valid values and which are passed through unchanged.
+
+ All input arguments that are not passed unchanged are returned
+ as masked arrays if any masked points are found, otherwise as
+ ndarrays.
+
+ """
+ if not len(args):
+ return ()
+ if is_scalar_or_string(args[0]):
+ raise ValueError("First argument must be a sequence")
+ nrecs = len(args[0])
+ margs = [] # Output args; some may be modified.
+ seqlist = [False] * len(args) # Flags: True if output will be masked.
+ masks = [] # List of masks.
+ for i, x in enumerate(args):
+ if is_scalar_or_string(x) or len(x) != nrecs:
+ margs.append(x) # Leave it unmodified.
+ else:
+ if isinstance(x, np.ma.MaskedArray) and x.ndim > 1:
+ raise ValueError("Masked arrays must be 1-D")
+ try:
+ x = np.asanyarray(x)
+ except (VisibleDeprecationWarning, ValueError):
+ # NumPy 1.19 raises a warning about ragged arrays, but we want
+ # to accept basically anything here.
+ x = np.asanyarray(x, dtype=object)
+ if x.ndim == 1:
+ x = safe_masked_invalid(x)
+ seqlist[i] = True
+ if np.ma.is_masked(x):
+ masks.append(np.ma.getmaskarray(x))
+ margs.append(x) # Possibly modified.
+ if len(masks):
+ mask = np.logical_or.reduce(masks)
+ for i, x in enumerate(margs):
+ if seqlist[i]:
+ margs[i] = np.ma.array(x, mask=mask)
+ return margs
+
+
+def _broadcast_with_masks(*args, compress=False):
+ """
+ Broadcast inputs, combining all masked arrays.
+
+ Parameters
+ ----------
+ *args : array-like
+ The inputs to broadcast.
+ compress : bool, default: False
+ Whether to compress the masked arrays. If False, the masked values
+ are replaced by NaNs.
+
+ Returns
+ -------
+ list of array-like
+ The broadcasted and masked inputs.
+ """
+ # extract the masks, if any
+ masks = [k.mask for k in args if isinstance(k, np.ma.MaskedArray)]
+ # broadcast to match the shape
+ bcast = np.broadcast_arrays(*args, *masks)
+ inputs = bcast[:len(args)]
+ masks = bcast[len(args):]
+ if masks:
+ # combine the masks into one
+ mask = np.logical_or.reduce(masks)
+ # put mask on and compress
+ if compress:
+ inputs = [np.ma.array(k, mask=mask).compressed()
+ for k in inputs]
+ else:
+ inputs = [np.ma.array(k, mask=mask, dtype=float).filled(np.nan).ravel()
+ for k in inputs]
+ else:
+ inputs = [np.ravel(k) for k in inputs]
+ return inputs
+
+
+def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False):
+ r"""
+ Return a list of dictionaries of statistics used to draw a series of box
+ and whisker plots using `~.Axes.bxp`.
+
+ Parameters
+ ----------
+ X : array-like
+ Data that will be represented in the boxplots. Should have 2 or
+ fewer dimensions.
+
+ whis : float or (float, float), default: 1.5
+ The position of the whiskers.
+
+ If a float, the lower whisker is at the lowest datum above
+ ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum below
+ ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and third
+ quartiles. The default value of ``whis = 1.5`` corresponds to Tukey's
+ original definition of boxplots.
+
+ If a pair of floats, they indicate the percentiles at which to draw the
+ whiskers (e.g., (5, 95)). In particular, setting this to (0, 100)
+ results in whiskers covering the whole range of the data.
+
+ In the edge case where ``Q1 == Q3``, *whis* is automatically set to
+ (0, 100) (cover the whole range of the data) if *autorange* is True.
+
+ Beyond the whiskers, data are considered outliers and are plotted as
+ individual points.
+
+ bootstrap : int, optional
+ Number of times the confidence intervals around the median
+ should be bootstrapped (percentile method).
+
+ labels : list of str, optional
+ Labels for each dataset. Length must be compatible with
+ dimensions of *X*.
+
+ autorange : bool, optional (False)
+ When `True` and the data are distributed such that the 25th and 75th
+ percentiles are equal, ``whis`` is set to (0, 100) such that the
+ whisker ends are at the minimum and maximum of the data.
+
+ Returns
+ -------
+ list of dict
+ A list of dictionaries containing the results for each column
+ of data. Keys of each dictionary are the following:
+
+ ======== ===================================
+ Key Value Description
+ ======== ===================================
+ label tick label for the boxplot
+ mean arithmetic mean value
+ med 50th percentile
+ q1 first quartile (25th percentile)
+ q3 third quartile (75th percentile)
+ iqr interquartile range
+ cilo lower notch around the median
+ cihi upper notch around the median
+ whislo end of the lower whisker
+ whishi end of the upper whisker
+ fliers outliers
+ ======== ===================================
+
+ Notes
+ -----
+ Non-bootstrapping approach to confidence interval uses Gaussian-based
+ asymptotic approximation:
+
+ .. math::
+
+ \mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}}
+
+ General approach from:
+ McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
+ Boxplots", The American Statistician, 32:12-16.
+ """
+
+ def _bootstrap_median(data, N=5000):
+ # determine 95% confidence intervals of the median
+ M = len(data)
+ percentiles = [2.5, 97.5]
+
+ bs_index = np.random.randint(M, size=(N, M))
+ bsData = data[bs_index]
+ estimate = np.median(bsData, axis=1, overwrite_input=True)
+
+ CI = np.percentile(estimate, percentiles)
+ return CI
+
+ def _compute_conf_interval(data, med, iqr, bootstrap):
+ if bootstrap is not None:
+ # Do a bootstrap estimate of notch locations.
+ # get conf. intervals around median
+ CI = _bootstrap_median(data, N=bootstrap)
+ notch_min = CI[0]
+ notch_max = CI[1]
+ else:
+
+ N = len(data)
+ notch_min = med - 1.57 * iqr / np.sqrt(N)
+ notch_max = med + 1.57 * iqr / np.sqrt(N)
+
+ return notch_min, notch_max
+
+ # output is a list of dicts
+ bxpstats = []
+
+ # convert X to a list of lists
+ X = _reshape_2D(X, "X")
+
+ ncols = len(X)
+ if labels is None:
+ labels = itertools.repeat(None)
+ elif len(labels) != ncols:
+ raise ValueError("Dimensions of labels and X must be compatible")
+
+ input_whis = whis
+ for ii, (x, label) in enumerate(zip(X, labels)):
+
+ # empty dict
+ stats = {}
+ if label is not None:
+ stats['label'] = label
+
+ # restore whis to the input values in case it got changed in the loop
+ whis = input_whis
+
+ # note tricksiness, append up here and then mutate below
+ bxpstats.append(stats)
+
+ # if empty, bail
+ if len(x) == 0:
+ stats['fliers'] = np.array([])
+ stats['mean'] = np.nan
+ stats['med'] = np.nan
+ stats['q1'] = np.nan
+ stats['q3'] = np.nan
+ stats['iqr'] = np.nan
+ stats['cilo'] = np.nan
+ stats['cihi'] = np.nan
+ stats['whislo'] = np.nan
+ stats['whishi'] = np.nan
+ continue
+
+ # up-convert to an array, just to be safe
+ x = np.ma.asarray(x)
+ x = x.data[~x.mask].ravel()
+
+ # arithmetic mean
+ stats['mean'] = np.mean(x)
+
+ # medians and quartiles
+ q1, med, q3 = np.percentile(x, [25, 50, 75])
+
+ # interquartile range
+ stats['iqr'] = q3 - q1
+ if stats['iqr'] == 0 and autorange:
+ whis = (0, 100)
+
+ # conf. interval around median
+ stats['cilo'], stats['cihi'] = _compute_conf_interval(
+ x, med, stats['iqr'], bootstrap
+ )
+
+ # lowest/highest non-outliers
+ if np.iterable(whis) and not isinstance(whis, str):
+ loval, hival = np.percentile(x, whis)
+ elif np.isreal(whis):
+ loval = q1 - whis * stats['iqr']
+ hival = q3 + whis * stats['iqr']
+ else:
+ raise ValueError('whis must be a float or list of percentiles')
+
+ # get high extreme
+ wiskhi = x[x <= hival]
+ if len(wiskhi) == 0 or np.max(wiskhi) < q3:
+ stats['whishi'] = q3
+ else:
+ stats['whishi'] = np.max(wiskhi)
+
+ # get low extreme
+ wisklo = x[x >= loval]
+ if len(wisklo) == 0 or np.min(wisklo) > q1:
+ stats['whislo'] = q1
+ else:
+ stats['whislo'] = np.min(wisklo)
+
+ # compute a single array of outliers
+ stats['fliers'] = np.concatenate([
+ x[x < stats['whislo']],
+ x[x > stats['whishi']],
+ ])
+
+ # add in the remaining stats
+ stats['q1'], stats['med'], stats['q3'] = q1, med, q3
+
+ return bxpstats
+
+
+#: Maps short codes for line style to their full name used by backends.
+ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
+#: Maps full names for line styles used by backends to their short codes.
+ls_mapper_r = {v: k for k, v in ls_mapper.items()}
+
+
+def contiguous_regions(mask):
+ """
+ Return a list of (ind0, ind1) such that ``mask[ind0:ind1].all()`` is
+ True and we cover all such regions.
+ """
+ mask = np.asarray(mask, dtype=bool)
+
+ if not mask.size:
+ return []
+
+ # Find the indices of region changes, and correct offset
+ idx, = np.nonzero(mask[:-1] != mask[1:])
+ idx += 1
+
+ # List operations are faster for moderately sized arrays
+ idx = idx.tolist()
+
+ # Add first and/or last index if needed
+ if mask[0]:
+ idx = [0] + idx
+ if mask[-1]:
+ idx.append(len(mask))
+
+ return list(zip(idx[::2], idx[1::2]))
+
+
+def is_math_text(s):
+ """
+ Return whether the string *s* contains math expressions.
+
+ This is done by checking whether *s* contains an even number of
+ non-escaped dollar signs.
+ """
+ s = str(s)
+ dollar_count = s.count(r'$') - s.count(r'\$')
+ even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
+ return even_dollars
+
+
+def _to_unmasked_float_array(x):
+ """
+ Convert a sequence to a float array; if input was a masked array, masked
+ values are converted to nans.
+ """
+ if hasattr(x, 'mask'):
+ return np.ma.asarray(x, float).filled(np.nan)
+ else:
+ return np.asarray(x, float)
+
+
+def _check_1d(x):
+ """Convert scalars to 1D arrays; pass-through arrays as is."""
+ # Unpack in case of e.g. Pandas or xarray object
+ x = _unpack_to_numpy(x)
+ # plot requires `shape` and `ndim`. If passed an
+ # object that doesn't provide them, then force to numpy array.
+ # Note this will strip unit information.
+ if (not hasattr(x, 'shape') or
+ not hasattr(x, 'ndim') or
+ len(x.shape) < 1):
+ return np.atleast_1d(x)
+ else:
+ return x
+
+
+def _reshape_2D(X, name):
+ """
+ Use Fortran ordering to convert ndarrays and lists of iterables to lists of
+ 1D arrays.
+
+ Lists of iterables are converted by applying `numpy.asanyarray` to each of
+ their elements. 1D ndarrays are returned in a singleton list containing
+ them. 2D ndarrays are converted to the list of their *columns*.
+
+ *name* is used to generate the error message for invalid inputs.
+ """
+
+ # Unpack in case of e.g. Pandas or xarray object
+ X = _unpack_to_numpy(X)
+
+ # Iterate over columns for ndarrays.
+ if isinstance(X, np.ndarray):
+ X = X.T
+
+ if len(X) == 0:
+ return [[]]
+ elif X.ndim == 1 and np.ndim(X[0]) == 0:
+ # 1D array of scalars: directly return it.
+ return [X]
+ elif X.ndim in [1, 2]:
+ # 2D array, or 1D array of iterables: flatten them first.
+ return [np.reshape(x, -1) for x in X]
+ else:
+ raise ValueError(f'{name} must have 2 or fewer dimensions')
+
+ # Iterate over list of iterables.
+ if len(X) == 0:
+ return [[]]
+
+ result = []
+ is_1d = True
+ for xi in X:
+ # check if this is iterable, except for strings which we
+ # treat as singletons.
+ if not isinstance(xi, str):
+ try:
+ iter(xi)
+ except TypeError:
+ pass
+ else:
+ is_1d = False
+ xi = np.asanyarray(xi)
+ nd = np.ndim(xi)
+ if nd > 1:
+ raise ValueError(f'{name} must have 2 or fewer dimensions')
+ result.append(xi.reshape(-1))
+
+ if is_1d:
+ # 1D array of scalars: directly return it.
+ return [np.reshape(result, -1)]
+ else:
+ # 2D array, or 1D array of iterables: use flattened version.
+ return result
+
+
+def violin_stats(X, method, points=100, quantiles=None):
+ """
+ Return a list of dictionaries of data which can be used to draw a series
+ of violin plots.
+
+ See the ``Returns`` section below to view the required keys of the
+ dictionary.
+
+ Users can skip this function and pass a user-defined set of dictionaries
+ with the same keys to `~.axes.Axes.violinplot` instead of using Matplotlib
+ to do the calculations. See the *Returns* section below for the keys
+ that must be present in the dictionaries.
+
+ Parameters
+ ----------
+ X : array-like
+ Sample data that will be used to produce the gaussian kernel density
+ estimates. Must have 2 or fewer dimensions.
+
+ method : callable
+ The method used to calculate the kernel density estimate for each
+ column of data. When called via ``method(v, coords)``, it should
+ return a vector of the values of the KDE evaluated at the values
+ specified in coords.
+
+ points : int, default: 100
+ Defines the number of points to evaluate each of the gaussian kernel
+ density estimates at.
+
+ quantiles : array-like, default: None
+ Defines (if not None) a list of floats in interval [0, 1] for each
+ column of data, which represents the quantiles that will be rendered
+ for that column of data. Must have 2 or fewer dimensions. 1D array will
+ be treated as a singleton list containing them.
+
+ Returns
+ -------
+ list of dict
+ A list of dictionaries containing the results for each column of data.
+ The dictionaries contain at least the following:
+
+ - coords: A list of scalars containing the coordinates this particular
+ kernel density estimate was evaluated at.
+ - vals: A list of scalars containing the values of the kernel density
+ estimate at each of the coordinates given in *coords*.
+ - mean: The mean value for this column of data.
+ - median: The median value for this column of data.
+ - min: The minimum value for this column of data.
+ - max: The maximum value for this column of data.
+ - quantiles: The quantile values for this column of data.
+ """
+
+ # List of dictionaries describing each of the violins.
+ vpstats = []
+
+ # Want X to be a list of data sequences
+ X = _reshape_2D(X, "X")
+
+ # Want quantiles to be as the same shape as data sequences
+ if quantiles is not None and len(quantiles) != 0:
+ quantiles = _reshape_2D(quantiles, "quantiles")
+ # Else, mock quantiles if it's none or empty
+ else:
+ quantiles = [[]] * len(X)
+
+ # quantiles should have the same size as dataset
+ if len(X) != len(quantiles):
+ raise ValueError("List of violinplot statistics and quantiles values"
+ " must have the same length")
+
+ # Zip x and quantiles
+ for (x, q) in zip(X, quantiles):
+ # Dictionary of results for this distribution
+ stats = {}
+
+ # Calculate basic stats for the distribution
+ min_val = np.min(x)
+ max_val = np.max(x)
+ quantile_val = np.percentile(x, 100 * q)
+
+ # Evaluate the kernel density estimate
+ coords = np.linspace(min_val, max_val, points)
+ stats['vals'] = method(x, coords)
+ stats['coords'] = coords
+
+ # Store additional statistics for this distribution
+ stats['mean'] = np.mean(x)
+ stats['median'] = np.median(x)
+ stats['min'] = min_val
+ stats['max'] = max_val
+ stats['quantiles'] = np.atleast_1d(quantile_val)
+
+ # Append to output
+ vpstats.append(stats)
+
+ return vpstats
+
+
+def pts_to_prestep(x, *args):
+ """
+ Convert continuous line to pre-steps.
+
+ Given a set of ``N`` points, convert to ``2N - 1`` points, which when
+ connected linearly give a step function which changes values at the
+ beginning of the intervals.
+
+ Parameters
+ ----------
+ x : array
+ The x location of the steps. May be empty.
+
+ y1, ..., yp : array
+ y arrays to be turned into steps; all must be the same length as ``x``.
+
+ Returns
+ -------
+ array
+ The x and y values converted to steps in the same order as the input;
+ can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
+ length ``N``, each of these arrays will be length ``2N + 1``. For
+ ``N=0``, the length will be 0.
+
+ Examples
+ --------
+ >>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
+ """
+ steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
+ # In all `pts_to_*step` functions, only assign once using *x* and *args*,
+ # as converting to an array may be expensive.
+ steps[0, 0::2] = x
+ steps[0, 1::2] = steps[0, 0:-2:2]
+ steps[1:, 0::2] = args
+ steps[1:, 1::2] = steps[1:, 2::2]
+ return steps
+
+
+def pts_to_poststep(x, *args):
+ """
+ Convert continuous line to post-steps.
+
+ Given a set of ``N`` points convert to ``2N + 1`` points, which when
+ connected linearly give a step function which changes values at the end of
+ the intervals.
+
+ Parameters
+ ----------
+ x : array
+ The x location of the steps. May be empty.
+
+ y1, ..., yp : array
+ y arrays to be turned into steps; all must be the same length as ``x``.
+
+ Returns
+ -------
+ array
+ The x and y values converted to steps in the same order as the input;
+ can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
+ length ``N``, each of these arrays will be length ``2N + 1``. For
+ ``N=0``, the length will be 0.
+
+ Examples
+ --------
+ >>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
+ """
+ steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
+ steps[0, 0::2] = x
+ steps[0, 1::2] = steps[0, 2::2]
+ steps[1:, 0::2] = args
+ steps[1:, 1::2] = steps[1:, 0:-2:2]
+ return steps
+
+
+def pts_to_midstep(x, *args):
+ """
+ Convert continuous line to mid-steps.
+
+ Given a set of ``N`` points convert to ``2N`` points which when connected
+ linearly give a step function which changes values at the middle of the
+ intervals.
+
+ Parameters
+ ----------
+ x : array
+ The x location of the steps. May be empty.
+
+ y1, ..., yp : array
+ y arrays to be turned into steps; all must be the same length as
+ ``x``.
+
+ Returns
+ -------
+ array
+ The x and y values converted to steps in the same order as the input;
+ can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
+ length ``N``, each of these arrays will be length ``2N``.
+
+ Examples
+ --------
+ >>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
+ """
+ steps = np.zeros((1 + len(args), 2 * len(x)))
+ x = np.asanyarray(x)
+ steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2
+ steps[0, :1] = x[:1] # Also works for zero-sized input.
+ steps[0, -1:] = x[-1:]
+ steps[1:, 0::2] = args
+ steps[1:, 1::2] = steps[1:, 0::2]
+ return steps
+
+
+STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y),
+ 'steps': pts_to_prestep,
+ 'steps-pre': pts_to_prestep,
+ 'steps-post': pts_to_poststep,
+ 'steps-mid': pts_to_midstep}
+
+
+def index_of(y):
+ """
+ A helper function to create reasonable x values for the given *y*.
+
+ This is used for plotting (x, y) if x values are not explicitly given.
+
+ First try ``y.index`` (assuming *y* is a `pandas.Series`), if that
+ fails, use ``range(len(y))``.
+
+ This will be extended in the future to deal with more types of
+ labeled data.
+
+ Parameters
+ ----------
+ y : float or array-like
+
+ Returns
+ -------
+ x, y : ndarray
+ The x and y values to plot.
+ """
+ try:
+ return y.index.to_numpy(), y.to_numpy()
+ except AttributeError:
+ pass
+ try:
+ y = _check_1d(y)
+ except (VisibleDeprecationWarning, ValueError):
+ # NumPy 1.19 will warn on ragged input, and we can't actually use it.
+ pass
+ else:
+ return np.arange(y.shape[0], dtype=float), y
+ raise ValueError('Input could not be cast to an at-least-1D NumPy array')
+
+
+def safe_first_element(obj):
+ """
+ Return the first element in *obj*.
+
+ This is a type-independent way of obtaining the first element,
+ supporting both index access and the iterator protocol.
+ """
+ if isinstance(obj, collections.abc.Iterator):
+ # needed to accept `array.flat` as input.
+ # np.flatiter reports as an instance of collections.Iterator but can still be
+ # indexed via []. This has the side effect of re-setting the iterator, but
+ # that is acceptable.
+ try:
+ return obj[0]
+ except TypeError:
+ pass
+ raise RuntimeError("matplotlib does not support generators as input")
+ return next(iter(obj))
+
+
+def _safe_first_finite(obj):
+ """
+ Return the first finite element in *obj* if one is available and skip_nonfinite is
+ True. Otherwise, return the first element.
+
+ This is a method for internal use.
+
+ This is a type-independent way of obtaining the first finite element, supporting
+ both index access and the iterator protocol.
+ """
+ def safe_isfinite(val):
+ if val is None:
+ return False
+ try:
+ return math.isfinite(val)
+ except (TypeError, ValueError):
+ # if the outer object is 2d, then val is a 1d array, and
+ # - math.isfinite(numpy.zeros(3)) raises TypeError
+ # - math.isfinite(torch.zeros(3)) raises ValueError
+ pass
+ try:
+ return np.isfinite(val) if np.isscalar(val) else True
+ except TypeError:
+ # This is something that NumPy cannot make heads or tails of,
+ # assume "finite"
+ return True
+
+ if isinstance(obj, np.flatiter):
+ # TODO do the finite filtering on this
+ return obj[0]
+ elif isinstance(obj, collections.abc.Iterator):
+ raise RuntimeError("matplotlib does not support generators as input")
+ else:
+ for val in obj:
+ if safe_isfinite(val):
+ return val
+ return safe_first_element(obj)
+
+
+def sanitize_sequence(data):
+ """
+ Convert dictview objects to list. Other inputs are returned unchanged.
+ """
+ return (list(data) if isinstance(data, collections.abc.MappingView)
+ else data)
+
+
+def normalize_kwargs(kw, alias_mapping=None):
+ """
+ Helper function to normalize kwarg inputs.
+
+ Parameters
+ ----------
+ kw : dict or None
+ A dict of keyword arguments. None is explicitly supported and treated
+ as an empty dict, to support functions with an optional parameter of
+ the form ``props=None``.
+
+ alias_mapping : dict or Artist subclass or Artist instance, optional
+ A mapping between a canonical name to a list of aliases, in order of
+ precedence from lowest to highest.
+
+ If the canonical value is not in the list it is assumed to have the
+ highest priority.
+
+ If an Artist subclass or instance is passed, use its properties alias
+ mapping.
+
+ Raises
+ ------
+ TypeError
+ To match what Python raises if invalid arguments/keyword arguments are
+ passed to a callable.
+ """
+ from matplotlib.artist import Artist
+
+ if kw is None:
+ return {}
+
+ # deal with default value of alias_mapping
+ if alias_mapping is None:
+ alias_mapping = {}
+ elif (isinstance(alias_mapping, type) and issubclass(alias_mapping, Artist)
+ or isinstance(alias_mapping, Artist)):
+ alias_mapping = getattr(alias_mapping, "_alias_map", {})
+
+ to_canonical = {alias: canonical
+ for canonical, alias_list in alias_mapping.items()
+ for alias in alias_list}
+ canonical_to_seen = {}
+ ret = {} # output dictionary
+
+ for k, v in kw.items():
+ canonical = to_canonical.get(k, k)
+ if canonical in canonical_to_seen:
+ raise TypeError(f"Got both {canonical_to_seen[canonical]!r} and "
+ f"{k!r}, which are aliases of one another")
+ canonical_to_seen[canonical] = k
+ ret[canonical] = v
+
+ return ret
+
+
+@contextlib.contextmanager
+def _lock_path(path):
+ """
+ Context manager for locking a path.
+
+ Usage::
+
+ with _lock_path(path):
+ ...
+
+ Another thread or process that attempts to lock the same path will wait
+ until this context manager is exited.
+
+ The lock is implemented by creating a temporary file in the parent
+ directory, so that directory must exist and be writable.
+ """
+ path = Path(path)
+ lock_path = path.with_name(path.name + ".matplotlib-lock")
+ retries = 50
+ sleeptime = 0.1
+ for _ in range(retries):
+ try:
+ with lock_path.open("xb"):
+ break
+ except FileExistsError:
+ time.sleep(sleeptime)
+ else:
+ raise TimeoutError("""\
+Lock error: Matplotlib failed to acquire the following lock file:
+ {}
+This maybe due to another process holding this lock file. If you are sure no
+other Matplotlib process is running, remove this file and try again.""".format(
+ lock_path))
+ try:
+ yield
+ finally:
+ lock_path.unlink()
+
+
+def _topmost_artist(
+ artists,
+ _cached_max=functools.partial(max, key=operator.attrgetter("zorder"))):
+ """
+ Get the topmost artist of a list.
+
+ In case of a tie, return the *last* of the tied artists, as it will be
+ drawn on top of the others. `max` returns the first maximum in case of
+ ties, so we need to iterate over the list in reverse order.
+ """
+ return _cached_max(reversed(artists))
+
+
+def _str_equal(obj, s):
+ """
+ Return whether *obj* is a string equal to string *s*.
+
+ This helper solely exists to handle the case where *obj* is a numpy array,
+ because in such cases, a naive ``obj == s`` would yield an array, which
+ cannot be used in a boolean context.
+ """
+ return isinstance(obj, str) and obj == s
+
+
+def _str_lower_equal(obj, s):
+ """
+ Return whether *obj* is a string equal, when lowercased, to string *s*.
+
+ This helper solely exists to handle the case where *obj* is a numpy array,
+ because in such cases, a naive ``obj == s`` would yield an array, which
+ cannot be used in a boolean context.
+ """
+ return isinstance(obj, str) and obj.lower() == s
+
+
+def _array_perimeter(arr):
+ """
+ Get the elements on the perimeter of *arr*.
+
+ Parameters
+ ----------
+ arr : ndarray, shape (M, N)
+ The input array.
+
+ Returns
+ -------
+ ndarray, shape (2*(M - 1) + 2*(N - 1),)
+ The elements on the perimeter of the array::
+
+ [arr[0, 0], ..., arr[0, -1], ..., arr[-1, -1], ..., arr[-1, 0], ...]
+
+ Examples
+ --------
+ >>> i, j = np.ogrid[:3, :4]
+ >>> a = i*10 + j
+ >>> a
+ array([[ 0, 1, 2, 3],
+ [10, 11, 12, 13],
+ [20, 21, 22, 23]])
+ >>> _array_perimeter(a)
+ array([ 0, 1, 2, 3, 13, 23, 22, 21, 20, 10])
+ """
+ # note we use Python's half-open ranges to avoid repeating
+ # the corners
+ forward = np.s_[0:-1] # [0 ... -1)
+ backward = np.s_[-1:0:-1] # [-1 ... 0)
+ return np.concatenate((
+ arr[0, forward],
+ arr[forward, -1],
+ arr[-1, backward],
+ arr[backward, 0],
+ ))
+
+
+def _unfold(arr, axis, size, step):
+ """
+ Append an extra dimension containing sliding windows along *axis*.
+
+ All windows are of size *size* and begin with every *step* elements.
+
+ Parameters
+ ----------
+ arr : ndarray, shape (N_1, ..., N_k)
+ The input array
+ axis : int
+ Axis along which the windows are extracted
+ size : int
+ Size of the windows
+ step : int
+ Stride between first elements of subsequent windows.
+
+ Returns
+ -------
+ ndarray, shape (N_1, ..., 1 + (N_axis-size)/step, ..., N_k, size)
+
+ Examples
+ --------
+ >>> i, j = np.ogrid[:3, :7]
+ >>> a = i*10 + j
+ >>> a
+ array([[ 0, 1, 2, 3, 4, 5, 6],
+ [10, 11, 12, 13, 14, 15, 16],
+ [20, 21, 22, 23, 24, 25, 26]])
+ >>> _unfold(a, axis=1, size=3, step=2)
+ array([[[ 0, 1, 2],
+ [ 2, 3, 4],
+ [ 4, 5, 6]],
+ [[10, 11, 12],
+ [12, 13, 14],
+ [14, 15, 16]],
+ [[20, 21, 22],
+ [22, 23, 24],
+ [24, 25, 26]]])
+ """
+ new_shape = [*arr.shape, size]
+ new_strides = [*arr.strides, arr.strides[axis]]
+ new_shape[axis] = (new_shape[axis] - size) // step + 1
+ new_strides[axis] = new_strides[axis] * step
+ return np.lib.stride_tricks.as_strided(arr,
+ shape=new_shape,
+ strides=new_strides,
+ writeable=False)
+
+
+def _array_patch_perimeters(x, rstride, cstride):
+ """
+ Extract perimeters of patches from *arr*.
+
+ Extracted patches are of size (*rstride* + 1) x (*cstride* + 1) and
+ share perimeters with their neighbors. The ordering of the vertices matches
+ that returned by ``_array_perimeter``.
+
+ Parameters
+ ----------
+ x : ndarray, shape (N, M)
+ Input array
+ rstride : int
+ Vertical (row) stride between corresponding elements of each patch
+ cstride : int
+ Horizontal (column) stride between corresponding elements of each patch
+
+ Returns
+ -------
+ ndarray, shape (N/rstride * M/cstride, 2 * (rstride + cstride))
+ """
+ assert rstride > 0 and cstride > 0
+ assert (x.shape[0] - 1) % rstride == 0
+ assert (x.shape[1] - 1) % cstride == 0
+ # We build up each perimeter from four half-open intervals. Here is an
+ # illustrated explanation for rstride == cstride == 3
+ #
+ # T T T R
+ # L R
+ # L R
+ # L B B B
+ #
+ # where T means that this element will be in the top array, R for right,
+ # B for bottom and L for left. Each of the arrays below has a shape of:
+ #
+ # (number of perimeters that can be extracted vertically,
+ # number of perimeters that can be extracted horizontally,
+ # cstride for top and bottom and rstride for left and right)
+ #
+ # Note that _unfold doesn't incur any memory copies, so the only costly
+ # operation here is the np.concatenate.
+ top = _unfold(x[:-1:rstride, :-1], 1, cstride, cstride)
+ bottom = _unfold(x[rstride::rstride, 1:], 1, cstride, cstride)[..., ::-1]
+ right = _unfold(x[:-1, cstride::cstride], 0, rstride, rstride)
+ left = _unfold(x[1:, :-1:cstride], 0, rstride, rstride)[..., ::-1]
+ return (np.concatenate((top, right, bottom, left), axis=2)
+ .reshape(-1, 2 * (rstride + cstride)))
+
+
+@contextlib.contextmanager
+def _setattr_cm(obj, **kwargs):
+ """
+ Temporarily set some attributes; restore original state at context exit.
+ """
+ sentinel = object()
+ origs = {}
+ for attr in kwargs:
+ orig = getattr(obj, attr, sentinel)
+ if attr in obj.__dict__ or orig is sentinel:
+ # if we are pulling from the instance dict or the object
+ # does not have this attribute we can trust the above
+ origs[attr] = orig
+ else:
+ # if the attribute is not in the instance dict it must be
+ # from the class level
+ cls_orig = getattr(type(obj), attr)
+ # if we are dealing with a property (but not a general descriptor)
+ # we want to set the original value back.
+ if isinstance(cls_orig, property):
+ origs[attr] = orig
+ # otherwise this is _something_ we are going to shadow at
+ # the instance dict level from higher up in the MRO. We
+ # are going to assume we can delattr(obj, attr) to clean
+ # up after ourselves. It is possible that this code will
+ # fail if used with a non-property custom descriptor which
+ # implements __set__ (and __delete__ does not act like a
+ # stack). However, this is an internal tool and we do not
+ # currently have any custom descriptors.
+ else:
+ origs[attr] = sentinel
+
+ try:
+ for attr, val in kwargs.items():
+ setattr(obj, attr, val)
+ yield
+ finally:
+ for attr, orig in origs.items():
+ if orig is sentinel:
+ delattr(obj, attr)
+ else:
+ setattr(obj, attr, orig)
+
+
+class _OrderedSet(collections.abc.MutableSet):
+ def __init__(self):
+ self._od = collections.OrderedDict()
+
+ def __contains__(self, key):
+ return key in self._od
+
+ def __iter__(self):
+ return iter(self._od)
+
+ def __len__(self):
+ return len(self._od)
+
+ def add(self, key):
+ self._od.pop(key, None)
+ self._od[key] = None
+
+ def discard(self, key):
+ self._od.pop(key, None)
+
+
+# Agg's buffers are unmultiplied RGBA8888, which neither PyQt<=5.1 nor cairo
+# support; however, both do support premultiplied ARGB32.
+
+
+def _premultiplied_argb32_to_unmultiplied_rgba8888(buf):
+ """
+ Convert a premultiplied ARGB32 buffer to an unmultiplied RGBA8888 buffer.
+ """
+ rgba = np.take( # .take() ensures C-contiguity of the result.
+ buf,
+ [2, 1, 0, 3] if sys.byteorder == "little" else [1, 2, 3, 0], axis=2)
+ rgb = rgba[..., :-1]
+ alpha = rgba[..., -1]
+ # Un-premultiply alpha. The formula is the same as in cairo-png.c.
+ mask = alpha != 0
+ for channel in np.rollaxis(rgb, -1):
+ channel[mask] = (
+ (channel[mask].astype(int) * 255 + alpha[mask] // 2)
+ // alpha[mask])
+ return rgba
+
+
+def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888):
+ """
+ Convert an unmultiplied RGBA8888 buffer to a premultiplied ARGB32 buffer.
+ """
+ if sys.byteorder == "little":
+ argb32 = np.take(rgba8888, [2, 1, 0, 3], axis=2)
+ rgb24 = argb32[..., :-1]
+ alpha8 = argb32[..., -1:]
+ else:
+ argb32 = np.take(rgba8888, [3, 0, 1, 2], axis=2)
+ alpha8 = argb32[..., :1]
+ rgb24 = argb32[..., 1:]
+ # Only bother premultiplying when the alpha channel is not fully opaque,
+ # as the cost is not negligible. The unsafe cast is needed to do the
+ # multiplication in-place in an integer buffer.
+ if alpha8.min() != 0xff:
+ np.multiply(rgb24, alpha8 / 0xff, out=rgb24, casting="unsafe")
+ return argb32
+
+
+def _get_nonzero_slices(buf):
+ """
+ Return the bounds of the nonzero region of a 2D array as a pair of slices.
+
+ ``buf[_get_nonzero_slices(buf)]`` is the smallest sub-rectangle in *buf*
+ that encloses all non-zero entries in *buf*. If *buf* is fully zero, then
+ ``(slice(0, 0), slice(0, 0))`` is returned.
+ """
+ x_nz, = buf.any(axis=0).nonzero()
+ y_nz, = buf.any(axis=1).nonzero()
+ if len(x_nz) and len(y_nz):
+ l, r = x_nz[[0, -1]]
+ b, t = y_nz[[0, -1]]
+ return slice(b, t + 1), slice(l, r + 1)
+ else:
+ return slice(0, 0), slice(0, 0)
+
+
+def _pformat_subprocess(command):
+ """Pretty-format a subprocess command for printing/logging purposes."""
+ return (command if isinstance(command, str)
+ else " ".join(shlex.quote(os.fspath(arg)) for arg in command))
+
+
+def _check_and_log_subprocess(command, logger, **kwargs):
+ """
+ Run *command*, returning its stdout output if it succeeds.
+
+ If it fails (exits with nonzero return code), raise an exception whose text
+ includes the failed command and captured stdout and stderr output.
+
+ Regardless of the return code, the command is logged at DEBUG level on
+ *logger*. In case of success, the output is likewise logged.
+ """
+ logger.debug('%s', _pformat_subprocess(command))
+ proc = subprocess.run(command, capture_output=True, **kwargs)
+ if proc.returncode:
+ stdout = proc.stdout
+ if isinstance(stdout, bytes):
+ stdout = stdout.decode()
+ stderr = proc.stderr
+ if isinstance(stderr, bytes):
+ stderr = stderr.decode()
+ raise RuntimeError(
+ f"The command\n"
+ f" {_pformat_subprocess(command)}\n"
+ f"failed and generated the following output:\n"
+ f"{stdout}\n"
+ f"and the following error:\n"
+ f"{stderr}")
+ if proc.stdout:
+ logger.debug("stdout:\n%s", proc.stdout)
+ if proc.stderr:
+ logger.debug("stderr:\n%s", proc.stderr)
+ return proc.stdout
+
+
+def _setup_new_guiapp():
+ """
+ Perform OS-dependent setup when Matplotlib creates a new GUI application.
+ """
+ # Windows: If not explicit app user model id has been set yet (so we're not
+ # already embedded), then set it to "matplotlib", so that taskbar icons are
+ # correct.
+ try:
+ _c_internal_utils.Win32_GetCurrentProcessExplicitAppUserModelID()
+ except OSError:
+ _c_internal_utils.Win32_SetCurrentProcessExplicitAppUserModelID(
+ "matplotlib")
+
+
+def _format_approx(number, precision):
+ """
+ Format the number with at most the number of decimals given as precision.
+ Remove trailing zeros and possibly the decimal point.
+ """
+ return f'{number:.{precision}f}'.rstrip('0').rstrip('.') or '0'
+
+
+def _g_sig_digits(value, delta):
+ """
+ Return the number of significant digits to %g-format *value*, assuming that
+ it is known with an error of *delta*.
+ """
+ if delta == 0:
+ if value == 0:
+ # if both value and delta are 0, np.spacing below returns 5e-324
+ # which results in rather silly results
+ return 3
+ # delta = 0 may occur when trying to format values over a tiny range;
+ # in that case, replace it by the distance to the closest float.
+ delta = abs(np.spacing(value))
+ # If e.g. value = 45.67 and delta = 0.02, then we want to round to 2 digits
+ # after the decimal point (floor(log10(0.02)) = -2); 45.67 contributes 2
+ # digits before the decimal point (floor(log10(45.67)) + 1 = 2): the total
+ # is 4 significant digits. A value of 0 contributes 1 "digit" before the
+ # decimal point.
+ # For inf or nan, the precision doesn't matter.
+ return max(
+ 0,
+ (math.floor(math.log10(abs(value))) + 1 if value else 1)
+ - math.floor(math.log10(delta))) if math.isfinite(value) else 0
+
+
+def _unikey_or_keysym_to_mplkey(unikey, keysym):
+ """
+ Convert a Unicode key or X keysym to a Matplotlib key name.
+
+ The Unicode key is checked first; this avoids having to list most printable
+ keysyms such as ``EuroSign``.
+ """
+ # For non-printable characters, gtk3 passes "\0" whereas tk passes an "".
+ if unikey and unikey.isprintable():
+ return unikey
+ key = keysym.lower()
+ if key.startswith("kp_"): # keypad_x (including kp_enter).
+ key = key[3:]
+ if key.startswith("page_"): # page_{up,down}
+ key = key.replace("page_", "page")
+ if key.endswith(("_l", "_r")): # alt_l, ctrl_l, shift_l.
+ key = key[:-2]
+ if sys.platform == "darwin" and key == "meta":
+ # meta should be reported as command on mac
+ key = "cmd"
+ key = {
+ "return": "enter",
+ "prior": "pageup", # Used by tk.
+ "next": "pagedown", # Used by tk.
+ }.get(key, key)
+ return key
+
+
+@functools.cache
+def _make_class_factory(mixin_class, fmt, attr_name=None):
+ """
+ Return a function that creates picklable classes inheriting from a mixin.
+
+ After ::
+
+ factory = _make_class_factory(FooMixin, fmt, attr_name)
+ FooAxes = factory(Axes)
+
+ ``Foo`` is a class that inherits from ``FooMixin`` and ``Axes`` and **is
+ picklable** (picklability is what differentiates this from a plain call to
+ `type`). Its ``__name__`` is set to ``fmt.format(Axes.__name__)`` and the
+ base class is stored in the ``attr_name`` attribute, if not None.
+
+ Moreover, the return value of ``factory`` is memoized: calls with the same
+ ``Axes`` class always return the same subclass.
+ """
+
+ @functools.cache
+ def class_factory(axes_class):
+ # if we have already wrapped this class, declare victory!
+ if issubclass(axes_class, mixin_class):
+ return axes_class
+
+ # The parameter is named "axes_class" for backcompat but is really just
+ # a base class; no axes semantics are used.
+ base_class = axes_class
+
+ class subcls(mixin_class, base_class):
+ # Better approximation than __module__ = "matplotlib.cbook".
+ __module__ = mixin_class.__module__
+
+ def __reduce__(self):
+ return (_picklable_class_constructor,
+ (mixin_class, fmt, attr_name, base_class),
+ self.__getstate__())
+
+ subcls.__name__ = subcls.__qualname__ = fmt.format(base_class.__name__)
+ if attr_name is not None:
+ setattr(subcls, attr_name, base_class)
+ return subcls
+
+ class_factory.__module__ = mixin_class.__module__
+ return class_factory
+
+
+def _picklable_class_constructor(mixin_class, fmt, attr_name, base_class):
+ """Internal helper for _make_class_factory."""
+ factory = _make_class_factory(mixin_class, fmt, attr_name)
+ cls = factory(base_class)
+ return cls.__new__(cls)
+
+
+def _is_torch_array(x):
+ """Check if 'x' is a PyTorch Tensor."""
+ try:
+ # we're intentionally not attempting to import torch. If somebody
+ # has created a torch array, torch should already be in sys.modules
+ return isinstance(x, sys.modules['torch'].Tensor)
+ except Exception: # TypeError, KeyError, AttributeError, maybe others?
+ # we're attempting to access attributes on imported modules which
+ # may have arbitrary user code, so we deliberately catch all exceptions
+ return False
+
+
+def _is_jax_array(x):
+ """Check if 'x' is a JAX Array."""
+ try:
+ # we're intentionally not attempting to import jax. If somebody
+ # has created a jax array, jax should already be in sys.modules
+ return isinstance(x, sys.modules['jax'].Array)
+ except Exception: # TypeError, KeyError, AttributeError, maybe others?
+ # we're attempting to access attributes on imported modules which
+ # may have arbitrary user code, so we deliberately catch all exceptions
+ return False
+
+
+def _is_tensorflow_array(x):
+ """Check if 'x' is a TensorFlow Tensor or Variable."""
+ try:
+ # we're intentionally not attempting to import TensorFlow. If somebody
+ # has created a TensorFlow array, TensorFlow should already be in sys.modules
+ # we use `is_tensor` to not depend on the class structure of TensorFlow
+ # arrays, as `tf.Variables` are not instances of `tf.Tensor`
+ # (they both convert the same way)
+ return isinstance(x, sys.modules['tensorflow'].is_tensor(x))
+ except Exception: # TypeError, KeyError, AttributeError, maybe others?
+ # we're attempting to access attributes on imported modules which
+ # may have arbitrary user code, so we deliberately catch all exceptions
+ return False
+
+
+def _unpack_to_numpy(x):
+ """Internal helper to extract data from e.g. pandas and xarray objects."""
+ if isinstance(x, np.ndarray):
+ # If numpy, return directly
+ return x
+ if hasattr(x, 'to_numpy'):
+ # Assume that any to_numpy() method actually returns a numpy array
+ return x.to_numpy()
+ if hasattr(x, 'values'):
+ xtmp = x.values
+ # For example a dict has a 'values' attribute, but it is not a property
+ # so in this case we do not want to return a function
+ if isinstance(xtmp, np.ndarray):
+ return xtmp
+ if _is_torch_array(x) or _is_jax_array(x) or _is_tensorflow_array(x):
+ # using np.asarray() instead of explicitly __array__(), as the latter is
+ # only _one_ of many methods, and it's the last resort, see also
+ # https://numpy.org/devdocs/user/basics.interoperability.html#using-arbitrary-objects-in-numpy
+ # therefore, let arrays do better if they can
+ xtmp = np.asarray(x)
+
+ # In case np.asarray method does not return a numpy array in future
+ if isinstance(xtmp, np.ndarray):
+ return xtmp
+ return x
+
+
+def _auto_format_str(fmt, value):
+ """
+ Apply *value* to the format string *fmt*.
+
+ This works both with unnamed %-style formatting and
+ unnamed {}-style formatting. %-style formatting has priority.
+ If *fmt* is %-style formattable that will be used. Otherwise,
+ {}-formatting is applied. Strings without formatting placeholders
+ are passed through as is.
+
+ Examples
+ --------
+ >>> _auto_format_str('%.2f m', 0.2)
+ '0.20 m'
+ >>> _auto_format_str('{} m', 0.2)
+ '0.2 m'
+ >>> _auto_format_str('const', 0.2)
+ 'const'
+ >>> _auto_format_str('%d or {}', 0.2)
+ '0 or {}'
+ """
+ try:
+ return fmt % (value,)
+ except (TypeError, ValueError):
+ return fmt.format(value)
+
+
+def _is_pandas_dataframe(x):
+ """Check if 'x' is a Pandas DataFrame."""
+ try:
+ # we're intentionally not attempting to import Pandas. If somebody
+ # has created a Pandas DataFrame, Pandas should already be in sys.modules
+ return isinstance(x, sys.modules['pandas'].DataFrame)
+ except Exception: # TypeError, KeyError, AttributeError, maybe others?
+ # we're attempting to access attributes on imported modules which
+ # may have arbitrary user code, so we deliberately catch all exceptions
+ return False
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/cm.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/cm.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c3c62095684aaa7b7a59490412889096b3cded61
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/cm.pyi
@@ -0,0 +1,24 @@
+from collections.abc import Iterator, Mapping
+from matplotlib import colors
+from matplotlib.colorizer import _ScalarMappable
+
+
+class ColormapRegistry(Mapping[str, colors.Colormap]):
+ def __init__(self, cmaps: Mapping[str, colors.Colormap]) -> None: ...
+ def __getitem__(self, item: str) -> colors.Colormap: ...
+ def __iter__(self) -> Iterator[str]: ...
+ def __len__(self) -> int: ...
+ def __call__(self) -> list[str]: ...
+ def register(
+ self, cmap: colors.Colormap, *, name: str | None = ..., force: bool = ...
+ ) -> None: ...
+ def unregister(self, name: str) -> None: ...
+ def get_cmap(self, cmap: str | colors.Colormap) -> colors.Colormap: ...
+
+_colormaps: ColormapRegistry = ...
+_multivar_colormaps: ColormapRegistry = ...
+_bivar_colormaps: ColormapRegistry = ...
+
+def get_cmap(name: str | colors.Colormap | None = ..., lut: int | None = ...) -> colors.Colormap: ...
+
+ScalarMappable = _ScalarMappable
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/colorbar.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/colorbar.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..07467ca74f3d5a528f8c1c0859fc25a2eb285664
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/colorbar.pyi
@@ -0,0 +1,139 @@
+import matplotlib.spines as mspines
+from matplotlib import cm, collections, colors, contour, colorizer
+from matplotlib.axes import Axes
+from matplotlib.axis import Axis
+from matplotlib.backend_bases import RendererBase
+from matplotlib.patches import Patch
+from matplotlib.ticker import Locator, Formatter
+from matplotlib.transforms import Bbox
+
+import numpy as np
+from numpy.typing import ArrayLike
+from collections.abc import Sequence
+from typing import Any, Literal, overload
+from .typing import ColorType
+
+class _ColorbarSpine(mspines.Spines):
+ def __init__(self, axes: Axes): ...
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox:...
+ def set_xy(self, xy: ArrayLike) -> None: ...
+ def draw(self, renderer: RendererBase | None) -> None:...
+
+
+class Colorbar:
+ n_rasterize: int
+ mappable: cm.ScalarMappable | colorizer.ColorizingArtist
+ ax: Axes
+ alpha: float | None
+ cmap: colors.Colormap
+ norm: colors.Normalize
+ values: Sequence[float] | None
+ boundaries: Sequence[float] | None
+ extend: Literal["neither", "both", "min", "max"]
+ spacing: Literal["uniform", "proportional"]
+ orientation: Literal["vertical", "horizontal"]
+ drawedges: bool
+ extendfrac: Literal["auto"] | float | Sequence[float] | None
+ extendrect: bool
+ solids: None | collections.QuadMesh
+ solids_patches: list[Patch]
+ lines: list[collections.LineCollection]
+ outline: _ColorbarSpine
+ dividers: collections.LineCollection
+ ticklocation: Literal["left", "right", "top", "bottom"]
+ def __init__(
+ self,
+ ax: Axes,
+ mappable: cm.ScalarMappable | colorizer.ColorizingArtist | None = ...,
+ *,
+ cmap: str | colors.Colormap | None = ...,
+ norm: colors.Normalize | None = ...,
+ alpha: float | None = ...,
+ values: Sequence[float] | None = ...,
+ boundaries: Sequence[float] | None = ...,
+ orientation: Literal["vertical", "horizontal"] | None = ...,
+ ticklocation: Literal["auto", "left", "right", "top", "bottom"] = ...,
+ extend: Literal["neither", "both", "min", "max"] | None = ...,
+ spacing: Literal["uniform", "proportional"] = ...,
+ ticks: Sequence[float] | Locator | None = ...,
+ format: str | Formatter | None = ...,
+ drawedges: bool = ...,
+ extendfrac: Literal["auto"] | float | Sequence[float] | None = ...,
+ extendrect: bool = ...,
+ label: str = ...,
+ location: Literal["left", "right", "top", "bottom"] | None = ...
+ ) -> None: ...
+ @property
+ def long_axis(self) -> Axis: ...
+ @property
+ def locator(self) -> Locator: ...
+ @locator.setter
+ def locator(self, loc: Locator) -> None: ...
+ @property
+ def minorlocator(self) -> Locator: ...
+ @minorlocator.setter
+ def minorlocator(self, loc: Locator) -> None: ...
+ @property
+ def formatter(self) -> Formatter: ...
+ @formatter.setter
+ def formatter(self, fmt: Formatter) -> None: ...
+ @property
+ def minorformatter(self) -> Formatter: ...
+ @minorformatter.setter
+ def minorformatter(self, fmt: Formatter) -> None: ...
+ def update_normal(self, mappable: cm.ScalarMappable | None = ...) -> None: ...
+ @overload
+ def add_lines(self, CS: contour.ContourSet, erase: bool = ...) -> None: ...
+ @overload
+ def add_lines(
+ self,
+ levels: ArrayLike,
+ colors: ColorType | Sequence[ColorType],
+ linewidths: float | ArrayLike,
+ erase: bool = ...,
+ ) -> None: ...
+ def update_ticks(self) -> None: ...
+ def set_ticks(
+ self,
+ ticks: Sequence[float] | Locator,
+ *,
+ labels: Sequence[str] | None = ...,
+ minor: bool = ...,
+ **kwargs
+ ) -> None: ...
+ def get_ticks(self, minor: bool = ...) -> np.ndarray: ...
+ def set_ticklabels(
+ self,
+ ticklabels: Sequence[str],
+ *,
+ minor: bool = ...,
+ **kwargs
+ ) -> None: ...
+ def minorticks_on(self) -> None: ...
+ def minorticks_off(self) -> None: ...
+ def set_label(self, label: str, *, loc: str | None = ..., **kwargs) -> None: ...
+ def set_alpha(self, alpha: float | np.ndarray) -> None: ...
+ def remove(self) -> None: ...
+ def drag_pan(self, button: Any, key: Any, x: float, y: float) -> None: ...
+
+ColorbarBase = Colorbar
+
+def make_axes(
+ parents: Axes | list[Axes] | np.ndarray,
+ location: Literal["left", "right", "top", "bottom"] | None = ...,
+ orientation: Literal["vertical", "horizontal"] | None = ...,
+ fraction: float = ...,
+ shrink: float = ...,
+ aspect: float = ...,
+ **kwargs
+) -> tuple[Axes, dict[str, Any]]: ...
+def make_axes_gridspec(
+ parent: Axes,
+ *,
+ location: Literal["left", "right", "top", "bottom"] | None = ...,
+ orientation: Literal["vertical", "horizontal"] | None = ...,
+ fraction: float = ...,
+ shrink: float = ...,
+ aspect: float = ...,
+ **kwargs
+) -> tuple[Axes, dict[str, Any]]: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/container.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/container.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c66e7ba4b4c32fc5e27fe06761efb6a3c7f86172
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/container.pyi
@@ -0,0 +1,56 @@
+from matplotlib.artist import Artist
+from matplotlib.lines import Line2D
+from matplotlib.collections import LineCollection
+from matplotlib.patches import Rectangle
+
+from collections.abc import Callable
+from typing import Any, Literal
+from numpy.typing import ArrayLike
+
+class Container(tuple):
+ def __new__(cls, *args, **kwargs): ...
+ def __init__(self, kl, label: Any | None = ...) -> None: ...
+ def remove(self) -> None: ...
+ def get_children(self) -> list[Artist]: ...
+ def get_label(self) -> str | None: ...
+ def set_label(self, s: Any) -> None: ...
+ def add_callback(self, func: Callable[[Artist], Any]) -> int: ...
+ def remove_callback(self, oid: int) -> None: ...
+ def pchanged(self) -> None: ...
+
+class BarContainer(Container):
+ patches: list[Rectangle]
+ errorbar: None | ErrorbarContainer
+ datavalues: None | ArrayLike
+ orientation: None | Literal["vertical", "horizontal"]
+ def __init__(
+ self,
+ patches: list[Rectangle],
+ errorbar: ErrorbarContainer | None = ...,
+ *,
+ datavalues: ArrayLike | None = ...,
+ orientation: Literal["vertical", "horizontal"] | None = ...,
+ **kwargs
+ ) -> None: ...
+
+class ErrorbarContainer(Container):
+ lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]]
+ has_xerr: bool
+ has_yerr: bool
+ def __init__(
+ self,
+ lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]],
+ has_xerr: bool = ...,
+ has_yerr: bool = ...,
+ **kwargs
+ ) -> None: ...
+
+class StemContainer(Container):
+ markerline: Line2D
+ stemlines: LineCollection
+ baseline: Line2D
+ def __init__(
+ self,
+ markerline_stemlines_baseline: tuple[Line2D, LineCollection, Line2D],
+ **kwargs
+ ) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/contour.py b/llava_video/lib/python3.10/site-packages/matplotlib/contour.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b685fa0ed6ac2672f618b921c4cc091d1b00faf
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/contour.py
@@ -0,0 +1,1709 @@
+"""
+Classes to support contour plotting and labelling for the Axes class.
+"""
+
+from contextlib import ExitStack
+import functools
+import math
+from numbers import Integral
+
+import numpy as np
+from numpy import ma
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring
+from matplotlib.backend_bases import MouseButton
+from matplotlib.lines import Line2D
+from matplotlib.path import Path
+from matplotlib.text import Text
+import matplotlib.ticker as ticker
+import matplotlib.cm as cm
+import matplotlib.colors as mcolors
+import matplotlib.collections as mcoll
+import matplotlib.font_manager as font_manager
+import matplotlib.cbook as cbook
+import matplotlib.patches as mpatches
+import matplotlib.transforms as mtransforms
+
+
+def _contour_labeler_event_handler(cs, inline, inline_spacing, event):
+ canvas = cs.axes.get_figure(root=True).canvas
+ is_button = event.name == "button_press_event"
+ is_key = event.name == "key_press_event"
+ # Quit (even if not in infinite mode; this is consistent with
+ # MATLAB and sometimes quite useful, but will require the user to
+ # test how many points were actually returned before using data).
+ if (is_button and event.button == MouseButton.MIDDLE
+ or is_key and event.key in ["escape", "enter"]):
+ canvas.stop_event_loop()
+ # Pop last click.
+ elif (is_button and event.button == MouseButton.RIGHT
+ or is_key and event.key in ["backspace", "delete"]):
+ # Unfortunately, if one is doing inline labels, then there is currently
+ # no way to fix the broken contour - once humpty-dumpty is broken, he
+ # can't be put back together. In inline mode, this does nothing.
+ if not inline:
+ cs.pop_label()
+ canvas.draw()
+ # Add new click.
+ elif (is_button and event.button == MouseButton.LEFT
+ # On macOS/gtk, some keys return None.
+ or is_key and event.key is not None):
+ if cs.axes.contains(event)[0]:
+ cs.add_label_near(event.x, event.y, transform=False,
+ inline=inline, inline_spacing=inline_spacing)
+ canvas.draw()
+
+
+class ContourLabeler:
+ """Mixin to provide labelling capability to `.ContourSet`."""
+
+ def clabel(self, levels=None, *,
+ fontsize=None, inline=True, inline_spacing=5, fmt=None,
+ colors=None, use_clabeltext=False, manual=False,
+ rightside_up=True, zorder=None):
+ """
+ Label a contour plot.
+
+ Adds labels to line contours in this `.ContourSet` (which inherits from
+ this mixin class).
+
+ Parameters
+ ----------
+ levels : array-like, optional
+ A list of level values, that should be labeled. The list must be
+ a subset of ``cs.levels``. If not given, all levels are labeled.
+
+ fontsize : str or float, default: :rc:`font.size`
+ Size in points or relative size e.g., 'smaller', 'x-large'.
+ See `.Text.set_size` for accepted string values.
+
+ colors : :mpltype:`color` or colors or None, default: None
+ The label colors:
+
+ - If *None*, the color of each label matches the color of
+ the corresponding contour.
+
+ - If one string color, e.g., *colors* = 'r' or *colors* =
+ 'red', all labels will be plotted in this color.
+
+ - If a tuple of colors (string, float, RGB, etc), different labels
+ will be plotted in different colors in the order specified.
+
+ inline : bool, default: True
+ If ``True`` the underlying contour is removed where the label is
+ placed.
+
+ inline_spacing : float, default: 5
+ Space in pixels to leave on each side of label when placing inline.
+
+ This spacing will be exact for labels at locations where the
+ contour is straight, less so for labels on curved contours.
+
+ fmt : `.Formatter` or str or callable or dict, optional
+ How the levels are formatted:
+
+ - If a `.Formatter`, it is used to format all levels at once, using
+ its `.Formatter.format_ticks` method.
+ - If a str, it is interpreted as a %-style format string.
+ - If a callable, it is called with one level at a time and should
+ return the corresponding label.
+ - If a dict, it should directly map levels to labels.
+
+ The default is to use a standard `.ScalarFormatter`.
+
+ manual : bool or iterable, default: False
+ If ``True``, contour labels will be placed manually using
+ mouse clicks. Click the first button near a contour to
+ add a label, click the second button (or potentially both
+ mouse buttons at once) to finish adding labels. The third
+ button can be used to remove the last label added, but
+ only if labels are not inline. Alternatively, the keyboard
+ can be used to select label locations (enter to end label
+ placement, delete or backspace act like the third mouse button,
+ and any other key will select a label location).
+
+ *manual* can also be an iterable object of (x, y) tuples.
+ Contour labels will be created as if mouse is clicked at each
+ (x, y) position.
+
+ rightside_up : bool, default: True
+ If ``True``, label rotations will always be plus
+ or minus 90 degrees from level.
+
+ use_clabeltext : bool, default: False
+ If ``True``, use `.Text.set_transform_rotates_text` to ensure that
+ label rotation is updated whenever the Axes aspect changes.
+
+ zorder : float or None, default: ``(2 + contour.get_zorder())``
+ zorder of the contour labels.
+
+ Returns
+ -------
+ labels
+ A list of `.Text` instances for the labels.
+ """
+
+ # Based on the input arguments, clabel() adds a list of "label
+ # specific" attributes to the ContourSet object. These attributes are
+ # all of the form label* and names should be fairly self explanatory.
+ #
+ # Once these attributes are set, clabel passes control to the labels()
+ # method (for automatic label placement) or blocking_input_loop and
+ # _contour_labeler_event_handler (for manual label placement).
+
+ if fmt is None:
+ fmt = ticker.ScalarFormatter(useOffset=False)
+ fmt.create_dummy_axis()
+ self.labelFmt = fmt
+ self._use_clabeltext = use_clabeltext
+ self.labelManual = manual
+ self.rightside_up = rightside_up
+ self._clabel_zorder = 2 + self.get_zorder() if zorder is None else zorder
+
+ if levels is None:
+ levels = self.levels
+ indices = list(range(len(self.cvalues)))
+ else:
+ levlabs = list(levels)
+ indices, levels = [], []
+ for i, lev in enumerate(self.levels):
+ if lev in levlabs:
+ indices.append(i)
+ levels.append(lev)
+ if len(levels) < len(levlabs):
+ raise ValueError(f"Specified levels {levlabs} don't match "
+ f"available levels {self.levels}")
+ self.labelLevelList = levels
+ self.labelIndiceList = indices
+
+ self._label_font_props = font_manager.FontProperties(size=fontsize)
+
+ if colors is None:
+ self.labelMappable = self
+ self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
+ else:
+ cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
+ self.labelCValueList = list(range(len(self.labelLevelList)))
+ self.labelMappable = cm.ScalarMappable(cmap=cmap,
+ norm=mcolors.NoNorm())
+
+ self.labelXYs = []
+
+ if np.iterable(manual):
+ for x, y in manual:
+ self.add_label_near(x, y, inline, inline_spacing)
+ elif manual:
+ print('Select label locations manually using first mouse button.')
+ print('End manual selection with second mouse button.')
+ if not inline:
+ print('Remove last label by clicking third mouse button.')
+ mpl._blocking_input.blocking_input_loop(
+ self.axes.get_figure(root=True),
+ ["button_press_event", "key_press_event"],
+ timeout=-1, handler=functools.partial(
+ _contour_labeler_event_handler,
+ self, inline, inline_spacing))
+ else:
+ self.labels(inline, inline_spacing)
+
+ return cbook.silent_list('text.Text', self.labelTexts)
+
+ def print_label(self, linecontour, labelwidth):
+ """Return whether a contour is long enough to hold a label."""
+ return (len(linecontour) > 10 * labelwidth
+ or (len(linecontour)
+ and (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()))
+
+ def too_close(self, x, y, lw):
+ """Return whether a label is already near this location."""
+ thresh = (1.2 * lw) ** 2
+ return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
+ for loc in self.labelXYs)
+
+ def _get_nth_label_width(self, nth):
+ """Return the width of the *nth* label, in pixels."""
+ fig = self.axes.get_figure(root=False)
+ renderer = fig.get_figure(root=True)._get_renderer()
+ return (Text(0, 0,
+ self.get_text(self.labelLevelList[nth], self.labelFmt),
+ figure=fig, fontproperties=self._label_font_props)
+ .get_window_extent(renderer).width)
+
+ def get_text(self, lev, fmt):
+ """Get the text of the label."""
+ if isinstance(lev, str):
+ return lev
+ elif isinstance(fmt, dict):
+ return fmt.get(lev, '%1.3f')
+ elif callable(getattr(fmt, "format_ticks", None)):
+ return fmt.format_ticks([*self.labelLevelList, lev])[-1]
+ elif callable(fmt):
+ return fmt(lev)
+ else:
+ return fmt % lev
+
+ def locate_label(self, linecontour, labelwidth):
+ """
+ Find good place to draw a label (relatively flat part of the contour).
+ """
+ ctr_size = len(linecontour)
+ n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1
+ block_size = ctr_size if n_blocks == 1 else int(labelwidth)
+ # Split contour into blocks of length ``block_size``, filling the last
+ # block by cycling the contour start (per `np.resize` semantics). (Due
+ # to cycling, the index returned is taken modulo ctr_size.)
+ xx = np.resize(linecontour[:, 0], (n_blocks, block_size))
+ yy = np.resize(linecontour[:, 1], (n_blocks, block_size))
+ yfirst = yy[:, :1]
+ ylast = yy[:, -1:]
+ xfirst = xx[:, :1]
+ xlast = xx[:, -1:]
+ s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst)
+ l = np.hypot(xlast - xfirst, ylast - yfirst)
+ # Ignore warning that divide by zero throws, as this is a valid option
+ with np.errstate(divide='ignore', invalid='ignore'):
+ distances = (abs(s) / l).sum(axis=-1)
+ # Labels are drawn in the middle of the block (``hbsize``) where the
+ # contour is the closest (per ``distances``) to a straight line, but
+ # not `too_close()` to a preexisting label.
+ hbsize = block_size // 2
+ adist = np.argsort(distances)
+ # If all candidates are `too_close()`, go back to the straightest part
+ # (``adist[0]``).
+ for idx in np.append(adist, adist[0]):
+ x, y = xx[idx, hbsize], yy[idx, hbsize]
+ if not self.too_close(x, y, labelwidth):
+ break
+ return x, y, (idx * block_size + hbsize) % ctr_size
+
+ def _split_path_and_get_label_rotation(self, path, idx, screen_pos, lw, spacing=5):
+ """
+ Prepare for insertion of a label at index *idx* of *path*.
+
+ Parameters
+ ----------
+ path : Path
+ The path where the label will be inserted, in data space.
+ idx : int
+ The vertex index after which the label will be inserted.
+ screen_pos : (float, float)
+ The position where the label will be inserted, in screen space.
+ lw : float
+ The label width, in screen space.
+ spacing : float
+ Extra spacing around the label, in screen space.
+
+ Returns
+ -------
+ path : Path
+ The path, broken so that the label can be drawn over it.
+ angle : float
+ The rotation of the label.
+
+ Notes
+ -----
+ Both tasks are done together to avoid calculating path lengths multiple times,
+ which is relatively costly.
+
+ The method used here involves computing the path length along the contour in
+ pixel coordinates and then looking (label width / 2) away from central point to
+ determine rotation and then to break contour if desired. The extra spacing is
+ taken into account when breaking the path, but not when computing the angle.
+ """
+ xys = path.vertices
+ codes = path.codes
+
+ # Insert a vertex at idx/pos (converting back to data space), if there isn't yet
+ # a vertex there. With infinite precision one could also always insert the
+ # extra vertex (it will get masked out by the label below anyways), but floating
+ # point inaccuracies (the point can have undergone a data->screen->data
+ # transform loop) can slightly shift the point and e.g. shift the angle computed
+ # below from exactly zero to nonzero.
+ pos = self.get_transform().inverted().transform(screen_pos)
+ if not np.allclose(pos, xys[idx]):
+ xys = np.insert(xys, idx, pos, axis=0)
+ codes = np.insert(codes, idx, Path.LINETO)
+
+ # Find the connected component where the label will be inserted. Note that a
+ # path always starts with a MOVETO, and we consider there's an implicit
+ # MOVETO (closing the last path) at the end.
+ movetos = (codes == Path.MOVETO).nonzero()[0]
+ start = movetos[movetos <= idx][-1]
+ try:
+ stop = movetos[movetos > idx][0]
+ except IndexError:
+ stop = len(codes)
+
+ # Restrict ourselves to the connected component.
+ cc_xys = xys[start:stop]
+ idx -= start
+
+ # If the path is closed, rotate it s.t. it starts at the label.
+ is_closed_path = codes[stop - 1] == Path.CLOSEPOLY
+ if is_closed_path:
+ cc_xys = np.concatenate([cc_xys[idx:-1], cc_xys[:idx+1]])
+ idx = 0
+
+ # Like np.interp, but additionally vectorized over fp.
+ def interp_vec(x, xp, fp): return [np.interp(x, xp, col) for col in fp.T]
+
+ # Use cumulative path lengths ("cpl") as curvilinear coordinate along contour.
+ screen_xys = self.get_transform().transform(cc_xys)
+ path_cpls = np.insert(
+ np.cumsum(np.hypot(*np.diff(screen_xys, axis=0).T)), 0, 0)
+ path_cpls -= path_cpls[idx]
+
+ # Use linear interpolation to get end coordinates of label.
+ target_cpls = np.array([-lw/2, lw/2])
+ if is_closed_path: # For closed paths, target from the other end.
+ target_cpls[0] += (path_cpls[-1] - path_cpls[0])
+ (sx0, sx1), (sy0, sy1) = interp_vec(target_cpls, path_cpls, screen_xys)
+ angle = np.rad2deg(np.arctan2(sy1 - sy0, sx1 - sx0)) # Screen space.
+ if self.rightside_up: # Fix angle so text is never upside-down
+ angle = (angle + 90) % 180 - 90
+
+ target_cpls += [-spacing, +spacing] # Expand range by spacing.
+
+ # Get indices near points of interest; use -1 as out of bounds marker.
+ i0, i1 = np.interp(target_cpls, path_cpls, range(len(path_cpls)),
+ left=-1, right=-1)
+ i0 = math.floor(i0)
+ i1 = math.ceil(i1)
+ (x0, x1), (y0, y1) = interp_vec(target_cpls, path_cpls, cc_xys)
+
+ # Actually break contours (dropping zero-len parts).
+ new_xy_blocks = []
+ new_code_blocks = []
+ if is_closed_path:
+ if i0 != -1 and i1 != -1:
+ # This is probably wrong in the case that the entire contour would
+ # be discarded, but ensures that a valid path is returned and is
+ # consistent with behavior of mpl <3.8
+ points = cc_xys[i1:i0+1]
+ new_xy_blocks.extend([[(x1, y1)], points, [(x0, y0)]])
+ nlines = len(points) + 1
+ new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * nlines])
+ else:
+ if i0 != -1:
+ new_xy_blocks.extend([cc_xys[:i0 + 1], [(x0, y0)]])
+ new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * (i0 + 1)])
+ if i1 != -1:
+ new_xy_blocks.extend([[(x1, y1)], cc_xys[i1:]])
+ new_code_blocks.extend([
+ [Path.MOVETO], [Path.LINETO] * (len(cc_xys) - i1)])
+
+ # Back to the full path.
+ xys = np.concatenate([xys[:start], *new_xy_blocks, xys[stop:]])
+ codes = np.concatenate([codes[:start], *new_code_blocks, codes[stop:]])
+
+ return angle, Path(xys, codes)
+
+ def add_label(self, x, y, rotation, lev, cvalue):
+ """Add a contour label, respecting whether *use_clabeltext* was set."""
+ data_x, data_y = self.axes.transData.inverted().transform((x, y))
+ t = Text(
+ data_x, data_y,
+ text=self.get_text(lev, self.labelFmt),
+ rotation=rotation,
+ horizontalalignment='center', verticalalignment='center',
+ zorder=self._clabel_zorder,
+ color=self.labelMappable.to_rgba(cvalue, alpha=self.get_alpha()),
+ fontproperties=self._label_font_props,
+ clip_box=self.axes.bbox)
+ if self._use_clabeltext:
+ data_rotation, = self.axes.transData.inverted().transform_angles(
+ [rotation], [[x, y]])
+ t.set(rotation=data_rotation, transform_rotates_text=True)
+ self.labelTexts.append(t)
+ self.labelCValues.append(cvalue)
+ self.labelXYs.append((x, y))
+ # Add label to plot here - useful for manual mode label selection
+ self.axes.add_artist(t)
+
+ def add_label_near(self, x, y, inline=True, inline_spacing=5,
+ transform=None):
+ """
+ Add a label near the point ``(x, y)``.
+
+ Parameters
+ ----------
+ x, y : float
+ The approximate location of the label.
+ inline : bool, default: True
+ If *True* remove the segment of the contour beneath the label.
+ inline_spacing : int, default: 5
+ Space in pixels to leave on each side of label when placing
+ inline. This spacing will be exact for labels at locations where
+ the contour is straight, less so for labels on curved contours.
+ transform : `.Transform` or `False`, default: ``self.axes.transData``
+ A transform applied to ``(x, y)`` before labeling. The default
+ causes ``(x, y)`` to be interpreted as data coordinates. `False`
+ is a synonym for `.IdentityTransform`; i.e. ``(x, y)`` should be
+ interpreted as display coordinates.
+ """
+
+ if transform is None:
+ transform = self.axes.transData
+ if transform:
+ x, y = transform.transform((x, y))
+
+ idx_level_min, idx_vtx_min, proj = self._find_nearest_contour(
+ (x, y), self.labelIndiceList)
+ path = self._paths[idx_level_min]
+ level = self.labelIndiceList.index(idx_level_min)
+ label_width = self._get_nth_label_width(level)
+ rotation, path = self._split_path_and_get_label_rotation(
+ path, idx_vtx_min, proj, label_width, inline_spacing)
+ self.add_label(*proj, rotation, self.labelLevelList[idx_level_min],
+ self.labelCValueList[idx_level_min])
+
+ if inline:
+ self._paths[idx_level_min] = path
+
+ def pop_label(self, index=-1):
+ """Defaults to removing last label, but any index can be supplied"""
+ self.labelCValues.pop(index)
+ t = self.labelTexts.pop(index)
+ t.remove()
+
+ def labels(self, inline, inline_spacing):
+ for idx, (icon, lev, cvalue) in enumerate(zip(
+ self.labelIndiceList,
+ self.labelLevelList,
+ self.labelCValueList,
+ )):
+ trans = self.get_transform()
+ label_width = self._get_nth_label_width(idx)
+ additions = []
+ for subpath in self._paths[icon]._iter_connected_components():
+ screen_xys = trans.transform(subpath.vertices)
+ # Check if long enough for a label
+ if self.print_label(screen_xys, label_width):
+ x, y, idx = self.locate_label(screen_xys, label_width)
+ rotation, path = self._split_path_and_get_label_rotation(
+ subpath, idx, (x, y),
+ label_width, inline_spacing)
+ self.add_label(x, y, rotation, lev, cvalue) # Really add label.
+ if inline: # If inline, add new contours
+ additions.append(path)
+ else: # If not adding label, keep old path
+ additions.append(subpath)
+ # After looping over all segments on a contour, replace old path by new one
+ # if inlining.
+ if inline:
+ self._paths[icon] = Path.make_compound_path(*additions)
+
+ def remove(self):
+ super().remove()
+ for text in self.labelTexts:
+ text.remove()
+
+
+def _find_closest_point_on_path(xys, p):
+ """
+ Parameters
+ ----------
+ xys : (N, 2) array-like
+ Coordinates of vertices.
+ p : (float, float)
+ Coordinates of point.
+
+ Returns
+ -------
+ d2min : float
+ Minimum square distance of *p* to *xys*.
+ proj : (float, float)
+ Projection of *p* onto *xys*.
+ imin : (int, int)
+ Consecutive indices of vertices of segment in *xys* where *proj* is.
+ Segments are considered as including their end-points; i.e. if the
+ closest point on the path is a node in *xys* with index *i*, this
+ returns ``(i-1, i)``. For the special case where *xys* is a single
+ point, this returns ``(0, 0)``.
+ """
+ if len(xys) == 1:
+ return (((p - xys[0]) ** 2).sum(), xys[0], (0, 0))
+ dxys = xys[1:] - xys[:-1] # Individual segment vectors.
+ norms = (dxys ** 2).sum(axis=1)
+ norms[norms == 0] = 1 # For zero-length segment, replace 0/0 by 0/1.
+ rel_projs = np.clip( # Project onto each segment in relative 0-1 coords.
+ ((p - xys[:-1]) * dxys).sum(axis=1) / norms,
+ 0, 1)[:, None]
+ projs = xys[:-1] + rel_projs * dxys # Projs. onto each segment, in (x, y).
+ d2s = ((projs - p) ** 2).sum(axis=1) # Squared distances.
+ imin = np.argmin(d2s)
+ return (d2s[imin], projs[imin], (imin, imin+1))
+
+
+_docstring.interpd.register(contour_set_attributes=r"""
+Attributes
+----------
+ax : `~matplotlib.axes.Axes`
+ The Axes object in which the contours are drawn.
+
+collections : `.silent_list` of `.PathCollection`\s
+ The `.Artist`\s representing the contour. This is a list of
+ `.PathCollection`\s for both line and filled contours.
+
+levels : array
+ The values of the contour levels.
+
+layers : array
+ Same as levels for line contours; half-way between
+ levels for filled contours. See ``ContourSet._process_colors``.
+""")
+
+
+@_docstring.interpd
+class ContourSet(ContourLabeler, mcoll.Collection):
+ """
+ Store a set of contour lines or filled regions.
+
+ User-callable method: `~.Axes.clabel`
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+
+ levels : [level0, level1, ..., leveln]
+ A list of floating point numbers indicating the contour levels.
+
+ allsegs : [level0segs, level1segs, ...]
+ List of all the polygon segments for all the *levels*.
+ For contour lines ``len(allsegs) == len(levels)``, and for
+ filled contour regions ``len(allsegs) = len(levels)-1``. The lists
+ should look like ::
+
+ level0segs = [polygon0, polygon1, ...]
+ polygon0 = [[x0, y0], [x1, y1], ...]
+
+ allkinds : ``None`` or [level0kinds, level1kinds, ...]
+ Optional list of all the polygon vertex kinds (code types), as
+ described and used in Path. This is used to allow multiply-
+ connected paths such as holes within filled polygons.
+ If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
+ should look like ::
+
+ level0kinds = [polygon0kinds, ...]
+ polygon0kinds = [vertexcode0, vertexcode1, ...]
+
+ If *allkinds* is not ``None``, usually all polygons for a
+ particular contour level are grouped together so that
+ ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
+
+ **kwargs
+ Keyword arguments are as described in the docstring of
+ `~.Axes.contour`.
+
+ %(contour_set_attributes)s
+ """
+
+ def __init__(self, ax, *args,
+ levels=None, filled=False, linewidths=None, linestyles=None,
+ hatches=(None,), alpha=None, origin=None, extent=None,
+ cmap=None, colors=None, norm=None, vmin=None, vmax=None,
+ colorizer=None, extend='neither', antialiased=None, nchunk=0,
+ locator=None, transform=None, negative_linestyles=None, clip_path=None,
+ **kwargs):
+ """
+ Draw contour lines or filled regions, depending on
+ whether keyword arg *filled* is ``False`` (default) or ``True``.
+
+ Call signature::
+
+ ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` object to draw on.
+
+ levels : [level0, level1, ..., leveln]
+ A list of floating point numbers indicating the contour
+ levels.
+
+ allsegs : [level0segs, level1segs, ...]
+ List of all the polygon segments for all the *levels*.
+ For contour lines ``len(allsegs) == len(levels)``, and for
+ filled contour regions ``len(allsegs) = len(levels)-1``. The lists
+ should look like ::
+
+ level0segs = [polygon0, polygon1, ...]
+ polygon0 = [[x0, y0], [x1, y1], ...]
+
+ allkinds : [level0kinds, level1kinds, ...], optional
+ Optional list of all the polygon vertex kinds (code types), as
+ described and used in Path. This is used to allow multiply-
+ connected paths such as holes within filled polygons.
+ If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
+ should look like ::
+
+ level0kinds = [polygon0kinds, ...]
+ polygon0kinds = [vertexcode0, vertexcode1, ...]
+
+ If *allkinds* is not ``None``, usually all polygons for a
+ particular contour level are grouped together so that
+ ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
+
+ **kwargs
+ Keyword arguments are as described in the docstring of
+ `~.Axes.contour`.
+ """
+ if antialiased is None and filled:
+ # Eliminate artifacts; we are not stroking the boundaries.
+ antialiased = False
+ # The default for line contours will be taken from the
+ # LineCollection default, which uses :rc:`lines.antialiased`.
+ super().__init__(
+ antialiaseds=antialiased,
+ alpha=alpha,
+ clip_path=clip_path,
+ transform=transform,
+ colorizer=colorizer,
+ )
+ self.axes = ax
+ self.levels = levels
+ self.filled = filled
+ self.hatches = hatches
+ self.origin = origin
+ self.extent = extent
+ self.colors = colors
+ self.extend = extend
+
+ self.nchunk = nchunk
+ self.locator = locator
+
+ if colorizer:
+ self._set_colorizer_check_keywords(colorizer, cmap=cmap,
+ norm=norm, vmin=vmin,
+ vmax=vmax, colors=colors)
+ norm = colorizer.norm
+ cmap = colorizer.cmap
+ if (isinstance(norm, mcolors.LogNorm)
+ or isinstance(self.locator, ticker.LogLocator)):
+ self.logscale = True
+ if norm is None:
+ norm = mcolors.LogNorm()
+ else:
+ self.logscale = False
+
+ _api.check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
+ if self.extent is not None and len(self.extent) != 4:
+ raise ValueError(
+ "If given, 'extent' must be None or (x0, x1, y0, y1)")
+ if self.colors is not None and cmap is not None:
+ raise ValueError('Either colors or cmap must be None')
+ if self.origin == 'image':
+ self.origin = mpl.rcParams['image.origin']
+
+ self._orig_linestyles = linestyles # Only kept for user access.
+ self.negative_linestyles = negative_linestyles
+ # If negative_linestyles was not defined as a keyword argument, define
+ # negative_linestyles with rcParams
+ if self.negative_linestyles is None:
+ self.negative_linestyles = \
+ mpl.rcParams['contour.negative_linestyle']
+
+ kwargs = self._process_args(*args, **kwargs)
+ self._process_levels()
+
+ self._extend_min = self.extend in ['min', 'both']
+ self._extend_max = self.extend in ['max', 'both']
+ if self.colors is not None:
+ if mcolors.is_color_like(self.colors):
+ color_sequence = [self.colors]
+ else:
+ color_sequence = self.colors
+
+ ncolors = len(self.levels)
+ if self.filled:
+ ncolors -= 1
+ i0 = 0
+
+ # Handle the case where colors are given for the extended
+ # parts of the contour.
+
+ use_set_under_over = False
+ # if we are extending the lower end, and we've been given enough
+ # colors then skip the first color in the resulting cmap. For the
+ # extend_max case we don't need to worry about passing more colors
+ # than ncolors as ListedColormap will clip.
+ total_levels = (ncolors +
+ int(self._extend_min) +
+ int(self._extend_max))
+ if (len(color_sequence) == total_levels and
+ (self._extend_min or self._extend_max)):
+ use_set_under_over = True
+ if self._extend_min:
+ i0 = 1
+
+ cmap = mcolors.ListedColormap(color_sequence[i0:None], N=ncolors)
+
+ if use_set_under_over:
+ if self._extend_min:
+ cmap.set_under(color_sequence[0])
+ if self._extend_max:
+ cmap.set_over(color_sequence[-1])
+
+ # label lists must be initialized here
+ self.labelTexts = []
+ self.labelCValues = []
+
+ self.set_cmap(cmap)
+ if norm is not None:
+ self.set_norm(norm)
+ with self.norm.callbacks.blocked(signal="changed"):
+ if vmin is not None:
+ self.norm.vmin = vmin
+ if vmax is not None:
+ self.norm.vmax = vmax
+ self.norm._changed()
+ self._process_colors()
+
+ if self._paths is None:
+ self._paths = self._make_paths_from_contour_generator()
+
+ if self.filled:
+ if linewidths is not None:
+ _api.warn_external('linewidths is ignored by contourf')
+ # Lower and upper contour levels.
+ lowers, uppers = self._get_lowers_and_uppers()
+ self.set(
+ edgecolor="none",
+ # Default zorder taken from Collection
+ zorder=kwargs.pop("zorder", 1),
+ )
+
+ else:
+ self.set(
+ facecolor="none",
+ linewidths=self._process_linewidths(linewidths),
+ linestyle=self._process_linestyles(linestyles),
+ # Default zorder taken from LineCollection, which is higher
+ # than for filled contours so that lines are displayed on top.
+ zorder=kwargs.pop("zorder", 2),
+ label="_nolegend_",
+ )
+
+ self.axes.add_collection(self, autolim=False)
+ self.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
+ self.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
+ self.axes.update_datalim([self._mins, self._maxs])
+ self.axes.autoscale_view(tight=True)
+
+ self.changed() # set the colors
+
+ if kwargs:
+ _api.warn_external(
+ 'The following kwargs were not used by contour: ' +
+ ", ".join(map(repr, kwargs))
+ )
+
+ allsegs = property(lambda self: [
+ [subp.vertices for subp in p._iter_connected_components()]
+ for p in self.get_paths()])
+ allkinds = property(lambda self: [
+ [subp.codes for subp in p._iter_connected_components()]
+ for p in self.get_paths()])
+ alpha = property(lambda self: self.get_alpha())
+ linestyles = property(lambda self: self._orig_linestyles)
+
+ def get_transform(self):
+ """Return the `.Transform` instance used by this ContourSet."""
+ if self._transform is None:
+ self._transform = self.axes.transData
+ elif (not isinstance(self._transform, mtransforms.Transform)
+ and hasattr(self._transform, '_as_mpl_transform')):
+ self._transform = self._transform._as_mpl_transform(self.axes)
+ return self._transform
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ # the C object _contour_generator cannot currently be pickled. This
+ # isn't a big issue as it is not actually used once the contour has
+ # been calculated.
+ state['_contour_generator'] = None
+ return state
+
+ def legend_elements(self, variable_name='x', str_format=str):
+ """
+ Return a list of artists and labels suitable for passing through
+ to `~.Axes.legend` which represent this ContourSet.
+
+ The labels have the form "0 < x <= 1" stating the data ranges which
+ the artists represent.
+
+ Parameters
+ ----------
+ variable_name : str
+ The string used inside the inequality used on the labels.
+ str_format : function: float -> str
+ Function used to format the numbers in the labels.
+
+ Returns
+ -------
+ artists : list[`.Artist`]
+ A list of the artists.
+ labels : list[str]
+ A list of the labels.
+ """
+ artists = []
+ labels = []
+
+ if self.filled:
+ lowers, uppers = self._get_lowers_and_uppers()
+ n_levels = len(self._paths)
+ for idx in range(n_levels):
+ artists.append(mpatches.Rectangle(
+ (0, 0), 1, 1,
+ facecolor=self.get_facecolor()[idx],
+ hatch=self.hatches[idx % len(self.hatches)],
+ ))
+ lower = str_format(lowers[idx])
+ upper = str_format(uppers[idx])
+ if idx == 0 and self.extend in ('min', 'both'):
+ labels.append(fr'${variable_name} \leq {lower}s$')
+ elif idx == n_levels - 1 and self.extend in ('max', 'both'):
+ labels.append(fr'${variable_name} > {upper}s$')
+ else:
+ labels.append(fr'${lower} < {variable_name} \leq {upper}$')
+ else:
+ for idx, level in enumerate(self.levels):
+ artists.append(Line2D(
+ [], [],
+ color=self.get_edgecolor()[idx],
+ linewidth=self.get_linewidths()[idx],
+ linestyle=self.get_linestyles()[idx],
+ ))
+ labels.append(fr'${variable_name} = {str_format(level)}$')
+
+ return artists, labels
+
+ def _process_args(self, *args, **kwargs):
+ """
+ Process *args* and *kwargs*; override in derived classes.
+
+ Must set self.levels, self.zmin and self.zmax, and update Axes limits.
+ """
+ self.levels = args[0]
+ allsegs = args[1]
+ allkinds = args[2] if len(args) > 2 else None
+ self.zmax = np.max(self.levels)
+ self.zmin = np.min(self.levels)
+
+ if allkinds is None:
+ allkinds = [[None] * len(segs) for segs in allsegs]
+
+ # Check lengths of levels and allsegs.
+ if self.filled:
+ if len(allsegs) != len(self.levels) - 1:
+ raise ValueError('must be one less number of segments as '
+ 'levels')
+ else:
+ if len(allsegs) != len(self.levels):
+ raise ValueError('must be same number of segments as levels')
+
+ # Check length of allkinds.
+ if len(allkinds) != len(allsegs):
+ raise ValueError('allkinds has different length to allsegs')
+
+ # Determine x, y bounds and update axes data limits.
+ flatseglist = [s for seg in allsegs for s in seg]
+ points = np.concatenate(flatseglist, axis=0)
+ self._mins = points.min(axis=0)
+ self._maxs = points.max(axis=0)
+
+ # Each entry in (allsegs, allkinds) is a list of (segs, kinds): segs is a list
+ # of (N, 2) arrays of xy coordinates, kinds is a list of arrays of corresponding
+ # pathcodes. However, kinds can also be None; in which case all paths in that
+ # list are codeless (this case is normalized above). These lists are used to
+ # construct paths, which then get concatenated.
+ self._paths = [Path.make_compound_path(*map(Path, segs, kinds))
+ for segs, kinds in zip(allsegs, allkinds)]
+
+ return kwargs
+
+ def _make_paths_from_contour_generator(self):
+ """Compute ``paths`` using C extension."""
+ if self._paths is not None:
+ return self._paths
+ cg = self._contour_generator
+ empty_path = Path(np.empty((0, 2)))
+ vertices_and_codes = (
+ map(cg.create_filled_contour, *self._get_lowers_and_uppers())
+ if self.filled else
+ map(cg.create_contour, self.levels))
+ return [Path(np.concatenate(vs), np.concatenate(cs)) if len(vs) else empty_path
+ for vs, cs in vertices_and_codes]
+
+ def _get_lowers_and_uppers(self):
+ """
+ Return ``(lowers, uppers)`` for filled contours.
+ """
+ lowers = self._levels[:-1]
+ if self.zmin == lowers[0]:
+ # Include minimum values in lowest interval
+ lowers = lowers.copy() # so we don't change self._levels
+ if self.logscale:
+ lowers[0] = 0.99 * self.zmin
+ else:
+ lowers[0] -= 1
+ uppers = self._levels[1:]
+ return (lowers, uppers)
+
+ def changed(self):
+ if not hasattr(self, "cvalues"):
+ self._process_colors() # Sets cvalues.
+ # Force an autoscale immediately because self.to_rgba() calls
+ # autoscale_None() internally with the data passed to it,
+ # so if vmin/vmax are not set yet, this would override them with
+ # content from *cvalues* rather than levels like we want
+ self.norm.autoscale_None(self.levels)
+ self.set_array(self.cvalues)
+ self.update_scalarmappable()
+ alphas = np.broadcast_to(self.get_alpha(), len(self.cvalues))
+ for label, cv, alpha in zip(self.labelTexts, self.labelCValues, alphas):
+ label.set_alpha(alpha)
+ label.set_color(self.labelMappable.to_rgba(cv))
+ super().changed()
+
+ def _autolev(self, N):
+ """
+ Select contour levels to span the data.
+
+ The target number of levels, *N*, is used only when the
+ scale is not log and default locator is used.
+
+ We need two more levels for filled contours than for
+ line contours, because for the latter we need to specify
+ the lower and upper boundary of each range. For example,
+ a single contour boundary, say at z = 0, requires only
+ one contour line, but two filled regions, and therefore
+ three levels to provide boundaries for both regions.
+ """
+ if self.locator is None:
+ if self.logscale:
+ self.locator = ticker.LogLocator()
+ else:
+ self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
+
+ lev = self.locator.tick_values(self.zmin, self.zmax)
+
+ try:
+ if self.locator._symmetric:
+ return lev
+ except AttributeError:
+ pass
+
+ # Trim excess levels the locator may have supplied.
+ under = np.nonzero(lev < self.zmin)[0]
+ i0 = under[-1] if len(under) else 0
+ over = np.nonzero(lev > self.zmax)[0]
+ i1 = over[0] + 1 if len(over) else len(lev)
+ if self.extend in ('min', 'both'):
+ i0 += 1
+ if self.extend in ('max', 'both'):
+ i1 -= 1
+
+ if i1 - i0 < 3:
+ i0, i1 = 0, len(lev)
+
+ return lev[i0:i1]
+
+ def _process_contour_level_args(self, args, z_dtype):
+ """
+ Determine the contour levels and store in self.levels.
+ """
+ if self.levels is None:
+ if args:
+ levels_arg = args[0]
+ elif np.issubdtype(z_dtype, bool):
+ if self.filled:
+ levels_arg = [0, .5, 1]
+ else:
+ levels_arg = [.5]
+ else:
+ levels_arg = 7 # Default, hard-wired.
+ else:
+ levels_arg = self.levels
+ if isinstance(levels_arg, Integral):
+ self.levels = self._autolev(levels_arg)
+ else:
+ self.levels = np.asarray(levels_arg, np.float64)
+ if self.filled and len(self.levels) < 2:
+ raise ValueError("Filled contours require at least 2 levels.")
+ if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
+ raise ValueError("Contour levels must be increasing")
+
+ def _process_levels(self):
+ """
+ Assign values to :attr:`layers` based on :attr:`levels`,
+ adding extended layers as needed if contours are filled.
+
+ For line contours, layers simply coincide with levels;
+ a line is a thin layer. No extended levels are needed
+ with line contours.
+ """
+ # Make a private _levels to include extended regions; we
+ # want to leave the original levels attribute unchanged.
+ # (Colorbar needs this even for line contours.)
+ self._levels = list(self.levels)
+
+ if self.logscale:
+ lower, upper = 1e-250, 1e250
+ else:
+ lower, upper = -1e250, 1e250
+
+ if self.extend in ('both', 'min'):
+ self._levels.insert(0, lower)
+ if self.extend in ('both', 'max'):
+ self._levels.append(upper)
+ self._levels = np.asarray(self._levels)
+
+ if not self.filled:
+ self.layers = self.levels
+ return
+
+ # Layer values are mid-way between levels in screen space.
+ if self.logscale:
+ # Avoid overflow by taking sqrt before multiplying.
+ self.layers = (np.sqrt(self._levels[:-1])
+ * np.sqrt(self._levels[1:]))
+ else:
+ self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
+
+ def _process_colors(self):
+ """
+ Color argument processing for contouring.
+
+ Note that we base the colormapping on the contour levels
+ and layers, not on the actual range of the Z values. This
+ means we don't have to worry about bad values in Z, and we
+ always have the full dynamic range available for the selected
+ levels.
+
+ The color is based on the midpoint of the layer, except for
+ extended end layers. By default, the norm vmin and vmax
+ are the extreme values of the non-extended levels. Hence,
+ the layer color extremes are not the extreme values of
+ the colormap itself, but approach those values as the number
+ of levels increases. An advantage of this scheme is that
+ line contours, when added to filled contours, take on
+ colors that are consistent with those of the filled regions;
+ for example, a contour line on the boundary between two
+ regions will have a color intermediate between those
+ of the regions.
+
+ """
+ self.monochrome = self.cmap.monochrome
+ if self.colors is not None:
+ # Generate integers for direct indexing.
+ i0, i1 = 0, len(self.levels)
+ if self.filled:
+ i1 -= 1
+ # Out of range indices for over and under:
+ if self.extend in ('both', 'min'):
+ i0 -= 1
+ if self.extend in ('both', 'max'):
+ i1 += 1
+ self.cvalues = list(range(i0, i1))
+ self.set_norm(mcolors.NoNorm())
+ else:
+ self.cvalues = self.layers
+ self.norm.autoscale_None(self.levels)
+ self.set_array(self.cvalues)
+ self.update_scalarmappable()
+ if self.extend in ('both', 'max', 'min'):
+ self.norm.clip = False
+
+ def _process_linewidths(self, linewidths):
+ Nlev = len(self.levels)
+ if linewidths is None:
+ default_linewidth = mpl.rcParams['contour.linewidth']
+ if default_linewidth is None:
+ default_linewidth = mpl.rcParams['lines.linewidth']
+ return [default_linewidth] * Nlev
+ elif not np.iterable(linewidths):
+ return [linewidths] * Nlev
+ else:
+ linewidths = list(linewidths)
+ return (linewidths * math.ceil(Nlev / len(linewidths)))[:Nlev]
+
+ def _process_linestyles(self, linestyles):
+ Nlev = len(self.levels)
+ if linestyles is None:
+ tlinestyles = ['solid'] * Nlev
+ if self.monochrome:
+ eps = - (self.zmax - self.zmin) * 1e-15
+ for i, lev in enumerate(self.levels):
+ if lev < eps:
+ tlinestyles[i] = self.negative_linestyles
+ else:
+ if isinstance(linestyles, str):
+ tlinestyles = [linestyles] * Nlev
+ elif np.iterable(linestyles):
+ tlinestyles = list(linestyles)
+ if len(tlinestyles) < Nlev:
+ nreps = int(np.ceil(Nlev / len(linestyles)))
+ tlinestyles = tlinestyles * nreps
+ if len(tlinestyles) > Nlev:
+ tlinestyles = tlinestyles[:Nlev]
+ else:
+ raise ValueError("Unrecognized type for linestyles kwarg")
+ return tlinestyles
+
+ def _find_nearest_contour(self, xy, indices=None):
+ """
+ Find the point in the unfilled contour plot that is closest (in screen
+ space) to point *xy*.
+
+ Parameters
+ ----------
+ xy : tuple[float, float]
+ The reference point (in screen space).
+ indices : list of int or None, default: None
+ Indices of contour levels to consider. If None (the default), all levels
+ are considered.
+
+ Returns
+ -------
+ idx_level_min : int
+ The index of the contour level closest to *xy*.
+ idx_vtx_min : int
+ The index of the `.Path` segment closest to *xy* (at that level).
+ proj : (float, float)
+ The point in the contour plot closest to *xy*.
+ """
+
+ # Convert each contour segment to pixel coordinates and then compare the given
+ # point to those coordinates for each contour. This is fast enough in normal
+ # cases, but speedups may be possible.
+
+ if self.filled:
+ raise ValueError("Method does not support filled contours")
+
+ if indices is None:
+ indices = range(len(self._paths))
+
+ d2min = np.inf
+ idx_level_min = idx_vtx_min = proj_min = None
+
+ for idx_level in indices:
+ path = self._paths[idx_level]
+ idx_vtx_start = 0
+ for subpath in path._iter_connected_components():
+ if not len(subpath.vertices):
+ continue
+ lc = self.get_transform().transform(subpath.vertices)
+ d2, proj, leg = _find_closest_point_on_path(lc, xy)
+ if d2 < d2min:
+ d2min = d2
+ idx_level_min = idx_level
+ idx_vtx_min = leg[1] + idx_vtx_start
+ proj_min = proj
+ idx_vtx_start += len(subpath)
+
+ return idx_level_min, idx_vtx_min, proj_min
+
+ def find_nearest_contour(self, x, y, indices=None, pixel=True):
+ """
+ Find the point in the contour plot that is closest to ``(x, y)``.
+
+ This method does not support filled contours.
+
+ Parameters
+ ----------
+ x, y : float
+ The reference point.
+ indices : list of int or None, default: None
+ Indices of contour levels to consider. If None (the default), all
+ levels are considered.
+ pixel : bool, default: True
+ If *True*, measure distance in pixel (screen) space, which is
+ useful for manual contour labeling; else, measure distance in axes
+ space.
+
+ Returns
+ -------
+ path : int
+ The index of the path that is closest to ``(x, y)``. Each path corresponds
+ to one contour level.
+ subpath : int
+ The index within that closest path of the subpath that is closest to
+ ``(x, y)``. Each subpath corresponds to one unbroken contour line.
+ index : int
+ The index of the vertices within that subpath that are closest to
+ ``(x, y)``.
+ xmin, ymin : float
+ The point in the contour plot that is closest to ``(x, y)``.
+ d2 : float
+ The squared distance from ``(xmin, ymin)`` to ``(x, y)``.
+ """
+ segment = index = d2 = None
+
+ with ExitStack() as stack:
+ if not pixel:
+ # _find_nearest_contour works in pixel space. We want axes space, so
+ # effectively disable the transformation here by setting to identity.
+ stack.enter_context(self._cm_set(
+ transform=mtransforms.IdentityTransform()))
+
+ i_level, i_vtx, (xmin, ymin) = self._find_nearest_contour((x, y), indices)
+
+ if i_level is not None:
+ cc_cumlens = np.cumsum(
+ [*map(len, self._paths[i_level]._iter_connected_components())])
+ segment = cc_cumlens.searchsorted(i_vtx, "right")
+ index = i_vtx if segment == 0 else i_vtx - cc_cumlens[segment - 1]
+ d2 = (xmin-x)**2 + (ymin-y)**2
+
+ return (i_level, segment, index, xmin, ymin, d2)
+
+ def draw(self, renderer):
+ paths = self._paths
+ n_paths = len(paths)
+ if not self.filled or all(hatch is None for hatch in self.hatches):
+ super().draw(renderer)
+ return
+ # In presence of hatching, draw contours one at a time.
+ edgecolors = self.get_edgecolors()
+ if edgecolors.size == 0:
+ edgecolors = ("none",)
+ for idx in range(n_paths):
+ with cbook._setattr_cm(self, _paths=[paths[idx]]), self._cm_set(
+ hatch=self.hatches[idx % len(self.hatches)],
+ array=[self.get_array()[idx]],
+ linewidths=[self.get_linewidths()[idx % len(self.get_linewidths())]],
+ linestyles=[self.get_linestyles()[idx % len(self.get_linestyles())]],
+ edgecolors=edgecolors[idx % len(edgecolors)],
+ ):
+ super().draw(renderer)
+
+
+@_docstring.interpd
+class QuadContourSet(ContourSet):
+ """
+ Create and store a set of contour lines or filled regions.
+
+ This class is typically not instantiated directly by the user but by
+ `~.Axes.contour` and `~.Axes.contourf`.
+
+ %(contour_set_attributes)s
+ """
+
+ def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs):
+ """
+ Process args and kwargs.
+ """
+ if args and isinstance(args[0], QuadContourSet):
+ if self.levels is None:
+ self.levels = args[0].levels
+ self.zmin = args[0].zmin
+ self.zmax = args[0].zmax
+ self._corner_mask = args[0]._corner_mask
+ contour_generator = args[0]._contour_generator
+ self._mins = args[0]._mins
+ self._maxs = args[0]._maxs
+ self._algorithm = args[0]._algorithm
+ else:
+ import contourpy
+
+ if algorithm is None:
+ algorithm = mpl.rcParams['contour.algorithm']
+ mpl.rcParams.validate["contour.algorithm"](algorithm)
+ self._algorithm = algorithm
+
+ if corner_mask is None:
+ if self._algorithm == "mpl2005":
+ # mpl2005 does not support corner_mask=True so if not
+ # specifically requested then disable it.
+ corner_mask = False
+ else:
+ corner_mask = mpl.rcParams['contour.corner_mask']
+ self._corner_mask = corner_mask
+
+ x, y, z = self._contour_args(args, kwargs)
+
+ contour_generator = contourpy.contour_generator(
+ x, y, z, name=self._algorithm, corner_mask=self._corner_mask,
+ line_type=contourpy.LineType.SeparateCode,
+ fill_type=contourpy.FillType.OuterCode,
+ chunk_size=self.nchunk)
+
+ t = self.get_transform()
+
+ # if the transform is not trans data, and some part of it
+ # contains transData, transform the xs and ys to data coordinates
+ if (t != self.axes.transData and
+ any(t.contains_branch_seperately(self.axes.transData))):
+ trans_to_data = t - self.axes.transData
+ pts = np.vstack([x.flat, y.flat]).T
+ transformed_pts = trans_to_data.transform(pts)
+ x = transformed_pts[..., 0]
+ y = transformed_pts[..., 1]
+
+ self._mins = [ma.min(x), ma.min(y)]
+ self._maxs = [ma.max(x), ma.max(y)]
+
+ self._contour_generator = contour_generator
+
+ return kwargs
+
+ def _contour_args(self, args, kwargs):
+ if self.filled:
+ fn = 'contourf'
+ else:
+ fn = 'contour'
+ nargs = len(args)
+
+ if 0 < nargs <= 2:
+ z, *args = args
+ z = ma.asarray(z)
+ x, y = self._initialize_x_y(z)
+ elif 2 < nargs <= 4:
+ x, y, z_orig, *args = args
+ x, y, z = self._check_xyz(x, y, z_orig, kwargs)
+
+ else:
+ raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)
+ z = ma.masked_invalid(z, copy=False)
+ self.zmax = z.max().astype(float)
+ self.zmin = z.min().astype(float)
+ if self.logscale and self.zmin <= 0:
+ z = ma.masked_where(z <= 0, z)
+ _api.warn_external('Log scale: values of z <= 0 have been masked')
+ self.zmin = z.min().astype(float)
+ self._process_contour_level_args(args, z.dtype)
+ return (x, y, z)
+
+ def _check_xyz(self, x, y, z, kwargs):
+ """
+ Check that the shapes of the input arrays match; if x and y are 1D,
+ convert them to 2D using meshgrid.
+ """
+ x, y = self.axes._process_unit_info([("x", x), ("y", y)], kwargs)
+
+ x = np.asarray(x, dtype=np.float64)
+ y = np.asarray(y, dtype=np.float64)
+ z = ma.asarray(z)
+
+ if z.ndim != 2:
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
+ if z.shape[0] < 2 or z.shape[1] < 2:
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
+ f"but has shape {z.shape}")
+ Ny, Nx = z.shape
+
+ if x.ndim != y.ndim:
+ raise TypeError(f"Number of dimensions of x ({x.ndim}) and y "
+ f"({y.ndim}) do not match")
+ if x.ndim == 1:
+ nx, = x.shape
+ ny, = y.shape
+ if nx != Nx:
+ raise TypeError(f"Length of x ({nx}) must match number of "
+ f"columns in z ({Nx})")
+ if ny != Ny:
+ raise TypeError(f"Length of y ({ny}) must match number of "
+ f"rows in z ({Ny})")
+ x, y = np.meshgrid(x, y)
+ elif x.ndim == 2:
+ if x.shape != z.shape:
+ raise TypeError(
+ f"Shapes of x {x.shape} and z {z.shape} do not match")
+ if y.shape != z.shape:
+ raise TypeError(
+ f"Shapes of y {y.shape} and z {z.shape} do not match")
+ else:
+ raise TypeError(f"Inputs x and y must be 1D or 2D, not {x.ndim}D")
+
+ return x, y, z
+
+ def _initialize_x_y(self, z):
+ """
+ Return X, Y arrays such that contour(Z) will match imshow(Z)
+ if origin is not None.
+ The center of pixel Z[i, j] depends on origin:
+ if origin is None, x = j, y = i;
+ if origin is 'lower', x = j + 0.5, y = i + 0.5;
+ if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
+ If extent is not None, x and y will be scaled to match,
+ as in imshow.
+ If origin is None and extent is not None, then extent
+ will give the minimum and maximum values of x and y.
+ """
+ if z.ndim != 2:
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
+ elif z.shape[0] < 2 or z.shape[1] < 2:
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
+ f"but has shape {z.shape}")
+ else:
+ Ny, Nx = z.shape
+ if self.origin is None: # Not for image-matching.
+ if self.extent is None:
+ return np.meshgrid(np.arange(Nx), np.arange(Ny))
+ else:
+ x0, x1, y0, y1 = self.extent
+ x = np.linspace(x0, x1, Nx)
+ y = np.linspace(y0, y1, Ny)
+ return np.meshgrid(x, y)
+ # Match image behavior:
+ if self.extent is None:
+ x0, x1, y0, y1 = (0, Nx, 0, Ny)
+ else:
+ x0, x1, y0, y1 = self.extent
+ dx = (x1 - x0) / Nx
+ dy = (y1 - y0) / Ny
+ x = x0 + (np.arange(Nx) + 0.5) * dx
+ y = y0 + (np.arange(Ny) + 0.5) * dy
+ if self.origin == 'upper':
+ y = y[::-1]
+ return np.meshgrid(x, y)
+
+
+_docstring.interpd.register(contour_doc="""
+`.contour` and `.contourf` draw contour lines and filled contours,
+respectively. Except as noted, function signatures and return values
+are the same for both versions.
+
+Parameters
+----------
+X, Y : array-like, optional
+ The coordinates of the values in *Z*.
+
+ *X* and *Y* must both be 2D with the same shape as *Z* (e.g.
+ created via `numpy.meshgrid`), or they must both be 1-D such
+ that ``len(X) == N`` is the number of columns in *Z* and
+ ``len(Y) == M`` is the number of rows in *Z*.
+
+ *X* and *Y* must both be ordered monotonically.
+
+ If not given, they are assumed to be integer indices, i.e.
+ ``X = range(N)``, ``Y = range(M)``.
+
+Z : (M, N) array-like
+ The height values over which the contour is drawn. Color-mapping is
+ controlled by *cmap*, *norm*, *vmin*, and *vmax*.
+
+levels : int or array-like, optional
+ Determines the number and positions of the contour lines / regions.
+
+ If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries
+ to automatically choose no more than *n+1* "nice" contour levels
+ between minimum and maximum numeric values of *Z*.
+
+ If array-like, draw contour lines at the specified levels.
+ The values must be in increasing order.
+
+Returns
+-------
+`~.contour.QuadContourSet`
+
+Other Parameters
+----------------
+corner_mask : bool, default: :rc:`contour.corner_mask`
+ Enable/disable corner masking, which only has an effect if *Z* is
+ a masked array. If ``False``, any quad touching a masked point is
+ masked out. If ``True``, only the triangular corners of quads
+ nearest those points are always masked out, other triangular
+ corners comprising three unmasked points are contoured as usual.
+
+colors : :mpltype:`color` or list of :mpltype:`color`, optional
+ The colors of the levels, i.e. the lines for `.contour` and the
+ areas for `.contourf`.
+
+ The sequence is cycled for the levels in ascending order. If the
+ sequence is shorter than the number of levels, it's repeated.
+
+ As a shortcut, a single color may be used in place of one-element lists, i.e.
+ ``'red'`` instead of ``['red']`` to color all levels with the same color.
+
+ .. versionchanged:: 3.10
+ Previously a single color had to be expressed as a string, but now any
+ valid color format may be passed.
+
+ By default (value *None*), the colormap specified by *cmap*
+ will be used.
+
+alpha : float, default: 1
+ The alpha blending value, between 0 (transparent) and 1 (opaque).
+
+%(cmap_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+%(norm_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+%(vmin_vmax_doc)s
+
+ If *vmin* or *vmax* are not given, the default color scaling is based on
+ *levels*.
+
+ This parameter is ignored if *colors* is set.
+
+%(colorizer_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+origin : {*None*, 'upper', 'lower', 'image'}, default: None
+ Determines the orientation and exact position of *Z* by specifying
+ the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*
+ are not given.
+
+ - *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
+ - 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
+ - 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
+ corner.
+ - 'image': Use the value from :rc:`image.origin`.
+
+extent : (x0, x1, y0, y1), optional
+ If *origin* is not *None*, then *extent* is interpreted as in
+ `.imshow`: it gives the outer pixel boundaries. In this case, the
+ position of Z[0, 0] is the center of the pixel, not a corner. If
+ *origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],
+ and (*x1*, *y1*) is the position of Z[-1, -1].
+
+ This argument is ignored if *X* and *Y* are specified in the call
+ to contour.
+
+locator : ticker.Locator subclass, optional
+ The locator is used to determine the contour levels if they
+ are not given explicitly via *levels*.
+ Defaults to `~.ticker.MaxNLocator`.
+
+extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
+ Determines the ``contourf``-coloring of values that are outside the
+ *levels* range.
+
+ If 'neither', values outside the *levels* range are not colored.
+ If 'min', 'max' or 'both', color the values below, above or below
+ and above the *levels* range.
+
+ Values below ``min(levels)`` and above ``max(levels)`` are mapped
+ to the under/over values of the `.Colormap`. Note that most
+ colormaps do not have dedicated colors for these by default, so
+ that the over and under values are the edge values of the colormap.
+ You may want to set these values explicitly using
+ `.Colormap.set_under` and `.Colormap.set_over`.
+
+ .. note::
+
+ An existing `.QuadContourSet` does not get notified if
+ properties of its colormap are changed. Therefore, an explicit
+ call `~.ContourSet.changed()` is needed after modifying the
+ colormap. The explicit call can be left out, if a colorbar is
+ assigned to the `.QuadContourSet` because it internally calls
+ `~.ContourSet.changed()`.
+
+ Example::
+
+ x = np.arange(1, 10)
+ y = x.reshape(-1, 1)
+ h = x * y
+
+ cs = plt.contourf(h, levels=[10, 30, 50],
+ colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
+ cs.cmap.set_over('red')
+ cs.cmap.set_under('blue')
+ cs.changed()
+
+xunits, yunits : registered units, optional
+ Override axis units by specifying an instance of a
+ :class:`matplotlib.units.ConversionInterface`.
+
+antialiased : bool, optional
+ Enable antialiasing, overriding the defaults. For
+ filled contours, the default is *False*. For line contours,
+ it is taken from :rc:`lines.antialiased`.
+
+nchunk : int >= 0, optional
+ If 0, no subdivision of the domain. Specify a positive integer to
+ divide the domain into subdomains of *nchunk* by *nchunk* quads.
+ Chunking reduces the maximum length of polygons generated by the
+ contouring algorithm which reduces the rendering workload passed
+ on to the backend and also requires slightly less RAM. It can
+ however introduce rendering artifacts at chunk boundaries depending
+ on the backend, the *antialiased* flag and value of *alpha*.
+
+linewidths : float or array-like, default: :rc:`contour.linewidth`
+ *Only applies to* `.contour`.
+
+ The line width of the contour lines.
+
+ If a number, all levels will be plotted with this linewidth.
+
+ If a sequence, the levels in ascending order will be plotted with
+ the linewidths in the order specified.
+
+ If None, this falls back to :rc:`lines.linewidth`.
+
+linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
+ *Only applies to* `.contour`.
+
+ If *linestyles* is *None*, the default is 'solid' unless the lines are
+ monochrome. In that case, negative contours will instead take their
+ linestyle from the *negative_linestyles* argument.
+
+ *linestyles* can also be an iterable of the above strings specifying a set
+ of linestyles to be used. If this iterable is shorter than the number of
+ contour levels it will be repeated as necessary.
+
+negative_linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, \
+ optional
+ *Only applies to* `.contour`.
+
+ If *linestyles* is *None* and the lines are monochrome, this argument
+ specifies the line style for negative contours.
+
+ If *negative_linestyles* is *None*, the default is taken from
+ :rc:`contour.negative_linestyle`.
+
+ *negative_linestyles* can also be an iterable of the above strings
+ specifying a set of linestyles to be used. If this iterable is shorter than
+ the number of contour levels it will be repeated as necessary.
+
+hatches : list[str], optional
+ *Only applies to* `.contourf`.
+
+ A list of cross hatch patterns to use on the filled areas.
+ If None, no hatching will be added to the contour.
+
+algorithm : {'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional
+ Which contouring algorithm to use to calculate the contour lines and
+ polygons. The algorithms are implemented in
+ `ContourPy `_, consult the
+ `ContourPy documentation `_ for
+ further information.
+
+ The default is taken from :rc:`contour.algorithm`.
+
+clip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`
+ Set the clip path. See `~matplotlib.artist.Artist.set_clip_path`.
+
+ .. versionadded:: 3.8
+
+data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+
+Notes
+-----
+1. `.contourf` differs from the MATLAB version in that it does not draw
+ the polygon edges. To draw edges, add line contours with calls to
+ `.contour`.
+
+2. `.contourf` fills intervals that are closed at the top; that is, for
+ boundaries *z1* and *z2*, the filled region is::
+
+ z1 < Z <= z2
+
+ except for the lowest interval, which is closed on both sides (i.e.
+ it includes the lowest value).
+
+3. `.contour` and `.contourf` use a `marching squares
+ `_ algorithm to
+ compute contour locations. More information can be found in
+ `ContourPy documentation `_.
+""" % _docstring.interpd.params)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/contour.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/contour.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..7400fac50993f4560c0fd76d12c530abdd286f26
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/contour.pyi
@@ -0,0 +1,140 @@
+import matplotlib.cm as cm
+from matplotlib.artist import Artist
+from matplotlib.axes import Axes
+from matplotlib.collections import Collection, PathCollection
+from matplotlib.colorizer import Colorizer, ColorizingArtist
+from matplotlib.colors import Colormap, Normalize
+from matplotlib.path import Path
+from matplotlib.patches import Patch
+from matplotlib.text import Text
+from matplotlib.transforms import Transform, TransformedPatchPath, TransformedPath
+from matplotlib.ticker import Locator, Formatter
+
+from numpy.typing import ArrayLike
+import numpy as np
+from collections.abc import Callable, Iterable, Sequence
+from typing import Literal
+from .typing import ColorType
+
+
+
+class ContourLabeler:
+ labelFmt: str | Formatter | Callable[[float], str] | dict[float, str]
+ labelManual: bool | Iterable[tuple[float, float]]
+ rightside_up: bool
+ labelLevelList: list[float]
+ labelIndiceList: list[int]
+ labelMappable: cm.ScalarMappable | ColorizingArtist
+ labelCValueList: list[ColorType]
+ labelXYs: list[tuple[float, float]]
+ def clabel(
+ self,
+ levels: ArrayLike | None = ...,
+ *,
+ fontsize: str | float | None = ...,
+ inline: bool = ...,
+ inline_spacing: float = ...,
+ fmt: str | Formatter | Callable[[float], str] | dict[float, str] | None = ...,
+ colors: ColorType | Sequence[ColorType] | None = ...,
+ use_clabeltext: bool = ...,
+ manual: bool | Iterable[tuple[float, float]] = ...,
+ rightside_up: bool = ...,
+ zorder: float | None = ...
+ ) -> list[Text]: ...
+ def print_label(self, linecontour: ArrayLike, labelwidth: float) -> bool: ...
+ def too_close(self, x: float, y: float, lw: float) -> bool: ...
+ def get_text(
+ self,
+ lev: float,
+ fmt: str | Formatter | Callable[[float], str] | dict[float, str],
+ ) -> str: ...
+ def locate_label(
+ self, linecontour: ArrayLike, labelwidth: float
+ ) -> tuple[float, float, float]: ...
+ def add_label(
+ self, x: float, y: float, rotation: float, lev: float, cvalue: ColorType
+ ) -> None: ...
+ def add_label_near(
+ self,
+ x: float,
+ y: float,
+ inline: bool = ...,
+ inline_spacing: int = ...,
+ transform: Transform | Literal[False] | None = ...,
+ ) -> None: ...
+ def pop_label(self, index: int = ...) -> None: ...
+ def labels(self, inline: bool, inline_spacing: int) -> None: ...
+ def remove(self) -> None: ...
+
+class ContourSet(ContourLabeler, Collection):
+ axes: Axes
+ levels: Iterable[float]
+ filled: bool
+ linewidths: float | ArrayLike | None
+ hatches: Iterable[str | None]
+ origin: Literal["upper", "lower", "image"] | None
+ extent: tuple[float, float, float, float] | None
+ colors: ColorType | Sequence[ColorType]
+ extend: Literal["neither", "both", "min", "max"]
+ nchunk: int
+ locator: Locator | None
+ logscale: bool
+ negative_linestyles: None | Literal[
+ "solid", "dashed", "dashdot", "dotted"
+ ] | Iterable[Literal["solid", "dashed", "dashdot", "dotted"]]
+ clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None
+ labelTexts: list[Text]
+ labelCValues: list[ColorType]
+
+ @property
+ def allkinds(self) -> list[list[np.ndarray | None]]: ...
+ @property
+ def allsegs(self) -> list[list[np.ndarray]]: ...
+ @property
+ def alpha(self) -> float | None: ...
+ @property
+ def linestyles(self) -> (
+ None |
+ Literal["solid", "dashed", "dashdot", "dotted"] |
+ Iterable[Literal["solid", "dashed", "dashdot", "dotted"]]
+ ): ...
+
+ def __init__(
+ self,
+ ax: Axes,
+ *args,
+ levels: Iterable[float] | None = ...,
+ filled: bool = ...,
+ linewidths: float | ArrayLike | None = ...,
+ linestyles: Literal["solid", "dashed", "dashdot", "dotted"]
+ | Iterable[Literal["solid", "dashed", "dashdot", "dotted"]]
+ | None = ...,
+ hatches: Iterable[str | None] = ...,
+ alpha: float | None = ...,
+ origin: Literal["upper", "lower", "image"] | None = ...,
+ extent: tuple[float, float, float, float] | None = ...,
+ cmap: str | Colormap | None = ...,
+ colors: ColorType | Sequence[ColorType] | None = ...,
+ norm: str | Normalize | None = ...,
+ vmin: float | None = ...,
+ vmax: float | None = ...,
+ colorizer: Colorizer | None = ...,
+ extend: Literal["neither", "both", "min", "max"] = ...,
+ antialiased: bool | None = ...,
+ nchunk: int = ...,
+ locator: Locator | None = ...,
+ transform: Transform | None = ...,
+ negative_linestyles: Literal["solid", "dashed", "dashdot", "dotted"]
+ | Iterable[Literal["solid", "dashed", "dashdot", "dotted"]]
+ | None = ...,
+ clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None = ...,
+ **kwargs
+ ) -> None: ...
+ def legend_elements(
+ self, variable_name: str = ..., str_format: Callable[[float], str] = ...
+ ) -> tuple[list[Artist], list[str]]: ...
+ def find_nearest_contour(
+ self, x: float, y: float, indices: Iterable[int] | None = ..., pixel: bool = ...
+ ) -> tuple[int, int, int, float, float, float]: ...
+
+class QuadContourSet(ContourSet): ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/dates.py b/llava_video/lib/python3.10/site-packages/matplotlib/dates.py
new file mode 100644
index 0000000000000000000000000000000000000000..511e1c6df6ccbd8747c76f297e0a6c20947cda3a
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/dates.py
@@ -0,0 +1,1840 @@
+"""
+Matplotlib provides sophisticated date plotting capabilities, standing on the
+shoulders of python :mod:`datetime` and the add-on module dateutil_.
+
+By default, Matplotlib uses the units machinery described in
+`~matplotlib.units` to convert `datetime.datetime`, and `numpy.datetime64`
+objects when plotted on an x- or y-axis. The user does not
+need to do anything for dates to be formatted, but dates often have strict
+formatting needs, so this module provides many tick locators and formatters.
+A basic example using `numpy.datetime64` is::
+
+ import numpy as np
+
+ times = np.arange(np.datetime64('2001-01-02'),
+ np.datetime64('2002-02-03'), np.timedelta64(75, 'm'))
+ y = np.random.randn(len(times))
+
+ fig, ax = plt.subplots()
+ ax.plot(times, y)
+
+.. seealso::
+
+ - :doc:`/gallery/text_labels_and_annotations/date`
+ - :doc:`/gallery/ticks/date_concise_formatter`
+ - :doc:`/gallery/ticks/date_demo_convert`
+
+.. _date-format:
+
+Matplotlib date format
+----------------------
+
+Matplotlib represents dates using floating point numbers specifying the number
+of days since a default epoch of 1970-01-01 UTC; for example,
+1970-01-01, 06:00 is the floating point number 0.25. The formatters and
+locators require the use of `datetime.datetime` objects, so only dates between
+year 0001 and 9999 can be represented. Microsecond precision
+is achievable for (approximately) 70 years on either side of the epoch, and
+20 microseconds for the rest of the allowable range of dates (year 0001 to
+9999). The epoch can be changed at import time via `.dates.set_epoch` or
+:rc:`date.epoch` to other dates if necessary; see
+:doc:`/gallery/ticks/date_precision_and_epochs` for a discussion.
+
+.. note::
+
+ Before Matplotlib 3.3, the epoch was 0000-12-31 which lost modern
+ microsecond precision and also made the default axis limit of 0 an invalid
+ datetime. In 3.3 the epoch was changed as above. To convert old
+ ordinal floats to the new epoch, users can do::
+
+ new_ordinal = old_ordinal + mdates.date2num(np.datetime64('0000-12-31'))
+
+
+There are a number of helper functions to convert between :mod:`datetime`
+objects and Matplotlib dates:
+
+.. currentmodule:: matplotlib.dates
+
+.. autosummary::
+ :nosignatures:
+
+ datestr2num
+ date2num
+ num2date
+ num2timedelta
+ drange
+ set_epoch
+ get_epoch
+
+.. note::
+
+ Like Python's `datetime.datetime`, Matplotlib uses the Gregorian calendar
+ for all conversions between dates and floating point numbers. This practice
+ is not universal, and calendar differences can cause confusing
+ differences between what Python and Matplotlib give as the number of days
+ since 0001-01-01 and what other software and databases yield. For
+ example, the US Naval Observatory uses a calendar that switches
+ from Julian to Gregorian in October, 1582. Hence, using their
+ calculator, the number of days between 0001-01-01 and 2006-04-01 is
+ 732403, whereas using the Gregorian calendar via the datetime
+ module we find::
+
+ In [1]: date(2006, 4, 1).toordinal() - date(1, 1, 1).toordinal()
+ Out[1]: 732401
+
+All the Matplotlib date converters, locators and formatters are timezone aware.
+If no explicit timezone is provided, :rc:`timezone` is assumed, provided as a
+string. If you want to use a different timezone, pass the *tz* keyword
+argument of `num2date` to any date tick locators or formatters you create. This
+can be either a `datetime.tzinfo` instance or a string with the timezone name
+that can be parsed by `~dateutil.tz.gettz`.
+
+A wide range of specific and general purpose date tick locators and
+formatters are provided in this module. See
+:mod:`matplotlib.ticker` for general information on tick locators
+and formatters. These are described below.
+
+The dateutil_ module provides additional code to handle date ticking, making it
+easy to place ticks on any kinds of dates. See examples below.
+
+.. _dateutil: https://dateutil.readthedocs.io
+
+.. _date-locators:
+
+Date tick locators
+------------------
+
+Most of the date tick locators can locate single or multiple ticks. For example::
+
+ # import constants for the days of the week
+ from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU
+
+ # tick on Mondays every week
+ loc = WeekdayLocator(byweekday=MO, tz=tz)
+
+ # tick on Mondays and Saturdays
+ loc = WeekdayLocator(byweekday=(MO, SA))
+
+In addition, most of the constructors take an interval argument::
+
+ # tick on Mondays every second week
+ loc = WeekdayLocator(byweekday=MO, interval=2)
+
+The rrule locator allows completely general date ticking::
+
+ # tick every 5th easter
+ rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
+ loc = RRuleLocator(rule)
+
+The available date tick locators are:
+
+* `MicrosecondLocator`: Locate microseconds.
+
+* `SecondLocator`: Locate seconds.
+
+* `MinuteLocator`: Locate minutes.
+
+* `HourLocator`: Locate hours.
+
+* `DayLocator`: Locate specified days of the month.
+
+* `WeekdayLocator`: Locate days of the week, e.g., MO, TU.
+
+* `MonthLocator`: Locate months, e.g., 7 for July.
+
+* `YearLocator`: Locate years that are multiples of base.
+
+* `RRuleLocator`: Locate using a `rrulewrapper`.
+ `rrulewrapper` is a simple wrapper around dateutil_'s `dateutil.rrule`
+ which allow almost arbitrary date tick specifications.
+ See :doc:`rrule example `.
+
+* `AutoDateLocator`: On autoscale, this class picks the best `DateLocator`
+ (e.g., `RRuleLocator`) to set the view limits and the tick locations. If
+ called with ``interval_multiples=True`` it will make ticks line up with
+ sensible multiples of the tick intervals. For example, if the interval is
+ 4 hours, it will pick hours 0, 4, 8, etc. as ticks. This behaviour is not
+ guaranteed by default.
+
+.. _date-formatters:
+
+Date formatters
+---------------
+
+The available date formatters are:
+
+* `AutoDateFormatter`: attempts to figure out the best format to use. This is
+ most useful when used with the `AutoDateLocator`.
+
+* `ConciseDateFormatter`: also attempts to figure out the best format to use,
+ and to make the format as compact as possible while still having complete
+ date information. This is most useful when used with the `AutoDateLocator`.
+
+* `DateFormatter`: use `~datetime.datetime.strftime` format strings.
+"""
+
+import datetime
+import functools
+import logging
+import re
+
+from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
+ MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
+ SECONDLY)
+from dateutil.relativedelta import relativedelta
+import dateutil.parser
+import dateutil.tz
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, cbook, ticker, units
+
+__all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange',
+ 'set_epoch', 'get_epoch', 'DateFormatter', 'ConciseDateFormatter',
+ 'AutoDateFormatter', 'DateLocator', 'RRuleLocator',
+ 'AutoDateLocator', 'YearLocator', 'MonthLocator', 'WeekdayLocator',
+ 'DayLocator', 'HourLocator', 'MinuteLocator',
+ 'SecondLocator', 'MicrosecondLocator',
+ 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',
+ 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
+ 'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta',
+ 'DateConverter', 'ConciseDateConverter', 'rrulewrapper')
+
+
+_log = logging.getLogger(__name__)
+UTC = datetime.timezone.utc
+
+
+def _get_tzinfo(tz=None):
+ """
+ Generate `~datetime.tzinfo` from a string or return `~datetime.tzinfo`.
+ If None, retrieve the preferred timezone from the rcParams dictionary.
+ """
+ tz = mpl._val_or_rc(tz, 'timezone')
+ if tz == 'UTC':
+ return UTC
+ if isinstance(tz, str):
+ tzinfo = dateutil.tz.gettz(tz)
+ if tzinfo is None:
+ raise ValueError(f"{tz} is not a valid timezone as parsed by"
+ " dateutil.tz.gettz.")
+ return tzinfo
+ if isinstance(tz, datetime.tzinfo):
+ return tz
+ raise TypeError(f"tz must be string or tzinfo subclass, not {tz!r}.")
+
+
+# Time-related constants.
+EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal())
+# EPOCH_OFFSET is not used by matplotlib
+MICROSECONDLY = SECONDLY + 1
+HOURS_PER_DAY = 24.
+MIN_PER_HOUR = 60.
+SEC_PER_MIN = 60.
+MONTHS_PER_YEAR = 12.
+
+DAYS_PER_WEEK = 7.
+DAYS_PER_MONTH = 30.
+DAYS_PER_YEAR = 365.0
+
+MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY
+
+SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
+SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
+SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK
+
+MUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY
+
+MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (
+ MO, TU, WE, TH, FR, SA, SU)
+WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
+
+# default epoch: passed to np.datetime64...
+_epoch = None
+
+
+def _reset_epoch_test_example():
+ """
+ Reset the Matplotlib date epoch so it can be set again.
+
+ Only for use in tests and examples.
+ """
+ global _epoch
+ _epoch = None
+
+
+def set_epoch(epoch):
+ """
+ Set the epoch (origin for dates) for datetime calculations.
+
+ The default epoch is :rc:`date.epoch`.
+
+ If microsecond accuracy is desired, the date being plotted needs to be
+ within approximately 70 years of the epoch. Matplotlib internally
+ represents dates as days since the epoch, so floating point dynamic
+ range needs to be within a factor of 2^52.
+
+ `~.dates.set_epoch` must be called before any dates are converted
+ (i.e. near the import section) or a RuntimeError will be raised.
+
+ See also :doc:`/gallery/ticks/date_precision_and_epochs`.
+
+ Parameters
+ ----------
+ epoch : str
+ valid UTC date parsable by `numpy.datetime64` (do not include
+ timezone).
+
+ """
+ global _epoch
+ if _epoch is not None:
+ raise RuntimeError('set_epoch must be called before dates plotted.')
+ _epoch = epoch
+
+
+def get_epoch():
+ """
+ Get the epoch used by `.dates`.
+
+ Returns
+ -------
+ epoch : str
+ String for the epoch (parsable by `numpy.datetime64`).
+ """
+ global _epoch
+
+ _epoch = mpl._val_or_rc(_epoch, 'date.epoch')
+ return _epoch
+
+
+def _dt64_to_ordinalf(d):
+ """
+ Convert `numpy.datetime64` or an `numpy.ndarray` of those types to
+ Gregorian date as UTC float relative to the epoch (see `.get_epoch`).
+ Roundoff is float64 precision. Practically: microseconds for dates
+ between 290301 BC, 294241 AD, milliseconds for larger dates
+ (see `numpy.datetime64`).
+ """
+
+ # the "extra" ensures that we at least allow the dynamic range out to
+ # seconds. That should get out to +/-2e11 years.
+ dseconds = d.astype('datetime64[s]')
+ extra = (d - dseconds).astype('timedelta64[ns]')
+ t0 = np.datetime64(get_epoch(), 's')
+ dt = (dseconds - t0).astype(np.float64)
+ dt += extra.astype(np.float64) / 1.0e9
+ dt = dt / SEC_PER_DAY
+
+ NaT_int = np.datetime64('NaT').astype(np.int64)
+ d_int = d.astype(np.int64)
+ dt[d_int == NaT_int] = np.nan
+ return dt
+
+
+def _from_ordinalf(x, tz=None):
+ """
+ Convert Gregorian float of the date, preserving hours, minutes,
+ seconds and microseconds. Return value is a `.datetime`.
+
+ The input date *x* is a float in ordinal days at UTC, and the output will
+ be the specified `.datetime` object corresponding to that time in
+ timezone *tz*, or if *tz* is ``None``, in the timezone specified in
+ :rc:`timezone`.
+ """
+
+ tz = _get_tzinfo(tz)
+
+ dt = (np.datetime64(get_epoch()) +
+ np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
+ if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'):
+ raise ValueError(f'Date ordinal {x} converts to {dt} (using '
+ f'epoch {get_epoch()}), but Matplotlib dates must be '
+ 'between year 0001 and 9999.')
+ # convert from datetime64 to datetime:
+ dt = dt.tolist()
+
+ # datetime64 is always UTC:
+ dt = dt.replace(tzinfo=dateutil.tz.gettz('UTC'))
+ # but maybe we are working in a different timezone so move.
+ dt = dt.astimezone(tz)
+ # fix round off errors
+ if np.abs(x) > 70 * 365:
+ # if x is big, round off to nearest twenty microseconds.
+ # This avoids floating point roundoff error
+ ms = round(dt.microsecond / 20) * 20
+ if ms == 1000000:
+ dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1)
+ else:
+ dt = dt.replace(microsecond=ms)
+
+ return dt
+
+
+# a version of _from_ordinalf that can operate on numpy arrays
+_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes="O")
+# a version of dateutil.parser.parse that can operate on numpy arrays
+_dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse)
+
+
+def datestr2num(d, default=None):
+ """
+ Convert a date string to a datenum using `dateutil.parser.parse`.
+
+ Parameters
+ ----------
+ d : str or sequence of str
+ The dates to convert.
+
+ default : datetime.datetime, optional
+ The default date to use when fields are missing in *d*.
+ """
+ if isinstance(d, str):
+ dt = dateutil.parser.parse(d, default=default)
+ return date2num(dt)
+ else:
+ if default is not None:
+ d = [date2num(dateutil.parser.parse(s, default=default))
+ for s in d]
+ return np.asarray(d)
+ d = np.asarray(d)
+ if not d.size:
+ return d
+ return date2num(_dateutil_parser_parse_np_vectorized(d))
+
+
+def date2num(d):
+ """
+ Convert datetime objects to Matplotlib dates.
+
+ Parameters
+ ----------
+ d : `datetime.datetime` or `numpy.datetime64` or sequences of these
+
+ Returns
+ -------
+ float or sequence of floats
+ Number of days since the epoch. See `.get_epoch` for the
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`. If
+ the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970
+ ("1970-01-01T12:00:00") returns 0.5.
+
+ Notes
+ -----
+ The Gregorian calendar is assumed; this is not universal practice.
+ For details see the module docstring.
+ """
+ # Unpack in case of e.g. Pandas or xarray object
+ d = cbook._unpack_to_numpy(d)
+
+ # make an iterable, but save state to unpack later:
+ iterable = np.iterable(d)
+ if not iterable:
+ d = [d]
+
+ masked = np.ma.is_masked(d)
+ mask = np.ma.getmask(d)
+ d = np.asarray(d)
+
+ # convert to datetime64 arrays, if not already:
+ if not np.issubdtype(d.dtype, np.datetime64):
+ # datetime arrays
+ if not d.size:
+ # deals with an empty array...
+ return d
+ tzi = getattr(d[0], 'tzinfo', None)
+ if tzi is not None:
+ # make datetime naive:
+ d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]
+ d = np.asarray(d)
+ d = d.astype('datetime64[us]')
+
+ d = np.ma.masked_array(d, mask=mask) if masked else d
+ d = _dt64_to_ordinalf(d)
+
+ return d if iterable else d[0]
+
+
+def num2date(x, tz=None):
+ """
+ Convert Matplotlib dates to `~datetime.datetime` objects.
+
+ Parameters
+ ----------
+ x : float or sequence of floats
+ Number of days (fraction part represents hours, minutes, seconds)
+ since the epoch. See `.get_epoch` for the
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Timezone of *x*. If a string, *tz* is passed to `dateutil.tz`.
+
+ Returns
+ -------
+ `~datetime.datetime` or sequence of `~datetime.datetime`
+ Dates are returned in timezone *tz*.
+
+ If *x* is a sequence, a sequence of `~datetime.datetime` objects will
+ be returned.
+
+ Notes
+ -----
+ The Gregorian calendar is assumed; this is not universal practice.
+ For details, see the module docstring.
+ """
+ tz = _get_tzinfo(tz)
+ return _from_ordinalf_np_vectorized(x, tz).tolist()
+
+
+_ordinalf_to_timedelta_np_vectorized = np.vectorize(
+ lambda x: datetime.timedelta(days=x), otypes="O")
+
+
+def num2timedelta(x):
+ """
+ Convert number of days to a `~datetime.timedelta` object.
+
+ If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
+ be returned.
+
+ Parameters
+ ----------
+ x : float, sequence of floats
+ Number of days. The fraction part represents hours, minutes, seconds.
+
+ Returns
+ -------
+ `datetime.timedelta` or list[`datetime.timedelta`]
+ """
+ return _ordinalf_to_timedelta_np_vectorized(x).tolist()
+
+
+def drange(dstart, dend, delta):
+ """
+ Return a sequence of equally spaced Matplotlib dates.
+
+ The dates start at *dstart* and reach up to, but not including *dend*.
+ They are spaced by *delta*.
+
+ Parameters
+ ----------
+ dstart, dend : `~datetime.datetime`
+ The date limits.
+ delta : `datetime.timedelta`
+ Spacing of the dates.
+
+ Returns
+ -------
+ `numpy.array`
+ A list floats representing Matplotlib dates.
+
+ """
+ f1 = date2num(dstart)
+ f2 = date2num(dend)
+ step = delta.total_seconds() / SEC_PER_DAY
+
+ # calculate the difference between dend and dstart in times of delta
+ num = int(np.ceil((f2 - f1) / step))
+
+ # calculate end of the interval which will be generated
+ dinterval_end = dstart + num * delta
+
+ # ensure, that an half open interval will be generated [dstart, dend)
+ if dinterval_end >= dend:
+ # if the endpoint is greater than or equal to dend,
+ # just subtract one delta
+ dinterval_end -= delta
+ num -= 1
+
+ f2 = date2num(dinterval_end) # new float-endpoint
+ return np.linspace(f1, f2, num + 1)
+
+
+def _wrap_in_tex(text):
+ p = r'([a-zA-Z]+)'
+ ret_text = re.sub(p, r'}$\1$\\mathdefault{', text)
+
+ # Braces ensure symbols are not spaced like binary operators.
+ ret_text = ret_text.replace('-', '{-}').replace(':', '{:}')
+ # To not concatenate space between numbers.
+ ret_text = ret_text.replace(' ', r'\;')
+ ret_text = '$\\mathdefault{' + ret_text + '}$'
+ ret_text = ret_text.replace('$\\mathdefault{}$', '')
+ return ret_text
+
+
+## date tick locators and formatters ###
+
+
+class DateFormatter(ticker.Formatter):
+ """
+ Format a tick (in days since the epoch) with a
+ `~datetime.datetime.strftime` format string.
+ """
+
+ def __init__(self, fmt, tz=None, *, usetex=None):
+ """
+ Parameters
+ ----------
+ fmt : str
+ `~datetime.datetime.strftime` format string
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the
+ results of the formatter.
+ """
+ self.tz = _get_tzinfo(tz)
+ self.fmt = fmt
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
+
+ def __call__(self, x, pos=0):
+ result = num2date(x, self.tz).strftime(self.fmt)
+ return _wrap_in_tex(result) if self._usetex else result
+
+ def set_tzinfo(self, tz):
+ self.tz = _get_tzinfo(tz)
+
+
+class ConciseDateFormatter(ticker.Formatter):
+ """
+ A `.Formatter` which attempts to figure out the best format to use for the
+ date, and to make it as compact as possible, but still be complete. This is
+ most useful when used with the `AutoDateLocator`::
+
+ >>> locator = AutoDateLocator()
+ >>> formatter = ConciseDateFormatter(locator)
+
+ Parameters
+ ----------
+ locator : `.ticker.Locator`
+ Locator that this axis is using.
+
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone, passed to `.dates.num2date`.
+
+ formats : list of 6 strings, optional
+ Format strings for 6 levels of tick labelling: mostly years,
+ months, days, hours, minutes, and seconds. Strings use
+ the same format codes as `~datetime.datetime.strftime`. Default is
+ ``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']``
+
+ zero_formats : list of 6 strings, optional
+ Format strings for tick labels that are "zeros" for a given tick
+ level. For instance, if most ticks are months, ticks around 1 Jan 2005
+ will be labeled "Dec", "2005", "Feb". The default is
+ ``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']``
+
+ offset_formats : list of 6 strings, optional
+ Format strings for the 6 levels that is applied to the "offset"
+ string found on the right side of an x-axis, or top of a y-axis.
+ Combined with the tick labels this should completely specify the
+ date. The default is::
+
+ ['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M']
+
+ show_offset : bool, default: True
+ Whether to show the offset or not.
+
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the results
+ of the formatter.
+
+ Examples
+ --------
+ See :doc:`/gallery/ticks/date_concise_formatter`
+
+ .. plot::
+
+ import datetime
+ import matplotlib.dates as mdates
+
+ base = datetime.datetime(2005, 2, 1)
+ dates = np.array([base + datetime.timedelta(hours=(2 * i))
+ for i in range(732)])
+ N = len(dates)
+ np.random.seed(19680801)
+ y = np.cumsum(np.random.randn(N))
+
+ fig, ax = plt.subplots(constrained_layout=True)
+ locator = mdates.AutoDateLocator()
+ formatter = mdates.ConciseDateFormatter(locator)
+ ax.xaxis.set_major_locator(locator)
+ ax.xaxis.set_major_formatter(formatter)
+
+ ax.plot(dates, y)
+ ax.set_title('Concise Date Formatter')
+
+ """
+
+ def __init__(self, locator, tz=None, formats=None, offset_formats=None,
+ zero_formats=None, show_offset=True, *, usetex=None):
+ """
+ Autoformat the date labels. The default format is used to form an
+ initial string, and then redundant elements are removed.
+ """
+ self._locator = locator
+ self._tz = tz
+ self.defaultfmt = '%Y'
+ # there are 6 levels with each level getting a specific format
+ # 0: mostly years, 1: months, 2: days,
+ # 3: hours, 4: minutes, 5: seconds
+ if formats:
+ if len(formats) != 6:
+ raise ValueError('formats argument must be a list of '
+ '6 format strings (or None)')
+ self.formats = formats
+ else:
+ self.formats = ['%Y', # ticks are mostly years
+ '%b', # ticks are mostly months
+ '%d', # ticks are mostly days
+ '%H:%M', # hrs
+ '%H:%M', # min
+ '%S.%f', # secs
+ ]
+ # fmt for zeros ticks at this level. These are
+ # ticks that should be labeled w/ info the level above.
+ # like 1 Jan can just be labelled "Jan". 02:02:00 can
+ # just be labeled 02:02.
+ if zero_formats:
+ if len(zero_formats) != 6:
+ raise ValueError('zero_formats argument must be a list of '
+ '6 format strings (or None)')
+ self.zero_formats = zero_formats
+ elif formats:
+ # use the users formats for the zero tick formats
+ self.zero_formats = [''] + self.formats[:-1]
+ else:
+ # make the defaults a bit nicer:
+ self.zero_formats = [''] + self.formats[:-1]
+ self.zero_formats[3] = '%b-%d'
+
+ if offset_formats:
+ if len(offset_formats) != 6:
+ raise ValueError('offset_formats argument must be a list of '
+ '6 format strings (or None)')
+ self.offset_formats = offset_formats
+ else:
+ self.offset_formats = ['',
+ '%Y',
+ '%Y-%b',
+ '%Y-%b-%d',
+ '%Y-%b-%d',
+ '%Y-%b-%d %H:%M']
+ self.offset_string = ''
+ self.show_offset = show_offset
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
+
+ def __call__(self, x, pos=None):
+ formatter = DateFormatter(self.defaultfmt, self._tz,
+ usetex=self._usetex)
+ return formatter(x, pos=pos)
+
+ def format_ticks(self, values):
+ tickdatetime = [num2date(value, tz=self._tz) for value in values]
+ tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime])
+
+ # basic algorithm:
+ # 1) only display a part of the date if it changes over the ticks.
+ # 2) don't display the smaller part of the date if:
+ # it is always the same or if it is the start of the
+ # year, month, day etc.
+ # fmt for most ticks at this level
+ fmts = self.formats
+ # format beginnings of days, months, years, etc.
+ zerofmts = self.zero_formats
+ # offset fmt are for the offset in the upper left of the
+ # or lower right of the axis.
+ offsetfmts = self.offset_formats
+ show_offset = self.show_offset
+
+ # determine the level we will label at:
+ # mostly 0: years, 1: months, 2: days,
+ # 3: hours, 4: minutes, 5: seconds, 6: microseconds
+ for level in range(5, -1, -1):
+ unique = np.unique(tickdate[:, level])
+ if len(unique) > 1:
+ # if 1 is included in unique, the year is shown in ticks
+ if level < 2 and np.any(unique == 1):
+ show_offset = False
+ break
+ elif level == 0:
+ # all tickdate are the same, so only micros might be different
+ # set to the most precise (6: microseconds doesn't exist...)
+ level = 5
+
+ # level is the basic level we will label at.
+ # now loop through and decide the actual ticklabels
+ zerovals = [0, 1, 1, 0, 0, 0, 0]
+ labels = [''] * len(tickdate)
+ for nn in range(len(tickdate)):
+ if level < 5:
+ if tickdate[nn][level] == zerovals[level]:
+ fmt = zerofmts[level]
+ else:
+ fmt = fmts[level]
+ else:
+ # special handling for seconds + microseconds
+ if (tickdatetime[nn].second == tickdatetime[nn].microsecond
+ == 0):
+ fmt = zerofmts[level]
+ else:
+ fmt = fmts[level]
+ labels[nn] = tickdatetime[nn].strftime(fmt)
+
+ # special handling of seconds and microseconds:
+ # strip extra zeros and decimal if possible.
+ # this is complicated by two factors. 1) we have some level-4 strings
+ # here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the
+ # same number of decimals for each string (i.e. 0.5 and 1.0).
+ if level >= 5:
+ trailing_zeros = min(
+ (len(s) - len(s.rstrip('0')) for s in labels if '.' in s),
+ default=None)
+ if trailing_zeros:
+ for nn in range(len(labels)):
+ if '.' in labels[nn]:
+ labels[nn] = labels[nn][:-trailing_zeros].rstrip('.')
+
+ if show_offset:
+ # set the offset string:
+ if (self._locator.axis and
+ self._locator.axis.__name__ in ('xaxis', 'yaxis')
+ and self._locator.axis.get_inverted()):
+ self.offset_string = tickdatetime[0].strftime(offsetfmts[level])
+ else:
+ self.offset_string = tickdatetime[-1].strftime(offsetfmts[level])
+ if self._usetex:
+ self.offset_string = _wrap_in_tex(self.offset_string)
+ else:
+ self.offset_string = ''
+
+ if self._usetex:
+ return [_wrap_in_tex(l) for l in labels]
+ else:
+ return labels
+
+ def get_offset(self):
+ return self.offset_string
+
+ def format_data_short(self, value):
+ return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S')
+
+
+class AutoDateFormatter(ticker.Formatter):
+ """
+ A `.Formatter` which attempts to figure out the best format to use. This
+ is most useful when used with the `AutoDateLocator`.
+
+ `.AutoDateFormatter` has a ``.scale`` dictionary that maps tick scales (the
+ interval in days between one major tick) to format strings; this dictionary
+ defaults to ::
+
+ self.scaled = {
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
+ 1: rcParams['date.autoformatter.day'],
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond'],
+ }
+
+ The formatter uses the format string corresponding to the lowest key in
+ the dictionary that is greater or equal to the current scale. Dictionary
+ entries can be customized::
+
+ locator = AutoDateLocator()
+ formatter = AutoDateFormatter(locator)
+ formatter.scaled[1/(24*60)] = '%M:%S' # only show min and sec
+
+ Custom callables can also be used instead of format strings. The following
+ example shows how to use a custom format function to strip trailing zeros
+ from decimal seconds and adds the date to the first ticklabel::
+
+ def my_format_function(x, pos=None):
+ x = matplotlib.dates.num2date(x)
+ if pos == 0:
+ fmt = '%D %H:%M:%S.%f'
+ else:
+ fmt = '%H:%M:%S.%f'
+ label = x.strftime(fmt)
+ label = label.rstrip("0")
+ label = label.rstrip(".")
+ return label
+
+ formatter.scaled[1/(24*60)] = my_format_function
+ """
+
+ # This can be improved by providing some user-level direction on
+ # how to choose the best format (precedence, etc.).
+
+ # Perhaps a 'struct' that has a field for each time-type where a
+ # zero would indicate "don't show" and a number would indicate
+ # "show" with some sort of priority. Same priorities could mean
+ # show all with the same priority.
+
+ # Or more simply, perhaps just a format string for each
+ # possibility...
+
+ def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d', *,
+ usetex=None):
+ """
+ Autoformat the date labels.
+
+ Parameters
+ ----------
+ locator : `.ticker.Locator`
+ Locator that this axis is using.
+
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+
+ defaultfmt : str
+ The default format to use if none of the values in ``self.scaled``
+ are greater than the unit returned by ``locator._get_unit()``.
+
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the
+ results of the formatter. If any entries in ``self.scaled`` are set
+ as functions, then it is up to the customized function to enable or
+ disable TeX's math mode itself.
+ """
+ self._locator = locator
+ self._tz = tz
+ self.defaultfmt = defaultfmt
+ self._formatter = DateFormatter(self.defaultfmt, tz)
+ rcParams = mpl.rcParams
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
+ self.scaled = {
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
+ 1: rcParams['date.autoformatter.day'],
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond']
+ }
+
+ def _set_locator(self, locator):
+ self._locator = locator
+
+ def __call__(self, x, pos=None):
+ try:
+ locator_unit_scale = float(self._locator._get_unit())
+ except AttributeError:
+ locator_unit_scale = 1
+ # Pick the first scale which is greater than the locator unit.
+ fmt = next((fmt for scale, fmt in sorted(self.scaled.items())
+ if scale >= locator_unit_scale),
+ self.defaultfmt)
+
+ if isinstance(fmt, str):
+ self._formatter = DateFormatter(fmt, self._tz, usetex=self._usetex)
+ result = self._formatter(x, pos)
+ elif callable(fmt):
+ result = fmt(x, pos)
+ else:
+ raise TypeError(f'Unexpected type passed to {self!r}.')
+
+ return result
+
+
+class rrulewrapper:
+ """
+ A simple wrapper around a `dateutil.rrule` allowing flexible
+ date tick specifications.
+ """
+ def __init__(self, freq, tzinfo=None, **kwargs):
+ """
+ Parameters
+ ----------
+ freq : {YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY}
+ Tick frequency. These constants are defined in `dateutil.rrule`,
+ but they are accessible from `matplotlib.dates` as well.
+ tzinfo : `datetime.tzinfo`, optional
+ Time zone information. The default is None.
+ **kwargs
+ Additional keyword arguments are passed to the `dateutil.rrule`.
+ """
+ kwargs['freq'] = freq
+ self._base_tzinfo = tzinfo
+
+ self._update_rrule(**kwargs)
+
+ def set(self, **kwargs):
+ """Set parameters for an existing wrapper."""
+ self._construct.update(kwargs)
+
+ self._update_rrule(**self._construct)
+
+ def _update_rrule(self, **kwargs):
+ tzinfo = self._base_tzinfo
+
+ # rrule does not play nicely with timezones - especially pytz time
+ # zones, it's best to use naive zones and attach timezones once the
+ # datetimes are returned
+ if 'dtstart' in kwargs:
+ dtstart = kwargs['dtstart']
+ if dtstart.tzinfo is not None:
+ if tzinfo is None:
+ tzinfo = dtstart.tzinfo
+ else:
+ dtstart = dtstart.astimezone(tzinfo)
+
+ kwargs['dtstart'] = dtstart.replace(tzinfo=None)
+
+ if 'until' in kwargs:
+ until = kwargs['until']
+ if until.tzinfo is not None:
+ if tzinfo is not None:
+ until = until.astimezone(tzinfo)
+ else:
+ raise ValueError('until cannot be aware if dtstart '
+ 'is naive and tzinfo is None')
+
+ kwargs['until'] = until.replace(tzinfo=None)
+
+ self._construct = kwargs.copy()
+ self._tzinfo = tzinfo
+ self._rrule = rrule(**self._construct)
+
+ def _attach_tzinfo(self, dt, tzinfo):
+ # pytz zones are attached by "localizing" the datetime
+ if hasattr(tzinfo, 'localize'):
+ return tzinfo.localize(dt, is_dst=True)
+
+ return dt.replace(tzinfo=tzinfo)
+
+ def _aware_return_wrapper(self, f, returns_list=False):
+ """Decorator function that allows rrule methods to handle tzinfo."""
+ # This is only necessary if we're actually attaching a tzinfo
+ if self._tzinfo is None:
+ return f
+
+ # All datetime arguments must be naive. If they are not naive, they are
+ # converted to the _tzinfo zone before dropping the zone.
+ def normalize_arg(arg):
+ if isinstance(arg, datetime.datetime) and arg.tzinfo is not None:
+ if arg.tzinfo is not self._tzinfo:
+ arg = arg.astimezone(self._tzinfo)
+
+ return arg.replace(tzinfo=None)
+
+ return arg
+
+ def normalize_args(args, kwargs):
+ args = tuple(normalize_arg(arg) for arg in args)
+ kwargs = {kw: normalize_arg(arg) for kw, arg in kwargs.items()}
+
+ return args, kwargs
+
+ # There are two kinds of functions we care about - ones that return
+ # dates and ones that return lists of dates.
+ if not returns_list:
+ def inner_func(*args, **kwargs):
+ args, kwargs = normalize_args(args, kwargs)
+ dt = f(*args, **kwargs)
+ return self._attach_tzinfo(dt, self._tzinfo)
+ else:
+ def inner_func(*args, **kwargs):
+ args, kwargs = normalize_args(args, kwargs)
+ dts = f(*args, **kwargs)
+ return [self._attach_tzinfo(dt, self._tzinfo) for dt in dts]
+
+ return functools.wraps(f)(inner_func)
+
+ def __getattr__(self, name):
+ if name in self.__dict__:
+ return self.__dict__[name]
+
+ f = getattr(self._rrule, name)
+
+ if name in {'after', 'before'}:
+ return self._aware_return_wrapper(f)
+ elif name in {'xafter', 'xbefore', 'between'}:
+ return self._aware_return_wrapper(f, returns_list=True)
+ else:
+ return f
+
+ def __setstate__(self, state):
+ self.__dict__.update(state)
+
+
+class DateLocator(ticker.Locator):
+ """
+ Determines the tick locations when plotting dates.
+
+ This class is subclassed by other Locators and
+ is not meant to be used on its own.
+ """
+ hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0}
+
+ def __init__(self, tz=None):
+ """
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ self.tz = _get_tzinfo(tz)
+
+ def set_tzinfo(self, tz):
+ """
+ Set timezone info.
+
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ self.tz = _get_tzinfo(tz)
+
+ def datalim_to_dt(self):
+ """Convert axis data interval to datetime objects."""
+ dmin, dmax = self.axis.get_data_interval()
+ if dmin > dmax:
+ dmin, dmax = dmax, dmin
+
+ return num2date(dmin, self.tz), num2date(dmax, self.tz)
+
+ def viewlim_to_dt(self):
+ """Convert the view interval to datetime objects."""
+ vmin, vmax = self.axis.get_view_interval()
+ if vmin > vmax:
+ vmin, vmax = vmax, vmin
+ return num2date(vmin, self.tz), num2date(vmax, self.tz)
+
+ def _get_unit(self):
+ """
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
+ """
+ return 1
+
+ def _get_interval(self):
+ """
+ Return the number of units for each tick.
+ """
+ return 1
+
+ def nonsingular(self, vmin, vmax):
+ """
+ Given the proposed upper and lower extent, adjust the range
+ if it is too close to being singular (i.e. a range of ~0).
+ """
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
+ # Except if there is no data, then use 1970 as default.
+ return (date2num(datetime.date(1970, 1, 1)),
+ date2num(datetime.date(1970, 1, 2)))
+ if vmax < vmin:
+ vmin, vmax = vmax, vmin
+ unit = self._get_unit()
+ interval = self._get_interval()
+ if abs(vmax - vmin) < 1e-6:
+ vmin -= 2 * unit * interval
+ vmax += 2 * unit * interval
+ return vmin, vmax
+
+
+class RRuleLocator(DateLocator):
+ # use the dateutil rrule instance
+
+ def __init__(self, o, tz=None):
+ super().__init__(tz)
+ self.rule = o
+
+ def __call__(self):
+ # if no data have been set, this will tank with a ValueError
+ try:
+ dmin, dmax = self.viewlim_to_dt()
+ except ValueError:
+ return []
+
+ return self.tick_values(dmin, dmax)
+
+ def tick_values(self, vmin, vmax):
+ start, stop = self._create_rrule(vmin, vmax)
+ dates = self.rule.between(start, stop, True)
+ if len(dates) == 0:
+ return date2num([vmin, vmax])
+ return self.raise_if_exceeds(date2num(dates))
+
+ def _create_rrule(self, vmin, vmax):
+ # set appropriate rrule dtstart and until and return
+ # start and end
+ delta = relativedelta(vmax, vmin)
+
+ # We need to cap at the endpoints of valid datetime
+ try:
+ start = vmin - delta
+ except (ValueError, OverflowError):
+ # cap
+ start = datetime.datetime(1, 1, 1, 0, 0, 0,
+ tzinfo=datetime.timezone.utc)
+
+ try:
+ stop = vmax + delta
+ except (ValueError, OverflowError):
+ # cap
+ stop = datetime.datetime(9999, 12, 31, 23, 59, 59,
+ tzinfo=datetime.timezone.utc)
+
+ self.rule.set(dtstart=start, until=stop)
+
+ return vmin, vmax
+
+ def _get_unit(self):
+ # docstring inherited
+ freq = self.rule._rrule._freq
+ return self.get_unit_generic(freq)
+
+ @staticmethod
+ def get_unit_generic(freq):
+ if freq == YEARLY:
+ return DAYS_PER_YEAR
+ elif freq == MONTHLY:
+ return DAYS_PER_MONTH
+ elif freq == WEEKLY:
+ return DAYS_PER_WEEK
+ elif freq == DAILY:
+ return 1.0
+ elif freq == HOURLY:
+ return 1.0 / HOURS_PER_DAY
+ elif freq == MINUTELY:
+ return 1.0 / MINUTES_PER_DAY
+ elif freq == SECONDLY:
+ return 1.0 / SEC_PER_DAY
+ else:
+ # error
+ return -1 # or should this just return '1'?
+
+ def _get_interval(self):
+ return self.rule._rrule._interval
+
+
+class AutoDateLocator(DateLocator):
+ """
+ On autoscale, this class picks the best `DateLocator` to set the view
+ limits and the tick locations.
+
+ Attributes
+ ----------
+ intervald : dict
+
+ Mapping of tick frequencies to multiples allowed for that ticking.
+ The default is ::
+
+ self.intervald = {
+ YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
+ 1000, 2000, 4000, 5000, 10000],
+ MONTHLY : [1, 2, 3, 4, 6],
+ DAILY : [1, 2, 3, 7, 14, 21],
+ HOURLY : [1, 2, 3, 4, 6, 12],
+ MINUTELY: [1, 5, 10, 15, 30],
+ SECONDLY: [1, 5, 10, 15, 30],
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500,
+ 1000, 2000, 5000, 10000, 20000, 50000,
+ 100000, 200000, 500000, 1000000],
+ }
+
+ where the keys are defined in `dateutil.rrule`.
+
+ The interval is used to specify multiples that are appropriate for
+ the frequency of ticking. For instance, every 7 days is sensible
+ for daily ticks, but for minutes/seconds, 15 or 30 make sense.
+
+ When customizing, you should only modify the values for the existing
+ keys. You should not add or delete entries.
+
+ Example for forcing ticks every 3 hours::
+
+ locator = AutoDateLocator()
+ locator.intervald[HOURLY] = [3] # only show every 3 hours
+ """
+
+ def __init__(self, tz=None, minticks=5, maxticks=None,
+ interval_multiples=True):
+ """
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ minticks : int
+ The minimum number of ticks desired; controls whether ticks occur
+ yearly, monthly, etc.
+ maxticks : int
+ The maximum number of ticks desired; controls the interval between
+ ticks (ticking every other, every 3, etc.). For fine-grained
+ control, this can be a dictionary mapping individual rrule
+ frequency constants (YEARLY, MONTHLY, etc.) to their own maximum
+ number of ticks. This can be used to keep the number of ticks
+ appropriate to the format chosen in `AutoDateFormatter`. Any
+ frequency not specified in this dictionary is given a default
+ value.
+ interval_multiples : bool, default: True
+ Whether ticks should be chosen to be multiple of the interval,
+ locking them to 'nicer' locations. For example, this will force
+ the ticks to be at hours 0, 6, 12, 18 when hourly ticking is done
+ at 6 hour intervals.
+ """
+ super().__init__(tz=tz)
+ self._freq = YEARLY
+ self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY,
+ SECONDLY, MICROSECONDLY]
+ self.minticks = minticks
+
+ self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12,
+ MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8}
+ if maxticks is not None:
+ try:
+ self.maxticks.update(maxticks)
+ except TypeError:
+ # Assume we were given an integer. Use this as the maximum
+ # number of ticks for every frequency and create a
+ # dictionary for this
+ self.maxticks = dict.fromkeys(self._freqs, maxticks)
+ self.interval_multiples = interval_multiples
+ self.intervald = {
+ YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
+ 1000, 2000, 4000, 5000, 10000],
+ MONTHLY: [1, 2, 3, 4, 6],
+ DAILY: [1, 2, 3, 7, 14, 21],
+ HOURLY: [1, 2, 3, 4, 6, 12],
+ MINUTELY: [1, 5, 10, 15, 30],
+ SECONDLY: [1, 5, 10, 15, 30],
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,
+ 5000, 10000, 20000, 50000, 100000, 200000, 500000,
+ 1000000],
+ }
+ if interval_multiples:
+ # Swap "3" for "4" in the DAILY list; If we use 3 we get bad
+ # tick loc for months w/ 31 days: 1, 4, ..., 28, 31, 1
+ # If we use 4 then we get: 1, 5, ... 25, 29, 1
+ self.intervald[DAILY] = [1, 2, 4, 7, 14]
+
+ self._byranges = [None, range(1, 13), range(1, 32),
+ range(0, 24), range(0, 60), range(0, 60), None]
+
+ def __call__(self):
+ # docstring inherited
+ dmin, dmax = self.viewlim_to_dt()
+ locator = self.get_locator(dmin, dmax)
+ return locator()
+
+ def tick_values(self, vmin, vmax):
+ return self.get_locator(vmin, vmax).tick_values(vmin, vmax)
+
+ def nonsingular(self, vmin, vmax):
+ # whatever is thrown at us, we can scale the unit.
+ # But default nonsingular date plots at an ~4 year period.
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
+ # Except if there is no data, then use 1970 as default.
+ return (date2num(datetime.date(1970, 1, 1)),
+ date2num(datetime.date(1970, 1, 2)))
+ if vmax < vmin:
+ vmin, vmax = vmax, vmin
+ if vmin == vmax:
+ vmin = vmin - DAYS_PER_YEAR * 2
+ vmax = vmax + DAYS_PER_YEAR * 2
+ return vmin, vmax
+
+ def _get_unit(self):
+ if self._freq in [MICROSECONDLY]:
+ return 1. / MUSECONDS_PER_DAY
+ else:
+ return RRuleLocator.get_unit_generic(self._freq)
+
+ def get_locator(self, dmin, dmax):
+ """Pick the best locator based on a distance."""
+ delta = relativedelta(dmax, dmin)
+ tdelta = dmax - dmin
+
+ # take absolute difference
+ if dmin > dmax:
+ delta = -delta
+ tdelta = -tdelta
+ # The following uses a mix of calls to relativedelta and timedelta
+ # methods because there is incomplete overlap in the functionality of
+ # these similar functions, and it's best to avoid doing our own math
+ # whenever possible.
+ numYears = float(delta.years)
+ numMonths = numYears * MONTHS_PER_YEAR + delta.months
+ numDays = tdelta.days # Avoids estimates of days/month, days/year.
+ numHours = numDays * HOURS_PER_DAY + delta.hours
+ numMinutes = numHours * MIN_PER_HOUR + delta.minutes
+ numSeconds = np.floor(tdelta.total_seconds())
+ numMicroseconds = np.floor(tdelta.total_seconds() * 1e6)
+
+ nums = [numYears, numMonths, numDays, numHours, numMinutes,
+ numSeconds, numMicroseconds]
+
+ use_rrule_locator = [True] * 6 + [False]
+
+ # Default setting of bymonth, etc. to pass to rrule
+ # [unused (for year), bymonth, bymonthday, byhour, byminute,
+ # bysecond, unused (for microseconds)]
+ byranges = [None, 1, 1, 0, 0, 0, None]
+
+ # Loop over all the frequencies and try to find one that gives at
+ # least a minticks tick positions. Once this is found, look for
+ # an interval from a list specific to that frequency that gives no
+ # more than maxticks tick positions. Also, set up some ranges
+ # (bymonth, etc.) as appropriate to be passed to rrulewrapper.
+ for i, (freq, num) in enumerate(zip(self._freqs, nums)):
+ # If this particular frequency doesn't give enough ticks, continue
+ if num < self.minticks:
+ # Since we're not using this particular frequency, set
+ # the corresponding by_ to None so the rrule can act as
+ # appropriate
+ byranges[i] = None
+ continue
+
+ # Find the first available interval that doesn't give too many
+ # ticks
+ for interval in self.intervald[freq]:
+ if num <= interval * (self.maxticks[freq] - 1):
+ break
+ else:
+ if not (self.interval_multiples and freq == DAILY):
+ _api.warn_external(
+ f"AutoDateLocator was unable to pick an appropriate "
+ f"interval for this date range. It may be necessary "
+ f"to add an interval value to the AutoDateLocator's "
+ f"intervald dictionary. Defaulting to {interval}.")
+
+ # Set some parameters as appropriate
+ self._freq = freq
+
+ if self._byranges[i] and self.interval_multiples:
+ byranges[i] = self._byranges[i][::interval]
+ if i in (DAILY, WEEKLY):
+ if interval == 14:
+ # just make first and 15th. Avoids 30th.
+ byranges[i] = [1, 15]
+ elif interval == 7:
+ byranges[i] = [1, 8, 15, 22]
+
+ interval = 1
+ else:
+ byranges[i] = self._byranges[i]
+ break
+ else:
+ interval = 1
+
+ if (freq == YEARLY) and self.interval_multiples:
+ locator = YearLocator(interval, tz=self.tz)
+ elif use_rrule_locator[i]:
+ _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges
+ rrule = rrulewrapper(self._freq, interval=interval,
+ dtstart=dmin, until=dmax,
+ bymonth=bymonth, bymonthday=bymonthday,
+ byhour=byhour, byminute=byminute,
+ bysecond=bysecond)
+
+ locator = RRuleLocator(rrule, tz=self.tz)
+ else:
+ locator = MicrosecondLocator(interval, tz=self.tz)
+ if date2num(dmin) > 70 * 365 and interval < 1000:
+ _api.warn_external(
+ 'Plotting microsecond time intervals for dates far from '
+ f'the epoch (time origin: {get_epoch()}) is not well-'
+ 'supported. See matplotlib.dates.set_epoch to change the '
+ 'epoch.')
+
+ locator.set_axis(self.axis)
+ return locator
+
+
+class YearLocator(RRuleLocator):
+ """
+ Make ticks on a given day of each year that is a multiple of base.
+
+ Examples::
+
+ # Tick every year on Jan 1st
+ locator = YearLocator()
+
+ # Tick every 5 years on July 4th
+ locator = YearLocator(5, month=7, day=4)
+ """
+ def __init__(self, base=1, month=1, day=1, tz=None):
+ """
+ Parameters
+ ----------
+ base : int, default: 1
+ Mark ticks every *base* years.
+ month : int, default: 1
+ The month on which to place the ticks, starting from 1. Default is
+ January.
+ day : int, default: 1
+ The day on which to place the ticks.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ rule = rrulewrapper(YEARLY, interval=base, bymonth=month,
+ bymonthday=day, **self.hms0d)
+ super().__init__(rule, tz=tz)
+ self.base = ticker._Edge_integer(base, 0)
+
+ def _create_rrule(self, vmin, vmax):
+ # 'start' needs to be a multiple of the interval to create ticks on
+ # interval multiples when the tick frequency is YEARLY
+ ymin = max(self.base.le(vmin.year) * self.base.step, 1)
+ ymax = min(self.base.ge(vmax.year) * self.base.step, 9999)
+
+ c = self.rule._construct
+ replace = {'year': ymin,
+ 'month': c.get('bymonth', 1),
+ 'day': c.get('bymonthday', 1),
+ 'hour': 0, 'minute': 0, 'second': 0}
+
+ start = vmin.replace(**replace)
+ stop = start.replace(year=ymax)
+ self.rule.set(dtstart=start, until=stop)
+
+ return start, stop
+
+
+class MonthLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each month, e.g., 1, 3, 12.
+ """
+ def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bymonth : int or list of int, default: all months
+ Ticks will be placed on every month in *bymonth*. Default is
+ ``range(1, 13)``, i.e. every month.
+ bymonthday : int, default: 1
+ The day on which to place the ticks.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if bymonth is None:
+ bymonth = range(1, 13)
+
+ rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class WeekdayLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each weekday.
+ """
+
+ def __init__(self, byweekday=1, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byweekday : int or list of int, default: all days
+ Ticks will be placed on every weekday in *byweekday*. Default is
+ every day.
+
+ Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
+ SU, the constants from :mod:`dateutil.rrule`, which have been
+ imported into the :mod:`matplotlib.dates` namespace.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ rule = rrulewrapper(DAILY, byweekday=byweekday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class DayLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each day of the month. For example,
+ 1, 15, 30.
+ """
+ def __init__(self, bymonthday=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bymonthday : int or list of int, default: all days
+ Ticks will be placed on every day in *bymonthday*. Default is
+ ``bymonthday=range(1, 32)``, i.e., every day of the month.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if interval != int(interval) or interval < 1:
+ raise ValueError("interval must be an integer greater than 0")
+ if bymonthday is None:
+ bymonthday = range(1, 32)
+
+ rule = rrulewrapper(DAILY, bymonthday=bymonthday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class HourLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each hour.
+ """
+ def __init__(self, byhour=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byhour : int or list of int, default: all hours
+ Ticks will be placed on every hour in *byhour*. Default is
+ ``byhour=range(24)``, i.e., every hour.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if byhour is None:
+ byhour = range(24)
+
+ rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,
+ byminute=0, bysecond=0)
+ super().__init__(rule, tz=tz)
+
+
+class MinuteLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each minute.
+ """
+ def __init__(self, byminute=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byminute : int or list of int, default: all minutes
+ Ticks will be placed on every minute in *byminute*. Default is
+ ``byminute=range(60)``, i.e., every minute.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if byminute is None:
+ byminute = range(60)
+
+ rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,
+ bysecond=0)
+ super().__init__(rule, tz=tz)
+
+
+class SecondLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each second.
+ """
+ def __init__(self, bysecond=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bysecond : int or list of int, default: all seconds
+ Ticks will be placed on every second in *bysecond*. Default is
+ ``bysecond = range(60)``, i.e., every second.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if bysecond is None:
+ bysecond = range(60)
+
+ rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)
+ super().__init__(rule, tz=tz)
+
+
+class MicrosecondLocator(DateLocator):
+ """
+ Make ticks on regular intervals of one or more microsecond(s).
+
+ .. note::
+
+ By default, Matplotlib uses a floating point representation of time in
+ days since the epoch, so plotting data with
+ microsecond time resolution does not work well for
+ dates that are far (about 70 years) from the epoch (check with
+ `~.dates.get_epoch`).
+
+ If you want sub-microsecond resolution time plots, it is strongly
+ recommended to use floating point seconds, not datetime-like
+ time representation.
+
+ If you really must use datetime.datetime() or similar and still
+ need microsecond precision, change the time origin via
+ `.dates.set_epoch` to something closer to the dates being plotted.
+ See :doc:`/gallery/ticks/date_precision_and_epochs`.
+
+ """
+ def __init__(self, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ super().__init__(tz=tz)
+ self._interval = interval
+ self._wrapped_locator = ticker.MultipleLocator(interval)
+
+ def set_axis(self, axis):
+ self._wrapped_locator.set_axis(axis)
+ return super().set_axis(axis)
+
+ def __call__(self):
+ # if no data have been set, this will tank with a ValueError
+ try:
+ dmin, dmax = self.viewlim_to_dt()
+ except ValueError:
+ return []
+
+ return self.tick_values(dmin, dmax)
+
+ def tick_values(self, vmin, vmax):
+ nmin, nmax = date2num((vmin, vmax))
+ t0 = np.floor(nmin)
+ nmax = nmax - t0
+ nmin = nmin - t0
+ nmin *= MUSECONDS_PER_DAY
+ nmax *= MUSECONDS_PER_DAY
+
+ ticks = self._wrapped_locator.tick_values(nmin, nmax)
+
+ ticks = ticks / MUSECONDS_PER_DAY + t0
+ return ticks
+
+ def _get_unit(self):
+ # docstring inherited
+ return 1. / MUSECONDS_PER_DAY
+
+ def _get_interval(self):
+ # docstring inherited
+ return self._interval
+
+
+class DateConverter(units.ConversionInterface):
+ """
+ Converter for `datetime.date` and `datetime.datetime` data, or for
+ date/time data represented as it would be converted by `date2num`.
+
+ The 'unit' tag for such data is None or a `~datetime.tzinfo` instance.
+ """
+
+ def __init__(self, *, interval_multiples=True):
+ self._interval_multiples = interval_multiples
+ super().__init__()
+
+ def axisinfo(self, unit, axis):
+ """
+ Return the `~matplotlib.units.AxisInfo` for *unit*.
+
+ *unit* is a `~datetime.tzinfo` instance or None.
+ The *axis* argument is required but not used.
+ """
+ tz = unit
+
+ majloc = AutoDateLocator(tz=tz,
+ interval_multiples=self._interval_multiples)
+ majfmt = AutoDateFormatter(majloc, tz=tz)
+ datemin = datetime.date(1970, 1, 1)
+ datemax = datetime.date(1970, 1, 2)
+
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
+ default_limits=(datemin, datemax))
+
+ @staticmethod
+ def convert(value, unit, axis):
+ """
+ If *value* is not already a number or sequence of numbers, convert it
+ with `date2num`.
+
+ The *unit* and *axis* arguments are not used.
+ """
+ return date2num(value)
+
+ @staticmethod
+ def default_units(x, axis):
+ """
+ Return the `~datetime.tzinfo` instance of *x* or of its first element,
+ or None
+ """
+ if isinstance(x, np.ndarray):
+ x = x.ravel()
+
+ try:
+ x = cbook._safe_first_finite(x)
+ except (TypeError, StopIteration):
+ pass
+
+ try:
+ return x.tzinfo
+ except AttributeError:
+ pass
+ return None
+
+
+class ConciseDateConverter(DateConverter):
+ # docstring inherited
+
+ def __init__(self, formats=None, zero_formats=None, offset_formats=None,
+ show_offset=True, *, interval_multiples=True):
+ self._formats = formats
+ self._zero_formats = zero_formats
+ self._offset_formats = offset_formats
+ self._show_offset = show_offset
+ self._interval_multiples = interval_multiples
+ super().__init__()
+
+ def axisinfo(self, unit, axis):
+ # docstring inherited
+ tz = unit
+ majloc = AutoDateLocator(tz=tz,
+ interval_multiples=self._interval_multiples)
+ majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats,
+ zero_formats=self._zero_formats,
+ offset_formats=self._offset_formats,
+ show_offset=self._show_offset)
+ datemin = datetime.date(1970, 1, 1)
+ datemax = datetime.date(1970, 1, 2)
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
+ default_limits=(datemin, datemax))
+
+
+class _SwitchableDateConverter:
+ """
+ Helper converter-like object that generates and dispatches to
+ temporary ConciseDateConverter or DateConverter instances based on
+ :rc:`date.converter` and :rc:`date.interval_multiples`.
+ """
+
+ @staticmethod
+ def _get_converter():
+ converter_cls = {
+ "concise": ConciseDateConverter, "auto": DateConverter}[
+ mpl.rcParams["date.converter"]]
+ interval_multiples = mpl.rcParams["date.interval_multiples"]
+ return converter_cls(interval_multiples=interval_multiples)
+
+ def axisinfo(self, *args, **kwargs):
+ return self._get_converter().axisinfo(*args, **kwargs)
+
+ def default_units(self, *args, **kwargs):
+ return self._get_converter().default_units(*args, **kwargs)
+
+ def convert(self, *args, **kwargs):
+ return self._get_converter().convert(*args, **kwargs)
+
+
+units.registry[np.datetime64] = \
+ units.registry[datetime.date] = \
+ units.registry[datetime.datetime] = \
+ _SwitchableDateConverter()
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/figure.py b/llava_video/lib/python3.10/site-packages/matplotlib/figure.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d6f9a7f4c1617aa8af106bc0123128ec77cb448
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/figure.py
@@ -0,0 +1,3726 @@
+"""
+`matplotlib.figure` implements the following classes:
+
+`Figure`
+ Top level `~matplotlib.artist.Artist`, which holds all plot elements.
+ Many methods are implemented in `FigureBase`.
+
+`SubFigure`
+ A logical figure inside a figure, usually added to a figure (or parent `SubFigure`)
+ with `Figure.add_subfigure` or `Figure.subfigures` methods.
+
+Figures are typically created using pyplot methods `~.pyplot.figure`,
+`~.pyplot.subplots`, and `~.pyplot.subplot_mosaic`.
+
+.. plot::
+ :include-source:
+
+ fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue',
+ layout='constrained')
+ fig.suptitle('Figure')
+ ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')
+
+Some situations call for directly instantiating a `~.figure.Figure` class,
+usually inside an application of some sort (see :ref:`user_interfaces` for a
+list of examples) . More information about Figures can be found at
+:ref:`figure-intro`.
+"""
+
+from contextlib import ExitStack
+import inspect
+import itertools
+import functools
+import logging
+from numbers import Integral
+import threading
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _blocking_input, backend_bases, _docstring, projections
+from matplotlib.artist import (
+ Artist, allow_rasterization, _finalize_rasterization)
+from matplotlib.backend_bases import (
+ DrawEvent, FigureCanvasBase, NonGuiException, MouseButton, _get_renderer)
+import matplotlib._api as _api
+import matplotlib.cbook as cbook
+import matplotlib.colorbar as cbar
+import matplotlib.image as mimage
+
+from matplotlib.axes import Axes
+from matplotlib.gridspec import GridSpec, SubplotParams
+from matplotlib.layout_engine import (
+ ConstrainedLayoutEngine, TightLayoutEngine, LayoutEngine,
+ PlaceHolderLayoutEngine
+)
+import matplotlib.legend as mlegend
+from matplotlib.patches import Rectangle
+from matplotlib.text import Text
+from matplotlib.transforms import (Affine2D, Bbox, BboxTransformTo,
+ TransformedBbox)
+
+_log = logging.getLogger(__name__)
+
+
+def _stale_figure_callback(self, val):
+ if (fig := self.get_figure(root=False)) is not None:
+ fig.stale = val
+
+
+class _AxesStack:
+ """
+ Helper class to track Axes in a figure.
+
+ Axes are tracked both in the order in which they have been added
+ (``self._axes`` insertion/iteration order) and in the separate "gca" stack
+ (which is the index to which they map in the ``self._axes`` dict).
+ """
+
+ def __init__(self):
+ self._axes = {} # Mapping of Axes to "gca" order.
+ self._counter = itertools.count()
+
+ def as_list(self):
+ """List the Axes that have been added to the figure."""
+ return [*self._axes] # This relies on dict preserving order.
+
+ def remove(self, a):
+ """Remove the Axes from the stack."""
+ self._axes.pop(a)
+
+ def bubble(self, a):
+ """Move an Axes, which must already exist in the stack, to the top."""
+ if a not in self._axes:
+ raise ValueError("Axes has not been added yet")
+ self._axes[a] = next(self._counter)
+
+ def add(self, a):
+ """Add an Axes to the stack, ignoring it if already present."""
+ if a not in self._axes:
+ self._axes[a] = next(self._counter)
+
+ def current(self):
+ """Return the active Axes, or None if the stack is empty."""
+ return max(self._axes, key=self._axes.__getitem__, default=None)
+
+ def __getstate__(self):
+ return {
+ **vars(self),
+ "_counter": max(self._axes.values(), default=0)
+ }
+
+ def __setstate__(self, state):
+ next_counter = state.pop('_counter')
+ vars(self).update(state)
+ self._counter = itertools.count(next_counter)
+
+
+class FigureBase(Artist):
+ """
+ Base class for `.Figure` and `.SubFigure` containing the methods that add
+ artists to the figure or subfigure, create Axes, etc.
+ """
+ def __init__(self, **kwargs):
+ super().__init__()
+ # remove the non-figure artist _axes property
+ # as it makes no sense for a figure to be _in_ an Axes
+ # this is used by the property methods in the artist base class
+ # which are over-ridden in this class
+ del self._axes
+
+ self._suptitle = None
+ self._supxlabel = None
+ self._supylabel = None
+
+ # groupers to keep track of x, y labels and title we want to align.
+ # see self.align_xlabels, self.align_ylabels,
+ # self.align_titles, and axis._get_tick_boxes_siblings
+ self._align_label_groups = {
+ "x": cbook.Grouper(),
+ "y": cbook.Grouper(),
+ "title": cbook.Grouper()
+ }
+
+ self._localaxes = [] # track all Axes
+ self.artists = []
+ self.lines = []
+ self.patches = []
+ self.texts = []
+ self.images = []
+ self.legends = []
+ self.subfigs = []
+ self.stale = True
+ self.suppressComposite = None
+ self.set(**kwargs)
+
+ def _get_draw_artists(self, renderer):
+ """Also runs apply_aspect"""
+ artists = self.get_children()
+
+ artists.remove(self.patch)
+ artists = sorted(
+ (artist for artist in artists if not artist.get_animated()),
+ key=lambda artist: artist.get_zorder())
+ for ax in self._localaxes:
+ locator = ax.get_axes_locator()
+ ax.apply_aspect(locator(ax, renderer) if locator else None)
+
+ for child in ax.get_children():
+ if hasattr(child, 'apply_aspect'):
+ locator = child.get_axes_locator()
+ child.apply_aspect(
+ locator(child, renderer) if locator else None)
+ return artists
+
+ def autofmt_xdate(
+ self, bottom=0.2, rotation=30, ha='right', which='major'):
+ """
+ Date ticklabels often overlap, so it is useful to rotate them
+ and right align them. Also, a common use case is a number of
+ subplots with shared x-axis where the x-axis is date data. The
+ ticklabels are often long, and it helps to rotate them on the
+ bottom subplot and turn them off on other subplots, as well as
+ turn off xlabels.
+
+ Parameters
+ ----------
+ bottom : float, default: 0.2
+ The bottom of the subplots for `subplots_adjust`.
+ rotation : float, default: 30 degrees
+ The rotation angle of the xtick labels in degrees.
+ ha : {'left', 'center', 'right'}, default: 'right'
+ The horizontal alignment of the xticklabels.
+ which : {'major', 'minor', 'both'}, default: 'major'
+ Selects which ticklabels to rotate.
+ """
+ _api.check_in_list(['major', 'minor', 'both'], which=which)
+ axes = [ax for ax in self.axes if ax._label != '']
+ allsubplots = all(ax.get_subplotspec() for ax in axes)
+ if len(axes) == 1:
+ for label in self.axes[0].get_xticklabels(which=which):
+ label.set_ha(ha)
+ label.set_rotation(rotation)
+ else:
+ if allsubplots:
+ for ax in axes:
+ if ax.get_subplotspec().is_last_row():
+ for label in ax.get_xticklabels(which=which):
+ label.set_ha(ha)
+ label.set_rotation(rotation)
+ else:
+ for label in ax.get_xticklabels(which=which):
+ label.set_visible(False)
+ ax.set_xlabel('')
+
+ engine = self.get_layout_engine()
+ if allsubplots and (engine is None or engine.adjust_compatible):
+ self.subplots_adjust(bottom=bottom)
+ self.stale = True
+
+ def get_children(self):
+ """Get a list of artists contained in the figure."""
+ return [self.patch,
+ *self.artists,
+ *self._localaxes,
+ *self.lines,
+ *self.patches,
+ *self.texts,
+ *self.images,
+ *self.legends,
+ *self.subfigs]
+
+ def get_figure(self, root=None):
+ """
+ Return the `.Figure` or `.SubFigure` instance the (Sub)Figure belongs to.
+
+ Parameters
+ ----------
+ root : bool, default=True
+ If False, return the (Sub)Figure this artist is on. If True,
+ return the root Figure for a nested tree of SubFigures.
+
+ .. deprecated:: 3.10
+
+ From version 3.12 *root* will default to False.
+ """
+ if self._root_figure is self:
+ # Top level Figure
+ return self
+
+ if self._parent is self._root_figure:
+ # Return early to prevent the deprecation warning when *root* does not
+ # matter
+ return self._parent
+
+ if root is None:
+ # When deprecation expires, consider removing the docstring and just
+ # inheriting the one from Artist.
+ message = ('From Matplotlib 3.12 SubFigure.get_figure will by default '
+ 'return the direct parent figure, which may be a SubFigure. '
+ 'To suppress this warning, pass the root parameter. Pass '
+ '`True` to maintain the old behavior and `False` to opt-in to '
+ 'the future behavior.')
+ _api.warn_deprecated('3.10', message=message)
+ root = True
+
+ if root:
+ return self._root_figure
+
+ return self._parent
+
+ def set_figure(self, fig):
+ """
+ .. deprecated:: 3.10
+ Currently this method will raise an exception if *fig* is anything other
+ than the root `.Figure` this (Sub)Figure is on. In future it will always
+ raise an exception.
+ """
+ no_switch = ("The parent and root figures of a (Sub)Figure are set at "
+ "instantiation and cannot be changed.")
+ if fig is self._root_figure:
+ _api.warn_deprecated(
+ "3.10",
+ message=(f"{no_switch} From Matplotlib 3.12 this operation will raise "
+ "an exception."))
+ return
+
+ raise ValueError(no_switch)
+
+ figure = property(functools.partial(get_figure, root=True), set_figure,
+ doc=("The root `Figure`. To get the parent of a `SubFigure`, "
+ "use the `get_figure` method."))
+
+ def contains(self, mouseevent):
+ """
+ Test whether the mouse event occurred on the figure.
+
+ Returns
+ -------
+ bool, {}
+ """
+ if self._different_canvas(mouseevent):
+ return False, {}
+ inside = self.bbox.contains(mouseevent.x, mouseevent.y)
+ return inside, {}
+
+ def get_window_extent(self, renderer=None):
+ # docstring inherited
+ return self.bbox
+
+ def _suplabels(self, t, info, **kwargs):
+ """
+ Add a centered %(name)s to the figure.
+
+ Parameters
+ ----------
+ t : str
+ The %(name)s text.
+ x : float, default: %(x0)s
+ The x location of the text in figure coordinates.
+ y : float, default: %(y0)s
+ The y location of the text in figure coordinates.
+ horizontalalignment, ha : {'center', 'left', 'right'}, default: %(ha)s
+ The horizontal alignment of the text relative to (*x*, *y*).
+ verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
+default: %(va)s
+ The vertical alignment of the text relative to (*x*, *y*).
+ fontsize, size : default: :rc:`figure.%(rc)ssize`
+ The font size of the text. See `.Text.set_size` for possible
+ values.
+ fontweight, weight : default: :rc:`figure.%(rc)sweight`
+ The font weight of the text. See `.Text.set_weight` for possible
+ values.
+
+ Returns
+ -------
+ text
+ The `.Text` instance of the %(name)s.
+
+ Other Parameters
+ ----------------
+ fontproperties : None or dict, optional
+ A dict of font properties. If *fontproperties* is given the
+ default values for font size and weight are taken from the
+ `.FontProperties` defaults. :rc:`figure.%(rc)ssize` and
+ :rc:`figure.%(rc)sweight` are ignored in this case.
+
+ **kwargs
+ Additional kwargs are `matplotlib.text.Text` properties.
+ """
+
+ x = kwargs.pop('x', None)
+ y = kwargs.pop('y', None)
+ if info['name'] in ['_supxlabel', '_suptitle']:
+ autopos = y is None
+ elif info['name'] == '_supylabel':
+ autopos = x is None
+ if x is None:
+ x = info['x0']
+ if y is None:
+ y = info['y0']
+
+ kwargs = cbook.normalize_kwargs(kwargs, Text)
+ kwargs.setdefault('horizontalalignment', info['ha'])
+ kwargs.setdefault('verticalalignment', info['va'])
+ kwargs.setdefault('rotation', info['rotation'])
+
+ if 'fontproperties' not in kwargs:
+ kwargs.setdefault('fontsize', mpl.rcParams[info['size']])
+ kwargs.setdefault('fontweight', mpl.rcParams[info['weight']])
+
+ suplab = getattr(self, info['name'])
+ if suplab is not None:
+ suplab.set_text(t)
+ suplab.set_position((x, y))
+ suplab.set(**kwargs)
+ else:
+ suplab = self.text(x, y, t, **kwargs)
+ setattr(self, info['name'], suplab)
+ suplab._autopos = autopos
+ self.stale = True
+ return suplab
+
+ @_docstring.Substitution(x0=0.5, y0=0.98, name='super title', ha='center',
+ va='top', rc='title')
+ @_docstring.copy(_suplabels)
+ def suptitle(self, t, **kwargs):
+ # docstring from _suplabels...
+ info = {'name': '_suptitle', 'x0': 0.5, 'y0': 0.98,
+ 'ha': 'center', 'va': 'top', 'rotation': 0,
+ 'size': 'figure.titlesize', 'weight': 'figure.titleweight'}
+ return self._suplabels(t, info, **kwargs)
+
+ def get_suptitle(self):
+ """Return the suptitle as string or an empty string if not set."""
+ text_obj = self._suptitle
+ return "" if text_obj is None else text_obj.get_text()
+
+ @_docstring.Substitution(x0=0.5, y0=0.01, name='super xlabel', ha='center',
+ va='bottom', rc='label')
+ @_docstring.copy(_suplabels)
+ def supxlabel(self, t, **kwargs):
+ # docstring from _suplabels...
+ info = {'name': '_supxlabel', 'x0': 0.5, 'y0': 0.01,
+ 'ha': 'center', 'va': 'bottom', 'rotation': 0,
+ 'size': 'figure.labelsize', 'weight': 'figure.labelweight'}
+ return self._suplabels(t, info, **kwargs)
+
+ def get_supxlabel(self):
+ """Return the supxlabel as string or an empty string if not set."""
+ text_obj = self._supxlabel
+ return "" if text_obj is None else text_obj.get_text()
+
+ @_docstring.Substitution(x0=0.02, y0=0.5, name='super ylabel', ha='left',
+ va='center', rc='label')
+ @_docstring.copy(_suplabels)
+ def supylabel(self, t, **kwargs):
+ # docstring from _suplabels...
+ info = {'name': '_supylabel', 'x0': 0.02, 'y0': 0.5,
+ 'ha': 'left', 'va': 'center', 'rotation': 'vertical',
+ 'rotation_mode': 'anchor', 'size': 'figure.labelsize',
+ 'weight': 'figure.labelweight'}
+ return self._suplabels(t, info, **kwargs)
+
+ def get_supylabel(self):
+ """Return the supylabel as string or an empty string if not set."""
+ text_obj = self._supylabel
+ return "" if text_obj is None else text_obj.get_text()
+
+ def get_edgecolor(self):
+ """Get the edge color of the Figure rectangle."""
+ return self.patch.get_edgecolor()
+
+ def get_facecolor(self):
+ """Get the face color of the Figure rectangle."""
+ return self.patch.get_facecolor()
+
+ def get_frameon(self):
+ """
+ Return the figure's background patch visibility, i.e.
+ whether the figure background will be drawn. Equivalent to
+ ``Figure.patch.get_visible()``.
+ """
+ return self.patch.get_visible()
+
+ def set_linewidth(self, linewidth):
+ """
+ Set the line width of the Figure rectangle.
+
+ Parameters
+ ----------
+ linewidth : number
+ """
+ self.patch.set_linewidth(linewidth)
+
+ def get_linewidth(self):
+ """
+ Get the line width of the Figure rectangle.
+ """
+ return self.patch.get_linewidth()
+
+ def set_edgecolor(self, color):
+ """
+ Set the edge color of the Figure rectangle.
+
+ Parameters
+ ----------
+ color : :mpltype:`color`
+ """
+ self.patch.set_edgecolor(color)
+
+ def set_facecolor(self, color):
+ """
+ Set the face color of the Figure rectangle.
+
+ Parameters
+ ----------
+ color : :mpltype:`color`
+ """
+ self.patch.set_facecolor(color)
+
+ def set_frameon(self, b):
+ """
+ Set the figure's background patch visibility, i.e.
+ whether the figure background will be drawn. Equivalent to
+ ``Figure.patch.set_visible()``.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ self.patch.set_visible(b)
+ self.stale = True
+
+ frameon = property(get_frameon, set_frameon)
+
+ def add_artist(self, artist, clip=False):
+ """
+ Add an `.Artist` to the figure.
+
+ Usually artists are added to `~.axes.Axes` objects using
+ `.Axes.add_artist`; this method can be used in the rare cases where
+ one needs to add artists directly to the figure instead.
+
+ Parameters
+ ----------
+ artist : `~matplotlib.artist.Artist`
+ The artist to add to the figure. If the added artist has no
+ transform previously set, its transform will be set to
+ ``figure.transSubfigure``.
+ clip : bool, default: False
+ Whether the added artist should be clipped by the figure patch.
+
+ Returns
+ -------
+ `~matplotlib.artist.Artist`
+ The added artist.
+ """
+ artist.set_figure(self)
+ self.artists.append(artist)
+ artist._remove_method = self.artists.remove
+
+ if not artist.is_transform_set():
+ artist.set_transform(self.transSubfigure)
+
+ if clip and artist.get_clip_path() is None:
+ artist.set_clip_path(self.patch)
+
+ self.stale = True
+ return artist
+
+ @_docstring.interpd
+ def add_axes(self, *args, **kwargs):
+ """
+ Add an `~.axes.Axes` to the figure.
+
+ Call signatures::
+
+ add_axes(rect, projection=None, polar=False, **kwargs)
+ add_axes(ax)
+
+ Parameters
+ ----------
+ rect : tuple (left, bottom, width, height)
+ The dimensions (left, bottom, width, height) of the new
+ `~.axes.Axes`. All quantities are in fractions of figure width and
+ height.
+
+ projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
+'polar', 'rectilinear', str}, optional
+ The projection type of the `~.axes.Axes`. *str* is the name of
+ a custom projection, see `~matplotlib.projections`. The default
+ None results in a 'rectilinear' projection.
+
+ polar : bool, default: False
+ If True, equivalent to projection='polar'.
+
+ axes_class : subclass type of `~.axes.Axes`, optional
+ The `.axes.Axes` subclass that is instantiated. This parameter
+ is incompatible with *projection* and *polar*. See
+ :ref:`axisartist_users-guide-index` for examples.
+
+ sharex, sharey : `~matplotlib.axes.Axes`, optional
+ Share the x or y `~matplotlib.axis` with sharex and/or sharey.
+ The axis will have the same limits, ticks, and scale as the axis
+ of the shared Axes.
+
+ label : str
+ A label for the returned Axes.
+
+ Returns
+ -------
+ `~.axes.Axes`, or a subclass of `~.axes.Axes`
+ The returned Axes class depends on the projection used. It is
+ `~.axes.Axes` if rectilinear projection is used and
+ `.projections.polar.PolarAxes` if polar projection is used.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ This method also takes the keyword arguments for
+ the returned Axes class. The keyword arguments for the
+ rectilinear Axes class `~.axes.Axes` can be found in
+ the following table but there might also be other keyword
+ arguments if another projection is used, see the actual Axes
+ class.
+
+ %(Axes:kwdoc)s
+
+ Notes
+ -----
+ In rare circumstances, `.add_axes` may be called with a single
+ argument, an Axes instance already created in the present figure but
+ not in the figure's list of Axes.
+
+ See Also
+ --------
+ .Figure.add_subplot
+ .pyplot.subplot
+ .pyplot.axes
+ .Figure.subplots
+ .pyplot.subplots
+
+ Examples
+ --------
+ Some simple examples::
+
+ rect = l, b, w, h
+ fig = plt.figure()
+ fig.add_axes(rect)
+ fig.add_axes(rect, frameon=False, facecolor='g')
+ fig.add_axes(rect, polar=True)
+ ax = fig.add_axes(rect, projection='polar')
+ fig.delaxes(ax)
+ fig.add_axes(ax)
+ """
+
+ if not len(args) and 'rect' not in kwargs:
+ raise TypeError("add_axes() missing 1 required positional argument: 'rect'")
+ elif 'rect' in kwargs:
+ if len(args):
+ raise TypeError("add_axes() got multiple values for argument 'rect'")
+ args = (kwargs.pop('rect'), )
+ if len(args) != 1:
+ raise _api.nargs_error("add_axes", 1, len(args))
+
+ if isinstance(args[0], Axes):
+ a, = args
+ key = a._projection_init
+ if a.get_figure(root=False) is not self:
+ raise ValueError(
+ "The Axes must have been created in the present figure")
+ else:
+ rect, = args
+ if not np.isfinite(rect).all():
+ raise ValueError(f'all entries in rect must be finite not {rect}')
+ projection_class, pkw = self._process_projection_requirements(**kwargs)
+
+ # create the new Axes using the Axes class given
+ a = projection_class(self, rect, **pkw)
+ key = (projection_class, pkw)
+
+ return self._add_axes_internal(a, key)
+
+ @_docstring.interpd
+ def add_subplot(self, *args, **kwargs):
+ """
+ Add an `~.axes.Axes` to the figure as part of a subplot arrangement.
+
+ Call signatures::
+
+ add_subplot(nrows, ncols, index, **kwargs)
+ add_subplot(pos, **kwargs)
+ add_subplot(ax)
+ add_subplot()
+
+ Parameters
+ ----------
+ *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
+ The position of the subplot described by one of
+
+ - Three integers (*nrows*, *ncols*, *index*). The subplot will
+ take the *index* position on a grid with *nrows* rows and
+ *ncols* columns. *index* starts at 1 in the upper left corner
+ and increases to the right. *index* can also be a two-tuple
+ specifying the (*first*, *last*) indices (1-based, and including
+ *last*) of the subplot, e.g., ``fig.add_subplot(3, 1, (1, 2))``
+ makes a subplot that spans the upper 2/3 of the figure.
+ - A 3-digit integer. The digits are interpreted as if given
+ separately as three single-digit integers, i.e.
+ ``fig.add_subplot(235)`` is the same as
+ ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
+ if there are no more than 9 subplots.
+ - A `.SubplotSpec`.
+
+ In rare circumstances, `.add_subplot` may be called with a single
+ argument, a subplot Axes instance already created in the
+ present figure but not in the figure's list of Axes.
+
+ projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
+'polar', 'rectilinear', str}, optional
+ The projection type of the subplot (`~.axes.Axes`). *str* is the
+ name of a custom projection, see `~matplotlib.projections`. The
+ default None results in a 'rectilinear' projection.
+
+ polar : bool, default: False
+ If True, equivalent to projection='polar'.
+
+ axes_class : subclass type of `~.axes.Axes`, optional
+ The `.axes.Axes` subclass that is instantiated. This parameter
+ is incompatible with *projection* and *polar*. See
+ :ref:`axisartist_users-guide-index` for examples.
+
+ sharex, sharey : `~matplotlib.axes.Axes`, optional
+ Share the x or y `~matplotlib.axis` with sharex and/or sharey.
+ The axis will have the same limits, ticks, and scale as the axis
+ of the shared Axes.
+
+ label : str
+ A label for the returned Axes.
+
+ Returns
+ -------
+ `~.axes.Axes`
+
+ The Axes of the subplot. The returned Axes can actually be an
+ instance of a subclass, such as `.projections.polar.PolarAxes` for
+ polar projections.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ This method also takes the keyword arguments for the returned Axes
+ base class; except for the *figure* argument. The keyword arguments
+ for the rectilinear base class `~.axes.Axes` can be found in
+ the following table but there might also be other keyword
+ arguments if another projection is used.
+
+ %(Axes:kwdoc)s
+
+ See Also
+ --------
+ .Figure.add_axes
+ .pyplot.subplot
+ .pyplot.axes
+ .Figure.subplots
+ .pyplot.subplots
+
+ Examples
+ --------
+ ::
+
+ fig = plt.figure()
+
+ fig.add_subplot(231)
+ ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
+
+ fig.add_subplot(232, frameon=False) # subplot with no frame
+ fig.add_subplot(233, projection='polar') # polar subplot
+ fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
+ fig.add_subplot(235, facecolor="red") # red subplot
+
+ ax1.remove() # delete ax1 from the figure
+ fig.add_subplot(ax1) # add ax1 back to the figure
+ """
+ if 'figure' in kwargs:
+ # Axes itself allows for a 'figure' kwarg, but since we want to
+ # bind the created Axes to self, it is not allowed here.
+ raise _api.kwarg_error("add_subplot", "figure")
+
+ if (len(args) == 1
+ and isinstance(args[0], mpl.axes._base._AxesBase)
+ and args[0].get_subplotspec()):
+ ax = args[0]
+ key = ax._projection_init
+ if ax.get_figure(root=False) is not self:
+ raise ValueError("The Axes must have been created in "
+ "the present figure")
+ else:
+ if not args:
+ args = (1, 1, 1)
+ # Normalize correct ijk values to (i, j, k) here so that
+ # add_subplot(211) == add_subplot(2, 1, 1). Invalid values will
+ # trigger errors later (via SubplotSpec._from_subplot_args).
+ if (len(args) == 1 and isinstance(args[0], Integral)
+ and 100 <= args[0] <= 999):
+ args = tuple(map(int, str(args[0])))
+ projection_class, pkw = self._process_projection_requirements(**kwargs)
+ ax = projection_class(self, *args, **pkw)
+ key = (projection_class, pkw)
+ return self._add_axes_internal(ax, key)
+
+ def _add_axes_internal(self, ax, key):
+ """Private helper for `add_axes` and `add_subplot`."""
+ self._axstack.add(ax)
+ if ax not in self._localaxes:
+ self._localaxes.append(ax)
+ self.sca(ax)
+ ax._remove_method = self.delaxes
+ # this is to support plt.subplot's re-selection logic
+ ax._projection_init = key
+ self.stale = True
+ ax.stale_callback = _stale_figure_callback
+ return ax
+
+ def subplots(self, nrows=1, ncols=1, *, sharex=False, sharey=False,
+ squeeze=True, width_ratios=None, height_ratios=None,
+ subplot_kw=None, gridspec_kw=None):
+ """
+ Add a set of subplots to this figure.
+
+ This utility wrapper makes it convenient to create common layouts of
+ subplots in a single call.
+
+ Parameters
+ ----------
+ nrows, ncols : int, default: 1
+ Number of rows/columns of the subplot grid.
+
+ sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
+ Controls sharing of x-axis (*sharex*) or y-axis (*sharey*):
+
+ - True or 'all': x- or y-axis will be shared among all subplots.
+ - False or 'none': each subplot x- or y-axis will be independent.
+ - 'row': each subplot row will share an x- or y-axis.
+ - 'col': each subplot column will share an x- or y-axis.
+
+ When subplots have a shared x-axis along a column, only the x tick
+ labels of the bottom subplot are created. Similarly, when subplots
+ have a shared y-axis along a row, only the y tick labels of the
+ first column subplot are created. To later turn other subplots'
+ ticklabels on, use `~matplotlib.axes.Axes.tick_params`.
+
+ When subplots have a shared axis that has units, calling
+ `.Axis.set_units` will update each axis with the new units.
+
+ Note that it is not possible to unshare axes.
+
+ squeeze : bool, default: True
+ - If True, extra dimensions are squeezed out from the returned
+ array of Axes:
+
+ - if only one subplot is constructed (nrows=ncols=1), the
+ resulting single Axes object is returned as a scalar.
+ - for Nx1 or 1xM subplots, the returned object is a 1D numpy
+ object array of Axes objects.
+ - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
+
+ - If False, no squeezing at all is done: the returned Axes object
+ is always a 2D array containing Axes instances, even if it ends
+ up being 1x1.
+
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width. Equivalent
+ to ``gridspec_kw={'width_ratios': [...]}``.
+
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height. Equivalent
+ to ``gridspec_kw={'height_ratios': [...]}``.
+
+ subplot_kw : dict, optional
+ Dict with keywords passed to the `.Figure.add_subplot` call used to
+ create each subplot.
+
+ gridspec_kw : dict, optional
+ Dict with keywords passed to the
+ `~matplotlib.gridspec.GridSpec` constructor used to create
+ the grid the subplots are placed on.
+
+ Returns
+ -------
+ `~.axes.Axes` or array of Axes
+ Either a single `~matplotlib.axes.Axes` object or an array of Axes
+ objects if more than one subplot was created. The dimensions of the
+ resulting array can be controlled with the *squeeze* keyword, see
+ above.
+
+ See Also
+ --------
+ .pyplot.subplots
+ .Figure.add_subplot
+ .pyplot.subplot
+
+ Examples
+ --------
+ ::
+
+ # First create some toy data:
+ x = np.linspace(0, 2*np.pi, 400)
+ y = np.sin(x**2)
+
+ # Create a figure
+ fig = plt.figure()
+
+ # Create a subplot
+ ax = fig.subplots()
+ ax.plot(x, y)
+ ax.set_title('Simple plot')
+
+ # Create two subplots and unpack the output array immediately
+ ax1, ax2 = fig.subplots(1, 2, sharey=True)
+ ax1.plot(x, y)
+ ax1.set_title('Sharing Y axis')
+ ax2.scatter(x, y)
+
+ # Create four polar Axes and access them through the returned array
+ axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
+ axes[0, 0].plot(x, y)
+ axes[1, 1].scatter(x, y)
+
+ # Share an X-axis with each column of subplots
+ fig.subplots(2, 2, sharex='col')
+
+ # Share a Y-axis with each row of subplots
+ fig.subplots(2, 2, sharey='row')
+
+ # Share both X- and Y-axes with all subplots
+ fig.subplots(2, 2, sharex='all', sharey='all')
+
+ # Note that this is the same as
+ fig.subplots(2, 2, sharex=True, sharey=True)
+ """
+ gridspec_kw = dict(gridspec_kw or {})
+ if height_ratios is not None:
+ if 'height_ratios' in gridspec_kw:
+ raise ValueError("'height_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['height_ratios'] = height_ratios
+ if width_ratios is not None:
+ if 'width_ratios' in gridspec_kw:
+ raise ValueError("'width_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['width_ratios'] = width_ratios
+
+ gs = self.add_gridspec(nrows, ncols, figure=self, **gridspec_kw)
+ axs = gs.subplots(sharex=sharex, sharey=sharey, squeeze=squeeze,
+ subplot_kw=subplot_kw)
+ return axs
+
+ def delaxes(self, ax):
+ """
+ Remove the `~.axes.Axes` *ax* from the figure; update the current Axes.
+ """
+ self._remove_axes(ax, owners=[self._axstack, self._localaxes])
+
+ def _remove_axes(self, ax, owners):
+ """
+ Common helper for removal of standard Axes (via delaxes) and of child Axes.
+
+ Parameters
+ ----------
+ ax : `~.AxesBase`
+ The Axes to remove.
+ owners
+ List of objects (list or _AxesStack) "owning" the Axes, from which the Axes
+ will be remove()d.
+ """
+ for owner in owners:
+ owner.remove(ax)
+
+ self._axobservers.process("_axes_change_event", self)
+ self.stale = True
+ self._root_figure.canvas.release_mouse(ax)
+
+ for name in ax._axis_names: # Break link between any shared Axes
+ grouper = ax._shared_axes[name]
+ siblings = [other for other in grouper.get_siblings(ax) if other is not ax]
+ if not siblings: # Axes was not shared along this axis; we're done.
+ continue
+ grouper.remove(ax)
+ # Formatters and locators may previously have been associated with the now
+ # removed axis. Update them to point to an axis still there (we can pick
+ # any of them, and use the first sibling).
+ remaining_axis = siblings[0]._axis_map[name]
+ remaining_axis.get_major_formatter().set_axis(remaining_axis)
+ remaining_axis.get_major_locator().set_axis(remaining_axis)
+ remaining_axis.get_minor_formatter().set_axis(remaining_axis)
+ remaining_axis.get_minor_locator().set_axis(remaining_axis)
+
+ ax._twinned_axes.remove(ax) # Break link between any twinned Axes.
+
+ def clear(self, keep_observers=False):
+ """
+ Clear the figure.
+
+ Parameters
+ ----------
+ keep_observers : bool, default: False
+ Set *keep_observers* to True if, for example,
+ a gui widget is tracking the Axes in the figure.
+ """
+ self.suppressComposite = None
+
+ # first clear the Axes in any subfigures
+ for subfig in self.subfigs:
+ subfig.clear(keep_observers=keep_observers)
+ self.subfigs = []
+
+ for ax in tuple(self.axes): # Iterate over the copy.
+ ax.clear()
+ self.delaxes(ax) # Remove ax from self._axstack.
+
+ self.artists = []
+ self.lines = []
+ self.patches = []
+ self.texts = []
+ self.images = []
+ self.legends = []
+ if not keep_observers:
+ self._axobservers = cbook.CallbackRegistry()
+ self._suptitle = None
+ self._supxlabel = None
+ self._supylabel = None
+
+ self.stale = True
+
+ # synonym for `clear`.
+ def clf(self, keep_observers=False):
+ """
+ [*Discouraged*] Alias for the `clear()` method.
+
+ .. admonition:: Discouraged
+
+ The use of ``clf()`` is discouraged. Use ``clear()`` instead.
+
+ Parameters
+ ----------
+ keep_observers : bool, default: False
+ Set *keep_observers* to True if, for example,
+ a gui widget is tracking the Axes in the figure.
+ """
+ return self.clear(keep_observers=keep_observers)
+
+ # Note: the docstring below is modified with replace for the pyplot
+ # version of this function because the method name differs (plt.figlegend)
+ # the replacements are:
+ # " legend(" -> " figlegend(" for the signatures
+ # "fig.legend(" -> "plt.figlegend" for the code examples
+ # "ax.plot" -> "plt.plot" for consistency in using pyplot when able
+ @_docstring.interpd
+ def legend(self, *args, **kwargs):
+ """
+ Place a legend on the figure.
+
+ Call signatures::
+
+ legend()
+ legend(handles, labels)
+ legend(handles=handles)
+ legend(labels)
+
+ The call signatures correspond to the following different ways to use
+ this method:
+
+ **1. Automatic detection of elements to be shown in the legend**
+
+ The elements to be added to the legend are automatically determined,
+ when you do not pass in any extra arguments.
+
+ In this case, the labels are taken from the artist. You can specify
+ them either at artist creation or by calling the
+ :meth:`~.Artist.set_label` method on the artist::
+
+ ax.plot([1, 2, 3], label='Inline label')
+ fig.legend()
+
+ or::
+
+ line, = ax.plot([1, 2, 3])
+ line.set_label('Label via method')
+ fig.legend()
+
+ Specific lines can be excluded from the automatic legend element
+ selection by defining a label starting with an underscore.
+ This is default for all artists, so calling `.Figure.legend` without
+ any arguments and without setting the labels manually will result in
+ no legend being drawn.
+
+
+ **2. Explicitly listing the artists and labels in the legend**
+
+ For full control of which artists have a legend entry, it is possible
+ to pass an iterable of legend artists followed by an iterable of
+ legend labels respectively::
+
+ fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
+
+
+ **3. Explicitly listing the artists in the legend**
+
+ This is similar to 2, but the labels are taken from the artists'
+ label properties. Example::
+
+ line1, = ax1.plot([1, 2, 3], label='label1')
+ line2, = ax2.plot([1, 2, 3], label='label2')
+ fig.legend(handles=[line1, line2])
+
+
+ **4. Labeling existing plot elements**
+
+ .. admonition:: Discouraged
+
+ This call signature is discouraged, because the relation between
+ plot elements and labels is only implicit by their order and can
+ easily be mixed up.
+
+ To make a legend for all artists on all Axes, call this function with
+ an iterable of strings, one for each legend item. For example::
+
+ fig, (ax1, ax2) = plt.subplots(1, 2)
+ ax1.plot([1, 3, 5], color='blue')
+ ax2.plot([2, 4, 6], color='red')
+ fig.legend(['the blues', 'the reds'])
+
+
+ Parameters
+ ----------
+ handles : list of `.Artist`, optional
+ A list of Artists (lines, patches) to be added to the legend.
+ Use this together with *labels*, if you need full control on what
+ is shown in the legend and the automatic mechanism described above
+ is not sufficient.
+
+ The length of handles and labels should be the same in this
+ case. If they are not, they are truncated to the smaller length.
+
+ labels : list of str, optional
+ A list of labels to show next to the artists.
+ Use this together with *handles*, if you need full control on what
+ is shown in the legend and the automatic mechanism described above
+ is not sufficient.
+
+ Returns
+ -------
+ `~matplotlib.legend.Legend`
+
+ Other Parameters
+ ----------------
+ %(_legend_kw_figure)s
+
+ See Also
+ --------
+ .Axes.legend
+
+ Notes
+ -----
+ Some artists are not supported by this function. See
+ :ref:`legend_guide` for details.
+ """
+
+ handles, labels, kwargs = mlegend._parse_legend_args(self.axes, *args, **kwargs)
+ # explicitly set the bbox transform if the user hasn't.
+ kwargs.setdefault("bbox_transform", self.transSubfigure)
+ l = mlegend.Legend(self, handles, labels, **kwargs)
+ self.legends.append(l)
+ l._remove_method = self.legends.remove
+ self.stale = True
+ return l
+
+ @_docstring.interpd
+ def text(self, x, y, s, fontdict=None, **kwargs):
+ """
+ Add text to figure.
+
+ Parameters
+ ----------
+ x, y : float
+ The position to place the text. By default, this is in figure
+ coordinates, floats in [0, 1]. The coordinate system can be changed
+ using the *transform* keyword.
+
+ s : str
+ The text string.
+
+ fontdict : dict, optional
+ A dictionary to override the default text properties. If not given,
+ the defaults are determined by :rc:`font.*`. Properties passed as
+ *kwargs* override the corresponding ones given in *fontdict*.
+
+ Returns
+ -------
+ `~.text.Text`
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.text.Text` properties
+ Other miscellaneous text parameters.
+
+ %(Text:kwdoc)s
+
+ See Also
+ --------
+ .Axes.text
+ .pyplot.text
+ """
+ effective_kwargs = {
+ 'transform': self.transSubfigure,
+ **(fontdict if fontdict is not None else {}),
+ **kwargs,
+ }
+ text = Text(x=x, y=y, text=s, **effective_kwargs)
+ text.set_figure(self)
+ text.stale_callback = _stale_figure_callback
+
+ self.texts.append(text)
+ text._remove_method = self.texts.remove
+ self.stale = True
+ return text
+
+ @_docstring.interpd
+ def colorbar(
+ self, mappable, cax=None, ax=None, use_gridspec=True, **kwargs):
+ """
+ Add a colorbar to a plot.
+
+ Parameters
+ ----------
+ mappable
+ The `matplotlib.cm.ScalarMappable` (i.e., `.AxesImage`,
+ `.ContourSet`, etc.) described by this colorbar. This argument is
+ mandatory for the `.Figure.colorbar` method but optional for the
+ `.pyplot.colorbar` function, which sets the default to the current
+ image.
+
+ Note that one can create a `.ScalarMappable` "on-the-fly" to
+ generate colorbars not attached to a previously drawn artist, e.g.
+ ::
+
+ fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
+
+ cax : `~matplotlib.axes.Axes`, optional
+ Axes into which the colorbar will be drawn. If `None`, then a new
+ Axes is created and the space for it will be stolen from the Axes(s)
+ specified in *ax*.
+
+ ax : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of Axes, optional
+ The one or more parent Axes from which space for a new colorbar Axes
+ will be stolen. This parameter is only used if *cax* is not set.
+
+ Defaults to the Axes that contains the mappable used to create the
+ colorbar.
+
+ use_gridspec : bool, optional
+ If *cax* is ``None``, a new *cax* is created as an instance of
+ Axes. If *ax* is positioned with a subplotspec and *use_gridspec*
+ is ``True``, then *cax* is also positioned with a subplotspec.
+
+ Returns
+ -------
+ colorbar : `~matplotlib.colorbar.Colorbar`
+
+ Other Parameters
+ ----------------
+ %(_make_axes_kw_doc)s
+ %(_colormap_kw_doc)s
+
+ Notes
+ -----
+ If *mappable* is a `~.contour.ContourSet`, its *extend* kwarg is
+ included automatically.
+
+ The *shrink* kwarg provides a simple way to scale the colorbar with
+ respect to the Axes. Note that if *cax* is specified, it determines the
+ size of the colorbar, and *shrink* and *aspect* are ignored.
+
+ For more precise control, you can manually specify the positions of the
+ axes objects in which the mappable and the colorbar are drawn. In this
+ case, do not use any of the Axes properties kwargs.
+
+ It is known that some vector graphics viewers (svg and pdf) render
+ white gaps between segments of the colorbar. This is due to bugs in
+ the viewers, not Matplotlib. As a workaround, the colorbar can be
+ rendered with overlapping segments::
+
+ cbar = colorbar()
+ cbar.solids.set_edgecolor("face")
+ draw()
+
+ However, this has negative consequences in other circumstances, e.g.
+ with semi-transparent images (alpha < 1) and colorbar extensions;
+ therefore, this workaround is not used by default (see issue #1188).
+
+ """
+
+ if ax is None:
+ ax = getattr(mappable, "axes", None)
+
+ if cax is None:
+ if ax is None:
+ raise ValueError(
+ 'Unable to determine Axes to steal space for Colorbar. '
+ 'Either provide the *cax* argument to use as the Axes for '
+ 'the Colorbar, provide the *ax* argument to steal space '
+ 'from it, or add *mappable* to an Axes.')
+ fig = ( # Figure of first Axes; logic copied from make_axes.
+ [*ax.flat] if isinstance(ax, np.ndarray)
+ else [*ax] if np.iterable(ax)
+ else [ax])[0].get_figure(root=False)
+ current_ax = fig.gca()
+ if (fig.get_layout_engine() is not None and
+ not fig.get_layout_engine().colorbar_gridspec):
+ use_gridspec = False
+ if (use_gridspec
+ and isinstance(ax, mpl.axes._base._AxesBase)
+ and ax.get_subplotspec()):
+ cax, kwargs = cbar.make_axes_gridspec(ax, **kwargs)
+ else:
+ cax, kwargs = cbar.make_axes(ax, **kwargs)
+ # make_axes calls add_{axes,subplot} which changes gca; undo that.
+ fig.sca(current_ax)
+ cax.grid(visible=False, which='both', axis='both')
+
+ if (hasattr(mappable, "get_figure") and
+ (mappable_host_fig := mappable.get_figure(root=True)) is not None):
+ # Warn in case of mismatch
+ if mappable_host_fig is not self._root_figure:
+ _api.warn_external(
+ f'Adding colorbar to a different Figure '
+ f'{repr(mappable_host_fig)} than '
+ f'{repr(self._root_figure)} which '
+ f'fig.colorbar is called on.')
+
+ NON_COLORBAR_KEYS = [ # remove kws that cannot be passed to Colorbar
+ 'fraction', 'pad', 'shrink', 'aspect', 'anchor', 'panchor']
+ cb = cbar.Colorbar(cax, mappable, **{
+ k: v for k, v in kwargs.items() if k not in NON_COLORBAR_KEYS})
+ cax.get_figure(root=False).stale = True
+ return cb
+
+ def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
+ wspace=None, hspace=None):
+ """
+ Adjust the subplot layout parameters.
+
+ Unset parameters are left unmodified; initial values are given by
+ :rc:`figure.subplot.[name]`.
+
+ .. plot:: _embedded_plots/figure_subplots_adjust.py
+
+ Parameters
+ ----------
+ left : float, optional
+ The position of the left edge of the subplots,
+ as a fraction of the figure width.
+ right : float, optional
+ The position of the right edge of the subplots,
+ as a fraction of the figure width.
+ bottom : float, optional
+ The position of the bottom edge of the subplots,
+ as a fraction of the figure height.
+ top : float, optional
+ The position of the top edge of the subplots,
+ as a fraction of the figure height.
+ wspace : float, optional
+ The width of the padding between subplots,
+ as a fraction of the average Axes width.
+ hspace : float, optional
+ The height of the padding between subplots,
+ as a fraction of the average Axes height.
+ """
+ if (self.get_layout_engine() is not None and
+ not self.get_layout_engine().adjust_compatible):
+ _api.warn_external(
+ "This figure was using a layout engine that is "
+ "incompatible with subplots_adjust and/or tight_layout; "
+ "not calling subplots_adjust.")
+ return
+ self.subplotpars.update(left, bottom, right, top, wspace, hspace)
+ for ax in self.axes:
+ if ax.get_subplotspec() is not None:
+ ax._set_position(ax.get_subplotspec().get_position(self))
+ self.stale = True
+
+ def align_xlabels(self, axs=None):
+ """
+ Align the xlabels of subplots in the same subplot row if label
+ alignment is being done automatically (i.e. the label position is
+ not manually set).
+
+ Alignment persists for draw events after this is called.
+
+ If a label is on the bottom, it is aligned with labels on Axes that
+ also have their label on the bottom and that have the same
+ bottom-most subplot row. If the label is on the top,
+ it is aligned with labels on Axes with the same top-most row.
+
+ Parameters
+ ----------
+ axs : list of `~matplotlib.axes.Axes`
+ Optional list of (or `~numpy.ndarray`) `~matplotlib.axes.Axes`
+ to align the xlabels.
+ Default is to align all Axes on the figure.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.align_ylabels
+ matplotlib.figure.Figure.align_titles
+ matplotlib.figure.Figure.align_labels
+
+ Notes
+ -----
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
+ so that their `.SubplotSpec` positions correspond to figure positions.
+
+ Examples
+ --------
+ Example with rotated xtick labels::
+
+ fig, axs = plt.subplots(1, 2)
+ for tick in axs[0].get_xticklabels():
+ tick.set_rotation(55)
+ axs[0].set_xlabel('XLabel 0')
+ axs[1].set_xlabel('XLabel 1')
+ fig.align_xlabels()
+ """
+ if axs is None:
+ axs = self.axes
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
+ for ax in axs:
+ _log.debug(' Working on: %s', ax.get_xlabel())
+ rowspan = ax.get_subplotspec().rowspan
+ pos = ax.xaxis.get_label_position() # top or bottom
+ # Search through other Axes for label positions that are same as
+ # this one and that share the appropriate row number.
+ # Add to a grouper associated with each Axes of siblings.
+ # This list is inspected in `axis.draw` by
+ # `axis._update_label_position`.
+ for axc in axs:
+ if axc.xaxis.get_label_position() == pos:
+ rowspanc = axc.get_subplotspec().rowspan
+ if (pos == 'top' and rowspan.start == rowspanc.start or
+ pos == 'bottom' and rowspan.stop == rowspanc.stop):
+ # grouper for groups of xlabels to align
+ self._align_label_groups['x'].join(ax, axc)
+
+ def align_ylabels(self, axs=None):
+ """
+ Align the ylabels of subplots in the same subplot column if label
+ alignment is being done automatically (i.e. the label position is
+ not manually set).
+
+ Alignment persists for draw events after this is called.
+
+ If a label is on the left, it is aligned with labels on Axes that
+ also have their label on the left and that have the same
+ left-most subplot column. If the label is on the right,
+ it is aligned with labels on Axes with the same right-most column.
+
+ Parameters
+ ----------
+ axs : list of `~matplotlib.axes.Axes`
+ Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes`
+ to align the ylabels.
+ Default is to align all Axes on the figure.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.align_xlabels
+ matplotlib.figure.Figure.align_titles
+ matplotlib.figure.Figure.align_labels
+
+ Notes
+ -----
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
+ so that their `.SubplotSpec` positions correspond to figure positions.
+
+ Examples
+ --------
+ Example with large yticks labels::
+
+ fig, axs = plt.subplots(2, 1)
+ axs[0].plot(np.arange(0, 1000, 50))
+ axs[0].set_ylabel('YLabel 0')
+ axs[1].set_ylabel('YLabel 1')
+ fig.align_ylabels()
+ """
+ if axs is None:
+ axs = self.axes
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
+ for ax in axs:
+ _log.debug(' Working on: %s', ax.get_ylabel())
+ colspan = ax.get_subplotspec().colspan
+ pos = ax.yaxis.get_label_position() # left or right
+ # Search through other Axes for label positions that are same as
+ # this one and that share the appropriate column number.
+ # Add to a list associated with each Axes of siblings.
+ # This list is inspected in `axis.draw` by
+ # `axis._update_label_position`.
+ for axc in axs:
+ if axc.yaxis.get_label_position() == pos:
+ colspanc = axc.get_subplotspec().colspan
+ if (pos == 'left' and colspan.start == colspanc.start or
+ pos == 'right' and colspan.stop == colspanc.stop):
+ # grouper for groups of ylabels to align
+ self._align_label_groups['y'].join(ax, axc)
+
+ def align_titles(self, axs=None):
+ """
+ Align the titles of subplots in the same subplot row if title
+ alignment is being done automatically (i.e. the title position is
+ not manually set).
+
+ Alignment persists for draw events after this is called.
+
+ Parameters
+ ----------
+ axs : list of `~matplotlib.axes.Axes`
+ Optional list of (or ndarray) `~matplotlib.axes.Axes`
+ to align the titles.
+ Default is to align all Axes on the figure.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.align_xlabels
+ matplotlib.figure.Figure.align_ylabels
+ matplotlib.figure.Figure.align_labels
+
+ Notes
+ -----
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
+ so that their `.SubplotSpec` positions correspond to figure positions.
+
+ Examples
+ --------
+ Example with titles::
+
+ fig, axs = plt.subplots(1, 2)
+ axs[0].set_aspect('equal')
+ axs[0].set_title('Title 0')
+ axs[1].set_title('Title 1')
+ fig.align_titles()
+ """
+ if axs is None:
+ axs = self.axes
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
+ for ax in axs:
+ _log.debug(' Working on: %s', ax.get_title())
+ rowspan = ax.get_subplotspec().rowspan
+ for axc in axs:
+ rowspanc = axc.get_subplotspec().rowspan
+ if (rowspan.start == rowspanc.start):
+ self._align_label_groups['title'].join(ax, axc)
+
+ def align_labels(self, axs=None):
+ """
+ Align the xlabels and ylabels of subplots with the same subplots
+ row or column (respectively) if label alignment is being
+ done automatically (i.e. the label position is not manually set).
+
+ Alignment persists for draw events after this is called.
+
+ Parameters
+ ----------
+ axs : list of `~matplotlib.axes.Axes`
+ Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes`
+ to align the labels.
+ Default is to align all Axes on the figure.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.align_xlabels
+ matplotlib.figure.Figure.align_ylabels
+ matplotlib.figure.Figure.align_titles
+
+ Notes
+ -----
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
+ so that their `.SubplotSpec` positions correspond to figure positions.
+ """
+ self.align_xlabels(axs=axs)
+ self.align_ylabels(axs=axs)
+
+ def add_gridspec(self, nrows=1, ncols=1, **kwargs):
+ """
+ Low-level API for creating a `.GridSpec` that has this figure as a parent.
+
+ This is a low-level API, allowing you to create a gridspec and
+ subsequently add subplots based on the gridspec. Most users do
+ not need that freedom and should use the higher-level methods
+ `~.Figure.subplots` or `~.Figure.subplot_mosaic`.
+
+ Parameters
+ ----------
+ nrows : int, default: 1
+ Number of rows in grid.
+
+ ncols : int, default: 1
+ Number of columns in grid.
+
+ Returns
+ -------
+ `.GridSpec`
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Keyword arguments are passed to `.GridSpec`.
+
+ See Also
+ --------
+ matplotlib.pyplot.subplots
+
+ Examples
+ --------
+ Adding a subplot that spans two rows::
+
+ fig = plt.figure()
+ gs = fig.add_gridspec(2, 2)
+ ax1 = fig.add_subplot(gs[0, 0])
+ ax2 = fig.add_subplot(gs[1, 0])
+ # spans two rows:
+ ax3 = fig.add_subplot(gs[:, 1])
+
+ """
+
+ _ = kwargs.pop('figure', None) # pop in case user has added this...
+ gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)
+ return gs
+
+ def subfigures(self, nrows=1, ncols=1, squeeze=True,
+ wspace=None, hspace=None,
+ width_ratios=None, height_ratios=None,
+ **kwargs):
+ """
+ Add a set of subfigures to this figure or subfigure.
+
+ A subfigure has the same artist methods as a figure, and is logically
+ the same as a figure, but cannot print itself.
+ See :doc:`/gallery/subplots_axes_and_figures/subfigures`.
+
+ .. versionchanged:: 3.10
+ subfigures are now added in row-major order.
+
+ Parameters
+ ----------
+ nrows, ncols : int, default: 1
+ Number of rows/columns of the subfigure grid.
+
+ squeeze : bool, default: True
+ If True, extra dimensions are squeezed out from the returned
+ array of subfigures.
+
+ wspace, hspace : float, default: None
+ The amount of width/height reserved for space between subfigures,
+ expressed as a fraction of the average subfigure width/height.
+ If not given, the values will be inferred from rcParams if using
+ constrained layout (see `~.ConstrainedLayoutEngine`), or zero if
+ not using a layout engine.
+
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width.
+
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height.
+ """
+ gs = GridSpec(nrows=nrows, ncols=ncols, figure=self,
+ wspace=wspace, hspace=hspace,
+ width_ratios=width_ratios,
+ height_ratios=height_ratios,
+ left=0, right=1, bottom=0, top=1)
+
+ sfarr = np.empty((nrows, ncols), dtype=object)
+ for i in range(nrows):
+ for j in range(ncols):
+ sfarr[i, j] = self.add_subfigure(gs[i, j], **kwargs)
+
+ if self.get_layout_engine() is None and (wspace is not None or
+ hspace is not None):
+ # Gridspec wspace and hspace is ignored on subfigure instantiation,
+ # and no space is left. So need to account for it here if required.
+ bottoms, tops, lefts, rights = gs.get_grid_positions(self)
+ for sfrow, bottom, top in zip(sfarr, bottoms, tops):
+ for sf, left, right in zip(sfrow, lefts, rights):
+ bbox = Bbox.from_extents(left, bottom, right, top)
+ sf._redo_transform_rel_fig(bbox=bbox)
+
+ if squeeze:
+ # Discarding unneeded dimensions that equal 1. If we only have one
+ # subfigure, just return it instead of a 1-element array.
+ return sfarr.item() if sfarr.size == 1 else sfarr.squeeze()
+ else:
+ # Returned axis array will be always 2-d, even if nrows=ncols=1.
+ return sfarr
+
+ def add_subfigure(self, subplotspec, **kwargs):
+ """
+ Add a `.SubFigure` to the figure as part of a subplot arrangement.
+
+ Parameters
+ ----------
+ subplotspec : `.gridspec.SubplotSpec`
+ Defines the region in a parent gridspec where the subfigure will
+ be placed.
+
+ Returns
+ -------
+ `.SubFigure`
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Are passed to the `.SubFigure` object.
+
+ See Also
+ --------
+ .Figure.subfigures
+ """
+ sf = SubFigure(self, subplotspec, **kwargs)
+ self.subfigs += [sf]
+ sf._remove_method = self.subfigs.remove
+ sf.stale_callback = _stale_figure_callback
+ self.stale = True
+ return sf
+
+ def sca(self, a):
+ """Set the current Axes to be *a* and return *a*."""
+ self._axstack.bubble(a)
+ self._axobservers.process("_axes_change_event", self)
+ return a
+
+ def gca(self):
+ """
+ Get the current Axes.
+
+ If there is currently no Axes on this Figure, a new one is created
+ using `.Figure.add_subplot`. (To test whether there is currently an
+ Axes on a Figure, check whether ``figure.axes`` is empty. To test
+ whether there is currently a Figure on the pyplot figure stack, check
+ whether `.pyplot.get_fignums()` is empty.)
+ """
+ ax = self._axstack.current()
+ return ax if ax is not None else self.add_subplot()
+
+ def _gci(self):
+ # Helper for `~matplotlib.pyplot.gci`. Do not use elsewhere.
+ """
+ Get the current colorable artist.
+
+ Specifically, returns the current `.ScalarMappable` instance (`.Image`
+ created by `imshow` or `figimage`, `.Collection` created by `pcolor` or
+ `scatter`, etc.), or *None* if no such instance has been defined.
+
+ The current image is an attribute of the current Axes, or the nearest
+ earlier Axes in the current figure that contains an image.
+
+ Notes
+ -----
+ Historically, the only colorable artists were images; hence the name
+ ``gci`` (get current image).
+ """
+ # Look first for an image in the current Axes.
+ ax = self._axstack.current()
+ if ax is None:
+ return None
+ im = ax._gci()
+ if im is not None:
+ return im
+ # If there is no image in the current Axes, search for
+ # one in a previously created Axes. Whether this makes
+ # sense is debatable, but it is the documented behavior.
+ for ax in reversed(self.axes):
+ im = ax._gci()
+ if im is not None:
+ return im
+ return None
+
+ def _process_projection_requirements(self, *, axes_class=None, polar=False,
+ projection=None, **kwargs):
+ """
+ Handle the args/kwargs to add_axes/add_subplot/gca, returning::
+
+ (axes_proj_class, proj_class_kwargs)
+
+ which can be used for new Axes initialization/identification.
+ """
+ if axes_class is not None:
+ if polar or projection is not None:
+ raise ValueError(
+ "Cannot combine 'axes_class' and 'projection' or 'polar'")
+ projection_class = axes_class
+ else:
+
+ if polar:
+ if projection is not None and projection != 'polar':
+ raise ValueError(
+ f"polar={polar}, yet projection={projection!r}. "
+ "Only one of these arguments should be supplied."
+ )
+ projection = 'polar'
+
+ if isinstance(projection, str) or projection is None:
+ projection_class = projections.get_projection_class(projection)
+ elif hasattr(projection, '_as_mpl_axes'):
+ projection_class, extra_kwargs = projection._as_mpl_axes()
+ kwargs.update(**extra_kwargs)
+ else:
+ raise TypeError(
+ f"projection must be a string, None or implement a "
+ f"_as_mpl_axes method, not {projection!r}")
+ return projection_class, kwargs
+
+ def get_default_bbox_extra_artists(self):
+ """
+ Return a list of Artists typically used in `.Figure.get_tightbbox`.
+ """
+ bbox_artists = [artist for artist in self.get_children()
+ if (artist.get_visible() and artist.get_in_layout())]
+ for ax in self.axes:
+ if ax.get_visible():
+ bbox_artists.extend(ax.get_default_bbox_extra_artists())
+ return bbox_artists
+
+ def get_tightbbox(self, renderer=None, *, bbox_extra_artists=None):
+ """
+ Return a (tight) bounding box of the figure *in inches*.
+
+ Note that `.FigureBase` differs from all other artists, which return
+ their `.Bbox` in pixels.
+
+ Artists that have ``artist.set_in_layout(False)`` are not included
+ in the bbox.
+
+ Parameters
+ ----------
+ renderer : `.RendererBase` subclass
+ Renderer that will be used to draw the figures (i.e.
+ ``fig.canvas.get_renderer()``)
+
+ bbox_extra_artists : list of `.Artist` or ``None``
+ List of artists to include in the tight bounding box. If
+ ``None`` (default), then all artist children of each Axes are
+ included in the tight bounding box.
+
+ Returns
+ -------
+ `.BboxBase`
+ containing the bounding box (in figure inches).
+ """
+
+ if renderer is None:
+ renderer = self.get_figure(root=True)._get_renderer()
+
+ bb = []
+ if bbox_extra_artists is None:
+ artists = [artist for artist in self.get_children()
+ if (artist not in self.axes and artist.get_visible()
+ and artist.get_in_layout())]
+ else:
+ artists = bbox_extra_artists
+
+ for a in artists:
+ bbox = a.get_tightbbox(renderer)
+ if bbox is not None:
+ bb.append(bbox)
+
+ for ax in self.axes:
+ if ax.get_visible():
+ # some Axes don't take the bbox_extra_artists kwarg so we
+ # need this conditional....
+ try:
+ bbox = ax.get_tightbbox(
+ renderer, bbox_extra_artists=bbox_extra_artists)
+ except TypeError:
+ bbox = ax.get_tightbbox(renderer)
+ bb.append(bbox)
+ bb = [b for b in bb
+ if (np.isfinite(b.width) and np.isfinite(b.height)
+ and (b.width != 0 or b.height != 0))]
+
+ isfigure = hasattr(self, 'bbox_inches')
+ if len(bb) == 0:
+ if isfigure:
+ return self.bbox_inches
+ else:
+ # subfigures do not have bbox_inches, but do have a bbox
+ bb = [self.bbox]
+
+ _bbox = Bbox.union(bb)
+
+ if isfigure:
+ # transform from pixels to inches...
+ _bbox = TransformedBbox(_bbox, self.dpi_scale_trans.inverted())
+
+ return _bbox
+
+ @staticmethod
+ def _norm_per_subplot_kw(per_subplot_kw):
+ expanded = {}
+ for k, v in per_subplot_kw.items():
+ if isinstance(k, tuple):
+ for sub_key in k:
+ if sub_key in expanded:
+ raise ValueError(f'The key {sub_key!r} appears multiple times.')
+ expanded[sub_key] = v
+ else:
+ if k in expanded:
+ raise ValueError(f'The key {k!r} appears multiple times.')
+ expanded[k] = v
+ return expanded
+
+ @staticmethod
+ def _normalize_grid_string(layout):
+ if '\n' not in layout:
+ # single-line string
+ return [list(ln) for ln in layout.split(';')]
+ else:
+ # multi-line string
+ layout = inspect.cleandoc(layout)
+ return [list(ln) for ln in layout.strip('\n').split('\n')]
+
+ def subplot_mosaic(self, mosaic, *, sharex=False, sharey=False,
+ width_ratios=None, height_ratios=None,
+ empty_sentinel='.',
+ subplot_kw=None, per_subplot_kw=None, gridspec_kw=None):
+ """
+ Build a layout of Axes based on ASCII art or nested lists.
+
+ This is a helper function to build complex GridSpec layouts visually.
+
+ See :ref:`mosaic`
+ for an example and full API documentation
+
+ Parameters
+ ----------
+ mosaic : list of list of {hashable or nested} or str
+
+ A visual layout of how you want your Axes to be arranged
+ labeled as strings. For example ::
+
+ x = [['A panel', 'A panel', 'edge'],
+ ['C panel', '.', 'edge']]
+
+ produces 4 Axes:
+
+ - 'A panel' which is 1 row high and spans the first two columns
+ - 'edge' which is 2 rows high and is on the right edge
+ - 'C panel' which in 1 row and 1 column wide in the bottom left
+ - a blank space 1 row and 1 column wide in the bottom center
+
+ Any of the entries in the layout can be a list of lists
+ of the same form to create nested layouts.
+
+ If input is a str, then it can either be a multi-line string of
+ the form ::
+
+ '''
+ AAE
+ C.E
+ '''
+
+ where each character is a column and each line is a row. Or it
+ can be a single-line string where rows are separated by ``;``::
+
+ 'AB;CC'
+
+ The string notation allows only single character Axes labels and
+ does not support nesting but is very terse.
+
+ The Axes identifiers may be `str` or a non-iterable hashable
+ object (e.g. `tuple` s may not be used).
+
+ sharex, sharey : bool, default: False
+ If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared
+ among all subplots. In that case, tick label visibility and axis
+ units behave as for `subplots`. If False, each subplot's x- or
+ y-axis will be independent.
+
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width. Equivalent
+ to ``gridspec_kw={'width_ratios': [...]}``. In the case of nested
+ layouts, this argument applies only to the outer layout.
+
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height. Equivalent
+ to ``gridspec_kw={'height_ratios': [...]}``. In the case of nested
+ layouts, this argument applies only to the outer layout.
+
+ subplot_kw : dict, optional
+ Dictionary with keywords passed to the `.Figure.add_subplot` call
+ used to create each subplot. These values may be overridden by
+ values in *per_subplot_kw*.
+
+ per_subplot_kw : dict, optional
+ A dictionary mapping the Axes identifiers or tuples of identifiers
+ to a dictionary of keyword arguments to be passed to the
+ `.Figure.add_subplot` call used to create each subplot. The values
+ in these dictionaries have precedence over the values in
+ *subplot_kw*.
+
+ If *mosaic* is a string, and thus all keys are single characters,
+ it is possible to use a single string instead of a tuple as keys;
+ i.e. ``"AB"`` is equivalent to ``("A", "B")``.
+
+ .. versionadded:: 3.7
+
+ gridspec_kw : dict, optional
+ Dictionary with keywords passed to the `.GridSpec` constructor used
+ to create the grid the subplots are placed on. In the case of
+ nested layouts, this argument applies only to the outer layout.
+ For more complex layouts, users should use `.Figure.subfigures`
+ to create the nesting.
+
+ empty_sentinel : object, optional
+ Entry in the layout to mean "leave this space empty". Defaults
+ to ``'.'``. Note, if *layout* is a string, it is processed via
+ `inspect.cleandoc` to remove leading white space, which may
+ interfere with using white-space as the empty sentinel.
+
+ Returns
+ -------
+ dict[label, Axes]
+ A dictionary mapping the labels to the Axes objects. The order of
+ the Axes is left-to-right and top-to-bottom of their position in the
+ total layout.
+
+ """
+ subplot_kw = subplot_kw or {}
+ gridspec_kw = dict(gridspec_kw or {})
+ per_subplot_kw = per_subplot_kw or {}
+
+ if height_ratios is not None:
+ if 'height_ratios' in gridspec_kw:
+ raise ValueError("'height_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['height_ratios'] = height_ratios
+ if width_ratios is not None:
+ if 'width_ratios' in gridspec_kw:
+ raise ValueError("'width_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['width_ratios'] = width_ratios
+
+ # special-case string input
+ if isinstance(mosaic, str):
+ mosaic = self._normalize_grid_string(mosaic)
+ per_subplot_kw = {
+ tuple(k): v for k, v in per_subplot_kw.items()
+ }
+
+ per_subplot_kw = self._norm_per_subplot_kw(per_subplot_kw)
+
+ # Only accept strict bools to allow a possible future API expansion.
+ _api.check_isinstance(bool, sharex=sharex, sharey=sharey)
+
+ def _make_array(inp):
+ """
+ Convert input into 2D array
+
+ We need to have this internal function rather than
+ ``np.asarray(..., dtype=object)`` so that a list of lists
+ of lists does not get converted to an array of dimension > 2.
+
+ Returns
+ -------
+ 2D object array
+ """
+ r0, *rest = inp
+ if isinstance(r0, str):
+ raise ValueError('List mosaic specification must be 2D')
+ for j, r in enumerate(rest, start=1):
+ if isinstance(r, str):
+ raise ValueError('List mosaic specification must be 2D')
+ if len(r0) != len(r):
+ raise ValueError(
+ "All of the rows must be the same length, however "
+ f"the first row ({r0!r}) has length {len(r0)} "
+ f"and row {j} ({r!r}) has length {len(r)}."
+ )
+ out = np.zeros((len(inp), len(r0)), dtype=object)
+ for j, r in enumerate(inp):
+ for k, v in enumerate(r):
+ out[j, k] = v
+ return out
+
+ def _identify_keys_and_nested(mosaic):
+ """
+ Given a 2D object array, identify unique IDs and nested mosaics
+
+ Parameters
+ ----------
+ mosaic : 2D object array
+
+ Returns
+ -------
+ unique_ids : tuple
+ The unique non-sub mosaic entries in this mosaic
+ nested : dict[tuple[int, int], 2D object array]
+ """
+ # make sure we preserve the user supplied order
+ unique_ids = cbook._OrderedSet()
+ nested = {}
+ for j, row in enumerate(mosaic):
+ for k, v in enumerate(row):
+ if v == empty_sentinel:
+ continue
+ elif not cbook.is_scalar_or_string(v):
+ nested[(j, k)] = _make_array(v)
+ else:
+ unique_ids.add(v)
+
+ return tuple(unique_ids), nested
+
+ def _do_layout(gs, mosaic, unique_ids, nested):
+ """
+ Recursively do the mosaic.
+
+ Parameters
+ ----------
+ gs : GridSpec
+ mosaic : 2D object array
+ The input converted to a 2D array for this level.
+ unique_ids : tuple
+ The identified scalar labels at this level of nesting.
+ nested : dict[tuple[int, int]], 2D object array
+ The identified nested mosaics, if any.
+
+ Returns
+ -------
+ dict[label, Axes]
+ A flat dict of all of the Axes created.
+ """
+ output = dict()
+
+ # we need to merge together the Axes at this level and the Axes
+ # in the (recursively) nested sub-mosaics so that we can add
+ # them to the figure in the "natural" order if you were to
+ # ravel in c-order all of the Axes that will be created
+ #
+ # This will stash the upper left index of each object (axes or
+ # nested mosaic) at this level
+ this_level = dict()
+
+ # go through the unique keys,
+ for name in unique_ids:
+ # sort out where each axes starts/ends
+ indx = np.argwhere(mosaic == name)
+ start_row, start_col = np.min(indx, axis=0)
+ end_row, end_col = np.max(indx, axis=0) + 1
+ # and construct the slice object
+ slc = (slice(start_row, end_row), slice(start_col, end_col))
+ # some light error checking
+ if (mosaic[slc] != name).any():
+ raise ValueError(
+ f"While trying to layout\n{mosaic!r}\n"
+ f"we found that the label {name!r} specifies a "
+ "non-rectangular or non-contiguous area.")
+ # and stash this slice for later
+ this_level[(start_row, start_col)] = (name, slc, 'axes')
+
+ # do the same thing for the nested mosaics (simpler because these
+ # cannot be spans yet!)
+ for (j, k), nested_mosaic in nested.items():
+ this_level[(j, k)] = (None, nested_mosaic, 'nested')
+
+ # now go through the things in this level and add them
+ # in order left-to-right top-to-bottom
+ for key in sorted(this_level):
+ name, arg, method = this_level[key]
+ # we are doing some hokey function dispatch here based
+ # on the 'method' string stashed above to sort out if this
+ # element is an Axes or a nested mosaic.
+ if method == 'axes':
+ slc = arg
+ # add a single Axes
+ if name in output:
+ raise ValueError(f"There are duplicate keys {name} "
+ f"in the layout\n{mosaic!r}")
+ ax = self.add_subplot(
+ gs[slc], **{
+ 'label': str(name),
+ **subplot_kw,
+ **per_subplot_kw.get(name, {})
+ }
+ )
+ output[name] = ax
+ elif method == 'nested':
+ nested_mosaic = arg
+ j, k = key
+ # recursively add the nested mosaic
+ rows, cols = nested_mosaic.shape
+ nested_output = _do_layout(
+ gs[j, k].subgridspec(rows, cols),
+ nested_mosaic,
+ *_identify_keys_and_nested(nested_mosaic)
+ )
+ overlap = set(output) & set(nested_output)
+ if overlap:
+ raise ValueError(
+ f"There are duplicate keys {overlap} "
+ f"between the outer layout\n{mosaic!r}\n"
+ f"and the nested layout\n{nested_mosaic}"
+ )
+ output.update(nested_output)
+ else:
+ raise RuntimeError("This should never happen")
+ return output
+
+ mosaic = _make_array(mosaic)
+ rows, cols = mosaic.shape
+ gs = self.add_gridspec(rows, cols, **gridspec_kw)
+ ret = _do_layout(gs, mosaic, *_identify_keys_and_nested(mosaic))
+ ax0 = next(iter(ret.values()))
+ for ax in ret.values():
+ if sharex:
+ ax.sharex(ax0)
+ ax._label_outer_xaxis(skip_non_rectangular_axes=True)
+ if sharey:
+ ax.sharey(ax0)
+ ax._label_outer_yaxis(skip_non_rectangular_axes=True)
+ if extra := set(per_subplot_kw) - set(ret):
+ raise ValueError(
+ f"The keys {extra} are in *per_subplot_kw* "
+ "but not in the mosaic."
+ )
+ return ret
+
+ def _set_artist_props(self, a):
+ if a != self:
+ a.set_figure(self)
+ a.stale_callback = _stale_figure_callback
+ a.set_transform(self.transSubfigure)
+
+
+@_docstring.interpd
+class SubFigure(FigureBase):
+ """
+ Logical figure that can be placed inside a figure.
+
+ See :ref:`figure-api-subfigure` for an index of methods on this class.
+ Typically instantiated using `.Figure.add_subfigure` or
+ `.SubFigure.add_subfigure`, or `.SubFigure.subfigures`. A subfigure has
+ the same methods as a figure except for those particularly tied to the size
+ or dpi of the figure, and is confined to a prescribed region of the figure.
+ For example the following puts two subfigures side-by-side::
+
+ fig = plt.figure()
+ sfigs = fig.subfigures(1, 2)
+ axsL = sfigs[0].subplots(1, 2)
+ axsR = sfigs[1].subplots(2, 1)
+
+ See :doc:`/gallery/subplots_axes_and_figures/subfigures`
+ """
+
+ def __init__(self, parent, subplotspec, *,
+ facecolor=None,
+ edgecolor=None,
+ linewidth=0.0,
+ frameon=None,
+ **kwargs):
+ """
+ Parameters
+ ----------
+ parent : `.Figure` or `.SubFigure`
+ Figure or subfigure that contains the SubFigure. SubFigures
+ can be nested.
+
+ subplotspec : `.gridspec.SubplotSpec`
+ Defines the region in a parent gridspec where the subfigure will
+ be placed.
+
+ facecolor : default: ``"none"``
+ The figure patch face color; transparent by default.
+
+ edgecolor : default: :rc:`figure.edgecolor`
+ The figure patch edge color.
+
+ linewidth : float
+ The linewidth of the frame (i.e. the edge linewidth of the figure
+ patch).
+
+ frameon : bool, default: :rc:`figure.frameon`
+ If ``False``, suppress drawing the figure background patch.
+
+ Other Parameters
+ ----------------
+ **kwargs : `.SubFigure` properties, optional
+
+ %(SubFigure:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ if facecolor is None:
+ facecolor = "none"
+ if edgecolor is None:
+ edgecolor = mpl.rcParams['figure.edgecolor']
+ if frameon is None:
+ frameon = mpl.rcParams['figure.frameon']
+
+ self._subplotspec = subplotspec
+ self._parent = parent
+ self._root_figure = parent._root_figure
+
+ # subfigures use the parent axstack
+ self._axstack = parent._axstack
+ self.subplotpars = parent.subplotpars
+ self.dpi_scale_trans = parent.dpi_scale_trans
+ self._axobservers = parent._axobservers
+ self.transFigure = parent.transFigure
+ self.bbox_relative = Bbox.null()
+ self._redo_transform_rel_fig()
+ self.figbbox = self._parent.figbbox
+ self.bbox = TransformedBbox(self.bbox_relative,
+ self._parent.transSubfigure)
+ self.transSubfigure = BboxTransformTo(self.bbox)
+
+ self.patch = Rectangle(
+ xy=(0, 0), width=1, height=1, visible=frameon,
+ facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
+ # Don't let the figure patch influence bbox calculation.
+ in_layout=False, transform=self.transSubfigure)
+ self._set_artist_props(self.patch)
+ self.patch.set_antialiased(False)
+
+ @property
+ def canvas(self):
+ return self._parent.canvas
+
+ @property
+ def dpi(self):
+ return self._parent.dpi
+
+ @dpi.setter
+ def dpi(self, value):
+ self._parent.dpi = value
+
+ def get_dpi(self):
+ """
+ Return the resolution of the parent figure in dots-per-inch as a float.
+ """
+ return self._parent.dpi
+
+ def set_dpi(self, val):
+ """
+ Set the resolution of parent figure in dots-per-inch.
+
+ Parameters
+ ----------
+ val : float
+ """
+ self._parent.dpi = val
+ self.stale = True
+
+ def _get_renderer(self):
+ return self._parent._get_renderer()
+
+ def _redo_transform_rel_fig(self, bbox=None):
+ """
+ Make the transSubfigure bbox relative to Figure transform.
+
+ Parameters
+ ----------
+ bbox : bbox or None
+ If not None, then the bbox is used for relative bounding box.
+ Otherwise, it is calculated from the subplotspec.
+ """
+ if bbox is not None:
+ self.bbox_relative.p0 = bbox.p0
+ self.bbox_relative.p1 = bbox.p1
+ return
+ # need to figure out *where* this subplotspec is.
+ gs = self._subplotspec.get_gridspec()
+ wr = np.asarray(gs.get_width_ratios())
+ hr = np.asarray(gs.get_height_ratios())
+ dx = wr[self._subplotspec.colspan].sum() / wr.sum()
+ dy = hr[self._subplotspec.rowspan].sum() / hr.sum()
+ x0 = wr[:self._subplotspec.colspan.start].sum() / wr.sum()
+ y0 = 1 - hr[:self._subplotspec.rowspan.stop].sum() / hr.sum()
+ self.bbox_relative.p0 = (x0, y0)
+ self.bbox_relative.p1 = (x0 + dx, y0 + dy)
+
+ def get_constrained_layout(self):
+ """
+ Return whether constrained layout is being used.
+
+ See :ref:`constrainedlayout_guide`.
+ """
+ return self._parent.get_constrained_layout()
+
+ def get_constrained_layout_pads(self, relative=False):
+ """
+ Get padding for ``constrained_layout``.
+
+ Returns a list of ``w_pad, h_pad`` in inches and
+ ``wspace`` and ``hspace`` as fractions of the subplot.
+
+ See :ref:`constrainedlayout_guide`.
+
+ Parameters
+ ----------
+ relative : bool
+ If `True`, then convert from inches to figure relative.
+ """
+ return self._parent.get_constrained_layout_pads(relative=relative)
+
+ def get_layout_engine(self):
+ return self._parent.get_layout_engine()
+
+ @property
+ def axes(self):
+ """
+ List of Axes in the SubFigure. You can access and modify the Axes
+ in the SubFigure through this list.
+
+ Modifying this list has no effect. Instead, use `~.SubFigure.add_axes`,
+ `~.SubFigure.add_subplot` or `~.SubFigure.delaxes` to add or remove an
+ Axes.
+
+ Note: The `.SubFigure.axes` property and `~.SubFigure.get_axes` method
+ are equivalent.
+ """
+ return self._localaxes[:]
+
+ get_axes = axes.fget
+
+ def draw(self, renderer):
+ # docstring inherited
+
+ # draw the figure bounding box, perhaps none for white figure
+ if not self.get_visible():
+ return
+
+ artists = self._get_draw_artists(renderer)
+
+ try:
+ renderer.open_group('subfigure', gid=self.get_gid())
+ self.patch.draw(renderer)
+ mimage._draw_list_compositing_images(
+ renderer, self, artists, self.get_figure(root=True).suppressComposite)
+ renderer.close_group('subfigure')
+
+ finally:
+ self.stale = False
+
+
+@_docstring.interpd
+class Figure(FigureBase):
+ """
+ The top level container for all the plot elements.
+
+ See `matplotlib.figure` for an index of class methods.
+
+ Attributes
+ ----------
+ patch
+ The `.Rectangle` instance representing the figure background patch.
+
+ suppressComposite
+ For multiple images, the figure will make composite images
+ depending on the renderer option_image_nocomposite function. If
+ *suppressComposite* is a boolean, this will override the renderer.
+ """
+
+ # we want to cache the fonts and mathtext at a global level so that when
+ # multiple figures are created we can reuse them. This helps with a bug on
+ # windows where the creation of too many figures leads to too many open
+ # file handles and improves the performance of parsing mathtext. However,
+ # these global caches are not thread safe. The solution here is to let the
+ # Figure acquire a shared lock at the start of the draw, and release it when it
+ # is done. This allows multiple renderers to share the cached fonts and
+ # parsed text, but only one figure can draw at a time and so the font cache
+ # and mathtext cache are used by only one renderer at a time.
+
+ _render_lock = threading.RLock()
+
+ def __str__(self):
+ return "Figure(%gx%g)" % tuple(self.bbox.size)
+
+ def __repr__(self):
+ return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format(
+ clsname=self.__class__.__name__,
+ h=self.bbox.size[0], w=self.bbox.size[1],
+ naxes=len(self.axes),
+ )
+
+ def __init__(self,
+ figsize=None,
+ dpi=None,
+ *,
+ facecolor=None,
+ edgecolor=None,
+ linewidth=0.0,
+ frameon=None,
+ subplotpars=None, # rc figure.subplot.*
+ tight_layout=None, # rc figure.autolayout
+ constrained_layout=None, # rc figure.constrained_layout.use
+ layout=None,
+ **kwargs
+ ):
+ """
+ Parameters
+ ----------
+ figsize : 2-tuple of floats, default: :rc:`figure.figsize`
+ Figure dimension ``(width, height)`` in inches.
+
+ dpi : float, default: :rc:`figure.dpi`
+ Dots per inch.
+
+ facecolor : default: :rc:`figure.facecolor`
+ The figure patch facecolor.
+
+ edgecolor : default: :rc:`figure.edgecolor`
+ The figure patch edge color.
+
+ linewidth : float
+ The linewidth of the frame (i.e. the edge linewidth of the figure
+ patch).
+
+ frameon : bool, default: :rc:`figure.frameon`
+ If ``False``, suppress drawing the figure background patch.
+
+ subplotpars : `~matplotlib.gridspec.SubplotParams`
+ Subplot parameters. If not given, the default subplot
+ parameters :rc:`figure.subplot.*` are used.
+
+ tight_layout : bool or dict, default: :rc:`figure.autolayout`
+ Whether to use the tight layout mechanism. See `.set_tight_layout`.
+
+ .. admonition:: Discouraged
+
+ The use of this parameter is discouraged. Please use
+ ``layout='tight'`` instead for the common case of
+ ``tight_layout=True`` and use `.set_tight_layout` otherwise.
+
+ constrained_layout : bool, default: :rc:`figure.constrained_layout.use`
+ This is equal to ``layout='constrained'``.
+
+ .. admonition:: Discouraged
+
+ The use of this parameter is discouraged. Please use
+ ``layout='constrained'`` instead.
+
+ layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, \
+None}, default: None
+ The layout mechanism for positioning of plot elements to avoid
+ overlapping Axes decorations (labels, ticks, etc). Note that
+ layout managers can have significant performance penalties.
+
+ - 'constrained': The constrained layout solver adjusts Axes sizes
+ to avoid overlapping Axes decorations. Can handle complex plot
+ layouts and colorbars, and is thus recommended.
+
+ See :ref:`constrainedlayout_guide` for examples.
+
+ - 'compressed': uses the same algorithm as 'constrained', but
+ removes extra space between fixed-aspect-ratio Axes. Best for
+ simple grids of Axes.
+
+ - 'tight': Use the tight layout mechanism. This is a relatively
+ simple algorithm that adjusts the subplot parameters so that
+ decorations do not overlap.
+
+ See :ref:`tight_layout_guide` for examples.
+
+ - 'none': Do not use a layout engine.
+
+ - A `.LayoutEngine` instance. Builtin layout classes are
+ `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily
+ accessible by 'constrained' and 'tight'. Passing an instance
+ allows third parties to provide their own layout engine.
+
+ If not given, fall back to using the parameters *tight_layout* and
+ *constrained_layout*, including their config defaults
+ :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`.
+
+ Other Parameters
+ ----------------
+ **kwargs : `.Figure` properties, optional
+
+ %(Figure:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._root_figure = self
+ self._layout_engine = None
+
+ if layout is not None:
+ if (tight_layout is not None):
+ _api.warn_external(
+ "The Figure parameters 'layout' and 'tight_layout' cannot "
+ "be used together. Please use 'layout' only.")
+ if (constrained_layout is not None):
+ _api.warn_external(
+ "The Figure parameters 'layout' and 'constrained_layout' "
+ "cannot be used together. Please use 'layout' only.")
+ self.set_layout_engine(layout=layout)
+ elif tight_layout is not None:
+ if constrained_layout is not None:
+ _api.warn_external(
+ "The Figure parameters 'tight_layout' and "
+ "'constrained_layout' cannot be used together. Please use "
+ "'layout' parameter")
+ self.set_layout_engine(layout='tight')
+ if isinstance(tight_layout, dict):
+ self.get_layout_engine().set(**tight_layout)
+ elif constrained_layout is not None:
+ if isinstance(constrained_layout, dict):
+ self.set_layout_engine(layout='constrained')
+ self.get_layout_engine().set(**constrained_layout)
+ elif constrained_layout:
+ self.set_layout_engine(layout='constrained')
+
+ else:
+ # everything is None, so use default:
+ self.set_layout_engine(layout=layout)
+
+ # Callbacks traditionally associated with the canvas (and exposed with
+ # a proxy property), but that actually need to be on the figure for
+ # pickling.
+ self._canvas_callbacks = cbook.CallbackRegistry(
+ signals=FigureCanvasBase.events)
+ connect = self._canvas_callbacks._connect_picklable
+ self._mouse_key_ids = [
+ connect('key_press_event', backend_bases._key_handler),
+ connect('key_release_event', backend_bases._key_handler),
+ connect('key_release_event', backend_bases._key_handler),
+ connect('button_press_event', backend_bases._mouse_handler),
+ connect('button_release_event', backend_bases._mouse_handler),
+ connect('scroll_event', backend_bases._mouse_handler),
+ connect('motion_notify_event', backend_bases._mouse_handler),
+ ]
+ self._button_pick_id = connect('button_press_event', self.pick)
+ self._scroll_pick_id = connect('scroll_event', self.pick)
+
+ if figsize is None:
+ figsize = mpl.rcParams['figure.figsize']
+ if dpi is None:
+ dpi = mpl.rcParams['figure.dpi']
+ if facecolor is None:
+ facecolor = mpl.rcParams['figure.facecolor']
+ if edgecolor is None:
+ edgecolor = mpl.rcParams['figure.edgecolor']
+ if frameon is None:
+ frameon = mpl.rcParams['figure.frameon']
+
+ if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any():
+ raise ValueError('figure size must be positive finite not '
+ f'{figsize}')
+ self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
+
+ self.dpi_scale_trans = Affine2D().scale(dpi)
+ # do not use property as it will trigger
+ self._dpi = dpi
+ self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
+ self.figbbox = self.bbox
+ self.transFigure = BboxTransformTo(self.bbox)
+ self.transSubfigure = self.transFigure
+
+ self.patch = Rectangle(
+ xy=(0, 0), width=1, height=1, visible=frameon,
+ facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
+ # Don't let the figure patch influence bbox calculation.
+ in_layout=False)
+ self._set_artist_props(self.patch)
+ self.patch.set_antialiased(False)
+
+ FigureCanvasBase(self) # Set self.canvas.
+
+ if subplotpars is None:
+ subplotpars = SubplotParams()
+
+ self.subplotpars = subplotpars
+
+ self._axstack = _AxesStack() # track all figure Axes and current Axes
+ self.clear()
+
+ def pick(self, mouseevent):
+ if not self.canvas.widgetlock.locked():
+ super().pick(mouseevent)
+
+ def _check_layout_engines_compat(self, old, new):
+ """
+ Helper for set_layout engine
+
+ If the figure has used the old engine and added a colorbar then the
+ value of colorbar_gridspec must be the same on the new engine.
+ """
+ if old is None or new is None:
+ return True
+ if old.colorbar_gridspec == new.colorbar_gridspec:
+ return True
+ # colorbar layout different, so check if any colorbars are on the
+ # figure...
+ for ax in self.axes:
+ if hasattr(ax, '_colorbar'):
+ # colorbars list themselves as a colorbar.
+ return False
+ return True
+
+ def set_layout_engine(self, layout=None, **kwargs):
+ """
+ Set the layout engine for this figure.
+
+ Parameters
+ ----------
+ layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}
+
+ - 'constrained' will use `~.ConstrainedLayoutEngine`
+ - 'compressed' will also use `~.ConstrainedLayoutEngine`, but with
+ a correction that attempts to make a good layout for fixed-aspect
+ ratio Axes.
+ - 'tight' uses `~.TightLayoutEngine`
+ - 'none' removes layout engine.
+
+ If a `.LayoutEngine` instance, that instance will be used.
+
+ If `None`, the behavior is controlled by :rc:`figure.autolayout`
+ (which if `True` behaves as if 'tight' was passed) and
+ :rc:`figure.constrained_layout.use` (which if `True` behaves as if
+ 'constrained' was passed). If both are `True`,
+ :rc:`figure.autolayout` takes priority.
+
+ Users and libraries can define their own layout engines and pass
+ the instance directly as well.
+
+ **kwargs
+ The keyword arguments are passed to the layout engine to set things
+ like padding and margin sizes. Only used if *layout* is a string.
+
+ """
+ if layout is None:
+ if mpl.rcParams['figure.autolayout']:
+ layout = 'tight'
+ elif mpl.rcParams['figure.constrained_layout.use']:
+ layout = 'constrained'
+ else:
+ self._layout_engine = None
+ return
+ if layout == 'tight':
+ new_layout_engine = TightLayoutEngine(**kwargs)
+ elif layout == 'constrained':
+ new_layout_engine = ConstrainedLayoutEngine(**kwargs)
+ elif layout == 'compressed':
+ new_layout_engine = ConstrainedLayoutEngine(compress=True,
+ **kwargs)
+ elif layout == 'none':
+ if self._layout_engine is not None:
+ new_layout_engine = PlaceHolderLayoutEngine(
+ self._layout_engine.adjust_compatible,
+ self._layout_engine.colorbar_gridspec
+ )
+ else:
+ new_layout_engine = None
+ elif isinstance(layout, LayoutEngine):
+ new_layout_engine = layout
+ else:
+ raise ValueError(f"Invalid value for 'layout': {layout!r}")
+
+ if self._check_layout_engines_compat(self._layout_engine,
+ new_layout_engine):
+ self._layout_engine = new_layout_engine
+ else:
+ raise RuntimeError('Colorbar layout of new layout engine not '
+ 'compatible with old engine, and a colorbar '
+ 'has been created. Engine not changed.')
+
+ def get_layout_engine(self):
+ return self._layout_engine
+
+ # TODO: I'd like to dynamically add the _repr_html_ method
+ # to the figure in the right context, but then IPython doesn't
+ # use it, for some reason.
+
+ def _repr_html_(self):
+ # We can't use "isinstance" here, because then we'd end up importing
+ # webagg unconditionally.
+ if 'WebAgg' in type(self.canvas).__name__:
+ from matplotlib.backends import backend_webagg
+ return backend_webagg.ipython_inline_display(self)
+
+ def show(self, warn=True):
+ """
+ If using a GUI backend with pyplot, display the figure window.
+
+ If the figure was not created using `~.pyplot.figure`, it will lack
+ a `~.backend_bases.FigureManagerBase`, and this method will raise an
+ AttributeError.
+
+ .. warning::
+
+ This does not manage an GUI event loop. Consequently, the figure
+ may only be shown briefly or not shown at all if you or your
+ environment are not managing an event loop.
+
+ Use cases for `.Figure.show` include running this from a GUI
+ application (where there is persistently an event loop running) or
+ from a shell, like IPython, that install an input hook to allow the
+ interactive shell to accept input while the figure is also being
+ shown and interactive. Some, but not all, GUI toolkits will
+ register an input hook on import. See :ref:`cp_integration` for
+ more details.
+
+ If you're in a shell without input hook integration or executing a
+ python script, you should use `matplotlib.pyplot.show` with
+ ``block=True`` instead, which takes care of starting and running
+ the event loop for you.
+
+ Parameters
+ ----------
+ warn : bool, default: True
+ If ``True`` and we are not running headless (i.e. on Linux with an
+ unset DISPLAY), issue warning when called on a non-GUI backend.
+
+ """
+ if self.canvas.manager is None:
+ raise AttributeError(
+ "Figure.show works only for figures managed by pyplot, "
+ "normally created by pyplot.figure()")
+ try:
+ self.canvas.manager.show()
+ except NonGuiException as exc:
+ if warn:
+ _api.warn_external(str(exc))
+
+ @property
+ def axes(self):
+ """
+ List of Axes in the Figure. You can access and modify the Axes in the
+ Figure through this list.
+
+ Do not modify the list itself. Instead, use `~Figure.add_axes`,
+ `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an Axes.
+
+ Note: The `.Figure.axes` property and `~.Figure.get_axes` method are
+ equivalent.
+ """
+ return self._axstack.as_list()
+
+ get_axes = axes.fget
+
+ @property
+ def number(self):
+ """The figure id, used to identify figures in `.pyplot`."""
+ # Historically, pyplot dynamically added a number attribute to figure.
+ # However, this number must stay in sync with the figure manager.
+ # AFAICS overwriting the number attribute does not have the desired
+ # effect for pyplot. But there are some repos in GitHub that do change
+ # number. So let's take it slow and properly migrate away from writing.
+ #
+ # Making the dynamic attribute private and wrapping it in a property
+ # allows to maintain current behavior and deprecate write-access.
+ #
+ # When the deprecation expires, there's no need for duplicate state
+ # anymore and the private _number attribute can be replaced by
+ # `self.canvas.manager.num` if that exists and None otherwise.
+ if hasattr(self, '_number'):
+ return self._number
+ else:
+ raise AttributeError(
+ "'Figure' object has no attribute 'number'. In the future this"
+ "will change to returning 'None' instead.")
+
+ @number.setter
+ def number(self, num):
+ _api.warn_deprecated(
+ "3.10",
+ message="Changing 'Figure.number' is deprecated since %(since)s and "
+ "will raise an error starting %(removal)s")
+ self._number = num
+
+ def _get_renderer(self):
+ if hasattr(self.canvas, 'get_renderer'):
+ return self.canvas.get_renderer()
+ else:
+ return _get_renderer(self)
+
+ def _get_dpi(self):
+ return self._dpi
+
+ def _set_dpi(self, dpi, forward=True):
+ """
+ Parameters
+ ----------
+ dpi : float
+
+ forward : bool
+ Passed on to `~.Figure.set_size_inches`
+ """
+ if dpi == self._dpi:
+ # We don't want to cause undue events in backends.
+ return
+ self._dpi = dpi
+ self.dpi_scale_trans.clear().scale(dpi)
+ w, h = self.get_size_inches()
+ self.set_size_inches(w, h, forward=forward)
+
+ dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.")
+
+ def get_tight_layout(self):
+ """Return whether `.Figure.tight_layout` is called when drawing."""
+ return isinstance(self.get_layout_engine(), TightLayoutEngine)
+
+ @_api.deprecated("3.6", alternative="set_layout_engine",
+ pending=True)
+ def set_tight_layout(self, tight):
+ """
+ Set whether and how `.Figure.tight_layout` is called when drawing.
+
+ Parameters
+ ----------
+ tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
+ If a bool, sets whether to call `.Figure.tight_layout` upon drawing.
+ If ``None``, use :rc:`figure.autolayout` instead.
+ If a dict, pass it as kwargs to `.Figure.tight_layout`, overriding the
+ default paddings.
+ """
+ if tight is None:
+ tight = mpl.rcParams['figure.autolayout']
+ _tight = 'tight' if bool(tight) else 'none'
+ _tight_parameters = tight if isinstance(tight, dict) else {}
+ self.set_layout_engine(_tight, **_tight_parameters)
+ self.stale = True
+
+ def get_constrained_layout(self):
+ """
+ Return whether constrained layout is being used.
+
+ See :ref:`constrainedlayout_guide`.
+ """
+ return isinstance(self.get_layout_engine(), ConstrainedLayoutEngine)
+
+ @_api.deprecated("3.6", alternative="set_layout_engine('constrained')",
+ pending=True)
+ def set_constrained_layout(self, constrained):
+ """
+ Set whether ``constrained_layout`` is used upon drawing.
+
+ If None, :rc:`figure.constrained_layout.use` value will be used.
+
+ When providing a dict containing the keys ``w_pad``, ``h_pad``
+ the default ``constrained_layout`` paddings will be
+ overridden. These pads are in inches and default to 3.0/72.0.
+ ``w_pad`` is the width padding and ``h_pad`` is the height padding.
+
+ Parameters
+ ----------
+ constrained : bool or dict or None
+ """
+ if constrained is None:
+ constrained = mpl.rcParams['figure.constrained_layout.use']
+ _constrained = 'constrained' if bool(constrained) else 'none'
+ _parameters = constrained if isinstance(constrained, dict) else {}
+ self.set_layout_engine(_constrained, **_parameters)
+ self.stale = True
+
+ @_api.deprecated(
+ "3.6", alternative="figure.get_layout_engine().set()",
+ pending=True)
+ def set_constrained_layout_pads(self, **kwargs):
+ """
+ Set padding for ``constrained_layout``.
+
+ Tip: The parameters can be passed from a dictionary by using
+ ``fig.set_constrained_layout(**pad_dict)``.
+
+ See :ref:`constrainedlayout_guide`.
+
+ Parameters
+ ----------
+ w_pad : float, default: :rc:`figure.constrained_layout.w_pad`
+ Width padding in inches. This is the pad around Axes
+ and is meant to make sure there is enough room for fonts to
+ look good. Defaults to 3 pts = 0.04167 inches
+
+ h_pad : float, default: :rc:`figure.constrained_layout.h_pad`
+ Height padding in inches. Defaults to 3 pts.
+
+ wspace : float, default: :rc:`figure.constrained_layout.wspace`
+ Width padding between subplots, expressed as a fraction of the
+ subplot width. The total padding ends up being w_pad + wspace.
+
+ hspace : float, default: :rc:`figure.constrained_layout.hspace`
+ Height padding between subplots, expressed as a fraction of the
+ subplot width. The total padding ends up being h_pad + hspace.
+
+ """
+ if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine):
+ self.get_layout_engine().set(**kwargs)
+
+ @_api.deprecated("3.6", alternative="fig.get_layout_engine().get()",
+ pending=True)
+ def get_constrained_layout_pads(self, relative=False):
+ """
+ Get padding for ``constrained_layout``.
+
+ Returns a list of ``w_pad, h_pad`` in inches and
+ ``wspace`` and ``hspace`` as fractions of the subplot.
+ All values are None if ``constrained_layout`` is not used.
+
+ See :ref:`constrainedlayout_guide`.
+
+ Parameters
+ ----------
+ relative : bool
+ If `True`, then convert from inches to figure relative.
+ """
+ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine):
+ return None, None, None, None
+ info = self.get_layout_engine().get()
+ w_pad = info['w_pad']
+ h_pad = info['h_pad']
+ wspace = info['wspace']
+ hspace = info['hspace']
+
+ if relative and (w_pad is not None or h_pad is not None):
+ renderer = self._get_renderer()
+ dpi = renderer.dpi
+ w_pad = w_pad * dpi / renderer.width
+ h_pad = h_pad * dpi / renderer.height
+
+ return w_pad, h_pad, wspace, hspace
+
+ def set_canvas(self, canvas):
+ """
+ Set the canvas that contains the figure
+
+ Parameters
+ ----------
+ canvas : FigureCanvas
+ """
+ self.canvas = canvas
+
+ @_docstring.interpd
+ def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None,
+ vmin=None, vmax=None, origin=None, resize=False, *,
+ colorizer=None, **kwargs):
+ """
+ Add a non-resampled image to the figure.
+
+ The image is attached to the lower or upper left corner depending on
+ *origin*.
+
+ Parameters
+ ----------
+ X
+ The image data. This is an array of one of the following shapes:
+
+ - (M, N): an image with scalar data. Color-mapping is controlled
+ by *cmap*, *norm*, *vmin*, and *vmax*.
+ - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
+ - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
+ i.e. including transparency.
+
+ xo, yo : int
+ The *x*/*y* image offset in pixels.
+
+ alpha : None or float
+ The alpha blending value.
+
+ %(cmap_doc)s
+
+ This parameter is ignored if *X* is RGB(A).
+
+ %(norm_doc)s
+
+ This parameter is ignored if *X* is RGB(A).
+
+ %(vmin_vmax_doc)s
+
+ This parameter is ignored if *X* is RGB(A).
+
+ origin : {'upper', 'lower'}, default: :rc:`image.origin`
+ Indicates where the [0, 0] index of the array is in the upper left
+ or lower left corner of the Axes.
+
+ resize : bool
+ If *True*, resize the figure to match the given image size.
+
+ %(colorizer_doc)s
+
+ This parameter is ignored if *X* is RGB(A).
+
+ Returns
+ -------
+ `matplotlib.image.FigureImage`
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`.
+
+ Notes
+ -----
+ figimage complements the Axes image (`~matplotlib.axes.Axes.imshow`)
+ which will be resampled to fit the current Axes. If you want
+ a resampled image to fill the entire figure, you can define an
+ `~matplotlib.axes.Axes` with extent [0, 0, 1, 1].
+
+ Examples
+ --------
+ ::
+
+ f = plt.figure()
+ nx = int(f.get_figwidth() * f.dpi)
+ ny = int(f.get_figheight() * f.dpi)
+ data = np.random.random((ny, nx))
+ f.figimage(data)
+ plt.show()
+ """
+ if resize:
+ dpi = self.get_dpi()
+ figsize = [x / dpi for x in (X.shape[1], X.shape[0])]
+ self.set_size_inches(figsize, forward=True)
+
+ im = mimage.FigureImage(self, cmap=cmap, norm=norm,
+ colorizer=colorizer,
+ offsetx=xo, offsety=yo,
+ origin=origin, **kwargs)
+ im.stale_callback = _stale_figure_callback
+
+ im.set_array(X)
+ im.set_alpha(alpha)
+ if norm is None:
+ im._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax)
+ im.set_clim(vmin, vmax)
+ self.images.append(im)
+ im._remove_method = self.images.remove
+ self.stale = True
+ return im
+
+ def set_size_inches(self, w, h=None, forward=True):
+ """
+ Set the figure size in inches.
+
+ Call signatures::
+
+ fig.set_size_inches(w, h) # OR
+ fig.set_size_inches((w, h))
+
+ Parameters
+ ----------
+ w : (float, float) or float
+ Width and height in inches (if height not specified as a separate
+ argument) or width.
+ h : float
+ Height in inches.
+ forward : bool, default: True
+ If ``True``, the canvas size is automatically updated, e.g.,
+ you can resize the figure window from the shell.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.get_size_inches
+ matplotlib.figure.Figure.set_figwidth
+ matplotlib.figure.Figure.set_figheight
+
+ Notes
+ -----
+ To transform from pixels to inches divide by `Figure.dpi`.
+ """
+ if h is None: # Got called with a single pair as argument.
+ w, h = w
+ size = np.array([w, h])
+ if not np.isfinite(size).all() or (size < 0).any():
+ raise ValueError(f'figure size must be positive finite not {size}')
+ self.bbox_inches.p1 = size
+ if forward:
+ manager = self.canvas.manager
+ if manager is not None:
+ manager.resize(*(size * self.dpi).astype(int))
+ self.stale = True
+
+ def get_size_inches(self):
+ """
+ Return the current size of the figure in inches.
+
+ Returns
+ -------
+ ndarray
+ The size (width, height) of the figure in inches.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.set_size_inches
+ matplotlib.figure.Figure.get_figwidth
+ matplotlib.figure.Figure.get_figheight
+
+ Notes
+ -----
+ The size in pixels can be obtained by multiplying with `Figure.dpi`.
+ """
+ return np.array(self.bbox_inches.p1)
+
+ def get_figwidth(self):
+ """Return the figure width in inches."""
+ return self.bbox_inches.width
+
+ def get_figheight(self):
+ """Return the figure height in inches."""
+ return self.bbox_inches.height
+
+ def get_dpi(self):
+ """Return the resolution in dots per inch as a float."""
+ return self.dpi
+
+ def set_dpi(self, val):
+ """
+ Set the resolution of the figure in dots-per-inch.
+
+ Parameters
+ ----------
+ val : float
+ """
+ self.dpi = val
+ self.stale = True
+
+ def set_figwidth(self, val, forward=True):
+ """
+ Set the width of the figure in inches.
+
+ Parameters
+ ----------
+ val : float
+ forward : bool
+ See `set_size_inches`.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.set_figheight
+ matplotlib.figure.Figure.set_size_inches
+ """
+ self.set_size_inches(val, self.get_figheight(), forward=forward)
+
+ def set_figheight(self, val, forward=True):
+ """
+ Set the height of the figure in inches.
+
+ Parameters
+ ----------
+ val : float
+ forward : bool
+ See `set_size_inches`.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.set_figwidth
+ matplotlib.figure.Figure.set_size_inches
+ """
+ self.set_size_inches(self.get_figwidth(), val, forward=forward)
+
+ def clear(self, keep_observers=False):
+ # docstring inherited
+ super().clear(keep_observers=keep_observers)
+ # FigureBase.clear does not clear toolbars, as
+ # only Figure can have toolbars
+ toolbar = self.canvas.toolbar
+ if toolbar is not None:
+ toolbar.update()
+
+ @_finalize_rasterization
+ @allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+ if not self.get_visible():
+ return
+
+ with self._render_lock:
+
+ artists = self._get_draw_artists(renderer)
+ try:
+ renderer.open_group('figure', gid=self.get_gid())
+ if self.axes and self.get_layout_engine() is not None:
+ try:
+ self.get_layout_engine().execute(self)
+ except ValueError:
+ pass
+ # ValueError can occur when resizing a window.
+
+ self.patch.draw(renderer)
+ mimage._draw_list_compositing_images(
+ renderer, self, artists, self.suppressComposite)
+
+ renderer.close_group('figure')
+ finally:
+ self.stale = False
+
+ DrawEvent("draw_event", self.canvas, renderer)._process()
+
+ def draw_without_rendering(self):
+ """
+ Draw the figure with no output. Useful to get the final size of
+ artists that require a draw before their size is known (e.g. text).
+ """
+ renderer = _get_renderer(self)
+ with renderer._draw_disabled():
+ self.draw(renderer)
+
+ def draw_artist(self, a):
+ """
+ Draw `.Artist` *a* only.
+ """
+ a.draw(self.canvas.get_renderer())
+
+ def __getstate__(self):
+ state = super().__getstate__()
+
+ # The canvas cannot currently be pickled, but this has the benefit
+ # of meaning that a figure can be detached from one canvas, and
+ # re-attached to another.
+ state.pop("canvas")
+
+ # discard any changes to the dpi due to pixel ratio changes
+ state["_dpi"] = state.get('_original_dpi', state['_dpi'])
+
+ # add version information to the state
+ state['__mpl_version__'] = mpl.__version__
+
+ # check whether the figure manager (if any) is registered with pyplot
+ from matplotlib import _pylab_helpers
+ if self.canvas.manager in _pylab_helpers.Gcf.figs.values():
+ state['_restore_to_pylab'] = True
+ return state
+
+ def __setstate__(self, state):
+ version = state.pop('__mpl_version__')
+ restore_to_pylab = state.pop('_restore_to_pylab', False)
+
+ if version != mpl.__version__:
+ _api.warn_external(
+ f"This figure was saved with matplotlib version {version} and "
+ f"loaded with {mpl.__version__} so may not function correctly."
+ )
+ self.__dict__ = state
+
+ # re-initialise some of the unstored state information
+ FigureCanvasBase(self) # Set self.canvas.
+
+ if restore_to_pylab:
+ # lazy import to avoid circularity
+ import matplotlib.pyplot as plt
+ import matplotlib._pylab_helpers as pylab_helpers
+ allnums = plt.get_fignums()
+ num = max(allnums) + 1 if allnums else 1
+ backend = plt._get_backend_mod()
+ mgr = backend.new_figure_manager_given_figure(num, self)
+ pylab_helpers.Gcf._set_new_active_manager(mgr)
+ plt.draw_if_interactive()
+
+ self.stale = True
+
+ def add_axobserver(self, func):
+ """Whenever the Axes state change, ``func(self)`` will be called."""
+ # Connect a wrapper lambda and not func itself, to avoid it being
+ # weakref-collected.
+ self._axobservers.connect("_axes_change_event", lambda arg: func(arg))
+
+ def savefig(self, fname, *, transparent=None, **kwargs):
+ """
+ Save the current figure as an image or vector graphic to a file.
+
+ Call signature::
+
+ savefig(fname, *, transparent=None, dpi='figure', format=None,
+ metadata=None, bbox_inches=None, pad_inches=0.1,
+ facecolor='auto', edgecolor='auto', backend=None,
+ **kwargs
+ )
+
+ The available output formats depend on the backend being used.
+
+ Parameters
+ ----------
+ fname : str or path-like or binary file-like
+ A path, or a Python file-like object, or
+ possibly some backend-dependent object such as
+ `matplotlib.backends.backend_pdf.PdfPages`.
+
+ If *format* is set, it determines the output format, and the file
+ is saved as *fname*. Note that *fname* is used verbatim, and there
+ is no attempt to make the extension, if any, of *fname* match
+ *format*, and no extension is appended.
+
+ If *format* is not set, then the format is inferred from the
+ extension of *fname*, if there is one. If *format* is not
+ set and *fname* has no extension, then the file is saved with
+ :rc:`savefig.format` and the appropriate extension is appended to
+ *fname*.
+
+ Other Parameters
+ ----------------
+ transparent : bool, default: :rc:`savefig.transparent`
+ If *True*, the Axes patches will all be transparent; the
+ Figure patch will also be transparent unless *facecolor*
+ and/or *edgecolor* are specified via kwargs.
+
+ If *False* has no effect and the color of the Axes and
+ Figure patches are unchanged (unless the Figure patch
+ is specified via the *facecolor* and/or *edgecolor* keyword
+ arguments in which case those colors are used).
+
+ The transparency of these patches will be restored to their
+ original values upon exit of this function.
+
+ This is useful, for example, for displaying
+ a plot on top of a colored background on a web page.
+
+ dpi : float or 'figure', default: :rc:`savefig.dpi`
+ The resolution in dots per inch. If 'figure', use the figure's
+ dpi value.
+
+ format : str
+ The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when
+ this is unset is documented under *fname*.
+
+ metadata : dict, optional
+ Key/value pairs to store in the image metadata. The supported keys
+ and defaults depend on the image format and backend:
+
+ - 'png' with Agg backend: See the parameter ``metadata`` of
+ `~.FigureCanvasAgg.print_png`.
+ - 'pdf' with pdf backend: See the parameter ``metadata`` of
+ `~.backend_pdf.PdfPages`.
+ - 'svg' with svg backend: See the parameter ``metadata`` of
+ `~.FigureCanvasSVG.print_svg`.
+ - 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
+
+ Not supported for 'pgf', 'raw', and 'rgba' as those formats do not support
+ embedding metadata.
+ Does not currently support 'jpg', 'tiff', or 'webp', but may include
+ embedding EXIF metadata in the future.
+
+ bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox`
+ Bounding box in inches: only the given portion of the figure is
+ saved. If 'tight', try to figure out the tight bbox of the figure.
+
+ pad_inches : float or 'layout', default: :rc:`savefig.pad_inches`
+ Amount of padding in inches around the figure when bbox_inches is
+ 'tight'. If 'layout' use the padding from the constrained or
+ compressed layout engine; ignored if one of those engines is not in
+ use.
+
+ facecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.facecolor`
+ The facecolor of the figure. If 'auto', use the current figure
+ facecolor.
+
+ edgecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.edgecolor`
+ The edgecolor of the figure. If 'auto', use the current figure
+ edgecolor.
+
+ backend : str, optional
+ Use a non-default backend to render the file, e.g. to render a
+ png file with the "cairo" backend rather than the default "agg",
+ or a pdf file with the "pgf" backend rather than the default
+ "pdf". Note that the default backend is normally sufficient. See
+ :ref:`the-builtin-backends` for a list of valid backends for each
+ file format. Custom backends can be referenced as "module://...".
+
+ orientation : {'landscape', 'portrait'}
+ Currently only supported by the postscript backend.
+
+ papertype : str
+ One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
+ 'a10', 'b0' through 'b10'. Only supported for postscript
+ output.
+
+ bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
+ A list of extra artists that will be considered when the
+ tight bbox is calculated.
+
+ pil_kwargs : dict, optional
+ Additional keyword arguments that are passed to
+ `PIL.Image.Image.save` when saving the figure.
+
+ """
+
+ kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi'])
+ if transparent is None:
+ transparent = mpl.rcParams['savefig.transparent']
+
+ with ExitStack() as stack:
+ if transparent:
+ def _recursively_make_subfig_transparent(exit_stack, subfig):
+ exit_stack.enter_context(
+ subfig.patch._cm_set(
+ facecolor="none", edgecolor="none"))
+ for ax in subfig.axes:
+ exit_stack.enter_context(
+ ax.patch._cm_set(
+ facecolor="none", edgecolor="none"))
+ for sub_subfig in subfig.subfigs:
+ _recursively_make_subfig_transparent(
+ exit_stack, sub_subfig)
+
+ def _recursively_make_axes_transparent(exit_stack, ax):
+ exit_stack.enter_context(
+ ax.patch._cm_set(facecolor="none", edgecolor="none"))
+ for child_ax in ax.child_axes:
+ exit_stack.enter_context(
+ child_ax.patch._cm_set(
+ facecolor="none", edgecolor="none"))
+ for child_childax in ax.child_axes:
+ _recursively_make_axes_transparent(
+ exit_stack, child_childax)
+
+ kwargs.setdefault('facecolor', 'none')
+ kwargs.setdefault('edgecolor', 'none')
+ # set subfigure to appear transparent in printed image
+ for subfig in self.subfigs:
+ _recursively_make_subfig_transparent(stack, subfig)
+ # set Axes to be transparent
+ for ax in self.axes:
+ _recursively_make_axes_transparent(stack, ax)
+ self.canvas.print_figure(fname, **kwargs)
+
+ def ginput(self, n=1, timeout=30, show_clicks=True,
+ mouse_add=MouseButton.LEFT,
+ mouse_pop=MouseButton.RIGHT,
+ mouse_stop=MouseButton.MIDDLE):
+ """
+ Blocking call to interact with a figure.
+
+ Wait until the user clicks *n* times on the figure, and return the
+ coordinates of each click in a list.
+
+ There are three possible interactions:
+
+ - Add a point.
+ - Remove the most recently added point.
+ - Stop the interaction and return the points added so far.
+
+ The actions are assigned to mouse buttons via the arguments
+ *mouse_add*, *mouse_pop* and *mouse_stop*.
+
+ Parameters
+ ----------
+ n : int, default: 1
+ Number of mouse clicks to accumulate. If negative, accumulate
+ clicks until the input is terminated manually.
+ timeout : float, default: 30 seconds
+ Number of seconds to wait before timing out. If zero or negative
+ will never time out.
+ show_clicks : bool, default: True
+ If True, show a red cross at the location of each click.
+ mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT`
+ Mouse button used to add points.
+ mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT`
+ Mouse button used to remove the most recently added point.
+ mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE`
+ Mouse button used to stop input.
+
+ Returns
+ -------
+ list of tuples
+ A list of the clicked (x, y) coordinates.
+
+ Notes
+ -----
+ The keyboard can also be used to select points in case your mouse
+ does not have one or more of the buttons. The delete and backspace
+ keys act like right-clicking (i.e., remove last point), the enter key
+ terminates input and any other key (not already used by the window
+ manager) selects a point.
+ """
+ clicks = []
+ marks = []
+
+ def handler(event):
+ is_button = event.name == "button_press_event"
+ is_key = event.name == "key_press_event"
+ # Quit (even if not in infinite mode; this is consistent with
+ # MATLAB and sometimes quite useful, but will require the user to
+ # test how many points were actually returned before using data).
+ if (is_button and event.button == mouse_stop
+ or is_key and event.key in ["escape", "enter"]):
+ self.canvas.stop_event_loop()
+ # Pop last click.
+ elif (is_button and event.button == mouse_pop
+ or is_key and event.key in ["backspace", "delete"]):
+ if clicks:
+ clicks.pop()
+ if show_clicks:
+ marks.pop().remove()
+ self.canvas.draw()
+ # Add new click.
+ elif (is_button and event.button == mouse_add
+ # On macOS/gtk, some keys return None.
+ or is_key and event.key is not None):
+ if event.inaxes:
+ clicks.append((event.xdata, event.ydata))
+ _log.info("input %i: %f, %f",
+ len(clicks), event.xdata, event.ydata)
+ if show_clicks:
+ line = mpl.lines.Line2D([event.xdata], [event.ydata],
+ marker="+", color="r")
+ event.inaxes.add_line(line)
+ marks.append(line)
+ self.canvas.draw()
+ if len(clicks) == n and n > 0:
+ self.canvas.stop_event_loop()
+
+ _blocking_input.blocking_input_loop(
+ self, ["button_press_event", "key_press_event"], timeout, handler)
+
+ # Cleanup.
+ for mark in marks:
+ mark.remove()
+ self.canvas.draw()
+
+ return clicks
+
+ def waitforbuttonpress(self, timeout=-1):
+ """
+ Blocking call to interact with the figure.
+
+ Wait for user input and return True if a key was pressed, False if a
+ mouse button was pressed and None if no input was given within
+ *timeout* seconds. Negative values deactivate *timeout*.
+ """
+ event = None
+
+ def handler(ev):
+ nonlocal event
+ event = ev
+ self.canvas.stop_event_loop()
+
+ _blocking_input.blocking_input_loop(
+ self, ["button_press_event", "key_press_event"], timeout, handler)
+
+ return None if event is None else event.name == "key_press_event"
+
+ def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None):
+ """
+ Adjust the padding between and around subplots.
+
+ To exclude an artist on the Axes from the bounding box calculation
+ that determines the subplot parameters (i.e. legend, or annotation),
+ set ``a.set_in_layout(False)`` for that artist.
+
+ Parameters
+ ----------
+ pad : float, default: 1.08
+ Padding between the figure edge and the edges of subplots,
+ as a fraction of the font size.
+ h_pad, w_pad : float, default: *pad*
+ Padding (height/width) between edges of adjacent subplots,
+ as a fraction of the font size.
+ rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1)
+ A rectangle in normalized figure coordinates into which the whole
+ subplots area (including labels) will fit.
+
+ See Also
+ --------
+ .Figure.set_layout_engine
+ .pyplot.tight_layout
+ """
+ # note that here we do not permanently set the figures engine to
+ # tight_layout but rather just perform the layout in place and remove
+ # any previous engines.
+ engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
+ try:
+ previous_engine = self.get_layout_engine()
+ self.set_layout_engine(engine)
+ engine.execute(self)
+ if previous_engine is not None and not isinstance(
+ previous_engine, (TightLayoutEngine, PlaceHolderLayoutEngine)
+ ):
+ _api.warn_external('The figure layout has changed to tight')
+ finally:
+ self.set_layout_engine('none')
+
+
+def figaspect(arg):
+ """
+ Calculate the width and height for a figure with a specified aspect ratio.
+
+ While the height is taken from :rc:`figure.figsize`, the width is
+ adjusted to match the desired aspect ratio. Additionally, it is ensured
+ that the width is in the range [4., 16.] and the height is in the range
+ [2., 16.]. If necessary, the default height is adjusted to ensure this.
+
+ Parameters
+ ----------
+ arg : float or 2D array
+ If a float, this defines the aspect ratio (i.e. the ratio height /
+ width).
+ In case of an array the aspect ratio is number of rows / number of
+ columns, so that the array could be fitted in the figure undistorted.
+
+ Returns
+ -------
+ width, height : float
+ The figure size in inches.
+
+ Notes
+ -----
+ If you want to create an Axes within the figure, that still preserves the
+ aspect ratio, be sure to create it with equal width and height. See
+ examples below.
+
+ Thanks to Fernando Perez for this function.
+
+ Examples
+ --------
+ Make a figure twice as tall as it is wide::
+
+ w, h = figaspect(2.)
+ fig = Figure(figsize=(w, h))
+ ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
+ ax.imshow(A, **kwargs)
+
+ Make a figure with the proper aspect for an array::
+
+ A = rand(5, 3)
+ w, h = figaspect(A)
+ fig = Figure(figsize=(w, h))
+ ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
+ ax.imshow(A, **kwargs)
+ """
+
+ isarray = hasattr(arg, 'shape') and not np.isscalar(arg)
+
+ # min/max sizes to respect when autoscaling. If John likes the idea, they
+ # could become rc parameters, for now they're hardwired.
+ figsize_min = np.array((4.0, 2.0)) # min length for width/height
+ figsize_max = np.array((16.0, 16.0)) # max length for width/height
+
+ # Extract the aspect ratio of the array
+ if isarray:
+ nr, nc = arg.shape[:2]
+ arr_ratio = nr / nc
+ else:
+ arr_ratio = arg
+
+ # Height of user figure defaults
+ fig_height = mpl.rcParams['figure.figsize'][1]
+
+ # New size for the figure, keeping the aspect ratio of the caller
+ newsize = np.array((fig_height / arr_ratio, fig_height))
+
+ # Sanity checks, don't drop either dimension below figsize_min
+ newsize /= min(1.0, *(newsize / figsize_min))
+
+ # Avoid humongous windows as well
+ newsize /= max(1.0, *(newsize / figsize_max))
+
+ # Finally, if we have a really funky aspect ratio, break it but respect
+ # the min/max dimensions (we don't want figures 10 feet tall!)
+ newsize = np.clip(newsize, figsize_min, figsize_max)
+ return newsize
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/figure.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/figure.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..08bf1505532bb8f097db7d2e907f5f4243aa652f
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/figure.pyi
@@ -0,0 +1,421 @@
+from collections.abc import Callable, Hashable, Iterable, Sequence
+import os
+from typing import Any, IO, Literal, TypeVar, overload
+
+import numpy as np
+from numpy.typing import ArrayLike
+
+from matplotlib.artist import Artist
+from matplotlib.axes import Axes
+from matplotlib.backend_bases import (
+ FigureCanvasBase,
+ MouseButton,
+ MouseEvent,
+ RendererBase,
+)
+from matplotlib.colors import Colormap, Normalize
+from matplotlib.colorbar import Colorbar
+from matplotlib.colorizer import ColorizingArtist, Colorizer
+from matplotlib.cm import ScalarMappable
+from matplotlib.gridspec import GridSpec, SubplotSpec, SubplotParams as SubplotParams
+from matplotlib.image import _ImageBase, FigureImage
+from matplotlib.layout_engine import LayoutEngine
+from matplotlib.legend import Legend
+from matplotlib.lines import Line2D
+from matplotlib.patches import Rectangle, Patch
+from matplotlib.text import Text
+from matplotlib.transforms import Affine2D, Bbox, BboxBase, Transform
+from .typing import ColorType, HashableList
+
+_T = TypeVar("_T")
+
+class FigureBase(Artist):
+ artists: list[Artist]
+ lines: list[Line2D]
+ patches: list[Patch]
+ texts: list[Text]
+ images: list[_ImageBase]
+ legends: list[Legend]
+ subfigs: list[SubFigure]
+ stale: bool
+ suppressComposite: bool | None
+ def __init__(self, **kwargs) -> None: ...
+ def autofmt_xdate(
+ self,
+ bottom: float = ...,
+ rotation: int = ...,
+ ha: Literal["left", "center", "right"] = ...,
+ which: Literal["major", "minor", "both"] = ...,
+ ) -> None: ...
+ def get_children(self) -> list[Artist]: ...
+ def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ...
+ def suptitle(self, t: str, **kwargs) -> Text: ...
+ def get_suptitle(self) -> str: ...
+ def supxlabel(self, t: str, **kwargs) -> Text: ...
+ def get_supxlabel(self) -> str: ...
+ def supylabel(self, t: str, **kwargs) -> Text: ...
+ def get_supylabel(self) -> str: ...
+ def get_edgecolor(self) -> ColorType: ...
+ def get_facecolor(self) -> ColorType: ...
+ def get_frameon(self) -> bool: ...
+ def set_linewidth(self, linewidth: float) -> None: ...
+ def get_linewidth(self) -> float: ...
+ def set_edgecolor(self, color: ColorType) -> None: ...
+ def set_facecolor(self, color: ColorType) -> None: ...
+ @overload
+ def get_figure(self, root: Literal[True]) -> Figure: ...
+ @overload
+ def get_figure(self, root: Literal[False]) -> Figure | SubFigure: ...
+ @overload
+ def get_figure(self, root: bool = ...) -> Figure | SubFigure: ...
+ def set_frameon(self, b: bool) -> None: ...
+ @property
+ def frameon(self) -> bool: ...
+ @frameon.setter
+ def frameon(self, b: bool) -> None: ...
+ def add_artist(self, artist: Artist, clip: bool = ...) -> Artist: ...
+ @overload
+ def add_axes(self, ax: Axes) -> Axes: ...
+ @overload
+ def add_axes(
+ self,
+ rect: tuple[float, float, float, float],
+ projection: None | str = ...,
+ polar: bool = ...,
+ **kwargs
+ ) -> Axes: ...
+
+ # TODO: docstring indicates SubplotSpec a valid arg, but none of the listed signatures appear to be that
+ @overload
+ def add_subplot(
+ self, nrows: int, ncols: int, index: int | tuple[int, int], **kwargs
+ ) -> Axes: ...
+ @overload
+ def add_subplot(self, pos: int, **kwargs) -> Axes: ...
+ @overload
+ def add_subplot(self, ax: Axes, **kwargs) -> Axes: ...
+ @overload
+ def add_subplot(self, ax: SubplotSpec, **kwargs) -> Axes: ...
+ @overload
+ def add_subplot(self, **kwargs) -> Axes: ...
+ @overload
+ def subplots(
+ self,
+ nrows: Literal[1] = ...,
+ ncols: Literal[1] = ...,
+ *,
+ sharex: bool | Literal["none", "all", "row", "col"] = ...,
+ sharey: bool | Literal["none", "all", "row", "col"] = ...,
+ squeeze: Literal[True] = ...,
+ width_ratios: Sequence[float] | None = ...,
+ height_ratios: Sequence[float] | None = ...,
+ subplot_kw: dict[str, Any] | None = ...,
+ gridspec_kw: dict[str, Any] | None = ...,
+ ) -> Axes: ...
+ @overload
+ def subplots(
+ self,
+ nrows: int = ...,
+ ncols: int = ...,
+ *,
+ sharex: bool | Literal["none", "all", "row", "col"] = ...,
+ sharey: bool | Literal["none", "all", "row", "col"] = ...,
+ squeeze: Literal[False],
+ width_ratios: Sequence[float] | None = ...,
+ height_ratios: Sequence[float] | None = ...,
+ subplot_kw: dict[str, Any] | None = ...,
+ gridspec_kw: dict[str, Any] | None = ...,
+ ) -> np.ndarray: ... # TODO numpy/numpy#24738
+ @overload
+ def subplots(
+ self,
+ nrows: int = ...,
+ ncols: int = ...,
+ *,
+ sharex: bool | Literal["none", "all", "row", "col"] = ...,
+ sharey: bool | Literal["none", "all", "row", "col"] = ...,
+ squeeze: bool = ...,
+ width_ratios: Sequence[float] | None = ...,
+ height_ratios: Sequence[float] | None = ...,
+ subplot_kw: dict[str, Any] | None = ...,
+ gridspec_kw: dict[str, Any] | None = ...,
+ ) -> Any: ...
+ def delaxes(self, ax: Axes) -> None: ...
+ def clear(self, keep_observers: bool = ...) -> None: ...
+ def clf(self, keep_observers: bool = ...) -> None: ...
+
+ @overload
+ def legend(self) -> Legend: ...
+ @overload
+ def legend(self, handles: Iterable[Artist], labels: Iterable[str], **kwargs) -> Legend: ...
+ @overload
+ def legend(self, *, handles: Iterable[Artist], **kwargs) -> Legend: ...
+ @overload
+ def legend(self, labels: Iterable[str], **kwargs) -> Legend: ...
+ @overload
+ def legend(self, **kwargs) -> Legend: ...
+
+ def text(
+ self,
+ x: float,
+ y: float,
+ s: str,
+ fontdict: dict[str, Any] | None = ...,
+ **kwargs
+ ) -> Text: ...
+ def colorbar(
+ self,
+ mappable: ScalarMappable | ColorizingArtist,
+ cax: Axes | None = ...,
+ ax: Axes | Iterable[Axes] | None = ...,
+ use_gridspec: bool = ...,
+ **kwargs
+ ) -> Colorbar: ...
+ def subplots_adjust(
+ self,
+ left: float | None = ...,
+ bottom: float | None = ...,
+ right: float | None = ...,
+ top: float | None = ...,
+ wspace: float | None = ...,
+ hspace: float | None = ...,
+ ) -> None: ...
+ def align_xlabels(self, axs: Iterable[Axes] | None = ...) -> None: ...
+ def align_ylabels(self, axs: Iterable[Axes] | None = ...) -> None: ...
+ def align_titles(self, axs: Iterable[Axes] | None = ...) -> None: ...
+ def align_labels(self, axs: Iterable[Axes] | None = ...) -> None: ...
+ def add_gridspec(self, nrows: int = ..., ncols: int = ..., **kwargs) -> GridSpec: ...
+ @overload
+ def subfigures(
+ self,
+ nrows: int = ...,
+ ncols: int = ...,
+ squeeze: Literal[False] = ...,
+ wspace: float | None = ...,
+ hspace: float | None = ...,
+ width_ratios: ArrayLike | None = ...,
+ height_ratios: ArrayLike | None = ...,
+ **kwargs
+ ) -> np.ndarray: ...
+ @overload
+ def subfigures(
+ self,
+ nrows: int = ...,
+ ncols: int = ...,
+ squeeze: Literal[True] = ...,
+ wspace: float | None = ...,
+ hspace: float | None = ...,
+ width_ratios: ArrayLike | None = ...,
+ height_ratios: ArrayLike | None = ...,
+ **kwargs
+ ) -> np.ndarray | SubFigure: ...
+ def add_subfigure(self, subplotspec: SubplotSpec, **kwargs) -> SubFigure: ...
+ def sca(self, a: Axes) -> Axes: ...
+ def gca(self) -> Axes: ...
+ def _gci(self) -> ColorizingArtist | None: ...
+ def _process_projection_requirements(
+ self, *, axes_class=None, polar=False, projection=None, **kwargs
+ ) -> tuple[type[Axes], dict[str, Any]]: ...
+ def get_default_bbox_extra_artists(self) -> list[Artist]: ...
+ def get_tightbbox(
+ self,
+ renderer: RendererBase | None = ...,
+ *,
+ bbox_extra_artists: Iterable[Artist] | None = ...,
+ ) -> Bbox: ...
+ @overload
+ def subplot_mosaic(
+ self,
+ mosaic: str,
+ *,
+ sharex: bool = ...,
+ sharey: bool = ...,
+ width_ratios: ArrayLike | None = ...,
+ height_ratios: ArrayLike | None = ...,
+ empty_sentinel: str = ...,
+ subplot_kw: dict[str, Any] | None = ...,
+ per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | None = ...,
+ gridspec_kw: dict[str, Any] | None = ...,
+ ) -> dict[str, Axes]: ...
+ @overload
+ def subplot_mosaic(
+ self,
+ mosaic: list[HashableList[_T]],
+ *,
+ sharex: bool = ...,
+ sharey: bool = ...,
+ width_ratios: ArrayLike | None = ...,
+ height_ratios: ArrayLike | None = ...,
+ empty_sentinel: _T = ...,
+ subplot_kw: dict[str, Any] | None = ...,
+ per_subplot_kw: dict[_T | tuple[_T, ...], dict[str, Any]] | None = ...,
+ gridspec_kw: dict[str, Any] | None = ...,
+ ) -> dict[_T, Axes]: ...
+ @overload
+ def subplot_mosaic(
+ self,
+ mosaic: list[HashableList[Hashable]],
+ *,
+ sharex: bool = ...,
+ sharey: bool = ...,
+ width_ratios: ArrayLike | None = ...,
+ height_ratios: ArrayLike | None = ...,
+ empty_sentinel: Any = ...,
+ subplot_kw: dict[str, Any] | None = ...,
+ per_subplot_kw: dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = ...,
+ gridspec_kw: dict[str, Any] | None = ...,
+ ) -> dict[Hashable, Axes]: ...
+
+class SubFigure(FigureBase):
+ @property
+ def figure(self) -> Figure: ...
+ subplotpars: SubplotParams
+ dpi_scale_trans: Affine2D
+ transFigure: Transform
+ bbox_relative: Bbox
+ figbbox: BboxBase
+ bbox: BboxBase
+ transSubfigure: Transform
+ patch: Rectangle
+ def __init__(
+ self,
+ parent: Figure | SubFigure,
+ subplotspec: SubplotSpec,
+ *,
+ facecolor: ColorType | None = ...,
+ edgecolor: ColorType | None = ...,
+ linewidth: float = ...,
+ frameon: bool | None = ...,
+ **kwargs
+ ) -> None: ...
+ @property
+ def canvas(self) -> FigureCanvasBase: ...
+ @property
+ def dpi(self) -> float: ...
+ @dpi.setter
+ def dpi(self, value: float) -> None: ...
+ def get_dpi(self) -> float: ...
+ def set_dpi(self, val) -> None: ...
+ def get_constrained_layout(self) -> bool: ...
+ def get_constrained_layout_pads(
+ self, relative: bool = ...
+ ) -> tuple[float, float, float, float]: ...
+ def get_layout_engine(self) -> LayoutEngine: ...
+ @property # type: ignore[misc]
+ def axes(self) -> list[Axes]: ... # type: ignore[override]
+ def get_axes(self) -> list[Axes]: ...
+
+class Figure(FigureBase):
+ @property
+ def figure(self) -> Figure: ...
+ bbox_inches: Bbox
+ dpi_scale_trans: Affine2D
+ bbox: BboxBase
+ figbbox: BboxBase
+ transFigure: Transform
+ transSubfigure: Transform
+ patch: Rectangle
+ subplotpars: SubplotParams
+ def __init__(
+ self,
+ figsize: tuple[float, float] | None = ...,
+ dpi: float | None = ...,
+ *,
+ facecolor: ColorType | None = ...,
+ edgecolor: ColorType | None = ...,
+ linewidth: float = ...,
+ frameon: bool | None = ...,
+ subplotpars: SubplotParams | None = ...,
+ tight_layout: bool | dict[str, Any] | None = ...,
+ constrained_layout: bool | dict[str, Any] | None = ...,
+ layout: Literal["constrained", "compressed", "tight"]
+ | LayoutEngine
+ | None = ...,
+ **kwargs
+ ) -> None: ...
+ def pick(self, mouseevent: MouseEvent) -> None: ...
+ def set_layout_engine(
+ self,
+ layout: Literal["constrained", "compressed", "tight", "none"]
+ | LayoutEngine
+ | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_layout_engine(self) -> LayoutEngine | None: ...
+ def _repr_html_(self) -> str | None: ...
+ def show(self, warn: bool = ...) -> None: ...
+ @property
+ def number(self) -> int | str: ...
+ @number.setter
+ def number(self, num: int | str) -> None: ...
+ @property # type: ignore[misc]
+ def axes(self) -> list[Axes]: ... # type: ignore[override]
+ def get_axes(self) -> list[Axes]: ...
+ @property
+ def dpi(self) -> float: ...
+ @dpi.setter
+ def dpi(self, dpi: float) -> None: ...
+ def get_tight_layout(self) -> bool: ...
+ def get_constrained_layout_pads(
+ self, relative: bool = ...
+ ) -> tuple[float, float, float, float]: ...
+ def get_constrained_layout(self) -> bool: ...
+ canvas: FigureCanvasBase
+ def set_canvas(self, canvas: FigureCanvasBase) -> None: ...
+ def figimage(
+ self,
+ X: ArrayLike,
+ xo: int = ...,
+ yo: int = ...,
+ alpha: float | None = ...,
+ norm: str | Normalize | None = ...,
+ cmap: str | Colormap | None = ...,
+ vmin: float | None = ...,
+ vmax: float | None = ...,
+ origin: Literal["upper", "lower"] | None = ...,
+ resize: bool = ...,
+ *,
+ colorizer: Colorizer | None = ...,
+ **kwargs
+ ) -> FigureImage: ...
+ def set_size_inches(
+ self, w: float | tuple[float, float], h: float | None = ..., forward: bool = ...
+ ) -> None: ...
+ def get_size_inches(self) -> np.ndarray: ...
+ def get_figwidth(self) -> float: ...
+ def get_figheight(self) -> float: ...
+ def get_dpi(self) -> float: ...
+ def set_dpi(self, val: float) -> None: ...
+ def set_figwidth(self, val: float, forward: bool = ...) -> None: ...
+ def set_figheight(self, val: float, forward: bool = ...) -> None: ...
+ def clear(self, keep_observers: bool = ...) -> None: ...
+ def draw_without_rendering(self) -> None: ...
+ def draw_artist(self, a: Artist) -> None: ...
+ def add_axobserver(self, func: Callable[[Figure], Any]) -> None: ...
+ def savefig(
+ self,
+ fname: str | os.PathLike | IO,
+ *,
+ transparent: bool | None = ...,
+ **kwargs
+ ) -> None: ...
+ def ginput(
+ self,
+ n: int = ...,
+ timeout: float = ...,
+ show_clicks: bool = ...,
+ mouse_add: MouseButton = ...,
+ mouse_pop: MouseButton = ...,
+ mouse_stop: MouseButton = ...,
+ ) -> list[tuple[int, int]]: ...
+ def waitforbuttonpress(self, timeout: float = ...) -> None | bool: ...
+ def tight_layout(
+ self,
+ *,
+ pad: float = ...,
+ h_pad: float | None = ...,
+ w_pad: float | None = ...,
+ rect: tuple[float, float, float, float] | None = ...
+ ) -> None: ...
+
+def figaspect(arg: float | ArrayLike) -> tuple[float, float]: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/ft2font.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/ft2font.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1638bac692d34b9827fc5a1788527f4f55c1b6ea
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/ft2font.pyi
@@ -0,0 +1,310 @@
+from enum import Enum, Flag
+import sys
+from typing import BinaryIO, Literal, TypedDict, final, overload
+from typing_extensions import Buffer # < Py 3.12
+
+import numpy as np
+from numpy.typing import NDArray
+
+__freetype_build_type__: str
+__freetype_version__: str
+
+class FaceFlags(Flag):
+ SCALABLE: int
+ FIXED_SIZES: int
+ FIXED_WIDTH: int
+ SFNT: int
+ HORIZONTAL: int
+ VERTICAL: int
+ KERNING: int
+ FAST_GLYPHS: int
+ MULTIPLE_MASTERS: int
+ GLYPH_NAMES: int
+ EXTERNAL_STREAM: int
+ HINTER: int
+ CID_KEYED: int
+ TRICKY: int
+ COLOR: int
+ # VARIATION: int # FT 2.9
+ # SVG: int # FT 2.12
+ # SBIX: int # FT 2.12
+ # SBIX_OVERLAY: int # FT 2.12
+
+class Kerning(Enum):
+ DEFAULT: int
+ UNFITTED: int
+ UNSCALED: int
+
+class LoadFlags(Flag):
+ DEFAULT: int
+ NO_SCALE: int
+ NO_HINTING: int
+ RENDER: int
+ NO_BITMAP: int
+ VERTICAL_LAYOUT: int
+ FORCE_AUTOHINT: int
+ CROP_BITMAP: int
+ PEDANTIC: int
+ IGNORE_GLOBAL_ADVANCE_WIDTH: int
+ NO_RECURSE: int
+ IGNORE_TRANSFORM: int
+ MONOCHROME: int
+ LINEAR_DESIGN: int
+ NO_AUTOHINT: int
+ COLOR: int
+ COMPUTE_METRICS: int # FT 2.6.1
+ # BITMAP_METRICS_ONLY: int # FT 2.7.1
+ # NO_SVG: int # FT 2.13.1
+ # The following should be unique, but the above can be OR'd together.
+ TARGET_NORMAL: int
+ TARGET_LIGHT: int
+ TARGET_MONO: int
+ TARGET_LCD: int
+ TARGET_LCD_V: int
+
+class StyleFlags(Flag):
+ NORMAL: int
+ ITALIC: int
+ BOLD: int
+
+class _SfntHeadDict(TypedDict):
+ version: tuple[int, int]
+ fontRevision: tuple[int, int]
+ checkSumAdjustment: int
+ magicNumber: int
+ flags: int
+ unitsPerEm: int
+ created: tuple[int, int]
+ modified: tuple[int, int]
+ xMin: int
+ yMin: int
+ xMax: int
+ yMax: int
+ macStyle: int
+ lowestRecPPEM: int
+ fontDirectionHint: int
+ indexToLocFormat: int
+ glyphDataFormat: int
+
+class _SfntMaxpDict(TypedDict):
+ version: tuple[int, int]
+ numGlyphs: int
+ maxPoints: int
+ maxContours: int
+ maxComponentPoints: int
+ maxComponentContours: int
+ maxZones: int
+ maxTwilightPoints: int
+ maxStorage: int
+ maxFunctionDefs: int
+ maxInstructionDefs: int
+ maxStackElements: int
+ maxSizeOfInstructions: int
+ maxComponentElements: int
+ maxComponentDepth: int
+
+class _SfntOs2Dict(TypedDict):
+ version: int
+ xAvgCharWidth: int
+ usWeightClass: int
+ usWidthClass: int
+ fsType: int
+ ySubscriptXSize: int
+ ySubscriptYSize: int
+ ySubscriptXOffset: int
+ ySubscriptYOffset: int
+ ySuperscriptXSize: int
+ ySuperscriptYSize: int
+ ySuperscriptXOffset: int
+ ySuperscriptYOffset: int
+ yStrikeoutSize: int
+ yStrikeoutPosition: int
+ sFamilyClass: int
+ panose: bytes
+ ulCharRange: tuple[int, int, int, int]
+ achVendID: bytes
+ fsSelection: int
+ fsFirstCharIndex: int
+ fsLastCharIndex: int
+
+class _SfntHheaDict(TypedDict):
+ version: tuple[int, int]
+ ascent: int
+ descent: int
+ lineGap: int
+ advanceWidthMax: int
+ minLeftBearing: int
+ minRightBearing: int
+ xMaxExtent: int
+ caretSlopeRise: int
+ caretSlopeRun: int
+ caretOffset: int
+ metricDataFormat: int
+ numOfLongHorMetrics: int
+
+class _SfntVheaDict(TypedDict):
+ version: tuple[int, int]
+ vertTypoAscender: int
+ vertTypoDescender: int
+ vertTypoLineGap: int
+ advanceHeightMax: int
+ minTopSideBearing: int
+ minBottomSizeBearing: int
+ yMaxExtent: int
+ caretSlopeRise: int
+ caretSlopeRun: int
+ caretOffset: int
+ metricDataFormat: int
+ numOfLongVerMetrics: int
+
+class _SfntPostDict(TypedDict):
+ format: tuple[int, int]
+ italicAngle: tuple[int, int]
+ underlinePosition: int
+ underlineThickness: int
+ isFixedPitch: int
+ minMemType42: int
+ maxMemType42: int
+ minMemType1: int
+ maxMemType1: int
+
+class _SfntPcltDict(TypedDict):
+ version: tuple[int, int]
+ fontNumber: int
+ pitch: int
+ xHeight: int
+ style: int
+ typeFamily: int
+ capHeight: int
+ symbolSet: int
+ typeFace: bytes
+ characterComplement: bytes
+ strokeWeight: int
+ widthType: int
+ serifStyle: int
+
+@final
+class FT2Font(Buffer):
+ def __init__(
+ self,
+ filename: str | BinaryIO,
+ hinting_factor: int = ...,
+ *,
+ _fallback_list: list[FT2Font] | None = ...,
+ _kerning_factor: int = ...
+ ) -> None: ...
+ if sys.version_info[:2] >= (3, 12):
+ def __buffer__(self, flags: int) -> memoryview: ...
+ def _get_fontmap(self, string: str) -> dict[str, FT2Font]: ...
+ def clear(self) -> None: ...
+ def draw_glyph_to_bitmap(
+ self, image: FT2Image, x: int, y: int, glyph: Glyph, antialiased: bool = ...
+ ) -> None: ...
+ def draw_glyphs_to_bitmap(self, antialiased: bool = ...) -> None: ...
+ def get_bitmap_offset(self) -> tuple[int, int]: ...
+ def get_char_index(self, codepoint: int) -> int: ...
+ def get_charmap(self) -> dict[int, int]: ...
+ def get_descent(self) -> int: ...
+ def get_glyph_name(self, index: int) -> str: ...
+ def get_image(self) -> NDArray[np.uint8]: ...
+ def get_kerning(self, left: int, right: int, mode: Kerning) -> int: ...
+ def get_name_index(self, name: str) -> int: ...
+ def get_num_glyphs(self) -> int: ...
+ def get_path(self) -> tuple[NDArray[np.float64], NDArray[np.int8]]: ...
+ def get_ps_font_info(
+ self,
+ ) -> tuple[str, str, str, str, str, int, int, int, int]: ...
+ def get_sfnt(self) -> dict[tuple[int, int, int, int], bytes]: ...
+ @overload
+ def get_sfnt_table(self, name: Literal["head"]) -> _SfntHeadDict | None: ...
+ @overload
+ def get_sfnt_table(self, name: Literal["maxp"]) -> _SfntMaxpDict | None: ...
+ @overload
+ def get_sfnt_table(self, name: Literal["OS/2"]) -> _SfntOs2Dict | None: ...
+ @overload
+ def get_sfnt_table(self, name: Literal["hhea"]) -> _SfntHheaDict | None: ...
+ @overload
+ def get_sfnt_table(self, name: Literal["vhea"]) -> _SfntVheaDict | None: ...
+ @overload
+ def get_sfnt_table(self, name: Literal["post"]) -> _SfntPostDict | None: ...
+ @overload
+ def get_sfnt_table(self, name: Literal["pclt"]) -> _SfntPcltDict | None: ...
+ def get_width_height(self) -> tuple[int, int]: ...
+ def load_char(self, charcode: int, flags: LoadFlags = ...) -> Glyph: ...
+ def load_glyph(self, glyphindex: int, flags: LoadFlags = ...) -> Glyph: ...
+ def select_charmap(self, i: int) -> None: ...
+ def set_charmap(self, i: int) -> None: ...
+ def set_size(self, ptsize: float, dpi: float) -> None: ...
+ def set_text(
+ self, string: str, angle: float = ..., flags: LoadFlags = ...
+ ) -> NDArray[np.float64]: ...
+ @property
+ def ascender(self) -> int: ...
+ @property
+ def bbox(self) -> tuple[int, int, int, int]: ...
+ @property
+ def descender(self) -> int: ...
+ @property
+ def face_flags(self) -> FaceFlags: ...
+ @property
+ def family_name(self) -> str: ...
+ @property
+ def fname(self) -> str: ...
+ @property
+ def height(self) -> int: ...
+ @property
+ def max_advance_height(self) -> int: ...
+ @property
+ def max_advance_width(self) -> int: ...
+ @property
+ def num_charmaps(self) -> int: ...
+ @property
+ def num_faces(self) -> int: ...
+ @property
+ def num_fixed_sizes(self) -> int: ...
+ @property
+ def num_glyphs(self) -> int: ...
+ @property
+ def postscript_name(self) -> str: ...
+ @property
+ def scalable(self) -> bool: ...
+ @property
+ def style_flags(self) -> StyleFlags: ...
+ @property
+ def style_name(self) -> str: ...
+ @property
+ def underline_position(self) -> int: ...
+ @property
+ def underline_thickness(self) -> int: ...
+ @property
+ def units_per_EM(self) -> int: ...
+
+@final
+class FT2Image(Buffer):
+ def __init__(self, width: int, height: int) -> None: ...
+ def draw_rect_filled(self, x0: int, y0: int, x1: int, y1: int) -> None: ...
+ if sys.version_info[:2] >= (3, 12):
+ def __buffer__(self, flags: int) -> memoryview: ...
+
+@final
+class Glyph:
+ @property
+ def width(self) -> int: ...
+ @property
+ def height(self) -> int: ...
+ @property
+ def horiBearingX(self) -> int: ...
+ @property
+ def horiBearingY(self) -> int: ...
+ @property
+ def horiAdvance(self) -> int: ...
+ @property
+ def linearHoriAdvance(self) -> int: ...
+ @property
+ def vertBearingX(self) -> int: ...
+ @property
+ def vertBearingY(self) -> int: ...
+ @property
+ def vertAdvance(self) -> int: ...
+ @property
+ def bbox(self) -> tuple[int, int, int, int]: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/gridspec.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/gridspec.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..08c4dd7f4e4918a259b86c2201db7055602a4000
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/gridspec.pyi
@@ -0,0 +1,160 @@
+from typing import Any, Literal, overload
+
+from numpy.typing import ArrayLike
+import numpy as np
+
+from matplotlib.axes import Axes
+from matplotlib.backend_bases import RendererBase
+from matplotlib.figure import Figure
+from matplotlib.transforms import Bbox
+
+class GridSpecBase:
+ def __init__(
+ self,
+ nrows: int,
+ ncols: int,
+ height_ratios: ArrayLike | None = ...,
+ width_ratios: ArrayLike | None = ...,
+ ) -> None: ...
+ @property
+ def nrows(self) -> int: ...
+ @property
+ def ncols(self) -> int: ...
+ def get_geometry(self) -> tuple[int, int]: ...
+ def get_subplot_params(self, figure: Figure | None = ...) -> SubplotParams: ...
+ def new_subplotspec(
+ self, loc: tuple[int, int], rowspan: int = ..., colspan: int = ...
+ ) -> SubplotSpec: ...
+ def set_width_ratios(self, width_ratios: ArrayLike | None) -> None: ...
+ def get_width_ratios(self) -> ArrayLike: ...
+ def set_height_ratios(self, height_ratios: ArrayLike | None) -> None: ...
+ def get_height_ratios(self) -> ArrayLike: ...
+ def get_grid_positions(
+ self, fig: Figure
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: ...
+ @staticmethod
+ def _check_gridspec_exists(figure: Figure, nrows: int, ncols: int) -> GridSpec: ...
+ def __getitem__(
+ self, key: tuple[int | slice, int | slice] | slice | int
+ ) -> SubplotSpec: ...
+ @overload
+ def subplots(
+ self,
+ *,
+ sharex: bool | Literal["all", "row", "col", "none"] = ...,
+ sharey: bool | Literal["all", "row", "col", "none"] = ...,
+ squeeze: Literal[False],
+ subplot_kw: dict[str, Any] | None = ...
+ ) -> np.ndarray: ...
+ @overload
+ def subplots(
+ self,
+ *,
+ sharex: bool | Literal["all", "row", "col", "none"] = ...,
+ sharey: bool | Literal["all", "row", "col", "none"] = ...,
+ squeeze: Literal[True] = ...,
+ subplot_kw: dict[str, Any] | None = ...
+ ) -> np.ndarray | Axes: ...
+
+class GridSpec(GridSpecBase):
+ left: float | None
+ bottom: float | None
+ right: float | None
+ top: float | None
+ wspace: float | None
+ hspace: float | None
+ figure: Figure | None
+ def __init__(
+ self,
+ nrows: int,
+ ncols: int,
+ figure: Figure | None = ...,
+ left: float | None = ...,
+ bottom: float | None = ...,
+ right: float | None = ...,
+ top: float | None = ...,
+ wspace: float | None = ...,
+ hspace: float | None = ...,
+ width_ratios: ArrayLike | None = ...,
+ height_ratios: ArrayLike | None = ...,
+ ) -> None: ...
+ def update(self, **kwargs: float | None) -> None: ...
+ def locally_modified_subplot_params(self) -> list[str]: ...
+ def tight_layout(
+ self,
+ figure: Figure,
+ renderer: RendererBase | None = ...,
+ pad: float = ...,
+ h_pad: float | None = ...,
+ w_pad: float | None = ...,
+ rect: tuple[float, float, float, float] | None = ...,
+ ) -> None: ...
+
+class GridSpecFromSubplotSpec(GridSpecBase):
+ figure: Figure | None
+ def __init__(
+ self,
+ nrows: int,
+ ncols: int,
+ subplot_spec: SubplotSpec,
+ wspace: float | None = ...,
+ hspace: float | None = ...,
+ height_ratios: ArrayLike | None = ...,
+ width_ratios: ArrayLike | None = ...,
+ ) -> None: ...
+ def get_topmost_subplotspec(self) -> SubplotSpec: ...
+
+class SubplotSpec:
+ num1: int
+ def __init__(
+ self, gridspec: GridSpecBase, num1: int, num2: int | None = ...
+ ) -> None: ...
+ @staticmethod
+ def _from_subplot_args(figure, args): ...
+ @property
+ def num2(self) -> int: ...
+ @num2.setter
+ def num2(self, value: int) -> None: ...
+ def get_gridspec(self) -> GridSpec: ...
+ def get_geometry(self) -> tuple[int, int, int, int]: ...
+ @property
+ def rowspan(self) -> range: ...
+ @property
+ def colspan(self) -> range: ...
+ def is_first_row(self) -> bool: ...
+ def is_last_row(self) -> bool: ...
+ def is_first_col(self) -> bool: ...
+ def is_last_col(self) -> bool: ...
+ def get_position(self, figure: Figure) -> Bbox: ...
+ def get_topmost_subplotspec(self) -> SubplotSpec: ...
+ def __eq__(self, other: object) -> bool: ...
+ def __hash__(self) -> int: ...
+ def subgridspec(
+ self, nrows: int, ncols: int, **kwargs
+ ) -> GridSpecFromSubplotSpec: ...
+
+class SubplotParams:
+ def __init__(
+ self,
+ left: float | None = ...,
+ bottom: float | None = ...,
+ right: float | None = ...,
+ top: float | None = ...,
+ wspace: float | None = ...,
+ hspace: float | None = ...,
+ ) -> None: ...
+ left: float
+ right: float
+ bottom: float
+ top: float
+ wspace: float
+ hspace: float
+ def update(
+ self,
+ left: float | None = ...,
+ bottom: float | None = ...,
+ right: float | None = ...,
+ top: float | None = ...,
+ wspace: float | None = ...,
+ hspace: float | None = ...,
+ ) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/hatch.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/hatch.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..348cf5214984bd0ba23b3953b2e79300d0e04e3f
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/hatch.pyi
@@ -0,0 +1,68 @@
+from matplotlib.path import Path
+
+import numpy as np
+from numpy.typing import ArrayLike
+
+class HatchPatternBase: ...
+
+class HorizontalHatch(HatchPatternBase):
+ num_lines: int
+ num_vertices: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+ def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
+
+class VerticalHatch(HatchPatternBase):
+ num_lines: int
+ num_vertices: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+ def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
+
+class NorthEastHatch(HatchPatternBase):
+ num_lines: int
+ num_vertices: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+ def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
+
+class SouthEastHatch(HatchPatternBase):
+ num_lines: int
+ num_vertices: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+ def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
+
+class Shapes(HatchPatternBase):
+ filled: bool
+ num_shapes: int
+ num_vertices: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+ def set_vertices_and_codes(self, vertices: ArrayLike, codes: ArrayLike) -> None: ...
+
+class Circles(Shapes):
+ shape_vertices: np.ndarray
+ shape_codes: np.ndarray
+ def __init__(self, hatch: str, density: int) -> None: ...
+
+class SmallCircles(Circles):
+ size: float
+ num_rows: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+
+class LargeCircles(Circles):
+ size: float
+ num_rows: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+
+class SmallFilledCircles(Circles):
+ size: float
+ filled: bool
+ num_rows: int
+ def __init__(self, hatch: str, density: int) -> None: ...
+
+class Stars(Shapes):
+ size: float
+ filled: bool
+ num_rows: int
+ shape_vertices: np.ndarray
+ shape_codes: np.ndarray
+ def __init__(self, hatch: str, density: int) -> None: ...
+
+def get_path(hatchpattern: str, density: int = ...) -> Path: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/image.py b/llava_video/lib/python3.10/site-packages/matplotlib/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..37a1d11678fa6d464262813c9ffc13f6ad62f268
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/image.py
@@ -0,0 +1,1763 @@
+"""
+The image module supports basic image loading, rescaling and display
+operations.
+"""
+
+import math
+import os
+import logging
+from pathlib import Path
+import warnings
+
+import numpy as np
+import PIL.Image
+import PIL.PngImagePlugin
+
+import matplotlib as mpl
+from matplotlib import _api, cbook
+# For clarity, names from _image are given explicitly in this module
+from matplotlib import _image
+# For user convenience, the names from _image are also imported into
+# the image namespace
+from matplotlib._image import * # noqa: F401, F403
+import matplotlib.artist as martist
+import matplotlib.colorizer as mcolorizer
+from matplotlib.backend_bases import FigureCanvasBase
+import matplotlib.colors as mcolors
+from matplotlib.transforms import (
+ Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo,
+ IdentityTransform, TransformedBbox)
+
+_log = logging.getLogger(__name__)
+
+# map interpolation strings to module constants
+_interpd_ = {
+ 'auto': _image.NEAREST, # this will use nearest or Hanning...
+ 'none': _image.NEAREST, # fall back to nearest when not supported
+ 'nearest': _image.NEAREST,
+ 'bilinear': _image.BILINEAR,
+ 'bicubic': _image.BICUBIC,
+ 'spline16': _image.SPLINE16,
+ 'spline36': _image.SPLINE36,
+ 'hanning': _image.HANNING,
+ 'hamming': _image.HAMMING,
+ 'hermite': _image.HERMITE,
+ 'kaiser': _image.KAISER,
+ 'quadric': _image.QUADRIC,
+ 'catrom': _image.CATROM,
+ 'gaussian': _image.GAUSSIAN,
+ 'bessel': _image.BESSEL,
+ 'mitchell': _image.MITCHELL,
+ 'sinc': _image.SINC,
+ 'lanczos': _image.LANCZOS,
+ 'blackman': _image.BLACKMAN,
+ 'antialiased': _image.NEAREST, # this will use nearest or Hanning...
+}
+
+interpolations_names = set(_interpd_)
+
+
+def composite_images(images, renderer, magnification=1.0):
+ """
+ Composite a number of RGBA images into one. The images are
+ composited in the order in which they appear in the *images* list.
+
+ Parameters
+ ----------
+ images : list of Images
+ Each must have a `make_image` method. For each image,
+ `can_composite` should return `True`, though this is not
+ enforced by this function. Each image must have a purely
+ affine transformation with no shear.
+
+ renderer : `.RendererBase`
+
+ magnification : float, default: 1
+ The additional magnification to apply for the renderer in use.
+
+ Returns
+ -------
+ image : (M, N, 4) `numpy.uint8` array
+ The composited RGBA image.
+ offset_x, offset_y : float
+ The (left, bottom) offset where the composited image should be placed
+ in the output figure.
+ """
+ if len(images) == 0:
+ return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
+
+ parts = []
+ bboxes = []
+ for image in images:
+ data, x, y, trans = image.make_image(renderer, magnification)
+ if data is not None:
+ x *= magnification
+ y *= magnification
+ parts.append((data, x, y, image._get_scalar_alpha()))
+ bboxes.append(
+ Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]]))
+
+ if len(parts) == 0:
+ return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
+
+ bbox = Bbox.union(bboxes)
+
+ output = np.zeros(
+ (int(bbox.height), int(bbox.width), 4), dtype=np.uint8)
+
+ for data, x, y, alpha in parts:
+ trans = Affine2D().translate(x - bbox.x0, y - bbox.y0)
+ _image.resample(data, output, trans, _image.NEAREST,
+ resample=False, alpha=alpha)
+
+ return output, bbox.x0 / magnification, bbox.y0 / magnification
+
+
+def _draw_list_compositing_images(
+ renderer, parent, artists, suppress_composite=None):
+ """
+ Draw a sorted list of artists, compositing images into a single
+ image where possible.
+
+ For internal Matplotlib use only: It is here to reduce duplication
+ between `Figure.draw` and `Axes.draw`, but otherwise should not be
+ generally useful.
+ """
+ has_images = any(isinstance(x, _ImageBase) for x in artists)
+
+ # override the renderer default if suppressComposite is not None
+ not_composite = (suppress_composite if suppress_composite is not None
+ else renderer.option_image_nocomposite())
+
+ if not_composite or not has_images:
+ for a in artists:
+ a.draw(renderer)
+ else:
+ # Composite any adjacent images together
+ image_group = []
+ mag = renderer.get_image_magnification()
+
+ def flush_images():
+ if len(image_group) == 1:
+ image_group[0].draw(renderer)
+ elif len(image_group) > 1:
+ data, l, b = composite_images(image_group, renderer, mag)
+ if data.size != 0:
+ gc = renderer.new_gc()
+ gc.set_clip_rectangle(parent.bbox)
+ gc.set_clip_path(parent.get_clip_path())
+ renderer.draw_image(gc, round(l), round(b), data)
+ gc.restore()
+ del image_group[:]
+
+ for a in artists:
+ if (isinstance(a, _ImageBase) and a.can_composite() and
+ a.get_clip_on() and not a.get_clip_path()):
+ image_group.append(a)
+ else:
+ flush_images()
+ a.draw(renderer)
+ flush_images()
+
+
+def _resample(
+ image_obj, data, out_shape, transform, *, resample=None, alpha=1):
+ """
+ Convenience wrapper around `._image.resample` to resample *data* to
+ *out_shape* (with a third dimension if *data* is RGBA) that takes care of
+ allocating the output array and fetching the relevant properties from the
+ Image object *image_obj*.
+ """
+ # AGG can only handle coordinates smaller than 24-bit signed integers,
+ # so raise errors if the input data is larger than _image.resample can
+ # handle.
+ msg = ('Data with more than {n} cannot be accurately displayed. '
+ 'Downsampling to less than {n} before displaying. '
+ 'To remove this warning, manually downsample your data.')
+ if data.shape[1] > 2**23:
+ warnings.warn(msg.format(n='2**23 columns'))
+ step = int(np.ceil(data.shape[1] / 2**23))
+ data = data[:, ::step]
+ transform = Affine2D().scale(step, 1) + transform
+ if data.shape[0] > 2**24:
+ warnings.warn(msg.format(n='2**24 rows'))
+ step = int(np.ceil(data.shape[0] / 2**24))
+ data = data[::step, :]
+ transform = Affine2D().scale(1, step) + transform
+ # decide if we need to apply anti-aliasing if the data is upsampled:
+ # compare the number of displayed pixels to the number of
+ # the data pixels.
+ interpolation = image_obj.get_interpolation()
+ if interpolation in ['antialiased', 'auto']:
+ # don't antialias if upsampling by an integer number or
+ # if zooming in more than a factor of 3
+ pos = np.array([[0, 0], [data.shape[1], data.shape[0]]])
+ disp = transform.transform(pos)
+ dispx = np.abs(np.diff(disp[:, 0]))
+ dispy = np.abs(np.diff(disp[:, 1]))
+ if ((dispx > 3 * data.shape[1] or
+ dispx == data.shape[1] or
+ dispx == 2 * data.shape[1]) and
+ (dispy > 3 * data.shape[0] or
+ dispy == data.shape[0] or
+ dispy == 2 * data.shape[0])):
+ interpolation = 'nearest'
+ else:
+ interpolation = 'hanning'
+ out = np.zeros(out_shape + data.shape[2:], data.dtype) # 2D->2D, 3D->3D.
+ if resample is None:
+ resample = image_obj.get_resample()
+ _image.resample(data, out, transform,
+ _interpd_[interpolation],
+ resample,
+ alpha,
+ image_obj.get_filternorm(),
+ image_obj.get_filterrad())
+ return out
+
+
+def _rgb_to_rgba(A):
+ """
+ Convert an RGB image to RGBA, as required by the image resample C++
+ extension.
+ """
+ rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype)
+ rgba[:, :, :3] = A
+ if rgba.dtype == np.uint8:
+ rgba[:, :, 3] = 255
+ else:
+ rgba[:, :, 3] = 1.0
+ return rgba
+
+
+class _ImageBase(mcolorizer.ColorizingArtist):
+ """
+ Base class for images.
+
+ interpolation and cmap default to their rc settings
+
+ cmap is a colors.Colormap instance
+ norm is a colors.Normalize instance to map luminance to 0-1
+
+ extent is data axes (left, right, bottom, top) for making image plots
+ registered with data plots. Default is to label the pixel
+ centers with the zero-based row and column indices.
+
+ Additional kwargs are matplotlib.artist properties
+ """
+ zorder = 0
+
+ def __init__(self, ax,
+ cmap=None,
+ norm=None,
+ colorizer=None,
+ interpolation=None,
+ origin=None,
+ filternorm=True,
+ filterrad=4.0,
+ resample=False,
+ *,
+ interpolation_stage=None,
+ **kwargs
+ ):
+ super().__init__(self._get_colorizer(cmap, norm, colorizer))
+ if origin is None:
+ origin = mpl.rcParams['image.origin']
+ _api.check_in_list(["upper", "lower"], origin=origin)
+ self.origin = origin
+ self.set_filternorm(filternorm)
+ self.set_filterrad(filterrad)
+ self.set_interpolation(interpolation)
+ self.set_interpolation_stage(interpolation_stage)
+ self.set_resample(resample)
+ self.axes = ax
+
+ self._imcache = None
+
+ self._internal_update(kwargs)
+
+ def __str__(self):
+ try:
+ shape = self.get_shape()
+ return f"{type(self).__name__}(shape={shape!r})"
+ except RuntimeError:
+ return type(self).__name__
+
+ def __getstate__(self):
+ # Save some space on the pickle by not saving the cache.
+ return {**super().__getstate__(), "_imcache": None}
+
+ def get_size(self):
+ """Return the size of the image as tuple (numrows, numcols)."""
+ return self.get_shape()[:2]
+
+ def get_shape(self):
+ """
+ Return the shape of the image as tuple (numrows, numcols, channels).
+ """
+ if self._A is None:
+ raise RuntimeError('You must first set the image array')
+
+ return self._A.shape
+
+ def set_alpha(self, alpha):
+ """
+ Set the alpha value used for blending - not supported on all backends.
+
+ Parameters
+ ----------
+ alpha : float or 2D array-like or None
+ """
+ martist.Artist._set_alpha_for_array(self, alpha)
+ if np.ndim(alpha) not in (0, 2):
+ raise TypeError('alpha must be a float, two-dimensional '
+ 'array, or None')
+ self._imcache = None
+
+ def _get_scalar_alpha(self):
+ """
+ Get a scalar alpha value to be applied to the artist as a whole.
+
+ If the alpha value is a matrix, the method returns 1.0 because pixels
+ have individual alpha values (see `~._ImageBase._make_image` for
+ details). If the alpha value is a scalar, the method returns said value
+ to be applied to the artist as a whole because pixels do not have
+ individual alpha values.
+ """
+ return 1.0 if self._alpha is None or np.ndim(self._alpha) > 0 \
+ else self._alpha
+
+ def changed(self):
+ """
+ Call this whenever the mappable is changed so observers can update.
+ """
+ self._imcache = None
+ super().changed()
+
+ def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
+ unsampled=False, round_to_pixel_border=True):
+ """
+ Normalize, rescale, and colormap the image *A* from the given *in_bbox*
+ (in data space), to the given *out_bbox* (in pixel space) clipped to
+ the given *clip_bbox* (also in pixel space), and magnified by the
+ *magnification* factor.
+
+ Parameters
+ ----------
+ A : ndarray
+
+ - a (M, N) array interpreted as scalar (greyscale) image,
+ with one of the dtypes `~numpy.float32`, `~numpy.float64`,
+ `~numpy.float128`, `~numpy.uint16` or `~numpy.uint8`.
+ - (M, N, 4) RGBA image with a dtype of `~numpy.float32`,
+ `~numpy.float64`, `~numpy.float128`, or `~numpy.uint8`.
+
+ in_bbox : `~matplotlib.transforms.Bbox`
+
+ out_bbox : `~matplotlib.transforms.Bbox`
+
+ clip_bbox : `~matplotlib.transforms.Bbox`
+
+ magnification : float, default: 1
+
+ unsampled : bool, default: False
+ If True, the image will not be scaled, but an appropriate
+ affine transformation will be returned instead.
+
+ round_to_pixel_border : bool, default: True
+ If True, the output image size will be rounded to the nearest pixel
+ boundary. This makes the images align correctly with the Axes.
+ It should not be used if exact scaling is needed, such as for
+ `.FigureImage`.
+
+ Returns
+ -------
+ image : (M, N, 4) `numpy.uint8` array
+ The RGBA image, resampled unless *unsampled* is True.
+ x, y : float
+ The upper left corner where the image should be drawn, in pixel
+ space.
+ trans : `~matplotlib.transforms.Affine2D`
+ The affine transformation from image to pixel space.
+ """
+ if A is None:
+ raise RuntimeError('You must first set the image '
+ 'array or the image attribute')
+ if A.size == 0:
+ raise RuntimeError("_make_image must get a non-empty image. "
+ "Your Artist's draw method must filter before "
+ "this method is called.")
+
+ clipped_bbox = Bbox.intersection(out_bbox, clip_bbox)
+
+ if clipped_bbox is None:
+ return None, 0, 0, None
+
+ out_width_base = clipped_bbox.width * magnification
+ out_height_base = clipped_bbox.height * magnification
+
+ if out_width_base == 0 or out_height_base == 0:
+ return None, 0, 0, None
+
+ if self.origin == 'upper':
+ # Flip the input image using a transform. This avoids the
+ # problem with flipping the array, which results in a copy
+ # when it is converted to contiguous in the C wrapper
+ t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1)
+ else:
+ t0 = IdentityTransform()
+
+ t0 += (
+ Affine2D()
+ .scale(
+ in_bbox.width / A.shape[1],
+ in_bbox.height / A.shape[0])
+ .translate(in_bbox.x0, in_bbox.y0)
+ + self.get_transform())
+
+ t = (t0
+ + (Affine2D()
+ .translate(-clipped_bbox.x0, -clipped_bbox.y0)
+ .scale(magnification)))
+
+ # So that the image is aligned with the edge of the Axes, we want to
+ # round up the output width to the next integer. This also means
+ # scaling the transform slightly to account for the extra subpixel.
+ if ((not unsampled) and t.is_affine and round_to_pixel_border and
+ (out_width_base % 1.0 != 0.0 or out_height_base % 1.0 != 0.0)):
+ out_width = math.ceil(out_width_base)
+ out_height = math.ceil(out_height_base)
+ extra_width = (out_width - out_width_base) / out_width_base
+ extra_height = (out_height - out_height_base) / out_height_base
+ t += Affine2D().scale(1.0 + extra_width, 1.0 + extra_height)
+ else:
+ out_width = int(out_width_base)
+ out_height = int(out_height_base)
+ out_shape = (out_height, out_width)
+
+ if not unsampled:
+ if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in (3, 4)):
+ raise ValueError(f"Invalid shape {A.shape} for image data")
+
+ # if antialiased, this needs to change as window sizes
+ # change:
+ interpolation_stage = self._interpolation_stage
+ if interpolation_stage in ['antialiased', 'auto']:
+ pos = np.array([[0, 0], [A.shape[1], A.shape[0]]])
+ disp = t.transform(pos)
+ dispx = np.abs(np.diff(disp[:, 0])) / A.shape[1]
+ dispy = np.abs(np.diff(disp[:, 1])) / A.shape[0]
+ if (dispx < 3) or (dispy < 3):
+ interpolation_stage = 'rgba'
+ else:
+ interpolation_stage = 'data'
+
+ if A.ndim == 2 and interpolation_stage == 'data':
+ # if we are a 2D array, then we are running through the
+ # norm + colormap transformation. However, in general the
+ # input data is not going to match the size on the screen so we
+ # have to resample to the correct number of pixels
+
+ if A.dtype.kind == 'f': # Float dtype: scale to same dtype.
+ scaled_dtype = np.dtype("f8" if A.dtype.itemsize > 4 else "f4")
+ if scaled_dtype.itemsize < A.dtype.itemsize:
+ _api.warn_external(f"Casting input data from {A.dtype}"
+ f" to {scaled_dtype} for imshow.")
+ else: # Int dtype, likely.
+ # TODO slice input array first
+ # Scale to appropriately sized float: use float32 if the
+ # dynamic range is small, to limit the memory footprint.
+ da = A.max().astype("f8") - A.min().astype("f8")
+ scaled_dtype = "f8" if da > 1e8 else "f4"
+
+ # resample the input data to the correct resolution and shape
+ A_resampled = _resample(self, A.astype(scaled_dtype), out_shape, t)
+
+ # if using NoNorm, cast back to the original datatype
+ if isinstance(self.norm, mcolors.NoNorm):
+ A_resampled = A_resampled.astype(A.dtype)
+
+ # Compute out_mask (what screen pixels include "bad" data
+ # pixels) and out_alpha (to what extent screen pixels are
+ # covered by data pixels: 0 outside the data extent, 1 inside
+ # (even for bad data), and intermediate values at the edges).
+ mask = (np.where(A.mask, np.float32(np.nan), np.float32(1))
+ if A.mask.shape == A.shape # nontrivial mask
+ else np.ones_like(A, np.float32))
+ # we always have to interpolate the mask to account for
+ # non-affine transformations
+ out_alpha = _resample(self, mask, out_shape, t, resample=True)
+ del mask # Make sure we don't use mask anymore!
+ out_mask = np.isnan(out_alpha)
+ out_alpha[out_mask] = 1
+ # Apply the pixel-by-pixel alpha values if present
+ alpha = self.get_alpha()
+ if alpha is not None and np.ndim(alpha) > 0:
+ out_alpha *= _resample(self, alpha, out_shape, t, resample=True)
+ # mask and run through the norm
+ resampled_masked = np.ma.masked_array(A_resampled, out_mask)
+ output = self.norm(resampled_masked)
+ else:
+ if A.ndim == 2: # interpolation_stage = 'rgba'
+ self.norm.autoscale_None(A)
+ A = self.to_rgba(A)
+ alpha = self._get_scalar_alpha()
+ if A.shape[2] == 3:
+ # No need to resample alpha or make a full array; NumPy will expand
+ # this out and cast to uint8 if necessary when it's assigned to the
+ # alpha channel below.
+ output_alpha = (255 * alpha) if A.dtype == np.uint8 else alpha
+ else:
+ output_alpha = _resample( # resample alpha channel
+ self, A[..., 3], out_shape, t, alpha=alpha)
+ output = _resample( # resample rgb channels
+ self, _rgb_to_rgba(A[..., :3]), out_shape, t, alpha=alpha)
+ output[..., 3] = output_alpha # recombine rgb and alpha
+
+ # output is now either a 2D array of normed (int or float) data
+ # or an RGBA array of re-sampled input
+ output = self.to_rgba(output, bytes=True, norm=False)
+ # output is now a correctly sized RGBA array of uint8
+
+ # Apply alpha *after* if the input was greyscale without a mask
+ if A.ndim == 2:
+ alpha = self._get_scalar_alpha()
+ alpha_channel = output[:, :, 3]
+ alpha_channel[:] = ( # Assignment will cast to uint8.
+ alpha_channel.astype(np.float32) * out_alpha * alpha)
+
+ else:
+ if self._imcache is None:
+ self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2))
+ output = self._imcache
+
+ # Subset the input image to only the part that will be displayed.
+ subset = TransformedBbox(clip_bbox, t0.inverted()).frozen()
+ output = output[
+ int(max(subset.ymin, 0)):
+ int(min(subset.ymax + 1, output.shape[0])),
+ int(max(subset.xmin, 0)):
+ int(min(subset.xmax + 1, output.shape[1]))]
+
+ t = Affine2D().translate(
+ int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t
+
+ return output, clipped_bbox.x0, clipped_bbox.y0, t
+
+ def make_image(self, renderer, magnification=1.0, unsampled=False):
+ """
+ Normalize, rescale, and colormap this image's data for rendering using
+ *renderer*, with the given *magnification*.
+
+ If *unsampled* is True, the image will not be scaled, but an
+ appropriate affine transformation will be returned instead.
+
+ Returns
+ -------
+ image : (M, N, 4) `numpy.uint8` array
+ The RGBA image, resampled unless *unsampled* is True.
+ x, y : float
+ The upper left corner where the image should be drawn, in pixel
+ space.
+ trans : `~matplotlib.transforms.Affine2D`
+ The affine transformation from image to pixel space.
+ """
+ raise NotImplementedError('The make_image method must be overridden')
+
+ def _check_unsampled_image(self):
+ """
+ Return whether the image is better to be drawn unsampled.
+
+ The derived class needs to override it.
+ """
+ return False
+
+ @martist.allow_rasterization
+ def draw(self, renderer):
+ # if not visible, declare victory and return
+ if not self.get_visible():
+ self.stale = False
+ return
+ # for empty images, there is nothing to draw!
+ if self.get_array().size == 0:
+ self.stale = False
+ return
+ # actually render the image.
+ gc = renderer.new_gc()
+ self._set_gc_clip(gc)
+ gc.set_alpha(self._get_scalar_alpha())
+ gc.set_url(self.get_url())
+ gc.set_gid(self.get_gid())
+ if (renderer.option_scale_image() # Renderer supports transform kwarg.
+ and self._check_unsampled_image()
+ and self.get_transform().is_affine):
+ im, l, b, trans = self.make_image(renderer, unsampled=True)
+ if im is not None:
+ trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans
+ renderer.draw_image(gc, l, b, im, trans)
+ else:
+ im, l, b, trans = self.make_image(
+ renderer, renderer.get_image_magnification())
+ if im is not None:
+ renderer.draw_image(gc, l, b, im)
+ gc.restore()
+ self.stale = False
+
+ def contains(self, mouseevent):
+ """Test whether the mouse event occurred within the image."""
+ if (self._different_canvas(mouseevent)
+ # This doesn't work for figimage.
+ or not self.axes.contains(mouseevent)[0]):
+ return False, {}
+ # TODO: make sure this is consistent with patch and patch
+ # collection on nonlinear transformed coordinates.
+ # TODO: consider returning image coordinates (shouldn't
+ # be too difficult given that the image is rectilinear
+ trans = self.get_transform().inverted()
+ x, y = trans.transform([mouseevent.x, mouseevent.y])
+ xmin, xmax, ymin, ymax = self.get_extent()
+ # This checks xmin <= x <= xmax *or* xmax <= x <= xmin.
+ inside = (x is not None and (x - xmin) * (x - xmax) <= 0
+ and y is not None and (y - ymin) * (y - ymax) <= 0)
+ return inside, {}
+
+ def write_png(self, fname):
+ """Write the image to png file *fname*."""
+ im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
+ bytes=True, norm=True)
+ PIL.Image.fromarray(im).save(fname, format="png")
+
+ @staticmethod
+ def _normalize_image_array(A):
+ """
+ Check validity of image-like input *A* and normalize it to a format suitable for
+ Image subclasses.
+ """
+ A = cbook.safe_masked_invalid(A, copy=True)
+ if A.dtype != np.uint8 and not np.can_cast(A.dtype, float, "same_kind"):
+ raise TypeError(f"Image data of dtype {A.dtype} cannot be "
+ f"converted to float")
+ if A.ndim == 3 and A.shape[-1] == 1:
+ A = A.squeeze(-1) # If just (M, N, 1), assume scalar and apply colormap.
+ if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in [3, 4]):
+ raise TypeError(f"Invalid shape {A.shape} for image data")
+ if A.ndim == 3:
+ # If the input data has values outside the valid range (after
+ # normalisation), we issue a warning and then clip X to the bounds
+ # - otherwise casting wraps extreme values, hiding outliers and
+ # making reliable interpretation impossible.
+ high = 255 if np.issubdtype(A.dtype, np.integer) else 1
+ if A.min() < 0 or high < A.max():
+ _log.warning(
+ 'Clipping input data to the valid range for imshow with '
+ 'RGB data ([0..1] for floats or [0..255] for integers). '
+ 'Got range [%s..%s].',
+ A.min(), A.max()
+ )
+ A = np.clip(A, 0, high)
+ # Cast unsupported integer types to uint8
+ if A.dtype != np.uint8 and np.issubdtype(A.dtype, np.integer):
+ A = A.astype(np.uint8)
+ return A
+
+ def set_data(self, A):
+ """
+ Set the image array.
+
+ Note that this function does *not* update the normalization used.
+
+ Parameters
+ ----------
+ A : array-like or `PIL.Image.Image`
+ """
+ if isinstance(A, PIL.Image.Image):
+ A = pil_to_array(A) # Needed e.g. to apply png palette.
+ self._A = self._normalize_image_array(A)
+ self._imcache = None
+ self.stale = True
+
+ def set_array(self, A):
+ """
+ Retained for backwards compatibility - use set_data instead.
+
+ Parameters
+ ----------
+ A : array-like
+ """
+ # This also needs to be here to override the inherited
+ # cm.ScalarMappable.set_array method so it is not invoked by mistake.
+ self.set_data(A)
+
+ def get_interpolation(self):
+ """
+ Return the interpolation method the image uses when resizing.
+
+ One of 'auto', 'antialiased', 'nearest', 'bilinear', 'bicubic',
+ 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
+ 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos',
+ or 'none'.
+ """
+ return self._interpolation
+
+ def set_interpolation(self, s):
+ """
+ Set the interpolation method the image uses when resizing.
+
+ If None, use :rc:`image.interpolation`. If 'none', the image is
+ shown as is without interpolating. 'none' is only supported in
+ agg, ps and pdf backends and will fall back to 'nearest' mode
+ for other backends.
+
+ Parameters
+ ----------
+ s : {'auto', 'nearest', 'bilinear', 'bicubic', 'spline16', \
+'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', \
+'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None
+ """
+ s = mpl._val_or_rc(s, 'image.interpolation').lower()
+ _api.check_in_list(interpolations_names, interpolation=s)
+ self._interpolation = s
+ self.stale = True
+
+ def get_interpolation_stage(self):
+ """
+ Return when interpolation happens during the transform to RGBA.
+
+ One of 'data', 'rgba', 'auto'.
+ """
+ return self._interpolation_stage
+
+ def set_interpolation_stage(self, s):
+ """
+ Set when interpolation happens during the transform to RGBA.
+
+ Parameters
+ ----------
+ s : {'data', 'rgba', 'auto'} or None
+ Whether to apply up/downsampling interpolation in data or RGBA
+ space. If None, use :rc:`image.interpolation_stage`.
+ If 'auto' we will check upsampling rate and if less
+ than 3 then use 'rgba', otherwise use 'data'.
+ """
+ s = mpl._val_or_rc(s, 'image.interpolation_stage')
+ _api.check_in_list(['data', 'rgba', 'auto'], s=s)
+ self._interpolation_stage = s
+ self.stale = True
+
+ def can_composite(self):
+ """Return whether the image can be composited with its neighbors."""
+ trans = self.get_transform()
+ return (
+ self._interpolation != 'none' and
+ trans.is_affine and
+ trans.is_separable)
+
+ def set_resample(self, v):
+ """
+ Set whether image resampling is used.
+
+ Parameters
+ ----------
+ v : bool or None
+ If None, use :rc:`image.resample`.
+ """
+ v = mpl._val_or_rc(v, 'image.resample')
+ self._resample = v
+ self.stale = True
+
+ def get_resample(self):
+ """Return whether image resampling is used."""
+ return self._resample
+
+ def set_filternorm(self, filternorm):
+ """
+ Set whether the resize filter normalizes the weights.
+
+ See help for `~.Axes.imshow`.
+
+ Parameters
+ ----------
+ filternorm : bool
+ """
+ self._filternorm = bool(filternorm)
+ self.stale = True
+
+ def get_filternorm(self):
+ """Return whether the resize filter normalizes the weights."""
+ return self._filternorm
+
+ def set_filterrad(self, filterrad):
+ """
+ Set the resize filter radius only applicable to some
+ interpolation schemes -- see help for imshow
+
+ Parameters
+ ----------
+ filterrad : positive float
+ """
+ r = float(filterrad)
+ if r <= 0:
+ raise ValueError("The filter radius must be a positive number")
+ self._filterrad = r
+ self.stale = True
+
+ def get_filterrad(self):
+ """Return the filterrad setting."""
+ return self._filterrad
+
+
+class AxesImage(_ImageBase):
+ """
+ An image attached to an Axes.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The Axes the image will belong to.
+ cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
+ The Colormap instance or registered colormap name used to map scalar
+ data to colors.
+ norm : str or `~matplotlib.colors.Normalize`
+ Maps luminance to 0-1.
+ interpolation : str, default: :rc:`image.interpolation`
+ Supported values are 'none', 'auto', 'nearest', 'bilinear',
+ 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
+ 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
+ 'sinc', 'lanczos', 'blackman'.
+ interpolation_stage : {'data', 'rgba'}, default: 'data'
+ If 'data', interpolation
+ is carried out on the data provided by the user. If 'rgba', the
+ interpolation is carried out after the colormapping has been
+ applied (visual interpolation).
+ origin : {'upper', 'lower'}, default: :rc:`image.origin`
+ Place the [0, 0] index of the array in the upper left or lower left
+ corner of the Axes. The convention 'upper' is typically used for
+ matrices and images.
+ extent : tuple, optional
+ The data axes (left, right, bottom, top) for making image plots
+ registered with data plots. Default is to label the pixel
+ centers with the zero-based row and column indices.
+ filternorm : bool, default: True
+ A parameter for the antigrain image resize filter
+ (see the antigrain documentation).
+ If filternorm is set, the filter normalizes integer values and corrects
+ the rounding errors. It doesn't do anything with the source floating
+ point values, it corrects only integers according to the rule of 1.0
+ which means that any sum of pixel weights must be equal to 1.0. So,
+ the filter function must produce a graph of the proper shape.
+ filterrad : float > 0, default: 4
+ The filter radius for filters that have a radius parameter, i.e. when
+ interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
+ resample : bool, default: False
+ When True, use a full resampling method. When False, only resample when
+ the output image is larger than the input image.
+ **kwargs : `~matplotlib.artist.Artist` properties
+ """
+
+ def __init__(self, ax,
+ *,
+ cmap=None,
+ norm=None,
+ colorizer=None,
+ interpolation=None,
+ origin=None,
+ extent=None,
+ filternorm=True,
+ filterrad=4.0,
+ resample=False,
+ interpolation_stage=None,
+ **kwargs
+ ):
+
+ self._extent = extent
+
+ super().__init__(
+ ax,
+ cmap=cmap,
+ norm=norm,
+ colorizer=colorizer,
+ interpolation=interpolation,
+ origin=origin,
+ filternorm=filternorm,
+ filterrad=filterrad,
+ resample=resample,
+ interpolation_stage=interpolation_stage,
+ **kwargs
+ )
+
+ def get_window_extent(self, renderer=None):
+ x0, x1, y0, y1 = self._extent
+ bbox = Bbox.from_extents([x0, y0, x1, y1])
+ return bbox.transformed(self.get_transform())
+
+ def make_image(self, renderer, magnification=1.0, unsampled=False):
+ # docstring inherited
+ trans = self.get_transform()
+ # image is created in the canvas coordinate.
+ x1, x2, y1, y2 = self.get_extent()
+ bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
+ transformed_bbox = TransformedBbox(bbox, trans)
+ clip = ((self.get_clip_box() or self.axes.bbox) if self.get_clip_on()
+ else self.get_figure(root=True).bbox)
+ return self._make_image(self._A, bbox, transformed_bbox, clip,
+ magnification, unsampled=unsampled)
+
+ def _check_unsampled_image(self):
+ """Return whether the image would be better drawn unsampled."""
+ return self.get_interpolation() == "none"
+
+ def set_extent(self, extent, **kwargs):
+ """
+ Set the image extent.
+
+ Parameters
+ ----------
+ extent : 4-tuple of float
+ The position and size of the image as tuple
+ ``(left, right, bottom, top)`` in data coordinates.
+ **kwargs
+ Other parameters from which unit info (i.e., the *xunits*,
+ *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for
+ polar Axes) entries are applied, if present.
+
+ Notes
+ -----
+ This updates `.Axes.dataLim`, and, if autoscaling, sets `.Axes.viewLim`
+ to tightly fit the image, regardless of `~.Axes.dataLim`. Autoscaling
+ state is not changed, so a subsequent call to `.Axes.autoscale_view`
+ will redo the autoscaling in accord with `~.Axes.dataLim`.
+ """
+ (xmin, xmax), (ymin, ymax) = self.axes._process_unit_info(
+ [("x", [extent[0], extent[1]]),
+ ("y", [extent[2], extent[3]])],
+ kwargs)
+ if kwargs:
+ raise _api.kwarg_error("set_extent", kwargs)
+ xmin = self.axes._validate_converted_limits(
+ xmin, self.convert_xunits)
+ xmax = self.axes._validate_converted_limits(
+ xmax, self.convert_xunits)
+ ymin = self.axes._validate_converted_limits(
+ ymin, self.convert_yunits)
+ ymax = self.axes._validate_converted_limits(
+ ymax, self.convert_yunits)
+ extent = [xmin, xmax, ymin, ymax]
+
+ self._extent = extent
+ corners = (xmin, ymin), (xmax, ymax)
+ self.axes.update_datalim(corners)
+ self.sticky_edges.x[:] = [xmin, xmax]
+ self.sticky_edges.y[:] = [ymin, ymax]
+ if self.axes.get_autoscalex_on():
+ self.axes.set_xlim((xmin, xmax), auto=None)
+ if self.axes.get_autoscaley_on():
+ self.axes.set_ylim((ymin, ymax), auto=None)
+ self.stale = True
+
+ def get_extent(self):
+ """Return the image extent as tuple (left, right, bottom, top)."""
+ if self._extent is not None:
+ return self._extent
+ else:
+ sz = self.get_size()
+ numrows, numcols = sz
+ if self.origin == 'upper':
+ return (-0.5, numcols-0.5, numrows-0.5, -0.5)
+ else:
+ return (-0.5, numcols-0.5, -0.5, numrows-0.5)
+
+ def get_cursor_data(self, event):
+ """
+ Return the image value at the event position or *None* if the event is
+ outside the image.
+
+ See Also
+ --------
+ matplotlib.artist.Artist.get_cursor_data
+ """
+ xmin, xmax, ymin, ymax = self.get_extent()
+ if self.origin == 'upper':
+ ymin, ymax = ymax, ymin
+ arr = self.get_array()
+ data_extent = Bbox([[xmin, ymin], [xmax, ymax]])
+ array_extent = Bbox([[0, 0], [arr.shape[1], arr.shape[0]]])
+ trans = self.get_transform().inverted()
+ trans += BboxTransform(boxin=data_extent, boxout=array_extent)
+ point = trans.transform([event.x, event.y])
+ if any(np.isnan(point)):
+ return None
+ j, i = point.astype(int)
+ # Clip the coordinates at array bounds
+ if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]):
+ return None
+ else:
+ return arr[i, j]
+
+
+class NonUniformImage(AxesImage):
+
+ def __init__(self, ax, *, interpolation='nearest', **kwargs):
+ """
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The Axes the image will belong to.
+ interpolation : {'nearest', 'bilinear'}, default: 'nearest'
+ The interpolation scheme used in the resampling.
+ **kwargs
+ All other keyword arguments are identical to those of `.AxesImage`.
+ """
+ super().__init__(ax, **kwargs)
+ self.set_interpolation(interpolation)
+
+ def _check_unsampled_image(self):
+ """Return False. Do not use unsampled image."""
+ return False
+
+ def make_image(self, renderer, magnification=1.0, unsampled=False):
+ # docstring inherited
+ if self._A is None:
+ raise RuntimeError('You must first set the image array')
+ if unsampled:
+ raise ValueError('unsampled not supported on NonUniformImage')
+ A = self._A
+ if A.ndim == 2:
+ if A.dtype != np.uint8:
+ A = self.to_rgba(A, bytes=True)
+ else:
+ A = np.repeat(A[:, :, np.newaxis], 4, 2)
+ A[:, :, 3] = 255
+ else:
+ if A.dtype != np.uint8:
+ A = (255*A).astype(np.uint8)
+ if A.shape[2] == 3:
+ B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8)
+ B[:, :, 0:3] = A
+ B[:, :, 3] = 255
+ A = B
+ l, b, r, t = self.axes.bbox.extents
+ width = int(((round(r) + 0.5) - (round(l) - 0.5)) * magnification)
+ height = int(((round(t) + 0.5) - (round(b) - 0.5)) * magnification)
+
+ invertedTransform = self.axes.transData.inverted()
+ x_pix = invertedTransform.transform(
+ [(x, b) for x in np.linspace(l, r, width)])[:, 0]
+ y_pix = invertedTransform.transform(
+ [(l, y) for y in np.linspace(b, t, height)])[:, 1]
+
+ if self._interpolation == "nearest":
+ x_mid = (self._Ax[:-1] + self._Ax[1:]) / 2
+ y_mid = (self._Ay[:-1] + self._Ay[1:]) / 2
+ x_int = x_mid.searchsorted(x_pix)
+ y_int = y_mid.searchsorted(y_pix)
+ # The following is equal to `A[y_int[:, None], x_int[None, :]]`,
+ # but many times faster. Both casting to uint32 (to have an
+ # effectively 1D array) and manual index flattening matter.
+ im = (
+ np.ascontiguousarray(A).view(np.uint32).ravel()[
+ np.add.outer(y_int * A.shape[1], x_int)]
+ .view(np.uint8).reshape((height, width, 4)))
+ else: # self._interpolation == "bilinear"
+ # Use np.interp to compute x_int/x_float has similar speed.
+ x_int = np.clip(
+ self._Ax.searchsorted(x_pix) - 1, 0, len(self._Ax) - 2)
+ y_int = np.clip(
+ self._Ay.searchsorted(y_pix) - 1, 0, len(self._Ay) - 2)
+ idx_int = np.add.outer(y_int * A.shape[1], x_int)
+ x_frac = np.clip(
+ np.divide(x_pix - self._Ax[x_int], np.diff(self._Ax)[x_int],
+ dtype=np.float32), # Downcasting helps with speed.
+ 0, 1)
+ y_frac = np.clip(
+ np.divide(y_pix - self._Ay[y_int], np.diff(self._Ay)[y_int],
+ dtype=np.float32),
+ 0, 1)
+ f00 = np.outer(1 - y_frac, 1 - x_frac)
+ f10 = np.outer(y_frac, 1 - x_frac)
+ f01 = np.outer(1 - y_frac, x_frac)
+ f11 = np.outer(y_frac, x_frac)
+ im = np.empty((height, width, 4), np.uint8)
+ for chan in range(4):
+ ac = A[:, :, chan].reshape(-1) # reshape(-1) avoids a copy.
+ # Shifting the buffer start (`ac[offset:]`) avoids an array
+ # addition (`ac[idx_int + offset]`).
+ buf = f00 * ac[idx_int]
+ buf += f10 * ac[A.shape[1]:][idx_int]
+ buf += f01 * ac[1:][idx_int]
+ buf += f11 * ac[A.shape[1] + 1:][idx_int]
+ im[:, :, chan] = buf # Implicitly casts to uint8.
+ return im, l, b, IdentityTransform()
+
+ def set_data(self, x, y, A):
+ """
+ Set the grid for the pixel centers, and the pixel values.
+
+ Parameters
+ ----------
+ x, y : 1D array-like
+ Monotonic arrays of shapes (N,) and (M,), respectively, specifying
+ pixel centers.
+ A : array-like
+ (M, N) `~numpy.ndarray` or masked array of values to be
+ colormapped, or (M, N, 3) RGB array, or (M, N, 4) RGBA array.
+ """
+ A = self._normalize_image_array(A)
+ x = np.array(x, np.float32)
+ y = np.array(y, np.float32)
+ if not (x.ndim == y.ndim == 1 and A.shape[:2] == y.shape + x.shape):
+ raise TypeError("Axes don't match array shape")
+ self._A = A
+ self._Ax = x
+ self._Ay = y
+ self._imcache = None
+ self.stale = True
+
+ def set_array(self, *args):
+ raise NotImplementedError('Method not supported')
+
+ def set_interpolation(self, s):
+ """
+ Parameters
+ ----------
+ s : {'nearest', 'bilinear'} or None
+ If None, use :rc:`image.interpolation`.
+ """
+ if s is not None and s not in ('nearest', 'bilinear'):
+ raise NotImplementedError('Only nearest neighbor and '
+ 'bilinear interpolations are supported')
+ super().set_interpolation(s)
+
+ def get_extent(self):
+ if self._A is None:
+ raise RuntimeError('Must set data first')
+ return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1]
+
+ def set_filternorm(self, filternorm):
+ pass
+
+ def set_filterrad(self, filterrad):
+ pass
+
+ def set_norm(self, norm):
+ if self._A is not None:
+ raise RuntimeError('Cannot change colors after loading data')
+ super().set_norm(norm)
+
+ def set_cmap(self, cmap):
+ if self._A is not None:
+ raise RuntimeError('Cannot change colors after loading data')
+ super().set_cmap(cmap)
+
+ def get_cursor_data(self, event):
+ # docstring inherited
+ x, y = event.xdata, event.ydata
+ if (x < self._Ax[0] or x > self._Ax[-1] or
+ y < self._Ay[0] or y > self._Ay[-1]):
+ return None
+ j = np.searchsorted(self._Ax, x) - 1
+ i = np.searchsorted(self._Ay, y) - 1
+ return self._A[i, j]
+
+
+class PcolorImage(AxesImage):
+ """
+ Make a pcolor-style plot with an irregular rectangular grid.
+
+ This uses a variation of the original irregular image code,
+ and it is used by pcolorfast for the corresponding grid type.
+ """
+
+ def __init__(self, ax,
+ x=None,
+ y=None,
+ A=None,
+ *,
+ cmap=None,
+ norm=None,
+ colorizer=None,
+ **kwargs
+ ):
+ """
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The Axes the image will belong to.
+ x, y : 1D array-like, optional
+ Monotonic arrays of length N+1 and M+1, respectively, specifying
+ rectangle boundaries. If not given, will default to
+ ``range(N + 1)`` and ``range(M + 1)``, respectively.
+ A : array-like
+ The data to be color-coded. The interpretation depends on the
+ shape:
+
+ - (M, N) `~numpy.ndarray` or masked array: values to be colormapped
+ - (M, N, 3): RGB array
+ - (M, N, 4): RGBA array
+
+ cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
+ The Colormap instance or registered colormap name used to map
+ scalar data to colors.
+ norm : str or `~matplotlib.colors.Normalize`
+ Maps luminance to 0-1.
+ **kwargs : `~matplotlib.artist.Artist` properties
+ """
+ super().__init__(ax, norm=norm, cmap=cmap, colorizer=colorizer)
+ self._internal_update(kwargs)
+ if A is not None:
+ self.set_data(x, y, A)
+
+ def make_image(self, renderer, magnification=1.0, unsampled=False):
+ # docstring inherited
+ if self._A is None:
+ raise RuntimeError('You must first set the image array')
+ if unsampled:
+ raise ValueError('unsampled not supported on PColorImage')
+
+ if self._imcache is None:
+ A = self.to_rgba(self._A, bytes=True)
+ self._imcache = np.pad(A, [(1, 1), (1, 1), (0, 0)], "constant")
+ padded_A = self._imcache
+ bg = mcolors.to_rgba(self.axes.patch.get_facecolor(), 0)
+ bg = (np.array(bg) * 255).astype(np.uint8)
+ if (padded_A[0, 0] != bg).all():
+ padded_A[[0, -1], :] = padded_A[:, [0, -1]] = bg
+
+ l, b, r, t = self.axes.bbox.extents
+ width = (round(r) + 0.5) - (round(l) - 0.5)
+ height = (round(t) + 0.5) - (round(b) - 0.5)
+ width = round(width * magnification)
+ height = round(height * magnification)
+ vl = self.axes.viewLim
+
+ x_pix = np.linspace(vl.x0, vl.x1, width)
+ y_pix = np.linspace(vl.y0, vl.y1, height)
+ x_int = self._Ax.searchsorted(x_pix)
+ y_int = self._Ay.searchsorted(y_pix)
+ im = ( # See comment in NonUniformImage.make_image re: performance.
+ padded_A.view(np.uint32).ravel()[
+ np.add.outer(y_int * padded_A.shape[1], x_int)]
+ .view(np.uint8).reshape((height, width, 4)))
+ return im, l, b, IdentityTransform()
+
+ def _check_unsampled_image(self):
+ return False
+
+ def set_data(self, x, y, A):
+ """
+ Set the grid for the rectangle boundaries, and the data values.
+
+ Parameters
+ ----------
+ x, y : 1D array-like, optional
+ Monotonic arrays of length N+1 and M+1, respectively, specifying
+ rectangle boundaries. If not given, will default to
+ ``range(N + 1)`` and ``range(M + 1)``, respectively.
+ A : array-like
+ The data to be color-coded. The interpretation depends on the
+ shape:
+
+ - (M, N) `~numpy.ndarray` or masked array: values to be colormapped
+ - (M, N, 3): RGB array
+ - (M, N, 4): RGBA array
+ """
+ A = self._normalize_image_array(A)
+ x = np.arange(0., A.shape[1] + 1) if x is None else np.array(x, float).ravel()
+ y = np.arange(0., A.shape[0] + 1) if y is None else np.array(y, float).ravel()
+ if A.shape[:2] != (y.size - 1, x.size - 1):
+ raise ValueError(
+ "Axes don't match array shape. Got %s, expected %s." %
+ (A.shape[:2], (y.size - 1, x.size - 1)))
+ # For efficient cursor readout, ensure x and y are increasing.
+ if x[-1] < x[0]:
+ x = x[::-1]
+ A = A[:, ::-1]
+ if y[-1] < y[0]:
+ y = y[::-1]
+ A = A[::-1]
+ self._A = A
+ self._Ax = x
+ self._Ay = y
+ self._imcache = None
+ self.stale = True
+
+ def set_array(self, *args):
+ raise NotImplementedError('Method not supported')
+
+ def get_cursor_data(self, event):
+ # docstring inherited
+ x, y = event.xdata, event.ydata
+ if (x < self._Ax[0] or x > self._Ax[-1] or
+ y < self._Ay[0] or y > self._Ay[-1]):
+ return None
+ j = np.searchsorted(self._Ax, x) - 1
+ i = np.searchsorted(self._Ay, y) - 1
+ return self._A[i, j]
+
+
+class FigureImage(_ImageBase):
+ """An image attached to a figure."""
+
+ zorder = 0
+
+ _interpolation = 'nearest'
+
+ def __init__(self, fig,
+ *,
+ cmap=None,
+ norm=None,
+ colorizer=None,
+ offsetx=0,
+ offsety=0,
+ origin=None,
+ **kwargs
+ ):
+ """
+ cmap is a colors.Colormap instance
+ norm is a colors.Normalize instance to map luminance to 0-1
+
+ kwargs are an optional list of Artist keyword args
+ """
+ super().__init__(
+ None,
+ norm=norm,
+ cmap=cmap,
+ colorizer=colorizer,
+ origin=origin
+ )
+ self.set_figure(fig)
+ self.ox = offsetx
+ self.oy = offsety
+ self._internal_update(kwargs)
+ self.magnification = 1.0
+
+ def get_extent(self):
+ """Return the image extent as tuple (left, right, bottom, top)."""
+ numrows, numcols = self.get_size()
+ return (-0.5 + self.ox, numcols-0.5 + self.ox,
+ -0.5 + self.oy, numrows-0.5 + self.oy)
+
+ def make_image(self, renderer, magnification=1.0, unsampled=False):
+ # docstring inherited
+ fig = self.get_figure(root=True)
+ fac = renderer.dpi/fig.dpi
+ # fac here is to account for pdf, eps, svg backends where
+ # figure.dpi is set to 72. This means we need to scale the
+ # image (using magnification) and offset it appropriately.
+ bbox = Bbox([[self.ox/fac, self.oy/fac],
+ [(self.ox/fac + self._A.shape[1]),
+ (self.oy/fac + self._A.shape[0])]])
+ width, height = fig.get_size_inches()
+ width *= renderer.dpi
+ height *= renderer.dpi
+ clip = Bbox([[0, 0], [width, height]])
+ return self._make_image(
+ self._A, bbox, bbox, clip, magnification=magnification / fac,
+ unsampled=unsampled, round_to_pixel_border=False)
+
+ def set_data(self, A):
+ """Set the image array."""
+ super().set_data(A)
+ self.stale = True
+
+
+class BboxImage(_ImageBase):
+ """The Image class whose size is determined by the given bbox."""
+
+ def __init__(self, bbox,
+ *,
+ cmap=None,
+ norm=None,
+ colorizer=None,
+ interpolation=None,
+ origin=None,
+ filternorm=True,
+ filterrad=4.0,
+ resample=False,
+ **kwargs
+ ):
+ """
+ cmap is a colors.Colormap instance
+ norm is a colors.Normalize instance to map luminance to 0-1
+
+ kwargs are an optional list of Artist keyword args
+ """
+ super().__init__(
+ None,
+ cmap=cmap,
+ norm=norm,
+ colorizer=colorizer,
+ interpolation=interpolation,
+ origin=origin,
+ filternorm=filternorm,
+ filterrad=filterrad,
+ resample=resample,
+ **kwargs
+ )
+ self.bbox = bbox
+
+ def get_window_extent(self, renderer=None):
+ if renderer is None:
+ renderer = self.get_figure()._get_renderer()
+
+ if isinstance(self.bbox, BboxBase):
+ return self.bbox
+ elif callable(self.bbox):
+ return self.bbox(renderer)
+ else:
+ raise ValueError("Unknown type of bbox")
+
+ def contains(self, mouseevent):
+ """Test whether the mouse event occurred within the image."""
+ if self._different_canvas(mouseevent) or not self.get_visible():
+ return False, {}
+ x, y = mouseevent.x, mouseevent.y
+ inside = self.get_window_extent().contains(x, y)
+ return inside, {}
+
+ def make_image(self, renderer, magnification=1.0, unsampled=False):
+ # docstring inherited
+ width, height = renderer.get_canvas_width_height()
+ bbox_in = self.get_window_extent(renderer).frozen()
+ bbox_in._points /= [width, height]
+ bbox_out = self.get_window_extent(renderer)
+ clip = Bbox([[0, 0], [width, height]])
+ self._transform = BboxTransformTo(clip)
+ return self._make_image(
+ self._A,
+ bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
+
+
+def imread(fname, format=None):
+ """
+ Read an image from a file into an array.
+
+ .. note::
+
+ This function exists for historical reasons. It is recommended to
+ use `PIL.Image.open` instead for loading images.
+
+ Parameters
+ ----------
+ fname : str or file-like
+ The image file to read: a filename, a URL or a file-like object opened
+ in read-binary mode.
+
+ Passing a URL is deprecated. Please open the URL
+ for reading and pass the result to Pillow, e.g. with
+ ``np.array(PIL.Image.open(urllib.request.urlopen(url)))``.
+ format : str, optional
+ The image file format assumed for reading the data. The image is
+ loaded as a PNG file if *format* is set to "png", if *fname* is a path
+ or opened file with a ".png" extension, or if it is a URL. In all
+ other cases, *format* is ignored and the format is auto-detected by
+ `PIL.Image.open`.
+
+ Returns
+ -------
+ `numpy.array`
+ The image data. The returned array has shape
+
+ - (M, N) for grayscale images.
+ - (M, N, 3) for RGB images.
+ - (M, N, 4) for RGBA images.
+
+ PNG images are returned as float arrays (0-1). All other formats are
+ returned as int arrays, with a bit depth determined by the file's
+ contents.
+ """
+ # hide imports to speed initial import on systems with slow linkers
+ from urllib import parse
+
+ if format is None:
+ if isinstance(fname, str):
+ parsed = parse.urlparse(fname)
+ # If the string is a URL (Windows paths appear as if they have a
+ # length-1 scheme), assume png.
+ if len(parsed.scheme) > 1:
+ ext = 'png'
+ else:
+ ext = Path(fname).suffix.lower()[1:]
+ elif hasattr(fname, 'geturl'): # Returned by urlopen().
+ # We could try to parse the url's path and use the extension, but
+ # returning png is consistent with the block above. Note that this
+ # if clause has to come before checking for fname.name as
+ # urlopen("file:///...") also has a name attribute (with the fixed
+ # value "").
+ ext = 'png'
+ elif hasattr(fname, 'name'):
+ ext = Path(fname.name).suffix.lower()[1:]
+ else:
+ ext = 'png'
+ else:
+ ext = format
+ img_open = (
+ PIL.PngImagePlugin.PngImageFile if ext == 'png' else PIL.Image.open)
+ if isinstance(fname, str) and len(parse.urlparse(fname).scheme) > 1:
+ # Pillow doesn't handle URLs directly.
+ raise ValueError(
+ "Please open the URL for reading and pass the "
+ "result to Pillow, e.g. with "
+ "``np.array(PIL.Image.open(urllib.request.urlopen(url)))``."
+ )
+ with img_open(fname) as image:
+ return (_pil_png_to_float_array(image)
+ if isinstance(image, PIL.PngImagePlugin.PngImageFile) else
+ pil_to_array(image))
+
+
+def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
+ origin=None, dpi=100, *, metadata=None, pil_kwargs=None):
+ """
+ Colormap and save an array as an image file.
+
+ RGB(A) images are passed through. Single channel images will be
+ colormapped according to *cmap* and *norm*.
+
+ .. note::
+
+ If you want to save a single channel image as gray scale please use an
+ image I/O library (such as pillow, tifffile, or imageio) directly.
+
+ Parameters
+ ----------
+ fname : str or path-like or file-like
+ A path or a file-like object to store the image in.
+ If *format* is not set, then the output format is inferred from the
+ extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
+ If *format* is set, it determines the output format.
+ arr : array-like
+ The image data. The shape can be one of
+ MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
+ vmin, vmax : float, optional
+ *vmin* and *vmax* set the color scaling for the image by fixing the
+ values that map to the colormap color limits. If either *vmin*
+ or *vmax* is None, that limit is determined from the *arr*
+ min/max value.
+ cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
+ A Colormap instance or registered colormap name. The colormap
+ maps scalar data to colors. It is ignored for RGB(A) data.
+ format : str, optional
+ The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this
+ is unset is documented under *fname*.
+ origin : {'upper', 'lower'}, default: :rc:`image.origin`
+ Indicates whether the ``(0, 0)`` index of the array is in the upper
+ left or lower left corner of the Axes.
+ dpi : float
+ The DPI to store in the metadata of the file. This does not affect the
+ resolution of the output image. Depending on file format, this may be
+ rounded to the nearest integer.
+ metadata : dict, optional
+ Metadata in the image file. The supported keys depend on the output
+ format, see the documentation of the respective backends for more
+ information.
+ Currently only supported for "png", "pdf", "ps", "eps", and "svg".
+ pil_kwargs : dict, optional
+ Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo'
+ key is present, it completely overrides *metadata*, including the
+ default 'Software' key.
+ """
+ from matplotlib.figure import Figure
+ if isinstance(fname, os.PathLike):
+ fname = os.fspath(fname)
+ if format is None:
+ format = (Path(fname).suffix[1:] if isinstance(fname, str)
+ else mpl.rcParams["savefig.format"]).lower()
+ if format in ["pdf", "ps", "eps", "svg"]:
+ # Vector formats that are not handled by PIL.
+ if pil_kwargs is not None:
+ raise ValueError(
+ f"Cannot use 'pil_kwargs' when saving to {format}")
+ fig = Figure(dpi=dpi, frameon=False)
+ fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
+ resize=True)
+ fig.savefig(fname, dpi=dpi, format=format, transparent=True,
+ metadata=metadata)
+ else:
+ # Don't bother creating an image; this avoids rounding errors on the
+ # size when dividing and then multiplying by dpi.
+ if origin is None:
+ origin = mpl.rcParams["image.origin"]
+ else:
+ _api.check_in_list(('upper', 'lower'), origin=origin)
+ if origin == "lower":
+ arr = arr[::-1]
+ if (isinstance(arr, memoryview) and arr.format == "B"
+ and arr.ndim == 3 and arr.shape[-1] == 4):
+ # Such an ``arr`` would also be handled fine by sm.to_rgba below
+ # (after casting with asarray), but it is useful to special-case it
+ # because that's what backend_agg passes, and can be in fact used
+ # as is, saving a few operations.
+ rgba = arr
+ else:
+ sm = mcolorizer.Colorizer(cmap=cmap)
+ sm.set_clim(vmin, vmax)
+ rgba = sm.to_rgba(arr, bytes=True)
+ if pil_kwargs is None:
+ pil_kwargs = {}
+ else:
+ # we modify this below, so make a copy (don't modify caller's dict)
+ pil_kwargs = pil_kwargs.copy()
+ pil_shape = (rgba.shape[1], rgba.shape[0])
+ rgba = np.require(rgba, requirements='C')
+ image = PIL.Image.frombuffer(
+ "RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1)
+ if format == "png":
+ # Only use the metadata kwarg if pnginfo is not set, because the
+ # semantics of duplicate keys in pnginfo is unclear.
+ if "pnginfo" in pil_kwargs:
+ if metadata:
+ _api.warn_external("'metadata' is overridden by the "
+ "'pnginfo' entry in 'pil_kwargs'.")
+ else:
+ metadata = {
+ "Software": (f"Matplotlib version{mpl.__version__}, "
+ f"https://matplotlib.org/"),
+ **(metadata if metadata is not None else {}),
+ }
+ pil_kwargs["pnginfo"] = pnginfo = PIL.PngImagePlugin.PngInfo()
+ for k, v in metadata.items():
+ if v is not None:
+ pnginfo.add_text(k, v)
+ elif metadata is not None:
+ raise ValueError(f"metadata not supported for format {format!r}")
+ if format in ["jpg", "jpeg"]:
+ format = "jpeg" # Pillow doesn't recognize "jpg".
+ facecolor = mpl.rcParams["savefig.facecolor"]
+ if cbook._str_equal(facecolor, "auto"):
+ facecolor = mpl.rcParams["figure.facecolor"]
+ color = tuple(int(x * 255) for x in mcolors.to_rgb(facecolor))
+ background = PIL.Image.new("RGB", pil_shape, color)
+ background.paste(image, image)
+ image = background
+ pil_kwargs.setdefault("format", format)
+ pil_kwargs.setdefault("dpi", (dpi, dpi))
+ image.save(fname, **pil_kwargs)
+
+
+def pil_to_array(pilImage):
+ """
+ Load a `PIL image`_ and return it as a numpy int array.
+
+ .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
+
+ Returns
+ -------
+ numpy.array
+
+ The array shape depends on the image type:
+
+ - (M, N) for grayscale images.
+ - (M, N, 3) for RGB images.
+ - (M, N, 4) for RGBA images.
+ """
+ if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
+ # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
+ return np.asarray(pilImage)
+ elif pilImage.mode.startswith('I;16'):
+ # return MxN luminance array of uint16
+ raw = pilImage.tobytes('raw', pilImage.mode)
+ if pilImage.mode.endswith('B'):
+ x = np.frombuffer(raw, '>u2')
+ else:
+ x = np.frombuffer(raw, ' None: ...
+
+#
+# END names re-exported from matplotlib._image.
+#
+
+interpolations_names: set[str]
+
+def composite_images(
+ images: Sequence[_ImageBase], renderer: RendererBase, magnification: float = ...
+) -> tuple[np.ndarray, float, float]: ...
+
+class _ImageBase(colorizer.ColorizingArtist):
+ zorder: float
+ origin: Literal["upper", "lower"]
+ axes: Axes
+ def __init__(
+ self,
+ ax: Axes,
+ cmap: str | Colormap | None = ...,
+ norm: str | Normalize | None = ...,
+ colorizer: Colorizer | None = ...,
+ interpolation: str | None = ...,
+ origin: Literal["upper", "lower"] | None = ...,
+ filternorm: bool = ...,
+ filterrad: float = ...,
+ resample: bool | None = ...,
+ *,
+ interpolation_stage: Literal["data", "rgba", "auto"] | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_size(self) -> tuple[int, int]: ...
+ def set_alpha(self, alpha: float | ArrayLike | None) -> None: ...
+ def changed(self) -> None: ...
+ def make_image(
+ self, renderer: RendererBase, magnification: float = ..., unsampled: bool = ...
+ ) -> tuple[np.ndarray, float, float, Affine2D]: ...
+ def draw(self, renderer: RendererBase) -> None: ...
+ def write_png(self, fname: str | pathlib.Path | BinaryIO) -> None: ...
+ def set_data(self, A: ArrayLike | None) -> None: ...
+ def set_array(self, A: ArrayLike | None) -> None: ...
+ def get_shape(self) -> tuple[int, int, int]: ...
+ def get_interpolation(self) -> str: ...
+ def set_interpolation(self, s: str | None) -> None: ...
+ def get_interpolation_stage(self) -> Literal["data", "rgba", "auto"]: ...
+ def set_interpolation_stage(self, s: Literal["data", "rgba", "auto"]) -> None: ...
+ def can_composite(self) -> bool: ...
+ def set_resample(self, v: bool | None) -> None: ...
+ def get_resample(self) -> bool: ...
+ def set_filternorm(self, filternorm: bool) -> None: ...
+ def get_filternorm(self) -> bool: ...
+ def set_filterrad(self, filterrad: float) -> None: ...
+ def get_filterrad(self) -> float: ...
+
+class AxesImage(_ImageBase):
+ def __init__(
+ self,
+ ax: Axes,
+ *,
+ cmap: str | Colormap | None = ...,
+ norm: str | Normalize | None = ...,
+ colorizer: Colorizer | None = ...,
+ interpolation: str | None = ...,
+ origin: Literal["upper", "lower"] | None = ...,
+ extent: tuple[float, float, float, float] | None = ...,
+ filternorm: bool = ...,
+ filterrad: float = ...,
+ resample: bool = ...,
+ interpolation_stage: Literal["data", "rgba", "auto"] | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
+ def make_image(
+ self, renderer: RendererBase, magnification: float = ..., unsampled: bool = ...
+ ) -> tuple[np.ndarray, float, float, Affine2D]: ...
+ def set_extent(
+ self, extent: tuple[float, float, float, float], **kwargs
+ ) -> None: ...
+ def get_extent(self) -> tuple[float, float, float, float]: ...
+ def get_cursor_data(self, event: MouseEvent) -> None | float: ...
+
+class NonUniformImage(AxesImage):
+ mouseover: bool
+ def __init__(
+ self, ax: Axes, *, interpolation: Literal["nearest", "bilinear"] = ..., **kwargs
+ ) -> None: ...
+ def set_data(self, x: ArrayLike, y: ArrayLike, A: ArrayLike) -> None: ... # type: ignore[override]
+ # more limited interpolation available here than base class
+ def set_interpolation(self, s: Literal["nearest", "bilinear"]) -> None: ... # type: ignore[override]
+
+class PcolorImage(AxesImage):
+ def __init__(
+ self,
+ ax: Axes,
+ x: ArrayLike | None = ...,
+ y: ArrayLike | None = ...,
+ A: ArrayLike | None = ...,
+ *,
+ cmap: str | Colormap | None = ...,
+ norm: str | Normalize | None = ...,
+ colorizer: Colorizer | None = ...,
+ **kwargs
+ ) -> None: ...
+ def set_data(self, x: ArrayLike, y: ArrayLike, A: ArrayLike) -> None: ... # type: ignore[override]
+
+class FigureImage(_ImageBase):
+ zorder: float
+ figure: Figure
+ ox: float
+ oy: float
+ magnification: float
+ def __init__(
+ self,
+ fig: Figure,
+ *,
+ cmap: str | Colormap | None = ...,
+ norm: str | Normalize | None = ...,
+ colorizer: Colorizer | None = ...,
+ offsetx: int = ...,
+ offsety: int = ...,
+ origin: Literal["upper", "lower"] | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_extent(self) -> tuple[float, float, float, float]: ...
+
+class BboxImage(_ImageBase):
+ bbox: BboxBase
+ def __init__(
+ self,
+ bbox: BboxBase | Callable[[RendererBase | None], Bbox],
+ *,
+ cmap: str | Colormap | None = ...,
+ norm: str | Normalize | None = ...,
+ colorizer: Colorizer | None = ...,
+ interpolation: str | None = ...,
+ origin: Literal["upper", "lower"] | None = ...,
+ filternorm: bool = ...,
+ filterrad: float = ...,
+ resample: bool = ...,
+ **kwargs
+ ) -> None: ...
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
+
+def imread(
+ fname: str | pathlib.Path | BinaryIO, format: str | None = ...
+) -> np.ndarray: ...
+def imsave(
+ fname: str | os.PathLike | BinaryIO,
+ arr: ArrayLike,
+ vmin: float | None = ...,
+ vmax: float | None = ...,
+ cmap: str | Colormap | None = ...,
+ format: str | None = ...,
+ origin: Literal["upper", "lower"] | None = ...,
+ dpi: float = ...,
+ *,
+ metadata: dict[str, str] | None = ...,
+ pil_kwargs: dict[str, Any] | None = ...
+) -> None: ...
+def pil_to_array(pilImage: PIL.Image.Image) -> np.ndarray: ...
+def thumbnail(
+ infile: str | BinaryIO,
+ thumbfile: str | BinaryIO,
+ scale: float = ...,
+ interpolation: str = ...,
+ preview: bool = ...,
+) -> Figure: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/inset.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/inset.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e895fd7be27c40ad07167aeca73fc7380b4d0d23
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/inset.pyi
@@ -0,0 +1,25 @@
+from . import artist
+from .axes import Axes
+from .backend_bases import RendererBase
+from .patches import ConnectionPatch, Rectangle
+
+from .typing import ColorType, LineStyleType
+
+class InsetIndicator(artist.Artist):
+ def __init__(
+ self,
+ bounds: tuple[float, float, float, float] | None = ...,
+ inset_ax: Axes | None = ...,
+ zorder: float | None = ...,
+ **kwargs
+ ) -> None: ...
+ def set_alpha(self, alpha: float | None) -> None: ...
+ def set_edgecolor(self, color: ColorType | None) -> None: ...
+ def set_color(self, c: ColorType | None) -> None: ...
+ def set_linewidth(self, w: float | None) -> None: ...
+ def set_linestyle(self, ls: LineStyleType | None) -> None: ...
+ @property
+ def rectangle(self) -> Rectangle: ...
+ @property
+ def connectors(self) -> tuple[ConnectionPatch, ConnectionPatch, ConnectionPatch, ConnectionPatch] | None: ...
+ def draw(self, renderer: RendererBase) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/layout_engine.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/layout_engine.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..5b8c812ff47f53913ff2812b58fcaf3652985a86
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/layout_engine.pyi
@@ -0,0 +1,62 @@
+from matplotlib.figure import Figure
+
+from typing import Any
+
+class LayoutEngine:
+ def __init__(self, **kwargs: Any) -> None: ...
+ def set(self) -> None: ...
+ @property
+ def colorbar_gridspec(self) -> bool: ...
+ @property
+ def adjust_compatible(self) -> bool: ...
+ def get(self) -> dict[str, Any]: ...
+ def execute(self, fig: Figure) -> None: ...
+
+class PlaceHolderLayoutEngine(LayoutEngine):
+ def __init__(
+ self, adjust_compatible: bool, colorbar_gridspec: bool, **kwargs: Any
+ ) -> None: ...
+ def execute(self, fig: Figure) -> None: ...
+
+class TightLayoutEngine(LayoutEngine):
+ def __init__(
+ self,
+ *,
+ pad: float = ...,
+ h_pad: float | None = ...,
+ w_pad: float | None = ...,
+ rect: tuple[float, float, float, float] = ...,
+ **kwargs: Any
+ ) -> None: ...
+ def execute(self, fig: Figure) -> None: ...
+ def set(
+ self,
+ *,
+ pad: float | None = ...,
+ w_pad: float | None = ...,
+ h_pad: float | None = ...,
+ rect: tuple[float, float, float, float] | None = ...
+ ) -> None: ...
+
+class ConstrainedLayoutEngine(LayoutEngine):
+ def __init__(
+ self,
+ *,
+ h_pad: float | None = ...,
+ w_pad: float | None = ...,
+ hspace: float | None = ...,
+ wspace: float | None = ...,
+ rect: tuple[float, float, float, float] = ...,
+ compress: bool = ...,
+ **kwargs: Any
+ ) -> None: ...
+ def execute(self, fig: Figure) -> Any: ...
+ def set(
+ self,
+ *,
+ h_pad: float | None = ...,
+ w_pad: float | None = ...,
+ hspace: float | None = ...,
+ wspace: float | None = ...,
+ rect: tuple[float, float, float, float] | None = ...
+ ) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/legend_handler.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/legend_handler.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..db028a136a48ed5fe58f80b56854288564316851
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/legend_handler.pyi
@@ -0,0 +1,294 @@
+from collections.abc import Callable, Sequence
+from matplotlib.artist import Artist
+from matplotlib.legend import Legend
+from matplotlib.offsetbox import OffsetBox
+from matplotlib.transforms import Transform
+
+from typing import TypeVar
+
+from numpy.typing import ArrayLike
+
+def update_from_first_child(tgt: Artist, src: Artist) -> None: ...
+
+class HandlerBase:
+ def __init__(
+ self,
+ xpad: float = ...,
+ ypad: float = ...,
+ update_func: Callable[[Artist, Artist], None] | None = ...,
+ ) -> None: ...
+ def update_prop(
+ self, legend_handle: Artist, orig_handle: Artist, legend: Legend
+ ) -> None: ...
+ def adjust_drawing_area(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ ) -> tuple[float, float, float, float]: ...
+ def legend_artist(
+ self, legend: Legend, orig_handle: Artist, fontsize: float, handlebox: OffsetBox
+ ) -> Artist: ...
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerNpoints(HandlerBase):
+ def __init__(
+ self, marker_pad: float = ..., numpoints: int | None = ..., **kwargs
+ ) -> None: ...
+ def get_numpoints(self, legend: Legend) -> int | None: ...
+ def get_xdata(
+ self,
+ legend: Legend,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ ) -> tuple[ArrayLike, ArrayLike]: ...
+
+class HandlerNpointsYoffsets(HandlerNpoints):
+ def __init__(
+ self,
+ numpoints: int | None = ...,
+ yoffsets: Sequence[float] | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_ydata(
+ self,
+ legend: Legend,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ ) -> ArrayLike: ...
+
+class HandlerLine2DCompound(HandlerNpoints):
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerLine2D(HandlerNpoints):
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerPatch(HandlerBase):
+ def __init__(self, patch_func: Callable | None = ..., **kwargs) -> None: ...
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerStepPatch(HandlerBase):
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerLineCollection(HandlerLine2D):
+ def get_numpoints(self, legend: Legend) -> int: ...
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+_T = TypeVar("_T", bound=Artist)
+
+class HandlerRegularPolyCollection(HandlerNpointsYoffsets):
+ def __init__(
+ self,
+ yoffsets: Sequence[float] | None = ...,
+ sizes: Sequence[float] | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_numpoints(self, legend: Legend) -> int: ...
+ def get_sizes(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ ) -> Sequence[float]: ...
+ def update_prop(
+ self, legend_handle, orig_handle: Artist, legend: Legend
+ ) -> None: ...
+ def create_collection(
+ self,
+ orig_handle: _T,
+ sizes: Sequence[float] | None,
+ offsets: Sequence[float] | None,
+ offset_transform: Transform,
+ ) -> _T: ...
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerPathCollection(HandlerRegularPolyCollection):
+ def create_collection(
+ self,
+ orig_handle: _T,
+ sizes: Sequence[float] | None,
+ offsets: Sequence[float] | None,
+ offset_transform: Transform,
+ ) -> _T: ...
+
+class HandlerCircleCollection(HandlerRegularPolyCollection):
+ def create_collection(
+ self,
+ orig_handle: _T,
+ sizes: Sequence[float] | None,
+ offsets: Sequence[float] | None,
+ offset_transform: Transform,
+ ) -> _T: ...
+
+class HandlerErrorbar(HandlerLine2D):
+ def __init__(
+ self,
+ xerr_size: float = ...,
+ yerr_size: float | None = ...,
+ marker_pad: float = ...,
+ numpoints: int | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_err_size(
+ self,
+ legend: Legend,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ ) -> tuple[float, float]: ...
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerStem(HandlerNpointsYoffsets):
+ def __init__(
+ self,
+ marker_pad: float = ...,
+ numpoints: int | None = ...,
+ bottom: float | None = ...,
+ yoffsets: Sequence[float] | None = ...,
+ **kwargs
+ ) -> None: ...
+ def get_ydata(
+ self,
+ legend: Legend,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ ) -> ArrayLike: ...
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerTuple(HandlerBase):
+ def __init__(
+ self, ndivide: int | None = ..., pad: float | None = ..., **kwargs
+ ) -> None: ...
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
+
+class HandlerPolyCollection(HandlerBase):
+ def create_artists(
+ self,
+ legend: Legend,
+ orig_handle: Artist,
+ xdescent: float,
+ ydescent: float,
+ width: float,
+ height: float,
+ fontsize: float,
+ trans: Transform,
+ ) -> Sequence[Artist]: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/lines.py b/llava_video/lib/python3.10/site-packages/matplotlib/lines.py
new file mode 100644
index 0000000000000000000000000000000000000000..65a4ccb6d950d92340e965599be244d71ebe029b
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/lines.py
@@ -0,0 +1,1706 @@
+"""
+2D lines with support for a variety of line styles, markers, colors, etc.
+"""
+
+import copy
+
+from numbers import Integral, Number, Real
+import logging
+
+import numpy as np
+
+import matplotlib as mpl
+from . import _api, cbook, colors as mcolors, _docstring
+from .artist import Artist, allow_rasterization
+from .cbook import (
+ _to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP)
+from .markers import MarkerStyle
+from .path import Path
+from .transforms import Bbox, BboxTransformTo, TransformedPath
+from ._enums import JoinStyle, CapStyle
+
+# Imported here for backward compatibility, even though they don't
+# really belong.
+from . import _path
+from .markers import ( # noqa
+ CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
+ CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE,
+ TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN)
+
+_log = logging.getLogger(__name__)
+
+
+def _get_dash_pattern(style):
+ """Convert linestyle to dash pattern."""
+ # go from short hand -> full strings
+ if isinstance(style, str):
+ style = ls_mapper.get(style, style)
+ # un-dashed styles
+ if style in ['solid', 'None']:
+ offset = 0
+ dashes = None
+ # dashed styles
+ elif style in ['dashed', 'dashdot', 'dotted']:
+ offset = 0
+ dashes = tuple(mpl.rcParams[f'lines.{style}_pattern'])
+ #
+ elif isinstance(style, tuple):
+ offset, dashes = style
+ if offset is None:
+ raise ValueError(f'Unrecognized linestyle: {style!r}')
+ else:
+ raise ValueError(f'Unrecognized linestyle: {style!r}')
+
+ # normalize offset to be positive and shorter than the dash cycle
+ if dashes is not None:
+ dsum = sum(dashes)
+ if dsum:
+ offset %= dsum
+
+ return offset, dashes
+
+
+def _get_inverse_dash_pattern(offset, dashes):
+ """Return the inverse of the given dash pattern, for filling the gaps."""
+ # Define the inverse pattern by moving the last gap to the start of the
+ # sequence.
+ gaps = dashes[-1:] + dashes[:-1]
+ # Set the offset so that this new first segment is skipped
+ # (see backend_bases.GraphicsContextBase.set_dashes for offset definition).
+ offset_gaps = offset + dashes[-1]
+
+ return offset_gaps, gaps
+
+
+def _scale_dashes(offset, dashes, lw):
+ if not mpl.rcParams['lines.scale_dashes']:
+ return offset, dashes
+ scaled_offset = offset * lw
+ scaled_dashes = ([x * lw if x is not None else None for x in dashes]
+ if dashes is not None else None)
+ return scaled_offset, scaled_dashes
+
+
+def segment_hits(cx, cy, x, y, radius):
+ """
+ Return the indices of the segments in the polyline with coordinates (*cx*,
+ *cy*) that are within a distance *radius* of the point (*x*, *y*).
+ """
+ # Process single points specially
+ if len(x) <= 1:
+ res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2)
+ return res
+
+ # We need to lop the last element off a lot.
+ xr, yr = x[:-1], y[:-1]
+
+ # Only look at line segments whose nearest point to C on the line
+ # lies within the segment.
+ dx, dy = x[1:] - xr, y[1:] - yr
+ Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0
+ u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq
+ candidates = (u >= 0) & (u <= 1)
+
+ # Note that there is a little area near one side of each point
+ # which will be near neither segment, and another which will
+ # be near both, depending on the angle of the lines. The
+ # following radius test eliminates these ambiguities.
+ point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2
+ candidates = candidates & ~(point_hits[:-1] | point_hits[1:])
+
+ # For those candidates which remain, determine how far they lie away
+ # from the line.
+ px, py = xr + u * dx, yr + u * dy
+ line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2
+ line_hits = line_hits & candidates
+ points, = point_hits.ravel().nonzero()
+ lines, = line_hits.ravel().nonzero()
+ return np.concatenate((points, lines))
+
+
+def _mark_every_path(markevery, tpath, affine, ax):
+ """
+ Helper function that sorts out how to deal the input
+ `markevery` and returns the points where markers should be drawn.
+
+ Takes in the `markevery` value and the line path and returns the
+ sub-sampled path.
+ """
+ # pull out the two bits of data we want from the path
+ codes, verts = tpath.codes, tpath.vertices
+
+ def _slice_or_none(in_v, slc):
+ """Helper function to cope with `codes` being an ndarray or `None`."""
+ if in_v is None:
+ return None
+ return in_v[slc]
+
+ # if just an int, assume starting at 0 and make a tuple
+ if isinstance(markevery, Integral):
+ markevery = (0, markevery)
+ # if just a float, assume starting at 0.0 and make a tuple
+ elif isinstance(markevery, Real):
+ markevery = (0.0, markevery)
+
+ if isinstance(markevery, tuple):
+ if len(markevery) != 2:
+ raise ValueError('`markevery` is a tuple but its len is not 2; '
+ f'markevery={markevery}')
+ start, step = markevery
+ # if step is an int, old behavior
+ if isinstance(step, Integral):
+ # tuple of 2 int is for backwards compatibility,
+ if not isinstance(start, Integral):
+ raise ValueError(
+ '`markevery` is a tuple with len 2 and second element is '
+ 'an int, but the first element is not an int; '
+ f'markevery={markevery}')
+ # just return, we are done here
+
+ return Path(verts[slice(start, None, step)],
+ _slice_or_none(codes, slice(start, None, step)))
+
+ elif isinstance(step, Real):
+ if not isinstance(start, Real):
+ raise ValueError(
+ '`markevery` is a tuple with len 2 and second element is '
+ 'a float, but the first element is not a float or an int; '
+ f'markevery={markevery}')
+ if ax is None:
+ raise ValueError(
+ "markevery is specified relative to the Axes size, but "
+ "the line does not have a Axes as parent")
+
+ # calc cumulative distance along path (in display coords):
+ fin = np.isfinite(verts).all(axis=1)
+ fverts = verts[fin]
+ disp_coords = affine.transform(fverts)
+
+ delta = np.empty((len(disp_coords), 2))
+ delta[0, :] = 0
+ delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :]
+ delta = np.hypot(*delta.T).cumsum()
+ # calc distance between markers along path based on the Axes
+ # bounding box diagonal being a distance of unity:
+ (x0, y0), (x1, y1) = ax.transAxes.transform([[0, 0], [1, 1]])
+ scale = np.hypot(x1 - x0, y1 - y0)
+ marker_delta = np.arange(start * scale, delta[-1], step * scale)
+ # find closest actual data point that is closest to
+ # the theoretical distance along the path:
+ inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis])
+ inds = inds.argmin(axis=1)
+ inds = np.unique(inds)
+ # return, we are done here
+ return Path(fverts[inds], _slice_or_none(codes, inds))
+ else:
+ raise ValueError(
+ f"markevery={markevery!r} is a tuple with len 2, but its "
+ f"second element is not an int or a float")
+
+ elif isinstance(markevery, slice):
+ # mazol tov, it's already a slice, just return
+ return Path(verts[markevery], _slice_or_none(codes, markevery))
+
+ elif np.iterable(markevery):
+ # fancy indexing
+ try:
+ return Path(verts[markevery], _slice_or_none(codes, markevery))
+ except (ValueError, IndexError) as err:
+ raise ValueError(
+ f"markevery={markevery!r} is iterable but not a valid numpy "
+ f"fancy index") from err
+ else:
+ raise ValueError(f"markevery={markevery!r} is not a recognized value")
+
+
+@_docstring.interpd
+@_api.define_aliases({
+ "antialiased": ["aa"],
+ "color": ["c"],
+ "drawstyle": ["ds"],
+ "linestyle": ["ls"],
+ "linewidth": ["lw"],
+ "markeredgecolor": ["mec"],
+ "markeredgewidth": ["mew"],
+ "markerfacecolor": ["mfc"],
+ "markerfacecoloralt": ["mfcalt"],
+ "markersize": ["ms"],
+})
+class Line2D(Artist):
+ """
+ A line - the line can have both a solid linestyle connecting all
+ the vertices, and a marker at each vertex. Additionally, the
+ drawing of the solid line is influenced by the drawstyle, e.g., one
+ can create "stepped" lines in various styles.
+ """
+
+ lineStyles = _lineStyles = { # hidden names deprecated
+ '-': '_draw_solid',
+ '--': '_draw_dashed',
+ '-.': '_draw_dash_dot',
+ ':': '_draw_dotted',
+ 'None': '_draw_nothing',
+ ' ': '_draw_nothing',
+ '': '_draw_nothing',
+ }
+
+ _drawStyles_l = {
+ 'default': '_draw_lines',
+ 'steps-mid': '_draw_steps_mid',
+ 'steps-pre': '_draw_steps_pre',
+ 'steps-post': '_draw_steps_post',
+ }
+
+ _drawStyles_s = {
+ 'steps': '_draw_steps_pre',
+ }
+
+ # drawStyles should now be deprecated.
+ drawStyles = {**_drawStyles_l, **_drawStyles_s}
+ # Need a list ordered with long names first:
+ drawStyleKeys = [*_drawStyles_l, *_drawStyles_s]
+
+ # Referenced here to maintain API. These are defined in
+ # MarkerStyle
+ markers = MarkerStyle.markers
+ filled_markers = MarkerStyle.filled_markers
+ fillStyles = MarkerStyle.fillstyles
+
+ zorder = 2
+
+ _subslice_optim_min_size = 1000
+
+ def __str__(self):
+ if self._label != "":
+ return f"Line2D({self._label})"
+ elif self._x is None:
+ return "Line2D()"
+ elif len(self._x) > 3:
+ return "Line2D(({:g},{:g}),({:g},{:g}),...,({:g},{:g}))".format(
+ self._x[0], self._y[0],
+ self._x[1], self._y[1],
+ self._x[-1], self._y[-1])
+ else:
+ return "Line2D(%s)" % ",".join(
+ map("({:g},{:g})".format, self._x, self._y))
+
+ def __init__(self, xdata, ydata, *,
+ linewidth=None, # all Nones default to rc
+ linestyle=None,
+ color=None,
+ gapcolor=None,
+ marker=None,
+ markersize=None,
+ markeredgewidth=None,
+ markeredgecolor=None,
+ markerfacecolor=None,
+ markerfacecoloralt='none',
+ fillstyle=None,
+ antialiased=None,
+ dash_capstyle=None,
+ solid_capstyle=None,
+ dash_joinstyle=None,
+ solid_joinstyle=None,
+ pickradius=5,
+ drawstyle=None,
+ markevery=None,
+ **kwargs
+ ):
+ """
+ Create a `.Line2D` instance with *x* and *y* data in sequences of
+ *xdata*, *ydata*.
+
+ Additional keyword arguments are `.Line2D` properties:
+
+ %(Line2D:kwdoc)s
+
+ See :meth:`set_linestyle` for a description of the line styles,
+ :meth:`set_marker` for a description of the markers, and
+ :meth:`set_drawstyle` for a description of the draw styles.
+
+ """
+ super().__init__()
+
+ # Convert sequences to NumPy arrays.
+ if not np.iterable(xdata):
+ raise RuntimeError('xdata must be a sequence')
+ if not np.iterable(ydata):
+ raise RuntimeError('ydata must be a sequence')
+
+ if linewidth is None:
+ linewidth = mpl.rcParams['lines.linewidth']
+
+ if linestyle is None:
+ linestyle = mpl.rcParams['lines.linestyle']
+ if marker is None:
+ marker = mpl.rcParams['lines.marker']
+ if color is None:
+ color = mpl.rcParams['lines.color']
+
+ if markersize is None:
+ markersize = mpl.rcParams['lines.markersize']
+ if antialiased is None:
+ antialiased = mpl.rcParams['lines.antialiased']
+ if dash_capstyle is None:
+ dash_capstyle = mpl.rcParams['lines.dash_capstyle']
+ if dash_joinstyle is None:
+ dash_joinstyle = mpl.rcParams['lines.dash_joinstyle']
+ if solid_capstyle is None:
+ solid_capstyle = mpl.rcParams['lines.solid_capstyle']
+ if solid_joinstyle is None:
+ solid_joinstyle = mpl.rcParams['lines.solid_joinstyle']
+
+ if drawstyle is None:
+ drawstyle = 'default'
+
+ self._dashcapstyle = None
+ self._dashjoinstyle = None
+ self._solidjoinstyle = None
+ self._solidcapstyle = None
+ self.set_dash_capstyle(dash_capstyle)
+ self.set_dash_joinstyle(dash_joinstyle)
+ self.set_solid_capstyle(solid_capstyle)
+ self.set_solid_joinstyle(solid_joinstyle)
+
+ self._linestyles = None
+ self._drawstyle = None
+ self._linewidth = linewidth
+ self._unscaled_dash_pattern = (0, None) # offset, dash
+ self._dash_pattern = (0, None) # offset, dash (scaled by linewidth)
+
+ self.set_linewidth(linewidth)
+ self.set_linestyle(linestyle)
+ self.set_drawstyle(drawstyle)
+
+ self._color = None
+ self.set_color(color)
+ if marker is None:
+ marker = 'none' # Default.
+ if not isinstance(marker, MarkerStyle):
+ self._marker = MarkerStyle(marker, fillstyle)
+ else:
+ self._marker = marker
+
+ self._gapcolor = None
+ self.set_gapcolor(gapcolor)
+
+ self._markevery = None
+ self._markersize = None
+ self._antialiased = None
+
+ self.set_markevery(markevery)
+ self.set_antialiased(antialiased)
+ self.set_markersize(markersize)
+
+ self._markeredgecolor = None
+ self._markeredgewidth = None
+ self._markerfacecolor = None
+ self._markerfacecoloralt = None
+
+ self.set_markerfacecolor(markerfacecolor) # Normalizes None to rc.
+ self.set_markerfacecoloralt(markerfacecoloralt)
+ self.set_markeredgecolor(markeredgecolor) # Normalizes None to rc.
+ self.set_markeredgewidth(markeredgewidth)
+
+ # update kwargs before updating data to give the caller a
+ # chance to init axes (and hence unit support)
+ self._internal_update(kwargs)
+ self.pickradius = pickradius
+ self.ind_offset = 0
+ if (isinstance(self._picker, Number) and
+ not isinstance(self._picker, bool)):
+ self._pickradius = self._picker
+
+ self._xorig = np.asarray([])
+ self._yorig = np.asarray([])
+ self._invalidx = True
+ self._invalidy = True
+ self._x = None
+ self._y = None
+ self._xy = None
+ self._path = None
+ self._transformed_path = None
+ self._subslice = False
+ self._x_filled = None # used in subslicing; only x is needed
+
+ self.set_data(xdata, ydata)
+
+ def contains(self, mouseevent):
+ """
+ Test whether *mouseevent* occurred on the line.
+
+ An event is deemed to have occurred "on" the line if it is less
+ than ``self.pickradius`` (default: 5 points) away from it. Use
+ `~.Line2D.get_pickradius` or `~.Line2D.set_pickradius` to get or set
+ the pick radius.
+
+ Parameters
+ ----------
+ mouseevent : `~matplotlib.backend_bases.MouseEvent`
+
+ Returns
+ -------
+ contains : bool
+ Whether any values are within the radius.
+ details : dict
+ A dictionary ``{'ind': pointlist}``, where *pointlist* is a
+ list of points of the line that are within the pickradius around
+ the event position.
+
+ TODO: sort returned indices by distance
+ """
+ if self._different_canvas(mouseevent):
+ return False, {}
+
+ # Make sure we have data to plot
+ if self._invalidy or self._invalidx:
+ self.recache()
+ if len(self._xy) == 0:
+ return False, {}
+
+ # Convert points to pixels
+ transformed_path = self._get_transformed_path()
+ path, affine = transformed_path.get_transformed_path_and_affine()
+ path = affine.transform_path(path)
+ xy = path.vertices
+ xt = xy[:, 0]
+ yt = xy[:, 1]
+
+ # Convert pick radius from points to pixels
+ fig = self.get_figure(root=True)
+ if fig is None:
+ _log.warning('no figure set when check if mouse is on line')
+ pixels = self._pickradius
+ else:
+ pixels = fig.dpi / 72. * self._pickradius
+
+ # The math involved in checking for containment (here and inside of
+ # segment_hits) assumes that it is OK to overflow, so temporarily set
+ # the error flags accordingly.
+ with np.errstate(all='ignore'):
+ # Check for collision
+ if self._linestyle in ['None', None]:
+ # If no line, return the nearby point(s)
+ ind, = np.nonzero(
+ (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
+ <= pixels ** 2)
+ else:
+ # If line, return the nearby segment(s)
+ ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
+ if self._drawstyle.startswith("steps"):
+ ind //= 2
+
+ ind += self.ind_offset
+
+ # Return the point(s) within radius
+ return len(ind) > 0, dict(ind=ind)
+
+ def get_pickradius(self):
+ """
+ Return the pick radius used for containment tests.
+
+ See `.contains` for more details.
+ """
+ return self._pickradius
+
+ def set_pickradius(self, pickradius):
+ """
+ Set the pick radius used for containment tests.
+
+ See `.contains` for more details.
+
+ Parameters
+ ----------
+ pickradius : float
+ Pick radius, in points.
+ """
+ if not isinstance(pickradius, Real) or pickradius < 0:
+ raise ValueError("pick radius should be a distance")
+ self._pickradius = pickradius
+
+ pickradius = property(get_pickradius, set_pickradius)
+
+ def get_fillstyle(self):
+ """
+ Return the marker fill style.
+
+ See also `~.Line2D.set_fillstyle`.
+ """
+ return self._marker.get_fillstyle()
+
+ def set_fillstyle(self, fs):
+ """
+ Set the marker fill style.
+
+ Parameters
+ ----------
+ fs : {'full', 'left', 'right', 'bottom', 'top', 'none'}
+ Possible values:
+
+ - 'full': Fill the whole marker with the *markerfacecolor*.
+ - 'left', 'right', 'bottom', 'top': Fill the marker half at
+ the given side with the *markerfacecolor*. The other
+ half of the marker is filled with *markerfacecoloralt*.
+ - 'none': No filling.
+
+ For examples see :ref:`marker_fill_styles`.
+ """
+ self.set_marker(MarkerStyle(self._marker.get_marker(), fs))
+ self.stale = True
+
+ def set_markevery(self, every):
+ """
+ Set the markevery property to subsample the plot when using markers.
+
+ e.g., if ``every=5``, every 5-th marker will be plotted.
+
+ Parameters
+ ----------
+ every : None or int or (int, int) or slice or list[int] or float or \
+(float, float) or list[bool]
+ Which markers to plot.
+
+ - ``every=None``: every point will be plotted.
+ - ``every=N``: every N-th marker will be plotted starting with
+ marker 0.
+ - ``every=(start, N)``: every N-th marker, starting at index
+ *start*, will be plotted.
+ - ``every=slice(start, end, N)``: every N-th marker, starting at
+ index *start*, up to but not including index *end*, will be
+ plotted.
+ - ``every=[i, j, m, ...]``: only markers at the given indices
+ will be plotted.
+ - ``every=[True, False, True, ...]``: only positions that are True
+ will be plotted. The list must have the same length as the data
+ points.
+ - ``every=0.1``, (i.e. a float): markers will be spaced at
+ approximately equal visual distances along the line; the distance
+ along the line between markers is determined by multiplying the
+ display-coordinate distance of the Axes bounding-box diagonal
+ by the value of *every*.
+ - ``every=(0.5, 0.1)`` (i.e. a length-2 tuple of float): similar
+ to ``every=0.1`` but the first marker will be offset along the
+ line by 0.5 multiplied by the
+ display-coordinate-diagonal-distance along the line.
+
+ For examples see
+ :doc:`/gallery/lines_bars_and_markers/markevery_demo`.
+
+ Notes
+ -----
+ Setting *markevery* will still only draw markers at actual data points.
+ While the float argument form aims for uniform visual spacing, it has
+ to coerce from the ideal spacing to the nearest available data point.
+ Depending on the number and distribution of data points, the result
+ may still not look evenly spaced.
+
+ When using a start offset to specify the first marker, the offset will
+ be from the first data point which may be different from the first
+ the visible data point if the plot is zoomed in.
+
+ If zooming in on a plot when using float arguments then the actual
+ data points that have markers will change because the distance between
+ markers is always determined from the display-coordinates
+ axes-bounding-box-diagonal regardless of the actual axes data limits.
+
+ """
+ self._markevery = every
+ self.stale = True
+
+ def get_markevery(self):
+ """
+ Return the markevery setting for marker subsampling.
+
+ See also `~.Line2D.set_markevery`.
+ """
+ return self._markevery
+
+ def set_picker(self, p):
+ """
+ Set the event picker details for the line.
+
+ Parameters
+ ----------
+ p : float or callable[[Artist, Event], tuple[bool, dict]]
+ If a float, it is used as the pick radius in points.
+ """
+ if not callable(p):
+ self.set_pickradius(p)
+ self._picker = p
+
+ def get_bbox(self):
+ """Get the bounding box of this line."""
+ bbox = Bbox([[0, 0], [0, 0]])
+ bbox.update_from_data_xy(self.get_xydata())
+ return bbox
+
+ def get_window_extent(self, renderer=None):
+ bbox = Bbox([[0, 0], [0, 0]])
+ trans_data_to_xy = self.get_transform().transform
+ bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()),
+ ignore=True)
+ # correct for marker size, if any
+ if self._marker:
+ ms = (self._markersize / 72.0 * self.get_figure(root=True).dpi) * 0.5
+ bbox = bbox.padded(ms)
+ return bbox
+
+ def set_data(self, *args):
+ """
+ Set the x and y data.
+
+ Parameters
+ ----------
+ *args : (2, N) array or two 1D arrays
+
+ See Also
+ --------
+ set_xdata
+ set_ydata
+ """
+ if len(args) == 1:
+ (x, y), = args
+ else:
+ x, y = args
+
+ self.set_xdata(x)
+ self.set_ydata(y)
+
+ def recache_always(self):
+ self.recache(always=True)
+
+ def recache(self, always=False):
+ if always or self._invalidx:
+ xconv = self.convert_xunits(self._xorig)
+ x = _to_unmasked_float_array(xconv).ravel()
+ else:
+ x = self._x
+ if always or self._invalidy:
+ yconv = self.convert_yunits(self._yorig)
+ y = _to_unmasked_float_array(yconv).ravel()
+ else:
+ y = self._y
+
+ self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float)
+ self._x, self._y = self._xy.T # views
+
+ self._subslice = False
+ if (self.axes
+ and len(x) > self._subslice_optim_min_size
+ and _path.is_sorted_and_has_non_nan(x)
+ and self.axes.name == 'rectilinear'
+ and self.axes.get_xscale() == 'linear'
+ and self._markevery is None
+ and self.get_clip_on()
+ and self.get_transform() == self.axes.transData):
+ self._subslice = True
+ nanmask = np.isnan(x)
+ if nanmask.any():
+ self._x_filled = self._x.copy()
+ indices = np.arange(len(x))
+ self._x_filled[nanmask] = np.interp(
+ indices[nanmask], indices[~nanmask], self._x[~nanmask])
+ else:
+ self._x_filled = self._x
+
+ if self._path is not None:
+ interpolation_steps = self._path._interpolation_steps
+ else:
+ interpolation_steps = 1
+ xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy.T)
+ self._path = Path(np.asarray(xy).T,
+ _interpolation_steps=interpolation_steps)
+ self._transformed_path = None
+ self._invalidx = False
+ self._invalidy = False
+
+ def _transform_path(self, subslice=None):
+ """
+ Put a TransformedPath instance at self._transformed_path;
+ all invalidation of the transform is then handled by the
+ TransformedPath instance.
+ """
+ # Masked arrays are now handled by the Path class itself
+ if subslice is not None:
+ xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy[subslice, :].T)
+ _path = Path(np.asarray(xy).T,
+ _interpolation_steps=self._path._interpolation_steps)
+ else:
+ _path = self._path
+ self._transformed_path = TransformedPath(_path, self.get_transform())
+
+ def _get_transformed_path(self):
+ """Return this line's `~matplotlib.transforms.TransformedPath`."""
+ if self._transformed_path is None:
+ self._transform_path()
+ return self._transformed_path
+
+ def set_transform(self, t):
+ # docstring inherited
+ self._invalidx = True
+ self._invalidy = True
+ super().set_transform(t)
+
+ @allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+
+ if not self.get_visible():
+ return
+
+ if self._invalidy or self._invalidx:
+ self.recache()
+ self.ind_offset = 0 # Needed for contains() method.
+ if self._subslice and self.axes:
+ x0, x1 = self.axes.get_xbound()
+ i0 = self._x_filled.searchsorted(x0, 'left')
+ i1 = self._x_filled.searchsorted(x1, 'right')
+ subslice = slice(max(i0 - 1, 0), i1 + 1)
+ self.ind_offset = subslice.start
+ self._transform_path(subslice)
+ else:
+ subslice = None
+
+ if self.get_path_effects():
+ from matplotlib.patheffects import PathEffectRenderer
+ renderer = PathEffectRenderer(self.get_path_effects(), renderer)
+
+ renderer.open_group('line2d', self.get_gid())
+ if self._lineStyles[self._linestyle] != '_draw_nothing':
+ tpath, affine = (self._get_transformed_path()
+ .get_transformed_path_and_affine())
+ if len(tpath.vertices):
+ gc = renderer.new_gc()
+ self._set_gc_clip(gc)
+ gc.set_url(self.get_url())
+
+ gc.set_antialiased(self._antialiased)
+ gc.set_linewidth(self._linewidth)
+
+ if self.is_dashed():
+ cap = self._dashcapstyle
+ join = self._dashjoinstyle
+ else:
+ cap = self._solidcapstyle
+ join = self._solidjoinstyle
+ gc.set_joinstyle(join)
+ gc.set_capstyle(cap)
+ gc.set_snap(self.get_snap())
+ if self.get_sketch_params() is not None:
+ gc.set_sketch_params(*self.get_sketch_params())
+
+ # We first draw a path within the gaps if needed.
+ if self.is_dashed() and self._gapcolor is not None:
+ lc_rgba = mcolors.to_rgba(self._gapcolor, self._alpha)
+ gc.set_foreground(lc_rgba, isRGBA=True)
+
+ offset_gaps, gaps = _get_inverse_dash_pattern(
+ *self._dash_pattern)
+
+ gc.set_dashes(offset_gaps, gaps)
+ renderer.draw_path(gc, tpath, affine.frozen())
+
+ lc_rgba = mcolors.to_rgba(self._color, self._alpha)
+ gc.set_foreground(lc_rgba, isRGBA=True)
+
+ gc.set_dashes(*self._dash_pattern)
+ renderer.draw_path(gc, tpath, affine.frozen())
+ gc.restore()
+
+ if self._marker and self._markersize > 0:
+ gc = renderer.new_gc()
+ self._set_gc_clip(gc)
+ gc.set_url(self.get_url())
+ gc.set_linewidth(self._markeredgewidth)
+ gc.set_antialiased(self._antialiased)
+
+ ec_rgba = mcolors.to_rgba(
+ self.get_markeredgecolor(), self._alpha)
+ fc_rgba = mcolors.to_rgba(
+ self._get_markerfacecolor(), self._alpha)
+ fcalt_rgba = mcolors.to_rgba(
+ self._get_markerfacecolor(alt=True), self._alpha)
+ # If the edgecolor is "auto", it is set according to the *line*
+ # color but inherits the alpha value of the *face* color, if any.
+ if (cbook._str_equal(self._markeredgecolor, "auto")
+ and not cbook._str_lower_equal(
+ self.get_markerfacecolor(), "none")):
+ ec_rgba = ec_rgba[:3] + (fc_rgba[3],)
+ gc.set_foreground(ec_rgba, isRGBA=True)
+ if self.get_sketch_params() is not None:
+ scale, length, randomness = self.get_sketch_params()
+ gc.set_sketch_params(scale/2, length/2, 2*randomness)
+
+ marker = self._marker
+
+ # Markers *must* be drawn ignoring the drawstyle (but don't pay the
+ # recaching if drawstyle is already "default").
+ if self.get_drawstyle() != "default":
+ with cbook._setattr_cm(
+ self, _drawstyle="default", _transformed_path=None):
+ self.recache()
+ self._transform_path(subslice)
+ tpath, affine = (self._get_transformed_path()
+ .get_transformed_points_and_affine())
+ else:
+ tpath, affine = (self._get_transformed_path()
+ .get_transformed_points_and_affine())
+
+ if len(tpath.vertices):
+ # subsample the markers if markevery is not None
+ markevery = self.get_markevery()
+ if markevery is not None:
+ subsampled = _mark_every_path(
+ markevery, tpath, affine, self.axes)
+ else:
+ subsampled = tpath
+
+ snap = marker.get_snap_threshold()
+ if isinstance(snap, Real):
+ snap = renderer.points_to_pixels(self._markersize) >= snap
+ gc.set_snap(snap)
+ gc.set_joinstyle(marker.get_joinstyle())
+ gc.set_capstyle(marker.get_capstyle())
+ marker_path = marker.get_path()
+ marker_trans = marker.get_transform()
+ w = renderer.points_to_pixels(self._markersize)
+
+ if cbook._str_equal(marker.get_marker(), ","):
+ gc.set_linewidth(0)
+ else:
+ # Don't scale for pixels, and don't stroke them
+ marker_trans = marker_trans.scale(w)
+ renderer.draw_markers(gc, marker_path, marker_trans,
+ subsampled, affine.frozen(),
+ fc_rgba)
+
+ alt_marker_path = marker.get_alt_path()
+ if alt_marker_path:
+ alt_marker_trans = marker.get_alt_transform()
+ alt_marker_trans = alt_marker_trans.scale(w)
+ renderer.draw_markers(
+ gc, alt_marker_path, alt_marker_trans, subsampled,
+ affine.frozen(), fcalt_rgba)
+
+ gc.restore()
+
+ renderer.close_group('line2d')
+ self.stale = False
+
+ def get_antialiased(self):
+ """Return whether antialiased rendering is used."""
+ return self._antialiased
+
+ def get_color(self):
+ """
+ Return the line color.
+
+ See also `~.Line2D.set_color`.
+ """
+ return self._color
+
+ def get_drawstyle(self):
+ """
+ Return the drawstyle.
+
+ See also `~.Line2D.set_drawstyle`.
+ """
+ return self._drawstyle
+
+ def get_gapcolor(self):
+ """
+ Return the line gapcolor.
+
+ See also `~.Line2D.set_gapcolor`.
+ """
+ return self._gapcolor
+
+ def get_linestyle(self):
+ """
+ Return the linestyle.
+
+ See also `~.Line2D.set_linestyle`.
+ """
+ return self._linestyle
+
+ def get_linewidth(self):
+ """
+ Return the linewidth in points.
+
+ See also `~.Line2D.set_linewidth`.
+ """
+ return self._linewidth
+
+ def get_marker(self):
+ """
+ Return the line marker.
+
+ See also `~.Line2D.set_marker`.
+ """
+ return self._marker.get_marker()
+
+ def get_markeredgecolor(self):
+ """
+ Return the marker edge color.
+
+ See also `~.Line2D.set_markeredgecolor`.
+ """
+ mec = self._markeredgecolor
+ if cbook._str_equal(mec, 'auto'):
+ if mpl.rcParams['_internal.classic_mode']:
+ if self._marker.get_marker() in ('.', ','):
+ return self._color
+ if (self._marker.is_filled()
+ and self._marker.get_fillstyle() != 'none'):
+ return 'k' # Bad hard-wired default...
+ return self._color
+ else:
+ return mec
+
+ def get_markeredgewidth(self):
+ """
+ Return the marker edge width in points.
+
+ See also `~.Line2D.set_markeredgewidth`.
+ """
+ return self._markeredgewidth
+
+ def _get_markerfacecolor(self, alt=False):
+ if self._marker.get_fillstyle() == 'none':
+ return 'none'
+ fc = self._markerfacecoloralt if alt else self._markerfacecolor
+ if cbook._str_lower_equal(fc, 'auto'):
+ return self._color
+ else:
+ return fc
+
+ def get_markerfacecolor(self):
+ """
+ Return the marker face color.
+
+ See also `~.Line2D.set_markerfacecolor`.
+ """
+ return self._get_markerfacecolor(alt=False)
+
+ def get_markerfacecoloralt(self):
+ """
+ Return the alternate marker face color.
+
+ See also `~.Line2D.set_markerfacecoloralt`.
+ """
+ return self._get_markerfacecolor(alt=True)
+
+ def get_markersize(self):
+ """
+ Return the marker size in points.
+
+ See also `~.Line2D.set_markersize`.
+ """
+ return self._markersize
+
+ def get_data(self, orig=True):
+ """
+ Return the line data as an ``(xdata, ydata)`` pair.
+
+ If *orig* is *True*, return the original data.
+ """
+ return self.get_xdata(orig=orig), self.get_ydata(orig=orig)
+
+ def get_xdata(self, orig=True):
+ """
+ Return the xdata.
+
+ If *orig* is *True*, return the original data, else the
+ processed data.
+ """
+ if orig:
+ return self._xorig
+ if self._invalidx:
+ self.recache()
+ return self._x
+
+ def get_ydata(self, orig=True):
+ """
+ Return the ydata.
+
+ If *orig* is *True*, return the original data, else the
+ processed data.
+ """
+ if orig:
+ return self._yorig
+ if self._invalidy:
+ self.recache()
+ return self._y
+
+ def get_path(self):
+ """Return the `~matplotlib.path.Path` associated with this line."""
+ if self._invalidy or self._invalidx:
+ self.recache()
+ return self._path
+
+ def get_xydata(self):
+ """Return the *xy* data as a (N, 2) array."""
+ if self._invalidy or self._invalidx:
+ self.recache()
+ return self._xy
+
+ def set_antialiased(self, b):
+ """
+ Set whether to use antialiased rendering.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ if self._antialiased != b:
+ self.stale = True
+ self._antialiased = b
+
+ def set_color(self, color):
+ """
+ Set the color of the line.
+
+ Parameters
+ ----------
+ color : :mpltype:`color`
+ """
+ mcolors._check_color_like(color=color)
+ self._color = color
+ self.stale = True
+
+ def set_drawstyle(self, drawstyle):
+ """
+ Set the drawstyle of the plot.
+
+ The drawstyle determines how the points are connected.
+
+ Parameters
+ ----------
+ drawstyle : {'default', 'steps', 'steps-pre', 'steps-mid', \
+'steps-post'}, default: 'default'
+ For 'default', the points are connected with straight lines.
+
+ The steps variants connect the points with step-like lines,
+ i.e. horizontal lines with vertical steps. They differ in the
+ location of the step:
+
+ - 'steps-pre': The step is at the beginning of the line segment,
+ i.e. the line will be at the y-value of point to the right.
+ - 'steps-mid': The step is halfway between the points.
+ - 'steps-post: The step is at the end of the line segment,
+ i.e. the line will be at the y-value of the point to the left.
+ - 'steps' is equal to 'steps-pre' and is maintained for
+ backward-compatibility.
+
+ For examples see :doc:`/gallery/lines_bars_and_markers/step_demo`.
+ """
+ if drawstyle is None:
+ drawstyle = 'default'
+ _api.check_in_list(self.drawStyles, drawstyle=drawstyle)
+ if self._drawstyle != drawstyle:
+ self.stale = True
+ # invalidate to trigger a recache of the path
+ self._invalidx = True
+ self._drawstyle = drawstyle
+
+ def set_gapcolor(self, gapcolor):
+ """
+ Set a color to fill the gaps in the dashed line style.
+
+ .. note::
+
+ Striped lines are created by drawing two interleaved dashed lines.
+ There can be overlaps between those two, which may result in
+ artifacts when using transparency.
+
+ This functionality is experimental and may change.
+
+ Parameters
+ ----------
+ gapcolor : :mpltype:`color` or None
+ The color with which to fill the gaps. If None, the gaps are
+ unfilled.
+ """
+ if gapcolor is not None:
+ mcolors._check_color_like(color=gapcolor)
+ self._gapcolor = gapcolor
+ self.stale = True
+
+ def set_linewidth(self, w):
+ """
+ Set the line width in points.
+
+ Parameters
+ ----------
+ w : float
+ Line width, in points.
+ """
+ w = float(w)
+ if self._linewidth != w:
+ self.stale = True
+ self._linewidth = w
+ self._dash_pattern = _scale_dashes(*self._unscaled_dash_pattern, w)
+
+ def set_linestyle(self, ls):
+ """
+ Set the linestyle of the line.
+
+ Parameters
+ ----------
+ ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
+ Possible values:
+
+ - A string:
+
+ ========================================== =================
+ linestyle description
+ ========================================== =================
+ ``'-'`` or ``'solid'`` solid line
+ ``'--'`` or ``'dashed'`` dashed line
+ ``'-.'`` or ``'dashdot'`` dash-dotted line
+ ``':'`` or ``'dotted'`` dotted line
+ ``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing
+ ========================================== =================
+
+ - Alternatively a dash tuple of the following form can be
+ provided::
+
+ (offset, onoffseq)
+
+ where ``onoffseq`` is an even length tuple of on and off ink
+ in points. See also :meth:`set_dashes`.
+
+ For examples see :doc:`/gallery/lines_bars_and_markers/linestyles`.
+ """
+ if isinstance(ls, str):
+ if ls in [' ', '', 'none']:
+ ls = 'None'
+ _api.check_in_list([*self._lineStyles, *ls_mapper_r], ls=ls)
+ if ls not in self._lineStyles:
+ ls = ls_mapper_r[ls]
+ self._linestyle = ls
+ else:
+ self._linestyle = '--'
+ self._unscaled_dash_pattern = _get_dash_pattern(ls)
+ self._dash_pattern = _scale_dashes(
+ *self._unscaled_dash_pattern, self._linewidth)
+ self.stale = True
+
+ @_docstring.interpd
+ def set_marker(self, marker):
+ """
+ Set the line marker.
+
+ Parameters
+ ----------
+ marker : marker style string, `~.path.Path` or `~.markers.MarkerStyle`
+ See `~matplotlib.markers` for full description of possible
+ arguments.
+ """
+ self._marker = MarkerStyle(marker, self._marker.get_fillstyle())
+ self.stale = True
+
+ def _set_markercolor(self, name, has_rcdefault, val):
+ if val is None:
+ val = mpl.rcParams[f"lines.{name}"] if has_rcdefault else "auto"
+ attr = f"_{name}"
+ current = getattr(self, attr)
+ if current is None:
+ self.stale = True
+ else:
+ neq = current != val
+ # Much faster than `np.any(current != val)` if no arrays are used.
+ if neq.any() if isinstance(neq, np.ndarray) else neq:
+ self.stale = True
+ setattr(self, attr, val)
+
+ def set_markeredgecolor(self, ec):
+ """
+ Set the marker edge color.
+
+ Parameters
+ ----------
+ ec : :mpltype:`color`
+ """
+ self._set_markercolor("markeredgecolor", True, ec)
+
+ def set_markerfacecolor(self, fc):
+ """
+ Set the marker face color.
+
+ Parameters
+ ----------
+ fc : :mpltype:`color`
+ """
+ self._set_markercolor("markerfacecolor", True, fc)
+
+ def set_markerfacecoloralt(self, fc):
+ """
+ Set the alternate marker face color.
+
+ Parameters
+ ----------
+ fc : :mpltype:`color`
+ """
+ self._set_markercolor("markerfacecoloralt", False, fc)
+
+ def set_markeredgewidth(self, ew):
+ """
+ Set the marker edge width in points.
+
+ Parameters
+ ----------
+ ew : float
+ Marker edge width, in points.
+ """
+ if ew is None:
+ ew = mpl.rcParams['lines.markeredgewidth']
+ if self._markeredgewidth != ew:
+ self.stale = True
+ self._markeredgewidth = ew
+
+ def set_markersize(self, sz):
+ """
+ Set the marker size in points.
+
+ Parameters
+ ----------
+ sz : float
+ Marker size, in points.
+ """
+ sz = float(sz)
+ if self._markersize != sz:
+ self.stale = True
+ self._markersize = sz
+
+ def set_xdata(self, x):
+ """
+ Set the data array for x.
+
+ Parameters
+ ----------
+ x : 1D array
+
+ See Also
+ --------
+ set_data
+ set_ydata
+ """
+ if not np.iterable(x):
+ raise RuntimeError('x must be a sequence')
+ self._xorig = copy.copy(x)
+ self._invalidx = True
+ self.stale = True
+
+ def set_ydata(self, y):
+ """
+ Set the data array for y.
+
+ Parameters
+ ----------
+ y : 1D array
+
+ See Also
+ --------
+ set_data
+ set_xdata
+ """
+ if not np.iterable(y):
+ raise RuntimeError('y must be a sequence')
+ self._yorig = copy.copy(y)
+ self._invalidy = True
+ self.stale = True
+
+ def set_dashes(self, seq):
+ """
+ Set the dash sequence.
+
+ The dash sequence is a sequence of floats of even length describing
+ the length of dashes and spaces in points.
+
+ For example, (5, 2, 1, 2) describes a sequence of 5 point and 1 point
+ dashes separated by 2 point spaces.
+
+ See also `~.Line2D.set_gapcolor`, which allows those spaces to be
+ filled with a color.
+
+ Parameters
+ ----------
+ seq : sequence of floats (on/off ink in points) or (None, None)
+ If *seq* is empty or ``(None, None)``, the linestyle will be set
+ to solid.
+ """
+ if seq == (None, None) or len(seq) == 0:
+ self.set_linestyle('-')
+ else:
+ self.set_linestyle((0, seq))
+
+ def update_from(self, other):
+ """Copy properties from *other* to self."""
+ super().update_from(other)
+ self._linestyle = other._linestyle
+ self._linewidth = other._linewidth
+ self._color = other._color
+ self._gapcolor = other._gapcolor
+ self._markersize = other._markersize
+ self._markerfacecolor = other._markerfacecolor
+ self._markerfacecoloralt = other._markerfacecoloralt
+ self._markeredgecolor = other._markeredgecolor
+ self._markeredgewidth = other._markeredgewidth
+ self._unscaled_dash_pattern = other._unscaled_dash_pattern
+ self._dash_pattern = other._dash_pattern
+ self._dashcapstyle = other._dashcapstyle
+ self._dashjoinstyle = other._dashjoinstyle
+ self._solidcapstyle = other._solidcapstyle
+ self._solidjoinstyle = other._solidjoinstyle
+
+ self._linestyle = other._linestyle
+ self._marker = MarkerStyle(marker=other._marker)
+ self._drawstyle = other._drawstyle
+
+ @_docstring.interpd
+ def set_dash_joinstyle(self, s):
+ """
+ How to join segments of the line if it `~Line2D.is_dashed`.
+
+ The default joinstyle is :rc:`lines.dash_joinstyle`.
+
+ Parameters
+ ----------
+ s : `.JoinStyle` or %(JoinStyle)s
+ """
+ js = JoinStyle(s)
+ if self._dashjoinstyle != js:
+ self.stale = True
+ self._dashjoinstyle = js
+
+ @_docstring.interpd
+ def set_solid_joinstyle(self, s):
+ """
+ How to join segments if the line is solid (not `~Line2D.is_dashed`).
+
+ The default joinstyle is :rc:`lines.solid_joinstyle`.
+
+ Parameters
+ ----------
+ s : `.JoinStyle` or %(JoinStyle)s
+ """
+ js = JoinStyle(s)
+ if self._solidjoinstyle != js:
+ self.stale = True
+ self._solidjoinstyle = js
+
+ def get_dash_joinstyle(self):
+ """
+ Return the `.JoinStyle` for dashed lines.
+
+ See also `~.Line2D.set_dash_joinstyle`.
+ """
+ return self._dashjoinstyle.name
+
+ def get_solid_joinstyle(self):
+ """
+ Return the `.JoinStyle` for solid lines.
+
+ See also `~.Line2D.set_solid_joinstyle`.
+ """
+ return self._solidjoinstyle.name
+
+ @_docstring.interpd
+ def set_dash_capstyle(self, s):
+ """
+ How to draw the end caps if the line is `~Line2D.is_dashed`.
+
+ The default capstyle is :rc:`lines.dash_capstyle`.
+
+ Parameters
+ ----------
+ s : `.CapStyle` or %(CapStyle)s
+ """
+ cs = CapStyle(s)
+ if self._dashcapstyle != cs:
+ self.stale = True
+ self._dashcapstyle = cs
+
+ @_docstring.interpd
+ def set_solid_capstyle(self, s):
+ """
+ How to draw the end caps if the line is solid (not `~Line2D.is_dashed`)
+
+ The default capstyle is :rc:`lines.solid_capstyle`.
+
+ Parameters
+ ----------
+ s : `.CapStyle` or %(CapStyle)s
+ """
+ cs = CapStyle(s)
+ if self._solidcapstyle != cs:
+ self.stale = True
+ self._solidcapstyle = cs
+
+ def get_dash_capstyle(self):
+ """
+ Return the `.CapStyle` for dashed lines.
+
+ See also `~.Line2D.set_dash_capstyle`.
+ """
+ return self._dashcapstyle.name
+
+ def get_solid_capstyle(self):
+ """
+ Return the `.CapStyle` for solid lines.
+
+ See also `~.Line2D.set_solid_capstyle`.
+ """
+ return self._solidcapstyle.name
+
+ def is_dashed(self):
+ """
+ Return whether line has a dashed linestyle.
+
+ A custom linestyle is assumed to be dashed, we do not inspect the
+ ``onoffseq`` directly.
+
+ See also `~.Line2D.set_linestyle`.
+ """
+ return self._linestyle in ('--', '-.', ':')
+
+
+class AxLine(Line2D):
+ """
+ A helper class that implements `~.Axes.axline`, by recomputing the artist
+ transform at draw time.
+ """
+
+ def __init__(self, xy1, xy2, slope, **kwargs):
+ """
+ Parameters
+ ----------
+ xy1 : (float, float)
+ The first set of (x, y) coordinates for the line to pass through.
+ xy2 : (float, float) or None
+ The second set of (x, y) coordinates for the line to pass through.
+ Both *xy2* and *slope* must be passed, but one of them must be None.
+ slope : float or None
+ The slope of the line. Both *xy2* and *slope* must be passed, but one of
+ them must be None.
+ """
+ super().__init__([0, 1], [0, 1], **kwargs)
+
+ if (xy2 is None and slope is None or
+ xy2 is not None and slope is not None):
+ raise TypeError(
+ "Exactly one of 'xy2' and 'slope' must be given")
+
+ self._slope = slope
+ self._xy1 = xy1
+ self._xy2 = xy2
+
+ def get_transform(self):
+ ax = self.axes
+ points_transform = self._transform - ax.transData + ax.transScale
+
+ if self._xy2 is not None:
+ # two points were given
+ (x1, y1), (x2, y2) = \
+ points_transform.transform([self._xy1, self._xy2])
+ dx = x2 - x1
+ dy = y2 - y1
+ if dx == 0:
+ if dy == 0:
+ raise ValueError(
+ f"Cannot draw a line through two identical points "
+ f"(x={(x1, x2)}, y={(y1, y2)})")
+ slope = np.inf
+ else:
+ slope = dy / dx
+ else:
+ # one point and a slope were given
+ x1, y1 = points_transform.transform(self._xy1)
+ slope = self._slope
+ (vxlo, vylo), (vxhi, vyhi) = ax.transScale.transform(ax.viewLim)
+ # General case: find intersections with view limits in either
+ # direction, and draw between the middle two points.
+ if slope == 0:
+ start = vxlo, y1
+ stop = vxhi, y1
+ elif np.isinf(slope):
+ start = x1, vylo
+ stop = x1, vyhi
+ else:
+ _, start, stop, _ = sorted([
+ (vxlo, y1 + (vxlo - x1) * slope),
+ (vxhi, y1 + (vxhi - x1) * slope),
+ (x1 + (vylo - y1) / slope, vylo),
+ (x1 + (vyhi - y1) / slope, vyhi),
+ ])
+ return (BboxTransformTo(Bbox([start, stop]))
+ + ax.transLimits + ax.transAxes)
+
+ def draw(self, renderer):
+ self._transformed_path = None # Force regen.
+ super().draw(renderer)
+
+ def get_xy1(self):
+ """Return the *xy1* value of the line."""
+ return self._xy1
+
+ def get_xy2(self):
+ """Return the *xy2* value of the line."""
+ return self._xy2
+
+ def get_slope(self):
+ """Return the *slope* value of the line."""
+ return self._slope
+
+ def set_xy1(self, *args, **kwargs):
+ """
+ Set the *xy1* value of the line.
+
+ Parameters
+ ----------
+ xy1 : tuple[float, float]
+ Points for the line to pass through.
+ """
+ params = _api.select_matching_signature([
+ lambda self, x, y: locals(), lambda self, xy1: locals(),
+ ], self, *args, **kwargs)
+ if "x" in params:
+ _api.warn_deprecated("3.10", message=(
+ "Passing x and y separately to AxLine.set_xy1 is deprecated since "
+ "%(since)s; pass them as a single tuple instead."))
+ xy1 = params["x"], params["y"]
+ else:
+ xy1 = params["xy1"]
+ self._xy1 = xy1
+
+ def set_xy2(self, *args, **kwargs):
+ """
+ Set the *xy2* value of the line.
+
+ .. note::
+
+ You can only set *xy2* if the line was created using the *xy2*
+ parameter. If the line was created using *slope*, please use
+ `~.AxLine.set_slope`.
+
+ Parameters
+ ----------
+ xy2 : tuple[float, float]
+ Points for the line to pass through.
+ """
+ if self._slope is None:
+ params = _api.select_matching_signature([
+ lambda self, x, y: locals(), lambda self, xy2: locals(),
+ ], self, *args, **kwargs)
+ if "x" in params:
+ _api.warn_deprecated("3.10", message=(
+ "Passing x and y separately to AxLine.set_xy2 is deprecated since "
+ "%(since)s; pass them as a single tuple instead."))
+ xy2 = params["x"], params["y"]
+ else:
+ xy2 = params["xy2"]
+ self._xy2 = xy2
+ else:
+ raise ValueError("Cannot set an 'xy2' value while 'slope' is set;"
+ " they differ but their functionalities overlap")
+
+ def set_slope(self, slope):
+ """
+ Set the *slope* value of the line.
+
+ .. note::
+
+ You can only set *slope* if the line was created using the *slope*
+ parameter. If the line was created using *xy2*, please use
+ `~.AxLine.set_xy2`.
+
+ Parameters
+ ----------
+ slope : float
+ The slope of the line.
+ """
+ if self._xy2 is None:
+ self._slope = slope
+ else:
+ raise ValueError("Cannot set a 'slope' value while 'xy2' is set;"
+ " they differ but their functionalities overlap")
+
+
+class VertexSelector:
+ """
+ Manage the callbacks to maintain a list of selected vertices for `.Line2D`.
+ Derived classes should override the `process_selected` method to do
+ something with the picks.
+
+ Here is an example which highlights the selected verts with red circles::
+
+ import numpy as np
+ import matplotlib.pyplot as plt
+ import matplotlib.lines as lines
+
+ class HighlightSelected(lines.VertexSelector):
+ def __init__(self, line, fmt='ro', **kwargs):
+ super().__init__(line)
+ self.markers, = self.axes.plot([], [], fmt, **kwargs)
+
+ def process_selected(self, ind, xs, ys):
+ self.markers.set_data(xs, ys)
+ self.canvas.draw()
+
+ fig, ax = plt.subplots()
+ x, y = np.random.rand(2, 30)
+ line, = ax.plot(x, y, 'bs-', picker=5)
+
+ selector = HighlightSelected(line)
+ plt.show()
+ """
+
+ def __init__(self, line):
+ """
+ Parameters
+ ----------
+ line : `~matplotlib.lines.Line2D`
+ The line must already have been added to an `~.axes.Axes` and must
+ have its picker property set.
+ """
+ if line.axes is None:
+ raise RuntimeError('You must first add the line to the Axes')
+ if line.get_picker() is None:
+ raise RuntimeError('You must first set the picker property '
+ 'of the line')
+ self.axes = line.axes
+ self.line = line
+ self.cid = self.canvas.callbacks._connect_picklable(
+ 'pick_event', self.onpick)
+ self.ind = set()
+
+ canvas = property(lambda self: self.axes.get_figure(root=True).canvas)
+
+ def process_selected(self, ind, xs, ys):
+ """
+ Default "do nothing" implementation of the `process_selected` method.
+
+ Parameters
+ ----------
+ ind : list of int
+ The indices of the selected vertices.
+ xs, ys : array-like
+ The coordinates of the selected vertices.
+ """
+ pass
+
+ def onpick(self, event):
+ """When the line is picked, update the set of selected indices."""
+ if event.artist is not self.line:
+ return
+ self.ind ^= set(event.ind)
+ ind = sorted(self.ind)
+ xdata, ydata = self.line.get_data()
+ self.process_selected(ind, xdata[ind], ydata[ind])
+
+
+lineStyles = Line2D._lineStyles
+lineMarkers = MarkerStyle.markers
+drawStyles = Line2D.drawStyles
+fillStyles = MarkerStyle.fillstyles
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/lines.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/lines.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..7989a03dae3a0680f63511a0d5347517753a2d1e
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/lines.pyi
@@ -0,0 +1,153 @@
+from .artist import Artist
+from .axes import Axes
+from .backend_bases import MouseEvent, FigureCanvasBase
+from .path import Path
+from .transforms import Bbox
+
+from collections.abc import Callable, Sequence
+from typing import Any, Literal, overload
+from .typing import (
+ ColorType,
+ DrawStyleType,
+ FillStyleType,
+ LineStyleType,
+ CapStyleType,
+ JoinStyleType,
+ MarkEveryType,
+ MarkerType,
+)
+from numpy.typing import ArrayLike
+
+def segment_hits(
+ cx: ArrayLike, cy: ArrayLike, x: ArrayLike, y: ArrayLike, radius: ArrayLike
+) -> ArrayLike: ...
+
+class Line2D(Artist):
+ lineStyles: dict[str, str]
+ drawStyles: dict[str, str]
+ drawStyleKeys: list[str]
+ markers: dict[str | int, str]
+ filled_markers: tuple[str, ...]
+ fillStyles: tuple[str, ...]
+ zorder: float
+ ind_offset: float
+ def __init__(
+ self,
+ xdata: ArrayLike,
+ ydata: ArrayLike,
+ *,
+ linewidth: float | None = ...,
+ linestyle: LineStyleType | None = ...,
+ color: ColorType | None = ...,
+ gapcolor: ColorType | None = ...,
+ marker: MarkerType | None = ...,
+ markersize: float | None = ...,
+ markeredgewidth: float | None = ...,
+ markeredgecolor: ColorType | None = ...,
+ markerfacecolor: ColorType | None = ...,
+ markerfacecoloralt: ColorType = ...,
+ fillstyle: FillStyleType | None = ...,
+ antialiased: bool | None = ...,
+ dash_capstyle: CapStyleType | None = ...,
+ solid_capstyle: CapStyleType | None = ...,
+ dash_joinstyle: JoinStyleType | None = ...,
+ solid_joinstyle: JoinStyleType | None = ...,
+ pickradius: float = ...,
+ drawstyle: DrawStyleType | None = ...,
+ markevery: MarkEveryType | None = ...,
+ **kwargs
+ ) -> None: ...
+ def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict]: ...
+ def get_pickradius(self) -> float: ...
+ def set_pickradius(self, pickradius: float) -> None: ...
+ pickradius: float
+ def get_fillstyle(self) -> FillStyleType: ...
+ stale: bool
+ def set_fillstyle(self, fs: FillStyleType) -> None: ...
+ def set_markevery(self, every: MarkEveryType) -> None: ...
+ def get_markevery(self) -> MarkEveryType: ...
+ def set_picker(
+ self, p: None | bool | float | Callable[[Artist, MouseEvent], tuple[bool, dict]]
+ ) -> None: ...
+ def get_bbox(self) -> Bbox: ...
+ @overload
+ def set_data(self, args: ArrayLike) -> None: ...
+ @overload
+ def set_data(self, x: ArrayLike, y: ArrayLike) -> None: ...
+ def recache_always(self) -> None: ...
+ def recache(self, always: bool = ...) -> None: ...
+ def get_antialiased(self) -> bool: ...
+ def get_color(self) -> ColorType: ...
+ def get_drawstyle(self) -> DrawStyleType: ...
+ def get_gapcolor(self) -> ColorType: ...
+ def get_linestyle(self) -> LineStyleType: ...
+ def get_linewidth(self) -> float: ...
+ def get_marker(self) -> MarkerType: ...
+ def get_markeredgecolor(self) -> ColorType: ...
+ def get_markeredgewidth(self) -> float: ...
+ def get_markerfacecolor(self) -> ColorType: ...
+ def get_markerfacecoloralt(self) -> ColorType: ...
+ def get_markersize(self) -> float: ...
+ def get_data(self, orig: bool = ...) -> tuple[ArrayLike, ArrayLike]: ...
+ def get_xdata(self, orig: bool = ...) -> ArrayLike: ...
+ def get_ydata(self, orig: bool = ...) -> ArrayLike: ...
+ def get_path(self) -> Path: ...
+ def get_xydata(self) -> ArrayLike: ...
+ def set_antialiased(self, b: bool) -> None: ...
+ def set_color(self, color: ColorType) -> None: ...
+ def set_drawstyle(self, drawstyle: DrawStyleType | None) -> None: ...
+ def set_gapcolor(self, gapcolor: ColorType | None) -> None: ...
+ def set_linewidth(self, w: float) -> None: ...
+ def set_linestyle(self, ls: LineStyleType) -> None: ...
+ def set_marker(self, marker: MarkerType) -> None: ...
+ def set_markeredgecolor(self, ec: ColorType | None) -> None: ...
+ def set_markerfacecolor(self, fc: ColorType | None) -> None: ...
+ def set_markerfacecoloralt(self, fc: ColorType | None) -> None: ...
+ def set_markeredgewidth(self, ew: float | None) -> None: ...
+ def set_markersize(self, sz: float) -> None: ...
+ def set_xdata(self, x: ArrayLike) -> None: ...
+ def set_ydata(self, y: ArrayLike) -> None: ...
+ def set_dashes(self, seq: Sequence[float] | tuple[None, None]) -> None: ...
+ def update_from(self, other: Artist) -> None: ...
+ def set_dash_joinstyle(self, s: JoinStyleType) -> None: ...
+ def set_solid_joinstyle(self, s: JoinStyleType) -> None: ...
+ def get_dash_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
+ def get_solid_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
+ def set_dash_capstyle(self, s: CapStyleType) -> None: ...
+ def set_solid_capstyle(self, s: CapStyleType) -> None: ...
+ def get_dash_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
+ def get_solid_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
+ def is_dashed(self) -> bool: ...
+
+class AxLine(Line2D):
+ def __init__(
+ self,
+ xy1: tuple[float, float],
+ xy2: tuple[float, float] | None,
+ slope: float | None,
+ **kwargs
+ ) -> None: ...
+ def get_xy1(self) -> tuple[float, float] | None: ...
+ def get_xy2(self) -> tuple[float, float] | None: ...
+ def get_slope(self) -> float: ...
+ def set_xy1(self, xy1: tuple[float, float]) -> None: ...
+ def set_xy2(self, xy2: tuple[float, float]) -> None: ...
+ def set_slope(self, slope: float) -> None: ...
+
+class VertexSelector:
+ axes: Axes
+ line: Line2D
+ cid: int
+ ind: set[int]
+ def __init__(self, line: Line2D) -> None: ...
+ @property
+ def canvas(self) -> FigureCanvasBase: ...
+ def process_selected(
+ self, ind: Sequence[int], xs: ArrayLike, ys: ArrayLike
+ ) -> None: ...
+ def onpick(self, event: Any) -> None: ...
+
+lineStyles: dict[str, str]
+lineMarkers: dict[str | int, str]
+drawStyles: dict[str, str]
+fillStyles: tuple[FillStyleType, ...]
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/markers.py b/llava_video/lib/python3.10/site-packages/matplotlib/markers.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa5e66e73ade4926c518905c0575e6bf99dfcb24
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/markers.py
@@ -0,0 +1,908 @@
+r"""
+Functions to handle markers; used by the marker functionality of
+`~matplotlib.axes.Axes.plot`, `~matplotlib.axes.Axes.scatter`, and
+`~matplotlib.axes.Axes.errorbar`.
+
+All possible markers are defined here:
+
+============================== ====== =========================================
+marker symbol description
+============================== ====== =========================================
+``"."`` |m00| point
+``","`` |m01| pixel
+``"o"`` |m02| circle
+``"v"`` |m03| triangle_down
+``"^"`` |m04| triangle_up
+``"<"`` |m05| triangle_left
+``">"`` |m06| triangle_right
+``"1"`` |m07| tri_down
+``"2"`` |m08| tri_up
+``"3"`` |m09| tri_left
+``"4"`` |m10| tri_right
+``"8"`` |m11| octagon
+``"s"`` |m12| square
+``"p"`` |m13| pentagon
+``"P"`` |m23| plus (filled)
+``"*"`` |m14| star
+``"h"`` |m15| hexagon1
+``"H"`` |m16| hexagon2
+``"+"`` |m17| plus
+``"x"`` |m18| x
+``"X"`` |m24| x (filled)
+``"D"`` |m19| diamond
+``"d"`` |m20| thin_diamond
+``"|"`` |m21| vline
+``"_"`` |m22| hline
+``0`` (``TICKLEFT``) |m25| tickleft
+``1`` (``TICKRIGHT``) |m26| tickright
+``2`` (``TICKUP``) |m27| tickup
+``3`` (``TICKDOWN``) |m28| tickdown
+``4`` (``CARETLEFT``) |m29| caretleft
+``5`` (``CARETRIGHT``) |m30| caretright
+``6`` (``CARETUP``) |m31| caretup
+``7`` (``CARETDOWN``) |m32| caretdown
+``8`` (``CARETLEFTBASE``) |m33| caretleft (centered at base)
+``9`` (``CARETRIGHTBASE``) |m34| caretright (centered at base)
+``10`` (``CARETUPBASE``) |m35| caretup (centered at base)
+``11`` (``CARETDOWNBASE``) |m36| caretdown (centered at base)
+``"none"`` or ``"None"`` nothing
+``" "`` or ``""`` nothing
+``"$...$"`` |m37| Render the string using mathtext.
+ E.g ``"$f$"`` for marker showing the
+ letter ``f``.
+``verts`` A list of (x, y) pairs used for Path
+ vertices. The center of the marker is
+ located at (0, 0) and the size is
+ normalized, such that the created path
+ is encapsulated inside the unit cell.
+``path`` A `~matplotlib.path.Path` instance.
+``(numsides, 0, angle)`` A regular polygon with ``numsides``
+ sides, rotated by ``angle``.
+``(numsides, 1, angle)`` A star-like symbol with ``numsides``
+ sides, rotated by ``angle``.
+``(numsides, 2, angle)`` An asterisk with ``numsides`` sides,
+ rotated by ``angle``.
+============================== ====== =========================================
+
+Note that special symbols can be defined via the
+:ref:`STIX math font `,
+e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer to the
+`STIX font table `_.
+Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
+
+Integer numbers from ``0`` to ``11`` create lines and triangles. Those are
+equally accessible via capitalized variables, like ``CARETDOWNBASE``.
+Hence the following are equivalent::
+
+ plt.plot([1, 2, 3], marker=11)
+ plt.plot([1, 2, 3], marker=matplotlib.markers.CARETDOWNBASE)
+
+Markers join and cap styles can be customized by creating a new instance of
+MarkerStyle.
+A MarkerStyle can also have a custom `~matplotlib.transforms.Transform`
+allowing it to be arbitrarily rotated or offset.
+
+Examples showing the use of markers:
+
+* :doc:`/gallery/lines_bars_and_markers/marker_reference`
+* :doc:`/gallery/lines_bars_and_markers/scatter_star_poly`
+* :doc:`/gallery/lines_bars_and_markers/multivariate_marker_plot`
+
+.. |m00| image:: /_static/markers/m00.png
+.. |m01| image:: /_static/markers/m01.png
+.. |m02| image:: /_static/markers/m02.png
+.. |m03| image:: /_static/markers/m03.png
+.. |m04| image:: /_static/markers/m04.png
+.. |m05| image:: /_static/markers/m05.png
+.. |m06| image:: /_static/markers/m06.png
+.. |m07| image:: /_static/markers/m07.png
+.. |m08| image:: /_static/markers/m08.png
+.. |m09| image:: /_static/markers/m09.png
+.. |m10| image:: /_static/markers/m10.png
+.. |m11| image:: /_static/markers/m11.png
+.. |m12| image:: /_static/markers/m12.png
+.. |m13| image:: /_static/markers/m13.png
+.. |m14| image:: /_static/markers/m14.png
+.. |m15| image:: /_static/markers/m15.png
+.. |m16| image:: /_static/markers/m16.png
+.. |m17| image:: /_static/markers/m17.png
+.. |m18| image:: /_static/markers/m18.png
+.. |m19| image:: /_static/markers/m19.png
+.. |m20| image:: /_static/markers/m20.png
+.. |m21| image:: /_static/markers/m21.png
+.. |m22| image:: /_static/markers/m22.png
+.. |m23| image:: /_static/markers/m23.png
+.. |m24| image:: /_static/markers/m24.png
+.. |m25| image:: /_static/markers/m25.png
+.. |m26| image:: /_static/markers/m26.png
+.. |m27| image:: /_static/markers/m27.png
+.. |m28| image:: /_static/markers/m28.png
+.. |m29| image:: /_static/markers/m29.png
+.. |m30| image:: /_static/markers/m30.png
+.. |m31| image:: /_static/markers/m31.png
+.. |m32| image:: /_static/markers/m32.png
+.. |m33| image:: /_static/markers/m33.png
+.. |m34| image:: /_static/markers/m34.png
+.. |m35| image:: /_static/markers/m35.png
+.. |m36| image:: /_static/markers/m36.png
+.. |m37| image:: /_static/markers/m37.png
+"""
+import copy
+
+from collections.abc import Sized
+
+import numpy as np
+
+import matplotlib as mpl
+from . import _api, cbook
+from .path import Path
+from .transforms import IdentityTransform, Affine2D
+from ._enums import JoinStyle, CapStyle
+
+# special-purpose marker identifiers:
+(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN,
+ CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
+ CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = range(12)
+
+_empty_path = Path(np.empty((0, 2)))
+
+
+class MarkerStyle:
+ """
+ A class representing marker types.
+
+ Instances are immutable. If you need to change anything, create a new
+ instance.
+
+ Attributes
+ ----------
+ markers : dict
+ All known markers.
+ filled_markers : tuple
+ All known filled markers. This is a subset of *markers*.
+ fillstyles : tuple
+ The supported fillstyles.
+ """
+
+ markers = {
+ '.': 'point',
+ ',': 'pixel',
+ 'o': 'circle',
+ 'v': 'triangle_down',
+ '^': 'triangle_up',
+ '<': 'triangle_left',
+ '>': 'triangle_right',
+ '1': 'tri_down',
+ '2': 'tri_up',
+ '3': 'tri_left',
+ '4': 'tri_right',
+ '8': 'octagon',
+ 's': 'square',
+ 'p': 'pentagon',
+ '*': 'star',
+ 'h': 'hexagon1',
+ 'H': 'hexagon2',
+ '+': 'plus',
+ 'x': 'x',
+ 'D': 'diamond',
+ 'd': 'thin_diamond',
+ '|': 'vline',
+ '_': 'hline',
+ 'P': 'plus_filled',
+ 'X': 'x_filled',
+ TICKLEFT: 'tickleft',
+ TICKRIGHT: 'tickright',
+ TICKUP: 'tickup',
+ TICKDOWN: 'tickdown',
+ CARETLEFT: 'caretleft',
+ CARETRIGHT: 'caretright',
+ CARETUP: 'caretup',
+ CARETDOWN: 'caretdown',
+ CARETLEFTBASE: 'caretleftbase',
+ CARETRIGHTBASE: 'caretrightbase',
+ CARETUPBASE: 'caretupbase',
+ CARETDOWNBASE: 'caretdownbase',
+ "None": 'nothing',
+ "none": 'nothing',
+ ' ': 'nothing',
+ '': 'nothing'
+ }
+
+ # Just used for informational purposes. is_filled()
+ # is calculated in the _set_* functions.
+ filled_markers = (
+ '.', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd',
+ 'P', 'X')
+
+ fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none')
+ _half_fillstyles = ('left', 'right', 'bottom', 'top')
+
+ def __init__(self, marker,
+ fillstyle=None, transform=None, capstyle=None, joinstyle=None):
+ """
+ Parameters
+ ----------
+ marker : str, array-like, Path, MarkerStyle
+ - Another instance of `MarkerStyle` copies the details of that *marker*.
+ - For other possible marker values, see the module docstring
+ `matplotlib.markers`.
+
+ fillstyle : str, default: :rc:`markers.fillstyle`
+ One of 'full', 'left', 'right', 'bottom', 'top', 'none'.
+
+ transform : `~matplotlib.transforms.Transform`, optional
+ Transform that will be combined with the native transform of the
+ marker.
+
+ capstyle : `.CapStyle` or %(CapStyle)s, optional
+ Cap style that will override the default cap style of the marker.
+
+ joinstyle : `.JoinStyle` or %(JoinStyle)s, optional
+ Join style that will override the default join style of the marker.
+ """
+ self._marker_function = None
+ self._user_transform = transform
+ self._user_capstyle = CapStyle(capstyle) if capstyle is not None else None
+ self._user_joinstyle = JoinStyle(joinstyle) if joinstyle is not None else None
+ self._set_fillstyle(fillstyle)
+ self._set_marker(marker)
+
+ def _recache(self):
+ if self._marker_function is None:
+ return
+ self._path = _empty_path
+ self._transform = IdentityTransform()
+ self._alt_path = None
+ self._alt_transform = None
+ self._snap_threshold = None
+ self._joinstyle = JoinStyle.round
+ self._capstyle = self._user_capstyle or CapStyle.butt
+ # Initial guess: Assume the marker is filled unless the fillstyle is
+ # set to 'none'. The marker function will override this for unfilled
+ # markers.
+ self._filled = self._fillstyle != 'none'
+ self._marker_function()
+
+ def __bool__(self):
+ return bool(len(self._path.vertices))
+
+ def is_filled(self):
+ return self._filled
+
+ def get_fillstyle(self):
+ return self._fillstyle
+
+ def _set_fillstyle(self, fillstyle):
+ """
+ Set the fillstyle.
+
+ Parameters
+ ----------
+ fillstyle : {'full', 'left', 'right', 'bottom', 'top', 'none'}
+ The part of the marker surface that is colored with
+ markerfacecolor.
+ """
+ if fillstyle is None:
+ fillstyle = mpl.rcParams['markers.fillstyle']
+ _api.check_in_list(self.fillstyles, fillstyle=fillstyle)
+ self._fillstyle = fillstyle
+
+ def get_joinstyle(self):
+ return self._joinstyle.name
+
+ def get_capstyle(self):
+ return self._capstyle.name
+
+ def get_marker(self):
+ return self._marker
+
+ def _set_marker(self, marker):
+ """
+ Set the marker.
+
+ Parameters
+ ----------
+ marker : str, array-like, Path, MarkerStyle
+ - Another instance of `MarkerStyle` copies the details of that *marker*.
+ - For other possible marker values see the module docstring
+ `matplotlib.markers`.
+ """
+ if isinstance(marker, str) and cbook.is_math_text(marker):
+ self._marker_function = self._set_mathtext_path
+ elif isinstance(marker, (int, str)) and marker in self.markers:
+ self._marker_function = getattr(self, '_set_' + self.markers[marker])
+ elif (isinstance(marker, np.ndarray) and marker.ndim == 2 and
+ marker.shape[1] == 2):
+ self._marker_function = self._set_vertices
+ elif isinstance(marker, Path):
+ self._marker_function = self._set_path_marker
+ elif (isinstance(marker, Sized) and len(marker) in (2, 3) and
+ marker[1] in (0, 1, 2)):
+ self._marker_function = self._set_tuple_marker
+ elif isinstance(marker, MarkerStyle):
+ self.__dict__ = copy.deepcopy(marker.__dict__)
+ else:
+ try:
+ Path(marker)
+ self._marker_function = self._set_vertices
+ except ValueError as err:
+ raise ValueError(
+ f'Unrecognized marker style {marker!r}') from err
+
+ if not isinstance(marker, MarkerStyle):
+ self._marker = marker
+ self._recache()
+
+ def get_path(self):
+ """
+ Return a `.Path` for the primary part of the marker.
+
+ For unfilled markers this is the whole marker, for filled markers,
+ this is the area to be drawn with *markerfacecolor*.
+ """
+ return self._path
+
+ def get_transform(self):
+ """
+ Return the transform to be applied to the `.Path` from
+ `MarkerStyle.get_path()`.
+ """
+ if self._user_transform is None:
+ return self._transform.frozen()
+ else:
+ return (self._transform + self._user_transform).frozen()
+
+ def get_alt_path(self):
+ """
+ Return a `.Path` for the alternate part of the marker.
+
+ For unfilled markers, this is *None*; for filled markers, this is the
+ area to be drawn with *markerfacecoloralt*.
+ """
+ return self._alt_path
+
+ def get_alt_transform(self):
+ """
+ Return the transform to be applied to the `.Path` from
+ `MarkerStyle.get_alt_path()`.
+ """
+ if self._user_transform is None:
+ return self._alt_transform.frozen()
+ else:
+ return (self._alt_transform + self._user_transform).frozen()
+
+ def get_snap_threshold(self):
+ return self._snap_threshold
+
+ def get_user_transform(self):
+ """Return user supplied part of marker transform."""
+ if self._user_transform is not None:
+ return self._user_transform.frozen()
+
+ def transformed(self, transform):
+ """
+ Return a new version of this marker with the transform applied.
+
+ Parameters
+ ----------
+ transform : `~matplotlib.transforms.Affine2D`
+ Transform will be combined with current user supplied transform.
+ """
+ new_marker = MarkerStyle(self)
+ if new_marker._user_transform is not None:
+ new_marker._user_transform += transform
+ else:
+ new_marker._user_transform = transform
+ return new_marker
+
+ def rotated(self, *, deg=None, rad=None):
+ """
+ Return a new version of this marker rotated by specified angle.
+
+ Parameters
+ ----------
+ deg : float, optional
+ Rotation angle in degrees.
+
+ rad : float, optional
+ Rotation angle in radians.
+
+ .. note:: You must specify exactly one of deg or rad.
+ """
+ if deg is None and rad is None:
+ raise ValueError('One of deg or rad is required')
+ if deg is not None and rad is not None:
+ raise ValueError('Only one of deg and rad can be supplied')
+ new_marker = MarkerStyle(self)
+ if new_marker._user_transform is None:
+ new_marker._user_transform = Affine2D()
+
+ if deg is not None:
+ new_marker._user_transform.rotate_deg(deg)
+ if rad is not None:
+ new_marker._user_transform.rotate(rad)
+
+ return new_marker
+
+ def scaled(self, sx, sy=None):
+ """
+ Return new marker scaled by specified scale factors.
+
+ If *sy* is not given, the same scale is applied in both the *x*- and
+ *y*-directions.
+
+ Parameters
+ ----------
+ sx : float
+ *X*-direction scaling factor.
+ sy : float, optional
+ *Y*-direction scaling factor.
+ """
+ if sy is None:
+ sy = sx
+
+ new_marker = MarkerStyle(self)
+ _transform = new_marker._user_transform or Affine2D()
+ new_marker._user_transform = _transform.scale(sx, sy)
+ return new_marker
+
+ def _set_nothing(self):
+ self._filled = False
+
+ def _set_custom_marker(self, path):
+ rescale = np.max(np.abs(path.vertices)) # max of x's and y's.
+ self._transform = Affine2D().scale(0.5 / rescale)
+ self._path = path
+
+ def _set_path_marker(self):
+ self._set_custom_marker(self._marker)
+
+ def _set_vertices(self):
+ self._set_custom_marker(Path(self._marker))
+
+ def _set_tuple_marker(self):
+ marker = self._marker
+ if len(marker) == 2:
+ numsides, rotation = marker[0], 0.0
+ elif len(marker) == 3:
+ numsides, rotation = marker[0], marker[2]
+ symstyle = marker[1]
+ if symstyle == 0:
+ self._path = Path.unit_regular_polygon(numsides)
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+ elif symstyle == 1:
+ self._path = Path.unit_regular_star(numsides)
+ self._joinstyle = self._user_joinstyle or JoinStyle.bevel
+ elif symstyle == 2:
+ self._path = Path.unit_regular_asterisk(numsides)
+ self._filled = False
+ self._joinstyle = self._user_joinstyle or JoinStyle.bevel
+ else:
+ raise ValueError(f"Unexpected tuple marker: {marker}")
+ self._transform = Affine2D().scale(0.5).rotate_deg(rotation)
+
+ def _set_mathtext_path(self):
+ """
+ Draw mathtext markers '$...$' using `.TextPath` object.
+
+ Submitted by tcb
+ """
+ from matplotlib.text import TextPath
+
+ # again, the properties could be initialised just once outside
+ # this function
+ text = TextPath(xy=(0, 0), s=self.get_marker(),
+ usetex=mpl.rcParams['text.usetex'])
+ if len(text.vertices) == 0:
+ return
+
+ bbox = text.get_extents()
+ max_dim = max(bbox.width, bbox.height)
+ self._transform = (
+ Affine2D()
+ .translate(-bbox.xmin + 0.5 * -bbox.width, -bbox.ymin + 0.5 * -bbox.height)
+ .scale(1.0 / max_dim))
+ self._path = text
+ self._snap = False
+
+ def _half_fill(self):
+ return self.get_fillstyle() in self._half_fillstyles
+
+ def _set_circle(self, size=1.0):
+ self._transform = Affine2D().scale(0.5 * size)
+ self._snap_threshold = np.inf
+ if not self._half_fill():
+ self._path = Path.unit_circle()
+ else:
+ self._path = self._alt_path = Path.unit_circle_righthalf()
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180.)
+
+ def _set_point(self):
+ self._set_circle(size=0.5)
+
+ def _set_pixel(self):
+ self._path = Path.unit_rectangle()
+ # Ideally, you'd want -0.5, -0.5 here, but then the snapping
+ # algorithm in the Agg backend will round this to a 2x2
+ # rectangle from (-1, -1) to (1, 1). By offsetting it
+ # slightly, we can force it to be (0, 0) to (1, 1), which both
+ # makes it only be a single pixel and places it correctly
+ # aligned to 1-width stroking (i.e. the ticks). This hack is
+ # the best of a number of bad alternatives, mainly because the
+ # backends are not aware of what marker is actually being used
+ # beyond just its path data.
+ self._transform = Affine2D().translate(-0.49999, -0.49999)
+ self._snap_threshold = None
+
+ _triangle_path = Path._create_closed([[0, 1], [-1, -1], [1, -1]])
+ # Going down halfway looks to small. Golden ratio is too far.
+ _triangle_path_u = Path._create_closed([[0, 1], [-3/5, -1/5], [3/5, -1/5]])
+ _triangle_path_d = Path._create_closed(
+ [[-3/5, -1/5], [3/5, -1/5], [1, -1], [-1, -1]])
+ _triangle_path_l = Path._create_closed([[0, 1], [0, -1], [-1, -1]])
+ _triangle_path_r = Path._create_closed([[0, 1], [0, -1], [1, -1]])
+
+ def _set_triangle(self, rot, skip):
+ self._transform = Affine2D().scale(0.5).rotate_deg(rot)
+ self._snap_threshold = 5.0
+
+ if not self._half_fill():
+ self._path = self._triangle_path
+ else:
+ mpaths = [self._triangle_path_u,
+ self._triangle_path_l,
+ self._triangle_path_d,
+ self._triangle_path_r]
+
+ fs = self.get_fillstyle()
+ if fs == 'top':
+ self._path = mpaths[(0 + skip) % 4]
+ self._alt_path = mpaths[(2 + skip) % 4]
+ elif fs == 'bottom':
+ self._path = mpaths[(2 + skip) % 4]
+ self._alt_path = mpaths[(0 + skip) % 4]
+ elif fs == 'left':
+ self._path = mpaths[(1 + skip) % 4]
+ self._alt_path = mpaths[(3 + skip) % 4]
+ else:
+ self._path = mpaths[(3 + skip) % 4]
+ self._alt_path = mpaths[(1 + skip) % 4]
+
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_triangle_up(self):
+ return self._set_triangle(0.0, 0)
+
+ def _set_triangle_down(self):
+ return self._set_triangle(180.0, 2)
+
+ def _set_triangle_left(self):
+ return self._set_triangle(90.0, 3)
+
+ def _set_triangle_right(self):
+ return self._set_triangle(270.0, 1)
+
+ def _set_square(self):
+ self._transform = Affine2D().translate(-0.5, -0.5)
+ self._snap_threshold = 2.0
+ if not self._half_fill():
+ self._path = Path.unit_rectangle()
+ else:
+ # Build a bottom filled square out of two rectangles, one filled.
+ self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5],
+ [0.0, 0.5], [0.0, 0.0]])
+ self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0],
+ [0.0, 1.0], [0.0, 0.5]])
+ fs = self.get_fillstyle()
+ rotate = {'bottom': 0, 'right': 90, 'top': 180, 'left': 270}[fs]
+ self._transform.rotate_deg(rotate)
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_diamond(self):
+ self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45)
+ self._snap_threshold = 5.0
+ if not self._half_fill():
+ self._path = Path.unit_rectangle()
+ else:
+ self._path = Path([[0, 0], [1, 0], [1, 1], [0, 0]])
+ self._alt_path = Path([[0, 0], [0, 1], [1, 1], [0, 0]])
+ fs = self.get_fillstyle()
+ rotate = {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs]
+ self._transform.rotate_deg(rotate)
+ self._alt_transform = self._transform
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_thin_diamond(self):
+ self._set_diamond()
+ self._transform.scale(0.6, 1.0)
+
+ def _set_pentagon(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+
+ polypath = Path.unit_regular_polygon(5)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ y = (1 + np.sqrt(5)) / 4.
+ top = Path(verts[[0, 1, 4, 0]])
+ bottom = Path(verts[[1, 2, 3, 4, 1]])
+ left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]])
+ right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]])
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_star(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+
+ polypath = Path.unit_regular_star(5, innerCircle=0.381966)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ top = Path(np.concatenate([verts[0:4], verts[7:10], verts[0:1]]))
+ bottom = Path(np.concatenate([verts[3:8], verts[3:4]]))
+ left = Path(np.concatenate([verts[0:6], verts[0:1]]))
+ right = Path(np.concatenate([verts[0:1], verts[5:10], verts[0:1]]))
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.bevel
+
+ def _set_hexagon1(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = None
+
+ polypath = Path.unit_regular_polygon(6)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ # not drawing inside lines
+ x = np.abs(np.cos(5 * np.pi / 6.))
+ top = Path(np.concatenate([[(-x, 0)], verts[[1, 0, 5]], [(x, 0)]]))
+ bottom = Path(np.concatenate([[(-x, 0)], verts[2:5], [(x, 0)]]))
+ left = Path(verts[0:4])
+ right = Path(verts[[0, 5, 4, 3]])
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_hexagon2(self):
+ self._transform = Affine2D().scale(0.5).rotate_deg(30)
+ self._snap_threshold = None
+
+ polypath = Path.unit_regular_polygon(6)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ # not drawing inside lines
+ x, y = np.sqrt(3) / 4, 3 / 4.
+ top = Path(verts[[1, 0, 5, 4, 1]])
+ bottom = Path(verts[1:5])
+ left = Path(np.concatenate([
+ [(x, y)], verts[:3], [(-x, -y), (x, y)]]))
+ right = Path(np.concatenate([
+ [(x, y)], verts[5:2:-1], [(-x, -y)]]))
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_octagon(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+
+ polypath = Path.unit_regular_polygon(8)
+
+ if not self._half_fill():
+ self._transform.rotate_deg(22.5)
+ self._path = polypath
+ else:
+ x = np.sqrt(2.) / 4.
+ self._path = self._alt_path = Path(
+ [[0, -1], [0, 1], [-x, 1], [-1, x],
+ [-1, -x], [-x, -1], [0, -1]])
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'left': 0, 'bottom': 90, 'right': 180, 'top': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180.0)
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ _line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]])
+
+ def _set_vline(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._line_marker_path
+
+ def _set_hline(self):
+ self._set_vline()
+ self._transform = self._transform.rotate_deg(90)
+
+ _tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]])
+
+ def _set_tickleft(self):
+ self._transform = Affine2D().scale(-1.0, 1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickhoriz_path
+
+ def _set_tickright(self):
+ self._transform = Affine2D().scale(1.0, 1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickhoriz_path
+
+ _tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]])
+
+ def _set_tickup(self):
+ self._transform = Affine2D().scale(1.0, 1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickvert_path
+
+ def _set_tickdown(self):
+ self._transform = Affine2D().scale(1.0, -1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickvert_path
+
+ _tri_path = Path([[0.0, 0.0], [0.0, -1.0],
+ [0.0, 0.0], [0.8, 0.5],
+ [0.0, 0.0], [-0.8, 0.5]],
+ [Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO])
+
+ def _set_tri_down(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+ self._filled = False
+ self._path = self._tri_path
+
+ def _set_tri_up(self):
+ self._set_tri_down()
+ self._transform = self._transform.rotate_deg(180)
+
+ def _set_tri_left(self):
+ self._set_tri_down()
+ self._transform = self._transform.rotate_deg(270)
+
+ def _set_tri_right(self):
+ self._set_tri_down()
+ self._transform = self._transform.rotate_deg(90)
+
+ _caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]])
+
+ def _set_caretdown(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 3.0
+ self._filled = False
+ self._path = self._caret_path
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_caretup(self):
+ self._set_caretdown()
+ self._transform = self._transform.rotate_deg(180)
+
+ def _set_caretleft(self):
+ self._set_caretdown()
+ self._transform = self._transform.rotate_deg(270)
+
+ def _set_caretright(self):
+ self._set_caretdown()
+ self._transform = self._transform.rotate_deg(90)
+
+ _caret_path_base = Path([[-1.0, 0.0], [0.0, -1.5], [1.0, 0]])
+
+ def _set_caretdownbase(self):
+ self._set_caretdown()
+ self._path = self._caret_path_base
+
+ def _set_caretupbase(self):
+ self._set_caretdownbase()
+ self._transform = self._transform.rotate_deg(180)
+
+ def _set_caretleftbase(self):
+ self._set_caretdownbase()
+ self._transform = self._transform.rotate_deg(270)
+
+ def _set_caretrightbase(self):
+ self._set_caretdownbase()
+ self._transform = self._transform.rotate_deg(90)
+
+ _plus_path = Path([[-1.0, 0.0], [1.0, 0.0],
+ [0.0, -1.0], [0.0, 1.0]],
+ [Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO])
+
+ def _set_plus(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._plus_path
+
+ _x_path = Path([[-1.0, -1.0], [1.0, 1.0],
+ [-1.0, 1.0], [1.0, -1.0]],
+ [Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO])
+
+ def _set_x(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 3.0
+ self._filled = False
+ self._path = self._x_path
+
+ _plus_filled_path = Path._create_closed(np.array([
+ (-1, -3), (+1, -3), (+1, -1), (+3, -1), (+3, +1), (+1, +1),
+ (+1, +3), (-1, +3), (-1, +1), (-3, +1), (-3, -1), (-1, -1)]) / 6)
+ _plus_filled_path_t = Path._create_closed(np.array([
+ (+3, 0), (+3, +1), (+1, +1), (+1, +3),
+ (-1, +3), (-1, +1), (-3, +1), (-3, 0)]) / 6)
+
+ def _set_plus_filled(self):
+ self._transform = Affine2D()
+ self._snap_threshold = 5.0
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+ if not self._half_fill():
+ self._path = self._plus_filled_path
+ else:
+ # Rotate top half path to support all partitions
+ self._path = self._alt_path = self._plus_filled_path_t
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180)
+
+ _x_filled_path = Path._create_closed(np.array([
+ (-1, -2), (0, -1), (+1, -2), (+2, -1), (+1, 0), (+2, +1),
+ (+1, +2), (0, +1), (-1, +2), (-2, +1), (-1, 0), (-2, -1)]) / 4)
+ _x_filled_path_t = Path._create_closed(np.array([
+ (+1, 0), (+2, +1), (+1, +2), (0, +1),
+ (-1, +2), (-2, +1), (-1, 0)]) / 4)
+
+ def _set_x_filled(self):
+ self._transform = Affine2D()
+ self._snap_threshold = 5.0
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+ if not self._half_fill():
+ self._path = self._x_filled_path
+ else:
+ # Rotate top half path to support all partitions
+ self._path = self._alt_path = self._x_filled_path_t
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/mathtext.py b/llava_video/lib/python3.10/site-packages/matplotlib/mathtext.py
new file mode 100644
index 0000000000000000000000000000000000000000..a88c35c15676b027c773eead1e9d0a8b13270768
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/mathtext.py
@@ -0,0 +1,140 @@
+r"""
+A module for parsing a subset of the TeX math syntax and rendering it to a
+Matplotlib backend.
+
+For a tutorial of its usage, see :ref:`mathtext`. This
+document is primarily concerned with implementation details.
+
+The module uses pyparsing_ to parse the TeX expression.
+
+.. _pyparsing: https://pypi.org/project/pyparsing/
+
+The Bakoma distribution of the TeX Computer Modern fonts, and STIX
+fonts are supported. There is experimental support for using
+arbitrary fonts, but results may vary without proper tweaking and
+metrics for those fonts.
+"""
+
+import functools
+import logging
+
+import matplotlib as mpl
+from matplotlib import _api, _mathtext
+from matplotlib.ft2font import LoadFlags
+from matplotlib.font_manager import FontProperties
+from ._mathtext import ( # noqa: F401, reexported API
+ RasterParse, VectorParse, get_unicode_index)
+
+_log = logging.getLogger(__name__)
+
+
+get_unicode_index.__module__ = __name__
+
+##############################################################################
+# MAIN
+
+
+class MathTextParser:
+ _parser = None
+ _font_type_mapping = {
+ 'cm': _mathtext.BakomaFonts,
+ 'dejavuserif': _mathtext.DejaVuSerifFonts,
+ 'dejavusans': _mathtext.DejaVuSansFonts,
+ 'stix': _mathtext.StixFonts,
+ 'stixsans': _mathtext.StixSansFonts,
+ 'custom': _mathtext.UnicodeFonts,
+ }
+
+ def __init__(self, output):
+ """
+ Create a MathTextParser for the given backend *output*.
+
+ Parameters
+ ----------
+ output : {"path", "agg"}
+ Whether to return a `VectorParse` ("path") or a
+ `RasterParse` ("agg", or its synonym "macosx").
+ """
+ self._output_type = _api.check_getitem(
+ {"path": "vector", "agg": "raster", "macosx": "raster"},
+ output=output.lower())
+
+ def parse(self, s, dpi=72, prop=None, *, antialiased=None):
+ """
+ Parse the given math expression *s* at the given *dpi*. If *prop* is
+ provided, it is a `.FontProperties` object specifying the "default"
+ font to use in the math expression, used for all non-math text.
+
+ The results are cached, so multiple calls to `parse`
+ with the same expression should be fast.
+
+ Depending on the *output* type, this returns either a `VectorParse` or
+ a `RasterParse`.
+ """
+ # lru_cache can't decorate parse() directly because prop is
+ # mutable, so we key the cache using an internal copy (see
+ # Text._get_text_metrics_with_cache for a similar case); likewise,
+ # we need to check the mutable state of the text.antialiased and
+ # text.hinting rcParams.
+ prop = prop.copy() if prop is not None else None
+ antialiased = mpl._val_or_rc(antialiased, 'text.antialiased')
+ from matplotlib.backends import backend_agg
+ load_glyph_flags = {
+ "vector": LoadFlags.NO_HINTING,
+ "raster": backend_agg.get_hinting_flag(),
+ }[self._output_type]
+ return self._parse_cached(s, dpi, prop, antialiased, load_glyph_flags)
+
+ @functools.lru_cache(50)
+ def _parse_cached(self, s, dpi, prop, antialiased, load_glyph_flags):
+ if prop is None:
+ prop = FontProperties()
+ fontset_class = _api.check_getitem(
+ self._font_type_mapping, fontset=prop.get_math_fontfamily())
+ fontset = fontset_class(prop, load_glyph_flags)
+ fontsize = prop.get_size_in_points()
+
+ if self._parser is None: # Cache the parser globally.
+ self.__class__._parser = _mathtext.Parser()
+
+ box = self._parser.parse(s, fontset, fontsize, dpi)
+ output = _mathtext.ship(box)
+ if self._output_type == "vector":
+ return output.to_vector()
+ elif self._output_type == "raster":
+ return output.to_raster(antialiased=antialiased)
+
+
+def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None,
+ *, color=None):
+ """
+ Given a math expression, renders it in a closely-clipped bounding
+ box to an image file.
+
+ Parameters
+ ----------
+ s : str
+ A math expression. The math portion must be enclosed in dollar signs.
+ filename_or_obj : str or path-like or file-like
+ Where to write the image data.
+ prop : `.FontProperties`, optional
+ The size and style of the text.
+ dpi : float, optional
+ The output dpi. If not set, the dpi is determined as for
+ `.Figure.savefig`.
+ format : str, optional
+ The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not set, the
+ format is determined as for `.Figure.savefig`.
+ color : str, optional
+ Foreground color, defaults to :rc:`text.color`.
+ """
+ from matplotlib import figure
+
+ parser = MathTextParser('path')
+ width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
+
+ fig = figure.Figure(figsize=(width / 72.0, height / 72.0))
+ fig.text(0, depth/height, s, fontproperties=prop, color=color)
+ fig.savefig(filename_or_obj, dpi=dpi, format=format)
+
+ return depth
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/mathtext.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/mathtext.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..607501a275c67941e2a67883dc9c99a887ac0581
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/mathtext.pyi
@@ -0,0 +1,33 @@
+import os
+from typing import Generic, IO, Literal, TypeVar, overload
+
+from matplotlib.font_manager import FontProperties
+from matplotlib.typing import ColorType
+
+# Re-exported API from _mathtext.
+from ._mathtext import (
+ RasterParse as RasterParse,
+ VectorParse as VectorParse,
+ get_unicode_index as get_unicode_index,
+)
+
+_ParseType = TypeVar("_ParseType", RasterParse, VectorParse)
+
+class MathTextParser(Generic[_ParseType]):
+ @overload
+ def __init__(self: MathTextParser[VectorParse], output: Literal["path"]) -> None: ...
+ @overload
+ def __init__(self: MathTextParser[RasterParse], output: Literal["agg", "raster", "macosx"]) -> None: ...
+ def parse(
+ self, s: str, dpi: float = ..., prop: FontProperties | None = ..., *, antialiased: bool | None = ...
+ ) -> _ParseType: ...
+
+def math_to_image(
+ s: str,
+ filename_or_obj: str | os.PathLike | IO,
+ prop: FontProperties | None = ...,
+ dpi: float | None = ...,
+ format: str | None = ...,
+ *,
+ color: ColorType | None = ...
+) -> float: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/mlab.py b/llava_video/lib/python3.10/site-packages/matplotlib/mlab.py
new file mode 100644
index 0000000000000000000000000000000000000000..8326ac186e31bbc29d9027e64ae65f999a6f73dd
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/mlab.py
@@ -0,0 +1,913 @@
+"""
+Numerical Python functions written for compatibility with MATLAB
+commands with the same names. Most numerical Python functions can be found in
+the `NumPy`_ and `SciPy`_ libraries. What remains here is code for performing
+spectral computations and kernel density estimations.
+
+.. _NumPy: https://numpy.org
+.. _SciPy: https://www.scipy.org
+
+Spectral functions
+------------------
+
+`cohere`
+ Coherence (normalized cross spectral density)
+
+`csd`
+ Cross spectral density using Welch's average periodogram
+
+`detrend`
+ Remove the mean or best fit line from an array
+
+`psd`
+ Power spectral density using Welch's average periodogram
+
+`specgram`
+ Spectrogram (spectrum over segments of time)
+
+`complex_spectrum`
+ Return the complex-valued frequency spectrum of a signal
+
+`magnitude_spectrum`
+ Return the magnitude of the frequency spectrum of a signal
+
+`angle_spectrum`
+ Return the angle (wrapped phase) of the frequency spectrum of a signal
+
+`phase_spectrum`
+ Return the phase (unwrapped angle) of the frequency spectrum of a signal
+
+`detrend_mean`
+ Remove the mean from a line.
+
+`detrend_linear`
+ Remove the best fit line from a line.
+
+`detrend_none`
+ Return the original line.
+"""
+
+import functools
+from numbers import Number
+
+import numpy as np
+
+from matplotlib import _api, _docstring, cbook
+
+
+def window_hanning(x):
+ """
+ Return *x* times the Hanning (or Hann) window of len(*x*).
+
+ See Also
+ --------
+ window_none : Another window algorithm.
+ """
+ return np.hanning(len(x))*x
+
+
+def window_none(x):
+ """
+ No window function; simply return *x*.
+
+ See Also
+ --------
+ window_hanning : Another window algorithm.
+ """
+ return x
+
+
+def detrend(x, key=None, axis=None):
+ """
+ Return *x* with its trend removed.
+
+ Parameters
+ ----------
+ x : array or sequence
+ Array or sequence containing the data.
+
+ key : {'default', 'constant', 'mean', 'linear', 'none'} or function
+ The detrending algorithm to use. 'default', 'mean', and 'constant' are
+ the same as `detrend_mean`. 'linear' is the same as `detrend_linear`.
+ 'none' is the same as `detrend_none`. The default is 'mean'. See the
+ corresponding functions for more details regarding the algorithms. Can
+ also be a function that carries out the detrend operation.
+
+ axis : int
+ The axis along which to do the detrending.
+
+ See Also
+ --------
+ detrend_mean : Implementation of the 'mean' algorithm.
+ detrend_linear : Implementation of the 'linear' algorithm.
+ detrend_none : Implementation of the 'none' algorithm.
+ """
+ if key is None or key in ['constant', 'mean', 'default']:
+ return detrend(x, key=detrend_mean, axis=axis)
+ elif key == 'linear':
+ return detrend(x, key=detrend_linear, axis=axis)
+ elif key == 'none':
+ return detrend(x, key=detrend_none, axis=axis)
+ elif callable(key):
+ x = np.asarray(x)
+ if axis is not None and axis + 1 > x.ndim:
+ raise ValueError(f'axis(={axis}) out of bounds')
+ if (axis is None and x.ndim == 0) or (not axis and x.ndim == 1):
+ return key(x)
+ # try to use the 'axis' argument if the function supports it,
+ # otherwise use apply_along_axis to do it
+ try:
+ return key(x, axis=axis)
+ except TypeError:
+ return np.apply_along_axis(key, axis=axis, arr=x)
+ else:
+ raise ValueError(
+ f"Unknown value for key: {key!r}, must be one of: 'default', "
+ f"'constant', 'mean', 'linear', or a function")
+
+
+def detrend_mean(x, axis=None):
+ """
+ Return *x* minus the mean(*x*).
+
+ Parameters
+ ----------
+ x : array or sequence
+ Array or sequence containing the data
+ Can have any dimensionality
+
+ axis : int
+ The axis along which to take the mean. See `numpy.mean` for a
+ description of this argument.
+
+ See Also
+ --------
+ detrend_linear : Another detrend algorithm.
+ detrend_none : Another detrend algorithm.
+ detrend : A wrapper around all the detrend algorithms.
+ """
+ x = np.asarray(x)
+
+ if axis is not None and axis+1 > x.ndim:
+ raise ValueError('axis(=%s) out of bounds' % axis)
+
+ return x - x.mean(axis, keepdims=True)
+
+
+def detrend_none(x, axis=None):
+ """
+ Return *x*: no detrending.
+
+ Parameters
+ ----------
+ x : any object
+ An object containing the data
+
+ axis : int
+ This parameter is ignored.
+ It is included for compatibility with detrend_mean
+
+ See Also
+ --------
+ detrend_mean : Another detrend algorithm.
+ detrend_linear : Another detrend algorithm.
+ detrend : A wrapper around all the detrend algorithms.
+ """
+ return x
+
+
+def detrend_linear(y):
+ """
+ Return *x* minus best fit line; 'linear' detrending.
+
+ Parameters
+ ----------
+ y : 0-D or 1-D array or sequence
+ Array or sequence containing the data
+
+ See Also
+ --------
+ detrend_mean : Another detrend algorithm.
+ detrend_none : Another detrend algorithm.
+ detrend : A wrapper around all the detrend algorithms.
+ """
+ # This is faster than an algorithm based on linalg.lstsq.
+ y = np.asarray(y)
+
+ if y.ndim > 1:
+ raise ValueError('y cannot have ndim > 1')
+
+ # short-circuit 0-D array.
+ if not y.ndim:
+ return np.array(0., dtype=y.dtype)
+
+ x = np.arange(y.size, dtype=float)
+
+ C = np.cov(x, y, bias=1)
+ b = C[0, 1]/C[0, 0]
+
+ a = y.mean() - b*x.mean()
+ return y - (b*x + a)
+
+
+def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
+ window=None, noverlap=None, pad_to=None,
+ sides=None, scale_by_freq=None, mode=None):
+ """
+ Private helper implementing the common parts between the psd, csd,
+ spectrogram and complex, magnitude, angle, and phase spectrums.
+ """
+ if y is None:
+ # if y is None use x for y
+ same_data = True
+ else:
+ # The checks for if y is x are so that we can use the same function to
+ # implement the core of psd(), csd(), and spectrogram() without doing
+ # extra calculations. We return the unaveraged Pxy, freqs, and t.
+ same_data = y is x
+
+ if Fs is None:
+ Fs = 2
+ if noverlap is None:
+ noverlap = 0
+ if detrend_func is None:
+ detrend_func = detrend_none
+ if window is None:
+ window = window_hanning
+
+ # if NFFT is set to None use the whole signal
+ if NFFT is None:
+ NFFT = 256
+
+ if noverlap >= NFFT:
+ raise ValueError('noverlap must be less than NFFT')
+
+ if mode is None or mode == 'default':
+ mode = 'psd'
+ _api.check_in_list(
+ ['default', 'psd', 'complex', 'magnitude', 'angle', 'phase'],
+ mode=mode)
+
+ if not same_data and mode != 'psd':
+ raise ValueError("x and y must be equal if mode is not 'psd'")
+
+ # Make sure we're dealing with a numpy array. If y and x were the same
+ # object to start with, keep them that way
+ x = np.asarray(x)
+ if not same_data:
+ y = np.asarray(y)
+
+ if sides is None or sides == 'default':
+ if np.iscomplexobj(x):
+ sides = 'twosided'
+ else:
+ sides = 'onesided'
+ _api.check_in_list(['default', 'onesided', 'twosided'], sides=sides)
+
+ # zero pad x and y up to NFFT if they are shorter than NFFT
+ if len(x) < NFFT:
+ n = len(x)
+ x = np.resize(x, NFFT)
+ x[n:] = 0
+
+ if not same_data and len(y) < NFFT:
+ n = len(y)
+ y = np.resize(y, NFFT)
+ y[n:] = 0
+
+ if pad_to is None:
+ pad_to = NFFT
+
+ if mode != 'psd':
+ scale_by_freq = False
+ elif scale_by_freq is None:
+ scale_by_freq = True
+
+ # For real x, ignore the negative frequencies unless told otherwise
+ if sides == 'twosided':
+ numFreqs = pad_to
+ if pad_to % 2:
+ freqcenter = (pad_to - 1)//2 + 1
+ else:
+ freqcenter = pad_to//2
+ scaling_factor = 1.
+ elif sides == 'onesided':
+ if pad_to % 2:
+ numFreqs = (pad_to + 1)//2
+ else:
+ numFreqs = pad_to//2 + 1
+ scaling_factor = 2.
+
+ if not np.iterable(window):
+ window = window(np.ones(NFFT, x.dtype))
+ if len(window) != NFFT:
+ raise ValueError(
+ "The window length must match the data's first dimension")
+
+ result = np.lib.stride_tricks.sliding_window_view(
+ x, NFFT, axis=0)[::NFFT - noverlap].T
+ result = detrend(result, detrend_func, axis=0)
+ result = result * window.reshape((-1, 1))
+ result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :]
+ freqs = np.fft.fftfreq(pad_to, 1/Fs)[:numFreqs]
+
+ if not same_data:
+ # if same_data is False, mode must be 'psd'
+ resultY = np.lib.stride_tricks.sliding_window_view(
+ y, NFFT, axis=0)[::NFFT - noverlap].T
+ resultY = detrend(resultY, detrend_func, axis=0)
+ resultY = resultY * window.reshape((-1, 1))
+ resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :]
+ result = np.conj(result) * resultY
+ elif mode == 'psd':
+ result = np.conj(result) * result
+ elif mode == 'magnitude':
+ result = np.abs(result) / window.sum()
+ elif mode == 'angle' or mode == 'phase':
+ # we unwrap the phase later to handle the onesided vs. twosided case
+ result = np.angle(result)
+ elif mode == 'complex':
+ result /= window.sum()
+
+ if mode == 'psd':
+
+ # Also include scaling factors for one-sided densities and dividing by
+ # the sampling frequency, if desired. Scale everything, except the DC
+ # component and the NFFT/2 component:
+
+ # if we have a even number of frequencies, don't scale NFFT/2
+ if not NFFT % 2:
+ slc = slice(1, -1, None)
+ # if we have an odd number, just don't scale DC
+ else:
+ slc = slice(1, None, None)
+
+ result[slc] *= scaling_factor
+
+ # MATLAB divides by the sampling frequency so that density function
+ # has units of dB/Hz and can be integrated by the plotted frequency
+ # values. Perform the same scaling here.
+ if scale_by_freq:
+ result /= Fs
+ # Scale the spectrum by the norm of the window to compensate for
+ # windowing loss; see Bendat & Piersol Sec 11.5.2.
+ result /= (window**2).sum()
+ else:
+ # In this case, preserve power in the segment, not amplitude
+ result /= window.sum()**2
+
+ t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs
+
+ if sides == 'twosided':
+ # center the frequency range at zero
+ freqs = np.roll(freqs, -freqcenter, axis=0)
+ result = np.roll(result, -freqcenter, axis=0)
+ elif not pad_to % 2:
+ # get the last value correctly, it is negative otherwise
+ freqs[-1] *= -1
+
+ # we unwrap the phase here to handle the onesided vs. twosided case
+ if mode == 'phase':
+ result = np.unwrap(result, axis=0)
+
+ return result, freqs, t
+
+
+def _single_spectrum_helper(
+ mode, x, Fs=None, window=None, pad_to=None, sides=None):
+ """
+ Private helper implementing the commonality between the complex, magnitude,
+ angle, and phase spectrums.
+ """
+ _api.check_in_list(['complex', 'magnitude', 'angle', 'phase'], mode=mode)
+
+ if pad_to is None:
+ pad_to = len(x)
+
+ spec, freqs, _ = _spectral_helper(x=x, y=None, NFFT=len(x), Fs=Fs,
+ detrend_func=detrend_none, window=window,
+ noverlap=0, pad_to=pad_to,
+ sides=sides,
+ scale_by_freq=False,
+ mode=mode)
+ if mode != 'complex':
+ spec = spec.real
+
+ if spec.ndim == 2 and spec.shape[1] == 1:
+ spec = spec[:, 0]
+
+ return spec, freqs
+
+
+# Split out these keyword docs so that they can be used elsewhere
+_docstring.interpd.register(
+ Spectral="""\
+Fs : float, default: 2
+ The sampling frequency (samples per time unit). It is used to calculate
+ the Fourier frequencies, *freqs*, in cycles per time unit.
+
+window : callable or ndarray, default: `.window_hanning`
+ A function or a vector of length *NFFT*. To create window vectors see
+ `.window_hanning`, `.window_none`, `numpy.blackman`, `numpy.hamming`,
+ `numpy.bartlett`, `scipy.signal`, `scipy.signal.get_window`, etc. If a
+ function is passed as the argument, it must take a data segment as an
+ argument and return the windowed version of the segment.
+
+sides : {'default', 'onesided', 'twosided'}, optional
+ Which sides of the spectrum to return. 'default' is one-sided for real
+ data and two-sided for complex data. 'onesided' forces the return of a
+ one-sided spectrum, while 'twosided' forces two-sided.""",
+
+ Single_Spectrum="""\
+pad_to : int, optional
+ The number of points to which the data segment is padded when performing
+ the FFT. While not increasing the actual resolution of the spectrum (the
+ minimum distance between resolvable peaks), this can give more points in
+ the plot, allowing for more detail. This corresponds to the *n* parameter
+ in the call to `~numpy.fft.fft`. The default is None, which sets *pad_to*
+ equal to the length of the input signal (i.e. no padding).""",
+
+ PSD="""\
+pad_to : int, optional
+ The number of points to which the data segment is padded when performing
+ the FFT. This can be different from *NFFT*, which specifies the number
+ of data points used. While not increasing the actual resolution of the
+ spectrum (the minimum distance between resolvable peaks), this can give
+ more points in the plot, allowing for more detail. This corresponds to
+ the *n* parameter in the call to `~numpy.fft.fft`. The default is None,
+ which sets *pad_to* equal to *NFFT*
+
+NFFT : int, default: 256
+ The number of data points used in each block for the FFT. A power 2 is
+ most efficient. This should *NOT* be used to get zero padding, or the
+ scaling of the result will be incorrect; use *pad_to* for this instead.
+
+detrend : {'none', 'mean', 'linear'} or callable, default: 'none'
+ The function applied to each segment before fft-ing, designed to remove
+ the mean or linear trend. Unlike in MATLAB, where the *detrend* parameter
+ is a vector, in Matplotlib it is a function. The :mod:`~matplotlib.mlab`
+ module defines `.detrend_none`, `.detrend_mean`, and `.detrend_linear`,
+ but you can use a custom function as well. You can also use a string to
+ choose one of the functions: 'none' calls `.detrend_none`. 'mean' calls
+ `.detrend_mean`. 'linear' calls `.detrend_linear`.
+
+scale_by_freq : bool, default: True
+ Whether the resulting density values should be scaled by the scaling
+ frequency, which gives density in units of 1/Hz. This allows for
+ integration over the returned frequency values. The default is True for
+ MATLAB compatibility.""")
+
+
+@_docstring.interpd
+def psd(x, NFFT=None, Fs=None, detrend=None, window=None,
+ noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
+ r"""
+ Compute the power spectral density.
+
+ The power spectral density :math:`P_{xx}` by Welch's average
+ periodogram method. The vector *x* is divided into *NFFT* length
+ segments. Each segment is detrended by function *detrend* and
+ windowed by function *window*. *noverlap* gives the length of
+ the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
+ of each segment :math:`i` are averaged to compute :math:`P_{xx}`.
+
+ If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
+
+ Parameters
+ ----------
+ x : 1-D array or sequence
+ Array or sequence containing the data
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 0 (no overlap)
+ The number of points of overlap between segments.
+
+ Returns
+ -------
+ Pxx : 1-D array
+ The values for the power spectrum :math:`P_{xx}` (real valued)
+
+ freqs : 1-D array
+ The frequencies corresponding to the elements in *Pxx*
+
+ References
+ ----------
+ Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
+ Wiley & Sons (1986)
+
+ See Also
+ --------
+ specgram
+ `specgram` differs in the default overlap; in not returning the mean of
+ the segment periodograms; and in returning the times of the segments.
+
+ magnitude_spectrum : returns the magnitude spectrum.
+
+ csd : returns the spectral density between two signals.
+ """
+ Pxx, freqs = csd(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend=detrend,
+ window=window, noverlap=noverlap, pad_to=pad_to,
+ sides=sides, scale_by_freq=scale_by_freq)
+ return Pxx.real, freqs
+
+
+@_docstring.interpd
+def csd(x, y, NFFT=None, Fs=None, detrend=None, window=None,
+ noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
+ """
+ Compute the cross-spectral density.
+
+ The cross spectral density :math:`P_{xy}` by Welch's average
+ periodogram method. The vectors *x* and *y* are divided into
+ *NFFT* length segments. Each segment is detrended by function
+ *detrend* and windowed by function *window*. *noverlap* gives
+ the length of the overlap between segments. The product of
+ the direct FFTs of *x* and *y* are averaged over each segment
+ to compute :math:`P_{xy}`, with a scaling to correct for power
+ loss due to windowing.
+
+ If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
+ padded to *NFFT*.
+
+ Parameters
+ ----------
+ x, y : 1-D arrays or sequences
+ Arrays or sequences containing the data
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 0 (no overlap)
+ The number of points of overlap between segments.
+
+ Returns
+ -------
+ Pxy : 1-D array
+ The values for the cross spectrum :math:`P_{xy}` before scaling (real
+ valued)
+
+ freqs : 1-D array
+ The frequencies corresponding to the elements in *Pxy*
+
+ References
+ ----------
+ Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
+ Wiley & Sons (1986)
+
+ See Also
+ --------
+ psd : equivalent to setting ``y = x``.
+ """
+ if NFFT is None:
+ NFFT = 256
+ Pxy, freqs, _ = _spectral_helper(x=x, y=y, NFFT=NFFT, Fs=Fs,
+ detrend_func=detrend, window=window,
+ noverlap=noverlap, pad_to=pad_to,
+ sides=sides, scale_by_freq=scale_by_freq,
+ mode='psd')
+
+ if Pxy.ndim == 2:
+ if Pxy.shape[1] > 1:
+ Pxy = Pxy.mean(axis=1)
+ else:
+ Pxy = Pxy[:, 0]
+ return Pxy, freqs
+
+
+_single_spectrum_docs = """\
+Compute the {quantity} of *x*.
+Data is padded to a length of *pad_to* and the windowing function *window* is
+applied to the signal.
+
+Parameters
+----------
+x : 1-D array or sequence
+ Array or sequence containing the data
+
+{Spectral}
+
+{Single_Spectrum}
+
+Returns
+-------
+spectrum : 1-D array
+ The {quantity}.
+freqs : 1-D array
+ The frequencies corresponding to the elements in *spectrum*.
+
+See Also
+--------
+psd
+ Returns the power spectral density.
+complex_spectrum
+ Returns the complex-valued frequency spectrum.
+magnitude_spectrum
+ Returns the absolute value of the `complex_spectrum`.
+angle_spectrum
+ Returns the angle of the `complex_spectrum`.
+phase_spectrum
+ Returns the phase (unwrapped angle) of the `complex_spectrum`.
+specgram
+ Can return the complex spectrum of segments within the signal.
+"""
+
+
+complex_spectrum = functools.partial(_single_spectrum_helper, "complex")
+complex_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="complex-valued frequency spectrum",
+ **_docstring.interpd.params)
+magnitude_spectrum = functools.partial(_single_spectrum_helper, "magnitude")
+magnitude_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="magnitude (absolute value) of the frequency spectrum",
+ **_docstring.interpd.params)
+angle_spectrum = functools.partial(_single_spectrum_helper, "angle")
+angle_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="angle of the frequency spectrum (wrapped phase spectrum)",
+ **_docstring.interpd.params)
+phase_spectrum = functools.partial(_single_spectrum_helper, "phase")
+phase_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="phase of the frequency spectrum (unwrapped phase spectrum)",
+ **_docstring.interpd.params)
+
+
+@_docstring.interpd
+def specgram(x, NFFT=None, Fs=None, detrend=None, window=None,
+ noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
+ mode=None):
+ """
+ Compute a spectrogram.
+
+ Compute and plot a spectrogram of data in *x*. Data are split into
+ *NFFT* length segments and the spectrum of each section is
+ computed. The windowing function *window* is applied to each
+ segment, and the amount of overlap of each segment is
+ specified with *noverlap*.
+
+ Parameters
+ ----------
+ x : array-like
+ 1-D array or sequence.
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 128
+ The number of points of overlap between blocks.
+ mode : str, default: 'psd'
+ What sort of spectrum to use:
+ 'psd'
+ Returns the power spectral density.
+ 'complex'
+ Returns the complex-valued frequency spectrum.
+ 'magnitude'
+ Returns the magnitude spectrum.
+ 'angle'
+ Returns the phase spectrum without unwrapping.
+ 'phase'
+ Returns the phase spectrum with unwrapping.
+
+ Returns
+ -------
+ spectrum : array-like
+ 2D array, columns are the periodograms of successive segments.
+
+ freqs : array-like
+ 1-D array, frequencies corresponding to the rows in *spectrum*.
+
+ t : array-like
+ 1-D array, the times corresponding to midpoints of segments
+ (i.e the columns in *spectrum*).
+
+ See Also
+ --------
+ psd : differs in the overlap and in the return values.
+ complex_spectrum : similar, but with complex valued frequencies.
+ magnitude_spectrum : similar single segment when *mode* is 'magnitude'.
+ angle_spectrum : similar to single segment when *mode* is 'angle'.
+ phase_spectrum : similar to single segment when *mode* is 'phase'.
+
+ Notes
+ -----
+ *detrend* and *scale_by_freq* only apply when *mode* is set to 'psd'.
+
+ """
+ if noverlap is None:
+ noverlap = 128 # default in _spectral_helper() is noverlap = 0
+ if NFFT is None:
+ NFFT = 256 # same default as in _spectral_helper()
+ if len(x) <= NFFT:
+ _api.warn_external("Only one segment is calculated since parameter "
+ f"NFFT (={NFFT}) >= signal length (={len(x)}).")
+
+ spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs,
+ detrend_func=detrend, window=window,
+ noverlap=noverlap, pad_to=pad_to,
+ sides=sides,
+ scale_by_freq=scale_by_freq,
+ mode=mode)
+
+ if mode != 'complex':
+ spec = spec.real # Needed since helper implements generically
+
+ return spec, freqs, t
+
+
+@_docstring.interpd
+def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
+ noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
+ r"""
+ The coherence between *x* and *y*. Coherence is the normalized
+ cross spectral density:
+
+ .. math::
+
+ C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}
+
+ Parameters
+ ----------
+ x, y
+ Array or sequence containing the data
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 0 (no overlap)
+ The number of points of overlap between segments.
+
+ Returns
+ -------
+ Cxy : 1-D array
+ The coherence vector.
+ freqs : 1-D array
+ The frequencies for the elements in *Cxy*.
+
+ See Also
+ --------
+ :func:`psd`, :func:`csd` :
+ For information about the methods used to compute :math:`P_{xy}`,
+ :math:`P_{xx}` and :math:`P_{yy}`.
+ """
+ if len(x) < 2 * NFFT:
+ raise ValueError(
+ "Coherence is calculated by averaging over *NFFT* length "
+ "segments. Your signal is too short for your choice of *NFFT*.")
+ Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
+ scale_by_freq)
+ Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
+ scale_by_freq)
+ Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
+ scale_by_freq)
+ Cxy = np.abs(Pxy) ** 2 / (Pxx * Pyy)
+ return Cxy, f
+
+
+class GaussianKDE:
+ """
+ Representation of a kernel-density estimate using Gaussian kernels.
+
+ Parameters
+ ----------
+ dataset : array-like
+ Datapoints to estimate from. In case of univariate data this is a 1-D
+ array, otherwise a 2D array with shape (# of dims, # of data).
+ bw_method : {'scott', 'silverman'} or float or callable, optional
+ The method used to calculate the estimator bandwidth. If a
+ float, this will be used directly as `kde.factor`. If a
+ callable, it should take a `GaussianKDE` instance as only
+ parameter and return a float. If None (default), 'scott' is used.
+
+ Attributes
+ ----------
+ dataset : ndarray
+ The dataset passed to the constructor.
+ dim : int
+ Number of dimensions.
+ num_dp : int
+ Number of datapoints.
+ factor : float
+ The bandwidth factor, obtained from `kde.covariance_factor`, with which
+ the covariance matrix is multiplied.
+ covariance : ndarray
+ The covariance matrix of *dataset*, scaled by the calculated bandwidth
+ (`kde.factor`).
+ inv_cov : ndarray
+ The inverse of *covariance*.
+
+ Methods
+ -------
+ kde.evaluate(points) : ndarray
+ Evaluate the estimated pdf on a provided set of points.
+ kde(points) : ndarray
+ Same as kde.evaluate(points)
+ """
+
+ # This implementation with minor modification was too good to pass up.
+ # from scipy: https://github.com/scipy/scipy/blob/master/scipy/stats/kde.py
+
+ def __init__(self, dataset, bw_method=None):
+ self.dataset = np.atleast_2d(dataset)
+ if not np.array(self.dataset).size > 1:
+ raise ValueError("`dataset` input should have multiple elements.")
+
+ self.dim, self.num_dp = np.array(self.dataset).shape
+
+ if bw_method is None:
+ pass
+ elif cbook._str_equal(bw_method, 'scott'):
+ self.covariance_factor = self.scotts_factor
+ elif cbook._str_equal(bw_method, 'silverman'):
+ self.covariance_factor = self.silverman_factor
+ elif isinstance(bw_method, Number):
+ self._bw_method = 'use constant'
+ self.covariance_factor = lambda: bw_method
+ elif callable(bw_method):
+ self._bw_method = bw_method
+ self.covariance_factor = lambda: self._bw_method(self)
+ else:
+ raise ValueError("`bw_method` should be 'scott', 'silverman', a "
+ "scalar or a callable")
+
+ # Computes the covariance matrix for each Gaussian kernel using
+ # covariance_factor().
+
+ self.factor = self.covariance_factor()
+ # Cache covariance and inverse covariance of the data
+ if not hasattr(self, '_data_inv_cov'):
+ self.data_covariance = np.atleast_2d(
+ np.cov(
+ self.dataset,
+ rowvar=1,
+ bias=False))
+ self.data_inv_cov = np.linalg.inv(self.data_covariance)
+
+ self.covariance = self.data_covariance * self.factor ** 2
+ self.inv_cov = self.data_inv_cov / self.factor ** 2
+ self.norm_factor = (np.sqrt(np.linalg.det(2 * np.pi * self.covariance))
+ * self.num_dp)
+
+ def scotts_factor(self):
+ return np.power(self.num_dp, -1. / (self.dim + 4))
+
+ def silverman_factor(self):
+ return np.power(
+ self.num_dp * (self.dim + 2.0) / 4.0, -1. / (self.dim + 4))
+
+ # Default method to calculate bandwidth, can be overwritten by subclass
+ covariance_factor = scotts_factor
+
+ def evaluate(self, points):
+ """
+ Evaluate the estimated pdf on a set of points.
+
+ Parameters
+ ----------
+ points : (# of dimensions, # of points)-array
+ Alternatively, a (# of dimensions,) vector can be passed in and
+ treated as a single point.
+
+ Returns
+ -------
+ (# of points,)-array
+ The values at each point.
+
+ Raises
+ ------
+ ValueError : if the dimensionality of the input points is different
+ than the dimensionality of the KDE.
+
+ """
+ points = np.atleast_2d(points)
+
+ dim, num_m = np.array(points).shape
+ if dim != self.dim:
+ raise ValueError(f"points have dimension {dim}, dataset has "
+ f"dimension {self.dim}")
+
+ result = np.zeros(num_m)
+
+ if num_m >= self.num_dp:
+ # there are more points than data, so loop over data
+ for i in range(self.num_dp):
+ diff = self.dataset[:, i, np.newaxis] - points
+ tdiff = np.dot(self.inv_cov, diff)
+ energy = np.sum(diff * tdiff, axis=0) / 2.0
+ result = result + np.exp(-energy)
+ else:
+ # loop over points
+ for i in range(num_m):
+ diff = self.dataset - points[:, i, np.newaxis]
+ tdiff = np.dot(self.inv_cov, diff)
+ energy = np.sum(diff * tdiff, axis=0) / 2.0
+ result[i] = np.sum(np.exp(-energy), axis=0)
+
+ result = result / self.norm_factor
+
+ return result
+
+ __call__ = evaluate
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/mlab.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/mlab.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1f23288dd10b1d8c4be54c0117bc6e34352d33c7
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/mlab.pyi
@@ -0,0 +1,100 @@
+from collections.abc import Callable
+import functools
+from typing import Literal
+
+import numpy as np
+from numpy.typing import ArrayLike
+
+def window_hanning(x: ArrayLike) -> ArrayLike: ...
+def window_none(x: ArrayLike) -> ArrayLike: ...
+def detrend(
+ x: ArrayLike,
+ key: Literal["default", "constant", "mean", "linear", "none"]
+ | Callable[[ArrayLike, int | None], ArrayLike]
+ | None = ...,
+ axis: int | None = ...,
+) -> ArrayLike: ...
+def detrend_mean(x: ArrayLike, axis: int | None = ...) -> ArrayLike: ...
+def detrend_none(x: ArrayLike, axis: int | None = ...) -> ArrayLike: ...
+def detrend_linear(y: ArrayLike) -> ArrayLike: ...
+def psd(
+ x: ArrayLike,
+ NFFT: int | None = ...,
+ Fs: float | None = ...,
+ detrend: Literal["none", "mean", "linear"]
+ | Callable[[ArrayLike, int | None], ArrayLike]
+ | None = ...,
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
+ noverlap: int | None = ...,
+ pad_to: int | None = ...,
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
+ scale_by_freq: bool | None = ...,
+) -> tuple[ArrayLike, ArrayLike]: ...
+def csd(
+ x: ArrayLike,
+ y: ArrayLike | None,
+ NFFT: int | None = ...,
+ Fs: float | None = ...,
+ detrend: Literal["none", "mean", "linear"]
+ | Callable[[ArrayLike, int | None], ArrayLike]
+ | None = ...,
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
+ noverlap: int | None = ...,
+ pad_to: int | None = ...,
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
+ scale_by_freq: bool | None = ...,
+) -> tuple[ArrayLike, ArrayLike]: ...
+
+complex_spectrum = functools.partial(tuple[ArrayLike, ArrayLike])
+magnitude_spectrum = functools.partial(tuple[ArrayLike, ArrayLike])
+angle_spectrum = functools.partial(tuple[ArrayLike, ArrayLike])
+phase_spectrum = functools.partial(tuple[ArrayLike, ArrayLike])
+
+def specgram(
+ x: ArrayLike,
+ NFFT: int | None = ...,
+ Fs: float | None = ...,
+ detrend: Literal["none", "mean", "linear"] | Callable[[ArrayLike, int | None], ArrayLike] | None = ...,
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
+ noverlap: int | None = ...,
+ pad_to: int | None = ...,
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
+ scale_by_freq: bool | None = ...,
+ mode: Literal["psd", "complex", "magnitude", "angle", "phase"] | None = ...,
+) -> tuple[ArrayLike, ArrayLike, ArrayLike]: ...
+def cohere(
+ x: ArrayLike,
+ y: ArrayLike,
+ NFFT: int = ...,
+ Fs: float = ...,
+ detrend: Literal["none", "mean", "linear"] | Callable[[ArrayLike, int | None], ArrayLike] = ...,
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike = ...,
+ noverlap: int = ...,
+ pad_to: int | None = ...,
+ sides: Literal["default", "onesided", "twosided"] = ...,
+ scale_by_freq: bool | None = ...,
+) -> tuple[ArrayLike, ArrayLike]: ...
+
+class GaussianKDE:
+ dataset: ArrayLike
+ dim: int
+ num_dp: int
+ factor: float
+ data_covariance: ArrayLike
+ data_inv_cov: ArrayLike
+ covariance: ArrayLike
+ inv_cov: ArrayLike
+ norm_factor: float
+ def __init__(
+ self,
+ dataset: ArrayLike,
+ bw_method: Literal["scott", "silverman"]
+ | float
+ | Callable[[GaussianKDE], float]
+ | None = ...,
+ ) -> None: ...
+ def scotts_factor(self) -> float: ...
+ def silverman_factor(self) -> float: ...
+ def covariance_factor(self) -> float: ...
+ def evaluate(self, points: ArrayLike) -> np.ndarray: ...
+ def __call__(self, points: ArrayLike) -> np.ndarray: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/patches.py b/llava_video/lib/python3.10/site-packages/matplotlib/patches.py
new file mode 100644
index 0000000000000000000000000000000000000000..f47c8abee32da45a5c6988f56d9f92f146d5f9bf
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/patches.py
@@ -0,0 +1,4719 @@
+r"""
+Patches are `.Artist`\s with a face color and an edge color.
+"""
+
+import functools
+import inspect
+import math
+from numbers import Number, Real
+import textwrap
+from types import SimpleNamespace
+from collections import namedtuple
+from matplotlib.transforms import Affine2D
+
+import numpy as np
+
+import matplotlib as mpl
+from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch,
+ lines as mlines, transforms)
+from .bezier import (
+ NonIntersectingPathException, get_cos_sin, get_intersection,
+ get_parallels, inside_circle, make_wedged_bezier2,
+ split_bezier_intersecting_with_closedpath, split_path_inout)
+from .path import Path
+from ._enums import JoinStyle, CapStyle
+
+
+@_docstring.interpd
+@_api.define_aliases({
+ "antialiased": ["aa"],
+ "edgecolor": ["ec"],
+ "facecolor": ["fc"],
+ "linestyle": ["ls"],
+ "linewidth": ["lw"],
+})
+class Patch(artist.Artist):
+ """
+ A patch is a 2D artist with a face color and an edge color.
+
+ If any of *edgecolor*, *facecolor*, *linewidth*, or *antialiased*
+ are *None*, they default to their rc params setting.
+ """
+ zorder = 1
+
+ # Whether to draw an edge by default. Set on a
+ # subclass-by-subclass basis.
+ _edge_default = False
+
+ def __init__(self, *,
+ edgecolor=None,
+ facecolor=None,
+ color=None,
+ linewidth=None,
+ linestyle=None,
+ antialiased=None,
+ hatch=None,
+ fill=True,
+ capstyle=None,
+ joinstyle=None,
+ **kwargs):
+ """
+ The following kwarg properties are supported
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__()
+
+ if linestyle is None:
+ linestyle = "solid"
+ if capstyle is None:
+ capstyle = CapStyle.butt
+ if joinstyle is None:
+ joinstyle = JoinStyle.miter
+
+ self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color'])
+ self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
+ self._fill = bool(fill) # needed for set_facecolor call
+ if color is not None:
+ if edgecolor is not None or facecolor is not None:
+ _api.warn_external(
+ "Setting the 'color' property will override "
+ "the edgecolor or facecolor properties.")
+ self.set_color(color)
+ else:
+ self.set_edgecolor(edgecolor)
+ self.set_facecolor(facecolor)
+
+ self._linewidth = 0
+ self._unscaled_dash_pattern = (0, None) # offset, dash
+ self._dash_pattern = (0, None) # offset, dash (scaled by linewidth)
+
+ self.set_linestyle(linestyle)
+ self.set_linewidth(linewidth)
+ self.set_antialiased(antialiased)
+ self.set_hatch(hatch)
+ self.set_capstyle(capstyle)
+ self.set_joinstyle(joinstyle)
+
+ if len(kwargs):
+ self._internal_update(kwargs)
+
+ def get_verts(self):
+ """
+ Return a copy of the vertices used in this patch.
+
+ If the patch contains Bézier curves, the curves will be interpolated by
+ line segments. To access the curves as curves, use `get_path`.
+ """
+ trans = self.get_transform()
+ path = self.get_path()
+ polygons = path.to_polygons(trans)
+ if len(polygons):
+ return polygons[0]
+ return []
+
+ def _process_radius(self, radius):
+ if radius is not None:
+ return radius
+ if isinstance(self._picker, Number):
+ _radius = self._picker
+ else:
+ if self.get_edgecolor()[3] == 0:
+ _radius = 0
+ else:
+ _radius = self.get_linewidth()
+ return _radius
+
+ def contains(self, mouseevent, radius=None):
+ """
+ Test whether the mouse event occurred in the patch.
+
+ Parameters
+ ----------
+ mouseevent : `~matplotlib.backend_bases.MouseEvent`
+ Where the user clicked.
+
+ radius : float, optional
+ Additional margin on the patch in target coordinates of
+ `.Patch.get_transform`. See `.Path.contains_point` for further
+ details.
+
+ If `None`, the default value depends on the state of the object:
+
+ - If `.Artist.get_picker` is a number, the default
+ is that value. This is so that picking works as expected.
+ - Otherwise if the edge color has a non-zero alpha, the default
+ is half of the linewidth. This is so that all the colored
+ pixels are "in" the patch.
+ - Finally, if the edge has 0 alpha, the default is 0. This is
+ so that patches without a stroked edge do not have points
+ outside of the filled region report as "in" due to an
+ invisible edge.
+
+
+ Returns
+ -------
+ (bool, empty dict)
+ """
+ if self._different_canvas(mouseevent):
+ return False, {}
+ radius = self._process_radius(radius)
+ codes = self.get_path().codes
+ if codes is not None:
+ vertices = self.get_path().vertices
+ # if the current path is concatenated by multiple sub paths.
+ # get the indexes of the starting code(MOVETO) of all sub paths
+ idxs, = np.where(codes == Path.MOVETO)
+ # Don't split before the first MOVETO.
+ idxs = idxs[1:]
+ subpaths = map(
+ Path, np.split(vertices, idxs), np.split(codes, idxs))
+ else:
+ subpaths = [self.get_path()]
+ inside = any(
+ subpath.contains_point(
+ (mouseevent.x, mouseevent.y), self.get_transform(), radius)
+ for subpath in subpaths)
+ return inside, {}
+
+ def contains_point(self, point, radius=None):
+ """
+ Return whether the given point is inside the patch.
+
+ Parameters
+ ----------
+ point : (float, float)
+ The point (x, y) to check, in target coordinates of
+ ``.Patch.get_transform()``. These are display coordinates for patches
+ that are added to a figure or Axes.
+ radius : float, optional
+ Additional margin on the patch in target coordinates of
+ `.Patch.get_transform`. See `.Path.contains_point` for further
+ details.
+
+ If `None`, the default value depends on the state of the object:
+
+ - If `.Artist.get_picker` is a number, the default
+ is that value. This is so that picking works as expected.
+ - Otherwise if the edge color has a non-zero alpha, the default
+ is half of the linewidth. This is so that all the colored
+ pixels are "in" the patch.
+ - Finally, if the edge has 0 alpha, the default is 0. This is
+ so that patches without a stroked edge do not have points
+ outside of the filled region report as "in" due to an
+ invisible edge.
+
+ Returns
+ -------
+ bool
+
+ Notes
+ -----
+ The proper use of this method depends on the transform of the patch.
+ Isolated patches do not have a transform. In this case, the patch
+ creation coordinates and the point coordinates match. The following
+ example checks that the center of a circle is within the circle
+
+ >>> center = 0, 0
+ >>> c = Circle(center, radius=1)
+ >>> c.contains_point(center)
+ True
+
+ The convention of checking against the transformed patch stems from
+ the fact that this method is predominantly used to check if display
+ coordinates (e.g. from mouse events) are within the patch. If you want
+ to do the above check with data coordinates, you have to properly
+ transform them first:
+
+ >>> center = 0, 0
+ >>> c = Circle(center, radius=3)
+ >>> plt.gca().add_patch(c)
+ >>> transformed_interior_point = c.get_data_transform().transform((0, 2))
+ >>> c.contains_point(transformed_interior_point)
+ True
+
+ """
+ radius = self._process_radius(radius)
+ return self.get_path().contains_point(point,
+ self.get_transform(),
+ radius)
+
+ def contains_points(self, points, radius=None):
+ """
+ Return whether the given points are inside the patch.
+
+ Parameters
+ ----------
+ points : (N, 2) array
+ The points to check, in target coordinates of
+ ``self.get_transform()``. These are display coordinates for patches
+ that are added to a figure or Axes. Columns contain x and y values.
+ radius : float, optional
+ Additional margin on the patch in target coordinates of
+ `.Patch.get_transform`. See `.Path.contains_point` for further
+ details.
+
+ If `None`, the default value depends on the state of the object:
+
+ - If `.Artist.get_picker` is a number, the default
+ is that value. This is so that picking works as expected.
+ - Otherwise if the edge color has a non-zero alpha, the default
+ is half of the linewidth. This is so that all the colored
+ pixels are "in" the patch.
+ - Finally, if the edge has 0 alpha, the default is 0. This is
+ so that patches without a stroked edge do not have points
+ outside of the filled region report as "in" due to an
+ invisible edge.
+
+ Returns
+ -------
+ length-N bool array
+
+ Notes
+ -----
+ The proper use of this method depends on the transform of the patch.
+ See the notes on `.Patch.contains_point`.
+ """
+ radius = self._process_radius(radius)
+ return self.get_path().contains_points(points,
+ self.get_transform(),
+ radius)
+
+ def update_from(self, other):
+ # docstring inherited.
+ super().update_from(other)
+ # For some properties we don't need or don't want to go through the
+ # getters/setters, so we just copy them directly.
+ self._edgecolor = other._edgecolor
+ self._facecolor = other._facecolor
+ self._original_edgecolor = other._original_edgecolor
+ self._original_facecolor = other._original_facecolor
+ self._fill = other._fill
+ self._hatch = other._hatch
+ self._hatch_color = other._hatch_color
+ self._unscaled_dash_pattern = other._unscaled_dash_pattern
+ self.set_linewidth(other._linewidth) # also sets scaled dashes
+ self.set_transform(other.get_data_transform())
+ # If the transform of other needs further initialization, then it will
+ # be the case for this artist too.
+ self._transformSet = other.is_transform_set()
+
+ def get_extents(self):
+ """
+ Return the `Patch`'s axis-aligned extents as a `~.transforms.Bbox`.
+ """
+ return self.get_path().get_extents(self.get_transform())
+
+ def get_transform(self):
+ """Return the `~.transforms.Transform` applied to the `Patch`."""
+ return self.get_patch_transform() + artist.Artist.get_transform(self)
+
+ def get_data_transform(self):
+ """
+ Return the `~.transforms.Transform` mapping data coordinates to
+ physical coordinates.
+ """
+ return artist.Artist.get_transform(self)
+
+ def get_patch_transform(self):
+ """
+ Return the `~.transforms.Transform` instance mapping patch coordinates
+ to data coordinates.
+
+ For example, one may define a patch of a circle which represents a
+ radius of 5 by providing coordinates for a unit circle, and a
+ transform which scales the coordinates (the patch coordinate) by 5.
+ """
+ return transforms.IdentityTransform()
+
+ def get_antialiased(self):
+ """Return whether antialiasing is used for drawing."""
+ return self._antialiased
+
+ def get_edgecolor(self):
+ """Return the edge color."""
+ return self._edgecolor
+
+ def get_facecolor(self):
+ """Return the face color."""
+ return self._facecolor
+
+ def get_linewidth(self):
+ """Return the line width in points."""
+ return self._linewidth
+
+ def get_linestyle(self):
+ """Return the linestyle."""
+ return self._linestyle
+
+ def set_antialiased(self, aa):
+ """
+ Set whether to use antialiased rendering.
+
+ Parameters
+ ----------
+ aa : bool or None
+ """
+ if aa is None:
+ aa = mpl.rcParams['patch.antialiased']
+ self._antialiased = aa
+ self.stale = True
+
+ def _set_edgecolor(self, color):
+ set_hatch_color = True
+ if color is None:
+ if (mpl.rcParams['patch.force_edgecolor'] or
+ not self._fill or self._edge_default):
+ color = mpl.rcParams['patch.edgecolor']
+ else:
+ color = 'none'
+ set_hatch_color = False
+
+ self._edgecolor = colors.to_rgba(color, self._alpha)
+ if set_hatch_color:
+ self._hatch_color = self._edgecolor
+ self.stale = True
+
+ def set_edgecolor(self, color):
+ """
+ Set the patch edge color.
+
+ Parameters
+ ----------
+ color : :mpltype:`color` or None
+ """
+ self._original_edgecolor = color
+ self._set_edgecolor(color)
+
+ def _set_facecolor(self, color):
+ if color is None:
+ color = mpl.rcParams['patch.facecolor']
+ alpha = self._alpha if self._fill else 0
+ self._facecolor = colors.to_rgba(color, alpha)
+ self.stale = True
+
+ def set_facecolor(self, color):
+ """
+ Set the patch face color.
+
+ Parameters
+ ----------
+ color : :mpltype:`color` or None
+ """
+ self._original_facecolor = color
+ self._set_facecolor(color)
+
+ def set_color(self, c):
+ """
+ Set both the edgecolor and the facecolor.
+
+ Parameters
+ ----------
+ c : :mpltype:`color`
+
+ See Also
+ --------
+ Patch.set_facecolor, Patch.set_edgecolor
+ For setting the edge or face color individually.
+ """
+ self.set_facecolor(c)
+ self.set_edgecolor(c)
+
+ def set_alpha(self, alpha):
+ # docstring inherited
+ super().set_alpha(alpha)
+ self._set_facecolor(self._original_facecolor)
+ self._set_edgecolor(self._original_edgecolor)
+ # stale is already True
+
+ def set_linewidth(self, w):
+ """
+ Set the patch linewidth in points.
+
+ Parameters
+ ----------
+ w : float or None
+ """
+ if w is None:
+ w = mpl.rcParams['patch.linewidth']
+ self._linewidth = float(w)
+ self._dash_pattern = mlines._scale_dashes(
+ *self._unscaled_dash_pattern, w)
+ self.stale = True
+
+ def set_linestyle(self, ls):
+ """
+ Set the patch linestyle.
+
+ ========================================== =================
+ linestyle description
+ ========================================== =================
+ ``'-'`` or ``'solid'`` solid line
+ ``'--'`` or ``'dashed'`` dashed line
+ ``'-.'`` or ``'dashdot'`` dash-dotted line
+ ``':'`` or ``'dotted'`` dotted line
+ ``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing
+ ========================================== =================
+
+ Alternatively a dash tuple of the following form can be provided::
+
+ (offset, onoffseq)
+
+ where ``onoffseq`` is an even length tuple of on and off ink in points.
+
+ Parameters
+ ----------
+ ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
+ The line style.
+ """
+ if ls is None:
+ ls = "solid"
+ if ls in [' ', '', 'none']:
+ ls = 'None'
+ self._linestyle = ls
+ self._unscaled_dash_pattern = mlines._get_dash_pattern(ls)
+ self._dash_pattern = mlines._scale_dashes(
+ *self._unscaled_dash_pattern, self._linewidth)
+ self.stale = True
+
+ def set_fill(self, b):
+ """
+ Set whether to fill the patch.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ self._fill = bool(b)
+ self._set_facecolor(self._original_facecolor)
+ self._set_edgecolor(self._original_edgecolor)
+ self.stale = True
+
+ def get_fill(self):
+ """Return whether the patch is filled."""
+ return self._fill
+
+ # Make fill a property so as to preserve the long-standing
+ # but somewhat inconsistent behavior in which fill was an
+ # attribute.
+ fill = property(get_fill, set_fill)
+
+ @_docstring.interpd
+ def set_capstyle(self, s):
+ """
+ Set the `.CapStyle`.
+
+ The default capstyle is 'round' for `.FancyArrowPatch` and 'butt' for
+ all other patches.
+
+ Parameters
+ ----------
+ s : `.CapStyle` or %(CapStyle)s
+ """
+ cs = CapStyle(s)
+ self._capstyle = cs
+ self.stale = True
+
+ def get_capstyle(self):
+ """Return the capstyle."""
+ return self._capstyle.name
+
+ @_docstring.interpd
+ def set_joinstyle(self, s):
+ """
+ Set the `.JoinStyle`.
+
+ The default joinstyle is 'round' for `.FancyArrowPatch` and 'miter' for
+ all other patches.
+
+ Parameters
+ ----------
+ s : `.JoinStyle` or %(JoinStyle)s
+ """
+ js = JoinStyle(s)
+ self._joinstyle = js
+ self.stale = True
+
+ def get_joinstyle(self):
+ """Return the joinstyle."""
+ return self._joinstyle.name
+
+ def set_hatch(self, hatch):
+ r"""
+ Set the hatching pattern.
+
+ *hatch* can be one of::
+
+ / - diagonal hatching
+ \ - back diagonal
+ | - vertical
+ - - horizontal
+ + - crossed
+ x - crossed diagonal
+ o - small circle
+ O - large circle
+ . - dots
+ * - stars
+
+ Letters can be combined, in which case all the specified
+ hatchings are done. If same letter repeats, it increases the
+ density of hatching of that pattern.
+
+ Parameters
+ ----------
+ hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
+ """
+ # Use validate_hatch(list) after deprecation.
+ mhatch._validate_hatch_pattern(hatch)
+ self._hatch = hatch
+ self.stale = True
+
+ def get_hatch(self):
+ """Return the hatching pattern."""
+ return self._hatch
+
+ def set_hatch_linewidth(self, lw):
+ """Set the hatch linewidth."""
+ self._hatch_linewidth = lw
+
+ def get_hatch_linewidth(self):
+ """Return the hatch linewidth."""
+ return self._hatch_linewidth
+
+ def _draw_paths_with_artist_properties(
+ self, renderer, draw_path_args_list):
+ """
+ ``draw()`` helper factored out for sharing with `FancyArrowPatch`.
+
+ Configure *renderer* and the associated graphics context *gc*
+ from the artist properties, then repeatedly call
+ ``renderer.draw_path(gc, *draw_path_args)`` for each tuple
+ *draw_path_args* in *draw_path_args_list*.
+ """
+
+ renderer.open_group('patch', self.get_gid())
+ gc = renderer.new_gc()
+
+ gc.set_foreground(self._edgecolor, isRGBA=True)
+
+ lw = self._linewidth
+ if self._edgecolor[3] == 0 or self._linestyle == 'None':
+ lw = 0
+ gc.set_linewidth(lw)
+ gc.set_dashes(*self._dash_pattern)
+ gc.set_capstyle(self._capstyle)
+ gc.set_joinstyle(self._joinstyle)
+
+ gc.set_antialiased(self._antialiased)
+ self._set_gc_clip(gc)
+ gc.set_url(self._url)
+ gc.set_snap(self.get_snap())
+
+ gc.set_alpha(self._alpha)
+
+ if self._hatch:
+ gc.set_hatch(self._hatch)
+ gc.set_hatch_color(self._hatch_color)
+ gc.set_hatch_linewidth(self._hatch_linewidth)
+
+ if self.get_sketch_params() is not None:
+ gc.set_sketch_params(*self.get_sketch_params())
+
+ if self.get_path_effects():
+ from matplotlib.patheffects import PathEffectRenderer
+ renderer = PathEffectRenderer(self.get_path_effects(), renderer)
+
+ for draw_path_args in draw_path_args_list:
+ renderer.draw_path(gc, *draw_path_args)
+
+ gc.restore()
+ renderer.close_group('patch')
+ self.stale = False
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+ if not self.get_visible():
+ return
+ path = self.get_path()
+ transform = self.get_transform()
+ tpath = transform.transform_path_non_affine(path)
+ affine = transform.get_affine()
+ self._draw_paths_with_artist_properties(
+ renderer,
+ [(tpath, affine,
+ # Work around a bug in the PDF and SVG renderers, which
+ # do not draw the hatches if the facecolor is fully
+ # transparent, but do if it is None.
+ self._facecolor if self._facecolor[3] else None)])
+
+ def get_path(self):
+ """Return the path of this patch."""
+ raise NotImplementedError('Derived must override')
+
+ def get_window_extent(self, renderer=None):
+ return self.get_path().get_extents(self.get_transform())
+
+ def _convert_xy_units(self, xy):
+ """Convert x and y units for a tuple (x, y)."""
+ x = self.convert_xunits(xy[0])
+ y = self.convert_yunits(xy[1])
+ return x, y
+
+
+class Shadow(Patch):
+ def __str__(self):
+ return f"Shadow({self.patch})"
+
+ @_docstring.interpd
+ def __init__(self, patch, ox, oy, *, shade=0.7, **kwargs):
+ """
+ Create a shadow of the given *patch*.
+
+ By default, the shadow will have the same face color as the *patch*,
+ but darkened. The darkness can be controlled by *shade*.
+
+ Parameters
+ ----------
+ patch : `~matplotlib.patches.Patch`
+ The patch to create the shadow for.
+ ox, oy : float
+ The shift of the shadow in data coordinates, scaled by a factor
+ of dpi/72.
+ shade : float, default: 0.7
+ How the darkness of the shadow relates to the original color. If 1, the
+ shadow is black, if 0, the shadow has the same color as the *patch*.
+
+ .. versionadded:: 3.8
+
+ **kwargs
+ Properties of the shadow patch. Supported keys are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__()
+ self.patch = patch
+ self._ox, self._oy = ox, oy
+ self._shadow_transform = transforms.Affine2D()
+
+ self.update_from(self.patch)
+ if not 0 <= shade <= 1:
+ raise ValueError("shade must be between 0 and 1.")
+ color = (1 - shade) * np.asarray(colors.to_rgb(self.patch.get_facecolor()))
+ self.update({'facecolor': color, 'edgecolor': color, 'alpha': 0.5,
+ # Place shadow patch directly behind the inherited patch.
+ 'zorder': np.nextafter(self.patch.zorder, -np.inf),
+ **kwargs})
+
+ def _update_transform(self, renderer):
+ ox = renderer.points_to_pixels(self._ox)
+ oy = renderer.points_to_pixels(self._oy)
+ self._shadow_transform.clear().translate(ox, oy)
+
+ def get_path(self):
+ return self.patch.get_path()
+
+ def get_patch_transform(self):
+ return self.patch.get_patch_transform() + self._shadow_transform
+
+ def draw(self, renderer):
+ self._update_transform(renderer)
+ super().draw(renderer)
+
+
+class Rectangle(Patch):
+ """
+ A rectangle defined via an anchor point *xy* and its *width* and *height*.
+
+ The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction
+ and from ``xy[1]`` to ``xy[1] + height`` in y-direction. ::
+
+ : +------------------+
+ : | |
+ : height |
+ : | |
+ : (xy)---- width -----+
+
+ One may picture *xy* as the bottom left corner, but which corner *xy* is
+ actually depends on the direction of the axis and the sign of *width*
+ and *height*; e.g. *xy* would be the bottom right corner if the x-axis
+ was inverted or if *width* was negative.
+ """
+
+ def __str__(self):
+ pars = self._x0, self._y0, self._width, self._height, self.angle
+ fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)"
+ return fmt % pars
+
+ @_docstring.interpd
+ def __init__(self, xy, width, height, *,
+ angle=0.0, rotation_point='xy', **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The anchor point.
+ width : float
+ Rectangle width.
+ height : float
+ Rectangle height.
+ angle : float, default: 0
+ Rotation in degrees anti-clockwise about the rotation point.
+ rotation_point : {'xy', 'center', (number, number)}, default: 'xy'
+ If ``'xy'``, rotate around the anchor point. If ``'center'`` rotate
+ around the center. If 2-tuple of number, rotate around this
+ coordinate.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._x0 = xy[0]
+ self._y0 = xy[1]
+ self._width = width
+ self._height = height
+ self.angle = float(angle)
+ self.rotation_point = rotation_point
+ # Required for RectangleSelector with axes aspect ratio != 1
+ # The patch is defined in data coordinates and when changing the
+ # selector with square modifier and not in data coordinates, we need
+ # to correct for the aspect ratio difference between the data and
+ # display coordinate systems. Its value is typically provide by
+ # Axes._get_aspect_ratio()
+ self._aspect_ratio_correction = 1.0
+ self._convert_units() # Validate the inputs.
+
+ def get_path(self):
+ """Return the vertices of the rectangle."""
+ return Path.unit_rectangle()
+
+ def _convert_units(self):
+ """Convert bounds of the rectangle."""
+ x0 = self.convert_xunits(self._x0)
+ y0 = self.convert_yunits(self._y0)
+ x1 = self.convert_xunits(self._x0 + self._width)
+ y1 = self.convert_yunits(self._y0 + self._height)
+ return x0, y0, x1, y1
+
+ def get_patch_transform(self):
+ # Note: This cannot be called until after this has been added to
+ # an Axes, otherwise unit conversion will fail. This makes it very
+ # important to call the accessor method and not directly access the
+ # transformation member variable.
+ bbox = self.get_bbox()
+ if self.rotation_point == 'center':
+ width, height = bbox.x1 - bbox.x0, bbox.y1 - bbox.y0
+ rotation_point = bbox.x0 + width / 2., bbox.y0 + height / 2.
+ elif self.rotation_point == 'xy':
+ rotation_point = bbox.x0, bbox.y0
+ else:
+ rotation_point = self.rotation_point
+ return transforms.BboxTransformTo(bbox) \
+ + transforms.Affine2D() \
+ .translate(-rotation_point[0], -rotation_point[1]) \
+ .scale(1, self._aspect_ratio_correction) \
+ .rotate_deg(self.angle) \
+ .scale(1, 1 / self._aspect_ratio_correction) \
+ .translate(*rotation_point)
+
+ @property
+ def rotation_point(self):
+ """The rotation point of the patch."""
+ return self._rotation_point
+
+ @rotation_point.setter
+ def rotation_point(self, value):
+ if value in ['center', 'xy'] or (
+ isinstance(value, tuple) and len(value) == 2 and
+ isinstance(value[0], Real) and isinstance(value[1], Real)
+ ):
+ self._rotation_point = value
+ else:
+ raise ValueError("`rotation_point` must be one of "
+ "{'xy', 'center', (number, number)}.")
+
+ def get_x(self):
+ """Return the left coordinate of the rectangle."""
+ return self._x0
+
+ def get_y(self):
+ """Return the bottom coordinate of the rectangle."""
+ return self._y0
+
+ def get_xy(self):
+ """Return the left and bottom coords of the rectangle as a tuple."""
+ return self._x0, self._y0
+
+ def get_corners(self):
+ """
+ Return the corners of the rectangle, moving anti-clockwise from
+ (x0, y0).
+ """
+ return self.get_patch_transform().transform(
+ [(0, 0), (1, 0), (1, 1), (0, 1)])
+
+ def get_center(self):
+ """Return the centre of the rectangle."""
+ return self.get_patch_transform().transform((0.5, 0.5))
+
+ def get_width(self):
+ """Return the width of the rectangle."""
+ return self._width
+
+ def get_height(self):
+ """Return the height of the rectangle."""
+ return self._height
+
+ def get_angle(self):
+ """Get the rotation angle in degrees."""
+ return self.angle
+
+ def set_x(self, x):
+ """Set the left coordinate of the rectangle."""
+ self._x0 = x
+ self.stale = True
+
+ def set_y(self, y):
+ """Set the bottom coordinate of the rectangle."""
+ self._y0 = y
+ self.stale = True
+
+ def set_angle(self, angle):
+ """
+ Set the rotation angle in degrees.
+
+ The rotation is performed anti-clockwise around *xy*.
+ """
+ self.angle = angle
+ self.stale = True
+
+ def set_xy(self, xy):
+ """
+ Set the left and bottom coordinates of the rectangle.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ """
+ self._x0, self._y0 = xy
+ self.stale = True
+
+ def set_width(self, w):
+ """Set the width of the rectangle."""
+ self._width = w
+ self.stale = True
+
+ def set_height(self, h):
+ """Set the height of the rectangle."""
+ self._height = h
+ self.stale = True
+
+ def set_bounds(self, *args):
+ """
+ Set the bounds of the rectangle as *left*, *bottom*, *width*, *height*.
+
+ The values may be passed as separate parameters or as a tuple::
+
+ set_bounds(left, bottom, width, height)
+ set_bounds((left, bottom, width, height))
+
+ .. ACCEPTS: (left, bottom, width, height)
+ """
+ if len(args) == 1:
+ l, b, w, h = args[0]
+ else:
+ l, b, w, h = args
+ self._x0 = l
+ self._y0 = b
+ self._width = w
+ self._height = h
+ self.stale = True
+
+ def get_bbox(self):
+ """Return the `.Bbox`."""
+ return transforms.Bbox.from_extents(*self._convert_units())
+
+ xy = property(get_xy, set_xy)
+
+
+class RegularPolygon(Patch):
+ """A regular polygon patch."""
+
+ def __str__(self):
+ s = "RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)"
+ return s % (self.xy[0], self.xy[1], self.numvertices, self.radius,
+ self.orientation)
+
+ @_docstring.interpd
+ def __init__(self, xy, numVertices, *,
+ radius=5, orientation=0, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The center position.
+
+ numVertices : int
+ The number of vertices.
+
+ radius : float
+ The distance from the center to each of the vertices.
+
+ orientation : float
+ The polygon rotation angle (in radians).
+
+ **kwargs
+ `Patch` properties:
+
+ %(Patch:kwdoc)s
+ """
+ self.xy = xy
+ self.numvertices = numVertices
+ self.orientation = orientation
+ self.radius = radius
+ self._path = Path.unit_regular_polygon(numVertices)
+ self._patch_transform = transforms.Affine2D()
+ super().__init__(**kwargs)
+
+ def get_path(self):
+ return self._path
+
+ def get_patch_transform(self):
+ return self._patch_transform.clear() \
+ .scale(self.radius) \
+ .rotate(self.orientation) \
+ .translate(*self.xy)
+
+
+class PathPatch(Patch):
+ """A general polycurve path patch."""
+
+ _edge_default = True
+
+ def __str__(self):
+ s = "PathPatch%d((%g, %g) ...)"
+ return s % (len(self._path.vertices), *tuple(self._path.vertices[0]))
+
+ @_docstring.interpd
+ def __init__(self, path, **kwargs):
+ """
+ *path* is a `.Path` object.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._path = path
+
+ def get_path(self):
+ return self._path
+
+ def set_path(self, path):
+ self._path = path
+
+
+class StepPatch(PathPatch):
+ """
+ A path patch describing a stepwise constant function.
+
+ By default, the path is not closed and starts and stops at
+ baseline value.
+ """
+
+ _edge_default = False
+
+ @_docstring.interpd
+ def __init__(self, values, edges, *,
+ orientation='vertical', baseline=0, **kwargs):
+ """
+ Parameters
+ ----------
+ values : array-like
+ The step heights.
+
+ edges : array-like
+ The edge positions, with ``len(edges) == len(vals) + 1``,
+ between which the curve takes on vals values.
+
+ orientation : {'vertical', 'horizontal'}, default: 'vertical'
+ The direction of the steps. Vertical means that *values* are
+ along the y-axis, and edges are along the x-axis.
+
+ baseline : float, array-like or None, default: 0
+ The bottom value of the bounding edges or when
+ ``fill=True``, position of lower edge. If *fill* is
+ True or an array is passed to *baseline*, a closed
+ path is drawn.
+
+ **kwargs
+ `Patch` properties:
+
+ %(Patch:kwdoc)s
+ """
+ self.orientation = orientation
+ self._edges = np.asarray(edges)
+ self._values = np.asarray(values)
+ self._baseline = np.asarray(baseline) if baseline is not None else None
+ self._update_path()
+ super().__init__(self._path, **kwargs)
+
+ def _update_path(self):
+ if np.isnan(np.sum(self._edges)):
+ raise ValueError('Nan values in "edges" are disallowed')
+ if self._edges.size - 1 != self._values.size:
+ raise ValueError('Size mismatch between "values" and "edges". '
+ "Expected `len(values) + 1 == len(edges)`, but "
+ f"`len(values) = {self._values.size}` and "
+ f"`len(edges) = {self._edges.size}`.")
+ # Initializing with empty arrays allows supporting empty stairs.
+ verts, codes = [np.empty((0, 2))], [np.empty(0, dtype=Path.code_type)]
+
+ _nan_mask = np.isnan(self._values)
+ if self._baseline is not None:
+ _nan_mask |= np.isnan(self._baseline)
+ for idx0, idx1 in cbook.contiguous_regions(~_nan_mask):
+ x = np.repeat(self._edges[idx0:idx1+1], 2)
+ y = np.repeat(self._values[idx0:idx1], 2)
+ if self._baseline is None:
+ y = np.concatenate([y[:1], y, y[-1:]])
+ elif self._baseline.ndim == 0: # single baseline value
+ y = np.concatenate([[self._baseline], y, [self._baseline]])
+ elif self._baseline.ndim == 1: # baseline array
+ base = np.repeat(self._baseline[idx0:idx1], 2)[::-1]
+ x = np.concatenate([x, x[::-1]])
+ y = np.concatenate([base[-1:], y, base[:1],
+ base[:1], base, base[-1:]])
+ else: # no baseline
+ raise ValueError('Invalid `baseline` specified')
+ if self.orientation == 'vertical':
+ xy = np.column_stack([x, y])
+ else:
+ xy = np.column_stack([y, x])
+ verts.append(xy)
+ codes.append([Path.MOVETO] + [Path.LINETO]*(len(xy)-1))
+ self._path = Path(np.concatenate(verts), np.concatenate(codes))
+
+ def get_data(self):
+ """Get `.StepPatch` values, edges and baseline as namedtuple."""
+ StairData = namedtuple('StairData', 'values edges baseline')
+ return StairData(self._values, self._edges, self._baseline)
+
+ def set_data(self, values=None, edges=None, baseline=None):
+ """
+ Set `.StepPatch` values, edges and baseline.
+
+ Parameters
+ ----------
+ values : 1D array-like or None
+ Will not update values, if passing None
+ edges : 1D array-like, optional
+ baseline : float, 1D array-like or None
+ """
+ if values is None and edges is None and baseline is None:
+ raise ValueError("Must set *values*, *edges* or *baseline*.")
+ if values is not None:
+ self._values = np.asarray(values)
+ if edges is not None:
+ self._edges = np.asarray(edges)
+ if baseline is not None:
+ self._baseline = np.asarray(baseline)
+ self._update_path()
+ self.stale = True
+
+
+class Polygon(Patch):
+ """A general polygon patch."""
+
+ def __str__(self):
+ if len(self._path.vertices):
+ s = "Polygon%d((%g, %g) ...)"
+ return s % (len(self._path.vertices), *self._path.vertices[0])
+ else:
+ return "Polygon0()"
+
+ @_docstring.interpd
+ def __init__(self, xy, *, closed=True, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (N, 2) array
+
+ closed : bool, default: True
+ Whether the polygon is closed (i.e., has identical start and end
+ points).
+
+ **kwargs
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._closed = closed
+ self.set_xy(xy)
+
+ def get_path(self):
+ """Get the `.Path` of the polygon."""
+ return self._path
+
+ def get_closed(self):
+ """Return whether the polygon is closed."""
+ return self._closed
+
+ def set_closed(self, closed):
+ """
+ Set whether the polygon is closed.
+
+ Parameters
+ ----------
+ closed : bool
+ True if the polygon is closed
+ """
+ if self._closed == bool(closed):
+ return
+ self._closed = bool(closed)
+ self.set_xy(self.get_xy())
+ self.stale = True
+
+ def get_xy(self):
+ """
+ Get the vertices of the path.
+
+ Returns
+ -------
+ (N, 2) array
+ The coordinates of the vertices.
+ """
+ return self._path.vertices
+
+ def set_xy(self, xy):
+ """
+ Set the vertices of the polygon.
+
+ Parameters
+ ----------
+ xy : (N, 2) array-like
+ The coordinates of the vertices.
+
+ Notes
+ -----
+ Unlike `.Path`, we do not ignore the last input vertex. If the
+ polygon is meant to be closed, and the last point of the polygon is not
+ equal to the first, we assume that the user has not explicitly passed a
+ ``CLOSEPOLY`` vertex, and add it ourselves.
+ """
+ xy = np.asarray(xy)
+ nverts, _ = xy.shape
+ if self._closed:
+ # if the first and last vertex are the "same", then we assume that
+ # the user explicitly passed the CLOSEPOLY vertex. Otherwise, we
+ # have to append one since the last vertex will be "ignored" by
+ # Path
+ if nverts == 1 or nverts > 1 and (xy[0] != xy[-1]).any():
+ xy = np.concatenate([xy, [xy[0]]])
+ else:
+ # if we aren't closed, and the last vertex matches the first, then
+ # we assume we have an unnecessary CLOSEPOLY vertex and remove it
+ if nverts > 2 and (xy[0] == xy[-1]).all():
+ xy = xy[:-1]
+ self._path = Path(xy, closed=self._closed)
+ self.stale = True
+
+ xy = property(get_xy, set_xy,
+ doc='The vertices of the path as a (N, 2) array.')
+
+
+class Wedge(Patch):
+ """Wedge shaped patch."""
+
+ def __str__(self):
+ pars = (self.center[0], self.center[1], self.r,
+ self.theta1, self.theta2, self.width)
+ fmt = "Wedge(center=(%g, %g), r=%g, theta1=%g, theta2=%g, width=%s)"
+ return fmt % pars
+
+ @_docstring.interpd
+ def __init__(self, center, r, theta1, theta2, *, width=None, **kwargs):
+ """
+ A wedge centered at *x*, *y* center with radius *r* that
+ sweeps *theta1* to *theta2* (in degrees). If *width* is given,
+ then a partial wedge is drawn from inner radius *r* - *width*
+ to outer radius *r*.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self.center = center
+ self.r, self.width = r, width
+ self.theta1, self.theta2 = theta1, theta2
+ self._patch_transform = transforms.IdentityTransform()
+ self._recompute_path()
+
+ def _recompute_path(self):
+ # Inner and outer rings are connected unless the annulus is complete
+ if abs((self.theta2 - self.theta1) - 360) <= 1e-12:
+ theta1, theta2 = 0, 360
+ connector = Path.MOVETO
+ else:
+ theta1, theta2 = self.theta1, self.theta2
+ connector = Path.LINETO
+
+ # Form the outer ring
+ arc = Path.arc(theta1, theta2)
+
+ if self.width is not None:
+ # Partial annulus needs to draw the outer ring
+ # followed by a reversed and scaled inner ring
+ v1 = arc.vertices
+ v2 = arc.vertices[::-1] * (self.r - self.width) / self.r
+ v = np.concatenate([v1, v2, [(0, 0)]])
+ c = [*arc.codes, connector, *arc.codes[1:], Path.CLOSEPOLY]
+ else:
+ # Wedge doesn't need an inner ring
+ v = np.concatenate([arc.vertices, [(0, 0), (0, 0)]])
+ c = [*arc.codes, connector, Path.CLOSEPOLY]
+
+ # Shift and scale the wedge to the final location.
+ self._path = Path(v * self.r + self.center, c)
+
+ def set_center(self, center):
+ self._path = None
+ self.center = center
+ self.stale = True
+
+ def set_radius(self, radius):
+ self._path = None
+ self.r = radius
+ self.stale = True
+
+ def set_theta1(self, theta1):
+ self._path = None
+ self.theta1 = theta1
+ self.stale = True
+
+ def set_theta2(self, theta2):
+ self._path = None
+ self.theta2 = theta2
+ self.stale = True
+
+ def set_width(self, width):
+ self._path = None
+ self.width = width
+ self.stale = True
+
+ def get_path(self):
+ if self._path is None:
+ self._recompute_path()
+ return self._path
+
+
+# COVERAGE NOTE: Not used internally or from examples
+class Arrow(Patch):
+ """An arrow patch."""
+
+ def __str__(self):
+ return "Arrow()"
+
+ _path = Path._create_closed([
+ [0.0, 0.1], [0.0, -0.1], [0.8, -0.1], [0.8, -0.3], [1.0, 0.0],
+ [0.8, 0.3], [0.8, 0.1]])
+
+ @_docstring.interpd
+ def __init__(self, x, y, dx, dy, *, width=1.0, **kwargs):
+ """
+ Draws an arrow from (*x*, *y*) to (*x* + *dx*, *y* + *dy*).
+ The width of the arrow is scaled by *width*.
+
+ Parameters
+ ----------
+ x : float
+ x coordinate of the arrow tail.
+ y : float
+ y coordinate of the arrow tail.
+ dx : float
+ Arrow length in the x direction.
+ dy : float
+ Arrow length in the y direction.
+ width : float, default: 1
+ Scale factor for the width of the arrow. With a default value of 1,
+ the tail width is 0.2 and head width is 0.6.
+ **kwargs
+ Keyword arguments control the `Patch` properties:
+
+ %(Patch:kwdoc)s
+
+ See Also
+ --------
+ FancyArrow
+ Patch that allows independent control of the head and tail
+ properties.
+ """
+ super().__init__(**kwargs)
+ self.set_data(x, y, dx, dy, width)
+
+ def get_path(self):
+ return self._path
+
+ def get_patch_transform(self):
+ return self._patch_transform
+
+ def set_data(self, x=None, y=None, dx=None, dy=None, width=None):
+ """
+ Set `.Arrow` x, y, dx, dy and width.
+ Values left as None will not be updated.
+
+ Parameters
+ ----------
+ x, y : float or None, default: None
+ The x and y coordinates of the arrow base.
+
+ dx, dy : float or None, default: None
+ The length of the arrow along x and y direction.
+
+ width : float or None, default: None
+ Width of full arrow tail.
+ """
+ if x is not None:
+ self._x = x
+ if y is not None:
+ self._y = y
+ if dx is not None:
+ self._dx = dx
+ if dy is not None:
+ self._dy = dy
+ if width is not None:
+ self._width = width
+ self._patch_transform = (
+ transforms.Affine2D()
+ .scale(np.hypot(self._dx, self._dy), self._width)
+ .rotate(np.arctan2(self._dy, self._dx))
+ .translate(self._x, self._y)
+ .frozen())
+
+
+class FancyArrow(Polygon):
+ """
+ Like Arrow, but lets you set head width and head height independently.
+ """
+
+ _edge_default = True
+
+ def __str__(self):
+ return "FancyArrow()"
+
+ @_docstring.interpd
+ def __init__(self, x, y, dx, dy, *,
+ width=0.001, length_includes_head=False, head_width=None,
+ head_length=None, shape='full', overhang=0,
+ head_starts_at_zero=False, **kwargs):
+ """
+ Parameters
+ ----------
+ x, y : float
+ The x and y coordinates of the arrow base.
+
+ dx, dy : float
+ The length of the arrow along x and y direction.
+
+ width : float, default: 0.001
+ Width of full arrow tail.
+
+ length_includes_head : bool, default: False
+ True if head is to be counted in calculating the length.
+
+ head_width : float or None, default: 3*width
+ Total width of the full arrow head.
+
+ head_length : float or None, default: 1.5*head_width
+ Length of arrow head.
+
+ shape : {'full', 'left', 'right'}, default: 'full'
+ Draw the left-half, right-half, or full arrow.
+
+ overhang : float, default: 0
+ Fraction that the arrow is swept back (0 overhang means
+ triangular shape). Can be negative or greater than one.
+
+ head_starts_at_zero : bool, default: False
+ If True, the head starts being drawn at coordinate 0
+ instead of ending at coordinate 0.
+
+ **kwargs
+ `.Patch` properties:
+
+ %(Patch:kwdoc)s
+ """
+ self._x = x
+ self._y = y
+ self._dx = dx
+ self._dy = dy
+ self._width = width
+ self._length_includes_head = length_includes_head
+ self._head_width = head_width
+ self._head_length = head_length
+ self._shape = shape
+ self._overhang = overhang
+ self._head_starts_at_zero = head_starts_at_zero
+ self._make_verts()
+ super().__init__(self.verts, closed=True, **kwargs)
+
+ def set_data(self, *, x=None, y=None, dx=None, dy=None, width=None,
+ head_width=None, head_length=None):
+ """
+ Set `.FancyArrow` x, y, dx, dy, width, head_with, and head_length.
+ Values left as None will not be updated.
+
+ Parameters
+ ----------
+ x, y : float or None, default: None
+ The x and y coordinates of the arrow base.
+
+ dx, dy : float or None, default: None
+ The length of the arrow along x and y direction.
+
+ width : float or None, default: None
+ Width of full arrow tail.
+
+ head_width : float or None, default: None
+ Total width of the full arrow head.
+
+ head_length : float or None, default: None
+ Length of arrow head.
+ """
+ if x is not None:
+ self._x = x
+ if y is not None:
+ self._y = y
+ if dx is not None:
+ self._dx = dx
+ if dy is not None:
+ self._dy = dy
+ if width is not None:
+ self._width = width
+ if head_width is not None:
+ self._head_width = head_width
+ if head_length is not None:
+ self._head_length = head_length
+ self._make_verts()
+ self.set_xy(self.verts)
+
+ def _make_verts(self):
+ if self._head_width is None:
+ head_width = 3 * self._width
+ else:
+ head_width = self._head_width
+ if self._head_length is None:
+ head_length = 1.5 * head_width
+ else:
+ head_length = self._head_length
+
+ distance = np.hypot(self._dx, self._dy)
+
+ if self._length_includes_head:
+ length = distance
+ else:
+ length = distance + head_length
+ if not length:
+ self.verts = np.empty([0, 2]) # display nothing if empty
+ else:
+ # start by drawing horizontal arrow, point at (0, 0)
+ hw, hl = head_width, head_length
+ hs, lw = self._overhang, self._width
+ left_half_arrow = np.array([
+ [0.0, 0.0], # tip
+ [-hl, -hw / 2], # leftmost
+ [-hl * (1 - hs), -lw / 2], # meets stem
+ [-length, -lw / 2], # bottom left
+ [-length, 0],
+ ])
+ # if we're not including the head, shift up by head length
+ if not self._length_includes_head:
+ left_half_arrow += [head_length, 0]
+ # if the head starts at 0, shift up by another head length
+ if self._head_starts_at_zero:
+ left_half_arrow += [head_length / 2, 0]
+ # figure out the shape, and complete accordingly
+ if self._shape == 'left':
+ coords = left_half_arrow
+ else:
+ right_half_arrow = left_half_arrow * [1, -1]
+ if self._shape == 'right':
+ coords = right_half_arrow
+ elif self._shape == 'full':
+ # The half-arrows contain the midpoint of the stem,
+ # which we can omit from the full arrow. Including it
+ # twice caused a problem with xpdf.
+ coords = np.concatenate([left_half_arrow[:-1],
+ right_half_arrow[-2::-1]])
+ else:
+ raise ValueError(f"Got unknown shape: {self._shape!r}")
+ if distance != 0:
+ cx = self._dx / distance
+ sx = self._dy / distance
+ else:
+ # Account for division by zero
+ cx, sx = 0, 1
+ M = [[cx, sx], [-sx, cx]]
+ self.verts = np.dot(coords, M) + [
+ self._x + self._dx,
+ self._y + self._dy,
+ ]
+
+
+_docstring.interpd.register(
+ FancyArrow="\n".join(
+ (inspect.getdoc(FancyArrow.__init__) or "").splitlines()[2:]))
+
+
+class CirclePolygon(RegularPolygon):
+ """A polygon-approximation of a circle patch."""
+
+ def __str__(self):
+ s = "CirclePolygon((%g, %g), radius=%g, resolution=%d)"
+ return s % (self.xy[0], self.xy[1], self.radius, self.numvertices)
+
+ @_docstring.interpd
+ def __init__(self, xy, radius=5, *,
+ resolution=20, # the number of vertices
+ ** kwargs):
+ """
+ Create a circle at *xy* = (*x*, *y*) with given *radius*.
+
+ This circle is approximated by a regular polygon with *resolution*
+ sides. For a smoother circle drawn with splines, see `Circle`.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(
+ xy, resolution, radius=radius, orientation=0, **kwargs)
+
+
+class Ellipse(Patch):
+ """A scale-free ellipse."""
+
+ def __str__(self):
+ pars = (self._center[0], self._center[1],
+ self.width, self.height, self.angle)
+ fmt = "Ellipse(xy=(%s, %s), width=%s, height=%s, angle=%s)"
+ return fmt % pars
+
+ @_docstring.interpd
+ def __init__(self, xy, width, height, *, angle=0, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ xy coordinates of ellipse centre.
+ width : float
+ Total length (diameter) of horizontal axis.
+ height : float
+ Total length (diameter) of vertical axis.
+ angle : float, default: 0
+ Rotation in degrees anti-clockwise.
+
+ Notes
+ -----
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+
+ self._center = xy
+ self._width, self._height = width, height
+ self._angle = angle
+ self._path = Path.unit_circle()
+ # Required for EllipseSelector with axes aspect ratio != 1
+ # The patch is defined in data coordinates and when changing the
+ # selector with square modifier and not in data coordinates, we need
+ # to correct for the aspect ratio difference between the data and
+ # display coordinate systems.
+ self._aspect_ratio_correction = 1.0
+ # Note: This cannot be calculated until this is added to an Axes
+ self._patch_transform = transforms.IdentityTransform()
+
+ def _recompute_transform(self):
+ """
+ Notes
+ -----
+ This cannot be called until after this has been added to an Axes,
+ otherwise unit conversion will fail. This makes it very important to
+ call the accessor method and not directly access the transformation
+ member variable.
+ """
+ center = (self.convert_xunits(self._center[0]),
+ self.convert_yunits(self._center[1]))
+ width = self.convert_xunits(self._width)
+ height = self.convert_yunits(self._height)
+ self._patch_transform = transforms.Affine2D() \
+ .scale(width * 0.5, height * 0.5 * self._aspect_ratio_correction) \
+ .rotate_deg(self.angle) \
+ .scale(1, 1 / self._aspect_ratio_correction) \
+ .translate(*center)
+
+ def get_path(self):
+ """Return the path of the ellipse."""
+ return self._path
+
+ def get_patch_transform(self):
+ self._recompute_transform()
+ return self._patch_transform
+
+ def set_center(self, xy):
+ """
+ Set the center of the ellipse.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ """
+ self._center = xy
+ self.stale = True
+
+ def get_center(self):
+ """Return the center of the ellipse."""
+ return self._center
+
+ center = property(get_center, set_center)
+
+ def set_width(self, width):
+ """
+ Set the width of the ellipse.
+
+ Parameters
+ ----------
+ width : float
+ """
+ self._width = width
+ self.stale = True
+
+ def get_width(self):
+ """
+ Return the width of the ellipse.
+ """
+ return self._width
+
+ width = property(get_width, set_width)
+
+ def set_height(self, height):
+ """
+ Set the height of the ellipse.
+
+ Parameters
+ ----------
+ height : float
+ """
+ self._height = height
+ self.stale = True
+
+ def get_height(self):
+ """Return the height of the ellipse."""
+ return self._height
+
+ height = property(get_height, set_height)
+
+ def set_angle(self, angle):
+ """
+ Set the angle of the ellipse.
+
+ Parameters
+ ----------
+ angle : float
+ """
+ self._angle = angle
+ self.stale = True
+
+ def get_angle(self):
+ """Return the angle of the ellipse."""
+ return self._angle
+
+ angle = property(get_angle, set_angle)
+
+ def get_corners(self):
+ """
+ Return the corners of the ellipse bounding box.
+
+ The bounding box orientation is moving anti-clockwise from the
+ lower left corner defined before rotation.
+ """
+ return self.get_patch_transform().transform(
+ [(-1, -1), (1, -1), (1, 1), (-1, 1)])
+
+ def get_vertices(self):
+ """
+ Return the vertices coordinates of the ellipse.
+
+ The definition can be found `here `_
+
+ .. versionadded:: 3.8
+ """
+ if self.width < self.height:
+ ret = self.get_patch_transform().transform([(0, 1), (0, -1)])
+ else:
+ ret = self.get_patch_transform().transform([(1, 0), (-1, 0)])
+ return [tuple(x) for x in ret]
+
+ def get_co_vertices(self):
+ """
+ Return the co-vertices coordinates of the ellipse.
+
+ The definition can be found `here `_
+
+ .. versionadded:: 3.8
+ """
+ if self.width < self.height:
+ ret = self.get_patch_transform().transform([(1, 0), (-1, 0)])
+ else:
+ ret = self.get_patch_transform().transform([(0, 1), (0, -1)])
+ return [tuple(x) for x in ret]
+
+
+class Annulus(Patch):
+ """
+ An elliptical annulus.
+ """
+
+ @_docstring.interpd
+ def __init__(self, xy, r, width, angle=0.0, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ xy coordinates of annulus centre.
+ r : float or (float, float)
+ The radius, or semi-axes:
+
+ - If float: radius of the outer circle.
+ - If two floats: semi-major and -minor axes of outer ellipse.
+ width : float
+ Width (thickness) of the annular ring. The width is measured inward
+ from the outer ellipse so that for the inner ellipse the semi-axes
+ are given by ``r - width``. *width* must be less than or equal to
+ the semi-minor axis.
+ angle : float, default: 0
+ Rotation angle in degrees (anti-clockwise from the positive
+ x-axis). Ignored for circular annuli (i.e., if *r* is a scalar).
+ **kwargs
+ Keyword arguments control the `Patch` properties:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+
+ self.set_radii(r)
+ self.center = xy
+ self.width = width
+ self.angle = angle
+ self._path = None
+
+ def __str__(self):
+ if self.a == self.b:
+ r = self.a
+ else:
+ r = (self.a, self.b)
+
+ return "Annulus(xy=(%s, %s), r=%s, width=%s, angle=%s)" % \
+ (*self.center, r, self.width, self.angle)
+
+ def set_center(self, xy):
+ """
+ Set the center of the annulus.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ """
+ self._center = xy
+ self._path = None
+ self.stale = True
+
+ def get_center(self):
+ """Return the center of the annulus."""
+ return self._center
+
+ center = property(get_center, set_center)
+
+ def set_width(self, width):
+ """
+ Set the width (thickness) of the annulus ring.
+
+ The width is measured inwards from the outer ellipse.
+
+ Parameters
+ ----------
+ width : float
+ """
+ if width > min(self.a, self.b):
+ raise ValueError(
+ 'Width of annulus must be less than or equal to semi-minor axis')
+
+ self._width = width
+ self._path = None
+ self.stale = True
+
+ def get_width(self):
+ """Return the width (thickness) of the annulus ring."""
+ return self._width
+
+ width = property(get_width, set_width)
+
+ def set_angle(self, angle):
+ """
+ Set the tilt angle of the annulus.
+
+ Parameters
+ ----------
+ angle : float
+ """
+ self._angle = angle
+ self._path = None
+ self.stale = True
+
+ def get_angle(self):
+ """Return the angle of the annulus."""
+ return self._angle
+
+ angle = property(get_angle, set_angle)
+
+ def set_semimajor(self, a):
+ """
+ Set the semi-major axis *a* of the annulus.
+
+ Parameters
+ ----------
+ a : float
+ """
+ self.a = float(a)
+ self._path = None
+ self.stale = True
+
+ def set_semiminor(self, b):
+ """
+ Set the semi-minor axis *b* of the annulus.
+
+ Parameters
+ ----------
+ b : float
+ """
+ self.b = float(b)
+ self._path = None
+ self.stale = True
+
+ def set_radii(self, r):
+ """
+ Set the semi-major (*a*) and semi-minor radii (*b*) of the annulus.
+
+ Parameters
+ ----------
+ r : float or (float, float)
+ The radius, or semi-axes:
+
+ - If float: radius of the outer circle.
+ - If two floats: semi-major and -minor axes of outer ellipse.
+ """
+ if np.shape(r) == (2,):
+ self.a, self.b = r
+ elif np.shape(r) == ():
+ self.a = self.b = float(r)
+ else:
+ raise ValueError("Parameter 'r' must be one or two floats.")
+
+ self._path = None
+ self.stale = True
+
+ def get_radii(self):
+ """Return the semi-major and semi-minor radii of the annulus."""
+ return self.a, self.b
+
+ radii = property(get_radii, set_radii)
+
+ def _transform_verts(self, verts, a, b):
+ return transforms.Affine2D() \
+ .scale(*self._convert_xy_units((a, b))) \
+ .rotate_deg(self.angle) \
+ .translate(*self._convert_xy_units(self.center)) \
+ .transform(verts)
+
+ def _recompute_path(self):
+ # circular arc
+ arc = Path.arc(0, 360)
+
+ # annulus needs to draw an outer ring
+ # followed by a reversed and scaled inner ring
+ a, b, w = self.a, self.b, self.width
+ v1 = self._transform_verts(arc.vertices, a, b)
+ v2 = self._transform_verts(arc.vertices[::-1], a - w, b - w)
+ v = np.vstack([v1, v2, v1[0, :], (0, 0)])
+ c = np.hstack([arc.codes, Path.MOVETO,
+ arc.codes[1:], Path.MOVETO,
+ Path.CLOSEPOLY])
+ self._path = Path(v, c)
+
+ def get_path(self):
+ if self._path is None:
+ self._recompute_path()
+ return self._path
+
+
+class Circle(Ellipse):
+ """
+ A circle patch.
+ """
+ def __str__(self):
+ pars = self.center[0], self.center[1], self.radius
+ fmt = "Circle(xy=(%g, %g), radius=%g)"
+ return fmt % pars
+
+ @_docstring.interpd
+ def __init__(self, xy, radius=5, **kwargs):
+ """
+ Create a true circle at center *xy* = (*x*, *y*) with given *radius*.
+
+ Unlike `CirclePolygon` which is a polygonal approximation, this uses
+ Bezier splines and is much closer to a scale-free circle.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(xy, radius * 2, radius * 2, **kwargs)
+ self.radius = radius
+
+ def set_radius(self, radius):
+ """
+ Set the radius of the circle.
+
+ Parameters
+ ----------
+ radius : float
+ """
+ self.width = self.height = 2 * radius
+ self.stale = True
+
+ def get_radius(self):
+ """Return the radius of the circle."""
+ return self.width / 2.
+
+ radius = property(get_radius, set_radius)
+
+
+class Arc(Ellipse):
+ """
+ An elliptical arc, i.e. a segment of an ellipse.
+
+ Due to internal optimizations, the arc cannot be filled.
+ """
+
+ def __str__(self):
+ pars = (self.center[0], self.center[1], self.width,
+ self.height, self.angle, self.theta1, self.theta2)
+ fmt = ("Arc(xy=(%g, %g), width=%g, "
+ "height=%g, angle=%g, theta1=%g, theta2=%g)")
+ return fmt % pars
+
+ @_docstring.interpd
+ def __init__(self, xy, width, height, *,
+ angle=0.0, theta1=0.0, theta2=360.0, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The center of the ellipse.
+
+ width : float
+ The length of the horizontal axis.
+
+ height : float
+ The length of the vertical axis.
+
+ angle : float
+ Rotation of the ellipse in degrees (counterclockwise).
+
+ theta1, theta2 : float, default: 0, 360
+ Starting and ending angles of the arc in degrees. These values
+ are relative to *angle*, e.g. if *angle* = 45 and *theta1* = 90
+ the absolute starting angle is 135.
+ Default *theta1* = 0, *theta2* = 360, i.e. a complete ellipse.
+ The arc is drawn in the counterclockwise direction.
+ Angles greater than or equal to 360, or smaller than 0, are
+ represented by an equivalent angle in the range [0, 360), by
+ taking the input value mod 360.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties
+ Most `.Patch` properties are supported as keyword arguments,
+ except *fill* and *facecolor* because filling is not supported.
+
+ %(Patch:kwdoc)s
+ """
+ fill = kwargs.setdefault('fill', False)
+ if fill:
+ raise ValueError("Arc objects cannot be filled")
+
+ super().__init__(xy, width, height, angle=angle, **kwargs)
+
+ self.theta1 = theta1
+ self.theta2 = theta2
+ (self._theta1, self._theta2, self._stretched_width,
+ self._stretched_height) = self._theta_stretch()
+ self._path = Path.arc(self._theta1, self._theta2)
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ """
+ Draw the arc to the given *renderer*.
+
+ Notes
+ -----
+ Ellipses are normally drawn using an approximation that uses
+ eight cubic Bezier splines. The error of this approximation
+ is 1.89818e-6, according to this unverified source:
+
+ Lancaster, Don. *Approximating a Circle or an Ellipse Using
+ Four Bezier Cubic Splines.*
+
+ https://www.tinaja.com/glib/ellipse4.pdf
+
+ There is a use case where very large ellipses must be drawn
+ with very high accuracy, and it is too expensive to render the
+ entire ellipse with enough segments (either splines or line
+ segments). Therefore, in the case where either radius of the
+ ellipse is large enough that the error of the spline
+ approximation will be visible (greater than one pixel offset
+ from the ideal), a different technique is used.
+
+ In that case, only the visible parts of the ellipse are drawn,
+ with each visible arc using a fixed number of spline segments
+ (8). The algorithm proceeds as follows:
+
+ 1. The points where the ellipse intersects the axes (or figure)
+ bounding box are located. (This is done by performing an inverse
+ transformation on the bbox such that it is relative to the unit
+ circle -- this makes the intersection calculation much easier than
+ doing rotated ellipse intersection directly.)
+
+ This uses the "line intersecting a circle" algorithm from:
+
+ Vince, John. *Geometry for Computer Graphics: Formulae,
+ Examples & Proofs.* London: Springer-Verlag, 2005.
+
+ 2. The angles of each of the intersection points are calculated.
+
+ 3. Proceeding counterclockwise starting in the positive
+ x-direction, each of the visible arc-segments between the
+ pairs of vertices are drawn using the Bezier arc
+ approximation technique implemented in `.Path.arc`.
+ """
+ if not self.get_visible():
+ return
+
+ self._recompute_transform()
+
+ self._update_path()
+ # Get width and height in pixels we need to use
+ # `self.get_data_transform` rather than `self.get_transform`
+ # because we want the transform from dataspace to the
+ # screen space to estimate how big the arc will be in physical
+ # units when rendered (the transform that we get via
+ # `self.get_transform()` goes from an idealized unit-radius
+ # space to screen space).
+ data_to_screen_trans = self.get_data_transform()
+ pwidth, pheight = (
+ data_to_screen_trans.transform((self._stretched_width,
+ self._stretched_height)) -
+ data_to_screen_trans.transform((0, 0)))
+ inv_error = (1.0 / 1.89818e-6) * 0.5
+
+ if pwidth < inv_error and pheight < inv_error:
+ return Patch.draw(self, renderer)
+
+ def line_circle_intersect(x0, y0, x1, y1):
+ dx = x1 - x0
+ dy = y1 - y0
+ dr2 = dx * dx + dy * dy
+ D = x0 * y1 - x1 * y0
+ D2 = D * D
+ discrim = dr2 - D2
+ if discrim >= 0.0:
+ sign_dy = np.copysign(1, dy) # +/-1, never 0.
+ sqrt_discrim = np.sqrt(discrim)
+ return np.array(
+ [[(D * dy + sign_dy * dx * sqrt_discrim) / dr2,
+ (-D * dx + abs(dy) * sqrt_discrim) / dr2],
+ [(D * dy - sign_dy * dx * sqrt_discrim) / dr2,
+ (-D * dx - abs(dy) * sqrt_discrim) / dr2]])
+ else:
+ return np.empty((0, 2))
+
+ def segment_circle_intersect(x0, y0, x1, y1):
+ epsilon = 1e-9
+ if x1 < x0:
+ x0e, x1e = x1, x0
+ else:
+ x0e, x1e = x0, x1
+ if y1 < y0:
+ y0e, y1e = y1, y0
+ else:
+ y0e, y1e = y0, y1
+ xys = line_circle_intersect(x0, y0, x1, y1)
+ xs, ys = xys.T
+ return xys[
+ (x0e - epsilon < xs) & (xs < x1e + epsilon)
+ & (y0e - epsilon < ys) & (ys < y1e + epsilon)
+ ]
+
+ # Transform the Axes (or figure) box_path so that it is relative to
+ # the unit circle in the same way that it is relative to the desired
+ # ellipse.
+ box_path_transform = (
+ transforms.BboxTransformTo((self.axes or self.get_figure(root=False)).bbox)
+ - self.get_transform())
+ box_path = Path.unit_rectangle().transformed(box_path_transform)
+
+ thetas = set()
+ # For each of the point pairs, there is a line segment
+ for p0, p1 in zip(box_path.vertices[:-1], box_path.vertices[1:]):
+ xy = segment_circle_intersect(*p0, *p1)
+ x, y = xy.T
+ # arctan2 return [-pi, pi), the rest of our angles are in
+ # [0, 360], adjust as needed.
+ theta = (np.rad2deg(np.arctan2(y, x)) + 360) % 360
+ thetas.update(
+ theta[(self._theta1 < theta) & (theta < self._theta2)])
+ thetas = sorted(thetas) + [self._theta2]
+ last_theta = self._theta1
+ theta1_rad = np.deg2rad(self._theta1)
+ inside = box_path.contains_point(
+ (np.cos(theta1_rad), np.sin(theta1_rad))
+ )
+
+ # save original path
+ path_original = self._path
+ for theta in thetas:
+ if inside:
+ self._path = Path.arc(last_theta, theta, 8)
+ Patch.draw(self, renderer)
+ inside = False
+ else:
+ inside = True
+ last_theta = theta
+
+ # restore original path
+ self._path = path_original
+
+ def _update_path(self):
+ # Compute new values and update and set new _path if any value changed
+ stretched = self._theta_stretch()
+ if any(a != b for a, b in zip(
+ stretched, (self._theta1, self._theta2, self._stretched_width,
+ self._stretched_height))):
+ (self._theta1, self._theta2, self._stretched_width,
+ self._stretched_height) = stretched
+ self._path = Path.arc(self._theta1, self._theta2)
+
+ def _theta_stretch(self):
+ # If the width and height of ellipse are not equal, take into account
+ # stretching when calculating angles to draw between
+ def theta_stretch(theta, scale):
+ theta = np.deg2rad(theta)
+ x = np.cos(theta)
+ y = np.sin(theta)
+ stheta = np.rad2deg(np.arctan2(scale * y, x))
+ # arctan2 has the range [-pi, pi], we expect [0, 2*pi]
+ return (stheta + 360) % 360
+
+ width = self.convert_xunits(self.width)
+ height = self.convert_yunits(self.height)
+ if (
+ # if we need to stretch the angles because we are distorted
+ width != height
+ # and we are not doing a full circle.
+ #
+ # 0 and 360 do not exactly round-trip through the angle
+ # stretching (due to both float precision limitations and
+ # the difference between the range of arctan2 [-pi, pi] and
+ # this method [0, 360]) so avoid doing it if we don't have to.
+ and not (self.theta1 != self.theta2 and
+ self.theta1 % 360 == self.theta2 % 360)
+ ):
+ theta1 = theta_stretch(self.theta1, width / height)
+ theta2 = theta_stretch(self.theta2, width / height)
+ return theta1, theta2, width, height
+ return self.theta1, self.theta2, width, height
+
+
+def bbox_artist(artist, renderer, props=None, fill=True):
+ """
+ A debug function to draw a rectangle around the bounding
+ box returned by an artist's `.Artist.get_window_extent`
+ to test whether the artist is returning the correct bbox.
+
+ *props* is a dict of rectangle props with the additional property
+ 'pad' that sets the padding around the bbox in points.
+ """
+ if props is None:
+ props = {}
+ props = props.copy() # don't want to alter the pad externally
+ pad = props.pop('pad', 4)
+ pad = renderer.points_to_pixels(pad)
+ bbox = artist.get_window_extent(renderer)
+ r = Rectangle(
+ xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2),
+ width=bbox.width + pad, height=bbox.height + pad,
+ fill=fill, transform=transforms.IdentityTransform(), clip_on=False)
+ r.update(props)
+ r.draw(renderer)
+
+
+def draw_bbox(bbox, renderer, color='k', trans=None):
+ """
+ A debug function to draw a rectangle around the bounding
+ box returned by an artist's `.Artist.get_window_extent`
+ to test whether the artist is returning the correct bbox.
+ """
+ r = Rectangle(xy=bbox.p0, width=bbox.width, height=bbox.height,
+ edgecolor=color, fill=False, clip_on=False)
+ if trans is not None:
+ r.set_transform(trans)
+ r.draw(renderer)
+
+
+class _Style:
+ """
+ A base class for the Styles. It is meant to be a container class,
+ where actual styles are declared as subclass of it, and it
+ provides some helper functions.
+ """
+
+ def __init_subclass__(cls):
+ # Automatically perform docstring interpolation on the subclasses:
+ # This allows listing the supported styles via
+ # - %(BoxStyle:table)s
+ # - %(ConnectionStyle:table)s
+ # - %(ArrowStyle:table)s
+ # and additionally adding .. ACCEPTS: blocks via
+ # - %(BoxStyle:table_and_accepts)s
+ # - %(ConnectionStyle:table_and_accepts)s
+ # - %(ArrowStyle:table_and_accepts)s
+ _docstring.interpd.register(**{
+ f"{cls.__name__}:table": cls.pprint_styles(),
+ f"{cls.__name__}:table_and_accepts": (
+ cls.pprint_styles()
+ + "\n\n .. ACCEPTS: ["
+ + "|".join(map(" '{}' ".format, cls._style_list))
+ + "]")
+ })
+
+ def __new__(cls, stylename, **kwargs):
+ """Return the instance of the subclass with the given style name."""
+ # The "class" should have the _style_list attribute, which is a mapping
+ # of style names to style classes.
+ _list = stylename.replace(" ", "").split(",")
+ _name = _list[0].lower()
+ try:
+ _cls = cls._style_list[_name]
+ except KeyError as err:
+ raise ValueError(f"Unknown style: {stylename!r}") from err
+ try:
+ _args_pair = [cs.split("=") for cs in _list[1:]]
+ _args = {k: float(v) for k, v in _args_pair}
+ except ValueError as err:
+ raise ValueError(
+ f"Incorrect style argument: {stylename!r}") from err
+ return _cls(**{**_args, **kwargs})
+
+ @classmethod
+ def get_styles(cls):
+ """Return a dictionary of available styles."""
+ return cls._style_list
+
+ @classmethod
+ def pprint_styles(cls):
+ """Return the available styles as pretty-printed string."""
+ table = [('Class', 'Name', 'Attrs'),
+ *[(cls.__name__,
+ # Add backquotes, as - and | have special meaning in reST.
+ f'``{name}``',
+ # [1:-1] drops the surrounding parentheses.
+ str(inspect.signature(cls))[1:-1] or 'None')
+ for name, cls in cls._style_list.items()]]
+ # Convert to rst table.
+ col_len = [max(len(cell) for cell in column) for column in zip(*table)]
+ table_formatstr = ' '.join('=' * cl for cl in col_len)
+ rst_table = '\n'.join([
+ '',
+ table_formatstr,
+ ' '.join(cell.ljust(cl) for cell, cl in zip(table[0], col_len)),
+ table_formatstr,
+ *[' '.join(cell.ljust(cl) for cell, cl in zip(row, col_len))
+ for row in table[1:]],
+ table_formatstr,
+ ])
+ return textwrap.indent(rst_table, prefix=' ' * 4)
+
+ @classmethod
+ @_api.deprecated(
+ '3.10.0',
+ message="This method is never used internally.",
+ alternative="No replacement. Please open an issue if you use this."
+ )
+ def register(cls, name, style):
+ """Register a new style."""
+ if not issubclass(style, cls._Base):
+ raise ValueError(f"{style} must be a subclass of {cls._Base}")
+ cls._style_list[name] = style
+
+
+def _register_style(style_list, cls=None, *, name=None):
+ """Class decorator that stashes a class in a (style) dictionary."""
+ if cls is None:
+ return functools.partial(_register_style, style_list, name=name)
+ style_list[name or cls.__name__.lower()] = cls
+ return cls
+
+
+@_docstring.interpd
+class BoxStyle(_Style):
+ """
+ `BoxStyle` is a container class which defines several
+ boxstyle classes, which are used for `FancyBboxPatch`.
+
+ A style object can be created as::
+
+ BoxStyle.Round(pad=0.2)
+
+ or::
+
+ BoxStyle("Round", pad=0.2)
+
+ or::
+
+ BoxStyle("Round, pad=0.2")
+
+ The following boxstyle classes are defined.
+
+ %(BoxStyle:table)s
+
+ An instance of a boxstyle class is a callable object, with the signature ::
+
+ __call__(self, x0, y0, width, height, mutation_size) -> Path
+
+ *x0*, *y0*, *width* and *height* specify the location and size of the box
+ to be drawn; *mutation_size* scales the outline properties such as padding.
+ """
+
+ _style_list = {}
+
+ @_register_style(_style_list)
+ class Square:
+ """A square box."""
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ pad = mutation_size * self.pad
+ # width and height with padding added.
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ x1, y1 = x0 + width, y0 + height
+ return Path._create_closed(
+ [(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
+
+ @_register_style(_style_list)
+ class Circle:
+ """A circular box."""
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ pad = mutation_size * self.pad
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ return Path.circle((x0 + width / 2, y0 + height / 2),
+ max(width, height) / 2)
+
+ @_register_style(_style_list)
+ class Ellipse:
+ """
+ An elliptical box.
+
+ .. versionadded:: 3.7
+ """
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ pad = mutation_size * self.pad
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ a = width / math.sqrt(2)
+ b = height / math.sqrt(2)
+ trans = Affine2D().scale(a, b).translate(x0 + width / 2,
+ y0 + height / 2)
+ return trans.transform_path(Path.unit_circle())
+
+ @_register_style(_style_list)
+ class LArrow:
+ """A box in the shape of a left-pointing arrow."""
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ # padding
+ pad = mutation_size * self.pad
+ # width and height with padding added.
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad,
+ x1, y1 = x0 + width, y0 + height
+
+ dx = (y1 - y0) / 2
+ dxx = dx / 2
+ x0 = x0 + pad / 1.4 # adjust by ~sqrt(2)
+
+ return Path._create_closed(
+ [(x0 + dxx, y0), (x1, y0), (x1, y1), (x0 + dxx, y1),
+ (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
+ (x0 + dxx, y0 - dxx), # arrow
+ (x0 + dxx, y0)])
+
+ @_register_style(_style_list)
+ class RArrow(LArrow):
+ """A box in the shape of a right-pointing arrow."""
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ p = BoxStyle.LArrow.__call__(
+ self, x0, y0, width, height, mutation_size)
+ p.vertices[:, 0] = 2 * x0 + width - p.vertices[:, 0]
+ return p
+
+ @_register_style(_style_list)
+ class DArrow:
+ """A box in the shape of a two-way arrow."""
+ # Modified from LArrow to add a right arrow to the bbox.
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ # padding
+ pad = mutation_size * self.pad
+ # width and height with padding added.
+ # The width is padded by the arrows, so we don't need to pad it.
+ height = height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ x1, y1 = x0 + width, y0 + height
+
+ dx = (y1 - y0) / 2
+ dxx = dx / 2
+ x0 = x0 + pad / 1.4 # adjust by ~sqrt(2)
+
+ return Path._create_closed([
+ (x0 + dxx, y0), (x1, y0), # bot-segment
+ (x1, y0 - dxx), (x1 + dx + dxx, y0 + dx),
+ (x1, y1 + dxx), # right-arrow
+ (x1, y1), (x0 + dxx, y1), # top-segment
+ (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
+ (x0 + dxx, y0 - dxx), # left-arrow
+ (x0 + dxx, y0)])
+
+ @_register_style(_style_list)
+ class Round:
+ """A box with round corners."""
+
+ def __init__(self, pad=0.3, rounding_size=None):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ rounding_size : float, default: *pad*
+ Radius of the corners.
+ """
+ self.pad = pad
+ self.rounding_size = rounding_size
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+
+ # padding
+ pad = mutation_size * self.pad
+
+ # size of the rounding corner
+ if self.rounding_size:
+ dr = mutation_size * self.rounding_size
+ else:
+ dr = pad
+
+ width, height = width + 2 * pad, height + 2 * pad
+
+ x0, y0 = x0 - pad, y0 - pad,
+ x1, y1 = x0 + width, y0 + height
+
+ # Round corners are implemented as quadratic Bezier, e.g.,
+ # [(x0, y0-dr), (x0, y0), (x0+dr, y0)] for lower left corner.
+ cp = [(x0 + dr, y0),
+ (x1 - dr, y0),
+ (x1, y0), (x1, y0 + dr),
+ (x1, y1 - dr),
+ (x1, y1), (x1 - dr, y1),
+ (x0 + dr, y1),
+ (x0, y1), (x0, y1 - dr),
+ (x0, y0 + dr),
+ (x0, y0), (x0 + dr, y0),
+ (x0 + dr, y0)]
+
+ com = [Path.MOVETO,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.CLOSEPOLY]
+
+ return Path(cp, com)
+
+ @_register_style(_style_list)
+ class Round4:
+ """A box with rounded edges."""
+
+ def __init__(self, pad=0.3, rounding_size=None):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ rounding_size : float, default: *pad*/2
+ Rounding of edges.
+ """
+ self.pad = pad
+ self.rounding_size = rounding_size
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+
+ # padding
+ pad = mutation_size * self.pad
+
+ # Rounding size; defaults to half of the padding.
+ if self.rounding_size:
+ dr = mutation_size * self.rounding_size
+ else:
+ dr = pad / 2.
+
+ width = width + 2 * pad - 2 * dr
+ height = height + 2 * pad - 2 * dr
+
+ x0, y0 = x0 - pad + dr, y0 - pad + dr,
+ x1, y1 = x0 + width, y0 + height
+
+ cp = [(x0, y0),
+ (x0 + dr, y0 - dr), (x1 - dr, y0 - dr), (x1, y0),
+ (x1 + dr, y0 + dr), (x1 + dr, y1 - dr), (x1, y1),
+ (x1 - dr, y1 + dr), (x0 + dr, y1 + dr), (x0, y1),
+ (x0 - dr, y1 - dr), (x0 - dr, y0 + dr), (x0, y0),
+ (x0, y0)]
+
+ com = [Path.MOVETO,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CLOSEPOLY]
+
+ return Path(cp, com)
+
+ @_register_style(_style_list)
+ class Sawtooth:
+ """A box with a sawtooth outline."""
+
+ def __init__(self, pad=0.3, tooth_size=None):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ tooth_size : float, default: *pad*/2
+ Size of the sawtooth.
+ """
+ self.pad = pad
+ self.tooth_size = tooth_size
+
+ def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size):
+
+ # padding
+ pad = mutation_size * self.pad
+
+ # size of sawtooth
+ if self.tooth_size is None:
+ tooth_size = self.pad * .5 * mutation_size
+ else:
+ tooth_size = self.tooth_size * mutation_size
+
+ hsz = tooth_size / 2
+ width = width + 2 * pad - tooth_size
+ height = height + 2 * pad - tooth_size
+
+ # the sizes of the vertical and horizontal sawtooth are
+ # separately adjusted to fit the given box size.
+ dsx_n = round((width - tooth_size) / (tooth_size * 2)) * 2
+ dsy_n = round((height - tooth_size) / (tooth_size * 2)) * 2
+
+ x0, y0 = x0 - pad + hsz, y0 - pad + hsz
+ x1, y1 = x0 + width, y0 + height
+
+ xs = [
+ x0, *np.linspace(x0 + hsz, x1 - hsz, 2 * dsx_n + 1), # bottom
+ *([x1, x1 + hsz, x1, x1 - hsz] * dsy_n)[:2*dsy_n+2], # right
+ x1, *np.linspace(x1 - hsz, x0 + hsz, 2 * dsx_n + 1), # top
+ *([x0, x0 - hsz, x0, x0 + hsz] * dsy_n)[:2*dsy_n+2], # left
+ ]
+ ys = [
+ *([y0, y0 - hsz, y0, y0 + hsz] * dsx_n)[:2*dsx_n+2], # bottom
+ y0, *np.linspace(y0 + hsz, y1 - hsz, 2 * dsy_n + 1), # right
+ *([y1, y1 + hsz, y1, y1 - hsz] * dsx_n)[:2*dsx_n+2], # top
+ y1, *np.linspace(y1 - hsz, y0 + hsz, 2 * dsy_n + 1), # left
+ ]
+
+ return [*zip(xs, ys), (xs[0], ys[0])]
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ saw_vertices = self._get_sawtooth_vertices(x0, y0, width,
+ height, mutation_size)
+ return Path(saw_vertices, closed=True)
+
+ @_register_style(_style_list)
+ class Roundtooth(Sawtooth):
+ """A box with a rounded sawtooth outline."""
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ saw_vertices = self._get_sawtooth_vertices(x0, y0,
+ width, height,
+ mutation_size)
+ # Add a trailing vertex to allow us to close the polygon correctly
+ saw_vertices = np.concatenate([saw_vertices, [saw_vertices[0]]])
+ codes = ([Path.MOVETO] +
+ [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1)//2) +
+ [Path.CLOSEPOLY])
+ return Path(saw_vertices, codes)
+
+
+@_docstring.interpd
+class ConnectionStyle(_Style):
+ """
+ `ConnectionStyle` is a container class which defines
+ several connectionstyle classes, which is used to create a path
+ between two points. These are mainly used with `FancyArrowPatch`.
+
+ A connectionstyle object can be either created as::
+
+ ConnectionStyle.Arc3(rad=0.2)
+
+ or::
+
+ ConnectionStyle("Arc3", rad=0.2)
+
+ or::
+
+ ConnectionStyle("Arc3, rad=0.2")
+
+ The following classes are defined
+
+ %(ConnectionStyle:table)s
+
+ An instance of any connection style class is a callable object,
+ whose call signature is::
+
+ __call__(self, posA, posB,
+ patchA=None, patchB=None,
+ shrinkA=2., shrinkB=2.)
+
+ and it returns a `.Path` instance. *posA* and *posB* are
+ tuples of (x, y) coordinates of the two points to be
+ connected. *patchA* (or *patchB*) is given, the returned path is
+ clipped so that it start (or end) from the boundary of the
+ patch. The path is further shrunk by *shrinkA* (or *shrinkB*)
+ which is given in points.
+ """
+
+ _style_list = {}
+
+ class _Base:
+ """
+ A base class for connectionstyle classes. The subclass needs
+ to implement a *connect* method whose call signature is::
+
+ connect(posA, posB)
+
+ where posA and posB are tuples of x, y coordinates to be
+ connected. The method needs to return a path connecting two
+ points. This base class defines a __call__ method, and a few
+ helper methods.
+ """
+ def _in_patch(self, patch):
+ """
+ Return a predicate function testing whether a point *xy* is
+ contained in *patch*.
+ """
+ return lambda xy: patch.contains(
+ SimpleNamespace(x=xy[0], y=xy[1]))[0]
+
+ def _clip(self, path, in_start, in_stop):
+ """
+ Clip *path* at its start by the region where *in_start* returns
+ True, and at its stop by the region where *in_stop* returns True.
+
+ The original path is assumed to start in the *in_start* region and
+ to stop in the *in_stop* region.
+ """
+ if in_start:
+ try:
+ _, path = split_path_inout(path, in_start)
+ except ValueError:
+ pass
+ if in_stop:
+ try:
+ path, _ = split_path_inout(path, in_stop)
+ except ValueError:
+ pass
+ return path
+
+ def __call__(self, posA, posB,
+ shrinkA=2., shrinkB=2., patchA=None, patchB=None):
+ """
+ Call the *connect* method to create a path between *posA* and
+ *posB*; then clip and shrink the path.
+ """
+ path = self.connect(posA, posB)
+ path = self._clip(
+ path,
+ self._in_patch(patchA) if patchA else None,
+ self._in_patch(patchB) if patchB else None,
+ )
+ path = self._clip(
+ path,
+ inside_circle(*path.vertices[0], shrinkA) if shrinkA else None,
+ inside_circle(*path.vertices[-1], shrinkB) if shrinkB else None
+ )
+ return path
+
+ @_register_style(_style_list)
+ class Arc3(_Base):
+ """
+ Creates a simple quadratic Bézier curve between two
+ points. The curve is created so that the middle control point
+ (C1) is located at the same distance from the start (C0) and
+ end points(C2) and the distance of the C1 to the line
+ connecting C0-C2 is *rad* times the distance of C0-C2.
+ """
+
+ def __init__(self, rad=0.):
+ """
+ Parameters
+ ----------
+ rad : float
+ Curvature of the curve.
+ """
+ self.rad = rad
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+ x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2.
+ dx, dy = x2 - x1, y2 - y1
+
+ f = self.rad
+
+ cx, cy = x12 + f * dy, y12 - f * dx
+
+ vertices = [(x1, y1),
+ (cx, cy),
+ (x2, y2)]
+ codes = [Path.MOVETO,
+ Path.CURVE3,
+ Path.CURVE3]
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Angle3(_Base):
+ """
+ Creates a simple quadratic Bézier curve between two points. The middle
+ control point is placed at the intersecting point of two lines which
+ cross the start and end point, and have a slope of *angleA* and
+ *angleB*, respectively.
+ """
+
+ def __init__(self, angleA=90, angleB=0):
+ """
+ Parameters
+ ----------
+ angleA : float
+ Starting angle of the path.
+
+ angleB : float
+ Ending angle of the path.
+ """
+
+ self.angleA = angleA
+ self.angleB = angleB
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+
+ cosA = math.cos(math.radians(self.angleA))
+ sinA = math.sin(math.radians(self.angleA))
+ cosB = math.cos(math.radians(self.angleB))
+ sinB = math.sin(math.radians(self.angleB))
+
+ cx, cy = get_intersection(x1, y1, cosA, sinA,
+ x2, y2, cosB, sinB)
+
+ vertices = [(x1, y1), (cx, cy), (x2, y2)]
+ codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Angle(_Base):
+ """
+ Creates a piecewise continuous quadratic Bézier path between two
+ points. The path has a one passing-through point placed at the
+ intersecting point of two lines which cross the start and end point,
+ and have a slope of *angleA* and *angleB*, respectively.
+ The connecting edges are rounded with *rad*.
+ """
+
+ def __init__(self, angleA=90, angleB=0, rad=0.):
+ """
+ Parameters
+ ----------
+ angleA : float
+ Starting angle of the path.
+
+ angleB : float
+ Ending angle of the path.
+
+ rad : float
+ Rounding radius of the edge.
+ """
+
+ self.angleA = angleA
+ self.angleB = angleB
+
+ self.rad = rad
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+
+ cosA = math.cos(math.radians(self.angleA))
+ sinA = math.sin(math.radians(self.angleA))
+ cosB = math.cos(math.radians(self.angleB))
+ sinB = math.sin(math.radians(self.angleB))
+
+ cx, cy = get_intersection(x1, y1, cosA, sinA,
+ x2, y2, cosB, sinB)
+
+ vertices = [(x1, y1)]
+ codes = [Path.MOVETO]
+
+ if self.rad == 0.:
+ vertices.append((cx, cy))
+ codes.append(Path.LINETO)
+ else:
+ dx1, dy1 = x1 - cx, y1 - cy
+ d1 = np.hypot(dx1, dy1)
+ f1 = self.rad / d1
+ dx2, dy2 = x2 - cx, y2 - cy
+ d2 = np.hypot(dx2, dy2)
+ f2 = self.rad / d2
+ vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
+ (cx, cy),
+ (cx + dx2 * f2, cy + dy2 * f2)])
+ codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3])
+
+ vertices.append((x2, y2))
+ codes.append(Path.LINETO)
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Arc(_Base):
+ """
+ Creates a piecewise continuous quadratic Bézier path between two
+ points. The path can have two passing-through points, a
+ point placed at the distance of *armA* and angle of *angleA* from
+ point A, another point with respect to point B. The edges are
+ rounded with *rad*.
+ """
+
+ def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.):
+ """
+ Parameters
+ ----------
+ angleA : float
+ Starting angle of the path.
+
+ angleB : float
+ Ending angle of the path.
+
+ armA : float or None
+ Length of the starting arm.
+
+ armB : float or None
+ Length of the ending arm.
+
+ rad : float
+ Rounding radius of the edges.
+ """
+
+ self.angleA = angleA
+ self.angleB = angleB
+ self.armA = armA
+ self.armB = armB
+
+ self.rad = rad
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+
+ vertices = [(x1, y1)]
+ rounded = []
+ codes = [Path.MOVETO]
+
+ if self.armA:
+ cosA = math.cos(math.radians(self.angleA))
+ sinA = math.sin(math.radians(self.angleA))
+ # x_armA, y_armB
+ d = self.armA - self.rad
+ rounded.append((x1 + d * cosA, y1 + d * sinA))
+ d = self.armA
+ rounded.append((x1 + d * cosA, y1 + d * sinA))
+
+ if self.armB:
+ cosB = math.cos(math.radians(self.angleB))
+ sinB = math.sin(math.radians(self.angleB))
+ x_armB, y_armB = x2 + self.armB * cosB, y2 + self.armB * sinB
+
+ if rounded:
+ xp, yp = rounded[-1]
+ dx, dy = x_armB - xp, y_armB - yp
+ dd = (dx * dx + dy * dy) ** .5
+
+ rounded.append((xp + self.rad * dx / dd,
+ yp + self.rad * dy / dd))
+ vertices.extend(rounded)
+ codes.extend([Path.LINETO,
+ Path.CURVE3,
+ Path.CURVE3])
+ else:
+ xp, yp = vertices[-1]
+ dx, dy = x_armB - xp, y_armB - yp
+ dd = (dx * dx + dy * dy) ** .5
+
+ d = dd - self.rad
+ rounded = [(xp + d * dx / dd, yp + d * dy / dd),
+ (x_armB, y_armB)]
+
+ if rounded:
+ xp, yp = rounded[-1]
+ dx, dy = x2 - xp, y2 - yp
+ dd = (dx * dx + dy * dy) ** .5
+
+ rounded.append((xp + self.rad * dx / dd,
+ yp + self.rad * dy / dd))
+ vertices.extend(rounded)
+ codes.extend([Path.LINETO,
+ Path.CURVE3,
+ Path.CURVE3])
+
+ vertices.append((x2, y2))
+ codes.append(Path.LINETO)
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Bar(_Base):
+ """
+ A line with *angle* between A and B with *armA* and *armB*. One of the
+ arms is extended so that they are connected in a right angle. The
+ length of *armA* is determined by (*armA* + *fraction* x AB distance).
+ Same for *armB*.
+ """
+
+ def __init__(self, armA=0., armB=0., fraction=0.3, angle=None):
+ """
+ Parameters
+ ----------
+ armA : float
+ Minimum length of armA.
+
+ armB : float
+ Minimum length of armB.
+
+ fraction : float
+ A fraction of the distance between two points that will be
+ added to armA and armB.
+
+ angle : float or None
+ Angle of the connecting line (if None, parallel to A and B).
+ """
+ self.armA = armA
+ self.armB = armB
+ self.fraction = fraction
+ self.angle = angle
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x20, y20 = x2, y2 = posB
+
+ theta1 = math.atan2(y2 - y1, x2 - x1)
+ dx, dy = x2 - x1, y2 - y1
+ dd = (dx * dx + dy * dy) ** .5
+ ddx, ddy = dx / dd, dy / dd
+
+ armA, armB = self.armA, self.armB
+
+ if self.angle is not None:
+ theta0 = np.deg2rad(self.angle)
+ dtheta = theta1 - theta0
+ dl = dd * math.sin(dtheta)
+ dL = dd * math.cos(dtheta)
+ x2, y2 = x1 + dL * math.cos(theta0), y1 + dL * math.sin(theta0)
+ armB = armB - dl
+
+ # update
+ dx, dy = x2 - x1, y2 - y1
+ dd2 = (dx * dx + dy * dy) ** .5
+ ddx, ddy = dx / dd2, dy / dd2
+
+ arm = max(armA, armB)
+ f = self.fraction * dd + arm
+
+ cx1, cy1 = x1 + f * ddy, y1 - f * ddx
+ cx2, cy2 = x2 + f * ddy, y2 - f * ddx
+
+ vertices = [(x1, y1),
+ (cx1, cy1),
+ (cx2, cy2),
+ (x20, y20)]
+ codes = [Path.MOVETO,
+ Path.LINETO,
+ Path.LINETO,
+ Path.LINETO]
+
+ return Path(vertices, codes)
+
+
+def _point_along_a_line(x0, y0, x1, y1, d):
+ """
+ Return the point on the line connecting (*x0*, *y0*) -- (*x1*, *y1*) whose
+ distance from (*x0*, *y0*) is *d*.
+ """
+ dx, dy = x0 - x1, y0 - y1
+ ff = d / (dx * dx + dy * dy) ** .5
+ x2, y2 = x0 - ff * dx, y0 - ff * dy
+
+ return x2, y2
+
+
+@_docstring.interpd
+class ArrowStyle(_Style):
+ """
+ `ArrowStyle` is a container class which defines several
+ arrowstyle classes, which is used to create an arrow path along a
+ given path. These are mainly used with `FancyArrowPatch`.
+
+ An arrowstyle object can be either created as::
+
+ ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4)
+
+ or::
+
+ ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4)
+
+ or::
+
+ ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4")
+
+ The following classes are defined
+
+ %(ArrowStyle:table)s
+
+ For an overview of the visual appearance, see
+ :doc:`/gallery/text_labels_and_annotations/fancyarrow_demo`.
+
+ An instance of any arrow style class is a callable object,
+ whose call signature is::
+
+ __call__(self, path, mutation_size, linewidth, aspect_ratio=1.)
+
+ and it returns a tuple of a `.Path` instance and a boolean
+ value. *path* is a `.Path` instance along which the arrow
+ will be drawn. *mutation_size* and *aspect_ratio* have the same
+ meaning as in `BoxStyle`. *linewidth* is a line width to be
+ stroked. This is meant to be used to correct the location of the
+ head so that it does not overshoot the destination point, but not all
+ classes support it.
+
+ Notes
+ -----
+ *angleA* and *angleB* specify the orientation of the bracket, as either a
+ clockwise or counterclockwise angle depending on the arrow type. 0 degrees
+ means perpendicular to the line connecting the arrow's head and tail.
+
+ .. plot:: gallery/text_labels_and_annotations/angles_on_bracket_arrows.py
+ """
+
+ _style_list = {}
+
+ class _Base:
+ """
+ Arrow Transmuter Base class
+
+ ArrowTransmuterBase and its derivatives are used to make a fancy
+ arrow around a given path. The __call__ method returns a path
+ (which will be used to create a PathPatch instance) and a boolean
+ value indicating the path is open therefore is not fillable. This
+ class is not an artist and actual drawing of the fancy arrow is
+ done by the FancyArrowPatch class.
+ """
+
+ # The derived classes are required to be able to be initialized
+ # w/o arguments, i.e., all its argument (except self) must have
+ # the default values.
+
+ @staticmethod
+ def ensure_quadratic_bezier(path):
+ """
+ Some ArrowStyle classes only works with a simple quadratic
+ Bézier curve (created with `.ConnectionStyle.Arc3` or
+ `.ConnectionStyle.Angle3`). This static method checks if the
+ provided path is a simple quadratic Bézier curve and returns its
+ control points if true.
+ """
+ segments = list(path.iter_segments())
+ if (len(segments) != 2 or segments[0][1] != Path.MOVETO or
+ segments[1][1] != Path.CURVE3):
+ raise ValueError(
+ "'path' is not a valid quadratic Bezier curve")
+ return [*segments[0][0], *segments[1][0]]
+
+ def transmute(self, path, mutation_size, linewidth):
+ """
+ The transmute method is the very core of the ArrowStyle class and
+ must be overridden in the subclasses. It receives the *path*
+ object along which the arrow will be drawn, and the
+ *mutation_size*, with which the arrow head etc. will be scaled.
+ The *linewidth* may be used to adjust the path so that it does not
+ pass beyond the given points. It returns a tuple of a `.Path`
+ instance and a boolean. The boolean value indicate whether the
+ path can be filled or not. The return value can also be a list of
+ paths and list of booleans of the same length.
+ """
+ raise NotImplementedError('Derived must override')
+
+ def __call__(self, path, mutation_size, linewidth,
+ aspect_ratio=1.):
+ """
+ The __call__ method is a thin wrapper around the transmute method
+ and takes care of the aspect ratio.
+ """
+
+ if aspect_ratio is not None:
+ # Squeeze the given height by the aspect_ratio
+ vertices = path.vertices / [1, aspect_ratio]
+ path_shrunk = Path(vertices, path.codes)
+ # call transmute method with squeezed height.
+ path_mutated, fillable = self.transmute(path_shrunk,
+ mutation_size,
+ linewidth)
+ if np.iterable(fillable):
+ # Restore the height
+ path_list = [Path(p.vertices * [1, aspect_ratio], p.codes)
+ for p in path_mutated]
+ return path_list, fillable
+ else:
+ return path_mutated, fillable
+ else:
+ return self.transmute(path, mutation_size, linewidth)
+
+ class _Curve(_Base):
+ """
+ A simple arrow which will work with any path instance. The
+ returned path is the concatenation of the original path, and at
+ most two paths representing the arrow head or bracket at the start
+ point and at the end point. The arrow heads can be either open
+ or closed.
+ """
+
+ arrow = "-"
+ fillbegin = fillend = False # Whether arrows are filled.
+
+ def __init__(self, head_length=.4, head_width=.2, widthA=1., widthB=1.,
+ lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None,
+ scaleB=None):
+ """
+ Parameters
+ ----------
+ head_length : float, default: 0.4
+ Length of the arrow head, relative to *mutation_size*.
+ head_width : float, default: 0.2
+ Width of the arrow head, relative to *mutation_size*.
+ widthA, widthB : float, default: 1.0
+ Width of the bracket.
+ lengthA, lengthB : float, default: 0.2
+ Length of the bracket.
+ angleA, angleB : float, default: 0
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ scaleA, scaleB : float, default: *mutation_size*
+ The scale of the brackets.
+ """
+
+ self.head_length, self.head_width = head_length, head_width
+ self.widthA, self.widthB = widthA, widthB
+ self.lengthA, self.lengthB = lengthA, lengthB
+ self.angleA, self.angleB = angleA, angleB
+ self.scaleA, self.scaleB = scaleA, scaleB
+
+ self._beginarrow_head = False
+ self._beginarrow_bracket = False
+ self._endarrow_head = False
+ self._endarrow_bracket = False
+
+ if "-" not in self.arrow:
+ raise ValueError("arrow must have the '-' between "
+ "the two heads")
+
+ beginarrow, endarrow = self.arrow.split("-", 1)
+
+ if beginarrow == "<":
+ self._beginarrow_head = True
+ self._beginarrow_bracket = False
+ elif beginarrow == "<|":
+ self._beginarrow_head = True
+ self._beginarrow_bracket = False
+ self.fillbegin = True
+ elif beginarrow in ("]", "|"):
+ self._beginarrow_head = False
+ self._beginarrow_bracket = True
+
+ if endarrow == ">":
+ self._endarrow_head = True
+ self._endarrow_bracket = False
+ elif endarrow == "|>":
+ self._endarrow_head = True
+ self._endarrow_bracket = False
+ self.fillend = True
+ elif endarrow in ("[", "|"):
+ self._endarrow_head = False
+ self._endarrow_bracket = True
+
+ super().__init__()
+
+ def _get_arrow_wedge(self, x0, y0, x1, y1,
+ head_dist, cos_t, sin_t, linewidth):
+ """
+ Return the paths for arrow heads. Since arrow lines are
+ drawn with capstyle=projected, The arrow goes beyond the
+ desired point. This method also returns the amount of the path
+ to be shrunken so that it does not overshoot.
+ """
+
+ # arrow from x0, y0 to x1, y1
+ dx, dy = x0 - x1, y0 - y1
+
+ cp_distance = np.hypot(dx, dy)
+
+ # pad_projected : amount of pad to account the
+ # overshooting of the projection of the wedge
+ pad_projected = (.5 * linewidth / sin_t)
+
+ # Account for division by zero
+ if cp_distance == 0:
+ cp_distance = 1
+
+ # apply pad for projected edge
+ ddx = pad_projected * dx / cp_distance
+ ddy = pad_projected * dy / cp_distance
+
+ # offset for arrow wedge
+ dx = dx / cp_distance * head_dist
+ dy = dy / cp_distance * head_dist
+
+ dx1, dy1 = cos_t * dx + sin_t * dy, -sin_t * dx + cos_t * dy
+ dx2, dy2 = cos_t * dx - sin_t * dy, sin_t * dx + cos_t * dy
+
+ vertices_arrow = [(x1 + ddx + dx1, y1 + ddy + dy1),
+ (x1 + ddx, y1 + ddy),
+ (x1 + ddx + dx2, y1 + ddy + dy2)]
+ codes_arrow = [Path.MOVETO,
+ Path.LINETO,
+ Path.LINETO]
+
+ return vertices_arrow, codes_arrow, ddx, ddy
+
+ def _get_bracket(self, x0, y0,
+ x1, y1, width, length, angle):
+
+ cos_t, sin_t = get_cos_sin(x1, y1, x0, y0)
+
+ # arrow from x0, y0 to x1, y1
+ from matplotlib.bezier import get_normal_points
+ x1, y1, x2, y2 = get_normal_points(x0, y0, cos_t, sin_t, width)
+
+ dx, dy = length * cos_t, length * sin_t
+
+ vertices_arrow = [(x1 + dx, y1 + dy),
+ (x1, y1),
+ (x2, y2),
+ (x2 + dx, y2 + dy)]
+ codes_arrow = [Path.MOVETO,
+ Path.LINETO,
+ Path.LINETO,
+ Path.LINETO]
+
+ if angle:
+ trans = transforms.Affine2D().rotate_deg_around(x0, y0, angle)
+ vertices_arrow = trans.transform(vertices_arrow)
+
+ return vertices_arrow, codes_arrow
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ if self._beginarrow_head or self._endarrow_head:
+ head_length = self.head_length * mutation_size
+ head_width = self.head_width * mutation_size
+ head_dist = np.hypot(head_length, head_width)
+ cos_t, sin_t = head_length / head_dist, head_width / head_dist
+
+ scaleA = mutation_size if self.scaleA is None else self.scaleA
+ scaleB = mutation_size if self.scaleB is None else self.scaleB
+
+ # begin arrow
+ x0, y0 = path.vertices[0]
+ x1, y1 = path.vertices[1]
+
+ # If there is no room for an arrow and a line, then skip the arrow
+ has_begin_arrow = self._beginarrow_head and (x0, y0) != (x1, y1)
+ verticesA, codesA, ddxA, ddyA = (
+ self._get_arrow_wedge(x1, y1, x0, y0,
+ head_dist, cos_t, sin_t, linewidth)
+ if has_begin_arrow
+ else ([], [], 0, 0)
+ )
+
+ # end arrow
+ x2, y2 = path.vertices[-2]
+ x3, y3 = path.vertices[-1]
+
+ # If there is no room for an arrow and a line, then skip the arrow
+ has_end_arrow = self._endarrow_head and (x2, y2) != (x3, y3)
+ verticesB, codesB, ddxB, ddyB = (
+ self._get_arrow_wedge(x2, y2, x3, y3,
+ head_dist, cos_t, sin_t, linewidth)
+ if has_end_arrow
+ else ([], [], 0, 0)
+ )
+
+ # This simple code will not work if ddx, ddy is greater than the
+ # separation between vertices.
+ paths = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)],
+ path.vertices[1:-1],
+ [(x3 + ddxB, y3 + ddyB)]]),
+ path.codes)]
+ fills = [False]
+
+ if has_begin_arrow:
+ if self.fillbegin:
+ paths.append(
+ Path([*verticesA, (0, 0)], [*codesA, Path.CLOSEPOLY]))
+ fills.append(True)
+ else:
+ paths.append(Path(verticesA, codesA))
+ fills.append(False)
+ elif self._beginarrow_bracket:
+ x0, y0 = path.vertices[0]
+ x1, y1 = path.vertices[1]
+ verticesA, codesA = self._get_bracket(x0, y0, x1, y1,
+ self.widthA * scaleA,
+ self.lengthA * scaleA,
+ self.angleA)
+
+ paths.append(Path(verticesA, codesA))
+ fills.append(False)
+
+ if has_end_arrow:
+ if self.fillend:
+ fills.append(True)
+ paths.append(
+ Path([*verticesB, (0, 0)], [*codesB, Path.CLOSEPOLY]))
+ else:
+ fills.append(False)
+ paths.append(Path(verticesB, codesB))
+ elif self._endarrow_bracket:
+ x0, y0 = path.vertices[-1]
+ x1, y1 = path.vertices[-2]
+ verticesB, codesB = self._get_bracket(x0, y0, x1, y1,
+ self.widthB * scaleB,
+ self.lengthB * scaleB,
+ self.angleB)
+
+ paths.append(Path(verticesB, codesB))
+ fills.append(False)
+
+ return paths, fills
+
+ @_register_style(_style_list, name="-")
+ class Curve(_Curve):
+ """A simple curve without any arrow head."""
+
+ def __init__(self): # hide head_length, head_width
+ # These attributes (whose values come from backcompat) only matter
+ # if someone modifies beginarrow/etc. on an ArrowStyle instance.
+ super().__init__(head_length=.2, head_width=.1)
+
+ @_register_style(_style_list, name="<-")
+ class CurveA(_Curve):
+ """An arrow with a head at its start point."""
+ arrow = "<-"
+
+ @_register_style(_style_list, name="->")
+ class CurveB(_Curve):
+ """An arrow with a head at its end point."""
+ arrow = "->"
+
+ @_register_style(_style_list, name="<->")
+ class CurveAB(_Curve):
+ """An arrow with heads both at the start and the end point."""
+ arrow = "<->"
+
+ @_register_style(_style_list, name="<|-")
+ class CurveFilledA(_Curve):
+ """An arrow with filled triangle head at the start."""
+ arrow = "<|-"
+
+ @_register_style(_style_list, name="-|>")
+ class CurveFilledB(_Curve):
+ """An arrow with filled triangle head at the end."""
+ arrow = "-|>"
+
+ @_register_style(_style_list, name="<|-|>")
+ class CurveFilledAB(_Curve):
+ """An arrow with filled triangle heads at both ends."""
+ arrow = "<|-|>"
+
+ @_register_style(_style_list, name="]-")
+ class BracketA(_Curve):
+ """An arrow with an outward square bracket at its start."""
+ arrow = "]-"
+
+ def __init__(self, widthA=1., lengthA=0.2, angleA=0):
+ """
+ Parameters
+ ----------
+ widthA : float, default: 1.0
+ Width of the bracket.
+ lengthA : float, default: 0.2
+ Length of the bracket.
+ angleA : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA)
+
+ @_register_style(_style_list, name="-[")
+ class BracketB(_Curve):
+ """An arrow with an outward square bracket at its end."""
+ arrow = "-["
+
+ def __init__(self, widthB=1., lengthB=0.2, angleB=0):
+ """
+ Parameters
+ ----------
+ widthB : float, default: 1.0
+ Width of the bracket.
+ lengthB : float, default: 0.2
+ Length of the bracket.
+ angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthB=widthB, lengthB=lengthB, angleB=angleB)
+
+ @_register_style(_style_list, name="]-[")
+ class BracketAB(_Curve):
+ """An arrow with outward square brackets at both ends."""
+ arrow = "]-["
+
+ def __init__(self,
+ widthA=1., lengthA=0.2, angleA=0,
+ widthB=1., lengthB=0.2, angleB=0):
+ """
+ Parameters
+ ----------
+ widthA, widthB : float, default: 1.0
+ Width of the bracket.
+ lengthA, lengthB : float, default: 0.2
+ Length of the bracket.
+ angleA, angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA,
+ widthB=widthB, lengthB=lengthB, angleB=angleB)
+
+ @_register_style(_style_list, name="|-|")
+ class BarAB(_Curve):
+ """An arrow with vertical bars ``|`` at both ends."""
+ arrow = "|-|"
+
+ def __init__(self, widthA=1., angleA=0, widthB=1., angleB=0):
+ """
+ Parameters
+ ----------
+ widthA, widthB : float, default: 1.0
+ Width of the bracket.
+ angleA, angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=0, angleA=angleA,
+ widthB=widthB, lengthB=0, angleB=angleB)
+
+ @_register_style(_style_list, name=']->')
+ class BracketCurve(_Curve):
+ """
+ An arrow with an outward square bracket at its start and a head at
+ the end.
+ """
+ arrow = "]->"
+
+ def __init__(self, widthA=1., lengthA=0.2, angleA=None):
+ """
+ Parameters
+ ----------
+ widthA : float, default: 1.0
+ Width of the bracket.
+ lengthA : float, default: 0.2
+ Length of the bracket.
+ angleA : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA)
+
+ @_register_style(_style_list, name='<-[')
+ class CurveBracket(_Curve):
+ """
+ An arrow with an outward square bracket at its end and a head at
+ the start.
+ """
+ arrow = "<-["
+
+ def __init__(self, widthB=1., lengthB=0.2, angleB=None):
+ """
+ Parameters
+ ----------
+ widthB : float, default: 1.0
+ Width of the bracket.
+ lengthB : float, default: 0.2
+ Length of the bracket.
+ angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthB=widthB, lengthB=lengthB, angleB=angleB)
+
+ @_register_style(_style_list)
+ class Simple(_Base):
+ """A simple arrow. Only works with a quadratic Bézier curve."""
+
+ def __init__(self, head_length=.5, head_width=.5, tail_width=.2):
+ """
+ Parameters
+ ----------
+ head_length : float, default: 0.5
+ Length of the arrow head.
+
+ head_width : float, default: 0.5
+ Width of the arrow head.
+
+ tail_width : float, default: 0.2
+ Width of the arrow tail.
+ """
+ self.head_length, self.head_width, self.tail_width = \
+ head_length, head_width, tail_width
+ super().__init__()
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
+
+ # divide the path into a head and a tail
+ head_length = self.head_length * mutation_size
+ in_f = inside_circle(x2, y2, head_length)
+ arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
+
+ try:
+ arrow_out, arrow_in = \
+ split_bezier_intersecting_with_closedpath(arrow_path, in_f)
+ except NonIntersectingPathException:
+ # if this happens, make a straight line of the head_length
+ # long.
+ x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
+ x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
+ arrow_in = [(x0, y0), (x1n, y1n), (x2, y2)]
+ arrow_out = None
+
+ # head
+ head_width = self.head_width * mutation_size
+ head_left, head_right = make_wedged_bezier2(arrow_in,
+ head_width / 2., wm=.5)
+
+ # tail
+ if arrow_out is not None:
+ tail_width = self.tail_width * mutation_size
+ tail_left, tail_right = get_parallels(arrow_out,
+ tail_width / 2.)
+
+ patch_path = [(Path.MOVETO, tail_right[0]),
+ (Path.CURVE3, tail_right[1]),
+ (Path.CURVE3, tail_right[2]),
+ (Path.LINETO, head_right[0]),
+ (Path.CURVE3, head_right[1]),
+ (Path.CURVE3, head_right[2]),
+ (Path.CURVE3, head_left[1]),
+ (Path.CURVE3, head_left[0]),
+ (Path.LINETO, tail_left[2]),
+ (Path.CURVE3, tail_left[1]),
+ (Path.CURVE3, tail_left[0]),
+ (Path.LINETO, tail_right[0]),
+ (Path.CLOSEPOLY, tail_right[0]),
+ ]
+ else:
+ patch_path = [(Path.MOVETO, head_right[0]),
+ (Path.CURVE3, head_right[1]),
+ (Path.CURVE3, head_right[2]),
+ (Path.CURVE3, head_left[1]),
+ (Path.CURVE3, head_left[0]),
+ (Path.CLOSEPOLY, head_left[0]),
+ ]
+
+ path = Path([p for c, p in patch_path], [c for c, p in patch_path])
+
+ return path, True
+
+ @_register_style(_style_list)
+ class Fancy(_Base):
+ """A fancy arrow. Only works with a quadratic Bézier curve."""
+
+ def __init__(self, head_length=.4, head_width=.4, tail_width=.4):
+ """
+ Parameters
+ ----------
+ head_length : float, default: 0.4
+ Length of the arrow head.
+
+ head_width : float, default: 0.4
+ Width of the arrow head.
+
+ tail_width : float, default: 0.4
+ Width of the arrow tail.
+ """
+ self.head_length, self.head_width, self.tail_width = \
+ head_length, head_width, tail_width
+ super().__init__()
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
+
+ # divide the path into a head and a tail
+ head_length = self.head_length * mutation_size
+ arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
+
+ # path for head
+ in_f = inside_circle(x2, y2, head_length)
+ try:
+ path_out, path_in = split_bezier_intersecting_with_closedpath(
+ arrow_path, in_f)
+ except NonIntersectingPathException:
+ # if this happens, make a straight line of the head_length
+ # long.
+ x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
+ x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
+ arrow_path = [(x0, y0), (x1n, y1n), (x2, y2)]
+ path_head = arrow_path
+ else:
+ path_head = path_in
+
+ # path for head
+ in_f = inside_circle(x2, y2, head_length * .8)
+ path_out, path_in = split_bezier_intersecting_with_closedpath(
+ arrow_path, in_f)
+ path_tail = path_out
+
+ # head
+ head_width = self.head_width * mutation_size
+ head_l, head_r = make_wedged_bezier2(path_head,
+ head_width / 2.,
+ wm=.6)
+
+ # tail
+ tail_width = self.tail_width * mutation_size
+ tail_left, tail_right = make_wedged_bezier2(path_tail,
+ tail_width * .5,
+ w1=1., wm=0.6, w2=0.3)
+
+ # path for head
+ in_f = inside_circle(x0, y0, tail_width * .3)
+ path_in, path_out = split_bezier_intersecting_with_closedpath(
+ arrow_path, in_f)
+ tail_start = path_in[-1]
+
+ head_right, head_left = head_r, head_l
+ patch_path = [(Path.MOVETO, tail_start),
+ (Path.LINETO, tail_right[0]),
+ (Path.CURVE3, tail_right[1]),
+ (Path.CURVE3, tail_right[2]),
+ (Path.LINETO, head_right[0]),
+ (Path.CURVE3, head_right[1]),
+ (Path.CURVE3, head_right[2]),
+ (Path.CURVE3, head_left[1]),
+ (Path.CURVE3, head_left[0]),
+ (Path.LINETO, tail_left[2]),
+ (Path.CURVE3, tail_left[1]),
+ (Path.CURVE3, tail_left[0]),
+ (Path.LINETO, tail_start),
+ (Path.CLOSEPOLY, tail_start),
+ ]
+ path = Path([p for c, p in patch_path], [c for c, p in patch_path])
+
+ return path, True
+
+ @_register_style(_style_list)
+ class Wedge(_Base):
+ """
+ Wedge(?) shape. Only works with a quadratic Bézier curve. The
+ start point has a width of the *tail_width* and the end point has a
+ width of 0. At the middle, the width is *shrink_factor*x*tail_width*.
+ """
+
+ def __init__(self, tail_width=.3, shrink_factor=0.5):
+ """
+ Parameters
+ ----------
+ tail_width : float, default: 0.3
+ Width of the tail.
+
+ shrink_factor : float, default: 0.5
+ Fraction of the arrow width at the middle point.
+ """
+ self.tail_width = tail_width
+ self.shrink_factor = shrink_factor
+ super().__init__()
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
+
+ arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
+ b_plus, b_minus = make_wedged_bezier2(
+ arrow_path,
+ self.tail_width * mutation_size / 2.,
+ wm=self.shrink_factor)
+
+ patch_path = [(Path.MOVETO, b_plus[0]),
+ (Path.CURVE3, b_plus[1]),
+ (Path.CURVE3, b_plus[2]),
+ (Path.LINETO, b_minus[2]),
+ (Path.CURVE3, b_minus[1]),
+ (Path.CURVE3, b_minus[0]),
+ (Path.CLOSEPOLY, b_minus[0]),
+ ]
+ path = Path([p for c, p in patch_path], [c for c, p in patch_path])
+
+ return path, True
+
+
+class FancyBboxPatch(Patch):
+ """
+ A fancy box around a rectangle with lower left at *xy* = (*x*, *y*)
+ with specified width and height.
+
+ `.FancyBboxPatch` is similar to `.Rectangle`, but it draws a fancy box
+ around the rectangle. The transformation of the rectangle box to the
+ fancy box is delegated to the style classes defined in `.BoxStyle`.
+ """
+
+ _edge_default = True
+
+ def __str__(self):
+ s = self.__class__.__name__ + "((%g, %g), width=%g, height=%g)"
+ return s % (self._x, self._y, self._width, self._height)
+
+ @_docstring.interpd
+ def __init__(self, xy, width, height, boxstyle="round", *,
+ mutation_scale=1, mutation_aspect=1, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The lower left corner of the box.
+
+ width : float
+ The width of the box.
+
+ height : float
+ The height of the box.
+
+ boxstyle : str or `~matplotlib.patches.BoxStyle`
+ The style of the fancy box. This can either be a `.BoxStyle`
+ instance or a string of the style name and optionally comma
+ separated attributes (e.g. "Round, pad=0.2"). This string is
+ passed to `.BoxStyle` to construct a `.BoxStyle` object. See
+ there for a full documentation.
+
+ The following box styles are available:
+
+ %(BoxStyle:table)s
+
+ mutation_scale : float, default: 1
+ Scaling factor applied to the attributes of the box style
+ (e.g. pad or rounding_size).
+
+ mutation_aspect : float, default: 1
+ The height of the rectangle will be squeezed by this value before
+ the mutation and the mutated box will be stretched by the inverse
+ of it. For example, this allows different horizontal and vertical
+ padding.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties
+
+ %(Patch:kwdoc)s
+ """
+
+ super().__init__(**kwargs)
+ self._x, self._y = xy
+ self._width = width
+ self._height = height
+ self.set_boxstyle(boxstyle)
+ self._mutation_scale = mutation_scale
+ self._mutation_aspect = mutation_aspect
+ self.stale = True
+
+ @_docstring.interpd
+ def set_boxstyle(self, boxstyle=None, **kwargs):
+ """
+ Set the box style, possibly with further attributes.
+
+ Attributes from the previous box style are not reused.
+
+ Without argument (or with ``boxstyle=None``), the available box styles
+ are returned as a human-readable string.
+
+ Parameters
+ ----------
+ boxstyle : str or `~matplotlib.patches.BoxStyle`
+ The style of the box: either a `.BoxStyle` instance, or a string,
+ which is the style name and optionally comma separated attributes
+ (e.g. "Round,pad=0.2"). Such a string is used to construct a
+ `.BoxStyle` object, as documented in that class.
+
+ The following box styles are available:
+
+ %(BoxStyle:table_and_accepts)s
+
+ **kwargs
+ Additional attributes for the box style. See the table above for
+ supported parameters.
+
+ Examples
+ --------
+ ::
+
+ set_boxstyle("Round,pad=0.2")
+ set_boxstyle("round", pad=0.2)
+ """
+ if boxstyle is None:
+ return BoxStyle.pprint_styles()
+ self._bbox_transmuter = (
+ BoxStyle(boxstyle, **kwargs)
+ if isinstance(boxstyle, str) else boxstyle)
+ self.stale = True
+
+ def get_boxstyle(self):
+ """Return the boxstyle object."""
+ return self._bbox_transmuter
+
+ def set_mutation_scale(self, scale):
+ """
+ Set the mutation scale.
+
+ Parameters
+ ----------
+ scale : float
+ """
+ self._mutation_scale = scale
+ self.stale = True
+
+ def get_mutation_scale(self):
+ """Return the mutation scale."""
+ return self._mutation_scale
+
+ def set_mutation_aspect(self, aspect):
+ """
+ Set the aspect ratio of the bbox mutation.
+
+ Parameters
+ ----------
+ aspect : float
+ """
+ self._mutation_aspect = aspect
+ self.stale = True
+
+ def get_mutation_aspect(self):
+ """Return the aspect ratio of the bbox mutation."""
+ return (self._mutation_aspect if self._mutation_aspect is not None
+ else 1) # backcompat.
+
+ def get_path(self):
+ """Return the mutated path of the rectangle."""
+ boxstyle = self.get_boxstyle()
+ m_aspect = self.get_mutation_aspect()
+ # Call boxstyle with y, height squeezed by aspect_ratio.
+ path = boxstyle(self._x, self._y / m_aspect,
+ self._width, self._height / m_aspect,
+ self.get_mutation_scale())
+ return Path(path.vertices * [1, m_aspect], path.codes) # Unsqueeze y.
+
+ # Following methods are borrowed from the Rectangle class.
+
+ def get_x(self):
+ """Return the left coord of the rectangle."""
+ return self._x
+
+ def get_y(self):
+ """Return the bottom coord of the rectangle."""
+ return self._y
+
+ def get_width(self):
+ """Return the width of the rectangle."""
+ return self._width
+
+ def get_height(self):
+ """Return the height of the rectangle."""
+ return self._height
+
+ def set_x(self, x):
+ """
+ Set the left coord of the rectangle.
+
+ Parameters
+ ----------
+ x : float
+ """
+ self._x = x
+ self.stale = True
+
+ def set_y(self, y):
+ """
+ Set the bottom coord of the rectangle.
+
+ Parameters
+ ----------
+ y : float
+ """
+ self._y = y
+ self.stale = True
+
+ def set_width(self, w):
+ """
+ Set the rectangle width.
+
+ Parameters
+ ----------
+ w : float
+ """
+ self._width = w
+ self.stale = True
+
+ def set_height(self, h):
+ """
+ Set the rectangle height.
+
+ Parameters
+ ----------
+ h : float
+ """
+ self._height = h
+ self.stale = True
+
+ def set_bounds(self, *args):
+ """
+ Set the bounds of the rectangle.
+
+ Call signatures::
+
+ set_bounds(left, bottom, width, height)
+ set_bounds((left, bottom, width, height))
+
+ Parameters
+ ----------
+ left, bottom : float
+ The coordinates of the bottom left corner of the rectangle.
+ width, height : float
+ The width/height of the rectangle.
+ """
+ if len(args) == 1:
+ l, b, w, h = args[0]
+ else:
+ l, b, w, h = args
+ self._x = l
+ self._y = b
+ self._width = w
+ self._height = h
+ self.stale = True
+
+ def get_bbox(self):
+ """Return the `.Bbox`."""
+ return transforms.Bbox.from_bounds(self._x, self._y,
+ self._width, self._height)
+
+
+class FancyArrowPatch(Patch):
+ """
+ A fancy arrow patch.
+
+ It draws an arrow using the `ArrowStyle`. It is primarily used by the
+ `~.axes.Axes.annotate` method. For most purposes, use the annotate method for
+ drawing arrows.
+
+ The head and tail positions are fixed at the specified start and end points
+ of the arrow, but the size and shape (in display coordinates) of the arrow
+ does not change when the axis is moved or zoomed.
+ """
+ _edge_default = True
+
+ def __str__(self):
+ if self._posA_posB is not None:
+ (x1, y1), (x2, y2) = self._posA_posB
+ return f"{type(self).__name__}(({x1:g}, {y1:g})->({x2:g}, {y2:g}))"
+ else:
+ return f"{type(self).__name__}({self._path_original})"
+
+ @_docstring.interpd
+ def __init__(self, posA=None, posB=None, *,
+ path=None, arrowstyle="simple", connectionstyle="arc3",
+ patchA=None, patchB=None, shrinkA=2, shrinkB=2,
+ mutation_scale=1, mutation_aspect=1, **kwargs):
+ """
+ There are two ways for defining an arrow:
+
+ - If *posA* and *posB* are given, a path connecting two points is
+ created according to *connectionstyle*. The path will be
+ clipped with *patchA* and *patchB* and further shrunken by
+ *shrinkA* and *shrinkB*. An arrow is drawn along this
+ resulting path using the *arrowstyle* parameter.
+
+ - Alternatively if *path* is provided, an arrow is drawn along this
+ path and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored.
+
+ Parameters
+ ----------
+ posA, posB : (float, float), default: None
+ (x, y) coordinates of arrow tail and arrow head respectively.
+
+ path : `~matplotlib.path.Path`, default: None
+ If provided, an arrow is drawn along this path and *patchA*,
+ *patchB*, *shrinkA*, and *shrinkB* are ignored.
+
+ arrowstyle : str or `.ArrowStyle`, default: 'simple'
+ The `.ArrowStyle` with which the fancy arrow is drawn. If a
+ string, it should be one of the available arrowstyle names, with
+ optional comma-separated attributes. The optional attributes are
+ meant to be scaled with the *mutation_scale*. The following arrow
+ styles are available:
+
+ %(ArrowStyle:table)s
+
+ connectionstyle : str or `.ConnectionStyle` or None, optional, \
+default: 'arc3'
+ The `.ConnectionStyle` with which *posA* and *posB* are connected.
+ If a string, it should be one of the available connectionstyle
+ names, with optional comma-separated attributes. The following
+ connection styles are available:
+
+ %(ConnectionStyle:table)s
+
+ patchA, patchB : `~matplotlib.patches.Patch`, default: None
+ Head and tail patches, respectively.
+
+ shrinkA, shrinkB : float, default: 2
+ Shrink amount, in points, of the tail and head of the arrow respectively.
+
+ mutation_scale : float, default: 1
+ Value with which attributes of *arrowstyle* (e.g., *head_length*)
+ will be scaled.
+
+ mutation_aspect : None or float, default: None
+ The height of the rectangle will be squeezed by this value before
+ the mutation and the mutated box will be stretched by the inverse
+ of it.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties, optional
+ Here is a list of available `.Patch` properties:
+
+ %(Patch:kwdoc)s
+
+ In contrast to other patches, the default ``capstyle`` and
+ ``joinstyle`` for `FancyArrowPatch` are set to ``"round"``.
+ """
+ # Traditionally, the cap- and joinstyle for FancyArrowPatch are round
+ kwargs.setdefault("joinstyle", JoinStyle.round)
+ kwargs.setdefault("capstyle", CapStyle.round)
+
+ super().__init__(**kwargs)
+
+ if posA is not None and posB is not None and path is None:
+ self._posA_posB = [posA, posB]
+
+ if connectionstyle is None:
+ connectionstyle = "arc3"
+ self.set_connectionstyle(connectionstyle)
+
+ elif posA is None and posB is None and path is not None:
+ self._posA_posB = None
+ else:
+ raise ValueError("Either posA and posB, or path need to provided")
+
+ self.patchA = patchA
+ self.patchB = patchB
+ self.shrinkA = shrinkA
+ self.shrinkB = shrinkB
+
+ self._path_original = path
+
+ self.set_arrowstyle(arrowstyle)
+
+ self._mutation_scale = mutation_scale
+ self._mutation_aspect = mutation_aspect
+
+ self._dpi_cor = 1.0
+
+ def set_positions(self, posA, posB):
+ """
+ Set the start and end positions of the connecting path.
+
+ Parameters
+ ----------
+ posA, posB : None, tuple
+ (x, y) coordinates of arrow tail and arrow head respectively. If
+ `None` use current value.
+ """
+ if posA is not None:
+ self._posA_posB[0] = posA
+ if posB is not None:
+ self._posA_posB[1] = posB
+ self.stale = True
+
+ def set_patchA(self, patchA):
+ """
+ Set the tail patch.
+
+ Parameters
+ ----------
+ patchA : `.patches.Patch`
+ """
+ self.patchA = patchA
+ self.stale = True
+
+ def set_patchB(self, patchB):
+ """
+ Set the head patch.
+
+ Parameters
+ ----------
+ patchB : `.patches.Patch`
+ """
+ self.patchB = patchB
+ self.stale = True
+
+ @_docstring.interpd
+ def set_connectionstyle(self, connectionstyle=None, **kwargs):
+ """
+ Set the connection style, possibly with further attributes.
+
+ Attributes from the previous connection style are not reused.
+
+ Without argument (or with ``connectionstyle=None``), the available box
+ styles are returned as a human-readable string.
+
+ Parameters
+ ----------
+ connectionstyle : str or `~matplotlib.patches.ConnectionStyle`
+ The style of the connection: either a `.ConnectionStyle` instance,
+ or a string, which is the style name and optionally comma separated
+ attributes (e.g. "Arc,armA=30,rad=10"). Such a string is used to
+ construct a `.ConnectionStyle` object, as documented in that class.
+
+ The following connection styles are available:
+
+ %(ConnectionStyle:table_and_accepts)s
+
+ **kwargs
+ Additional attributes for the connection style. See the table above
+ for supported parameters.
+
+ Examples
+ --------
+ ::
+
+ set_connectionstyle("Arc,armA=30,rad=10")
+ set_connectionstyle("arc", armA=30, rad=10)
+ """
+ if connectionstyle is None:
+ return ConnectionStyle.pprint_styles()
+ self._connector = (
+ ConnectionStyle(connectionstyle, **kwargs)
+ if isinstance(connectionstyle, str) else connectionstyle)
+ self.stale = True
+
+ def get_connectionstyle(self):
+ """Return the `ConnectionStyle` used."""
+ return self._connector
+
+ @_docstring.interpd
+ def set_arrowstyle(self, arrowstyle=None, **kwargs):
+ """
+ Set the arrow style, possibly with further attributes.
+
+ Attributes from the previous arrow style are not reused.
+
+ Without argument (or with ``arrowstyle=None``), the available box
+ styles are returned as a human-readable string.
+
+ Parameters
+ ----------
+ arrowstyle : str or `~matplotlib.patches.ArrowStyle`
+ The style of the arrow: either a `.ArrowStyle` instance, or a
+ string, which is the style name and optionally comma separated
+ attributes (e.g. "Fancy,head_length=0.2"). Such a string is used to
+ construct a `.ArrowStyle` object, as documented in that class.
+
+ The following arrow styles are available:
+
+ %(ArrowStyle:table_and_accepts)s
+
+ **kwargs
+ Additional attributes for the arrow style. See the table above for
+ supported parameters.
+
+ Examples
+ --------
+ ::
+
+ set_arrowstyle("Fancy,head_length=0.2")
+ set_arrowstyle("fancy", head_length=0.2)
+ """
+ if arrowstyle is None:
+ return ArrowStyle.pprint_styles()
+ self._arrow_transmuter = (
+ ArrowStyle(arrowstyle, **kwargs)
+ if isinstance(arrowstyle, str) else arrowstyle)
+ self.stale = True
+
+ def get_arrowstyle(self):
+ """Return the arrowstyle object."""
+ return self._arrow_transmuter
+
+ def set_mutation_scale(self, scale):
+ """
+ Set the mutation scale.
+
+ Parameters
+ ----------
+ scale : float
+ """
+ self._mutation_scale = scale
+ self.stale = True
+
+ def get_mutation_scale(self):
+ """
+ Return the mutation scale.
+
+ Returns
+ -------
+ scalar
+ """
+ return self._mutation_scale
+
+ def set_mutation_aspect(self, aspect):
+ """
+ Set the aspect ratio of the bbox mutation.
+
+ Parameters
+ ----------
+ aspect : float
+ """
+ self._mutation_aspect = aspect
+ self.stale = True
+
+ def get_mutation_aspect(self):
+ """Return the aspect ratio of the bbox mutation."""
+ return (self._mutation_aspect if self._mutation_aspect is not None
+ else 1) # backcompat.
+
+ def get_path(self):
+ """Return the path of the arrow in the data coordinates."""
+ # The path is generated in display coordinates, then converted back to
+ # data coordinates.
+ _path, fillable = self._get_path_in_displaycoord()
+ if np.iterable(fillable):
+ _path = Path.make_compound_path(*_path)
+ return self.get_transform().inverted().transform_path(_path)
+
+ def _get_path_in_displaycoord(self):
+ """Return the mutated path of the arrow in display coordinates."""
+ dpi_cor = self._dpi_cor
+
+ if self._posA_posB is not None:
+ posA = self._convert_xy_units(self._posA_posB[0])
+ posB = self._convert_xy_units(self._posA_posB[1])
+ (posA, posB) = self.get_transform().transform((posA, posB))
+ _path = self.get_connectionstyle()(posA, posB,
+ patchA=self.patchA,
+ patchB=self.patchB,
+ shrinkA=self.shrinkA * dpi_cor,
+ shrinkB=self.shrinkB * dpi_cor
+ )
+ else:
+ _path = self.get_transform().transform_path(self._path_original)
+
+ _path, fillable = self.get_arrowstyle()(
+ _path,
+ self.get_mutation_scale() * dpi_cor,
+ self.get_linewidth() * dpi_cor,
+ self.get_mutation_aspect())
+
+ return _path, fillable
+
+ def draw(self, renderer):
+ if not self.get_visible():
+ return
+
+ # FIXME: dpi_cor is for the dpi-dependency of the linewidth. There
+ # could be room for improvement. Maybe _get_path_in_displaycoord could
+ # take a renderer argument, but get_path should be adapted too.
+ self._dpi_cor = renderer.points_to_pixels(1.)
+ path, fillable = self._get_path_in_displaycoord()
+
+ if not np.iterable(fillable):
+ path = [path]
+ fillable = [fillable]
+
+ affine = transforms.IdentityTransform()
+
+ self._draw_paths_with_artist_properties(
+ renderer,
+ [(p, affine, self._facecolor if f and self._facecolor[3] else None)
+ for p, f in zip(path, fillable)])
+
+
+class ConnectionPatch(FancyArrowPatch):
+ """A patch that connects two points (possibly in different Axes)."""
+
+ def __str__(self):
+ return "ConnectionPatch((%g, %g), (%g, %g))" % \
+ (self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1])
+
+ @_docstring.interpd
+ def __init__(self, xyA, xyB, coordsA, coordsB=None, *,
+ axesA=None, axesB=None,
+ arrowstyle="-",
+ connectionstyle="arc3",
+ patchA=None,
+ patchB=None,
+ shrinkA=0.,
+ shrinkB=0.,
+ mutation_scale=10.,
+ mutation_aspect=None,
+ clip_on=False,
+ **kwargs):
+ """
+ Connect point *xyA* in *coordsA* with point *xyB* in *coordsB*.
+
+ Valid keys are
+
+ =============== ======================================================
+ Key Description
+ =============== ======================================================
+ arrowstyle the arrow style
+ connectionstyle the connection style
+ relpos default is (0.5, 0.5)
+ patchA default is bounding box of the text
+ patchB default is None
+ shrinkA default is 2 points
+ shrinkB default is 2 points
+ mutation_scale default is text size (in points)
+ mutation_aspect default is 1.
+ ? any key for `matplotlib.patches.PathPatch`
+ =============== ======================================================
+
+ *coordsA* and *coordsB* are strings that indicate the
+ coordinates of *xyA* and *xyB*.
+
+ ==================== ==================================================
+ Property Description
+ ==================== ==================================================
+ 'figure points' points from the lower left corner of the figure
+ 'figure pixels' pixels from the lower left corner of the figure
+ 'figure fraction' 0, 0 is lower left of figure and 1, 1 is upper
+ right
+ 'subfigure points' points from the lower left corner of the subfigure
+ 'subfigure pixels' pixels from the lower left corner of the subfigure
+ 'subfigure fraction' fraction of the subfigure, 0, 0 is lower left.
+ 'axes points' points from lower left corner of the Axes
+ 'axes pixels' pixels from lower left corner of the Axes
+ 'axes fraction' 0, 0 is lower left of Axes and 1, 1 is upper right
+ 'data' use the coordinate system of the object being
+ annotated (default)
+ 'offset points' offset (in points) from the *xy* value
+ 'polar' you can specify *theta*, *r* for the annotation,
+ even in cartesian plots. Note that if you are
+ using a polar Axes, you do not need to specify
+ polar for the coordinate system since that is the
+ native "data" coordinate system.
+ ==================== ==================================================
+
+ Alternatively they can be set to any valid
+ `~matplotlib.transforms.Transform`.
+
+ Note that 'subfigure pixels' and 'figure pixels' are the same
+ for the parent figure, so users who want code that is usable in
+ a subfigure can use 'subfigure pixels'.
+
+ .. note::
+
+ Using `ConnectionPatch` across two `~.axes.Axes` instances
+ is not directly compatible with :ref:`constrained layout
+ `. Add the artist
+ directly to the `.Figure` instead of adding it to a specific Axes,
+ or exclude it from the layout using ``con.set_in_layout(False)``.
+
+ .. code-block:: default
+
+ fig, ax = plt.subplots(1, 2, constrained_layout=True)
+ con = ConnectionPatch(..., axesA=ax[0], axesB=ax[1])
+ fig.add_artist(con)
+
+ """
+ if coordsB is None:
+ coordsB = coordsA
+ # we'll draw ourself after the artist we annotate by default
+ self.xy1 = xyA
+ self.xy2 = xyB
+ self.coords1 = coordsA
+ self.coords2 = coordsB
+
+ self.axesA = axesA
+ self.axesB = axesB
+
+ super().__init__(posA=(0, 0), posB=(1, 1),
+ arrowstyle=arrowstyle,
+ connectionstyle=connectionstyle,
+ patchA=patchA, patchB=patchB,
+ shrinkA=shrinkA, shrinkB=shrinkB,
+ mutation_scale=mutation_scale,
+ mutation_aspect=mutation_aspect,
+ clip_on=clip_on,
+ **kwargs)
+ # if True, draw annotation only if self.xy is inside the Axes
+ self._annotation_clip = None
+
+ def _get_xy(self, xy, s, axes=None):
+ """Calculate the pixel position of given point."""
+ s0 = s # For the error message, if needed.
+ if axes is None:
+ axes = self.axes
+
+ # preserve mixed type input (such as str, int)
+ x = np.array(xy[0])
+ y = np.array(xy[1])
+
+ fig = self.get_figure(root=False)
+ if s in ["figure points", "axes points"]:
+ x = x * fig.dpi / 72
+ y = y * fig.dpi / 72
+ s = s.replace("points", "pixels")
+ elif s == "figure fraction":
+ s = fig.transFigure
+ elif s == "subfigure fraction":
+ s = fig.transSubfigure
+ elif s == "axes fraction":
+ s = axes.transAxes
+
+ if s == 'data':
+ trans = axes.transData
+ x = cbook._to_unmasked_float_array(axes.xaxis.convert_units(x))
+ y = cbook._to_unmasked_float_array(axes.yaxis.convert_units(y))
+ return trans.transform((x, y))
+ elif s == 'offset points':
+ if self.xycoords == 'offset points': # prevent recursion
+ return self._get_xy(self.xy, 'data')
+ return (
+ self._get_xy(self.xy, self.xycoords) # converted data point
+ + xy * self.get_figure(root=True).dpi / 72) # converted offset
+ elif s == 'polar':
+ theta, r = x, y
+ x = r * np.cos(theta)
+ y = r * np.sin(theta)
+ trans = axes.transData
+ return trans.transform((x, y))
+ elif s == 'figure pixels':
+ # pixels from the lower left corner of the figure
+ bb = self.get_figure(root=False).figbbox
+ x = bb.x0 + x if x >= 0 else bb.x1 + x
+ y = bb.y0 + y if y >= 0 else bb.y1 + y
+ return x, y
+ elif s == 'subfigure pixels':
+ # pixels from the lower left corner of the figure
+ bb = self.get_figure(root=False).bbox
+ x = bb.x0 + x if x >= 0 else bb.x1 + x
+ y = bb.y0 + y if y >= 0 else bb.y1 + y
+ return x, y
+ elif s == 'axes pixels':
+ # pixels from the lower left corner of the Axes
+ bb = axes.bbox
+ x = bb.x0 + x if x >= 0 else bb.x1 + x
+ y = bb.y0 + y if y >= 0 else bb.y1 + y
+ return x, y
+ elif isinstance(s, transforms.Transform):
+ return s.transform(xy)
+ else:
+ raise ValueError(f"{s0} is not a valid coordinate transformation")
+
+ def set_annotation_clip(self, b):
+ """
+ Set the annotation's clipping behavior.
+
+ Parameters
+ ----------
+ b : bool or None
+ - True: The annotation will be clipped when ``self.xy`` is
+ outside the Axes.
+ - False: The annotation will always be drawn.
+ - None: The annotation will be clipped when ``self.xy`` is
+ outside the Axes and ``self.xycoords == "data"``.
+ """
+ self._annotation_clip = b
+ self.stale = True
+
+ def get_annotation_clip(self):
+ """
+ Return the clipping behavior.
+
+ See `.set_annotation_clip` for the meaning of the return value.
+ """
+ return self._annotation_clip
+
+ def _get_path_in_displaycoord(self):
+ """Return the mutated path of the arrow in display coordinates."""
+ dpi_cor = self._dpi_cor
+ posA = self._get_xy(self.xy1, self.coords1, self.axesA)
+ posB = self._get_xy(self.xy2, self.coords2, self.axesB)
+ path = self.get_connectionstyle()(
+ posA, posB,
+ patchA=self.patchA, patchB=self.patchB,
+ shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor,
+ )
+ path, fillable = self.get_arrowstyle()(
+ path,
+ self.get_mutation_scale() * dpi_cor,
+ self.get_linewidth() * dpi_cor,
+ self.get_mutation_aspect()
+ )
+ return path, fillable
+
+ def _check_xy(self, renderer):
+ """Check whether the annotation needs to be drawn."""
+
+ b = self.get_annotation_clip()
+
+ if b or (b is None and self.coords1 == "data"):
+ xy_pixel = self._get_xy(self.xy1, self.coords1, self.axesA)
+ if self.axesA is None:
+ axes = self.axes
+ else:
+ axes = self.axesA
+ if not axes.contains_point(xy_pixel):
+ return False
+
+ if b or (b is None and self.coords2 == "data"):
+ xy_pixel = self._get_xy(self.xy2, self.coords2, self.axesB)
+ if self.axesB is None:
+ axes = self.axes
+ else:
+ axes = self.axesB
+ if not axes.contains_point(xy_pixel):
+ return False
+
+ return True
+
+ def draw(self, renderer):
+ if not self.get_visible() or not self._check_xy(renderer):
+ return
+ super().draw(renderer)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/patheffects.py b/llava_video/lib/python3.10/site-packages/matplotlib/patheffects.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7a0138bd7507a18f96e445572c59fdd2cde0e7c
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/patheffects.py
@@ -0,0 +1,511 @@
+"""
+Defines classes for path effects. The path effects are supported in `.Text`,
+`.Line2D` and `.Patch`.
+
+.. seealso::
+ :ref:`patheffects_guide`
+"""
+
+from matplotlib.backend_bases import RendererBase
+from matplotlib import colors as mcolors
+from matplotlib import patches as mpatches
+from matplotlib import transforms as mtransforms
+from matplotlib.path import Path
+import numpy as np
+
+
+class AbstractPathEffect:
+ """
+ A base class for path effects.
+
+ Subclasses should override the ``draw_path`` method to add effect
+ functionality.
+ """
+
+ def __init__(self, offset=(0., 0.)):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (0, 0)
+ The (x, y) offset to apply to the path, measured in points.
+ """
+ self._offset = offset
+
+ def _offset_transform(self, renderer):
+ """Apply the offset to the given transform."""
+ return mtransforms.Affine2D().translate(
+ *map(renderer.points_to_pixels, self._offset))
+
+ def _update_gc(self, gc, new_gc_dict):
+ """
+ Update the given GraphicsContext with the given dict of properties.
+
+ The keys in the dictionary are used to identify the appropriate
+ ``set_`` method on the *gc*.
+ """
+ new_gc_dict = new_gc_dict.copy()
+
+ dashes = new_gc_dict.pop("dashes", None)
+ if dashes:
+ gc.set_dashes(**dashes)
+
+ for k, v in new_gc_dict.items():
+ set_method = getattr(gc, 'set_' + k, None)
+ if not callable(set_method):
+ raise AttributeError(f'Unknown property {k}')
+ set_method(v)
+ return gc
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace=None):
+ """
+ Derived should override this method. The arguments are the same
+ as :meth:`matplotlib.backend_bases.RendererBase.draw_path`
+ except the first argument is a renderer.
+ """
+ # Get the real renderer, not a PathEffectRenderer.
+ if isinstance(renderer, PathEffectRenderer):
+ renderer = renderer._renderer
+ return renderer.draw_path(gc, tpath, affine, rgbFace)
+
+
+class PathEffectRenderer(RendererBase):
+ """
+ Implements a Renderer which contains another renderer.
+
+ This proxy then intercepts draw calls, calling the appropriate
+ :class:`AbstractPathEffect` draw method.
+
+ .. note::
+ Not all methods have been overridden on this RendererBase subclass.
+ It may be necessary to add further methods to extend the PathEffects
+ capabilities further.
+ """
+
+ def __init__(self, path_effects, renderer):
+ """
+ Parameters
+ ----------
+ path_effects : iterable of :class:`AbstractPathEffect`
+ The path effects which this renderer represents.
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass
+
+ """
+ self._path_effects = path_effects
+ self._renderer = renderer
+
+ def copy_with_path_effect(self, path_effects):
+ return self.__class__(path_effects, self._renderer)
+
+ def __getattribute__(self, name):
+ if name in ['flipy', 'get_canvas_width_height', 'new_gc',
+ 'points_to_pixels', '_text2path', 'height', 'width']:
+ return getattr(self._renderer, name)
+ else:
+ return object.__getattribute__(self, name)
+
+ def draw_path(self, gc, tpath, affine, rgbFace=None):
+ for path_effect in self._path_effects:
+ path_effect.draw_path(self._renderer, gc, tpath, affine,
+ rgbFace)
+
+ def draw_markers(
+ self, gc, marker_path, marker_trans, path, *args, **kwargs):
+ # We do a little shimmy so that all markers are drawn for each path
+ # effect in turn. Essentially, we induce recursion (depth 1) which is
+ # terminated once we have just a single path effect to work with.
+ if len(self._path_effects) == 1:
+ # Call the base path effect function - this uses the unoptimised
+ # approach of calling "draw_path" multiple times.
+ return super().draw_markers(gc, marker_path, marker_trans, path,
+ *args, **kwargs)
+
+ for path_effect in self._path_effects:
+ renderer = self.copy_with_path_effect([path_effect])
+ # Recursively call this method, only next time we will only have
+ # one path effect.
+ renderer.draw_markers(gc, marker_path, marker_trans, path,
+ *args, **kwargs)
+
+ def draw_path_collection(self, gc, master_transform, paths, *args,
+ **kwargs):
+ # We do a little shimmy so that all paths are drawn for each path
+ # effect in turn. Essentially, we induce recursion (depth 1) which is
+ # terminated once we have just a single path effect to work with.
+ if len(self._path_effects) == 1:
+ # Call the base path effect function - this uses the unoptimised
+ # approach of calling "draw_path" multiple times.
+ return super().draw_path_collection(gc, master_transform, paths,
+ *args, **kwargs)
+
+ for path_effect in self._path_effects:
+ renderer = self.copy_with_path_effect([path_effect])
+ # Recursively call this method, only next time we will only have
+ # one path effect.
+ renderer.draw_path_collection(gc, master_transform, paths,
+ *args, **kwargs)
+
+ def open_group(self, s, gid=None):
+ return self._renderer.open_group(s, gid)
+
+ def close_group(self, s):
+ return self._renderer.close_group(s)
+
+
+class Normal(AbstractPathEffect):
+ """
+ The "identity" PathEffect.
+
+ The Normal PathEffect's sole purpose is to draw the original artist with
+ no special path effect.
+ """
+
+
+def _subclass_with_normal(effect_class):
+ """
+ Create a PathEffect class combining *effect_class* and a normal draw.
+ """
+
+ class withEffect(effect_class):
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ super().draw_path(renderer, gc, tpath, affine, rgbFace)
+ renderer.draw_path(gc, tpath, affine, rgbFace)
+
+ withEffect.__name__ = f"with{effect_class.__name__}"
+ withEffect.__qualname__ = f"with{effect_class.__name__}"
+ withEffect.__doc__ = f"""
+ A shortcut PathEffect for applying `.{effect_class.__name__}` and then
+ drawing the original Artist.
+
+ With this class you can use ::
+
+ artist.set_path_effects([patheffects.with{effect_class.__name__}()])
+
+ as a shortcut for ::
+
+ artist.set_path_effects([patheffects.{effect_class.__name__}(),
+ patheffects.Normal()])
+ """
+ # Docstring inheritance doesn't work for locally-defined subclasses.
+ withEffect.draw_path.__doc__ = effect_class.draw_path.__doc__
+ return withEffect
+
+
+class Stroke(AbstractPathEffect):
+ """A line based PathEffect which re-draws a stroke."""
+
+ def __init__(self, offset=(0, 0), **kwargs):
+ """
+ The path will be stroked with its gc updated with the given
+ keyword arguments, i.e., the keyword arguments should be valid
+ gc parameter values.
+ """
+ super().__init__(offset)
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """Draw the path with updated gc."""
+ gc0 = renderer.new_gc() # Don't modify gc, but a copy!
+ gc0.copy_properties(gc)
+ gc0 = self._update_gc(gc0, self._gc)
+ renderer.draw_path(
+ gc0, tpath, affine + self._offset_transform(renderer), rgbFace)
+ gc0.restore()
+
+
+withStroke = _subclass_with_normal(effect_class=Stroke)
+
+
+class SimplePatchShadow(AbstractPathEffect):
+ """A simple shadow via a filled patch."""
+
+ def __init__(self, offset=(2, -2),
+ shadow_rgbFace=None, alpha=None,
+ rho=0.3, **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (2, -2)
+ The (x, y) offset of the shadow in points.
+ shadow_rgbFace : :mpltype:`color`
+ The shadow color.
+ alpha : float, default: 0.3
+ The alpha transparency of the created shadow patch.
+ rho : float, default: 0.3
+ A scale factor to apply to the rgbFace color if *shadow_rgbFace*
+ is not specified.
+ **kwargs
+ Extra keywords are stored and passed through to
+ :meth:`AbstractPathEffect._update_gc`.
+
+ """
+ super().__init__(offset)
+
+ if shadow_rgbFace is None:
+ self._shadow_rgbFace = shadow_rgbFace
+ else:
+ self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)
+
+ if alpha is None:
+ alpha = 0.3
+
+ self._alpha = alpha
+ self._rho = rho
+
+ #: The dictionary of keywords to update the graphics collection with.
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """
+ Overrides the standard draw_path to add the shadow offset and
+ necessary color changes for the shadow.
+ """
+ gc0 = renderer.new_gc() # Don't modify gc, but a copy!
+ gc0.copy_properties(gc)
+
+ if self._shadow_rgbFace is None:
+ r, g, b = (rgbFace or (1., 1., 1.))[:3]
+ # Scale the colors by a factor to improve the shadow effect.
+ shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
+ else:
+ shadow_rgbFace = self._shadow_rgbFace
+
+ gc0.set_foreground("none")
+ gc0.set_alpha(self._alpha)
+ gc0.set_linewidth(0)
+
+ gc0 = self._update_gc(gc0, self._gc)
+ renderer.draw_path(
+ gc0, tpath, affine + self._offset_transform(renderer),
+ shadow_rgbFace)
+ gc0.restore()
+
+
+withSimplePatchShadow = _subclass_with_normal(effect_class=SimplePatchShadow)
+
+
+class SimpleLineShadow(AbstractPathEffect):
+ """A simple shadow via a line."""
+
+ def __init__(self, offset=(2, -2),
+ shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (2, -2)
+ The (x, y) offset to apply to the path, in points.
+ shadow_color : :mpltype:`color`, default: 'black'
+ The shadow color.
+ A value of ``None`` takes the original artist's color
+ with a scale factor of *rho*.
+ alpha : float, default: 0.3
+ The alpha transparency of the created shadow patch.
+ rho : float, default: 0.3
+ A scale factor to apply to the rgbFace color if *shadow_color*
+ is ``None``.
+ **kwargs
+ Extra keywords are stored and passed through to
+ :meth:`AbstractPathEffect._update_gc`.
+ """
+ super().__init__(offset)
+ if shadow_color is None:
+ self._shadow_color = shadow_color
+ else:
+ self._shadow_color = mcolors.to_rgba(shadow_color)
+ self._alpha = alpha
+ self._rho = rho
+ #: The dictionary of keywords to update the graphics collection with.
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """
+ Overrides the standard draw_path to add the shadow offset and
+ necessary color changes for the shadow.
+ """
+ gc0 = renderer.new_gc() # Don't modify gc, but a copy!
+ gc0.copy_properties(gc)
+
+ if self._shadow_color is None:
+ r, g, b = (gc0.get_foreground() or (1., 1., 1.))[:3]
+ # Scale the colors by a factor to improve the shadow effect.
+ shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
+ else:
+ shadow_rgbFace = self._shadow_color
+
+ gc0.set_foreground(shadow_rgbFace)
+ gc0.set_alpha(self._alpha)
+
+ gc0 = self._update_gc(gc0, self._gc)
+ renderer.draw_path(
+ gc0, tpath, affine + self._offset_transform(renderer))
+ gc0.restore()
+
+
+class PathPatchEffect(AbstractPathEffect):
+ """
+ Draws a `.PathPatch` instance whose Path comes from the original
+ PathEffect artist.
+ """
+
+ def __init__(self, offset=(0, 0), **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (0, 0)
+ The (x, y) offset to apply to the path, in points.
+ **kwargs
+ All keyword arguments are passed through to the
+ :class:`~matplotlib.patches.PathPatch` constructor. The
+ properties which cannot be overridden are "path", "clip_box"
+ "transform" and "clip_path".
+ """
+ super().__init__(offset=offset)
+ self.patch = mpatches.PathPatch([], **kwargs)
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ self.patch._path = tpath
+ self.patch.set_transform(affine + self._offset_transform(renderer))
+ self.patch.set_clip_box(gc.get_clip_rectangle())
+ clip_path = gc.get_clip_path()
+ if clip_path and self.patch.get_clip_path() is None:
+ self.patch.set_clip_path(*clip_path)
+ self.patch.draw(renderer)
+
+
+class TickedStroke(AbstractPathEffect):
+ """
+ A line-based PathEffect which draws a path with a ticked style.
+
+ This line style is frequently used to represent constraints in
+ optimization. The ticks may be used to indicate that one side
+ of the line is invalid or to represent a closed boundary of a
+ domain (i.e. a wall or the edge of a pipe).
+
+ The spacing, length, and angle of ticks can be controlled.
+
+ This line style is sometimes referred to as a hatched line.
+
+ See also the :doc:`/gallery/misc/tickedstroke_demo` example.
+ """
+
+ def __init__(self, offset=(0, 0),
+ spacing=10.0, angle=45.0, length=np.sqrt(2),
+ **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (0, 0)
+ The (x, y) offset to apply to the path, in points.
+ spacing : float, default: 10.0
+ The spacing between ticks in points.
+ angle : float, default: 45.0
+ The angle between the path and the tick in degrees. The angle
+ is measured as if you were an ant walking along the curve, with
+ zero degrees pointing directly ahead, 90 to your left, -90
+ to your right, and 180 behind you. To change side of the ticks,
+ change sign of the angle.
+ length : float, default: 1.414
+ The length of the tick relative to spacing.
+ Recommended length = 1.414 (sqrt(2)) when angle=45, length=1.0
+ when angle=90 and length=2.0 when angle=60.
+ **kwargs
+ Extra keywords are stored and passed through to
+ :meth:`AbstractPathEffect._update_gc`.
+
+ Examples
+ --------
+ See :doc:`/gallery/misc/tickedstroke_demo`.
+ """
+ super().__init__(offset)
+
+ self._spacing = spacing
+ self._angle = angle
+ self._length = length
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """Draw the path with updated gc."""
+ # Do not modify the input! Use copy instead.
+ gc0 = renderer.new_gc()
+ gc0.copy_properties(gc)
+
+ gc0 = self._update_gc(gc0, self._gc)
+ trans = affine + self._offset_transform(renderer)
+
+ theta = -np.radians(self._angle)
+ trans_matrix = np.array([[np.cos(theta), -np.sin(theta)],
+ [np.sin(theta), np.cos(theta)]])
+
+ # Convert spacing parameter to pixels.
+ spacing_px = renderer.points_to_pixels(self._spacing)
+
+ # Transform before evaluation because to_polygons works at resolution
+ # of one -- assuming it is working in pixel space.
+ transpath = affine.transform_path(tpath)
+
+ # Evaluate path to straight line segments that can be used to
+ # construct line ticks.
+ polys = transpath.to_polygons(closed_only=False)
+
+ for p in polys:
+ x = p[:, 0]
+ y = p[:, 1]
+
+ # Can not interpolate points or draw line if only one point in
+ # polyline.
+ if x.size < 2:
+ continue
+
+ # Find distance between points on the line
+ ds = np.hypot(x[1:] - x[:-1], y[1:] - y[:-1])
+
+ # Build parametric coordinate along curve
+ s = np.concatenate(([0.0], np.cumsum(ds)))
+ s_total = s[-1]
+
+ num = int(np.ceil(s_total / spacing_px)) - 1
+ # Pick parameter values for ticks.
+ s_tick = np.linspace(spacing_px/2, s_total - spacing_px/2, num)
+
+ # Find points along the parameterized curve
+ x_tick = np.interp(s_tick, s, x)
+ y_tick = np.interp(s_tick, s, y)
+
+ # Find unit vectors in local direction of curve
+ delta_s = self._spacing * .001
+ u = (np.interp(s_tick + delta_s, s, x) - x_tick) / delta_s
+ v = (np.interp(s_tick + delta_s, s, y) - y_tick) / delta_s
+
+ # Normalize slope into unit slope vector.
+ n = np.hypot(u, v)
+ mask = n == 0
+ n[mask] = 1.0
+
+ uv = np.array([u / n, v / n]).T
+ uv[mask] = np.array([0, 0]).T
+
+ # Rotate and scale unit vector into tick vector
+ dxy = np.dot(uv, trans_matrix) * self._length * spacing_px
+
+ # Build tick endpoints
+ x_end = x_tick + dxy[:, 0]
+ y_end = y_tick + dxy[:, 1]
+
+ # Interleave ticks to form Path vertices
+ xyt = np.empty((2 * num, 2), dtype=x_tick.dtype)
+ xyt[0::2, 0] = x_tick
+ xyt[1::2, 0] = x_end
+ xyt[0::2, 1] = y_tick
+ xyt[1::2, 1] = y_end
+
+ # Build up vector of Path codes
+ codes = np.tile([Path.MOVETO, Path.LINETO], num)
+
+ # Construct and draw resulting path
+ h = Path(xyt, codes)
+ # Transform back to data space during render
+ renderer.draw_path(gc0, h, affine.inverted() + trans, rgbFace)
+
+ gc0.restore()
+
+
+withTickedStroke = _subclass_with_normal(effect_class=TickedStroke)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/patheffects.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/patheffects.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..2c1634ca9314700c437df83a41b2bb8a58f4dec6
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/patheffects.pyi
@@ -0,0 +1,106 @@
+from collections.abc import Iterable, Sequence
+from typing import Any
+
+from matplotlib.backend_bases import RendererBase, GraphicsContextBase
+from matplotlib.path import Path
+from matplotlib.patches import Patch
+from matplotlib.transforms import Transform
+
+from matplotlib.typing import ColorType
+
+class AbstractPathEffect:
+ def __init__(self, offset: tuple[float, float] = ...) -> None: ...
+ def draw_path(
+ self,
+ renderer: RendererBase,
+ gc: GraphicsContextBase,
+ tpath: Path,
+ affine: Transform,
+ rgbFace: ColorType | None = ...,
+ ) -> None: ...
+
+class PathEffectRenderer(RendererBase):
+ def __init__(
+ self, path_effects: Iterable[AbstractPathEffect], renderer: RendererBase
+ ) -> None: ...
+ def copy_with_path_effect(self, path_effects: Iterable[AbstractPathEffect]) -> PathEffectRenderer: ...
+ def draw_path(
+ self,
+ gc: GraphicsContextBase,
+ tpath: Path,
+ affine: Transform,
+ rgbFace: ColorType | None = ...,
+ ) -> None: ...
+ def draw_markers(
+ self,
+ gc: GraphicsContextBase,
+ marker_path: Path,
+ marker_trans: Transform,
+ path: Path,
+ *args,
+ **kwargs
+ ) -> None: ...
+ def draw_path_collection(
+ self,
+ gc: GraphicsContextBase,
+ master_transform: Transform,
+ paths: Sequence[Path],
+ *args,
+ **kwargs
+ ) -> None: ...
+ def __getattribute__(self, name: str) -> Any: ...
+
+class Normal(AbstractPathEffect): ...
+
+class Stroke(AbstractPathEffect):
+ def __init__(self, offset: tuple[float, float] = ..., **kwargs) -> None: ...
+ # rgbFace becomes non-optional
+ def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
+
+class withStroke(Stroke): ...
+
+class SimplePatchShadow(AbstractPathEffect):
+ def __init__(
+ self,
+ offset: tuple[float, float] = ...,
+ shadow_rgbFace: ColorType | None = ...,
+ alpha: float | None = ...,
+ rho: float = ...,
+ **kwargs
+ ) -> None: ...
+ # rgbFace becomes non-optional
+ def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
+
+class withSimplePatchShadow(SimplePatchShadow): ...
+
+class SimpleLineShadow(AbstractPathEffect):
+ def __init__(
+ self,
+ offset: tuple[float, float] = ...,
+ shadow_color: ColorType = ...,
+ alpha: float = ...,
+ rho: float = ...,
+ **kwargs
+ ) -> None: ...
+ # rgbFace becomes non-optional
+ def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
+
+class PathPatchEffect(AbstractPathEffect):
+ patch: Patch
+ def __init__(self, offset: tuple[float, float] = ..., **kwargs) -> None: ...
+ # rgbFace becomes non-optional
+ def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
+
+class TickedStroke(AbstractPathEffect):
+ def __init__(
+ self,
+ offset: tuple[float, float] = ...,
+ spacing: float = ...,
+ angle: float = ...,
+ length: float = ...,
+ **kwargs
+ ) -> None: ...
+ # rgbFace becomes non-optional
+ def draw_path(self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, rgbFace: ColorType) -> None: ... # type: ignore[override]
+
+class withTickedStroke(TickedStroke): ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/pylab.py b/llava_video/lib/python3.10/site-packages/matplotlib/pylab.py
new file mode 100644
index 0000000000000000000000000000000000000000..a50779cf6d264408f1f99a086a25cb5c9d525588
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/pylab.py
@@ -0,0 +1,67 @@
+"""
+`pylab` is a historic interface and its use is strongly discouraged. The equivalent
+replacement is `matplotlib.pyplot`. See :ref:`api_interfaces` for a full overview
+of Matplotlib interfaces.
+
+`pylab` was designed to support a MATLAB-like way of working with all plotting related
+functions directly available in the global namespace. This was achieved through a
+wildcard import (``from pylab import *``).
+
+.. warning::
+ The use of `pylab` is discouraged for the following reasons:
+
+ ``from pylab import *`` imports all the functions from `matplotlib.pyplot`, `numpy`,
+ `numpy.fft`, `numpy.linalg`, and `numpy.random`, and some additional functions into
+ the global namespace.
+
+ Such a pattern is considered bad practice in modern python, as it clutters the global
+ namespace. Even more severely, in the case of `pylab`, this will overwrite some
+ builtin functions (e.g. the builtin `sum` will be replaced by `numpy.sum`), which
+ can lead to unexpected behavior.
+
+"""
+
+from matplotlib.cbook import flatten, silent_list
+
+import matplotlib as mpl
+
+from matplotlib.dates import (
+ date2num, num2date, datestr2num, drange, DateFormatter, DateLocator,
+ RRuleLocator, YearLocator, MonthLocator, WeekdayLocator, DayLocator,
+ HourLocator, MinuteLocator, SecondLocator, rrule, MO, TU, WE, TH, FR,
+ SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY,
+ relativedelta)
+
+# bring all the symbols in so folks can import them from
+# pylab in one fell swoop
+
+## We are still importing too many things from mlab; more cleanup is needed.
+
+from matplotlib.mlab import (
+ detrend, detrend_linear, detrend_mean, detrend_none, window_hanning,
+ window_none)
+
+from matplotlib import cbook, mlab, pyplot as plt
+from matplotlib.pyplot import *
+
+from numpy import *
+from numpy.fft import *
+from numpy.random import *
+from numpy.linalg import *
+
+import numpy as np
+import numpy.ma as ma
+
+# don't let numpy's datetime hide stdlib
+import datetime
+
+# This is needed, or bytes will be numpy.random.bytes from
+# "from numpy.random import *" above
+bytes = __import__("builtins").bytes
+# We also don't want the numpy version of these functions
+abs = __import__("builtins").abs
+bool = __import__("builtins").bool
+max = __import__("builtins").max
+min = __import__("builtins").min
+pow = __import__("builtins").pow
+round = __import__("builtins").round
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/quiver.py b/llava_video/lib/python3.10/site-packages/matplotlib/quiver.py
new file mode 100644
index 0000000000000000000000000000000000000000..e66f1f97b21f65ac3cdeaadd4ff6ef4b74ddaed8
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/quiver.py
@@ -0,0 +1,1228 @@
+"""
+Support for plotting vector fields.
+
+Presently this contains Quiver and Barb. Quiver plots an arrow in the
+direction of the vector, with the size of the arrow related to the
+magnitude of the vector.
+
+Barbs are like quiver in that they point along a vector, but
+the magnitude of the vector is given schematically by the presence of barbs
+or flags on the barb.
+
+This will also become a home for things such as standard
+deviation ellipses, which can and will be derived very easily from
+the Quiver code.
+"""
+
+import math
+
+import numpy as np
+from numpy import ma
+
+from matplotlib import _api, cbook, _docstring
+import matplotlib.artist as martist
+import matplotlib.collections as mcollections
+from matplotlib.patches import CirclePolygon
+import matplotlib.text as mtext
+import matplotlib.transforms as transforms
+
+
+_quiver_doc = """
+Plot a 2D field of arrows.
+
+Call signature::
+
+ quiver([X, Y], U, V, [C], /, **kwargs)
+
+*X*, *Y* define the arrow locations, *U*, *V* define the arrow directions, and
+*C* optionally sets the color. The arguments *X*, *Y*, *U*, *V*, *C* are
+positional-only.
+
+**Arrow length**
+
+The default settings auto-scales the length of the arrows to a reasonable size.
+To change this behavior see the *scale* and *scale_units* parameters.
+
+**Arrow shape**
+
+The arrow shape is determined by *width*, *headwidth*, *headlength* and
+*headaxislength*. See the notes below.
+
+**Arrow styling**
+
+Each arrow is internally represented by a filled polygon with a default edge
+linewidth of 0. As a result, an arrow is rather a filled area, not a line with
+a head, and `.PolyCollection` properties like *linewidth*, *edgecolor*,
+*facecolor*, etc. act accordingly.
+
+
+Parameters
+----------
+X, Y : 1D or 2D array-like, optional
+ The x and y coordinates of the arrow locations.
+
+ If not given, they will be generated as a uniform integer meshgrid based
+ on the dimensions of *U* and *V*.
+
+ If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D
+ using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)``
+ must match the column and row dimensions of *U* and *V*.
+
+U, V : 1D or 2D array-like
+ The x and y direction components of the arrow vectors. The interpretation
+ of these components (in data or in screen space) depends on *angles*.
+
+ *U* and *V* must have the same number of elements, matching the number of
+ arrow locations in *X*, *Y*. *U* and *V* may be masked. Locations masked
+ in any of *U*, *V*, and *C* will not be drawn.
+
+C : 1D or 2D array-like, optional
+ Numeric data that defines the arrow colors by colormapping via *norm* and
+ *cmap*.
+
+ This does not support explicit colors. If you want to set colors directly,
+ use *color* instead. The size of *C* must match the number of arrow
+ locations.
+
+angles : {'uv', 'xy'} or array-like, default: 'uv'
+ Method for determining the angle of the arrows.
+
+ - 'uv': Arrow directions are based on
+ :ref:`display coordinates `; i.e. a 45° angle will
+ always show up as diagonal on the screen, irrespective of figure or Axes
+ aspect ratio or Axes data ranges. This is useful when the arrows represent
+ a quantity whose direction is not tied to the x and y data coordinates.
+
+ If *U* == *V* the orientation of the arrow on the plot is 45 degrees
+ counter-clockwise from the horizontal axis (positive to the right).
+
+ - 'xy': Arrow direction in data coordinates, i.e. the arrows point from
+ (x, y) to (x+u, y+v). This is ideal for vector fields or gradient plots
+ where the arrows should directly represent movements or gradients in the
+ x and y directions.
+
+ - Arbitrary angles may be specified explicitly as an array of values
+ in degrees, counter-clockwise from the horizontal axis.
+
+ In this case *U*, *V* is only used to determine the length of the
+ arrows.
+
+ For example, ``angles=[30, 60, 90]`` will orient the arrows at 30, 60, and 90
+ degrees respectively, regardless of the *U* and *V* components.
+
+ Note: inverting a data axis will correspondingly invert the
+ arrows only with ``angles='xy'``.
+
+pivot : {'tail', 'mid', 'middle', 'tip'}, default: 'tail'
+ The part of the arrow that is anchored to the *X*, *Y* grid. The arrow
+ rotates about this point.
+
+ 'mid' is a synonym for 'middle'.
+
+scale : float, optional
+ Scales the length of the arrow inversely.
+
+ Number of data values represented by one unit of arrow length on the plot.
+ For example, if the data represents velocity in meters per second (m/s), the
+ scale parameter determines how many meters per second correspond to one unit of
+ arrow length relative to the width of the plot.
+ Smaller scale parameter makes the arrow longer.
+
+ By default, an autoscaling algorithm is used to scale the arrow length to a
+ reasonable size, which is based on the average vector length and the number of
+ vectors.
+
+ The arrow length unit is given by the *scale_units* parameter.
+
+scale_units : {'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width'
+
+ The physical image unit, which is used for rendering the scaled arrow data *U*, *V*.
+
+ The rendered arrow length is given by
+
+ length in x direction = $\\frac{u}{\\mathrm{scale}} \\mathrm{scale_unit}$
+
+ length in y direction = $\\frac{v}{\\mathrm{scale}} \\mathrm{scale_unit}$
+
+ For example, ``(u, v) = (0.5, 0)`` with ``scale=10, scale_unit="width"`` results
+ in a horizontal arrow with a length of *0.5 / 10 * "width"*, i.e. 0.05 times the
+ Axes width.
+
+ Supported values are:
+
+ - 'width' or 'height': The arrow length is scaled relative to the width or height
+ of the Axes.
+ For example, ``scale_units='width', scale=1.0``, will result in an arrow length
+ of width of the Axes.
+
+ - 'dots': The arrow length of the arrows is in measured in display dots (pixels).
+
+ - 'inches': Arrow lengths are scaled based on the DPI (dots per inch) of the figure.
+ This ensures that the arrows have a consistent physical size on the figure,
+ in inches, regardless of data values or plot scaling.
+ For example, ``(u, v) = (1, 0)`` with ``scale_units='inches', scale=2`` results
+ in a 0.5 inch-long arrow.
+
+ - 'x' or 'y': The arrow length is scaled relative to the x or y axis units.
+ For example, ``(u, v) = (0, 1)`` with ``scale_units='x', scale=1`` results
+ in a vertical arrow with the length of 1 x-axis unit.
+
+ - 'xy': Arrow length will be same as 'x' or 'y' units.
+ This is useful for creating vectors in the x-y plane where u and v have
+ the same units as x and y. To plot vectors in the x-y plane with u and v having
+ the same units as x and y, use ``angles='xy', scale_units='xy', scale=1``.
+
+ Note: Setting *scale_units* without setting scale does not have any effect because
+ the scale units only differ by a constant factor and that is rescaled through
+ autoscaling.
+
+units : {'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width'
+ Affects the arrow size (except for the length). In particular, the shaft
+ *width* is measured in multiples of this unit.
+
+ Supported values are:
+
+ - 'width', 'height': The width or height of the Axes.
+ - 'dots', 'inches': Pixels or inches based on the figure dpi.
+ - 'x', 'y', 'xy': *X*, *Y* or :math:`\\sqrt{X^2 + Y^2}` in data units.
+
+ The following table summarizes how these values affect the visible arrow
+ size under zooming and figure size changes:
+
+ ================= ================= ==================
+ units zoom figure size change
+ ================= ================= ==================
+ 'x', 'y', 'xy' arrow size scales —
+ 'width', 'height' — arrow size scales
+ 'dots', 'inches' — —
+ ================= ================= ==================
+
+width : float, optional
+ Shaft width in arrow units. All head parameters are relative to *width*.
+
+ The default depends on choice of *units* above, and number of vectors;
+ a typical starting value is about 0.005 times the width of the plot.
+
+headwidth : float, default: 3
+ Head width as multiple of shaft *width*. See the notes below.
+
+headlength : float, default: 5
+ Head length as multiple of shaft *width*. See the notes below.
+
+headaxislength : float, default: 4.5
+ Head length at shaft intersection as multiple of shaft *width*.
+ See the notes below.
+
+minshaft : float, default: 1
+ Length below which arrow scales, in units of head length. Do not
+ set this to less than 1, or small arrows will look terrible!
+
+minlength : float, default: 1
+ Minimum length as a multiple of shaft width; if an arrow length
+ is less than this, plot a dot (hexagon) of this diameter instead.
+
+color : :mpltype:`color` or list :mpltype:`color`, optional
+ Explicit color(s) for the arrows. If *C* has been set, *color* has no
+ effect.
+
+ This is a synonym for the `.PolyCollection` *facecolor* parameter.
+
+Other Parameters
+----------------
+data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+
+**kwargs : `~matplotlib.collections.PolyCollection` properties, optional
+ All other keyword arguments are passed on to `.PolyCollection`:
+
+ %(PolyCollection:kwdoc)s
+
+Returns
+-------
+`~matplotlib.quiver.Quiver`
+
+See Also
+--------
+.Axes.quiverkey : Add a key to a quiver plot.
+
+Notes
+-----
+
+**Arrow shape**
+
+The arrow is drawn as a polygon using the nodes as shown below. The values
+*headwidth*, *headlength*, and *headaxislength* are in units of *width*.
+
+.. image:: /_static/quiver_sizes.svg
+ :width: 500px
+
+The defaults give a slightly swept-back arrow. Here are some guidelines how to
+get other head shapes:
+
+- To make the head a triangle, make *headaxislength* the same as *headlength*.
+- To make the arrow more pointed, reduce *headwidth* or increase *headlength*
+ and *headaxislength*.
+- To make the head smaller relative to the shaft, scale down all the head
+ parameters proportionally.
+- To remove the head completely, set all *head* parameters to 0.
+- To get a diamond-shaped head, make *headaxislength* larger than *headlength*.
+- Warning: For *headaxislength* < (*headlength* / *headwidth*), the "headaxis"
+ nodes (i.e. the ones connecting the head with the shaft) will protrude out
+ of the head in forward direction so that the arrow head looks broken.
+""" % _docstring.interpd.params
+
+_docstring.interpd.register(quiver_doc=_quiver_doc)
+
+
+class QuiverKey(martist.Artist):
+ """Labelled arrow for use as a quiver plot scale key."""
+ halign = {'N': 'center', 'S': 'center', 'E': 'left', 'W': 'right'}
+ valign = {'N': 'bottom', 'S': 'top', 'E': 'center', 'W': 'center'}
+ pivot = {'N': 'middle', 'S': 'middle', 'E': 'tip', 'W': 'tail'}
+
+ def __init__(self, Q, X, Y, U, label,
+ *, angle=0, coordinates='axes', color=None, labelsep=0.1,
+ labelpos='N', labelcolor=None, fontproperties=None,
+ zorder=None, **kwargs):
+ """
+ Add a key to a quiver plot.
+
+ The positioning of the key depends on *X*, *Y*, *coordinates*, and
+ *labelpos*. If *labelpos* is 'N' or 'S', *X*, *Y* give the position of
+ the middle of the key arrow. If *labelpos* is 'E', *X*, *Y* positions
+ the head, and if *labelpos* is 'W', *X*, *Y* positions the tail; in
+ either of these two cases, *X*, *Y* is somewhere in the middle of the
+ arrow+label key object.
+
+ Parameters
+ ----------
+ Q : `~matplotlib.quiver.Quiver`
+ A `.Quiver` object as returned by a call to `~.Axes.quiver()`.
+ X, Y : float
+ The location of the key.
+ U : float
+ The length of the key.
+ label : str
+ The key label (e.g., length and units of the key).
+ angle : float, default: 0
+ The angle of the key arrow, in degrees anti-clockwise from the
+ horizontal axis.
+ coordinates : {'axes', 'figure', 'data', 'inches'}, default: 'axes'
+ Coordinate system and units for *X*, *Y*: 'axes' and 'figure' are
+ normalized coordinate systems with (0, 0) in the lower left and
+ (1, 1) in the upper right; 'data' are the axes data coordinates
+ (used for the locations of the vectors in the quiver plot itself);
+ 'inches' is position in the figure in inches, with (0, 0) at the
+ lower left corner.
+ color : :mpltype:`color`
+ Overrides face and edge colors from *Q*.
+ labelpos : {'N', 'S', 'E', 'W'}
+ Position the label above, below, to the right, to the left of the
+ arrow, respectively.
+ labelsep : float, default: 0.1
+ Distance in inches between the arrow and the label.
+ labelcolor : :mpltype:`color`, default: :rc:`text.color`
+ Label color.
+ fontproperties : dict, optional
+ A dictionary with keyword arguments accepted by the
+ `~matplotlib.font_manager.FontProperties` initializer:
+ *family*, *style*, *variant*, *size*, *weight*.
+ zorder : float
+ The zorder of the key. The default is 0.1 above *Q*.
+ **kwargs
+ Any additional keyword arguments are used to override vector
+ properties taken from *Q*.
+ """
+ super().__init__()
+ self.Q = Q
+ self.X = X
+ self.Y = Y
+ self.U = U
+ self.angle = angle
+ self.coord = coordinates
+ self.color = color
+ self.label = label
+ self._labelsep_inches = labelsep
+
+ self.labelpos = labelpos
+ self.labelcolor = labelcolor
+ self.fontproperties = fontproperties or dict()
+ self.kw = kwargs
+ self.text = mtext.Text(
+ text=label,
+ horizontalalignment=self.halign[self.labelpos],
+ verticalalignment=self.valign[self.labelpos],
+ fontproperties=self.fontproperties)
+ if self.labelcolor is not None:
+ self.text.set_color(self.labelcolor)
+ self._dpi_at_last_init = None
+ self.zorder = zorder if zorder is not None else Q.zorder + 0.1
+
+ @property
+ def labelsep(self):
+ return self._labelsep_inches * self.Q.axes.get_figure(root=True).dpi
+
+ def _init(self):
+ if True: # self._dpi_at_last_init != self.axes.get_figure().dpi
+ if self.Q._dpi_at_last_init != self.Q.axes.get_figure(root=True).dpi:
+ self.Q._init()
+ self._set_transform()
+ with cbook._setattr_cm(self.Q, pivot=self.pivot[self.labelpos],
+ # Hack: save and restore the Umask
+ Umask=ma.nomask):
+ u = self.U * np.cos(np.radians(self.angle))
+ v = self.U * np.sin(np.radians(self.angle))
+ self.verts = self.Q._make_verts([[0., 0.]],
+ np.array([u]), np.array([v]), 'uv')
+ kwargs = self.Q.polykw
+ kwargs.update(self.kw)
+ self.vector = mcollections.PolyCollection(
+ self.verts,
+ offsets=[(self.X, self.Y)],
+ offset_transform=self.get_transform(),
+ **kwargs)
+ if self.color is not None:
+ self.vector.set_color(self.color)
+ self.vector.set_transform(self.Q.get_transform())
+ self.vector.set_figure(self.get_figure())
+ self._dpi_at_last_init = self.Q.axes.get_figure(root=True).dpi
+
+ def _text_shift(self):
+ return {
+ "N": (0, +self.labelsep),
+ "S": (0, -self.labelsep),
+ "E": (+self.labelsep, 0),
+ "W": (-self.labelsep, 0),
+ }[self.labelpos]
+
+ @martist.allow_rasterization
+ def draw(self, renderer):
+ self._init()
+ self.vector.draw(renderer)
+ pos = self.get_transform().transform((self.X, self.Y))
+ self.text.set_position(pos + self._text_shift())
+ self.text.draw(renderer)
+ self.stale = False
+
+ def _set_transform(self):
+ fig = self.Q.axes.get_figure(root=False)
+ self.set_transform(_api.check_getitem({
+ "data": self.Q.axes.transData,
+ "axes": self.Q.axes.transAxes,
+ "figure": fig.transFigure,
+ "inches": fig.dpi_scale_trans,
+ }, coordinates=self.coord))
+
+ def set_figure(self, fig):
+ super().set_figure(fig)
+ self.text.set_figure(fig)
+
+ def contains(self, mouseevent):
+ if self._different_canvas(mouseevent):
+ return False, {}
+ # Maybe the dictionary should allow one to
+ # distinguish between a text hit and a vector hit.
+ if (self.text.contains(mouseevent)[0] or
+ self.vector.contains(mouseevent)[0]):
+ return True, {}
+ return False, {}
+
+
+def _parse_args(*args, caller_name='function'):
+ """
+ Helper function to parse positional parameters for colored vector plots.
+
+ This is currently used for Quiver and Barbs.
+
+ Parameters
+ ----------
+ *args : list
+ list of 2-5 arguments. Depending on their number they are parsed to::
+
+ U, V
+ U, V, C
+ X, Y, U, V
+ X, Y, U, V, C
+
+ caller_name : str
+ Name of the calling method (used in error messages).
+ """
+ X = Y = C = None
+
+ nargs = len(args)
+ if nargs == 2:
+ # The use of atleast_1d allows for handling scalar arguments while also
+ # keeping masked arrays
+ U, V = np.atleast_1d(*args)
+ elif nargs == 3:
+ U, V, C = np.atleast_1d(*args)
+ elif nargs == 4:
+ X, Y, U, V = np.atleast_1d(*args)
+ elif nargs == 5:
+ X, Y, U, V, C = np.atleast_1d(*args)
+ else:
+ raise _api.nargs_error(caller_name, takes="from 2 to 5", given=nargs)
+
+ nr, nc = (1, U.shape[0]) if U.ndim == 1 else U.shape
+
+ if X is not None:
+ X = X.ravel()
+ Y = Y.ravel()
+ if len(X) == nc and len(Y) == nr:
+ X, Y = (a.ravel() for a in np.meshgrid(X, Y))
+ elif len(X) != len(Y):
+ raise ValueError('X and Y must be the same size, but '
+ f'X.size is {X.size} and Y.size is {Y.size}.')
+ else:
+ indexgrid = np.meshgrid(np.arange(nc), np.arange(nr))
+ X, Y = (np.ravel(a) for a in indexgrid)
+ # Size validation for U, V, C is left to the set_UVC method.
+ return X, Y, U, V, C
+
+
+def _check_consistent_shapes(*arrays):
+ all_shapes = {a.shape for a in arrays}
+ if len(all_shapes) != 1:
+ raise ValueError('The shapes of the passed in arrays do not match')
+
+
+class Quiver(mcollections.PolyCollection):
+ """
+ Specialized PolyCollection for arrows.
+
+ The only API method is set_UVC(), which can be used
+ to change the size, orientation, and color of the
+ arrows; their locations are fixed when the class is
+ instantiated. Possibly this method will be useful
+ in animations.
+
+ Much of the work in this class is done in the draw()
+ method so that as much information as possible is available
+ about the plot. In subsequent draw() calls, recalculation
+ is limited to things that might have changed, so there
+ should be no performance penalty from putting the calculations
+ in the draw() method.
+ """
+
+ _PIVOT_VALS = ('tail', 'middle', 'tip')
+
+ @_docstring.Substitution(_quiver_doc)
+ def __init__(self, ax, *args,
+ scale=None, headwidth=3, headlength=5, headaxislength=4.5,
+ minshaft=1, minlength=1, units='width', scale_units=None,
+ angles='uv', width=None, color='k', pivot='tail', **kwargs):
+ """
+ The constructor takes one required argument, an Axes
+ instance, followed by the args and kwargs described
+ by the following pyplot interface documentation:
+ %s
+ """
+ self._axes = ax # The attr actually set by the Artist.axes property.
+ X, Y, U, V, C = _parse_args(*args, caller_name='quiver')
+ self.X = X
+ self.Y = Y
+ self.XY = np.column_stack((X, Y))
+ self.N = len(X)
+ self.scale = scale
+ self.headwidth = headwidth
+ self.headlength = float(headlength)
+ self.headaxislength = headaxislength
+ self.minshaft = minshaft
+ self.minlength = minlength
+ self.units = units
+ self.scale_units = scale_units
+ self.angles = angles
+ self.width = width
+
+ if pivot.lower() == 'mid':
+ pivot = 'middle'
+ self.pivot = pivot.lower()
+ _api.check_in_list(self._PIVOT_VALS, pivot=self.pivot)
+
+ self.transform = kwargs.pop('transform', ax.transData)
+ kwargs.setdefault('facecolors', color)
+ kwargs.setdefault('linewidths', (0,))
+ super().__init__([], offsets=self.XY, offset_transform=self.transform,
+ closed=False, **kwargs)
+ self.polykw = kwargs
+ self.set_UVC(U, V, C)
+ self._dpi_at_last_init = None
+
+ def _init(self):
+ """
+ Initialization delayed until first draw;
+ allow time for axes setup.
+ """
+ # It seems that there are not enough event notifications
+ # available to have this work on an as-needed basis at present.
+ if True: # self._dpi_at_last_init != self.axes.figure.dpi
+ trans = self._set_transform()
+ self.span = trans.inverted().transform_bbox(self.axes.bbox).width
+ if self.width is None:
+ sn = np.clip(math.sqrt(self.N), 8, 25)
+ self.width = 0.06 * self.span / sn
+
+ # _make_verts sets self.scale if not already specified
+ if (self._dpi_at_last_init != self.axes.get_figure(root=True).dpi
+ and self.scale is None):
+ self._make_verts(self.XY, self.U, self.V, self.angles)
+
+ self._dpi_at_last_init = self.axes.get_figure(root=True).dpi
+
+ def get_datalim(self, transData):
+ trans = self.get_transform()
+ offset_trf = self.get_offset_transform()
+ full_transform = (trans - transData) + (offset_trf - transData)
+ XY = full_transform.transform(self.XY)
+ bbox = transforms.Bbox.null()
+ bbox.update_from_data_xy(XY, ignore=True)
+ return bbox
+
+ @martist.allow_rasterization
+ def draw(self, renderer):
+ self._init()
+ verts = self._make_verts(self.XY, self.U, self.V, self.angles)
+ self.set_verts(verts, closed=False)
+ super().draw(renderer)
+ self.stale = False
+
+ def set_UVC(self, U, V, C=None):
+ # We need to ensure we have a copy, not a reference
+ # to an array that might change before draw().
+ U = ma.masked_invalid(U, copy=True).ravel()
+ V = ma.masked_invalid(V, copy=True).ravel()
+ if C is not None:
+ C = ma.masked_invalid(C, copy=True).ravel()
+ for name, var in zip(('U', 'V', 'C'), (U, V, C)):
+ if not (var is None or var.size == self.N or var.size == 1):
+ raise ValueError(f'Argument {name} has a size {var.size}'
+ f' which does not match {self.N},'
+ ' the number of arrow positions')
+
+ mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True)
+ if C is not None:
+ mask = ma.mask_or(mask, C.mask, copy=False, shrink=True)
+ if mask is ma.nomask:
+ C = C.filled()
+ else:
+ C = ma.array(C, mask=mask, copy=False)
+ self.U = U.filled(1)
+ self.V = V.filled(1)
+ self.Umask = mask
+ if C is not None:
+ self.set_array(C)
+ self.stale = True
+
+ def _dots_per_unit(self, units):
+ """Return a scale factor for converting from units to pixels."""
+ bb = self.axes.bbox
+ vl = self.axes.viewLim
+ return _api.check_getitem({
+ 'x': bb.width / vl.width,
+ 'y': bb.height / vl.height,
+ 'xy': np.hypot(*bb.size) / np.hypot(*vl.size),
+ 'width': bb.width,
+ 'height': bb.height,
+ 'dots': 1.,
+ 'inches': self.axes.get_figure(root=True).dpi,
+ }, units=units)
+
+ def _set_transform(self):
+ """
+ Set the PolyCollection transform to go
+ from arrow width units to pixels.
+ """
+ dx = self._dots_per_unit(self.units)
+ self._trans_scale = dx # pixels per arrow width unit
+ trans = transforms.Affine2D().scale(dx)
+ self.set_transform(trans)
+ return trans
+
+ # Calculate angles and lengths for segment between (x, y), (x+u, y+v)
+ def _angles_lengths(self, XY, U, V, eps=1):
+ xy = self.axes.transData.transform(XY)
+ uv = np.column_stack((U, V))
+ xyp = self.axes.transData.transform(XY + eps * uv)
+ dxy = xyp - xy
+ angles = np.arctan2(dxy[:, 1], dxy[:, 0])
+ lengths = np.hypot(*dxy.T) / eps
+ return angles, lengths
+
+ # XY is stacked [X, Y].
+ # See quiver() doc for meaning of X, Y, U, V, angles.
+ def _make_verts(self, XY, U, V, angles):
+ uv = (U + V * 1j)
+ str_angles = angles if isinstance(angles, str) else ''
+ if str_angles == 'xy' and self.scale_units == 'xy':
+ # Here eps is 1 so that if we get U, V by diffing
+ # the X, Y arrays, the vectors will connect the
+ # points, regardless of the axis scaling (including log).
+ angles, lengths = self._angles_lengths(XY, U, V, eps=1)
+ elif str_angles == 'xy' or self.scale_units == 'xy':
+ # Calculate eps based on the extents of the plot
+ # so that we don't end up with roundoff error from
+ # adding a small number to a large.
+ eps = np.abs(self.axes.dataLim.extents).max() * 0.001
+ angles, lengths = self._angles_lengths(XY, U, V, eps=eps)
+
+ if str_angles and self.scale_units == 'xy':
+ a = lengths
+ else:
+ a = np.abs(uv)
+
+ if self.scale is None:
+ sn = max(10, math.sqrt(self.N))
+ if self.Umask is not ma.nomask:
+ amean = a[~self.Umask].mean()
+ else:
+ amean = a.mean()
+ # crude auto-scaling
+ # scale is typical arrow length as a multiple of the arrow width
+ scale = 1.8 * amean * sn / self.span
+
+ if self.scale_units is None:
+ if self.scale is None:
+ self.scale = scale
+ widthu_per_lenu = 1.0
+ else:
+ if self.scale_units == 'xy':
+ dx = 1
+ else:
+ dx = self._dots_per_unit(self.scale_units)
+ widthu_per_lenu = dx / self._trans_scale
+ if self.scale is None:
+ self.scale = scale * widthu_per_lenu
+ length = a * (widthu_per_lenu / (self.scale * self.width))
+ X, Y = self._h_arrows(length)
+ if str_angles == 'xy':
+ theta = angles
+ elif str_angles == 'uv':
+ theta = np.angle(uv)
+ else:
+ theta = ma.masked_invalid(np.deg2rad(angles)).filled(0)
+ theta = theta.reshape((-1, 1)) # for broadcasting
+ xy = (X + Y * 1j) * np.exp(1j * theta) * self.width
+ XY = np.stack((xy.real, xy.imag), axis=2)
+ if self.Umask is not ma.nomask:
+ XY = ma.array(XY)
+ XY[self.Umask] = ma.masked
+ # This might be handled more efficiently with nans, given
+ # that nans will end up in the paths anyway.
+
+ return XY
+
+ def _h_arrows(self, length):
+ """Length is in arrow width units."""
+ # It might be possible to streamline the code
+ # and speed it up a bit by using complex (x, y)
+ # instead of separate arrays; but any gain would be slight.
+ minsh = self.minshaft * self.headlength
+ N = len(length)
+ length = length.reshape(N, 1)
+ # This number is chosen based on when pixel values overflow in Agg
+ # causing rendering errors
+ # length = np.minimum(length, 2 ** 16)
+ np.clip(length, 0, 2 ** 16, out=length)
+ # x, y: normal horizontal arrow
+ x = np.array([0, -self.headaxislength,
+ -self.headlength, 0],
+ np.float64)
+ x = x + np.array([0, 1, 1, 1]) * length
+ y = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
+ y = np.repeat(y[np.newaxis, :], N, axis=0)
+ # x0, y0: arrow without shaft, for short vectors
+ x0 = np.array([0, minsh - self.headaxislength,
+ minsh - self.headlength, minsh], np.float64)
+ y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
+ ii = [0, 1, 2, 3, 2, 1, 0, 0]
+ X = x[:, ii]
+ Y = y[:, ii]
+ Y[:, 3:-1] *= -1
+ X0 = x0[ii]
+ Y0 = y0[ii]
+ Y0[3:-1] *= -1
+ shrink = length / minsh if minsh != 0. else 0.
+ X0 = shrink * X0[np.newaxis, :]
+ Y0 = shrink * Y0[np.newaxis, :]
+ short = np.repeat(length < minsh, 8, axis=1)
+ # Now select X0, Y0 if short, otherwise X, Y
+ np.copyto(X, X0, where=short)
+ np.copyto(Y, Y0, where=short)
+ if self.pivot == 'middle':
+ X -= 0.5 * X[:, 3, np.newaxis]
+ elif self.pivot == 'tip':
+ # numpy bug? using -= does not work here unless we multiply by a
+ # float first, as with 'mid'.
+ X = X - X[:, 3, np.newaxis]
+ elif self.pivot != 'tail':
+ _api.check_in_list(["middle", "tip", "tail"], pivot=self.pivot)
+
+ tooshort = length < self.minlength
+ if tooshort.any():
+ # Use a heptagonal dot:
+ th = np.arange(0, 8, 1, np.float64) * (np.pi / 3.0)
+ x1 = np.cos(th) * self.minlength * 0.5
+ y1 = np.sin(th) * self.minlength * 0.5
+ X1 = np.repeat(x1[np.newaxis, :], N, axis=0)
+ Y1 = np.repeat(y1[np.newaxis, :], N, axis=0)
+ tooshort = np.repeat(tooshort, 8, 1)
+ np.copyto(X, X1, where=tooshort)
+ np.copyto(Y, Y1, where=tooshort)
+ # Mask handling is deferred to the caller, _make_verts.
+ return X, Y
+
+
+_barbs_doc = r"""
+Plot a 2D field of wind barbs.
+
+Call signature::
+
+ barbs([X, Y], U, V, [C], /, **kwargs)
+
+Where *X*, *Y* define the barb locations, *U*, *V* define the barb
+directions, and *C* optionally sets the color.
+
+The arguments *X*, *Y*, *U*, *V*, *C* are positional-only and may be
+1D or 2D. *U*, *V*, *C* may be masked arrays, but masked *X*, *Y*
+are not supported at present.
+
+Barbs are traditionally used in meteorology as a way to plot the speed
+and direction of wind observations, but can technically be used to
+plot any two dimensional vector quantity. As opposed to arrows, which
+give vector magnitude by the length of the arrow, the barbs give more
+quantitative information about the vector magnitude by putting slanted
+lines or a triangle for various increments in magnitude, as show
+schematically below::
+
+ : /\ \
+ : / \ \
+ : / \ \ \
+ : / \ \ \
+ : ------------------------------
+
+The largest increment is given by a triangle (or "flag"). After those
+come full lines (barbs). The smallest increment is a half line. There
+is only, of course, ever at most 1 half line. If the magnitude is
+small and only needs a single half-line and no full lines or
+triangles, the half-line is offset from the end of the barb so that it
+can be easily distinguished from barbs with a single full line. The
+magnitude for the barb shown above would nominally be 65, using the
+standard increments of 50, 10, and 5.
+
+See also https://en.wikipedia.org/wiki/Wind_barb.
+
+Parameters
+----------
+X, Y : 1D or 2D array-like, optional
+ The x and y coordinates of the barb locations. See *pivot* for how the
+ barbs are drawn to the x, y positions.
+
+ If not given, they will be generated as a uniform integer meshgrid based
+ on the dimensions of *U* and *V*.
+
+ If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D
+ using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)``
+ must match the column and row dimensions of *U* and *V*.
+
+U, V : 1D or 2D array-like
+ The x and y components of the barb shaft.
+
+C : 1D or 2D array-like, optional
+ Numeric data that defines the barb colors by colormapping via *norm* and
+ *cmap*.
+
+ This does not support explicit colors. If you want to set colors directly,
+ use *barbcolor* instead.
+
+length : float, default: 7
+ Length of the barb in points; the other parts of the barb
+ are scaled against this.
+
+pivot : {'tip', 'middle'} or float, default: 'tip'
+ The part of the arrow that is anchored to the *X*, *Y* grid. The barb
+ rotates about this point. This can also be a number, which shifts the
+ start of the barb that many points away from grid point.
+
+barbcolor : :mpltype:`color` or color sequence
+ The color of all parts of the barb except for the flags. This parameter
+ is analogous to the *edgecolor* parameter for polygons, which can be used
+ instead. However this parameter will override facecolor.
+
+flagcolor : :mpltype:`color` or color sequence
+ The color of any flags on the barb. This parameter is analogous to the
+ *facecolor* parameter for polygons, which can be used instead. However,
+ this parameter will override facecolor. If this is not set (and *C* has
+ not either) then *flagcolor* will be set to match *barbcolor* so that the
+ barb has a uniform color. If *C* has been set, *flagcolor* has no effect.
+
+sizes : dict, optional
+ A dictionary of coefficients specifying the ratio of a given
+ feature to the length of the barb. Only those values one wishes to
+ override need to be included. These features include:
+
+ - 'spacing' - space between features (flags, full/half barbs)
+ - 'height' - height (distance from shaft to top) of a flag or full barb
+ - 'width' - width of a flag, twice the width of a full barb
+ - 'emptybarb' - radius of the circle used for low magnitudes
+
+fill_empty : bool, default: False
+ Whether the empty barbs (circles) that are drawn should be filled with
+ the flag color. If they are not filled, the center is transparent.
+
+rounding : bool, default: True
+ Whether the vector magnitude should be rounded when allocating barb
+ components. If True, the magnitude is rounded to the nearest multiple
+ of the half-barb increment. If False, the magnitude is simply truncated
+ to the next lowest multiple.
+
+barb_increments : dict, optional
+ A dictionary of increments specifying values to associate with
+ different parts of the barb. Only those values one wishes to
+ override need to be included.
+
+ - 'half' - half barbs (Default is 5)
+ - 'full' - full barbs (Default is 10)
+ - 'flag' - flags (default is 50)
+
+flip_barb : bool or array-like of bool, default: False
+ Whether the lines and flags should point opposite to normal.
+ Normal behavior is for the barbs and lines to point right (comes from wind
+ barbs having these features point towards low pressure in the Northern
+ Hemisphere).
+
+ A single value is applied to all barbs. Individual barbs can be flipped by
+ passing a bool array of the same size as *U* and *V*.
+
+Returns
+-------
+barbs : `~matplotlib.quiver.Barbs`
+
+Other Parameters
+----------------
+data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+
+**kwargs
+ The barbs can further be customized using `.PolyCollection` keyword
+ arguments:
+
+ %(PolyCollection:kwdoc)s
+""" % _docstring.interpd.params
+
+_docstring.interpd.register(barbs_doc=_barbs_doc)
+
+
+class Barbs(mcollections.PolyCollection):
+ """
+ Specialized PolyCollection for barbs.
+
+ The only API method is :meth:`set_UVC`, which can be used to
+ change the size, orientation, and color of the arrows. Locations
+ are changed using the :meth:`set_offsets` collection method.
+ Possibly this method will be useful in animations.
+
+ There is one internal function :meth:`_find_tails` which finds
+ exactly what should be put on the barb given the vector magnitude.
+ From there :meth:`_make_barbs` is used to find the vertices of the
+ polygon to represent the barb based on this information.
+ """
+
+ # This may be an abuse of polygons here to render what is essentially maybe
+ # 1 triangle and a series of lines. It works fine as far as I can tell
+ # however.
+
+ @_docstring.interpd
+ def __init__(self, ax, *args,
+ pivot='tip', length=7, barbcolor=None, flagcolor=None,
+ sizes=None, fill_empty=False, barb_increments=None,
+ rounding=True, flip_barb=False, **kwargs):
+ """
+ The constructor takes one required argument, an Axes
+ instance, followed by the args and kwargs described
+ by the following pyplot interface documentation:
+ %(barbs_doc)s
+ """
+ self.sizes = sizes or dict()
+ self.fill_empty = fill_empty
+ self.barb_increments = barb_increments or dict()
+ self.rounding = rounding
+ self.flip = np.atleast_1d(flip_barb)
+ transform = kwargs.pop('transform', ax.transData)
+ self._pivot = pivot
+ self._length = length
+
+ # Flagcolor and barbcolor provide convenience parameters for
+ # setting the facecolor and edgecolor, respectively, of the barb
+ # polygon. We also work here to make the flag the same color as the
+ # rest of the barb by default
+
+ if None in (barbcolor, flagcolor):
+ kwargs['edgecolors'] = 'face'
+ if flagcolor:
+ kwargs['facecolors'] = flagcolor
+ elif barbcolor:
+ kwargs['facecolors'] = barbcolor
+ else:
+ # Set to facecolor passed in or default to black
+ kwargs.setdefault('facecolors', 'k')
+ else:
+ kwargs['edgecolors'] = barbcolor
+ kwargs['facecolors'] = flagcolor
+
+ # Explicitly set a line width if we're not given one, otherwise
+ # polygons are not outlined and we get no barbs
+ if 'linewidth' not in kwargs and 'lw' not in kwargs:
+ kwargs['linewidth'] = 1
+
+ # Parse out the data arrays from the various configurations supported
+ x, y, u, v, c = _parse_args(*args, caller_name='barbs')
+ self.x = x
+ self.y = y
+ xy = np.column_stack((x, y))
+
+ # Make a collection
+ barb_size = self._length ** 2 / 4 # Empirically determined
+ super().__init__(
+ [], (barb_size,), offsets=xy, offset_transform=transform, **kwargs)
+ self.set_transform(transforms.IdentityTransform())
+
+ self.set_UVC(u, v, c)
+
+ def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50):
+ """
+ Find how many of each of the tail pieces is necessary.
+
+ Parameters
+ ----------
+ mag : `~numpy.ndarray`
+ Vector magnitudes; must be non-negative (and an actual ndarray).
+ rounding : bool, default: True
+ Whether to round or to truncate to the nearest half-barb.
+ half, full, flag : float, defaults: 5, 10, 50
+ Increments for a half-barb, a barb, and a flag.
+
+ Returns
+ -------
+ n_flags, n_barbs : int array
+ For each entry in *mag*, the number of flags and barbs.
+ half_flag : bool array
+ For each entry in *mag*, whether a half-barb is needed.
+ empty_flag : bool array
+ For each entry in *mag*, whether nothing is drawn.
+ """
+ # If rounding, round to the nearest multiple of half, the smallest
+ # increment
+ if rounding:
+ mag = half * np.around(mag / half)
+ n_flags, mag = divmod(mag, flag)
+ n_barb, mag = divmod(mag, full)
+ half_flag = mag >= half
+ empty_flag = ~(half_flag | (n_flags > 0) | (n_barb > 0))
+ return n_flags.astype(int), n_barb.astype(int), half_flag, empty_flag
+
+ def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,
+ pivot, sizes, fill_empty, flip):
+ """
+ Create the wind barbs.
+
+ Parameters
+ ----------
+ u, v
+ Components of the vector in the x and y directions, respectively.
+
+ nflags, nbarbs, half_barb, empty_flag
+ Respectively, the number of flags, number of barbs, flag for
+ half a barb, and flag for empty barb, ostensibly obtained from
+ :meth:`_find_tails`.
+
+ length
+ The length of the barb staff in points.
+
+ pivot : {"tip", "middle"} or number
+ The point on the barb around which the entire barb should be
+ rotated. If a number, the start of the barb is shifted by that
+ many points from the origin.
+
+ sizes : dict
+ Coefficients specifying the ratio of a given feature to the length
+ of the barb. These features include:
+
+ - *spacing*: space between features (flags, full/half barbs).
+ - *height*: distance from shaft of top of a flag or full barb.
+ - *width*: width of a flag, twice the width of a full barb.
+ - *emptybarb*: radius of the circle used for low magnitudes.
+
+ fill_empty : bool
+ Whether the circle representing an empty barb should be filled or
+ not (this changes the drawing of the polygon).
+
+ flip : list of bool
+ Whether the features should be flipped to the other side of the
+ barb (useful for winds in the southern hemisphere).
+
+ Returns
+ -------
+ list of arrays of vertices
+ Polygon vertices for each of the wind barbs. These polygons have
+ been rotated to properly align with the vector direction.
+ """
+
+ # These control the spacing and size of barb elements relative to the
+ # length of the shaft
+ spacing = length * sizes.get('spacing', 0.125)
+ full_height = length * sizes.get('height', 0.4)
+ full_width = length * sizes.get('width', 0.25)
+ empty_rad = length * sizes.get('emptybarb', 0.15)
+
+ # Controls y point where to pivot the barb.
+ pivot_points = dict(tip=0.0, middle=-length / 2.)
+
+ endx = 0.0
+ try:
+ endy = float(pivot)
+ except ValueError:
+ endy = pivot_points[pivot.lower()]
+
+ # Get the appropriate angle for the vector components. The offset is
+ # due to the way the barb is initially drawn, going down the y-axis.
+ # This makes sense in a meteorological mode of thinking since there 0
+ # degrees corresponds to north (the y-axis traditionally)
+ angles = -(ma.arctan2(v, u) + np.pi / 2)
+
+ # Used for low magnitude. We just get the vertices, so if we make it
+ # out here, it can be reused. The center set here should put the
+ # center of the circle at the location(offset), rather than at the
+ # same point as the barb pivot; this seems more sensible.
+ circ = CirclePolygon((0, 0), radius=empty_rad).get_verts()
+ if fill_empty:
+ empty_barb = circ
+ else:
+ # If we don't want the empty one filled, we make a degenerate
+ # polygon that wraps back over itself
+ empty_barb = np.concatenate((circ, circ[::-1]))
+
+ barb_list = []
+ for index, angle in np.ndenumerate(angles):
+ # If the vector magnitude is too weak to draw anything, plot an
+ # empty circle instead
+ if empty_flag[index]:
+ # We can skip the transform since the circle has no preferred
+ # orientation
+ barb_list.append(empty_barb)
+ continue
+
+ poly_verts = [(endx, endy)]
+ offset = length
+
+ # Handle if this barb should be flipped
+ barb_height = -full_height if flip[index] else full_height
+
+ # Add vertices for each flag
+ for i in range(nflags[index]):
+ # The spacing that works for the barbs is a little to much for
+ # the flags, but this only occurs when we have more than 1
+ # flag.
+ if offset != length:
+ offset += spacing / 2.
+ poly_verts.extend(
+ [[endx, endy + offset],
+ [endx + barb_height, endy - full_width / 2 + offset],
+ [endx, endy - full_width + offset]])
+
+ offset -= full_width + spacing
+
+ # Add vertices for each barb. These really are lines, but works
+ # great adding 3 vertices that basically pull the polygon out and
+ # back down the line
+ for i in range(nbarbs[index]):
+ poly_verts.extend(
+ [(endx, endy + offset),
+ (endx + barb_height, endy + offset + full_width / 2),
+ (endx, endy + offset)])
+
+ offset -= spacing
+
+ # Add the vertices for half a barb, if needed
+ if half_barb[index]:
+ # If the half barb is the first on the staff, traditionally it
+ # is offset from the end to make it easy to distinguish from a
+ # barb with a full one
+ if offset == length:
+ poly_verts.append((endx, endy + offset))
+ offset -= 1.5 * spacing
+ poly_verts.extend(
+ [(endx, endy + offset),
+ (endx + barb_height / 2, endy + offset + full_width / 4),
+ (endx, endy + offset)])
+
+ # Rotate the barb according the angle. Making the barb first and
+ # then rotating it made the math for drawing the barb really easy.
+ # Also, the transform framework makes doing the rotation simple.
+ poly_verts = transforms.Affine2D().rotate(-angle).transform(
+ poly_verts)
+ barb_list.append(poly_verts)
+
+ return barb_list
+
+ def set_UVC(self, U, V, C=None):
+ # We need to ensure we have a copy, not a reference to an array that
+ # might change before draw().
+ self.u = ma.masked_invalid(U, copy=True).ravel()
+ self.v = ma.masked_invalid(V, copy=True).ravel()
+
+ # Flip needs to have the same number of entries as everything else.
+ # Use broadcast_to to avoid a bloated array of identical values.
+ # (can't rely on actual broadcasting)
+ if len(self.flip) == 1:
+ flip = np.broadcast_to(self.flip, self.u.shape)
+ else:
+ flip = self.flip
+
+ if C is not None:
+ c = ma.masked_invalid(C, copy=True).ravel()
+ x, y, u, v, c, flip = cbook.delete_masked_points(
+ self.x.ravel(), self.y.ravel(), self.u, self.v, c,
+ flip.ravel())
+ _check_consistent_shapes(x, y, u, v, c, flip)
+ else:
+ x, y, u, v, flip = cbook.delete_masked_points(
+ self.x.ravel(), self.y.ravel(), self.u, self.v, flip.ravel())
+ _check_consistent_shapes(x, y, u, v, flip)
+
+ magnitude = np.hypot(u, v)
+ flags, barbs, halves, empty = self._find_tails(
+ magnitude, self.rounding, **self.barb_increments)
+
+ # Get the vertices for each of the barbs
+
+ plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty,
+ self._length, self._pivot, self.sizes,
+ self.fill_empty, flip)
+ self.set_verts(plot_barbs)
+
+ # Set the color array
+ if C is not None:
+ self.set_array(c)
+
+ # Update the offsets in case the masked data changed
+ xy = np.column_stack((x, y))
+ self._offsets = xy
+ self.stale = True
+
+ def set_offsets(self, xy):
+ """
+ Set the offsets for the barb polygons. This saves the offsets passed
+ in and masks them as appropriate for the existing U/V data.
+
+ Parameters
+ ----------
+ xy : sequence of pairs of floats
+ """
+ self.x = xy[:, 0]
+ self.y = xy[:, 1]
+ x, y, u, v = cbook.delete_masked_points(
+ self.x.ravel(), self.y.ravel(), self.u, self.v)
+ _check_consistent_shapes(x, y, u, v)
+ xy = np.column_stack((x, y))
+ super().set_offsets(xy)
+ self.stale = True
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/scale.py b/llava_video/lib/python3.10/site-packages/matplotlib/scale.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccaaae6caf5dcbd21959bd13f017d30d14a14a6b
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/scale.py
@@ -0,0 +1,748 @@
+"""
+Scales define the distribution of data values on an axis, e.g. a log scaling.
+They are defined as subclasses of `ScaleBase`.
+
+See also `.axes.Axes.set_xscale` and the scales examples in the documentation.
+
+See :doc:`/gallery/scales/custom_scale` for a full example of defining a custom
+scale.
+
+Matplotlib also supports non-separable transformations that operate on both
+`~.axis.Axis` at the same time. They are known as projections, and defined in
+`matplotlib.projections`.
+"""
+
+import inspect
+import textwrap
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring
+from matplotlib.ticker import (
+ NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
+ NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
+ SymmetricalLogLocator, AsinhLocator, LogitLocator)
+from matplotlib.transforms import Transform, IdentityTransform
+
+
+class ScaleBase:
+ """
+ The base class for all scales.
+
+ Scales are separable transformations, working on a single dimension.
+
+ Subclasses should override
+
+ :attr:`name`
+ The scale's name.
+ :meth:`get_transform`
+ A method returning a `.Transform`, which converts data coordinates to
+ scaled coordinates. This transform should be invertible, so that e.g.
+ mouse positions can be converted back to data coordinates.
+ :meth:`set_default_locators_and_formatters`
+ A method that sets default locators and formatters for an `~.axis.Axis`
+ that uses this scale.
+ :meth:`limit_range_for_scale`
+ An optional method that "fixes" the axis range to acceptable values,
+ e.g. restricting log-scaled axes to positive values.
+ """
+
+ def __init__(self, axis):
+ r"""
+ Construct a new scale.
+
+ Notes
+ -----
+ The following note is for scale implementers.
+
+ For back-compatibility reasons, scales take an `~matplotlib.axis.Axis`
+ object as first argument. However, this argument should not
+ be used: a single scale object should be usable by multiple
+ `~matplotlib.axis.Axis`\es at the same time.
+ """
+
+ def get_transform(self):
+ """
+ Return the `.Transform` object associated with this scale.
+ """
+ raise NotImplementedError()
+
+ def set_default_locators_and_formatters(self, axis):
+ """
+ Set the locators and formatters of *axis* to instances suitable for
+ this scale.
+ """
+ raise NotImplementedError()
+
+ def limit_range_for_scale(self, vmin, vmax, minpos):
+ """
+ Return the range *vmin*, *vmax*, restricted to the
+ domain supported by this scale (if any).
+
+ *minpos* should be the minimum positive value in the data.
+ This is used by log scales to determine a minimum value.
+ """
+ return vmin, vmax
+
+
+class LinearScale(ScaleBase):
+ """
+ The default linear scale.
+ """
+
+ name = 'linear'
+
+ def __init__(self, axis):
+ # This method is present only to prevent inheritance of the base class'
+ # constructor docstring, which would otherwise end up interpolated into
+ # the docstring of Axis.set_scale.
+ """
+ """ # noqa: D419
+
+ def set_default_locators_and_formatters(self, axis):
+ # docstring inherited
+ axis.set_major_locator(AutoLocator())
+ axis.set_major_formatter(ScalarFormatter())
+ axis.set_minor_formatter(NullFormatter())
+ # update the minor locator for x and y axis based on rcParams
+ if (axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or
+ axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']):
+ axis.set_minor_locator(AutoMinorLocator())
+ else:
+ axis.set_minor_locator(NullLocator())
+
+ def get_transform(self):
+ """
+ Return the transform for linear scaling, which is just the
+ `~matplotlib.transforms.IdentityTransform`.
+ """
+ return IdentityTransform()
+
+
+class FuncTransform(Transform):
+ """
+ A simple transform that takes and arbitrary function for the
+ forward and inverse transform.
+ """
+
+ input_dims = output_dims = 1
+
+ def __init__(self, forward, inverse):
+ """
+ Parameters
+ ----------
+ forward : callable
+ The forward function for the transform. This function must have
+ an inverse and, for best behavior, be monotonic.
+ It must have the signature::
+
+ def forward(values: array-like) -> array-like
+
+ inverse : callable
+ The inverse of the forward function. Signature as ``forward``.
+ """
+ super().__init__()
+ if callable(forward) and callable(inverse):
+ self._forward = forward
+ self._inverse = inverse
+ else:
+ raise ValueError('arguments to FuncTransform must be functions')
+
+ def transform_non_affine(self, values):
+ return self._forward(values)
+
+ def inverted(self):
+ return FuncTransform(self._inverse, self._forward)
+
+
+class FuncScale(ScaleBase):
+ """
+ Provide an arbitrary scale with user-supplied function for the axis.
+ """
+
+ name = 'function'
+
+ def __init__(self, axis, functions):
+ """
+ Parameters
+ ----------
+ axis : `~matplotlib.axis.Axis`
+ The axis for the scale.
+ functions : (callable, callable)
+ two-tuple of the forward and inverse functions for the scale.
+ The forward function must be monotonic.
+
+ Both functions must have the signature::
+
+ def forward(values: array-like) -> array-like
+ """
+ forward, inverse = functions
+ transform = FuncTransform(forward, inverse)
+ self._transform = transform
+
+ def get_transform(self):
+ """Return the `.FuncTransform` associated with this scale."""
+ return self._transform
+
+ def set_default_locators_and_formatters(self, axis):
+ # docstring inherited
+ axis.set_major_locator(AutoLocator())
+ axis.set_major_formatter(ScalarFormatter())
+ axis.set_minor_formatter(NullFormatter())
+ # update the minor locator for x and y axis based on rcParams
+ if (axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or
+ axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']):
+ axis.set_minor_locator(AutoMinorLocator())
+ else:
+ axis.set_minor_locator(NullLocator())
+
+
+class LogTransform(Transform):
+ input_dims = output_dims = 1
+
+ def __init__(self, base, nonpositive='clip'):
+ super().__init__()
+ if base <= 0 or base == 1:
+ raise ValueError('The log base cannot be <= 0 or == 1')
+ self.base = base
+ self._clip = _api.check_getitem(
+ {"clip": True, "mask": False}, nonpositive=nonpositive)
+
+ def __str__(self):
+ return "{}(base={}, nonpositive={!r})".format(
+ type(self).__name__, self.base, "clip" if self._clip else "mask")
+
+ def transform_non_affine(self, values):
+ # Ignore invalid values due to nans being passed to the transform.
+ with np.errstate(divide="ignore", invalid="ignore"):
+ log = {np.e: np.log, 2: np.log2, 10: np.log10}.get(self.base)
+ if log: # If possible, do everything in a single call to NumPy.
+ out = log(values)
+ else:
+ out = np.log(values)
+ out /= np.log(self.base)
+ if self._clip:
+ # SVG spec says that conforming viewers must support values up
+ # to 3.4e38 (C float); however experiments suggest that
+ # Inkscape (which uses cairo for rendering) runs into cairo's
+ # 24-bit limit (which is apparently shared by Agg).
+ # Ghostscript (used for pdf rendering appears to overflow even
+ # earlier, with the max value around 2 ** 15 for the tests to
+ # pass. On the other hand, in practice, we want to clip beyond
+ # np.log10(np.nextafter(0, 1)) ~ -323
+ # so 1000 seems safe.
+ out[values <= 0] = -1000
+ return out
+
+ def inverted(self):
+ return InvertedLogTransform(self.base)
+
+
+class InvertedLogTransform(Transform):
+ input_dims = output_dims = 1
+
+ def __init__(self, base):
+ super().__init__()
+ self.base = base
+
+ def __str__(self):
+ return f"{type(self).__name__}(base={self.base})"
+
+ def transform_non_affine(self, values):
+ return np.power(self.base, values)
+
+ def inverted(self):
+ return LogTransform(self.base)
+
+
+class LogScale(ScaleBase):
+ """
+ A standard logarithmic scale. Care is taken to only plot positive values.
+ """
+ name = 'log'
+
+ def __init__(self, axis, *, base=10, subs=None, nonpositive="clip"):
+ """
+ Parameters
+ ----------
+ axis : `~matplotlib.axis.Axis`
+ The axis for the scale.
+ base : float, default: 10
+ The base of the logarithm.
+ nonpositive : {'clip', 'mask'}, default: 'clip'
+ Determines the behavior for non-positive values. They can either
+ be masked as invalid, or clipped to a very small positive number.
+ subs : sequence of int, default: None
+ Where to place the subticks between each major tick. For example,
+ in a log10 scale, ``[2, 3, 4, 5, 6, 7, 8, 9]`` will place 8
+ logarithmically spaced minor ticks between each major tick.
+ """
+ self._transform = LogTransform(base, nonpositive)
+ self.subs = subs
+
+ base = property(lambda self: self._transform.base)
+
+ def set_default_locators_and_formatters(self, axis):
+ # docstring inherited
+ axis.set_major_locator(LogLocator(self.base))
+ axis.set_major_formatter(LogFormatterSciNotation(self.base))
+ axis.set_minor_locator(LogLocator(self.base, self.subs))
+ axis.set_minor_formatter(
+ LogFormatterSciNotation(self.base,
+ labelOnlyBase=(self.subs is not None)))
+
+ def get_transform(self):
+ """Return the `.LogTransform` associated with this scale."""
+ return self._transform
+
+ def limit_range_for_scale(self, vmin, vmax, minpos):
+ """Limit the domain to positive values."""
+ if not np.isfinite(minpos):
+ minpos = 1e-300 # Should rarely (if ever) have a visible effect.
+
+ return (minpos if vmin <= 0 else vmin,
+ minpos if vmax <= 0 else vmax)
+
+
+class FuncScaleLog(LogScale):
+ """
+ Provide an arbitrary scale with user-supplied function for the axis and
+ then put on a logarithmic axes.
+ """
+
+ name = 'functionlog'
+
+ def __init__(self, axis, functions, base=10):
+ """
+ Parameters
+ ----------
+ axis : `~matplotlib.axis.Axis`
+ The axis for the scale.
+ functions : (callable, callable)
+ two-tuple of the forward and inverse functions for the scale.
+ The forward function must be monotonic.
+
+ Both functions must have the signature::
+
+ def forward(values: array-like) -> array-like
+
+ base : float, default: 10
+ Logarithmic base of the scale.
+ """
+ forward, inverse = functions
+ self.subs = None
+ self._transform = FuncTransform(forward, inverse) + LogTransform(base)
+
+ @property
+ def base(self):
+ return self._transform._b.base # Base of the LogTransform.
+
+ def get_transform(self):
+ """Return the `.Transform` associated with this scale."""
+ return self._transform
+
+
+class SymmetricalLogTransform(Transform):
+ input_dims = output_dims = 1
+
+ def __init__(self, base, linthresh, linscale):
+ super().__init__()
+ if base <= 1.0:
+ raise ValueError("'base' must be larger than 1")
+ if linthresh <= 0.0:
+ raise ValueError("'linthresh' must be positive")
+ if linscale <= 0.0:
+ raise ValueError("'linscale' must be positive")
+ self.base = base
+ self.linthresh = linthresh
+ self.linscale = linscale
+ self._linscale_adj = (linscale / (1.0 - self.base ** -1))
+ self._log_base = np.log(base)
+
+ def transform_non_affine(self, values):
+ abs_a = np.abs(values)
+ with np.errstate(divide="ignore", invalid="ignore"):
+ out = np.sign(values) * self.linthresh * (
+ self._linscale_adj +
+ np.log(abs_a / self.linthresh) / self._log_base)
+ inside = abs_a <= self.linthresh
+ out[inside] = values[inside] * self._linscale_adj
+ return out
+
+ def inverted(self):
+ return InvertedSymmetricalLogTransform(self.base, self.linthresh,
+ self.linscale)
+
+
+class InvertedSymmetricalLogTransform(Transform):
+ input_dims = output_dims = 1
+
+ def __init__(self, base, linthresh, linscale):
+ super().__init__()
+ symlog = SymmetricalLogTransform(base, linthresh, linscale)
+ self.base = base
+ self.linthresh = linthresh
+ self.invlinthresh = symlog.transform(linthresh)
+ self.linscale = linscale
+ self._linscale_adj = (linscale / (1.0 - self.base ** -1))
+
+ def transform_non_affine(self, values):
+ abs_a = np.abs(values)
+ with np.errstate(divide="ignore", invalid="ignore"):
+ out = np.sign(values) * self.linthresh * (
+ np.power(self.base,
+ abs_a / self.linthresh - self._linscale_adj))
+ inside = abs_a <= self.invlinthresh
+ out[inside] = values[inside] / self._linscale_adj
+ return out
+
+ def inverted(self):
+ return SymmetricalLogTransform(self.base,
+ self.linthresh, self.linscale)
+
+
+class SymmetricalLogScale(ScaleBase):
+ """
+ The symmetrical logarithmic scale is logarithmic in both the
+ positive and negative directions from the origin.
+
+ Since the values close to zero tend toward infinity, there is a
+ need to have a range around zero that is linear. The parameter
+ *linthresh* allows the user to specify the size of this range
+ (-*linthresh*, *linthresh*).
+
+ Parameters
+ ----------
+ base : float, default: 10
+ The base of the logarithm.
+
+ linthresh : float, default: 2
+ Defines the range ``(-x, x)``, within which the plot is linear.
+ This avoids having the plot go to infinity around zero.
+
+ subs : sequence of int
+ Where to place the subticks between each major tick.
+ For example, in a log10 scale: ``[2, 3, 4, 5, 6, 7, 8, 9]`` will place
+ 8 logarithmically spaced minor ticks between each major tick.
+
+ linscale : float, optional
+ This allows the linear range ``(-linthresh, linthresh)`` to be
+ stretched relative to the logarithmic range. Its value is the number of
+ decades to use for each half of the linear range. For example, when
+ *linscale* == 1.0 (the default), the space used for the positive and
+ negative halves of the linear range will be equal to one decade in
+ the logarithmic range.
+ """
+ name = 'symlog'
+
+ def __init__(self, axis, *, base=10, linthresh=2, subs=None, linscale=1):
+ self._transform = SymmetricalLogTransform(base, linthresh, linscale)
+ self.subs = subs
+
+ base = property(lambda self: self._transform.base)
+ linthresh = property(lambda self: self._transform.linthresh)
+ linscale = property(lambda self: self._transform.linscale)
+
+ def set_default_locators_and_formatters(self, axis):
+ # docstring inherited
+ axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
+ axis.set_major_formatter(LogFormatterSciNotation(self.base))
+ axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(),
+ self.subs))
+ axis.set_minor_formatter(NullFormatter())
+
+ def get_transform(self):
+ """Return the `.SymmetricalLogTransform` associated with this scale."""
+ return self._transform
+
+
+class AsinhTransform(Transform):
+ """Inverse hyperbolic-sine transformation used by `.AsinhScale`"""
+ input_dims = output_dims = 1
+
+ def __init__(self, linear_width):
+ super().__init__()
+ if linear_width <= 0.0:
+ raise ValueError("Scale parameter 'linear_width' " +
+ "must be strictly positive")
+ self.linear_width = linear_width
+
+ def transform_non_affine(self, values):
+ return self.linear_width * np.arcsinh(values / self.linear_width)
+
+ def inverted(self):
+ return InvertedAsinhTransform(self.linear_width)
+
+
+class InvertedAsinhTransform(Transform):
+ """Hyperbolic sine transformation used by `.AsinhScale`"""
+ input_dims = output_dims = 1
+
+ def __init__(self, linear_width):
+ super().__init__()
+ self.linear_width = linear_width
+
+ def transform_non_affine(self, values):
+ return self.linear_width * np.sinh(values / self.linear_width)
+
+ def inverted(self):
+ return AsinhTransform(self.linear_width)
+
+
+class AsinhScale(ScaleBase):
+ """
+ A quasi-logarithmic scale based on the inverse hyperbolic sine (asinh)
+
+ For values close to zero, this is essentially a linear scale,
+ but for large magnitude values (either positive or negative)
+ it is asymptotically logarithmic. The transition between these
+ linear and logarithmic regimes is smooth, and has no discontinuities
+ in the function gradient in contrast to
+ the `.SymmetricalLogScale` ("symlog") scale.
+
+ Specifically, the transformation of an axis coordinate :math:`a` is
+ :math:`a \\rightarrow a_0 \\sinh^{-1} (a / a_0)` where :math:`a_0`
+ is the effective width of the linear region of the transformation.
+ In that region, the transformation is
+ :math:`a \\rightarrow a + \\mathcal{O}(a^3)`.
+ For large values of :math:`a` the transformation behaves as
+ :math:`a \\rightarrow a_0 \\, \\mathrm{sgn}(a) \\ln |a| + \\mathcal{O}(1)`.
+
+ .. note::
+
+ This API is provisional and may be revised in the future
+ based on early user feedback.
+ """
+
+ name = 'asinh'
+
+ auto_tick_multipliers = {
+ 3: (2, ),
+ 4: (2, ),
+ 5: (2, ),
+ 8: (2, 4),
+ 10: (2, 5),
+ 16: (2, 4, 8),
+ 64: (4, 16),
+ 1024: (256, 512)
+ }
+
+ def __init__(self, axis, *, linear_width=1.0,
+ base=10, subs='auto', **kwargs):
+ """
+ Parameters
+ ----------
+ linear_width : float, default: 1
+ The scale parameter (elsewhere referred to as :math:`a_0`)
+ defining the extent of the quasi-linear region,
+ and the coordinate values beyond which the transformation
+ becomes asymptotically logarithmic.
+ base : int, default: 10
+ The number base used for rounding tick locations
+ on a logarithmic scale. If this is less than one,
+ then rounding is to the nearest integer multiple
+ of powers of ten.
+ subs : sequence of int
+ Multiples of the number base used for minor ticks.
+ If set to 'auto', this will use built-in defaults,
+ e.g. (2, 5) for base=10.
+ """
+ super().__init__(axis)
+ self._transform = AsinhTransform(linear_width)
+ self._base = int(base)
+ if subs == 'auto':
+ self._subs = self.auto_tick_multipliers.get(self._base)
+ else:
+ self._subs = subs
+
+ linear_width = property(lambda self: self._transform.linear_width)
+
+ def get_transform(self):
+ return self._transform
+
+ def set_default_locators_and_formatters(self, axis):
+ axis.set(major_locator=AsinhLocator(self.linear_width,
+ base=self._base),
+ minor_locator=AsinhLocator(self.linear_width,
+ base=self._base,
+ subs=self._subs),
+ minor_formatter=NullFormatter())
+ if self._base > 1:
+ axis.set_major_formatter(LogFormatterSciNotation(self._base))
+ else:
+ axis.set_major_formatter('{x:.3g}')
+
+
+class LogitTransform(Transform):
+ input_dims = output_dims = 1
+
+ def __init__(self, nonpositive='mask'):
+ super().__init__()
+ _api.check_in_list(['mask', 'clip'], nonpositive=nonpositive)
+ self._nonpositive = nonpositive
+ self._clip = {"clip": True, "mask": False}[nonpositive]
+
+ def transform_non_affine(self, values):
+ """logit transform (base 10), masked or clipped"""
+ with np.errstate(divide="ignore", invalid="ignore"):
+ out = np.log10(values / (1 - values))
+ if self._clip: # See LogTransform for choice of clip value.
+ out[values <= 0] = -1000
+ out[1 <= values] = 1000
+ return out
+
+ def inverted(self):
+ return LogisticTransform(self._nonpositive)
+
+ def __str__(self):
+ return f"{type(self).__name__}({self._nonpositive!r})"
+
+
+class LogisticTransform(Transform):
+ input_dims = output_dims = 1
+
+ def __init__(self, nonpositive='mask'):
+ super().__init__()
+ self._nonpositive = nonpositive
+
+ def transform_non_affine(self, values):
+ """logistic transform (base 10)"""
+ return 1.0 / (1 + 10**(-values))
+
+ def inverted(self):
+ return LogitTransform(self._nonpositive)
+
+ def __str__(self):
+ return f"{type(self).__name__}({self._nonpositive!r})"
+
+
+class LogitScale(ScaleBase):
+ """
+ Logit scale for data between zero and one, both excluded.
+
+ This scale is similar to a log scale close to zero and to one, and almost
+ linear around 0.5. It maps the interval ]0, 1[ onto ]-infty, +infty[.
+ """
+ name = 'logit'
+
+ def __init__(self, axis, nonpositive='mask', *,
+ one_half=r"\frac{1}{2}", use_overline=False):
+ r"""
+ Parameters
+ ----------
+ axis : `~matplotlib.axis.Axis`
+ Currently unused.
+ nonpositive : {'mask', 'clip'}
+ Determines the behavior for values beyond the open interval ]0, 1[.
+ They can either be masked as invalid, or clipped to a number very
+ close to 0 or 1.
+ use_overline : bool, default: False
+ Indicate the usage of survival notation (\overline{x}) in place of
+ standard notation (1-x) for probability close to one.
+ one_half : str, default: r"\frac{1}{2}"
+ The string used for ticks formatter to represent 1/2.
+ """
+ self._transform = LogitTransform(nonpositive)
+ self._use_overline = use_overline
+ self._one_half = one_half
+
+ def get_transform(self):
+ """Return the `.LogitTransform` associated with this scale."""
+ return self._transform
+
+ def set_default_locators_and_formatters(self, axis):
+ # docstring inherited
+ # ..., 0.01, 0.1, 0.5, 0.9, 0.99, ...
+ axis.set_major_locator(LogitLocator())
+ axis.set_major_formatter(
+ LogitFormatter(
+ one_half=self._one_half,
+ use_overline=self._use_overline
+ )
+ )
+ axis.set_minor_locator(LogitLocator(minor=True))
+ axis.set_minor_formatter(
+ LogitFormatter(
+ minor=True,
+ one_half=self._one_half,
+ use_overline=self._use_overline
+ )
+ )
+
+ def limit_range_for_scale(self, vmin, vmax, minpos):
+ """
+ Limit the domain to values between 0 and 1 (excluded).
+ """
+ if not np.isfinite(minpos):
+ minpos = 1e-7 # Should rarely (if ever) have a visible effect.
+ return (minpos if vmin <= 0 else vmin,
+ 1 - minpos if vmax >= 1 else vmax)
+
+
+_scale_mapping = {
+ 'linear': LinearScale,
+ 'log': LogScale,
+ 'symlog': SymmetricalLogScale,
+ 'asinh': AsinhScale,
+ 'logit': LogitScale,
+ 'function': FuncScale,
+ 'functionlog': FuncScaleLog,
+ }
+
+
+def get_scale_names():
+ """Return the names of the available scales."""
+ return sorted(_scale_mapping)
+
+
+def scale_factory(scale, axis, **kwargs):
+ """
+ Return a scale class by name.
+
+ Parameters
+ ----------
+ scale : {%(names)s}
+ axis : `~matplotlib.axis.Axis`
+ """
+ scale_cls = _api.check_getitem(_scale_mapping, scale=scale)
+ return scale_cls(axis, **kwargs)
+
+
+if scale_factory.__doc__:
+ scale_factory.__doc__ = scale_factory.__doc__ % {
+ "names": ", ".join(map(repr, get_scale_names()))}
+
+
+def register_scale(scale_class):
+ """
+ Register a new kind of scale.
+
+ Parameters
+ ----------
+ scale_class : subclass of `ScaleBase`
+ The scale to register.
+ """
+ _scale_mapping[scale_class.name] = scale_class
+
+
+def _get_scale_docs():
+ """
+ Helper function for generating docstrings related to scales.
+ """
+ docs = []
+ for name, scale_class in _scale_mapping.items():
+ docstring = inspect.getdoc(scale_class.__init__) or ""
+ docs.extend([
+ f" {name!r}",
+ "",
+ textwrap.indent(docstring, " " * 8),
+ ""
+ ])
+ return "\n".join(docs)
+
+
+_docstring.interpd.register(
+ scale_type='{%s}' % ', '.join([repr(x) for x in get_scale_names()]),
+ scale_docs=_get_scale_docs().rstrip(),
+ )
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/spines.py b/llava_video/lib/python3.10/site-packages/matplotlib/spines.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e77a393f2a28ff9fe976292f0062a6cc7e5adf3
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/spines.py
@@ -0,0 +1,596 @@
+from collections.abc import MutableMapping
+import functools
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring
+from matplotlib.artist import allow_rasterization
+import matplotlib.transforms as mtransforms
+import matplotlib.patches as mpatches
+import matplotlib.path as mpath
+
+
+class Spine(mpatches.Patch):
+ """
+ An axis spine -- the line noting the data area boundaries.
+
+ Spines are the lines connecting the axis tick marks and noting the
+ boundaries of the data area. They can be placed at arbitrary
+ positions. See `~.Spine.set_position` for more information.
+
+ The default position is ``('outward', 0)``.
+
+ Spines are subclasses of `.Patch`, and inherit much of their behavior.
+
+ Spines draw a line, a circle, or an arc depending on if
+ `~.Spine.set_patch_line`, `~.Spine.set_patch_circle`, or
+ `~.Spine.set_patch_arc` has been called. Line-like is the default.
+
+ For examples see :ref:`spines_examples`.
+ """
+ def __str__(self):
+ return "Spine"
+
+ @_docstring.interpd
+ def __init__(self, axes, spine_type, path, **kwargs):
+ """
+ Parameters
+ ----------
+ axes : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` instance containing the spine.
+ spine_type : str
+ The spine type.
+ path : `~matplotlib.path.Path`
+ The `.Path` instance used to draw the spine.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self.axes = axes
+ self.set_figure(self.axes.get_figure(root=False))
+ self.spine_type = spine_type
+ self.set_facecolor('none')
+ self.set_edgecolor(mpl.rcParams['axes.edgecolor'])
+ self.set_linewidth(mpl.rcParams['axes.linewidth'])
+ self.set_capstyle('projecting')
+ self.axis = None
+
+ self.set_zorder(2.5)
+ self.set_transform(self.axes.transData) # default transform
+
+ self._bounds = None # default bounds
+
+ # Defer initial position determination. (Not much support for
+ # non-rectangular axes is currently implemented, and this lets
+ # them pass through the spines machinery without errors.)
+ self._position = None
+ _api.check_isinstance(mpath.Path, path=path)
+ self._path = path
+
+ # To support drawing both linear and circular spines, this
+ # class implements Patch behavior three ways. If
+ # self._patch_type == 'line', behave like a mpatches.PathPatch
+ # instance. If self._patch_type == 'circle', behave like a
+ # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
+ # a mpatches.Arc instance.
+ self._patch_type = 'line'
+
+ # Behavior copied from mpatches.Ellipse:
+ # Note: This cannot be calculated until this is added to an Axes
+ self._patch_transform = mtransforms.IdentityTransform()
+
+ def set_patch_arc(self, center, radius, theta1, theta2):
+ """Set the spine to be arc-like."""
+ self._patch_type = 'arc'
+ self._center = center
+ self._width = radius * 2
+ self._height = radius * 2
+ self._theta1 = theta1
+ self._theta2 = theta2
+ self._path = mpath.Path.arc(theta1, theta2)
+ # arc drawn on axes transform
+ self.set_transform(self.axes.transAxes)
+ self.stale = True
+
+ def set_patch_circle(self, center, radius):
+ """Set the spine to be circular."""
+ self._patch_type = 'circle'
+ self._center = center
+ self._width = radius * 2
+ self._height = radius * 2
+ # circle drawn on axes transform
+ self.set_transform(self.axes.transAxes)
+ self.stale = True
+
+ def set_patch_line(self):
+ """Set the spine to be linear."""
+ self._patch_type = 'line'
+ self.stale = True
+
+ # Behavior copied from mpatches.Ellipse:
+ def _recompute_transform(self):
+ """
+ Notes
+ -----
+ This cannot be called until after this has been added to an Axes,
+ otherwise unit conversion will fail. This makes it very important to
+ call the accessor method and not directly access the transformation
+ member variable.
+ """
+ assert self._patch_type in ('arc', 'circle')
+ center = (self.convert_xunits(self._center[0]),
+ self.convert_yunits(self._center[1]))
+ width = self.convert_xunits(self._width)
+ height = self.convert_yunits(self._height)
+ self._patch_transform = mtransforms.Affine2D() \
+ .scale(width * 0.5, height * 0.5) \
+ .translate(*center)
+
+ def get_patch_transform(self):
+ if self._patch_type in ('arc', 'circle'):
+ self._recompute_transform()
+ return self._patch_transform
+ else:
+ return super().get_patch_transform()
+
+ def get_window_extent(self, renderer=None):
+ """
+ Return the window extent of the spines in display space, including
+ padding for ticks (but not their labels)
+
+ See Also
+ --------
+ matplotlib.axes.Axes.get_tightbbox
+ matplotlib.axes.Axes.get_window_extent
+ """
+ # make sure the location is updated so that transforms etc are correct:
+ self._adjust_location()
+ bb = super().get_window_extent(renderer=renderer)
+ if self.axis is None or not self.axis.get_visible():
+ return bb
+ bboxes = [bb]
+ drawn_ticks = self.axis._update_ticks()
+
+ major_tick = next(iter({*drawn_ticks} & {*self.axis.majorTicks}), None)
+ minor_tick = next(iter({*drawn_ticks} & {*self.axis.minorTicks}), None)
+ for tick in [major_tick, minor_tick]:
+ if tick is None:
+ continue
+ bb0 = bb.frozen()
+ tickl = tick._size
+ tickdir = tick._tickdir
+ if tickdir == 'out':
+ padout = 1
+ padin = 0
+ elif tickdir == 'in':
+ padout = 0
+ padin = 1
+ else:
+ padout = 0.5
+ padin = 0.5
+ dpi = self.get_figure(root=True).dpi
+ padout = padout * tickl / 72 * dpi
+ padin = padin * tickl / 72 * dpi
+
+ if tick.tick1line.get_visible():
+ if self.spine_type == 'left':
+ bb0.x0 = bb0.x0 - padout
+ bb0.x1 = bb0.x1 + padin
+ elif self.spine_type == 'bottom':
+ bb0.y0 = bb0.y0 - padout
+ bb0.y1 = bb0.y1 + padin
+
+ if tick.tick2line.get_visible():
+ if self.spine_type == 'right':
+ bb0.x1 = bb0.x1 + padout
+ bb0.x0 = bb0.x0 - padin
+ elif self.spine_type == 'top':
+ bb0.y1 = bb0.y1 + padout
+ bb0.y0 = bb0.y0 - padout
+ bboxes.append(bb0)
+
+ return mtransforms.Bbox.union(bboxes)
+
+ def get_path(self):
+ return self._path
+
+ def _ensure_position_is_set(self):
+ if self._position is None:
+ # default position
+ self._position = ('outward', 0.0) # in points
+ self.set_position(self._position)
+
+ def register_axis(self, axis):
+ """
+ Register an axis.
+
+ An axis should be registered with its corresponding spine from
+ the Axes instance. This allows the spine to clear any axis
+ properties when needed.
+ """
+ self.axis = axis
+ self.stale = True
+
+ def clear(self):
+ """Clear the current spine."""
+ self._clear()
+ if self.axis is not None:
+ self.axis.clear()
+
+ def _clear(self):
+ """
+ Clear things directly related to the spine.
+
+ In this way it is possible to avoid clearing the Axis as well when calling
+ from library code where it is known that the Axis is cleared separately.
+ """
+ self._position = None # clear position
+
+ def _adjust_location(self):
+ """Automatically set spine bounds to the view interval."""
+
+ if self.spine_type == 'circle':
+ return
+
+ if self._bounds is not None:
+ low, high = self._bounds
+ elif self.spine_type in ('left', 'right'):
+ low, high = self.axes.viewLim.intervaly
+ elif self.spine_type in ('top', 'bottom'):
+ low, high = self.axes.viewLim.intervalx
+ else:
+ raise ValueError(f'unknown spine spine_type: {self.spine_type}')
+
+ if self._patch_type == 'arc':
+ if self.spine_type in ('bottom', 'top'):
+ try:
+ direction = self.axes.get_theta_direction()
+ except AttributeError:
+ direction = 1
+ try:
+ offset = self.axes.get_theta_offset()
+ except AttributeError:
+ offset = 0
+ low = low * direction + offset
+ high = high * direction + offset
+ if low > high:
+ low, high = high, low
+
+ self._path = mpath.Path.arc(np.rad2deg(low), np.rad2deg(high))
+
+ if self.spine_type == 'bottom':
+ rmin, rmax = self.axes.viewLim.intervaly
+ try:
+ rorigin = self.axes.get_rorigin()
+ except AttributeError:
+ rorigin = rmin
+ scaled_diameter = (rmin - rorigin) / (rmax - rorigin)
+ self._height = scaled_diameter
+ self._width = scaled_diameter
+
+ else:
+ raise ValueError('unable to set bounds for spine "%s"' %
+ self.spine_type)
+ else:
+ v1 = self._path.vertices
+ assert v1.shape == (2, 2), 'unexpected vertices shape'
+ if self.spine_type in ['left', 'right']:
+ v1[0, 1] = low
+ v1[1, 1] = high
+ elif self.spine_type in ['bottom', 'top']:
+ v1[0, 0] = low
+ v1[1, 0] = high
+ else:
+ raise ValueError('unable to set bounds for spine "%s"' %
+ self.spine_type)
+
+ @allow_rasterization
+ def draw(self, renderer):
+ self._adjust_location()
+ ret = super().draw(renderer)
+ self.stale = False
+ return ret
+
+ def set_position(self, position):
+ """
+ Set the position of the spine.
+
+ Spine position is specified by a 2 tuple of (position type,
+ amount). The position types are:
+
+ * 'outward': place the spine out from the data area by the specified
+ number of points. (Negative values place the spine inwards.)
+ * 'axes': place the spine at the specified Axes coordinate (0 to 1).
+ * 'data': place the spine at the specified data coordinate.
+
+ Additionally, shorthand notations define a special positions:
+
+ * 'center' -> ``('axes', 0.5)``
+ * 'zero' -> ``('data', 0.0)``
+
+ Examples
+ --------
+ :doc:`/gallery/spines/spine_placement_demo`
+ """
+ if position in ('center', 'zero'): # special positions
+ pass
+ else:
+ if len(position) != 2:
+ raise ValueError("position should be 'center' or 2-tuple")
+ if position[0] not in ['outward', 'axes', 'data']:
+ raise ValueError("position[0] should be one of 'outward', "
+ "'axes', or 'data' ")
+ self._position = position
+ self.set_transform(self.get_spine_transform())
+ if self.axis is not None:
+ self.axis.reset_ticks()
+ self.stale = True
+
+ def get_position(self):
+ """Return the spine position."""
+ self._ensure_position_is_set()
+ return self._position
+
+ def get_spine_transform(self):
+ """Return the spine transform."""
+ self._ensure_position_is_set()
+
+ position = self._position
+ if isinstance(position, str):
+ if position == 'center':
+ position = ('axes', 0.5)
+ elif position == 'zero':
+ position = ('data', 0)
+ assert len(position) == 2, 'position should be 2-tuple'
+ position_type, amount = position
+ _api.check_in_list(['axes', 'outward', 'data'],
+ position_type=position_type)
+ if self.spine_type in ['left', 'right']:
+ base_transform = self.axes.get_yaxis_transform(which='grid')
+ elif self.spine_type in ['top', 'bottom']:
+ base_transform = self.axes.get_xaxis_transform(which='grid')
+ else:
+ raise ValueError(f'unknown spine spine_type: {self.spine_type!r}')
+
+ if position_type == 'outward':
+ if amount == 0: # short circuit commonest case
+ return base_transform
+ else:
+ offset_vec = {'left': (-1, 0), 'right': (1, 0),
+ 'bottom': (0, -1), 'top': (0, 1),
+ }[self.spine_type]
+ # calculate x and y offset in dots
+ offset_dots = amount * np.array(offset_vec) / 72
+ return (base_transform
+ + mtransforms.ScaledTranslation(
+ *offset_dots, self.get_figure(root=False).dpi_scale_trans))
+ elif position_type == 'axes':
+ if self.spine_type in ['left', 'right']:
+ # keep y unchanged, fix x at amount
+ return (mtransforms.Affine2D.from_values(0, 0, 0, 1, amount, 0)
+ + base_transform)
+ elif self.spine_type in ['bottom', 'top']:
+ # keep x unchanged, fix y at amount
+ return (mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, amount)
+ + base_transform)
+ elif position_type == 'data':
+ if self.spine_type in ('right', 'top'):
+ # The right and top spines have a default position of 1 in
+ # axes coordinates. When specifying the position in data
+ # coordinates, we need to calculate the position relative to 0.
+ amount -= 1
+ if self.spine_type in ('left', 'right'):
+ return mtransforms.blended_transform_factory(
+ mtransforms.Affine2D().translate(amount, 0)
+ + self.axes.transData,
+ self.axes.transData)
+ elif self.spine_type in ('bottom', 'top'):
+ return mtransforms.blended_transform_factory(
+ self.axes.transData,
+ mtransforms.Affine2D().translate(0, amount)
+ + self.axes.transData)
+
+ def set_bounds(self, low=None, high=None):
+ """
+ Set the spine bounds.
+
+ Parameters
+ ----------
+ low : float or None, optional
+ The lower spine bound. Passing *None* leaves the limit unchanged.
+
+ The bounds may also be passed as the tuple (*low*, *high*) as the
+ first positional argument.
+
+ .. ACCEPTS: (low: float, high: float)
+
+ high : float or None, optional
+ The higher spine bound. Passing *None* leaves the limit unchanged.
+ """
+ if self.spine_type == 'circle':
+ raise ValueError(
+ 'set_bounds() method incompatible with circular spines')
+ if high is None and np.iterable(low):
+ low, high = low
+ old_low, old_high = self.get_bounds() or (None, None)
+ if low is None:
+ low = old_low
+ if high is None:
+ high = old_high
+ self._bounds = (low, high)
+ self.stale = True
+
+ def get_bounds(self):
+ """Get the bounds of the spine."""
+ return self._bounds
+
+ @classmethod
+ def linear_spine(cls, axes, spine_type, **kwargs):
+ """Create and return a linear `Spine`."""
+ # all values of 0.999 get replaced upon call to set_bounds()
+ if spine_type == 'left':
+ path = mpath.Path([(0.0, 0.999), (0.0, 0.999)])
+ elif spine_type == 'right':
+ path = mpath.Path([(1.0, 0.999), (1.0, 0.999)])
+ elif spine_type == 'bottom':
+ path = mpath.Path([(0.999, 0.0), (0.999, 0.0)])
+ elif spine_type == 'top':
+ path = mpath.Path([(0.999, 1.0), (0.999, 1.0)])
+ else:
+ raise ValueError('unable to make path for spine "%s"' % spine_type)
+ result = cls(axes, spine_type, path, **kwargs)
+ result.set_visible(mpl.rcParams[f'axes.spines.{spine_type}'])
+
+ return result
+
+ @classmethod
+ def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2,
+ **kwargs):
+ """Create and return an arc `Spine`."""
+ path = mpath.Path.arc(theta1, theta2)
+ result = cls(axes, spine_type, path, **kwargs)
+ result.set_patch_arc(center, radius, theta1, theta2)
+ return result
+
+ @classmethod
+ def circular_spine(cls, axes, center, radius, **kwargs):
+ """Create and return a circular `Spine`."""
+ path = mpath.Path.unit_circle()
+ spine_type = 'circle'
+ result = cls(axes, spine_type, path, **kwargs)
+ result.set_patch_circle(center, radius)
+ return result
+
+ def set_color(self, c):
+ """
+ Set the edgecolor.
+
+ Parameters
+ ----------
+ c : :mpltype:`color`
+
+ Notes
+ -----
+ This method does not modify the facecolor (which defaults to "none"),
+ unlike the `.Patch.set_color` method defined in the parent class. Use
+ `.Patch.set_facecolor` to set the facecolor.
+ """
+ self.set_edgecolor(c)
+ self.stale = True
+
+
+class SpinesProxy:
+ """
+ A proxy to broadcast ``set_*()`` and ``set()`` method calls to contained `.Spines`.
+
+ The proxy cannot be used for any other operations on its members.
+
+ The supported methods are determined dynamically based on the contained
+ spines. If not all spines support a given method, it's executed only on
+ the subset of spines that support it.
+ """
+ def __init__(self, spine_dict):
+ self._spine_dict = spine_dict
+
+ def __getattr__(self, name):
+ broadcast_targets = [spine for spine in self._spine_dict.values()
+ if hasattr(spine, name)]
+ if (name != 'set' and not name.startswith('set_')) or not broadcast_targets:
+ raise AttributeError(
+ f"'SpinesProxy' object has no attribute '{name}'")
+
+ def x(_targets, _funcname, *args, **kwargs):
+ for spine in _targets:
+ getattr(spine, _funcname)(*args, **kwargs)
+ x = functools.partial(x, broadcast_targets, name)
+ x.__doc__ = broadcast_targets[0].__doc__
+ return x
+
+ def __dir__(self):
+ names = []
+ for spine in self._spine_dict.values():
+ names.extend(name
+ for name in dir(spine) if name.startswith('set_'))
+ return list(sorted(set(names)))
+
+
+class Spines(MutableMapping):
+ r"""
+ The container of all `.Spine`\s in an Axes.
+
+ The interface is dict-like mapping names (e.g. 'left') to `.Spine` objects.
+ Additionally, it implements some pandas.Series-like features like accessing
+ elements by attribute::
+
+ spines['top'].set_visible(False)
+ spines.top.set_visible(False)
+
+ Multiple spines can be addressed simultaneously by passing a list::
+
+ spines[['top', 'right']].set_visible(False)
+
+ Use an open slice to address all spines::
+
+ spines[:].set_visible(False)
+
+ The latter two indexing methods will return a `SpinesProxy` that broadcasts all
+ ``set_*()`` and ``set()`` calls to its members, but cannot be used for any other
+ operation.
+ """
+ def __init__(self, **kwargs):
+ self._dict = kwargs
+
+ @classmethod
+ def from_dict(cls, d):
+ return cls(**d)
+
+ def __getstate__(self):
+ return self._dict
+
+ def __setstate__(self, state):
+ self.__init__(**state)
+
+ def __getattr__(self, name):
+ try:
+ return self._dict[name]
+ except KeyError:
+ raise AttributeError(
+ f"'Spines' object does not contain a '{name}' spine")
+
+ def __getitem__(self, key):
+ if isinstance(key, list):
+ unknown_keys = [k for k in key if k not in self._dict]
+ if unknown_keys:
+ raise KeyError(', '.join(unknown_keys))
+ return SpinesProxy({k: v for k, v in self._dict.items()
+ if k in key})
+ if isinstance(key, tuple):
+ raise ValueError('Multiple spines must be passed as a single list')
+ if isinstance(key, slice):
+ if key.start is None and key.stop is None and key.step is None:
+ return SpinesProxy(self._dict)
+ else:
+ raise ValueError(
+ 'Spines does not support slicing except for the fully '
+ 'open slice [:] to access all spines.')
+ return self._dict[key]
+
+ def __setitem__(self, key, value):
+ # TODO: Do we want to deprecate adding spines?
+ self._dict[key] = value
+
+ def __delitem__(self, key):
+ # TODO: Do we want to deprecate deleting spines?
+ del self._dict[key]
+
+ def __iter__(self):
+ return iter(self._dict)
+
+ def __len__(self):
+ return len(self._dict)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/spines.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/spines.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ff2a1a40bf947005692ccaf2b95977e57a1747b6
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/spines.pyi
@@ -0,0 +1,83 @@
+from collections.abc import Callable, Iterator, MutableMapping
+from typing import Literal, TypeVar, overload
+
+import matplotlib.patches as mpatches
+from matplotlib.axes import Axes
+from matplotlib.axis import Axis
+from matplotlib.path import Path
+from matplotlib.transforms import Transform
+from matplotlib.typing import ColorType
+
+class Spine(mpatches.Patch):
+ axes: Axes
+ spine_type: str
+ axis: Axis | None
+ def __init__(self, axes: Axes, spine_type: str, path: Path, **kwargs) -> None: ...
+ def set_patch_arc(
+ self, center: tuple[float, float], radius: float, theta1: float, theta2: float
+ ) -> None: ...
+ def set_patch_circle(self, center: tuple[float, float], radius: float) -> None: ...
+ def set_patch_line(self) -> None: ...
+ def get_patch_transform(self) -> Transform: ...
+ def get_path(self) -> Path: ...
+ def register_axis(self, axis: Axis) -> None: ...
+ def clear(self) -> None: ...
+ def set_position(
+ self,
+ position: Literal["center", "zero"]
+ | tuple[Literal["outward", "axes", "data"], float],
+ ) -> None: ...
+ def get_position(
+ self,
+ ) -> Literal["center", "zero"] | tuple[
+ Literal["outward", "axes", "data"], float
+ ]: ...
+ def get_spine_transform(self) -> Transform: ...
+ def set_bounds(self, low: float | None = ..., high: float | None = ...) -> None: ...
+ def get_bounds(self) -> tuple[float, float]: ...
+
+ _T = TypeVar("_T", bound=Spine)
+ @classmethod
+ def linear_spine(
+ cls: type[_T],
+ axes: Axes,
+ spine_type: Literal["left", "right", "bottom", "top"],
+ **kwargs
+ ) -> _T: ...
+ @classmethod
+ def arc_spine(
+ cls: type[_T],
+ axes: Axes,
+ spine_type: Literal["left", "right", "bottom", "top"],
+ center: tuple[float, float],
+ radius: float,
+ theta1: float,
+ theta2: float,
+ **kwargs
+ ) -> _T: ...
+ @classmethod
+ def circular_spine(
+ cls: type[_T], axes: Axes, center: tuple[float, float], radius: float, **kwargs
+ ) -> _T: ...
+ def set_color(self, c: ColorType | None) -> None: ...
+
+class SpinesProxy:
+ def __init__(self, spine_dict: dict[str, Spine]) -> None: ...
+ def __getattr__(self, name: str) -> Callable[..., None]: ...
+ def __dir__(self) -> list[str]: ...
+
+class Spines(MutableMapping[str, Spine]):
+ def __init__(self, **kwargs: Spine) -> None: ...
+ @classmethod
+ def from_dict(cls, d: dict[str, Spine]) -> Spines: ...
+ def __getattr__(self, name: str) -> Spine: ...
+ @overload
+ def __getitem__(self, key: str) -> Spine: ...
+ @overload
+ def __getitem__(self, key: list[str]) -> SpinesProxy: ...
+ @overload
+ def __getitem__(self, key: slice) -> SpinesProxy: ...
+ def __setitem__(self, key: str, value: Spine) -> None: ...
+ def __delitem__(self, key: str) -> None: ...
+ def __iter__(self) -> Iterator[str]: ...
+ def __len__(self) -> int: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/stackplot.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/stackplot.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..2981d449b56617dfb92840241998dafb73064f25
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/stackplot.pyi
@@ -0,0 +1,18 @@
+from matplotlib.axes import Axes
+from matplotlib.collections import PolyCollection
+
+from collections.abc import Iterable
+from typing import Literal
+from numpy.typing import ArrayLike
+from matplotlib.typing import ColorType
+
+def stackplot(
+ axes: Axes,
+ x: ArrayLike,
+ *args: ArrayLike,
+ labels: Iterable[str] = ...,
+ colors: Iterable[ColorType] | None = ...,
+ hatch: Iterable[str] | str | None = ...,
+ baseline: Literal["zero", "sym", "wiggle", "weighted_wiggle"] = ...,
+ **kwargs
+) -> list[PolyCollection]: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/streamplot.py b/llava_video/lib/python3.10/site-packages/matplotlib/streamplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..84f99732c709d25a0efb2518156ef213f3ee6a4d
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/streamplot.py
@@ -0,0 +1,712 @@
+"""
+Streamline plotting for 2D vector fields.
+
+"""
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, cm, patches
+import matplotlib.colors as mcolors
+import matplotlib.collections as mcollections
+import matplotlib.lines as mlines
+
+
+__all__ = ['streamplot']
+
+
+def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
+ cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
+ minlength=0.1, transform=None, zorder=None, start_points=None,
+ maxlength=4.0, integration_direction='both',
+ broken_streamlines=True):
+ """
+ Draw streamlines of a vector flow.
+
+ Parameters
+ ----------
+ x, y : 1D/2D arrays
+ Evenly spaced strictly increasing arrays to make a grid. If 2D, all
+ rows of *x* must be equal and all columns of *y* must be equal; i.e.,
+ they must be as if generated by ``np.meshgrid(x_1d, y_1d)``.
+ u, v : 2D arrays
+ *x* and *y*-velocities. The number of rows and columns must match
+ the length of *y* and *x*, respectively.
+ density : float or (float, float)
+ Controls the closeness of streamlines. When ``density = 1``, the domain
+ is divided into a 30x30 grid. *density* linearly scales this grid.
+ Each cell in the grid can have, at most, one traversing streamline.
+ For different densities in each direction, use a tuple
+ (density_x, density_y).
+ linewidth : float or 2D array
+ The width of the streamlines. With a 2D array the line width can be
+ varied across the grid. The array must have the same shape as *u*
+ and *v*.
+ color : :mpltype:`color` or 2D array
+ The streamline color. If given an array, its values are converted to
+ colors using *cmap* and *norm*. The array must have the same shape
+ as *u* and *v*.
+ cmap, norm
+ Data normalization and colormapping parameters for *color*; only used
+ if *color* is an array of floats. See `~.Axes.imshow` for a detailed
+ description.
+ arrowsize : float
+ Scaling factor for the arrow size.
+ arrowstyle : str
+ Arrow style specification.
+ See `~matplotlib.patches.FancyArrowPatch`.
+ minlength : float
+ Minimum length of streamline in axes coordinates.
+ start_points : (N, 2) array
+ Coordinates of starting points for the streamlines in data coordinates
+ (the same coordinates as the *x* and *y* arrays).
+ zorder : float
+ The zorder of the streamlines and arrows.
+ Artists with lower zorder values are drawn first.
+ maxlength : float
+ Maximum length of streamline in axes coordinates.
+ integration_direction : {'forward', 'backward', 'both'}, default: 'both'
+ Integrate the streamline in forward, backward or both directions.
+ data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+ broken_streamlines : boolean, default: True
+ If False, forces streamlines to continue until they
+ leave the plot domain. If True, they may be terminated if they
+ come too close to another streamline.
+
+ Returns
+ -------
+ StreamplotSet
+ Container object with attributes
+
+ - ``lines``: `.LineCollection` of streamlines
+
+ - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch`
+ objects representing the arrows half-way along streamlines.
+
+ This container will probably change in the future to allow changes
+ to the colormap, alpha, etc. for both lines and arrows, but these
+ changes should be backward compatible.
+ """
+ grid = Grid(x, y)
+ mask = StreamMask(density)
+ dmap = DomainMap(grid, mask)
+
+ if zorder is None:
+ zorder = mlines.Line2D.zorder
+
+ # default to data coordinates
+ if transform is None:
+ transform = axes.transData
+
+ if color is None:
+ color = axes._get_lines.get_next_color()
+
+ if linewidth is None:
+ linewidth = mpl.rcParams['lines.linewidth']
+
+ line_kw = {}
+ arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)
+
+ _api.check_in_list(['both', 'forward', 'backward'],
+ integration_direction=integration_direction)
+
+ if integration_direction == 'both':
+ maxlength /= 2.
+
+ use_multicolor_lines = isinstance(color, np.ndarray)
+ if use_multicolor_lines:
+ if color.shape != grid.shape:
+ raise ValueError("If 'color' is given, it must match the shape of "
+ "the (x, y) grid")
+ line_colors = [[]] # Empty entry allows concatenation of zero arrays.
+ color = np.ma.masked_invalid(color)
+ else:
+ line_kw['color'] = color
+ arrow_kw['color'] = color
+
+ if isinstance(linewidth, np.ndarray):
+ if linewidth.shape != grid.shape:
+ raise ValueError("If 'linewidth' is given, it must match the "
+ "shape of the (x, y) grid")
+ line_kw['linewidth'] = []
+ else:
+ line_kw['linewidth'] = linewidth
+ arrow_kw['linewidth'] = linewidth
+
+ line_kw['zorder'] = zorder
+ arrow_kw['zorder'] = zorder
+
+ # Sanity checks.
+ if u.shape != grid.shape or v.shape != grid.shape:
+ raise ValueError("'u' and 'v' must match the shape of the (x, y) grid")
+
+ u = np.ma.masked_invalid(u)
+ v = np.ma.masked_invalid(v)
+
+ integrate = _get_integrator(u, v, dmap, minlength, maxlength,
+ integration_direction)
+
+ trajectories = []
+ if start_points is None:
+ for xm, ym in _gen_starting_points(mask.shape):
+ if mask[ym, xm] == 0:
+ xg, yg = dmap.mask2grid(xm, ym)
+ t = integrate(xg, yg, broken_streamlines)
+ if t is not None:
+ trajectories.append(t)
+ else:
+ sp2 = np.asanyarray(start_points, dtype=float).copy()
+
+ # Check if start_points are outside the data boundaries
+ for xs, ys in sp2:
+ if not (grid.x_origin <= xs <= grid.x_origin + grid.width and
+ grid.y_origin <= ys <= grid.y_origin + grid.height):
+ raise ValueError(f"Starting point ({xs}, {ys}) outside of "
+ "data boundaries")
+
+ # Convert start_points from data to array coords
+ # Shift the seed points from the bottom left of the data so that
+ # data2grid works properly.
+ sp2[:, 0] -= grid.x_origin
+ sp2[:, 1] -= grid.y_origin
+
+ for xs, ys in sp2:
+ xg, yg = dmap.data2grid(xs, ys)
+ # Floating point issues can cause xg, yg to be slightly out of
+ # bounds for xs, ys on the upper boundaries. Because we have
+ # already checked that the starting points are within the original
+ # grid, clip the xg, yg to the grid to work around this issue
+ xg = np.clip(xg, 0, grid.nx - 1)
+ yg = np.clip(yg, 0, grid.ny - 1)
+
+ t = integrate(xg, yg, broken_streamlines)
+ if t is not None:
+ trajectories.append(t)
+
+ if use_multicolor_lines:
+ if norm is None:
+ norm = mcolors.Normalize(color.min(), color.max())
+ cmap = cm._ensure_cmap(cmap)
+
+ streamlines = []
+ arrows = []
+ for t in trajectories:
+ tgx, tgy = t.T
+ # Rescale from grid-coordinates to data-coordinates.
+ tx, ty = dmap.grid2data(tgx, tgy)
+ tx += grid.x_origin
+ ty += grid.y_origin
+
+ # Create multiple tiny segments if varying width or color is given
+ if isinstance(linewidth, np.ndarray) or use_multicolor_lines:
+ points = np.transpose([tx, ty]).reshape(-1, 1, 2)
+ streamlines.extend(np.hstack([points[:-1], points[1:]]))
+ else:
+ points = np.transpose([tx, ty])
+ streamlines.append(points)
+
+ # Add arrows halfway along each trajectory.
+ s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
+ n = np.searchsorted(s, s[-1] / 2.)
+ arrow_tail = (tx[n], ty[n])
+ arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
+
+ if isinstance(linewidth, np.ndarray):
+ line_widths = interpgrid(linewidth, tgx, tgy)[:-1]
+ line_kw['linewidth'].extend(line_widths)
+ arrow_kw['linewidth'] = line_widths[n]
+
+ if use_multicolor_lines:
+ color_values = interpgrid(color, tgx, tgy)[:-1]
+ line_colors.append(color_values)
+ arrow_kw['color'] = cmap(norm(color_values[n]))
+
+ p = patches.FancyArrowPatch(
+ arrow_tail, arrow_head, transform=transform, **arrow_kw)
+ arrows.append(p)
+
+ lc = mcollections.LineCollection(
+ streamlines, transform=transform, **line_kw)
+ lc.sticky_edges.x[:] = [grid.x_origin, grid.x_origin + grid.width]
+ lc.sticky_edges.y[:] = [grid.y_origin, grid.y_origin + grid.height]
+ if use_multicolor_lines:
+ lc.set_array(np.ma.hstack(line_colors))
+ lc.set_cmap(cmap)
+ lc.set_norm(norm)
+ axes.add_collection(lc)
+
+ ac = mcollections.PatchCollection(arrows)
+ # Adding the collection itself is broken; see #2341.
+ for p in arrows:
+ axes.add_patch(p)
+
+ axes.autoscale_view()
+ stream_container = StreamplotSet(lc, ac)
+ return stream_container
+
+
+class StreamplotSet:
+
+ def __init__(self, lines, arrows):
+ self.lines = lines
+ self.arrows = arrows
+
+
+# Coordinate definitions
+# ========================
+
+class DomainMap:
+ """
+ Map representing different coordinate systems.
+
+ Coordinate definitions:
+
+ * axes-coordinates goes from 0 to 1 in the domain.
+ * data-coordinates are specified by the input x-y coordinates.
+ * grid-coordinates goes from 0 to N and 0 to M for an N x M grid,
+ where N and M match the shape of the input data.
+ * mask-coordinates goes from 0 to N and 0 to M for an N x M mask,
+ where N and M are user-specified to control the density of streamlines.
+
+ This class also has methods for adding trajectories to the StreamMask.
+ Before adding a trajectory, run `start_trajectory` to keep track of regions
+ crossed by a given trajectory. Later, if you decide the trajectory is bad
+ (e.g., if the trajectory is very short) just call `undo_trajectory`.
+ """
+
+ def __init__(self, grid, mask):
+ self.grid = grid
+ self.mask = mask
+ # Constants for conversion between grid- and mask-coordinates
+ self.x_grid2mask = (mask.nx - 1) / (grid.nx - 1)
+ self.y_grid2mask = (mask.ny - 1) / (grid.ny - 1)
+
+ self.x_mask2grid = 1. / self.x_grid2mask
+ self.y_mask2grid = 1. / self.y_grid2mask
+
+ self.x_data2grid = 1. / grid.dx
+ self.y_data2grid = 1. / grid.dy
+
+ def grid2mask(self, xi, yi):
+ """Return nearest space in mask-coords from given grid-coords."""
+ return round(xi * self.x_grid2mask), round(yi * self.y_grid2mask)
+
+ def mask2grid(self, xm, ym):
+ return xm * self.x_mask2grid, ym * self.y_mask2grid
+
+ def data2grid(self, xd, yd):
+ return xd * self.x_data2grid, yd * self.y_data2grid
+
+ def grid2data(self, xg, yg):
+ return xg / self.x_data2grid, yg / self.y_data2grid
+
+ def start_trajectory(self, xg, yg, broken_streamlines=True):
+ xm, ym = self.grid2mask(xg, yg)
+ self.mask._start_trajectory(xm, ym, broken_streamlines)
+
+ def reset_start_point(self, xg, yg):
+ xm, ym = self.grid2mask(xg, yg)
+ self.mask._current_xy = (xm, ym)
+
+ def update_trajectory(self, xg, yg, broken_streamlines=True):
+ if not self.grid.within_grid(xg, yg):
+ raise InvalidIndexError
+ xm, ym = self.grid2mask(xg, yg)
+ self.mask._update_trajectory(xm, ym, broken_streamlines)
+
+ def undo_trajectory(self):
+ self.mask._undo_trajectory()
+
+
+class Grid:
+ """Grid of data."""
+ def __init__(self, x, y):
+
+ if np.ndim(x) == 1:
+ pass
+ elif np.ndim(x) == 2:
+ x_row = x[0]
+ if not np.allclose(x_row, x):
+ raise ValueError("The rows of 'x' must be equal")
+ x = x_row
+ else:
+ raise ValueError("'x' can have at maximum 2 dimensions")
+
+ if np.ndim(y) == 1:
+ pass
+ elif np.ndim(y) == 2:
+ yt = np.transpose(y) # Also works for nested lists.
+ y_col = yt[0]
+ if not np.allclose(y_col, yt):
+ raise ValueError("The columns of 'y' must be equal")
+ y = y_col
+ else:
+ raise ValueError("'y' can have at maximum 2 dimensions")
+
+ if not (np.diff(x) > 0).all():
+ raise ValueError("'x' must be strictly increasing")
+ if not (np.diff(y) > 0).all():
+ raise ValueError("'y' must be strictly increasing")
+
+ self.nx = len(x)
+ self.ny = len(y)
+
+ self.dx = x[1] - x[0]
+ self.dy = y[1] - y[0]
+
+ self.x_origin = x[0]
+ self.y_origin = y[0]
+
+ self.width = x[-1] - x[0]
+ self.height = y[-1] - y[0]
+
+ if not np.allclose(np.diff(x), self.width / (self.nx - 1)):
+ raise ValueError("'x' values must be equally spaced")
+ if not np.allclose(np.diff(y), self.height / (self.ny - 1)):
+ raise ValueError("'y' values must be equally spaced")
+
+ @property
+ def shape(self):
+ return self.ny, self.nx
+
+ def within_grid(self, xi, yi):
+ """Return whether (*xi*, *yi*) is a valid index of the grid."""
+ # Note that xi/yi can be floats; so, for example, we can't simply check
+ # `xi < self.nx` since *xi* can be `self.nx - 1 < xi < self.nx`
+ return 0 <= xi <= self.nx - 1 and 0 <= yi <= self.ny - 1
+
+
+class StreamMask:
+ """
+ Mask to keep track of discrete regions crossed by streamlines.
+
+ The resolution of this grid determines the approximate spacing between
+ trajectories. Streamlines are only allowed to pass through zeroed cells:
+ When a streamline enters a cell, that cell is set to 1, and no new
+ streamlines are allowed to enter.
+ """
+
+ def __init__(self, density):
+ try:
+ self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int)
+ except ValueError as err:
+ raise ValueError("'density' must be a scalar or be of length "
+ "2") from err
+ if self.nx < 0 or self.ny < 0:
+ raise ValueError("'density' must be positive")
+ self._mask = np.zeros((self.ny, self.nx))
+ self.shape = self._mask.shape
+
+ self._current_xy = None
+
+ def __getitem__(self, args):
+ return self._mask[args]
+
+ def _start_trajectory(self, xm, ym, broken_streamlines=True):
+ """Start recording streamline trajectory"""
+ self._traj = []
+ self._update_trajectory(xm, ym, broken_streamlines)
+
+ def _undo_trajectory(self):
+ """Remove current trajectory from mask"""
+ for t in self._traj:
+ self._mask[t] = 0
+
+ def _update_trajectory(self, xm, ym, broken_streamlines=True):
+ """
+ Update current trajectory position in mask.
+
+ If the new position has already been filled, raise `InvalidIndexError`.
+ """
+ if self._current_xy != (xm, ym):
+ if self[ym, xm] == 0:
+ self._traj.append((ym, xm))
+ self._mask[ym, xm] = 1
+ self._current_xy = (xm, ym)
+ else:
+ if broken_streamlines:
+ raise InvalidIndexError
+ else:
+ pass
+
+
+class InvalidIndexError(Exception):
+ pass
+
+
+class TerminateTrajectory(Exception):
+ pass
+
+
+# Integrator definitions
+# =======================
+
+def _get_integrator(u, v, dmap, minlength, maxlength, integration_direction):
+
+ # rescale velocity onto grid-coordinates for integrations.
+ u, v = dmap.data2grid(u, v)
+
+ # speed (path length) will be in axes-coordinates
+ u_ax = u / (dmap.grid.nx - 1)
+ v_ax = v / (dmap.grid.ny - 1)
+ speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2)
+
+ def forward_time(xi, yi):
+ if not dmap.grid.within_grid(xi, yi):
+ raise OutOfBounds
+ ds_dt = interpgrid(speed, xi, yi)
+ if ds_dt == 0:
+ raise TerminateTrajectory()
+ dt_ds = 1. / ds_dt
+ ui = interpgrid(u, xi, yi)
+ vi = interpgrid(v, xi, yi)
+ return ui * dt_ds, vi * dt_ds
+
+ def backward_time(xi, yi):
+ dxi, dyi = forward_time(xi, yi)
+ return -dxi, -dyi
+
+ def integrate(x0, y0, broken_streamlines=True):
+ """
+ Return x, y grid-coordinates of trajectory based on starting point.
+
+ Integrate both forward and backward in time from starting point in
+ grid coordinates.
+
+ Integration is terminated when a trajectory reaches a domain boundary
+ or when it crosses into an already occupied cell in the StreamMask. The
+ resulting trajectory is None if it is shorter than `minlength`.
+ """
+
+ stotal, xy_traj = 0., []
+
+ try:
+ dmap.start_trajectory(x0, y0, broken_streamlines)
+ except InvalidIndexError:
+ return None
+ if integration_direction in ['both', 'backward']:
+ s, xyt = _integrate_rk12(x0, y0, dmap, backward_time, maxlength,
+ broken_streamlines)
+ stotal += s
+ xy_traj += xyt[::-1]
+
+ if integration_direction in ['both', 'forward']:
+ dmap.reset_start_point(x0, y0)
+ s, xyt = _integrate_rk12(x0, y0, dmap, forward_time, maxlength,
+ broken_streamlines)
+ stotal += s
+ xy_traj += xyt[1:]
+
+ if stotal > minlength:
+ return np.broadcast_arrays(xy_traj, np.empty((1, 2)))[0]
+ else: # reject short trajectories
+ dmap.undo_trajectory()
+ return None
+
+ return integrate
+
+
+class OutOfBounds(IndexError):
+ pass
+
+
+def _integrate_rk12(x0, y0, dmap, f, maxlength, broken_streamlines=True):
+ """
+ 2nd-order Runge-Kutta algorithm with adaptive step size.
+
+ This method is also referred to as the improved Euler's method, or Heun's
+ method. This method is favored over higher-order methods because:
+
+ 1. To get decent looking trajectories and to sample every mask cell
+ on the trajectory we need a small timestep, so a lower order
+ solver doesn't hurt us unless the data is *very* high resolution.
+ In fact, for cases where the user inputs
+ data smaller or of similar grid size to the mask grid, the higher
+ order corrections are negligible because of the very fast linear
+ interpolation used in `interpgrid`.
+
+ 2. For high resolution input data (i.e. beyond the mask
+ resolution), we must reduce the timestep. Therefore, an adaptive
+ timestep is more suited to the problem as this would be very hard
+ to judge automatically otherwise.
+
+ This integrator is about 1.5 - 2x as fast as RK4 and RK45 solvers (using
+ similar Python implementations) in most setups.
+ """
+ # This error is below that needed to match the RK4 integrator. It
+ # is set for visual reasons -- too low and corners start
+ # appearing ugly and jagged. Can be tuned.
+ maxerror = 0.003
+
+ # This limit is important (for all integrators) to avoid the
+ # trajectory skipping some mask cells. We could relax this
+ # condition if we use the code which is commented out below to
+ # increment the location gradually. However, due to the efficient
+ # nature of the interpolation, this doesn't boost speed by much
+ # for quite a bit of complexity.
+ maxds = min(1. / dmap.mask.nx, 1. / dmap.mask.ny, 0.1)
+
+ ds = maxds
+ stotal = 0
+ xi = x0
+ yi = y0
+ xyf_traj = []
+
+ while True:
+ try:
+ if dmap.grid.within_grid(xi, yi):
+ xyf_traj.append((xi, yi))
+ else:
+ raise OutOfBounds
+
+ # Compute the two intermediate gradients.
+ # f should raise OutOfBounds if the locations given are
+ # outside the grid.
+ k1x, k1y = f(xi, yi)
+ k2x, k2y = f(xi + ds * k1x, yi + ds * k1y)
+
+ except OutOfBounds:
+ # Out of the domain during this step.
+ # Take an Euler step to the boundary to improve neatness
+ # unless the trajectory is currently empty.
+ if xyf_traj:
+ ds, xyf_traj = _euler_step(xyf_traj, dmap, f)
+ stotal += ds
+ break
+ except TerminateTrajectory:
+ break
+
+ dx1 = ds * k1x
+ dy1 = ds * k1y
+ dx2 = ds * 0.5 * (k1x + k2x)
+ dy2 = ds * 0.5 * (k1y + k2y)
+
+ ny, nx = dmap.grid.shape
+ # Error is normalized to the axes coordinates
+ error = np.hypot((dx2 - dx1) / (nx - 1), (dy2 - dy1) / (ny - 1))
+
+ # Only save step if within error tolerance
+ if error < maxerror:
+ xi += dx2
+ yi += dy2
+ try:
+ dmap.update_trajectory(xi, yi, broken_streamlines)
+ except InvalidIndexError:
+ break
+ if stotal + ds > maxlength:
+ break
+ stotal += ds
+
+ # recalculate stepsize based on step error
+ if error == 0:
+ ds = maxds
+ else:
+ ds = min(maxds, 0.85 * ds * (maxerror / error) ** 0.5)
+
+ return stotal, xyf_traj
+
+
+def _euler_step(xyf_traj, dmap, f):
+ """Simple Euler integration step that extends streamline to boundary."""
+ ny, nx = dmap.grid.shape
+ xi, yi = xyf_traj[-1]
+ cx, cy = f(xi, yi)
+ if cx == 0:
+ dsx = np.inf
+ elif cx < 0:
+ dsx = xi / -cx
+ else:
+ dsx = (nx - 1 - xi) / cx
+ if cy == 0:
+ dsy = np.inf
+ elif cy < 0:
+ dsy = yi / -cy
+ else:
+ dsy = (ny - 1 - yi) / cy
+ ds = min(dsx, dsy)
+ xyf_traj.append((xi + cx * ds, yi + cy * ds))
+ return ds, xyf_traj
+
+
+# Utility functions
+# ========================
+
+def interpgrid(a, xi, yi):
+ """Fast 2D, linear interpolation on an integer grid"""
+
+ Ny, Nx = np.shape(a)
+ if isinstance(xi, np.ndarray):
+ x = xi.astype(int)
+ y = yi.astype(int)
+ # Check that xn, yn don't exceed max index
+ xn = np.clip(x + 1, 0, Nx - 1)
+ yn = np.clip(y + 1, 0, Ny - 1)
+ else:
+ x = int(xi)
+ y = int(yi)
+ # conditional is faster than clipping for integers
+ if x == (Nx - 1):
+ xn = x
+ else:
+ xn = x + 1
+ if y == (Ny - 1):
+ yn = y
+ else:
+ yn = y + 1
+
+ a00 = a[y, x]
+ a01 = a[y, xn]
+ a10 = a[yn, x]
+ a11 = a[yn, xn]
+ xt = xi - x
+ yt = yi - y
+ a0 = a00 * (1 - xt) + a01 * xt
+ a1 = a10 * (1 - xt) + a11 * xt
+ ai = a0 * (1 - yt) + a1 * yt
+
+ if not isinstance(xi, np.ndarray):
+ if np.ma.is_masked(ai):
+ raise TerminateTrajectory
+
+ return ai
+
+
+def _gen_starting_points(shape):
+ """
+ Yield starting points for streamlines.
+
+ Trying points on the boundary first gives higher quality streamlines.
+ This algorithm starts with a point on the mask corner and spirals inward.
+ This algorithm is inefficient, but fast compared to rest of streamplot.
+ """
+ ny, nx = shape
+ xfirst = 0
+ yfirst = 1
+ xlast = nx - 1
+ ylast = ny - 1
+ x, y = 0, 0
+ direction = 'right'
+ for i in range(nx * ny):
+ yield x, y
+
+ if direction == 'right':
+ x += 1
+ if x >= xlast:
+ xlast -= 1
+ direction = 'up'
+ elif direction == 'up':
+ y += 1
+ if y >= ylast:
+ ylast -= 1
+ direction = 'left'
+ elif direction == 'left':
+ x -= 1
+ if x <= xfirst:
+ xfirst += 1
+ direction = 'down'
+ elif direction == 'down':
+ y -= 1
+ if y <= yfirst:
+ yfirst += 1
+ direction = 'right'
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/table.py b/llava_video/lib/python3.10/site-packages/matplotlib/table.py
new file mode 100644
index 0000000000000000000000000000000000000000..21518c4c67268cffe8f3fb49aad45ea2ba182776
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/table.py
@@ -0,0 +1,842 @@
+# Original code by:
+# John Gill
+# Copyright 2004 John Gill and John Hunter
+#
+# Subsequent changes:
+# The Matplotlib development team
+# Copyright The Matplotlib development team
+
+"""
+Tables drawing.
+
+.. note::
+ The table implementation in Matplotlib is lightly maintained. For a more
+ featureful table implementation, you may wish to try `blume
+ `_.
+
+Use the factory function `~matplotlib.table.table` to create a ready-made
+table from texts. If you need more control, use the `.Table` class and its
+methods.
+
+The table consists of a grid of cells, which are indexed by (row, column).
+The cell (0, 0) is positioned at the top left.
+
+Thanks to John Gill for providing the class and table.
+"""
+
+import numpy as np
+
+from . import _api, _docstring
+from .artist import Artist, allow_rasterization
+from .patches import Rectangle
+from .text import Text
+from .transforms import Bbox
+from .path import Path
+
+from .cbook import _is_pandas_dataframe
+
+
+class Cell(Rectangle):
+ """
+ A cell is a `.Rectangle` with some associated `.Text`.
+
+ As a user, you'll most likely not creates cells yourself. Instead, you
+ should use either the `~matplotlib.table.table` factory function or
+ `.Table.add_cell`.
+ """
+
+ PAD = 0.1
+ """Padding between text and rectangle."""
+
+ _edges = 'BRTL'
+ _edge_aliases = {'open': '',
+ 'closed': _edges, # default
+ 'horizontal': 'BT',
+ 'vertical': 'RL'
+ }
+
+ def __init__(self, xy, width, height, *,
+ edgecolor='k', facecolor='w',
+ fill=True,
+ text='',
+ loc='right',
+ fontproperties=None,
+ visible_edges='closed',
+ ):
+ """
+ Parameters
+ ----------
+ xy : 2-tuple
+ The position of the bottom left corner of the cell.
+ width : float
+ The cell width.
+ height : float
+ The cell height.
+ edgecolor : :mpltype:`color`, default: 'k'
+ The color of the cell border.
+ facecolor : :mpltype:`color`, default: 'w'
+ The cell facecolor.
+ fill : bool, default: True
+ Whether the cell background is filled.
+ text : str, optional
+ The cell text.
+ loc : {'right', 'center', 'left'}
+ The alignment of the text within the cell.
+ fontproperties : dict, optional
+ A dict defining the font properties of the text. Supported keys and
+ values are the keyword arguments accepted by `.FontProperties`.
+ visible_edges : {'closed', 'open', 'horizontal', 'vertical'} or \
+substring of 'BRTL'
+ The cell edges to be drawn with a line: a substring of 'BRTL'
+ (bottom, right, top, left), or one of 'open' (no edges drawn),
+ 'closed' (all edges drawn), 'horizontal' (bottom and top),
+ 'vertical' (right and left).
+ """
+
+ # Call base
+ super().__init__(xy, width=width, height=height, fill=fill,
+ edgecolor=edgecolor, facecolor=facecolor)
+ self.set_clip_on(False)
+ self.visible_edges = visible_edges
+
+ # Create text object
+ self._loc = loc
+ self._text = Text(x=xy[0], y=xy[1], clip_on=False,
+ text=text, fontproperties=fontproperties,
+ horizontalalignment=loc, verticalalignment='center')
+
+ def set_transform(self, t):
+ super().set_transform(t)
+ # the text does not get the transform!
+ self.stale = True
+
+ def set_figure(self, fig):
+ super().set_figure(fig)
+ self._text.set_figure(fig)
+
+ def get_text(self):
+ """Return the cell `.Text` instance."""
+ return self._text
+
+ def set_fontsize(self, size):
+ """Set the text fontsize."""
+ self._text.set_fontsize(size)
+ self.stale = True
+
+ def get_fontsize(self):
+ """Return the cell fontsize."""
+ return self._text.get_fontsize()
+
+ def auto_set_font_size(self, renderer):
+ """Shrink font size until the text fits into the cell width."""
+ fontsize = self.get_fontsize()
+ required = self.get_required_width(renderer)
+ while fontsize > 1 and required > self.get_width():
+ fontsize -= 1
+ self.set_fontsize(fontsize)
+ required = self.get_required_width(renderer)
+
+ return fontsize
+
+ @allow_rasterization
+ def draw(self, renderer):
+ if not self.get_visible():
+ return
+ # draw the rectangle
+ super().draw(renderer)
+ # position the text
+ self._set_text_position(renderer)
+ self._text.draw(renderer)
+ self.stale = False
+
+ def _set_text_position(self, renderer):
+ """Set text up so it is drawn in the right place."""
+ bbox = self.get_window_extent(renderer)
+ # center vertically
+ y = bbox.y0 + bbox.height / 2
+ # position horizontally
+ loc = self._text.get_horizontalalignment()
+ if loc == 'center':
+ x = bbox.x0 + bbox.width / 2
+ elif loc == 'left':
+ x = bbox.x0 + bbox.width * self.PAD
+ else: # right.
+ x = bbox.x0 + bbox.width * (1 - self.PAD)
+ self._text.set_position((x, y))
+
+ def get_text_bounds(self, renderer):
+ """
+ Return the text bounds as *(x, y, width, height)* in table coordinates.
+ """
+ return (self._text.get_window_extent(renderer)
+ .transformed(self.get_data_transform().inverted())
+ .bounds)
+
+ def get_required_width(self, renderer):
+ """Return the minimal required width for the cell."""
+ l, b, w, h = self.get_text_bounds(renderer)
+ return w * (1.0 + (2.0 * self.PAD))
+
+ @_docstring.interpd
+ def set_text_props(self, **kwargs):
+ """
+ Update the text properties.
+
+ Valid keyword arguments are:
+
+ %(Text:kwdoc)s
+ """
+ self._text._internal_update(kwargs)
+ self.stale = True
+
+ @property
+ def visible_edges(self):
+ """
+ The cell edges to be drawn with a line.
+
+ Reading this property returns a substring of 'BRTL' (bottom, right,
+ top, left').
+
+ When setting this property, you can use a substring of 'BRTL' or one
+ of {'open', 'closed', 'horizontal', 'vertical'}.
+ """
+ return self._visible_edges
+
+ @visible_edges.setter
+ def visible_edges(self, value):
+ if value is None:
+ self._visible_edges = self._edges
+ elif value in self._edge_aliases:
+ self._visible_edges = self._edge_aliases[value]
+ else:
+ if any(edge not in self._edges for edge in value):
+ raise ValueError('Invalid edge param {}, must only be one of '
+ '{} or string of {}'.format(
+ value,
+ ", ".join(self._edge_aliases),
+ ", ".join(self._edges)))
+ self._visible_edges = value
+ self.stale = True
+
+ def get_path(self):
+ """Return a `.Path` for the `.visible_edges`."""
+ codes = [Path.MOVETO]
+ codes.extend(
+ Path.LINETO if edge in self._visible_edges else Path.MOVETO
+ for edge in self._edges)
+ if Path.MOVETO not in codes[1:]: # All sides are visible
+ codes[-1] = Path.CLOSEPOLY
+ return Path(
+ [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
+ codes,
+ readonly=True
+ )
+
+
+CustomCell = Cell # Backcompat. alias.
+
+
+class Table(Artist):
+ """
+ A table of cells.
+
+ The table consists of a grid of cells, which are indexed by (row, column).
+
+ For a simple table, you'll have a full grid of cells with indices from
+ (0, 0) to (num_rows-1, num_cols-1), in which the cell (0, 0) is positioned
+ at the top left. However, you can also add cells with negative indices.
+ You don't have to add a cell to every grid position, so you can create
+ tables that have holes.
+
+ *Note*: You'll usually not create an empty table from scratch. Instead use
+ `~matplotlib.table.table` to create a table from data.
+ """
+ codes = {'best': 0,
+ 'upper right': 1, # default
+ 'upper left': 2,
+ 'lower left': 3,
+ 'lower right': 4,
+ 'center left': 5,
+ 'center right': 6,
+ 'lower center': 7,
+ 'upper center': 8,
+ 'center': 9,
+ 'top right': 10,
+ 'top left': 11,
+ 'bottom left': 12,
+ 'bottom right': 13,
+ 'right': 14,
+ 'left': 15,
+ 'top': 16,
+ 'bottom': 17,
+ }
+ """Possible values where to place the table relative to the Axes."""
+
+ FONTSIZE = 10
+
+ AXESPAD = 0.02
+ """The border between the Axes and the table edge in Axes units."""
+
+ def __init__(self, ax, loc=None, bbox=None, **kwargs):
+ """
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` to plot the table into.
+ loc : str, optional
+ The position of the cell with respect to *ax*. This must be one of
+ the `~.Table.codes`.
+ bbox : `.Bbox` or [xmin, ymin, width, height], optional
+ A bounding box to draw the table into. If this is not *None*, this
+ overrides *loc*.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ `.Artist` properties.
+ """
+
+ super().__init__()
+
+ if isinstance(loc, str):
+ if loc not in self.codes:
+ raise ValueError(
+ "Unrecognized location {!r}. Valid locations are\n\t{}"
+ .format(loc, '\n\t'.join(self.codes)))
+ loc = self.codes[loc]
+ self.set_figure(ax.get_figure(root=False))
+ self._axes = ax
+ self._loc = loc
+ self._bbox = bbox
+
+ # use axes coords
+ ax._unstale_viewLim()
+ self.set_transform(ax.transAxes)
+
+ self._cells = {}
+ self._edges = None
+ self._autoColumns = []
+ self._autoFontsize = True
+ self._internal_update(kwargs)
+
+ self.set_clip_on(False)
+
+ def add_cell(self, row, col, *args, **kwargs):
+ """
+ Create a cell and add it to the table.
+
+ Parameters
+ ----------
+ row : int
+ Row index.
+ col : int
+ Column index.
+ *args, **kwargs
+ All other parameters are passed on to `Cell`.
+
+ Returns
+ -------
+ `.Cell`
+ The created cell.
+
+ """
+ xy = (0, 0)
+ cell = Cell(xy, visible_edges=self.edges, *args, **kwargs)
+ self[row, col] = cell
+ return cell
+
+ def __setitem__(self, position, cell):
+ """
+ Set a custom cell in a given position.
+ """
+ _api.check_isinstance(Cell, cell=cell)
+ try:
+ row, col = position[0], position[1]
+ except Exception as err:
+ raise KeyError('Only tuples length 2 are accepted as '
+ 'coordinates') from err
+ cell.set_figure(self.get_figure(root=False))
+ cell.set_transform(self.get_transform())
+ cell.set_clip_on(False)
+ self._cells[row, col] = cell
+ self.stale = True
+
+ def __getitem__(self, position):
+ """Retrieve a custom cell from a given position."""
+ return self._cells[position]
+
+ @property
+ def edges(self):
+ """
+ The default value of `~.Cell.visible_edges` for newly added
+ cells using `.add_cell`.
+
+ Notes
+ -----
+ This setting does currently only affect newly created cells using
+ `.add_cell`.
+
+ To change existing cells, you have to set their edges explicitly::
+
+ for c in tab.get_celld().values():
+ c.visible_edges = 'horizontal'
+
+ """
+ return self._edges
+
+ @edges.setter
+ def edges(self, value):
+ self._edges = value
+ self.stale = True
+
+ def _approx_text_height(self):
+ return (self.FONTSIZE / 72.0 * self.get_figure(root=True).dpi /
+ self._axes.bbox.height * 1.2)
+
+ @allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+
+ # Need a renderer to do hit tests on mouseevent; assume the last one
+ # will do
+ if renderer is None:
+ renderer = self.get_figure(root=True)._get_renderer()
+ if renderer is None:
+ raise RuntimeError('No renderer defined')
+
+ if not self.get_visible():
+ return
+ renderer.open_group('table', gid=self.get_gid())
+ self._update_positions(renderer)
+
+ for key in sorted(self._cells):
+ self._cells[key].draw(renderer)
+
+ renderer.close_group('table')
+ self.stale = False
+
+ def _get_grid_bbox(self, renderer):
+ """
+ Get a bbox, in axes coordinates for the cells.
+
+ Only include those in the range (0, 0) to (maxRow, maxCol).
+ """
+ boxes = [cell.get_window_extent(renderer)
+ for (row, col), cell in self._cells.items()
+ if row >= 0 and col >= 0]
+ bbox = Bbox.union(boxes)
+ return bbox.transformed(self.get_transform().inverted())
+
+ def contains(self, mouseevent):
+ # docstring inherited
+ if self._different_canvas(mouseevent):
+ return False, {}
+ # TODO: Return index of the cell containing the cursor so that the user
+ # doesn't have to bind to each one individually.
+ renderer = self.get_figure(root=True)._get_renderer()
+ if renderer is not None:
+ boxes = [cell.get_window_extent(renderer)
+ for (row, col), cell in self._cells.items()
+ if row >= 0 and col >= 0]
+ bbox = Bbox.union(boxes)
+ return bbox.contains(mouseevent.x, mouseevent.y), {}
+ else:
+ return False, {}
+
+ def get_children(self):
+ """Return the Artists contained by the table."""
+ return list(self._cells.values())
+
+ def get_window_extent(self, renderer=None):
+ # docstring inherited
+ if renderer is None:
+ renderer = self.get_figure(root=True)._get_renderer()
+ self._update_positions(renderer)
+ boxes = [cell.get_window_extent(renderer)
+ for cell in self._cells.values()]
+ return Bbox.union(boxes)
+
+ def _do_cell_alignment(self):
+ """
+ Calculate row heights and column widths; position cells accordingly.
+ """
+ # Calculate row/column widths
+ widths = {}
+ heights = {}
+ for (row, col), cell in self._cells.items():
+ height = heights.setdefault(row, 0.0)
+ heights[row] = max(height, cell.get_height())
+ width = widths.setdefault(col, 0.0)
+ widths[col] = max(width, cell.get_width())
+
+ # work out left position for each column
+ xpos = 0
+ lefts = {}
+ for col in sorted(widths):
+ lefts[col] = xpos
+ xpos += widths[col]
+
+ ypos = 0
+ bottoms = {}
+ for row in sorted(heights, reverse=True):
+ bottoms[row] = ypos
+ ypos += heights[row]
+
+ # set cell positions
+ for (row, col), cell in self._cells.items():
+ cell.set_x(lefts[col])
+ cell.set_y(bottoms[row])
+
+ def auto_set_column_width(self, col):
+ """
+ Automatically set the widths of given columns to optimal sizes.
+
+ Parameters
+ ----------
+ col : int or sequence of ints
+ The indices of the columns to auto-scale.
+ """
+ col1d = np.atleast_1d(col)
+ if not np.issubdtype(col1d.dtype, np.integer):
+ raise TypeError("col must be an int or sequence of ints.")
+ for cell in col1d:
+ self._autoColumns.append(cell)
+
+ self.stale = True
+
+ def _auto_set_column_width(self, col, renderer):
+ """Automatically set width for column."""
+ cells = [cell for key, cell in self._cells.items() if key[1] == col]
+ max_width = max((cell.get_required_width(renderer) for cell in cells),
+ default=0)
+ for cell in cells:
+ cell.set_width(max_width)
+
+ def auto_set_font_size(self, value=True):
+ """Automatically set font size."""
+ self._autoFontsize = value
+ self.stale = True
+
+ def _auto_set_font_size(self, renderer):
+
+ if len(self._cells) == 0:
+ return
+ fontsize = next(iter(self._cells.values())).get_fontsize()
+ cells = []
+ for key, cell in self._cells.items():
+ # ignore auto-sized columns
+ if key[1] in self._autoColumns:
+ continue
+ size = cell.auto_set_font_size(renderer)
+ fontsize = min(fontsize, size)
+ cells.append(cell)
+
+ # now set all fontsizes equal
+ for cell in self._cells.values():
+ cell.set_fontsize(fontsize)
+
+ def scale(self, xscale, yscale):
+ """Scale column widths by *xscale* and row heights by *yscale*."""
+ for c in self._cells.values():
+ c.set_width(c.get_width() * xscale)
+ c.set_height(c.get_height() * yscale)
+
+ def set_fontsize(self, size):
+ """
+ Set the font size, in points, of the cell text.
+
+ Parameters
+ ----------
+ size : float
+
+ Notes
+ -----
+ As long as auto font size has not been disabled, the value will be
+ clipped such that the text fits horizontally into the cell.
+
+ You can disable this behavior using `.auto_set_font_size`.
+
+ >>> the_table.auto_set_font_size(False)
+ >>> the_table.set_fontsize(20)
+
+ However, there is no automatic scaling of the row height so that the
+ text may exceed the cell boundary.
+ """
+ for cell in self._cells.values():
+ cell.set_fontsize(size)
+ self.stale = True
+
+ def _offset(self, ox, oy):
+ """Move all the artists by ox, oy (axes coords)."""
+ for c in self._cells.values():
+ x, y = c.get_x(), c.get_y()
+ c.set_x(x + ox)
+ c.set_y(y + oy)
+
+ def _update_positions(self, renderer):
+ # called from renderer to allow more precise estimates of
+ # widths and heights with get_window_extent
+
+ # Do any auto width setting
+ for col in self._autoColumns:
+ self._auto_set_column_width(col, renderer)
+
+ if self._autoFontsize:
+ self._auto_set_font_size(renderer)
+
+ # Align all the cells
+ self._do_cell_alignment()
+
+ bbox = self._get_grid_bbox(renderer)
+ l, b, w, h = bbox.bounds
+
+ if self._bbox is not None:
+ # Position according to bbox
+ if isinstance(self._bbox, Bbox):
+ rl, rb, rw, rh = self._bbox.bounds
+ else:
+ rl, rb, rw, rh = self._bbox
+ self.scale(rw / w, rh / h)
+ ox = rl - l
+ oy = rb - b
+ self._do_cell_alignment()
+ else:
+ # Position using loc
+ (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C,
+ TR, TL, BL, BR, R, L, T, B) = range(len(self.codes))
+ # defaults for center
+ ox = (0.5 - w / 2) - l
+ oy = (0.5 - h / 2) - b
+ if self._loc in (UL, LL, CL): # left
+ ox = self.AXESPAD - l
+ if self._loc in (BEST, UR, LR, R, CR): # right
+ ox = 1 - (l + w + self.AXESPAD)
+ if self._loc in (BEST, UR, UL, UC): # upper
+ oy = 1 - (b + h + self.AXESPAD)
+ if self._loc in (LL, LR, LC): # lower
+ oy = self.AXESPAD - b
+ if self._loc in (LC, UC, C): # center x
+ ox = (0.5 - w / 2) - l
+ if self._loc in (CL, CR, C): # center y
+ oy = (0.5 - h / 2) - b
+
+ if self._loc in (TL, BL, L): # out left
+ ox = - (l + w)
+ if self._loc in (TR, BR, R): # out right
+ ox = 1.0 - l
+ if self._loc in (TR, TL, T): # out top
+ oy = 1.0 - b
+ if self._loc in (BL, BR, B): # out bottom
+ oy = - (b + h)
+
+ self._offset(ox, oy)
+
+ def get_celld(self):
+ r"""
+ Return a dict of cells in the table mapping *(row, column)* to
+ `.Cell`\s.
+
+ Notes
+ -----
+ You can also directly index into the Table object to access individual
+ cells::
+
+ cell = table[row, col]
+
+ """
+ return self._cells
+
+
+@_docstring.interpd
+def table(ax,
+ cellText=None, cellColours=None,
+ cellLoc='right', colWidths=None,
+ rowLabels=None, rowColours=None, rowLoc='left',
+ colLabels=None, colColours=None, colLoc='center',
+ loc='bottom', bbox=None, edges='closed',
+ **kwargs):
+ """
+ Add a table to an `~.axes.Axes`.
+
+ At least one of *cellText* or *cellColours* must be specified. These
+ parameters must be 2D lists, in which the outer lists define the rows and
+ the inner list define the column values per row. Each row must have the
+ same number of elements.
+
+ The table can optionally have row and column headers, which are configured
+ using *rowLabels*, *rowColours*, *rowLoc* and *colLabels*, *colColours*,
+ *colLoc* respectively.
+
+ For finer grained control over tables, use the `.Table` class and add it to
+ the Axes with `.Axes.add_table`.
+
+ Parameters
+ ----------
+ cellText : 2D list of str or pandas.DataFrame, optional
+ The texts to place into the table cells.
+
+ *Note*: Line breaks in the strings are currently not accounted for and
+ will result in the text exceeding the cell boundaries.
+
+ cellColours : 2D list of :mpltype:`color`, optional
+ The background colors of the cells.
+
+ cellLoc : {'right', 'center', 'left'}
+ The alignment of the text within the cells.
+
+ colWidths : list of float, optional
+ The column widths in units of the axes. If not given, all columns will
+ have a width of *1 / ncols*.
+
+ rowLabels : list of str, optional
+ The text of the row header cells.
+
+ rowColours : list of :mpltype:`color`, optional
+ The colors of the row header cells.
+
+ rowLoc : {'left', 'center', 'right'}
+ The text alignment of the row header cells.
+
+ colLabels : list of str, optional
+ The text of the column header cells.
+
+ colColours : list of :mpltype:`color`, optional
+ The colors of the column header cells.
+
+ colLoc : {'center', 'left', 'right'}
+ The text alignment of the column header cells.
+
+ loc : str, default: 'bottom'
+ The position of the cell with respect to *ax*. This must be one of
+ the `~.Table.codes`.
+
+ bbox : `.Bbox` or [xmin, ymin, width, height], optional
+ A bounding box to draw the table into. If this is not *None*, this
+ overrides *loc*.
+
+ edges : {'closed', 'open', 'horizontal', 'vertical'} or substring of 'BRTL'
+ The cell edges to be drawn with a line. See also
+ `~.Cell.visible_edges`.
+
+ Returns
+ -------
+ `~matplotlib.table.Table`
+ The created table.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ `.Table` properties.
+
+ %(Table:kwdoc)s
+ """
+
+ if cellColours is None and cellText is None:
+ raise ValueError('At least one argument from "cellColours" or '
+ '"cellText" must be provided to create a table.')
+
+ # Check we have some cellText
+ if cellText is None:
+ # assume just colours are needed
+ rows = len(cellColours)
+ cols = len(cellColours[0])
+ cellText = [[''] * cols] * rows
+
+ # Check if we have a Pandas DataFrame
+ if _is_pandas_dataframe(cellText):
+ # if rowLabels/colLabels are empty, use DataFrame entries.
+ # Otherwise, throw an error.
+ if rowLabels is None:
+ rowLabels = cellText.index
+ else:
+ raise ValueError("rowLabels cannot be used alongside Pandas DataFrame")
+ if colLabels is None:
+ colLabels = cellText.columns
+ else:
+ raise ValueError("colLabels cannot be used alongside Pandas DataFrame")
+ # Update cellText with only values
+ cellText = cellText.values
+
+ rows = len(cellText)
+ cols = len(cellText[0])
+ for row in cellText:
+ if len(row) != cols:
+ raise ValueError(f"Each row in 'cellText' must have {cols} "
+ "columns")
+
+ if cellColours is not None:
+ if len(cellColours) != rows:
+ raise ValueError(f"'cellColours' must have {rows} rows")
+ for row in cellColours:
+ if len(row) != cols:
+ raise ValueError("Each row in 'cellColours' must have "
+ f"{cols} columns")
+ else:
+ cellColours = ['w' * cols] * rows
+
+ # Set colwidths if not given
+ if colWidths is None:
+ colWidths = [1.0 / cols] * cols
+
+ # Fill in missing information for column
+ # and row labels
+ rowLabelWidth = 0
+ if rowLabels is None:
+ if rowColours is not None:
+ rowLabels = [''] * rows
+ rowLabelWidth = colWidths[0]
+ elif rowColours is None:
+ rowColours = 'w' * rows
+
+ if rowLabels is not None:
+ if len(rowLabels) != rows:
+ raise ValueError(f"'rowLabels' must be of length {rows}")
+
+ # If we have column labels, need to shift
+ # the text and colour arrays down 1 row
+ offset = 1
+ if colLabels is None:
+ if colColours is not None:
+ colLabels = [''] * cols
+ else:
+ offset = 0
+ elif colColours is None:
+ colColours = 'w' * cols
+
+ # Set up cell colours if not given
+ if cellColours is None:
+ cellColours = ['w' * cols] * rows
+
+ # Now create the table
+ table = Table(ax, loc, bbox, **kwargs)
+ table.edges = edges
+ height = table._approx_text_height()
+
+ # Add the cells
+ for row in range(rows):
+ for col in range(cols):
+ table.add_cell(row + offset, col,
+ width=colWidths[col], height=height,
+ text=cellText[row][col],
+ facecolor=cellColours[row][col],
+ loc=cellLoc)
+ # Do column labels
+ if colLabels is not None:
+ for col in range(cols):
+ table.add_cell(0, col,
+ width=colWidths[col], height=height,
+ text=colLabels[col], facecolor=colColours[col],
+ loc=colLoc)
+
+ # Do row labels
+ if rowLabels is not None:
+ for row in range(rows):
+ table.add_cell(row + offset, -1,
+ width=rowLabelWidth or 1e-15, height=height,
+ text=rowLabels[row], facecolor=rowColours[row],
+ loc=rowLoc)
+ if rowLabelWidth == 0:
+ table.auto_set_column_width(-1)
+
+ ax.add_table(table)
+ return table
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/table.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/table.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..07d2427f66dc184efaf46af83e6733d157bc089b
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/table.pyi
@@ -0,0 +1,87 @@
+from .artist import Artist
+from .axes import Axes
+from .backend_bases import RendererBase
+from .patches import Rectangle
+from .path import Path
+from .text import Text
+from .transforms import Bbox
+from .typing import ColorType
+
+from collections.abc import Sequence
+from typing import Any, Literal, TYPE_CHECKING
+
+from pandas import DataFrame
+
+class Cell(Rectangle):
+ PAD: float
+ def __init__(
+ self,
+ xy: tuple[float, float],
+ width: float,
+ height: float,
+ *,
+ edgecolor: ColorType = ...,
+ facecolor: ColorType = ...,
+ fill: bool = ...,
+ text: str = ...,
+ loc: Literal["left", "center", "right"] = ...,
+ fontproperties: dict[str, Any] | None = ...,
+ visible_edges: str | None = ...
+ ) -> None: ...
+ def get_text(self) -> Text: ...
+ def set_fontsize(self, size: float) -> None: ...
+ def get_fontsize(self) -> float: ...
+ def auto_set_font_size(self, renderer: RendererBase) -> float: ...
+ def get_text_bounds(
+ self, renderer: RendererBase
+ ) -> tuple[float, float, float, float]: ...
+ def get_required_width(self, renderer: RendererBase) -> float: ...
+ def set_text_props(self, **kwargs) -> None: ...
+ @property
+ def visible_edges(self) -> str: ...
+ @visible_edges.setter
+ def visible_edges(self, value: str | None) -> None: ...
+ def get_path(self) -> Path: ...
+
+CustomCell = Cell
+
+class Table(Artist):
+ codes: dict[str, int]
+ FONTSIZE: float
+ AXESPAD: float
+ def __init__(
+ self, ax: Axes, loc: str | None = ..., bbox: Bbox | None = ..., **kwargs
+ ) -> None: ...
+ def add_cell(self, row: int, col: int, *args, **kwargs) -> Cell: ...
+ def __setitem__(self, position: tuple[int, int], cell: Cell) -> None: ...
+ def __getitem__(self, position: tuple[int, int]) -> Cell: ...
+ @property
+ def edges(self) -> str | None: ...
+ @edges.setter
+ def edges(self, value: str | None) -> None: ...
+ def draw(self, renderer) -> None: ...
+ def get_children(self) -> list[Artist]: ...
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
+ def auto_set_column_width(self, col: int | Sequence[int]) -> None: ...
+ def auto_set_font_size(self, value: bool = ...) -> None: ...
+ def scale(self, xscale: float, yscale: float) -> None: ...
+ def set_fontsize(self, size: float) -> None: ...
+ def get_celld(self) -> dict[tuple[int, int], Cell]: ...
+
+def table(
+ ax: Axes,
+ cellText: Sequence[Sequence[str]] | DataFrame | None = ...,
+ cellColours: Sequence[Sequence[ColorType]] | None = ...,
+ cellLoc: Literal["left", "center", "right"] = ...,
+ colWidths: Sequence[float] | None = ...,
+ rowLabels: Sequence[str] | None = ...,
+ rowColours: Sequence[ColorType] | None = ...,
+ rowLoc: Literal["left", "center", "right"] = ...,
+ colLabels: Sequence[str] | None = ...,
+ colColours: Sequence[ColorType] | None = ...,
+ colLoc: Literal["left", "center", "right"] = ...,
+ loc: str = ...,
+ bbox: Bbox | None = ...,
+ edges: str = ...,
+ **kwargs
+) -> Table: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/texmanager.py b/llava_video/lib/python3.10/site-packages/matplotlib/texmanager.py
new file mode 100644
index 0000000000000000000000000000000000000000..a374bfba8cab0a0200e7d07d01692fcb1828fbc0
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/texmanager.py
@@ -0,0 +1,365 @@
+r"""
+Support for embedded TeX expressions in Matplotlib.
+
+Requirements:
+
+* LaTeX.
+* \*Agg backends: dvipng>=1.6.
+* PS backend: PSfrag, dvips, and Ghostscript>=9.0.
+* PDF and SVG backends: if LuaTeX is present, it will be used to speed up some
+ post-processing steps, but note that it is not used to parse the TeX string
+ itself (only LaTeX is supported).
+
+To enable TeX rendering of all text in your Matplotlib figure, set
+:rc:`text.usetex` to True.
+
+TeX and dvipng/dvips processing results are cached
+in ~/.matplotlib/tex.cache for reuse between sessions.
+
+`TexManager.get_rgba` can also be used to directly obtain raster output as RGBA
+NumPy arrays.
+"""
+
+import functools
+import hashlib
+import logging
+import os
+from pathlib import Path
+import subprocess
+from tempfile import TemporaryDirectory
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import cbook, dviread
+
+_log = logging.getLogger(__name__)
+
+
+def _usepackage_if_not_loaded(package, *, option=None):
+ """
+ Output LaTeX code that loads a package (possibly with an option) if it
+ hasn't been loaded yet.
+
+ LaTeX cannot load twice a package with different options, so this helper
+ can be used to protect against users loading arbitrary packages/options in
+ their custom preamble.
+ """
+ option = f"[{option}]" if option is not None else ""
+ return (
+ r"\makeatletter"
+ r"\@ifpackageloaded{%(package)s}{}{\usepackage%(option)s{%(package)s}}"
+ r"\makeatother"
+ ) % {"package": package, "option": option}
+
+
+class TexManager:
+ """
+ Convert strings to dvi files using TeX, caching the results to a directory.
+
+ The cache directory is called ``tex.cache`` and is located in the directory
+ returned by `.get_cachedir`.
+
+ Repeated calls to this constructor always return the same instance.
+ """
+
+ _texcache = os.path.join(mpl.get_cachedir(), 'tex.cache')
+ _grey_arrayd = {}
+
+ _font_families = ('serif', 'sans-serif', 'cursive', 'monospace')
+ _font_preambles = {
+ 'new century schoolbook': r'\renewcommand{\rmdefault}{pnc}',
+ 'bookman': r'\renewcommand{\rmdefault}{pbk}',
+ 'times': r'\usepackage{mathptmx}',
+ 'palatino': r'\usepackage{mathpazo}',
+ 'zapf chancery': r'\usepackage{chancery}',
+ 'cursive': r'\usepackage{chancery}',
+ 'charter': r'\usepackage{charter}',
+ 'serif': '',
+ 'sans-serif': '',
+ 'helvetica': r'\usepackage{helvet}',
+ 'avant garde': r'\usepackage{avant}',
+ 'courier': r'\usepackage{courier}',
+ # Loading the type1ec package ensures that cm-super is installed, which
+ # is necessary for Unicode computer modern. (It also allows the use of
+ # computer modern at arbitrary sizes, but that's just a side effect.)
+ 'monospace': r'\usepackage{type1ec}',
+ 'computer modern roman': r'\usepackage{type1ec}',
+ 'computer modern sans serif': r'\usepackage{type1ec}',
+ 'computer modern typewriter': r'\usepackage{type1ec}',
+ }
+ _font_types = {
+ 'new century schoolbook': 'serif',
+ 'bookman': 'serif',
+ 'times': 'serif',
+ 'palatino': 'serif',
+ 'zapf chancery': 'cursive',
+ 'charter': 'serif',
+ 'helvetica': 'sans-serif',
+ 'avant garde': 'sans-serif',
+ 'courier': 'monospace',
+ 'computer modern roman': 'serif',
+ 'computer modern sans serif': 'sans-serif',
+ 'computer modern typewriter': 'monospace',
+ }
+
+ @functools.lru_cache # Always return the same instance.
+ def __new__(cls):
+ Path(cls._texcache).mkdir(parents=True, exist_ok=True)
+ return object.__new__(cls)
+
+ @classmethod
+ def _get_font_family_and_reduced(cls):
+ """Return the font family name and whether the font is reduced."""
+ ff = mpl.rcParams['font.family']
+ ff_val = ff[0].lower() if len(ff) == 1 else None
+ if len(ff) == 1 and ff_val in cls._font_families:
+ return ff_val, False
+ elif len(ff) == 1 and ff_val in cls._font_preambles:
+ return cls._font_types[ff_val], True
+ else:
+ _log.info('font.family must be one of (%s) when text.usetex is '
+ 'True. serif will be used by default.',
+ ', '.join(cls._font_families))
+ return 'serif', False
+
+ @classmethod
+ def _get_font_preamble_and_command(cls):
+ requested_family, is_reduced_font = cls._get_font_family_and_reduced()
+
+ preambles = {}
+ for font_family in cls._font_families:
+ if is_reduced_font and font_family == requested_family:
+ preambles[font_family] = cls._font_preambles[
+ mpl.rcParams['font.family'][0].lower()]
+ else:
+ rcfonts = mpl.rcParams[f"font.{font_family}"]
+ for i, font in enumerate(map(str.lower, rcfonts)):
+ if font in cls._font_preambles:
+ preambles[font_family] = cls._font_preambles[font]
+ _log.debug(
+ 'family: %s, package: %s, font: %s, skipped: %s',
+ font_family, cls._font_preambles[font], rcfonts[i],
+ ', '.join(rcfonts[:i]),
+ )
+ break
+ else:
+ _log.info('No LaTeX-compatible font found for the %s font'
+ 'family in rcParams. Using default.',
+ font_family)
+ preambles[font_family] = cls._font_preambles[font_family]
+
+ # The following packages and commands need to be included in the latex
+ # file's preamble:
+ cmd = {preambles[family]
+ for family in ['serif', 'sans-serif', 'monospace']}
+ if requested_family == 'cursive':
+ cmd.add(preambles['cursive'])
+ cmd.add(r'\usepackage{type1cm}')
+ preamble = '\n'.join(sorted(cmd))
+ fontcmd = (r'\sffamily' if requested_family == 'sans-serif' else
+ r'\ttfamily' if requested_family == 'monospace' else
+ r'\rmfamily')
+ return preamble, fontcmd
+
+ @classmethod
+ def get_basefile(cls, tex, fontsize, dpi=None):
+ """
+ Return a filename based on a hash of the string, fontsize, and dpi.
+ """
+ src = cls._get_tex_source(tex, fontsize) + str(dpi)
+ filehash = hashlib.md5(src.encode('utf-8')).hexdigest()
+ filepath = Path(cls._texcache)
+
+ num_letters, num_levels = 2, 2
+ for i in range(0, num_letters*num_levels, num_letters):
+ filepath = filepath / Path(filehash[i:i+2])
+
+ filepath.mkdir(parents=True, exist_ok=True)
+ return os.path.join(filepath, filehash)
+
+ @classmethod
+ def get_font_preamble(cls):
+ """
+ Return a string containing font configuration for the tex preamble.
+ """
+ font_preamble, command = cls._get_font_preamble_and_command()
+ return font_preamble
+
+ @classmethod
+ def get_custom_preamble(cls):
+ """Return a string containing user additions to the tex preamble."""
+ return mpl.rcParams['text.latex.preamble']
+
+ @classmethod
+ def _get_tex_source(cls, tex, fontsize):
+ """Return the complete TeX source for processing a TeX string."""
+ font_preamble, fontcmd = cls._get_font_preamble_and_command()
+ baselineskip = 1.25 * fontsize
+ return "\n".join([
+ r"\documentclass{article}",
+ r"% Pass-through \mathdefault, which is used in non-usetex mode",
+ r"% to use the default text font but was historically suppressed",
+ r"% in usetex mode.",
+ r"\newcommand{\mathdefault}[1]{#1}",
+ font_preamble,
+ r"\usepackage[utf8]{inputenc}",
+ r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}",
+ r"% geometry is loaded before the custom preamble as ",
+ r"% convert_psfrags relies on a custom preamble to change the ",
+ r"% geometry.",
+ r"\usepackage[papersize=72in, margin=1in]{geometry}",
+ cls.get_custom_preamble(),
+ r"% Use `underscore` package to take care of underscores in text.",
+ r"% The [strings] option allows to use underscores in file names.",
+ _usepackage_if_not_loaded("underscore", option="strings"),
+ r"% Custom packages (e.g. newtxtext) may already have loaded ",
+ r"% textcomp with different options.",
+ _usepackage_if_not_loaded("textcomp"),
+ r"\pagestyle{empty}",
+ r"\begin{document}",
+ r"% The empty hbox ensures that a page is printed even for empty",
+ r"% inputs, except when using psfrag which gets confused by it.",
+ r"% matplotlibbaselinemarker is used by dviread to detect the",
+ r"% last line's baseline.",
+ rf"\fontsize{{{fontsize}}}{{{baselineskip}}}%",
+ r"\ifdefined\psfrag\else\hbox{}\fi%",
+ rf"{{{fontcmd} {tex}}}%",
+ r"\end{document}",
+ ])
+
+ @classmethod
+ def make_tex(cls, tex, fontsize):
+ """
+ Generate a tex file to render the tex string at a specific font size.
+
+ Return the file name.
+ """
+ texfile = cls.get_basefile(tex, fontsize) + ".tex"
+ Path(texfile).write_text(cls._get_tex_source(tex, fontsize),
+ encoding='utf-8')
+ return texfile
+
+ @classmethod
+ def _run_checked_subprocess(cls, command, tex, *, cwd=None):
+ _log.debug(cbook._pformat_subprocess(command))
+ try:
+ report = subprocess.check_output(
+ command, cwd=cwd if cwd is not None else cls._texcache,
+ stderr=subprocess.STDOUT)
+ except FileNotFoundError as exc:
+ raise RuntimeError(
+ f'Failed to process string with tex because {command[0]} '
+ 'could not be found') from exc
+ except subprocess.CalledProcessError as exc:
+ raise RuntimeError(
+ '{prog} was not able to process the following string:\n'
+ '{tex!r}\n\n'
+ 'Here is the full command invocation and its output:\n\n'
+ '{format_command}\n\n'
+ '{exc}\n\n'.format(
+ prog=command[0],
+ format_command=cbook._pformat_subprocess(command),
+ tex=tex.encode('unicode_escape'),
+ exc=exc.output.decode('utf-8', 'backslashreplace'))
+ ) from None
+ _log.debug(report)
+ return report
+
+ @classmethod
+ def make_dvi(cls, tex, fontsize):
+ """
+ Generate a dvi file containing latex's layout of tex string.
+
+ Return the file name.
+ """
+ basefile = cls.get_basefile(tex, fontsize)
+ dvifile = '%s.dvi' % basefile
+ if not os.path.exists(dvifile):
+ texfile = Path(cls.make_tex(tex, fontsize))
+ # Generate the dvi in a temporary directory to avoid race
+ # conditions e.g. if multiple processes try to process the same tex
+ # string at the same time. Having tmpdir be a subdirectory of the
+ # final output dir ensures that they are on the same filesystem,
+ # and thus replace() works atomically. It also allows referring to
+ # the texfile with a relative path (for pathological MPLCONFIGDIRs,
+ # the absolute path may contain characters (e.g. ~) that TeX does
+ # not support; n.b. relative paths cannot traverse parents, or it
+ # will be blocked when `openin_any = p` in texmf.cnf).
+ cwd = Path(dvifile).parent
+ with TemporaryDirectory(dir=cwd) as tmpdir:
+ tmppath = Path(tmpdir)
+ cls._run_checked_subprocess(
+ ["latex", "-interaction=nonstopmode", "--halt-on-error",
+ f"--output-directory={tmppath.name}",
+ f"{texfile.name}"], tex, cwd=cwd)
+ (tmppath / Path(dvifile).name).replace(dvifile)
+ return dvifile
+
+ @classmethod
+ def make_png(cls, tex, fontsize, dpi):
+ """
+ Generate a png file containing latex's rendering of tex string.
+
+ Return the file name.
+ """
+ basefile = cls.get_basefile(tex, fontsize, dpi)
+ pngfile = '%s.png' % basefile
+ # see get_rgba for a discussion of the background
+ if not os.path.exists(pngfile):
+ dvifile = cls.make_dvi(tex, fontsize)
+ cmd = ["dvipng", "-bg", "Transparent", "-D", str(dpi),
+ "-T", "tight", "-o", pngfile, dvifile]
+ # When testing, disable FreeType rendering for reproducibility; but
+ # dvipng 1.16 has a bug (fixed in f3ff241) that breaks --freetype0
+ # mode, so for it we keep FreeType enabled; the image will be
+ # slightly off.
+ if (getattr(mpl, "_called_from_pytest", False) and
+ mpl._get_executable_info("dvipng").raw_version != "1.16"):
+ cmd.insert(1, "--freetype0")
+ cls._run_checked_subprocess(cmd, tex)
+ return pngfile
+
+ @classmethod
+ def get_grey(cls, tex, fontsize=None, dpi=None):
+ """Return the alpha channel."""
+ if not fontsize:
+ fontsize = mpl.rcParams['font.size']
+ if not dpi:
+ dpi = mpl.rcParams['savefig.dpi']
+ key = cls._get_tex_source(tex, fontsize), dpi
+ alpha = cls._grey_arrayd.get(key)
+ if alpha is None:
+ pngfile = cls.make_png(tex, fontsize, dpi)
+ rgba = mpl.image.imread(os.path.join(cls._texcache, pngfile))
+ cls._grey_arrayd[key] = alpha = rgba[:, :, -1]
+ return alpha
+
+ @classmethod
+ def get_rgba(cls, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
+ r"""
+ Return latex's rendering of the tex string as an RGBA array.
+
+ Examples
+ --------
+ >>> texmanager = TexManager()
+ >>> s = r"\TeX\ is $\displaystyle\sum_n\frac{-e^{i\pi}}{2^n}$!"
+ >>> Z = texmanager.get_rgba(s, fontsize=12, dpi=80, rgb=(1, 0, 0))
+ """
+ alpha = cls.get_grey(tex, fontsize, dpi)
+ rgba = np.empty((*alpha.shape, 4))
+ rgba[..., :3] = mpl.colors.to_rgb(rgb)
+ rgba[..., -1] = alpha
+ return rgba
+
+ @classmethod
+ def get_text_width_height_descent(cls, tex, fontsize, renderer=None):
+ """Return width, height and descent of the text."""
+ if tex.strip() == '':
+ return 0, 0, 0
+ dvifile = cls.make_dvi(tex, fontsize)
+ dpi_fraction = renderer.points_to_pixels(1.) if renderer else 1
+ with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
+ page, = dvi
+ # A total height (including the descent) needs to be returned.
+ return page.width, page.height + page.descent, page.descent
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/texmanager.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/texmanager.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..94f0d76fa814c6015fd4acefca5b1c1732645c85
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/texmanager.pyi
@@ -0,0 +1,38 @@
+from .backend_bases import RendererBase
+
+from matplotlib.typing import ColorType
+
+import numpy as np
+
+class TexManager:
+ texcache: str
+ @classmethod
+ def get_basefile(
+ cls, tex: str, fontsize: float, dpi: float | None = ...
+ ) -> str: ...
+ @classmethod
+ def get_font_preamble(cls) -> str: ...
+ @classmethod
+ def get_custom_preamble(cls) -> str: ...
+ @classmethod
+ def make_tex(cls, tex: str, fontsize: float) -> str: ...
+ @classmethod
+ def make_dvi(cls, tex: str, fontsize: float) -> str: ...
+ @classmethod
+ def make_png(cls, tex: str, fontsize: float, dpi: float) -> str: ...
+ @classmethod
+ def get_grey(
+ cls, tex: str, fontsize: float | None = ..., dpi: float | None = ...
+ ) -> np.ndarray: ...
+ @classmethod
+ def get_rgba(
+ cls,
+ tex: str,
+ fontsize: float | None = ...,
+ dpi: float | None = ...,
+ rgb: ColorType = ...,
+ ) -> np.ndarray: ...
+ @classmethod
+ def get_text_width_height_descent(
+ cls, tex: str, fontsize, renderer: RendererBase | None = ...
+ ) -> tuple[int, int, int]: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/text.py b/llava_video/lib/python3.10/site-packages/matplotlib/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b65450f760b72209a577807d35dcb5490c0399e
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/text.py
@@ -0,0 +1,2035 @@
+"""
+Classes for including text in a figure.
+"""
+
+import functools
+import logging
+import math
+from numbers import Real
+import weakref
+
+import numpy as np
+
+import matplotlib as mpl
+from . import _api, artist, cbook, _docstring
+from .artist import Artist
+from .font_manager import FontProperties
+from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle
+from .textpath import TextPath, TextToPath # noqa # Logically located here
+from .transforms import (
+ Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform)
+
+
+_log = logging.getLogger(__name__)
+
+
+def _get_textbox(text, renderer):
+ """
+ Calculate the bounding box of the text.
+
+ The bbox position takes text rotation into account, but the width and
+ height are those of the unrotated box (unlike `.Text.get_window_extent`).
+ """
+ # TODO : This function may move into the Text class as a method. As a
+ # matter of fact, the information from the _get_textbox function
+ # should be available during the Text._get_layout() call, which is
+ # called within the _get_textbox. So, it would better to move this
+ # function as a method with some refactoring of _get_layout method.
+
+ projected_xs = []
+ projected_ys = []
+
+ theta = np.deg2rad(text.get_rotation())
+ tr = Affine2D().rotate(-theta)
+
+ _, parts, d = text._get_layout(renderer)
+
+ for t, wh, x, y in parts:
+ w, h = wh
+
+ xt1, yt1 = tr.transform((x, y))
+ yt1 -= d
+ xt2, yt2 = xt1 + w, yt1 + h
+
+ projected_xs.extend([xt1, xt2])
+ projected_ys.extend([yt1, yt2])
+
+ xt_box, yt_box = min(projected_xs), min(projected_ys)
+ w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box
+
+ x_box, y_box = Affine2D().rotate(theta).transform((xt_box, yt_box))
+
+ return x_box, y_box, w_box, h_box
+
+
+def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):
+ """Call ``renderer.get_text_width_height_descent``, caching the results."""
+ # Cached based on a copy of fontprop so that later in-place mutations of
+ # the passed-in argument do not mess up the cache.
+ return _get_text_metrics_with_cache_impl(
+ weakref.ref(renderer), text, fontprop.copy(), ismath, dpi)
+
+
+@functools.lru_cache(4096)
+def _get_text_metrics_with_cache_impl(
+ renderer_ref, text, fontprop, ismath, dpi):
+ # dpi is unused, but participates in cache invalidation (via the renderer).
+ return renderer_ref().get_text_width_height_descent(text, fontprop, ismath)
+
+
+@_docstring.interpd
+@_api.define_aliases({
+ "color": ["c"],
+ "fontproperties": ["font", "font_properties"],
+ "fontfamily": ["family"],
+ "fontname": ["name"],
+ "fontsize": ["size"],
+ "fontstretch": ["stretch"],
+ "fontstyle": ["style"],
+ "fontvariant": ["variant"],
+ "fontweight": ["weight"],
+ "horizontalalignment": ["ha"],
+ "verticalalignment": ["va"],
+ "multialignment": ["ma"],
+})
+class Text(Artist):
+ """Handle storing and drawing of text in window or data coordinates."""
+
+ zorder = 3
+ _charsize_cache = dict()
+
+ def __repr__(self):
+ return f"Text({self._x}, {self._y}, {self._text!r})"
+
+ def __init__(self,
+ x=0, y=0, text='', *,
+ color=None, # defaults to rc params
+ verticalalignment='baseline',
+ horizontalalignment='left',
+ multialignment=None,
+ fontproperties=None, # defaults to FontProperties()
+ rotation=None,
+ linespacing=None,
+ rotation_mode=None,
+ usetex=None, # defaults to rcParams['text.usetex']
+ wrap=False,
+ transform_rotates_text=False,
+ parse_math=None, # defaults to rcParams['text.parse_math']
+ antialiased=None, # defaults to rcParams['text.antialiased']
+ **kwargs
+ ):
+ """
+ Create a `.Text` instance at *x*, *y* with string *text*.
+
+ The text is aligned relative to the anchor point (*x*, *y*) according
+ to ``horizontalalignment`` (default: 'left') and ``verticalalignment``
+ (default: 'baseline'). See also
+ :doc:`/gallery/text_labels_and_annotations/text_alignment`.
+
+ While Text accepts the 'label' keyword argument, by default it is not
+ added to the handles of a legend.
+
+ Valid keyword arguments are:
+
+ %(Text:kwdoc)s
+ """
+ super().__init__()
+ self._x, self._y = x, y
+ self._text = ''
+ self._reset_visual_defaults(
+ text=text,
+ color=color,
+ fontproperties=fontproperties,
+ usetex=usetex,
+ parse_math=parse_math,
+ wrap=wrap,
+ verticalalignment=verticalalignment,
+ horizontalalignment=horizontalalignment,
+ multialignment=multialignment,
+ rotation=rotation,
+ transform_rotates_text=transform_rotates_text,
+ linespacing=linespacing,
+ rotation_mode=rotation_mode,
+ antialiased=antialiased
+ )
+ self.update(kwargs)
+
+ def _reset_visual_defaults(
+ self,
+ text='',
+ color=None,
+ fontproperties=None,
+ usetex=None,
+ parse_math=None,
+ wrap=False,
+ verticalalignment='baseline',
+ horizontalalignment='left',
+ multialignment=None,
+ rotation=None,
+ transform_rotates_text=False,
+ linespacing=None,
+ rotation_mode=None,
+ antialiased=None
+ ):
+ self.set_text(text)
+ self.set_color(mpl._val_or_rc(color, "text.color"))
+ self.set_fontproperties(fontproperties)
+ self.set_usetex(usetex)
+ self.set_parse_math(mpl._val_or_rc(parse_math, 'text.parse_math'))
+ self.set_wrap(wrap)
+ self.set_verticalalignment(verticalalignment)
+ self.set_horizontalalignment(horizontalalignment)
+ self._multialignment = multialignment
+ self.set_rotation(rotation)
+ self._transform_rotates_text = transform_rotates_text
+ self._bbox_patch = None # a FancyBboxPatch instance
+ self._renderer = None
+ if linespacing is None:
+ linespacing = 1.2 # Maybe use rcParam later.
+ self.set_linespacing(linespacing)
+ self.set_rotation_mode(rotation_mode)
+ self.set_antialiased(antialiased if antialiased is not None else
+ mpl.rcParams['text.antialiased'])
+
+ def update(self, kwargs):
+ # docstring inherited
+ ret = []
+ kwargs = cbook.normalize_kwargs(kwargs, Text)
+ sentinel = object() # bbox can be None, so use another sentinel.
+ # Update fontproperties first, as it has lowest priority.
+ fontproperties = kwargs.pop("fontproperties", sentinel)
+ if fontproperties is not sentinel:
+ ret.append(self.set_fontproperties(fontproperties))
+ # Update bbox last, as it depends on font properties.
+ bbox = kwargs.pop("bbox", sentinel)
+ ret.extend(super().update(kwargs))
+ if bbox is not sentinel:
+ ret.append(self.set_bbox(bbox))
+ return ret
+
+ def __getstate__(self):
+ d = super().__getstate__()
+ # remove the cached _renderer (if it exists)
+ d['_renderer'] = None
+ return d
+
+ def contains(self, mouseevent):
+ """
+ Return whether the mouse event occurred inside the axis-aligned
+ bounding-box of the text.
+ """
+ if (self._different_canvas(mouseevent) or not self.get_visible()
+ or self._renderer is None):
+ return False, {}
+ # Explicitly use Text.get_window_extent(self) and not
+ # self.get_window_extent() so that Annotation.contains does not
+ # accidentally cover the entire annotation bounding box.
+ bbox = Text.get_window_extent(self)
+ inside = (bbox.x0 <= mouseevent.x <= bbox.x1
+ and bbox.y0 <= mouseevent.y <= bbox.y1)
+ cattr = {}
+ # if the text has a surrounding patch, also check containment for it,
+ # and merge the results with the results for the text.
+ if self._bbox_patch:
+ patch_inside, patch_cattr = self._bbox_patch.contains(mouseevent)
+ inside = inside or patch_inside
+ cattr["bbox_patch"] = patch_cattr
+ return inside, cattr
+
+ def _get_xy_display(self):
+ """
+ Get the (possibly unit converted) transformed x, y in display coords.
+ """
+ x, y = self.get_unitless_position()
+ return self.get_transform().transform((x, y))
+
+ def _get_multialignment(self):
+ if self._multialignment is not None:
+ return self._multialignment
+ else:
+ return self._horizontalalignment
+
+ def _char_index_at(self, x):
+ """
+ Calculate the index closest to the coordinate x in display space.
+
+ The position of text[index] is assumed to be the sum of the widths
+ of all preceding characters text[:index].
+
+ This works only on single line texts.
+ """
+ if not self._text:
+ return 0
+
+ text = self._text
+
+ fontproperties = str(self._fontproperties)
+ if fontproperties not in Text._charsize_cache:
+ Text._charsize_cache[fontproperties] = dict()
+
+ charsize_cache = Text._charsize_cache[fontproperties]
+ for char in set(text):
+ if char not in charsize_cache:
+ self.set_text(char)
+ bb = self.get_window_extent()
+ charsize_cache[char] = bb.x1 - bb.x0
+
+ self.set_text(text)
+ bb = self.get_window_extent()
+
+ size_accum = np.cumsum([0] + [charsize_cache[x] for x in text])
+ std_x = x - bb.x0
+ return (np.abs(size_accum - std_x)).argmin()
+
+ def get_rotation(self):
+ """Return the text angle in degrees between 0 and 360."""
+ if self.get_transform_rotates_text():
+ return self.get_transform().transform_angles(
+ [self._rotation], [self.get_unitless_position()]).item(0)
+ else:
+ return self._rotation
+
+ def get_transform_rotates_text(self):
+ """
+ Return whether rotations of the transform affect the text direction.
+ """
+ return self._transform_rotates_text
+
+ def set_rotation_mode(self, m):
+ """
+ Set text rotation mode.
+
+ Parameters
+ ----------
+ m : {None, 'default', 'anchor'}
+ If ``"default"``, the text will be first rotated, then aligned according
+ to their horizontal and vertical alignments. If ``"anchor"``, then
+ alignment occurs before rotation. Passing ``None`` will set the rotation
+ mode to ``"default"``.
+ """
+ if m is None:
+ m = "default"
+ else:
+ _api.check_in_list(("anchor", "default"), rotation_mode=m)
+ self._rotation_mode = m
+ self.stale = True
+
+ def get_rotation_mode(self):
+ """Return the text rotation mode."""
+ return self._rotation_mode
+
+ def set_antialiased(self, antialiased):
+ """
+ Set whether to use antialiased rendering.
+
+ Parameters
+ ----------
+ antialiased : bool
+
+ Notes
+ -----
+ Antialiasing will be determined by :rc:`text.antialiased`
+ and the parameter *antialiased* will have no effect if the text contains
+ math expressions.
+ """
+ self._antialiased = antialiased
+ self.stale = True
+
+ def get_antialiased(self):
+ """Return whether antialiased rendering is used."""
+ return self._antialiased
+
+ def update_from(self, other):
+ # docstring inherited
+ super().update_from(other)
+ self._color = other._color
+ self._multialignment = other._multialignment
+ self._verticalalignment = other._verticalalignment
+ self._horizontalalignment = other._horizontalalignment
+ self._fontproperties = other._fontproperties.copy()
+ self._usetex = other._usetex
+ self._rotation = other._rotation
+ self._transform_rotates_text = other._transform_rotates_text
+ self._picker = other._picker
+ self._linespacing = other._linespacing
+ self._antialiased = other._antialiased
+ self.stale = True
+
+ def _get_layout(self, renderer):
+ """
+ Return the extent (bbox) of the text together with
+ multiple-alignment information. Note that it returns an extent
+ of a rotated text when necessary.
+ """
+ thisx, thisy = 0.0, 0.0
+ lines = self._get_wrapped_text().split("\n") # Ensures lines is not empty.
+
+ ws = []
+ hs = []
+ xs = []
+ ys = []
+
+ # Full vertical extent of font, including ascenders and descenders:
+ _, lp_h, lp_d = _get_text_metrics_with_cache(
+ renderer, "lp", self._fontproperties,
+ ismath="TeX" if self.get_usetex() else False,
+ dpi=self.get_figure(root=True).dpi)
+ min_dy = (lp_h - lp_d) * self._linespacing
+
+ for i, line in enumerate(lines):
+ clean_line, ismath = self._preprocess_math(line)
+ if clean_line:
+ w, h, d = _get_text_metrics_with_cache(
+ renderer, clean_line, self._fontproperties,
+ ismath=ismath, dpi=self.get_figure(root=True).dpi)
+ else:
+ w = h = d = 0
+
+ # For multiline text, increase the line spacing when the text
+ # net-height (excluding baseline) is larger than that of a "l"
+ # (e.g., use of superscripts), which seems what TeX does.
+ h = max(h, lp_h)
+ d = max(d, lp_d)
+
+ ws.append(w)
+ hs.append(h)
+
+ # Metrics of the last line that are needed later:
+ baseline = (h - d) - thisy
+
+ if i == 0:
+ # position at baseline
+ thisy = -(h - d)
+ else:
+ # put baseline a good distance from bottom of previous line
+ thisy -= max(min_dy, (h - d) * self._linespacing)
+
+ xs.append(thisx) # == 0.
+ ys.append(thisy)
+
+ thisy -= d
+
+ # Metrics of the last line that are needed later:
+ descent = d
+
+ # Bounding box definition:
+ width = max(ws)
+ xmin = 0
+ xmax = width
+ ymax = 0
+ ymin = ys[-1] - descent # baseline of last line minus its descent
+
+ # get the rotation matrix
+ M = Affine2D().rotate_deg(self.get_rotation())
+
+ # now offset the individual text lines within the box
+ malign = self._get_multialignment()
+ if malign == 'left':
+ offset_layout = [(x, y) for x, y in zip(xs, ys)]
+ elif malign == 'center':
+ offset_layout = [(x + width / 2 - w / 2, y)
+ for x, y, w in zip(xs, ys, ws)]
+ elif malign == 'right':
+ offset_layout = [(x + width - w, y)
+ for x, y, w in zip(xs, ys, ws)]
+
+ # the corners of the unrotated bounding box
+ corners_horiz = np.array(
+ [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)])
+
+ # now rotate the bbox
+ corners_rotated = M.transform(corners_horiz)
+ # compute the bounds of the rotated box
+ xmin = corners_rotated[:, 0].min()
+ xmax = corners_rotated[:, 0].max()
+ ymin = corners_rotated[:, 1].min()
+ ymax = corners_rotated[:, 1].max()
+ width = xmax - xmin
+ height = ymax - ymin
+
+ # Now move the box to the target position offset the display
+ # bbox by alignment
+ halign = self._horizontalalignment
+ valign = self._verticalalignment
+
+ rotation_mode = self.get_rotation_mode()
+ if rotation_mode != "anchor":
+ # compute the text location in display coords and the offsets
+ # necessary to align the bbox with that location
+ if halign == 'center':
+ offsetx = (xmin + xmax) / 2
+ elif halign == 'right':
+ offsetx = xmax
+ else:
+ offsetx = xmin
+
+ if valign == 'center':
+ offsety = (ymin + ymax) / 2
+ elif valign == 'top':
+ offsety = ymax
+ elif valign == 'baseline':
+ offsety = ymin + descent
+ elif valign == 'center_baseline':
+ offsety = ymin + height - baseline / 2.0
+ else:
+ offsety = ymin
+ else:
+ xmin1, ymin1 = corners_horiz[0]
+ xmax1, ymax1 = corners_horiz[2]
+
+ if halign == 'center':
+ offsetx = (xmin1 + xmax1) / 2.0
+ elif halign == 'right':
+ offsetx = xmax1
+ else:
+ offsetx = xmin1
+
+ if valign == 'center':
+ offsety = (ymin1 + ymax1) / 2.0
+ elif valign == 'top':
+ offsety = ymax1
+ elif valign == 'baseline':
+ offsety = ymax1 - baseline
+ elif valign == 'center_baseline':
+ offsety = ymax1 - baseline / 2.0
+ else:
+ offsety = ymin1
+
+ offsetx, offsety = M.transform((offsetx, offsety))
+
+ xmin -= offsetx
+ ymin -= offsety
+
+ bbox = Bbox.from_bounds(xmin, ymin, width, height)
+
+ # now rotate the positions around the first (x, y) position
+ xys = M.transform(offset_layout) - (offsetx, offsety)
+
+ return bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent
+
+ def set_bbox(self, rectprops):
+ """
+ Draw a bounding box around self.
+
+ Parameters
+ ----------
+ rectprops : dict with properties for `.patches.FancyBboxPatch`
+ The default boxstyle is 'square'. The mutation
+ scale of the `.patches.FancyBboxPatch` is set to the fontsize.
+
+ Examples
+ --------
+ ::
+
+ t.set_bbox(dict(facecolor='red', alpha=0.5))
+ """
+
+ if rectprops is not None:
+ props = rectprops.copy()
+ boxstyle = props.pop("boxstyle", None)
+ pad = props.pop("pad", None)
+ if boxstyle is None:
+ boxstyle = "square"
+ if pad is None:
+ pad = 4 # points
+ pad /= self.get_size() # to fraction of font size
+ else:
+ if pad is None:
+ pad = 0.3
+ # boxstyle could be a callable or a string
+ if isinstance(boxstyle, str) and "pad" not in boxstyle:
+ boxstyle += ",pad=%0.2f" % pad
+ self._bbox_patch = FancyBboxPatch(
+ (0, 0), 1, 1,
+ boxstyle=boxstyle, transform=IdentityTransform(), **props)
+ else:
+ self._bbox_patch = None
+
+ self._update_clip_properties()
+
+ def get_bbox_patch(self):
+ """
+ Return the bbox Patch, or None if the `.patches.FancyBboxPatch`
+ is not made.
+ """
+ return self._bbox_patch
+
+ def update_bbox_position_size(self, renderer):
+ """
+ Update the location and the size of the bbox.
+
+ This method should be used when the position and size of the bbox needs
+ to be updated before actually drawing the bbox.
+ """
+ if self._bbox_patch:
+ # don't use self.get_unitless_position here, which refers to text
+ # position in Text:
+ posx = float(self.convert_xunits(self._x))
+ posy = float(self.convert_yunits(self._y))
+ posx, posy = self.get_transform().transform((posx, posy))
+
+ x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
+ self._bbox_patch.set_bounds(0., 0., w_box, h_box)
+ self._bbox_patch.set_transform(
+ Affine2D()
+ .rotate_deg(self.get_rotation())
+ .translate(posx + x_box, posy + y_box))
+ fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
+ self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
+
+ def _update_clip_properties(self):
+ if self._bbox_patch:
+ clipprops = dict(clip_box=self.clipbox,
+ clip_path=self._clippath,
+ clip_on=self._clipon)
+ self._bbox_patch.update(clipprops)
+
+ def set_clip_box(self, clipbox):
+ # docstring inherited.
+ super().set_clip_box(clipbox)
+ self._update_clip_properties()
+
+ def set_clip_path(self, path, transform=None):
+ # docstring inherited.
+ super().set_clip_path(path, transform)
+ self._update_clip_properties()
+
+ def set_clip_on(self, b):
+ # docstring inherited.
+ super().set_clip_on(b)
+ self._update_clip_properties()
+
+ def get_wrap(self):
+ """Return whether the text can be wrapped."""
+ return self._wrap
+
+ def set_wrap(self, wrap):
+ """
+ Set whether the text can be wrapped.
+
+ Wrapping makes sure the text is confined to the (sub)figure box. It
+ does not take into account any other artists.
+
+ Parameters
+ ----------
+ wrap : bool
+
+ Notes
+ -----
+ Wrapping does not work together with
+ ``savefig(..., bbox_inches='tight')`` (which is also used internally
+ by ``%matplotlib inline`` in IPython/Jupyter). The 'tight' setting
+ rescales the canvas to accommodate all content and happens before
+ wrapping.
+ """
+ self._wrap = wrap
+
+ def _get_wrap_line_width(self):
+ """
+ Return the maximum line width for wrapping text based on the current
+ orientation.
+ """
+ x0, y0 = self.get_transform().transform(self.get_position())
+ figure_box = self.get_figure().get_window_extent()
+
+ # Calculate available width based on text alignment
+ alignment = self.get_horizontalalignment()
+ self.set_rotation_mode('anchor')
+ rotation = self.get_rotation()
+
+ left = self._get_dist_to_box(rotation, x0, y0, figure_box)
+ right = self._get_dist_to_box(
+ (180 + rotation) % 360, x0, y0, figure_box)
+
+ if alignment == 'left':
+ line_width = left
+ elif alignment == 'right':
+ line_width = right
+ else:
+ line_width = 2 * min(left, right)
+
+ return line_width
+
+ def _get_dist_to_box(self, rotation, x0, y0, figure_box):
+ """
+ Return the distance from the given points to the boundaries of a
+ rotated box, in pixels.
+ """
+ if rotation > 270:
+ quad = rotation - 270
+ h1 = (y0 - figure_box.y0) / math.cos(math.radians(quad))
+ h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad))
+ elif rotation > 180:
+ quad = rotation - 180
+ h1 = (x0 - figure_box.x0) / math.cos(math.radians(quad))
+ h2 = (y0 - figure_box.y0) / math.cos(math.radians(90 - quad))
+ elif rotation > 90:
+ quad = rotation - 90
+ h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad))
+ h2 = (x0 - figure_box.x0) / math.cos(math.radians(90 - quad))
+ else:
+ h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation))
+ h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation))
+
+ return min(h1, h2)
+
+ def _get_rendered_text_width(self, text):
+ """
+ Return the width of a given text string, in pixels.
+ """
+
+ w, h, d = self._renderer.get_text_width_height_descent(
+ text,
+ self.get_fontproperties(),
+ cbook.is_math_text(text))
+ return math.ceil(w)
+
+ def _get_wrapped_text(self):
+ """
+ Return a copy of the text string with new lines added so that the text
+ is wrapped relative to the parent figure (if `get_wrap` is True).
+ """
+ if not self.get_wrap():
+ return self.get_text()
+
+ # Not fit to handle breaking up latex syntax correctly, so
+ # ignore latex for now.
+ if self.get_usetex():
+ return self.get_text()
+
+ # Build the line incrementally, for a more accurate measure of length
+ line_width = self._get_wrap_line_width()
+ wrapped_lines = []
+
+ # New lines in the user's text force a split
+ unwrapped_lines = self.get_text().split('\n')
+
+ # Now wrap each individual unwrapped line
+ for unwrapped_line in unwrapped_lines:
+
+ sub_words = unwrapped_line.split(' ')
+ # Remove items from sub_words as we go, so stop when empty
+ while len(sub_words) > 0:
+ if len(sub_words) == 1:
+ # Only one word, so just add it to the end
+ wrapped_lines.append(sub_words.pop(0))
+ continue
+
+ for i in range(2, len(sub_words) + 1):
+ # Get width of all words up to and including here
+ line = ' '.join(sub_words[:i])
+ current_width = self._get_rendered_text_width(line)
+
+ # If all these words are too wide, append all not including
+ # last word
+ if current_width > line_width:
+ wrapped_lines.append(' '.join(sub_words[:i - 1]))
+ sub_words = sub_words[i - 1:]
+ break
+
+ # Otherwise if all words fit in the width, append them all
+ elif i == len(sub_words):
+ wrapped_lines.append(' '.join(sub_words[:i]))
+ sub_words = []
+ break
+
+ return '\n'.join(wrapped_lines)
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+
+ if renderer is not None:
+ self._renderer = renderer
+ if not self.get_visible():
+ return
+ if self.get_text() == '':
+ return
+
+ renderer.open_group('text', self.get_gid())
+
+ with self._cm_set(text=self._get_wrapped_text()):
+ bbox, info, descent = self._get_layout(renderer)
+ trans = self.get_transform()
+
+ # don't use self.get_position here, which refers to text
+ # position in Text:
+ x, y = self._x, self._y
+ if np.ma.is_masked(x):
+ x = np.nan
+ if np.ma.is_masked(y):
+ y = np.nan
+ posx = float(self.convert_xunits(x))
+ posy = float(self.convert_yunits(y))
+ posx, posy = trans.transform((posx, posy))
+ if np.isnan(posx) or np.isnan(posy):
+ return # don't throw a warning here
+ if not np.isfinite(posx) or not np.isfinite(posy):
+ _log.warning("posx and posy should be finite values")
+ return
+ canvasw, canvash = renderer.get_canvas_width_height()
+
+ # Update the location and size of the bbox
+ # (`.patches.FancyBboxPatch`), and draw it.
+ if self._bbox_patch:
+ self.update_bbox_position_size(renderer)
+ self._bbox_patch.draw(renderer)
+
+ gc = renderer.new_gc()
+ gc.set_foreground(self.get_color())
+ gc.set_alpha(self.get_alpha())
+ gc.set_url(self._url)
+ gc.set_antialiased(self._antialiased)
+ self._set_gc_clip(gc)
+
+ angle = self.get_rotation()
+
+ for line, wh, x, y in info:
+
+ mtext = self if len(info) == 1 else None
+ x = x + posx
+ y = y + posy
+ if renderer.flipy():
+ y = canvash - y
+ clean_line, ismath = self._preprocess_math(line)
+
+ if self.get_path_effects():
+ from matplotlib.patheffects import PathEffectRenderer
+ textrenderer = PathEffectRenderer(
+ self.get_path_effects(), renderer)
+ else:
+ textrenderer = renderer
+
+ if self.get_usetex():
+ textrenderer.draw_tex(gc, x, y, clean_line,
+ self._fontproperties, angle,
+ mtext=mtext)
+ else:
+ textrenderer.draw_text(gc, x, y, clean_line,
+ self._fontproperties, angle,
+ ismath=ismath, mtext=mtext)
+
+ gc.restore()
+ renderer.close_group('text')
+ self.stale = False
+
+ def get_color(self):
+ """Return the color of the text."""
+ return self._color
+
+ def get_fontproperties(self):
+ """Return the `.font_manager.FontProperties`."""
+ return self._fontproperties
+
+ def get_fontfamily(self):
+ """
+ Return the list of font families used for font lookup.
+
+ See Also
+ --------
+ .font_manager.FontProperties.get_family
+ """
+ return self._fontproperties.get_family()
+
+ def get_fontname(self):
+ """
+ Return the font name as a string.
+
+ See Also
+ --------
+ .font_manager.FontProperties.get_name
+ """
+ return self._fontproperties.get_name()
+
+ def get_fontstyle(self):
+ """
+ Return the font style as a string.
+
+ See Also
+ --------
+ .font_manager.FontProperties.get_style
+ """
+ return self._fontproperties.get_style()
+
+ def get_fontsize(self):
+ """
+ Return the font size as an integer.
+
+ See Also
+ --------
+ .font_manager.FontProperties.get_size_in_points
+ """
+ return self._fontproperties.get_size_in_points()
+
+ def get_fontvariant(self):
+ """
+ Return the font variant as a string.
+
+ See Also
+ --------
+ .font_manager.FontProperties.get_variant
+ """
+ return self._fontproperties.get_variant()
+
+ def get_fontweight(self):
+ """
+ Return the font weight as a string or a number.
+
+ See Also
+ --------
+ .font_manager.FontProperties.get_weight
+ """
+ return self._fontproperties.get_weight()
+
+ def get_stretch(self):
+ """
+ Return the font stretch as a string or a number.
+
+ See Also
+ --------
+ .font_manager.FontProperties.get_stretch
+ """
+ return self._fontproperties.get_stretch()
+
+ def get_horizontalalignment(self):
+ """
+ Return the horizontal alignment as a string. Will be one of
+ 'left', 'center' or 'right'.
+ """
+ return self._horizontalalignment
+
+ def get_unitless_position(self):
+ """Return the (x, y) unitless position of the text."""
+ # This will get the position with all unit information stripped away.
+ # This is here for convenience since it is done in several locations.
+ x = float(self.convert_xunits(self._x))
+ y = float(self.convert_yunits(self._y))
+ return x, y
+
+ def get_position(self):
+ """Return the (x, y) position of the text."""
+ # This should return the same data (possible unitized) as was
+ # specified with 'set_x' and 'set_y'.
+ return self._x, self._y
+
+ def get_text(self):
+ """Return the text string."""
+ return self._text
+
+ def get_verticalalignment(self):
+ """
+ Return the vertical alignment as a string. Will be one of
+ 'top', 'center', 'bottom', 'baseline' or 'center_baseline'.
+ """
+ return self._verticalalignment
+
+ def get_window_extent(self, renderer=None, dpi=None):
+ """
+ Return the `.Bbox` bounding the text, in display units.
+
+ In addition to being used internally, this is useful for specifying
+ clickable regions in a png file on a web page.
+
+ Parameters
+ ----------
+ renderer : Renderer, optional
+ A renderer is needed to compute the bounding box. If the artist
+ has already been drawn, the renderer is cached; thus, it is only
+ necessary to pass this argument when calling `get_window_extent`
+ before the first draw. In practice, it is usually easier to
+ trigger a draw first, e.g. by calling
+ `~.Figure.draw_without_rendering` or ``plt.show()``.
+
+ dpi : float, optional
+ The dpi value for computing the bbox, defaults to
+ ``self.get_figure(root=True).dpi`` (*not* the renderer dpi); should be set
+ e.g. if to match regions with a figure saved with a custom dpi value.
+ """
+ if not self.get_visible():
+ return Bbox.unit()
+
+ fig = self.get_figure(root=True)
+ if dpi is None:
+ dpi = fig.dpi
+ if self.get_text() == '':
+ with cbook._setattr_cm(fig, dpi=dpi):
+ tx, ty = self._get_xy_display()
+ return Bbox.from_bounds(tx, ty, 0, 0)
+
+ if renderer is not None:
+ self._renderer = renderer
+ if self._renderer is None:
+ self._renderer = fig._get_renderer()
+ if self._renderer is None:
+ raise RuntimeError(
+ "Cannot get window extent of text w/o renderer. You likely "
+ "want to call 'figure.draw_without_rendering()' first.")
+
+ with cbook._setattr_cm(fig, dpi=dpi):
+ bbox, info, descent = self._get_layout(self._renderer)
+ x, y = self.get_unitless_position()
+ x, y = self.get_transform().transform((x, y))
+ bbox = bbox.translated(x, y)
+ return bbox
+
+ def set_backgroundcolor(self, color):
+ """
+ Set the background color of the text by updating the bbox.
+
+ Parameters
+ ----------
+ color : :mpltype:`color`
+
+ See Also
+ --------
+ .set_bbox : To change the position of the bounding box
+ """
+ if self._bbox_patch is None:
+ self.set_bbox(dict(facecolor=color, edgecolor=color))
+ else:
+ self._bbox_patch.update(dict(facecolor=color))
+
+ self._update_clip_properties()
+ self.stale = True
+
+ def set_color(self, color):
+ """
+ Set the foreground color of the text
+
+ Parameters
+ ----------
+ color : :mpltype:`color`
+ """
+ # "auto" is only supported by axisartist, but we can just let it error
+ # out at draw time for simplicity.
+ if not cbook._str_equal(color, "auto"):
+ mpl.colors._check_color_like(color=color)
+ self._color = color
+ self.stale = True
+
+ def set_horizontalalignment(self, align):
+ """
+ Set the horizontal alignment relative to the anchor point.
+
+ See also :doc:`/gallery/text_labels_and_annotations/text_alignment`.
+
+ Parameters
+ ----------
+ align : {'left', 'center', 'right'}
+ """
+ _api.check_in_list(['center', 'right', 'left'], align=align)
+ self._horizontalalignment = align
+ self.stale = True
+
+ def set_multialignment(self, align):
+ """
+ Set the text alignment for multiline texts.
+
+ The layout of the bounding box of all the lines is determined by the
+ horizontalalignment and verticalalignment properties. This property
+ controls the alignment of the text lines within that box.
+
+ Parameters
+ ----------
+ align : {'left', 'right', 'center'}
+ """
+ _api.check_in_list(['center', 'right', 'left'], align=align)
+ self._multialignment = align
+ self.stale = True
+
+ def set_linespacing(self, spacing):
+ """
+ Set the line spacing as a multiple of the font size.
+
+ The default line spacing is 1.2.
+
+ Parameters
+ ----------
+ spacing : float (multiple of font size)
+ """
+ _api.check_isinstance(Real, spacing=spacing)
+ self._linespacing = spacing
+ self.stale = True
+
+ def set_fontfamily(self, fontname):
+ """
+ Set the font family. Can be either a single string, or a list of
+ strings in decreasing priority. Each string may be either a real font
+ name or a generic font class name. If the latter, the specific font
+ names will be looked up in the corresponding rcParams.
+
+ If a `Text` instance is constructed with ``fontfamily=None``, then the
+ font is set to :rc:`font.family`, and the
+ same is done when `set_fontfamily()` is called on an existing
+ `Text` instance.
+
+ Parameters
+ ----------
+ fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
+'monospace'}
+
+ See Also
+ --------
+ .font_manager.FontProperties.set_family
+ """
+ self._fontproperties.set_family(fontname)
+ self.stale = True
+
+ def set_fontvariant(self, variant):
+ """
+ Set the font variant.
+
+ Parameters
+ ----------
+ variant : {'normal', 'small-caps'}
+
+ See Also
+ --------
+ .font_manager.FontProperties.set_variant
+ """
+ self._fontproperties.set_variant(variant)
+ self.stale = True
+
+ def set_fontstyle(self, fontstyle):
+ """
+ Set the font style.
+
+ Parameters
+ ----------
+ fontstyle : {'normal', 'italic', 'oblique'}
+
+ See Also
+ --------
+ .font_manager.FontProperties.set_style
+ """
+ self._fontproperties.set_style(fontstyle)
+ self.stale = True
+
+ def set_fontsize(self, fontsize):
+ """
+ Set the font size.
+
+ Parameters
+ ----------
+ fontsize : float or {'xx-small', 'x-small', 'small', 'medium', \
+'large', 'x-large', 'xx-large'}
+ If a float, the fontsize in points. The string values denote sizes
+ relative to the default font size.
+
+ See Also
+ --------
+ .font_manager.FontProperties.set_size
+ """
+ self._fontproperties.set_size(fontsize)
+ self.stale = True
+
+ def get_math_fontfamily(self):
+ """
+ Return the font family name for math text rendered by Matplotlib.
+
+ The default value is :rc:`mathtext.fontset`.
+
+ See Also
+ --------
+ set_math_fontfamily
+ """
+ return self._fontproperties.get_math_fontfamily()
+
+ def set_math_fontfamily(self, fontfamily):
+ """
+ Set the font family for math text rendered by Matplotlib.
+
+ This does only affect Matplotlib's own math renderer. It has no effect
+ when rendering with TeX (``usetex=True``).
+
+ Parameters
+ ----------
+ fontfamily : str
+ The name of the font family.
+
+ Available font families are defined in the
+ :ref:`default matplotlibrc file
+ `.
+
+ See Also
+ --------
+ get_math_fontfamily
+ """
+ self._fontproperties.set_math_fontfamily(fontfamily)
+
+ def set_fontweight(self, weight):
+ """
+ Set the font weight.
+
+ Parameters
+ ----------
+ weight : {a numeric value in range 0-1000, 'ultralight', 'light', \
+'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', \
+'demi', 'bold', 'heavy', 'extra bold', 'black'}
+
+ See Also
+ --------
+ .font_manager.FontProperties.set_weight
+ """
+ self._fontproperties.set_weight(weight)
+ self.stale = True
+
+ def set_fontstretch(self, stretch):
+ """
+ Set the font stretch (horizontal condensation or expansion).
+
+ Parameters
+ ----------
+ stretch : {a numeric value in range 0-1000, 'ultra-condensed', \
+'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', \
+'expanded', 'extra-expanded', 'ultra-expanded'}
+
+ See Also
+ --------
+ .font_manager.FontProperties.set_stretch
+ """
+ self._fontproperties.set_stretch(stretch)
+ self.stale = True
+
+ def set_position(self, xy):
+ """
+ Set the (*x*, *y*) position of the text.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ """
+ self.set_x(xy[0])
+ self.set_y(xy[1])
+
+ def set_x(self, x):
+ """
+ Set the *x* position of the text.
+
+ Parameters
+ ----------
+ x : float
+ """
+ self._x = x
+ self.stale = True
+
+ def set_y(self, y):
+ """
+ Set the *y* position of the text.
+
+ Parameters
+ ----------
+ y : float
+ """
+ self._y = y
+ self.stale = True
+
+ def set_rotation(self, s):
+ """
+ Set the rotation of the text.
+
+ Parameters
+ ----------
+ s : float or {'vertical', 'horizontal'}
+ The rotation angle in degrees in mathematically positive direction
+ (counterclockwise). 'horizontal' equals 0, 'vertical' equals 90.
+ """
+ if isinstance(s, Real):
+ self._rotation = float(s) % 360
+ elif cbook._str_equal(s, 'horizontal') or s is None:
+ self._rotation = 0.
+ elif cbook._str_equal(s, 'vertical'):
+ self._rotation = 90.
+ else:
+ raise ValueError("rotation must be 'vertical', 'horizontal' or "
+ f"a number, not {s}")
+ self.stale = True
+
+ def set_transform_rotates_text(self, t):
+ """
+ Whether rotations of the transform affect the text direction.
+
+ Parameters
+ ----------
+ t : bool
+ """
+ self._transform_rotates_text = t
+ self.stale = True
+
+ def set_verticalalignment(self, align):
+ """
+ Set the vertical alignment relative to the anchor point.
+
+ See also :doc:`/gallery/text_labels_and_annotations/text_alignment`.
+
+ Parameters
+ ----------
+ align : {'baseline', 'bottom', 'center', 'center_baseline', 'top'}
+ """
+ _api.check_in_list(
+ ['top', 'bottom', 'center', 'baseline', 'center_baseline'],
+ align=align)
+ self._verticalalignment = align
+ self.stale = True
+
+ def set_text(self, s):
+ r"""
+ Set the text string *s*.
+
+ It may contain newlines (``\n``) or math in LaTeX syntax.
+
+ Parameters
+ ----------
+ s : object
+ Any object gets converted to its `str` representation, except for
+ ``None`` which is converted to an empty string.
+ """
+ s = '' if s is None else str(s)
+ if s != self._text:
+ self._text = s
+ self.stale = True
+
+ def _preprocess_math(self, s):
+ """
+ Return the string *s* after mathtext preprocessing, and the kind of
+ mathtext support needed.
+
+ - If *self* is configured to use TeX, return *s* unchanged except that
+ a single space gets escaped, and the flag "TeX".
+ - Otherwise, if *s* is mathtext (has an even number of unescaped dollar
+ signs) and ``parse_math`` is not set to False, return *s* and the
+ flag True.
+ - Otherwise, return *s* with dollar signs unescaped, and the flag
+ False.
+ """
+ if self.get_usetex():
+ if s == " ":
+ s = r"\ "
+ return s, "TeX"
+ elif not self.get_parse_math():
+ return s, False
+ elif cbook.is_math_text(s):
+ return s, True
+ else:
+ return s.replace(r"\$", "$"), False
+
+ def set_fontproperties(self, fp):
+ """
+ Set the font properties that control the text.
+
+ Parameters
+ ----------
+ fp : `.font_manager.FontProperties` or `str` or `pathlib.Path`
+ If a `str`, it is interpreted as a fontconfig pattern parsed by
+ `.FontProperties`. If a `pathlib.Path`, it is interpreted as the
+ absolute path to a font file.
+ """
+ self._fontproperties = FontProperties._from_any(fp).copy()
+ self.stale = True
+
+ @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
+ def set_usetex(self, usetex):
+ """
+ Parameters
+ ----------
+ usetex : bool or None
+ Whether to render using TeX, ``None`` means to use
+ :rc:`text.usetex`.
+ """
+ if usetex is None:
+ self._usetex = mpl.rcParams['text.usetex']
+ else:
+ self._usetex = bool(usetex)
+ self.stale = True
+
+ def get_usetex(self):
+ """Return whether this `Text` object uses TeX for rendering."""
+ return self._usetex
+
+ def set_parse_math(self, parse_math):
+ """
+ Override switch to disable any mathtext parsing for this `Text`.
+
+ Parameters
+ ----------
+ parse_math : bool
+ If False, this `Text` will never use mathtext. If True, mathtext
+ will be used if there is an even number of unescaped dollar signs.
+ """
+ self._parse_math = bool(parse_math)
+
+ def get_parse_math(self):
+ """Return whether mathtext parsing is considered for this `Text`."""
+ return self._parse_math
+
+ def set_fontname(self, fontname):
+ """
+ Alias for `set_fontfamily`.
+
+ One-way alias only: the getter differs.
+
+ Parameters
+ ----------
+ fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
+'monospace'}
+
+ See Also
+ --------
+ .font_manager.FontProperties.set_family
+
+ """
+ self.set_fontfamily(fontname)
+
+
+class OffsetFrom:
+ """Callable helper class for working with `Annotation`."""
+
+ def __init__(self, artist, ref_coord, unit="points"):
+ """
+ Parameters
+ ----------
+ artist : `~matplotlib.artist.Artist` or `.BboxBase` or `.Transform`
+ The object to compute the offset from.
+
+ ref_coord : (float, float)
+ If *artist* is an `.Artist` or `.BboxBase`, this values is
+ the location to of the offset origin in fractions of the
+ *artist* bounding box.
+
+ If *artist* is a transform, the offset origin is the
+ transform applied to this value.
+
+ unit : {'points, 'pixels'}, default: 'points'
+ The screen units to use (pixels or points) for the offset input.
+ """
+ self._artist = artist
+ x, y = ref_coord # Make copy when ref_coord is an array (and check the shape).
+ self._ref_coord = x, y
+ self.set_unit(unit)
+
+ def set_unit(self, unit):
+ """
+ Set the unit for input to the transform used by ``__call__``.
+
+ Parameters
+ ----------
+ unit : {'points', 'pixels'}
+ """
+ _api.check_in_list(["points", "pixels"], unit=unit)
+ self._unit = unit
+
+ def get_unit(self):
+ """Return the unit for input to the transform used by ``__call__``."""
+ return self._unit
+
+ def __call__(self, renderer):
+ """
+ Return the offset transform.
+
+ Parameters
+ ----------
+ renderer : `RendererBase`
+ The renderer to use to compute the offset
+
+ Returns
+ -------
+ `Transform`
+ Maps (x, y) in pixel or point units to screen units
+ relative to the given artist.
+ """
+ if isinstance(self._artist, Artist):
+ bbox = self._artist.get_window_extent(renderer)
+ xf, yf = self._ref_coord
+ x = bbox.x0 + bbox.width * xf
+ y = bbox.y0 + bbox.height * yf
+ elif isinstance(self._artist, BboxBase):
+ bbox = self._artist
+ xf, yf = self._ref_coord
+ x = bbox.x0 + bbox.width * xf
+ y = bbox.y0 + bbox.height * yf
+ elif isinstance(self._artist, Transform):
+ x, y = self._artist.transform(self._ref_coord)
+ else:
+ _api.check_isinstance((Artist, BboxBase, Transform), artist=self._artist)
+ scale = 1 if self._unit == "pixels" else renderer.points_to_pixels(1)
+ return Affine2D().scale(scale).translate(x, y)
+
+
+class _AnnotationBase:
+ def __init__(self,
+ xy,
+ xycoords='data',
+ annotation_clip=None):
+
+ x, y = xy # Make copy when xy is an array (and check the shape).
+ self.xy = x, y
+ self.xycoords = xycoords
+ self.set_annotation_clip(annotation_clip)
+
+ self._draggable = None
+
+ def _get_xy(self, renderer, xy, coords):
+ x, y = xy
+ xcoord, ycoord = coords if isinstance(coords, tuple) else (coords, coords)
+ if xcoord == 'data':
+ x = float(self.convert_xunits(x))
+ if ycoord == 'data':
+ y = float(self.convert_yunits(y))
+ return self._get_xy_transform(renderer, coords).transform((x, y))
+
+ def _get_xy_transform(self, renderer, coords):
+
+ if isinstance(coords, tuple):
+ xcoord, ycoord = coords
+ from matplotlib.transforms import blended_transform_factory
+ tr1 = self._get_xy_transform(renderer, xcoord)
+ tr2 = self._get_xy_transform(renderer, ycoord)
+ return blended_transform_factory(tr1, tr2)
+ elif callable(coords):
+ tr = coords(renderer)
+ if isinstance(tr, BboxBase):
+ return BboxTransformTo(tr)
+ elif isinstance(tr, Transform):
+ return tr
+ else:
+ raise TypeError(
+ f"xycoords callable must return a BboxBase or Transform, not a "
+ f"{type(tr).__name__}")
+ elif isinstance(coords, Artist):
+ bbox = coords.get_window_extent(renderer)
+ return BboxTransformTo(bbox)
+ elif isinstance(coords, BboxBase):
+ return BboxTransformTo(coords)
+ elif isinstance(coords, Transform):
+ return coords
+ elif not isinstance(coords, str):
+ raise TypeError(
+ f"'xycoords' must be an instance of str, tuple[str, str], Artist, "
+ f"Transform, or Callable, not a {type(coords).__name__}")
+
+ if coords == 'data':
+ return self.axes.transData
+ elif coords == 'polar':
+ from matplotlib.projections import PolarAxes
+ tr = PolarAxes.PolarTransform(apply_theta_transforms=False)
+ trans = tr + self.axes.transData
+ return trans
+
+ try:
+ bbox_name, unit = coords.split()
+ except ValueError: # i.e. len(coords.split()) != 2.
+ raise ValueError(f"{coords!r} is not a valid coordinate") from None
+
+ bbox0, xy0 = None, None
+
+ # if unit is offset-like
+ if bbox_name == "figure":
+ bbox0 = self.get_figure(root=False).figbbox
+ elif bbox_name == "subfigure":
+ bbox0 = self.get_figure(root=False).bbox
+ elif bbox_name == "axes":
+ bbox0 = self.axes.bbox
+
+ # reference x, y in display coordinate
+ if bbox0 is not None:
+ xy0 = bbox0.p0
+ elif bbox_name == "offset":
+ xy0 = self._get_position_xy(renderer)
+ else:
+ raise ValueError(f"{coords!r} is not a valid coordinate")
+
+ if unit == "points":
+ tr = Affine2D().scale(
+ self.get_figure(root=True).dpi / 72) # dpi/72 dots per point
+ elif unit == "pixels":
+ tr = Affine2D()
+ elif unit == "fontsize":
+ tr = Affine2D().scale(
+ self.get_size() * self.get_figure(root=True).dpi / 72)
+ elif unit == "fraction":
+ tr = Affine2D().scale(*bbox0.size)
+ else:
+ raise ValueError(f"{unit!r} is not a recognized unit")
+
+ return tr.translate(*xy0)
+
+ def set_annotation_clip(self, b):
+ """
+ Set the annotation's clipping behavior.
+
+ Parameters
+ ----------
+ b : bool or None
+ - True: The annotation will be clipped when ``self.xy`` is
+ outside the Axes.
+ - False: The annotation will always be drawn.
+ - None: The annotation will be clipped when ``self.xy`` is
+ outside the Axes and ``self.xycoords == "data"``.
+ """
+ self._annotation_clip = b
+
+ def get_annotation_clip(self):
+ """
+ Return the annotation's clipping behavior.
+
+ See `set_annotation_clip` for the meaning of return values.
+ """
+ return self._annotation_clip
+
+ def _get_position_xy(self, renderer):
+ """Return the pixel position of the annotated point."""
+ return self._get_xy(renderer, self.xy, self.xycoords)
+
+ def _check_xy(self, renderer=None):
+ """Check whether the annotation at *xy_pixel* should be drawn."""
+ if renderer is None:
+ renderer = self.get_figure(root=True)._get_renderer()
+ b = self.get_annotation_clip()
+ if b or (b is None and self.xycoords == "data"):
+ # check if self.xy is inside the Axes.
+ xy_pixel = self._get_position_xy(renderer)
+ return self.axes.contains_point(xy_pixel)
+ return True
+
+ def draggable(self, state=None, use_blit=False):
+ """
+ Set whether the annotation is draggable with the mouse.
+
+ Parameters
+ ----------
+ state : bool or None
+ - True or False: set the draggability.
+ - None: toggle the draggability.
+ use_blit : bool, default: False
+ Use blitting for faster image composition. For details see
+ :ref:`func-animation`.
+
+ Returns
+ -------
+ DraggableAnnotation or None
+ If the annotation is draggable, the corresponding
+ `.DraggableAnnotation` helper is returned.
+ """
+ from matplotlib.offsetbox import DraggableAnnotation
+ is_draggable = self._draggable is not None
+
+ # if state is None we'll toggle
+ if state is None:
+ state = not is_draggable
+
+ if state:
+ if self._draggable is None:
+ self._draggable = DraggableAnnotation(self, use_blit)
+ else:
+ if self._draggable is not None:
+ self._draggable.disconnect()
+ self._draggable = None
+
+ return self._draggable
+
+
+class Annotation(Text, _AnnotationBase):
+ """
+ An `.Annotation` is a `.Text` that can refer to a specific position *xy*.
+ Optionally an arrow pointing from the text to *xy* can be drawn.
+
+ Attributes
+ ----------
+ xy
+ The annotated position.
+ xycoords
+ The coordinate system for *xy*.
+ arrow_patch
+ A `.FancyArrowPatch` to point from *xytext* to *xy*.
+ """
+
+ def __str__(self):
+ return f"Annotation({self.xy[0]:g}, {self.xy[1]:g}, {self._text!r})"
+
+ def __init__(self, text, xy,
+ xytext=None,
+ xycoords='data',
+ textcoords=None,
+ arrowprops=None,
+ annotation_clip=None,
+ **kwargs):
+ """
+ Annotate the point *xy* with text *text*.
+
+ In the simplest form, the text is placed at *xy*.
+
+ Optionally, the text can be displayed in another position *xytext*.
+ An arrow pointing from the text to the annotated point *xy* can then
+ be added by defining *arrowprops*.
+
+ Parameters
+ ----------
+ text : str
+ The text of the annotation.
+
+ xy : (float, float)
+ The point *(x, y)* to annotate. The coordinate system is determined
+ by *xycoords*.
+
+ xytext : (float, float), default: *xy*
+ The position *(x, y)* to place the text at. The coordinate system
+ is determined by *textcoords*.
+
+ xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \
+callable, default: 'data'
+
+ The coordinate system that *xy* is given in. The following types
+ of values are supported:
+
+ - One of the following strings:
+
+ ==================== ============================================
+ Value Description
+ ==================== ============================================
+ 'figure points' Points from the lower left of the figure
+ 'figure pixels' Pixels from the lower left of the figure
+ 'figure fraction' Fraction of figure from lower left
+ 'subfigure points' Points from the lower left of the subfigure
+ 'subfigure pixels' Pixels from the lower left of the subfigure
+ 'subfigure fraction' Fraction of subfigure from lower left
+ 'axes points' Points from lower left corner of the Axes
+ 'axes pixels' Pixels from lower left corner of the Axes
+ 'axes fraction' Fraction of Axes from lower left
+ 'data' Use the coordinate system of the object
+ being annotated (default)
+ 'polar' *(theta, r)* if not native 'data'
+ coordinates
+ ==================== ============================================
+
+ Note that 'subfigure pixels' and 'figure pixels' are the same
+ for the parent figure, so users who want code that is usable in
+ a subfigure can use 'subfigure pixels'.
+
+ - An `.Artist`: *xy* is interpreted as a fraction of the artist's
+ `~matplotlib.transforms.Bbox`. E.g. *(0, 0)* would be the lower
+ left corner of the bounding box and *(0.5, 1)* would be the
+ center top of the bounding box.
+
+ - A `.Transform` to transform *xy* to screen coordinates.
+
+ - A function with one of the following signatures::
+
+ def transform(renderer) -> Bbox
+ def transform(renderer) -> Transform
+
+ where *renderer* is a `.RendererBase` subclass.
+
+ The result of the function is interpreted like the `.Artist` and
+ `.Transform` cases above.
+
+ - A tuple *(xcoords, ycoords)* specifying separate coordinate
+ systems for *x* and *y*. *xcoords* and *ycoords* must each be
+ of one of the above described types.
+
+ See :ref:`plotting-guide-annotation` for more details.
+
+ textcoords : single or two-tuple of str or `.Artist` or `.Transform` \
+or callable, default: value of *xycoords*
+ The coordinate system that *xytext* is given in.
+
+ All *xycoords* values are valid as well as the following strings:
+
+ ================= =================================================
+ Value Description
+ ================= =================================================
+ 'offset points' Offset, in points, from the *xy* value
+ 'offset pixels' Offset, in pixels, from the *xy* value
+ 'offset fontsize' Offset, relative to fontsize, from the *xy* value
+ ================= =================================================
+
+ arrowprops : dict, optional
+ The properties used to draw a `.FancyArrowPatch` arrow between the
+ positions *xy* and *xytext*. Defaults to None, i.e. no arrow is
+ drawn.
+
+ For historical reasons there are two different ways to specify
+ arrows, "simple" and "fancy":
+
+ **Simple arrow:**
+
+ If *arrowprops* does not contain the key 'arrowstyle' the
+ allowed keys are:
+
+ ========== =================================================
+ Key Description
+ ========== =================================================
+ width The width of the arrow in points
+ headwidth The width of the base of the arrow head in points
+ headlength The length of the arrow head in points
+ shrink Fraction of total length to shrink from both ends
+ ? Any `.FancyArrowPatch` property
+ ========== =================================================
+
+ The arrow is attached to the edge of the text box, the exact
+ position (corners or centers) depending on where it's pointing to.
+
+ **Fancy arrow:**
+
+ This is used if 'arrowstyle' is provided in the *arrowprops*.
+
+ Valid keys are the following `.FancyArrowPatch` parameters:
+
+ =============== ===================================
+ Key Description
+ =============== ===================================
+ arrowstyle The arrow style
+ connectionstyle The connection style
+ relpos See below; default is (0.5, 0.5)
+ patchA Default is bounding box of the text
+ patchB Default is None
+ shrinkA In points. Default is 2 points
+ shrinkB In points. Default is 2 points
+ mutation_scale Default is text size (in points)
+ mutation_aspect Default is 1
+ ? Any `.FancyArrowPatch` property
+ =============== ===================================
+
+ The exact starting point position of the arrow is defined by
+ *relpos*. It's a tuple of relative coordinates of the text box,
+ where (0, 0) is the lower left corner and (1, 1) is the upper
+ right corner. Values <0 and >1 are supported and specify points
+ outside the text box. By default (0.5, 0.5), so the starting point
+ is centered in the text box.
+
+ annotation_clip : bool or None, default: None
+ Whether to clip (i.e. not draw) the annotation when the annotation
+ point *xy* is outside the Axes area.
+
+ - If *True*, the annotation will be clipped when *xy* is outside
+ the Axes.
+ - If *False*, the annotation will always be drawn.
+ - If *None*, the annotation will be clipped when *xy* is outside
+ the Axes and *xycoords* is 'data'.
+
+ **kwargs
+ Additional kwargs are passed to `.Text`.
+
+ Returns
+ -------
+ `.Annotation`
+
+ See Also
+ --------
+ :ref:`annotations`
+
+ """
+ _AnnotationBase.__init__(self,
+ xy,
+ xycoords=xycoords,
+ annotation_clip=annotation_clip)
+ # warn about wonky input data
+ if (xytext is None and
+ textcoords is not None and
+ textcoords != xycoords):
+ _api.warn_external("You have used the `textcoords` kwarg, but "
+ "not the `xytext` kwarg. This can lead to "
+ "surprising results.")
+
+ # clean up textcoords and assign default
+ if textcoords is None:
+ textcoords = self.xycoords
+ self._textcoords = textcoords
+
+ # cleanup xytext defaults
+ if xytext is None:
+ xytext = self.xy
+ x, y = xytext
+
+ self.arrowprops = arrowprops
+ if arrowprops is not None:
+ arrowprops = arrowprops.copy()
+ if "arrowstyle" in arrowprops:
+ self._arrow_relpos = arrowprops.pop("relpos", (0.5, 0.5))
+ else:
+ # modified YAArrow API to be used with FancyArrowPatch
+ for key in ['width', 'headwidth', 'headlength', 'shrink']:
+ arrowprops.pop(key, None)
+ self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **arrowprops)
+ else:
+ self.arrow_patch = None
+
+ # Must come last, as some kwargs may be propagated to arrow_patch.
+ Text.__init__(self, x, y, text, **kwargs)
+
+ def contains(self, mouseevent):
+ if self._different_canvas(mouseevent):
+ return False, {}
+ contains, tinfo = Text.contains(self, mouseevent)
+ if self.arrow_patch is not None:
+ in_patch, _ = self.arrow_patch.contains(mouseevent)
+ contains = contains or in_patch
+ return contains, tinfo
+
+ @property
+ def xycoords(self):
+ return self._xycoords
+
+ @xycoords.setter
+ def xycoords(self, xycoords):
+ def is_offset(s):
+ return isinstance(s, str) and s.startswith("offset")
+
+ if (isinstance(xycoords, tuple) and any(map(is_offset, xycoords))
+ or is_offset(xycoords)):
+ raise ValueError("xycoords cannot be an offset coordinate")
+ self._xycoords = xycoords
+
+ @property
+ def xyann(self):
+ """
+ The text position.
+
+ See also *xytext* in `.Annotation`.
+ """
+ return self.get_position()
+
+ @xyann.setter
+ def xyann(self, xytext):
+ self.set_position(xytext)
+
+ def get_anncoords(self):
+ """
+ Return the coordinate system to use for `.Annotation.xyann`.
+
+ See also *xycoords* in `.Annotation`.
+ """
+ return self._textcoords
+
+ def set_anncoords(self, coords):
+ """
+ Set the coordinate system to use for `.Annotation.xyann`.
+
+ See also *xycoords* in `.Annotation`.
+ """
+ self._textcoords = coords
+
+ anncoords = property(get_anncoords, set_anncoords, doc="""
+ The coordinate system to use for `.Annotation.xyann`.""")
+
+ def set_figure(self, fig):
+ # docstring inherited
+ if self.arrow_patch is not None:
+ self.arrow_patch.set_figure(fig)
+ Artist.set_figure(self, fig)
+
+ def update_positions(self, renderer):
+ """
+ Update the pixel positions of the annotation text and the arrow patch.
+ """
+ # generate transformation
+ self.set_transform(self._get_xy_transform(renderer, self.anncoords))
+
+ arrowprops = self.arrowprops
+ if arrowprops is None:
+ return
+
+ bbox = Text.get_window_extent(self, renderer)
+
+ arrow_end = x1, y1 = self._get_position_xy(renderer) # Annotated pos.
+
+ ms = arrowprops.get("mutation_scale", self.get_size())
+ self.arrow_patch.set_mutation_scale(ms)
+
+ if "arrowstyle" not in arrowprops:
+ # Approximately simulate the YAArrow.
+ shrink = arrowprops.get('shrink', 0.0)
+ width = arrowprops.get('width', 4)
+ headwidth = arrowprops.get('headwidth', 12)
+ headlength = arrowprops.get('headlength', 12)
+
+ # NB: ms is in pts
+ stylekw = dict(head_length=headlength / ms,
+ head_width=headwidth / ms,
+ tail_width=width / ms)
+
+ self.arrow_patch.set_arrowstyle('simple', **stylekw)
+
+ # using YAArrow style:
+ # pick the corner of the text bbox closest to annotated point.
+ xpos = [(bbox.x0, 0), ((bbox.x0 + bbox.x1) / 2, 0.5), (bbox.x1, 1)]
+ ypos = [(bbox.y0, 0), ((bbox.y0 + bbox.y1) / 2, 0.5), (bbox.y1, 1)]
+ x, relposx = min(xpos, key=lambda v: abs(v[0] - x1))
+ y, relposy = min(ypos, key=lambda v: abs(v[0] - y1))
+ self._arrow_relpos = (relposx, relposy)
+ r = np.hypot(y - y1, x - x1)
+ shrink_pts = shrink * r / renderer.points_to_pixels(1)
+ self.arrow_patch.shrinkA = self.arrow_patch.shrinkB = shrink_pts
+
+ # adjust the starting point of the arrow relative to the textbox.
+ # TODO : Rotation needs to be accounted.
+ arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos
+ # The arrow is drawn from arrow_begin to arrow_end. It will be first
+ # clipped by patchA and patchB. Then it will be shrunk by shrinkA and
+ # shrinkB (in points). If patchA is not set, self.bbox_patch is used.
+ self.arrow_patch.set_positions(arrow_begin, arrow_end)
+
+ if "patchA" in arrowprops:
+ patchA = arrowprops["patchA"]
+ elif self._bbox_patch:
+ patchA = self._bbox_patch
+ elif self.get_text() == "":
+ patchA = None
+ else:
+ pad = renderer.points_to_pixels(4)
+ patchA = Rectangle(
+ xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2),
+ width=bbox.width + pad, height=bbox.height + pad,
+ transform=IdentityTransform(), clip_on=False)
+ self.arrow_patch.set_patchA(patchA)
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+ if renderer is not None:
+ self._renderer = renderer
+ if not self.get_visible() or not self._check_xy(renderer):
+ return
+ # Update text positions before `Text.draw` would, so that the
+ # FancyArrowPatch is correctly positioned.
+ self.update_positions(renderer)
+ self.update_bbox_position_size(renderer)
+ if self.arrow_patch is not None: # FancyArrowPatch
+ if (self.arrow_patch.get_figure(root=False) is None and
+ (fig := self.get_figure(root=False)) is not None):
+ self.arrow_patch.set_figure(fig)
+ self.arrow_patch.draw(renderer)
+ # Draw text, including FancyBboxPatch, after FancyArrowPatch.
+ # Otherwise, a wedge arrowstyle can land partly on top of the Bbox.
+ Text.draw(self, renderer)
+
+ def get_window_extent(self, renderer=None):
+ # docstring inherited
+ # This block is the same as in Text.get_window_extent, but we need to
+ # set the renderer before calling update_positions().
+ if not self.get_visible() or not self._check_xy(renderer):
+ return Bbox.unit()
+ if renderer is not None:
+ self._renderer = renderer
+ if self._renderer is None:
+ self._renderer = self.get_figure(root=True)._get_renderer()
+ if self._renderer is None:
+ raise RuntimeError('Cannot get window extent without renderer')
+
+ self.update_positions(self._renderer)
+
+ text_bbox = Text.get_window_extent(self)
+ bboxes = [text_bbox]
+
+ if self.arrow_patch is not None:
+ bboxes.append(self.arrow_patch.get_window_extent())
+
+ return Bbox.union(bboxes)
+
+ def get_tightbbox(self, renderer=None):
+ # docstring inherited
+ if not self._check_xy(renderer):
+ return Bbox.null()
+ return super().get_tightbbox(renderer)
+
+
+_docstring.interpd.register(Annotation=Annotation.__init__.__doc__)
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/ticker.pyi b/llava_video/lib/python3.10/site-packages/matplotlib/ticker.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..f990bf53ca429b0f6b06cc6f492013888f280437
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/ticker.pyi
@@ -0,0 +1,297 @@
+from collections.abc import Callable, Sequence
+from typing import Any, Literal
+
+from matplotlib.axis import Axis
+from matplotlib.transforms import Transform
+from matplotlib.projections.polar import _AxisWrapper
+
+import numpy as np
+
+class _DummyAxis:
+ __name__: str
+ def __init__(self, minpos: float = ...) -> None: ...
+ def get_view_interval(self) -> tuple[float, float]: ...
+ def set_view_interval(self, vmin: float, vmax: float) -> None: ...
+ def get_minpos(self) -> float: ...
+ def get_data_interval(self) -> tuple[float, float]: ...
+ def set_data_interval(self, vmin: float, vmax: float) -> None: ...
+ def get_tick_space(self) -> int: ...
+
+class TickHelper:
+ axis: None | Axis | _DummyAxis | _AxisWrapper
+ def set_axis(self, axis: Axis | _DummyAxis | _AxisWrapper | None) -> None: ...
+ def create_dummy_axis(self, **kwargs) -> None: ...
+
+class Formatter(TickHelper):
+ locs: list[float]
+ def __call__(self, x: float, pos: int | None = ...) -> str: ...
+ def format_ticks(self, values: list[float]) -> list[str]: ...
+ def format_data(self, value: float) -> str: ...
+ def format_data_short(self, value: float) -> str: ...
+ def get_offset(self) -> str: ...
+ def set_locs(self, locs: list[float]) -> None: ...
+ @staticmethod
+ def fix_minus(s: str) -> str: ...
+
+class NullFormatter(Formatter): ...
+
+class FixedFormatter(Formatter):
+ seq: Sequence[str]
+ offset_string: str
+ def __init__(self, seq: Sequence[str]) -> None: ...
+ def set_offset_string(self, ofs: str) -> None: ...
+
+class FuncFormatter(Formatter):
+ func: Callable[[float, int | None], str]
+ offset_string: str
+ # Callable[[float, int | None], str] | Callable[[float], str]
+ def __init__(self, func: Callable[..., str]) -> None: ...
+ def set_offset_string(self, ofs: str) -> None: ...
+
+class FormatStrFormatter(Formatter):
+ fmt: str
+ def __init__(self, fmt: str) -> None: ...
+
+class StrMethodFormatter(Formatter):
+ fmt: str
+ def __init__(self, fmt: str) -> None: ...
+
+class ScalarFormatter(Formatter):
+ orderOfMagnitude: int
+ format: str
+ def __init__(
+ self,
+ useOffset: bool | float | None = ...,
+ useMathText: bool | None = ...,
+ useLocale: bool | None = ...,
+ *,
+ usetex: bool | None = ...,
+ ) -> None: ...
+ offset: float
+ def get_usetex(self) -> bool: ...
+ def set_usetex(self, val: bool) -> None: ...
+ @property
+ def usetex(self) -> bool: ...
+ @usetex.setter
+ def usetex(self, val: bool) -> None: ...
+ def get_useOffset(self) -> bool: ...
+ def set_useOffset(self, val: bool | float) -> None: ...
+ @property
+ def useOffset(self) -> bool: ...
+ @useOffset.setter
+ def useOffset(self, val: bool | float) -> None: ...
+ def get_useLocale(self) -> bool: ...
+ def set_useLocale(self, val: bool | None) -> None: ...
+ @property
+ def useLocale(self) -> bool: ...
+ @useLocale.setter
+ def useLocale(self, val: bool | None) -> None: ...
+ def get_useMathText(self) -> bool: ...
+ def set_useMathText(self, val: bool | None) -> None: ...
+ @property
+ def useMathText(self) -> bool: ...
+ @useMathText.setter
+ def useMathText(self, val: bool | None) -> None: ...
+ def set_scientific(self, b: bool) -> None: ...
+ def set_powerlimits(self, lims: tuple[int, int]) -> None: ...
+ def format_data_short(self, value: float | np.ma.MaskedArray) -> str: ...
+ def format_data(self, value: float) -> str: ...
+
+class LogFormatter(Formatter):
+ minor_thresholds: tuple[float, float]
+ def __init__(
+ self,
+ base: float = ...,
+ labelOnlyBase: bool = ...,
+ minor_thresholds: tuple[float, float] | None = ...,
+ linthresh: float | None = ...,
+ ) -> None: ...
+ def set_base(self, base: float) -> None: ...
+ labelOnlyBase: bool
+ def set_label_minor(self, labelOnlyBase: bool) -> None: ...
+ def set_locs(self, locs: Any | None = ...) -> None: ...
+ def format_data(self, value: float) -> str: ...
+ def format_data_short(self, value: float) -> str: ...
+
+class LogFormatterExponent(LogFormatter): ...
+class LogFormatterMathtext(LogFormatter): ...
+class LogFormatterSciNotation(LogFormatterMathtext): ...
+
+class LogitFormatter(Formatter):
+ def __init__(
+ self,
+ *,
+ use_overline: bool = ...,
+ one_half: str = ...,
+ minor: bool = ...,
+ minor_threshold: int = ...,
+ minor_number: int = ...
+ ) -> None: ...
+ def use_overline(self, use_overline: bool) -> None: ...
+ def set_one_half(self, one_half: str) -> None: ...
+ def set_minor_threshold(self, minor_threshold: int) -> None: ...
+ def set_minor_number(self, minor_number: int) -> None: ...
+ def format_data_short(self, value: float) -> str: ...
+
+class EngFormatter(ScalarFormatter):
+ ENG_PREFIXES: dict[int, str]
+ unit: str
+ places: int | None
+ sep: str
+ def __init__(
+ self,
+ unit: str = ...,
+ places: int | None = ...,
+ sep: str = ...,
+ *,
+ usetex: bool | None = ...,
+ useMathText: bool | None = ...,
+ useOffset: bool | float | None = ...,
+ ) -> None: ...
+ def format_eng(self, num: float) -> str: ...
+
+class PercentFormatter(Formatter):
+ xmax: float
+ decimals: int | None
+ def __init__(
+ self,
+ xmax: float = ...,
+ decimals: int | None = ...,
+ symbol: str | None = ...,
+ is_latex: bool = ...,
+ ) -> None: ...
+ def format_pct(self, x: float, display_range: float) -> str: ...
+ def convert_to_pct(self, x: float) -> float: ...
+ @property
+ def symbol(self) -> str: ...
+ @symbol.setter
+ def symbol(self, symbol: str) -> None: ...
+
+class Locator(TickHelper):
+ MAXTICKS: int
+ def tick_values(self, vmin: float, vmax: float) -> Sequence[float]: ...
+ # Implementation accepts **kwargs, but is a no-op other than a warning
+ # Typing as **kwargs would require each subclass to accept **kwargs for mypy
+ def set_params(self) -> None: ...
+ def __call__(self) -> Sequence[float]: ...
+ def raise_if_exceeds(self, locs: Sequence[float]) -> Sequence[float]: ...
+ def nonsingular(self, v0: float, v1: float) -> tuple[float, float]: ...
+ def view_limits(self, vmin: float, vmax: float) -> tuple[float, float]: ...
+
+class IndexLocator(Locator):
+ offset: float
+ def __init__(self, base: float, offset: float) -> None: ...
+ def set_params(
+ self, base: float | None = ..., offset: float | None = ...
+ ) -> None: ...
+
+class FixedLocator(Locator):
+ nbins: int | None
+ def __init__(self, locs: Sequence[float], nbins: int | None = ...) -> None: ...
+ def set_params(self, nbins: int | None = ...) -> None: ...
+
+class NullLocator(Locator): ...
+
+class LinearLocator(Locator):
+ presets: dict[tuple[float, float], Sequence[float]]
+ def __init__(
+ self,
+ numticks: int | None = ...,
+ presets: dict[tuple[float, float], Sequence[float]] | None = ...,
+ ) -> None: ...
+ @property
+ def numticks(self) -> int: ...
+ @numticks.setter
+ def numticks(self, numticks: int | None) -> None: ...
+ def set_params(
+ self,
+ numticks: int | None = ...,
+ presets: dict[tuple[float, float], Sequence[float]] | None = ...,
+ ) -> None: ...
+
+class MultipleLocator(Locator):
+ def __init__(self, base: float = ..., offset: float = ...) -> None: ...
+ def set_params(self, base: float | None = ..., offset: float | None = ...) -> None: ...
+ def view_limits(self, dmin: float, dmax: float) -> tuple[float, float]: ...
+
+class _Edge_integer:
+ step: float
+ def __init__(self, step: float, offset: float) -> None: ...
+ def closeto(self, ms: float, edge: float) -> bool: ...
+ def le(self, x: float) -> float: ...
+ def ge(self, x: float) -> float: ...
+
+class MaxNLocator(Locator):
+ default_params: dict[str, Any]
+ def __init__(self, nbins: int | Literal["auto"] | None = ..., **kwargs) -> None: ...
+ def set_params(self, **kwargs) -> None: ...
+ def view_limits(self, dmin: float, dmax: float) -> tuple[float, float]: ...
+
+class LogLocator(Locator):
+ numticks: int | None
+ def __init__(
+ self,
+ base: float = ...,
+ subs: None | Literal["auto", "all"] | Sequence[float] = ...,
+ *,
+ numticks: int | None = ...,
+ ) -> None: ...
+ def set_params(
+ self,
+ base: float | None = ...,
+ subs: Literal["auto", "all"] | Sequence[float] | None = ...,
+ *,
+ numticks: int | None = ...,
+ ) -> None: ...
+
+class SymmetricalLogLocator(Locator):
+ numticks: int
+ def __init__(
+ self,
+ transform: Transform | None = ...,
+ subs: Sequence[float] | None = ...,
+ linthresh: float | None = ...,
+ base: float | None = ...,
+ ) -> None: ...
+ def set_params(
+ self, subs: Sequence[float] | None = ..., numticks: int | None = ...
+ ) -> None: ...
+
+class AsinhLocator(Locator):
+ linear_width: float
+ numticks: int
+ symthresh: float
+ base: int
+ subs: Sequence[float] | None
+ def __init__(
+ self,
+ linear_width: float,
+ numticks: int = ...,
+ symthresh: float = ...,
+ base: int = ...,
+ subs: Sequence[float] | None = ...,
+ ) -> None: ...
+ def set_params(
+ self,
+ numticks: int | None = ...,
+ symthresh: float | None = ...,
+ base: int | None = ...,
+ subs: Sequence[float] | None = ...,
+ ) -> None: ...
+
+class LogitLocator(MaxNLocator):
+ def __init__(
+ self, minor: bool = ..., *, nbins: Literal["auto"] | int = ...
+ ) -> None: ...
+ def set_params(self, minor: bool | None = ..., **kwargs) -> None: ...
+ @property
+ def minor(self) -> bool: ...
+ @minor.setter
+ def minor(self, value: bool) -> None: ...
+
+class AutoLocator(MaxNLocator):
+ def __init__(self) -> None: ...
+
+class AutoMinorLocator(Locator):
+ ndivs: int
+ def __init__(self, n: int | None = ...) -> None: ...
diff --git a/llava_video/lib/python3.10/site-packages/matplotlib/widgets.py b/llava_video/lib/python3.10/site-packages/matplotlib/widgets.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c676574310c3ccbed5daefca32278084750a3d8
--- /dev/null
+++ b/llava_video/lib/python3.10/site-packages/matplotlib/widgets.py
@@ -0,0 +1,4175 @@
+"""
+GUI neutral widgets
+===================
+
+Widgets that are designed to work for any of the GUI backends.
+All of these widgets require you to predefine an `~.axes.Axes`
+instance and pass that as the first parameter. Matplotlib doesn't try to
+be too smart with respect to layout -- you will have to figure out how
+wide and tall you want your Axes to be to accommodate your widget.
+"""
+
+from contextlib import ExitStack
+import copy
+import itertools
+from numbers import Integral, Number
+
+from cycler import cycler
+import numpy as np
+
+import matplotlib as mpl
+from . import (_api, _docstring, backend_tools, cbook, collections, colors,
+ text as mtext, ticker, transforms)
+from .lines import Line2D
+from .patches import Rectangle, Ellipse, Polygon
+from .transforms import TransformedPatchPath, Affine2D
+
+
+class LockDraw:
+ """
+ Some widgets, like the cursor, draw onto the canvas, and this is not
+ desirable under all circumstances, like when the toolbar is in zoom-to-rect
+ mode and drawing a rectangle. To avoid this, a widget can acquire a
+ canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the
+ canvas; this will prevent other widgets from doing so at the same time (if
+ they also try to acquire the lock first).
+ """
+
+ def __init__(self):
+ self._owner = None
+
+ def __call__(self, o):
+ """Reserve the lock for *o*."""
+ if not self.available(o):
+ raise ValueError('already locked')
+ self._owner = o
+
+ def release(self, o):
+ """Release the lock from *o*."""
+ if not self.available(o):
+ raise ValueError('you do not own this lock')
+ self._owner = None
+
+ def available(self, o):
+ """Return whether drawing is available to *o*."""
+ return not self.locked() or self.isowner(o)
+
+ def isowner(self, o):
+ """Return whether *o* owns this lock."""
+ return self._owner is o
+
+ def locked(self):
+ """Return whether the lock is currently held by an owner."""
+ return self._owner is not None
+
+
+class Widget:
+ """
+ Abstract base class for GUI neutral widgets.
+ """
+ drawon = True
+ eventson = True
+ _active = True
+
+ def set_active(self, active):
+ """Set whether the widget is active."""
+ self._active = active
+
+ def get_active(self):
+ """Get whether the widget is active."""
+ return self._active
+
+ # set_active is overridden by SelectorWidgets.
+ active = property(get_active, set_active, doc="Is the widget active?")
+
+ def ignore(self, event):
+ """
+ Return whether *event* should be ignored.
+
+ This method should be called at the beginning of any event callback.
+ """
+ return not self.active
+
+
+class AxesWidget(Widget):
+ """
+ Widget connected to a single `~matplotlib.axes.Axes`.
+
+ To guarantee that the widget remains responsive and not garbage-collected,
+ a reference to the object should be maintained by the user.
+
+ This is necessary because the callback registry
+ maintains only weak-refs to the functions, which are member
+ functions of the widget. If there are no references to the widget
+ object it may be garbage collected which will disconnect the callbacks.
+
+ Attributes
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+ canvas : `~matplotlib.backend_bases.FigureCanvasBase`
+ The parent figure canvas for the widget.
+ active : bool
+ If False, the widget does not respond to events.
+ """
+
+ def __init__(self, ax):
+ self.ax = ax
+ self._cids = []
+
+ canvas = property(lambda self: self.ax.get_figure(root=True).canvas)
+
+ def connect_event(self, event, callback):
+ """
+ Connect a callback function with an event.
+
+ This should be used in lieu of ``figure.canvas.mpl_connect`` since this
+ function stores callback ids for later clean up.
+ """
+ cid = self.canvas.mpl_connect(event, callback)
+ self._cids.append(cid)
+
+ def disconnect_events(self):
+ """Disconnect all events created by this widget."""
+ for c in self._cids:
+ self.canvas.mpl_disconnect(c)
+
+ def _get_data_coords(self, event):
+ """Return *event*'s data coordinates in this widget's Axes."""
+ # This method handles the possibility that event.inaxes != self.ax (which may
+ # occur if multiple Axes are overlaid), in which case event.xdata/.ydata will
+ # be wrong. Note that we still special-case the common case where
+ # event.inaxes == self.ax and avoid re-running the inverse data transform,
+ # because that can introduce floating point errors for synthetic events.
+ return ((event.xdata, event.ydata) if event.inaxes is self.ax
+ else self.ax.transData.inverted().transform((event.x, event.y)))
+
+
+class Button(AxesWidget):
+ """
+ A GUI neutral button.
+
+ For the button to remain responsive you must keep a reference to it.
+ Call `.on_clicked` to connect to the button.
+
+ Attributes
+ ----------
+ ax
+ The `~.axes.Axes` the button renders into.
+ label
+ A `.Text` instance.
+ color
+ The color of the button when not hovering.
+ hovercolor
+ The color of the button when hovering.
+ """
+
+ def __init__(self, ax, label, image=None,
+ color='0.85', hovercolor='0.95', *, useblit=True):
+ """
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` instance the button will be placed into.
+ label : str
+ The button text.
+ image : array-like or PIL Image
+ The image to place in the button, if not *None*. The parameter is
+ directly forwarded to `~.axes.Axes.imshow`.
+ color : :mpltype:`color`
+ The color of the button when not activated.
+ hovercolor : :mpltype:`color`
+ The color of the button when the mouse is over it.
+ useblit : bool, default: True
+ Use blitting for faster drawing if supported by the backend.
+ See the tutorial :ref:`blitting` for details.
+
+ .. versionadded:: 3.7
+ """
+ super().__init__(ax)
+
+ if image is not None:
+ ax.imshow(image)
+ self.label = ax.text(0.5, 0.5, label,
+ verticalalignment='center',
+ horizontalalignment='center',
+ transform=ax.transAxes)
+
+ self._useblit = useblit and self.canvas.supports_blit
+
+ self._observers = cbook.CallbackRegistry(signals=["clicked"])
+
+ self.connect_event('button_press_event', self._click)
+ self.connect_event('button_release_event', self._release)
+ self.connect_event('motion_notify_event', self._motion)
+ ax.set_navigate(False)
+ ax.set_facecolor(color)
+ ax.set_xticks([])
+ ax.set_yticks([])
+ self.color = color
+ self.hovercolor = hovercolor
+
+ def _click(self, event):
+ if not self.eventson or self.ignore(event) or not self.ax.contains(event)[0]:
+ return
+ if event.canvas.mouse_grabber != self.ax:
+ event.canvas.grab_mouse(self.ax)
+
+ def _release(self, event):
+ if self.ignore(event) or event.canvas.mouse_grabber != self.ax:
+ return
+ event.canvas.release_mouse(self.ax)
+ if self.eventson and self.ax.contains(event)[0]:
+ self._observers.process('clicked', event)
+
+ def _motion(self, event):
+ if self.ignore(event):
+ return
+ c = self.hovercolor if self.ax.contains(event)[0] else self.color
+ if not colors.same_color(c, self.ax.get_facecolor()):
+ self.ax.set_facecolor(c)
+ if self.drawon:
+ if self._useblit:
+ self.ax.draw_artist(self.ax)
+ self.canvas.blit(self.ax.bbox)
+ else:
+ self.canvas.draw()
+
+ def on_clicked(self, func):
+ """
+ Connect the callback function *func* to button click events.
+
+ Returns a connection id, which can be used to disconnect the callback.
+ """
+ return self._observers.connect('clicked', lambda event: func(event))
+
+ def disconnect(self, cid):
+ """Remove the callback function with connection id *cid*."""
+ self._observers.disconnect(cid)
+
+
+class SliderBase(AxesWidget):
+ """
+ The base class for constructing Slider widgets. Not intended for direct
+ usage.
+
+ For the slider to remain responsive you must maintain a reference to it.
+ """
+ def __init__(self, ax, orientation, closedmin, closedmax,
+ valmin, valmax, valfmt, dragging, valstep):
+ if ax.name == '3d':
+ raise ValueError('Sliders cannot be added to 3D Axes')
+
+ super().__init__(ax)
+ _api.check_in_list(['horizontal', 'vertical'], orientation=orientation)
+
+ self.orientation = orientation
+ self.closedmin = closedmin
+ self.closedmax = closedmax
+ self.valmin = valmin
+ self.valmax = valmax
+ self.valstep = valstep
+ self.drag_active = False
+ self.valfmt = valfmt
+
+ if orientation == "vertical":
+ ax.set_ylim((valmin, valmax))
+ axis = ax.yaxis
+ else:
+ ax.set_xlim((valmin, valmax))
+ axis = ax.xaxis
+
+ self._fmt = axis.get_major_formatter()
+ if not isinstance(self._fmt, ticker.ScalarFormatter):
+ self._fmt = ticker.ScalarFormatter()
+ self._fmt.set_axis(axis)
+ self._fmt.set_useOffset(False) # No additive offset.
+ self._fmt.set_useMathText(True) # x sign before multiplicative offset.
+
+ ax.set_axis_off()
+ ax.set_navigate(False)
+
+ self.connect_event("button_press_event", self._update)
+ self.connect_event("button_release_event", self._update)
+ if dragging:
+ self.connect_event("motion_notify_event", self._update)
+ self._observers = cbook.CallbackRegistry(signals=["changed"])
+
+ def _stepped_value(self, val):
+ """Return *val* coerced to closest number in the ``valstep`` grid."""
+ if isinstance(self.valstep, Number):
+ val = (self.valmin
+ + round((val - self.valmin) / self.valstep) * self.valstep)
+ elif self.valstep is not None:
+ valstep = np.asanyarray(self.valstep)
+ if valstep.ndim != 1:
+ raise ValueError(
+ f"valstep must have 1 dimension but has {valstep.ndim}"
+ )
+ val = valstep[np.argmin(np.abs(valstep - val))]
+ return val
+
+ def disconnect(self, cid):
+ """
+ Remove the observer with connection id *cid*.
+
+ Parameters
+ ----------
+ cid : int
+ Connection id of the observer to be removed.
+ """
+ self._observers.disconnect(cid)
+
+ def reset(self):
+ """Reset the slider to the initial value."""
+ if np.any(self.val != self.valinit):
+ self.set_val(self.valinit)
+
+
+class Slider(SliderBase):
+ """
+ A slider representing a floating point range.
+
+ Create a slider from *valmin* to *valmax* in Axes *ax*. For the slider to
+ remain responsive you must maintain a reference to it. Call
+ :meth:`on_changed` to connect to the slider event.
+
+ Attributes
+ ----------
+ val : float
+ Slider value.
+ """
+
+ def __init__(self, ax, label, valmin, valmax, *, valinit=0.5, valfmt=None,
+ closedmin=True, closedmax=True, slidermin=None,
+ slidermax=None, dragging=True, valstep=None,
+ orientation='horizontal', initcolor='r',
+ track_color='lightgrey', handle_style=None, **kwargs):
+ """
+ Parameters
+ ----------
+ ax : Axes
+ The Axes to put the slider in.
+
+ label : str
+ Slider label.
+
+ valmin : float
+ The minimum value of the slider.
+
+ valmax : float
+ The maximum value of the slider.
+
+ valinit : float, default: 0.5
+ The slider initial position.
+
+ valfmt : str, default: None
+ %-format string used to format the slider value. If None, a
+ `.ScalarFormatter` is used instead.
+
+ closedmin : bool, default: True
+ Whether the slider interval is closed on the bottom.
+
+ closedmax : bool, default: True
+ Whether the slider interval is closed on the top.
+
+ slidermin : Slider, default: None
+ Do not allow the current slider to have a value less than
+ the value of the Slider *slidermin*.
+
+ slidermax : Slider, default: None
+ Do not allow the current slider to have a value greater than
+ the value of the Slider *slidermax*.
+
+ dragging : bool, default: True
+ If True the slider can be dragged by the mouse.
+
+ valstep : float or array-like, default: None
+ If a float, the slider will snap to multiples of *valstep*.
+ If an array the slider will snap to the values in the array.
+
+ orientation : {'horizontal', 'vertical'}, default: 'horizontal'
+ The orientation of the slider.
+
+ initcolor : :mpltype:`color`, default: 'r'
+ The color of the line at the *valinit* position. Set to ``'none'``
+ for no line.
+
+ track_color : :mpltype:`color`, default: 'lightgrey'
+ The color of the background track. The track is accessible for
+ further styling via the *track* attribute.
+
+ handle_style : dict
+ Properties of the slider handle. Default values are
+
+ ========= ===== ======= ========================================
+ Key Value Default Description
+ ========= ===== ======= ========================================
+ facecolor color 'white' The facecolor of the slider handle.
+ edgecolor color '.75' The edgecolor of the slider handle.
+ size int 10 The size of the slider handle in points.
+ ========= ===== ======= ========================================
+
+ Other values will be transformed as marker{foo} and passed to the
+ `~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
+ result in ``markerstyle = 'x'``.
+
+ Notes
+ -----
+ Additional kwargs are passed on to ``self.poly`` which is the
+ `~matplotlib.patches.Rectangle` that draws the slider knob. See the
+ `.Rectangle` documentation for valid property names (``facecolor``,
+ ``edgecolor``, ``alpha``, etc.).
+ """
+ super().__init__(ax, orientation, closedmin, closedmax,
+ valmin, valmax, valfmt, dragging, valstep)
+
+ if slidermin is not None and not hasattr(slidermin, 'val'):
+ raise ValueError(
+ f"Argument slidermin ({type(slidermin)}) has no 'val'")
+ if slidermax is not None and not hasattr(slidermax, 'val'):
+ raise ValueError(
+ f"Argument slidermax ({type(slidermax)}) has no 'val'")
+ self.slidermin = slidermin
+ self.slidermax = slidermax
+ valinit = self._value_in_bounds(valinit)
+ if valinit is None:
+ valinit = valmin
+ self.val = valinit
+ self.valinit = valinit
+
+ defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10}
+ handle_style = {} if handle_style is None else handle_style
+ marker_props = {
+ f'marker{k}': v for k, v in {**defaults, **handle_style}.items()
+ }
+
+ if orientation == 'vertical':
+ self.track = Rectangle(
+ (.25, 0), .5, 1,
+ transform=ax.transAxes,
+ facecolor=track_color
+ )
+ ax.add_patch(self.track)
+ self.poly = ax.axhspan(valmin, valinit, .25, .75, **kwargs)
+ # Drawing a longer line and clipping it to the track avoids
+ # pixelation-related asymmetries.
+ self.hline = ax.axhline(valinit, 0, 1, color=initcolor, lw=1,
+ clip_path=TransformedPatchPath(self.track))
+ handleXY = [[0.5], [valinit]]
+ else:
+ self.track = Rectangle(
+ (0, .25), 1, .5,
+ transform=ax.transAxes,
+ facecolor=track_color
+ )
+ ax.add_patch(self.track)
+ self.poly = ax.axvspan(valmin, valinit, .25, .75, **kwargs)
+ self.vline = ax.axvline(valinit, 0, 1, color=initcolor, lw=1,
+ clip_path=TransformedPatchPath(self.track))
+ handleXY = [[valinit], [0.5]]
+ self._handle, = ax.plot(
+ *handleXY,
+ "o",
+ **marker_props,
+ clip_on=False
+ )
+
+ if orientation == 'vertical':
+ self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes,
+ verticalalignment='bottom',
+ horizontalalignment='center')
+
+ self.valtext = ax.text(0.5, -0.02, self._format(valinit),
+ transform=ax.transAxes,
+ verticalalignment='top',
+ horizontalalignment='center')
+ else:
+ self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes,
+ verticalalignment='center',
+ horizontalalignment='right')
+
+ self.valtext = ax.text(1.02, 0.5, self._format(valinit),
+ transform=ax.transAxes,
+ verticalalignment='center',
+ horizontalalignment='left')
+
+ self.set_val(valinit)
+
+ def _value_in_bounds(self, val):
+ """Makes sure *val* is with given bounds."""
+ val = self._stepped_value(val)
+
+ if val <= self.valmin:
+ if not self.closedmin:
+ return
+ val = self.valmin
+ elif val >= self.valmax:
+ if not self.closedmax:
+ return
+ val = self.valmax
+
+ if self.slidermin is not None and val <= self.slidermin.val:
+ if not self.closedmin:
+ return
+ val = self.slidermin.val
+
+ if self.slidermax is not None and val >= self.slidermax.val:
+ if not self.closedmax:
+ return
+ val = self.slidermax.val
+ return val
+
+ def _update(self, event):
+ """Update the slider position."""
+ if self.ignore(event) or event.button != 1:
+ return
+
+ if event.name == 'button_press_event' and self.ax.contains(event)[0]:
+ self.drag_active = True
+ event.canvas.grab_mouse(self.ax)
+
+ if not self.drag_active:
+ return
+
+ if (event.name == 'button_release_event'
+ or event.name == 'button_press_event' and not self.ax.contains(event)[0]):
+ self.drag_active = False
+ event.canvas.release_mouse(self.ax)
+ return
+
+ xdata, ydata = self._get_data_coords(event)
+ val = self._value_in_bounds(
+ xdata if self.orientation == 'horizontal' else ydata)
+ if val not in [None, self.val]:
+ self.set_val(val)
+
+ def _format(self, val):
+ """Pretty-print *val*."""
+ if self.valfmt is not None:
+ return self.valfmt % val
+ else:
+ _, s, _ = self._fmt.format_ticks([self.valmin, val, self.valmax])
+ # fmt.get_offset is actually the multiplicative factor, if any.
+ return s + self._fmt.get_offset()
+
+ def set_val(self, val):
+ """
+ Set slider value to *val*.
+
+ Parameters
+ ----------
+ val : float
+ """
+ if self.orientation == 'vertical':
+ self.poly.set_height(val - self.poly.get_y())
+ self._handle.set_ydata([val])
+ else:
+ self.poly.set_width(val - self.poly.get_x())
+ self._handle.set_xdata([val])
+ self.valtext.set_text(self._format(val))
+ if self.drawon:
+ self.ax.get_figure(root=True).canvas.draw_idle()
+ self.val = val
+ if self.eventson:
+ self._observers.process('changed', val)
+
+ def on_changed(self, func):
+ """
+ Connect *func* as callback function to changes of the slider value.
+
+ Parameters
+ ----------
+ func : callable
+ Function to call when slider is changed.
+ The function must accept a single float as its arguments.
+
+ Returns
+ -------
+ int
+ Connection id (which can be used to disconnect *func*).
+ """
+ return self._observers.connect('changed', lambda val: func(val))
+
+
+class RangeSlider(SliderBase):
+ """
+ A slider representing a range of floating point values. Defines the min and
+ max of the range via the *val* attribute as a tuple of (min, max).
+
+ Create a slider that defines a range contained within [*valmin*, *valmax*]
+ in Axes *ax*. For the slider to remain responsive you must maintain a
+ reference to it. Call :meth:`on_changed` to connect to the slider event.
+
+ Attributes
+ ----------
+ val : tuple of float
+ Slider value.
+ """
+
+ def __init__(
+ self,
+ ax,
+ label,
+ valmin,
+ valmax,
+ *,
+ valinit=None,
+ valfmt=None,
+ closedmin=True,
+ closedmax=True,
+ dragging=True,
+ valstep=None,
+ orientation="horizontal",
+ track_color='lightgrey',
+ handle_style=None,
+ **kwargs,
+ ):
+ """
+ Parameters
+ ----------
+ ax : Axes
+ The Axes to put the slider in.
+
+ label : str
+ Slider label.
+
+ valmin : float
+ The minimum value of the slider.
+
+ valmax : float
+ The maximum value of the slider.
+
+ valinit : tuple of float or None, default: None
+ The initial positions of the slider. If None the initial positions
+ will be at the 25th and 75th percentiles of the range.
+
+ valfmt : str, default: None
+ %-format string used to format the slider values. If None, a
+ `.ScalarFormatter` is used instead.
+
+ closedmin : bool, default: True
+ Whether the slider interval is closed on the bottom.
+
+ closedmax : bool, default: True
+ Whether the slider interval is closed on the top.
+
+ dragging : bool, default: True
+ If True the slider can be dragged by the mouse.
+
+ valstep : float, default: None
+ If given, the slider will snap to multiples of *valstep*.
+
+ orientation : {'horizontal', 'vertical'}, default: 'horizontal'
+ The orientation of the slider.
+
+ track_color : :mpltype:`color`, default: 'lightgrey'
+ The color of the background track. The track is accessible for
+ further styling via the *track* attribute.
+
+ handle_style : dict
+ Properties of the slider handles. Default values are
+
+ ========= ===== ======= =========================================
+ Key Value Default Description
+ ========= ===== ======= =========================================
+ facecolor color 'white' The facecolor of the slider handles.
+ edgecolor color '.75' The edgecolor of the slider handles.
+ size int 10 The size of the slider handles in points.
+ ========= ===== ======= =========================================
+
+ Other values will be transformed as marker{foo} and passed to the
+ `~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
+ result in ``markerstyle = 'x'``.
+
+ Notes
+ -----
+ Additional kwargs are passed on to ``self.poly`` which is the
+ `~matplotlib.patches.Polygon` that draws the slider knob. See the
+ `.Polygon` documentation for valid property names (``facecolor``,
+ ``edgecolor``, ``alpha``, etc.).
+ """
+ super().__init__(ax, orientation, closedmin, closedmax,
+ valmin, valmax, valfmt, dragging, valstep)
+
+ # Set a value to allow _value_in_bounds() to work.
+ self.val = (valmin, valmax)
+ if valinit is None:
+ # Place at the 25th and 75th percentiles
+ extent = valmax - valmin
+ valinit = np.array([valmin + extent * 0.25,
+ valmin + extent * 0.75])
+ else:
+ valinit = self._value_in_bounds(valinit)
+ self.val = valinit
+ self.valinit = valinit
+
+ defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10}
+ handle_style = {} if handle_style is None else handle_style
+ marker_props = {
+ f'marker{k}': v for k, v in {**defaults, **handle_style}.items()
+ }
+
+ if orientation == "vertical":
+ self.track = Rectangle(
+ (.25, 0), .5, 2,
+ transform=ax.transAxes,
+ facecolor=track_color
+ )
+ ax.add_patch(self.track)
+ poly_transform = self.ax.get_yaxis_transform(which="grid")
+ handleXY_1 = [.5, valinit[0]]
+ handleXY_2 = [.5, valinit[1]]
+ else:
+ self.track = Rectangle(
+ (0, .25), 1, .5,
+ transform=ax.transAxes,
+ facecolor=track_color
+ )
+ ax.add_patch(self.track)
+ poly_transform = self.ax.get_xaxis_transform(which="grid")
+ handleXY_1 = [valinit[0], .5]
+ handleXY_2 = [valinit[1], .5]
+ self.poly = Polygon(np.zeros([5, 2]), **kwargs)
+ self._update_selection_poly(*valinit)
+ self.poly.set_transform(poly_transform)
+ self.poly.get_path()._interpolation_steps = 100
+ self.ax.add_patch(self.poly)
+ self.ax._request_autoscale_view()
+ self._handles = [
+ ax.plot(
+ *handleXY_1,
+ "o",
+ **marker_props,
+ clip_on=False
+ )[0],
+ ax.plot(
+ *handleXY_2,
+ "o",
+ **marker_props,
+ clip_on=False
+ )[0]
+ ]
+
+ if orientation == "vertical":
+ self.label = ax.text(
+ 0.5,
+ 1.02,
+ label,
+ transform=ax.transAxes,
+ verticalalignment="bottom",
+ horizontalalignment="center",
+ )
+
+ self.valtext = ax.text(
+ 0.5,
+ -0.02,
+ self._format(valinit),
+ transform=ax.transAxes,
+ verticalalignment="top",
+ horizontalalignment="center",
+ )
+ else:
+ self.label = ax.text(
+ -0.02,
+ 0.5,
+ label,
+ transform=ax.transAxes,
+ verticalalignment="center",
+ horizontalalignment="right",
+ )
+
+ self.valtext = ax.text(
+ 1.02,
+ 0.5,
+ self._format(valinit),
+ transform=ax.transAxes,
+ verticalalignment="center",
+ horizontalalignment="left",
+ )
+
+ self._active_handle = None
+ self.set_val(valinit)
+
+ def _update_selection_poly(self, vmin, vmax):
+ """
+ Update the vertices of the *self.poly* slider in-place
+ to cover the data range *vmin*, *vmax*.
+ """
+ # The vertices are positioned
+ # 1 ------ 2
+ # | |
+ # 0, 4 ---- 3
+ verts = self.poly.xy
+ if self.orientation == "vertical":
+ verts[0] = verts[4] = .25, vmin
+ verts[1] = .25, vmax
+ verts[2] = .75, vmax
+ verts[3] = .75, vmin
+ else:
+ verts[0] = verts[4] = vmin, .25
+ verts[1] = vmin, .75
+ verts[2] = vmax, .75
+ verts[3] = vmax, .25
+
+ def _min_in_bounds(self, min):
+ """Ensure the new min value is between valmin and self.val[1]."""
+ if min <= self.valmin:
+ if not self.closedmin:
+ return self.val[0]
+ min = self.valmin
+
+ if min > self.val[1]:
+ min = self.val[1]
+ return self._stepped_value(min)
+
+ def _max_in_bounds(self, max):
+ """Ensure the new max value is between valmax and self.val[0]."""
+ if max >= self.valmax:
+ if not self.closedmax:
+ return self.val[1]
+ max = self.valmax
+
+ if max <= self.val[0]:
+ max = self.val[0]
+ return self._stepped_value(max)
+
+ def _value_in_bounds(self, vals):
+ """Clip min, max values to the bounds."""
+ return (self._min_in_bounds(vals[0]), self._max_in_bounds(vals[1]))
+
+ def _update_val_from_pos(self, pos):
+ """Update the slider value based on a given position."""
+ idx = np.argmin(np.abs(self.val - pos))
+ if idx == 0:
+ val = self._min_in_bounds(pos)
+ self.set_min(val)
+ else:
+ val = self._max_in_bounds(pos)
+ self.set_max(val)
+ if self._active_handle:
+ if self.orientation == "vertical":
+ self._active_handle.set_ydata([val])
+ else:
+ self._active_handle.set_xdata([val])
+
+ def _update(self, event):
+ """Update the slider position."""
+ if self.ignore(event) or event.button != 1:
+ return
+
+ if event.name == "button_press_event" and self.ax.contains(event)[0]:
+ self.drag_active = True
+ event.canvas.grab_mouse(self.ax)
+
+ if not self.drag_active:
+ return
+
+ if (event.name == "button_release_event"
+ or event.name == "button_press_event" and not self.ax.contains(event)[0]):
+ self.drag_active = False
+ event.canvas.release_mouse(self.ax)
+ self._active_handle = None
+ return
+
+ # determine which handle was grabbed
+ xdata, ydata = self._get_data_coords(event)
+ handle_index = np.argmin(np.abs(
+ [h.get_xdata()[0] - xdata for h in self._handles]
+ if self.orientation == "horizontal" else
+ [h.get_ydata()[0] - ydata for h in self._handles]))
+ handle = self._handles[handle_index]
+
+ # these checks ensure smooth behavior if the handles swap which one
+ # has a higher value. i.e. if one is dragged over and past the other.
+ if handle is not self._active_handle:
+ self._active_handle = handle
+
+ self._update_val_from_pos(xdata if self.orientation == "horizontal" else ydata)
+
+ def _format(self, val):
+ """Pretty-print *val*."""
+ if self.valfmt is not None:
+ return f"({self.valfmt % val[0]}, {self.valfmt % val[1]})"
+ else:
+ _, s1, s2, _ = self._fmt.format_ticks(
+ [self.valmin, *val, self.valmax]
+ )
+ # fmt.get_offset is actually the multiplicative factor, if any.
+ s1 += self._fmt.get_offset()
+ s2 += self._fmt.get_offset()
+ # Use f string to avoid issues with backslashes when cast to a str
+ return f"({s1}, {s2})"
+
+ def set_min(self, min):
+ """
+ Set the lower value of the slider to *min*.
+
+ Parameters
+ ----------
+ min : float
+ """
+ self.set_val((min, self.val[1]))
+
+ def set_max(self, max):
+ """
+ Set the lower value of the slider to *max*.
+
+ Parameters
+ ----------
+ max : float
+ """
+ self.set_val((self.val[0], max))
+
+ def set_val(self, val):
+ """
+ Set slider value to *val*.
+
+ Parameters
+ ----------
+ val : tuple or array-like of float
+ """
+ val = np.sort(val)
+ _api.check_shape((2,), val=val)
+ # Reset value to allow _value_in_bounds() to work.
+ self.val = (self.valmin, self.valmax)
+ vmin, vmax = self._value_in_bounds(val)
+ self._update_selection_poly(vmin, vmax)
+ if self.orientation == "vertical":
+ self._handles[0].set_ydata([vmin])
+ self._handles[1].set_ydata([vmax])
+ else:
+ self._handles[0].set_xdata([vmin])
+ self._handles[1].set_xdata([vmax])
+
+ self.valtext.set_text(self._format((vmin, vmax)))
+
+ if self.drawon:
+ self.ax.get_figure(root=True).canvas.draw_idle()
+ self.val = (vmin, vmax)
+ if self.eventson:
+ self._observers.process("changed", (vmin, vmax))
+
+ def on_changed(self, func):
+ """
+ Connect *func* as callback function to changes of the slider value.
+
+ Parameters
+ ----------
+ func : callable
+ Function to call when slider is changed. The function
+ must accept a 2-tuple of floats as its argument.
+
+ Returns
+ -------
+ int
+ Connection id (which can be used to disconnect *func*).
+ """
+ return self._observers.connect('changed', lambda val: func(val))
+
+
+def _expand_text_props(props):
+ props = cbook.normalize_kwargs(props, mtext.Text)
+ return cycler(**props)() if props else itertools.repeat({})
+
+
+class CheckButtons(AxesWidget):
+ r"""
+ A GUI neutral set of check buttons.
+
+ For the check buttons to remain responsive you must keep a
+ reference to this object.
+
+ Connect to the CheckButtons with the `.on_clicked` method.
+
+ Attributes
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+ labels : list of `~matplotlib.text.Text`
+ The text label objects of the check buttons.
+ """
+
+ def __init__(self, ax, labels, actives=None, *, useblit=True,
+ label_props=None, frame_props=None, check_props=None):
+ """
+ Add check buttons to `~.axes.Axes` instance *ax*.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+ labels : list of str
+ The labels of the check buttons.
+ actives : list of bool, optional
+ The initial check states of the buttons. The list must have the
+ same length as *labels*. If not given, all buttons are unchecked.
+ useblit : bool, default: True
+ Use blitting for faster drawing if supported by the backend.
+ See the tutorial :ref:`blitting` for details.
+
+ .. versionadded:: 3.7
+
+ label_props : dict, optional
+ Dictionary of `.Text` properties to be used for the labels.
+
+ .. versionadded:: 3.7
+ frame_props : dict, optional
+ Dictionary of scatter `.Collection` properties to be used for the
+ check button frame. Defaults (label font size / 2)**2 size, black
+ edgecolor, no facecolor, and 1.0 linewidth.
+
+ .. versionadded:: 3.7
+ check_props : dict, optional
+ Dictionary of scatter `.Collection` properties to be used for the
+ check button check. Defaults to (label font size / 2)**2 size,
+ black color, and 1.0 linewidth.
+
+ .. versionadded:: 3.7
+ """
+ super().__init__(ax)
+
+ _api.check_isinstance((dict, None), label_props=label_props,
+ frame_props=frame_props, check_props=check_props)
+
+ ax.set_xticks([])
+ ax.set_yticks([])
+ ax.set_navigate(False)
+
+ if actives is None:
+ actives = [False] * len(labels)
+
+ self._useblit = useblit and self.canvas.supports_blit
+ self._background = None
+
+ ys = np.linspace(1, 0, len(labels)+2)[1:-1]
+
+ label_props = _expand_text_props(label_props)
+ self.labels = [
+ ax.text(0.25, y, label, transform=ax.transAxes,
+ horizontalalignment="left", verticalalignment="center",
+ **props)
+ for y, label, props in zip(ys, labels, label_props)]
+ text_size = np.array([text.get_fontsize() for text in self.labels]) / 2
+
+ frame_props = {
+ 's': text_size**2,
+ 'linewidth': 1,
+ **cbook.normalize_kwargs(frame_props, collections.PathCollection),
+ 'marker': 's',
+ 'transform': ax.transAxes,
+ }
+ frame_props.setdefault('facecolor', frame_props.get('color', 'none'))
+ frame_props.setdefault('edgecolor', frame_props.pop('color', 'black'))
+ self._frames = ax.scatter([0.15] * len(ys), ys, **frame_props)
+ check_props = {
+ 'linewidth': 1,
+ 's': text_size**2,
+ **cbook.normalize_kwargs(check_props, collections.PathCollection),
+ 'marker': 'x',
+ 'transform': ax.transAxes,
+ 'animated': self._useblit,
+ }
+ check_props.setdefault('facecolor', check_props.pop('color', 'black'))
+ self._checks = ax.scatter([0.15] * len(ys), ys, **check_props)
+ # The user may have passed custom colours in check_props, so we need to
+ # create the checks (above), and modify the visibility after getting
+ # whatever the user set.
+ self._init_status(actives)
+
+ self.connect_event('button_press_event', self._clicked)
+ if self._useblit:
+ self.connect_event('draw_event', self._clear)
+
+ self._observers = cbook.CallbackRegistry(signals=["clicked"])
+
+ def _clear(self, event):
+ """Internal event handler to clear the buttons."""
+ if self.ignore(event) or self.canvas.is_saving():
+ return
+ self._background = self.canvas.copy_from_bbox(self.ax.bbox)
+ self.ax.draw_artist(self._checks)
+
+ def _clicked(self, event):
+ if self.ignore(event) or event.button != 1 or not self.ax.contains(event)[0]:
+ return
+ idxs = [ # Indices of frames and of texts that contain the event.
+ *self._frames.contains(event)[1]["ind"],
+ *[i for i, text in enumerate(self.labels) if text.contains(event)[0]]]
+ if idxs:
+ coords = self._frames.get_offset_transform().transform(
+ self._frames.get_offsets())
+ self.set_active( # Closest index, only looking in idxs.
+ idxs[(((event.x, event.y) - coords[idxs]) ** 2).sum(-1).argmin()])
+
+ def set_label_props(self, props):
+ """
+ Set properties of the `.Text` labels.
+
+ .. versionadded:: 3.7
+
+ Parameters
+ ----------
+ props : dict
+ Dictionary of `.Text` properties to be used for the labels.
+ """
+ _api.check_isinstance(dict, props=props)
+ props = _expand_text_props(props)
+ for text, prop in zip(self.labels, props):
+ text.update(prop)
+
+ def set_frame_props(self, props):
+ """
+ Set properties of the check button frames.
+
+ .. versionadded:: 3.7
+
+ Parameters
+ ----------
+ props : dict
+ Dictionary of `.Collection` properties to be used for the check
+ button frames.
+ """
+ _api.check_isinstance(dict, props=props)
+ if 's' in props: # Keep API consistent with constructor.
+ props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels))
+ self._frames.update(props)
+
+ def set_check_props(self, props):
+ """
+ Set properties of the check button checks.
+
+ .. versionadded:: 3.7
+
+ Parameters
+ ----------
+ props : dict
+ Dictionary of `.Collection` properties to be used for the check
+ button check.
+ """
+ _api.check_isinstance(dict, props=props)
+ if 's' in props: # Keep API consistent with constructor.
+ props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels))
+ actives = self.get_status()
+ self._checks.update(props)
+ # If new colours are supplied, then we must re-apply the status.
+ self._init_status(actives)
+
+ def set_active(self, index, state=None):
+ """
+ Modify the state of a check button by index.
+
+ Callbacks will be triggered if :attr:`eventson` is True.
+
+ Parameters
+ ----------
+ index : int
+ Index of the check button to toggle.
+
+ state : bool, optional
+ If a boolean value, set the state explicitly. If no value is
+ provided, the state is toggled.
+
+ Raises
+ ------
+ ValueError
+ If *index* is invalid.
+ TypeError
+ If *state* is not boolean.
+ """
+ if index not in range(len(self.labels)):
+ raise ValueError(f'Invalid CheckButton index: {index}')
+ _api.check_isinstance((bool, None), state=state)
+
+ invisible = colors.to_rgba('none')
+
+ facecolors = self._checks.get_facecolor()
+ if state is None:
+ state = colors.same_color(facecolors[index], invisible)
+ facecolors[index] = self._active_check_colors[index] if state else invisible
+ self._checks.set_facecolor(facecolors)
+
+ if self.drawon:
+ if self._useblit:
+ if self._background is not None:
+ self.canvas.restore_region(self._background)
+ self.ax.draw_artist(self._checks)
+ self.canvas.blit(self.ax.bbox)
+ else:
+ self.canvas.draw()
+
+ if self.eventson:
+ self._observers.process('clicked', self.labels[index].get_text())
+
+ def _init_status(self, actives):
+ """
+ Initialize properties to match active status.
+
+ The user may have passed custom colours in *check_props* to the
+ constructor, or to `.set_check_props`, so we need to modify the
+ visibility after getting whatever the user set.
+ """
+ self._active_check_colors = self._checks.get_facecolor()
+ if len(self._active_check_colors) == 1:
+ self._active_check_colors = np.repeat(self._active_check_colors,
+ len(actives), axis=0)
+ self._checks.set_facecolor(
+ [ec if active else "none"
+ for ec, active in zip(self._active_check_colors, actives)])
+
+ def clear(self):
+ """Uncheck all checkboxes."""
+
+ self._checks.set_facecolor(['none'] * len(self._active_check_colors))
+
+ if hasattr(self, '_lines'):
+ for l1, l2 in self._lines:
+ l1.set_visible(False)
+ l2.set_visible(False)
+
+ if self.drawon:
+ self.canvas.draw()
+
+ if self.eventson:
+ # Call with no label, as all checkboxes are being cleared.
+ self._observers.process('clicked', None)
+
+ def get_status(self):
+ """
+ Return a list of the status (True/False) of all of the check buttons.
+ """
+ return [not colors.same_color(color, colors.to_rgba("none"))
+ for color in self._checks.get_facecolors()]
+
+ def get_checked_labels(self):
+ """Return a list of labels currently checked by user."""
+
+ return [l.get_text() for l, box_checked in
+ zip(self.labels, self.get_status())
+ if box_checked]
+
+ def on_clicked(self, func):
+ """
+ Connect the callback function *func* to button click events.
+
+ Parameters
+ ----------
+ func : callable
+ When the button is clicked, call *func* with button label.
+ When all buttons are cleared, call *func* with None.
+ The callback func must have the signature::
+
+ def func(label: str | None) -> Any
+
+ Return values may exist, but are ignored.
+
+ Returns
+ -------
+ A connection id, which can be used to disconnect the callback.
+ """
+ return self._observers.connect('clicked', lambda text: func(text))
+
+ def disconnect(self, cid):
+ """Remove the observer with connection id *cid*."""
+ self._observers.disconnect(cid)
+
+
+class TextBox(AxesWidget):
+ """
+ A GUI neutral text input box.
+
+ For the text box to remain responsive you must keep a reference to it.
+
+ Call `.on_text_change` to be updated whenever the text changes.
+
+ Call `.on_submit` to be updated whenever the user hits enter or
+ leaves the text entry field.
+
+ Attributes
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+ label : `~matplotlib.text.Text`
+
+ color : :mpltype:`color`
+ The color of the text box when not hovering.
+ hovercolor : :mpltype:`color`
+ The color of the text box when hovering.
+ """
+
+ def __init__(self, ax, label, initial='', *,
+ color='.95', hovercolor='1', label_pad=.01,
+ textalignment="left"):
+ """
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` instance the button will be placed into.
+ label : str
+ Label for this text box.
+ initial : str
+ Initial value in the text box.
+ color : :mpltype:`color`
+ The color of the box.
+ hovercolor : :mpltype:`color`
+ The color of the box when the mouse is over it.
+ label_pad : float
+ The distance between the label and the right side of the textbox.
+ textalignment : {'left', 'center', 'right'}
+ The horizontal location of the text.
+ """
+ super().__init__(ax)
+
+ self._text_position = _api.check_getitem(
+ {"left": 0.05, "center": 0.5, "right": 0.95},
+ textalignment=textalignment)
+
+ self.label = ax.text(
+ -label_pad, 0.5, label, transform=ax.transAxes,
+ verticalalignment='center', horizontalalignment='right')
+
+ # TextBox's text object should not parse mathtext at all.
+ self.text_disp = self.ax.text(
+ self._text_position, 0.5, initial, transform=self.ax.transAxes,
+ verticalalignment='center', horizontalalignment=textalignment,
+ parse_math=False)
+
+ self._observers = cbook.CallbackRegistry(signals=["change", "submit"])
+
+ ax.set(
+ xlim=(0, 1), ylim=(0, 1), # s.t. cursor appears from first click.
+ navigate=False, facecolor=color,
+ xticks=[], yticks=[])
+
+ self.cursor_index = 0
+
+ self.cursor = ax.vlines(0, 0, 0, visible=False, color="k", lw=1,
+ transform=mpl.transforms.IdentityTransform())
+
+ self.connect_event('button_press_event', self._click)
+ self.connect_event('button_release_event', self._release)
+ self.connect_event('motion_notify_event', self._motion)
+ self.connect_event('key_press_event', self._keypress)
+ self.connect_event('resize_event', self._resize)
+
+ self.color = color
+ self.hovercolor = hovercolor
+
+ self.capturekeystrokes = False
+
+ @property
+ def text(self):
+ return self.text_disp.get_text()
+
+ def _rendercursor(self):
+ # this is a hack to figure out where the cursor should go.
+ # we draw the text up to where the cursor should go, measure
+ # and save its dimensions, draw the real text, then put the cursor
+ # at the saved dimensions
+
+ # This causes a single extra draw if the figure has never been rendered
+ # yet, which should be fine as we're going to repeatedly re-render the
+ # figure later anyways.
+ fig = self.ax.get_figure(root=True)
+ if fig._get_renderer() is None:
+ fig.canvas.draw()
+
+ text = self.text_disp.get_text() # Save value before overwriting it.
+ widthtext = text[:self.cursor_index]
+
+ bb_text = self.text_disp.get_window_extent()
+ self.text_disp.set_text(widthtext or ",")
+ bb_widthtext = self.text_disp.get_window_extent()
+
+ if bb_text.y0 == bb_text.y1: # Restoring the height if no text.
+ bb_text.y0 -= bb_widthtext.height / 2
+ bb_text.y1 += bb_widthtext.height / 2
+ elif not widthtext: # Keep width to 0.
+ bb_text.x1 = bb_text.x0
+ else: # Move the cursor using width of bb_widthtext.
+ bb_text.x1 = bb_text.x0 + bb_widthtext.width
+
+ self.cursor.set(
+ segments=[[(bb_text.x1, bb_text.y0), (bb_text.x1, bb_text.y1)]],
+ visible=True)
+ self.text_disp.set_text(text)
+
+ fig.canvas.draw()
+
+ def _release(self, event):
+ if self.ignore(event):
+ return
+ if event.canvas.mouse_grabber != self.ax:
+ return
+ event.canvas.release_mouse(self.ax)
+
+ def _keypress(self, event):
+ if self.ignore(event):
+ return
+ if self.capturekeystrokes:
+ key = event.key
+ text = self.text
+ if len(key) == 1:
+ text = (text[:self.cursor_index] + key +
+ text[self.cursor_index:])
+ self.cursor_index += 1
+ elif key == "right":
+ if self.cursor_index != len(text):
+ self.cursor_index += 1
+ elif key == "left":
+ if self.cursor_index != 0:
+ self.cursor_index -= 1
+ elif key == "home":
+ self.cursor_index = 0
+ elif key == "end":
+ self.cursor_index = len(text)
+ elif key == "backspace":
+ if self.cursor_index != 0:
+ text = (text[:self.cursor_index - 1] +
+ text[self.cursor_index:])
+ self.cursor_index -= 1
+ elif key == "delete":
+ if self.cursor_index != len(self.text):
+ text = (text[:self.cursor_index] +
+ text[self.cursor_index + 1:])
+ self.text_disp.set_text(text)
+ self._rendercursor()
+ if self.eventson:
+ self._observers.process('change', self.text)
+ if key in ["enter", "return"]:
+ self._observers.process('submit', self.text)
+
+ def set_val(self, val):
+ newval = str(val)
+ if self.text == newval:
+ return
+ self.text_disp.set_text(newval)
+ self._rendercursor()
+ if self.eventson:
+ self._observers.process('change', self.text)
+ self._observers.process('submit', self.text)
+
+ def begin_typing(self):
+ self.capturekeystrokes = True
+ # Disable keypress shortcuts, which may otherwise cause the figure to
+ # be saved, closed, etc., until the user stops typing. The way to
+ # achieve this depends on whether toolmanager is in use.
+ stack = ExitStack() # Register cleanup actions when user stops typing.
+ self._on_stop_typing = stack.close
+ toolmanager = getattr(
+ self.ax.get_figure(root=True).canvas.manager, "toolmanager", None)
+ if toolmanager is not None:
+ # If using toolmanager, lock keypresses, and plan to release the
+ # lock when typing stops.
+ toolmanager.keypresslock(self)
+ stack.callback(toolmanager.keypresslock.release, self)
+ else:
+ # If not using toolmanager, disable all keypress-related rcParams.
+ # Avoid spurious warnings if keymaps are getting deprecated.
+ with _api.suppress_matplotlib_deprecation_warning():
+ stack.enter_context(mpl.rc_context(
+ {k: [] for k in mpl.rcParams if k.startswith("keymap.")}))
+
+ def stop_typing(self):
+ if self.capturekeystrokes:
+ self._on_stop_typing()
+ self._on_stop_typing = None
+ notifysubmit = True
+ else:
+ notifysubmit = False
+ self.capturekeystrokes = False
+ self.cursor.set_visible(False)
+ self.ax.get_figure(root=True).canvas.draw()
+ if notifysubmit and self.eventson:
+ # Because process() might throw an error in the user's code, only
+ # call it once we've already done our cleanup.
+ self._observers.process('submit', self.text)
+
+ def _click(self, event):
+ if self.ignore(event):
+ return
+ if not self.ax.contains(event)[0]:
+ self.stop_typing()
+ return
+ if not self.eventson:
+ return
+ if event.canvas.mouse_grabber != self.ax:
+ event.canvas.grab_mouse(self.ax)
+ if not self.capturekeystrokes:
+ self.begin_typing()
+ self.cursor_index = self.text_disp._char_index_at(event.x)
+ self._rendercursor()
+
+ def _resize(self, event):
+ self.stop_typing()
+
+ def _motion(self, event):
+ if self.ignore(event):
+ return
+ c = self.hovercolor if self.ax.contains(event)[0] else self.color
+ if not colors.same_color(c, self.ax.get_facecolor()):
+ self.ax.set_facecolor(c)
+ if self.drawon:
+ self.ax.get_figure(root=True).canvas.draw()
+
+ def on_text_change(self, func):
+ """
+ When the text changes, call this *func* with event.
+
+ A connection id is returned which can be used to disconnect.
+ """
+ return self._observers.connect('change', lambda text: func(text))
+
+ def on_submit(self, func):
+ """
+ When the user hits enter or leaves the submission box, call this
+ *func* with event.
+
+ A connection id is returned which can be used to disconnect.
+ """
+ return self._observers.connect('submit', lambda text: func(text))
+
+ def disconnect(self, cid):
+ """Remove the observer with connection id *cid*."""
+ self._observers.disconnect(cid)
+
+
+class RadioButtons(AxesWidget):
+ """
+ A GUI neutral radio button.
+
+ For the buttons to remain responsive you must keep a reference to this
+ object.
+
+ Connect to the RadioButtons with the `.on_clicked` method.
+
+ Attributes
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+ activecolor : :mpltype:`color`
+ The color of the selected button.
+ labels : list of `.Text`
+ The button labels.
+ value_selected : str
+ The label text of the currently selected button.
+ index_selected : int
+ The index of the selected button.
+ """
+
+ def __init__(self, ax, labels, active=0, activecolor=None, *,
+ useblit=True, label_props=None, radio_props=None):
+ """
+ Add radio buttons to an `~.axes.Axes`.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The Axes to add the buttons to.
+ labels : list of str
+ The button labels.
+ active : int
+ The index of the initially selected button.
+ activecolor : :mpltype:`color`
+ The color of the selected button. The default is ``'blue'`` if not
+ specified here or in *radio_props*.
+ useblit : bool, default: True
+ Use blitting for faster drawing if supported by the backend.
+ See the tutorial :ref:`blitting` for details.
+
+ .. versionadded:: 3.7
+
+ label_props : dict or list of dict, optional
+ Dictionary of `.Text` properties to be used for the labels.
+
+ .. versionadded:: 3.7
+ radio_props : dict, optional
+ Dictionary of scatter `.Collection` properties to be used for the
+ radio buttons. Defaults to (label font size / 2)**2 size, black
+ edgecolor, and *activecolor* facecolor (when active).
+
+ .. note::
+ If a facecolor is supplied in *radio_props*, it will override
+ *activecolor*. This may be used to provide an active color per
+ button.
+
+ .. versionadded:: 3.7
+ """
+ super().__init__(ax)
+
+ _api.check_isinstance((dict, None), label_props=label_props,
+ radio_props=radio_props)
+
+ radio_props = cbook.normalize_kwargs(radio_props,
+ collections.PathCollection)
+ if activecolor is not None:
+ if 'facecolor' in radio_props:
+ _api.warn_external(
+ 'Both the *activecolor* parameter and the *facecolor* '
+ 'key in the *radio_props* parameter has been specified. '
+ '*activecolor* will be ignored.')
+ else:
+ activecolor = 'blue' # Default.
+
+ self._activecolor = activecolor
+ self._initial_active = active
+ self.value_selected = labels[active]
+ self.index_selected = active
+
+ ax.set_xticks([])
+ ax.set_yticks([])
+ ax.set_navigate(False)
+
+ ys = np.linspace(1, 0, len(labels) + 2)[1:-1]
+
+ self._useblit = useblit and self.canvas.supports_blit
+ self._background = None
+
+ label_props = _expand_text_props(label_props)
+ self.labels = [
+ ax.text(0.25, y, label, transform=ax.transAxes,
+ horizontalalignment="left", verticalalignment="center",
+ **props)
+ for y, label, props in zip(ys, labels, label_props)]
+ text_size = np.array([text.get_fontsize() for text in self.labels]) / 2
+
+ radio_props = {
+ 's': text_size**2,
+ **radio_props,
+ 'marker': 'o',
+ 'transform': ax.transAxes,
+ 'animated': self._useblit,
+ }
+ radio_props.setdefault('edgecolor', radio_props.get('color', 'black'))
+ radio_props.setdefault('facecolor',
+ radio_props.pop('color', activecolor))
+ self._buttons = ax.scatter([.15] * len(ys), ys, **radio_props)
+ # The user may have passed custom colours in radio_props, so we need to
+ # create the radios, and modify the visibility after getting whatever
+ # the user set.
+ self._active_colors = self._buttons.get_facecolor()
+ if len(self._active_colors) == 1:
+ self._active_colors = np.repeat(self._active_colors, len(labels),
+ axis=0)
+ self._buttons.set_facecolor(
+ [activecolor if i == active else "none"
+ for i, activecolor in enumerate(self._active_colors)])
+
+ self.connect_event('button_press_event', self._clicked)
+ if self._useblit:
+ self.connect_event('draw_event', self._clear)
+
+ self._observers = cbook.CallbackRegistry(signals=["clicked"])
+
+ def _clear(self, event):
+ """Internal event handler to clear the buttons."""
+ if self.ignore(event) or self.canvas.is_saving():
+ return
+ self._background = self.canvas.copy_from_bbox(self.ax.bbox)
+ self.ax.draw_artist(self._buttons)
+
+ def _clicked(self, event):
+ if self.ignore(event) or event.button != 1 or not self.ax.contains(event)[0]:
+ return
+ idxs = [ # Indices of buttons and of texts that contain the event.
+ *self._buttons.contains(event)[1]["ind"],
+ *[i for i, text in enumerate(self.labels) if text.contains(event)[0]]]
+ if idxs:
+ coords = self._buttons.get_offset_transform().transform(
+ self._buttons.get_offsets())
+ self.set_active( # Closest index, only looking in idxs.
+ idxs[(((event.x, event.y) - coords[idxs]) ** 2).sum(-1).argmin()])
+
+ def set_label_props(self, props):
+ """
+ Set properties of the `.Text` labels.
+
+ .. versionadded:: 3.7
+
+ Parameters
+ ----------
+ props : dict
+ Dictionary of `.Text` properties to be used for the labels.
+ """
+ _api.check_isinstance(dict, props=props)
+ props = _expand_text_props(props)
+ for text, prop in zip(self.labels, props):
+ text.update(prop)
+
+ def set_radio_props(self, props):
+ """
+ Set properties of the `.Text` labels.
+
+ .. versionadded:: 3.7
+
+ Parameters
+ ----------
+ props : dict
+ Dictionary of `.Collection` properties to be used for the radio
+ buttons.
+ """
+ _api.check_isinstance(dict, props=props)
+ if 's' in props: # Keep API consistent with constructor.
+ props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels))
+ self._buttons.update(props)
+ self._active_colors = self._buttons.get_facecolor()
+ if len(self._active_colors) == 1:
+ self._active_colors = np.repeat(self._active_colors,
+ len(self.labels), axis=0)
+ self._buttons.set_facecolor(
+ [activecolor if text.get_text() == self.value_selected else "none"
+ for text, activecolor in zip(self.labels, self._active_colors)])
+
+ @property
+ def activecolor(self):
+ return self._activecolor
+
+ @activecolor.setter
+ def activecolor(self, activecolor):
+ colors._check_color_like(activecolor=activecolor)
+ self._activecolor = activecolor
+ self.set_radio_props({'facecolor': activecolor})
+
+ def set_active(self, index):
+ """
+ Select button with number *index*.
+
+ Callbacks will be triggered if :attr:`eventson` is True.
+
+ Parameters
+ ----------
+ index : int
+ The index of the button to activate.
+
+ Raises
+ ------
+ ValueError
+ If the index is invalid.
+ """
+ if index not in range(len(self.labels)):
+ raise ValueError(f'Invalid RadioButton index: {index}')
+ self.value_selected = self.labels[index].get_text()
+ self.index_selected = index
+ button_facecolors = self._buttons.get_facecolor()
+ button_facecolors[:] = colors.to_rgba("none")
+ button_facecolors[index] = colors.to_rgba(self._active_colors[index])
+ self._buttons.set_facecolor(button_facecolors)
+
+ if self.drawon:
+ if self._useblit:
+ if self._background is not None:
+ self.canvas.restore_region(self._background)
+ self.ax.draw_artist(self._buttons)
+ self.canvas.blit(self.ax.bbox)
+ else:
+ self.canvas.draw()
+
+ if self.eventson:
+ self._observers.process('clicked', self.labels[index].get_text())
+
+ def clear(self):
+ """Reset the active button to the initially active one."""
+ self.set_active(self._initial_active)
+
+ def on_clicked(self, func):
+ """
+ Connect the callback function *func* to button click events.
+
+ Parameters
+ ----------
+ func : callable
+ When the button is clicked, call *func* with button label.
+ When all buttons are cleared, call *func* with None.
+ The callback func must have the signature::
+
+ def func(label: str | None) -> Any
+
+ Return values may exist, but are ignored.
+
+ Returns
+ -------
+ A connection id, which can be used to disconnect the callback.
+ """
+ return self._observers.connect('clicked', func)
+
+ def disconnect(self, cid):
+ """Remove the observer with connection id *cid*."""
+ self._observers.disconnect(cid)
+
+
+class SubplotTool(Widget):
+ """
+ A tool to adjust the subplot params of a `.Figure`.
+ """
+
+ def __init__(self, targetfig, toolfig):
+ """
+ Parameters
+ ----------
+ targetfig : `~matplotlib.figure.Figure`
+ The figure instance to adjust.
+ toolfig : `~matplotlib.figure.Figure`
+ The figure instance to embed the subplot tool into.
+ """
+
+ self.figure = toolfig
+ self.targetfig = targetfig
+ toolfig.subplots_adjust(left=0.2, right=0.9)
+ toolfig.suptitle("Click on slider to adjust subplot param")
+
+ self._sliders = []
+ names = ["left", "bottom", "right", "top", "wspace", "hspace"]
+ # The last subplot, removed below, keeps space for the "Reset" button.
+ for name, ax in zip(names, toolfig.subplots(len(names) + 1)):
+ ax.set_navigate(False)
+ slider = Slider(ax, name, 0, 1,
+ valinit=getattr(targetfig.subplotpars, name))
+ slider.on_changed(self._on_slider_changed)
+ self._sliders.append(slider)
+ toolfig.axes[-1].remove()
+ (self.sliderleft, self.sliderbottom, self.sliderright, self.slidertop,
+ self.sliderwspace, self.sliderhspace) = self._sliders
+ for slider in [self.sliderleft, self.sliderbottom,
+ self.sliderwspace, self.sliderhspace]:
+ slider.closedmax = False
+ for slider in [self.sliderright, self.slidertop]:
+ slider.closedmin = False
+
+ # constraints
+ self.sliderleft.slidermax = self.sliderright
+ self.sliderright.slidermin = self.sliderleft
+ self.sliderbottom.slidermax = self.slidertop
+ self.slidertop.slidermin = self.sliderbottom
+
+ bax = toolfig.add_axes([0.8, 0.05, 0.15, 0.075])
+ self.buttonreset = Button(bax, 'Reset')
+ self.buttonreset.on_clicked(self._on_reset)
+
+ def _on_slider_changed(self, _):
+ self.targetfig.subplots_adjust(
+ **{slider.label.get_text(): slider.val
+ for slider in self._sliders})
+ if self.drawon:
+ self.targetfig.canvas.draw()
+
+ def _on_reset(self, event):
+ with ExitStack() as stack:
+ # Temporarily disable drawing on self and self's sliders, and
+ # disconnect slider events (as the subplotparams can be temporarily
+ # invalid, depending on the order in which they are restored).
+ stack.enter_context(cbook._setattr_cm(self, drawon=False))
+ for slider in self._sliders:
+ stack.enter_context(
+ cbook._setattr_cm(slider, drawon=False, eventson=False))
+ # Reset the slider to the initial position.
+ for slider in self._sliders:
+ slider.reset()
+ if self.drawon:
+ event.canvas.draw() # Redraw the subplottool canvas.
+ self._on_slider_changed(None) # Apply changes to the target window.
+
+
+class Cursor(AxesWidget):
+ """
+ A crosshair cursor that spans the Axes and moves with mouse cursor.
+
+ For the cursor to remain responsive you must keep a reference to it.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` to attach the cursor to.
+ horizOn : bool, default: True
+ Whether to draw the horizontal line.
+ vertOn : bool, default: True
+ Whether to draw the vertical line.
+ useblit : bool, default: False
+ Use blitting for faster drawing if supported by the backend.
+ See the tutorial :ref:`blitting` for details.
+
+ Other Parameters
+ ----------------
+ **lineprops
+ `.Line2D` properties that control the appearance of the lines.
+ See also `~.Axes.axhline`.
+
+ Examples
+ --------
+ See :doc:`/gallery/widgets/cursor`.
+ """
+ def __init__(self, ax, *, horizOn=True, vertOn=True, useblit=False,
+ **lineprops):
+ super().__init__(ax)
+
+ self.connect_event('motion_notify_event', self.onmove)
+ self.connect_event('draw_event', self.clear)
+
+ self.visible = True
+ self.horizOn = horizOn
+ self.vertOn = vertOn
+ self.useblit = useblit and self.canvas.supports_blit
+
+ if self.useblit:
+ lineprops['animated'] = True
+ self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops)
+ self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops)
+
+ self.background = None
+ self.needclear = False
+
+ def clear(self, event):
+ """Internal event handler to clear the cursor."""
+ if self.ignore(event) or self.canvas.is_saving():
+ return
+ if self.useblit:
+ self.background = self.canvas.copy_from_bbox(self.ax.bbox)
+
+ def onmove(self, event):
+ """Internal event handler to draw the cursor when the mouse moves."""
+ if self.ignore(event):
+ return
+ if not self.canvas.widgetlock.available(self):
+ return
+ if not self.ax.contains(event)[0]:
+ self.linev.set_visible(False)
+ self.lineh.set_visible(False)
+ if self.needclear:
+ self.canvas.draw()
+ self.needclear = False
+ return
+ self.needclear = True
+ xdata, ydata = self._get_data_coords(event)
+ self.linev.set_xdata((xdata, xdata))
+ self.linev.set_visible(self.visible and self.vertOn)
+ self.lineh.set_ydata((ydata, ydata))
+ self.lineh.set_visible(self.visible and self.horizOn)
+ if not (self.visible and (self.vertOn or self.horizOn)):
+ return
+ # Redraw.
+ if self.useblit:
+ if self.background is not None:
+ self.canvas.restore_region(self.background)
+ self.ax.draw_artist(self.linev)
+ self.ax.draw_artist(self.lineh)
+ self.canvas.blit(self.ax.bbox)
+ else:
+ self.canvas.draw_idle()
+
+
+class MultiCursor(Widget):
+ """
+ Provide a vertical (default) and/or horizontal line cursor shared between
+ multiple Axes.
+
+ For the cursor to remain responsive you must keep a reference to it.
+
+ Parameters
+ ----------
+ canvas : object
+ This parameter is entirely unused and only kept for back-compatibility.
+
+ axes : list of `~matplotlib.axes.Axes`
+ The `~.axes.Axes` to attach the cursor to.
+
+ useblit : bool, default: True
+ Use blitting for faster drawing if supported by the backend.
+ See the tutorial :ref:`blitting`
+ for details.
+
+ horizOn : bool, default: False
+ Whether to draw the horizontal line.
+
+ vertOn : bool, default: True
+ Whether to draw the vertical line.
+
+ Other Parameters
+ ----------------
+ **lineprops
+ `.Line2D` properties that control the appearance of the lines.
+ See also `~.Axes.axhline`.
+
+ Examples
+ --------
+ See :doc:`/gallery/widgets/multicursor`.
+ """
+
+ def __init__(self, canvas, axes, *, useblit=True, horizOn=False, vertOn=True,
+ **lineprops):
+ # canvas is stored only to provide the deprecated .canvas attribute;
+ # once it goes away the unused argument won't need to be stored at all.
+ self._canvas = canvas
+
+ self.axes = axes
+ self.horizOn = horizOn
+ self.vertOn = vertOn
+
+ self._canvas_infos = {
+ ax.get_figure(root=True).canvas:
+ {"cids": [], "background": None} for ax in axes}
+
+ xmin, xmax = axes[-1].get_xlim()
+ ymin, ymax = axes[-1].get_ylim()
+ xmid = 0.5 * (xmin + xmax)
+ ymid = 0.5 * (ymin + ymax)
+
+ self.visible = True
+ self.useblit = (
+ useblit
+ and all(canvas.supports_blit for canvas in self._canvas_infos))
+
+ if self.useblit:
+ lineprops['animated'] = True
+
+ self.vlines = [ax.axvline(xmid, visible=False, **lineprops)
+ for ax in axes]
+ self.hlines = [ax.axhline(ymid, visible=False, **lineprops)
+ for ax in axes]
+
+ self.connect()
+
+ def connect(self):
+ """Connect events."""
+ for canvas, info in self._canvas_infos.items():
+ info["cids"] = [
+ canvas.mpl_connect('motion_notify_event', self.onmove),
+ canvas.mpl_connect('draw_event', self.clear),
+ ]
+
+ def disconnect(self):
+ """Disconnect events."""
+ for canvas, info in self._canvas_infos.items():
+ for cid in info["cids"]:
+ canvas.mpl_disconnect(cid)
+ info["cids"].clear()
+
+ def clear(self, event):
+ """Clear the cursor."""
+ if self.ignore(event):
+ return
+ if self.useblit:
+ for canvas, info in self._canvas_infos.items():
+ # someone has switched the canvas on us! This happens if
+ # `savefig` needs to save to a format the previous backend did
+ # not support (e.g. saving a figure using an Agg based backend
+ # saved to a vector format).
+ if canvas is not canvas.figure.canvas:
+ continue
+ info["background"] = canvas.copy_from_bbox(canvas.figure.bbox)
+
+ def onmove(self, event):
+ axs = [ax for ax in self.axes if ax.contains(event)[0]]
+ if self.ignore(event) or not axs or not event.canvas.widgetlock.available(self):
+ return
+ ax = cbook._topmost_artist(axs)
+ xdata, ydata = ((event.xdata, event.ydata) if event.inaxes is ax
+ else ax.transData.inverted().transform((event.x, event.y)))
+ for line in self.vlines:
+ line.set_xdata((xdata, xdata))
+ line.set_visible(self.visible and self.vertOn)
+ for line in self.hlines:
+ line.set_ydata((ydata, ydata))
+ line.set_visible(self.visible and self.horizOn)
+ if not (self.visible and (self.vertOn or self.horizOn)):
+ return
+ # Redraw.
+ if self.useblit:
+ for canvas, info in self._canvas_infos.items():
+ if info["background"]:
+ canvas.restore_region(info["background"])
+ if self.vertOn:
+ for ax, line in zip(self.axes, self.vlines):
+ ax.draw_artist(line)
+ if self.horizOn:
+ for ax, line in zip(self.axes, self.hlines):
+ ax.draw_artist(line)
+ for canvas in self._canvas_infos:
+ canvas.blit()
+ else:
+ for canvas in self._canvas_infos:
+ canvas.draw_idle()
+
+
+class _SelectorWidget(AxesWidget):
+
+ def __init__(self, ax, onselect=None, useblit=False, button=None,
+ state_modifier_keys=None, use_data_coordinates=False):
+ super().__init__(ax)
+
+ self._visible = True
+ if onselect is None:
+ self.onselect = lambda *args: None
+ else:
+ self.onselect = onselect
+ self.useblit = useblit and self.canvas.supports_blit
+ self.connect_default_events()
+
+ self._state_modifier_keys = dict(move=' ', clear='escape',
+ square='shift', center='control',
+ rotate='r')
+ self._state_modifier_keys.update(state_modifier_keys or {})
+ self._use_data_coordinates = use_data_coordinates
+
+ self.background = None
+
+ if isinstance(button, Integral):
+ self.validButtons = [button]
+ else:
+ self.validButtons = button
+
+ # Set to True when a selection is completed, otherwise is False
+ self._selection_completed = False
+
+ # will save the data (position at mouseclick)
+ self._eventpress = None
+ # will save the data (pos. at mouserelease)
+ self._eventrelease = None
+ self._prev_event = None
+ self._state = set()
+
+ def set_active(self, active):
+ super().set_active(active)
+ if active:
+ self.update_background(None)
+
+ def _get_animated_artists(self):
+ """
+ Convenience method to get all animated artists of the figure containing
+ this widget, excluding those already present in self.artists.
+ The returned tuple is not sorted by 'z_order': z_order sorting is
+ valid only when considering all artists and not only a subset of all
+ artists.
+ """
+ return tuple(a for ax_ in self.ax.get_figure().get_axes()
+ for a in ax_.get_children()
+ if a.get_animated() and a not in self.artists)
+
+ def update_background(self, event):
+ """Force an update of the background."""
+ # If you add a call to `ignore` here, you'll want to check edge case:
+ # `release` can call a draw event even when `ignore` is True.
+ if not self.useblit:
+ return
+ # Make sure that widget artists don't get accidentally included in the
+ # background, by re-rendering the background if needed (and then
+ # re-re-rendering the canvas with the visible widget artists).
+ # We need to remove all artists which will be drawn when updating
+ # the selector: if we have animated artists in the figure, it is safer
+ # to redrawn by default, in case they have updated by the callback
+ # zorder needs to be respected when redrawing
+ artists = sorted(self.artists + self._get_animated_artists(),
+ key=lambda a: a.get_zorder())
+ needs_redraw = any(artist.get_visible() for artist in artists)
+ with ExitStack() as stack:
+ if needs_redraw:
+ for artist in artists:
+ stack.enter_context(artist._cm_set(visible=False))
+ self.canvas.draw()
+ self.background = self.canvas.copy_from_bbox(self.ax.bbox)
+ if needs_redraw:
+ for artist in artists:
+ self.ax.draw_artist(artist)
+
+ def connect_default_events(self):
+ """Connect the major canvas events to methods."""
+ self.connect_event('motion_notify_event', self.onmove)
+ self.connect_event('button_press_event', self.press)
+ self.connect_event('button_release_event', self.release)
+ self.connect_event('draw_event', self.update_background)
+ self.connect_event('key_press_event', self.on_key_press)
+ self.connect_event('key_release_event', self.on_key_release)
+ self.connect_event('scroll_event', self.on_scroll)
+
+ def ignore(self, event):
+ # docstring inherited
+ if not self.active or not self.ax.get_visible():
+ return True
+ # If canvas was locked
+ if not self.canvas.widgetlock.available(self):
+ return True
+ if not hasattr(event, 'button'):
+ event.button = None
+ # Only do rectangle selection if event was triggered
+ # with a desired button
+ if (self.validButtons is not None
+ and event.button not in self.validButtons):
+ return True
+ # If no button was pressed yet ignore the event if it was out of the Axes.
+ if self._eventpress is None:
+ return not self.ax.contains(event)[0]
+ # If a button was pressed, check if the release-button is the same.
+ if event.button == self._eventpress.button:
+ return False
+ # If a button was pressed, check if the release-button is the same.
+ return (not self.ax.contains(event)[0] or
+ event.button != self._eventpress.button)
+
+ def update(self):
+ """Draw using blit() or draw_idle(), depending on ``self.useblit``."""
+ if (not self.ax.get_visible() or
+ self.ax.get_figure(root=True)._get_renderer() is None):
+ return
+ if self.useblit:
+ if self.background is not None:
+ self.canvas.restore_region(self.background)
+ else:
+ self.update_background(None)
+ # We need to draw all artists, which are not included in the
+ # background, therefore we also draw self._get_animated_artists()
+ # and we make sure that we respect z_order
+ artists = sorted(self.artists + self._get_animated_artists(),
+ key=lambda a: a.get_zorder())
+ for artist in artists:
+ self.ax.draw_artist(artist)
+ self.canvas.blit(self.ax.bbox)
+ else:
+ self.canvas.draw_idle()
+
+ def _get_data(self, event):
+ """Get the xdata and ydata for event, with limits."""
+ if event.xdata is None:
+ return None, None
+ xdata, ydata = self._get_data_coords(event)
+ xdata = np.clip(xdata, *self.ax.get_xbound())
+ ydata = np.clip(ydata, *self.ax.get_ybound())
+ return xdata, ydata
+
+ def _clean_event(self, event):
+ """
+ Preprocess an event:
+
+ - Replace *event* by the previous event if *event* has no ``xdata``.
+ - Get ``xdata`` and ``ydata`` from this widget's Axes, and clip them to the axes
+ limits.
+ - Update the previous event.
+ """
+ if event.xdata is None:
+ event = self._prev_event
+ else:
+ event = copy.copy(event)
+ event.xdata, event.ydata = self._get_data(event)
+ self._prev_event = event
+ return event
+
+ def press(self, event):
+ """Button press handler and validator."""
+ if not self.ignore(event):
+ event = self._clean_event(event)
+ self._eventpress = event
+ self._prev_event = event
+ key = event.key or ''
+ key = key.replace('ctrl', 'control')
+ # move state is locked in on a button press
+ if key == self._state_modifier_keys['move']:
+ self._state.add('move')
+ self._press(event)
+ return True
+ return False
+
+ def _press(self, event):
+ """Button press event handler."""
+
+ def release(self, event):
+ """Button release event handler and validator."""
+ if not self.ignore(event) and self._eventpress:
+ event = self._clean_event(event)
+ self._eventrelease = event
+ self._release(event)
+ self._eventpress = None
+ self._eventrelease = None
+ self._state.discard('move')
+ return True
+ return False
+
+ def _release(self, event):
+ """Button release event handler."""
+
+ def onmove(self, event):
+ """Cursor move event handler and validator."""
+ if not self.ignore(event) and self._eventpress:
+ event = self._clean_event(event)
+ self._onmove(event)
+ return True
+ return False
+
+ def _onmove(self, event):
+ """Cursor move event handler."""
+
+ def on_scroll(self, event):
+ """Mouse scroll event handler and validator."""
+ if not self.ignore(event):
+ self._on_scroll(event)
+
+ def _on_scroll(self, event):
+ """Mouse scroll event handler."""
+
+ def on_key_press(self, event):
+ """Key press event handler and validator for all selection widgets."""
+ if self.active:
+ key = event.key or ''
+ key = key.replace('ctrl', 'control')
+ if key == self._state_modifier_keys['clear']:
+ self.clear()
+ return
+ for (state, modifier) in self._state_modifier_keys.items():
+ if modifier in key.split('+'):
+ # 'rotate' is changing _state on press and is not removed
+ # from _state when releasing
+ if state == 'rotate':
+ if state in self._state:
+ self._state.discard(state)
+ else:
+ self._state.add(state)
+ else:
+ self._state.add(state)
+ self._on_key_press(event)
+
+ def _on_key_press(self, event):
+ """Key press event handler - for widget-specific key press actions."""
+
+ def on_key_release(self, event):
+ """Key release event handler and validator."""
+ if self.active:
+ key = event.key or ''
+ for (state, modifier) in self._state_modifier_keys.items():
+ # 'rotate' is changing _state on press and is not removed
+ # from _state when releasing
+ if modifier in key.split('+') and state != 'rotate':
+ self._state.discard(state)
+ self._on_key_release(event)
+
+ def _on_key_release(self, event):
+ """Key release event handler."""
+
+ def set_visible(self, visible):
+ """Set the visibility of the selector artists."""
+ self._visible = visible
+ for artist in self.artists:
+ artist.set_visible(visible)
+
+ def get_visible(self):
+ """Get the visibility of the selector artists."""
+ return self._visible
+
+ def clear(self):
+ """Clear the selection and set the selector ready to make a new one."""
+ self._clear_without_update()
+ self.update()
+
+ def _clear_without_update(self):
+ self._selection_completed = False
+ self.set_visible(False)
+
+ @property
+ def artists(self):
+ """Tuple of the artists of the selector."""
+ handles_artists = getattr(self, '_handles_artists', ())
+ return (self._selection_artist,) + handles_artists
+
+ def set_props(self, **props):
+ """
+ Set the properties of the selector artist.
+
+ See the *props* argument in the selector docstring to know which properties are
+ supported.
+ """
+ artist = self._selection_artist
+ props = cbook.normalize_kwargs(props, artist)
+ artist.set(**props)
+ if self.useblit:
+ self.update()
+
+ def set_handle_props(self, **handle_props):
+ """
+ Set the properties of the handles selector artist. See the
+ `handle_props` argument in the selector docstring to know which
+ properties are supported.
+ """
+ if not hasattr(self, '_handles_artists'):
+ raise NotImplementedError("This selector doesn't have handles.")
+
+ artist = self._handles_artists[0]
+ handle_props = cbook.normalize_kwargs(handle_props, artist)
+ for handle in self._handles_artists:
+ handle.set(**handle_props)
+ if self.useblit:
+ self.update()
+ self._handle_props.update(handle_props)
+
+ def _validate_state(self, state):
+ supported_state = [
+ key for key, value in self._state_modifier_keys.items()
+ if key != 'clear' and value != 'not-applicable'
+ ]
+ _api.check_in_list(supported_state, state=state)
+
+ def add_state(self, state):
+ """
+ Add a state to define the widget's behavior. See the
+ `state_modifier_keys` parameters for details.
+
+ Parameters
+ ----------
+ state : str
+ Must be a supported state of the selector. See the
+ `state_modifier_keys` parameters for details.
+
+ Raises
+ ------
+ ValueError
+ When the state is not supported by the selector.
+
+ """
+ self._validate_state(state)
+ self._state.add(state)
+
+ def remove_state(self, state):
+ """
+ Remove a state to define the widget's behavior. See the
+ `state_modifier_keys` parameters for details.
+
+ Parameters
+ ----------
+ state : str
+ Must be a supported state of the selector. See the
+ `state_modifier_keys` parameters for details.
+
+ Raises
+ ------
+ ValueError
+ When the state is not supported by the selector.
+
+ """
+ self._validate_state(state)
+ self._state.remove(state)
+
+
+class SpanSelector(_SelectorWidget):
+ """
+ Visually select a min/max range on a single axis and call a function with
+ those values.
+
+ To guarantee that the selector remains responsive, keep a reference to it.
+
+ In order to turn off the SpanSelector, set ``span_selector.active`` to
+ False. To turn it back on, set it to True.
+
+ Press and release events triggered at the same coordinates outside the
+ selection will clear the selector, except when
+ ``ignore_event_outside=True``.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+
+ onselect : callable with signature ``func(min: float, max: float)``
+ A callback function that is called after a release event and the
+ selection is created, changed or removed.
+
+ direction : {"horizontal", "vertical"}
+ The direction along which to draw the span selector.
+
+ minspan : float, default: 0
+ If selection is less than or equal to *minspan*, the selection is
+ removed (when already existing) or cancelled.
+
+ useblit : bool, default: False
+ If True, use the backend-dependent blitting features for faster
+ canvas updates. See the tutorial :ref:`blitting` for details.
+
+ props : dict, default: {'facecolor': 'red', 'alpha': 0.5}
+ Dictionary of `.Patch` properties.
+
+ onmove_callback : callable with signature ``func(min: float, max: float)``, optional
+ Called on mouse move while the span is being selected.
+
+ interactive : bool, default: False
+ Whether to draw a set of handles that allow interaction with the
+ widget after it is drawn.
+
+ button : `.MouseButton` or list of `.MouseButton`, default: all buttons
+ The mouse buttons which activate the span selector.
+
+ handle_props : dict, default: None
+ Properties of the handle lines at the edges of the span. Only used
+ when *interactive* is True. See `.Line2D` for valid properties.
+
+ grab_range : float, default: 10
+ Distance in pixels within which the interactive tool handles can be activated.
+
+ state_modifier_keys : dict, optional
+ Keyboard modifiers which affect the widget's behavior. Values
+ amend the defaults, which are:
+
+ - "clear": Clear the current shape, default: "escape".
+
+ drag_from_anywhere : bool, default: False
+ If `True`, the widget can be moved by clicking anywhere within its bounds.
+
+ ignore_event_outside : bool, default: False
+ If `True`, the event triggered outside the span selector will be ignored.
+
+ snap_values : 1D array-like, optional
+ Snap the selector edges to the given values.
+
+ Examples
+ --------
+ >>> import matplotlib.pyplot as plt
+ >>> import matplotlib.widgets as mwidgets
+ >>> fig, ax = plt.subplots()
+ >>> ax.plot([1, 2, 3], [10, 50, 100])
+ >>> def onselect(vmin, vmax):
+ ... print(vmin, vmax)
+ >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
+ ... props=dict(facecolor='blue', alpha=0.5))
+ >>> fig.show()
+
+ See also: :doc:`/gallery/widgets/span_selector`
+ """
+
+ def __init__(self, ax, onselect, direction, *, minspan=0, useblit=False,
+ props=None, onmove_callback=None, interactive=False,
+ button=None, handle_props=None, grab_range=10,
+ state_modifier_keys=None, drag_from_anywhere=False,
+ ignore_event_outside=False, snap_values=None):
+
+ if state_modifier_keys is None:
+ state_modifier_keys = dict(clear='escape',
+ square='not-applicable',
+ center='not-applicable',
+ rotate='not-applicable')
+ super().__init__(ax, onselect, useblit=useblit, button=button,
+ state_modifier_keys=state_modifier_keys)
+
+ if props is None:
+ props = dict(facecolor='red', alpha=0.5)
+
+ props['animated'] = self.useblit
+
+ self.direction = direction
+ self._extents_on_press = None
+ self.snap_values = snap_values
+
+ self.onmove_callback = onmove_callback
+ self.minspan = minspan
+
+ self.grab_range = grab_range
+ self._interactive = interactive
+ self._edge_handles = None
+ self.drag_from_anywhere = drag_from_anywhere
+ self.ignore_event_outside = ignore_event_outside
+
+ self.new_axes(ax, _props=props, _init=True)
+
+ # Setup handles
+ self._handle_props = {
+ 'color': props.get('facecolor', 'r'),
+ **cbook.normalize_kwargs(handle_props, Line2D)}
+
+ if self._interactive:
+ self._edge_order = ['min', 'max']
+ self._setup_edge_handles(self._handle_props)
+
+ self._active_handle = None
+
+ def new_axes(self, ax, *, _props=None, _init=False):
+ """Set SpanSelector to operate on a new Axes."""
+ reconnect = False
+ if _init or self.canvas is not ax.get_figure(root=True).canvas:
+ if self.canvas is not None:
+ self.disconnect_events()
+ reconnect = True
+ self.ax = ax
+ if reconnect:
+ self.connect_default_events()
+
+ # Reset
+ self._selection_completed = False
+
+ if self.direction == 'horizontal':
+ trans = ax.get_xaxis_transform()
+ w, h = 0, 1
+ else:
+ trans = ax.get_yaxis_transform()
+ w, h = 1, 0
+ rect_artist = Rectangle((0, 0), w, h, transform=trans, visible=False)
+ if _props is not None:
+ rect_artist.update(_props)
+ elif self._selection_artist is not None:
+ rect_artist.update_from(self._selection_artist)
+
+ self.ax.add_patch(rect_artist)
+ self._selection_artist = rect_artist
+
+ def _setup_edge_handles(self, props):
+ # Define initial position using the axis bounds to keep the same bounds
+ if self.direction == 'horizontal':
+ positions = self.ax.get_xbound()
+ else:
+ positions = self.ax.get_ybound()
+ self._edge_handles = ToolLineHandles(self.ax, positions,
+ direction=self.direction,
+ line_props=props,
+ useblit=self.useblit)
+
+ @property
+ def _handles_artists(self):
+ if self._edge_handles is not None:
+ return self._edge_handles.artists
+ else:
+ return ()
+
+ def _set_cursor(self, enabled):
+ """Update the canvas cursor based on direction of the selector."""
+ if enabled:
+ cursor = (backend_tools.Cursors.RESIZE_HORIZONTAL
+ if self.direction == 'horizontal' else
+ backend_tools.Cursors.RESIZE_VERTICAL)
+ else:
+ cursor = backend_tools.Cursors.POINTER
+
+ self.ax.get_figure(root=True).canvas.set_cursor(cursor)
+
+ def connect_default_events(self):
+ # docstring inherited
+ super().connect_default_events()
+ if getattr(self, '_interactive', False):
+ self.connect_event('motion_notify_event', self._hover)
+
+ def _press(self, event):
+ """Button press event handler."""
+ self._set_cursor(True)
+ if self._interactive and self._selection_artist.get_visible():
+ self._set_active_handle(event)
+ else:
+ self._active_handle = None
+
+ if self._active_handle is None or not self._interactive:
+ # Clear previous rectangle before drawing new rectangle.
+ self.update()
+
+ xdata, ydata = self._get_data_coords(event)
+ v = xdata if self.direction == 'horizontal' else ydata
+
+ if self._active_handle is None and not self.ignore_event_outside:
+ # when the press event outside the span, we initially set the
+ # visibility to False and extents to (v, v)
+ # update will be called when setting the extents
+ self._visible = False
+ self._set_extents((v, v))
+ # We need to set the visibility back, so the span selector will be
+ # drawn when necessary (span width > 0)
+ self._visible = True
+ else:
+ self.set_visible(True)
+
+ return False
+
+ @property
+ def direction(self):
+ """Direction of the span selector: 'vertical' or 'horizontal'."""
+ return self._direction
+
+ @direction.setter
+ def direction(self, direction):
+ """Set the direction of the span selector."""
+ _api.check_in_list(['horizontal', 'vertical'], direction=direction)
+ if hasattr(self, '_direction') and direction != self._direction:
+ # remove previous artists
+ self._selection_artist.remove()
+ if self._interactive:
+ self._edge_handles.remove()
+ self._direction = direction
+ self.new_axes(self.ax)
+ if self._interactive:
+ self._setup_edge_handles(self._handle_props)
+ else:
+ self._direction = direction
+
+ def _release(self, event):
+ """Button release event handler."""
+ self._set_cursor(False)
+
+ if not self._interactive:
+ self._selection_artist.set_visible(False)
+
+ if (self._active_handle is None and self._selection_completed and
+ self.ignore_event_outside):
+ return
+
+ vmin, vmax = self.extents
+ span = vmax - vmin
+
+ if span <= self.minspan:
+ # Remove span and set self._selection_completed = False
+ self.set_visible(False)
+ if self._selection_completed:
+ # Call onselect, only when the span is already existing
+ self.onselect(vmin, vmax)
+ self._selection_completed = False
+ else:
+ self.onselect(vmin, vmax)
+ self._selection_completed = True
+
+ self.update()
+
+ self._active_handle = None
+
+ return False
+
+ def _hover(self, event):
+ """Update the canvas cursor if it's over a handle."""
+ if self.ignore(event):
+ return
+
+ if self._active_handle is not None or not self._selection_completed:
+ # Do nothing if button is pressed and a handle is active, which may
+ # occur with drag_from_anywhere=True.
+ # Do nothing if selection is not completed, which occurs when
+ # a selector has been cleared
+ return
+
+ _, e_dist = self._edge_handles.closest(event.x, event.y)
+ self._set_cursor(e_dist <= self.grab_range)
+
+ def _onmove(self, event):
+ """Motion notify event handler."""
+
+ xdata, ydata = self._get_data_coords(event)
+ if self.direction == 'horizontal':
+ v = xdata
+ vpress = self._eventpress.xdata
+ else:
+ v = ydata
+ vpress = self._eventpress.ydata
+
+ # move existing span
+ # When "dragging from anywhere", `self._active_handle` is set to 'C'
+ # (match notation used in the RectangleSelector)
+ if self._active_handle == 'C' and self._extents_on_press is not None:
+ vmin, vmax = self._extents_on_press
+ dv = v - vpress
+ vmin += dv
+ vmax += dv
+
+ # resize an existing shape
+ elif self._active_handle and self._active_handle != 'C':
+ vmin, vmax = self._extents_on_press
+ if self._active_handle == 'min':
+ vmin = v
+ else:
+ vmax = v
+ # new shape
+ else:
+ # Don't create a new span if there is already one when
+ # ignore_event_outside=True
+ if self.ignore_event_outside and self._selection_completed:
+ return
+ vmin, vmax = vpress, v
+ if vmin > vmax:
+ vmin, vmax = vmax, vmin
+
+ self._set_extents((vmin, vmax))
+
+ if self.onmove_callback is not None:
+ self.onmove_callback(vmin, vmax)
+
+ return False
+
+ def _draw_shape(self, vmin, vmax):
+ if vmin > vmax:
+ vmin, vmax = vmax, vmin
+ if self.direction == 'horizontal':
+ self._selection_artist.set_x(vmin)
+ self._selection_artist.set_width(vmax - vmin)
+ else:
+ self._selection_artist.set_y(vmin)
+ self._selection_artist.set_height(vmax - vmin)
+
+ def _set_active_handle(self, event):
+ """Set active handle based on the location of the mouse event."""
+ # Note: event.xdata/ydata in data coordinates, event.x/y in pixels
+ e_idx, e_dist = self._edge_handles.closest(event.x, event.y)
+
+ # Prioritise center handle over other handles
+ # Use 'C' to match the notation used in the RectangleSelector
+ if 'move' in self._state:
+ self._active_handle = 'C'
+ elif e_dist > self.grab_range:
+ # Not close to any handles
+ self._active_handle = None
+ if self.drag_from_anywhere and self._contains(event):
+ # Check if we've clicked inside the region
+ self._active_handle = 'C'
+ self._extents_on_press = self.extents
+ else:
+ self._active_handle = None
+ return
+ else:
+ # Closest to an edge handle
+ self._active_handle = self._edge_order[e_idx]
+
+ # Save coordinates of rectangle at the start of handle movement.
+ self._extents_on_press = self.extents
+
+ def _contains(self, event):
+ """Return True if event is within the patch."""
+ return self._selection_artist.contains(event, radius=0)[0]
+
+ @staticmethod
+ def _snap(values, snap_values):
+ """Snap values to a given array values (snap_values)."""
+ # take into account machine precision
+ eps = np.min(np.abs(np.diff(snap_values))) * 1e-12
+ return tuple(
+ snap_values[np.abs(snap_values - v + np.sign(v) * eps).argmin()]
+ for v in values)
+
+ @property
+ def extents(self):
+ """
+ (float, float)
+ The values, in data coordinates, for the start and end points of the current
+ selection. If there is no selection then the start and end values will be
+ the same.
+ """
+ if self.direction == 'horizontal':
+ vmin = self._selection_artist.get_x()
+ vmax = vmin + self._selection_artist.get_width()
+ else:
+ vmin = self._selection_artist.get_y()
+ vmax = vmin + self._selection_artist.get_height()
+ return vmin, vmax
+
+ @extents.setter
+ def extents(self, extents):
+ self._set_extents(extents)
+ self._selection_completed = True
+
+ def _set_extents(self, extents):
+ # Update displayed shape
+ if self.snap_values is not None:
+ extents = tuple(self._snap(extents, self.snap_values))
+ self._draw_shape(*extents)
+ if self._interactive:
+ # Update displayed handles
+ self._edge_handles.set_data(self.extents)
+ self.set_visible(self._visible)
+ self.update()
+
+
+class ToolLineHandles:
+ """
+ Control handles for canvas tools.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ Matplotlib Axes where tool handles are displayed.
+ positions : 1D array
+ Positions of handles in data coordinates.
+ direction : {"horizontal", "vertical"}
+ Direction of handles, either 'vertical' or 'horizontal'
+ line_props : dict, optional
+ Additional line properties. See `.Line2D`.
+ useblit : bool, default: True
+ Whether to use blitting for faster drawing (if supported by the
+ backend). See the tutorial :ref:`blitting`
+ for details.
+ """
+
+ def __init__(self, ax, positions, direction, *, line_props=None,
+ useblit=True):
+ self.ax = ax
+
+ _api.check_in_list(['horizontal', 'vertical'], direction=direction)
+ self._direction = direction
+
+ line_props = {
+ **(line_props if line_props is not None else {}),
+ 'visible': False,
+ 'animated': useblit,
+ }
+
+ line_fun = ax.axvline if self.direction == 'horizontal' else ax.axhline
+
+ self._artists = [line_fun(p, **line_props) for p in positions]
+
+ @property
+ def artists(self):
+ return tuple(self._artists)
+
+ @property
+ def positions(self):
+ """Positions of the handle in data coordinates."""
+ method = 'get_xdata' if self.direction == 'horizontal' else 'get_ydata'
+ return [getattr(line, method)()[0] for line in self.artists]
+
+ @property
+ def direction(self):
+ """Direction of the handle: 'vertical' or 'horizontal'."""
+ return self._direction
+
+ def set_data(self, positions):
+ """
+ Set x- or y-positions of handles, depending on if the lines are
+ vertical or horizontal.
+
+ Parameters
+ ----------
+ positions : tuple of length 2
+ Set the positions of the handle in data coordinates
+ """
+ method = 'set_xdata' if self.direction == 'horizontal' else 'set_ydata'
+ for line, p in zip(self.artists, positions):
+ getattr(line, method)([p, p])
+
+ def set_visible(self, value):
+ """Set the visibility state of the handles artist."""
+ for artist in self.artists:
+ artist.set_visible(value)
+
+ def set_animated(self, value):
+ """Set the animated state of the handles artist."""
+ for artist in self.artists:
+ artist.set_animated(value)
+
+ def remove(self):
+ """Remove the handles artist from the figure."""
+ for artist in self._artists:
+ artist.remove()
+
+ def closest(self, x, y):
+ """
+ Return index and pixel distance to closest handle.
+
+ Parameters
+ ----------
+ x, y : float
+ x, y position from which the distance will be calculated to
+ determinate the closest handle
+
+ Returns
+ -------
+ index, distance : index of the handle and its distance from
+ position x, y
+ """
+ if self.direction == 'horizontal':
+ p_pts = np.array([
+ self.ax.transData.transform((p, 0))[0] for p in self.positions
+ ])
+ dist = abs(p_pts - x)
+ else:
+ p_pts = np.array([
+ self.ax.transData.transform((0, p))[1] for p in self.positions
+ ])
+ dist = abs(p_pts - y)
+ index = np.argmin(dist)
+ return index, dist[index]
+
+
+class ToolHandles:
+ """
+ Control handles for canvas tools.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ Matplotlib Axes where tool handles are displayed.
+ x, y : 1D arrays
+ Coordinates of control handles.
+ marker : str, default: 'o'
+ Shape of marker used to display handle. See `~.pyplot.plot`.
+ marker_props : dict, optional
+ Additional marker properties. See `.Line2D`.
+ useblit : bool, default: True
+ Whether to use blitting for faster drawing (if supported by the
+ backend). See the tutorial :ref:`blitting`
+ for details.
+ """
+
+ def __init__(self, ax, x, y, *, marker='o', marker_props=None, useblit=True):
+ self.ax = ax
+ props = {'marker': marker, 'markersize': 7, 'markerfacecolor': 'w',
+ 'linestyle': 'none', 'alpha': 0.5, 'visible': False,
+ 'label': '_nolegend_',
+ **cbook.normalize_kwargs(marker_props, Line2D._alias_map)}
+ self._markers = Line2D(x, y, animated=useblit, **props)
+ self.ax.add_line(self._markers)
+
+ @property
+ def x(self):
+ return self._markers.get_xdata()
+
+ @property
+ def y(self):
+ return self._markers.get_ydata()
+
+ @property
+ def artists(self):
+ return (self._markers, )
+
+ def set_data(self, pts, y=None):
+ """Set x and y positions of handles."""
+ if y is not None:
+ x = pts
+ pts = np.array([x, y])
+ self._markers.set_data(pts)
+
+ def set_visible(self, val):
+ self._markers.set_visible(val)
+
+ def set_animated(self, val):
+ self._markers.set_animated(val)
+
+ def closest(self, x, y):
+ """Return index and pixel distance to closest index."""
+ pts = np.column_stack([self.x, self.y])
+ # Transform data coordinates to pixel coordinates.
+ pts = self.ax.transData.transform(pts)
+ diff = pts - [x, y]
+ dist = np.hypot(*diff.T)
+ min_index = np.argmin(dist)
+ return min_index, dist[min_index]
+
+
+_RECTANGLESELECTOR_PARAMETERS_DOCSTRING = \
+ r"""
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+
+ onselect : function, optional
+ A callback function that is called after a release event and the
+ selection is created, changed or removed.
+ It must have the signature::
+
+ def onselect(eclick: MouseEvent, erelease: MouseEvent)
+
+ where *eclick* and *erelease* are the mouse click and release
+ `.MouseEvent`\s that start and complete the selection.
+
+ minspanx : float, default: 0
+ Selections with an x-span less than or equal to *minspanx* are removed
+ (when already existing) or cancelled.
+
+ minspany : float, default: 0
+ Selections with an y-span less than or equal to *minspanx* are removed
+ (when already existing) or cancelled.
+
+ useblit : bool, default: False
+ Whether to use blitting for faster drawing (if supported by the
+ backend). See the tutorial :ref:`blitting`
+ for details.
+
+ props : dict, optional
+ Properties with which the __ARTIST_NAME__ is drawn. See
+ `.Patch` for valid properties.
+ Default:
+
+ ``dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True)``
+
+ spancoords : {"data", "pixels"}, default: "data"
+ Whether to interpret *minspanx* and *minspany* in data or in pixel
+ coordinates.
+
+ button : `.MouseButton`, list of `.MouseButton`, default: all buttons
+ Button(s) that trigger rectangle selection.
+
+ grab_range : float, default: 10
+ Distance in pixels within which the interactive tool handles can be
+ activated.
+
+ handle_props : dict, optional
+ Properties with which the interactive handles (marker artists) are
+ drawn. See the marker arguments in `.Line2D` for valid
+ properties. Default values are defined in ``mpl.rcParams`` except for
+ the default value of ``markeredgecolor`` which will be the same as the
+ ``edgecolor`` property in *props*.
+
+ interactive : bool, default: False
+ Whether to draw a set of handles that allow interaction with the
+ widget after it is drawn.
+
+ state_modifier_keys : dict, optional
+ Keyboard modifiers which affect the widget's behavior. Values
+ amend the defaults, which are:
+
+ - "move": Move the existing shape, default: no modifier.
+ - "clear": Clear the current shape, default: "escape".
+ - "square": Make the shape square, default: "shift".
+ - "center": change the shape around its center, default: "ctrl".
+ - "rotate": Rotate the shape around its center between -45° and 45°,
+ default: "r".
+
+ "square" and "center" can be combined. The square shape can be defined
+ in data or display coordinates as determined by the
+ ``use_data_coordinates`` argument specified when creating the selector.
+
+ drag_from_anywhere : bool, default: False
+ If `True`, the widget can be moved by clicking anywhere within
+ its bounds.
+
+ ignore_event_outside : bool, default: False
+ If `True`, the event triggered outside the span selector will be
+ ignored.
+
+ use_data_coordinates : bool, default: False
+ If `True`, the "square" shape of the selector is defined in
+ data coordinates instead of display coordinates.
+ """
+
+
+@_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace(
+ '__ARTIST_NAME__', 'rectangle'))
+class RectangleSelector(_SelectorWidget):
+ """
+ Select a rectangular region of an Axes.
+
+ For the cursor to remain responsive you must keep a reference to it.
+
+ Press and release events triggered at the same coordinates outside the
+ selection will clear the selector, except when
+ ``ignore_event_outside=True``.
+
+ %s
+
+ Examples
+ --------
+ >>> import matplotlib.pyplot as plt
+ >>> import matplotlib.widgets as mwidgets
+ >>> fig, ax = plt.subplots()
+ >>> ax.plot([1, 2, 3], [10, 50, 100])
+ >>> def onselect(eclick, erelease):
+ ... print(eclick.xdata, eclick.ydata)
+ ... print(erelease.xdata, erelease.ydata)
+ >>> props = dict(facecolor='blue', alpha=0.5)
+ >>> rect = mwidgets.RectangleSelector(ax, onselect, interactive=True,
+ ... props=props)
+ >>> fig.show()
+ >>> rect.add_state('square')
+
+ See also: :doc:`/gallery/widgets/rectangle_selector`
+ """
+
+ def __init__(self, ax, onselect=None, *, minspanx=0,
+ minspany=0, useblit=False,
+ props=None, spancoords='data', button=None, grab_range=10,
+ handle_props=None, interactive=False,
+ state_modifier_keys=None, drag_from_anywhere=False,
+ ignore_event_outside=False, use_data_coordinates=False):
+ super().__init__(ax, onselect, useblit=useblit, button=button,
+ state_modifier_keys=state_modifier_keys,
+ use_data_coordinates=use_data_coordinates)
+
+ self._interactive = interactive
+ self.drag_from_anywhere = drag_from_anywhere
+ self.ignore_event_outside = ignore_event_outside
+ self._rotation = 0.0
+ self._aspect_ratio_correction = 1.0
+
+ # State to allow the option of an interactive selector that can't be
+ # interactively drawn. This is used in PolygonSelector as an
+ # interactive bounding box to allow the polygon to be easily resized
+ self._allow_creation = True
+
+ if props is None:
+ props = dict(facecolor='red', edgecolor='black',
+ alpha=0.2, fill=True)
+ props = {**props, 'animated': self.useblit}
+ self._visible = props.pop('visible', self._visible)
+ to_draw = self._init_shape(**props)
+ self.ax.add_patch(to_draw)
+
+ self._selection_artist = to_draw
+ self._set_aspect_ratio_correction()
+
+ self.minspanx = minspanx
+ self.minspany = minspany
+
+ _api.check_in_list(['data', 'pixels'], spancoords=spancoords)
+ self.spancoords = spancoords
+
+ self.grab_range = grab_range
+
+ if self._interactive:
+ self._handle_props = {
+ 'markeredgecolor': (props or {}).get('edgecolor', 'black'),
+ **cbook.normalize_kwargs(handle_props, Line2D)}
+
+ self._corner_order = ['SW', 'SE', 'NE', 'NW']
+ xc, yc = self.corners
+ self._corner_handles = ToolHandles(self.ax, xc, yc,
+ marker_props=self._handle_props,
+ useblit=self.useblit)
+
+ self._edge_order = ['W', 'S', 'E', 'N']
+ xe, ye = self.edge_centers
+ self._edge_handles = ToolHandles(self.ax, xe, ye, marker='s',
+ marker_props=self._handle_props,
+ useblit=self.useblit)
+
+ xc, yc = self.center
+ self._center_handle = ToolHandles(self.ax, [xc], [yc], marker='s',
+ marker_props=self._handle_props,
+ useblit=self.useblit)
+
+ self._active_handle = None
+
+ self._extents_on_press = None
+
+ @property
+ def _handles_artists(self):
+ return (*self._center_handle.artists, *self._corner_handles.artists,
+ *self._edge_handles.artists)
+
+ def _init_shape(self, **props):
+ return Rectangle((0, 0), 0, 1, visible=False,
+ rotation_point='center', **props)
+
+ def _press(self, event):
+ """Button press event handler."""
+ # make the drawn box/line visible get the click-coordinates, button, ...
+ if self._interactive and self._selection_artist.get_visible():
+ self._set_active_handle(event)
+ else:
+ self._active_handle = None
+
+ if ((self._active_handle is None or not self._interactive) and
+ self._allow_creation):
+ # Clear previous rectangle before drawing new rectangle.
+ self.update()
+
+ if (self._active_handle is None and not self.ignore_event_outside and
+ self._allow_creation):
+ x, y = self._get_data_coords(event)
+ self._visible = False
+ self.extents = x, x, y, y
+ self._visible = True
+ else:
+ self.set_visible(True)
+
+ self._extents_on_press = self.extents
+ self._rotation_on_press = self._rotation
+ self._set_aspect_ratio_correction()
+
+ return False
+
+ def _release(self, event):
+ """Button release event handler."""
+ if not self._interactive:
+ self._selection_artist.set_visible(False)
+
+ if (self._active_handle is None and self._selection_completed and
+ self.ignore_event_outside):
+ return
+
+ # update the eventpress and eventrelease with the resulting extents
+ x0, x1, y0, y1 = self.extents
+ self._eventpress.xdata = x0
+ self._eventpress.ydata = y0
+ xy0 = self.ax.transData.transform([x0, y0])
+ self._eventpress.x, self._eventpress.y = xy0
+
+ self._eventrelease.xdata = x1
+ self._eventrelease.ydata = y1
+ xy1 = self.ax.transData.transform([x1, y1])
+ self._eventrelease.x, self._eventrelease.y = xy1
+
+ # calculate dimensions of box or line
+ if self.spancoords == 'data':
+ spanx = abs(self._eventpress.xdata - self._eventrelease.xdata)
+ spany = abs(self._eventpress.ydata - self._eventrelease.ydata)
+ elif self.spancoords == 'pixels':
+ spanx = abs(self._eventpress.x - self._eventrelease.x)
+ spany = abs(self._eventpress.y - self._eventrelease.y)
+ else:
+ _api.check_in_list(['data', 'pixels'],
+ spancoords=self.spancoords)
+ # check if drawn distance (if it exists) is not too small in
+ # either x or y-direction
+ if spanx <= self.minspanx or spany <= self.minspany:
+ if self._selection_completed:
+ # Call onselect, only when the selection is already existing
+ self.onselect(self._eventpress, self._eventrelease)
+ self._clear_without_update()
+ else:
+ self.onselect(self._eventpress, self._eventrelease)
+ self._selection_completed = True
+
+ self.update()
+ self._active_handle = None
+ self._extents_on_press = None
+
+ return False
+
+ def _onmove(self, event):
+ """
+ Motion notify event handler.
+
+ This can do one of four things:
+ - Translate
+ - Rotate
+ - Re-size
+ - Continue the creation of a new shape
+ """
+ eventpress = self._eventpress
+ # The calculations are done for rotation at zero: we apply inverse
+ # transformation to events except when we rotate and move
+ state = self._state
+ rotate = 'rotate' in state and self._active_handle in self._corner_order
+ move = self._active_handle == 'C'
+ resize = self._active_handle and not move
+
+ xdata, ydata = self._get_data_coords(event)
+ if resize:
+ inv_tr = self._get_rotation_transform().inverted()
+ xdata, ydata = inv_tr.transform([xdata, ydata])
+ eventpress.xdata, eventpress.ydata = inv_tr.transform(
+ (eventpress.xdata, eventpress.ydata))
+
+ dx = xdata - eventpress.xdata
+ dy = ydata - eventpress.ydata
+ # refmax is used when moving the corner handle with the square state
+ # and is the maximum between refx and refy
+ refmax = None
+ if self._use_data_coordinates:
+ refx, refy = dx, dy
+ else:
+ # Get dx/dy in display coordinates
+ refx = event.x - eventpress.x
+ refy = event.y - eventpress.y
+
+ x0, x1, y0, y1 = self._extents_on_press
+ # rotate an existing shape
+ if rotate:
+ # calculate angle abc
+ a = (eventpress.xdata, eventpress.ydata)
+ b = self.center
+ c = (xdata, ydata)
+ angle = (np.arctan2(c[1]-b[1], c[0]-b[0]) -
+ np.arctan2(a[1]-b[1], a[0]-b[0]))
+ self.rotation = np.rad2deg(self._rotation_on_press + angle)
+
+ elif resize:
+ size_on_press = [x1 - x0, y1 - y0]
+ center = (x0 + size_on_press[0] / 2, y0 + size_on_press[1] / 2)
+
+ # Keeping the center fixed
+ if 'center' in state:
+ # hh, hw are half-height and half-width
+ if 'square' in state:
+ # when using a corner, find which reference to use
+ if self._active_handle in self._corner_order:
+ refmax = max(refx, refy, key=abs)
+ if self._active_handle in ['E', 'W'] or refmax == refx:
+ hw = xdata - center[0]
+ hh = hw / self._aspect_ratio_correction
+ else:
+ hh = ydata - center[1]
+ hw = hh * self._aspect_ratio_correction
+ else:
+ hw = size_on_press[0] / 2
+ hh = size_on_press[1] / 2
+ # cancel changes in perpendicular direction
+ if self._active_handle in ['E', 'W'] + self._corner_order:
+ hw = abs(xdata - center[0])
+ if self._active_handle in ['N', 'S'] + self._corner_order:
+ hh = abs(ydata - center[1])
+
+ x0, x1, y0, y1 = (center[0] - hw, center[0] + hw,
+ center[1] - hh, center[1] + hh)
+
+ else:
+ # change sign of relative changes to simplify calculation
+ # Switch variables so that x1 and/or y1 are updated on move
+ if 'W' in self._active_handle:
+ x0 = x1
+ if 'S' in self._active_handle:
+ y0 = y1
+ if self._active_handle in ['E', 'W'] + self._corner_order:
+ x1 = xdata
+ if self._active_handle in ['N', 'S'] + self._corner_order:
+ y1 = ydata
+ if 'square' in state:
+ # when using a corner, find which reference to use
+ if self._active_handle in self._corner_order:
+ refmax = max(refx, refy, key=abs)
+ if self._active_handle in ['E', 'W'] or refmax == refx:
+ sign = np.sign(ydata - y0)
+ y1 = y0 + sign * abs(x1 - x0) / self._aspect_ratio_correction
+ else:
+ sign = np.sign(xdata - x0)
+ x1 = x0 + sign * abs(y1 - y0) * self._aspect_ratio_correction
+
+ elif move:
+ x0, x1, y0, y1 = self._extents_on_press
+ dx = xdata - eventpress.xdata
+ dy = ydata - eventpress.ydata
+ x0 += dx
+ x1 += dx
+ y0 += dy
+ y1 += dy
+
+ else:
+ # Create a new shape
+ self._rotation = 0
+ # Don't create a new rectangle if there is already one when
+ # ignore_event_outside=True
+ if ((self.ignore_event_outside and self._selection_completed) or
+ not self._allow_creation):
+ return
+ center = [eventpress.xdata, eventpress.ydata]
+ dx = (xdata - center[0]) / 2
+ dy = (ydata - center[1]) / 2
+
+ # square shape
+ if 'square' in state:
+ refmax = max(refx, refy, key=abs)
+ if refmax == refx:
+ dy = np.sign(dy) * abs(dx) / self._aspect_ratio_correction
+ else:
+ dx = np.sign(dx) * abs(dy) * self._aspect_ratio_correction
+
+ # from center
+ if 'center' in state:
+ dx *= 2
+ dy *= 2
+
+ # from corner
+ else:
+ center[0] += dx
+ center[1] += dy
+
+ x0, x1, y0, y1 = (center[0] - dx, center[0] + dx,
+ center[1] - dy, center[1] + dy)
+
+ self.extents = x0, x1, y0, y1
+
+ @property
+ def _rect_bbox(self):
+ return self._selection_artist.get_bbox().bounds
+
+ def _set_aspect_ratio_correction(self):
+ aspect_ratio = self.ax._get_aspect_ratio()
+ self._selection_artist._aspect_ratio_correction = aspect_ratio
+ if self._use_data_coordinates:
+ self._aspect_ratio_correction = 1
+ else:
+ self._aspect_ratio_correction = aspect_ratio
+
+ def _get_rotation_transform(self):
+ aspect_ratio = self.ax._get_aspect_ratio()
+ return Affine2D().translate(-self.center[0], -self.center[1]) \
+ .scale(1, aspect_ratio) \
+ .rotate(self._rotation) \
+ .scale(1, 1 / aspect_ratio) \
+ .translate(*self.center)
+
+ @property
+ def corners(self):
+ """
+ Corners of rectangle in data coordinates from lower left,
+ moving clockwise.
+ """
+ x0, y0, width, height = self._rect_bbox
+ xc = x0, x0 + width, x0 + width, x0
+ yc = y0, y0, y0 + height, y0 + height
+ transform = self._get_rotation_transform()
+ coords = transform.transform(np.array([xc, yc]).T).T
+ return coords[0], coords[1]
+
+ @property
+ def edge_centers(self):
+ """
+ Midpoint of rectangle edges in data coordinates from left,
+ moving anti-clockwise.
+ """
+ x0, y0, width, height = self._rect_bbox
+ w = width / 2.
+ h = height / 2.
+ xe = x0, x0 + w, x0 + width, x0 + w
+ ye = y0 + h, y0, y0 + h, y0 + height
+ transform = self._get_rotation_transform()
+ coords = transform.transform(np.array([xe, ye]).T).T
+ return coords[0], coords[1]
+
+ @property
+ def center(self):
+ """Center of rectangle in data coordinates."""
+ x0, y0, width, height = self._rect_bbox
+ return x0 + width / 2., y0 + height / 2.
+
+ @property
+ def extents(self):
+ """
+ Return (xmin, xmax, ymin, ymax) in data coordinates as defined by the
+ bounding box before rotation.
+ """
+ x0, y0, width, height = self._rect_bbox
+ xmin, xmax = sorted([x0, x0 + width])
+ ymin, ymax = sorted([y0, y0 + height])
+ return xmin, xmax, ymin, ymax
+
+ @extents.setter
+ def extents(self, extents):
+ # Update displayed shape
+ self._draw_shape(extents)
+ if self._interactive:
+ # Update displayed handles
+ self._corner_handles.set_data(*self.corners)
+ self._edge_handles.set_data(*self.edge_centers)
+ x, y = self.center
+ self._center_handle.set_data([x], [y])
+ self.set_visible(self._visible)
+ self.update()
+
+ @property
+ def rotation(self):
+ """
+ Rotation in degree in interval [-45°, 45°]. The rotation is limited in
+ range to keep the implementation simple.
+ """
+ return np.rad2deg(self._rotation)
+
+ @rotation.setter
+ def rotation(self, value):
+ # Restrict to a limited range of rotation [-45°, 45°] to avoid changing
+ # order of handles
+ if -45 <= value and value <= 45:
+ self._rotation = np.deg2rad(value)
+ # call extents setter to draw shape and update handles positions
+ self.extents = self.extents
+
+ def _draw_shape(self, extents):
+ x0, x1, y0, y1 = extents
+ xmin, xmax = sorted([x0, x1])
+ ymin, ymax = sorted([y0, y1])
+ xlim = sorted(self.ax.get_xlim())
+ ylim = sorted(self.ax.get_ylim())
+
+ xmin = max(xlim[0], xmin)
+ ymin = max(ylim[0], ymin)
+ xmax = min(xmax, xlim[1])
+ ymax = min(ymax, ylim[1])
+
+ self._selection_artist.set_x(xmin)
+ self._selection_artist.set_y(ymin)
+ self._selection_artist.set_width(xmax - xmin)
+ self._selection_artist.set_height(ymax - ymin)
+ self._selection_artist.set_angle(self.rotation)
+
+ def _set_active_handle(self, event):
+ """Set active handle based on the location of the mouse event."""
+ # Note: event.xdata/ydata in data coordinates, event.x/y in pixels
+ c_idx, c_dist = self._corner_handles.closest(event.x, event.y)
+ e_idx, e_dist = self._edge_handles.closest(event.x, event.y)
+ m_idx, m_dist = self._center_handle.closest(event.x, event.y)
+
+ if 'move' in self._state:
+ self._active_handle = 'C'
+ # Set active handle as closest handle, if mouse click is close enough.
+ elif m_dist < self.grab_range * 2:
+ # Prioritise center handle over other handles
+ self._active_handle = 'C'
+ elif c_dist > self.grab_range and e_dist > self.grab_range:
+ # Not close to any handles
+ if self.drag_from_anywhere and self._contains(event):
+ # Check if we've clicked inside the region
+ self._active_handle = 'C'
+ else:
+ self._active_handle = None
+ return
+ elif c_dist < e_dist:
+ # Closest to a corner handle
+ self._active_handle = self._corner_order[c_idx]
+ else:
+ # Closest to an edge handle
+ self._active_handle = self._edge_order[e_idx]
+
+ def _contains(self, event):
+ """Return True if event is within the patch."""
+ return self._selection_artist.contains(event, radius=0)[0]
+
+ @property
+ def geometry(self):
+ """
+ Return an array of shape (2, 5) containing the
+ x (``RectangleSelector.geometry[1, :]``) and
+ y (``RectangleSelector.geometry[0, :]``) data coordinates of the four
+ corners of the rectangle starting and ending in the top left corner.
+ """
+ if hasattr(self._selection_artist, 'get_verts'):
+ xfm = self.ax.transData.inverted()
+ y, x = xfm.transform(self._selection_artist.get_verts()).T
+ return np.array([x, y])
+ else:
+ return np.array(self._selection_artist.get_data())
+
+
+@_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace(
+ '__ARTIST_NAME__', 'ellipse'))
+class EllipseSelector(RectangleSelector):
+ """
+ Select an elliptical region of an Axes.
+
+ For the cursor to remain responsive you must keep a reference to it.
+
+ Press and release events triggered at the same coordinates outside the
+ selection will clear the selector, except when
+ ``ignore_event_outside=True``.
+
+ %s
+
+ Examples
+ --------
+ :doc:`/gallery/widgets/rectangle_selector`
+ """
+ def _init_shape(self, **props):
+ return Ellipse((0, 0), 0, 1, visible=False, **props)
+
+ def _draw_shape(self, extents):
+ x0, x1, y0, y1 = extents
+ xmin, xmax = sorted([x0, x1])
+ ymin, ymax = sorted([y0, y1])
+ center = [x0 + (x1 - x0) / 2., y0 + (y1 - y0) / 2.]
+ a = (xmax - xmin) / 2.
+ b = (ymax - ymin) / 2.
+
+ self._selection_artist.center = center
+ self._selection_artist.width = 2 * a
+ self._selection_artist.height = 2 * b
+ self._selection_artist.angle = self.rotation
+
+ @property
+ def _rect_bbox(self):
+ x, y = self._selection_artist.center
+ width = self._selection_artist.width
+ height = self._selection_artist.height
+ return x - width / 2., y - height / 2., width, height
+
+
+class LassoSelector(_SelectorWidget):
+ """
+ Selection curve of an arbitrary shape.
+
+ For the selector to remain responsive you must keep a reference to it.
+
+ The selected path can be used in conjunction with `~.Path.contains_point`
+ to select data points from an image.
+
+ In contrast to `Lasso`, `LassoSelector` is written with an interface
+ similar to `RectangleSelector` and `SpanSelector`, and will continue to
+ interact with the Axes until disconnected.
+
+ Example usage::
+
+ ax = plt.subplot()
+ ax.plot(x, y)
+
+ def onselect(verts):
+ print(verts)
+ lasso = LassoSelector(ax, onselect)
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+ onselect : function, optional
+ Whenever the lasso is released, the *onselect* function is called and
+ passed the vertices of the selected path.
+ useblit : bool, default: True
+ Whether to use blitting for faster drawing (if supported by the
+ backend). See the tutorial :ref:`blitting`
+ for details.
+ props : dict, optional
+ Properties with which the line is drawn, see `.Line2D`
+ for valid properties. Default values are defined in ``mpl.rcParams``.
+ button : `.MouseButton` or list of `.MouseButton`, optional
+ The mouse buttons used for rectangle selection. Default is ``None``,
+ which corresponds to all buttons.
+ """
+
+ def __init__(self, ax, onselect=None, *, useblit=True, props=None, button=None):
+ super().__init__(ax, onselect, useblit=useblit, button=button)
+ self.verts = None
+ props = {
+ **(props if props is not None else {}),
+ # Note that self.useblit may be != useblit, if the canvas doesn't
+ # support blitting.
+ 'animated': self.useblit, 'visible': False,
+ }
+ line = Line2D([], [], **props)
+ self.ax.add_line(line)
+ self._selection_artist = line
+
+ def _press(self, event):
+ self.verts = [self._get_data(event)]
+ self._selection_artist.set_visible(True)
+
+ def _release(self, event):
+ if self.verts is not None:
+ self.verts.append(self._get_data(event))
+ self.onselect(self.verts)
+ self._selection_artist.set_data([[], []])
+ self._selection_artist.set_visible(False)
+ self.verts = None
+
+ def _onmove(self, event):
+ if self.verts is None:
+ return
+ self.verts.append(self._get_data(event))
+ self._selection_artist.set_data(list(zip(*self.verts)))
+
+ self.update()
+
+
+class PolygonSelector(_SelectorWidget):
+ """
+ Select a polygon region of an Axes.
+
+ Place vertices with each mouse click, and make the selection by completing
+ the polygon (clicking on the first vertex). Once drawn individual vertices
+ can be moved by clicking and dragging with the left mouse button, or
+ removed by clicking the right mouse button.
+
+ In addition, the following modifier keys can be used:
+
+ - Hold *ctrl* and click and drag a vertex to reposition it before the
+ polygon has been completed.
+ - Hold the *shift* key and click and drag anywhere in the Axes to move
+ all vertices.
+ - Press the *esc* key to start a new polygon.
+
+ For the selector to remain responsive you must keep a reference to it.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+
+ onselect : function, optional
+ When a polygon is completed or modified after completion,
+ the *onselect* function is called and passed a list of the vertices as
+ ``(xdata, ydata)`` tuples.
+
+ useblit : bool, default: False
+ Whether to use blitting for faster drawing (if supported by the
+ backend). See the tutorial :ref:`blitting`
+ for details.
+
+ props : dict, optional
+ Properties with which the line is drawn, see `.Line2D` for valid properties.
+ Default::
+
+ dict(color='k', linestyle='-', linewidth=2, alpha=0.5)
+
+ handle_props : dict, optional
+ Artist properties for the markers drawn at the vertices of the polygon.
+ See the marker arguments in `.Line2D` for valid
+ properties. Default values are defined in ``mpl.rcParams`` except for
+ the default value of ``markeredgecolor`` which will be the same as the
+ ``color`` property in *props*.
+
+ grab_range : float, default: 10
+ A vertex is selected (to complete the polygon or to move a vertex) if
+ the mouse click is within *grab_range* pixels of the vertex.
+
+ draw_bounding_box : bool, optional
+ If `True`, a bounding box will be drawn around the polygon selector
+ once it is complete. This box can be used to move and resize the
+ selector.
+
+ box_handle_props : dict, optional
+ Properties to set for the box handles. See the documentation for the
+ *handle_props* argument to `RectangleSelector` for more info.
+
+ box_props : dict, optional
+ Properties to set for the box. See the documentation for the *props*
+ argument to `RectangleSelector` for more info.
+
+ Examples
+ --------
+ :doc:`/gallery/widgets/polygon_selector_simple`
+ :doc:`/gallery/widgets/polygon_selector_demo`
+
+ Notes
+ -----
+ If only one point remains after removing points, the selector reverts to an
+ incomplete state and you can start drawing a new polygon from the existing
+ point.
+ """
+
+ def __init__(self, ax, onselect=None, *, useblit=False,
+ props=None, handle_props=None, grab_range=10,
+ draw_bounding_box=False, box_handle_props=None,
+ box_props=None):
+ # The state modifiers 'move', 'square', and 'center' are expected by
+ # _SelectorWidget but are not supported by PolygonSelector
+ # Note: could not use the existing 'move' state modifier in-place of
+ # 'move_all' because _SelectorWidget automatically discards 'move'
+ # from the state on button release.
+ state_modifier_keys = dict(clear='escape', move_vertex='control',
+ move_all='shift', move='not-applicable',
+ square='not-applicable',
+ center='not-applicable',
+ rotate='not-applicable')
+ super().__init__(ax, onselect, useblit=useblit,
+ state_modifier_keys=state_modifier_keys)
+
+ self._xys = [(0, 0)]
+
+ if props is None:
+ props = dict(color='k', linestyle='-', linewidth=2, alpha=0.5)
+ props = {**props, 'animated': self.useblit}
+ self._selection_artist = line = Line2D([], [], **props)
+ self.ax.add_line(line)
+
+ if handle_props is None:
+ handle_props = dict(markeredgecolor='k',
+ markerfacecolor=props.get('color', 'k'))
+ self._handle_props = handle_props
+ self._polygon_handles = ToolHandles(self.ax, [], [],
+ useblit=self.useblit,
+ marker_props=self._handle_props)
+
+ self._active_handle_idx = -1
+ self.grab_range = grab_range
+
+ self.set_visible(True)
+ self._draw_box = draw_bounding_box
+ self._box = None
+
+ if box_handle_props is None:
+ box_handle_props = {}
+ self._box_handle_props = self._handle_props.update(box_handle_props)
+ self._box_props = box_props
+
+ def _get_bbox(self):
+ return self._selection_artist.get_bbox()
+
+ def _add_box(self):
+ self._box = RectangleSelector(self.ax,
+ useblit=self.useblit,
+ grab_range=self.grab_range,
+ handle_props=self._box_handle_props,
+ props=self._box_props,
+ interactive=True)
+ self._box._state_modifier_keys.pop('rotate')
+ self._box.connect_event('motion_notify_event', self._scale_polygon)
+ self._update_box()
+ # Set state that prevents the RectangleSelector from being created
+ # by the user
+ self._box._allow_creation = False
+ self._box._selection_completed = True
+ self._draw_polygon()
+
+ def _remove_box(self):
+ if self._box is not None:
+ self._box.set_visible(False)
+ self._box = None
+
+ def _update_box(self):
+ # Update selection box extents to the extents of the polygon
+ if self._box is not None:
+ bbox = self._get_bbox()
+ self._box.extents = [bbox.x0, bbox.x1, bbox.y0, bbox.y1]
+ # Save a copy
+ self._old_box_extents = self._box.extents
+
+ def _scale_polygon(self, event):
+ """
+ Scale the polygon selector points when the bounding box is moved or
+ scaled.
+
+ This is set as a callback on the bounding box RectangleSelector.
+ """
+ if not self._selection_completed:
+ return
+
+ if self._old_box_extents == self._box.extents:
+ return
+
+ # Create transform from old box to new box
+ x1, y1, w1, h1 = self._box._rect_bbox
+ old_bbox = self._get_bbox()
+ t = (transforms.Affine2D()
+ .translate(-old_bbox.x0, -old_bbox.y0)
+ .scale(1 / old_bbox.width, 1 / old_bbox.height)
+ .scale(w1, h1)
+ .translate(x1, y1))
+
+ # Update polygon verts. Must be a list of tuples for consistency.
+ new_verts = [(x, y) for x, y in t.transform(np.array(self.verts))]
+ self._xys = [*new_verts, new_verts[0]]
+ self._draw_polygon()
+ self._old_box_extents = self._box.extents
+
+ @property
+ def _handles_artists(self):
+ return self._polygon_handles.artists
+
+ def _remove_vertex(self, i):
+ """Remove vertex with index i."""
+ if (len(self._xys) > 2 and
+ self._selection_completed and
+ i in (0, len(self._xys) - 1)):
+ # If selecting the first or final vertex, remove both first and
+ # last vertex as they are the same for a closed polygon
+ self._xys.pop(0)
+ self._xys.pop(-1)
+ # Close the polygon again by appending the new first vertex to the
+ # end
+ self._xys.append(self._xys[0])
+ else:
+ self._xys.pop(i)
+ if len(self._xys) <= 2:
+ # If only one point left, return to incomplete state to let user
+ # start drawing again
+ self._selection_completed = False
+ self._remove_box()
+
+ def _press(self, event):
+ """Button press event handler."""
+ # Check for selection of a tool handle.
+ if ((self._selection_completed or 'move_vertex' in self._state)
+ and len(self._xys) > 0):
+ h_idx, h_dist = self._polygon_handles.closest(event.x, event.y)
+ if h_dist < self.grab_range:
+ self._active_handle_idx = h_idx
+ # Save the vertex positions at the time of the press event (needed to
+ # support the 'move_all' state modifier).
+ self._xys_at_press = self._xys.copy()
+
+ def _release(self, event):
+ """Button release event handler."""
+ # Release active tool handle.
+ if self._active_handle_idx >= 0:
+ if event.button == 3:
+ self._remove_vertex(self._active_handle_idx)
+ self._draw_polygon()
+ self._active_handle_idx = -1
+
+ # Complete the polygon.
+ elif len(self._xys) > 3 and self._xys[-1] == self._xys[0]:
+ self._selection_completed = True
+ if self._draw_box and self._box is None:
+ self._add_box()
+
+ # Place new vertex.
+ elif (not self._selection_completed
+ and 'move_all' not in self._state
+ and 'move_vertex' not in self._state):
+ self._xys.insert(-1, self._get_data_coords(event))
+
+ if self._selection_completed:
+ self.onselect(self.verts)
+
+ def onmove(self, event):
+ """Cursor move event handler and validator."""
+ # Method overrides _SelectorWidget.onmove because the polygon selector
+ # needs to process the move callback even if there is no button press.
+ # _SelectorWidget.onmove include logic to ignore move event if
+ # _eventpress is None.
+ if self.ignore(event):
+ # Hide the cursor when interactive zoom/pan is active
+ if not self.canvas.widgetlock.available(self) and self._xys:
+ self._xys[-1] = (np.nan, np.nan)
+ self._draw_polygon()
+ return False
+
+ else:
+ event = self._clean_event(event)
+ self._onmove(event)
+ return True
+
+ def _onmove(self, event):
+ """Cursor move event handler."""
+ # Move the active vertex (ToolHandle).
+ if self._active_handle_idx >= 0:
+ idx = self._active_handle_idx
+ self._xys[idx] = self._get_data_coords(event)
+ # Also update the end of the polygon line if the first vertex is
+ # the active handle and the polygon is completed.
+ if idx == 0 and self._selection_completed:
+ self._xys[-1] = self._get_data_coords(event)
+
+ # Move all vertices.
+ elif 'move_all' in self._state and self._eventpress:
+ xdata, ydata = self._get_data_coords(event)
+ dx = xdata - self._eventpress.xdata
+ dy = ydata - self._eventpress.ydata
+ for k in range(len(self._xys)):
+ x_at_press, y_at_press = self._xys_at_press[k]
+ self._xys[k] = x_at_press + dx, y_at_press + dy
+
+ # Do nothing if completed or waiting for a move.
+ elif (self._selection_completed
+ or 'move_vertex' in self._state or 'move_all' in self._state):
+ return
+
+ # Position pending vertex.
+ else:
+ # Calculate distance to the start vertex.
+ x0, y0 = \
+ self._selection_artist.get_transform().transform(self._xys[0])
+ v0_dist = np.hypot(x0 - event.x, y0 - event.y)
+ # Lock on to the start vertex if near it and ready to complete.
+ if len(self._xys) > 3 and v0_dist < self.grab_range:
+ self._xys[-1] = self._xys[0]
+ else:
+ self._xys[-1] = self._get_data_coords(event)
+
+ self._draw_polygon()
+
+ def _on_key_press(self, event):
+ """Key press event handler."""
+ # Remove the pending vertex if entering the 'move_vertex' or
+ # 'move_all' mode
+ if (not self._selection_completed
+ and ('move_vertex' in self._state or
+ 'move_all' in self._state)):
+ self._xys.pop()
+ self._draw_polygon()
+
+ def _on_key_release(self, event):
+ """Key release event handler."""
+ # Add back the pending vertex if leaving the 'move_vertex' or
+ # 'move_all' mode (by checking the released key)
+ if (not self._selection_completed
+ and
+ (event.key == self._state_modifier_keys.get('move_vertex')
+ or event.key == self._state_modifier_keys.get('move_all'))):
+ self._xys.append(self._get_data_coords(event))
+ self._draw_polygon()
+ # Reset the polygon if the released key is the 'clear' key.
+ elif event.key == self._state_modifier_keys.get('clear'):
+ event = self._clean_event(event)
+ self._xys = [self._get_data_coords(event)]
+ self._selection_completed = False
+ self._remove_box()
+ self.set_visible(True)
+
+ def _draw_polygon_without_update(self):
+ """Redraw the polygon based on new vertex positions, no update()."""
+ xs, ys = zip(*self._xys) if self._xys else ([], [])
+ self._selection_artist.set_data(xs, ys)
+ self._update_box()
+ # Only show one tool handle at the start and end vertex of the polygon
+ # if the polygon is completed or the user is locked on to the start
+ # vertex.
+ if (self._selection_completed
+ or (len(self._xys) > 3
+ and self._xys[-1] == self._xys[0])):
+ self._polygon_handles.set_data(xs[:-1], ys[:-1])
+ else:
+ self._polygon_handles.set_data(xs, ys)
+
+ def _draw_polygon(self):
+ """Redraw the polygon based on the new vertex positions."""
+ self._draw_polygon_without_update()
+ self.update()
+
+ @property
+ def verts(self):
+ """The polygon vertices, as a list of ``(x, y)`` pairs."""
+ return self._xys[:-1]
+
+ @verts.setter
+ def verts(self, xys):
+ """
+ Set the polygon vertices.
+
+ This will remove any preexisting vertices, creating a complete polygon
+ with the new vertices.
+ """
+ self._xys = [*xys, xys[0]]
+ self._selection_completed = True
+ self.set_visible(True)
+ if self._draw_box and self._box is None:
+ self._add_box()
+ self._draw_polygon()
+
+ def _clear_without_update(self):
+ self._selection_completed = False
+ self._xys = [(0, 0)]
+ self._draw_polygon_without_update()
+
+
+class Lasso(AxesWidget):
+ """
+ Selection curve of an arbitrary shape.
+
+ The selected path can be used in conjunction with
+ `~matplotlib.path.Path.contains_point` to select data points from an image.
+
+ Unlike `LassoSelector`, this must be initialized with a starting
+ point *xy*, and the `Lasso` events are destroyed upon release.
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The parent Axes for the widget.
+ xy : (float, float)
+ Coordinates of the start of the lasso.
+ callback : callable
+ Whenever the lasso is released, the *callback* function is called and
+ passed the vertices of the selected path.
+ useblit : bool, default: True
+ Whether to use blitting for faster drawing (if supported by the
+ backend). See the tutorial :ref:`blitting`
+ for details.
+ props: dict, optional
+ Lasso line properties. See `.Line2D` for valid properties.
+ Default *props* are::
+
+ {'linestyle' : '-', 'color' : 'black', 'lw' : 2}
+
+ .. versionadded:: 3.9
+ """
+ def __init__(self, ax, xy, callback, *, useblit=True, props=None):
+ super().__init__(ax)
+
+ self.useblit = useblit and self.canvas.supports_blit
+ if self.useblit:
+ self.background = self.canvas.copy_from_bbox(self.ax.bbox)
+
+ style = {'linestyle': '-', 'color': 'black', 'lw': 2}
+
+ if props is not None:
+ style.update(props)
+
+ x, y = xy
+ self.verts = [(x, y)]
+ self.line = Line2D([x], [y], **style)
+ self.ax.add_line(self.line)
+ self.callback = callback
+ self.connect_event('button_release_event', self.onrelease)
+ self.connect_event('motion_notify_event', self.onmove)
+
+ def onrelease(self, event):
+ if self.ignore(event):
+ return
+ if self.verts is not None:
+ self.verts.append(self._get_data_coords(event))
+ if len(self.verts) > 2:
+ self.callback(self.verts)
+ self.line.remove()
+ self.verts = None
+ self.disconnect_events()
+
+ def onmove(self, event):
+ if (self.ignore(event)
+ or self.verts is None
+ or event.button != 1
+ or not self.ax.contains(event)[0]):
+ return
+ self.verts.append(self._get_data_coords(event))
+ self.line.set_data(list(zip(*self.verts)))
+
+ if self.useblit:
+ self.canvas.restore_region(self.background)
+ self.ax.draw_artist(self.line)
+ self.canvas.blit(self.ax.bbox)
+ else:
+ self.canvas.draw_idle()
diff --git a/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_copy_native.h b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_copy_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..f5343c0a03a950e23bbba71c21c1ffb9039fb123
--- /dev/null
+++ b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_copy_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor _reshape_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size);
+} // namespace native
+} // namespace at
diff --git a/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices.h b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices.h
new file mode 100644
index 0000000000000000000000000000000000000000..fb2c9538a517042ca00dfafcf90d003d7f1daf6d
--- /dev/null
+++ b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices.h
@@ -0,0 +1,30 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+
+
+#include
+
+namespace at {
+
+
+// aten::_validate_compressed_sparse_indices(bool is_crow, Tensor compressed_idx, Tensor plain_idx, int cdim, int dim, int nnz) -> ()
+inline void _validate_compressed_sparse_indices(bool is_crow, const at::Tensor & compressed_idx, const at::Tensor & plain_idx, int64_t cdim, int64_t dim, int64_t nnz) {
+ return at::_ops::_validate_compressed_sparse_indices::call(is_crow, compressed_idx, plain_idx, cdim, dim, nnz);
+}
+
+}
diff --git a/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/concatenate_ops.h b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/concatenate_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..83fd5131d291727809b94c9ec18841a3cfa53923
--- /dev/null
+++ b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/concatenate_ops.h
@@ -0,0 +1,61 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include
+#include
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API concatenate {
+ using schema = at::Tensor (at::TensorList, int64_t);
+ using ptr_schema = schema*;
+ // See Note [static constexpr char* members for windows NVCC]
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concatenate")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concatenate(Tensor[] tensors, int dim=0) -> Tensor")
+ static at::Tensor call(at::TensorList tensors, int64_t dim);
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, int64_t dim);
+};
+
+struct TORCH_API concatenate_out {
+ using schema = at::Tensor & (at::TensorList, int64_t, at::Tensor &);
+ using ptr_schema = schema*;
+ // See Note [static constexpr char* members for windows NVCC]
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concatenate")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concatenate.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)")
+ static at::Tensor & call(at::TensorList tensors, int64_t dim, at::Tensor & out);
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, int64_t dim, at::Tensor & out);
+};
+
+struct TORCH_API concatenate_names {
+ using schema = at::Tensor (at::TensorList, at::Dimname);
+ using ptr_schema = schema*;
+ // See Note [static constexpr char* members for windows NVCC]
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concatenate")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concatenate.names(Tensor[] tensors, Dimname dim) -> Tensor")
+ static at::Tensor call(at::TensorList tensors, at::Dimname dim);
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, at::Dimname dim);
+};
+
+struct TORCH_API concatenate_names_out {
+ using schema = at::Tensor & (at::TensorList, at::Dimname, at::Tensor &);
+ using ptr_schema = schema*;
+ // See Note [static constexpr char* members for windows NVCC]
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concatenate")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_out")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concatenate.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)")
+ static at::Tensor & call(at::TensorList tensors, at::Dimname dim, at::Tensor & out);
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, at::Dimname dim, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/native_dropout_cpu_dispatch.h b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/native_dropout_cpu_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..c075861ca7dc656d1692b92a44355e8b5ef8f1e1
--- /dev/null
+++ b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/native_dropout_cpu_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include
+#include
+#include
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include
+
+namespace at {
+
+namespace cpu {
+
+TORCH_API ::std::tuple native_dropout(const at::Tensor & input, double p, ::std::optional train);
+
+} // namespace cpu
+} // namespace at
diff --git a/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy_compositeexplicitautogradnonfunctional_dispatch.h b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy_compositeexplicitautogradnonfunctional_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..dc512560868370538efd0470ddc264d57999d94c
--- /dev/null
+++ b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy_compositeexplicitautogradnonfunctional_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include
+#include
+#include
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include
+
+namespace at {
+
+namespace compositeexplicitautogradnonfunctional {
+
+TORCH_API at::Tensor permute_copy(const at::Tensor & self, at::IntArrayRef dims);
+
+} // namespace compositeexplicitautogradnonfunctional
+} // namespace at
diff --git a/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad1d_compositeexplicitautogradnonfunctional_dispatch.h b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad1d_compositeexplicitautogradnonfunctional_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..e1eeafc52b837e26baef8f39c6b65726f835bee3
--- /dev/null
+++ b/pllava/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad1d_compositeexplicitautogradnonfunctional_dispatch.h
@@ -0,0 +1,24 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include
+#include
+#include
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include
+
+namespace at {
+
+namespace compositeexplicitautogradnonfunctional {
+
+TORCH_API at::Tensor replication_pad1d(const at::Tensor & self, at::IntArrayRef padding);
+TORCH_API at::Tensor replication_pad1d_symint(const at::Tensor & self, c10::SymIntArrayRef padding);
+
+} // namespace compositeexplicitautogradnonfunctional
+} // namespace at