diff --git a/.gitattributes b/.gitattributes index ca8770b10429a154a863b3fde20f58aa02b04476..6f0f40154936db191c41c6512a373020a1fac75f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -362,3 +362,4 @@ llava_next/lib/python3.10/site-packages/scipy/optimize/_lsq/givens_elimination.c parrot/lib/python3.10/site-packages/torch/testing/_internal/generated/__pycache__/annotated_fn_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text llava_next/lib/python3.10/site-packages/scipy/optimize/_bglu_dense.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/torchvision.libs/libpng16.7f72a3c5.so.16 filter=lfs diff=lfs merge=lfs -text +llava_next/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/__init__.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..54b28a8318ef567edc04a986c2121d28077e5511 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/__init__.pyi @@ -0,0 +1,115 @@ +__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", + "color_sequences", +] + +import os +from pathlib import Path + +from collections.abc import Callable, Generator +import contextlib +from packaging.version import Version + +from matplotlib._api import MatplotlibDeprecationWarning +from typing import Any, NamedTuple + +class _VersionInfo(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + +__bibtex__: str +__version__: str +__version_info__: _VersionInfo + +def set_loglevel(level: str) -> None: ... + +class _ExecInfo(NamedTuple): + executable: str + raw_version: str + version: Version + +class ExecutableNotFoundError(FileNotFoundError): ... + +def _get_executable_info(name: str) -> _ExecInfo: ... +def get_configdir() -> str: ... +def get_cachedir() -> str: ... +def get_data_path() -> str: ... +def matplotlib_fname() -> str: ... + +class RcParams(dict[str, Any]): + validate: dict[str, Callable] + def __init__(self, *args, **kwargs) -> None: ... + def _set(self, key: str, val: Any) -> None: ... + def _get(self, key: str) -> Any: ... + def __setitem__(self, key: str, val: Any) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __iter__(self) -> Generator[str, None, None]: ... + def __len__(self) -> int: ... + def find_all(self, pattern: str) -> RcParams: ... + def copy(self) -> RcParams: ... + +def rc_params(fail_on_error: bool = ...) -> RcParams: ... +def rc_params_from_file( + fname: str | Path | os.PathLike, + fail_on_error: bool = ..., + use_default_template: bool = ..., +) -> RcParams: ... + +rcParamsDefault: RcParams +rcParams: RcParams +rcParamsOrig: RcParams +defaultParams: dict[str, Any] + +def rc(group: str, **kwargs) -> None: ... +def rcdefaults() -> None: ... +def rc_file_defaults() -> None: ... +def rc_file( + fname: str | Path | os.PathLike, *, use_default_template: bool = ... +) -> None: ... +@contextlib.contextmanager +def rc_context( + rc: dict[str, Any] | None = ..., fname: str | Path | os.PathLike | None = ... +) -> Generator[None, None, None]: ... +def use(backend: str, *, force: bool = ...) -> None: ... +def get_backend() -> str: ... +def interactive(b: bool) -> None: ... +def is_interactive() -> bool: ... + +def _preprocess_data( + func: Callable | None = ..., + *, + replace_names: list[str] | None = ..., + label_namer: str | None = ... +) -> Callable: ... + +from matplotlib.cm import _colormaps as colormaps +from matplotlib.colors import _color_sequences as color_sequences diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.py b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27d68529b7d43e43e0351b2576ed61b6b46e652e --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.py @@ -0,0 +1,381 @@ +""" +Helper functions for managing the Matplotlib API. + +This documentation is only relevant for Matplotlib developers, not for users. + +.. warning:: + + This module and its submodules are for internal use only. Do not use them + in your own code. We may change the API at any time with no warning. + +""" + +import functools +import itertools +import re +import sys +import warnings + +from .deprecation import ( # noqa: F401 + deprecated, warn_deprecated, + rename_parameter, delete_parameter, make_keyword_only, + deprecate_method_override, deprecate_privatize_attribute, + suppress_matplotlib_deprecation_warning, + MatplotlibDeprecationWarning) + + +class classproperty: + """ + Like `property`, but also triggers on access via the class, and it is the + *class* that's passed as argument. + + Examples + -------- + :: + + class C: + @classproperty + def foo(cls): + return cls.__name__ + + assert C.foo == "C" + """ + + def __init__(self, fget, fset=None, fdel=None, doc=None): + self._fget = fget + if fset is not None or fdel is not None: + raise ValueError('classproperty only implements fget.') + self.fset = fset + self.fdel = fdel + # docs are ignored for now + self._doc = doc + + def __get__(self, instance, owner): + return self._fget(owner) + + @property + def fget(self): + return self._fget + + +# In the following check_foo() functions, the first parameter is positional-only to make +# e.g. `_api.check_isinstance([...], types=foo)` work. + +def check_isinstance(types, /, **kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* is an instance + of one of *types*; if not, raise an appropriate TypeError. + + As a special case, a ``None`` entry in *types* is treated as NoneType. + + Examples + -------- + >>> _api.check_isinstance((SomeClass, None), arg=arg) + """ + none_type = type(None) + types = ((types,) if isinstance(types, type) else + (none_type,) if types is None else + tuple(none_type if tp is None else tp for tp in types)) + + def type_name(tp): + return ("None" if tp is none_type + else tp.__qualname__ if tp.__module__ == "builtins" + else f"{tp.__module__}.{tp.__qualname__}") + + for k, v in kwargs.items(): + if not isinstance(v, types): + names = [*map(type_name, types)] + if "None" in names: # Move it to the end for better wording. + names.remove("None") + names.append("None") + raise TypeError( + "{!r} must be an instance of {}, not a {}".format( + k, + ", ".join(names[:-1]) + " or " + names[-1] + if len(names) > 1 else names[0], + type_name(type(v)))) + + +def check_in_list(values, /, *, _print_supported_values=True, **kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* is in *values*; + if not, raise an appropriate ValueError. + + Parameters + ---------- + values : iterable + Sequence of values to check on. + _print_supported_values : bool, default: True + Whether to print *values* when raising ValueError. + **kwargs : dict + *key, value* pairs as keyword arguments to find in *values*. + + Raises + ------ + ValueError + If any *value* in *kwargs* is not found in *values*. + + Examples + -------- + >>> _api.check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg) + """ + if not kwargs: + raise TypeError("No argument to check!") + for key, val in kwargs.items(): + if val not in values: + msg = f"{val!r} is not a valid value for {key}" + if _print_supported_values: + msg += f"; supported values are {', '.join(map(repr, values))}" + raise ValueError(msg) + + +def check_shape(shape, /, **kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* has the shape *shape*; + if not, raise an appropriate ValueError. + + *None* in the shape is treated as a "free" size that can have any length. + e.g. (None, 2) -> (N, 2) + + The values checked must be numpy arrays. + + Examples + -------- + To check for (N, 2) shaped arrays + + >>> _api.check_shape((None, 2), arg=arg, other_arg=other_arg) + """ + for k, v in kwargs.items(): + data_shape = v.shape + + if (len(data_shape) != len(shape) + or any(s != t and t is not None for s, t in zip(data_shape, shape))): + dim_labels = iter(itertools.chain( + 'NMLKJIH', + (f"D{i}" for i in itertools.count()))) + text_shape = ", ".join([str(n) if n is not None else next(dim_labels) + for n in shape[::-1]][::-1]) + if len(shape) == 1: + text_shape += "," + + raise ValueError( + f"{k!r} must be {len(shape)}D with shape ({text_shape}), " + f"but your input has shape {v.shape}" + ) + + +def check_getitem(mapping, /, **kwargs): + """ + *kwargs* must consist of a single *key, value* pair. If *key* is in + *mapping*, return ``mapping[value]``; else, raise an appropriate + ValueError. + + Examples + -------- + >>> _api.check_getitem({"foo": "bar"}, arg=arg) + """ + if len(kwargs) != 1: + raise ValueError("check_getitem takes a single keyword argument") + (k, v), = kwargs.items() + try: + return mapping[v] + except KeyError: + raise ValueError( + f"{v!r} is not a valid value for {k}; supported values are " + f"{', '.join(map(repr, mapping))}") from None + + +def caching_module_getattr(cls): + """ + Helper decorator for implementing module-level ``__getattr__`` as a class. + + This decorator must be used at the module toplevel as follows:: + + @caching_module_getattr + class __getattr__: # The class *must* be named ``__getattr__``. + @property # Only properties are taken into account. + def name(self): ... + + The ``__getattr__`` class will be replaced by a ``__getattr__`` + function such that trying to access ``name`` on the module will + resolve the corresponding property (which may be decorated e.g. with + ``_api.deprecated`` for deprecating module globals). The properties are + all implicitly cached. Moreover, a suitable AttributeError is generated + and raised if no property with the given name exists. + """ + + assert cls.__name__ == "__getattr__" + # Don't accidentally export cls dunders. + props = {name: prop for name, prop in vars(cls).items() + if isinstance(prop, property)} + instance = cls() + + @functools.cache + def __getattr__(name): + if name in props: + return props[name].__get__(instance) + raise AttributeError( + f"module {cls.__module__!r} has no attribute {name!r}") + + return __getattr__ + + +def define_aliases(alias_d, cls=None): + """ + Class decorator for defining property aliases. + + Use as :: + + @_api.define_aliases({"property": ["alias", ...], ...}) + class C: ... + + For each property, if the corresponding ``get_property`` is defined in the + class so far, an alias named ``get_alias`` will be defined; the same will + be done for setters. If neither the getter nor the setter exists, an + exception will be raised. + + The alias map is stored as the ``_alias_map`` attribute on the class and + can be used by `.normalize_kwargs` (which assumes that higher priority + aliases come last). + """ + if cls is None: # Return the actual class decorator. + return functools.partial(define_aliases, alias_d) + + def make_alias(name): # Enforce a closure over *name*. + @functools.wraps(getattr(cls, name)) + def method(self, *args, **kwargs): + return getattr(self, name)(*args, **kwargs) + return method + + for prop, aliases in alias_d.items(): + exists = False + for prefix in ["get_", "set_"]: + if prefix + prop in vars(cls): + exists = True + for alias in aliases: + method = make_alias(prefix + prop) + method.__name__ = prefix + alias + method.__doc__ = f"Alias for `{prefix + prop}`." + setattr(cls, prefix + alias, method) + if not exists: + raise ValueError( + f"Neither getter nor setter exists for {prop!r}") + + def get_aliased_and_aliases(d): + return {*d, *(alias for aliases in d.values() for alias in aliases)} + + preexisting_aliases = getattr(cls, "_alias_map", {}) + conflicting = (get_aliased_and_aliases(preexisting_aliases) + & get_aliased_and_aliases(alias_d)) + if conflicting: + # Need to decide on conflict resolution policy. + raise NotImplementedError( + f"Parent class already defines conflicting aliases: {conflicting}") + cls._alias_map = {**preexisting_aliases, **alias_d} + return cls + + +def select_matching_signature(funcs, *args, **kwargs): + """ + Select and call the function that accepts ``*args, **kwargs``. + + *funcs* is a list of functions which should not raise any exception (other + than `TypeError` if the arguments passed do not match their signature). + + `select_matching_signature` tries to call each of the functions in *funcs* + with ``*args, **kwargs`` (in the order in which they are given). Calls + that fail with a `TypeError` are silently skipped. As soon as a call + succeeds, `select_matching_signature` returns its return value. If no + function accepts ``*args, **kwargs``, then the `TypeError` raised by the + last failing call is re-raised. + + Callers should normally make sure that any ``*args, **kwargs`` can only + bind a single *func* (to avoid any ambiguity), although this is not checked + by `select_matching_signature`. + + Notes + ----- + `select_matching_signature` is intended to help implementing + signature-overloaded functions. In general, such functions should be + avoided, except for back-compatibility concerns. A typical use pattern is + :: + + def my_func(*args, **kwargs): + params = select_matching_signature( + [lambda old1, old2: locals(), lambda new: locals()], + *args, **kwargs) + if "old1" in params: + warn_deprecated(...) + old1, old2 = params.values() # note that locals() is ordered. + else: + new, = params.values() + # do things with params + + which allows *my_func* to be called either with two parameters (*old1* and + *old2*) or a single one (*new*). Note that the new signature is given + last, so that callers get a `TypeError` corresponding to the new signature + if the arguments they passed in do not match any signature. + """ + # Rather than relying on locals() ordering, one could have just used func's + # signature (``bound = inspect.signature(func).bind(*args, **kwargs); + # bound.apply_defaults(); return bound``) but that is significantly slower. + for i, func in enumerate(funcs): + try: + return func(*args, **kwargs) + except TypeError: + if i == len(funcs) - 1: + raise + + +def nargs_error(name, takes, given): + """Generate a TypeError to be raised by function calls with wrong arity.""" + return TypeError(f"{name}() takes {takes} positional arguments but " + f"{given} were given") + + +def kwarg_error(name, kw): + """ + Generate a TypeError to be raised by function calls with wrong kwarg. + + Parameters + ---------- + name : str + The name of the calling function. + kw : str or Iterable[str] + Either the invalid keyword argument name, or an iterable yielding + invalid keyword arguments (e.g., a ``kwargs`` dict). + """ + if not isinstance(kw, str): + kw = next(iter(kw)) + return TypeError(f"{name}() got an unexpected keyword argument '{kw}'") + + +def recursive_subclasses(cls): + """Yield *cls* and direct and indirect subclasses of *cls*.""" + yield cls + for subcls in cls.__subclasses__(): + yield from recursive_subclasses(subcls) + + +def warn_external(message, category=None): + """ + `warnings.warn` wrapper that sets *stacklevel* to "outside Matplotlib". + + The original emitter of the warning can be obtained by patching this + function back to `warnings.warn`, i.e. ``_api.warn_external = + warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``, + etc.). + """ + frame = sys._getframe() + for stacklevel in itertools.count(1): + if frame is None: + # when called in embedded context may hit frame is None + break + if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.(?!tests\.))", + # Work around sphinx-gallery not setting __name__. + frame.f_globals.get("__name__", "")): + break + frame = frame.f_back + # preemptively break reference cycle between locals and the frame + del frame + warnings.warn(message, category, stacklevel) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4baff7cd804c45820e8a862559b9619a577f8cb9 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.pyi @@ -0,0 +1,59 @@ +from collections.abc import Callable, Generator, Mapping, Sequence +from typing import Any, Iterable, TypeVar, overload + +from numpy.typing import NDArray + +from .deprecation import ( # noqa: re-exported API + deprecated as deprecated, + warn_deprecated as warn_deprecated, + rename_parameter as rename_parameter, + delete_parameter as delete_parameter, + make_keyword_only as make_keyword_only, + deprecate_method_override as deprecate_method_override, + deprecate_privatize_attribute as deprecate_privatize_attribute, + suppress_matplotlib_deprecation_warning as suppress_matplotlib_deprecation_warning, + MatplotlibDeprecationWarning as MatplotlibDeprecationWarning, +) + +_T = TypeVar("_T") + +class classproperty(Any): + def __init__( + self, + fget: Callable[[_T], Any], + fset: None = ..., + fdel: None = ..., + doc: str | None = None, + ): ... + # Replace return with Self when py3.9 is dropped + @overload + def __get__(self, instance: None, owner: None) -> classproperty: ... + @overload + def __get__(self, instance: object, owner: type[object]) -> Any: ... + @property + def fget(self) -> Callable[[_T], Any]: ... + +def check_isinstance( + types: type | tuple[type | None, ...], /, **kwargs: Any +) -> None: ... +def check_in_list( + values: Sequence[Any], /, *, _print_supported_values: bool = ..., **kwargs: Any +) -> None: ... +def check_shape(shape: tuple[int | None, ...], /, **kwargs: NDArray) -> None: ... +def check_getitem(mapping: Mapping[Any, Any], /, **kwargs: Any) -> Any: ... +def caching_module_getattr(cls: type) -> Callable[[str], Any]: ... +@overload +def define_aliases( + alias_d: dict[str, list[str]], cls: None = ... +) -> Callable[[type[_T]], type[_T]]: ... +@overload +def define_aliases(alias_d: dict[str, list[str]], cls: type[_T]) -> type[_T]: ... +def select_matching_signature( + funcs: list[Callable], *args: Any, **kwargs: Any +) -> Any: ... +def nargs_error(name: str, takes: int | str, given: int) -> TypeError: ... +def kwarg_error(name: str, kw: str | Iterable[str]) -> TypeError: ... +def recursive_subclasses(cls: type) -> Generator[type, None, None]: ... +def warn_external( + message: str | Warning, category: type[Warning] | None = ... +) -> None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..290df08aac889bf6c771586309509b0bfc3f9ed0 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/deprecation.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a5c954221697739ade40ae0de2915e29ae982bc Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/deprecation.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.py b/llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..283a55f1beb084370f61109c8cb50b0b4a5003f1 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.py @@ -0,0 +1,513 @@ +""" +Helper functions for deprecating parts of the Matplotlib API. + +This documentation is only relevant for Matplotlib developers, not for users. + +.. warning:: + + This module is for internal use only. Do not use it in your own code. + We may change the API at any time with no warning. + +""" + +import contextlib +import functools +import inspect +import math +import warnings + + +class MatplotlibDeprecationWarning(DeprecationWarning): + """A class for issuing deprecation warnings for Matplotlib users.""" + + +def _generate_deprecation_warning( + since, message='', name='', alternative='', pending=False, obj_type='', + addendum='', *, removal=''): + if pending: + if removal: + raise ValueError( + "A pending deprecation cannot have a scheduled removal") + else: + if not removal: + macro, meso, *_ = since.split('.') + removal = f'{macro}.{int(meso) + 2}' + removal = f"in {removal}" + if not message: + message = ( + ("The %(name)s %(obj_type)s" if obj_type else "%(name)s") + + (" will be deprecated in a future version" + if pending else + " was deprecated in Matplotlib %(since)s and will be removed %(removal)s" + ) + + "." + + (" Use %(alternative)s instead." if alternative else "") + + (" %(addendum)s" if addendum else "")) + warning_cls = (PendingDeprecationWarning if pending + else MatplotlibDeprecationWarning) + return warning_cls(message % dict( + func=name, name=name, obj_type=obj_type, since=since, removal=removal, + alternative=alternative, addendum=addendum)) + + +def warn_deprecated( + since, *, message='', name='', alternative='', pending=False, + obj_type='', addendum='', removal=''): + """ + Display a standardized deprecation. + + Parameters + ---------- + since : str + The release at which this API became deprecated. + message : str, optional + Override the default deprecation message. The ``%(since)s``, + ``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``, + and ``%(removal)s`` format specifiers will be replaced by the values + of the respective arguments passed to this function. + name : str, optional + The name of the deprecated object. + alternative : str, optional + An alternative API that the user may use in place of the deprecated + API. The deprecation warning will tell the user about this alternative + if provided. + pending : bool, optional + If True, uses a PendingDeprecationWarning instead of a + DeprecationWarning. Cannot be used together with *removal*. + obj_type : str, optional + The object type being deprecated. + addendum : str, optional + Additional text appended directly to the final message. + removal : str, optional + The expected removal version. With the default (an empty string), a + removal version is automatically computed from *since*. Set to other + Falsy values to not schedule a removal date. Cannot be used together + with *pending*. + + Examples + -------- + :: + + # To warn of the deprecation of "matplotlib.name_of_module" + warn_deprecated('1.4.0', name='matplotlib.name_of_module', + obj_type='module') + """ + warning = _generate_deprecation_warning( + since, message, name, alternative, pending, obj_type, addendum, + removal=removal) + from . import warn_external + warn_external(warning, category=MatplotlibDeprecationWarning) + + +def deprecated(since, *, message='', name='', alternative='', pending=False, + obj_type=None, addendum='', removal=''): + """ + Decorator to mark a function, a class, or a property as deprecated. + + When deprecating a classmethod, a staticmethod, or a property, the + ``@deprecated`` decorator should go *under* ``@classmethod`` and + ``@staticmethod`` (i.e., `deprecated` should directly decorate the + underlying callable), but *over* ``@property``. + + When deprecating a class ``C`` intended to be used as a base class in a + multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method + (if ``C`` instead inherited its ``__init__`` from its own base class, then + ``@deprecated`` would mess up ``__init__`` inheritance when installing its + own (deprecation-emitting) ``C.__init__``). + + Parameters are the same as for `warn_deprecated`, except that *obj_type* + defaults to 'class' if decorating a class, 'attribute' if decorating a + property, and 'function' otherwise. + + Examples + -------- + :: + + @deprecated('1.4.0') + def the_function_to_deprecate(): + pass + """ + + def deprecate(obj, message=message, name=name, alternative=alternative, + pending=pending, obj_type=obj_type, addendum=addendum): + from matplotlib._api import classproperty + + if isinstance(obj, type): + if obj_type is None: + obj_type = "class" + func = obj.__init__ + name = name or obj.__name__ + old_doc = obj.__doc__ + + def finalize(wrapper, new_doc): + try: + obj.__doc__ = new_doc + except AttributeError: # Can't set on some extension objects. + pass + obj.__init__ = functools.wraps(obj.__init__)(wrapper) + return obj + + elif isinstance(obj, (property, classproperty)): + if obj_type is None: + obj_type = "attribute" + func = None + name = name or obj.fget.__name__ + old_doc = obj.__doc__ + + class _deprecated_property(type(obj)): + def __get__(self, instance, owner=None): + if instance is not None or owner is not None \ + and isinstance(self, classproperty): + emit_warning() + return super().__get__(instance, owner) + + def __set__(self, instance, value): + if instance is not None: + emit_warning() + return super().__set__(instance, value) + + def __delete__(self, instance): + if instance is not None: + emit_warning() + return super().__delete__(instance) + + def __set_name__(self, owner, set_name): + nonlocal name + if name == "": + name = set_name + + def finalize(_, new_doc): + return _deprecated_property( + fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc) + + else: + if obj_type is None: + obj_type = "function" + func = obj + name = name or obj.__name__ + old_doc = func.__doc__ + + def finalize(wrapper, new_doc): + wrapper = functools.wraps(func)(wrapper) + wrapper.__doc__ = new_doc + return wrapper + + def emit_warning(): + warn_deprecated( + since, message=message, name=name, alternative=alternative, + pending=pending, obj_type=obj_type, addendum=addendum, + removal=removal) + + def wrapper(*args, **kwargs): + emit_warning() + return func(*args, **kwargs) + + old_doc = inspect.cleandoc(old_doc or '').strip('\n') + + notes_header = '\nNotes\n-----' + second_arg = ' '.join([t.strip() for t in + (message, f"Use {alternative} instead." + if alternative else "", addendum) if t]) + new_doc = (f"[*Deprecated*] {old_doc}\n" + f"{notes_header if notes_header not in old_doc else ''}\n" + f".. deprecated:: {since}\n" + f" {second_arg}") + + if not old_doc: + # This is to prevent a spurious 'unexpected unindent' warning from + # docutils when the original docstring was blank. + new_doc += r'\ ' + + return finalize(wrapper, new_doc) + + return deprecate + + +class deprecate_privatize_attribute: + """ + Helper to deprecate public access to an attribute (or method). + + This helper should only be used at class scope, as follows:: + + class Foo: + attr = _deprecate_privatize_attribute(*args, **kwargs) + + where *all* parameters are forwarded to `deprecated`. This form makes + ``attr`` a property which forwards read and write access to ``self._attr`` + (same name but with a leading underscore), with a deprecation warning. + Note that the attribute name is derived from *the name this helper is + assigned to*. This helper also works for deprecating methods. + """ + + def __init__(self, *args, **kwargs): + self.deprecator = deprecated(*args, **kwargs) + + def __set_name__(self, owner, name): + setattr(owner, name, self.deprecator( + property(lambda self: getattr(self, f"_{name}"), + lambda self, value: setattr(self, f"_{name}", value)), + name=name)) + + +# Used by _copy_docstring_and_deprecators to redecorate pyplot wrappers and +# boilerplate.py to retrieve original signatures. It may seem natural to store +# this information as an attribute on the wrapper, but if the wrapper gets +# itself functools.wraps()ed, then such attributes are silently propagated to +# the outer wrapper, which is not desired. +DECORATORS = {} + + +def rename_parameter(since, old, new, func=None): + """ + Decorator indicating that parameter *old* of *func* is renamed to *new*. + + The actual implementation of *func* should use *new*, not *old*. If *old* + is passed to *func*, a DeprecationWarning is emitted, and its value is + used, even if *new* is also passed by keyword (this is to simplify pyplot + wrapper functions, which always pass *new* explicitly to the Axes method). + If *new* is also passed but positionally, a TypeError will be raised by the + underlying function during argument binding. + + Examples + -------- + :: + + @_api.rename_parameter("3.1", "bad_name", "good_name") + def func(good_name): ... + """ + + decorator = functools.partial(rename_parameter, since, old, new) + + if func is None: + return decorator + + signature = inspect.signature(func) + assert old not in signature.parameters, ( + f"Matplotlib internal error: {old!r} cannot be a parameter for " + f"{func.__name__}()") + assert new in signature.parameters, ( + f"Matplotlib internal error: {new!r} must be a parameter for " + f"{func.__name__}()") + + @functools.wraps(func) + def wrapper(*args, **kwargs): + if old in kwargs: + warn_deprecated( + since, message=f"The {old!r} parameter of {func.__name__}() " + f"has been renamed {new!r} since Matplotlib {since}; support " + f"for the old name will be dropped %(removal)s.") + kwargs[new] = kwargs.pop(old) + return func(*args, **kwargs) + + # wrapper() must keep the same documented signature as func(): if we + # instead made both *old* and *new* appear in wrapper()'s signature, they + # would both show up in the pyplot function for an Axes method as well and + # pyplot would explicitly pass both arguments to the Axes method. + + DECORATORS[wrapper] = decorator + return wrapper + + +class _deprecated_parameter_class: + def __repr__(self): + return "" + + +_deprecated_parameter = _deprecated_parameter_class() + + +def delete_parameter(since, name, func=None, **kwargs): + """ + Decorator indicating that parameter *name* of *func* is being deprecated. + + The actual implementation of *func* should keep the *name* parameter in its + signature, or accept a ``**kwargs`` argument (through which *name* would be + passed). + + Parameters that come after the deprecated parameter effectively become + keyword-only (as they cannot be passed positionally without triggering the + DeprecationWarning on the deprecated parameter), and should be marked as + such after the deprecation period has passed and the deprecated parameter + is removed. + + Parameters other than *since*, *name*, and *func* are keyword-only and + forwarded to `.warn_deprecated`. + + Examples + -------- + :: + + @_api.delete_parameter("3.1", "unused") + def func(used_arg, other_arg, unused, more_args): ... + """ + + decorator = functools.partial(delete_parameter, since, name, **kwargs) + + if func is None: + return decorator + + signature = inspect.signature(func) + # Name of `**kwargs` parameter of the decorated function, typically + # "kwargs" if such a parameter exists, or None if the decorated function + # doesn't accept `**kwargs`. + kwargs_name = next((param.name for param in signature.parameters.values() + if param.kind == inspect.Parameter.VAR_KEYWORD), None) + if name in signature.parameters: + kind = signature.parameters[name].kind + is_varargs = kind is inspect.Parameter.VAR_POSITIONAL + is_varkwargs = kind is inspect.Parameter.VAR_KEYWORD + if not is_varargs and not is_varkwargs: + name_idx = ( + # Deprecated parameter can't be passed positionally. + math.inf if kind is inspect.Parameter.KEYWORD_ONLY + # If call site has no more than this number of parameters, the + # deprecated parameter can't have been passed positionally. + else [*signature.parameters].index(name)) + func.__signature__ = signature = signature.replace(parameters=[ + param.replace(default=_deprecated_parameter) + if param.name == name else param + for param in signature.parameters.values()]) + else: + name_idx = -1 # Deprecated parameter can always have been passed. + else: + is_varargs = is_varkwargs = False + # Deprecated parameter can't be passed positionally. + name_idx = math.inf + assert kwargs_name, ( + f"Matplotlib internal error: {name!r} must be a parameter for " + f"{func.__name__}()") + + addendum = kwargs.pop('addendum', None) + + @functools.wraps(func) + def wrapper(*inner_args, **inner_kwargs): + if len(inner_args) <= name_idx and name not in inner_kwargs: + # Early return in the simple, non-deprecated case (much faster than + # calling bind()). + return func(*inner_args, **inner_kwargs) + arguments = signature.bind(*inner_args, **inner_kwargs).arguments + if is_varargs and arguments.get(name): + warn_deprecated( + since, message=f"Additional positional arguments to " + f"{func.__name__}() are deprecated since %(since)s and " + f"support for them will be removed %(removal)s.") + elif is_varkwargs and arguments.get(name): + warn_deprecated( + since, message=f"Additional keyword arguments to " + f"{func.__name__}() are deprecated since %(since)s and " + f"support for them will be removed %(removal)s.") + # We cannot just check `name not in arguments` because the pyplot + # wrappers always pass all arguments explicitly. + elif any(name in d and d[name] != _deprecated_parameter + for d in [arguments, arguments.get(kwargs_name, {})]): + deprecation_addendum = ( + f"If any parameter follows {name!r}, they should be passed as " + f"keyword, not positionally.") + warn_deprecated( + since, + name=repr(name), + obj_type=f"parameter of {func.__name__}()", + addendum=(addendum + " " + deprecation_addendum) if addendum + else deprecation_addendum, + **kwargs) + return func(*inner_args, **inner_kwargs) + + DECORATORS[wrapper] = decorator + return wrapper + + +def make_keyword_only(since, name, func=None): + """ + Decorator indicating that passing parameter *name* (or any of the following + ones) positionally to *func* is being deprecated. + + When used on a method that has a pyplot wrapper, this should be the + outermost decorator, so that :file:`boilerplate.py` can access the original + signature. + """ + + decorator = functools.partial(make_keyword_only, since, name) + + if func is None: + return decorator + + signature = inspect.signature(func) + POK = inspect.Parameter.POSITIONAL_OR_KEYWORD + KWO = inspect.Parameter.KEYWORD_ONLY + assert (name in signature.parameters + and signature.parameters[name].kind == POK), ( + f"Matplotlib internal error: {name!r} must be a positional-or-keyword " + f"parameter for {func.__name__}()") + names = [*signature.parameters] + name_idx = names.index(name) + kwonly = [name for name in names[name_idx:] + if signature.parameters[name].kind == POK] + + @functools.wraps(func) + def wrapper(*args, **kwargs): + # Don't use signature.bind here, as it would fail when stacked with + # rename_parameter and an "old" argument name is passed in + # (signature.bind would fail, but the actual call would succeed). + if len(args) > name_idx: + warn_deprecated( + since, message="Passing the %(name)s %(obj_type)s " + "positionally is deprecated since Matplotlib %(since)s; the " + "parameter will become keyword-only %(removal)s.", + name=name, obj_type=f"parameter of {func.__name__}()") + return func(*args, **kwargs) + + # Don't modify *func*'s signature, as boilerplate.py needs it. + wrapper.__signature__ = signature.replace(parameters=[ + param.replace(kind=KWO) if param.name in kwonly else param + for param in signature.parameters.values()]) + DECORATORS[wrapper] = decorator + return wrapper + + +def deprecate_method_override(method, obj, *, allow_empty=False, **kwargs): + """ + Return ``obj.method`` with a deprecation if it was overridden, else None. + + Parameters + ---------- + method + An unbound method, i.e. an expression of the form + ``Class.method_name``. Remember that within the body of a method, one + can always use ``__class__`` to refer to the class that is currently + being defined. + obj + Either an object of the class where *method* is defined, or a subclass + of that class. + allow_empty : bool, default: False + Whether to allow overrides by "empty" methods without emitting a + warning. + **kwargs + Additional parameters passed to `warn_deprecated` to generate the + deprecation warning; must at least include the "since" key. + """ + + def empty(): pass + def empty_with_docstring(): """doc""" + + name = method.__name__ + bound_child = getattr(obj, name) + bound_base = ( + method # If obj is a class, then we need to use unbound methods. + if isinstance(bound_child, type(empty)) and isinstance(obj, type) + else method.__get__(obj)) + if (bound_child != bound_base + and (not allow_empty + or (getattr(getattr(bound_child, "__code__", None), + "co_code", None) + not in [empty.__code__.co_code, + empty_with_docstring.__code__.co_code]))): + warn_deprecated(**{"name": name, "obj_type": "method", **kwargs}) + return bound_child + return None + + +@contextlib.contextmanager +def suppress_matplotlib_deprecation_warning(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", MatplotlibDeprecationWarning) + yield diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9619d1b484fc86719a045cc1da8d9a9c000bf1f5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.pyi @@ -0,0 +1,76 @@ +from collections.abc import Callable +import contextlib +from typing import Any, TypedDict, TypeVar, overload +from typing_extensions import ( + ParamSpec, # < Py 3.10 + Unpack, # < Py 3.11 +) + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_T = TypeVar("_T") + +class MatplotlibDeprecationWarning(DeprecationWarning): ... + +class DeprecationKwargs(TypedDict, total=False): + message: str + alternative: str + pending: bool + obj_type: str + addendum: str + removal: str + +class NamedDeprecationKwargs(DeprecationKwargs, total=False): + name: str + +def warn_deprecated(since: str, **kwargs: Unpack[NamedDeprecationKwargs]) -> None: ... +def deprecated( + since: str, **kwargs: Unpack[NamedDeprecationKwargs] +) -> Callable[[_T], _T]: ... + +class deprecate_privatize_attribute(Any): + def __init__(self, since: str, **kwargs: Unpack[NamedDeprecationKwargs]): ... + def __set_name__(self, owner: type[object], name: str) -> None: ... + +DECORATORS: dict[Callable, Callable] = ... + +@overload +def rename_parameter( + since: str, old: str, new: str, func: None = ... +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +@overload +def rename_parameter( + since: str, old: str, new: str, func: Callable[_P, _R] +) -> Callable[_P, _R]: ... + +class _deprecated_parameter_class: ... + +_deprecated_parameter: _deprecated_parameter_class + +@overload +def delete_parameter( + since: str, name: str, func: None = ..., **kwargs: Unpack[DeprecationKwargs] +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +@overload +def delete_parameter( + since: str, name: str, func: Callable[_P, _R], **kwargs: Unpack[DeprecationKwargs] +) -> Callable[_P, _R]: ... +@overload +def make_keyword_only( + since: str, name: str, func: None = ... +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +@overload +def make_keyword_only( + since: str, name: str, func: Callable[_P, _R] +) -> Callable[_P, _R]: ... +def deprecate_method_override( + method: Callable[_P, _R], + obj: object | type, + *, + allow_empty: bool = ..., + since: str, + **kwargs: Unpack[NamedDeprecationKwargs] +) -> Callable[_P, _R]: ... +def suppress_matplotlib_deprecation_warning() -> ( + contextlib.AbstractContextManager[None] +): ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_blocking_input.py b/llava_next/lib/python3.10/site-packages/matplotlib/_blocking_input.py new file mode 100644 index 0000000000000000000000000000000000000000..45f0775714431e73c283fede1f0cf12d7eaabb8d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_blocking_input.py @@ -0,0 +1,30 @@ +def blocking_input_loop(figure, event_names, timeout, handler): + """ + Run *figure*'s event loop while listening to interactive events. + + The events listed in *event_names* are passed to *handler*. + + This function is used to implement `.Figure.waitforbuttonpress`, + `.Figure.ginput`, and `.Axes.clabel`. + + Parameters + ---------- + figure : `~matplotlib.figure.Figure` + event_names : list of str + The names of the events passed to *handler*. + timeout : float + If positive, the event loop is stopped after *timeout* seconds. + handler : Callable[[Event], Any] + Function called for each event; it can force an early exit of the event + loop by calling ``canvas.stop_event_loop()``. + """ + if figure.canvas.manager: + figure.show() # Ensure that the figure is shown if we are managing it. + # Connect the events to the on_event function call. + cids = [figure.canvas.mpl_connect(name, handler) for name in event_names] + try: + figure.canvas.start_event_loop(timeout) # Start event loop. + finally: # Run even on exception like ctrl-c. + # Disconnect the callbacks. + for cid in cids: + figure.canvas.mpl_disconnect(cid) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_cm.py b/llava_next/lib/python3.10/site-packages/matplotlib/_cm.py new file mode 100644 index 0000000000000000000000000000000000000000..59d260107f3b7f0c09640cda4cbb053121a7a33f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_cm.py @@ -0,0 +1,1446 @@ +""" +Nothing here but dictionaries for generating LinearSegmentedColormaps, +and a dictionary of these dictionaries. + +Documentation for each is in pyplot.colormaps(). Please update this +with the purpose and type of your colormap if you add data for one here. +""" + +from functools import partial + +import numpy as np + +_binary_data = { + 'red': ((0., 1., 1.), (1., 0., 0.)), + 'green': ((0., 1., 1.), (1., 0., 0.)), + 'blue': ((0., 1., 1.), (1., 0., 0.)) + } + +_autumn_data = {'red': ((0., 1.0, 1.0), (1.0, 1.0, 1.0)), + 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)), + 'blue': ((0., 0., 0.), (1.0, 0., 0.))} + +_bone_data = {'red': ((0., 0., 0.), + (0.746032, 0.652778, 0.652778), + (1.0, 1.0, 1.0)), + 'green': ((0., 0., 0.), + (0.365079, 0.319444, 0.319444), + (0.746032, 0.777778, 0.777778), + (1.0, 1.0, 1.0)), + 'blue': ((0., 0., 0.), + (0.365079, 0.444444, 0.444444), + (1.0, 1.0, 1.0))} + +_cool_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)), + 'green': ((0., 1., 1.), (1.0, 0., 0.)), + 'blue': ((0., 1., 1.), (1.0, 1., 1.))} + +_copper_data = {'red': ((0., 0., 0.), + (0.809524, 1.000000, 1.000000), + (1.0, 1.0, 1.0)), + 'green': ((0., 0., 0.), + (1.0, 0.7812, 0.7812)), + 'blue': ((0., 0., 0.), + (1.0, 0.4975, 0.4975))} + +def _flag_red(x): return 0.75 * np.sin((x * 31.5 + 0.25) * np.pi) + 0.5 +def _flag_green(x): return np.sin(x * 31.5 * np.pi) +def _flag_blue(x): return 0.75 * np.sin((x * 31.5 - 0.25) * np.pi) + 0.5 +_flag_data = {'red': _flag_red, 'green': _flag_green, 'blue': _flag_blue} + +def _prism_red(x): return 0.75 * np.sin((x * 20.9 + 0.25) * np.pi) + 0.67 +def _prism_green(x): return 0.75 * np.sin((x * 20.9 - 0.25) * np.pi) + 0.33 +def _prism_blue(x): return -1.1 * np.sin((x * 20.9) * np.pi) +_prism_data = {'red': _prism_red, 'green': _prism_green, 'blue': _prism_blue} + +def _ch_helper(gamma, s, r, h, p0, p1, x): + """Helper function for generating picklable cubehelix colormaps.""" + # Apply gamma factor to emphasise low or high intensity values + xg = x ** gamma + # Calculate amplitude and angle of deviation from the black to white + # diagonal in the plane of constant perceived intensity. + a = h * xg * (1 - xg) / 2 + phi = 2 * np.pi * (s / 3 + r * x) + return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi)) + +def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0): + """ + Return custom data dictionary of (r, g, b) conversion functions, which can + be used with `.ColormapRegistry.register`, for the cubehelix color scheme. + + Unlike most other color schemes cubehelix was designed by D.A. Green to + be monotonically increasing in terms of perceived brightness. + Also, when printed on a black and white postscript printer, the scheme + results in a greyscale with monotonically increasing brightness. + This color scheme is named cubehelix because the (r, g, b) values produced + can be visualised as a squashed helix around the diagonal in the + (r, g, b) color cube. + + For a unit color cube (i.e. 3D coordinates for (r, g, b) each in the + range 0 to 1) the color scheme starts at (r, g, b) = (0, 0, 0), i.e. black, + and finishes at (r, g, b) = (1, 1, 1), i.e. white. For some fraction *x*, + between 0 and 1, the color is the corresponding grey value at that + fraction along the black to white diagonal (x, x, x) plus a color + element. This color element is calculated in a plane of constant + perceived intensity and controlled by the following parameters. + + Parameters + ---------- + gamma : float, default: 1 + Gamma factor emphasizing either low intensity values (gamma < 1), or + high intensity values (gamma > 1). + s : float, default: 0.5 (purple) + The starting color. + r : float, default: -1.5 + The number of r, g, b rotations in color that are made from the start + to the end of the color scheme. The default of -1.5 corresponds to -> + B -> G -> R -> B. + h : float, default: 1 + The hue, i.e. how saturated the colors are. If this parameter is zero + then the color scheme is purely a greyscale. + """ + return {'red': partial(_ch_helper, gamma, s, r, h, -0.14861, 1.78277), + 'green': partial(_ch_helper, gamma, s, r, h, -0.29227, -0.90649), + 'blue': partial(_ch_helper, gamma, s, r, h, 1.97294, 0.0)} + +_cubehelix_data = cubehelix() + +_bwr_data = ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0)) +_brg_data = ((0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) + +# Gnuplot palette functions +def _g0(x): return 0 +def _g1(x): return 0.5 +def _g2(x): return 1 +def _g3(x): return x +def _g4(x): return x ** 2 +def _g5(x): return x ** 3 +def _g6(x): return x ** 4 +def _g7(x): return np.sqrt(x) +def _g8(x): return np.sqrt(np.sqrt(x)) +def _g9(x): return np.sin(x * np.pi / 2) +def _g10(x): return np.cos(x * np.pi / 2) +def _g11(x): return np.abs(x - 0.5) +def _g12(x): return (2 * x - 1) ** 2 +def _g13(x): return np.sin(x * np.pi) +def _g14(x): return np.abs(np.cos(x * np.pi)) +def _g15(x): return np.sin(x * 2 * np.pi) +def _g16(x): return np.cos(x * 2 * np.pi) +def _g17(x): return np.abs(np.sin(x * 2 * np.pi)) +def _g18(x): return np.abs(np.cos(x * 2 * np.pi)) +def _g19(x): return np.abs(np.sin(x * 4 * np.pi)) +def _g20(x): return np.abs(np.cos(x * 4 * np.pi)) +def _g21(x): return 3 * x +def _g22(x): return 3 * x - 1 +def _g23(x): return 3 * x - 2 +def _g24(x): return np.abs(3 * x - 1) +def _g25(x): return np.abs(3 * x - 2) +def _g26(x): return (3 * x - 1) / 2 +def _g27(x): return (3 * x - 2) / 2 +def _g28(x): return np.abs((3 * x - 1) / 2) +def _g29(x): return np.abs((3 * x - 2) / 2) +def _g30(x): return x / 0.32 - 0.78125 +def _g31(x): return 2 * x - 0.84 +def _g32(x): + ret = np.zeros(len(x)) + m = (x < 0.25) + ret[m] = 4 * x[m] + m = (x >= 0.25) & (x < 0.92) + ret[m] = -2 * x[m] + 1.84 + m = (x >= 0.92) + ret[m] = x[m] / 0.08 - 11.5 + return ret +def _g33(x): return np.abs(2 * x - 0.5) +def _g34(x): return 2 * x +def _g35(x): return 2 * x - 0.5 +def _g36(x): return 2 * x - 1 + +gfunc = {i: globals()[f"_g{i}"] for i in range(37)} + +_gnuplot_data = { + 'red': gfunc[7], + 'green': gfunc[5], + 'blue': gfunc[15], +} + +_gnuplot2_data = { + 'red': gfunc[30], + 'green': gfunc[31], + 'blue': gfunc[32], +} + +_ocean_data = { + 'red': gfunc[23], + 'green': gfunc[28], + 'blue': gfunc[3], +} + +_afmhot_data = { + 'red': gfunc[34], + 'green': gfunc[35], + 'blue': gfunc[36], +} + +_rainbow_data = { + 'red': gfunc[33], + 'green': gfunc[13], + 'blue': gfunc[10], +} + +_seismic_data = ( + (0.0, 0.0, 0.3), (0.0, 0.0, 1.0), + (1.0, 1.0, 1.0), (1.0, 0.0, 0.0), + (0.5, 0.0, 0.0)) + +_terrain_data = ( + (0.00, (0.2, 0.2, 0.6)), + (0.15, (0.0, 0.6, 1.0)), + (0.25, (0.0, 0.8, 0.4)), + (0.50, (1.0, 1.0, 0.6)), + (0.75, (0.5, 0.36, 0.33)), + (1.00, (1.0, 1.0, 1.0))) + +_gray_data = {'red': ((0., 0, 0), (1., 1, 1)), + 'green': ((0., 0, 0), (1., 1, 1)), + 'blue': ((0., 0, 0), (1., 1, 1))} + +_hot_data = {'red': ((0., 0.0416, 0.0416), + (0.365079, 1.000000, 1.000000), + (1.0, 1.0, 1.0)), + 'green': ((0., 0., 0.), + (0.365079, 0.000000, 0.000000), + (0.746032, 1.000000, 1.000000), + (1.0, 1.0, 1.0)), + 'blue': ((0., 0., 0.), + (0.746032, 0.000000, 0.000000), + (1.0, 1.0, 1.0))} + +_hsv_data = {'red': ((0., 1., 1.), + (0.158730, 1.000000, 1.000000), + (0.174603, 0.968750, 0.968750), + (0.333333, 0.031250, 0.031250), + (0.349206, 0.000000, 0.000000), + (0.666667, 0.000000, 0.000000), + (0.682540, 0.031250, 0.031250), + (0.841270, 0.968750, 0.968750), + (0.857143, 1.000000, 1.000000), + (1.0, 1.0, 1.0)), + 'green': ((0., 0., 0.), + (0.158730, 0.937500, 0.937500), + (0.174603, 1.000000, 1.000000), + (0.507937, 1.000000, 1.000000), + (0.666667, 0.062500, 0.062500), + (0.682540, 0.000000, 0.000000), + (1.0, 0., 0.)), + 'blue': ((0., 0., 0.), + (0.333333, 0.000000, 0.000000), + (0.349206, 0.062500, 0.062500), + (0.507937, 1.000000, 1.000000), + (0.841270, 1.000000, 1.000000), + (0.857143, 0.937500, 0.937500), + (1.0, 0.09375, 0.09375))} + +_jet_data = {'red': ((0.00, 0, 0), + (0.35, 0, 0), + (0.66, 1, 1), + (0.89, 1, 1), + (1.00, 0.5, 0.5)), + 'green': ((0.000, 0, 0), + (0.125, 0, 0), + (0.375, 1, 1), + (0.640, 1, 1), + (0.910, 0, 0), + (1.000, 0, 0)), + 'blue': ((0.00, 0.5, 0.5), + (0.11, 1, 1), + (0.34, 1, 1), + (0.65, 0, 0), + (1.00, 0, 0))} + +_pink_data = {'red': ((0., 0.1178, 0.1178), (0.015873, 0.195857, 0.195857), + (0.031746, 0.250661, 0.250661), + (0.047619, 0.295468, 0.295468), + (0.063492, 0.334324, 0.334324), + (0.079365, 0.369112, 0.369112), + (0.095238, 0.400892, 0.400892), + (0.111111, 0.430331, 0.430331), + (0.126984, 0.457882, 0.457882), + (0.142857, 0.483867, 0.483867), + (0.158730, 0.508525, 0.508525), + (0.174603, 0.532042, 0.532042), + (0.190476, 0.554563, 0.554563), + (0.206349, 0.576204, 0.576204), + (0.222222, 0.597061, 0.597061), + (0.238095, 0.617213, 0.617213), + (0.253968, 0.636729, 0.636729), + (0.269841, 0.655663, 0.655663), + (0.285714, 0.674066, 0.674066), + (0.301587, 0.691980, 0.691980), + (0.317460, 0.709441, 0.709441), + (0.333333, 0.726483, 0.726483), + (0.349206, 0.743134, 0.743134), + (0.365079, 0.759421, 0.759421), + (0.380952, 0.766356, 0.766356), + (0.396825, 0.773229, 0.773229), + (0.412698, 0.780042, 0.780042), + (0.428571, 0.786796, 0.786796), + (0.444444, 0.793492, 0.793492), + (0.460317, 0.800132, 0.800132), + (0.476190, 0.806718, 0.806718), + (0.492063, 0.813250, 0.813250), + (0.507937, 0.819730, 0.819730), + (0.523810, 0.826160, 0.826160), + (0.539683, 0.832539, 0.832539), + (0.555556, 0.838870, 0.838870), + (0.571429, 0.845154, 0.845154), + (0.587302, 0.851392, 0.851392), + (0.603175, 0.857584, 0.857584), + (0.619048, 0.863731, 0.863731), + (0.634921, 0.869835, 0.869835), + (0.650794, 0.875897, 0.875897), + (0.666667, 0.881917, 0.881917), + (0.682540, 0.887896, 0.887896), + (0.698413, 0.893835, 0.893835), + (0.714286, 0.899735, 0.899735), + (0.730159, 0.905597, 0.905597), + (0.746032, 0.911421, 0.911421), + (0.761905, 0.917208, 0.917208), + (0.777778, 0.922958, 0.922958), + (0.793651, 0.928673, 0.928673), + (0.809524, 0.934353, 0.934353), + (0.825397, 0.939999, 0.939999), + (0.841270, 0.945611, 0.945611), + (0.857143, 0.951190, 0.951190), + (0.873016, 0.956736, 0.956736), + (0.888889, 0.962250, 0.962250), + (0.904762, 0.967733, 0.967733), + (0.920635, 0.973185, 0.973185), + (0.936508, 0.978607, 0.978607), + (0.952381, 0.983999, 0.983999), + (0.968254, 0.989361, 0.989361), + (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)), + 'green': ((0., 0., 0.), (0.015873, 0.102869, 0.102869), + (0.031746, 0.145479, 0.145479), + (0.047619, 0.178174, 0.178174), + (0.063492, 0.205738, 0.205738), + (0.079365, 0.230022, 0.230022), + (0.095238, 0.251976, 0.251976), + (0.111111, 0.272166, 0.272166), + (0.126984, 0.290957, 0.290957), + (0.142857, 0.308607, 0.308607), + (0.158730, 0.325300, 0.325300), + (0.174603, 0.341178, 0.341178), + (0.190476, 0.356348, 0.356348), + (0.206349, 0.370899, 0.370899), + (0.222222, 0.384900, 0.384900), + (0.238095, 0.398410, 0.398410), + (0.253968, 0.411476, 0.411476), + (0.269841, 0.424139, 0.424139), + (0.285714, 0.436436, 0.436436), + (0.301587, 0.448395, 0.448395), + (0.317460, 0.460044, 0.460044), + (0.333333, 0.471405, 0.471405), + (0.349206, 0.482498, 0.482498), + (0.365079, 0.493342, 0.493342), + (0.380952, 0.517549, 0.517549), + (0.396825, 0.540674, 0.540674), + (0.412698, 0.562849, 0.562849), + (0.428571, 0.584183, 0.584183), + (0.444444, 0.604765, 0.604765), + (0.460317, 0.624669, 0.624669), + (0.476190, 0.643958, 0.643958), + (0.492063, 0.662687, 0.662687), + (0.507937, 0.680900, 0.680900), + (0.523810, 0.698638, 0.698638), + (0.539683, 0.715937, 0.715937), + (0.555556, 0.732828, 0.732828), + (0.571429, 0.749338, 0.749338), + (0.587302, 0.765493, 0.765493), + (0.603175, 0.781313, 0.781313), + (0.619048, 0.796819, 0.796819), + (0.634921, 0.812029, 0.812029), + (0.650794, 0.826960, 0.826960), + (0.666667, 0.841625, 0.841625), + (0.682540, 0.856040, 0.856040), + (0.698413, 0.870216, 0.870216), + (0.714286, 0.884164, 0.884164), + (0.730159, 0.897896, 0.897896), + (0.746032, 0.911421, 0.911421), + (0.761905, 0.917208, 0.917208), + (0.777778, 0.922958, 0.922958), + (0.793651, 0.928673, 0.928673), + (0.809524, 0.934353, 0.934353), + (0.825397, 0.939999, 0.939999), + (0.841270, 0.945611, 0.945611), + (0.857143, 0.951190, 0.951190), + (0.873016, 0.956736, 0.956736), + (0.888889, 0.962250, 0.962250), + (0.904762, 0.967733, 0.967733), + (0.920635, 0.973185, 0.973185), + (0.936508, 0.978607, 0.978607), + (0.952381, 0.983999, 0.983999), + (0.968254, 0.989361, 0.989361), + (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)), + 'blue': ((0., 0., 0.), (0.015873, 0.102869, 0.102869), + (0.031746, 0.145479, 0.145479), + (0.047619, 0.178174, 0.178174), + (0.063492, 0.205738, 0.205738), + (0.079365, 0.230022, 0.230022), + (0.095238, 0.251976, 0.251976), + (0.111111, 0.272166, 0.272166), + (0.126984, 0.290957, 0.290957), + (0.142857, 0.308607, 0.308607), + (0.158730, 0.325300, 0.325300), + (0.174603, 0.341178, 0.341178), + (0.190476, 0.356348, 0.356348), + (0.206349, 0.370899, 0.370899), + (0.222222, 0.384900, 0.384900), + (0.238095, 0.398410, 0.398410), + (0.253968, 0.411476, 0.411476), + (0.269841, 0.424139, 0.424139), + (0.285714, 0.436436, 0.436436), + (0.301587, 0.448395, 0.448395), + (0.317460, 0.460044, 0.460044), + (0.333333, 0.471405, 0.471405), + (0.349206, 0.482498, 0.482498), + (0.365079, 0.493342, 0.493342), + (0.380952, 0.503953, 0.503953), + (0.396825, 0.514344, 0.514344), + (0.412698, 0.524531, 0.524531), + (0.428571, 0.534522, 0.534522), + (0.444444, 0.544331, 0.544331), + (0.460317, 0.553966, 0.553966), + (0.476190, 0.563436, 0.563436), + (0.492063, 0.572750, 0.572750), + (0.507937, 0.581914, 0.581914), + (0.523810, 0.590937, 0.590937), + (0.539683, 0.599824, 0.599824), + (0.555556, 0.608581, 0.608581), + (0.571429, 0.617213, 0.617213), + (0.587302, 0.625727, 0.625727), + (0.603175, 0.634126, 0.634126), + (0.619048, 0.642416, 0.642416), + (0.634921, 0.650600, 0.650600), + (0.650794, 0.658682, 0.658682), + (0.666667, 0.666667, 0.666667), + (0.682540, 0.674556, 0.674556), + (0.698413, 0.682355, 0.682355), + (0.714286, 0.690066, 0.690066), + (0.730159, 0.697691, 0.697691), + (0.746032, 0.705234, 0.705234), + (0.761905, 0.727166, 0.727166), + (0.777778, 0.748455, 0.748455), + (0.793651, 0.769156, 0.769156), + (0.809524, 0.789314, 0.789314), + (0.825397, 0.808969, 0.808969), + (0.841270, 0.828159, 0.828159), + (0.857143, 0.846913, 0.846913), + (0.873016, 0.865261, 0.865261), + (0.888889, 0.883229, 0.883229), + (0.904762, 0.900837, 0.900837), + (0.920635, 0.918109, 0.918109), + (0.936508, 0.935061, 0.935061), + (0.952381, 0.951711, 0.951711), + (0.968254, 0.968075, 0.968075), + (0.984127, 0.984167, 0.984167), (1.0, 1.0, 1.0))} + +_spring_data = {'red': ((0., 1., 1.), (1.0, 1.0, 1.0)), + 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)), + 'blue': ((0., 1., 1.), (1.0, 0.0, 0.0))} + + +_summer_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)), + 'green': ((0., 0.5, 0.5), (1.0, 1.0, 1.0)), + 'blue': ((0., 0.4, 0.4), (1.0, 0.4, 0.4))} + + +_winter_data = {'red': ((0., 0., 0.), (1.0, 0.0, 0.0)), + 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)), + 'blue': ((0., 1., 1.), (1.0, 0.5, 0.5))} + +_nipy_spectral_data = { + 'red': [ + (0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667), + (0.10, 0.5333, 0.5333), (0.15, 0.0, 0.0), + (0.20, 0.0, 0.0), (0.25, 0.0, 0.0), + (0.30, 0.0, 0.0), (0.35, 0.0, 0.0), + (0.40, 0.0, 0.0), (0.45, 0.0, 0.0), + (0.50, 0.0, 0.0), (0.55, 0.0, 0.0), + (0.60, 0.0, 0.0), (0.65, 0.7333, 0.7333), + (0.70, 0.9333, 0.9333), (0.75, 1.0, 1.0), + (0.80, 1.0, 1.0), (0.85, 1.0, 1.0), + (0.90, 0.8667, 0.8667), (0.95, 0.80, 0.80), + (1.0, 0.80, 0.80), + ], + 'green': [ + (0.0, 0.0, 0.0), (0.05, 0.0, 0.0), + (0.10, 0.0, 0.0), (0.15, 0.0, 0.0), + (0.20, 0.0, 0.0), (0.25, 0.4667, 0.4667), + (0.30, 0.6000, 0.6000), (0.35, 0.6667, 0.6667), + (0.40, 0.6667, 0.6667), (0.45, 0.6000, 0.6000), + (0.50, 0.7333, 0.7333), (0.55, 0.8667, 0.8667), + (0.60, 1.0, 1.0), (0.65, 1.0, 1.0), + (0.70, 0.9333, 0.9333), (0.75, 0.8000, 0.8000), + (0.80, 0.6000, 0.6000), (0.85, 0.0, 0.0), + (0.90, 0.0, 0.0), (0.95, 0.0, 0.0), + (1.0, 0.80, 0.80), + ], + 'blue': [ + (0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333), + (0.10, 0.6000, 0.6000), (0.15, 0.6667, 0.6667), + (0.20, 0.8667, 0.8667), (0.25, 0.8667, 0.8667), + (0.30, 0.8667, 0.8667), (0.35, 0.6667, 0.6667), + (0.40, 0.5333, 0.5333), (0.45, 0.0, 0.0), + (0.5, 0.0, 0.0), (0.55, 0.0, 0.0), + (0.60, 0.0, 0.0), (0.65, 0.0, 0.0), + (0.70, 0.0, 0.0), (0.75, 0.0, 0.0), + (0.80, 0.0, 0.0), (0.85, 0.0, 0.0), + (0.90, 0.0, 0.0), (0.95, 0.0, 0.0), + (1.0, 0.80, 0.80), + ], +} + + +# 34 colormaps based on color specifications and designs +# developed by Cynthia Brewer (https://colorbrewer2.org/). +# The ColorBrewer palettes have been included under the terms +# of an Apache-stype license (for details, see the file +# LICENSE_COLORBREWER in the license directory of the matplotlib +# source distribution). + +# RGB values taken from Brewer's Excel sheet, divided by 255 + +_Blues_data = ( + (0.96862745098039216, 0.98431372549019602, 1.0 ), + (0.87058823529411766, 0.92156862745098034, 0.96862745098039216), + (0.77647058823529413, 0.85882352941176465, 0.93725490196078431), + (0.61960784313725492, 0.792156862745098 , 0.88235294117647056), + (0.41960784313725491, 0.68235294117647061, 0.83921568627450982), + (0.25882352941176473, 0.5725490196078431 , 0.77647058823529413), + (0.12941176470588237, 0.44313725490196076, 0.70980392156862748), + (0.03137254901960784, 0.31764705882352939, 0.61176470588235299), + (0.03137254901960784, 0.18823529411764706, 0.41960784313725491) + ) + +_BrBG_data = ( + (0.32941176470588235, 0.18823529411764706, 0.0196078431372549 ), + (0.5490196078431373 , 0.31764705882352939, 0.0392156862745098 ), + (0.74901960784313726, 0.50588235294117645, 0.17647058823529413), + (0.87450980392156863, 0.76078431372549016, 0.49019607843137253), + (0.96470588235294119, 0.90980392156862744, 0.76470588235294112), + (0.96078431372549022, 0.96078431372549022, 0.96078431372549022), + (0.7803921568627451 , 0.91764705882352937, 0.89803921568627454), + (0.50196078431372548, 0.80392156862745101, 0.75686274509803919), + (0.20784313725490197, 0.59215686274509804, 0.5607843137254902 ), + (0.00392156862745098, 0.4 , 0.36862745098039218), + (0.0 , 0.23529411764705882, 0.18823529411764706) + ) + +_BuGn_data = ( + (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807), + (0.89803921568627454, 0.96078431372549022, 0.97647058823529409), + (0.8 , 0.92549019607843142, 0.90196078431372551), + (0.6 , 0.84705882352941175, 0.78823529411764703), + (0.4 , 0.76078431372549016, 0.64313725490196083), + (0.25490196078431371, 0.68235294117647061, 0.46274509803921571), + (0.13725490196078433, 0.54509803921568623, 0.27058823529411763), + (0.0 , 0.42745098039215684, 0.17254901960784313), + (0.0 , 0.26666666666666666, 0.10588235294117647) + ) + +_BuPu_data = ( + (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807), + (0.8784313725490196 , 0.92549019607843142, 0.95686274509803926), + (0.74901960784313726, 0.82745098039215681, 0.90196078431372551), + (0.61960784313725492, 0.73725490196078436, 0.85490196078431369), + (0.5490196078431373 , 0.58823529411764708, 0.77647058823529413), + (0.5490196078431373 , 0.41960784313725491, 0.69411764705882351), + (0.53333333333333333, 0.25490196078431371, 0.61568627450980395), + (0.50588235294117645, 0.05882352941176471, 0.48627450980392156), + (0.30196078431372547, 0.0 , 0.29411764705882354) + ) + +_GnBu_data = ( + (0.96862745098039216, 0.9882352941176471 , 0.94117647058823528), + (0.8784313725490196 , 0.95294117647058818, 0.85882352941176465), + (0.8 , 0.92156862745098034, 0.77254901960784317), + (0.6588235294117647 , 0.8666666666666667 , 0.70980392156862748), + (0.4823529411764706 , 0.8 , 0.7686274509803922 ), + (0.30588235294117649, 0.70196078431372544, 0.82745098039215681), + (0.16862745098039217, 0.5490196078431373 , 0.74509803921568629), + (0.03137254901960784, 0.40784313725490196, 0.67450980392156867), + (0.03137254901960784, 0.25098039215686274, 0.50588235294117645) + ) + +_Greens_data = ( + (0.96862745098039216, 0.9882352941176471 , 0.96078431372549022), + (0.89803921568627454, 0.96078431372549022, 0.8784313725490196 ), + (0.7803921568627451 , 0.9137254901960784 , 0.75294117647058822), + (0.63137254901960782, 0.85098039215686272, 0.60784313725490191), + (0.45490196078431372, 0.7686274509803922 , 0.46274509803921571), + (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116), + (0.13725490196078433, 0.54509803921568623, 0.27058823529411763), + (0.0 , 0.42745098039215684, 0.17254901960784313), + (0.0 , 0.26666666666666666, 0.10588235294117647) + ) + +_Greys_data = ( + (1.0 , 1.0 , 1.0 ), + (0.94117647058823528, 0.94117647058823528, 0.94117647058823528), + (0.85098039215686272, 0.85098039215686272, 0.85098039215686272), + (0.74117647058823533, 0.74117647058823533, 0.74117647058823533), + (0.58823529411764708, 0.58823529411764708, 0.58823529411764708), + (0.45098039215686275, 0.45098039215686275, 0.45098039215686275), + (0.32156862745098042, 0.32156862745098042, 0.32156862745098042), + (0.14509803921568629, 0.14509803921568629, 0.14509803921568629), + (0.0 , 0.0 , 0.0 ) + ) + +_Oranges_data = ( + (1.0 , 0.96078431372549022, 0.92156862745098034), + (0.99607843137254903, 0.90196078431372551, 0.80784313725490198), + (0.99215686274509807, 0.81568627450980391, 0.63529411764705879), + (0.99215686274509807, 0.68235294117647061, 0.41960784313725491), + (0.99215686274509807, 0.55294117647058827, 0.23529411764705882), + (0.94509803921568625, 0.41176470588235292, 0.07450980392156863), + (0.85098039215686272, 0.28235294117647058, 0.00392156862745098), + (0.65098039215686276, 0.21176470588235294, 0.01176470588235294), + (0.49803921568627452, 0.15294117647058825, 0.01568627450980392) + ) + +_OrRd_data = ( + (1.0 , 0.96862745098039216, 0.92549019607843142), + (0.99607843137254903, 0.90980392156862744, 0.78431372549019607), + (0.99215686274509807, 0.83137254901960789, 0.61960784313725492), + (0.99215686274509807, 0.73333333333333328, 0.51764705882352946), + (0.9882352941176471 , 0.55294117647058827, 0.34901960784313724), + (0.93725490196078431, 0.396078431372549 , 0.28235294117647058), + (0.84313725490196079, 0.18823529411764706, 0.12156862745098039), + (0.70196078431372544, 0.0 , 0.0 ), + (0.49803921568627452, 0.0 , 0.0 ) + ) + +_PiYG_data = ( + (0.55686274509803924, 0.00392156862745098, 0.32156862745098042), + (0.77254901960784317, 0.10588235294117647, 0.49019607843137253), + (0.87058823529411766, 0.46666666666666667, 0.68235294117647061), + (0.94509803921568625, 0.71372549019607845, 0.85490196078431369), + (0.99215686274509807, 0.8784313725490196 , 0.93725490196078431), + (0.96862745098039216, 0.96862745098039216, 0.96862745098039216), + (0.90196078431372551, 0.96078431372549022, 0.81568627450980391), + (0.72156862745098038, 0.88235294117647056, 0.52549019607843139), + (0.49803921568627452, 0.73725490196078436, 0.25490196078431371), + (0.30196078431372547, 0.5725490196078431 , 0.12941176470588237), + (0.15294117647058825, 0.39215686274509803, 0.09803921568627451) + ) + +_PRGn_data = ( + (0.25098039215686274, 0.0 , 0.29411764705882354), + (0.46274509803921571, 0.16470588235294117, 0.51372549019607838), + (0.6 , 0.4392156862745098 , 0.6705882352941176 ), + (0.76078431372549016, 0.6470588235294118 , 0.81176470588235294), + (0.90588235294117647, 0.83137254901960789, 0.90980392156862744), + (0.96862745098039216, 0.96862745098039216, 0.96862745098039216), + (0.85098039215686272, 0.94117647058823528, 0.82745098039215681), + (0.65098039215686276, 0.85882352941176465, 0.62745098039215685), + (0.35294117647058826, 0.68235294117647061, 0.38039215686274508), + (0.10588235294117647, 0.47058823529411764, 0.21568627450980393), + (0.0 , 0.26666666666666666, 0.10588235294117647) + ) + +_PuBu_data = ( + (1.0 , 0.96862745098039216, 0.98431372549019602), + (0.92549019607843142, 0.90588235294117647, 0.94901960784313721), + (0.81568627450980391, 0.81960784313725488, 0.90196078431372551), + (0.65098039215686276, 0.74117647058823533, 0.85882352941176465), + (0.45490196078431372, 0.66274509803921566, 0.81176470588235294), + (0.21176470588235294, 0.56470588235294117, 0.75294117647058822), + (0.0196078431372549 , 0.4392156862745098 , 0.69019607843137254), + (0.01568627450980392, 0.35294117647058826, 0.55294117647058827), + (0.00784313725490196, 0.2196078431372549 , 0.34509803921568627) + ) + +_PuBuGn_data = ( + (1.0 , 0.96862745098039216, 0.98431372549019602), + (0.92549019607843142, 0.88627450980392153, 0.94117647058823528), + (0.81568627450980391, 0.81960784313725488, 0.90196078431372551), + (0.65098039215686276, 0.74117647058823533, 0.85882352941176465), + (0.40392156862745099, 0.66274509803921566, 0.81176470588235294), + (0.21176470588235294, 0.56470588235294117, 0.75294117647058822), + (0.00784313725490196, 0.50588235294117645, 0.54117647058823526), + (0.00392156862745098, 0.42352941176470588, 0.34901960784313724), + (0.00392156862745098, 0.27450980392156865, 0.21176470588235294) + ) + +_PuOr_data = ( + (0.49803921568627452, 0.23137254901960785, 0.03137254901960784), + (0.70196078431372544, 0.34509803921568627, 0.02352941176470588), + (0.8784313725490196 , 0.50980392156862742, 0.07843137254901961), + (0.99215686274509807, 0.72156862745098038, 0.38823529411764707), + (0.99607843137254903, 0.8784313725490196 , 0.71372549019607845), + (0.96862745098039216, 0.96862745098039216, 0.96862745098039216), + (0.84705882352941175, 0.85490196078431369, 0.92156862745098034), + (0.69803921568627447, 0.6705882352941176 , 0.82352941176470584), + (0.50196078431372548, 0.45098039215686275, 0.67450980392156867), + (0.32941176470588235, 0.15294117647058825, 0.53333333333333333), + (0.17647058823529413, 0.0 , 0.29411764705882354) + ) + +_PuRd_data = ( + (0.96862745098039216, 0.95686274509803926, 0.97647058823529409), + (0.90588235294117647, 0.88235294117647056, 0.93725490196078431), + (0.83137254901960789, 0.72549019607843135, 0.85490196078431369), + (0.78823529411764703, 0.58039215686274515, 0.7803921568627451 ), + (0.87450980392156863, 0.396078431372549 , 0.69019607843137254), + (0.90588235294117647, 0.16078431372549021, 0.54117647058823526), + (0.80784313725490198, 0.07058823529411765, 0.33725490196078434), + (0.59607843137254901, 0.0 , 0.2627450980392157 ), + (0.40392156862745099, 0.0 , 0.12156862745098039) + ) + +_Purples_data = ( + (0.9882352941176471 , 0.98431372549019602, 0.99215686274509807), + (0.93725490196078431, 0.92941176470588238, 0.96078431372549022), + (0.85490196078431369, 0.85490196078431369, 0.92156862745098034), + (0.73725490196078436, 0.74117647058823533, 0.86274509803921573), + (0.61960784313725492, 0.60392156862745094, 0.78431372549019607), + (0.50196078431372548, 0.49019607843137253, 0.72941176470588232), + (0.41568627450980394, 0.31764705882352939, 0.63921568627450975), + (0.32941176470588235, 0.15294117647058825, 0.5607843137254902 ), + (0.24705882352941178, 0.0 , 0.49019607843137253) + ) + +_RdBu_data = ( + (0.40392156862745099, 0.0 , 0.12156862745098039), + (0.69803921568627447, 0.09411764705882353, 0.16862745098039217), + (0.83921568627450982, 0.37647058823529411, 0.30196078431372547), + (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742), + (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ), + (0.96862745098039216, 0.96862745098039216, 0.96862745098039216), + (0.81960784313725488, 0.89803921568627454, 0.94117647058823528), + (0.5725490196078431 , 0.77254901960784317, 0.87058823529411766), + (0.2627450980392157 , 0.57647058823529407, 0.76470588235294112), + (0.12941176470588237, 0.4 , 0.67450980392156867), + (0.0196078431372549 , 0.18823529411764706, 0.38039215686274508) + ) + +_RdGy_data = ( + (0.40392156862745099, 0.0 , 0.12156862745098039), + (0.69803921568627447, 0.09411764705882353, 0.16862745098039217), + (0.83921568627450982, 0.37647058823529411, 0.30196078431372547), + (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742), + (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ), + (1.0 , 1.0 , 1.0 ), + (0.8784313725490196 , 0.8784313725490196 , 0.8784313725490196 ), + (0.72941176470588232, 0.72941176470588232, 0.72941176470588232), + (0.52941176470588236, 0.52941176470588236, 0.52941176470588236), + (0.30196078431372547, 0.30196078431372547, 0.30196078431372547), + (0.10196078431372549, 0.10196078431372549, 0.10196078431372549) + ) + +_RdPu_data = ( + (1.0 , 0.96862745098039216, 0.95294117647058818), + (0.99215686274509807, 0.8784313725490196 , 0.86666666666666667), + (0.9882352941176471 , 0.77254901960784317, 0.75294117647058822), + (0.98039215686274506, 0.62352941176470589, 0.70980392156862748), + (0.96862745098039216, 0.40784313725490196, 0.63137254901960782), + (0.86666666666666667, 0.20392156862745098, 0.59215686274509804), + (0.68235294117647061, 0.00392156862745098, 0.49411764705882355), + (0.47843137254901963, 0.00392156862745098, 0.46666666666666667), + (0.28627450980392155, 0.0 , 0.41568627450980394) + ) + +_RdYlBu_data = ( + (0.6470588235294118 , 0.0 , 0.14901960784313725), + (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825), + (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ), + (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508), + (0.99607843137254903, 0.8784313725490196 , 0.56470588235294117), + (1.0 , 1.0 , 0.74901960784313726), + (0.8784313725490196 , 0.95294117647058818 , 0.97254901960784312), + (0.6705882352941176 , 0.85098039215686272 , 0.9137254901960784 ), + (0.45490196078431372, 0.67843137254901964 , 0.81960784313725488), + (0.27058823529411763, 0.45882352941176469 , 0.70588235294117652), + (0.19215686274509805, 0.21176470588235294 , 0.58431372549019611) + ) + +_RdYlGn_data = ( + (0.6470588235294118 , 0.0 , 0.14901960784313725), + (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825), + (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ), + (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508), + (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623), + (1.0 , 1.0 , 0.74901960784313726), + (0.85098039215686272, 0.93725490196078431 , 0.54509803921568623), + (0.65098039215686276, 0.85098039215686272 , 0.41568627450980394), + (0.4 , 0.74117647058823533 , 0.38823529411764707), + (0.10196078431372549, 0.59607843137254901 , 0.31372549019607843), + (0.0 , 0.40784313725490196 , 0.21568627450980393) + ) + +_Reds_data = ( + (1.0 , 0.96078431372549022 , 0.94117647058823528), + (0.99607843137254903, 0.8784313725490196 , 0.82352941176470584), + (0.9882352941176471 , 0.73333333333333328 , 0.63137254901960782), + (0.9882352941176471 , 0.5725490196078431 , 0.44705882352941179), + (0.98431372549019602, 0.41568627450980394 , 0.29019607843137257), + (0.93725490196078431, 0.23137254901960785 , 0.17254901960784313), + (0.79607843137254897, 0.094117647058823528, 0.11372549019607843), + (0.6470588235294118 , 0.058823529411764705, 0.08235294117647058), + (0.40392156862745099, 0.0 , 0.05098039215686274) + ) + +_Spectral_data = ( + (0.61960784313725492, 0.003921568627450980, 0.25882352941176473), + (0.83529411764705885, 0.24313725490196078 , 0.30980392156862746), + (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ), + (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508), + (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623), + (1.0 , 1.0 , 0.74901960784313726), + (0.90196078431372551, 0.96078431372549022 , 0.59607843137254901), + (0.6705882352941176 , 0.8666666666666667 , 0.64313725490196083), + (0.4 , 0.76078431372549016 , 0.6470588235294118 ), + (0.19607843137254902, 0.53333333333333333 , 0.74117647058823533), + (0.36862745098039218, 0.30980392156862746 , 0.63529411764705879) + ) + +_YlGn_data = ( + (1.0 , 1.0 , 0.89803921568627454), + (0.96862745098039216, 0.9882352941176471 , 0.72549019607843135), + (0.85098039215686272, 0.94117647058823528 , 0.63921568627450975), + (0.67843137254901964, 0.8666666666666667 , 0.55686274509803924), + (0.47058823529411764, 0.77647058823529413 , 0.47450980392156861), + (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116), + (0.13725490196078433, 0.51764705882352946 , 0.2627450980392157 ), + (0.0 , 0.40784313725490196 , 0.21568627450980393), + (0.0 , 0.27058823529411763 , 0.16078431372549021) + ) + +_YlGnBu_data = ( + (1.0 , 1.0 , 0.85098039215686272), + (0.92941176470588238, 0.97254901960784312 , 0.69411764705882351), + (0.7803921568627451 , 0.9137254901960784 , 0.70588235294117652), + (0.49803921568627452, 0.80392156862745101 , 0.73333333333333328), + (0.25490196078431371, 0.71372549019607845 , 0.7686274509803922 ), + (0.11372549019607843, 0.56862745098039214 , 0.75294117647058822), + (0.13333333333333333, 0.36862745098039218 , 0.6588235294117647 ), + (0.14509803921568629, 0.20392156862745098 , 0.58039215686274515), + (0.03137254901960784, 0.11372549019607843 , 0.34509803921568627) + ) + +_YlOrBr_data = ( + (1.0 , 1.0 , 0.89803921568627454), + (1.0 , 0.96862745098039216 , 0.73725490196078436), + (0.99607843137254903, 0.8901960784313725 , 0.56862745098039214), + (0.99607843137254903, 0.7686274509803922 , 0.30980392156862746), + (0.99607843137254903, 0.6 , 0.16078431372549021), + (0.92549019607843142, 0.4392156862745098 , 0.07843137254901961), + (0.8 , 0.29803921568627451 , 0.00784313725490196), + (0.6 , 0.20392156862745098 , 0.01568627450980392), + (0.4 , 0.14509803921568629 , 0.02352941176470588) + ) + +_YlOrRd_data = ( + (1.0 , 1.0 , 0.8 ), + (1.0 , 0.92941176470588238 , 0.62745098039215685), + (0.99607843137254903, 0.85098039215686272 , 0.46274509803921571), + (0.99607843137254903, 0.69803921568627447 , 0.29803921568627451), + (0.99215686274509807, 0.55294117647058827 , 0.23529411764705882), + (0.9882352941176471 , 0.30588235294117649 , 0.16470588235294117), + (0.8901960784313725 , 0.10196078431372549 , 0.10980392156862745), + (0.74117647058823533, 0.0 , 0.14901960784313725), + (0.50196078431372548, 0.0 , 0.14901960784313725) + ) + + +# ColorBrewer's qualitative maps, implemented using ListedColormap +# for use with mpl.colors.NoNorm + +_Accent_data = ( + (0.49803921568627452, 0.78823529411764703, 0.49803921568627452), + (0.74509803921568629, 0.68235294117647061, 0.83137254901960789), + (0.99215686274509807, 0.75294117647058822, 0.52549019607843139), + (1.0, 1.0, 0.6 ), + (0.2196078431372549, 0.42352941176470588, 0.69019607843137254), + (0.94117647058823528, 0.00784313725490196, 0.49803921568627452), + (0.74901960784313726, 0.35686274509803922, 0.09019607843137254), + (0.4, 0.4, 0.4 ), + ) + +_Dark2_data = ( + (0.10588235294117647, 0.61960784313725492, 0.46666666666666667), + (0.85098039215686272, 0.37254901960784315, 0.00784313725490196), + (0.45882352941176469, 0.4392156862745098, 0.70196078431372544), + (0.90588235294117647, 0.16078431372549021, 0.54117647058823526), + (0.4, 0.65098039215686276, 0.11764705882352941), + (0.90196078431372551, 0.6705882352941176, 0.00784313725490196), + (0.65098039215686276, 0.46274509803921571, 0.11372549019607843), + (0.4, 0.4, 0.4 ), + ) + +_Paired_data = ( + (0.65098039215686276, 0.80784313725490198, 0.8901960784313725 ), + (0.12156862745098039, 0.47058823529411764, 0.70588235294117652), + (0.69803921568627447, 0.87450980392156863, 0.54117647058823526), + (0.2, 0.62745098039215685, 0.17254901960784313), + (0.98431372549019602, 0.60392156862745094, 0.6 ), + (0.8901960784313725, 0.10196078431372549, 0.10980392156862745), + (0.99215686274509807, 0.74901960784313726, 0.43529411764705883), + (1.0, 0.49803921568627452, 0.0 ), + (0.792156862745098, 0.69803921568627447, 0.83921568627450982), + (0.41568627450980394, 0.23921568627450981, 0.60392156862745094), + (1.0, 1.0, 0.6 ), + (0.69411764705882351, 0.34901960784313724, 0.15686274509803921), + ) + +_Pastel1_data = ( + (0.98431372549019602, 0.70588235294117652, 0.68235294117647061), + (0.70196078431372544, 0.80392156862745101, 0.8901960784313725 ), + (0.8, 0.92156862745098034, 0.77254901960784317), + (0.87058823529411766, 0.79607843137254897, 0.89411764705882357), + (0.99607843137254903, 0.85098039215686272, 0.65098039215686276), + (1.0, 1.0, 0.8 ), + (0.89803921568627454, 0.84705882352941175, 0.74117647058823533), + (0.99215686274509807, 0.85490196078431369, 0.92549019607843142), + (0.94901960784313721, 0.94901960784313721, 0.94901960784313721), + ) + +_Pastel2_data = ( + (0.70196078431372544, 0.88627450980392153, 0.80392156862745101), + (0.99215686274509807, 0.80392156862745101, 0.67450980392156867), + (0.79607843137254897, 0.83529411764705885, 0.90980392156862744), + (0.95686274509803926, 0.792156862745098, 0.89411764705882357), + (0.90196078431372551, 0.96078431372549022, 0.78823529411764703), + (1.0, 0.94901960784313721, 0.68235294117647061), + (0.94509803921568625, 0.88627450980392153, 0.8 ), + (0.8, 0.8, 0.8 ), + ) + +_Set1_data = ( + (0.89411764705882357, 0.10196078431372549, 0.10980392156862745), + (0.21568627450980393, 0.49411764705882355, 0.72156862745098038), + (0.30196078431372547, 0.68627450980392157, 0.29019607843137257), + (0.59607843137254901, 0.30588235294117649, 0.63921568627450975), + (1.0, 0.49803921568627452, 0.0 ), + (1.0, 1.0, 0.2 ), + (0.65098039215686276, 0.33725490196078434, 0.15686274509803921), + (0.96862745098039216, 0.50588235294117645, 0.74901960784313726), + (0.6, 0.6, 0.6), + ) + +_Set2_data = ( + (0.4, 0.76078431372549016, 0.6470588235294118 ), + (0.9882352941176471, 0.55294117647058827, 0.3843137254901961 ), + (0.55294117647058827, 0.62745098039215685, 0.79607843137254897), + (0.90588235294117647, 0.54117647058823526, 0.76470588235294112), + (0.65098039215686276, 0.84705882352941175, 0.32941176470588235), + (1.0, 0.85098039215686272, 0.18431372549019609), + (0.89803921568627454, 0.7686274509803922, 0.58039215686274515), + (0.70196078431372544, 0.70196078431372544, 0.70196078431372544), + ) + +_Set3_data = ( + (0.55294117647058827, 0.82745098039215681, 0.7803921568627451 ), + (1.0, 1.0, 0.70196078431372544), + (0.74509803921568629, 0.72941176470588232, 0.85490196078431369), + (0.98431372549019602, 0.50196078431372548, 0.44705882352941179), + (0.50196078431372548, 0.69411764705882351, 0.82745098039215681), + (0.99215686274509807, 0.70588235294117652, 0.3843137254901961 ), + (0.70196078431372544, 0.87058823529411766, 0.41176470588235292), + (0.9882352941176471, 0.80392156862745101, 0.89803921568627454), + (0.85098039215686272, 0.85098039215686272, 0.85098039215686272), + (0.73725490196078436, 0.50196078431372548, 0.74117647058823533), + (0.8, 0.92156862745098034, 0.77254901960784317), + (1.0, 0.92941176470588238, 0.43529411764705883), + ) + + +# The next 7 palettes are from the Yorick scientific visualization package, +# an evolution of the GIST package, both by David H. Munro. +# They are released under a BSD-like license (see LICENSE_YORICK in +# the license directory of the matplotlib source distribution). +# +# Most palette functions have been reduced to simple function descriptions +# by Reinier Heeres, since the rgb components were mostly straight lines. +# gist_earth_data and gist_ncar_data were simplified by a script and some +# manual effort. + +_gist_earth_data = { + 'red': ( + (0.0, 0.0, 0.0000), + (0.2824, 0.1882, 0.1882), + (0.4588, 0.2714, 0.2714), + (0.5490, 0.4719, 0.4719), + (0.6980, 0.7176, 0.7176), + (0.7882, 0.7553, 0.7553), + (1.0000, 0.9922, 0.9922), + ), + 'green': ( + (0.0, 0.0, 0.0000), + (0.0275, 0.0000, 0.0000), + (0.1098, 0.1893, 0.1893), + (0.1647, 0.3035, 0.3035), + (0.2078, 0.3841, 0.3841), + (0.2824, 0.5020, 0.5020), + (0.5216, 0.6397, 0.6397), + (0.6980, 0.7171, 0.7171), + (0.7882, 0.6392, 0.6392), + (0.7922, 0.6413, 0.6413), + (0.8000, 0.6447, 0.6447), + (0.8078, 0.6481, 0.6481), + (0.8157, 0.6549, 0.6549), + (0.8667, 0.6991, 0.6991), + (0.8745, 0.7103, 0.7103), + (0.8824, 0.7216, 0.7216), + (0.8902, 0.7323, 0.7323), + (0.8980, 0.7430, 0.7430), + (0.9412, 0.8275, 0.8275), + (0.9569, 0.8635, 0.8635), + (0.9647, 0.8816, 0.8816), + (0.9961, 0.9733, 0.9733), + (1.0000, 0.9843, 0.9843), + ), + 'blue': ( + (0.0, 0.0, 0.0000), + (0.0039, 0.1684, 0.1684), + (0.0078, 0.2212, 0.2212), + (0.0275, 0.4329, 0.4329), + (0.0314, 0.4549, 0.4549), + (0.2824, 0.5004, 0.5004), + (0.4667, 0.2748, 0.2748), + (0.5451, 0.3205, 0.3205), + (0.7843, 0.3961, 0.3961), + (0.8941, 0.6651, 0.6651), + (1.0000, 0.9843, 0.9843), + ) +} + +_gist_gray_data = { + 'red': gfunc[3], + 'green': gfunc[3], + 'blue': gfunc[3], +} + +def _gist_heat_red(x): return 1.5 * x +def _gist_heat_green(x): return 2 * x - 1 +def _gist_heat_blue(x): return 4 * x - 3 +_gist_heat_data = { + 'red': _gist_heat_red, 'green': _gist_heat_green, 'blue': _gist_heat_blue} + +_gist_ncar_data = { + 'red': ( + (0.0, 0.0, 0.0000), + (0.3098, 0.0000, 0.0000), + (0.3725, 0.3993, 0.3993), + (0.4235, 0.5003, 0.5003), + (0.5333, 1.0000, 1.0000), + (0.7922, 1.0000, 1.0000), + (0.8471, 0.6218, 0.6218), + (0.8980, 0.9235, 0.9235), + (1.0000, 0.9961, 0.9961), + ), + 'green': ( + (0.0, 0.0, 0.0000), + (0.0510, 0.3722, 0.3722), + (0.1059, 0.0000, 0.0000), + (0.1569, 0.7202, 0.7202), + (0.1608, 0.7537, 0.7537), + (0.1647, 0.7752, 0.7752), + (0.2157, 1.0000, 1.0000), + (0.2588, 0.9804, 0.9804), + (0.2706, 0.9804, 0.9804), + (0.3176, 1.0000, 1.0000), + (0.3686, 0.8081, 0.8081), + (0.4275, 1.0000, 1.0000), + (0.5216, 1.0000, 1.0000), + (0.6314, 0.7292, 0.7292), + (0.6863, 0.2796, 0.2796), + (0.7451, 0.0000, 0.0000), + (0.7922, 0.0000, 0.0000), + (0.8431, 0.1753, 0.1753), + (0.8980, 0.5000, 0.5000), + (1.0000, 0.9725, 0.9725), + ), + 'blue': ( + (0.0, 0.5020, 0.5020), + (0.0510, 0.0222, 0.0222), + (0.1098, 1.0000, 1.0000), + (0.2039, 1.0000, 1.0000), + (0.2627, 0.6145, 0.6145), + (0.3216, 0.0000, 0.0000), + (0.4157, 0.0000, 0.0000), + (0.4745, 0.2342, 0.2342), + (0.5333, 0.0000, 0.0000), + (0.5804, 0.0000, 0.0000), + (0.6314, 0.0549, 0.0549), + (0.6902, 0.0000, 0.0000), + (0.7373, 0.0000, 0.0000), + (0.7922, 0.9738, 0.9738), + (0.8000, 1.0000, 1.0000), + (0.8431, 1.0000, 1.0000), + (0.8980, 0.9341, 0.9341), + (1.0000, 0.9961, 0.9961), + ) +} + +_gist_rainbow_data = ( + (0.000, (1.00, 0.00, 0.16)), + (0.030, (1.00, 0.00, 0.00)), + (0.215, (1.00, 1.00, 0.00)), + (0.400, (0.00, 1.00, 0.00)), + (0.586, (0.00, 1.00, 1.00)), + (0.770, (0.00, 0.00, 1.00)), + (0.954, (1.00, 0.00, 1.00)), + (1.000, (1.00, 0.00, 0.75)) +) + +_gist_stern_data = { + 'red': ( + (0.000, 0.000, 0.000), (0.0547, 1.000, 1.000), + (0.250, 0.027, 0.250), # (0.2500, 0.250, 0.250), + (1.000, 1.000, 1.000)), + 'green': ((0, 0, 0), (1, 1, 1)), + 'blue': ( + (0.000, 0.000, 0.000), (0.500, 1.000, 1.000), + (0.735, 0.000, 0.000), (1.000, 1.000, 1.000)) +} + +def _gist_yarg(x): return 1 - x +_gist_yarg_data = {'red': _gist_yarg, 'green': _gist_yarg, 'blue': _gist_yarg} + +# This bipolar colormap was generated from CoolWarmFloat33.csv of +# "Diverging Color Maps for Scientific Visualization" by Kenneth Moreland. +# +_coolwarm_data = { + 'red': [ + (0.0, 0.2298057, 0.2298057), + (0.03125, 0.26623388, 0.26623388), + (0.0625, 0.30386891, 0.30386891), + (0.09375, 0.342804478, 0.342804478), + (0.125, 0.38301334, 0.38301334), + (0.15625, 0.424369608, 0.424369608), + (0.1875, 0.46666708, 0.46666708), + (0.21875, 0.509635204, 0.509635204), + (0.25, 0.552953156, 0.552953156), + (0.28125, 0.596262162, 0.596262162), + (0.3125, 0.639176211, 0.639176211), + (0.34375, 0.681291281, 0.681291281), + (0.375, 0.722193294, 0.722193294), + (0.40625, 0.761464949, 0.761464949), + (0.4375, 0.798691636, 0.798691636), + (0.46875, 0.833466556, 0.833466556), + (0.5, 0.865395197, 0.865395197), + (0.53125, 0.897787179, 0.897787179), + (0.5625, 0.924127593, 0.924127593), + (0.59375, 0.944468518, 0.944468518), + (0.625, 0.958852946, 0.958852946), + (0.65625, 0.96732803, 0.96732803), + (0.6875, 0.969954137, 0.969954137), + (0.71875, 0.966811177, 0.966811177), + (0.75, 0.958003065, 0.958003065), + (0.78125, 0.943660866, 0.943660866), + (0.8125, 0.923944917, 0.923944917), + (0.84375, 0.89904617, 0.89904617), + (0.875, 0.869186849, 0.869186849), + (0.90625, 0.834620542, 0.834620542), + (0.9375, 0.795631745, 0.795631745), + (0.96875, 0.752534934, 0.752534934), + (1.0, 0.705673158, 0.705673158)], + 'green': [ + (0.0, 0.298717966, 0.298717966), + (0.03125, 0.353094838, 0.353094838), + (0.0625, 0.406535296, 0.406535296), + (0.09375, 0.458757618, 0.458757618), + (0.125, 0.50941904, 0.50941904), + (0.15625, 0.558148092, 0.558148092), + (0.1875, 0.604562568, 0.604562568), + (0.21875, 0.648280772, 0.648280772), + (0.25, 0.688929332, 0.688929332), + (0.28125, 0.726149107, 0.726149107), + (0.3125, 0.759599947, 0.759599947), + (0.34375, 0.788964712, 0.788964712), + (0.375, 0.813952739, 0.813952739), + (0.40625, 0.834302879, 0.834302879), + (0.4375, 0.849786142, 0.849786142), + (0.46875, 0.860207984, 0.860207984), + (0.5, 0.86541021, 0.86541021), + (0.53125, 0.848937047, 0.848937047), + (0.5625, 0.827384882, 0.827384882), + (0.59375, 0.800927443, 0.800927443), + (0.625, 0.769767752, 0.769767752), + (0.65625, 0.734132809, 0.734132809), + (0.6875, 0.694266682, 0.694266682), + (0.71875, 0.650421156, 0.650421156), + (0.75, 0.602842431, 0.602842431), + (0.78125, 0.551750968, 0.551750968), + (0.8125, 0.49730856, 0.49730856), + (0.84375, 0.439559467, 0.439559467), + (0.875, 0.378313092, 0.378313092), + (0.90625, 0.312874446, 0.312874446), + (0.9375, 0.24128379, 0.24128379), + (0.96875, 0.157246067, 0.157246067), + (1.0, 0.01555616, 0.01555616)], + 'blue': [ + (0.0, 0.753683153, 0.753683153), + (0.03125, 0.801466763, 0.801466763), + (0.0625, 0.84495867, 0.84495867), + (0.09375, 0.883725899, 0.883725899), + (0.125, 0.917387822, 0.917387822), + (0.15625, 0.945619588, 0.945619588), + (0.1875, 0.968154911, 0.968154911), + (0.21875, 0.98478814, 0.98478814), + (0.25, 0.995375608, 0.995375608), + (0.28125, 0.999836203, 0.999836203), + (0.3125, 0.998151185, 0.998151185), + (0.34375, 0.990363227, 0.990363227), + (0.375, 0.976574709, 0.976574709), + (0.40625, 0.956945269, 0.956945269), + (0.4375, 0.931688648, 0.931688648), + (0.46875, 0.901068838, 0.901068838), + (0.5, 0.865395561, 0.865395561), + (0.53125, 0.820880546, 0.820880546), + (0.5625, 0.774508472, 0.774508472), + (0.59375, 0.726736146, 0.726736146), + (0.625, 0.678007945, 0.678007945), + (0.65625, 0.628751763, 0.628751763), + (0.6875, 0.579375448, 0.579375448), + (0.71875, 0.530263762, 0.530263762), + (0.75, 0.481775914, 0.481775914), + (0.78125, 0.434243684, 0.434243684), + (0.8125, 0.387970225, 0.387970225), + (0.84375, 0.343229596, 0.343229596), + (0.875, 0.300267182, 0.300267182), + (0.90625, 0.259301199, 0.259301199), + (0.9375, 0.220525627, 0.220525627), + (0.96875, 0.184115123, 0.184115123), + (1.0, 0.150232812, 0.150232812)] + } + +# Implementation of Carey Rappaport's CMRmap. +# See `A Color Map for Effective Black-and-White Rendering of Color-Scale +# Images' by Carey Rappaport +# https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m +_CMRmap_data = {'red': ((0.000, 0.00, 0.00), + (0.125, 0.15, 0.15), + (0.250, 0.30, 0.30), + (0.375, 0.60, 0.60), + (0.500, 1.00, 1.00), + (0.625, 0.90, 0.90), + (0.750, 0.90, 0.90), + (0.875, 0.90, 0.90), + (1.000, 1.00, 1.00)), + 'green': ((0.000, 0.00, 0.00), + (0.125, 0.15, 0.15), + (0.250, 0.15, 0.15), + (0.375, 0.20, 0.20), + (0.500, 0.25, 0.25), + (0.625, 0.50, 0.50), + (0.750, 0.75, 0.75), + (0.875, 0.90, 0.90), + (1.000, 1.00, 1.00)), + 'blue': ((0.000, 0.00, 0.00), + (0.125, 0.50, 0.50), + (0.250, 0.75, 0.75), + (0.375, 0.50, 0.50), + (0.500, 0.15, 0.15), + (0.625, 0.00, 0.00), + (0.750, 0.10, 0.10), + (0.875, 0.50, 0.50), + (1.000, 1.00, 1.00))} + + +# An MIT licensed, colorblind-friendly heatmap from Wistia: +# https://github.com/wistia/heatmap-palette +# https://wistia.com/learn/culture/heatmaps-for-colorblindness +# +# >>> import matplotlib.colors as c +# >>> colors = ["#e4ff7a", "#ffe81a", "#ffbd00", "#ffa000", "#fc7f00"] +# >>> cm = c.LinearSegmentedColormap.from_list('wistia', colors) +# >>> _wistia_data = cm._segmentdata +# >>> del _wistia_data['alpha'] +# +_wistia_data = { + 'red': [(0.0, 0.8941176470588236, 0.8941176470588236), + (0.25, 1.0, 1.0), + (0.5, 1.0, 1.0), + (0.75, 1.0, 1.0), + (1.0, 0.9882352941176471, 0.9882352941176471)], + 'green': [(0.0, 1.0, 1.0), + (0.25, 0.9098039215686274, 0.9098039215686274), + (0.5, 0.7411764705882353, 0.7411764705882353), + (0.75, 0.6274509803921569, 0.6274509803921569), + (1.0, 0.4980392156862745, 0.4980392156862745)], + 'blue': [(0.0, 0.47843137254901963, 0.47843137254901963), + (0.25, 0.10196078431372549, 0.10196078431372549), + (0.5, 0.0, 0.0), + (0.75, 0.0, 0.0), + (1.0, 0.0, 0.0)], +} + + +# Categorical palettes from Vega: +# https://github.com/vega/vega/wiki/Scales +# (divided by 255) +# + +_tab10_data = ( + (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4 + (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e + (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c + (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728 + (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd + (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b + (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2 + (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f + (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22 + (0.09019607843137255, 0.7450980392156863, 0.8117647058823529), # 17becf +) + +_tab20_data = ( + (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4 + (0.6823529411764706, 0.7803921568627451, 0.9098039215686274 ), # aec7e8 + (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e + (1.0, 0.7333333333333333, 0.47058823529411764 ), # ffbb78 + (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c + (0.596078431372549, 0.8745098039215686, 0.5411764705882353 ), # 98df8a + (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728 + (1.0, 0.596078431372549, 0.5882352941176471 ), # ff9896 + (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd + (0.7725490196078432, 0.6901960784313725, 0.8352941176470589 ), # c5b0d5 + (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b + (0.7686274509803922, 0.611764705882353, 0.5803921568627451 ), # c49c94 + (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2 + (0.9686274509803922, 0.7137254901960784, 0.8235294117647058 ), # f7b6d2 + (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f + (0.7803921568627451, 0.7803921568627451, 0.7803921568627451 ), # c7c7c7 + (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22 + (0.8588235294117647, 0.8588235294117647, 0.5529411764705883 ), # dbdb8d + (0.09019607843137255, 0.7450980392156863, 0.8117647058823529 ), # 17becf + (0.6196078431372549, 0.8549019607843137, 0.8980392156862745), # 9edae5 +) + +_tab20b_data = ( + (0.2235294117647059, 0.23137254901960785, 0.4745098039215686 ), # 393b79 + (0.3215686274509804, 0.32941176470588235, 0.6392156862745098 ), # 5254a3 + (0.4196078431372549, 0.43137254901960786, 0.8117647058823529 ), # 6b6ecf + (0.611764705882353, 0.6196078431372549, 0.8705882352941177 ), # 9c9ede + (0.38823529411764707, 0.4745098039215686, 0.2235294117647059 ), # 637939 + (0.5490196078431373, 0.6352941176470588, 0.3215686274509804 ), # 8ca252 + (0.7098039215686275, 0.8117647058823529, 0.4196078431372549 ), # b5cf6b + (0.807843137254902, 0.8588235294117647, 0.611764705882353 ), # cedb9c + (0.5490196078431373, 0.42745098039215684, 0.19215686274509805), # 8c6d31 + (0.7411764705882353, 0.6196078431372549, 0.2235294117647059 ), # bd9e39 + (0.9058823529411765, 0.7294117647058823, 0.3215686274509804 ), # e7ba52 + (0.9058823529411765, 0.796078431372549, 0.5803921568627451 ), # e7cb94 + (0.5176470588235295, 0.23529411764705882, 0.2235294117647059 ), # 843c39 + (0.6784313725490196, 0.28627450980392155, 0.2901960784313726 ), # ad494a + (0.8392156862745098, 0.3803921568627451, 0.4196078431372549 ), # d6616b + (0.9058823529411765, 0.5882352941176471, 0.611764705882353 ), # e7969c + (0.4823529411764706, 0.2549019607843137, 0.45098039215686275), # 7b4173 + (0.6470588235294118, 0.3176470588235294, 0.5803921568627451 ), # a55194 + (0.807843137254902, 0.42745098039215684, 0.7411764705882353 ), # ce6dbd + (0.8705882352941177, 0.6196078431372549, 0.8392156862745098 ), # de9ed6 +) + +_tab20c_data = ( + (0.19215686274509805, 0.5098039215686274, 0.7411764705882353 ), # 3182bd + (0.4196078431372549, 0.6823529411764706, 0.8392156862745098 ), # 6baed6 + (0.6196078431372549, 0.792156862745098, 0.8823529411764706 ), # 9ecae1 + (0.7764705882352941, 0.8588235294117647, 0.9372549019607843 ), # c6dbef + (0.9019607843137255, 0.3333333333333333, 0.050980392156862744), # e6550d + (0.9921568627450981, 0.5529411764705883, 0.23529411764705882 ), # fd8d3c + (0.9921568627450981, 0.6823529411764706, 0.4196078431372549 ), # fdae6b + (0.9921568627450981, 0.8156862745098039, 0.6352941176470588 ), # fdd0a2 + (0.19215686274509805, 0.6392156862745098, 0.32941176470588235 ), # 31a354 + (0.4549019607843137, 0.7686274509803922, 0.4627450980392157 ), # 74c476 + (0.6313725490196078, 0.8509803921568627, 0.6078431372549019 ), # a1d99b + (0.7803921568627451, 0.9137254901960784, 0.7529411764705882 ), # c7e9c0 + (0.4588235294117647, 0.4196078431372549, 0.6941176470588235 ), # 756bb1 + (0.6196078431372549, 0.6039215686274509, 0.7843137254901961 ), # 9e9ac8 + (0.7372549019607844, 0.7411764705882353, 0.8627450980392157 ), # bcbddc + (0.8549019607843137, 0.8549019607843137, 0.9215686274509803 ), # dadaeb + (0.38823529411764707, 0.38823529411764707, 0.38823529411764707 ), # 636363 + (0.5882352941176471, 0.5882352941176471, 0.5882352941176471 ), # 969696 + (0.7411764705882353, 0.7411764705882353, 0.7411764705882353 ), # bdbdbd + (0.8509803921568627, 0.8509803921568627, 0.8509803921568627 ), # d9d9d9 +) + + +datad = { + 'Blues': _Blues_data, + 'BrBG': _BrBG_data, + 'BuGn': _BuGn_data, + 'BuPu': _BuPu_data, + 'CMRmap': _CMRmap_data, + 'GnBu': _GnBu_data, + 'Greens': _Greens_data, + 'Greys': _Greys_data, + 'OrRd': _OrRd_data, + 'Oranges': _Oranges_data, + 'PRGn': _PRGn_data, + 'PiYG': _PiYG_data, + 'PuBu': _PuBu_data, + 'PuBuGn': _PuBuGn_data, + 'PuOr': _PuOr_data, + 'PuRd': _PuRd_data, + 'Purples': _Purples_data, + 'RdBu': _RdBu_data, + 'RdGy': _RdGy_data, + 'RdPu': _RdPu_data, + 'RdYlBu': _RdYlBu_data, + 'RdYlGn': _RdYlGn_data, + 'Reds': _Reds_data, + 'Spectral': _Spectral_data, + 'Wistia': _wistia_data, + 'YlGn': _YlGn_data, + 'YlGnBu': _YlGnBu_data, + 'YlOrBr': _YlOrBr_data, + 'YlOrRd': _YlOrRd_data, + 'afmhot': _afmhot_data, + 'autumn': _autumn_data, + 'binary': _binary_data, + 'bone': _bone_data, + 'brg': _brg_data, + 'bwr': _bwr_data, + 'cool': _cool_data, + 'coolwarm': _coolwarm_data, + 'copper': _copper_data, + 'cubehelix': _cubehelix_data, + 'flag': _flag_data, + 'gist_earth': _gist_earth_data, + 'gist_gray': _gist_gray_data, + 'gist_heat': _gist_heat_data, + 'gist_ncar': _gist_ncar_data, + 'gist_rainbow': _gist_rainbow_data, + 'gist_stern': _gist_stern_data, + 'gist_yarg': _gist_yarg_data, + 'gnuplot': _gnuplot_data, + 'gnuplot2': _gnuplot2_data, + 'gray': _gray_data, + 'hot': _hot_data, + 'hsv': _hsv_data, + 'jet': _jet_data, + 'nipy_spectral': _nipy_spectral_data, + 'ocean': _ocean_data, + 'pink': _pink_data, + 'prism': _prism_data, + 'rainbow': _rainbow_data, + 'seismic': _seismic_data, + 'spring': _spring_data, + 'summer': _summer_data, + 'terrain': _terrain_data, + 'winter': _winter_data, + # Qualitative + 'Accent': {'listed': _Accent_data}, + 'Dark2': {'listed': _Dark2_data}, + 'Paired': {'listed': _Paired_data}, + 'Pastel1': {'listed': _Pastel1_data}, + 'Pastel2': {'listed': _Pastel2_data}, + 'Set1': {'listed': _Set1_data}, + 'Set2': {'listed': _Set2_data}, + 'Set3': {'listed': _Set3_data}, + 'tab10': {'listed': _tab10_data}, + 'tab20': {'listed': _tab20_data}, + 'tab20b': {'listed': _tab20b_data}, + 'tab20c': {'listed': _tab20c_data}, +} diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_cm_listed.py b/llava_next/lib/python3.10/site-packages/matplotlib/_cm_listed.py new file mode 100644 index 0000000000000000000000000000000000000000..a331ad74a5f03688005dc14d5867653b3d77e20c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_cm_listed.py @@ -0,0 +1,2071 @@ +from .colors import ListedColormap + +_magma_data = [[0.001462, 0.000466, 0.013866], + [0.002258, 0.001295, 0.018331], + [0.003279, 0.002305, 0.023708], + [0.004512, 0.003490, 0.029965], + [0.005950, 0.004843, 0.037130], + [0.007588, 0.006356, 0.044973], + [0.009426, 0.008022, 0.052844], + [0.011465, 0.009828, 0.060750], + [0.013708, 0.011771, 0.068667], + [0.016156, 0.013840, 0.076603], + [0.018815, 0.016026, 0.084584], + [0.021692, 0.018320, 0.092610], + [0.024792, 0.020715, 0.100676], + [0.028123, 0.023201, 0.108787], + [0.031696, 0.025765, 0.116965], + [0.035520, 0.028397, 0.125209], + [0.039608, 0.031090, 0.133515], + [0.043830, 0.033830, 0.141886], + [0.048062, 0.036607, 0.150327], + [0.052320, 0.039407, 0.158841], + [0.056615, 0.042160, 0.167446], + [0.060949, 0.044794, 0.176129], + [0.065330, 0.047318, 0.184892], + [0.069764, 0.049726, 0.193735], + [0.074257, 0.052017, 0.202660], + [0.078815, 0.054184, 0.211667], + [0.083446, 0.056225, 0.220755], + [0.088155, 0.058133, 0.229922], + [0.092949, 0.059904, 0.239164], + [0.097833, 0.061531, 0.248477], + [0.102815, 0.063010, 0.257854], + [0.107899, 0.064335, 0.267289], + [0.113094, 0.065492, 0.276784], + [0.118405, 0.066479, 0.286321], + [0.123833, 0.067295, 0.295879], + [0.129380, 0.067935, 0.305443], + [0.135053, 0.068391, 0.315000], + [0.140858, 0.068654, 0.324538], + [0.146785, 0.068738, 0.334011], + [0.152839, 0.068637, 0.343404], + [0.159018, 0.068354, 0.352688], + [0.165308, 0.067911, 0.361816], + [0.171713, 0.067305, 0.370771], + [0.178212, 0.066576, 0.379497], + [0.184801, 0.065732, 0.387973], + [0.191460, 0.064818, 0.396152], + [0.198177, 0.063862, 0.404009], + [0.204935, 0.062907, 0.411514], + [0.211718, 0.061992, 0.418647], + [0.218512, 0.061158, 0.425392], + [0.225302, 0.060445, 0.431742], + [0.232077, 0.059889, 0.437695], + [0.238826, 0.059517, 0.443256], + [0.245543, 0.059352, 0.448436], + [0.252220, 0.059415, 0.453248], + [0.258857, 0.059706, 0.457710], + [0.265447, 0.060237, 0.461840], + [0.271994, 0.060994, 0.465660], + [0.278493, 0.061978, 0.469190], + [0.284951, 0.063168, 0.472451], + [0.291366, 0.064553, 0.475462], + [0.297740, 0.066117, 0.478243], + [0.304081, 0.067835, 0.480812], + [0.310382, 0.069702, 0.483186], + [0.316654, 0.071690, 0.485380], + [0.322899, 0.073782, 0.487408], + [0.329114, 0.075972, 0.489287], + [0.335308, 0.078236, 0.491024], + [0.341482, 0.080564, 0.492631], + [0.347636, 0.082946, 0.494121], + [0.353773, 0.085373, 0.495501], + [0.359898, 0.087831, 0.496778], + [0.366012, 0.090314, 0.497960], + [0.372116, 0.092816, 0.499053], + [0.378211, 0.095332, 0.500067], + [0.384299, 0.097855, 0.501002], + [0.390384, 0.100379, 0.501864], + [0.396467, 0.102902, 0.502658], + [0.402548, 0.105420, 0.503386], + [0.408629, 0.107930, 0.504052], + [0.414709, 0.110431, 0.504662], + [0.420791, 0.112920, 0.505215], + [0.426877, 0.115395, 0.505714], + [0.432967, 0.117855, 0.506160], + [0.439062, 0.120298, 0.506555], + [0.445163, 0.122724, 0.506901], + [0.451271, 0.125132, 0.507198], + [0.457386, 0.127522, 0.507448], + [0.463508, 0.129893, 0.507652], + [0.469640, 0.132245, 0.507809], + [0.475780, 0.134577, 0.507921], + [0.481929, 0.136891, 0.507989], + [0.488088, 0.139186, 0.508011], + [0.494258, 0.141462, 0.507988], + [0.500438, 0.143719, 0.507920], + [0.506629, 0.145958, 0.507806], + [0.512831, 0.148179, 0.507648], + [0.519045, 0.150383, 0.507443], + [0.525270, 0.152569, 0.507192], + [0.531507, 0.154739, 0.506895], + [0.537755, 0.156894, 0.506551], + [0.544015, 0.159033, 0.506159], + [0.550287, 0.161158, 0.505719], + [0.556571, 0.163269, 0.505230], + [0.562866, 0.165368, 0.504692], + [0.569172, 0.167454, 0.504105], + [0.575490, 0.169530, 0.503466], + [0.581819, 0.171596, 0.502777], + [0.588158, 0.173652, 0.502035], + [0.594508, 0.175701, 0.501241], + [0.600868, 0.177743, 0.500394], + [0.607238, 0.179779, 0.499492], + [0.613617, 0.181811, 0.498536], + [0.620005, 0.183840, 0.497524], + [0.626401, 0.185867, 0.496456], + [0.632805, 0.187893, 0.495332], + [0.639216, 0.189921, 0.494150], + [0.645633, 0.191952, 0.492910], + [0.652056, 0.193986, 0.491611], + [0.658483, 0.196027, 0.490253], + [0.664915, 0.198075, 0.488836], + [0.671349, 0.200133, 0.487358], + [0.677786, 0.202203, 0.485819], + [0.684224, 0.204286, 0.484219], + [0.690661, 0.206384, 0.482558], + [0.697098, 0.208501, 0.480835], + [0.703532, 0.210638, 0.479049], + [0.709962, 0.212797, 0.477201], + [0.716387, 0.214982, 0.475290], + [0.722805, 0.217194, 0.473316], + [0.729216, 0.219437, 0.471279], + [0.735616, 0.221713, 0.469180], + [0.742004, 0.224025, 0.467018], + [0.748378, 0.226377, 0.464794], + [0.754737, 0.228772, 0.462509], + [0.761077, 0.231214, 0.460162], + [0.767398, 0.233705, 0.457755], + [0.773695, 0.236249, 0.455289], + [0.779968, 0.238851, 0.452765], + [0.786212, 0.241514, 0.450184], + [0.792427, 0.244242, 0.447543], + [0.798608, 0.247040, 0.444848], + [0.804752, 0.249911, 0.442102], + [0.810855, 0.252861, 0.439305], + [0.816914, 0.255895, 0.436461], + [0.822926, 0.259016, 0.433573], + [0.828886, 0.262229, 0.430644], + [0.834791, 0.265540, 0.427671], + [0.840636, 0.268953, 0.424666], + [0.846416, 0.272473, 0.421631], + [0.852126, 0.276106, 0.418573], + [0.857763, 0.279857, 0.415496], + [0.863320, 0.283729, 0.412403], + [0.868793, 0.287728, 0.409303], + [0.874176, 0.291859, 0.406205], + [0.879464, 0.296125, 0.403118], + [0.884651, 0.300530, 0.400047], + [0.889731, 0.305079, 0.397002], + [0.894700, 0.309773, 0.393995], + [0.899552, 0.314616, 0.391037], + [0.904281, 0.319610, 0.388137], + [0.908884, 0.324755, 0.385308], + [0.913354, 0.330052, 0.382563], + [0.917689, 0.335500, 0.379915], + [0.921884, 0.341098, 0.377376], + [0.925937, 0.346844, 0.374959], + [0.929845, 0.352734, 0.372677], + [0.933606, 0.358764, 0.370541], + [0.937221, 0.364929, 0.368567], + [0.940687, 0.371224, 0.366762], + [0.944006, 0.377643, 0.365136], + [0.947180, 0.384178, 0.363701], + [0.950210, 0.390820, 0.362468], + [0.953099, 0.397563, 0.361438], + [0.955849, 0.404400, 0.360619], + [0.958464, 0.411324, 0.360014], + [0.960949, 0.418323, 0.359630], + [0.963310, 0.425390, 0.359469], + [0.965549, 0.432519, 0.359529], + [0.967671, 0.439703, 0.359810], + [0.969680, 0.446936, 0.360311], + [0.971582, 0.454210, 0.361030], + [0.973381, 0.461520, 0.361965], + [0.975082, 0.468861, 0.363111], + [0.976690, 0.476226, 0.364466], + [0.978210, 0.483612, 0.366025], + [0.979645, 0.491014, 0.367783], + [0.981000, 0.498428, 0.369734], + [0.982279, 0.505851, 0.371874], + [0.983485, 0.513280, 0.374198], + [0.984622, 0.520713, 0.376698], + [0.985693, 0.528148, 0.379371], + [0.986700, 0.535582, 0.382210], + [0.987646, 0.543015, 0.385210], + [0.988533, 0.550446, 0.388365], + [0.989363, 0.557873, 0.391671], + [0.990138, 0.565296, 0.395122], + [0.990871, 0.572706, 0.398714], + [0.991558, 0.580107, 0.402441], + [0.992196, 0.587502, 0.406299], + [0.992785, 0.594891, 0.410283], + [0.993326, 0.602275, 0.414390], + [0.993834, 0.609644, 0.418613], + [0.994309, 0.616999, 0.422950], + [0.994738, 0.624350, 0.427397], + [0.995122, 0.631696, 0.431951], + [0.995480, 0.639027, 0.436607], + [0.995810, 0.646344, 0.441361], + [0.996096, 0.653659, 0.446213], + [0.996341, 0.660969, 0.451160], + [0.996580, 0.668256, 0.456192], + [0.996775, 0.675541, 0.461314], + [0.996925, 0.682828, 0.466526], + [0.997077, 0.690088, 0.471811], + [0.997186, 0.697349, 0.477182], + [0.997254, 0.704611, 0.482635], + [0.997325, 0.711848, 0.488154], + [0.997351, 0.719089, 0.493755], + [0.997351, 0.726324, 0.499428], + [0.997341, 0.733545, 0.505167], + [0.997285, 0.740772, 0.510983], + [0.997228, 0.747981, 0.516859], + [0.997138, 0.755190, 0.522806], + [0.997019, 0.762398, 0.528821], + [0.996898, 0.769591, 0.534892], + [0.996727, 0.776795, 0.541039], + [0.996571, 0.783977, 0.547233], + [0.996369, 0.791167, 0.553499], + [0.996162, 0.798348, 0.559820], + [0.995932, 0.805527, 0.566202], + [0.995680, 0.812706, 0.572645], + [0.995424, 0.819875, 0.579140], + [0.995131, 0.827052, 0.585701], + [0.994851, 0.834213, 0.592307], + [0.994524, 0.841387, 0.598983], + [0.994222, 0.848540, 0.605696], + [0.993866, 0.855711, 0.612482], + [0.993545, 0.862859, 0.619299], + [0.993170, 0.870024, 0.626189], + [0.992831, 0.877168, 0.633109], + [0.992440, 0.884330, 0.640099], + [0.992089, 0.891470, 0.647116], + [0.991688, 0.898627, 0.654202], + [0.991332, 0.905763, 0.661309], + [0.990930, 0.912915, 0.668481], + [0.990570, 0.920049, 0.675675], + [0.990175, 0.927196, 0.682926], + [0.989815, 0.934329, 0.690198], + [0.989434, 0.941470, 0.697519], + [0.989077, 0.948604, 0.704863], + [0.988717, 0.955742, 0.712242], + [0.988367, 0.962878, 0.719649], + [0.988033, 0.970012, 0.727077], + [0.987691, 0.977154, 0.734536], + [0.987387, 0.984288, 0.742002], + [0.987053, 0.991438, 0.749504]] + +_inferno_data = [[0.001462, 0.000466, 0.013866], + [0.002267, 0.001270, 0.018570], + [0.003299, 0.002249, 0.024239], + [0.004547, 0.003392, 0.030909], + [0.006006, 0.004692, 0.038558], + [0.007676, 0.006136, 0.046836], + [0.009561, 0.007713, 0.055143], + [0.011663, 0.009417, 0.063460], + [0.013995, 0.011225, 0.071862], + [0.016561, 0.013136, 0.080282], + [0.019373, 0.015133, 0.088767], + [0.022447, 0.017199, 0.097327], + [0.025793, 0.019331, 0.105930], + [0.029432, 0.021503, 0.114621], + [0.033385, 0.023702, 0.123397], + [0.037668, 0.025921, 0.132232], + [0.042253, 0.028139, 0.141141], + [0.046915, 0.030324, 0.150164], + [0.051644, 0.032474, 0.159254], + [0.056449, 0.034569, 0.168414], + [0.061340, 0.036590, 0.177642], + [0.066331, 0.038504, 0.186962], + [0.071429, 0.040294, 0.196354], + [0.076637, 0.041905, 0.205799], + [0.081962, 0.043328, 0.215289], + [0.087411, 0.044556, 0.224813], + [0.092990, 0.045583, 0.234358], + [0.098702, 0.046402, 0.243904], + [0.104551, 0.047008, 0.253430], + [0.110536, 0.047399, 0.262912], + [0.116656, 0.047574, 0.272321], + [0.122908, 0.047536, 0.281624], + [0.129285, 0.047293, 0.290788], + [0.135778, 0.046856, 0.299776], + [0.142378, 0.046242, 0.308553], + [0.149073, 0.045468, 0.317085], + [0.155850, 0.044559, 0.325338], + [0.162689, 0.043554, 0.333277], + [0.169575, 0.042489, 0.340874], + [0.176493, 0.041402, 0.348111], + [0.183429, 0.040329, 0.354971], + [0.190367, 0.039309, 0.361447], + [0.197297, 0.038400, 0.367535], + [0.204209, 0.037632, 0.373238], + [0.211095, 0.037030, 0.378563], + [0.217949, 0.036615, 0.383522], + [0.224763, 0.036405, 0.388129], + [0.231538, 0.036405, 0.392400], + [0.238273, 0.036621, 0.396353], + [0.244967, 0.037055, 0.400007], + [0.251620, 0.037705, 0.403378], + [0.258234, 0.038571, 0.406485], + [0.264810, 0.039647, 0.409345], + [0.271347, 0.040922, 0.411976], + [0.277850, 0.042353, 0.414392], + [0.284321, 0.043933, 0.416608], + [0.290763, 0.045644, 0.418637], + [0.297178, 0.047470, 0.420491], + [0.303568, 0.049396, 0.422182], + [0.309935, 0.051407, 0.423721], + [0.316282, 0.053490, 0.425116], + [0.322610, 0.055634, 0.426377], + [0.328921, 0.057827, 0.427511], + [0.335217, 0.060060, 0.428524], + [0.341500, 0.062325, 0.429425], + [0.347771, 0.064616, 0.430217], + [0.354032, 0.066925, 0.430906], + [0.360284, 0.069247, 0.431497], + [0.366529, 0.071579, 0.431994], + [0.372768, 0.073915, 0.432400], + [0.379001, 0.076253, 0.432719], + [0.385228, 0.078591, 0.432955], + [0.391453, 0.080927, 0.433109], + [0.397674, 0.083257, 0.433183], + [0.403894, 0.085580, 0.433179], + [0.410113, 0.087896, 0.433098], + [0.416331, 0.090203, 0.432943], + [0.422549, 0.092501, 0.432714], + [0.428768, 0.094790, 0.432412], + [0.434987, 0.097069, 0.432039], + [0.441207, 0.099338, 0.431594], + [0.447428, 0.101597, 0.431080], + [0.453651, 0.103848, 0.430498], + [0.459875, 0.106089, 0.429846], + [0.466100, 0.108322, 0.429125], + [0.472328, 0.110547, 0.428334], + [0.478558, 0.112764, 0.427475], + [0.484789, 0.114974, 0.426548], + [0.491022, 0.117179, 0.425552], + [0.497257, 0.119379, 0.424488], + [0.503493, 0.121575, 0.423356], + [0.509730, 0.123769, 0.422156], + [0.515967, 0.125960, 0.420887], + [0.522206, 0.128150, 0.419549], + [0.528444, 0.130341, 0.418142], + [0.534683, 0.132534, 0.416667], + [0.540920, 0.134729, 0.415123], + [0.547157, 0.136929, 0.413511], + [0.553392, 0.139134, 0.411829], + [0.559624, 0.141346, 0.410078], + [0.565854, 0.143567, 0.408258], + [0.572081, 0.145797, 0.406369], + [0.578304, 0.148039, 0.404411], + [0.584521, 0.150294, 0.402385], + [0.590734, 0.152563, 0.400290], + [0.596940, 0.154848, 0.398125], + [0.603139, 0.157151, 0.395891], + [0.609330, 0.159474, 0.393589], + [0.615513, 0.161817, 0.391219], + [0.621685, 0.164184, 0.388781], + [0.627847, 0.166575, 0.386276], + [0.633998, 0.168992, 0.383704], + [0.640135, 0.171438, 0.381065], + [0.646260, 0.173914, 0.378359], + [0.652369, 0.176421, 0.375586], + [0.658463, 0.178962, 0.372748], + [0.664540, 0.181539, 0.369846], + [0.670599, 0.184153, 0.366879], + [0.676638, 0.186807, 0.363849], + [0.682656, 0.189501, 0.360757], + [0.688653, 0.192239, 0.357603], + [0.694627, 0.195021, 0.354388], + [0.700576, 0.197851, 0.351113], + [0.706500, 0.200728, 0.347777], + [0.712396, 0.203656, 0.344383], + [0.718264, 0.206636, 0.340931], + [0.724103, 0.209670, 0.337424], + [0.729909, 0.212759, 0.333861], + [0.735683, 0.215906, 0.330245], + [0.741423, 0.219112, 0.326576], + [0.747127, 0.222378, 0.322856], + [0.752794, 0.225706, 0.319085], + [0.758422, 0.229097, 0.315266], + [0.764010, 0.232554, 0.311399], + [0.769556, 0.236077, 0.307485], + [0.775059, 0.239667, 0.303526], + [0.780517, 0.243327, 0.299523], + [0.785929, 0.247056, 0.295477], + [0.791293, 0.250856, 0.291390], + [0.796607, 0.254728, 0.287264], + [0.801871, 0.258674, 0.283099], + [0.807082, 0.262692, 0.278898], + [0.812239, 0.266786, 0.274661], + [0.817341, 0.270954, 0.270390], + [0.822386, 0.275197, 0.266085], + [0.827372, 0.279517, 0.261750], + [0.832299, 0.283913, 0.257383], + [0.837165, 0.288385, 0.252988], + [0.841969, 0.292933, 0.248564], + [0.846709, 0.297559, 0.244113], + [0.851384, 0.302260, 0.239636], + [0.855992, 0.307038, 0.235133], + [0.860533, 0.311892, 0.230606], + [0.865006, 0.316822, 0.226055], + [0.869409, 0.321827, 0.221482], + [0.873741, 0.326906, 0.216886], + [0.878001, 0.332060, 0.212268], + [0.882188, 0.337287, 0.207628], + [0.886302, 0.342586, 0.202968], + [0.890341, 0.347957, 0.198286], + [0.894305, 0.353399, 0.193584], + [0.898192, 0.358911, 0.188860], + [0.902003, 0.364492, 0.184116], + [0.905735, 0.370140, 0.179350], + [0.909390, 0.375856, 0.174563], + [0.912966, 0.381636, 0.169755], + [0.916462, 0.387481, 0.164924], + [0.919879, 0.393389, 0.160070], + [0.923215, 0.399359, 0.155193], + [0.926470, 0.405389, 0.150292], + [0.929644, 0.411479, 0.145367], + [0.932737, 0.417627, 0.140417], + [0.935747, 0.423831, 0.135440], + [0.938675, 0.430091, 0.130438], + [0.941521, 0.436405, 0.125409], + [0.944285, 0.442772, 0.120354], + [0.946965, 0.449191, 0.115272], + [0.949562, 0.455660, 0.110164], + [0.952075, 0.462178, 0.105031], + [0.954506, 0.468744, 0.099874], + [0.956852, 0.475356, 0.094695], + [0.959114, 0.482014, 0.089499], + [0.961293, 0.488716, 0.084289], + [0.963387, 0.495462, 0.079073], + [0.965397, 0.502249, 0.073859], + [0.967322, 0.509078, 0.068659], + [0.969163, 0.515946, 0.063488], + [0.970919, 0.522853, 0.058367], + [0.972590, 0.529798, 0.053324], + [0.974176, 0.536780, 0.048392], + [0.975677, 0.543798, 0.043618], + [0.977092, 0.550850, 0.039050], + [0.978422, 0.557937, 0.034931], + [0.979666, 0.565057, 0.031409], + [0.980824, 0.572209, 0.028508], + [0.981895, 0.579392, 0.026250], + [0.982881, 0.586606, 0.024661], + [0.983779, 0.593849, 0.023770], + [0.984591, 0.601122, 0.023606], + [0.985315, 0.608422, 0.024202], + [0.985952, 0.615750, 0.025592], + [0.986502, 0.623105, 0.027814], + [0.986964, 0.630485, 0.030908], + [0.987337, 0.637890, 0.034916], + [0.987622, 0.645320, 0.039886], + [0.987819, 0.652773, 0.045581], + [0.987926, 0.660250, 0.051750], + [0.987945, 0.667748, 0.058329], + [0.987874, 0.675267, 0.065257], + [0.987714, 0.682807, 0.072489], + [0.987464, 0.690366, 0.079990], + [0.987124, 0.697944, 0.087731], + [0.986694, 0.705540, 0.095694], + [0.986175, 0.713153, 0.103863], + [0.985566, 0.720782, 0.112229], + [0.984865, 0.728427, 0.120785], + [0.984075, 0.736087, 0.129527], + [0.983196, 0.743758, 0.138453], + [0.982228, 0.751442, 0.147565], + [0.981173, 0.759135, 0.156863], + [0.980032, 0.766837, 0.166353], + [0.978806, 0.774545, 0.176037], + [0.977497, 0.782258, 0.185923], + [0.976108, 0.789974, 0.196018], + [0.974638, 0.797692, 0.206332], + [0.973088, 0.805409, 0.216877], + [0.971468, 0.813122, 0.227658], + [0.969783, 0.820825, 0.238686], + [0.968041, 0.828515, 0.249972], + [0.966243, 0.836191, 0.261534], + [0.964394, 0.843848, 0.273391], + [0.962517, 0.851476, 0.285546], + [0.960626, 0.859069, 0.298010], + [0.958720, 0.866624, 0.310820], + [0.956834, 0.874129, 0.323974], + [0.954997, 0.881569, 0.337475], + [0.953215, 0.888942, 0.351369], + [0.951546, 0.896226, 0.365627], + [0.950018, 0.903409, 0.380271], + [0.948683, 0.910473, 0.395289], + [0.947594, 0.917399, 0.410665], + [0.946809, 0.924168, 0.426373], + [0.946392, 0.930761, 0.442367], + [0.946403, 0.937159, 0.458592], + [0.946903, 0.943348, 0.474970], + [0.947937, 0.949318, 0.491426], + [0.949545, 0.955063, 0.507860], + [0.951740, 0.960587, 0.524203], + [0.954529, 0.965896, 0.540361], + [0.957896, 0.971003, 0.556275], + [0.961812, 0.975924, 0.571925], + [0.966249, 0.980678, 0.587206], + [0.971162, 0.985282, 0.602154], + [0.976511, 0.989753, 0.616760], + [0.982257, 0.994109, 0.631017], + [0.988362, 0.998364, 0.644924]] + +_plasma_data = [[0.050383, 0.029803, 0.527975], + [0.063536, 0.028426, 0.533124], + [0.075353, 0.027206, 0.538007], + [0.086222, 0.026125, 0.542658], + [0.096379, 0.025165, 0.547103], + [0.105980, 0.024309, 0.551368], + [0.115124, 0.023556, 0.555468], + [0.123903, 0.022878, 0.559423], + [0.132381, 0.022258, 0.563250], + [0.140603, 0.021687, 0.566959], + [0.148607, 0.021154, 0.570562], + [0.156421, 0.020651, 0.574065], + [0.164070, 0.020171, 0.577478], + [0.171574, 0.019706, 0.580806], + [0.178950, 0.019252, 0.584054], + [0.186213, 0.018803, 0.587228], + [0.193374, 0.018354, 0.590330], + [0.200445, 0.017902, 0.593364], + [0.207435, 0.017442, 0.596333], + [0.214350, 0.016973, 0.599239], + [0.221197, 0.016497, 0.602083], + [0.227983, 0.016007, 0.604867], + [0.234715, 0.015502, 0.607592], + [0.241396, 0.014979, 0.610259], + [0.248032, 0.014439, 0.612868], + [0.254627, 0.013882, 0.615419], + [0.261183, 0.013308, 0.617911], + [0.267703, 0.012716, 0.620346], + [0.274191, 0.012109, 0.622722], + [0.280648, 0.011488, 0.625038], + [0.287076, 0.010855, 0.627295], + [0.293478, 0.010213, 0.629490], + [0.299855, 0.009561, 0.631624], + [0.306210, 0.008902, 0.633694], + [0.312543, 0.008239, 0.635700], + [0.318856, 0.007576, 0.637640], + [0.325150, 0.006915, 0.639512], + [0.331426, 0.006261, 0.641316], + [0.337683, 0.005618, 0.643049], + [0.343925, 0.004991, 0.644710], + [0.350150, 0.004382, 0.646298], + [0.356359, 0.003798, 0.647810], + [0.362553, 0.003243, 0.649245], + [0.368733, 0.002724, 0.650601], + [0.374897, 0.002245, 0.651876], + [0.381047, 0.001814, 0.653068], + [0.387183, 0.001434, 0.654177], + [0.393304, 0.001114, 0.655199], + [0.399411, 0.000859, 0.656133], + [0.405503, 0.000678, 0.656977], + [0.411580, 0.000577, 0.657730], + [0.417642, 0.000564, 0.658390], + [0.423689, 0.000646, 0.658956], + [0.429719, 0.000831, 0.659425], + [0.435734, 0.001127, 0.659797], + [0.441732, 0.001540, 0.660069], + [0.447714, 0.002080, 0.660240], + [0.453677, 0.002755, 0.660310], + [0.459623, 0.003574, 0.660277], + [0.465550, 0.004545, 0.660139], + [0.471457, 0.005678, 0.659897], + [0.477344, 0.006980, 0.659549], + [0.483210, 0.008460, 0.659095], + [0.489055, 0.010127, 0.658534], + [0.494877, 0.011990, 0.657865], + [0.500678, 0.014055, 0.657088], + [0.506454, 0.016333, 0.656202], + [0.512206, 0.018833, 0.655209], + [0.517933, 0.021563, 0.654109], + [0.523633, 0.024532, 0.652901], + [0.529306, 0.027747, 0.651586], + [0.534952, 0.031217, 0.650165], + [0.540570, 0.034950, 0.648640], + [0.546157, 0.038954, 0.647010], + [0.551715, 0.043136, 0.645277], + [0.557243, 0.047331, 0.643443], + [0.562738, 0.051545, 0.641509], + [0.568201, 0.055778, 0.639477], + [0.573632, 0.060028, 0.637349], + [0.579029, 0.064296, 0.635126], + [0.584391, 0.068579, 0.632812], + [0.589719, 0.072878, 0.630408], + [0.595011, 0.077190, 0.627917], + [0.600266, 0.081516, 0.625342], + [0.605485, 0.085854, 0.622686], + [0.610667, 0.090204, 0.619951], + [0.615812, 0.094564, 0.617140], + [0.620919, 0.098934, 0.614257], + [0.625987, 0.103312, 0.611305], + [0.631017, 0.107699, 0.608287], + [0.636008, 0.112092, 0.605205], + [0.640959, 0.116492, 0.602065], + [0.645872, 0.120898, 0.598867], + [0.650746, 0.125309, 0.595617], + [0.655580, 0.129725, 0.592317], + [0.660374, 0.134144, 0.588971], + [0.665129, 0.138566, 0.585582], + [0.669845, 0.142992, 0.582154], + [0.674522, 0.147419, 0.578688], + [0.679160, 0.151848, 0.575189], + [0.683758, 0.156278, 0.571660], + [0.688318, 0.160709, 0.568103], + [0.692840, 0.165141, 0.564522], + [0.697324, 0.169573, 0.560919], + [0.701769, 0.174005, 0.557296], + [0.706178, 0.178437, 0.553657], + [0.710549, 0.182868, 0.550004], + [0.714883, 0.187299, 0.546338], + [0.719181, 0.191729, 0.542663], + [0.723444, 0.196158, 0.538981], + [0.727670, 0.200586, 0.535293], + [0.731862, 0.205013, 0.531601], + [0.736019, 0.209439, 0.527908], + [0.740143, 0.213864, 0.524216], + [0.744232, 0.218288, 0.520524], + [0.748289, 0.222711, 0.516834], + [0.752312, 0.227133, 0.513149], + [0.756304, 0.231555, 0.509468], + [0.760264, 0.235976, 0.505794], + [0.764193, 0.240396, 0.502126], + [0.768090, 0.244817, 0.498465], + [0.771958, 0.249237, 0.494813], + [0.775796, 0.253658, 0.491171], + [0.779604, 0.258078, 0.487539], + [0.783383, 0.262500, 0.483918], + [0.787133, 0.266922, 0.480307], + [0.790855, 0.271345, 0.476706], + [0.794549, 0.275770, 0.473117], + [0.798216, 0.280197, 0.469538], + [0.801855, 0.284626, 0.465971], + [0.805467, 0.289057, 0.462415], + [0.809052, 0.293491, 0.458870], + [0.812612, 0.297928, 0.455338], + [0.816144, 0.302368, 0.451816], + [0.819651, 0.306812, 0.448306], + [0.823132, 0.311261, 0.444806], + [0.826588, 0.315714, 0.441316], + [0.830018, 0.320172, 0.437836], + [0.833422, 0.324635, 0.434366], + [0.836801, 0.329105, 0.430905], + [0.840155, 0.333580, 0.427455], + [0.843484, 0.338062, 0.424013], + [0.846788, 0.342551, 0.420579], + [0.850066, 0.347048, 0.417153], + [0.853319, 0.351553, 0.413734], + [0.856547, 0.356066, 0.410322], + [0.859750, 0.360588, 0.406917], + [0.862927, 0.365119, 0.403519], + [0.866078, 0.369660, 0.400126], + [0.869203, 0.374212, 0.396738], + [0.872303, 0.378774, 0.393355], + [0.875376, 0.383347, 0.389976], + [0.878423, 0.387932, 0.386600], + [0.881443, 0.392529, 0.383229], + [0.884436, 0.397139, 0.379860], + [0.887402, 0.401762, 0.376494], + [0.890340, 0.406398, 0.373130], + [0.893250, 0.411048, 0.369768], + [0.896131, 0.415712, 0.366407], + [0.898984, 0.420392, 0.363047], + [0.901807, 0.425087, 0.359688], + [0.904601, 0.429797, 0.356329], + [0.907365, 0.434524, 0.352970], + [0.910098, 0.439268, 0.349610], + [0.912800, 0.444029, 0.346251], + [0.915471, 0.448807, 0.342890], + [0.918109, 0.453603, 0.339529], + [0.920714, 0.458417, 0.336166], + [0.923287, 0.463251, 0.332801], + [0.925825, 0.468103, 0.329435], + [0.928329, 0.472975, 0.326067], + [0.930798, 0.477867, 0.322697], + [0.933232, 0.482780, 0.319325], + [0.935630, 0.487712, 0.315952], + [0.937990, 0.492667, 0.312575], + [0.940313, 0.497642, 0.309197], + [0.942598, 0.502639, 0.305816], + [0.944844, 0.507658, 0.302433], + [0.947051, 0.512699, 0.299049], + [0.949217, 0.517763, 0.295662], + [0.951344, 0.522850, 0.292275], + [0.953428, 0.527960, 0.288883], + [0.955470, 0.533093, 0.285490], + [0.957469, 0.538250, 0.282096], + [0.959424, 0.543431, 0.278701], + [0.961336, 0.548636, 0.275305], + [0.963203, 0.553865, 0.271909], + [0.965024, 0.559118, 0.268513], + [0.966798, 0.564396, 0.265118], + [0.968526, 0.569700, 0.261721], + [0.970205, 0.575028, 0.258325], + [0.971835, 0.580382, 0.254931], + [0.973416, 0.585761, 0.251540], + [0.974947, 0.591165, 0.248151], + [0.976428, 0.596595, 0.244767], + [0.977856, 0.602051, 0.241387], + [0.979233, 0.607532, 0.238013], + [0.980556, 0.613039, 0.234646], + [0.981826, 0.618572, 0.231287], + [0.983041, 0.624131, 0.227937], + [0.984199, 0.629718, 0.224595], + [0.985301, 0.635330, 0.221265], + [0.986345, 0.640969, 0.217948], + [0.987332, 0.646633, 0.214648], + [0.988260, 0.652325, 0.211364], + [0.989128, 0.658043, 0.208100], + [0.989935, 0.663787, 0.204859], + [0.990681, 0.669558, 0.201642], + [0.991365, 0.675355, 0.198453], + [0.991985, 0.681179, 0.195295], + [0.992541, 0.687030, 0.192170], + [0.993032, 0.692907, 0.189084], + [0.993456, 0.698810, 0.186041], + [0.993814, 0.704741, 0.183043], + [0.994103, 0.710698, 0.180097], + [0.994324, 0.716681, 0.177208], + [0.994474, 0.722691, 0.174381], + [0.994553, 0.728728, 0.171622], + [0.994561, 0.734791, 0.168938], + [0.994495, 0.740880, 0.166335], + [0.994355, 0.746995, 0.163821], + [0.994141, 0.753137, 0.161404], + [0.993851, 0.759304, 0.159092], + [0.993482, 0.765499, 0.156891], + [0.993033, 0.771720, 0.154808], + [0.992505, 0.777967, 0.152855], + [0.991897, 0.784239, 0.151042], + [0.991209, 0.790537, 0.149377], + [0.990439, 0.796859, 0.147870], + [0.989587, 0.803205, 0.146529], + [0.988648, 0.809579, 0.145357], + [0.987621, 0.815978, 0.144363], + [0.986509, 0.822401, 0.143557], + [0.985314, 0.828846, 0.142945], + [0.984031, 0.835315, 0.142528], + [0.982653, 0.841812, 0.142303], + [0.981190, 0.848329, 0.142279], + [0.979644, 0.854866, 0.142453], + [0.977995, 0.861432, 0.142808], + [0.976265, 0.868016, 0.143351], + [0.974443, 0.874622, 0.144061], + [0.972530, 0.881250, 0.144923], + [0.970533, 0.887896, 0.145919], + [0.968443, 0.894564, 0.147014], + [0.966271, 0.901249, 0.148180], + [0.964021, 0.907950, 0.149370], + [0.961681, 0.914672, 0.150520], + [0.959276, 0.921407, 0.151566], + [0.956808, 0.928152, 0.152409], + [0.954287, 0.934908, 0.152921], + [0.951726, 0.941671, 0.152925], + [0.949151, 0.948435, 0.152178], + [0.946602, 0.955190, 0.150328], + [0.944152, 0.961916, 0.146861], + [0.941896, 0.968590, 0.140956], + [0.940015, 0.975158, 0.131326]] + +_viridis_data = [[0.267004, 0.004874, 0.329415], + [0.268510, 0.009605, 0.335427], + [0.269944, 0.014625, 0.341379], + [0.271305, 0.019942, 0.347269], + [0.272594, 0.025563, 0.353093], + [0.273809, 0.031497, 0.358853], + [0.274952, 0.037752, 0.364543], + [0.276022, 0.044167, 0.370164], + [0.277018, 0.050344, 0.375715], + [0.277941, 0.056324, 0.381191], + [0.278791, 0.062145, 0.386592], + [0.279566, 0.067836, 0.391917], + [0.280267, 0.073417, 0.397163], + [0.280894, 0.078907, 0.402329], + [0.281446, 0.084320, 0.407414], + [0.281924, 0.089666, 0.412415], + [0.282327, 0.094955, 0.417331], + [0.282656, 0.100196, 0.422160], + [0.282910, 0.105393, 0.426902], + [0.283091, 0.110553, 0.431554], + [0.283197, 0.115680, 0.436115], + [0.283229, 0.120777, 0.440584], + [0.283187, 0.125848, 0.444960], + [0.283072, 0.130895, 0.449241], + [0.282884, 0.135920, 0.453427], + [0.282623, 0.140926, 0.457517], + [0.282290, 0.145912, 0.461510], + [0.281887, 0.150881, 0.465405], + [0.281412, 0.155834, 0.469201], + [0.280868, 0.160771, 0.472899], + [0.280255, 0.165693, 0.476498], + [0.279574, 0.170599, 0.479997], + [0.278826, 0.175490, 0.483397], + [0.278012, 0.180367, 0.486697], + [0.277134, 0.185228, 0.489898], + [0.276194, 0.190074, 0.493001], + [0.275191, 0.194905, 0.496005], + [0.274128, 0.199721, 0.498911], + [0.273006, 0.204520, 0.501721], + [0.271828, 0.209303, 0.504434], + [0.270595, 0.214069, 0.507052], + [0.269308, 0.218818, 0.509577], + [0.267968, 0.223549, 0.512008], + [0.266580, 0.228262, 0.514349], + [0.265145, 0.232956, 0.516599], + [0.263663, 0.237631, 0.518762], + [0.262138, 0.242286, 0.520837], + [0.260571, 0.246922, 0.522828], + [0.258965, 0.251537, 0.524736], + [0.257322, 0.256130, 0.526563], + [0.255645, 0.260703, 0.528312], + [0.253935, 0.265254, 0.529983], + [0.252194, 0.269783, 0.531579], + [0.250425, 0.274290, 0.533103], + [0.248629, 0.278775, 0.534556], + [0.246811, 0.283237, 0.535941], + [0.244972, 0.287675, 0.537260], + [0.243113, 0.292092, 0.538516], + [0.241237, 0.296485, 0.539709], + [0.239346, 0.300855, 0.540844], + [0.237441, 0.305202, 0.541921], + [0.235526, 0.309527, 0.542944], + [0.233603, 0.313828, 0.543914], + [0.231674, 0.318106, 0.544834], + [0.229739, 0.322361, 0.545706], + [0.227802, 0.326594, 0.546532], + [0.225863, 0.330805, 0.547314], + [0.223925, 0.334994, 0.548053], + [0.221989, 0.339161, 0.548752], + [0.220057, 0.343307, 0.549413], + [0.218130, 0.347432, 0.550038], + [0.216210, 0.351535, 0.550627], + [0.214298, 0.355619, 0.551184], + [0.212395, 0.359683, 0.551710], + [0.210503, 0.363727, 0.552206], + [0.208623, 0.367752, 0.552675], + [0.206756, 0.371758, 0.553117], + [0.204903, 0.375746, 0.553533], + [0.203063, 0.379716, 0.553925], + [0.201239, 0.383670, 0.554294], + [0.199430, 0.387607, 0.554642], + [0.197636, 0.391528, 0.554969], + [0.195860, 0.395433, 0.555276], + [0.194100, 0.399323, 0.555565], + [0.192357, 0.403199, 0.555836], + [0.190631, 0.407061, 0.556089], + [0.188923, 0.410910, 0.556326], + [0.187231, 0.414746, 0.556547], + [0.185556, 0.418570, 0.556753], + [0.183898, 0.422383, 0.556944], + [0.182256, 0.426184, 0.557120], + [0.180629, 0.429975, 0.557282], + [0.179019, 0.433756, 0.557430], + [0.177423, 0.437527, 0.557565], + [0.175841, 0.441290, 0.557685], + [0.174274, 0.445044, 0.557792], + [0.172719, 0.448791, 0.557885], + [0.171176, 0.452530, 0.557965], + [0.169646, 0.456262, 0.558030], + [0.168126, 0.459988, 0.558082], + [0.166617, 0.463708, 0.558119], + [0.165117, 0.467423, 0.558141], + [0.163625, 0.471133, 0.558148], + [0.162142, 0.474838, 0.558140], + [0.160665, 0.478540, 0.558115], + [0.159194, 0.482237, 0.558073], + [0.157729, 0.485932, 0.558013], + [0.156270, 0.489624, 0.557936], + [0.154815, 0.493313, 0.557840], + [0.153364, 0.497000, 0.557724], + [0.151918, 0.500685, 0.557587], + [0.150476, 0.504369, 0.557430], + [0.149039, 0.508051, 0.557250], + [0.147607, 0.511733, 0.557049], + [0.146180, 0.515413, 0.556823], + [0.144759, 0.519093, 0.556572], + [0.143343, 0.522773, 0.556295], + [0.141935, 0.526453, 0.555991], + [0.140536, 0.530132, 0.555659], + [0.139147, 0.533812, 0.555298], + [0.137770, 0.537492, 0.554906], + [0.136408, 0.541173, 0.554483], + [0.135066, 0.544853, 0.554029], + [0.133743, 0.548535, 0.553541], + [0.132444, 0.552216, 0.553018], + [0.131172, 0.555899, 0.552459], + [0.129933, 0.559582, 0.551864], + [0.128729, 0.563265, 0.551229], + [0.127568, 0.566949, 0.550556], + [0.126453, 0.570633, 0.549841], + [0.125394, 0.574318, 0.549086], + [0.124395, 0.578002, 0.548287], + [0.123463, 0.581687, 0.547445], + [0.122606, 0.585371, 0.546557], + [0.121831, 0.589055, 0.545623], + [0.121148, 0.592739, 0.544641], + [0.120565, 0.596422, 0.543611], + [0.120092, 0.600104, 0.542530], + [0.119738, 0.603785, 0.541400], + [0.119512, 0.607464, 0.540218], + [0.119423, 0.611141, 0.538982], + [0.119483, 0.614817, 0.537692], + [0.119699, 0.618490, 0.536347], + [0.120081, 0.622161, 0.534946], + [0.120638, 0.625828, 0.533488], + [0.121380, 0.629492, 0.531973], + [0.122312, 0.633153, 0.530398], + [0.123444, 0.636809, 0.528763], + [0.124780, 0.640461, 0.527068], + [0.126326, 0.644107, 0.525311], + [0.128087, 0.647749, 0.523491], + [0.130067, 0.651384, 0.521608], + [0.132268, 0.655014, 0.519661], + [0.134692, 0.658636, 0.517649], + [0.137339, 0.662252, 0.515571], + [0.140210, 0.665859, 0.513427], + [0.143303, 0.669459, 0.511215], + [0.146616, 0.673050, 0.508936], + [0.150148, 0.676631, 0.506589], + [0.153894, 0.680203, 0.504172], + [0.157851, 0.683765, 0.501686], + [0.162016, 0.687316, 0.499129], + [0.166383, 0.690856, 0.496502], + [0.170948, 0.694384, 0.493803], + [0.175707, 0.697900, 0.491033], + [0.180653, 0.701402, 0.488189], + [0.185783, 0.704891, 0.485273], + [0.191090, 0.708366, 0.482284], + [0.196571, 0.711827, 0.479221], + [0.202219, 0.715272, 0.476084], + [0.208030, 0.718701, 0.472873], + [0.214000, 0.722114, 0.469588], + [0.220124, 0.725509, 0.466226], + [0.226397, 0.728888, 0.462789], + [0.232815, 0.732247, 0.459277], + [0.239374, 0.735588, 0.455688], + [0.246070, 0.738910, 0.452024], + [0.252899, 0.742211, 0.448284], + [0.259857, 0.745492, 0.444467], + [0.266941, 0.748751, 0.440573], + [0.274149, 0.751988, 0.436601], + [0.281477, 0.755203, 0.432552], + [0.288921, 0.758394, 0.428426], + [0.296479, 0.761561, 0.424223], + [0.304148, 0.764704, 0.419943], + [0.311925, 0.767822, 0.415586], + [0.319809, 0.770914, 0.411152], + [0.327796, 0.773980, 0.406640], + [0.335885, 0.777018, 0.402049], + [0.344074, 0.780029, 0.397381], + [0.352360, 0.783011, 0.392636], + [0.360741, 0.785964, 0.387814], + [0.369214, 0.788888, 0.382914], + [0.377779, 0.791781, 0.377939], + [0.386433, 0.794644, 0.372886], + [0.395174, 0.797475, 0.367757], + [0.404001, 0.800275, 0.362552], + [0.412913, 0.803041, 0.357269], + [0.421908, 0.805774, 0.351910], + [0.430983, 0.808473, 0.346476], + [0.440137, 0.811138, 0.340967], + [0.449368, 0.813768, 0.335384], + [0.458674, 0.816363, 0.329727], + [0.468053, 0.818921, 0.323998], + [0.477504, 0.821444, 0.318195], + [0.487026, 0.823929, 0.312321], + [0.496615, 0.826376, 0.306377], + [0.506271, 0.828786, 0.300362], + [0.515992, 0.831158, 0.294279], + [0.525776, 0.833491, 0.288127], + [0.535621, 0.835785, 0.281908], + [0.545524, 0.838039, 0.275626], + [0.555484, 0.840254, 0.269281], + [0.565498, 0.842430, 0.262877], + [0.575563, 0.844566, 0.256415], + [0.585678, 0.846661, 0.249897], + [0.595839, 0.848717, 0.243329], + [0.606045, 0.850733, 0.236712], + [0.616293, 0.852709, 0.230052], + [0.626579, 0.854645, 0.223353], + [0.636902, 0.856542, 0.216620], + [0.647257, 0.858400, 0.209861], + [0.657642, 0.860219, 0.203082], + [0.668054, 0.861999, 0.196293], + [0.678489, 0.863742, 0.189503], + [0.688944, 0.865448, 0.182725], + [0.699415, 0.867117, 0.175971], + [0.709898, 0.868751, 0.169257], + [0.720391, 0.870350, 0.162603], + [0.730889, 0.871916, 0.156029], + [0.741388, 0.873449, 0.149561], + [0.751884, 0.874951, 0.143228], + [0.762373, 0.876424, 0.137064], + [0.772852, 0.877868, 0.131109], + [0.783315, 0.879285, 0.125405], + [0.793760, 0.880678, 0.120005], + [0.804182, 0.882046, 0.114965], + [0.814576, 0.883393, 0.110347], + [0.824940, 0.884720, 0.106217], + [0.835270, 0.886029, 0.102646], + [0.845561, 0.887322, 0.099702], + [0.855810, 0.888601, 0.097452], + [0.866013, 0.889868, 0.095953], + [0.876168, 0.891125, 0.095250], + [0.886271, 0.892374, 0.095374], + [0.896320, 0.893616, 0.096335], + [0.906311, 0.894855, 0.098125], + [0.916242, 0.896091, 0.100717], + [0.926106, 0.897330, 0.104071], + [0.935904, 0.898570, 0.108131], + [0.945636, 0.899815, 0.112838], + [0.955300, 0.901065, 0.118128], + [0.964894, 0.902323, 0.123941], + [0.974417, 0.903590, 0.130215], + [0.983868, 0.904867, 0.136897], + [0.993248, 0.906157, 0.143936]] + +_cividis_data = [[0.000000, 0.135112, 0.304751], + [0.000000, 0.138068, 0.311105], + [0.000000, 0.141013, 0.317579], + [0.000000, 0.143951, 0.323982], + [0.000000, 0.146877, 0.330479], + [0.000000, 0.149791, 0.337065], + [0.000000, 0.152673, 0.343704], + [0.000000, 0.155377, 0.350500], + [0.000000, 0.157932, 0.357521], + [0.000000, 0.160495, 0.364534], + [0.000000, 0.163058, 0.371608], + [0.000000, 0.165621, 0.378769], + [0.000000, 0.168204, 0.385902], + [0.000000, 0.170800, 0.393100], + [0.000000, 0.173420, 0.400353], + [0.000000, 0.176082, 0.407577], + [0.000000, 0.178802, 0.414764], + [0.000000, 0.181610, 0.421859], + [0.000000, 0.184550, 0.428802], + [0.000000, 0.186915, 0.435532], + [0.000000, 0.188769, 0.439563], + [0.000000, 0.190950, 0.441085], + [0.000000, 0.193366, 0.441561], + [0.003602, 0.195911, 0.441564], + [0.017852, 0.198528, 0.441248], + [0.032110, 0.201199, 0.440785], + [0.046205, 0.203903, 0.440196], + [0.058378, 0.206629, 0.439531], + [0.068968, 0.209372, 0.438863], + [0.078624, 0.212122, 0.438105], + [0.087465, 0.214879, 0.437342], + [0.095645, 0.217643, 0.436593], + [0.103401, 0.220406, 0.435790], + [0.110658, 0.223170, 0.435067], + [0.117612, 0.225935, 0.434308], + [0.124291, 0.228697, 0.433547], + [0.130669, 0.231458, 0.432840], + [0.136830, 0.234216, 0.432148], + [0.142852, 0.236972, 0.431404], + [0.148638, 0.239724, 0.430752], + [0.154261, 0.242475, 0.430120], + [0.159733, 0.245221, 0.429528], + [0.165113, 0.247965, 0.428908], + [0.170362, 0.250707, 0.428325], + [0.175490, 0.253444, 0.427790], + [0.180503, 0.256180, 0.427299], + [0.185453, 0.258914, 0.426788], + [0.190303, 0.261644, 0.426329], + [0.195057, 0.264372, 0.425924], + [0.199764, 0.267099, 0.425497], + [0.204385, 0.269823, 0.425126], + [0.208926, 0.272546, 0.424809], + [0.213431, 0.275266, 0.424480], + [0.217863, 0.277985, 0.424206], + [0.222264, 0.280702, 0.423914], + [0.226598, 0.283419, 0.423678], + [0.230871, 0.286134, 0.423498], + [0.235120, 0.288848, 0.423304], + [0.239312, 0.291562, 0.423167], + [0.243485, 0.294274, 0.423014], + [0.247605, 0.296986, 0.422917], + [0.251675, 0.299698, 0.422873], + [0.255731, 0.302409, 0.422814], + [0.259740, 0.305120, 0.422810], + [0.263738, 0.307831, 0.422789], + [0.267693, 0.310542, 0.422821], + [0.271639, 0.313253, 0.422837], + [0.275513, 0.315965, 0.422979], + [0.279411, 0.318677, 0.423031], + [0.283240, 0.321390, 0.423211], + [0.287065, 0.324103, 0.423373], + [0.290884, 0.326816, 0.423517], + [0.294669, 0.329531, 0.423716], + [0.298421, 0.332247, 0.423973], + [0.302169, 0.334963, 0.424213], + [0.305886, 0.337681, 0.424512], + [0.309601, 0.340399, 0.424790], + [0.313287, 0.343120, 0.425120], + [0.316941, 0.345842, 0.425512], + [0.320595, 0.348565, 0.425889], + [0.324250, 0.351289, 0.426250], + [0.327875, 0.354016, 0.426670], + [0.331474, 0.356744, 0.427144], + [0.335073, 0.359474, 0.427605], + [0.338673, 0.362206, 0.428053], + [0.342246, 0.364939, 0.428559], + [0.345793, 0.367676, 0.429127], + [0.349341, 0.370414, 0.429685], + [0.352892, 0.373153, 0.430226], + [0.356418, 0.375896, 0.430823], + [0.359916, 0.378641, 0.431501], + [0.363446, 0.381388, 0.432075], + [0.366923, 0.384139, 0.432796], + [0.370430, 0.386890, 0.433428], + [0.373884, 0.389646, 0.434209], + [0.377371, 0.392404, 0.434890], + [0.380830, 0.395164, 0.435653], + [0.384268, 0.397928, 0.436475], + [0.387705, 0.400694, 0.437305], + [0.391151, 0.403464, 0.438096], + [0.394568, 0.406236, 0.438986], + [0.397991, 0.409011, 0.439848], + [0.401418, 0.411790, 0.440708], + [0.404820, 0.414572, 0.441642], + [0.408226, 0.417357, 0.442570], + [0.411607, 0.420145, 0.443577], + [0.414992, 0.422937, 0.444578], + [0.418383, 0.425733, 0.445560], + [0.421748, 0.428531, 0.446640], + [0.425120, 0.431334, 0.447692], + [0.428462, 0.434140, 0.448864], + [0.431817, 0.436950, 0.449982], + [0.435168, 0.439763, 0.451134], + [0.438504, 0.442580, 0.452341], + [0.441810, 0.445402, 0.453659], + [0.445148, 0.448226, 0.454885], + [0.448447, 0.451053, 0.456264], + [0.451759, 0.453887, 0.457582], + [0.455072, 0.456718, 0.458976], + [0.458366, 0.459552, 0.460457], + [0.461616, 0.462405, 0.461969], + [0.464947, 0.465241, 0.463395], + [0.468254, 0.468083, 0.464908], + [0.471501, 0.470960, 0.466357], + [0.474812, 0.473832, 0.467681], + [0.478186, 0.476699, 0.468845], + [0.481622, 0.479573, 0.469767], + [0.485141, 0.482451, 0.470384], + [0.488697, 0.485318, 0.471008], + [0.492278, 0.488198, 0.471453], + [0.495913, 0.491076, 0.471751], + [0.499552, 0.493960, 0.472032], + [0.503185, 0.496851, 0.472305], + [0.506866, 0.499743, 0.472432], + [0.510540, 0.502643, 0.472550], + [0.514226, 0.505546, 0.472640], + [0.517920, 0.508454, 0.472707], + [0.521643, 0.511367, 0.472639], + [0.525348, 0.514285, 0.472660], + [0.529086, 0.517207, 0.472543], + [0.532829, 0.520135, 0.472401], + [0.536553, 0.523067, 0.472352], + [0.540307, 0.526005, 0.472163], + [0.544069, 0.528948, 0.471947], + [0.547840, 0.531895, 0.471704], + [0.551612, 0.534849, 0.471439], + [0.555393, 0.537807, 0.471147], + [0.559181, 0.540771, 0.470829], + [0.562972, 0.543741, 0.470488], + [0.566802, 0.546715, 0.469988], + [0.570607, 0.549695, 0.469593], + [0.574417, 0.552682, 0.469172], + [0.578236, 0.555673, 0.468724], + [0.582087, 0.558670, 0.468118], + [0.585916, 0.561674, 0.467618], + [0.589753, 0.564682, 0.467090], + [0.593622, 0.567697, 0.466401], + [0.597469, 0.570718, 0.465821], + [0.601354, 0.573743, 0.465074], + [0.605211, 0.576777, 0.464441], + [0.609105, 0.579816, 0.463638], + [0.612977, 0.582861, 0.462950], + [0.616852, 0.585913, 0.462237], + [0.620765, 0.588970, 0.461351], + [0.624654, 0.592034, 0.460583], + [0.628576, 0.595104, 0.459641], + [0.632506, 0.598180, 0.458668], + [0.636412, 0.601264, 0.457818], + [0.640352, 0.604354, 0.456791], + [0.644270, 0.607450, 0.455886], + [0.648222, 0.610553, 0.454801], + [0.652178, 0.613664, 0.453689], + [0.656114, 0.616780, 0.452702], + [0.660082, 0.619904, 0.451534], + [0.664055, 0.623034, 0.450338], + [0.668008, 0.626171, 0.449270], + [0.671991, 0.629316, 0.448018], + [0.675981, 0.632468, 0.446736], + [0.679979, 0.635626, 0.445424], + [0.683950, 0.638793, 0.444251], + [0.687957, 0.641966, 0.442886], + [0.691971, 0.645145, 0.441491], + [0.695985, 0.648334, 0.440072], + [0.700008, 0.651529, 0.438624], + [0.704037, 0.654731, 0.437147], + [0.708067, 0.657942, 0.435647], + [0.712105, 0.661160, 0.434117], + [0.716177, 0.664384, 0.432386], + [0.720222, 0.667618, 0.430805], + [0.724274, 0.670859, 0.429194], + [0.728334, 0.674107, 0.427554], + [0.732422, 0.677364, 0.425717], + [0.736488, 0.680629, 0.424028], + [0.740589, 0.683900, 0.422131], + [0.744664, 0.687181, 0.420393], + [0.748772, 0.690470, 0.418448], + [0.752886, 0.693766, 0.416472], + [0.756975, 0.697071, 0.414659], + [0.761096, 0.700384, 0.412638], + [0.765223, 0.703705, 0.410587], + [0.769353, 0.707035, 0.408516], + [0.773486, 0.710373, 0.406422], + [0.777651, 0.713719, 0.404112], + [0.781795, 0.717074, 0.401966], + [0.785965, 0.720438, 0.399613], + [0.790116, 0.723810, 0.397423], + [0.794298, 0.727190, 0.395016], + [0.798480, 0.730580, 0.392597], + [0.802667, 0.733978, 0.390153], + [0.806859, 0.737385, 0.387684], + [0.811054, 0.740801, 0.385198], + [0.815274, 0.744226, 0.382504], + [0.819499, 0.747659, 0.379785], + [0.823729, 0.751101, 0.377043], + [0.827959, 0.754553, 0.374292], + [0.832192, 0.758014, 0.371529], + [0.836429, 0.761483, 0.368747], + [0.840693, 0.764962, 0.365746], + [0.844957, 0.768450, 0.362741], + [0.849223, 0.771947, 0.359729], + [0.853515, 0.775454, 0.356500], + [0.857809, 0.778969, 0.353259], + [0.862105, 0.782494, 0.350011], + [0.866421, 0.786028, 0.346571], + [0.870717, 0.789572, 0.343333], + [0.875057, 0.793125, 0.339685], + [0.879378, 0.796687, 0.336241], + [0.883720, 0.800258, 0.332599], + [0.888081, 0.803839, 0.328770], + [0.892440, 0.807430, 0.324968], + [0.896818, 0.811030, 0.320982], + [0.901195, 0.814639, 0.317021], + [0.905589, 0.818257, 0.312889], + [0.910000, 0.821885, 0.308594], + [0.914407, 0.825522, 0.304348], + [0.918828, 0.829168, 0.299960], + [0.923279, 0.832822, 0.295244], + [0.927724, 0.836486, 0.290611], + [0.932180, 0.840159, 0.285880], + [0.936660, 0.843841, 0.280876], + [0.941147, 0.847530, 0.275815], + [0.945654, 0.851228, 0.270532], + [0.950178, 0.854933, 0.265085], + [0.954725, 0.858646, 0.259365], + [0.959284, 0.862365, 0.253563], + [0.963872, 0.866089, 0.247445], + [0.968469, 0.869819, 0.241310], + [0.973114, 0.873550, 0.234677], + [0.977780, 0.877281, 0.227954], + [0.982497, 0.881008, 0.220878], + [0.987293, 0.884718, 0.213336], + [0.992218, 0.888385, 0.205468], + [0.994847, 0.892954, 0.203445], + [0.995249, 0.898384, 0.207561], + [0.995503, 0.903866, 0.212370], + [0.995737, 0.909344, 0.217772]] + +_twilight_data = [ + [0.88575015840754434, 0.85000924943067835, 0.8879736506427196], + [0.88378520195539056, 0.85072940540310626, 0.88723222096949894], + [0.88172231059285788, 0.85127594077653468, 0.88638056925514819], + [0.8795410528270573, 0.85165675407495722, 0.8854143767924102], + [0.87724880858965482, 0.85187028338870274, 0.88434120381311432], + [0.87485347508575972, 0.85191526123023187, 0.88316926967613829], + [0.87233134085124076, 0.85180165478080894, 0.88189704355001619], + [0.86970474853509816, 0.85152403004797894, 0.88053883390003362], + [0.86696015505333579, 0.8510896085314068, 0.87909766977173343], + [0.86408985081463996, 0.85050391167507788, 0.87757925784892632], + [0.86110245436899846, 0.84976754857001258, 0.87599242923439569], + [0.85798259245670372, 0.84888934810281835, 0.87434038553446281], + [0.85472593189256985, 0.84787488124672816, 0.8726282980930582], + [0.85133714570857189, 0.84672735796116472, 0.87086081657350445], + [0.84780710702577922, 0.8454546229209523, 0.86904036783694438], + [0.8441261828674842, 0.84406482711037389, 0.86716973322690072], + [0.84030420805957784, 0.8425605950855084, 0.865250882410458], + [0.83634031809191178, 0.84094796518951942, 0.86328528001070159], + [0.83222705712934408, 0.83923490627754482, 0.86127563500427884], + [0.82796894316013536, 0.83742600751395202, 0.85922399451306786], + [0.82357429680252847, 0.83552487764795436, 0.85713191328514948], + [0.81904654677937527, 0.8335364929949034, 0.85500206287010105], + [0.81438982121143089, 0.83146558694197847, 0.85283759062147024], + [0.8095999819094809, 0.82931896673505456, 0.85064441601050367], + [0.80469164429814577, 0.82709838780560663, 0.84842449296974021], + [0.79967075421267997, 0.82480781812080928, 0.84618210029578533], + [0.79454305089231114, 0.82245116226304615, 0.84392184786827984], + [0.78931445564608915, 0.82003213188702007, 0.8416486380471222], + [0.78399101042764918, 0.81755426400533426, 0.83936747464036732], + [0.77857892008227592, 0.81502089378742548, 0.8370834463093898], + [0.77308416590170936, 0.81243524735466011, 0.83480172950579679], + [0.76751108504417864, 0.8098007598713145, 0.83252816638059668], + [0.76186907937980286, 0.80711949387647486, 0.830266486168872], + [0.75616443584381976, 0.80439408733477935, 0.82802138994719998], + [0.75040346765406696, 0.80162699008965321, 0.82579737851082424], + [0.74459247771890169, 0.79882047719583249, 0.82359867586156521], + [0.73873771700494939, 0.79597665735031009, 0.82142922780433014], + [0.73284543645523459, 0.79309746468844067, 0.81929263384230377], + [0.72692177512829703, 0.7901846863592763, 0.81719217466726379], + [0.72097280665536778, 0.78723995923452639, 0.81513073920879264], + [0.71500403076252128, 0.78426487091581187, 0.81311116559949914], + [0.70902078134539304, 0.78126088716070907, 0.81113591855117928], + [0.7030297722540817, 0.77822904973358131, 0.80920618848056969], + [0.6970365443886174, 0.77517050008066057, 0.80732335380063447], + [0.69104641009309098, 0.77208629460678091, 0.80548841690679074], + [0.68506446154395928, 0.7689774029354699, 0.80370206267176914], + [0.67909554499882152, 0.76584472131395898, 0.8019646617300199], + [0.67314422559426212, 0.76268908733890484, 0.80027628545809526], + [0.66721479803752815, 0.7595112803730375, 0.79863674654537764], + [0.6613112930078745, 0.75631202708719025, 0.7970456043491897], + [0.65543692326454717, 0.75309208756768431, 0.79550271129031047], + [0.64959573004253479, 0.74985201221941766, 0.79400674021499107], + [0.6437910831099849, 0.7465923800833657, 0.79255653201306053], + [0.63802586828545982, 0.74331376714033193, 0.79115100459573173], + [0.6323027138710603, 0.74001672160131404, 0.78978892762640429], + [0.62662402022604591, 0.73670175403699445, 0.78846901316334561], + [0.62099193064817548, 0.73336934798923203, 0.78718994624696581], + [0.61540846411770478, 0.73001995232739691, 0.78595022706750484], + [0.60987543176093062, 0.72665398759758293, 0.78474835732694714], + [0.60439434200274855, 0.7232718614323369, 0.78358295593535587], + [0.5989665814482068, 0.71987394892246725, 0.78245259899346642], + [0.59359335696837223, 0.7164606049658685, 0.78135588237640097], + [0.58827579780555495, 0.71303214646458135, 0.78029141405636515], + [0.58301487036932409, 0.70958887676997473, 0.77925781820476592], + [0.5778116438998202, 0.70613106157153982, 0.77825345121025524], + [0.5726668948158774, 0.7026589535425779, 0.77727702680911992], + [0.56758117853861967, 0.69917279302646274, 0.77632748534275298], + [0.56255515357219343, 0.69567278381629649, 0.77540359142309845], + [0.55758940419605174, 0.69215911458254054, 0.7745041337932782], + [0.55268450589347129, 0.68863194515166382, 0.7736279426902245], + [0.54784098153018634, 0.68509142218509878, 0.77277386473440868], + [0.54305932424018233, 0.68153767253065878, 0.77194079697835083], + [0.53834015575176275, 0.67797081129095405, 0.77112734439057717], + [0.53368389147728401, 0.67439093705212727, 0.7703325054879735], + [0.529090861832473, 0.67079812302806219, 0.76955552292313134], + [0.52456151470593582, 0.66719242996142225, 0.76879541714230948], + [0.52009627392235558, 0.66357391434030388, 0.76805119403344102], + [0.5156955988596057, 0.65994260812897998, 0.76732191489596169], + [0.51135992541601927, 0.65629853981831865, 0.76660663780645333], + [0.50708969576451657, 0.65264172403146448, 0.76590445660835849], + [0.5028853540415561, 0.64897216734095264, 0.76521446718174913], + [0.49874733661356069, 0.6452898684900934, 0.76453578734180083], + [0.4946761847863938, 0.64159484119504429, 0.76386719002130909], + [0.49067224938561221, 0.63788704858847078, 0.76320812763163837], + [0.4867359599430568, 0.63416646251100506, 0.76255780085924041], + [0.4828677867260272, 0.6304330455306234, 0.76191537149895305], + [0.47906816236197386, 0.62668676251860134, 0.76128000375662419], + [0.47533752394906287, 0.62292757283835809, 0.76065085571817748], + [0.47167629518877091, 0.61915543242884641, 0.76002709227883047], + [0.46808490970531597, 0.61537028695790286, 0.75940789891092741], + [0.46456376716303932, 0.61157208822864151, 0.75879242623025811], + [0.46111326647023881, 0.607760777169989, 0.75817986436807139], + [0.45773377230160567, 0.60393630046586455, 0.75756936901859162], + [0.45442563977552913, 0.60009859503858665, 0.75696013660606487], + [0.45118918687617743, 0.59624762051353541, 0.75635120643246645], + [0.44802470933589172, 0.59238331452146575, 0.75574176474107924], + [0.44493246854215379, 0.5885055998308617, 0.7551311041857901], + [0.44191271766696399, 0.58461441100175571, 0.75451838884410671], + [0.43896563958048396, 0.58070969241098491, 0.75390276208285945], + [0.43609138958356369, 0.57679137998186081, 0.7532834105961016], + [0.43329008867358393, 0.57285941625606673, 0.75265946532566674], + [0.43056179073057571, 0.56891374572457176, 0.75203008099312696], + [0.42790652284925834, 0.5649543060909209, 0.75139443521914839], + [0.42532423665011354, 0.56098104959950301, 0.75075164989005116], + [0.42281485675772662, 0.55699392126996583, 0.75010086988227642], + [0.42037822361396326, 0.55299287158108168, 0.7494412559451894], + [0.41801414079233629, 0.54897785421888889, 0.74877193167001121], + [0.4157223260454232, 0.54494882715350401, 0.74809204459000522], + [0.41350245743314729, 0.54090574771098476, 0.74740073297543086], + [0.41135414697304568, 0.53684857765005933, 0.74669712855065784], + [0.4092768899914751, 0.53277730177130322, 0.74598030635707824], + [0.40727018694219069, 0.52869188011057411, 0.74524942637581271], + [0.40533343789303178, 0.52459228174983119, 0.74450365836708132], + [0.40346600333905397, 0.52047847653840029, 0.74374215223567086], + [0.40166714010896104, 0.51635044969688759, 0.7429640345324835], + [0.39993606933454834, 0.51220818143218516, 0.74216844571317986], + [0.3982719152586337, 0.50805166539276136, 0.74135450918099721], + [0.39667374905665609, 0.50388089053847973, 0.74052138580516735], + [0.39514058808207631, 0.49969585326377758, 0.73966820211715711], + [0.39367135736822567, 0.49549655777451179, 0.738794102296364], + [0.39226494876209317, 0.49128300332899261, 0.73789824784475078], + [0.39092017571994903, 0.48705520251223039, 0.73697977133881254], + [0.38963580160340855, 0.48281316715123496, 0.73603782546932739], + [0.38841053300842432, 0.47855691131792805, 0.73507157641157261], + [0.38724301459330251, 0.47428645933635388, 0.73408016787854391], + [0.38613184178892102, 0.4700018340988123, 0.7330627749243106], + [0.38507556793651387, 0.46570306719930193, 0.73201854033690505], + [0.38407269378943537, 0.46139018782416635, 0.73094665432902683], + [0.38312168084402748, 0.45706323581407199, 0.72984626791353258], + [0.38222094988570376, 0.45272225034283325, 0.72871656144003782], + [0.38136887930454161, 0.44836727669277859, 0.72755671317141346], + [0.38056380696565623, 0.44399837208633719, 0.72636587045135315], + [0.37980403744848751, 0.43961558821222629, 0.72514323778761092], + [0.37908789283110761, 0.43521897612544935, 0.72388798691323131], + [0.378413635091359, 0.43080859411413064, 0.72259931993061044], + [0.37777949753513729, 0.4263845142616835, 0.72127639993530235], + [0.37718371844251231, 0.42194680223454828, 0.71991841524475775], + [0.37662448930806297, 0.41749553747893614, 0.71852454736176108], + [0.37610001286385814, 0.41303079952477062, 0.71709396919920232], + [0.37560846919442398, 0.40855267638072096, 0.71562585091587549], + [0.37514802505380473, 0.4040612609993941, 0.7141193695725726], + [0.37471686019302231, 0.3995566498711684, 0.71257368516500463], + [0.37431313199312338, 0.39503894828283309, 0.71098796522377461], + [0.37393499330475782, 0.39050827529375831, 0.70936134293478448], + [0.3735806215098284, 0.38596474386057539, 0.70769297607310577], + [0.37324816143326384, 0.38140848555753937, 0.70598200974806036], + [0.37293578646665032, 0.37683963835219841, 0.70422755780589941], + [0.37264166757849604, 0.37225835004836849, 0.7024287314570723], + [0.37236397858465387, 0.36766477862108266, 0.70058463496520773], + [0.37210089702443822, 0.36305909736982378, 0.69869434615073722], + [0.3718506155898596, 0.35844148285875221, 0.69675695810256544], + [0.37161133234400479, 0.3538121372967869, 0.69477149919380887], + [0.37138124223736607, 0.34917126878479027, 0.69273703471928827], + [0.37115856636209105, 0.34451911410230168, 0.69065253586464992], + [0.37094151551337329, 0.33985591488818123, 0.68851703379505125], + [0.37072833279422668, 0.33518193808489577, 0.68632948169606767], + [0.37051738634484427, 0.33049741244307851, 0.68408888788857214], + [0.37030682071842685, 0.32580269697872455, 0.68179411684486679], + [0.37009487130772695, 0.3210981375964933, 0.67944405399056851], + [0.36987980329025361, 0.31638410101153364, 0.67703755438090574], + [0.36965987626565955, 0.31166098762951971, 0.67457344743419545], + [0.36943334591276228, 0.30692923551862339, 0.67205052849120617], + [0.36919847837592484, 0.30218932176507068, 0.66946754331614522], + [0.36895355306596778, 0.29744175492366276, 0.66682322089824264], + [0.36869682231895268, 0.29268709856150099, 0.66411625298236909], + [0.36842655638020444, 0.28792596437778462, 0.66134526910944602], + [0.36814101479899719, 0.28315901221182987, 0.65850888806972308], + [0.36783843696531082, 0.27838697181297761, 0.65560566838453704], + [0.36751707094367697, 0.27361063317090978, 0.65263411711618635], + [0.36717513650699446, 0.26883085667326956, 0.64959272297892245], + [0.36681085540107988, 0.26404857724525643, 0.64647991652908243], + [0.36642243251550632, 0.25926481158628106, 0.64329409140765537], + [0.36600853966739794, 0.25448043878086224, 0.64003361803368586], + [0.36556698373538982, 0.24969683475296395, 0.63669675187488584], + [0.36509579845886808, 0.24491536803550484, 0.63328173520055586], + [0.36459308890125008, 0.24013747024823828, 0.62978680155026101], + [0.36405693022088509, 0.23536470386204195, 0.62621013451953023], + [0.36348537610385145, 0.23059876218396419, 0.62254988622392882], + [0.36287643560041027, 0.22584149293287031, 0.61880417410823019], + [0.36222809558295926, 0.22109488427338303, 0.61497112346096128], + [0.36153829010998356, 0.21636111429594002, 0.61104880679640927], + [0.36080493826624654, 0.21164251793458128, 0.60703532172064711], + [0.36002681809096376, 0.20694122817889948, 0.60292845431916875], + [0.35920088560930186, 0.20226037920758122, 0.5987265295935138], + [0.35832489966617809, 0.197602942459778, 0.59442768517501066], + [0.35739663292915563, 0.19297208197842461, 0.59003011251063131], + [0.35641381143126327, 0.18837119869242164, 0.5855320765920552], + [0.35537415306906722, 0.18380392577704466, 0.58093191431832802], + [0.35427534960663759, 0.17927413271618647, 0.57622809660668717], + [0.35311574421123737, 0.17478570377561287, 0.57141871523555288], + [0.35189248608873791, 0.17034320478524959, 0.56650284911216653], + [0.35060304441931012, 0.16595129984720861, 0.56147964703993225], + [0.34924513554955644, 0.16161477763045118, 0.55634837474163779], + [0.34781653238777782, 0.15733863511152979, 0.55110853452703257], + [0.34631507175793091, 0.15312802296627787, 0.5457599924248665], + [0.34473901574536375, 0.14898820589826409, 0.54030245920406539], + [0.34308600291572294, 0.14492465359918028, 0.53473704282067103], + [0.34135411074506483, 0.1409427920655632, 0.52906500940336754], + [0.33954168752669694, 0.13704801896718169, 0.52328797535085236], + [0.33764732090671112, 0.13324562282438077, 0.51740807573979475], + [0.33566978565015315, 0.12954074251271822, 0.51142807215168951], + [0.33360804901486002, 0.12593818301005921, 0.50535164796654897], + [0.33146154891145124, 0.12244245263391232, 0.49918274588431072], + [0.32923005203231409, 0.11905764321981127, 0.49292595612342666], + [0.3269137124539796, 0.1157873496841953, 0.48658646495697461], + [0.32451307931207785, 0.11263459791730848, 0.48017007211645196], + [0.32202882276069322, 0.10960114111258401, 0.47368494725726878], + [0.31946262395497965, 0.10668879882392659, 0.46713728801395243], + [0.31681648089023501, 0.10389861387653518, 0.46053414662739794], + [0.31409278414755532, 0.10123077676403242, 0.45388335612058467], + [0.31129434479712365, 0.098684771934052201, 0.44719313715161618], + [0.30842444457210105, 0.096259385340577736, 0.44047194882050544], + [0.30548675819945936, 0.093952764840823738, 0.43372849999361113], + [0.30248536364574252, 0.091761187397303601, 0.42697404043749887], + [0.29942483960214772, 0.089682253716750038, 0.42021619665853854], + [0.29631000388905288, 0.087713250960463951, 0.41346259134143476], + [0.29314593096985248, 0.085850656889620708, 0.40672178082365834], + [0.28993792445176608, 0.08409078829085731, 0.40000214725256295], + [0.28669151388283165, 0.082429873848480689, 0.39331182532243375], + [0.28341239797185225, 0.080864153365499375, 0.38665868550105914], + [0.28010638576975472, 0.079389994802261526, 0.38005028528138707], + [0.27677939615815589, 0.078003941033788216, 0.37349382846504675], + [0.27343739342450812, 0.076702800237496066, 0.36699616136347685], + [0.27008637749114051, 0.075483675584275545, 0.36056376228111864], + [0.26673233211995284, 0.074344018028546205, 0.35420276066240958], + [0.26338121807151404, 0.073281657939897077, 0.34791888996380105], + [0.26003895187439957, 0.072294781043362205, 0.3417175669546984], + [0.25671191651083902, 0.071380106242082242, 0.33560648984600089], + [0.25340685873736807, 0.070533582926851829, 0.3295945757321303], + [0.25012845306199383, 0.069758206429106989, 0.32368100685760637], + [0.24688226237958999, 0.069053639449204451, 0.31786993834254956], + [0.24367372557466271, 0.068419855150922693, 0.31216524050888372], + [0.24050813332295939, 0.067857103814855602, 0.30657054493678321], + [0.23739062429054825, 0.067365888050555517, 0.30108922184065873], + [0.23433055727563878, 0.066935599661639394, 0.29574009929867601], + [0.23132955273021344, 0.066576186939090592, 0.29051361067988485], + [0.2283917709422868, 0.06628997924139618, 0.28541074411068496], + [0.22552164337737857, 0.066078173119395595, 0.28043398847505197], + [0.22272706739121817, 0.065933790675651943, 0.27559714652053702], + [0.22001251100779617, 0.065857918918907604, 0.27090279994325861], + [0.21737845072382705, 0.065859661233562045, 0.26634209349669508], + [0.21482843531473683, 0.065940385613778491, 0.26191675992376573], + [0.21237411048541005, 0.066085024661758446, 0.25765165093569542], + [0.21001214221188125, 0.066308573918947178, 0.2535289048041211], + [0.2077442377448806, 0.06661453200418091, 0.24954644291943817], + [0.20558051999470117, 0.066990462397868739, 0.24572497420147632], + [0.20352007949514977, 0.067444179612424215, 0.24205576625191821], + [0.20156133764129841, 0.067983271026200248, 0.23852974228695395], + [0.19971571438603364, 0.068592710553704722, 0.23517094067076993], + [0.19794834061899208, 0.069314066071660657, 0.23194647381302336], + [0.1960826032659409, 0.070321227242423623, 0.22874673279569585], + [0.19410351363791453, 0.071608304856891569, 0.22558727307410353], + [0.19199449184606268, 0.073182830649273306, 0.22243385243433622], + [0.18975853639094634, 0.075019861862143766, 0.2193005075652994], + [0.18739228342697645, 0.077102096899588329, 0.21618875376309582], + [0.18488035509396164, 0.079425730279723883, 0.21307651648984993], + [0.18774482037046955, 0.077251588468039312, 0.21387448578597812], + [0.19049578401722037, 0.075311278416787641, 0.2146562337112265], + [0.1931548636579131, 0.073606819040117955, 0.21542362939081539], + [0.19571853588267552, 0.072157781039602742, 0.21617499187076789], + [0.19819343656336558, 0.070974625252738788, 0.21690975060032436], + [0.20058760685133747, 0.070064576149984209, 0.21762721310371608], + [0.20290365333558247, 0.069435248580458964, 0.21833167885096033], + [0.20531725273301316, 0.068919592266397572, 0.21911516689288835], + [0.20785704662965598, 0.068484398797025281, 0.22000133917653536], + [0.21052882914958676, 0.06812195249816172, 0.22098759107715404], + [0.2133313859647627, 0.067830148426026665, 0.22207043213024291], + [0.21625279838647882, 0.067616330270516389, 0.22324568672294431], + [0.21930503925136402, 0.067465786362940039, 0.22451023616807558], + [0.22247308588973624, 0.067388214053092838, 0.22585960379408354], + [0.2257539681670791, 0.067382132300147474, 0.22728984778098055], + [0.22915620278592841, 0.067434730871152565, 0.22879681433956656], + [0.23266299920501882, 0.067557104388479783, 0.23037617493752832], + [0.23627495835774248, 0.06774359820987802, 0.23202360805926608], + [0.23999586188690308, 0.067985029964779953, 0.23373434258507808], + [0.24381149720247919, 0.068289851529011875, 0.23550427698321885], + [0.24772092990501099, 0.068653337909486523, 0.2373288009471749], + [0.25172899728289466, 0.069064630826035506, 0.23920260612763083], + [0.25582135547481771, 0.06953231029187984, 0.24112190491594204], + [0.25999463887892144, 0.070053855603861875, 0.24308218808684579], + [0.26425512207060942, 0.070616595622995437, 0.24507758869355967], + [0.26859095948172862, 0.071226716277922458, 0.24710443563450618], + [0.27299701518897301, 0.071883555446163511, 0.24915847093232929], + [0.27747150809142801, 0.072582969899254779, 0.25123493995942769], + [0.28201746297366942, 0.073315693214040967, 0.25332800295084507], + [0.28662309235899847, 0.074088460826808866, 0.25543478673717029], + [0.29128515387578635, 0.074899049847466703, 0.25755101595750435], + [0.2960004726065818, 0.075745336000958424, 0.25967245030364566], + [0.30077276812918691, 0.076617824336164764, 0.26179294097819672], + [0.30559226007249934, 0.077521963107537312, 0.26391006692119662], + [0.31045520848595526, 0.078456871676182177, 0.2660200572779356], + [0.31535870009205808, 0.079420997315243186, 0.26811904076941961], + [0.32029986557994061, 0.080412994737554838, 0.27020322893039511], + [0.32527888860401261, 0.081428390076546092, 0.27226772884656186], + [0.33029174471181438, 0.08246763389003825, 0.27430929404579435], + [0.33533353224455448, 0.083532434119003962, 0.27632534356790039], + [0.34040164359597463, 0.084622236191702671, 0.27831254595259397], + [0.34549355713871799, 0.085736654965126335, 0.28026769921081435], + [0.35060678246032478, 0.08687555176033529, 0.28218770540182386], + [0.35573889947341125, 0.088038974350243354, 0.2840695897279818], + [0.36088752387578377, 0.089227194362745205, 0.28591050458531014], + [0.36605031412464006, 0.090440685427697898, 0.2877077458811747], + [0.37122508431309342, 0.091679997480262732, 0.28945865397633169], + [0.3764103053221462, 0.092945198093777909, 0.29116024157313919], + [0.38160247377467543, 0.094238731263712183, 0.29281107506269488], + [0.38679939079544168, 0.09556181960083443, 0.29440901248173756], + [0.39199887556812907, 0.09691583650296684, 0.29595212005509081], + [0.39719876876325577, 0.098302320968278623, 0.29743856476285779], + [0.40239692379737496, 0.099722930314950553, 0.29886674369733968], + [0.40759120392688708, 0.10117945586419633, 0.30023519507728602], + [0.41277985630360303, 0.1026734006932461, 0.30154226437468967], + [0.41796105205173684, 0.10420644885760968, 0.30278652039631843], + [0.42313214269556043, 0.10578120994917611, 0.3039675809469457], + [0.42829101315789753, 0.1073997763055258, 0.30508479060294547], + [0.4334355841041439, 0.1090642347484701, 0.30613767928289148], + [0.43856378187931538, 0.11077667828375456, 0.30712600062348083], + [0.44367358645071275, 0.11253912421257944, 0.30804973095465449], + [0.44876299173174822, 0.11435355574622549, 0.30890905921943196], + [0.45383005086999889, 0.11622183788331528, 0.30970441249844921], + [0.45887288947308297, 0.11814571137706886, 0.31043636979038808], + [0.46389102840284874, 0.12012561256850712, 0.31110343446582983], + [0.46888111384598413, 0.12216445576414045, 0.31170911458932665], + [0.473841437035254, 0.12426354237989065, 0.31225470169927194], + [0.47877034239726296, 0.12642401401409453, 0.31274172735821959], + [0.48366628618847957, 0.12864679022013889, 0.31317188565991266], + [0.48852847371852987, 0.13093210934893723, 0.31354553695453014], + [0.49335504375145617, 0.13328091630401023, 0.31386561956734976], + [0.49814435462074153, 0.13569380302451714, 0.314135190862664], + [0.50289524974970612, 0.13817086581280427, 0.31435662153833671], + [0.50760681181053691, 0.14071192654913128, 0.31453200120082569], + [0.51227835105321762, 0.14331656120063752, 0.3146630922831542], + [0.51690848800544464, 0.14598463068714407, 0.31475407592280041], + [0.52149652863229956, 0.14871544765633712, 0.31480767954534428], + [0.52604189625477482, 0.15150818660835483, 0.31482653406646727], + [0.53054420489856446, 0.15436183633886777, 0.31481299789187128], + [0.5350027976174474, 0.15727540775107324, 0.31477085207396532], + [0.53941736649199057, 0.16024769309971934, 0.31470295028655965], + [0.54378771313608565, 0.16327738551419116, 0.31461204226295625], + [0.54811370033467621, 0.1663630904279047, 0.31450102990914708], + [0.55239521572711914, 0.16950338809328983, 0.31437291554615371], + [0.55663229034969341, 0.17269677158182117, 0.31423043195101424], + [0.56082499039117173, 0.17594170887918095, 0.31407639883970623], + [0.56497343529017696, 0.17923664950367169, 0.3139136046337036], + [0.56907784784011428, 0.18258004462335425, 0.31374440956796529], + [0.57313845754107873, 0.18597036007065024, 0.31357126868520002], + [0.57715550812992045, 0.18940601489760422, 0.31339704333572083], + [0.58112932761586555, 0.19288548904692518, 0.31322399394183942], + [0.58506024396466882, 0.19640737049066315, 0.31305401163732732], + [0.58894861935544707, 0.19997020971775276, 0.31288922211590126], + [0.59279480536520257, 0.20357251410079796, 0.31273234839304942], + [0.59659918109122367, 0.207212956082026, 0.31258523031121233], + [0.60036213010411577, 0.21089030138947745, 0.31244934410414688], + [0.60408401696732739, 0.21460331490206347, 0.31232652641170694], + [0.60776523994818654, 0.21835070166659282, 0.31221903291870201], + [0.6114062072731884, 0.22213124697023234, 0.31212881396435238], + [0.61500723236391375, 0.22594402043981826, 0.31205680685765741], + [0.61856865258877192, 0.22978799249179921, 0.31200463838728931], + [0.62209079821082613, 0.2336621873300741, 0.31197383273627388], + [0.62557416500434959, 0.23756535071152696, 0.31196698314912269], + [0.62901892016985872, 0.24149689191922535, 0.31198447195645718], + [0.63242534854210275, 0.24545598775548677, 0.31202765974624452], + [0.6357937104834237, 0.24944185818822678, 0.31209793953300591], + [0.6391243387840212, 0.25345365461983138, 0.31219689612063978], + [0.642417577481186, 0.257490519876798, 0.31232631707560987], + [0.64567349382645434, 0.26155203161615281, 0.31248673753935263], + [0.64889230169458245, 0.26563755336209077, 0.31267941819570189], + [0.65207417290277303, 0.26974650525236699, 0.31290560605819168], + [0.65521932609327127, 0.27387826652410152, 0.3131666792687211], + [0.6583280801134499, 0.27803210957665631, 0.3134643447952643], + [0.66140037532601781, 0.28220778870555907, 0.31379912926498488], + [0.66443632469878844, 0.28640483614256179, 0.31417223403606975], + [0.66743603766369131, 0.29062280081258873, 0.31458483752056837], + [0.67039959547676198, 0.29486126309253047, 0.31503813956872212], + [0.67332725564817331, 0.29911962764489264, 0.31553372323982209], + [0.67621897924409746, 0.30339762792450425, 0.3160724937230589], + [0.67907474028157344, 0.30769497879760166, 0.31665545668946665], + [0.68189457150944521, 0.31201133280550686, 0.31728380489244951], + [0.68467850942494535, 0.31634634821222207, 0.31795870784057567], + [0.68742656435169625, 0.32069970535138104, 0.31868137622277692], + [0.6901389321505248, 0.32507091815606004, 0.31945332332898302], + [0.69281544846764931, 0.32945984647042675, 0.3202754315314667], + [0.69545608346891119, 0.33386622163232865, 0.32114884306985791], + [0.6980608153581771, 0.33828976326048621, 0.32207478855218091], + [0.70062962477242097, 0.34273019305341756, 0.32305449047765694], + [0.70316249458814151, 0.34718723719597999, 0.32408913679491225], + [0.70565951122610093, 0.35166052978120937, 0.32518014084085567], + [0.70812059568420482, 0.35614985523380299, 0.32632861885644465], + [0.7105456546582587, 0.36065500290840113, 0.32753574162788762], + [0.71293466839773467, 0.36517570519856757, 0.3288027427038317], + [0.71528760614847287, 0.36971170225223449, 0.3301308728723546], + [0.71760444908133847, 0.37426272710686193, 0.33152138620958932], + [0.71988521490549851, 0.37882848839337313, 0.33297555200245399], + [0.7221299918421461, 0.38340864508963057, 0.33449469983585844], + [0.72433865647781592, 0.38800301593162145, 0.33607995965691828], + [0.72651122900227549, 0.3926113126792577, 0.3377325942005665], + [0.72864773856716547, 0.39723324476747235, 0.33945384341064017], + [0.73074820754845171, 0.401868526884681, 0.3412449533046818], + [0.73281270506268747, 0.4065168468778026, 0.34310715173410822], + [0.73484133598564938, 0.41117787004519513, 0.34504169470809071], + [0.73683422173585866, 0.41585125850290111, 0.34704978520758401], + [0.73879140024599266, 0.42053672992315327, 0.34913260148542435], + [0.74071301619506091, 0.4252339389526239, 0.35129130890802607], + [0.7425992159973317, 0.42994254036133867, 0.35352709245374592], + [0.74445018676570673, 0.43466217184617112, 0.35584108091122535], + [0.74626615789163442, 0.43939245044973502, 0.35823439142300639], + [0.74804739275559562, 0.44413297780351974, 0.36070813602540136], + [0.74979420547170472, 0.44888333481548809, 0.36326337558360278], + [0.75150685045891663, 0.45364314496866825, 0.36590112443835765], + [0.75318566369046569, 0.45841199172949604, 0.36862236642234769], + [0.75483105066959544, 0.46318942799460555, 0.3714280448394211], + [0.75644341577140706, 0.46797501437948458, 0.37431909037543515], + [0.75802325538455839, 0.4727682731566229, 0.37729635531096678], + [0.75957111105340058, 0.47756871222057079, 0.380360657784311], + [0.7610876378057071, 0.48237579130289127, 0.38351275723852291], + [0.76257333554052609, 0.48718906673415824, 0.38675335037837993], + [0.76402885609288662, 0.49200802533379656, 0.39008308392311997], + [0.76545492593330511, 0.49683212909727231, 0.39350254000115381], + [0.76685228950643891, 0.5016608471009063, 0.39701221751773474], + [0.76822176599735303, 0.50649362371287909, 0.40061257089416885], + [0.7695642334401418, 0.5113298901696085, 0.40430398069682483], + [0.77088091962302474, 0.51616892643469103, 0.40808667584648967], + [0.77217257229605551, 0.5210102658711383, 0.41196089987122869], + [0.77344021829889886, 0.52585332093451564, 0.41592679539764366], + [0.77468494746063199, 0.53069749384776732, 0.41998440356963762], + [0.77590790730685699, 0.53554217882461186, 0.42413367909988375], + [0.7771103295521099, 0.54038674910561235, 0.42837450371258479], + [0.77829345807633121, 0.54523059488426595, 0.432706647838971], + [0.77945862731506643, 0.55007308413977274, 0.43712979856444761], + [0.78060774749483774, 0.55491335744890613, 0.44164332426364639], + [0.78174180478981836, 0.55975098052594863, 0.44624687186865436], + [0.78286225264440912, 0.56458533111166875, 0.45093985823706345], + [0.78397060836414478, 0.56941578326710418, 0.45572154742892063], + [0.78506845019606841, 0.5742417003617839, 0.46059116206904965], + [0.78615737132332963, 0.5790624629815756, 0.46554778281918402], + [0.78723904108188347, 0.58387743744557208, 0.47059039582133383], + [0.78831514045623963, 0.58868600173562435, 0.47571791879076081], + [0.78938737766251943, 0.5934875421745599, 0.48092913815357724], + [0.79045776847727878, 0.59828134277062461, 0.48622257801969754], + [0.79152832843475607, 0.60306670593147205, 0.49159667021646397], + [0.79260034304237448, 0.60784322087037024, 0.49705020621532009], + [0.79367559698664958, 0.61261029334072192, 0.50258161291269432], + [0.79475585972654039, 0.61736734400220705, 0.50818921213102985], + [0.79584292379583765, 0.62211378808451145, 0.51387124091909786], + [0.79693854719951607, 0.62684905679296699, 0.5196258425240281], + [0.79804447815136637, 0.63157258225089552, 0.52545108144834785], + [0.7991624518501963, 0.63628379372029187, 0.53134495942561433], + [0.80029415389753977, 0.64098213306749863, 0.53730535185141037], + [0.80144124292560048, 0.64566703459218766, 0.5433300863249918], + [0.80260531146112946, 0.65033793748103852, 0.54941691584603647], + [0.80378792531077625, 0.65499426549472628, 0.55556350867083815], + [0.80499054790810298, 0.65963545027564163, 0.56176745110546977], + [0.80621460526927058, 0.66426089585282289, 0.56802629178649788], + [0.8074614045096935, 0.6688700095398864, 0.57433746373459582], + [0.80873219170089694, 0.67346216702194517, 0.58069834805576737], + [0.81002809466520687, 0.67803672673971815, 0.58710626908082753], + [0.81135014011763329, 0.68259301546243389, 0.59355848909050757], + [0.81269922039881493, 0.68713033714618876, 0.60005214820435104], + [0.81407611046993344, 0.69164794791482131, 0.6065843782630862], + [0.81548146627279483, 0.69614505508308089, 0.61315221209322646], + [0.81691575775055891, 0.70062083014783982, 0.61975260637257923], + [0.81837931164498223, 0.70507438189635097, 0.62638245478933297], + [0.81987230650455289, 0.70950474978787481, 0.63303857040067113], + [0.8213947205565636, 0.7139109141951604, 0.63971766697672761], + [0.82294635110428427, 0.71829177331290062, 0.6464164243818421], + [0.8245268129450285, 0.72264614312088882, 0.65313137915422603], + [0.82613549710580259, 0.72697275518238258, 0.65985900156216504], + [0.8277716072353446, 0.73127023324078089, 0.66659570204682972], + [0.82943407816481474, 0.7355371221572935, 0.67333772009301907], + [0.83112163529096306, 0.73977184647638616, 0.68008125203631464], + [0.83283277185777982, 0.74397271817459876, 0.68682235874648545], + [0.8345656905566583, 0.7481379479992134, 0.69355697649863846], + [0.83631898844737929, 0.75226548952875261, 0.70027999028864962], + [0.83809123476131964, 0.75635314860808633, 0.70698561390212977], + [0.83987839884120874, 0.76039907199779677, 0.71367147811129228], + [0.84167750766845151, 0.76440101200982946, 0.72033299387284622], + [0.84348529222933699, 0.76835660399870176, 0.72696536998972039], + [0.84529810731955113, 0.77226338601044719, 0.73356368240541492], + [0.84711195507965098, 0.77611880236047159, 0.74012275762807056], + [0.84892245563117641, 0.77992021407650147, 0.74663719293664366], + [0.85072697023178789, 0.78366457342383888, 0.7530974636118285], + [0.85251907207708444, 0.78734936133548439, 0.7594994148789691], + [0.85429219611470464, 0.79097196777091994, 0.76583801477914104], + [0.85604022314725403, 0.79452963601550608, 0.77210610037674143], + [0.85775662943504905, 0.79801963142713928, 0.77829571667247499], + [0.8594346370300241, 0.8014392309950078, 0.78439788751383921], + [0.86107117027565516, 0.80478517909812231, 0.79039529663736285], + [0.86265601051127572, 0.80805523804261525, 0.796282666437655], + [0.86418343723941027, 0.81124644224653542, 0.80204612696863953], + [0.86564934325605325, 0.81435544067514909, 0.80766972324164554], + [0.86705314907048503, 0.81737804041911244, 0.81313419626911398], + [0.86839954695818633, 0.82030875512181523, 0.81841638963128993], + [0.86969131502613806, 0.82314158859569164, 0.82350476683173168], + [0.87093846717297507, 0.82586857889438514, 0.82838497261149613], + [0.87215331978454325, 0.82848052823709672, 0.8330486712880828], + [0.87335171360916275, 0.83096715251272624, 0.83748851001197089], + [0.87453793320260187, 0.83331972948645461, 0.84171925358069011], + [0.87571458709961403, 0.8355302318472394, 0.84575537519027078], + [0.87687848451614692, 0.83759238071186537, 0.84961373549150254], + [0.87802298436649007, 0.83950165618540074, 0.85330645352458923], + [0.87913244240792765, 0.84125554884475906, 0.85685572291039636], + [0.88019293315695812, 0.84285224824778615, 0.86027399927156634], + [0.88119169871341951, 0.84429066717717349, 0.86356595168669881], + [0.88211542489401606, 0.84557007254559347, 0.86673765046233331], + [0.88295168595448525, 0.84668970275699273, 0.86979617048190971], + [0.88369127145898041, 0.84764891761519268, 0.87274147101441557], + [0.88432713054113543, 0.84844741572055415, 0.87556785228242973], + [0.88485138159908572, 0.84908426422893801, 0.87828235285372469], + [0.88525897972630474, 0.84955892810989209, 0.88088414794024839], + [0.88554714811952384, 0.84987174283631584, 0.88336206121170946], + [0.88571155122845646, 0.85002186115856315, 0.88572538990087124]] + +_twilight_shifted_data = (_twilight_data[len(_twilight_data)//2:] + + _twilight_data[:len(_twilight_data)//2]) +_twilight_shifted_data.reverse() +_turbo_data = [[0.18995, 0.07176, 0.23217], + [0.19483, 0.08339, 0.26149], + [0.19956, 0.09498, 0.29024], + [0.20415, 0.10652, 0.31844], + [0.20860, 0.11802, 0.34607], + [0.21291, 0.12947, 0.37314], + [0.21708, 0.14087, 0.39964], + [0.22111, 0.15223, 0.42558], + [0.22500, 0.16354, 0.45096], + [0.22875, 0.17481, 0.47578], + [0.23236, 0.18603, 0.50004], + [0.23582, 0.19720, 0.52373], + [0.23915, 0.20833, 0.54686], + [0.24234, 0.21941, 0.56942], + [0.24539, 0.23044, 0.59142], + [0.24830, 0.24143, 0.61286], + [0.25107, 0.25237, 0.63374], + [0.25369, 0.26327, 0.65406], + [0.25618, 0.27412, 0.67381], + [0.25853, 0.28492, 0.69300], + [0.26074, 0.29568, 0.71162], + [0.26280, 0.30639, 0.72968], + [0.26473, 0.31706, 0.74718], + [0.26652, 0.32768, 0.76412], + [0.26816, 0.33825, 0.78050], + [0.26967, 0.34878, 0.79631], + [0.27103, 0.35926, 0.81156], + [0.27226, 0.36970, 0.82624], + [0.27334, 0.38008, 0.84037], + [0.27429, 0.39043, 0.85393], + [0.27509, 0.40072, 0.86692], + [0.27576, 0.41097, 0.87936], + [0.27628, 0.42118, 0.89123], + [0.27667, 0.43134, 0.90254], + [0.27691, 0.44145, 0.91328], + [0.27701, 0.45152, 0.92347], + [0.27698, 0.46153, 0.93309], + [0.27680, 0.47151, 0.94214], + [0.27648, 0.48144, 0.95064], + [0.27603, 0.49132, 0.95857], + [0.27543, 0.50115, 0.96594], + [0.27469, 0.51094, 0.97275], + [0.27381, 0.52069, 0.97899], + [0.27273, 0.53040, 0.98461], + [0.27106, 0.54015, 0.98930], + [0.26878, 0.54995, 0.99303], + [0.26592, 0.55979, 0.99583], + [0.26252, 0.56967, 0.99773], + [0.25862, 0.57958, 0.99876], + [0.25425, 0.58950, 0.99896], + [0.24946, 0.59943, 0.99835], + [0.24427, 0.60937, 0.99697], + [0.23874, 0.61931, 0.99485], + [0.23288, 0.62923, 0.99202], + [0.22676, 0.63913, 0.98851], + [0.22039, 0.64901, 0.98436], + [0.21382, 0.65886, 0.97959], + [0.20708, 0.66866, 0.97423], + [0.20021, 0.67842, 0.96833], + [0.19326, 0.68812, 0.96190], + [0.18625, 0.69775, 0.95498], + [0.17923, 0.70732, 0.94761], + [0.17223, 0.71680, 0.93981], + [0.16529, 0.72620, 0.93161], + [0.15844, 0.73551, 0.92305], + [0.15173, 0.74472, 0.91416], + [0.14519, 0.75381, 0.90496], + [0.13886, 0.76279, 0.89550], + [0.13278, 0.77165, 0.88580], + [0.12698, 0.78037, 0.87590], + [0.12151, 0.78896, 0.86581], + [0.11639, 0.79740, 0.85559], + [0.11167, 0.80569, 0.84525], + [0.10738, 0.81381, 0.83484], + [0.10357, 0.82177, 0.82437], + [0.10026, 0.82955, 0.81389], + [0.09750, 0.83714, 0.80342], + [0.09532, 0.84455, 0.79299], + [0.09377, 0.85175, 0.78264], + [0.09287, 0.85875, 0.77240], + [0.09267, 0.86554, 0.76230], + [0.09320, 0.87211, 0.75237], + [0.09451, 0.87844, 0.74265], + [0.09662, 0.88454, 0.73316], + [0.09958, 0.89040, 0.72393], + [0.10342, 0.89600, 0.71500], + [0.10815, 0.90142, 0.70599], + [0.11374, 0.90673, 0.69651], + [0.12014, 0.91193, 0.68660], + [0.12733, 0.91701, 0.67627], + [0.13526, 0.92197, 0.66556], + [0.14391, 0.92680, 0.65448], + [0.15323, 0.93151, 0.64308], + [0.16319, 0.93609, 0.63137], + [0.17377, 0.94053, 0.61938], + [0.18491, 0.94484, 0.60713], + [0.19659, 0.94901, 0.59466], + [0.20877, 0.95304, 0.58199], + [0.22142, 0.95692, 0.56914], + [0.23449, 0.96065, 0.55614], + [0.24797, 0.96423, 0.54303], + [0.26180, 0.96765, 0.52981], + [0.27597, 0.97092, 0.51653], + [0.29042, 0.97403, 0.50321], + [0.30513, 0.97697, 0.48987], + [0.32006, 0.97974, 0.47654], + [0.33517, 0.98234, 0.46325], + [0.35043, 0.98477, 0.45002], + [0.36581, 0.98702, 0.43688], + [0.38127, 0.98909, 0.42386], + [0.39678, 0.99098, 0.41098], + [0.41229, 0.99268, 0.39826], + [0.42778, 0.99419, 0.38575], + [0.44321, 0.99551, 0.37345], + [0.45854, 0.99663, 0.36140], + [0.47375, 0.99755, 0.34963], + [0.48879, 0.99828, 0.33816], + [0.50362, 0.99879, 0.32701], + [0.51822, 0.99910, 0.31622], + [0.53255, 0.99919, 0.30581], + [0.54658, 0.99907, 0.29581], + [0.56026, 0.99873, 0.28623], + [0.57357, 0.99817, 0.27712], + [0.58646, 0.99739, 0.26849], + [0.59891, 0.99638, 0.26038], + [0.61088, 0.99514, 0.25280], + [0.62233, 0.99366, 0.24579], + [0.63323, 0.99195, 0.23937], + [0.64362, 0.98999, 0.23356], + [0.65394, 0.98775, 0.22835], + [0.66428, 0.98524, 0.22370], + [0.67462, 0.98246, 0.21960], + [0.68494, 0.97941, 0.21602], + [0.69525, 0.97610, 0.21294], + [0.70553, 0.97255, 0.21032], + [0.71577, 0.96875, 0.20815], + [0.72596, 0.96470, 0.20640], + [0.73610, 0.96043, 0.20504], + [0.74617, 0.95593, 0.20406], + [0.75617, 0.95121, 0.20343], + [0.76608, 0.94627, 0.20311], + [0.77591, 0.94113, 0.20310], + [0.78563, 0.93579, 0.20336], + [0.79524, 0.93025, 0.20386], + [0.80473, 0.92452, 0.20459], + [0.81410, 0.91861, 0.20552], + [0.82333, 0.91253, 0.20663], + [0.83241, 0.90627, 0.20788], + [0.84133, 0.89986, 0.20926], + [0.85010, 0.89328, 0.21074], + [0.85868, 0.88655, 0.21230], + [0.86709, 0.87968, 0.21391], + [0.87530, 0.87267, 0.21555], + [0.88331, 0.86553, 0.21719], + [0.89112, 0.85826, 0.21880], + [0.89870, 0.85087, 0.22038], + [0.90605, 0.84337, 0.22188], + [0.91317, 0.83576, 0.22328], + [0.92004, 0.82806, 0.22456], + [0.92666, 0.82025, 0.22570], + [0.93301, 0.81236, 0.22667], + [0.93909, 0.80439, 0.22744], + [0.94489, 0.79634, 0.22800], + [0.95039, 0.78823, 0.22831], + [0.95560, 0.78005, 0.22836], + [0.96049, 0.77181, 0.22811], + [0.96507, 0.76352, 0.22754], + [0.96931, 0.75519, 0.22663], + [0.97323, 0.74682, 0.22536], + [0.97679, 0.73842, 0.22369], + [0.98000, 0.73000, 0.22161], + [0.98289, 0.72140, 0.21918], + [0.98549, 0.71250, 0.21650], + [0.98781, 0.70330, 0.21358], + [0.98986, 0.69382, 0.21043], + [0.99163, 0.68408, 0.20706], + [0.99314, 0.67408, 0.20348], + [0.99438, 0.66386, 0.19971], + [0.99535, 0.65341, 0.19577], + [0.99607, 0.64277, 0.19165], + [0.99654, 0.63193, 0.18738], + [0.99675, 0.62093, 0.18297], + [0.99672, 0.60977, 0.17842], + [0.99644, 0.59846, 0.17376], + [0.99593, 0.58703, 0.16899], + [0.99517, 0.57549, 0.16412], + [0.99419, 0.56386, 0.15918], + [0.99297, 0.55214, 0.15417], + [0.99153, 0.54036, 0.14910], + [0.98987, 0.52854, 0.14398], + [0.98799, 0.51667, 0.13883], + [0.98590, 0.50479, 0.13367], + [0.98360, 0.49291, 0.12849], + [0.98108, 0.48104, 0.12332], + [0.97837, 0.46920, 0.11817], + [0.97545, 0.45740, 0.11305], + [0.97234, 0.44565, 0.10797], + [0.96904, 0.43399, 0.10294], + [0.96555, 0.42241, 0.09798], + [0.96187, 0.41093, 0.09310], + [0.95801, 0.39958, 0.08831], + [0.95398, 0.38836, 0.08362], + [0.94977, 0.37729, 0.07905], + [0.94538, 0.36638, 0.07461], + [0.94084, 0.35566, 0.07031], + [0.93612, 0.34513, 0.06616], + [0.93125, 0.33482, 0.06218], + [0.92623, 0.32473, 0.05837], + [0.92105, 0.31489, 0.05475], + [0.91572, 0.30530, 0.05134], + [0.91024, 0.29599, 0.04814], + [0.90463, 0.28696, 0.04516], + [0.89888, 0.27824, 0.04243], + [0.89298, 0.26981, 0.03993], + [0.88691, 0.26152, 0.03753], + [0.88066, 0.25334, 0.03521], + [0.87422, 0.24526, 0.03297], + [0.86760, 0.23730, 0.03082], + [0.86079, 0.22945, 0.02875], + [0.85380, 0.22170, 0.02677], + [0.84662, 0.21407, 0.02487], + [0.83926, 0.20654, 0.02305], + [0.83172, 0.19912, 0.02131], + [0.82399, 0.19182, 0.01966], + [0.81608, 0.18462, 0.01809], + [0.80799, 0.17753, 0.01660], + [0.79971, 0.17055, 0.01520], + [0.79125, 0.16368, 0.01387], + [0.78260, 0.15693, 0.01264], + [0.77377, 0.15028, 0.01148], + [0.76476, 0.14374, 0.01041], + [0.75556, 0.13731, 0.00942], + [0.74617, 0.13098, 0.00851], + [0.73661, 0.12477, 0.00769], + [0.72686, 0.11867, 0.00695], + [0.71692, 0.11268, 0.00629], + [0.70680, 0.10680, 0.00571], + [0.69650, 0.10102, 0.00522], + [0.68602, 0.09536, 0.00481], + [0.67535, 0.08980, 0.00449], + [0.66449, 0.08436, 0.00424], + [0.65345, 0.07902, 0.00408], + [0.64223, 0.07380, 0.00401], + [0.63082, 0.06868, 0.00401], + [0.61923, 0.06367, 0.00410], + [0.60746, 0.05878, 0.00427], + [0.59550, 0.05399, 0.00453], + [0.58336, 0.04931, 0.00486], + [0.57103, 0.04474, 0.00529], + [0.55852, 0.04028, 0.00579], + [0.54583, 0.03593, 0.00638], + [0.53295, 0.03169, 0.00705], + [0.51989, 0.02756, 0.00780], + [0.50664, 0.02354, 0.00863], + [0.49321, 0.01963, 0.00955], + [0.47960, 0.01583, 0.01055]] + + +cmaps = { + name: ListedColormap(data, name=name) for name, data in [ + ('magma', _magma_data), + ('inferno', _inferno_data), + ('plasma', _plasma_data), + ('viridis', _viridis_data), + ('cividis', _cividis_data), + ('twilight', _twilight_data), + ('twilight_shifted', _twilight_shifted_data), + ('turbo', _turbo_data), + ]} diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_color_data.py b/llava_next/lib/python3.10/site-packages/matplotlib/_color_data.py new file mode 100644 index 0000000000000000000000000000000000000000..44f97adbb76aeaec2578cedfe60219a3278fd2ca --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_color_data.py @@ -0,0 +1,1141 @@ +BASE_COLORS = { + 'b': (0, 0, 1), # blue + 'g': (0, 0.5, 0), # green + 'r': (1, 0, 0), # red + 'c': (0, 0.75, 0.75), # cyan + 'm': (0.75, 0, 0.75), # magenta + 'y': (0.75, 0.75, 0), # yellow + 'k': (0, 0, 0), # black + 'w': (1, 1, 1), # white +} + + +# These colors are from Tableau +TABLEAU_COLORS = { + 'tab:blue': '#1f77b4', + 'tab:orange': '#ff7f0e', + 'tab:green': '#2ca02c', + 'tab:red': '#d62728', + 'tab:purple': '#9467bd', + 'tab:brown': '#8c564b', + 'tab:pink': '#e377c2', + 'tab:gray': '#7f7f7f', + 'tab:olive': '#bcbd22', + 'tab:cyan': '#17becf', +} + + +# This mapping of color names -> hex values is taken from +# a survey run by Randall Munroe see: +# https://blog.xkcd.com/2010/05/03/color-survey-results/ +# for more details. The results are hosted at +# https://xkcd.com/color/rgb/ +# and also available as a text file at +# https://xkcd.com/color/rgb.txt +# +# License: https://creativecommons.org/publicdomain/zero/1.0/ +XKCD_COLORS = { + 'cloudy blue': '#acc2d9', + 'dark pastel green': '#56ae57', + 'dust': '#b2996e', + 'electric lime': '#a8ff04', + 'fresh green': '#69d84f', + 'light eggplant': '#894585', + 'nasty green': '#70b23f', + 'really light blue': '#d4ffff', + 'tea': '#65ab7c', + 'warm purple': '#952e8f', + 'yellowish tan': '#fcfc81', + 'cement': '#a5a391', + 'dark grass green': '#388004', + 'dusty teal': '#4c9085', + 'grey teal': '#5e9b8a', + 'macaroni and cheese': '#efb435', + 'pinkish tan': '#d99b82', + 'spruce': '#0a5f38', + 'strong blue': '#0c06f7', + 'toxic green': '#61de2a', + 'windows blue': '#3778bf', + 'blue blue': '#2242c7', + 'blue with a hint of purple': '#533cc6', + 'booger': '#9bb53c', + 'bright sea green': '#05ffa6', + 'dark green blue': '#1f6357', + 'deep turquoise': '#017374', + 'green teal': '#0cb577', + 'strong pink': '#ff0789', + 'bland': '#afa88b', + 'deep aqua': '#08787f', + 'lavender pink': '#dd85d7', + 'light moss green': '#a6c875', + 'light seafoam green': '#a7ffb5', + 'olive yellow': '#c2b709', + 'pig pink': '#e78ea5', + 'deep lilac': '#966ebd', + 'desert': '#ccad60', + 'dusty lavender': '#ac86a8', + 'purpley grey': '#947e94', + 'purply': '#983fb2', + 'candy pink': '#ff63e9', + 'light pastel green': '#b2fba5', + 'boring green': '#63b365', + 'kiwi green': '#8ee53f', + 'light grey green': '#b7e1a1', + 'orange pink': '#ff6f52', + 'tea green': '#bdf8a3', + 'very light brown': '#d3b683', + 'egg shell': '#fffcc4', + 'eggplant purple': '#430541', + 'powder pink': '#ffb2d0', + 'reddish grey': '#997570', + 'baby shit brown': '#ad900d', + 'liliac': '#c48efd', + 'stormy blue': '#507b9c', + 'ugly brown': '#7d7103', + 'custard': '#fffd78', + 'darkish pink': '#da467d', + 'deep brown': '#410200', + 'greenish beige': '#c9d179', + 'manilla': '#fffa86', + 'off blue': '#5684ae', + 'battleship grey': '#6b7c85', + 'browny green': '#6f6c0a', + 'bruise': '#7e4071', + 'kelley green': '#009337', + 'sickly yellow': '#d0e429', + 'sunny yellow': '#fff917', + 'azul': '#1d5dec', + 'darkgreen': '#054907', + 'green/yellow': '#b5ce08', + 'lichen': '#8fb67b', + 'light light green': '#c8ffb0', + 'pale gold': '#fdde6c', + 'sun yellow': '#ffdf22', + 'tan green': '#a9be70', + 'burple': '#6832e3', + 'butterscotch': '#fdb147', + 'toupe': '#c7ac7d', + 'dark cream': '#fff39a', + 'indian red': '#850e04', + 'light lavendar': '#efc0fe', + 'poison green': '#40fd14', + 'baby puke green': '#b6c406', + 'bright yellow green': '#9dff00', + 'charcoal grey': '#3c4142', + 'squash': '#f2ab15', + 'cinnamon': '#ac4f06', + 'light pea green': '#c4fe82', + 'radioactive green': '#2cfa1f', + 'raw sienna': '#9a6200', + 'baby purple': '#ca9bf7', + 'cocoa': '#875f42', + 'light royal blue': '#3a2efe', + 'orangeish': '#fd8d49', + 'rust brown': '#8b3103', + 'sand brown': '#cba560', + 'swamp': '#698339', + 'tealish green': '#0cdc73', + 'burnt siena': '#b75203', + 'camo': '#7f8f4e', + 'dusk blue': '#26538d', + 'fern': '#63a950', + 'old rose': '#c87f89', + 'pale light green': '#b1fc99', + 'peachy pink': '#ff9a8a', + 'rosy pink': '#f6688e', + 'light bluish green': '#76fda8', + 'light bright green': '#53fe5c', + 'light neon green': '#4efd54', + 'light seafoam': '#a0febf', + 'tiffany blue': '#7bf2da', + 'washed out green': '#bcf5a6', + 'browny orange': '#ca6b02', + 'nice blue': '#107ab0', + 'sapphire': '#2138ab', + 'greyish teal': '#719f91', + 'orangey yellow': '#fdb915', + 'parchment': '#fefcaf', + 'straw': '#fcf679', + 'very dark brown': '#1d0200', + 'terracota': '#cb6843', + 'ugly blue': '#31668a', + 'clear blue': '#247afd', + 'creme': '#ffffb6', + 'foam green': '#90fda9', + 'grey/green': '#86a17d', + 'light gold': '#fddc5c', + 'seafoam blue': '#78d1b6', + 'topaz': '#13bbaf', + 'violet pink': '#fb5ffc', + 'wintergreen': '#20f986', + 'yellow tan': '#ffe36e', + 'dark fuchsia': '#9d0759', + 'indigo blue': '#3a18b1', + 'light yellowish green': '#c2ff89', + 'pale magenta': '#d767ad', + 'rich purple': '#720058', + 'sunflower yellow': '#ffda03', + 'green/blue': '#01c08d', + 'leather': '#ac7434', + 'racing green': '#014600', + 'vivid purple': '#9900fa', + 'dark royal blue': '#02066f', + 'hazel': '#8e7618', + 'muted pink': '#d1768f', + 'booger green': '#96b403', + 'canary': '#fdff63', + 'cool grey': '#95a3a6', + 'dark taupe': '#7f684e', + 'darkish purple': '#751973', + 'true green': '#089404', + 'coral pink': '#ff6163', + 'dark sage': '#598556', + 'dark slate blue': '#214761', + 'flat blue': '#3c73a8', + 'mushroom': '#ba9e88', + 'rich blue': '#021bf9', + 'dirty purple': '#734a65', + 'greenblue': '#23c48b', + 'icky green': '#8fae22', + 'light khaki': '#e6f2a2', + 'warm blue': '#4b57db', + 'dark hot pink': '#d90166', + 'deep sea blue': '#015482', + 'carmine': '#9d0216', + 'dark yellow green': '#728f02', + 'pale peach': '#ffe5ad', + 'plum purple': '#4e0550', + 'golden rod': '#f9bc08', + 'neon red': '#ff073a', + 'old pink': '#c77986', + 'very pale blue': '#d6fffe', + 'blood orange': '#fe4b03', + 'grapefruit': '#fd5956', + 'sand yellow': '#fce166', + 'clay brown': '#b2713d', + 'dark blue grey': '#1f3b4d', + 'flat green': '#699d4c', + 'light green blue': '#56fca2', + 'warm pink': '#fb5581', + 'dodger blue': '#3e82fc', + 'gross green': '#a0bf16', + 'ice': '#d6fffa', + 'metallic blue': '#4f738e', + 'pale salmon': '#ffb19a', + 'sap green': '#5c8b15', + 'algae': '#54ac68', + 'bluey grey': '#89a0b0', + 'greeny grey': '#7ea07a', + 'highlighter green': '#1bfc06', + 'light light blue': '#cafffb', + 'light mint': '#b6ffbb', + 'raw umber': '#a75e09', + 'vivid blue': '#152eff', + 'deep lavender': '#8d5eb7', + 'dull teal': '#5f9e8f', + 'light greenish blue': '#63f7b4', + 'mud green': '#606602', + 'pinky': '#fc86aa', + 'red wine': '#8c0034', + 'shit green': '#758000', + 'tan brown': '#ab7e4c', + 'darkblue': '#030764', + 'rosa': '#fe86a4', + 'lipstick': '#d5174e', + 'pale mauve': '#fed0fc', + 'claret': '#680018', + 'dandelion': '#fedf08', + 'orangered': '#fe420f', + 'poop green': '#6f7c00', + 'ruby': '#ca0147', + 'dark': '#1b2431', + 'greenish turquoise': '#00fbb0', + 'pastel red': '#db5856', + 'piss yellow': '#ddd618', + 'bright cyan': '#41fdfe', + 'dark coral': '#cf524e', + 'algae green': '#21c36f', + 'darkish red': '#a90308', + 'reddy brown': '#6e1005', + 'blush pink': '#fe828c', + 'camouflage green': '#4b6113', + 'lawn green': '#4da409', + 'putty': '#beae8a', + 'vibrant blue': '#0339f8', + 'dark sand': '#a88f59', + 'purple/blue': '#5d21d0', + 'saffron': '#feb209', + 'twilight': '#4e518b', + 'warm brown': '#964e02', + 'bluegrey': '#85a3b2', + 'bubble gum pink': '#ff69af', + 'duck egg blue': '#c3fbf4', + 'greenish cyan': '#2afeb7', + 'petrol': '#005f6a', + 'royal': '#0c1793', + 'butter': '#ffff81', + 'dusty orange': '#f0833a', + 'off yellow': '#f1f33f', + 'pale olive green': '#b1d27b', + 'orangish': '#fc824a', + 'leaf': '#71aa34', + 'light blue grey': '#b7c9e2', + 'dried blood': '#4b0101', + 'lightish purple': '#a552e6', + 'rusty red': '#af2f0d', + 'lavender blue': '#8b88f8', + 'light grass green': '#9af764', + 'light mint green': '#a6fbb2', + 'sunflower': '#ffc512', + 'velvet': '#750851', + 'brick orange': '#c14a09', + 'lightish red': '#fe2f4a', + 'pure blue': '#0203e2', + 'twilight blue': '#0a437a', + 'violet red': '#a50055', + 'yellowy brown': '#ae8b0c', + 'carnation': '#fd798f', + 'muddy yellow': '#bfac05', + 'dark seafoam green': '#3eaf76', + 'deep rose': '#c74767', + 'dusty red': '#b9484e', + 'grey/blue': '#647d8e', + 'lemon lime': '#bffe28', + 'purple/pink': '#d725de', + 'brown yellow': '#b29705', + 'purple brown': '#673a3f', + 'wisteria': '#a87dc2', + 'banana yellow': '#fafe4b', + 'lipstick red': '#c0022f', + 'water blue': '#0e87cc', + 'brown grey': '#8d8468', + 'vibrant purple': '#ad03de', + 'baby green': '#8cff9e', + 'barf green': '#94ac02', + 'eggshell blue': '#c4fff7', + 'sandy yellow': '#fdee73', + 'cool green': '#33b864', + 'pale': '#fff9d0', + 'blue/grey': '#758da3', + 'hot magenta': '#f504c9', + 'greyblue': '#77a1b5', + 'purpley': '#8756e4', + 'baby shit green': '#889717', + 'brownish pink': '#c27e79', + 'dark aquamarine': '#017371', + 'diarrhea': '#9f8303', + 'light mustard': '#f7d560', + 'pale sky blue': '#bdf6fe', + 'turtle green': '#75b84f', + 'bright olive': '#9cbb04', + 'dark grey blue': '#29465b', + 'greeny brown': '#696006', + 'lemon green': '#adf802', + 'light periwinkle': '#c1c6fc', + 'seaweed green': '#35ad6b', + 'sunshine yellow': '#fffd37', + 'ugly purple': '#a442a0', + 'medium pink': '#f36196', + 'puke brown': '#947706', + 'very light pink': '#fff4f2', + 'viridian': '#1e9167', + 'bile': '#b5c306', + 'faded yellow': '#feff7f', + 'very pale green': '#cffdbc', + 'vibrant green': '#0add08', + 'bright lime': '#87fd05', + 'spearmint': '#1ef876', + 'light aquamarine': '#7bfdc7', + 'light sage': '#bcecac', + 'yellowgreen': '#bbf90f', + 'baby poo': '#ab9004', + 'dark seafoam': '#1fb57a', + 'deep teal': '#00555a', + 'heather': '#a484ac', + 'rust orange': '#c45508', + 'dirty blue': '#3f829d', + 'fern green': '#548d44', + 'bright lilac': '#c95efb', + 'weird green': '#3ae57f', + 'peacock blue': '#016795', + 'avocado green': '#87a922', + 'faded orange': '#f0944d', + 'grape purple': '#5d1451', + 'hot green': '#25ff29', + 'lime yellow': '#d0fe1d', + 'mango': '#ffa62b', + 'shamrock': '#01b44c', + 'bubblegum': '#ff6cb5', + 'purplish brown': '#6b4247', + 'vomit yellow': '#c7c10c', + 'pale cyan': '#b7fffa', + 'key lime': '#aeff6e', + 'tomato red': '#ec2d01', + 'lightgreen': '#76ff7b', + 'merlot': '#730039', + 'night blue': '#040348', + 'purpleish pink': '#df4ec8', + 'apple': '#6ecb3c', + 'baby poop green': '#8f9805', + 'green apple': '#5edc1f', + 'heliotrope': '#d94ff5', + 'yellow/green': '#c8fd3d', + 'almost black': '#070d0d', + 'cool blue': '#4984b8', + 'leafy green': '#51b73b', + 'mustard brown': '#ac7e04', + 'dusk': '#4e5481', + 'dull brown': '#876e4b', + 'frog green': '#58bc08', + 'vivid green': '#2fef10', + 'bright light green': '#2dfe54', + 'fluro green': '#0aff02', + 'kiwi': '#9cef43', + 'seaweed': '#18d17b', + 'navy green': '#35530a', + 'ultramarine blue': '#1805db', + 'iris': '#6258c4', + 'pastel orange': '#ff964f', + 'yellowish orange': '#ffab0f', + 'perrywinkle': '#8f8ce7', + 'tealish': '#24bca8', + 'dark plum': '#3f012c', + 'pear': '#cbf85f', + 'pinkish orange': '#ff724c', + 'midnight purple': '#280137', + 'light urple': '#b36ff6', + 'dark mint': '#48c072', + 'greenish tan': '#bccb7a', + 'light burgundy': '#a8415b', + 'turquoise blue': '#06b1c4', + 'ugly pink': '#cd7584', + 'sandy': '#f1da7a', + 'electric pink': '#ff0490', + 'muted purple': '#805b87', + 'mid green': '#50a747', + 'greyish': '#a8a495', + 'neon yellow': '#cfff04', + 'banana': '#ffff7e', + 'carnation pink': '#ff7fa7', + 'tomato': '#ef4026', + 'sea': '#3c9992', + 'muddy brown': '#886806', + 'turquoise green': '#04f489', + 'buff': '#fef69e', + 'fawn': '#cfaf7b', + 'muted blue': '#3b719f', + 'pale rose': '#fdc1c5', + 'dark mint green': '#20c073', + 'amethyst': '#9b5fc0', + 'blue/green': '#0f9b8e', + 'chestnut': '#742802', + 'sick green': '#9db92c', + 'pea': '#a4bf20', + 'rusty orange': '#cd5909', + 'stone': '#ada587', + 'rose red': '#be013c', + 'pale aqua': '#b8ffeb', + 'deep orange': '#dc4d01', + 'earth': '#a2653e', + 'mossy green': '#638b27', + 'grassy green': '#419c03', + 'pale lime green': '#b1ff65', + 'light grey blue': '#9dbcd4', + 'pale grey': '#fdfdfe', + 'asparagus': '#77ab56', + 'blueberry': '#464196', + 'purple red': '#990147', + 'pale lime': '#befd73', + 'greenish teal': '#32bf84', + 'caramel': '#af6f09', + 'deep magenta': '#a0025c', + 'light peach': '#ffd8b1', + 'milk chocolate': '#7f4e1e', + 'ocher': '#bf9b0c', + 'off green': '#6ba353', + 'purply pink': '#f075e6', + 'lightblue': '#7bc8f6', + 'dusky blue': '#475f94', + 'golden': '#f5bf03', + 'light beige': '#fffeb6', + 'butter yellow': '#fffd74', + 'dusky purple': '#895b7b', + 'french blue': '#436bad', + 'ugly yellow': '#d0c101', + 'greeny yellow': '#c6f808', + 'orangish red': '#f43605', + 'shamrock green': '#02c14d', + 'orangish brown': '#b25f03', + 'tree green': '#2a7e19', + 'deep violet': '#490648', + 'gunmetal': '#536267', + 'blue/purple': '#5a06ef', + 'cherry': '#cf0234', + 'sandy brown': '#c4a661', + 'warm grey': '#978a84', + 'dark indigo': '#1f0954', + 'midnight': '#03012d', + 'bluey green': '#2bb179', + 'grey pink': '#c3909b', + 'soft purple': '#a66fb5', + 'blood': '#770001', + 'brown red': '#922b05', + 'medium grey': '#7d7f7c', + 'berry': '#990f4b', + 'poo': '#8f7303', + 'purpley pink': '#c83cb9', + 'light salmon': '#fea993', + 'snot': '#acbb0d', + 'easter purple': '#c071fe', + 'light yellow green': '#ccfd7f', + 'dark navy blue': '#00022e', + 'drab': '#828344', + 'light rose': '#ffc5cb', + 'rouge': '#ab1239', + 'purplish red': '#b0054b', + 'slime green': '#99cc04', + 'baby poop': '#937c00', + 'irish green': '#019529', + 'pink/purple': '#ef1de7', + 'dark navy': '#000435', + 'greeny blue': '#42b395', + 'light plum': '#9d5783', + 'pinkish grey': '#c8aca9', + 'dirty orange': '#c87606', + 'rust red': '#aa2704', + 'pale lilac': '#e4cbff', + 'orangey red': '#fa4224', + 'primary blue': '#0804f9', + 'kermit green': '#5cb200', + 'brownish purple': '#76424e', + 'murky green': '#6c7a0e', + 'wheat': '#fbdd7e', + 'very dark purple': '#2a0134', + 'bottle green': '#044a05', + 'watermelon': '#fd4659', + 'deep sky blue': '#0d75f8', + 'fire engine red': '#fe0002', + 'yellow ochre': '#cb9d06', + 'pumpkin orange': '#fb7d07', + 'pale olive': '#b9cc81', + 'light lilac': '#edc8ff', + 'lightish green': '#61e160', + 'carolina blue': '#8ab8fe', + 'mulberry': '#920a4e', + 'shocking pink': '#fe02a2', + 'auburn': '#9a3001', + 'bright lime green': '#65fe08', + 'celadon': '#befdb7', + 'pinkish brown': '#b17261', + 'poo brown': '#885f01', + 'bright sky blue': '#02ccfe', + 'celery': '#c1fd95', + 'dirt brown': '#836539', + 'strawberry': '#fb2943', + 'dark lime': '#84b701', + 'copper': '#b66325', + 'medium brown': '#7f5112', + 'muted green': '#5fa052', + "robin's egg": '#6dedfd', + 'bright aqua': '#0bf9ea', + 'bright lavender': '#c760ff', + 'ivory': '#ffffcb', + 'very light purple': '#f6cefc', + 'light navy': '#155084', + 'pink red': '#f5054f', + 'olive brown': '#645403', + 'poop brown': '#7a5901', + 'mustard green': '#a8b504', + 'ocean green': '#3d9973', + 'very dark blue': '#000133', + 'dusty green': '#76a973', + 'light navy blue': '#2e5a88', + 'minty green': '#0bf77d', + 'adobe': '#bd6c48', + 'barney': '#ac1db8', + 'jade green': '#2baf6a', + 'bright light blue': '#26f7fd', + 'light lime': '#aefd6c', + 'dark khaki': '#9b8f55', + 'orange yellow': '#ffad01', + 'ocre': '#c69c04', + 'maize': '#f4d054', + 'faded pink': '#de9dac', + 'british racing green': '#05480d', + 'sandstone': '#c9ae74', + 'mud brown': '#60460f', + 'light sea green': '#98f6b0', + 'robin egg blue': '#8af1fe', + 'aqua marine': '#2ee8bb', + 'dark sea green': '#11875d', + 'soft pink': '#fdb0c0', + 'orangey brown': '#b16002', + 'cherry red': '#f7022a', + 'burnt yellow': '#d5ab09', + 'brownish grey': '#86775f', + 'camel': '#c69f59', + 'purplish grey': '#7a687f', + 'marine': '#042e60', + 'greyish pink': '#c88d94', + 'pale turquoise': '#a5fbd5', + 'pastel yellow': '#fffe71', + 'bluey purple': '#6241c7', + 'canary yellow': '#fffe40', + 'faded red': '#d3494e', + 'sepia': '#985e2b', + 'coffee': '#a6814c', + 'bright magenta': '#ff08e8', + 'mocha': '#9d7651', + 'ecru': '#feffca', + 'purpleish': '#98568d', + 'cranberry': '#9e003a', + 'darkish green': '#287c37', + 'brown orange': '#b96902', + 'dusky rose': '#ba6873', + 'melon': '#ff7855', + 'sickly green': '#94b21c', + 'silver': '#c5c9c7', + 'purply blue': '#661aee', + 'purpleish blue': '#6140ef', + 'hospital green': '#9be5aa', + 'shit brown': '#7b5804', + 'mid blue': '#276ab3', + 'amber': '#feb308', + 'easter green': '#8cfd7e', + 'soft blue': '#6488ea', + 'cerulean blue': '#056eee', + 'golden brown': '#b27a01', + 'bright turquoise': '#0ffef9', + 'red pink': '#fa2a55', + 'red purple': '#820747', + 'greyish brown': '#7a6a4f', + 'vermillion': '#f4320c', + 'russet': '#a13905', + 'steel grey': '#6f828a', + 'lighter purple': '#a55af4', + 'bright violet': '#ad0afd', + 'prussian blue': '#004577', + 'slate green': '#658d6d', + 'dirty pink': '#ca7b80', + 'dark blue green': '#005249', + 'pine': '#2b5d34', + 'yellowy green': '#bff128', + 'dark gold': '#b59410', + 'bluish': '#2976bb', + 'darkish blue': '#014182', + 'dull red': '#bb3f3f', + 'pinky red': '#fc2647', + 'bronze': '#a87900', + 'pale teal': '#82cbb2', + 'military green': '#667c3e', + 'barbie pink': '#fe46a5', + 'bubblegum pink': '#fe83cc', + 'pea soup green': '#94a617', + 'dark mustard': '#a88905', + 'shit': '#7f5f00', + 'medium purple': '#9e43a2', + 'very dark green': '#062e03', + 'dirt': '#8a6e45', + 'dusky pink': '#cc7a8b', + 'red violet': '#9e0168', + 'lemon yellow': '#fdff38', + 'pistachio': '#c0fa8b', + 'dull yellow': '#eedc5b', + 'dark lime green': '#7ebd01', + 'denim blue': '#3b5b92', + 'teal blue': '#01889f', + 'lightish blue': '#3d7afd', + 'purpley blue': '#5f34e7', + 'light indigo': '#6d5acf', + 'swamp green': '#748500', + 'brown green': '#706c11', + 'dark maroon': '#3c0008', + 'hot purple': '#cb00f5', + 'dark forest green': '#002d04', + 'faded blue': '#658cbb', + 'drab green': '#749551', + 'light lime green': '#b9ff66', + 'snot green': '#9dc100', + 'yellowish': '#faee66', + 'light blue green': '#7efbb3', + 'bordeaux': '#7b002c', + 'light mauve': '#c292a1', + 'ocean': '#017b92', + 'marigold': '#fcc006', + 'muddy green': '#657432', + 'dull orange': '#d8863b', + 'steel': '#738595', + 'electric purple': '#aa23ff', + 'fluorescent green': '#08ff08', + 'yellowish brown': '#9b7a01', + 'blush': '#f29e8e', + 'soft green': '#6fc276', + 'bright orange': '#ff5b00', + 'lemon': '#fdff52', + 'purple grey': '#866f85', + 'acid green': '#8ffe09', + 'pale lavender': '#eecffe', + 'violet blue': '#510ac9', + 'light forest green': '#4f9153', + 'burnt red': '#9f2305', + 'khaki green': '#728639', + 'cerise': '#de0c62', + 'faded purple': '#916e99', + 'apricot': '#ffb16d', + 'dark olive green': '#3c4d03', + 'grey brown': '#7f7053', + 'green grey': '#77926f', + 'true blue': '#010fcc', + 'pale violet': '#ceaefa', + 'periwinkle blue': '#8f99fb', + 'light sky blue': '#c6fcff', + 'blurple': '#5539cc', + 'green brown': '#544e03', + 'bluegreen': '#017a79', + 'bright teal': '#01f9c6', + 'brownish yellow': '#c9b003', + 'pea soup': '#929901', + 'forest': '#0b5509', + 'barney purple': '#a00498', + 'ultramarine': '#2000b1', + 'purplish': '#94568c', + 'puke yellow': '#c2be0e', + 'bluish grey': '#748b97', + 'dark periwinkle': '#665fd1', + 'dark lilac': '#9c6da5', + 'reddish': '#c44240', + 'light maroon': '#a24857', + 'dusty purple': '#825f87', + 'terra cotta': '#c9643b', + 'avocado': '#90b134', + 'marine blue': '#01386a', + 'teal green': '#25a36f', + 'slate grey': '#59656d', + 'lighter green': '#75fd63', + 'electric green': '#21fc0d', + 'dusty blue': '#5a86ad', + 'golden yellow': '#fec615', + 'bright yellow': '#fffd01', + 'light lavender': '#dfc5fe', + 'umber': '#b26400', + 'poop': '#7f5e00', + 'dark peach': '#de7e5d', + 'jungle green': '#048243', + 'eggshell': '#ffffd4', + 'denim': '#3b638c', + 'yellow brown': '#b79400', + 'dull purple': '#84597e', + 'chocolate brown': '#411900', + 'wine red': '#7b0323', + 'neon blue': '#04d9ff', + 'dirty green': '#667e2c', + 'light tan': '#fbeeac', + 'ice blue': '#d7fffe', + 'cadet blue': '#4e7496', + 'dark mauve': '#874c62', + 'very light blue': '#d5ffff', + 'grey purple': '#826d8c', + 'pastel pink': '#ffbacd', + 'very light green': '#d1ffbd', + 'dark sky blue': '#448ee4', + 'evergreen': '#05472a', + 'dull pink': '#d5869d', + 'aubergine': '#3d0734', + 'mahogany': '#4a0100', + 'reddish orange': '#f8481c', + 'deep green': '#02590f', + 'vomit green': '#89a203', + 'purple pink': '#e03fd8', + 'dusty pink': '#d58a94', + 'faded green': '#7bb274', + 'camo green': '#526525', + 'pinky purple': '#c94cbe', + 'pink purple': '#db4bda', + 'brownish red': '#9e3623', + 'dark rose': '#b5485d', + 'mud': '#735c12', + 'brownish': '#9c6d57', + 'emerald green': '#028f1e', + 'pale brown': '#b1916e', + 'dull blue': '#49759c', + 'burnt umber': '#a0450e', + 'medium green': '#39ad48', + 'clay': '#b66a50', + 'light aqua': '#8cffdb', + 'light olive green': '#a4be5c', + 'brownish orange': '#cb7723', + 'dark aqua': '#05696b', + 'purplish pink': '#ce5dae', + 'dark salmon': '#c85a53', + 'greenish grey': '#96ae8d', + 'jade': '#1fa774', + 'ugly green': '#7a9703', + 'dark beige': '#ac9362', + 'emerald': '#01a049', + 'pale red': '#d9544d', + 'light magenta': '#fa5ff7', + 'sky': '#82cafc', + 'light cyan': '#acfffc', + 'yellow orange': '#fcb001', + 'reddish purple': '#910951', + 'reddish pink': '#fe2c54', + 'orchid': '#c875c4', + 'dirty yellow': '#cdc50a', + 'orange red': '#fd411e', + 'deep red': '#9a0200', + 'orange brown': '#be6400', + 'cobalt blue': '#030aa7', + 'neon pink': '#fe019a', + 'rose pink': '#f7879a', + 'greyish purple': '#887191', + 'raspberry': '#b00149', + 'aqua green': '#12e193', + 'salmon pink': '#fe7b7c', + 'tangerine': '#ff9408', + 'brownish green': '#6a6e09', + 'red brown': '#8b2e16', + 'greenish brown': '#696112', + 'pumpkin': '#e17701', + 'pine green': '#0a481e', + 'charcoal': '#343837', + 'baby pink': '#ffb7ce', + 'cornflower': '#6a79f7', + 'blue violet': '#5d06e9', + 'chocolate': '#3d1c02', + 'greyish green': '#82a67d', + 'scarlet': '#be0119', + 'green yellow': '#c9ff27', + 'dark olive': '#373e02', + 'sienna': '#a9561e', + 'pastel purple': '#caa0ff', + 'terracotta': '#ca6641', + 'aqua blue': '#02d8e9', + 'sage green': '#88b378', + 'blood red': '#980002', + 'deep pink': '#cb0162', + 'grass': '#5cac2d', + 'moss': '#769958', + 'pastel blue': '#a2bffe', + 'bluish green': '#10a674', + 'green blue': '#06b48b', + 'dark tan': '#af884a', + 'greenish blue': '#0b8b87', + 'pale orange': '#ffa756', + 'vomit': '#a2a415', + 'forrest green': '#154406', + 'dark lavender': '#856798', + 'dark violet': '#34013f', + 'purple blue': '#632de9', + 'dark cyan': '#0a888a', + 'olive drab': '#6f7632', + 'pinkish': '#d46a7e', + 'cobalt': '#1e488f', + 'neon purple': '#bc13fe', + 'light turquoise': '#7ef4cc', + 'apple green': '#76cd26', + 'dull green': '#74a662', + 'wine': '#80013f', + 'powder blue': '#b1d1fc', + 'off white': '#ffffe4', + 'electric blue': '#0652ff', + 'dark turquoise': '#045c5a', + 'blue purple': '#5729ce', + 'azure': '#069af3', + 'bright red': '#ff000d', + 'pinkish red': '#f10c45', + 'cornflower blue': '#5170d7', + 'light olive': '#acbf69', + 'grape': '#6c3461', + 'greyish blue': '#5e819d', + 'purplish blue': '#601ef9', + 'yellowish green': '#b0dd16', + 'greenish yellow': '#cdfd02', + 'medium blue': '#2c6fbb', + 'dusty rose': '#c0737a', + 'light violet': '#d6b4fc', + 'midnight blue': '#020035', + 'bluish purple': '#703be7', + 'red orange': '#fd3c06', + 'dark magenta': '#960056', + 'greenish': '#40a368', + 'ocean blue': '#03719c', + 'coral': '#fc5a50', + 'cream': '#ffffc2', + 'reddish brown': '#7f2b0a', + 'burnt sienna': '#b04e0f', + 'brick': '#a03623', + 'sage': '#87ae73', + 'grey green': '#789b73', + 'white': '#ffffff', + "robin's egg blue": '#98eff9', + 'moss green': '#658b38', + 'steel blue': '#5a7d9a', + 'eggplant': '#380835', + 'light yellow': '#fffe7a', + 'leaf green': '#5ca904', + 'light grey': '#d8dcd6', + 'puke': '#a5a502', + 'pinkish purple': '#d648d7', + 'sea blue': '#047495', + 'pale purple': '#b790d4', + 'slate blue': '#5b7c99', + 'blue grey': '#607c8e', + 'hunter green': '#0b4008', + 'fuchsia': '#ed0dd9', + 'crimson': '#8c000f', + 'pale yellow': '#ffff84', + 'ochre': '#bf9005', + 'mustard yellow': '#d2bd0a', + 'light red': '#ff474c', + 'cerulean': '#0485d1', + 'pale pink': '#ffcfdc', + 'deep blue': '#040273', + 'rust': '#a83c09', + 'light teal': '#90e4c1', + 'slate': '#516572', + 'goldenrod': '#fac205', + 'dark yellow': '#d5b60a', + 'dark grey': '#363737', + 'army green': '#4b5d16', + 'grey blue': '#6b8ba4', + 'seafoam': '#80f9ad', + 'puce': '#a57e52', + 'spring green': '#a9f971', + 'dark orange': '#c65102', + 'sand': '#e2ca76', + 'pastel green': '#b0ff9d', + 'mint': '#9ffeb0', + 'light orange': '#fdaa48', + 'bright pink': '#fe01b1', + 'chartreuse': '#c1f80a', + 'deep purple': '#36013f', + 'dark brown': '#341c02', + 'taupe': '#b9a281', + 'pea green': '#8eab12', + 'puke green': '#9aae07', + 'kelly green': '#02ab2e', + 'seafoam green': '#7af9ab', + 'blue green': '#137e6d', + 'khaki': '#aaa662', + 'burgundy': '#610023', + 'dark teal': '#014d4e', + 'brick red': '#8f1402', + 'royal purple': '#4b006e', + 'plum': '#580f41', + 'mint green': '#8fff9f', + 'gold': '#dbb40c', + 'baby blue': '#a2cffe', + 'yellow green': '#c0fb2d', + 'bright purple': '#be03fd', + 'dark red': '#840000', + 'pale blue': '#d0fefe', + 'grass green': '#3f9b0b', + 'navy': '#01153e', + 'aquamarine': '#04d8b2', + 'burnt orange': '#c04e01', + 'neon green': '#0cff0c', + 'bright blue': '#0165fc', + 'rose': '#cf6275', + 'light pink': '#ffd1df', + 'mustard': '#ceb301', + 'indigo': '#380282', + 'lime': '#aaff32', + 'sea green': '#53fca1', + 'periwinkle': '#8e82fe', + 'dark pink': '#cb416b', + 'olive green': '#677a04', + 'peach': '#ffb07c', + 'pale green': '#c7fdb5', + 'light brown': '#ad8150', + 'hot pink': '#ff028d', + 'black': '#000000', + 'lilac': '#cea2fd', + 'navy blue': '#001146', + 'royal blue': '#0504aa', + 'beige': '#e6daa6', + 'salmon': '#ff796c', + 'olive': '#6e750e', + 'maroon': '#650021', + 'bright green': '#01ff07', + 'dark purple': '#35063e', + 'mauve': '#ae7181', + 'forest green': '#06470c', + 'aqua': '#13eac9', + 'cyan': '#00ffff', + 'tan': '#d1b26f', + 'dark blue': '#00035b', + 'lavender': '#c79fef', + 'turquoise': '#06c2ac', + 'dark green': '#033500', + 'violet': '#9a0eea', + 'light purple': '#bf77f6', + 'lime green': '#89fe05', + 'grey': '#929591', + 'sky blue': '#75bbfd', + 'yellow': '#ffff14', + 'magenta': '#c20078', + 'light green': '#96f97b', + 'orange': '#f97306', + 'teal': '#029386', + 'light blue': '#95d0fc', + 'red': '#e50000', + 'brown': '#653700', + 'pink': '#ff81c0', + 'blue': '#0343df', + 'green': '#15b01a', + 'purple': '#7e1e9c'} + +# Normalize name to "xkcd:" to avoid name collisions. +XKCD_COLORS = {'xkcd:' + name: value for name, value in XKCD_COLORS.items()} + + +# https://drafts.csswg.org/css-color-4/#named-colors +CSS4_COLORS = { + 'aliceblue': '#F0F8FF', + 'antiquewhite': '#FAEBD7', + 'aqua': '#00FFFF', + 'aquamarine': '#7FFFD4', + 'azure': '#F0FFFF', + 'beige': '#F5F5DC', + 'bisque': '#FFE4C4', + 'black': '#000000', + 'blanchedalmond': '#FFEBCD', + 'blue': '#0000FF', + 'blueviolet': '#8A2BE2', + 'brown': '#A52A2A', + 'burlywood': '#DEB887', + 'cadetblue': '#5F9EA0', + 'chartreuse': '#7FFF00', + 'chocolate': '#D2691E', + 'coral': '#FF7F50', + 'cornflowerblue': '#6495ED', + 'cornsilk': '#FFF8DC', + 'crimson': '#DC143C', + 'cyan': '#00FFFF', + 'darkblue': '#00008B', + 'darkcyan': '#008B8B', + 'darkgoldenrod': '#B8860B', + 'darkgray': '#A9A9A9', + 'darkgreen': '#006400', + 'darkgrey': '#A9A9A9', + 'darkkhaki': '#BDB76B', + 'darkmagenta': '#8B008B', + 'darkolivegreen': '#556B2F', + 'darkorange': '#FF8C00', + 'darkorchid': '#9932CC', + 'darkred': '#8B0000', + 'darksalmon': '#E9967A', + 'darkseagreen': '#8FBC8F', + 'darkslateblue': '#483D8B', + 'darkslategray': '#2F4F4F', + 'darkslategrey': '#2F4F4F', + 'darkturquoise': '#00CED1', + 'darkviolet': '#9400D3', + 'deeppink': '#FF1493', + 'deepskyblue': '#00BFFF', + 'dimgray': '#696969', + 'dimgrey': '#696969', + 'dodgerblue': '#1E90FF', + 'firebrick': '#B22222', + 'floralwhite': '#FFFAF0', + 'forestgreen': '#228B22', + 'fuchsia': '#FF00FF', + 'gainsboro': '#DCDCDC', + 'ghostwhite': '#F8F8FF', + 'gold': '#FFD700', + 'goldenrod': '#DAA520', + 'gray': '#808080', + 'green': '#008000', + 'greenyellow': '#ADFF2F', + 'grey': '#808080', + 'honeydew': '#F0FFF0', + 'hotpink': '#FF69B4', + 'indianred': '#CD5C5C', + 'indigo': '#4B0082', + 'ivory': '#FFFFF0', + 'khaki': '#F0E68C', + 'lavender': '#E6E6FA', + 'lavenderblush': '#FFF0F5', + 'lawngreen': '#7CFC00', + 'lemonchiffon': '#FFFACD', + 'lightblue': '#ADD8E6', + 'lightcoral': '#F08080', + 'lightcyan': '#E0FFFF', + 'lightgoldenrodyellow': '#FAFAD2', + 'lightgray': '#D3D3D3', + 'lightgreen': '#90EE90', + 'lightgrey': '#D3D3D3', + 'lightpink': '#FFB6C1', + 'lightsalmon': '#FFA07A', + 'lightseagreen': '#20B2AA', + 'lightskyblue': '#87CEFA', + 'lightslategray': '#778899', + 'lightslategrey': '#778899', + 'lightsteelblue': '#B0C4DE', + 'lightyellow': '#FFFFE0', + 'lime': '#00FF00', + 'limegreen': '#32CD32', + 'linen': '#FAF0E6', + 'magenta': '#FF00FF', + 'maroon': '#800000', + 'mediumaquamarine': '#66CDAA', + 'mediumblue': '#0000CD', + 'mediumorchid': '#BA55D3', + 'mediumpurple': '#9370DB', + 'mediumseagreen': '#3CB371', + 'mediumslateblue': '#7B68EE', + 'mediumspringgreen': '#00FA9A', + 'mediumturquoise': '#48D1CC', + 'mediumvioletred': '#C71585', + 'midnightblue': '#191970', + 'mintcream': '#F5FFFA', + 'mistyrose': '#FFE4E1', + 'moccasin': '#FFE4B5', + 'navajowhite': '#FFDEAD', + 'navy': '#000080', + 'oldlace': '#FDF5E6', + 'olive': '#808000', + 'olivedrab': '#6B8E23', + 'orange': '#FFA500', + 'orangered': '#FF4500', + 'orchid': '#DA70D6', + 'palegoldenrod': '#EEE8AA', + 'palegreen': '#98FB98', + 'paleturquoise': '#AFEEEE', + 'palevioletred': '#DB7093', + 'papayawhip': '#FFEFD5', + 'peachpuff': '#FFDAB9', + 'peru': '#CD853F', + 'pink': '#FFC0CB', + 'plum': '#DDA0DD', + 'powderblue': '#B0E0E6', + 'purple': '#800080', + 'rebeccapurple': '#663399', + 'red': '#FF0000', + 'rosybrown': '#BC8F8F', + 'royalblue': '#4169E1', + 'saddlebrown': '#8B4513', + 'salmon': '#FA8072', + 'sandybrown': '#F4A460', + 'seagreen': '#2E8B57', + 'seashell': '#FFF5EE', + 'sienna': '#A0522D', + 'silver': '#C0C0C0', + 'skyblue': '#87CEEB', + 'slateblue': '#6A5ACD', + 'slategray': '#708090', + 'slategrey': '#708090', + 'snow': '#FFFAFA', + 'springgreen': '#00FF7F', + 'steelblue': '#4682B4', + 'tan': '#D2B48C', + 'teal': '#008080', + 'thistle': '#D8BFD8', + 'tomato': '#FF6347', + 'turquoise': '#40E0D0', + 'violet': '#EE82EE', + 'wheat': '#F5DEB3', + 'white': '#FFFFFF', + 'whitesmoke': '#F5F5F5', + 'yellow': '#FFFF00', + 'yellowgreen': '#9ACD32'} diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_docstring.py b/llava_next/lib/python3.10/site-packages/matplotlib/_docstring.py new file mode 100644 index 0000000000000000000000000000000000000000..f44d7b2c7674ceb13c8eddd2c7eae5e949986173 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_docstring.py @@ -0,0 +1,125 @@ +import inspect + +from . import _api + + +def kwarg_doc(text): + """ + Decorator for defining the kwdoc documentation of artist properties. + + This decorator can be applied to artist property setter methods. + The given text is stored in a private attribute ``_kwarg_doc`` on + the method. It is used to overwrite auto-generated documentation + in the *kwdoc list* for artists. The kwdoc list is used to document + ``**kwargs`` when they are properties of an artist. See e.g. the + ``**kwargs`` section in `.Axes.text`. + + The text should contain the supported types, as well as the default + value if applicable, e.g.: + + @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`") + def set_usetex(self, usetex): + + See Also + -------- + matplotlib.artist.kwdoc + + """ + def decorator(func): + func._kwarg_doc = text + return func + return decorator + + +class Substitution: + """ + A decorator that performs %-substitution on an object's docstring. + + This decorator should be robust even if ``obj.__doc__`` is None (for + example, if -OO was passed to the interpreter). + + Usage: construct a docstring.Substitution with a sequence or dictionary + suitable for performing substitution; then decorate a suitable function + with the constructed object, e.g.:: + + sub_author_name = Substitution(author='Jason') + + @sub_author_name + def some_function(x): + "%(author)s wrote this function" + + # note that some_function.__doc__ is now "Jason wrote this function" + + One can also use positional arguments:: + + sub_first_last_names = Substitution('Edgar Allen', 'Poe') + + @sub_first_last_names + def some_function(x): + "%s %s wrote the Raven" + """ + def __init__(self, *args, **kwargs): + if args and kwargs: + raise TypeError("Only positional or keyword args are allowed") + self.params = args or kwargs + + def __call__(self, func): + if func.__doc__: + func.__doc__ = inspect.cleandoc(func.__doc__) % self.params + return func + + def update(self, *args, **kwargs): + """ + Update ``self.params`` (which must be a dict) with the supplied args. + """ + self.params.update(*args, **kwargs) + + +class _ArtistKwdocLoader(dict): + def __missing__(self, key): + if not key.endswith(":kwdoc"): + raise KeyError(key) + name = key[:-len(":kwdoc")] + from matplotlib.artist import Artist, kwdoc + try: + cls, = [cls for cls in _api.recursive_subclasses(Artist) + if cls.__name__ == name] + except ValueError as e: + raise KeyError(key) from e + return self.setdefault(key, kwdoc(cls)) + + +class _ArtistPropertiesSubstitution(Substitution): + """ + A `.Substitution` with two additional features: + + - Substitutions of the form ``%(classname:kwdoc)s`` (ending with the + literal ":kwdoc" suffix) trigger lookup of an Artist subclass with the + given *classname*, and are substituted with the `.kwdoc` of that class. + - Decorating a class triggers substitution both on the class docstring and + on the class' ``__init__`` docstring (which is a commonly required + pattern for Artist subclasses). + """ + + def __init__(self): + self.params = _ArtistKwdocLoader() + + def __call__(self, obj): + super().__call__(obj) + if isinstance(obj, type) and obj.__init__ != object.__init__: + self(obj.__init__) + return obj + + +def copy(source): + """Copy a docstring from another source function (if present).""" + def do_copy(target): + if source.__doc__: + target.__doc__ = source.__doc__ + return target + return do_copy + + +# Create a decorator that will house the various docstring snippets reused +# throughout Matplotlib. +dedent_interpd = interpd = _ArtistPropertiesSubstitution() diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_enums.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/_enums.pyi new file mode 100644 index 0000000000000000000000000000000000000000..351088b3645315b54daf2bdcb92c18d32a6164b0 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_enums.pyi @@ -0,0 +1,18 @@ +from enum import Enum + +class _AutoStringNameEnum(Enum): + def __hash__(self) -> int: ... + +class JoinStyle(str, _AutoStringNameEnum): + miter: str + round: str + bevel: str + @staticmethod + def demo() -> None: ... + +class CapStyle(str, _AutoStringNameEnum): + butt: str + projecting: str + round: str + @staticmethod + def demo() -> None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_mathtext.py b/llava_next/lib/python3.10/site-packages/matplotlib/_mathtext.py new file mode 100644 index 0000000000000000000000000000000000000000..6e4df209b1f91cbcb45b534e835431ddfce730b5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_mathtext.py @@ -0,0 +1,2861 @@ +""" +Implementation details for :mod:`.mathtext`. +""" + +from __future__ import annotations + +import abc +import copy +import enum +import functools +import logging +import os +import re +import types +import unicodedata +import string +import typing as T +from typing import NamedTuple + +import numpy as np +from pyparsing import ( + Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, + ParseBaseException, ParseException, ParseExpression, ParseFatalException, + ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore, + pyparsing_common, Group) + +import matplotlib as mpl +from . import cbook +from ._mathtext_data import ( + latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni) +from .font_manager import FontProperties, findfont, get_font +from .ft2font import FT2Font, FT2Image, KERNING_DEFAULT + +from packaging.version import parse as parse_version +from pyparsing import __version__ as pyparsing_version +if parse_version(pyparsing_version).major < 3: + from pyparsing import nestedExpr as nested_expr +else: + from pyparsing import nested_expr + +if T.TYPE_CHECKING: + from collections.abc import Iterable + from .ft2font import Glyph + +ParserElement.enablePackrat() +_log = logging.getLogger("matplotlib.mathtext") + + +############################################################################## +# FONTS + + +def get_unicode_index(symbol: str) -> int: # Publicly exported. + r""" + Return the integer index (from the Unicode table) of *symbol*. + + Parameters + ---------- + symbol : str + A single (Unicode) character, a TeX command (e.g. r'\pi') or a Type1 + symbol name (e.g. 'phi'). + """ + try: # This will succeed if symbol is a single Unicode char + return ord(symbol) + except TypeError: + pass + try: # Is symbol a TeX symbol (i.e. \alpha) + return tex2uni[symbol.strip("\\")] + except KeyError as err: + raise ValueError( + f"{symbol!r} is not a valid Unicode character or TeX/Type1 symbol" + ) from err + + +class VectorParse(NamedTuple): + """ + The namedtuple type returned by ``MathTextParser("path").parse(...)``. + + Attributes + ---------- + width, height, depth : float + The global metrics. + glyphs : list + The glyphs including their positions. + rect : list + The list of rectangles. + """ + width: float + height: float + depth: float + glyphs: list[tuple[FT2Font, float, int, float, float]] + rects: list[tuple[float, float, float, float]] + +VectorParse.__module__ = "matplotlib.mathtext" + + +class RasterParse(NamedTuple): + """ + The namedtuple type returned by ``MathTextParser("agg").parse(...)``. + + Attributes + ---------- + ox, oy : float + The offsets are always zero. + width, height, depth : float + The global metrics. + image : FT2Image + A raster image. + """ + ox: float + oy: float + width: float + height: float + depth: float + image: FT2Image + +RasterParse.__module__ = "matplotlib.mathtext" + + +class Output: + r""" + Result of `ship`\ping a box: lists of positioned glyphs and rectangles. + + This class is not exposed to end users, but converted to a `VectorParse` or + a `RasterParse` by `.MathTextParser.parse`. + """ + + def __init__(self, box: Box): + self.box = box + self.glyphs: list[tuple[float, float, FontInfo]] = [] # (ox, oy, info) + self.rects: list[tuple[float, float, float, float]] = [] # (x1, y1, x2, y2) + + def to_vector(self) -> VectorParse: + w, h, d = map( + np.ceil, [self.box.width, self.box.height, self.box.depth]) + gs = [(info.font, info.fontsize, info.num, ox, h - oy + info.offset) + for ox, oy, info in self.glyphs] + rs = [(x1, h - y2, x2 - x1, y2 - y1) + for x1, y1, x2, y2 in self.rects] + return VectorParse(w, h + d, d, gs, rs) + + def to_raster(self, *, antialiased: bool) -> RasterParse: + # Metrics y's and mathtext y's are oriented in opposite directions, + # hence the switch between ymin and ymax. + xmin = min([*[ox + info.metrics.xmin for ox, oy, info in self.glyphs], + *[x1 for x1, y1, x2, y2 in self.rects], 0]) - 1 + ymin = min([*[oy - info.metrics.ymax for ox, oy, info in self.glyphs], + *[y1 for x1, y1, x2, y2 in self.rects], 0]) - 1 + xmax = max([*[ox + info.metrics.xmax for ox, oy, info in self.glyphs], + *[x2 for x1, y1, x2, y2 in self.rects], 0]) + 1 + ymax = max([*[oy - info.metrics.ymin for ox, oy, info in self.glyphs], + *[y2 for x1, y1, x2, y2 in self.rects], 0]) + 1 + w = xmax - xmin + h = ymax - ymin - self.box.depth + d = ymax - ymin - self.box.height + image = FT2Image(np.ceil(w), np.ceil(h + max(d, 0))) + + # Ideally, we could just use self.glyphs and self.rects here, shifting + # their coordinates by (-xmin, -ymin), but this yields slightly + # different results due to floating point slop; shipping twice is the + # old approach and keeps baseline images backcompat. + shifted = ship(self.box, (-xmin, -ymin)) + + for ox, oy, info in shifted.glyphs: + info.font.draw_glyph_to_bitmap( + image, ox, oy - info.metrics.iceberg, info.glyph, + antialiased=antialiased) + for x1, y1, x2, y2 in shifted.rects: + height = max(int(y2 - y1) - 1, 0) + if height == 0: + center = (y2 + y1) / 2 + y = int(center - (height + 1) / 2) + else: + y = int(y1) + image.draw_rect_filled(int(x1), y, np.ceil(x2), y + height) + return RasterParse(0, 0, w, h + d, d, image) + + +class FontMetrics(NamedTuple): + """ + Metrics of a font. + + Attributes + ---------- + advance : float + The advance distance (in points) of the glyph. + height : float + The height of the glyph in points. + width : float + The width of the glyph in points. + xmin, xmax, ymin, ymax : float + The ink rectangle of the glyph. + iceberg : float + The distance from the baseline to the top of the glyph. (This corresponds to + TeX's definition of "height".) + slanted : bool + Whether the glyph should be considered as "slanted" (currently used for kerning + sub/superscripts). + """ + advance: float + height: float + width: float + xmin: float + xmax: float + ymin: float + ymax: float + iceberg: float + slanted: bool + + +class FontInfo(NamedTuple): + font: FT2Font + fontsize: float + postscript_name: str + metrics: FontMetrics + num: int + glyph: Glyph + offset: float + + +class Fonts(abc.ABC): + """ + An abstract base class for a system of fonts to use for mathtext. + + The class must be able to take symbol keys and font file names and + return the character metrics. It also delegates to a backend class + to do the actual drawing. + """ + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + """ + Parameters + ---------- + default_font_prop : `~.font_manager.FontProperties` + The default non-math font, or the base font for Unicode (generic) + font rendering. + load_glyph_flags : int + Flags passed to the glyph loader (e.g. ``FT_Load_Glyph`` and + ``FT_Load_Char`` for FreeType-based fonts). + """ + self.default_font_prop = default_font_prop + self.load_glyph_flags = load_glyph_flags + + def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, + font2: str, fontclass2: str, sym2: str, fontsize2: float, + dpi: float) -> float: + """ + Get the kerning distance for font between *sym1* and *sym2*. + + See `~.Fonts.get_metrics` for a detailed description of the parameters. + """ + return 0. + + def _get_font(self, font: str) -> FT2Font: + raise NotImplementedError + + def _get_info(self, font: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontInfo: + raise NotImplementedError + + def get_metrics(self, font: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontMetrics: + r""" + Parameters + ---------- + font : str + One of the TeX font names: "tt", "it", "rm", "cal", "sf", "bf", + "default", "regular", "bb", "frak", "scr". "default" and "regular" + are synonyms and use the non-math font. + font_class : str + One of the TeX font names (as for *font*), but **not** "bb", + "frak", or "scr". This is used to combine two font classes. The + only supported combination currently is ``get_metrics("frak", "bf", + ...)``. + sym : str + A symbol in raw TeX form, e.g., "1", "x", or "\sigma". + fontsize : float + Font size in points. + dpi : float + Rendering dots-per-inch. + + Returns + ------- + FontMetrics + """ + info = self._get_info(font, font_class, sym, fontsize, dpi) + return info.metrics + + def render_glyph(self, output: Output, ox: float, oy: float, font: str, + font_class: str, sym: str, fontsize: float, dpi: float) -> None: + """ + At position (*ox*, *oy*), draw the glyph specified by the remaining + parameters (see `get_metrics` for their detailed description). + """ + info = self._get_info(font, font_class, sym, fontsize, dpi) + output.glyphs.append((ox, oy, info)) + + def render_rect_filled(self, output: Output, + x1: float, y1: float, x2: float, y2: float) -> None: + """ + Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*). + """ + output.rects.append((x1, y1, x2, y2)) + + def get_xheight(self, font: str, fontsize: float, dpi: float) -> float: + """ + Get the xheight for the given *font* and *fontsize*. + """ + raise NotImplementedError() + + def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: + """ + Get the line thickness that matches the given font. Used as a + base unit for drawing lines such as in a fraction or radical. + """ + raise NotImplementedError() + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + """ + Override if your font provides multiple sizes of the same + symbol. Should return a list of symbols matching *sym* in + various sizes. The expression renderer will select the most + appropriate size for a given situation from this list. + """ + return [(fontname, sym)] + + +class TruetypeFonts(Fonts, metaclass=abc.ABCMeta): + """ + A generic base class for all font setups that use Truetype fonts + (through FT2Font). + """ + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + super().__init__(default_font_prop, load_glyph_flags) + # Per-instance cache. + self._get_info = functools.cache(self._get_info) # type: ignore[method-assign] + self._fonts = {} + self.fontmap: dict[str | int, str] = {} + + filename = findfont(self.default_font_prop) + default_font = get_font(filename) + self._fonts['default'] = default_font + self._fonts['regular'] = default_font + + def _get_font(self, font: str | int) -> FT2Font: + if font in self.fontmap: + basename = self.fontmap[font] + else: + # NOTE: An int is only passed by subclasses which have placed int keys into + # `self.fontmap`, so we must cast this to confirm it to typing. + basename = T.cast(str, font) + cached_font = self._fonts.get(basename) + if cached_font is None and os.path.exists(basename): + cached_font = get_font(basename) + self._fonts[basename] = cached_font + self._fonts[cached_font.postscript_name] = cached_font + self._fonts[cached_font.postscript_name.lower()] = cached_font + return T.cast(FT2Font, cached_font) # FIXME: Not sure this is guaranteed. + + def _get_offset(self, font: FT2Font, glyph: Glyph, fontsize: float, + dpi: float) -> float: + if font.postscript_name == 'Cmex10': + return (glyph.height / 64 / 2) + (fontsize/3 * dpi/72) + return 0. + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + raise NotImplementedError + + # The return value of _get_info is cached per-instance. + def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float, + dpi: float) -> FontInfo: + font, num, slanted = self._get_glyph(fontname, font_class, sym) + font.set_size(fontsize, dpi) + glyph = font.load_char(num, flags=self.load_glyph_flags) + + xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] + offset = self._get_offset(font, glyph, fontsize, dpi) + metrics = FontMetrics( + advance = glyph.linearHoriAdvance/65536.0, + height = glyph.height/64.0, + width = glyph.width/64.0, + xmin = xmin, + xmax = xmax, + ymin = ymin+offset, + ymax = ymax+offset, + # iceberg is the equivalent of TeX's "height" + iceberg = glyph.horiBearingY/64.0 + offset, + slanted = slanted + ) + + return FontInfo( + font = font, + fontsize = fontsize, + postscript_name = font.postscript_name, + metrics = metrics, + num = num, + glyph = glyph, + offset = offset + ) + + def get_xheight(self, fontname: str, fontsize: float, dpi: float) -> float: + font = self._get_font(fontname) + font.set_size(fontsize, dpi) + pclt = font.get_sfnt_table('pclt') + if pclt is None: + # Some fonts don't store the xHeight, so we do a poor man's xHeight + metrics = self.get_metrics( + fontname, mpl.rcParams['mathtext.default'], 'x', fontsize, dpi) + return metrics.iceberg + xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0) + return xHeight + + def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: + # This function used to grab underline thickness from the font + # metrics, but that information is just too un-reliable, so it + # is now hardcoded. + return ((0.75 / 12.0) * fontsize * dpi) / 72.0 + + def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, + font2: str, fontclass2: str, sym2: str, fontsize2: float, + dpi: float) -> float: + if font1 == font2 and fontsize1 == fontsize2: + info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) + info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) + font = info1.font + return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64 + return super().get_kern(font1, fontclass1, sym1, fontsize1, + font2, fontclass2, sym2, fontsize2, dpi) + + +class BakomaFonts(TruetypeFonts): + """ + Use the Bakoma TrueType fonts for rendering. + + Symbols are strewn about a number of font files, each of which has + its own proprietary 8-bit encoding. + """ + _fontmap = { + 'cal': 'cmsy10', + 'rm': 'cmr10', + 'tt': 'cmtt10', + 'it': 'cmmi10', + 'bf': 'cmb10', + 'sf': 'cmss10', + 'ex': 'cmex10', + } + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + self._stix_fallback = StixFonts(default_font_prop, load_glyph_flags) + + super().__init__(default_font_prop, load_glyph_flags) + for key, val in self._fontmap.items(): + fullpath = findfont(val) + self.fontmap[key] = fullpath + self.fontmap[val] = fullpath + + _slanted_symbols = set(r"\int \oint".split()) + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + font = None + if fontname in self.fontmap and sym in latex_to_bakoma: + basename, num = latex_to_bakoma[sym] + slanted = (basename == "cmmi10") or sym in self._slanted_symbols + font = self._get_font(basename) + elif len(sym) == 1: + slanted = (fontname == "it") + font = self._get_font(fontname) + if font is not None: + num = ord(sym) + if font is not None and font.get_char_index(num) != 0: + return font, num, slanted + else: + return self._stix_fallback._get_glyph(fontname, font_class, sym) + + # The Bakoma fonts contain many pre-sized alternatives for the + # delimiters. The AutoSizedChar class will use these alternatives + # and select the best (closest sized) glyph. + _size_alternatives = { + '(': [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'), + ('ex', '\xb5'), ('ex', '\xc3')], + ')': [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'), + ('ex', '\xb6'), ('ex', '\x21')], + '{': [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'), + ('ex', '\xbd'), ('ex', '\x28')], + '}': [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), + ('ex', '\xbe'), ('ex', '\x29')], + # The fourth size of '[' is mysteriously missing from the BaKoMa + # font, so I've omitted it for both '[' and ']' + '[': [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), + ('ex', '\x22')], + ']': [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), + ('ex', '\x23')], + r'\lfloor': [('ex', '\xa5'), ('ex', '\x6a'), + ('ex', '\xb9'), ('ex', '\x24')], + r'\rfloor': [('ex', '\xa6'), ('ex', '\x6b'), + ('ex', '\xba'), ('ex', '\x25')], + r'\lceil': [('ex', '\xa7'), ('ex', '\x6c'), + ('ex', '\xbb'), ('ex', '\x26')], + r'\rceil': [('ex', '\xa8'), ('ex', '\x6d'), + ('ex', '\xbc'), ('ex', '\x27')], + r'\langle': [('ex', '\xad'), ('ex', '\x44'), + ('ex', '\xbf'), ('ex', '\x2a')], + r'\rangle': [('ex', '\xae'), ('ex', '\x45'), + ('ex', '\xc0'), ('ex', '\x2b')], + r'\__sqrt__': [('ex', '\x70'), ('ex', '\x71'), + ('ex', '\x72'), ('ex', '\x73')], + r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'), + ('ex', '\xc2'), ('ex', '\x2d')], + r'/': [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'), + ('ex', '\xcb'), ('ex', '\x2c')], + r'\widehat': [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'), + ('ex', '\x64')], + r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'), + ('ex', '\x67')], + r'<': [('cal', 'h'), ('ex', 'D')], + r'>': [('cal', 'i'), ('ex', 'E')] + } + + for alias, target in [(r'\leftparen', '('), + (r'\rightparent', ')'), + (r'\leftbrace', '{'), + (r'\rightbrace', '}'), + (r'\leftbracket', '['), + (r'\rightbracket', ']'), + (r'\{', '{'), + (r'\}', '}'), + (r'\[', '['), + (r'\]', ']')]: + _size_alternatives[alias] = _size_alternatives[target] + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + return self._size_alternatives.get(sym, [(fontname, sym)]) + + +class UnicodeFonts(TruetypeFonts): + """ + An abstract base class for handling Unicode fonts. + + While some reasonably complete Unicode fonts (such as DejaVu) may + work in some situations, the only Unicode font I'm aware of with a + complete set of math symbols is STIX. + + This class will "fallback" on the Bakoma fonts when a required + symbol cannot be found in the font. + """ + + # Some glyphs are not present in the `cmr10` font, and must be brought in + # from `cmsy10`. Map the Unicode indices of those glyphs to the indices at + # which they are found in `cmsy10`. + _cmr10_substitutions = { + 0x00D7: 0x00A3, # Multiplication sign. + 0x2212: 0x00A1, # Minus sign. + } + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + # This must come first so the backend's owner is set correctly + fallback_rc = mpl.rcParams['mathtext.fallback'] + font_cls: type[TruetypeFonts] | None = { + 'stix': StixFonts, + 'stixsans': StixSansFonts, + 'cm': BakomaFonts + }.get(fallback_rc) + self._fallback_font = (font_cls(default_font_prop, load_glyph_flags) + if font_cls else None) + + super().__init__(default_font_prop, load_glyph_flags) + for texfont in "cal rm tt it bf sf bfit".split(): + prop = mpl.rcParams['mathtext.' + texfont] + font = findfont(prop) + self.fontmap[texfont] = font + prop = FontProperties('cmex10') + font = findfont(prop) + self.fontmap['ex'] = font + + # include STIX sized alternatives for glyphs if fallback is STIX + if isinstance(self._fallback_font, StixFonts): + stixsizedaltfonts = { + 0: 'STIXGeneral', + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym'} + + for size, name in stixsizedaltfonts.items(): + fullpath = findfont(name) + self.fontmap[size] = fullpath + self.fontmap[name] = fullpath + + _slanted_symbols = set(r"\int \oint".split()) + + def _map_virtual_font(self, fontname: str, font_class: str, + uniindex: int) -> tuple[str, int]: + return fontname, uniindex + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + try: + uniindex = get_unicode_index(sym) + found_symbol = True + except ValueError: + uniindex = ord('?') + found_symbol = False + _log.warning("No TeX to Unicode mapping for %a.", sym) + + fontname, uniindex = self._map_virtual_font( + fontname, font_class, uniindex) + + new_fontname = fontname + + # Only characters in the "Letter" class should be italicized in 'it' + # mode. Greek capital letters should be Roman. + if found_symbol: + if fontname == 'it' and uniindex < 0x10000: + char = chr(uniindex) + if (unicodedata.category(char)[0] != "L" + or unicodedata.name(char).startswith("GREEK CAPITAL")): + new_fontname = 'rm' + + slanted = (new_fontname == 'it') or sym in self._slanted_symbols + found_symbol = False + font = self._get_font(new_fontname) + if font is not None: + if (uniindex in self._cmr10_substitutions + and font.family_name == "cmr10"): + font = get_font( + cbook._get_data_path("fonts/ttf/cmsy10.ttf")) + uniindex = self._cmr10_substitutions[uniindex] + glyphindex = font.get_char_index(uniindex) + if glyphindex != 0: + found_symbol = True + + if not found_symbol: + if self._fallback_font: + if (fontname in ('it', 'regular') + and isinstance(self._fallback_font, StixFonts)): + fontname = 'rm' + + g = self._fallback_font._get_glyph(fontname, font_class, sym) + family = g[0].family_name + if family in list(BakomaFonts._fontmap.values()): + family = "Computer Modern" + _log.info("Substituting symbol %s from %s", sym, family) + return g + + else: + if (fontname in ('it', 'regular') + and isinstance(self, StixFonts)): + return self._get_glyph('rm', font_class, sym) + _log.warning("Font %r does not have a glyph for %a [U+%x], " + "substituting with a dummy symbol.", + new_fontname, sym, uniindex) + font = self._get_font('rm') + uniindex = 0xA4 # currency char, for lack of anything better + slanted = False + + return font, uniindex, slanted + + def get_sized_alternatives_for_symbol(self, fontname: str, + sym: str) -> list[tuple[str, str]]: + if self._fallback_font: + return self._fallback_font.get_sized_alternatives_for_symbol( + fontname, sym) + return [(fontname, sym)] + + +class DejaVuFonts(UnicodeFonts, metaclass=abc.ABCMeta): + _fontmap: dict[str | int, str] = {} + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + # This must come first so the backend's owner is set correctly + if isinstance(self, DejaVuSerifFonts): + self._fallback_font = StixFonts(default_font_prop, load_glyph_flags) + else: + self._fallback_font = StixSansFonts(default_font_prop, load_glyph_flags) + self.bakoma = BakomaFonts(default_font_prop, load_glyph_flags) + TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) + # Include Stix sized alternatives for glyphs + self._fontmap.update({ + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym', + }) + for key, name in self._fontmap.items(): + fullpath = findfont(name) + self.fontmap[key] = fullpath + self.fontmap[name] = fullpath + + def _get_glyph(self, fontname: str, font_class: str, + sym: str) -> tuple[FT2Font, int, bool]: + # Override prime symbol to use Bakoma. + if sym == r'\prime': + return self.bakoma._get_glyph(fontname, font_class, sym) + else: + # check whether the glyph is available in the display font + uniindex = get_unicode_index(sym) + font = self._get_font('ex') + if font is not None: + glyphindex = font.get_char_index(uniindex) + if glyphindex != 0: + return super()._get_glyph('ex', font_class, sym) + # otherwise return regular glyph + return super()._get_glyph(fontname, font_class, sym) + + +class DejaVuSerifFonts(DejaVuFonts): + """ + A font handling class for the DejaVu Serif fonts + + If a glyph is not found it will fallback to Stix Serif + """ + _fontmap = { + 'rm': 'DejaVu Serif', + 'it': 'DejaVu Serif:italic', + 'bf': 'DejaVu Serif:weight=bold', + 'bfit': 'DejaVu Serif:italic:bold', + 'sf': 'DejaVu Sans', + 'tt': 'DejaVu Sans Mono', + 'ex': 'DejaVu Serif Display', + 0: 'DejaVu Serif', + } + + +class DejaVuSansFonts(DejaVuFonts): + """ + A font handling class for the DejaVu Sans fonts + + If a glyph is not found it will fallback to Stix Sans + """ + _fontmap = { + 'rm': 'DejaVu Sans', + 'it': 'DejaVu Sans:italic', + 'bf': 'DejaVu Sans:weight=bold', + 'bfit': 'DejaVu Sans:italic:bold', + 'sf': 'DejaVu Sans', + 'tt': 'DejaVu Sans Mono', + 'ex': 'DejaVu Sans Display', + 0: 'DejaVu Sans', + } + + +class StixFonts(UnicodeFonts): + """ + A font handling class for the STIX fonts. + + In addition to what UnicodeFonts provides, this class: + + - supports "virtual fonts" which are complete alpha numeric + character sets with different font styles at special Unicode + code points, such as "Blackboard". + + - handles sized alternative characters for the STIXSizeX fonts. + """ + _fontmap: dict[str | int, str] = { + 'rm': 'STIXGeneral', + 'it': 'STIXGeneral:italic', + 'bf': 'STIXGeneral:weight=bold', + 'bfit': 'STIXGeneral:italic:bold', + 'nonunirm': 'STIXNonUnicode', + 'nonuniit': 'STIXNonUnicode:italic', + 'nonunibf': 'STIXNonUnicode:weight=bold', + 0: 'STIXGeneral', + 1: 'STIXSizeOneSym', + 2: 'STIXSizeTwoSym', + 3: 'STIXSizeThreeSym', + 4: 'STIXSizeFourSym', + 5: 'STIXSizeFiveSym', + } + _fallback_font = None + _sans = False + + def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): + TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) + for key, name in self._fontmap.items(): + fullpath = findfont(name) + self.fontmap[key] = fullpath + self.fontmap[name] = fullpath + + def _map_virtual_font(self, fontname: str, font_class: str, + uniindex: int) -> tuple[str, int]: + # Handle these "fonts" that are actually embedded in + # other fonts. + font_mapping = stix_virtual_fonts.get(fontname) + if (self._sans and font_mapping is None + and fontname not in ('regular', 'default')): + font_mapping = stix_virtual_fonts['sf'] + doing_sans_conversion = True + else: + doing_sans_conversion = False + + if isinstance(font_mapping, dict): + try: + mapping = font_mapping[font_class] + except KeyError: + mapping = font_mapping['rm'] + elif isinstance(font_mapping, list): + mapping = font_mapping + else: + mapping = None + + if mapping is not None: + # Binary search for the source glyph + lo = 0 + hi = len(mapping) + while lo < hi: + mid = (lo+hi)//2 + range = mapping[mid] + if uniindex < range[0]: + hi = mid + elif uniindex <= range[1]: + break + else: + lo = mid + 1 + + if range[0] <= uniindex <= range[1]: + uniindex = uniindex - range[0] + range[3] + fontname = range[2] + elif not doing_sans_conversion: + # This will generate a dummy character + uniindex = 0x1 + fontname = mpl.rcParams['mathtext.default'] + + # Fix some incorrect glyphs. + if fontname in ('rm', 'it'): + uniindex = stix_glyph_fixes.get(uniindex, uniindex) + + # Handle private use area glyphs + if fontname in ('it', 'rm', 'bf', 'bfit') and 0xe000 <= uniindex <= 0xf8ff: + fontname = 'nonuni' + fontname + + return fontname, uniindex + + @functools.cache + def get_sized_alternatives_for_symbol( # type: ignore[override] + self, + fontname: str, + sym: str) -> list[tuple[str, str]] | list[tuple[int, str]]: + fixes = { + '\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']', + '<': '\N{MATHEMATICAL LEFT ANGLE BRACKET}', + '>': '\N{MATHEMATICAL RIGHT ANGLE BRACKET}', + } + sym = fixes.get(sym, sym) + try: + uniindex = get_unicode_index(sym) + except ValueError: + return [(fontname, sym)] + alternatives = [(i, chr(uniindex)) for i in range(6) + if self._get_font(i).get_char_index(uniindex) != 0] + # The largest size of the radical symbol in STIX has incorrect + # metrics that cause it to be disconnected from the stem. + if sym == r'\__sqrt__': + alternatives = alternatives[:-1] + return alternatives + + +class StixSansFonts(StixFonts): + """ + A font handling class for the STIX fonts (that uses sans-serif + characters by default). + """ + _sans = True + + +############################################################################## +# TeX-LIKE BOX MODEL + +# The following is based directly on the document 'woven' from the +# TeX82 source code. This information is also available in printed +# form: +# +# Knuth, Donald E.. 1986. Computers and Typesetting, Volume B: +# TeX: The Program. Addison-Wesley Professional. +# +# The most relevant "chapters" are: +# Data structures for boxes and their friends +# Shipping pages out (ship()) +# Packaging (hpack() and vpack()) +# Data structures for math mode +# Subroutines for math mode +# Typesetting math formulas +# +# Many of the docstrings below refer to a numbered "node" in that +# book, e.g., node123 +# +# Note that (as TeX) y increases downward, unlike many other parts of +# matplotlib. + +# How much text shrinks when going to the next-smallest level. +SHRINK_FACTOR = 0.7 +# The number of different sizes of chars to use, beyond which they will not +# get any smaller +NUM_SIZE_LEVELS = 6 + + +class FontConstantsBase: + """ + A set of constants that controls how certain things, such as sub- + and superscripts are laid out. These are all metrics that can't + be reliably retrieved from the font metrics in the font itself. + """ + # Percentage of x-height of additional horiz. space after sub/superscripts + script_space: T.ClassVar[float] = 0.05 + + # Percentage of x-height that sub/superscripts drop below the baseline + subdrop: T.ClassVar[float] = 0.4 + + # Percentage of x-height that superscripts are raised from the baseline + sup1: T.ClassVar[float] = 0.7 + + # Percentage of x-height that subscripts drop below the baseline + sub1: T.ClassVar[float] = 0.3 + + # Percentage of x-height that subscripts drop below the baseline when a + # superscript is present + sub2: T.ClassVar[float] = 0.5 + + # Percentage of x-height that sub/superscripts are offset relative to the + # nucleus edge for non-slanted nuclei + delta: T.ClassVar[float] = 0.025 + + # Additional percentage of last character height above 2/3 of the + # x-height that superscripts are offset relative to the subscript + # for slanted nuclei + delta_slanted: T.ClassVar[float] = 0.2 + + # Percentage of x-height that superscripts and subscripts are offset for + # integrals + delta_integral: T.ClassVar[float] = 0.1 + + +class ComputerModernFontConstants(FontConstantsBase): + script_space = 0.075 + subdrop = 0.2 + sup1 = 0.45 + sub1 = 0.2 + sub2 = 0.3 + delta = 0.075 + delta_slanted = 0.3 + delta_integral = 0.3 + + +class STIXFontConstants(FontConstantsBase): + script_space = 0.1 + sup1 = 0.8 + sub2 = 0.6 + delta = 0.05 + delta_slanted = 0.3 + delta_integral = 0.3 + + +class STIXSansFontConstants(FontConstantsBase): + script_space = 0.05 + sup1 = 0.8 + delta_slanted = 0.6 + delta_integral = 0.3 + + +class DejaVuSerifFontConstants(FontConstantsBase): + pass + + +class DejaVuSansFontConstants(FontConstantsBase): + pass + + +# Maps font family names to the FontConstantBase subclass to use +_font_constant_mapping = { + 'DejaVu Sans': DejaVuSansFontConstants, + 'DejaVu Sans Mono': DejaVuSansFontConstants, + 'DejaVu Serif': DejaVuSerifFontConstants, + 'cmb10': ComputerModernFontConstants, + 'cmex10': ComputerModernFontConstants, + 'cmmi10': ComputerModernFontConstants, + 'cmr10': ComputerModernFontConstants, + 'cmss10': ComputerModernFontConstants, + 'cmsy10': ComputerModernFontConstants, + 'cmtt10': ComputerModernFontConstants, + 'STIXGeneral': STIXFontConstants, + 'STIXNonUnicode': STIXFontConstants, + 'STIXSizeFiveSym': STIXFontConstants, + 'STIXSizeFourSym': STIXFontConstants, + 'STIXSizeThreeSym': STIXFontConstants, + 'STIXSizeTwoSym': STIXFontConstants, + 'STIXSizeOneSym': STIXFontConstants, + # Map the fonts we used to ship, just for good measure + 'Bitstream Vera Sans': DejaVuSansFontConstants, + 'Bitstream Vera': DejaVuSansFontConstants, + } + + +def _get_font_constant_set(state: ParserState) -> type[FontConstantsBase]: + constants = _font_constant_mapping.get( + state.fontset._get_font(state.font).family_name, FontConstantsBase) + # STIX sans isn't really its own fonts, just different code points + # in the STIX fonts, so we have to detect this one separately. + if (constants is STIXFontConstants and + isinstance(state.fontset, StixSansFonts)): + return STIXSansFontConstants + return constants + + +class Node: + """A node in the TeX box model.""" + + def __init__(self) -> None: + self.size = 0 + + def __repr__(self) -> str: + return type(self).__name__ + + def get_kerning(self, next: Node | None) -> float: + return 0.0 + + def shrink(self) -> None: + """ + Shrinks one level smaller. There are only three levels of + sizes, after which things will no longer get smaller. + """ + self.size += 1 + + def render(self, output: Output, x: float, y: float) -> None: + """Render this node.""" + + +class Box(Node): + """A node with a physical location.""" + + def __init__(self, width: float, height: float, depth: float) -> None: + super().__init__() + self.width = width + self.height = height + self.depth = depth + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.width *= SHRINK_FACTOR + self.height *= SHRINK_FACTOR + self.depth *= SHRINK_FACTOR + + def render(self, output: Output, # type: ignore[override] + x1: float, y1: float, x2: float, y2: float) -> None: + pass + + +class Vbox(Box): + """A box with only height (zero width).""" + + def __init__(self, height: float, depth: float): + super().__init__(0., height, depth) + + +class Hbox(Box): + """A box with only width (zero height and depth).""" + + def __init__(self, width: float): + super().__init__(width, 0., 0.) + + +class Char(Node): + """ + A single character. + + Unlike TeX, the font information and metrics are stored with each `Char` + to make it easier to lookup the font metrics when needed. Note that TeX + boxes have a width, height, and depth, unlike Type1 and TrueType which use + a full bounding box and an advance in the x-direction. The metrics must + be converted to the TeX model, and the advance (if different from width) + must be converted into a `Kern` node when the `Char` is added to its parent + `Hlist`. + """ + + def __init__(self, c: str, state: ParserState): + super().__init__() + self.c = c + self.fontset = state.fontset + self.font = state.font + self.font_class = state.font_class + self.fontsize = state.fontsize + self.dpi = state.dpi + # The real width, height and depth will be set during the + # pack phase, after we know the real fontsize + self._update_metrics() + + def __repr__(self) -> str: + return '`%s`' % self.c + + def _update_metrics(self) -> None: + metrics = self._metrics = self.fontset.get_metrics( + self.font, self.font_class, self.c, self.fontsize, self.dpi) + if self.c == ' ': + self.width = metrics.advance + else: + self.width = metrics.width + self.height = metrics.iceberg + self.depth = -(metrics.iceberg - metrics.height) + + def is_slanted(self) -> bool: + return self._metrics.slanted + + def get_kerning(self, next: Node | None) -> float: + """ + Return the amount of kerning between this and the given character. + + This method is called when characters are strung together into `Hlist` + to create `Kern` nodes. + """ + advance = self._metrics.advance - self.width + kern = 0. + if isinstance(next, Char): + kern = self.fontset.get_kern( + self.font, self.font_class, self.c, self.fontsize, + next.font, next.font_class, next.c, next.fontsize, + self.dpi) + return advance + kern + + def render(self, output: Output, x: float, y: float) -> None: + self.fontset.render_glyph( + output, x, y, + self.font, self.font_class, self.c, self.fontsize, self.dpi) + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.fontsize *= SHRINK_FACTOR + self.width *= SHRINK_FACTOR + self.height *= SHRINK_FACTOR + self.depth *= SHRINK_FACTOR + + +class Accent(Char): + """ + The font metrics need to be dealt with differently for accents, + since they are already offset correctly from the baseline in + TrueType fonts. + """ + def _update_metrics(self) -> None: + metrics = self._metrics = self.fontset.get_metrics( + self.font, self.font_class, self.c, self.fontsize, self.dpi) + self.width = metrics.xmax - metrics.xmin + self.height = metrics.ymax - metrics.ymin + self.depth = 0 + + def shrink(self) -> None: + super().shrink() + self._update_metrics() + + def render(self, output: Output, x: float, y: float) -> None: + self.fontset.render_glyph( + output, x - self._metrics.xmin, y + self._metrics.ymin, + self.font, self.font_class, self.c, self.fontsize, self.dpi) + + +class List(Box): + """A list of nodes (either horizontal or vertical).""" + + def __init__(self, elements: T.Sequence[Node]): + super().__init__(0., 0., 0.) + self.shift_amount = 0. # An arbitrary offset + self.children = [*elements] # The child nodes of this list + # The following parameters are set in the vpack and hpack functions + self.glue_set = 0. # The glue setting of this list + self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching + self.glue_order = 0 # The order of infinity (0 - 3) for the glue + + def __repr__(self) -> str: + return '{}[{}]'.format( + super().__repr__(), + self.width, self.height, + self.depth, self.shift_amount, + ', '.join([repr(x) for x in self.children])) + + def _set_glue(self, x: float, sign: int, totals: list[float], + error_type: str) -> None: + self.glue_order = o = next( + # Highest order of glue used by the members of this list. + (i for i in range(len(totals))[::-1] if totals[i] != 0), 0) + self.glue_sign = sign + if totals[o] != 0.: + self.glue_set = x / totals[o] + else: + self.glue_sign = 0 + self.glue_ratio = 0. + if o == 0: + if len(self.children): + _log.warning("%s %s: %r", + error_type, type(self).__name__, self) + + def shrink(self) -> None: + for child in self.children: + child.shrink() + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.shift_amount *= SHRINK_FACTOR + self.glue_set *= SHRINK_FACTOR + + +class Hlist(List): + """A horizontal list of boxes.""" + + def __init__(self, elements: T.Sequence[Node], w: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional', + do_kern: bool = True): + super().__init__(elements) + if do_kern: + self.kern() + self.hpack(w=w, m=m) + + def kern(self) -> None: + """ + Insert `Kern` nodes between `Char` nodes to set kerning. + + The `Char` nodes themselves determine the amount of kerning they need + (in `~Char.get_kerning`), and this function just creates the correct + linked list. + """ + new_children = [] + num_children = len(self.children) + if num_children: + for i in range(num_children): + elem = self.children[i] + if i < num_children - 1: + next = self.children[i + 1] + else: + next = None + + new_children.append(elem) + kerning_distance = elem.get_kerning(next) + if kerning_distance != 0.: + kern = Kern(kerning_distance) + new_children.append(kern) + self.children = new_children + + def hpack(self, w: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional') -> None: + r""" + Compute the dimensions of the resulting boxes, and adjust the glue if + one of those dimensions is pre-specified. The computed sizes normally + enclose all of the material inside the new box; but some items may + stick out if negative glue is used, if the box is overfull, or if a + ``\vbox`` includes other boxes that have been shifted left. + + Parameters + ---------- + w : float, default: 0 + A width. + m : {'exactly', 'additional'}, default: 'additional' + Whether to produce a box whose width is 'exactly' *w*; or a box + with the natural width of the contents, plus *w* ('additional'). + + Notes + ----- + The defaults produce a box with the natural width of the contents. + """ + # I don't know why these get reset in TeX. Shift_amount is pretty + # much useless if we do. + # self.shift_amount = 0. + h = 0. + d = 0. + x = 0. + total_stretch = [0.] * 4 + total_shrink = [0.] * 4 + for p in self.children: + if isinstance(p, Char): + x += p.width + h = max(h, p.height) + d = max(d, p.depth) + elif isinstance(p, Box): + x += p.width + if not np.isinf(p.height) and not np.isinf(p.depth): + s = getattr(p, 'shift_amount', 0.) + h = max(h, p.height - s) + d = max(d, p.depth + s) + elif isinstance(p, Glue): + glue_spec = p.glue_spec + x += glue_spec.width + total_stretch[glue_spec.stretch_order] += glue_spec.stretch + total_shrink[glue_spec.shrink_order] += glue_spec.shrink + elif isinstance(p, Kern): + x += p.width + self.height = h + self.depth = d + + if m == 'additional': + w += x + self.width = w + x = w - x + + if x == 0.: + self.glue_sign = 0 + self.glue_order = 0 + self.glue_ratio = 0. + return + if x > 0.: + self._set_glue(x, 1, total_stretch, "Overful") + else: + self._set_glue(x, -1, total_shrink, "Underful") + + +class Vlist(List): + """A vertical list of boxes.""" + + def __init__(self, elements: T.Sequence[Node], h: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional'): + super().__init__(elements) + self.vpack(h=h, m=m) + + def vpack(self, h: float = 0.0, + m: T.Literal['additional', 'exactly'] = 'additional', + l: float = np.inf) -> None: + """ + Compute the dimensions of the resulting boxes, and to adjust the glue + if one of those dimensions is pre-specified. + + Parameters + ---------- + h : float, default: 0 + A height. + m : {'exactly', 'additional'}, default: 'additional' + Whether to produce a box whose height is 'exactly' *h*; or a box + with the natural height of the contents, plus *h* ('additional'). + l : float, default: np.inf + The maximum height. + + Notes + ----- + The defaults produce a box with the natural height of the contents. + """ + # I don't know why these get reset in TeX. Shift_amount is pretty + # much useless if we do. + # self.shift_amount = 0. + w = 0. + d = 0. + x = 0. + total_stretch = [0.] * 4 + total_shrink = [0.] * 4 + for p in self.children: + if isinstance(p, Box): + x += d + p.height + d = p.depth + if not np.isinf(p.width): + s = getattr(p, 'shift_amount', 0.) + w = max(w, p.width + s) + elif isinstance(p, Glue): + x += d + d = 0. + glue_spec = p.glue_spec + x += glue_spec.width + total_stretch[glue_spec.stretch_order] += glue_spec.stretch + total_shrink[glue_spec.shrink_order] += glue_spec.shrink + elif isinstance(p, Kern): + x += d + p.width + d = 0. + elif isinstance(p, Char): + raise RuntimeError( + "Internal mathtext error: Char node found in Vlist") + + self.width = w + if d > l: + x += d - l + self.depth = l + else: + self.depth = d + + if m == 'additional': + h += x + self.height = h + x = h - x + + if x == 0: + self.glue_sign = 0 + self.glue_order = 0 + self.glue_ratio = 0. + return + + if x > 0.: + self._set_glue(x, 1, total_stretch, "Overful") + else: + self._set_glue(x, -1, total_shrink, "Underful") + + +class Rule(Box): + """ + A solid black rectangle. + + It has *width*, *depth*, and *height* fields just as in an `Hlist`. + However, if any of these dimensions is inf, the actual value will be + determined by running the rule up to the boundary of the innermost + enclosing box. This is called a "running dimension". The width is never + running in an `Hlist`; the height and depth are never running in a `Vlist`. + """ + + def __init__(self, width: float, height: float, depth: float, state: ParserState): + super().__init__(width, height, depth) + self.fontset = state.fontset + + def render(self, output: Output, # type: ignore[override] + x: float, y: float, w: float, h: float) -> None: + self.fontset.render_rect_filled(output, x, y, x + w, y + h) + + +class Hrule(Rule): + """Convenience class to create a horizontal rule.""" + + def __init__(self, state: ParserState, thickness: float | None = None): + if thickness is None: + thickness = state.get_current_underline_thickness() + height = depth = thickness * 0.5 + super().__init__(np.inf, height, depth, state) + + +class Vrule(Rule): + """Convenience class to create a vertical rule.""" + + def __init__(self, state: ParserState): + thickness = state.get_current_underline_thickness() + super().__init__(thickness, np.inf, np.inf, state) + + +class _GlueSpec(NamedTuple): + width: float + stretch: float + stretch_order: int + shrink: float + shrink_order: int + + +_GlueSpec._named = { # type: ignore[attr-defined] + 'fil': _GlueSpec(0., 1., 1, 0., 0), + 'fill': _GlueSpec(0., 1., 2, 0., 0), + 'filll': _GlueSpec(0., 1., 3, 0., 0), + 'neg_fil': _GlueSpec(0., 0., 0, 1., 1), + 'neg_fill': _GlueSpec(0., 0., 0, 1., 2), + 'neg_filll': _GlueSpec(0., 0., 0, 1., 3), + 'empty': _GlueSpec(0., 0., 0, 0., 0), + 'ss': _GlueSpec(0., 1., 1, -1., 1), +} + + +class Glue(Node): + """ + Most of the information in this object is stored in the underlying + ``_GlueSpec`` class, which is shared between multiple glue objects. + (This is a memory optimization which probably doesn't matter anymore, but + it's easier to stick to what TeX does.) + """ + + def __init__(self, + glue_type: _GlueSpec | T.Literal["fil", "fill", "filll", + "neg_fil", "neg_fill", "neg_filll", + "empty", "ss"]): + super().__init__() + if isinstance(glue_type, str): + glue_spec = _GlueSpec._named[glue_type] # type: ignore[attr-defined] + elif isinstance(glue_type, _GlueSpec): + glue_spec = glue_type + else: + raise ValueError("glue_type must be a glue spec name or instance") + self.glue_spec = glue_spec + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + g = self.glue_spec + self.glue_spec = g._replace(width=g.width * SHRINK_FACTOR) + + +class HCentered(Hlist): + """ + A convenience class to create an `Hlist` whose contents are + centered within its enclosing box. + """ + + def __init__(self, elements: list[Node]): + super().__init__([Glue('ss'), *elements, Glue('ss')], do_kern=False) + + +class VCentered(Vlist): + """ + A convenience class to create a `Vlist` whose contents are + centered within its enclosing box. + """ + + def __init__(self, elements: list[Node]): + super().__init__([Glue('ss'), *elements, Glue('ss')]) + + +class Kern(Node): + """ + A `Kern` node has a width field to specify a (normally + negative) amount of spacing. This spacing correction appears in + horizontal lists between letters like A and V when the font + designer said that it looks better to move them closer together or + further apart. A kern node can also appear in a vertical list, + when its *width* denotes additional spacing in the vertical + direction. + """ + + height = 0 + depth = 0 + + def __init__(self, width: float): + super().__init__() + self.width = width + + def __repr__(self) -> str: + return "k%.02f" % self.width + + def shrink(self) -> None: + super().shrink() + if self.size < NUM_SIZE_LEVELS: + self.width *= SHRINK_FACTOR + + +class AutoHeightChar(Hlist): + """ + A character as close to the given height and depth as possible. + + When using a font with multiple height versions of some characters (such as + the BaKoMa fonts), the correct glyph will be selected, otherwise this will + always just return a scaled version of the glyph. + """ + + def __init__(self, c: str, height: float, depth: float, state: ParserState, + always: bool = False, factor: float | None = None): + alternatives = state.fontset.get_sized_alternatives_for_symbol( + state.font, c) + + xHeight = state.fontset.get_xheight( + state.font, state.fontsize, state.dpi) + + state = state.copy() + target_total = height + depth + for fontname, sym in alternatives: + state.font = fontname + char = Char(sym, state) + # Ensure that size 0 is chosen when the text is regular sized but + # with descender glyphs by subtracting 0.2 * xHeight + if char.height + char.depth >= target_total - 0.2 * xHeight: + break + + shift = 0.0 + if state.font != 0 or len(alternatives) == 1: + if factor is None: + factor = target_total / (char.height + char.depth) + state.fontsize *= factor + char = Char(sym, state) + + shift = (depth - char.depth) + + super().__init__([char]) + self.shift_amount = shift + + +class AutoWidthChar(Hlist): + """ + A character as close to the given width as possible. + + When using a font with multiple width versions of some characters (such as + the BaKoMa fonts), the correct glyph will be selected, otherwise this will + always just return a scaled version of the glyph. + """ + + def __init__(self, c: str, width: float, state: ParserState, always: bool = False, + char_class: type[Char] = Char): + alternatives = state.fontset.get_sized_alternatives_for_symbol( + state.font, c) + + state = state.copy() + for fontname, sym in alternatives: + state.font = fontname + char = char_class(sym, state) + if char.width >= width: + break + + factor = width / char.width + state.fontsize *= factor + char = char_class(sym, state) + + super().__init__([char]) + self.width = char.width + + +def ship(box: Box, xy: tuple[float, float] = (0, 0)) -> Output: + """ + Ship out *box* at offset *xy*, converting it to an `Output`. + + Since boxes can be inside of boxes inside of boxes, the main work of `ship` + is done by two mutually recursive routines, `hlist_out` and `vlist_out`, + which traverse the `Hlist` nodes and `Vlist` nodes inside of horizontal + and vertical boxes. The global variables used in TeX to store state as it + processes have become local variables here. + """ + ox, oy = xy + cur_v = 0. + cur_h = 0. + off_h = ox + off_v = oy + box.height + output = Output(box) + + def clamp(value: float) -> float: + return -1e9 if value < -1e9 else +1e9 if value > +1e9 else value + + def hlist_out(box: Hlist) -> None: + nonlocal cur_v, cur_h, off_h, off_v + + cur_g = 0 + cur_glue = 0. + glue_order = box.glue_order + glue_sign = box.glue_sign + base_line = cur_v + left_edge = cur_h + + for p in box.children: + if isinstance(p, Char): + p.render(output, cur_h + off_h, cur_v + off_v) + cur_h += p.width + elif isinstance(p, Kern): + cur_h += p.width + elif isinstance(p, List): + # node623 + if len(p.children) == 0: + cur_h += p.width + else: + edge = cur_h + cur_v = base_line + p.shift_amount + if isinstance(p, Hlist): + hlist_out(p) + elif isinstance(p, Vlist): + # p.vpack(box.height + box.depth, 'exactly') + vlist_out(p) + else: + assert False, "unreachable code" + cur_h = edge + p.width + cur_v = base_line + elif isinstance(p, Box): + # node624 + rule_height = p.height + rule_depth = p.depth + rule_width = p.width + if np.isinf(rule_height): + rule_height = box.height + if np.isinf(rule_depth): + rule_depth = box.depth + if rule_height > 0 and rule_width > 0: + cur_v = base_line + rule_depth + p.render(output, + cur_h + off_h, cur_v + off_v, + rule_width, rule_height) + cur_v = base_line + cur_h += rule_width + elif isinstance(p, Glue): + # node625 + glue_spec = p.glue_spec + rule_width = glue_spec.width - cur_g + if glue_sign != 0: # normal + if glue_sign == 1: # stretching + if glue_spec.stretch_order == glue_order: + cur_glue += glue_spec.stretch + cur_g = round(clamp(box.glue_set * cur_glue)) + elif glue_spec.shrink_order == glue_order: + cur_glue += glue_spec.shrink + cur_g = round(clamp(box.glue_set * cur_glue)) + rule_width += cur_g + cur_h += rule_width + + def vlist_out(box: Vlist) -> None: + nonlocal cur_v, cur_h, off_h, off_v + + cur_g = 0 + cur_glue = 0. + glue_order = box.glue_order + glue_sign = box.glue_sign + left_edge = cur_h + cur_v -= box.height + top_edge = cur_v + + for p in box.children: + if isinstance(p, Kern): + cur_v += p.width + elif isinstance(p, List): + if len(p.children) == 0: + cur_v += p.height + p.depth + else: + cur_v += p.height + cur_h = left_edge + p.shift_amount + save_v = cur_v + p.width = box.width + if isinstance(p, Hlist): + hlist_out(p) + elif isinstance(p, Vlist): + vlist_out(p) + else: + assert False, "unreachable code" + cur_v = save_v + p.depth + cur_h = left_edge + elif isinstance(p, Box): + rule_height = p.height + rule_depth = p.depth + rule_width = p.width + if np.isinf(rule_width): + rule_width = box.width + rule_height += rule_depth + if rule_height > 0 and rule_depth > 0: + cur_v += rule_height + p.render(output, + cur_h + off_h, cur_v + off_v, + rule_width, rule_height) + elif isinstance(p, Glue): + glue_spec = p.glue_spec + rule_height = glue_spec.width - cur_g + if glue_sign != 0: # normal + if glue_sign == 1: # stretching + if glue_spec.stretch_order == glue_order: + cur_glue += glue_spec.stretch + cur_g = round(clamp(box.glue_set * cur_glue)) + elif glue_spec.shrink_order == glue_order: # shrinking + cur_glue += glue_spec.shrink + cur_g = round(clamp(box.glue_set * cur_glue)) + rule_height += cur_g + cur_v += rule_height + elif isinstance(p, Char): + raise RuntimeError( + "Internal mathtext error: Char node found in vlist") + + assert isinstance(box, Hlist) + hlist_out(box) + return output + + +############################################################################## +# PARSER + + +def Error(msg: str) -> ParserElement: + """Helper class to raise parser errors.""" + def raise_error(s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, loc, msg) + + return Empty().setParseAction(raise_error) + + +class ParserState: + """ + Parser state. + + States are pushed and popped from a stack as necessary, and the "current" + state is always at the top of the stack. + + Upon entering and leaving a group { } or math/non-math, the stack is pushed + and popped accordingly. + """ + + def __init__(self, fontset: Fonts, font: str, font_class: str, fontsize: float, + dpi: float): + self.fontset = fontset + self._font = font + self.font_class = font_class + self.fontsize = fontsize + self.dpi = dpi + + def copy(self) -> ParserState: + return copy.copy(self) + + @property + def font(self) -> str: + return self._font + + @font.setter + def font(self, name: str) -> None: + if name in ('rm', 'it', 'bf', 'bfit'): + self.font_class = name + self._font = name + + def get_current_underline_thickness(self) -> float: + """Return the underline thickness for this state.""" + return self.fontset.get_underline_thickness( + self.font, self.fontsize, self.dpi) + + +def cmd(expr: str, args: ParserElement) -> ParserElement: + r""" + Helper to define TeX commands. + + ``cmd("\cmd", args)`` is equivalent to + ``"\cmd" - (args | Error("Expected \cmd{arg}{...}"))`` where the names in + the error message are taken from element names in *args*. If *expr* + already includes arguments (e.g. "\cmd{arg}{...}"), then they are stripped + when constructing the parse element, but kept (and *expr* is used as is) in + the error message. + """ + + def names(elt: ParserElement) -> T.Generator[str, None, None]: + if isinstance(elt, ParseExpression): + for expr in elt.exprs: + yield from names(expr) + elif elt.resultsName: + yield elt.resultsName + + csname = expr.split("{", 1)[0] + err = (csname + "".join("{%s}" % name for name in names(args)) + if expr == csname else expr) + return csname - (args | Error(f"Expected {err}")) + + +class Parser: + """ + A pyparsing-based parser for strings containing math expressions. + + Raw text may also appear outside of pairs of ``$``. + + The grammar is based directly on that in TeX, though it cuts a few corners. + """ + + class _MathStyle(enum.Enum): + DISPLAYSTYLE = 0 + TEXTSTYLE = 1 + SCRIPTSTYLE = 2 + SCRIPTSCRIPTSTYLE = 3 + + _binary_operators = set( + '+ * - \N{MINUS SIGN}' + r''' + \pm \sqcap \rhd + \mp \sqcup \unlhd + \times \vee \unrhd + \div \wedge \oplus + \ast \setminus \ominus + \star \wr \otimes + \circ \diamond \oslash + \bullet \bigtriangleup \odot + \cdot \bigtriangledown \bigcirc + \cap \triangleleft \dagger + \cup \triangleright \ddagger + \uplus \lhd \amalg + \dotplus \dotminus \Cap + \Cup \barwedge \boxdot + \boxminus \boxplus \boxtimes + \curlyvee \curlywedge \divideontimes + \doublebarwedge \leftthreetimes \rightthreetimes + \slash \veebar \barvee + \cupdot \intercal \amalg + \circledcirc \circleddash \circledast + \boxbar \obar \merge + \minuscolon \dotsminusdots + '''.split()) + + _relation_symbols = set(r''' + = < > : + \leq \geq \equiv \models + \prec \succ \sim \perp + \preceq \succeq \simeq \mid + \ll \gg \asymp \parallel + \subset \supset \approx \bowtie + \subseteq \supseteq \cong \Join + \sqsubset \sqsupset \neq \smile + \sqsubseteq \sqsupseteq \doteq \frown + \in \ni \propto \vdash + \dashv \dots \doteqdot \leqq + \geqq \lneqq \gneqq \lessgtr + \leqslant \geqslant \eqgtr \eqless + \eqslantless \eqslantgtr \lesseqgtr \backsim + \backsimeq \lesssim \gtrsim \precsim + \precnsim \gnsim \lnsim \succsim + \succnsim \nsim \lesseqqgtr \gtreqqless + \gtreqless \subseteqq \supseteqq \subsetneqq + \supsetneqq \lessapprox \approxeq \gtrapprox + \precapprox \succapprox \precnapprox \succnapprox + \npreccurlyeq \nsucccurlyeq \nsqsubseteq \nsqsupseteq + \sqsubsetneq \sqsupsetneq \nlesssim \ngtrsim + \nlessgtr \ngtrless \lnapprox \gnapprox + \napprox \approxeq \approxident \lll + \ggg \nparallel \Vdash \Vvdash + \nVdash \nvdash \vDash \nvDash + \nVDash \oequal \simneqq \triangle + \triangleq \triangleeq \triangleleft + \triangleright \ntriangleleft \ntriangleright + \trianglelefteq \ntrianglelefteq \trianglerighteq + \ntrianglerighteq \blacktriangleleft \blacktriangleright + \equalparallel \measuredrightangle \varlrtriangle + \Doteq \Bumpeq \Subset \Supset + \backepsilon \because \therefore \bot + \top \bumpeq \circeq \coloneq + \curlyeqprec \curlyeqsucc \eqcirc \eqcolon + \eqsim \fallingdotseq \gtrdot \gtrless + \ltimes \rtimes \lessdot \ne + \ncong \nequiv \ngeq \ngtr + \nleq \nless \nmid \notin + \nprec \nsubset \nsubseteq \nsucc + \nsupset \nsupseteq \pitchfork \preccurlyeq + \risingdotseq \subsetneq \succcurlyeq \supsetneq + \varpropto \vartriangleleft \scurel + \vartriangleright \rightangle \equal \backcong + \eqdef \wedgeq \questeq \between + \veeeq \disin \varisins \isins + \isindot \varisinobar \isinobar \isinvb + \isinE \nisd \varnis \nis + \varniobar \niobar \bagmember \ratio + \Equiv \stareq \measeq \arceq + \rightassert \rightModels \smallin \smallowns + \notsmallowns \nsimeq'''.split()) + + _arrow_symbols = set(r""" + \leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow + \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow + \Longrightarrow \Downarrow \leftrightarrow \updownarrow + \longleftrightarrow \updownarrow \Leftrightarrow + \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow + \hookleftarrow \hookrightarrow \searrow \leftharpoonup + \rightharpoonup \swarrow \leftharpoondown \rightharpoondown + \nwarrow \rightleftharpoons \leadsto \dashrightarrow + \dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow + \Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft + \leftrightharpoons \curvearrowleft \circlearrowleft \Lsh + \upuparrows \upharpoonleft \downharpoonleft \multimap + \leftrightsquigarrow \rightrightarrows \rightleftarrows + \rightrightarrows \rightleftarrows \twoheadrightarrow + \rightarrowtail \looparrowright \rightleftharpoons + \curvearrowright \circlearrowright \Rsh \downdownarrows + \upharpoonright \downharpoonright \rightsquigarrow \nleftarrow + \nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow + \nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow + \leftsquigarrow \overleftarrow \overleftrightarrow \cwopencirclearrow + \downzigzagarrow \cupleftarrow \rightzigzagarrow \twoheaddownarrow + \updownarrowbar \twoheaduparrow \rightarrowbar \updownarrows + \barleftarrow \mapsfrom \mapsdown \mapsup \Ldsh \Rdsh + """.split()) + + _spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols + + _punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split()) + + _overunder_symbols = set(r''' + \sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee + \bigwedge \bigodot \bigotimes \bigoplus \biguplus + '''.split()) + + _overunder_functions = set("lim liminf limsup sup max min".split()) + + _dropsub_symbols = set(r'\int \oint \iint \oiint \iiint \oiiint \iiiint'.split()) + + _fontnames = set("rm cal it tt sf bf bfit " + "default bb frak scr regular".split()) + + _function_names = set(""" + arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim + liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan + coth inf max tanh""".split()) + + _ambi_delims = set(r""" + | \| / \backslash \uparrow \downarrow \updownarrow \Uparrow + \Downarrow \Updownarrow . \vert \Vert""".split()) + _left_delims = set(r""" + ( [ \{ < \lfloor \langle \lceil \lbrace \leftbrace \lbrack \leftparen \lgroup + """.split()) + _right_delims = set(r""" + ) ] \} > \rfloor \rangle \rceil \rbrace \rightbrace \rbrack \rightparen \rgroup + """.split()) + _delims = _left_delims | _right_delims | _ambi_delims + + _small_greek = set([unicodedata.name(chr(i)).split()[-1].lower() for i in + range(ord('\N{GREEK SMALL LETTER ALPHA}'), + ord('\N{GREEK SMALL LETTER OMEGA}') + 1)]) + _latin_alphabets = set(string.ascii_letters) + + def __init__(self) -> None: + p = types.SimpleNamespace() + + def set_names_and_parse_actions() -> None: + for key, val in vars(p).items(): + if not key.startswith('_'): + # Set names on (almost) everything -- very useful for debugging + # token, placeable, and auto_delim are forward references which + # are left without names to ensure useful error messages + if key not in ("token", "placeable", "auto_delim"): + val.setName(key) + # Set actions + if hasattr(self, key): + val.setParseAction(getattr(self, key)) + + # Root definitions. + + # In TeX parlance, a csname is a control sequence name (a "\foo"). + def csnames(group: str, names: Iterable[str]) -> Regex: + ends_with_alpha = [] + ends_with_nonalpha = [] + for name in names: + if name[-1].isalpha(): + ends_with_alpha.append(name) + else: + ends_with_nonalpha.append(name) + return Regex( + r"\\(?P<{group}>(?:{alpha})(?![A-Za-z]){additional}{nonalpha})".format( + group=group, + alpha="|".join(map(re.escape, ends_with_alpha)), + additional="|" if ends_with_nonalpha else "", + nonalpha="|".join(map(re.escape, ends_with_nonalpha)), + ) + ) + + p.float_literal = Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)") + p.space = oneOf(self._space_widths)("space") + + p.style_literal = oneOf( + [str(e.value) for e in self._MathStyle])("style_literal") + + p.symbol = Regex( + r"[a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|\U00000080-\U0001ffff]" + r"|\\[%${}\[\]_|]" + + r"|\\(?:{})(?![A-Za-z])".format( + "|".join(map(re.escape, tex2uni))) + )("sym").leaveWhitespace() + p.unknown_symbol = Regex(r"\\[A-Za-z]+")("name") + + p.font = csnames("font", self._fontnames) + p.start_group = Optional(r"\math" + oneOf(self._fontnames)("font")) + "{" + p.end_group = Literal("}") + + p.delim = oneOf(self._delims) + + # Mutually recursive definitions. (Minimizing the number of Forward + # elements is important for speed.) + p.auto_delim = Forward() + p.placeable = Forward() + p.named_placeable = Forward() + p.required_group = Forward() + p.optional_group = Forward() + p.token = Forward() + + # Workaround for placable being part of a cycle of definitions + # calling `p.placeable("name")` results in a copy, so not guaranteed + # to get the definition added after it is used. + # ref https://github.com/matplotlib/matplotlib/issues/25204 + # xref https://github.com/pyparsing/pyparsing/issues/95 + p.named_placeable <<= p.placeable + + set_names_and_parse_actions() # for mutually recursive definitions. + + p.optional_group <<= "{" + ZeroOrMore(p.token)("group") + "}" + p.required_group <<= "{" + OneOrMore(p.token)("group") + "}" + + p.customspace = cmd(r"\hspace", "{" + p.float_literal("space") + "}") + + p.accent = ( + csnames("accent", [*self._accent_map, *self._wide_accents]) + - p.named_placeable("sym")) + + p.function = csnames("name", self._function_names) + + p.group = p.start_group + ZeroOrMore(p.token)("group") + p.end_group + p.unclosed_group = (p.start_group + ZeroOrMore(p.token)("group") + StringEnd()) + + p.frac = cmd(r"\frac", p.required_group("num") + p.required_group("den")) + p.dfrac = cmd(r"\dfrac", p.required_group("num") + p.required_group("den")) + p.binom = cmd(r"\binom", p.required_group("num") + p.required_group("den")) + + p.genfrac = cmd( + r"\genfrac", + "{" + Optional(p.delim)("ldelim") + "}" + + "{" + Optional(p.delim)("rdelim") + "}" + + "{" + p.float_literal("rulesize") + "}" + + "{" + Optional(p.style_literal)("style") + "}" + + p.required_group("num") + + p.required_group("den")) + + p.sqrt = cmd( + r"\sqrt{value}", + Optional("[" + OneOrMore(NotAny("]") + p.token)("root") + "]") + + p.required_group("value")) + + p.overline = cmd(r"\overline", p.required_group("body")) + + p.overset = cmd( + r"\overset", + p.optional_group("annotation") + p.optional_group("body")) + p.underset = cmd( + r"\underset", + p.optional_group("annotation") + p.optional_group("body")) + + p.text = cmd(r"\text", QuotedString('{', '\\', endQuoteChar="}")) + + p.substack = cmd(r"\substack", + nested_expr(opener="{", closer="}", + content=Group(OneOrMore(p.token)) + + ZeroOrMore(Literal("\\\\").suppress()))("parts")) + + p.subsuper = ( + (Optional(p.placeable)("nucleus") + + OneOrMore(oneOf(["_", "^"]) - p.placeable)("subsuper") + + Regex("'*")("apostrophes")) + | Regex("'+")("apostrophes") + | (p.named_placeable("nucleus") + Regex("'*")("apostrophes")) + ) + + p.simple = p.space | p.customspace | p.font | p.subsuper + + p.token <<= ( + p.simple + | p.auto_delim + | p.unclosed_group + | p.unknown_symbol # Must be last + ) + + p.operatorname = cmd(r"\operatorname", "{" + ZeroOrMore(p.simple)("name") + "}") + + p.boldsymbol = cmd( + r"\boldsymbol", "{" + ZeroOrMore(p.simple)("value") + "}") + + p.placeable <<= ( + p.accent # Must be before symbol as all accents are symbols + | p.symbol # Must be second to catch all named symbols and single + # chars not in a group + | p.function + | p.operatorname + | p.group + | p.frac + | p.dfrac + | p.binom + | p.genfrac + | p.overset + | p.underset + | p.sqrt + | p.overline + | p.text + | p.boldsymbol + | p.substack + ) + + mdelim = r"\middle" - (p.delim("mdelim") | Error("Expected a delimiter")) + p.auto_delim <<= ( + r"\left" - (p.delim("left") | Error("Expected a delimiter")) + + ZeroOrMore(p.simple | p.auto_delim | mdelim)("mid") + + r"\right" - (p.delim("right") | Error("Expected a delimiter")) + ) + + # Leaf definitions. + p.math = OneOrMore(p.token) + p.math_string = QuotedString('$', '\\', unquoteResults=False) + p.non_math = Regex(r"(?:(?:\\[$])|[^$])*").leaveWhitespace() + p.main = ( + p.non_math + ZeroOrMore(p.math_string + p.non_math) + StringEnd() + ) + set_names_and_parse_actions() # for leaf definitions. + + self._expression = p.main + self._math_expression = p.math + + # To add space to nucleus operators after sub/superscripts + self._in_subscript_or_superscript = False + + def parse(self, s: str, fonts_object: Fonts, fontsize: float, dpi: float) -> Hlist: + """ + Parse expression *s* using the given *fonts_object* for + output, at the given *fontsize* and *dpi*. + + Returns the parse tree of `Node` instances. + """ + self._state_stack = [ + ParserState(fonts_object, 'default', 'rm', fontsize, dpi)] + self._em_width_cache: dict[tuple[str, float, float], float] = {} + try: + result = self._expression.parseString(s) + except ParseBaseException as err: + # explain becomes a plain method on pyparsing 3 (err.explain(0)). + raise ValueError("\n" + ParseException.explain(err, 0)) from None + self._state_stack = [] + self._in_subscript_or_superscript = False + # prevent operator spacing from leaking into a new expression + self._em_width_cache = {} + ParserElement.resetCache() + return T.cast(Hlist, result[0]) # Known return type from main. + + def get_state(self) -> ParserState: + """Get the current `State` of the parser.""" + return self._state_stack[-1] + + def pop_state(self) -> None: + """Pop a `State` off of the stack.""" + self._state_stack.pop() + + def push_state(self) -> None: + """Push a new `State` onto the stack, copying the current state.""" + self._state_stack.append(self.get_state().copy()) + + def main(self, toks: ParseResults) -> list[Hlist]: + return [Hlist(toks.asList())] + + def math_string(self, toks: ParseResults) -> ParseResults: + return self._math_expression.parseString(toks[0][1:-1], parseAll=True) + + def math(self, toks: ParseResults) -> T.Any: + hlist = Hlist(toks.asList()) + self.pop_state() + return [hlist] + + def non_math(self, toks: ParseResults) -> T.Any: + s = toks[0].replace(r'\$', '$') + symbols = [Char(c, self.get_state()) for c in s] + hlist = Hlist(symbols) + # We're going into math now, so set font to 'it' + self.push_state() + self.get_state().font = mpl.rcParams['mathtext.default'] + return [hlist] + + float_literal = staticmethod(pyparsing_common.convertToFloat) + + def text(self, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + state.font = 'rm' + hlist = Hlist([Char(c, state) for c in toks[1]]) + self.pop_state() + return [hlist] + + def _make_space(self, percentage: float) -> Kern: + # In TeX, an em (the unit usually used to measure horizontal lengths) + # is not the width of the character 'm'; it is the same in different + # font styles (e.g. roman or italic). Mathtext, however, uses 'm' in + # the italic style so that horizontal spaces don't depend on the + # current font style. + state = self.get_state() + key = (state.font, state.fontsize, state.dpi) + width = self._em_width_cache.get(key) + if width is None: + metrics = state.fontset.get_metrics( + 'it', mpl.rcParams['mathtext.default'], 'm', + state.fontsize, state.dpi) + width = metrics.advance + self._em_width_cache[key] = width + return Kern(width * percentage) + + _space_widths = { + r'\,': 0.16667, # 3/18 em = 3 mu + r'\thinspace': 0.16667, # 3/18 em = 3 mu + r'\/': 0.16667, # 3/18 em = 3 mu + r'\>': 0.22222, # 4/18 em = 4 mu + r'\:': 0.22222, # 4/18 em = 4 mu + r'\;': 0.27778, # 5/18 em = 5 mu + r'\ ': 0.33333, # 6/18 em = 6 mu + r'~': 0.33333, # 6/18 em = 6 mu, nonbreakable + r'\enspace': 0.5, # 9/18 em = 9 mu + r'\quad': 1, # 1 em = 18 mu + r'\qquad': 2, # 2 em = 36 mu + r'\!': -0.16667, # -3/18 em = -3 mu + } + + def space(self, toks: ParseResults) -> T.Any: + num = self._space_widths[toks["space"]] + box = self._make_space(num) + return [box] + + def customspace(self, toks: ParseResults) -> T.Any: + return [self._make_space(toks["space"])] + + def symbol(self, s: str, loc: int, + toks: ParseResults | dict[str, str]) -> T.Any: + c = toks["sym"] + if c == "-": + # "U+2212 minus sign is the preferred representation of the unary + # and binary minus sign rather than the ASCII-derived U+002D + # hyphen-minus, because minus sign is unambiguous and because it + # is rendered with a more desirable length, usually longer than a + # hyphen." (https://www.unicode.org/reports/tr25/) + c = "\N{MINUS SIGN}" + try: + char = Char(c, self.get_state()) + except ValueError as err: + raise ParseFatalException(s, loc, + "Unknown symbol: %s" % c) from err + + if c in self._spaced_symbols: + # iterate until we find previous character, needed for cases + # such as ${ -2}$, $ -2$, or $ -2$. + prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') + # Binary operators at start of string should not be spaced + # Also, operators in sub- or superscripts should not be spaced + if (self._in_subscript_or_superscript or ( + c in self._binary_operators and ( + len(s[:loc].split()) == 0 or prev_char == '{' or + prev_char in self._left_delims))): + return [char] + else: + return [Hlist([self._make_space(0.2), + char, + self._make_space(0.2)], + do_kern=True)] + elif c in self._punctuation_symbols: + prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') + next_char = next((c for c in s[loc + 1:] if c != ' '), '') + + # Do not space commas between brackets + if c == ',': + if prev_char == '{' and next_char == '}': + return [char] + + # Do not space dots as decimal separators + if c == '.' and prev_char.isdigit() and next_char.isdigit(): + return [char] + else: + return [Hlist([char, self._make_space(0.2)], do_kern=True)] + return [char] + + def unknown_symbol(self, s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, loc, f"Unknown symbol: {toks['name']}") + + _accent_map = { + r'hat': r'\circumflexaccent', + r'breve': r'\combiningbreve', + r'bar': r'\combiningoverline', + r'grave': r'\combininggraveaccent', + r'acute': r'\combiningacuteaccent', + r'tilde': r'\combiningtilde', + r'dot': r'\combiningdotabove', + r'ddot': r'\combiningdiaeresis', + r'dddot': r'\combiningthreedotsabove', + r'ddddot': r'\combiningfourdotsabove', + r'vec': r'\combiningrightarrowabove', + r'"': r'\combiningdiaeresis', + r"`": r'\combininggraveaccent', + r"'": r'\combiningacuteaccent', + r'~': r'\combiningtilde', + r'.': r'\combiningdotabove', + r'^': r'\circumflexaccent', + r'overrightarrow': r'\rightarrow', + r'overleftarrow': r'\leftarrow', + r'mathring': r'\circ', + } + + _wide_accents = set(r"widehat widetilde widebar".split()) + + def accent(self, toks: ParseResults) -> T.Any: + state = self.get_state() + thickness = state.get_current_underline_thickness() + accent = toks["accent"] + sym = toks["sym"] + accent_box: Node + if accent in self._wide_accents: + accent_box = AutoWidthChar( + '\\' + accent, sym.width, state, char_class=Accent) + else: + accent_box = Accent(self._accent_map[accent], state) + if accent == 'mathring': + accent_box.shrink() + accent_box.shrink() + centered = HCentered([Hbox(sym.width / 4.0), accent_box]) + centered.hpack(sym.width, 'exactly') + return Vlist([ + centered, + Vbox(0., thickness * 2.0), + Hlist([sym]) + ]) + + def function(self, s: str, loc: int, toks: ParseResults) -> T.Any: + hlist = self.operatorname(s, loc, toks) + hlist.function_name = toks["name"] + return hlist + + def operatorname(self, s: str, loc: int, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + state.font = 'rm' + hlist_list: list[Node] = [] + # Change the font of Chars, but leave Kerns alone + name = toks["name"] + for c in name: + if isinstance(c, Char): + c.font = 'rm' + c._update_metrics() + hlist_list.append(c) + elif isinstance(c, str): + hlist_list.append(Char(c, state)) + else: + hlist_list.append(c) + next_char_loc = loc + len(name) + 1 + if isinstance(name, ParseResults): + next_char_loc += len('operatorname{}') + next_char = next((c for c in s[next_char_loc:] if c != ' '), '') + delimiters = self._delims | {'^', '_'} + if (next_char not in delimiters and + name not in self._overunder_functions): + # Add thin space except when followed by parenthesis, bracket, etc. + hlist_list += [self._make_space(self._space_widths[r'\,'])] + self.pop_state() + # if followed by a super/subscript, set flag to true + # This flag tells subsuper to add space after this operator + if next_char in {'^', '_'}: + self._in_subscript_or_superscript = True + else: + self._in_subscript_or_superscript = False + + return Hlist(hlist_list) + + def start_group(self, toks: ParseResults) -> T.Any: + self.push_state() + # Deal with LaTeX-style font tokens + if toks.get("font"): + self.get_state().font = toks.get("font") + return [] + + def group(self, toks: ParseResults) -> T.Any: + grp = Hlist(toks.get("group", [])) + return [grp] + + def required_group(self, toks: ParseResults) -> T.Any: + return Hlist(toks.get("group", [])) + + optional_group = required_group + + def end_group(self) -> T.Any: + self.pop_state() + return [] + + def unclosed_group(self, s: str, loc: int, toks: ParseResults) -> T.Any: + raise ParseFatalException(s, len(s), "Expected '}'") + + def font(self, toks: ParseResults) -> T.Any: + self.get_state().font = toks["font"] + return [] + + def is_overunder(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.c in self._overunder_symbols + elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'): + return nucleus.function_name in self._overunder_functions + return False + + def is_dropsub(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.c in self._dropsub_symbols + return False + + def is_slanted(self, nucleus: Node) -> bool: + if isinstance(nucleus, Char): + return nucleus.is_slanted() + return False + + def subsuper(self, s: str, loc: int, toks: ParseResults) -> T.Any: + nucleus = toks.get("nucleus", Hbox(0)) + subsuper = toks.get("subsuper", []) + napostrophes = len(toks.get("apostrophes", [])) + + if not subsuper and not napostrophes: + return nucleus + + sub = super = None + while subsuper: + op, arg, *subsuper = subsuper + if op == '_': + if sub is not None: + raise ParseFatalException("Double subscript") + sub = arg + else: + if super is not None: + raise ParseFatalException("Double superscript") + super = arg + + state = self.get_state() + rule_thickness = state.fontset.get_underline_thickness( + state.font, state.fontsize, state.dpi) + xHeight = state.fontset.get_xheight( + state.font, state.fontsize, state.dpi) + + if napostrophes: + if super is None: + super = Hlist([]) + for i in range(napostrophes): + super.children.extend(self.symbol(s, loc, {"sym": "\\prime"})) + # kern() and hpack() needed to get the metrics right after + # extending + super.kern() + super.hpack() + + # Handle over/under symbols, such as sum or prod + if self.is_overunder(nucleus): + vlist = [] + shift = 0. + width = nucleus.width + if super is not None: + super.shrink() + width = max(width, super.width) + if sub is not None: + sub.shrink() + width = max(width, sub.width) + + vgap = rule_thickness * 3.0 + if super is not None: + hlist = HCentered([super]) + hlist.hpack(width, 'exactly') + vlist.extend([hlist, Vbox(0, vgap)]) + hlist = HCentered([nucleus]) + hlist.hpack(width, 'exactly') + vlist.append(hlist) + if sub is not None: + hlist = HCentered([sub]) + hlist.hpack(width, 'exactly') + vlist.extend([Vbox(0, vgap), hlist]) + shift = hlist.height + vgap + nucleus.depth + vlt = Vlist(vlist) + vlt.shift_amount = shift + result = Hlist([vlt]) + return [result] + + # We remove kerning on the last character for consistency (otherwise + # it will compute kerning based on non-shrunk characters and may put + # them too close together when superscripted) + # We change the width of the last character to match the advance to + # consider some fonts with weird metrics: e.g. stix's f has a width of + # 7.75 and a kerning of -4.0 for an advance of 3.72, and we want to put + # the superscript at the advance + last_char = nucleus + if isinstance(nucleus, Hlist): + new_children = nucleus.children + if len(new_children): + # remove last kern + if (isinstance(new_children[-1], Kern) and + hasattr(new_children[-2], '_metrics')): + new_children = new_children[:-1] + last_char = new_children[-1] + if hasattr(last_char, '_metrics'): + last_char.width = last_char._metrics.advance + # create new Hlist without kerning + nucleus = Hlist(new_children, do_kern=False) + else: + if isinstance(nucleus, Char): + last_char.width = last_char._metrics.advance + nucleus = Hlist([nucleus]) + + # Handle regular sub/superscripts + constants = _get_font_constant_set(state) + lc_height = last_char.height + lc_baseline = 0 + if self.is_dropsub(last_char): + lc_baseline = last_char.depth + + # Compute kerning for sub and super + superkern = constants.delta * xHeight + subkern = constants.delta * xHeight + if self.is_slanted(last_char): + superkern += constants.delta * xHeight + superkern += (constants.delta_slanted * + (lc_height - xHeight * 2. / 3.)) + if self.is_dropsub(last_char): + subkern = (3 * constants.delta - + constants.delta_integral) * lc_height + superkern = (3 * constants.delta + + constants.delta_integral) * lc_height + else: + subkern = 0 + + x: List + if super is None: + # node757 + # Note: One of super or sub must be a Node if we're in this function, but + # mypy can't know this, since it can't interpret pyparsing expressions, + # hence the cast. + x = Hlist([Kern(subkern), T.cast(Node, sub)]) + x.shrink() + if self.is_dropsub(last_char): + shift_down = lc_baseline + constants.subdrop * xHeight + else: + shift_down = constants.sub1 * xHeight + x.shift_amount = shift_down + else: + x = Hlist([Kern(superkern), super]) + x.shrink() + if self.is_dropsub(last_char): + shift_up = lc_height - constants.subdrop * xHeight + else: + shift_up = constants.sup1 * xHeight + if sub is None: + x.shift_amount = -shift_up + else: # Both sub and superscript + y = Hlist([Kern(subkern), sub]) + y.shrink() + if self.is_dropsub(last_char): + shift_down = lc_baseline + constants.subdrop * xHeight + else: + shift_down = constants.sub2 * xHeight + # If sub and superscript collide, move super up + clr = (2.0 * rule_thickness - + ((shift_up - x.depth) - (y.height - shift_down))) + if clr > 0.: + shift_up += clr + x = Vlist([ + x, + Kern((shift_up - x.depth) - (y.height - shift_down)), + y]) + x.shift_amount = shift_down + + if not self.is_dropsub(last_char): + x.width += constants.script_space * xHeight + + # Do we need to add a space after the nucleus? + # To find out, check the flag set by operatorname + spaced_nucleus = [nucleus, x] + if self._in_subscript_or_superscript: + spaced_nucleus += [self._make_space(self._space_widths[r'\,'])] + self._in_subscript_or_superscript = False + + result = Hlist(spaced_nucleus) + return [result] + + def _genfrac(self, ldelim: str, rdelim: str, rule: float | None, style: _MathStyle, + num: Hlist, den: Hlist) -> T.Any: + state = self.get_state() + thickness = state.get_current_underline_thickness() + + for _ in range(style.value): + num.shrink() + den.shrink() + cnum = HCentered([num]) + cden = HCentered([den]) + width = max(num.width, den.width) + cnum.hpack(width, 'exactly') + cden.hpack(width, 'exactly') + vlist = Vlist([cnum, # numerator + Vbox(0, thickness * 2.0), # space + Hrule(state, rule), # rule + Vbox(0, thickness * 2.0), # space + cden # denominator + ]) + + # Shift so the fraction line sits in the middle of the + # equals sign + metrics = state.fontset.get_metrics( + state.font, mpl.rcParams['mathtext.default'], + '=', state.fontsize, state.dpi) + shift = (cden.height - + ((metrics.ymax + metrics.ymin) / 2 - + thickness * 3.0)) + vlist.shift_amount = shift + + result = [Hlist([vlist, Hbox(thickness * 2.)])] + if ldelim or rdelim: + if ldelim == '': + ldelim = '.' + if rdelim == '': + rdelim = '.' + return self._auto_sized_delimiter(ldelim, + T.cast(list[T.Union[Box, Char, str]], + result), + rdelim) + return result + + def style_literal(self, toks: ParseResults) -> T.Any: + return self._MathStyle(int(toks["style_literal"])) + + def genfrac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + toks.get("ldelim", ""), toks.get("rdelim", ""), + toks["rulesize"], toks.get("style", self._MathStyle.TEXTSTYLE), + toks["num"], toks["den"]) + + def frac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "", "", self.get_state().get_current_underline_thickness(), + self._MathStyle.TEXTSTYLE, toks["num"], toks["den"]) + + def dfrac(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "", "", self.get_state().get_current_underline_thickness(), + self._MathStyle.DISPLAYSTYLE, toks["num"], toks["den"]) + + def binom(self, toks: ParseResults) -> T.Any: + return self._genfrac( + "(", ")", 0, + self._MathStyle.TEXTSTYLE, toks["num"], toks["den"]) + + def _genset(self, s: str, loc: int, toks: ParseResults) -> T.Any: + annotation = toks["annotation"] + body = toks["body"] + thickness = self.get_state().get_current_underline_thickness() + + annotation.shrink() + centered_annotation = HCentered([annotation]) + centered_body = HCentered([body]) + width = max(centered_annotation.width, centered_body.width) + centered_annotation.hpack(width, 'exactly') + centered_body.hpack(width, 'exactly') + + vgap = thickness * 3 + if s[loc + 1] == "u": # \underset + vlist = Vlist([ + centered_body, # body + Vbox(0, vgap), # space + centered_annotation # annotation + ]) + # Shift so the body sits in the same vertical position + vlist.shift_amount = centered_body.depth + centered_annotation.height + vgap + else: # \overset + vlist = Vlist([ + centered_annotation, # annotation + Vbox(0, vgap), # space + centered_body # body + ]) + + # To add horizontal gap between symbols: wrap the Vlist into + # an Hlist and extend it with an Hbox(0, horizontal_gap) + return vlist + + overset = underset = _genset + + def sqrt(self, toks: ParseResults) -> T.Any: + root = toks.get("root") + body = toks["value"] + state = self.get_state() + thickness = state.get_current_underline_thickness() + + # Determine the height of the body, and add a little extra to + # the height so it doesn't seem cramped + height = body.height - body.shift_amount + thickness * 5.0 + depth = body.depth + body.shift_amount + check = AutoHeightChar(r'\__sqrt__', height, depth, state, always=True) + height = check.height - check.shift_amount + depth = check.depth + check.shift_amount + + # Put a little extra space to the left and right of the body + padded_body = Hlist([Hbox(2 * thickness), body, Hbox(2 * thickness)]) + rightside = Vlist([Hrule(state), Glue('fill'), padded_body]) + # Stretch the glue between the hrule and the body + rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), + 'exactly', depth) + + # Add the root and shift it upward so it is above the tick. + # The value of 0.6 is a hard-coded hack ;) + if not root: + root = Box(check.width * 0.5, 0., 0.) + else: + root = Hlist(root) + root.shrink() + root.shrink() + + root_vlist = Vlist([Hlist([root])]) + root_vlist.shift_amount = -height * 0.6 + + hlist = Hlist([root_vlist, # Root + # Negative kerning to put root over tick + Kern(-check.width * 0.5), + check, # Check + rightside]) # Body + return [hlist] + + def overline(self, toks: ParseResults) -> T.Any: + body = toks["body"] + + state = self.get_state() + thickness = state.get_current_underline_thickness() + + height = body.height - body.shift_amount + thickness * 3.0 + depth = body.depth + body.shift_amount + + # Place overline above body + rightside = Vlist([Hrule(state), Glue('fill'), Hlist([body])]) + + # Stretch the glue between the hrule and the body + rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), + 'exactly', depth) + + hlist = Hlist([rightside]) + return [hlist] + + def _auto_sized_delimiter(self, front: str, + middle: list[Box | Char | str], + back: str) -> T.Any: + state = self.get_state() + if len(middle): + height = max([x.height for x in middle if not isinstance(x, str)]) + depth = max([x.depth for x in middle if not isinstance(x, str)]) + factor = None + for idx, el in enumerate(middle): + if el == r'\middle': + c = T.cast(str, middle[idx + 1]) # Should be one of p.delims. + if c != '.': + middle[idx + 1] = AutoHeightChar( + c, height, depth, state, factor=factor) + else: + middle.remove(c) + del middle[idx] + # There should only be \middle and its delimiter as str, which have + # just been removed. + middle_part = T.cast(list[T.Union[Box, Char]], middle) + else: + height = 0 + depth = 0 + factor = 1.0 + middle_part = [] + + parts: list[Node] = [] + # \left. and \right. aren't supposed to produce any symbols + if front != '.': + parts.append( + AutoHeightChar(front, height, depth, state, factor=factor)) + parts.extend(middle_part) + if back != '.': + parts.append( + AutoHeightChar(back, height, depth, state, factor=factor)) + hlist = Hlist(parts) + return hlist + + def auto_delim(self, toks: ParseResults) -> T.Any: + return self._auto_sized_delimiter( + toks["left"], + # if "mid" in toks ... can be removed when requiring pyparsing 3. + toks["mid"].asList() if "mid" in toks else [], + toks["right"]) + + def boldsymbol(self, toks: ParseResults) -> T.Any: + self.push_state() + state = self.get_state() + hlist: list[Node] = [] + name = toks["value"] + for c in name: + if isinstance(c, Hlist): + k = c.children[1] + if isinstance(k, Char): + k.font = "bf" + k._update_metrics() + hlist.append(c) + elif isinstance(c, Char): + c.font = "bf" + if (c.c in self._latin_alphabets or + c.c[1:] in self._small_greek): + c.font = "bfit" + c._update_metrics() + c._update_metrics() + hlist.append(c) + else: + hlist.append(c) + self.pop_state() + + return Hlist(hlist) + + def substack(self, toks: ParseResults) -> T.Any: + parts = toks["parts"] + state = self.get_state() + thickness = state.get_current_underline_thickness() + + hlist = [Hlist(k) for k in parts[0]] + max_width = max(map(lambda c: c.width, hlist)) + + vlist = [] + for sub in hlist: + cp = HCentered([sub]) + cp.hpack(max_width, 'exactly') + vlist.append(cp) + + stack = [val + for pair in zip(vlist, [Vbox(0, thickness * 2)] * len(vlist)) + for val in pair] + del stack[-1] + vlt = Vlist(stack) + result = [Hlist([vlt])] + return result diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py b/llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..cb6ca41d02c955c12122e4c88239eb16de7c79fe --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py @@ -0,0 +1,134 @@ +""" +Manage figures for the pyplot interface. +""" + +import atexit +from collections import OrderedDict + + +class Gcf: + """ + Singleton to maintain the relation between figures and their managers, and + keep track of and "active" figure and manager. + + The canvas of a figure created through pyplot is associated with a figure + manager, which handles the interaction between the figure and the backend. + pyplot keeps track of figure managers using an identifier, the "figure + number" or "manager number" (which can actually be any hashable value); + this number is available as the :attr:`number` attribute of the manager. + + This class is never instantiated; it consists of an `OrderedDict` mapping + figure/manager numbers to managers, and a set of class methods that + manipulate this `OrderedDict`. + + Attributes + ---------- + figs : OrderedDict + `OrderedDict` mapping numbers to managers; the active manager is at the + end. + """ + + figs = OrderedDict() + + @classmethod + def get_fig_manager(cls, num): + """ + If manager number *num* exists, make it the active one and return it; + otherwise return *None*. + """ + manager = cls.figs.get(num, None) + if manager is not None: + cls.set_active(manager) + return manager + + @classmethod + def destroy(cls, num): + """ + Destroy manager *num* -- either a manager instance or a manager number. + + In the interactive backends, this is bound to the window "destroy" and + "delete" events. + + It is recommended to pass a manager instance, to avoid confusion when + two managers share the same number. + """ + if all(hasattr(num, attr) for attr in ["num", "destroy"]): + manager = num + if cls.figs.get(manager.num) is manager: + cls.figs.pop(manager.num) + else: + try: + manager = cls.figs.pop(num) + except KeyError: + return + if hasattr(manager, "_cidgcf"): + manager.canvas.mpl_disconnect(manager._cidgcf) + manager.destroy() + + @classmethod + def destroy_fig(cls, fig): + """Destroy figure *fig*.""" + num = next((manager.num for manager in cls.figs.values() + if manager.canvas.figure == fig), None) + if num is not None: + cls.destroy(num) + + @classmethod + def destroy_all(cls): + """Destroy all figures.""" + for manager in list(cls.figs.values()): + manager.canvas.mpl_disconnect(manager._cidgcf) + manager.destroy() + cls.figs.clear() + + @classmethod + def has_fignum(cls, num): + """Return whether figure number *num* exists.""" + return num in cls.figs + + @classmethod + def get_all_fig_managers(cls): + """Return a list of figure managers.""" + return list(cls.figs.values()) + + @classmethod + def get_num_fig_managers(cls): + """Return the number of figures being managed.""" + return len(cls.figs) + + @classmethod + def get_active(cls): + """Return the active manager, or *None* if there is no manager.""" + return next(reversed(cls.figs.values())) if cls.figs else None + + @classmethod + def _set_new_active_manager(cls, manager): + """Adopt *manager* into pyplot and make it the active manager.""" + if not hasattr(manager, "_cidgcf"): + manager._cidgcf = manager.canvas.mpl_connect( + "button_press_event", lambda event: cls.set_active(manager)) + fig = manager.canvas.figure + fig.number = manager.num + label = fig.get_label() + if label: + manager.set_window_title(label) + cls.set_active(manager) + + @classmethod + def set_active(cls, manager): + """Make *manager* the active manager.""" + cls.figs[manager.num] = manager + cls.figs.move_to_end(manager.num) + + @classmethod + def draw_all(cls, force=False): + """ + Redraw all stale managed figures, or, if *force* is True, all managed + figures. + """ + for manager in cls.get_all_fig_managers(): + if force or manager.canvas.figure.stale: + manager.canvas.draw_idle() + + +atexit.register(Gcf.destroy_all) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bdd8cfba3173030b37b24af412970cbb62fee3ef --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi @@ -0,0 +1,29 @@ +from collections import OrderedDict + +from matplotlib.backend_bases import FigureManagerBase +from matplotlib.figure import Figure + +class Gcf: + figs: OrderedDict[int, FigureManagerBase] + @classmethod + def get_fig_manager(cls, num: int) -> FigureManagerBase | None: ... + @classmethod + def destroy(cls, num: int | FigureManagerBase) -> None: ... + @classmethod + def destroy_fig(cls, fig: Figure) -> None: ... + @classmethod + def destroy_all(cls) -> None: ... + @classmethod + def has_fignum(cls, num: int) -> bool: ... + @classmethod + def get_all_fig_managers(cls) -> list[FigureManagerBase]: ... + @classmethod + def get_num_fig_managers(cls) -> int: ... + @classmethod + def get_active(cls) -> FigureManagerBase | None: ... + @classmethod + def _set_new_active_manager(cls, manager: FigureManagerBase) -> None: ... + @classmethod + def set_active(cls, manager: FigureManagerBase) -> None: ... + @classmethod + def draw_all(cls, force: bool = ...) -> None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so b/llava_next/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7c9fd8ed138333d46a11a4bfd1d27ed7deb9ef7e --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a836803f31df00f7f280085ab7873f39703c0e3c3eb5335690e8a119121145ad +size 745280 diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_tight_layout.py b/llava_next/lib/python3.10/site-packages/matplotlib/_tight_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..548da79fff04320193a7170d5cf0f9b9fa743c0a --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_tight_layout.py @@ -0,0 +1,301 @@ +""" +Routines to adjust subplot params so that subplots are +nicely fit in the figure. In doing so, only axis labels, tick labels, Axes +titles and offsetboxes that are anchored to Axes are currently considered. + +Internally, this module assumes that the margins (left margin, etc.) which are +differences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent of +Axes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well as +such cases as when left or right margin are affected by xlabel. +""" + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, artist as martist +from matplotlib.font_manager import FontProperties +from matplotlib.transforms import Bbox + + +def _auto_adjust_subplotpars( + fig, renderer, shape, span_pairs, subplot_list, + ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None): + """ + Return a dict of subplot parameters to adjust spacing between subplots + or ``None`` if resulting Axes would have zero height or width. + + Note that this function ignores geometry information of subplot itself, but + uses what is given by the *shape* and *subplot_list* parameters. Also, the + results could be incorrect if some subplots have ``adjustable=datalim``. + + Parameters + ---------- + shape : tuple[int, int] + Number of rows and columns of the grid. + span_pairs : list[tuple[slice, slice]] + List of rowspans and colspans occupied by each subplot. + subplot_list : list of subplots + List of subplots that will be used to calculate optimal subplot_params. + pad : float + Padding between the figure edge and the edges of subplots, as a + fraction of the font size. + h_pad, w_pad : float + Padding (height/width) between edges of adjacent subplots, as a + fraction of the font size. Defaults to *pad*. + rect : tuple + (left, bottom, right, top), default: None. + """ + rows, cols = shape + + font_size_inch = (FontProperties( + size=mpl.rcParams["font.size"]).get_size_in_points() / 72) + pad_inch = pad * font_size_inch + vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch + hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch + + if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0: + raise ValueError + + if rect is None: + margin_left = margin_bottom = margin_right = margin_top = None + else: + margin_left, margin_bottom, _right, _top = rect + margin_right = 1 - _right if _right else None + margin_top = 1 - _top if _top else None + + vspaces = np.zeros((rows + 1, cols)) + hspaces = np.zeros((rows, cols + 1)) + + if ax_bbox_list is None: + ax_bbox_list = [ + Bbox.union([ax.get_position(original=True) for ax in subplots]) + for subplots in subplot_list] + + for subplots, ax_bbox, (rowspan, colspan) in zip( + subplot_list, ax_bbox_list, span_pairs): + if all(not ax.get_visible() for ax in subplots): + continue + + bb = [] + for ax in subplots: + if ax.get_visible(): + bb += [martist._get_tightbbox_for_layout_only(ax, renderer)] + + tight_bbox_raw = Bbox.union(bb) + tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw) + + hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l + hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r + vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t + vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b + + fig_width_inch, fig_height_inch = fig.get_size_inches() + + # margins can be negative for Axes with aspect applied, so use max(, 0) to + # make them nonnegative. + if not margin_left: + margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch + suplabel = fig._supylabel + if suplabel and suplabel.get_in_layout(): + rel_width = fig.transFigure.inverted().transform_bbox( + suplabel.get_window_extent(renderer)).width + margin_left += rel_width + pad_inch/fig_width_inch + if not margin_right: + margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch + if not margin_top: + margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch + if fig._suptitle and fig._suptitle.get_in_layout(): + rel_height = fig.transFigure.inverted().transform_bbox( + fig._suptitle.get_window_extent(renderer)).height + margin_top += rel_height + pad_inch/fig_height_inch + if not margin_bottom: + margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch + suplabel = fig._supxlabel + if suplabel and suplabel.get_in_layout(): + rel_height = fig.transFigure.inverted().transform_bbox( + suplabel.get_window_extent(renderer)).height + margin_bottom += rel_height + pad_inch/fig_height_inch + + if margin_left + margin_right >= 1: + _api.warn_external('Tight layout not applied. The left and right ' + 'margins cannot be made large enough to ' + 'accommodate all Axes decorations.') + return None + if margin_bottom + margin_top >= 1: + _api.warn_external('Tight layout not applied. The bottom and top ' + 'margins cannot be made large enough to ' + 'accommodate all Axes decorations.') + return None + + kwargs = dict(left=margin_left, + right=1 - margin_right, + bottom=margin_bottom, + top=1 - margin_top) + + if cols > 1: + hspace = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch + # axes widths: + h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols + if h_axes < 0: + _api.warn_external('Tight layout not applied. tight_layout ' + 'cannot make Axes width small enough to ' + 'accommodate all Axes decorations') + return None + else: + kwargs["wspace"] = hspace / h_axes + if rows > 1: + vspace = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch + v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows + if v_axes < 0: + _api.warn_external('Tight layout not applied. tight_layout ' + 'cannot make Axes height small enough to ' + 'accommodate all Axes decorations.') + return None + else: + kwargs["hspace"] = vspace / v_axes + + return kwargs + + +def get_subplotspec_list(axes_list, grid_spec=None): + """ + Return a list of subplotspec from the given list of Axes. + + For an instance of Axes that does not support subplotspec, None is inserted + in the list. + + If grid_spec is given, None is inserted for those not from the given + grid_spec. + """ + subplotspec_list = [] + for ax in axes_list: + axes_or_locator = ax.get_axes_locator() + if axes_or_locator is None: + axes_or_locator = ax + + if hasattr(axes_or_locator, "get_subplotspec"): + subplotspec = axes_or_locator.get_subplotspec() + if subplotspec is not None: + subplotspec = subplotspec.get_topmost_subplotspec() + gs = subplotspec.get_gridspec() + if grid_spec is not None: + if gs != grid_spec: + subplotspec = None + elif gs.locally_modified_subplot_params(): + subplotspec = None + else: + subplotspec = None + + subplotspec_list.append(subplotspec) + + return subplotspec_list + + +def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, + pad=1.08, h_pad=None, w_pad=None, rect=None): + """ + Return subplot parameters for tight-layouted-figure with specified padding. + + Parameters + ---------- + fig : Figure + axes_list : list of Axes + subplotspec_list : list of `.SubplotSpec` + The subplotspecs of each Axes. + renderer : renderer + pad : float + Padding between the figure edge and the edges of subplots, as a + fraction of the font size. + h_pad, w_pad : float + Padding (height/width) between edges of adjacent subplots. Defaults to + *pad*. + rect : tuple (left, bottom, right, top), default: None. + rectangle in normalized figure coordinates + that the whole subplots area (including labels) will fit into. + Defaults to using the entire figure. + + Returns + ------- + subplotspec or None + subplotspec kwargs to be passed to `.Figure.subplots_adjust` or + None if tight_layout could not be accomplished. + """ + + # Multiple Axes can share same subplotspec (e.g., if using axes_grid1); + # we need to group them together. + ss_to_subplots = {ss: [] for ss in subplotspec_list} + for ax, ss in zip(axes_list, subplotspec_list): + ss_to_subplots[ss].append(ax) + if ss_to_subplots.pop(None, None): + _api.warn_external( + "This figure includes Axes that are not compatible with " + "tight_layout, so results might be incorrect.") + if not ss_to_subplots: + return {} + subplot_list = list(ss_to_subplots.values()) + ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots] + + max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots) + max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots) + + span_pairs = [] + for ss in ss_to_subplots: + # The intent here is to support Axes from different gridspecs where + # one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4), + # but this doesn't actually work because the computed wspace, in + # relative-axes-height, corresponds to different physical spacings for + # the 2-row grid and the 4-row grid. Still, this code is left, mostly + # for backcompat. + rows, cols = ss.get_gridspec().get_geometry() + div_row, mod_row = divmod(max_nrows, rows) + div_col, mod_col = divmod(max_ncols, cols) + if mod_row != 0: + _api.warn_external('tight_layout not applied: number of rows ' + 'in subplot specifications must be ' + 'multiples of one another.') + return {} + if mod_col != 0: + _api.warn_external('tight_layout not applied: number of ' + 'columns in subplot specifications must be ' + 'multiples of one another.') + return {} + span_pairs.append(( + slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row), + slice(ss.colspan.start * div_col, ss.colspan.stop * div_col))) + + kwargs = _auto_adjust_subplotpars(fig, renderer, + shape=(max_nrows, max_ncols), + span_pairs=span_pairs, + subplot_list=subplot_list, + ax_bbox_list=ax_bbox_list, + pad=pad, h_pad=h_pad, w_pad=w_pad) + + # kwargs can be none if tight_layout fails... + if rect is not None and kwargs is not None: + # if rect is given, the whole subplots area (including + # labels) will fit into the rect instead of the + # figure. Note that the rect argument of + # *auto_adjust_subplotpars* specify the area that will be + # covered by the total area of axes.bbox. Thus we call + # auto_adjust_subplotpars twice, where the second run + # with adjusted rect parameters. + + left, bottom, right, top = rect + if left is not None: + left += kwargs["left"] + if bottom is not None: + bottom += kwargs["bottom"] + if right is not None: + right -= (1 - kwargs["right"]) + if top is not None: + top -= (1 - kwargs["top"]) + + kwargs = _auto_adjust_subplotpars(fig, renderer, + shape=(max_nrows, max_ncols), + span_pairs=span_pairs, + subplot_list=subplot_list, + ax_bbox_list=ax_bbox_list, + pad=pad, h_pad=h_pad, w_pad=w_pad, + rect=(left, bottom, right, top)) + + return kwargs diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_tri.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/_tri.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b6e79d7140b33ca863269c6b143d3b29495d03c8 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_tri.pyi @@ -0,0 +1,26 @@ +# This is a private module implemented in C++ +# As such these type stubs are overly generic, but here to allow these types +# as return types for public methods +from typing import Any, final + +@final +class TrapezoidMapTriFinder: + def __init__(self, *args, **kwargs) -> None: ... + def find_many(self, *args, **kwargs) -> Any: ... + def get_tree_stats(self, *args, **kwargs) -> Any: ... + def initialize(self, *args, **kwargs) -> Any: ... + def print_tree(self, *args, **kwargs) -> Any: ... + +@final +class TriContourGenerator: + def __init__(self, *args, **kwargs) -> None: ... + def create_contour(self, *args, **kwargs) -> Any: ... + def create_filled_contour(self, *args, **kwargs) -> Any: ... + +@final +class Triangulation: + def __init__(self, *args, **kwargs) -> None: ... + def calculate_plane_coefficients(self, *args, **kwargs) -> Any: ... + def get_edges(self, *args, **kwargs) -> Any: ... + def get_neighbors(self, *args, **kwargs) -> Any: ... + def set_mask(self, *args, **kwargs) -> Any: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/_version.py b/llava_next/lib/python3.10/site-packages/matplotlib/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..b66f1610747225bf90f85a85f4211dd0a3eaa818 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/_version.py @@ -0,0 +1 @@ +version = "3.9.2" diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/axis.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/axis.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e23ae381c3387b162a299db4d35e1d697d8cf806 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/axis.pyi @@ -0,0 +1,280 @@ +from collections.abc import Callable, Iterable, Sequence +import datetime +from typing import Any, Literal, overload + +import numpy as np +from numpy.typing import ArrayLike + +import matplotlib.artist as martist +from matplotlib import cbook +from matplotlib.axes import Axes +from matplotlib.backend_bases import RendererBase +from matplotlib.lines import Line2D +from matplotlib.text import Text +from matplotlib.ticker import Locator, Formatter +from matplotlib.transforms import Transform, Bbox +from matplotlib.typing import ColorType + + +GRIDLINE_INTERPOLATION_STEPS: int + +class Tick(martist.Artist): + axes: Axes + tick1line: Line2D + tick2line: Line2D + gridline: Line2D + label1: Text + label2: Text + def __init__( + self, + axes: Axes, + loc: float, + *, + size: float | None = ..., + width: float | None = ..., + color: ColorType | None = ..., + tickdir: Literal["in", "inout", "out"] | None = ..., + pad: float | None = ..., + labelsize: float | None = ..., + labelcolor: ColorType | None = ..., + labelfontfamily: str | Sequence[str] | None = ..., + zorder: float | None = ..., + gridOn: bool | None = ..., + tick1On: bool = ..., + tick2On: bool = ..., + label1On: bool = ..., + label2On: bool = ..., + major: bool = ..., + labelrotation: float = ..., + grid_color: ColorType | None = ..., + grid_linestyle: str | None = ..., + grid_linewidth: float | None = ..., + grid_alpha: float | None = ..., + **kwargs + ) -> None: ... + def get_tickdir(self) -> Literal["in", "inout", "out"]: ... + def get_tick_padding(self) -> float: ... + def get_children(self) -> list[martist.Artist]: ... + stale: bool + def set_pad(self, val: float) -> None: ... + def get_pad(self) -> None: ... + def get_loc(self) -> float: ... + def set_label1(self, s: object) -> None: ... + def set_label(self, s: object) -> None: ... + def set_label2(self, s: object) -> None: ... + def set_url(self, url: str | None) -> None: ... + def get_view_interval(self) -> ArrayLike: ... + def update_position(self, loc: float) -> None: ... + +class XTick(Tick): + __name__: str + def __init__(self, *args, **kwargs) -> None: ... + stale: bool + def update_position(self, loc: float) -> None: ... + def get_view_interval(self) -> np.ndarray: ... + +class YTick(Tick): + __name__: str + def __init__(self, *args, **kwargs) -> None: ... + stale: bool + def update_position(self, loc: float) -> None: ... + def get_view_interval(self) -> np.ndarray: ... + +class Ticker: + def __init__(self) -> None: ... + @property + def locator(self) -> Locator | None: ... + @locator.setter + def locator(self, locator: Locator) -> None: ... + @property + def formatter(self) -> Formatter | None: ... + @formatter.setter + def formatter(self, formatter: Formatter) -> None: ... + +class _LazyTickList: + def __init__(self, major: bool) -> None: ... + # Replace return with Self when py3.9 is dropped + @overload + def __get__(self, instance: None, owner: None) -> _LazyTickList: ... + @overload + def __get__(self, instance: Axis, owner: type[Axis]) -> list[Tick]: ... + +class Axis(martist.Artist): + OFFSETTEXTPAD: int + isDefault_label: bool + axes: Axes + major: Ticker + minor: Ticker + callbacks: cbook.CallbackRegistry + label: Text + offsetText: Text + labelpad: float + pickradius: float + def __init__(self, axes, *, pickradius: float = ..., + clear: bool = ...) -> None: ... + @property + def isDefault_majloc(self) -> bool: ... + @isDefault_majloc.setter + def isDefault_majloc(self, value: bool) -> None: ... + @property + def isDefault_majfmt(self) -> bool: ... + @isDefault_majfmt.setter + def isDefault_majfmt(self, value: bool) -> None: ... + @property + def isDefault_minloc(self) -> bool: ... + @isDefault_minloc.setter + def isDefault_minloc(self, value: bool) -> None: ... + @property + def isDefault_minfmt(self) -> bool: ... + @isDefault_minfmt.setter + def isDefault_minfmt(self, value: bool) -> None: ... + majorTicks: _LazyTickList + minorTicks: _LazyTickList + def get_remove_overlapping_locs(self) -> bool: ... + def set_remove_overlapping_locs(self, val: bool) -> None: ... + @property + def remove_overlapping_locs(self) -> bool: ... + @remove_overlapping_locs.setter + def remove_overlapping_locs(self, val: bool) -> None: ... + stale: bool + def set_label_coords( + self, x: float, y: float, transform: Transform | None = ... + ) -> None: ... + def get_transform(self) -> Transform: ... + def get_scale(self) -> str: ... + def limit_range_for_scale( + self, vmin: float, vmax: float + ) -> tuple[float, float]: ... + def get_children(self) -> list[martist.Artist]: ... + # TODO units + converter: Any + units: Any + def clear(self) -> None: ... + def reset_ticks(self) -> None: ... + def minorticks_on(self) -> None: ... + def minorticks_off(self) -> None: ... + def set_tick_params( + self, + which: Literal["major", "minor", "both"] = ..., + reset: bool = ..., + **kwargs + ) -> None: ... + def get_tick_params( + self, which: Literal["major", "minor"] = ... + ) -> dict[str, Any]: ... + def get_view_interval(self) -> tuple[float, float]: ... + def set_view_interval( + self, vmin: float, vmax: float, ignore: bool = ... + ) -> None: ... + def get_data_interval(self) -> tuple[float, float]: ... + def set_data_interval( + self, vmin: float, vmax: float, ignore: bool = ... + ) -> None: ... + def get_inverted(self) -> bool: ... + def set_inverted(self, inverted: bool) -> None: ... + def set_default_intervals(self) -> None: ... + def get_tightbbox( + self, renderer: RendererBase | None = ..., *, for_layout_only: bool = ... + ) -> Bbox | None: ... + def get_tick_padding(self) -> float: ... + def get_gridlines(self) -> list[Line2D]: ... + def get_label(self) -> Text: ... + def get_offset_text(self) -> Text: ... + def get_pickradius(self) -> float: ... + def get_majorticklabels(self) -> list[Text]: ... + def get_minorticklabels(self) -> list[Text]: ... + def get_ticklabels( + self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ... + ) -> list[Text]: ... + def get_majorticklines(self) -> list[Line2D]: ... + def get_minorticklines(self) -> list[Line2D]: ... + def get_ticklines(self, minor: bool = ...) -> list[Line2D]: ... + def get_majorticklocs(self) -> np.ndarray: ... + def get_minorticklocs(self) -> np.ndarray: ... + def get_ticklocs(self, *, minor: bool = ...) -> np.ndarray: ... + def get_ticks_direction(self, minor: bool = ...) -> np.ndarray: ... + def get_label_text(self) -> str: ... + def get_major_locator(self) -> Locator: ... + def get_minor_locator(self) -> Locator: ... + def get_major_formatter(self) -> Formatter: ... + def get_minor_formatter(self) -> Formatter: ... + def get_major_ticks(self, numticks: int | None = ...) -> list[Tick]: ... + def get_minor_ticks(self, numticks: int | None = ...) -> list[Tick]: ... + def grid( + self, + visible: bool | None = ..., + which: Literal["major", "minor", "both"] = ..., + **kwargs + ) -> None: ... + # TODO units + def update_units(self, data): ... + def have_units(self) -> bool: ... + def convert_units(self, x): ... + def set_units(self, u) -> None: ... + def get_units(self): ... + def set_label_text( + self, label: str, fontdict: dict[str, Any] | None = ..., **kwargs + ) -> Text: ... + def set_major_formatter( + self, formatter: Formatter | str | Callable[[float, float], str] + ) -> None: ... + def set_minor_formatter( + self, formatter: Formatter | str | Callable[[float, float], str] + ) -> None: ... + def set_major_locator(self, locator: Locator) -> None: ... + def set_minor_locator(self, locator: Locator) -> None: ... + def set_pickradius(self, pickradius: float) -> None: ... + def set_ticklabels( + self, + labels: Iterable[str | Text], + *, + minor: bool = ..., + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> list[Text]: ... + def set_ticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def axis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ... + def get_tick_space(self) -> int: ... + def get_label_position(self) -> Literal["top", "bottom"]: ... + def set_label_position( + self, position: Literal["top", "bottom", "left", "right"] + ) -> None: ... + def get_minpos(self) -> float: ... + +class XAxis(Axis): + __name__: str + axis_name: str + def __init__(self, *args, **kwargs) -> None: ... + label_position: Literal["bottom", "top"] + stale: bool + def set_label_position(self, position: Literal["bottom", "top"]) -> None: ... # type: ignore[override] + def set_ticks_position( + self, position: Literal["top", "bottom", "both", "default", "none"] + ) -> None: ... + def tick_top(self) -> None: ... + def tick_bottom(self) -> None: ... + def get_ticks_position(self) -> Literal["top", "bottom", "default", "unknown"]: ... + def get_tick_space(self) -> int: ... + +class YAxis(Axis): + __name__: str + axis_name: str + def __init__(self, *args, **kwargs) -> None: ... + label_position: Literal["left", "right"] + stale: bool + def set_label_position(self, position: Literal["left", "right"]) -> None: ... # type: ignore[override] + def set_offset_position(self, position: Literal["left", "right"]) -> None: ... + def set_ticks_position( + self, position: Literal["left", "right", "both", "default", "none"] + ) -> None: ... + def tick_right(self) -> None: ... + def tick_left(self) -> None: ... + def get_ticks_position(self) -> Literal["left", "right", "default", "unknown"]: ... + def get_tick_space(self) -> int: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/cbook.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/cbook.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d727b8065b7acbdaa0eda220c831bd351d8a37ad --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/cbook.pyi @@ -0,0 +1,186 @@ +import collections.abc +from collections.abc import Callable, Collection, Generator, Iterable, Iterator +import contextlib +import os +from pathlib import Path + +from matplotlib.artist import Artist + +import numpy as np +from numpy.typing import ArrayLike + +from typing import ( + Any, + Generic, + IO, + Literal, + TypeVar, + overload, +) + +_T = TypeVar("_T") + +def _get_running_interactive_framework() -> str | None: ... + +class CallbackRegistry: + exception_handler: Callable[[Exception], Any] + callbacks: dict[Any, dict[int, Any]] + def __init__( + self, + exception_handler: Callable[[Exception], Any] | None = ..., + *, + signals: Iterable[Any] | None = ..., + ) -> None: ... + def connect(self, signal: Any, func: Callable) -> int: ... + def disconnect(self, cid: int) -> None: ... + def process(self, s: Any, *args, **kwargs) -> None: ... + def blocked( + self, *, signal: Any | None = ... + ) -> contextlib.AbstractContextManager[None]: ... + +class silent_list(list[_T]): + type: str | None + def __init__(self, type: str | None, seq: Iterable[_T] | None = ...) -> None: ... + +def strip_math(s: str) -> str: ... +def is_writable_file_like(obj: Any) -> bool: ... +def file_requires_unicode(x: Any) -> bool: ... +@overload +def to_filehandle( + fname: str | os.PathLike | IO, + flag: str = ..., + return_opened: Literal[False] = ..., + encoding: str | None = ..., +) -> IO: ... +@overload +def to_filehandle( + fname: str | os.PathLike | IO, + flag: str, + return_opened: Literal[True], + encoding: str | None = ..., +) -> tuple[IO, bool]: ... +@overload +def to_filehandle( + fname: str | os.PathLike | IO, + *, # if flag given, will match previous sig + return_opened: Literal[True], + encoding: str | None = ..., +) -> tuple[IO, bool]: ... +def open_file_cm( + path_or_file: str | os.PathLike | IO, + mode: str = ..., + encoding: str | None = ..., +) -> contextlib.AbstractContextManager[IO]: ... +def is_scalar_or_string(val: Any) -> bool: ... +@overload +def get_sample_data( + fname: str | os.PathLike, asfileobj: Literal[True] = ..., *, np_load: Literal[True] +) -> np.ndarray: ... +@overload +def get_sample_data( + fname: str | os.PathLike, + asfileobj: Literal[True] = ..., + *, + np_load: Literal[False] = ..., +) -> IO: ... +@overload +def get_sample_data( + fname: str | os.PathLike, asfileobj: Literal[False], *, np_load: bool = ... +) -> str: ... +def _get_data_path(*args: Path | str) -> Path: ... +def flatten( + seq: Iterable[Any], scalarp: Callable[[Any], bool] = ... +) -> Generator[Any, None, None]: ... + +class Stack(Generic[_T]): + def __init__(self, default: _T | None = ...) -> None: ... + def __call__(self) -> _T: ... + def __len__(self) -> int: ... + def __getitem__(self, ind: int) -> _T: ... + def forward(self) -> _T: ... + def back(self) -> _T: ... + def push(self, o: _T) -> _T: ... + def home(self) -> _T: ... + def empty(self) -> bool: ... + def clear(self) -> None: ... + def bubble(self, o: _T) -> _T: ... + def remove(self, o: _T) -> None: ... + +def safe_masked_invalid(x: ArrayLike, copy: bool = ...) -> np.ndarray: ... +def print_cycles( + objects: Iterable[Any], outstream: IO = ..., show_progress: bool = ... +) -> None: ... + +class Grouper(Generic[_T]): + def __init__(self, init: Iterable[_T] = ...) -> None: ... + def __contains__(self, item: _T) -> bool: ... + def clean(self) -> None: ... + def join(self, a: _T, *args: _T) -> None: ... + def joined(self, a: _T, b: _T) -> bool: ... + def remove(self, a: _T) -> None: ... + def __iter__(self) -> Iterator[list[_T]]: ... + def get_siblings(self, a: _T) -> list[_T]: ... + +class GrouperView(Generic[_T]): + def __init__(self, grouper: Grouper[_T]) -> None: ... + def __contains__(self, item: _T) -> bool: ... + def __iter__(self) -> Iterator[list[_T]]: ... + def joined(self, a: _T, b: _T) -> bool: ... + def get_siblings(self, a: _T) -> list[_T]: ... + +def simple_linear_interpolation(a: ArrayLike, steps: int) -> np.ndarray: ... +def delete_masked_points(*args): ... +def _broadcast_with_masks(*args: ArrayLike, compress: bool = ...) -> list[ArrayLike]: ... +def boxplot_stats( + X: ArrayLike, + whis: float | tuple[float, float] = ..., + bootstrap: int | None = ..., + labels: ArrayLike | None = ..., + autorange: bool = ..., +) -> list[dict[str, Any]]: ... + +ls_mapper: dict[str, str] +ls_mapper_r: dict[str, str] + +def contiguous_regions(mask: ArrayLike) -> list[np.ndarray]: ... +def is_math_text(s: str) -> bool: ... +def violin_stats( + X: ArrayLike, method: Callable, points: int = ..., quantiles: ArrayLike | None = ... +) -> list[dict[str, Any]]: ... +def pts_to_prestep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ... +def pts_to_poststep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ... +def pts_to_midstep(x: np.ndarray, *args: np.ndarray) -> np.ndarray: ... + +STEP_LOOKUP_MAP: dict[str, Callable] + +def index_of(y: float | ArrayLike) -> tuple[np.ndarray, np.ndarray]: ... +def safe_first_element(obj: Collection[_T]) -> _T: ... +def sanitize_sequence(data): ... +def normalize_kwargs( + kw: dict[str, Any], + alias_mapping: dict[str, list[str]] | type[Artist] | Artist | None = ..., +) -> dict[str, Any]: ... +def _lock_path(path: str | os.PathLike) -> contextlib.AbstractContextManager[None]: ... +def _str_equal(obj: Any, s: str) -> bool: ... +def _str_lower_equal(obj: Any, s: str) -> bool: ... +def _array_perimeter(arr: np.ndarray) -> np.ndarray: ... +def _unfold(arr: np.ndarray, axis: int, size: int, step: int) -> np.ndarray: ... +def _array_patch_perimeters(x: np.ndarray, rstride: int, cstride: int) -> np.ndarray: ... +def _setattr_cm(obj: Any, **kwargs) -> contextlib.AbstractContextManager[None]: ... + +class _OrderedSet(collections.abc.MutableSet): + def __init__(self) -> None: ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def __len__(self) -> int: ... + def add(self, key) -> None: ... + def discard(self, key) -> None: ... + +def _setup_new_guiapp() -> None: ... +def _format_approx(number: float, precision: int) -> str: ... +def _g_sig_digits(value: float, delta: float) -> int: ... +def _unikey_or_keysym_to_mplkey(unikey: str, keysym: str) -> str: ... +def _is_torch_array(x: Any) -> bool: ... +def _is_jax_array(x: Any) -> bool: ... +def _unpack_to_numpy(x: Any) -> Any: ... +def _auto_format_str(fmt: str, value: Any) -> str: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/cm.py b/llava_next/lib/python3.10/site-packages/matplotlib/cm.py new file mode 100644 index 0000000000000000000000000000000000000000..b0cb3e9a7ec10288331ae05e9c17fdeea29c73d9 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/cm.py @@ -0,0 +1,664 @@ +""" +Builtin colormaps, colormap handling utilities, and the `ScalarMappable` mixin. + +.. seealso:: + + :doc:`/gallery/color/colormap_reference` for a list of builtin colormaps. + + :ref:`colormap-manipulation` for examples of how to make + colormaps. + + :ref:`colormaps` an in-depth discussion of choosing + colormaps. + + :ref:`colormapnorms` for more details about data normalization. +""" + +from collections.abc import Mapping +import functools + +import numpy as np +from numpy import ma + +import matplotlib as mpl +from matplotlib import _api, colors, cbook, scale +from matplotlib._cm import datad +from matplotlib._cm_listed import cmaps as cmaps_listed + + +_LUTSIZE = mpl.rcParams['image.lut'] + + +def _gen_cmap_registry(): + """ + Generate a dict mapping standard colormap names to standard colormaps, as + well as the reversed colormaps. + """ + cmap_d = {**cmaps_listed} + for name, spec in datad.items(): + cmap_d[name] = ( # Precache the cmaps at a fixed lutsize.. + colors.LinearSegmentedColormap(name, spec, _LUTSIZE) + if 'red' in spec else + colors.ListedColormap(spec['listed'], name) + if 'listed' in spec else + colors.LinearSegmentedColormap.from_list(name, spec, _LUTSIZE)) + + # Register colormap aliases for gray and grey. + cmap_d['grey'] = cmap_d['gray'] + cmap_d['gist_grey'] = cmap_d['gist_gray'] + cmap_d['gist_yerg'] = cmap_d['gist_yarg'] + cmap_d['Grays'] = cmap_d['Greys'] + + # Generate reversed cmaps. + for cmap in list(cmap_d.values()): + rmap = cmap.reversed() + cmap_d[rmap.name] = rmap + return cmap_d + + +class ColormapRegistry(Mapping): + r""" + Container for colormaps that are known to Matplotlib by name. + + The universal registry instance is `matplotlib.colormaps`. There should be + no need for users to instantiate `.ColormapRegistry` themselves. + + Read access uses a dict-like interface mapping names to `.Colormap`\s:: + + import matplotlib as mpl + cmap = mpl.colormaps['viridis'] + + Returned `.Colormap`\s are copies, so that their modification does not + change the global definition of the colormap. + + Additional colormaps can be added via `.ColormapRegistry.register`:: + + mpl.colormaps.register(my_colormap) + + To get a list of all registered colormaps, you can do:: + + from matplotlib import colormaps + list(colormaps) + """ + def __init__(self, cmaps): + self._cmaps = cmaps + self._builtin_cmaps = tuple(cmaps) + + def __getitem__(self, item): + try: + return self._cmaps[item].copy() + except KeyError: + raise KeyError(f"{item!r} is not a known colormap name") from None + + def __iter__(self): + return iter(self._cmaps) + + def __len__(self): + return len(self._cmaps) + + def __str__(self): + return ('ColormapRegistry; available colormaps:\n' + + ', '.join(f"'{name}'" for name in self)) + + def __call__(self): + """ + Return a list of the registered colormap names. + + This exists only for backward-compatibility in `.pyplot` which had a + ``plt.colormaps()`` method. The recommended way to get this list is + now ``list(colormaps)``. + """ + return list(self) + + def register(self, cmap, *, name=None, force=False): + """ + Register a new colormap. + + The colormap name can then be used as a string argument to any ``cmap`` + parameter in Matplotlib. It is also available in ``pyplot.get_cmap``. + + The colormap registry stores a copy of the given colormap, so that + future changes to the original colormap instance do not affect the + registered colormap. Think of this as the registry taking a snapshot + of the colormap at registration. + + Parameters + ---------- + cmap : matplotlib.colors.Colormap + The colormap to register. + + name : str, optional + The name for the colormap. If not given, ``cmap.name`` is used. + + force : bool, default: False + If False, a ValueError is raised if trying to overwrite an already + registered name. True supports overwriting registered colormaps + other than the builtin colormaps. + """ + _api.check_isinstance(colors.Colormap, cmap=cmap) + + name = name or cmap.name + if name in self: + if not force: + # don't allow registering an already existing cmap + # unless explicitly asked to + raise ValueError( + f'A colormap named "{name}" is already registered.') + elif name in self._builtin_cmaps: + # We don't allow overriding a builtin. + raise ValueError("Re-registering the builtin cmap " + f"{name!r} is not allowed.") + + # Warn that we are updating an already existing colormap + _api.warn_external(f"Overwriting the cmap {name!r} " + "that was already in the registry.") + + self._cmaps[name] = cmap.copy() + # Someone may set the extremes of a builtin colormap and want to register it + # with a different name for future lookups. The object would still have the + # builtin name, so we should update it to the registered name + if self._cmaps[name].name != name: + self._cmaps[name].name = name + + def unregister(self, name): + """ + Remove a colormap from the registry. + + You cannot remove built-in colormaps. + + If the named colormap is not registered, returns with no error, raises + if you try to de-register a default colormap. + + .. warning:: + + Colormap names are currently a shared namespace that may be used + by multiple packages. Use `unregister` only if you know you + have registered that name before. In particular, do not + unregister just in case to clean the name before registering a + new colormap. + + Parameters + ---------- + name : str + The name of the colormap to be removed. + + Raises + ------ + ValueError + If you try to remove a default built-in colormap. + """ + if name in self._builtin_cmaps: + raise ValueError(f"cannot unregister {name!r} which is a builtin " + "colormap.") + self._cmaps.pop(name, None) + + def get_cmap(self, cmap): + """ + Return a color map specified through *cmap*. + + Parameters + ---------- + cmap : str or `~matplotlib.colors.Colormap` or None + + - if a `.Colormap`, return it + - if a string, look it up in ``mpl.colormaps`` + - if None, return the Colormap defined in :rc:`image.cmap` + + Returns + ------- + Colormap + """ + # get the default color map + if cmap is None: + return self[mpl.rcParams["image.cmap"]] + + # if the user passed in a Colormap, simply return it + if isinstance(cmap, colors.Colormap): + return cmap + if isinstance(cmap, str): + _api.check_in_list(sorted(_colormaps), cmap=cmap) + # otherwise, it must be a string so look it up + return self[cmap] + raise TypeError( + 'get_cmap expects None or an instance of a str or Colormap . ' + + f'you passed {cmap!r} of type {type(cmap)}' + ) + + +# public access to the colormaps should be via `matplotlib.colormaps`. For now, +# we still create the registry here, but that should stay an implementation +# detail. +_colormaps = ColormapRegistry(_gen_cmap_registry()) +globals().update(_colormaps) + + +# This is an exact copy of pyplot.get_cmap(). It was removed in 3.9, but apparently +# caused more user trouble than expected. Re-added for 3.9.1 and extended the +# deprecation period for two additional minor releases. +@_api.deprecated( + '3.7', + removal='3.11', + alternative="``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()``" + " or ``pyplot.get_cmap()``" + ) +def get_cmap(name=None, lut=None): + """ + Get a colormap instance, defaulting to rc values if *name* is None. + + Parameters + ---------- + name : `~matplotlib.colors.Colormap` or str or None, default: None + If a `.Colormap` instance, it will be returned. Otherwise, the name of + a colormap known to Matplotlib, which will be resampled by *lut*. The + default, None, means :rc:`image.cmap`. + lut : int or None, default: None + If *name* is not already a Colormap instance and *lut* is not None, the + colormap will be resampled to have *lut* entries in the lookup table. + + Returns + ------- + Colormap + """ + if name is None: + name = mpl.rcParams['image.cmap'] + if isinstance(name, colors.Colormap): + return name + _api.check_in_list(sorted(_colormaps), name=name) + if lut is None: + return _colormaps[name] + else: + return _colormaps[name].resampled(lut) + + +def _auto_norm_from_scale(scale_cls): + """ + Automatically generate a norm class from *scale_cls*. + + This differs from `.colors.make_norm_from_scale` in the following points: + + - This function is not a class decorator, but directly returns a norm class + (as if decorating `.Normalize`). + - The scale is automatically constructed with ``nonpositive="mask"``, if it + supports such a parameter, to work around the difference in defaults + between standard scales (which use "clip") and norms (which use "mask"). + + Note that ``make_norm_from_scale`` caches the generated norm classes + (not the instances) and reuses them for later calls. For example, + ``type(_auto_norm_from_scale("log")) == LogNorm``. + """ + # Actually try to construct an instance, to verify whether + # ``nonpositive="mask"`` is supported. + try: + norm = colors.make_norm_from_scale( + functools.partial(scale_cls, nonpositive="mask"))( + colors.Normalize)() + except TypeError: + norm = colors.make_norm_from_scale(scale_cls)( + colors.Normalize)() + return type(norm) + + +class ScalarMappable: + """ + A mixin class to map scalar data to RGBA. + + The ScalarMappable applies data normalization before returning RGBA colors + from the given colormap. + """ + + def __init__(self, norm=None, cmap=None): + """ + Parameters + ---------- + norm : `.Normalize` (or subclass thereof) or str or None + The normalizing object which scales data, typically into the + interval ``[0, 1]``. + If a `str`, a `.Normalize` subclass is dynamically generated based + on the scale with the corresponding name. + If *None*, *norm* defaults to a *colors.Normalize* object which + initializes its scaling based on the first data processed. + cmap : str or `~matplotlib.colors.Colormap` + The colormap used to map normalized data values to RGBA colors. + """ + self._A = None + self._norm = None # So that the setter knows we're initializing. + self.set_norm(norm) # The Normalize instance of this ScalarMappable. + self.cmap = None # So that the setter knows we're initializing. + self.set_cmap(cmap) # The Colormap instance of this ScalarMappable. + #: The last colorbar associated with this ScalarMappable. May be None. + self.colorbar = None + self.callbacks = cbook.CallbackRegistry(signals=["changed"]) + + def _scale_norm(self, norm, vmin, vmax): + """ + Helper for initial scaling. + + Used by public functions that create a ScalarMappable and support + parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm* + will take precedence over *vmin*, *vmax*. + + Note that this method does not set the norm. + """ + if vmin is not None or vmax is not None: + self.set_clim(vmin, vmax) + if isinstance(norm, colors.Normalize): + raise ValueError( + "Passing a Normalize instance simultaneously with " + "vmin/vmax is not supported. Please pass vmin/vmax " + "directly to the norm when creating it.") + + # always resolve the autoscaling so we have concrete limits + # rather than deferring to draw time. + self.autoscale_None() + + def to_rgba(self, x, alpha=None, bytes=False, norm=True): + """ + Return a normalized RGBA array corresponding to *x*. + + In the normal case, *x* is a 1D or 2D sequence of scalars, and + the corresponding `~numpy.ndarray` of RGBA values will be returned, + based on the norm and colormap set for this ScalarMappable. + + There is one special case, for handling images that are already + RGB or RGBA, such as might have been read from an image file. + If *x* is an `~numpy.ndarray` with 3 dimensions, + and the last dimension is either 3 or 4, then it will be + treated as an RGB or RGBA array, and no mapping will be done. + The array can be `~numpy.uint8`, or it can be floats with + values in the 0-1 range; otherwise a ValueError will be raised. + Any NaNs or masked elements will be set to 0 alpha. + If the last dimension is 3, the *alpha* kwarg (defaulting to 1) + will be used to fill in the transparency. If the last dimension + is 4, the *alpha* kwarg is ignored; it does not + replace the preexisting alpha. A ValueError will be raised + if the third dimension is other than 3 or 4. + + In either case, if *bytes* is *False* (default), the RGBA + array will be floats in the 0-1 range; if it is *True*, + the returned RGBA array will be `~numpy.uint8` in the 0 to 255 range. + + If norm is False, no normalization of the input data is + performed, and it is assumed to be in the range (0-1). + + """ + # First check for special case, image input: + try: + if x.ndim == 3: + if x.shape[2] == 3: + if alpha is None: + alpha = 1 + if x.dtype == np.uint8: + alpha = np.uint8(alpha * 255) + m, n = x.shape[:2] + xx = np.empty(shape=(m, n, 4), dtype=x.dtype) + xx[:, :, :3] = x + xx[:, :, 3] = alpha + elif x.shape[2] == 4: + xx = x + else: + raise ValueError("Third dimension must be 3 or 4") + if xx.dtype.kind == 'f': + # If any of R, G, B, or A is nan, set to 0 + if np.any(nans := np.isnan(x)): + if x.shape[2] == 4: + xx = xx.copy() + xx[np.any(nans, axis=2), :] = 0 + + if norm and (xx.max() > 1 or xx.min() < 0): + raise ValueError("Floating point image RGB values " + "must be in the 0..1 range.") + if bytes: + xx = (xx * 255).astype(np.uint8) + elif xx.dtype == np.uint8: + if not bytes: + xx = xx.astype(np.float32) / 255 + else: + raise ValueError("Image RGB array must be uint8 or " + "floating point; found %s" % xx.dtype) + # Account for any masked entries in the original array + # If any of R, G, B, or A are masked for an entry, we set alpha to 0 + if np.ma.is_masked(x): + xx[np.any(np.ma.getmaskarray(x), axis=2), 3] = 0 + return xx + except AttributeError: + # e.g., x is not an ndarray; so try mapping it + pass + + # This is the normal case, mapping a scalar array: + x = ma.asarray(x) + if norm: + x = self.norm(x) + rgba = self.cmap(x, alpha=alpha, bytes=bytes) + return rgba + + def set_array(self, A): + """ + Set the value array from array-like *A*. + + Parameters + ---------- + A : array-like or None + The values that are mapped to colors. + + The base class `.ScalarMappable` does not make any assumptions on + the dimensionality and shape of the value array *A*. + """ + if A is None: + self._A = None + return + + A = cbook.safe_masked_invalid(A, copy=True) + if not np.can_cast(A.dtype, float, "same_kind"): + raise TypeError(f"Image data of dtype {A.dtype} cannot be " + "converted to float") + + self._A = A + if not self.norm.scaled(): + self.norm.autoscale_None(A) + + def get_array(self): + """ + Return the array of values, that are mapped to colors. + + The base class `.ScalarMappable` does not make any assumptions on + the dimensionality and shape of the array. + """ + return self._A + + def get_cmap(self): + """Return the `.Colormap` instance.""" + return self.cmap + + def get_clim(self): + """ + Return the values (min, max) that are mapped to the colormap limits. + """ + return self.norm.vmin, self.norm.vmax + + def set_clim(self, vmin=None, vmax=None): + """ + Set the norm limits for image scaling. + + Parameters + ---------- + vmin, vmax : float + The limits. + + The limits may also be passed as a tuple (*vmin*, *vmax*) as a + single positional argument. + + .. ACCEPTS: (vmin: float, vmax: float) + """ + # If the norm's limits are updated self.changed() will be called + # through the callbacks attached to the norm + if vmax is None: + try: + vmin, vmax = vmin + except (TypeError, ValueError): + pass + if vmin is not None: + self.norm.vmin = colors._sanitize_extrema(vmin) + if vmax is not None: + self.norm.vmax = colors._sanitize_extrema(vmax) + + def get_alpha(self): + """ + Returns + ------- + float + Always returns 1. + """ + # This method is intended to be overridden by Artist sub-classes + return 1. + + def set_cmap(self, cmap): + """ + Set the colormap for luminance data. + + Parameters + ---------- + cmap : `.Colormap` or str or None + """ + in_init = self.cmap is None + + self.cmap = _ensure_cmap(cmap) + if not in_init: + self.changed() # Things are not set up properly yet. + + @property + def norm(self): + return self._norm + + @norm.setter + def norm(self, norm): + _api.check_isinstance((colors.Normalize, str, None), norm=norm) + if norm is None: + norm = colors.Normalize() + elif isinstance(norm, str): + try: + scale_cls = scale._scale_mapping[norm] + except KeyError: + raise ValueError( + "Invalid norm str name; the following values are " + f"supported: {', '.join(scale._scale_mapping)}" + ) from None + norm = _auto_norm_from_scale(scale_cls)() + + if norm is self.norm: + # We aren't updating anything + return + + in_init = self.norm is None + # Remove the current callback and connect to the new one + if not in_init: + self.norm.callbacks.disconnect(self._id_norm) + self._norm = norm + self._id_norm = self.norm.callbacks.connect('changed', + self.changed) + if not in_init: + self.changed() + + def set_norm(self, norm): + """ + Set the normalization instance. + + Parameters + ---------- + norm : `.Normalize` or str or None + + Notes + ----- + If there are any colorbars using the mappable for this norm, setting + the norm of the mappable will reset the norm, locator, and formatters + on the colorbar to default. + """ + self.norm = norm + + def autoscale(self): + """ + Autoscale the scalar limits on the norm instance using the + current array + """ + if self._A is None: + raise TypeError('You must first set_array for mappable') + # If the norm's limits are updated self.changed() will be called + # through the callbacks attached to the norm + self.norm.autoscale(self._A) + + def autoscale_None(self): + """ + Autoscale the scalar limits on the norm instance using the + current array, changing only limits that are None + """ + if self._A is None: + raise TypeError('You must first set_array for mappable') + # If the norm's limits are updated self.changed() will be called + # through the callbacks attached to the norm + self.norm.autoscale_None(self._A) + + def changed(self): + """ + Call this whenever the mappable is changed to notify all the + callbackSM listeners to the 'changed' signal. + """ + self.callbacks.process('changed', self) + self.stale = True + + +# The docstrings here must be generic enough to apply to all relevant methods. +mpl._docstring.interpd.update( + cmap_doc="""\ +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_doc="""\ +norm : str or `~matplotlib.colors.Normalize`, optional + The normalization method used to scale scalar data to the [0, 1] range + before mapping to colors using *cmap*. By default, a linear scaling is + used, mapping the lowest value to 0 and the highest to 1. + + If given, this can be one of the following: + + - An instance of `.Normalize` or one of its subclasses + (see :ref:`colormapnorms`). + - A scale name, i.e. one of "linear", "log", "symlog", "logit", etc. For a + list of available scales, call `matplotlib.scale.get_scale_names()`. + In that case, a suitable `.Normalize` subclass is dynamically generated + and instantiated.""", + vmin_vmax_doc="""\ +vmin, vmax : float, optional + When using scalar data and no explicit *norm*, *vmin* and *vmax* define + the data range that the colormap covers. By default, the colormap covers + the complete value range of the supplied data. It is an error to use + *vmin*/*vmax* when a *norm* instance is given (but using a `str` *norm* + name together with *vmin*/*vmax* is acceptable).""", +) + + +def _ensure_cmap(cmap): + """ + Ensure that we have a `.Colormap` object. + + For internal use to preserve type stability of errors. + + Parameters + ---------- + cmap : None, str, Colormap + + - if a `Colormap`, return it + - if a string, look it up in mpl.colormaps + - if None, look up the default color map in mpl.colormaps + + Returns + ------- + Colormap + + """ + if isinstance(cmap, colors.Colormap): + return cmap + cmap_name = cmap if cmap is not None else mpl.rcParams["image.cmap"] + # use check_in_list to ensure type stability of the exception raised by + # the internal usage of this (ValueError vs KeyError) + if cmap_name not in _colormaps: + _api.check_in_list(sorted(_colormaps), cmap=cmap_name) + return mpl.colormaps[cmap_name] diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/collections.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/collections.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e4c46229517ffc259ad9813c93002fde32232ff5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/collections.pyi @@ -0,0 +1,236 @@ +from collections.abc import Callable, Iterable, Sequence +from typing import Literal + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from . import artist, cm, transforms +from .backend_bases import MouseEvent +from .artist import Artist +from .colors import Normalize, Colormap +from .lines import Line2D +from .path import Path +from .patches import Patch +from .ticker import Locator, Formatter +from .tri import Triangulation +from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType + +class Collection(artist.Artist, cm.ScalarMappable): + def __init__( + self, + *, + edgecolors: ColorType | Sequence[ColorType] | None = ..., + facecolors: ColorType | Sequence[ColorType] | None = ..., + linewidths: float | Sequence[float] | None = ..., + linestyles: LineStyleType | Sequence[LineStyleType] = ..., + capstyle: CapStyleType | None = ..., + joinstyle: JoinStyleType | None = ..., + antialiaseds: bool | Sequence[bool] | None = ..., + offsets: tuple[float, float] | Sequence[tuple[float, float]] | None = ..., + offset_transform: transforms.Transform | None = ..., + norm: Normalize | None = ..., + cmap: Colormap | None = ..., + pickradius: float = ..., + hatch: str | None = ..., + urls: Sequence[str] | None = ..., + zorder: float = ..., + **kwargs + ) -> None: ... + def get_paths(self) -> Sequence[Path]: ... + def set_paths(self, paths: Sequence[Path]) -> None: ... + def get_transforms(self) -> Sequence[transforms.Transform]: ... + def get_offset_transform(self) -> transforms.Transform: ... + def set_offset_transform(self, offset_transform: transforms.Transform) -> None: ... + def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ... + def set_pickradius(self, pickradius: float) -> None: ... + def get_pickradius(self) -> float: ... + def set_urls(self, urls: Sequence[str | None]) -> None: ... + def get_urls(self) -> Sequence[str | None]: ... + def set_hatch(self, hatch: str) -> None: ... + def get_hatch(self) -> str: ... + def set_offsets(self, offsets: ArrayLike) -> None: ... + def get_offsets(self) -> ArrayLike: ... + def set_linewidth(self, lw: float | Sequence[float]) -> None: ... + def set_linestyle(self, ls: LineStyleType | Sequence[LineStyleType]) -> None: ... + def set_capstyle(self, cs: CapStyleType) -> None: ... + def get_capstyle(self) -> Literal["butt", "projecting", "round"] | None: ... + def set_joinstyle(self, js: JoinStyleType) -> None: ... + def get_joinstyle(self) -> Literal["miter", "round", "bevel"] | None: ... + def set_antialiased(self, aa: bool | Sequence[bool]) -> None: ... + def get_antialiased(self) -> NDArray[np.bool_]: ... + def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_facecolor(self, c: ColorType | Sequence[ColorType]) -> None: ... + def get_facecolor(self) -> ColorType | Sequence[ColorType]: ... + def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ... + def set_edgecolor(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_alpha(self, alpha: float | Sequence[float] | None) -> None: ... + def get_linewidth(self) -> float | Sequence[float]: ... + def get_linestyle(self) -> LineStyleType | Sequence[LineStyleType]: ... + def update_scalarmappable(self) -> None: ... + def get_fill(self) -> bool: ... + def update_from(self, other: Artist) -> None: ... + +class _CollectionWithSizes(Collection): + def get_sizes(self) -> np.ndarray: ... + def set_sizes(self, sizes: ArrayLike | None, dpi: float = ...) -> None: ... + +class PathCollection(_CollectionWithSizes): + def __init__( + self, paths: Sequence[Path], sizes: ArrayLike | None = ..., **kwargs + ) -> None: ... + def set_paths(self, paths: Sequence[Path]) -> None: ... + def get_paths(self) -> Sequence[Path]: ... + def legend_elements( + self, + prop: Literal["colors", "sizes"] = ..., + num: int | Literal["auto"] | ArrayLike | Locator = ..., + fmt: str | Formatter | None = ..., + func: Callable[[ArrayLike], ArrayLike] = ..., + **kwargs, + ) -> tuple[list[Line2D], list[str]]: ... + +class PolyCollection(_CollectionWithSizes): + def __init__( + self, + verts: Sequence[ArrayLike], + sizes: ArrayLike | None = ..., + *, + closed: bool = ..., + **kwargs + ) -> None: ... + def set_verts( + self, verts: Sequence[ArrayLike | Path], closed: bool = ... + ) -> None: ... + def set_paths(self, verts: Sequence[Path], closed: bool = ...) -> None: ... + def set_verts_and_codes( + self, verts: Sequence[ArrayLike | Path], codes: Sequence[int] + ) -> None: ... + +class RegularPolyCollection(_CollectionWithSizes): + def __init__( + self, numsides: int, *, rotation: float = ..., sizes: ArrayLike = ..., **kwargs + ) -> None: ... + def get_numsides(self) -> int: ... + def get_rotation(self) -> float: ... + +class StarPolygonCollection(RegularPolyCollection): ... +class AsteriskPolygonCollection(RegularPolyCollection): ... + +class LineCollection(Collection): + def __init__( + self, segments: Sequence[ArrayLike], *, zorder: float = ..., **kwargs + ) -> None: ... + def set_segments(self, segments: Sequence[ArrayLike] | None) -> None: ... + def set_verts(self, segments: Sequence[ArrayLike] | None) -> None: ... + def set_paths(self, segments: Sequence[ArrayLike] | None) -> None: ... # type: ignore[override] + def get_segments(self) -> list[np.ndarray]: ... + def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_colors(self, c: ColorType | Sequence[ColorType]) -> None: ... + def set_gapcolor(self, gapcolor: ColorType | Sequence[ColorType] | None) -> None: ... + def get_color(self) -> ColorType | Sequence[ColorType]: ... + def get_colors(self) -> ColorType | Sequence[ColorType]: ... + def get_gapcolor(self) -> ColorType | Sequence[ColorType] | None: ... + + +class EventCollection(LineCollection): + def __init__( + self, + positions: ArrayLike, + orientation: Literal["horizontal", "vertical"] = ..., + *, + lineoffset: float = ..., + linelength: float = ..., + linewidth: float | Sequence[float] | None = ..., + color: ColorType | Sequence[ColorType] | None = ..., + linestyle: LineStyleType | Sequence[LineStyleType] = ..., + antialiased: bool | Sequence[bool] | None = ..., + **kwargs + ) -> None: ... + def get_positions(self) -> list[float]: ... + def set_positions(self, positions: Sequence[float] | None) -> None: ... + def add_positions(self, position: Sequence[float] | None) -> None: ... + def extend_positions(self, position: Sequence[float] | None) -> None: ... + def append_positions(self, position: Sequence[float] | None) -> None: ... + def is_horizontal(self) -> bool: ... + def get_orientation(self) -> Literal["horizontal", "vertical"]: ... + def switch_orientation(self) -> None: ... + def set_orientation( + self, orientation: Literal["horizontal", "vertical"] + ) -> None: ... + def get_linelength(self) -> float | Sequence[float]: ... + def set_linelength(self, linelength: float | Sequence[float]) -> None: ... + def get_lineoffset(self) -> float: ... + def set_lineoffset(self, lineoffset: float) -> None: ... + def get_linewidth(self) -> float: ... + def get_linewidths(self) -> Sequence[float]: ... + def get_color(self) -> ColorType: ... + +class CircleCollection(_CollectionWithSizes): + def __init__(self, sizes: float | ArrayLike, **kwargs) -> None: ... + +class EllipseCollection(Collection): + def __init__( + self, + widths: ArrayLike, + heights: ArrayLike, + angles: ArrayLike, + *, + units: Literal[ + "points", "inches", "dots", "width", "height", "x", "y", "xy" + ] = ..., + **kwargs + ) -> None: ... + def set_widths(self, widths: ArrayLike) -> None: ... + def set_heights(self, heights: ArrayLike) -> None: ... + def set_angles(self, angles: ArrayLike) -> None: ... + def get_widths(self) -> ArrayLike: ... + def get_heights(self) -> ArrayLike: ... + def get_angles(self) -> ArrayLike: ... + +class PatchCollection(Collection): + def __init__( + self, patches: Iterable[Patch], *, match_original: bool = ..., **kwargs + ) -> None: ... + def set_paths(self, patches: Iterable[Patch]) -> None: ... # type: ignore[override] + +class TriMesh(Collection): + def __init__(self, triangulation: Triangulation, **kwargs) -> None: ... + def get_paths(self) -> list[Path]: ... + # Parent class has an argument, perhaps add a noop arg? + def set_paths(self) -> None: ... # type: ignore[override] + @staticmethod + def convert_mesh_to_paths(tri: Triangulation) -> list[Path]: ... + +class _MeshData: + def __init__( + self, + coordinates: ArrayLike, + *, + shading: Literal["flat", "gouraud"] = ..., + ) -> None: ... + def set_array(self, A: ArrayLike | None) -> None: ... + def get_coordinates(self) -> ArrayLike: ... + def get_facecolor(self) -> ColorType | Sequence[ColorType]: ... + def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ... + +class QuadMesh(_MeshData, Collection): + def __init__( + self, + coordinates: ArrayLike, + *, + antialiased: bool = ..., + shading: Literal["flat", "gouraud"] = ..., + **kwargs + ) -> None: ... + def get_paths(self) -> list[Path]: ... + # Parent class has an argument, perhaps add a noop arg? + def set_paths(self) -> None: ... # type: ignore[override] + def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ... + def get_cursor_data(self, event: MouseEvent) -> float: ... + +class PolyQuadMesh(_MeshData, PolyCollection): + def __init__( + self, + coordinates: ArrayLike, + **kwargs + ) -> None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/colorbar.py b/llava_next/lib/python3.10/site-packages/matplotlib/colorbar.py new file mode 100644 index 0000000000000000000000000000000000000000..156ea2ff649786c7364d6eec2924c2299f826936 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/colorbar.py @@ -0,0 +1,1559 @@ +""" +Colorbars are a visualization of the mapping from scalar values to colors. +In Matplotlib they are drawn into a dedicated `~.axes.Axes`. + +.. note:: + Colorbars are typically created through `.Figure.colorbar` or its pyplot + wrapper `.pyplot.colorbar`, which internally use `.Colorbar` together with + `.make_axes_gridspec` (for `.GridSpec`-positioned Axes) or `.make_axes` (for + non-`.GridSpec`-positioned Axes). + + End-users most likely won't need to directly use this module's API. +""" + +import logging + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, collections, cm, colors, contour, ticker +import matplotlib.artist as martist +import matplotlib.patches as mpatches +import matplotlib.path as mpath +import matplotlib.spines as mspines +import matplotlib.transforms as mtransforms +from matplotlib import _docstring + +_log = logging.getLogger(__name__) + +_docstring.interpd.update( + _make_axes_kw_doc=""" +location : None or {'left', 'right', 'top', 'bottom'} + The location, relative to the parent Axes, where the colorbar Axes + is created. It also determines the *orientation* of the colorbar + (colorbars on the left and right are vertical, colorbars at the top + and bottom are horizontal). If None, the location will come from the + *orientation* if it is set (vertical colorbars on the right, horizontal + ones at the bottom), or default to 'right' if *orientation* is unset. + +orientation : None or {'vertical', 'horizontal'} + The orientation of the colorbar. It is preferable to set the *location* + of the colorbar, as that also determines the *orientation*; passing + incompatible values for *location* and *orientation* raises an exception. + +fraction : float, default: 0.15 + Fraction of original Axes to use for colorbar. + +shrink : float, default: 1.0 + Fraction by which to multiply the size of the colorbar. + +aspect : float, default: 20 + Ratio of long to short dimensions. + +pad : float, default: 0.05 if vertical, 0.15 if horizontal + Fraction of original Axes between colorbar and new image Axes. + +anchor : (float, float), optional + The anchor point of the colorbar Axes. + Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. + +panchor : (float, float), or *False*, optional + The anchor point of the colorbar parent Axes. If *False*, the parent + axes' anchor will be unchanged. + Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.""", + _colormap_kw_doc=""" +extend : {'neither', 'both', 'min', 'max'} + Make pointed end(s) for out-of-range values (unless 'neither'). These are + set for a given colormap using the colormap set_under and set_over methods. + +extendfrac : {*None*, 'auto', length, lengths} + If set to *None*, both the minimum and maximum triangular colorbar + extensions will have a length of 5% of the interior colorbar length (this + is the default setting). + + If set to 'auto', makes the triangular colorbar extensions the same lengths + as the interior boxes (when *spacing* is set to 'uniform') or the same + lengths as the respective adjacent interior boxes (when *spacing* is set to + 'proportional'). + + If a scalar, indicates the length of both the minimum and maximum + triangular colorbar extensions as a fraction of the interior colorbar + length. A two-element sequence of fractions may also be given, indicating + the lengths of the minimum and maximum colorbar extensions respectively as + a fraction of the interior colorbar length. + +extendrect : bool + If *False* the minimum and maximum colorbar extensions will be triangular + (the default). If *True* the extensions will be rectangular. + +spacing : {'uniform', 'proportional'} + For discrete colorbars (`.BoundaryNorm` or contours), 'uniform' gives each + color the same space; 'proportional' makes the space proportional to the + data interval. + +ticks : None or list of ticks or Locator + If None, ticks are determined automatically from the input. + +format : None or str or Formatter + If None, `~.ticker.ScalarFormatter` is used. + Format strings, e.g., ``"%4.2e"`` or ``"{x:.2e}"``, are supported. + An alternative `~.ticker.Formatter` may be given instead. + +drawedges : bool + Whether to draw lines at color boundaries. + +label : str + The label on the colorbar's long axis. + +boundaries, values : None or a sequence + If unset, the colormap will be displayed on a 0-1 scale. + If sequences, *values* must have a length 1 less than *boundaries*. For + each region delimited by adjacent entries in *boundaries*, the color mapped + to the corresponding value in values will be used. + Normally only useful for indexed colors (i.e. ``norm=NoNorm()``) or other + unusual circumstances.""") + + +def _set_ticks_on_axis_warn(*args, **kwargs): + # a top level function which gets put in at the axes' + # set_xticks and set_yticks by Colorbar.__init__. + _api.warn_external("Use the colorbar set_ticks() method instead.") + + +class _ColorbarSpine(mspines.Spine): + def __init__(self, axes): + self._ax = axes + super().__init__(axes, 'colorbar', mpath.Path(np.empty((0, 2)))) + mpatches.Patch.set_transform(self, axes.transAxes) + + def get_window_extent(self, renderer=None): + # This Spine has no Axis associated with it, and doesn't need to adjust + # its location, so we can directly get the window extent from the + # super-super-class. + return mpatches.Patch.get_window_extent(self, renderer=renderer) + + def set_xy(self, xy): + self._path = mpath.Path(xy, closed=True) + self._xy = xy + self.stale = True + + def draw(self, renderer): + ret = mpatches.Patch.draw(self, renderer) + self.stale = False + return ret + + +class _ColorbarAxesLocator: + """ + Shrink the Axes if there are triangular or rectangular extends. + """ + def __init__(self, cbar): + self._cbar = cbar + self._orig_locator = cbar.ax._axes_locator + + def __call__(self, ax, renderer): + if self._orig_locator is not None: + pos = self._orig_locator(ax, renderer) + else: + pos = ax.get_position(original=True) + if self._cbar.extend == 'neither': + return pos + + y, extendlen = self._cbar._proportional_y() + if not self._cbar._extend_lower(): + extendlen[0] = 0 + if not self._cbar._extend_upper(): + extendlen[1] = 0 + len = sum(extendlen) + 1 + shrink = 1 / len + offset = extendlen[0] / len + # we need to reset the aspect ratio of the axes to account + # of the extends... + if hasattr(ax, '_colorbar_info'): + aspect = ax._colorbar_info['aspect'] + else: + aspect = False + # now shrink and/or offset to take into account the + # extend tri/rectangles. + if self._cbar.orientation == 'vertical': + if aspect: + self._cbar.ax.set_box_aspect(aspect*shrink) + pos = pos.shrunk(1, shrink).translated(0, offset * pos.height) + else: + if aspect: + self._cbar.ax.set_box_aspect(1/(aspect * shrink)) + pos = pos.shrunk(shrink, 1).translated(offset * pos.width, 0) + return pos + + def get_subplotspec(self): + # make tight_layout happy.. + return ( + self._cbar.ax.get_subplotspec() + or getattr(self._orig_locator, "get_subplotspec", lambda: None)()) + + +@_docstring.interpd +class Colorbar: + r""" + Draw a colorbar in an existing Axes. + + Typically, colorbars are created using `.Figure.colorbar` or + `.pyplot.colorbar` and associated with `.ScalarMappable`\s (such as an + `.AxesImage` generated via `~.axes.Axes.imshow`). + + In order to draw a colorbar not associated with other elements in the + figure, e.g. when showing a colormap by itself, one can create an empty + `.ScalarMappable`, or directly pass *cmap* and *norm* instead of *mappable* + to `Colorbar`. + + Useful public methods are :meth:`set_label` and :meth:`add_lines`. + + Attributes + ---------- + ax : `~matplotlib.axes.Axes` + The `~.axes.Axes` instance in which the colorbar is drawn. + lines : list + A list of `.LineCollection` (empty if no lines were drawn). + dividers : `.LineCollection` + A LineCollection (empty if *drawedges* is ``False``). + + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The `~.axes.Axes` instance in which the colorbar is drawn. + + mappable : `.ScalarMappable` + The mappable whose colormap and norm will be used. + + To show the under- and over- value colors, the mappable's norm should + be specified as :: + + norm = colors.Normalize(clip=False) + + To show the colors versus index instead of on a 0-1 scale, use:: + + norm=colors.NoNorm() + + cmap : `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` + The colormap to use. This parameter is ignored, unless *mappable* is + None. + + norm : `~matplotlib.colors.Normalize` + The normalization to use. This parameter is ignored, unless *mappable* + is None. + + alpha : float + The colorbar transparency between 0 (transparent) and 1 (opaque). + + orientation : None or {'vertical', 'horizontal'} + If None, use the value determined by *location*. If both + *orientation* and *location* are None then defaults to 'vertical'. + + ticklocation : {'auto', 'left', 'right', 'top', 'bottom'} + The location of the colorbar ticks. The *ticklocation* must match + *orientation*. For example, a horizontal colorbar can only have ticks + at the top or the bottom. If 'auto', the ticks will be the same as + *location*, so a colorbar to the left will have ticks to the left. If + *location* is None, the ticks will be at the bottom for a horizontal + colorbar and at the right for a vertical. + + %(_colormap_kw_doc)s + + location : None or {'left', 'right', 'top', 'bottom'} + Set the *orientation* and *ticklocation* of the colorbar using a + single argument. Colorbars on the left and right are vertical, + colorbars at the top and bottom are horizontal. The *ticklocation* is + the same as *location*, so if *location* is 'top', the ticks are on + the top. *orientation* and/or *ticklocation* can be provided as well + and overrides the value set by *location*, but there will be an error + for incompatible combinations. + + .. versionadded:: 3.7 + """ + + n_rasterize = 50 # rasterize solids if number of colors >= n_rasterize + + def __init__(self, ax, mappable=None, *, cmap=None, + norm=None, + alpha=None, + values=None, + boundaries=None, + orientation=None, + ticklocation='auto', + extend=None, + spacing='uniform', # uniform or proportional + ticks=None, + format=None, + drawedges=False, + extendfrac=None, + extendrect=False, + label='', + location=None, + ): + + if mappable is None: + mappable = cm.ScalarMappable(norm=norm, cmap=cmap) + + self.mappable = mappable + cmap = mappable.cmap + norm = mappable.norm + + filled = True + if isinstance(mappable, contour.ContourSet): + cs = mappable + alpha = cs.get_alpha() + boundaries = cs._levels + values = cs.cvalues + extend = cs.extend + filled = cs.filled + if ticks is None: + ticks = ticker.FixedLocator(cs.levels, nbins=10) + elif isinstance(mappable, martist.Artist): + alpha = mappable.get_alpha() + + mappable.colorbar = self + mappable.colorbar_cid = mappable.callbacks.connect( + 'changed', self.update_normal) + + location_orientation = _get_orientation_from_location(location) + + _api.check_in_list( + [None, 'vertical', 'horizontal'], orientation=orientation) + _api.check_in_list( + ['auto', 'left', 'right', 'top', 'bottom'], + ticklocation=ticklocation) + _api.check_in_list( + ['uniform', 'proportional'], spacing=spacing) + + if location_orientation is not None and orientation is not None: + if location_orientation != orientation: + raise TypeError( + "location and orientation are mutually exclusive") + else: + orientation = orientation or location_orientation or "vertical" + + self.ax = ax + self.ax._axes_locator = _ColorbarAxesLocator(self) + + if extend is None: + if (not isinstance(mappable, contour.ContourSet) + and getattr(cmap, 'colorbar_extend', False) is not False): + extend = cmap.colorbar_extend + elif hasattr(norm, 'extend'): + extend = norm.extend + else: + extend = 'neither' + self.alpha = None + # Call set_alpha to handle array-like alphas properly + self.set_alpha(alpha) + self.cmap = cmap + self.norm = norm + self.values = values + self.boundaries = boundaries + self.extend = extend + self._inside = _api.check_getitem( + {'neither': slice(0, None), 'both': slice(1, -1), + 'min': slice(1, None), 'max': slice(0, -1)}, + extend=extend) + self.spacing = spacing + self.orientation = orientation + self.drawedges = drawedges + self._filled = filled + self.extendfrac = extendfrac + self.extendrect = extendrect + self._extend_patches = [] + self.solids = None + self.solids_patches = [] + self.lines = [] + + for spine in self.ax.spines.values(): + spine.set_visible(False) + self.outline = self.ax.spines['outline'] = _ColorbarSpine(self.ax) + + self.dividers = collections.LineCollection( + [], + colors=[mpl.rcParams['axes.edgecolor']], + linewidths=[0.5 * mpl.rcParams['axes.linewidth']], + clip_on=False) + self.ax.add_collection(self.dividers) + + self._locator = None + self._minorlocator = None + self._formatter = None + self._minorformatter = None + + if ticklocation == 'auto': + ticklocation = _get_ticklocation_from_orientation( + orientation) if location is None else location + self.ticklocation = ticklocation + + self.set_label(label) + self._reset_locator_formatter_scale() + + if np.iterable(ticks): + self._locator = ticker.FixedLocator(ticks, nbins=len(ticks)) + else: + self._locator = ticks + + if isinstance(format, str): + # Check format between FormatStrFormatter and StrMethodFormatter + try: + self._formatter = ticker.FormatStrFormatter(format) + _ = self._formatter(0) + except (TypeError, ValueError): + self._formatter = ticker.StrMethodFormatter(format) + else: + self._formatter = format # Assume it is a Formatter or None + self._draw_all() + + if isinstance(mappable, contour.ContourSet) and not mappable.filled: + self.add_lines(mappable) + + # Link the Axes and Colorbar for interactive use + self.ax._colorbar = self + # Don't navigate on any of these types of mappables + if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or + isinstance(self.mappable, contour.ContourSet)): + self.ax.set_navigate(False) + + # These are the functions that set up interactivity on this colorbar + self._interactive_funcs = ["_get_view", "_set_view", + "_set_view_from_bbox", "drag_pan"] + for x in self._interactive_funcs: + setattr(self.ax, x, getattr(self, x)) + # Set the cla function to the cbar's method to override it + self.ax.cla = self._cbar_cla + # Callbacks for the extend calculations to handle inverting the axis + self._extend_cid1 = self.ax.callbacks.connect( + "xlim_changed", self._do_extends) + self._extend_cid2 = self.ax.callbacks.connect( + "ylim_changed", self._do_extends) + + @property + def locator(self): + """Major tick `.Locator` for the colorbar.""" + return self._long_axis().get_major_locator() + + @locator.setter + def locator(self, loc): + self._long_axis().set_major_locator(loc) + self._locator = loc + + @property + def minorlocator(self): + """Minor tick `.Locator` for the colorbar.""" + return self._long_axis().get_minor_locator() + + @minorlocator.setter + def minorlocator(self, loc): + self._long_axis().set_minor_locator(loc) + self._minorlocator = loc + + @property + def formatter(self): + """Major tick label `.Formatter` for the colorbar.""" + return self._long_axis().get_major_formatter() + + @formatter.setter + def formatter(self, fmt): + self._long_axis().set_major_formatter(fmt) + self._formatter = fmt + + @property + def minorformatter(self): + """Minor tick `.Formatter` for the colorbar.""" + return self._long_axis().get_minor_formatter() + + @minorformatter.setter + def minorformatter(self, fmt): + self._long_axis().set_minor_formatter(fmt) + self._minorformatter = fmt + + def _cbar_cla(self): + """Function to clear the interactive colorbar state.""" + for x in self._interactive_funcs: + delattr(self.ax, x) + # We now restore the old cla() back and can call it directly + del self.ax.cla + self.ax.cla() + + def update_normal(self, mappable): + """ + Update solid patches, lines, etc. + + This is meant to be called when the norm of the image or contour plot + to which this colorbar belongs changes. + + If the norm on the mappable is different than before, this resets the + locator and formatter for the axis, so if these have been customized, + they will need to be customized again. However, if the norm only + changes values of *vmin*, *vmax* or *cmap* then the old formatter + and locator will be preserved. + """ + _log.debug('colorbar update normal %r %r', mappable.norm, self.norm) + self.mappable = mappable + self.set_alpha(mappable.get_alpha()) + self.cmap = mappable.cmap + if mappable.norm != self.norm: + self.norm = mappable.norm + self._reset_locator_formatter_scale() + + self._draw_all() + if isinstance(self.mappable, contour.ContourSet): + CS = self.mappable + if not CS.filled: + self.add_lines(CS) + self.stale = True + + def _draw_all(self): + """ + Calculate any free parameters based on the current cmap and norm, + and do all the drawing. + """ + if self.orientation == 'vertical': + if mpl.rcParams['ytick.minor.visible']: + self.minorticks_on() + else: + if mpl.rcParams['xtick.minor.visible']: + self.minorticks_on() + self._long_axis().set(label_position=self.ticklocation, + ticks_position=self.ticklocation) + self._short_axis().set_ticks([]) + self._short_axis().set_ticks([], minor=True) + + # Set self._boundaries and self._values, including extensions. + # self._boundaries are the edges of each square of color, and + # self._values are the value to map into the norm to get the + # color: + self._process_values() + # Set self.vmin and self.vmax to first and last boundary, excluding + # extensions: + self.vmin, self.vmax = self._boundaries[self._inside][[0, -1]] + # Compute the X/Y mesh. + X, Y = self._mesh() + # draw the extend triangles, and shrink the inner Axes to accommodate. + # also adds the outline path to self.outline spine: + self._do_extends() + lower, upper = self.vmin, self.vmax + if self._long_axis().get_inverted(): + # If the axis is inverted, we need to swap the vmin/vmax + lower, upper = upper, lower + if self.orientation == 'vertical': + self.ax.set_xlim(0, 1) + self.ax.set_ylim(lower, upper) + else: + self.ax.set_ylim(0, 1) + self.ax.set_xlim(lower, upper) + + # set up the tick locators and formatters. A bit complicated because + # boundary norms + uniform spacing requires a manual locator. + self.update_ticks() + + if self._filled: + ind = np.arange(len(self._values)) + if self._extend_lower(): + ind = ind[1:] + if self._extend_upper(): + ind = ind[:-1] + self._add_solids(X, Y, self._values[ind, np.newaxis]) + + def _add_solids(self, X, Y, C): + """Draw the colors; optionally add separators.""" + # Cleanup previously set artists. + if self.solids is not None: + self.solids.remove() + for solid in self.solids_patches: + solid.remove() + # Add new artist(s), based on mappable type. Use individual patches if + # hatching is needed, pcolormesh otherwise. + mappable = getattr(self, 'mappable', None) + if (isinstance(mappable, contour.ContourSet) + and any(hatch is not None for hatch in mappable.hatches)): + self._add_solids_patches(X, Y, C, mappable) + else: + self.solids = self.ax.pcolormesh( + X, Y, C, cmap=self.cmap, norm=self.norm, alpha=self.alpha, + edgecolors='none', shading='flat') + if not self.drawedges: + if len(self._y) >= self.n_rasterize: + self.solids.set_rasterized(True) + self._update_dividers() + + def _update_dividers(self): + if not self.drawedges: + self.dividers.set_segments([]) + return + # Place all *internal* dividers. + if self.orientation == 'vertical': + lims = self.ax.get_ylim() + bounds = (lims[0] < self._y) & (self._y < lims[1]) + else: + lims = self.ax.get_xlim() + bounds = (lims[0] < self._y) & (self._y < lims[1]) + y = self._y[bounds] + # And then add outer dividers if extensions are on. + if self._extend_lower(): + y = np.insert(y, 0, lims[0]) + if self._extend_upper(): + y = np.append(y, lims[1]) + X, Y = np.meshgrid([0, 1], y) + if self.orientation == 'vertical': + segments = np.dstack([X, Y]) + else: + segments = np.dstack([Y, X]) + self.dividers.set_segments(segments) + + def _add_solids_patches(self, X, Y, C, mappable): + hatches = mappable.hatches * (len(C) + 1) # Have enough hatches. + if self._extend_lower(): + # remove first hatch that goes into the extend patch + hatches = hatches[1:] + patches = [] + for i in range(len(X) - 1): + xy = np.array([[X[i, 0], Y[i, 1]], + [X[i, 1], Y[i, 0]], + [X[i + 1, 1], Y[i + 1, 0]], + [X[i + 1, 0], Y[i + 1, 1]]]) + patch = mpatches.PathPatch(mpath.Path(xy), + facecolor=self.cmap(self.norm(C[i][0])), + hatch=hatches[i], linewidth=0, + antialiased=False, alpha=self.alpha) + self.ax.add_patch(patch) + patches.append(patch) + self.solids_patches = patches + + def _do_extends(self, ax=None): + """ + Add the extend tri/rectangles on the outside of the Axes. + + ax is unused, but required due to the callbacks on xlim/ylim changed + """ + # Clean up any previous extend patches + for patch in self._extend_patches: + patch.remove() + self._extend_patches = [] + # extend lengths are fraction of the *inner* part of colorbar, + # not the total colorbar: + _, extendlen = self._proportional_y() + bot = 0 - (extendlen[0] if self._extend_lower() else 0) + top = 1 + (extendlen[1] if self._extend_upper() else 0) + + # xyout is the outline of the colorbar including the extend patches: + if not self.extendrect: + # triangle: + xyout = np.array([[0, 0], [0.5, bot], [1, 0], + [1, 1], [0.5, top], [0, 1], [0, 0]]) + else: + # rectangle: + xyout = np.array([[0, 0], [0, bot], [1, bot], [1, 0], + [1, 1], [1, top], [0, top], [0, 1], + [0, 0]]) + + if self.orientation == 'horizontal': + xyout = xyout[:, ::-1] + + # xyout is the path for the spine: + self.outline.set_xy(xyout) + if not self._filled: + return + + # Make extend triangles or rectangles filled patches. These are + # defined in the outer parent axes' coordinates: + mappable = getattr(self, 'mappable', None) + if (isinstance(mappable, contour.ContourSet) + and any(hatch is not None for hatch in mappable.hatches)): + hatches = mappable.hatches * (len(self._y) + 1) + else: + hatches = [None] * (len(self._y) + 1) + + if self._extend_lower(): + if not self.extendrect: + # triangle + xy = np.array([[0, 0], [0.5, bot], [1, 0]]) + else: + # rectangle + xy = np.array([[0, 0], [0, bot], [1., bot], [1, 0]]) + if self.orientation == 'horizontal': + xy = xy[:, ::-1] + # add the patch + val = -1 if self._long_axis().get_inverted() else 0 + color = self.cmap(self.norm(self._values[val])) + patch = mpatches.PathPatch( + mpath.Path(xy), facecolor=color, alpha=self.alpha, + linewidth=0, antialiased=False, + transform=self.ax.transAxes, + hatch=hatches[0], clip_on=False, + # Place it right behind the standard patches, which is + # needed if we updated the extends + zorder=np.nextafter(self.ax.patch.zorder, -np.inf)) + self.ax.add_patch(patch) + self._extend_patches.append(patch) + # remove first hatch that goes into the extend patch + hatches = hatches[1:] + if self._extend_upper(): + if not self.extendrect: + # triangle + xy = np.array([[0, 1], [0.5, top], [1, 1]]) + else: + # rectangle + xy = np.array([[0, 1], [0, top], [1, top], [1, 1]]) + if self.orientation == 'horizontal': + xy = xy[:, ::-1] + # add the patch + val = 0 if self._long_axis().get_inverted() else -1 + color = self.cmap(self.norm(self._values[val])) + hatch_idx = len(self._y) - 1 + patch = mpatches.PathPatch( + mpath.Path(xy), facecolor=color, alpha=self.alpha, + linewidth=0, antialiased=False, + transform=self.ax.transAxes, hatch=hatches[hatch_idx], + clip_on=False, + # Place it right behind the standard patches, which is + # needed if we updated the extends + zorder=np.nextafter(self.ax.patch.zorder, -np.inf)) + self.ax.add_patch(patch) + self._extend_patches.append(patch) + + self._update_dividers() + + def add_lines(self, *args, **kwargs): + """ + Draw lines on the colorbar. + + The lines are appended to the list :attr:`lines`. + + Parameters + ---------- + levels : array-like + The positions of the lines. + colors : :mpltype:`color` or list of :mpltype:`color` + Either a single color applying to all lines or one color value for + each line. + linewidths : float or array-like + Either a single linewidth applying to all lines or one linewidth + for each line. + erase : bool, default: True + Whether to remove any previously added lines. + + Notes + ----- + Alternatively, this method can also be called with the signature + ``colorbar.add_lines(contour_set, erase=True)``, in which case + *levels*, *colors*, and *linewidths* are taken from *contour_set*. + """ + params = _api.select_matching_signature( + [lambda self, CS, erase=True: locals(), + lambda self, levels, colors, linewidths, erase=True: locals()], + self, *args, **kwargs) + if "CS" in params: + self, cs, erase = params.values() + if not isinstance(cs, contour.ContourSet) or cs.filled: + raise ValueError("If a single artist is passed to add_lines, " + "it must be a ContourSet of lines") + # TODO: Make colorbar lines auto-follow changes in contour lines. + return self.add_lines( + cs.levels, + cs.to_rgba(cs.cvalues, cs.alpha), + cs.get_linewidths(), + erase=erase) + else: + self, levels, colors, linewidths, erase = params.values() + + y = self._locate(levels) + rtol = (self._y[-1] - self._y[0]) * 1e-10 + igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol) + y = y[igood] + if np.iterable(colors): + colors = np.asarray(colors)[igood] + if np.iterable(linewidths): + linewidths = np.asarray(linewidths)[igood] + X, Y = np.meshgrid([0, 1], y) + if self.orientation == 'vertical': + xy = np.stack([X, Y], axis=-1) + else: + xy = np.stack([Y, X], axis=-1) + col = collections.LineCollection(xy, linewidths=linewidths, + colors=colors) + + if erase and self.lines: + for lc in self.lines: + lc.remove() + self.lines = [] + self.lines.append(col) + + # make a clip path that is just a linewidth bigger than the Axes... + fac = np.max(linewidths) / 72 + xy = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]) + inches = self.ax.get_figure().dpi_scale_trans + # do in inches: + xy = inches.inverted().transform(self.ax.transAxes.transform(xy)) + xy[[0, 1, 4], 1] -= fac + xy[[2, 3], 1] += fac + # back to axes units... + xy = self.ax.transAxes.inverted().transform(inches.transform(xy)) + col.set_clip_path(mpath.Path(xy, closed=True), + self.ax.transAxes) + self.ax.add_collection(col) + self.stale = True + + def update_ticks(self): + """ + Set up the ticks and ticklabels. This should not be needed by users. + """ + # Get the locator and formatter; defaults to self._locator if not None. + self._get_ticker_locator_formatter() + self._long_axis().set_major_locator(self._locator) + self._long_axis().set_minor_locator(self._minorlocator) + self._long_axis().set_major_formatter(self._formatter) + + def _get_ticker_locator_formatter(self): + """ + Return the ``locator`` and ``formatter`` of the colorbar. + + If they have not been defined (i.e. are *None*), the formatter and + locator are retrieved from the axis, or from the value of the + boundaries for a boundary norm. + + Called by update_ticks... + """ + locator = self._locator + formatter = self._formatter + minorlocator = self._minorlocator + if isinstance(self.norm, colors.BoundaryNorm): + b = self.norm.boundaries + if locator is None: + locator = ticker.FixedLocator(b, nbins=10) + if minorlocator is None: + minorlocator = ticker.FixedLocator(b) + elif isinstance(self.norm, colors.NoNorm): + if locator is None: + # put ticks on integers between the boundaries of NoNorm + nv = len(self._values) + base = 1 + int(nv / 10) + locator = ticker.IndexLocator(base=base, offset=.5) + elif self.boundaries is not None: + b = self._boundaries[self._inside] + if locator is None: + locator = ticker.FixedLocator(b, nbins=10) + else: # most cases: + if locator is None: + # we haven't set the locator explicitly, so use the default + # for this axis: + locator = self._long_axis().get_major_locator() + if minorlocator is None: + minorlocator = self._long_axis().get_minor_locator() + + if minorlocator is None: + minorlocator = ticker.NullLocator() + + if formatter is None: + formatter = self._long_axis().get_major_formatter() + + self._locator = locator + self._formatter = formatter + self._minorlocator = minorlocator + _log.debug('locator: %r', locator) + + def set_ticks(self, ticks, *, labels=None, minor=False, **kwargs): + """ + Set tick locations. + + Parameters + ---------- + ticks : 1D array-like + List of tick locations. + labels : list of str, optional + List of tick labels. If not set, the labels show the data value. + minor : bool, default: False + If ``False``, set the major ticks; if ``True``, the minor ticks. + **kwargs + `.Text` properties for the labels. These take effect only if you + pass *labels*. In other cases, please use `~.Axes.tick_params`. + """ + if np.iterable(ticks): + self._long_axis().set_ticks(ticks, labels=labels, minor=minor, + **kwargs) + self._locator = self._long_axis().get_major_locator() + else: + self._locator = ticks + self._long_axis().set_major_locator(self._locator) + self.stale = True + + def get_ticks(self, minor=False): + """ + Return the ticks as a list of locations. + + Parameters + ---------- + minor : boolean, default: False + if True return the minor ticks. + """ + if minor: + return self._long_axis().get_minorticklocs() + else: + return self._long_axis().get_majorticklocs() + + def set_ticklabels(self, ticklabels, *, minor=False, **kwargs): + """ + [*Discouraged*] Set tick labels. + + .. admonition:: Discouraged + + The use of this method is discouraged, because of the dependency + on tick positions. In most cases, you'll want to use + ``set_ticks(positions, labels=labels)`` instead. + + If you are using this method, you should always fix the tick + positions before, e.g. by using `.Colorbar.set_ticks` or by + explicitly setting a `~.ticker.FixedLocator` on the long axis + of the colorbar. Otherwise, ticks are free to move and the + labels may end up in unexpected positions. + + Parameters + ---------- + ticklabels : sequence of str or of `.Text` + Texts for labeling each tick location in the sequence set by + `.Colorbar.set_ticks`; the number of labels must match the number + of locations. + + update_ticks : bool, default: True + This keyword argument is ignored and will be removed. + Deprecated + + minor : bool + If True, set minor ticks instead of major ticks. + + **kwargs + `.Text` properties for the labels. + """ + self._long_axis().set_ticklabels(ticklabels, minor=minor, **kwargs) + + def minorticks_on(self): + """ + Turn on colorbar minor ticks. + """ + self.ax.minorticks_on() + self._short_axis().set_minor_locator(ticker.NullLocator()) + + def minorticks_off(self): + """Turn the minor ticks of the colorbar off.""" + self._minorlocator = ticker.NullLocator() + self._long_axis().set_minor_locator(self._minorlocator) + + def set_label(self, label, *, loc=None, **kwargs): + """ + Add a label to the long axis of the colorbar. + + Parameters + ---------- + label : str + The label text. + loc : str, optional + The location of the label. + + - For horizontal orientation one of {'left', 'center', 'right'} + - For vertical orientation one of {'bottom', 'center', 'top'} + + Defaults to :rc:`xaxis.labellocation` or :rc:`yaxis.labellocation` + depending on the orientation. + **kwargs + Keyword arguments are passed to `~.Axes.set_xlabel` / + `~.Axes.set_ylabel`. + Supported keywords are *labelpad* and `.Text` properties. + """ + if self.orientation == "vertical": + self.ax.set_ylabel(label, loc=loc, **kwargs) + else: + self.ax.set_xlabel(label, loc=loc, **kwargs) + self.stale = True + + def set_alpha(self, alpha): + """ + Set the transparency between 0 (transparent) and 1 (opaque). + + If an array is provided, *alpha* will be set to None to use the + transparency values associated with the colormap. + """ + self.alpha = None if isinstance(alpha, np.ndarray) else alpha + + def _set_scale(self, scale, **kwargs): + """ + Set the colorbar long axis scale. + + Parameters + ---------- + scale : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase` + The axis scale type to apply. + + **kwargs + Different keyword arguments are accepted, depending on the scale. + See the respective class keyword arguments: + + - `matplotlib.scale.LinearScale` + - `matplotlib.scale.LogScale` + - `matplotlib.scale.SymmetricalLogScale` + - `matplotlib.scale.LogitScale` + - `matplotlib.scale.FuncScale` + - `matplotlib.scale.AsinhScale` + + Notes + ----- + By default, Matplotlib supports the above-mentioned scales. + Additionally, custom scales may be registered using + `matplotlib.scale.register_scale`. These scales can then also + be used here. + """ + self._long_axis()._set_axes_scale(scale, **kwargs) + + def remove(self): + """ + Remove this colorbar from the figure. + + If the colorbar was created with ``use_gridspec=True`` the previous + gridspec is restored. + """ + if hasattr(self.ax, '_colorbar_info'): + parents = self.ax._colorbar_info['parents'] + for a in parents: + if self.ax in a._colorbars: + a._colorbars.remove(self.ax) + + self.ax.remove() + + self.mappable.callbacks.disconnect(self.mappable.colorbar_cid) + self.mappable.colorbar = None + self.mappable.colorbar_cid = None + # Remove the extension callbacks + self.ax.callbacks.disconnect(self._extend_cid1) + self.ax.callbacks.disconnect(self._extend_cid2) + + try: + ax = self.mappable.axes + except AttributeError: + return + try: + subplotspec = self.ax.get_subplotspec().get_gridspec()._subplot_spec + except AttributeError: # use_gridspec was False + pos = ax.get_position(original=True) + ax._set_position(pos) + else: # use_gridspec was True + ax.set_subplotspec(subplotspec) + + def _process_values(self): + """ + Set `_boundaries` and `_values` based on the self.boundaries and + self.values if not None, or based on the size of the colormap and + the vmin/vmax of the norm. + """ + if self.values is not None: + # set self._boundaries from the values... + self._values = np.array(self.values) + if self.boundaries is None: + # bracket values by 1/2 dv: + b = np.zeros(len(self.values) + 1) + b[1:-1] = 0.5 * (self._values[:-1] + self._values[1:]) + b[0] = 2.0 * b[1] - b[2] + b[-1] = 2.0 * b[-2] - b[-3] + self._boundaries = b + return + self._boundaries = np.array(self.boundaries) + return + + # otherwise values are set from the boundaries + if isinstance(self.norm, colors.BoundaryNorm): + b = self.norm.boundaries + elif isinstance(self.norm, colors.NoNorm): + # NoNorm has N blocks, so N+1 boundaries, centered on integers: + b = np.arange(self.cmap.N + 1) - .5 + elif self.boundaries is not None: + b = self.boundaries + else: + # otherwise make the boundaries from the size of the cmap: + N = self.cmap.N + 1 + b, _ = self._uniform_y(N) + # add extra boundaries if needed: + if self._extend_lower(): + b = np.hstack((b[0] - 1, b)) + if self._extend_upper(): + b = np.hstack((b, b[-1] + 1)) + + # transform from 0-1 to vmin-vmax: + if self.mappable.get_array() is not None: + self.mappable.autoscale_None() + if not self.norm.scaled(): + # If we still aren't scaled after autoscaling, use 0, 1 as default + self.norm.vmin = 0 + self.norm.vmax = 1 + self.norm.vmin, self.norm.vmax = mtransforms.nonsingular( + self.norm.vmin, self.norm.vmax, expander=0.1) + if (not isinstance(self.norm, colors.BoundaryNorm) and + (self.boundaries is None)): + b = self.norm.inverse(b) + + self._boundaries = np.asarray(b, dtype=float) + self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:]) + if isinstance(self.norm, colors.NoNorm): + self._values = (self._values + 0.00001).astype(np.int16) + + def _mesh(self): + """ + Return the coordinate arrays for the colorbar pcolormesh/patches. + + These are scaled between vmin and vmax, and already handle colorbar + orientation. + """ + y, _ = self._proportional_y() + # Use the vmin and vmax of the colorbar, which may not be the same + # as the norm. There are situations where the colormap has a + # narrower range than the colorbar and we want to accommodate the + # extra contours. + if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) + or self.boundaries is not None): + # not using a norm. + y = y * (self.vmax - self.vmin) + self.vmin + else: + # Update the norm values in a context manager as it is only + # a temporary change and we don't want to propagate any signals + # attached to the norm (callbacks.blocked). + with self.norm.callbacks.blocked(), \ + cbook._setattr_cm(self.norm, + vmin=self.vmin, + vmax=self.vmax): + y = self.norm.inverse(y) + self._y = y + X, Y = np.meshgrid([0., 1.], y) + if self.orientation == 'vertical': + return (X, Y) + else: + return (Y, X) + + def _forward_boundaries(self, x): + # map boundaries equally between 0 and 1... + b = self._boundaries + y = np.interp(x, b, np.linspace(0, 1, len(b))) + # the following avoids ticks in the extends: + eps = (b[-1] - b[0]) * 1e-6 + # map these _well_ out of bounds to keep any ticks out + # of the extends region... + y[x < b[0]-eps] = -1 + y[x > b[-1]+eps] = 2 + return y + + def _inverse_boundaries(self, x): + # invert the above... + b = self._boundaries + return np.interp(x, np.linspace(0, 1, len(b)), b) + + def _reset_locator_formatter_scale(self): + """ + Reset the locator et al to defaults. Any user-hardcoded changes + need to be re-entered if this gets called (either at init, or when + the mappable normal gets changed: Colorbar.update_normal) + """ + self._process_values() + self._locator = None + self._minorlocator = None + self._formatter = None + self._minorformatter = None + if (isinstance(self.mappable, contour.ContourSet) and + isinstance(self.norm, colors.LogNorm)): + # if contours have lognorm, give them a log scale... + self._set_scale('log') + elif (self.boundaries is not None or + isinstance(self.norm, colors.BoundaryNorm)): + if self.spacing == 'uniform': + funcs = (self._forward_boundaries, self._inverse_boundaries) + self._set_scale('function', functions=funcs) + elif self.spacing == 'proportional': + self._set_scale('linear') + elif getattr(self.norm, '_scale', None): + # use the norm's scale (if it exists and is not None): + self._set_scale(self.norm._scale) + elif type(self.norm) is colors.Normalize: + # plain Normalize: + self._set_scale('linear') + else: + # norm._scale is None or not an attr: derive the scale from + # the Norm: + funcs = (self.norm, self.norm.inverse) + self._set_scale('function', functions=funcs) + + def _locate(self, x): + """ + Given a set of color data values, return their + corresponding colorbar data coordinates. + """ + if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)): + b = self._boundaries + xn = x + else: + # Do calculations using normalized coordinates so + # as to make the interpolation more accurate. + b = self.norm(self._boundaries, clip=False).filled() + xn = self.norm(x, clip=False).filled() + + bunique = b[self._inside] + yunique = self._y + + z = np.interp(xn, bunique, yunique) + return z + + # trivial helpers + + def _uniform_y(self, N): + """ + Return colorbar data coordinates for *N* uniformly + spaced boundaries, plus extension lengths if required. + """ + automin = automax = 1. / (N - 1.) + extendlength = self._get_extension_lengths(self.extendfrac, + automin, automax, + default=0.05) + y = np.linspace(0, 1, N) + return y, extendlength + + def _proportional_y(self): + """ + Return colorbar data coordinates for the boundaries of + a proportional colorbar, plus extension lengths if required: + """ + if (isinstance(self.norm, colors.BoundaryNorm) or + self.boundaries is not None): + y = (self._boundaries - self._boundaries[self._inside][0]) + y = y / (self._boundaries[self._inside][-1] - + self._boundaries[self._inside][0]) + # need yscaled the same as the axes scale to get + # the extend lengths. + if self.spacing == 'uniform': + yscaled = self._forward_boundaries(self._boundaries) + else: + yscaled = y + else: + y = self.norm(self._boundaries.copy()) + y = np.ma.filled(y, np.nan) + # the norm and the scale should be the same... + yscaled = y + y = y[self._inside] + yscaled = yscaled[self._inside] + # normalize from 0..1: + norm = colors.Normalize(y[0], y[-1]) + y = np.ma.filled(norm(y), np.nan) + norm = colors.Normalize(yscaled[0], yscaled[-1]) + yscaled = np.ma.filled(norm(yscaled), np.nan) + # make the lower and upper extend lengths proportional to the lengths + # of the first and last boundary spacing (if extendfrac='auto'): + automin = yscaled[1] - yscaled[0] + automax = yscaled[-1] - yscaled[-2] + extendlength = [0, 0] + if self._extend_lower() or self._extend_upper(): + extendlength = self._get_extension_lengths( + self.extendfrac, automin, automax, default=0.05) + return y, extendlength + + def _get_extension_lengths(self, frac, automin, automax, default=0.05): + """ + Return the lengths of colorbar extensions. + + This is a helper method for _uniform_y and _proportional_y. + """ + # Set the default value. + extendlength = np.array([default, default]) + if isinstance(frac, str): + _api.check_in_list(['auto'], extendfrac=frac.lower()) + # Use the provided values when 'auto' is required. + extendlength[:] = [automin, automax] + elif frac is not None: + try: + # Try to set min and max extension fractions directly. + extendlength[:] = frac + # If frac is a sequence containing None then NaN may + # be encountered. This is an error. + if np.isnan(extendlength).any(): + raise ValueError() + except (TypeError, ValueError) as err: + # Raise an error on encountering an invalid value for frac. + raise ValueError('invalid value for extendfrac') from err + return extendlength + + def _extend_lower(self): + """Return whether the lower limit is open ended.""" + minmax = "max" if self._long_axis().get_inverted() else "min" + return self.extend in ('both', minmax) + + def _extend_upper(self): + """Return whether the upper limit is open ended.""" + minmax = "min" if self._long_axis().get_inverted() else "max" + return self.extend in ('both', minmax) + + def _long_axis(self): + """Return the long axis""" + if self.orientation == 'vertical': + return self.ax.yaxis + return self.ax.xaxis + + def _short_axis(self): + """Return the short axis""" + if self.orientation == 'vertical': + return self.ax.xaxis + return self.ax.yaxis + + def _get_view(self): + # docstring inherited + # An interactive view for a colorbar is the norm's vmin/vmax + return self.norm.vmin, self.norm.vmax + + def _set_view(self, view): + # docstring inherited + # An interactive view for a colorbar is the norm's vmin/vmax + self.norm.vmin, self.norm.vmax = view + + def _set_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + # docstring inherited + # For colorbars, we use the zoom bbox to scale the norm's vmin/vmax + new_xbound, new_ybound = self.ax._prepare_view_from_bbox( + bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny) + if self.orientation == 'horizontal': + self.norm.vmin, self.norm.vmax = new_xbound + elif self.orientation == 'vertical': + self.norm.vmin, self.norm.vmax = new_ybound + + def drag_pan(self, button, key, x, y): + # docstring inherited + points = self.ax._get_pan_points(button, key, x, y) + if points is not None: + if self.orientation == 'horizontal': + self.norm.vmin, self.norm.vmax = points[:, 0] + elif self.orientation == 'vertical': + self.norm.vmin, self.norm.vmax = points[:, 1] + + +ColorbarBase = Colorbar # Backcompat API + + +def _normalize_location_orientation(location, orientation): + if location is None: + location = _get_ticklocation_from_orientation(orientation) + loc_settings = _api.check_getitem({ + "left": {"location": "left", "anchor": (1.0, 0.5), + "panchor": (0.0, 0.5), "pad": 0.10}, + "right": {"location": "right", "anchor": (0.0, 0.5), + "panchor": (1.0, 0.5), "pad": 0.05}, + "top": {"location": "top", "anchor": (0.5, 0.0), + "panchor": (0.5, 1.0), "pad": 0.05}, + "bottom": {"location": "bottom", "anchor": (0.5, 1.0), + "panchor": (0.5, 0.0), "pad": 0.15}, + }, location=location) + loc_settings["orientation"] = _get_orientation_from_location(location) + if orientation is not None and orientation != loc_settings["orientation"]: + # Allow the user to pass both if they are consistent. + raise TypeError("location and orientation are mutually exclusive") + return loc_settings + + +def _get_orientation_from_location(location): + return _api.check_getitem( + {None: None, "left": "vertical", "right": "vertical", + "top": "horizontal", "bottom": "horizontal"}, location=location) + + +def _get_ticklocation_from_orientation(orientation): + return _api.check_getitem( + {None: "right", "vertical": "right", "horizontal": "bottom"}, + orientation=orientation) + + +@_docstring.interpd +def make_axes(parents, location=None, orientation=None, fraction=0.15, + shrink=1.0, aspect=20, **kwargs): + """ + Create an `~.axes.Axes` suitable for a colorbar. + + The Axes is placed in the figure of the *parents* Axes, by resizing and + repositioning *parents*. + + Parameters + ---------- + parents : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of `~.axes.Axes` + The Axes to use as parents for placing the colorbar. + %(_make_axes_kw_doc)s + + Returns + ------- + cax : `~matplotlib.axes.Axes` + The child Axes. + kwargs : dict + The reduced keyword dictionary to be passed when creating the colorbar + instance. + """ + loc_settings = _normalize_location_orientation(location, orientation) + # put appropriate values into the kwargs dict for passing back to + # the Colorbar class + kwargs['orientation'] = loc_settings['orientation'] + location = kwargs['ticklocation'] = loc_settings['location'] + + anchor = kwargs.pop('anchor', loc_settings['anchor']) + panchor = kwargs.pop('panchor', loc_settings['panchor']) + aspect0 = aspect + # turn parents into a list if it is not already. Note we cannot + # use .flatten or .ravel as these copy the references rather than + # reuse them, leading to a memory leak + if isinstance(parents, np.ndarray): + parents = list(parents.flat) + elif np.iterable(parents): + parents = list(parents) + else: + parents = [parents] + + fig = parents[0].get_figure() + + pad0 = 0.05 if fig.get_constrained_layout() else loc_settings['pad'] + pad = kwargs.pop('pad', pad0) + + if not all(fig is ax.get_figure() for ax in parents): + raise ValueError('Unable to create a colorbar Axes as not all ' + 'parents share the same figure.') + + # take a bounding box around all of the given Axes + parents_bbox = mtransforms.Bbox.union( + [ax.get_position(original=True).frozen() for ax in parents]) + + pb = parents_bbox + if location in ('left', 'right'): + if location == 'left': + pbcb, _, pb1 = pb.splitx(fraction, fraction + pad) + else: + pb1, _, pbcb = pb.splitx(1 - fraction - pad, 1 - fraction) + pbcb = pbcb.shrunk(1.0, shrink).anchored(anchor, pbcb) + else: + if location == 'bottom': + pbcb, _, pb1 = pb.splity(fraction, fraction + pad) + else: + pb1, _, pbcb = pb.splity(1 - fraction - pad, 1 - fraction) + pbcb = pbcb.shrunk(shrink, 1.0).anchored(anchor, pbcb) + + # define the aspect ratio in terms of y's per x rather than x's per y + aspect = 1.0 / aspect + + # define a transform which takes us from old axes coordinates to + # new axes coordinates + shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1) + + # transform each of the Axes in parents using the new transform + for ax in parents: + new_posn = shrinking_trans.transform(ax.get_position(original=True)) + new_posn = mtransforms.Bbox(new_posn) + ax._set_position(new_posn) + if panchor is not False: + ax.set_anchor(panchor) + + cax = fig.add_axes(pbcb, label="") + for a in parents: + # tell the parent it has a colorbar + a._colorbars += [cax] + cax._colorbar_info = dict( + parents=parents, + location=location, + shrink=shrink, + anchor=anchor, + panchor=panchor, + fraction=fraction, + aspect=aspect0, + pad=pad) + # and we need to set the aspect ratio by hand... + cax.set_anchor(anchor) + cax.set_box_aspect(aspect) + cax.set_aspect('auto') + + return cax, kwargs + + +@_docstring.interpd +def make_axes_gridspec(parent, *, location=None, orientation=None, + fraction=0.15, shrink=1.0, aspect=20, **kwargs): + """ + Create an `~.axes.Axes` suitable for a colorbar. + + The Axes is placed in the figure of the *parent* Axes, by resizing and + repositioning *parent*. + + This function is similar to `.make_axes` and mostly compatible with it. + Primary differences are + + - `.make_axes_gridspec` requires the *parent* to have a subplotspec. + - `.make_axes` positions the Axes in figure coordinates; + `.make_axes_gridspec` positions it using a subplotspec. + - `.make_axes` updates the position of the parent. `.make_axes_gridspec` + replaces the parent gridspec with a new one. + + Parameters + ---------- + parent : `~matplotlib.axes.Axes` + The Axes to use as parent for placing the colorbar. + %(_make_axes_kw_doc)s + + Returns + ------- + cax : `~matplotlib.axes.Axes` + The child Axes. + kwargs : dict + The reduced keyword dictionary to be passed when creating the colorbar + instance. + """ + + loc_settings = _normalize_location_orientation(location, orientation) + kwargs['orientation'] = loc_settings['orientation'] + location = kwargs['ticklocation'] = loc_settings['location'] + + aspect0 = aspect + anchor = kwargs.pop('anchor', loc_settings['anchor']) + panchor = kwargs.pop('panchor', loc_settings['panchor']) + pad = kwargs.pop('pad', loc_settings["pad"]) + wh_space = 2 * pad / (1 - pad) + + if location in ('left', 'right'): + gs = parent.get_subplotspec().subgridspec( + 3, 2, wspace=wh_space, hspace=0, + height_ratios=[(1-anchor[1])*(1-shrink), shrink, anchor[1]*(1-shrink)]) + if location == 'left': + gs.set_width_ratios([fraction, 1 - fraction - pad]) + ss_main = gs[:, 1] + ss_cb = gs[1, 0] + else: + gs.set_width_ratios([1 - fraction - pad, fraction]) + ss_main = gs[:, 0] + ss_cb = gs[1, 1] + else: + gs = parent.get_subplotspec().subgridspec( + 2, 3, hspace=wh_space, wspace=0, + width_ratios=[anchor[0]*(1-shrink), shrink, (1-anchor[0])*(1-shrink)]) + if location == 'top': + gs.set_height_ratios([fraction, 1 - fraction - pad]) + ss_main = gs[1, :] + ss_cb = gs[0, 1] + else: + gs.set_height_ratios([1 - fraction - pad, fraction]) + ss_main = gs[0, :] + ss_cb = gs[1, 1] + aspect = 1 / aspect + + parent.set_subplotspec(ss_main) + if panchor is not False: + parent.set_anchor(panchor) + + fig = parent.get_figure() + cax = fig.add_subplot(ss_cb, label="") + cax.set_anchor(anchor) + cax.set_box_aspect(aspect) + cax.set_aspect('auto') + cax._colorbar_info = dict( + location=location, + parents=[parent], + shrink=shrink, + anchor=anchor, + panchor=panchor, + fraction=fraction, + aspect=aspect0, + pad=pad) + + return cax, kwargs diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/colors.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/colors.pyi new file mode 100644 index 0000000000000000000000000000000000000000..514801b714b8fbe6e7d90aef997149f187351426 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/colors.pyi @@ -0,0 +1,354 @@ +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from matplotlib import cbook, scale +import re + +from typing import Any, Literal, overload +from .typing import ColorType + +import numpy as np +from numpy.typing import ArrayLike + +# Explicitly export colors dictionaries which are imported in the impl +BASE_COLORS: dict[str, ColorType] +CSS4_COLORS: dict[str, ColorType] +TABLEAU_COLORS: dict[str, ColorType] +XKCD_COLORS: dict[str, ColorType] + +class _ColorMapping(dict[str, ColorType]): + cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]] + def __init__(self, mapping) -> None: ... + def __setitem__(self, key, value) -> None: ... + def __delitem__(self, key) -> None: ... + +def get_named_colors_mapping() -> _ColorMapping: ... + +class ColorSequenceRegistry(Mapping): + def __init__(self) -> None: ... + def __getitem__(self, item: str) -> list[ColorType]: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def register(self, name: str, color_list: Iterable[ColorType]) -> None: ... + def unregister(self, name: str) -> None: ... + +_color_sequences: ColorSequenceRegistry = ... + +def is_color_like(c: Any) -> bool: ... +def same_color(c1: ColorType, c2: ColorType) -> bool: ... +def to_rgba( + c: ColorType, alpha: float | None = ... +) -> tuple[float, float, float, float]: ... +def to_rgba_array( + c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ... +) -> np.ndarray: ... +def to_rgb(c: ColorType) -> tuple[float, float, float]: ... +def to_hex(c: ColorType, keep_alpha: bool = ...) -> str: ... + +cnames: dict[str, ColorType] +hexColorPattern: re.Pattern +rgb2hex = to_hex +hex2color = to_rgb + +class ColorConverter: + colors: _ColorMapping + cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]] + @staticmethod + def to_rgb(c: ColorType) -> tuple[float, float, float]: ... + @staticmethod + def to_rgba( + c: ColorType, alpha: float | None = ... + ) -> tuple[float, float, float, float]: ... + @staticmethod + def to_rgba_array( + c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ... + ) -> np.ndarray: ... + +colorConverter: ColorConverter + +class Colormap: + name: str + N: int + colorbar_extend: bool + def __init__(self, name: str, N: int = ...) -> None: ... + @overload + def __call__( + self, X: Sequence[float] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ... + ) -> np.ndarray: ... + @overload + def __call__( + self, X: float, alpha: float | None = ..., bytes: bool = ... + ) -> tuple[float, float, float, float]: ... + @overload + def __call__( + self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ... + ) -> tuple[float, float, float, float] | np.ndarray: ... + def __copy__(self) -> Colormap: ... + def __eq__(self, other: object) -> bool: ... + def get_bad(self) -> np.ndarray: ... + def set_bad(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... + def get_under(self) -> np.ndarray: ... + def set_under(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... + def get_over(self) -> np.ndarray: ... + def set_over(self, color: ColorType = ..., alpha: float | None = ...) -> None: ... + def set_extremes( + self, + *, + bad: ColorType | None = ..., + under: ColorType | None = ..., + over: ColorType | None = ... + ) -> None: ... + def with_extremes( + self, + *, + bad: ColorType | None = ..., + under: ColorType | None = ..., + over: ColorType | None = ... + ) -> Colormap: ... + def is_gray(self) -> bool: ... + def resampled(self, lutsize: int) -> Colormap: ... + def reversed(self, name: str | None = ...) -> Colormap: ... + def _repr_html_(self) -> str: ... + def _repr_png_(self) -> bytes: ... + def copy(self) -> Colormap: ... + +class LinearSegmentedColormap(Colormap): + monochrome: bool + def __init__( + self, + name: str, + segmentdata: dict[ + Literal["red", "green", "blue", "alpha"], Sequence[tuple[float, ...]] + ], + N: int = ..., + gamma: float = ..., + ) -> None: ... + def set_gamma(self, gamma: float) -> None: ... + @staticmethod + def from_list( + name: str, colors: ArrayLike | Sequence[tuple[float, ColorType]], N: int = ..., gamma: float = ... + ) -> LinearSegmentedColormap: ... + def resampled(self, lutsize: int) -> LinearSegmentedColormap: ... + def reversed(self, name: str | None = ...) -> LinearSegmentedColormap: ... + +class ListedColormap(Colormap): + monochrome: bool + colors: ArrayLike | ColorType + def __init__( + self, colors: ArrayLike | ColorType, name: str = ..., N: int | None = ... + ) -> None: ... + def resampled(self, lutsize: int) -> ListedColormap: ... + def reversed(self, name: str | None = ...) -> ListedColormap: ... + +class Normalize: + callbacks: cbook.CallbackRegistry + def __init__( + self, vmin: float | None = ..., vmax: float | None = ..., clip: bool = ... + ) -> None: ... + @property + def vmin(self) -> float | None: ... + @vmin.setter + def vmin(self, value: float | None) -> None: ... + @property + def vmax(self) -> float | None: ... + @vmax.setter + def vmax(self, value: float | None) -> None: ... + @property + def clip(self) -> bool: ... + @clip.setter + def clip(self, value: bool) -> None: ... + @staticmethod + def process_value(value: ArrayLike) -> tuple[np.ma.MaskedArray, bool]: ... + @overload + def __call__(self, value: float, clip: bool | None = ...) -> float: ... + @overload + def __call__(self, value: np.ndarray, clip: bool | None = ...) -> np.ma.MaskedArray: ... + @overload + def __call__(self, value: ArrayLike, clip: bool | None = ...) -> ArrayLike: ... + @overload + def inverse(self, value: float) -> float: ... + @overload + def inverse(self, value: np.ndarray) -> np.ma.MaskedArray: ... + @overload + def inverse(self, value: ArrayLike) -> ArrayLike: ... + def autoscale(self, A: ArrayLike) -> None: ... + def autoscale_None(self, A: ArrayLike) -> None: ... + def scaled(self) -> bool: ... + +class TwoSlopeNorm(Normalize): + def __init__( + self, vcenter: float, vmin: float | None = ..., vmax: float | None = ... + ) -> None: ... + @property + def vcenter(self) -> float: ... + @vcenter.setter + def vcenter(self, value: float) -> None: ... + def autoscale_None(self, A: ArrayLike) -> None: ... + +class CenteredNorm(Normalize): + def __init__( + self, vcenter: float = ..., halfrange: float | None = ..., clip: bool = ... + ) -> None: ... + @property + def vcenter(self) -> float: ... + @vcenter.setter + def vcenter(self, vcenter: float) -> None: ... + @property + def halfrange(self) -> float: ... + @halfrange.setter + def halfrange(self, halfrange: float) -> None: ... + +@overload +def make_norm_from_scale( + scale_cls: type[scale.ScaleBase], + base_norm_cls: type[Normalize], + *, + init: Callable | None = ... +) -> type[Normalize]: ... +@overload +def make_norm_from_scale( + scale_cls: type[scale.ScaleBase], + base_norm_cls: None = ..., + *, + init: Callable | None = ... +) -> Callable[[type[Normalize]], type[Normalize]]: ... + +class FuncNorm(Normalize): + def __init__( + self, + functions: tuple[Callable, Callable], + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + ) -> None: ... +class LogNorm(Normalize): ... + +class SymLogNorm(Normalize): + def __init__( + self, + linthresh: float, + linscale: float = ..., + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + *, + base: float = ..., + ) -> None: ... + @property + def linthresh(self) -> float: ... + @linthresh.setter + def linthresh(self, value: float) -> None: ... + +class AsinhNorm(Normalize): + def __init__( + self, + linear_width: float = ..., + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + ) -> None: ... + @property + def linear_width(self) -> float: ... + @linear_width.setter + def linear_width(self, value: float) -> None: ... + +class PowerNorm(Normalize): + gamma: float + def __init__( + self, + gamma: float, + vmin: float | None = ..., + vmax: float | None = ..., + clip: bool = ..., + ) -> None: ... + +class BoundaryNorm(Normalize): + boundaries: np.ndarray + N: int + Ncmap: int + extend: Literal["neither", "both", "min", "max"] + def __init__( + self, + boundaries: ArrayLike, + ncolors: int, + clip: bool = ..., + *, + extend: Literal["neither", "both", "min", "max"] = ... + ) -> None: ... + +class NoNorm(Normalize): ... + +def rgb_to_hsv(arr: ArrayLike) -> np.ndarray: ... +def hsv_to_rgb(hsv: ArrayLike) -> np.ndarray: ... + +class LightSource: + azdeg: float + altdeg: float + hsv_min_val: float + hsv_max_val: float + hsv_min_sat: float + hsv_max_sat: float + def __init__( + self, + azdeg: float = ..., + altdeg: float = ..., + hsv_min_val: float = ..., + hsv_max_val: float = ..., + hsv_min_sat: float = ..., + hsv_max_sat: float = ..., + ) -> None: ... + @property + def direction(self) -> np.ndarray: ... + def hillshade( + self, + elevation: ArrayLike, + vert_exag: float = ..., + dx: float = ..., + dy: float = ..., + fraction: float = ..., + ) -> np.ndarray: ... + def shade_normals( + self, normals: np.ndarray, fraction: float = ... + ) -> np.ndarray: ... + def shade( + self, + data: ArrayLike, + cmap: Colormap, + norm: Normalize | None = ..., + blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ..., + vmin: float | None = ..., + vmax: float | None = ..., + vert_exag: float = ..., + dx: float = ..., + dy: float = ..., + fraction: float = ..., + **kwargs + ) -> np.ndarray: ... + def shade_rgb( + self, + rgb: ArrayLike, + elevation: ArrayLike, + fraction: float = ..., + blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ..., + vert_exag: float = ..., + dx: float = ..., + dy: float = ..., + **kwargs + ) -> np.ndarray: ... + def blend_hsv( + self, + rgb: ArrayLike, + intensity: ArrayLike, + hsv_max_sat: float | None = ..., + hsv_max_val: float | None = ..., + hsv_min_val: float | None = ..., + hsv_min_sat: float | None = ..., + ) -> ArrayLike: ... + def blend_soft_light( + self, rgb: np.ndarray, intensity: np.ndarray + ) -> np.ndarray: ... + def blend_overlay(self, rgb: np.ndarray, intensity: np.ndarray) -> np.ndarray: ... + +def from_levels_and_colors( + levels: Sequence[float], + colors: Sequence[ColorType], + extend: Literal["neither", "min", "max", "both"] = ..., +) -> tuple[ListedColormap, BoundaryNorm]: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/container.py b/llava_next/lib/python3.10/site-packages/matplotlib/container.py new file mode 100644 index 0000000000000000000000000000000000000000..b6dd43724f34b219a7d8864542af4dbec81d89ff --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/container.py @@ -0,0 +1,141 @@ +from matplotlib import cbook +from matplotlib.artist import Artist + + +class Container(tuple): + """ + Base class for containers. + + Containers are classes that collect semantically related Artists such as + the bars of a bar plot. + """ + + def __repr__(self): + return f"<{type(self).__name__} object of {len(self)} artists>" + + def __new__(cls, *args, **kwargs): + return tuple.__new__(cls, args[0]) + + def __init__(self, kl, label=None): + self._callbacks = cbook.CallbackRegistry(signals=["pchanged"]) + self._remove_method = None + self._label = str(label) if label is not None else None + + def remove(self): + for c in cbook.flatten( + self, scalarp=lambda x: isinstance(x, Artist)): + if c is not None: + c.remove() + if self._remove_method: + self._remove_method(self) + + def get_children(self): + return [child for child in cbook.flatten(self) if child is not None] + + get_label = Artist.get_label + set_label = Artist.set_label + add_callback = Artist.add_callback + remove_callback = Artist.remove_callback + pchanged = Artist.pchanged + + +class BarContainer(Container): + """ + Container for the artists of bar plots (e.g. created by `.Axes.bar`). + + The container can be treated as a tuple of the *patches* themselves. + Additionally, you can access these and further parameters by the + attributes. + + Attributes + ---------- + patches : list of :class:`~matplotlib.patches.Rectangle` + The artists of the bars. + + errorbar : None or :class:`~matplotlib.container.ErrorbarContainer` + A container for the error bar artists if error bars are present. + *None* otherwise. + + datavalues : None or array-like + The underlying data values corresponding to the bars. + + orientation : {'vertical', 'horizontal'}, default: None + If 'vertical', the bars are assumed to be vertical. + If 'horizontal', the bars are assumed to be horizontal. + + """ + + def __init__(self, patches, errorbar=None, *, datavalues=None, + orientation=None, **kwargs): + self.patches = patches + self.errorbar = errorbar + self.datavalues = datavalues + self.orientation = orientation + super().__init__(patches, **kwargs) + + +class ErrorbarContainer(Container): + """ + Container for the artists of error bars (e.g. created by `.Axes.errorbar`). + + The container can be treated as the *lines* tuple itself. + Additionally, you can access these and further parameters by the + attributes. + + Attributes + ---------- + lines : tuple + Tuple of ``(data_line, caplines, barlinecols)``. + + - data_line : A `~matplotlib.lines.Line2D` instance of x, y plot markers + and/or line. + - caplines : A tuple of `~matplotlib.lines.Line2D` instances of the error + bar caps. + - barlinecols : A tuple of `~matplotlib.collections.LineCollection` with the + horizontal and vertical error ranges. + + has_xerr, has_yerr : bool + ``True`` if the errorbar has x/y errors. + + """ + + def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs): + self.lines = lines + self.has_xerr = has_xerr + self.has_yerr = has_yerr + super().__init__(lines, **kwargs) + + +class StemContainer(Container): + """ + Container for the artists created in a :meth:`.Axes.stem` plot. + + The container can be treated like a namedtuple ``(markerline, stemlines, + baseline)``. + + Attributes + ---------- + markerline : `~matplotlib.lines.Line2D` + The artist of the markers at the stem heads. + + stemlines : `~matplotlib.collections.LineCollection` + The artists of the vertical lines for all stems. + + baseline : `~matplotlib.lines.Line2D` + The artist of the horizontal baseline. + """ + def __init__(self, markerline_stemlines_baseline, **kwargs): + """ + Parameters + ---------- + markerline_stemlines_baseline : tuple + Tuple of ``(markerline, stemlines, baseline)``. + ``markerline`` contains the `.Line2D` of the markers, + ``stemlines`` is a `.LineCollection` of the main lines, + ``baseline`` is the `.Line2D` of the baseline. + """ + markerline, stemlines, baseline = markerline_stemlines_baseline + self.markerline = markerline + self.stemlines = stemlines + self.baseline = baseline + super().__init__(markerline_stemlines_baseline, **kwargs) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/dviread.py b/llava_next/lib/python3.10/site-packages/matplotlib/dviread.py new file mode 100644 index 0000000000000000000000000000000000000000..82f43b56292d2bc8de24d4510aaf203cd4e0027b --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/dviread.py @@ -0,0 +1,1107 @@ +""" +A module for reading dvi files output by TeX. Several limitations make +this not (currently) useful as a general-purpose dvi preprocessor, but +it is currently used by the pdf backend for processing usetex text. + +Interface:: + + with Dvi(filename, 72) as dvi: + # iterate over pages: + for page in dvi: + w, h, d = page.width, page.height, page.descent + for x, y, font, glyph, width in page.text: + fontname = font.texname + pointsize = font.size + ... + for x, y, height, width in page.boxes: + ... +""" + +from collections import namedtuple +import enum +from functools import lru_cache, partial, wraps +import logging +import os +from pathlib import Path +import re +import struct +import subprocess +import sys + +import numpy as np + +from matplotlib import _api, cbook + +_log = logging.getLogger(__name__) + +# Many dvi related files are looked for by external processes, require +# additional parsing, and are used many times per rendering, which is why they +# are cached using lru_cache(). + +# Dvi is a bytecode format documented in +# https://ctan.org/pkg/dvitype +# https://texdoc.org/serve/dvitype.pdf/0 +# +# The file consists of a preamble, some number of pages, a postamble, +# and a finale. Different opcodes are allowed in different contexts, +# so the Dvi object has a parser state: +# +# pre: expecting the preamble +# outer: between pages (followed by a page or the postamble, +# also e.g. font definitions are allowed) +# page: processing a page +# post_post: state after the postamble (our current implementation +# just stops reading) +# finale: the finale (unimplemented in our current implementation) + +_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale') + +# The marks on a page consist of text and boxes. A page also has dimensions. +Page = namedtuple('Page', 'text boxes height width descent') +Box = namedtuple('Box', 'x y height width') + + +# Also a namedtuple, for backcompat. +class Text(namedtuple('Text', 'x y font glyph width')): + """ + A glyph in the dvi file. + + The *x* and *y* attributes directly position the glyph. The *font*, + *glyph*, and *width* attributes are kept public for back-compatibility, + but users wanting to draw the glyph themselves are encouraged to instead + load the font specified by `font_path` at `font_size`, warp it with the + effects specified by `font_effects`, and load the glyph specified by + `glyph_name_or_index`. + """ + + def _get_pdftexmap_entry(self): + return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname] + + @property + def font_path(self): + """The `~pathlib.Path` to the font for this glyph.""" + psfont = self._get_pdftexmap_entry() + if psfont.filename is None: + raise ValueError("No usable font file found for {} ({}); " + "the font may lack a Type-1 version" + .format(psfont.psname.decode("ascii"), + psfont.texname.decode("ascii"))) + return Path(psfont.filename) + + @property + def font_size(self): + """The font size.""" + return self.font.size + + @property + def font_effects(self): + """ + The "font effects" dict for this glyph. + + This dict contains the values for this glyph of SlantFont and + ExtendFont (if any), read off :file:`pdftex.map`. + """ + return self._get_pdftexmap_entry().effects + + @property + def glyph_name_or_index(self): + """ + Either the glyph name or the native charmap glyph index. + + If :file:`pdftex.map` specifies an encoding for this glyph's font, that + is a mapping of glyph indices to Adobe glyph names; use it to convert + dvi indices to glyph names. Callers can then convert glyph names to + glyph indices (with FT_Get_Name_Index/get_name_index), and load the + glyph using FT_Load_Glyph/load_glyph. + + If :file:`pdftex.map` specifies no encoding, the indices directly map + to the font's "native" charmap; glyphs should directly load using + FT_Load_Char/load_char after selecting the native charmap. + """ + entry = self._get_pdftexmap_entry() + return (_parse_enc(entry.encoding)[self.glyph] + if entry.encoding is not None else self.glyph) + + +# Opcode argument parsing +# +# Each of the following functions takes a Dvi object and delta, which is the +# difference between the opcode and the minimum opcode with the same meaning. +# Dvi opcodes often encode the number of argument bytes in this delta. +_arg_mapping = dict( + # raw: Return delta as is. + raw=lambda dvi, delta: delta, + # u1: Read 1 byte as an unsigned number. + u1=lambda dvi, delta: dvi._arg(1, signed=False), + # u4: Read 4 bytes as an unsigned number. + u4=lambda dvi, delta: dvi._arg(4, signed=False), + # s4: Read 4 bytes as a signed number. + s4=lambda dvi, delta: dvi._arg(4, signed=True), + # slen: Read delta bytes as a signed number, or None if delta is None. + slen=lambda dvi, delta: dvi._arg(delta, signed=True) if delta else None, + # slen1: Read (delta + 1) bytes as a signed number. + slen1=lambda dvi, delta: dvi._arg(delta + 1, signed=True), + # ulen1: Read (delta + 1) bytes as an unsigned number. + ulen1=lambda dvi, delta: dvi._arg(delta + 1, signed=False), + # olen1: Read (delta + 1) bytes as an unsigned number if less than 4 bytes, + # as a signed number if 4 bytes. + olen1=lambda dvi, delta: dvi._arg(delta + 1, signed=(delta == 3)), +) + + +def _dispatch(table, min, max=None, state=None, args=('raw',)): + """ + Decorator for dispatch by opcode. Sets the values in *table* + from *min* to *max* to this method, adds a check that the Dvi state + matches *state* if not None, reads arguments from the file according + to *args*. + + Parameters + ---------- + table : dict[int, callable] + The dispatch table to be filled in. + + min, max : int + Range of opcodes that calls the registered function; *max* defaults to + *min*. + + state : _dvistate, optional + State of the Dvi object in which these opcodes are allowed. + + args : list[str], default: ['raw'] + Sequence of argument specifications: + + - 'raw': opcode minus minimum + - 'u1': read one unsigned byte + - 'u4': read four bytes, treat as an unsigned number + - 's4': read four bytes, treat as a signed number + - 'slen': read (opcode - minimum) bytes, treat as signed + - 'slen1': read (opcode - minimum + 1) bytes, treat as signed + - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned + - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned + if under four bytes, signed if four bytes + """ + def decorate(method): + get_args = [_arg_mapping[x] for x in args] + + @wraps(method) + def wrapper(self, byte): + if state is not None and self.state != state: + raise ValueError("state precondition failed") + return method(self, *[f(self, byte-min) for f in get_args]) + if max is None: + table[min] = wrapper + else: + for i in range(min, max+1): + assert table[i] is None + table[i] = wrapper + return wrapper + return decorate + + +class Dvi: + """ + A reader for a dvi ("device-independent") file, as produced by TeX. + + The current implementation can only iterate through pages in order, + and does not even attempt to verify the postamble. + + This class can be used as a context manager to close the underlying + file upon exit. Pages can be read via iteration. Here is an overly + simple way to extract text without trying to detect whitespace:: + + >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi: + ... for page in dvi: + ... print(''.join(chr(t.glyph) for t in page.text)) + """ + # dispatch table + _dtable = [None] * 256 + _dispatch = partial(_dispatch, _dtable) + + def __init__(self, filename, dpi): + """ + Read the data from the file named *filename* and convert + TeX's internal units to units of *dpi* per inch. + *dpi* only sets the units and does not limit the resolution. + Use None to return TeX's internal units. + """ + _log.debug('Dvi: %s', filename) + self.file = open(filename, 'rb') + self.dpi = dpi + self.fonts = {} + self.state = _dvistate.pre + + def __enter__(self): + """Context manager enter method, does nothing.""" + return self + + def __exit__(self, etype, evalue, etrace): + """ + Context manager exit method, closes the underlying file if it is open. + """ + self.close() + + def __iter__(self): + """ + Iterate through the pages of the file. + + Yields + ------ + Page + Details of all the text and box objects on the page. + The Page tuple contains lists of Text and Box tuples and + the page dimensions, and the Text and Box tuples contain + coordinates transformed into a standard Cartesian + coordinate system at the dpi value given when initializing. + The coordinates are floating point numbers, but otherwise + precision is not lost and coordinate values are not clipped to + integers. + """ + while self._read(): + yield self._output() + + def close(self): + """Close the underlying file if it is open.""" + if not self.file.closed: + self.file.close() + + def _output(self): + """ + Output the text and boxes belonging to the most recent page. + page = dvi._output() + """ + minx, miny, maxx, maxy = np.inf, np.inf, -np.inf, -np.inf + maxy_pure = -np.inf + for elt in self.text + self.boxes: + if isinstance(elt, Box): + x, y, h, w = elt + e = 0 # zero depth + else: # glyph + x, y, font, g, w = elt + h, e = font._height_depth_of(g) + minx = min(minx, x) + miny = min(miny, y - h) + maxx = max(maxx, x + w) + maxy = max(maxy, y + e) + maxy_pure = max(maxy_pure, y) + if self._baseline_v is not None: + maxy_pure = self._baseline_v # This should normally be the case. + self._baseline_v = None + + if not self.text and not self.boxes: # Avoid infs/nans from inf+/-inf. + return Page(text=[], boxes=[], width=0, height=0, descent=0) + + if self.dpi is None: + # special case for ease of debugging: output raw dvi coordinates + return Page(text=self.text, boxes=self.boxes, + width=maxx-minx, height=maxy_pure-miny, + descent=maxy-maxy_pure) + + # convert from TeX's "scaled points" to dpi units + d = self.dpi / (72.27 * 2**16) + descent = (maxy - maxy_pure) * d + + text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d) + for (x, y, f, g, w) in self.text] + boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d) + for (x, y, h, w) in self.boxes] + + return Page(text=text, boxes=boxes, width=(maxx-minx)*d, + height=(maxy_pure-miny)*d, descent=descent) + + def _read(self): + """ + Read one page from the file. Return True if successful, + False if there were no more pages. + """ + # Pages appear to start with the sequence + # bop (begin of page) + # xxx comment + # # if using chemformula + # down + # push + # down + # # if using xcolor + # down + # push + # down (possibly multiple) + # push <= here, v is the baseline position. + # etc. + # (dviasm is useful to explore this structure.) + # Thus, we use the vertical position at the first time the stack depth + # reaches 3, while at least three "downs" have been executed (excluding + # those popped out (corresponding to the chemformula preamble)), as the + # baseline (the "down" count is necessary to handle xcolor). + down_stack = [0] + self._baseline_v = None + while True: + byte = self.file.read(1)[0] + self._dtable[byte](self, byte) + name = self._dtable[byte].__name__ + if name == "_push": + down_stack.append(down_stack[-1]) + elif name == "_pop": + down_stack.pop() + elif name == "_down": + down_stack[-1] += 1 + if (self._baseline_v is None + and len(getattr(self, "stack", [])) == 3 + and down_stack[-1] >= 4): + self._baseline_v = self.v + if byte == 140: # end of page + return True + if self.state is _dvistate.post_post: # end of file + self.close() + return False + + def _arg(self, nbytes, signed=False): + """ + Read and return a big-endian integer *nbytes* long. + Signedness is determined by the *signed* keyword. + """ + return int.from_bytes(self.file.read(nbytes), "big", signed=signed) + + @_dispatch(min=0, max=127, state=_dvistate.inpage) + def _set_char_immediate(self, char): + self._put_char_real(char) + self.h += self.fonts[self.f]._width_of(char) + + @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',)) + def _set_char(self, char): + self._put_char_real(char) + self.h += self.fonts[self.f]._width_of(char) + + @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4')) + def _set_rule(self, a, b): + self._put_rule_real(a, b) + self.h += b + + @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',)) + def _put_char(self, char): + self._put_char_real(char) + + def _put_char_real(self, char): + font = self.fonts[self.f] + if font._vf is None: + self.text.append(Text(self.h, self.v, font, char, + font._width_of(char))) + else: + scale = font._scale + for x, y, f, g, w in font._vf[char].text: + newf = DviFont(scale=_mul2012(scale, f._scale), + tfm=f._tfm, texname=f.texname, vf=f._vf) + self.text.append(Text(self.h + _mul2012(x, scale), + self.v + _mul2012(y, scale), + newf, g, newf._width_of(g))) + self.boxes.extend([Box(self.h + _mul2012(x, scale), + self.v + _mul2012(y, scale), + _mul2012(a, scale), _mul2012(b, scale)) + for x, y, a, b in font._vf[char].boxes]) + + @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4')) + def _put_rule(self, a, b): + self._put_rule_real(a, b) + + def _put_rule_real(self, a, b): + if a > 0 and b > 0: + self.boxes.append(Box(self.h, self.v, a, b)) + + @_dispatch(138) + def _nop(self, _): + pass + + @_dispatch(139, state=_dvistate.outer, args=('s4',)*11) + def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p): + self.state = _dvistate.inpage + self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0 + self.stack = [] + self.text = [] # list of Text objects + self.boxes = [] # list of Box objects + + @_dispatch(140, state=_dvistate.inpage) + def _eop(self, _): + self.state = _dvistate.outer + del self.h, self.v, self.w, self.x, self.y, self.z, self.stack + + @_dispatch(141, state=_dvistate.inpage) + def _push(self, _): + self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z)) + + @_dispatch(142, state=_dvistate.inpage) + def _pop(self, _): + self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop() + + @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',)) + def _right(self, b): + self.h += b + + @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',)) + def _right_w(self, new_w): + if new_w is not None: + self.w = new_w + self.h += self.w + + @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',)) + def _right_x(self, new_x): + if new_x is not None: + self.x = new_x + self.h += self.x + + @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',)) + def _down(self, a): + self.v += a + + @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',)) + def _down_y(self, new_y): + if new_y is not None: + self.y = new_y + self.v += self.y + + @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',)) + def _down_z(self, new_z): + if new_z is not None: + self.z = new_z + self.v += self.z + + @_dispatch(min=171, max=234, state=_dvistate.inpage) + def _fnt_num_immediate(self, k): + self.f = k + + @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',)) + def _fnt_num(self, new_f): + self.f = new_f + + @_dispatch(min=239, max=242, args=('ulen1',)) + def _xxx(self, datalen): + special = self.file.read(datalen) + _log.debug( + 'Dvi._xxx: encountered special: %s', + ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch + for ch in special])) + + @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1')) + def _fnt_def(self, k, c, s, d, a, l): + self._fnt_def_real(k, c, s, d, a, l) + + def _fnt_def_real(self, k, c, s, d, a, l): + n = self.file.read(a + l) + fontname = n[-l:].decode('ascii') + tfm = _tfmfile(fontname) + if c != 0 and tfm.checksum != 0 and c != tfm.checksum: + raise ValueError('tfm checksum mismatch: %s' % n) + try: + vf = _vffile(fontname) + except FileNotFoundError: + vf = None + self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf) + + @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1')) + def _pre(self, i, num, den, mag, k): + self.file.read(k) # comment in the dvi file + if i != 2: + raise ValueError("Unknown dvi format %d" % i) + if num != 25400000 or den != 7227 * 2**16: + raise ValueError("Nonstandard units in dvi file") + # meaning: TeX always uses those exact values, so it + # should be enough for us to support those + # (There are 72.27 pt to an inch so 7227 pt = + # 7227 * 2**16 sp to 100 in. The numerator is multiplied + # by 10^5 to get units of 10**-7 meters.) + if mag != 1000: + raise ValueError("Nonstandard magnification in dvi file") + # meaning: LaTeX seems to frown on setting \mag, so + # I think we can assume this is constant + self.state = _dvistate.outer + + @_dispatch(248, state=_dvistate.outer) + def _post(self, _): + self.state = _dvistate.post_post + # TODO: actually read the postamble and finale? + # currently post_post just triggers closing the file + + @_dispatch(249) + def _post_post(self, _): + raise NotImplementedError + + @_dispatch(min=250, max=255) + def _malformed(self, offset): + raise ValueError(f"unknown command: byte {250 + offset}") + + +class DviFont: + """ + Encapsulation of a font that a DVI file can refer to. + + This class holds a font's texname and size, supports comparison, + and knows the widths of glyphs in the same units as the AFM file. + There are also internal attributes (for use by dviread.py) that + are *not* used for comparison. + + The size is in Adobe points (converted from TeX points). + + Parameters + ---------- + scale : float + Factor by which the font is scaled from its natural size. + tfm : Tfm + TeX font metrics for this font + texname : bytes + Name of the font as used internally by TeX and friends, as an ASCII + bytestring. This is usually very different from any external font + names; `PsfontsMap` can be used to find the external name of the font. + vf : Vf + A TeX "virtual font" file, or None if this font is not virtual. + + Attributes + ---------- + texname : bytes + size : float + Size of the font in Adobe points, converted from the slightly + smaller TeX points. + widths : list + Widths of glyphs in glyph-space units, typically 1/1000ths of + the point size. + + """ + __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm') + + def __init__(self, scale, tfm, texname, vf): + _api.check_isinstance(bytes, texname=texname) + self._scale = scale + self._tfm = tfm + self.texname = texname + self._vf = vf + self.size = scale * (72.0 / (72.27 * 2**16)) + try: + nchars = max(tfm.width) + 1 + except ValueError: + nchars = 0 + self.widths = [(1000*tfm.width.get(char, 0)) >> 20 + for char in range(nchars)] + + def __eq__(self, other): + return (type(self) is type(other) + and self.texname == other.texname and self.size == other.size) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + return f"<{type(self).__name__}: {self.texname}>" + + def _width_of(self, char): + """Width of char in dvi units.""" + width = self._tfm.width.get(char, None) + if width is not None: + return _mul2012(width, self._scale) + _log.debug('No width for char %d in font %s.', char, self.texname) + return 0 + + def _height_depth_of(self, char): + """Height and depth of char in dvi units.""" + result = [] + for metric, name in ((self._tfm.height, "height"), + (self._tfm.depth, "depth")): + value = metric.get(char, None) + if value is None: + _log.debug('No %s for char %d in font %s', + name, char, self.texname) + result.append(0) + else: + result.append(_mul2012(value, self._scale)) + # cmsyXX (symbols font) glyph 0 ("minus") has a nonzero descent + # so that TeX aligns equations properly + # (https://tex.stackexchange.com/q/526103/) + # but we actually care about the rasterization depth to align + # the dvipng-generated images. + if re.match(br'^cmsy\d+$', self.texname) and char == 0: + result[-1] = 0 + return result + + +class Vf(Dvi): + r""" + A virtual font (\*.vf file) containing subroutines for dvi files. + + Parameters + ---------- + filename : str or path-like + + Notes + ----- + The virtual font format is a derivative of dvi: + http://mirrors.ctan.org/info/knuth/virtual-fonts + This class reuses some of the machinery of `Dvi` + but replaces the `_read` loop and dispatch mechanism. + + Examples + -------- + :: + + vf = Vf(filename) + glyph = vf[code] + glyph.text, glyph.boxes, glyph.width + """ + + def __init__(self, filename): + super().__init__(filename, 0) + try: + self._first_font = None + self._chars = {} + self._read() + finally: + self.close() + + def __getitem__(self, code): + return self._chars[code] + + def _read(self): + """ + Read one page from the file. Return True if successful, + False if there were no more pages. + """ + packet_char, packet_ends = None, None + packet_len, packet_width = None, None + while True: + byte = self.file.read(1)[0] + # If we are in a packet, execute the dvi instructions + if self.state is _dvistate.inpage: + byte_at = self.file.tell()-1 + if byte_at == packet_ends: + self._finalize_packet(packet_char, packet_width) + packet_len, packet_char, packet_width = None, None, None + # fall through to out-of-packet code + elif byte_at > packet_ends: + raise ValueError("Packet length mismatch in vf file") + else: + if byte in (139, 140) or byte >= 243: + raise ValueError( + "Inappropriate opcode %d in vf file" % byte) + Dvi._dtable[byte](self, byte) + continue + + # We are outside a packet + if byte < 242: # a short packet (length given by byte) + packet_len = byte + packet_char, packet_width = self._arg(1), self._arg(3) + packet_ends = self._init_packet(byte) + self.state = _dvistate.inpage + elif byte == 242: # a long packet + packet_len, packet_char, packet_width = \ + [self._arg(x) for x in (4, 4, 4)] + self._init_packet(packet_len) + elif 243 <= byte <= 246: + k = self._arg(byte - 242, byte == 246) + c, s, d, a, l = [self._arg(x) for x in (4, 4, 4, 1, 1)] + self._fnt_def_real(k, c, s, d, a, l) + if self._first_font is None: + self._first_font = k + elif byte == 247: # preamble + i, k = self._arg(1), self._arg(1) + x = self.file.read(k) + cs, ds = self._arg(4), self._arg(4) + self._pre(i, x, cs, ds) + elif byte == 248: # postamble (just some number of 248s) + break + else: + raise ValueError("Unknown vf opcode %d" % byte) + + def _init_packet(self, pl): + if self.state != _dvistate.outer: + raise ValueError("Misplaced packet in vf file") + self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0 + self.stack, self.text, self.boxes = [], [], [] + self.f = self._first_font + return self.file.tell() + pl + + def _finalize_packet(self, packet_char, packet_width): + self._chars[packet_char] = Page( + text=self.text, boxes=self.boxes, width=packet_width, + height=None, descent=None) + self.state = _dvistate.outer + + def _pre(self, i, x, cs, ds): + if self.state is not _dvistate.pre: + raise ValueError("pre command in middle of vf file") + if i != 202: + raise ValueError("Unknown vf format %d" % i) + if len(x): + _log.debug('vf file comment: %s', x) + self.state = _dvistate.outer + # cs = checksum, ds = design size + + +def _mul2012(num1, num2): + """Multiply two numbers in 20.12 fixed point format.""" + # Separated into a function because >> has surprising precedence + return (num1*num2) >> 20 + + +class Tfm: + """ + A TeX Font Metric file. + + This implementation covers only the bare minimum needed by the Dvi class. + + Parameters + ---------- + filename : str or path-like + + Attributes + ---------- + checksum : int + Used for verifying against the dvi file. + design_size : int + Design size of the font (unknown units) + width, height, depth : dict + Dimensions of each character, need to be scaled by the factor + specified in the dvi file. These are dicts because indexing may + not start from 0. + """ + __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth') + + def __init__(self, filename): + _log.debug('opening tfm file %s', filename) + with open(filename, 'rb') as file: + header1 = file.read(24) + lh, bc, ec, nw, nh, nd = struct.unpack('!6H', header1[2:14]) + _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d', + lh, bc, ec, nw, nh, nd) + header2 = file.read(4*lh) + self.checksum, self.design_size = struct.unpack('!2I', header2[:8]) + # there is also encoding information etc. + char_info = file.read(4*(ec-bc+1)) + widths = struct.unpack(f'!{nw}i', file.read(4*nw)) + heights = struct.unpack(f'!{nh}i', file.read(4*nh)) + depths = struct.unpack(f'!{nd}i', file.read(4*nd)) + self.width, self.height, self.depth = {}, {}, {} + for idx, char in enumerate(range(bc, ec+1)): + byte0 = char_info[4*idx] + byte1 = char_info[4*idx+1] + self.width[char] = widths[byte0] + self.height[char] = heights[byte1 >> 4] + self.depth[char] = depths[byte1 & 0xf] + + +PsFont = namedtuple('PsFont', 'texname psname effects encoding filename') + + +class PsfontsMap: + """ + A psfonts.map formatted file, mapping TeX fonts to PS fonts. + + Parameters + ---------- + filename : str or path-like + + Notes + ----- + For historical reasons, TeX knows many Type-1 fonts by different + names than the outside world. (For one thing, the names have to + fit in eight characters.) Also, TeX's native fonts are not Type-1 + but Metafont, which is nontrivial to convert to PostScript except + as a bitmap. While high-quality conversions to Type-1 format exist + and are shipped with modern TeX distributions, we need to know + which Type-1 fonts are the counterparts of which native fonts. For + these reasons a mapping is needed from internal font names to font + file names. + + A texmf tree typically includes mapping files called e.g. + :file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`. + The file :file:`psfonts.map` is used by :program:`dvips`, + :file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map` + by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding + the 35 PostScript fonts (i.e., have no filename for them, as in + the Times-Bold example above), while the pdf-related files perhaps + only avoid the "Base 14" pdf fonts. But the user may have + configured these files differently. + + Examples + -------- + >>> map = PsfontsMap(find_tex_file('pdftex.map')) + >>> entry = map[b'ptmbo8r'] + >>> entry.texname + b'ptmbo8r' + >>> entry.psname + b'Times-Bold' + >>> entry.encoding + '/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc' + >>> entry.effects + {'slant': 0.16700000000000001} + >>> entry.filename + """ + __slots__ = ('_filename', '_unparsed', '_parsed') + + # Create a filename -> PsfontsMap cache, so that calling + # `PsfontsMap(filename)` with the same filename a second time immediately + # returns the same object. + @lru_cache + def __new__(cls, filename): + self = object.__new__(cls) + self._filename = os.fsdecode(filename) + # Some TeX distributions have enormous pdftex.map files which would + # take hundreds of milliseconds to parse, but it is easy enough to just + # store the unparsed lines (keyed by the first word, which is the + # texname) and parse them on-demand. + with open(filename, 'rb') as file: + self._unparsed = {} + for line in file: + tfmname = line.split(b' ', 1)[0] + self._unparsed.setdefault(tfmname, []).append(line) + self._parsed = {} + return self + + def __getitem__(self, texname): + assert isinstance(texname, bytes) + if texname in self._unparsed: + for line in self._unparsed.pop(texname): + if self._parse_and_cache_line(line): + break + try: + return self._parsed[texname] + except KeyError: + raise LookupError( + f"An associated PostScript font (required by Matplotlib) " + f"could not be found for TeX font {texname.decode('ascii')!r} " + f"in {self._filename!r}; this problem can often be solved by " + f"installing a suitable PostScript font package in your TeX " + f"package manager") from None + + def _parse_and_cache_line(self, line): + """ + Parse a line in the font mapping file. + + The format is (partially) documented at + http://mirrors.ctan.org/systems/doc/pdftex/manual/pdftex-a.pdf + https://tug.org/texinfohtml/dvips.html#psfonts_002emap + Each line can have the following fields: + + - tfmname (first, only required field), + - psname (defaults to tfmname, must come immediately after tfmname if + present), + - fontflags (integer, must come immediately after psname if present, + ignored by us), + - special (SlantFont and ExtendFont, only field that is double-quoted), + - fontfile, encodingfile (optional, prefixed by <, <<, or <[; << always + precedes a font, <[ always precedes an encoding, < can precede either + but then an encoding file must have extension .enc; < and << also + request different font subsetting behaviors but we ignore that; < can + be separated from the filename by whitespace). + + special, fontfile, and encodingfile can appear in any order. + """ + # If the map file specifies multiple encodings for a font, we + # follow pdfTeX in choosing the last one specified. Such + # entries are probably mistakes but they have occurred. + # https://tex.stackexchange.com/q/10826/ + + if not line or line.startswith((b" ", b"%", b"*", b";", b"#")): + return + tfmname = basename = special = encodingfile = fontfile = None + is_subsetted = is_t1 = is_truetype = False + matches = re.finditer(br'"([^"]*)(?:"|$)|(\S+)', line) + for match in matches: + quoted, unquoted = match.groups() + if unquoted: + if unquoted.startswith(b"<<"): # font + fontfile = unquoted[2:] + elif unquoted.startswith(b"<["): # encoding + encodingfile = unquoted[2:] + elif unquoted.startswith(b"<"): # font or encoding + word = ( + # foo + unquoted[1:] + # < by itself => read the next word + or next(filter(None, next(matches).groups()))) + if word.endswith(b".enc"): + encodingfile = word + else: + fontfile = word + is_subsetted = True + elif tfmname is None: + tfmname = unquoted + elif basename is None: + basename = unquoted + elif quoted: + special = quoted + effects = {} + if special: + words = reversed(special.split()) + for word in words: + if word == b"SlantFont": + effects["slant"] = float(next(words)) + elif word == b"ExtendFont": + effects["extend"] = float(next(words)) + + # Verify some properties of the line that would cause it to be ignored + # otherwise. + if fontfile is not None: + if fontfile.endswith((b".ttf", b".ttc")): + is_truetype = True + elif not fontfile.endswith(b".otf"): + is_t1 = True + elif basename is not None: + is_t1 = True + if is_truetype and is_subsetted and encodingfile is None: + return + if not is_t1 and ("slant" in effects or "extend" in effects): + return + if abs(effects.get("slant", 0)) > 1: + return + if abs(effects.get("extend", 0)) > 2: + return + + if basename is None: + basename = tfmname + if encodingfile is not None: + encodingfile = find_tex_file(encodingfile) + if fontfile is not None: + fontfile = find_tex_file(fontfile) + self._parsed[tfmname] = PsFont( + texname=tfmname, psname=basename, effects=effects, + encoding=encodingfile, filename=fontfile) + return True + + +def _parse_enc(path): + r""" + Parse a \*.enc file referenced from a psfonts.map style file. + + The format supported by this function is a tiny subset of PostScript. + + Parameters + ---------- + path : `os.PathLike` + + Returns + ------- + list + The nth entry of the list is the PostScript glyph name of the nth + glyph. + """ + no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii")) + array = re.search(r"(?s)\[(.*)\]", no_comments).group(1) + lines = [line for line in array.split() if line] + if all(line.startswith("/") for line in lines): + return [line[1:] for line in lines] + else: + raise ValueError(f"Failed to parse {path} as Postscript encoding") + + +class _LuatexKpsewhich: + @lru_cache # A singleton. + def __new__(cls): + self = object.__new__(cls) + self._proc = self._new_proc() + return self + + def _new_proc(self): + return subprocess.Popen( + ["luatex", "--luaonly", + str(cbook._get_data_path("kpsewhich.lua"))], + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + def search(self, filename): + if self._proc.poll() is not None: # Dead, restart it. + self._proc = self._new_proc() + self._proc.stdin.write(os.fsencode(filename) + b"\n") + self._proc.stdin.flush() + out = self._proc.stdout.readline().rstrip() + return None if out == b"nil" else os.fsdecode(out) + + +@lru_cache +def find_tex_file(filename): + """ + Find a file in the texmf tree using kpathsea_. + + The kpathsea library, provided by most existing TeX distributions, both + on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived + luatex process if luatex is installed, or via kpsewhich otherwise. + + .. _kpathsea: https://www.tug.org/kpathsea/ + + Parameters + ---------- + filename : str or path-like + + Raises + ------ + FileNotFoundError + If the file is not found. + """ + + # we expect these to always be ascii encoded, but use utf-8 + # out of caution + if isinstance(filename, bytes): + filename = filename.decode('utf-8', errors='replace') + + try: + lk = _LuatexKpsewhich() + except FileNotFoundError: + lk = None # Fallback to directly calling kpsewhich, as below. + + if lk: + path = lk.search(filename) + else: + if sys.platform == 'win32': + # On Windows only, kpathsea can use utf-8 for cmd args and output. + # The `command_line_encoding` environment variable is set to force + # it to always use utf-8 encoding. See Matplotlib issue #11848. + kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'}, + 'encoding': 'utf-8'} + else: # On POSIX, run through the equivalent of os.fsdecode(). + kwargs = {'encoding': sys.getfilesystemencoding(), + 'errors': 'surrogateescape'} + + try: + path = (cbook._check_and_log_subprocess(['kpsewhich', filename], + _log, **kwargs) + .rstrip('\n')) + except (FileNotFoundError, RuntimeError): + path = None + + if path: + return path + else: + raise FileNotFoundError( + f"Matplotlib's TeX implementation searched for a file named " + f"{filename!r} in your texmf tree, but could not find it") + + +@lru_cache +def _fontfile(cls, suffix, texname): + return cls(find_tex_file(texname + suffix)) + + +_tfmfile = partial(_fontfile, Tfm, ".tfm") +_vffile = partial(_fontfile, Vf, ".vf") + + +if __name__ == '__main__': + from argparse import ArgumentParser + import itertools + + parser = ArgumentParser() + parser.add_argument("filename") + parser.add_argument("dpi", nargs="?", type=float, default=None) + args = parser.parse_args() + with Dvi(args.filename, args.dpi) as dvi: + fontmap = PsfontsMap(find_tex_file('pdftex.map')) + for page in dvi: + print(f"=== new page === " + f"(w: {page.width}, h: {page.height}, d: {page.descent})") + for font, group in itertools.groupby( + page.text, lambda text: text.font): + print(f"font: {font.texname.decode('latin-1')!r}\t" + f"scale: {font._scale / 2 ** 20}") + print("x", "y", "glyph", "chr", "w", "(glyphs)", sep="\t") + for text in group: + print(text.x, text.y, text.glyph, + chr(text.glyph) if chr(text.glyph).isprintable() + else ".", + text.width, sep="\t") + if page.boxes: + print("x", "y", "h", "w", "", "(boxes)", sep="\t") + for box in page.boxes: + print(box.x, box.y, box.height, box.width, sep="\t") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/dviread.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/dviread.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bf5cfcbe317aa3eb1f8d8c520d58278faaf76854 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/dviread.pyi @@ -0,0 +1,90 @@ +from pathlib import Path +import io +import os +from enum import Enum +from collections.abc import Generator + +from typing import NamedTuple + +class _dvistate(Enum): + pre: int + outer: int + inpage: int + post_post: int + finale: int + +class Page(NamedTuple): + text: list[Text] + boxes: list[Box] + height: int + width: int + descent: int + +class Box(NamedTuple): + x: int + y: int + height: int + width: int + +class Text(NamedTuple): + x: int + y: int + font: DviFont + glyph: int + width: int + @property + def font_path(self) -> Path: ... + @property + def font_size(self) -> float: ... + @property + def font_effects(self) -> dict[str, float]: ... + @property + def glyph_name_or_index(self) -> int | str: ... + +class Dvi: + file: io.BufferedReader + dpi: float | None + fonts: dict[int, DviFont] + state: _dvistate + def __init__(self, filename: str | os.PathLike, dpi: float | None) -> None: ... + # Replace return with Self when py3.9 is dropped + def __enter__(self) -> Dvi: ... + def __exit__(self, etype, evalue, etrace) -> None: ... + def __iter__(self) -> Generator[Page, None, None]: ... + def close(self) -> None: ... + +class DviFont: + texname: bytes + size: float + widths: list[int] + def __init__( + self, scale: float, tfm: Tfm, texname: bytes, vf: Vf | None + ) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class Vf(Dvi): + def __init__(self, filename: str | os.PathLike) -> None: ... + def __getitem__(self, code: int) -> Page: ... + +class Tfm: + checksum: int + design_size: int + width: dict[int, int] + height: dict[int, int] + depth: dict[int, int] + def __init__(self, filename: str | os.PathLike) -> None: ... + +class PsFont(NamedTuple): + texname: bytes + psname: bytes + effects: dict[str, float] + encoding: None | bytes + filename: str + +class PsfontsMap: + # Replace return with Self when py3.9 is dropped + def __new__(cls, filename: str | os.PathLike) -> PsfontsMap: ... + def __getitem__(self, texname: bytes) -> PsFont: ... + +def find_tex_file(filename: str | os.PathLike) -> str: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/gridspec.py b/llava_next/lib/python3.10/site-packages/matplotlib/gridspec.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b363d36efa133e2433e7dfdbfa141b56298e41 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/gridspec.py @@ -0,0 +1,788 @@ +r""" +:mod:`~matplotlib.gridspec` contains classes that help to layout multiple +`~.axes.Axes` in a grid-like pattern within a figure. + +The `GridSpec` specifies the overall grid structure. Individual cells within +the grid are referenced by `SubplotSpec`\s. + +Often, users need not access this module directly, and can use higher-level +methods like `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` and +`~.Figure.subfigures`. See the tutorial :ref:`arranging_axes` for a guide. +""" + +import copy +import logging +from numbers import Integral + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, _pylab_helpers, _tight_layout +from matplotlib.transforms import Bbox + +_log = logging.getLogger(__name__) + + +class GridSpecBase: + """ + A base class of GridSpec that specifies the geometry of the grid + that a subplot will be placed. + """ + + def __init__(self, nrows, ncols, height_ratios=None, width_ratios=None): + """ + Parameters + ---------- + nrows, ncols : int + The number of rows and columns of the grid. + 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. + """ + if not isinstance(nrows, Integral) or nrows <= 0: + raise ValueError( + f"Number of rows must be a positive integer, not {nrows!r}") + if not isinstance(ncols, Integral) or ncols <= 0: + raise ValueError( + f"Number of columns must be a positive integer, not {ncols!r}") + self._nrows, self._ncols = nrows, ncols + self.set_height_ratios(height_ratios) + self.set_width_ratios(width_ratios) + + def __repr__(self): + height_arg = (f', height_ratios={self._row_height_ratios!r}' + if len(set(self._row_height_ratios)) != 1 else '') + width_arg = (f', width_ratios={self._col_width_ratios!r}' + if len(set(self._col_width_ratios)) != 1 else '') + return '{clsname}({nrows}, {ncols}{optionals})'.format( + clsname=self.__class__.__name__, + nrows=self._nrows, + ncols=self._ncols, + optionals=height_arg + width_arg, + ) + + nrows = property(lambda self: self._nrows, + doc="The number of rows in the grid.") + ncols = property(lambda self: self._ncols, + doc="The number of columns in the grid.") + + def get_geometry(self): + """ + Return a tuple containing the number of rows and columns in the grid. + """ + return self._nrows, self._ncols + + def get_subplot_params(self, figure=None): + # Must be implemented in subclasses + pass + + def new_subplotspec(self, loc, rowspan=1, colspan=1): + """ + Create and return a `.SubplotSpec` instance. + + Parameters + ---------- + loc : (int, int) + The position of the subplot in the grid as + ``(row_index, column_index)``. + rowspan, colspan : int, default: 1 + The number of rows and columns the subplot should span in the grid. + """ + loc1, loc2 = loc + subplotspec = self[loc1:loc1+rowspan, loc2:loc2+colspan] + return subplotspec + + def set_width_ratios(self, width_ratios): + """ + Set the relative widths of the columns. + + *width_ratios* must be of length *ncols*. Each column gets a relative + width of ``width_ratios[i] / sum(width_ratios)``. + """ + if width_ratios is None: + width_ratios = [1] * self._ncols + elif len(width_ratios) != self._ncols: + raise ValueError('Expected the given number of width ratios to ' + 'match the number of columns of the grid') + self._col_width_ratios = width_ratios + + def get_width_ratios(self): + """ + Return the width ratios. + + This is *None* if no width ratios have been set explicitly. + """ + return self._col_width_ratios + + def set_height_ratios(self, height_ratios): + """ + Set the relative heights of the rows. + + *height_ratios* must be of length *nrows*. Each row gets a relative + height of ``height_ratios[i] / sum(height_ratios)``. + """ + if height_ratios is None: + height_ratios = [1] * self._nrows + elif len(height_ratios) != self._nrows: + raise ValueError('Expected the given number of height ratios to ' + 'match the number of rows of the grid') + self._row_height_ratios = height_ratios + + def get_height_ratios(self): + """ + Return the height ratios. + + This is *None* if no height ratios have been set explicitly. + """ + return self._row_height_ratios + + def get_grid_positions(self, fig): + """ + Return the positions of the grid cells in figure coordinates. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The figure the grid should be applied to. The subplot parameters + (margins and spacing between subplots) are taken from *fig*. + + Returns + ------- + bottoms, tops, lefts, rights : array + The bottom, top, left, right positions of the grid cells in + figure coordinates. + """ + nrows, ncols = self.get_geometry() + subplot_params = self.get_subplot_params(fig) + left = subplot_params.left + right = subplot_params.right + bottom = subplot_params.bottom + top = subplot_params.top + wspace = subplot_params.wspace + hspace = subplot_params.hspace + tot_width = right - left + tot_height = top - bottom + + # calculate accumulated heights of columns + cell_h = tot_height / (nrows + hspace*(nrows-1)) + sep_h = hspace * cell_h + norm = cell_h * nrows / sum(self._row_height_ratios) + cell_heights = [r * norm for r in self._row_height_ratios] + sep_heights = [0] + ([sep_h] * (nrows-1)) + cell_hs = np.cumsum(np.column_stack([sep_heights, cell_heights]).flat) + + # calculate accumulated widths of rows + cell_w = tot_width / (ncols + wspace*(ncols-1)) + sep_w = wspace * cell_w + norm = cell_w * ncols / sum(self._col_width_ratios) + cell_widths = [r * norm for r in self._col_width_ratios] + sep_widths = [0] + ([sep_w] * (ncols-1)) + cell_ws = np.cumsum(np.column_stack([sep_widths, cell_widths]).flat) + + fig_tops, fig_bottoms = (top - cell_hs).reshape((-1, 2)).T + fig_lefts, fig_rights = (left + cell_ws).reshape((-1, 2)).T + return fig_bottoms, fig_tops, fig_lefts, fig_rights + + @staticmethod + def _check_gridspec_exists(figure, nrows, ncols): + """ + Check if the figure already has a gridspec with these dimensions, + or create a new one + """ + for ax in figure.get_axes(): + gs = ax.get_gridspec() + if gs is not None: + if hasattr(gs, 'get_topmost_subplotspec'): + # This is needed for colorbar gridspec layouts. + # This is probably OK because this whole logic tree + # is for when the user is doing simple things with the + # add_subplot command. For complicated layouts + # like subgridspecs the proper gridspec is passed in... + gs = gs.get_topmost_subplotspec().get_gridspec() + if gs.get_geometry() == (nrows, ncols): + return gs + # else gridspec not found: + return GridSpec(nrows, ncols, figure=figure) + + def __getitem__(self, key): + """Create and return a `.SubplotSpec` instance.""" + nrows, ncols = self.get_geometry() + + def _normalize(key, size, axis): # Includes last index. + orig_key = key + if isinstance(key, slice): + start, stop, _ = key.indices(size) + if stop > start: + return start, stop - 1 + raise IndexError("GridSpec slice would result in no space " + "allocated for subplot") + else: + if key < 0: + key = key + size + if 0 <= key < size: + return key, key + elif axis is not None: + raise IndexError(f"index {orig_key} is out of bounds for " + f"axis {axis} with size {size}") + else: # flat index + raise IndexError(f"index {orig_key} is out of bounds for " + f"GridSpec with size {size}") + + if isinstance(key, tuple): + try: + k1, k2 = key + except ValueError as err: + raise ValueError("Unrecognized subplot spec") from err + num1, num2 = np.ravel_multi_index( + [_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)], + (nrows, ncols)) + else: # Single key + num1, num2 = _normalize(key, nrows * ncols, None) + + return SubplotSpec(self, num1, num2) + + def subplots(self, *, sharex=False, sharey=False, squeeze=True, + subplot_kw=None): + """ + Add all subplots specified by this `GridSpec` to its parent figure. + + See `.Figure.subplots` for detailed documentation. + """ + + figure = self.figure + + if figure is None: + raise ValueError("GridSpec.subplots() only works for GridSpecs " + "created with a parent figure") + + if not isinstance(sharex, str): + sharex = "all" if sharex else "none" + if not isinstance(sharey, str): + sharey = "all" if sharey else "none" + + _api.check_in_list(["all", "row", "col", "none", False, True], + sharex=sharex, sharey=sharey) + if subplot_kw is None: + subplot_kw = {} + # don't mutate kwargs passed by user... + subplot_kw = subplot_kw.copy() + + # Create array to hold all Axes. + axarr = np.empty((self._nrows, self._ncols), dtype=object) + for row in range(self._nrows): + for col in range(self._ncols): + shared_with = {"none": None, "all": axarr[0, 0], + "row": axarr[row, 0], "col": axarr[0, col]} + subplot_kw["sharex"] = shared_with[sharex] + subplot_kw["sharey"] = shared_with[sharey] + axarr[row, col] = figure.add_subplot( + self[row, col], **subplot_kw) + + # turn off redundant tick labeling + if sharex in ["col", "all"]: + for ax in axarr.flat: + ax._label_outer_xaxis(skip_non_rectangular_axes=True) + if sharey in ["row", "all"]: + for ax in axarr.flat: + ax._label_outer_yaxis(skip_non_rectangular_axes=True) + + if squeeze: + # Discarding unneeded dimensions that equal 1. If we only have one + # subplot, just return it instead of a 1-element array. + return axarr.item() if axarr.size == 1 else axarr.squeeze() + else: + # Returned axis array will be always 2-d, even if nrows=ncols=1. + return axarr + + +class GridSpec(GridSpecBase): + """ + A grid layout to place subplots within a figure. + + The location of the grid cells is determined in a similar way to + `.SubplotParams` using *left*, *right*, *top*, *bottom*, *wspace* + and *hspace*. + + Indexing a GridSpec instance returns a `.SubplotSpec`. + """ + def __init__(self, nrows, ncols, figure=None, + left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None, + width_ratios=None, height_ratios=None): + """ + Parameters + ---------- + nrows, ncols : int + The number of rows and columns of the grid. + + figure : `.Figure`, optional + Only used for constrained layout to create a proper layoutgrid. + + left, right, top, bottom : float, optional + Extent of the subplots as a fraction of figure width or height. + Left cannot be larger than right, and bottom cannot be larger than + top. If not given, the values will be inferred from a figure or + rcParams at draw time. See also `GridSpec.get_subplot_params`. + + wspace : float, optional + The amount of width reserved for space between subplots, + expressed as a fraction of the average axis width. + If not given, the values will be inferred from a figure or + rcParams when necessary. See also `GridSpec.get_subplot_params`. + + hspace : float, optional + The amount of height reserved for space between subplots, + expressed as a fraction of the average axis height. + If not given, the values will be inferred from a figure or + rcParams when necessary. See also `GridSpec.get_subplot_params`. + + 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. + + """ + self.left = left + self.bottom = bottom + self.right = right + self.top = top + self.wspace = wspace + self.hspace = hspace + self.figure = figure + + super().__init__(nrows, ncols, + width_ratios=width_ratios, + height_ratios=height_ratios) + + _AllowedKeys = ["left", "bottom", "right", "top", "wspace", "hspace"] + + def update(self, **kwargs): + """ + Update the subplot parameters of the grid. + + Parameters that are not explicitly given are not changed. Setting a + parameter to *None* resets it to :rc:`figure.subplot.*`. + + Parameters + ---------- + left, right, top, bottom : float or None, optional + Extent of the subplots as a fraction of figure width or height. + wspace, hspace : float, optional + Spacing between the subplots as a fraction of the average subplot + width / height. + """ + for k, v in kwargs.items(): + if k in self._AllowedKeys: + setattr(self, k, v) + else: + raise AttributeError(f"{k} is an unknown keyword") + for figmanager in _pylab_helpers.Gcf.figs.values(): + for ax in figmanager.canvas.figure.axes: + if ax.get_subplotspec() is not None: + ss = ax.get_subplotspec().get_topmost_subplotspec() + if ss.get_gridspec() == self: + ax._set_position( + ax.get_subplotspec().get_position(ax.figure)) + + def get_subplot_params(self, figure=None): + """ + Return the `.SubplotParams` for the GridSpec. + + In order of precedence the values are taken from + + - non-*None* attributes of the GridSpec + - the provided *figure* + - :rc:`figure.subplot.*` + + Note that the ``figure`` attribute of the GridSpec is always ignored. + """ + if figure is None: + kw = {k: mpl.rcParams["figure.subplot."+k] + for k in self._AllowedKeys} + subplotpars = SubplotParams(**kw) + else: + subplotpars = copy.copy(figure.subplotpars) + + subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys}) + + return subplotpars + + def locally_modified_subplot_params(self): + """ + Return a list of the names of the subplot parameters explicitly set + in the GridSpec. + + This is a subset of the attributes of `.SubplotParams`. + """ + return [k for k in self._AllowedKeys if getattr(self, k)] + + def tight_layout(self, figure, renderer=None, + pad=1.08, h_pad=None, w_pad=None, rect=None): + """ + Adjust subplot parameters to give specified padding. + + Parameters + ---------- + figure : `.Figure` + The figure. + renderer : `.RendererBase` subclass, optional + The renderer to be used. + pad : float + Padding between the figure edge and the edges of subplots, as a + fraction of the font-size. + h_pad, w_pad : float, optional + Padding (height/width) between edges of adjacent subplots. + Defaults to *pad*. + rect : tuple (left, bottom, right, top), default: None + (left, bottom, right, top) rectangle in normalized figure + coordinates that the whole subplots area (including labels) will + fit into. Default (None) is the whole figure. + """ + if renderer is None: + renderer = figure._get_renderer() + kwargs = _tight_layout.get_tight_layout_figure( + figure, figure.axes, + _tight_layout.get_subplotspec_list(figure.axes, grid_spec=self), + renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) + if kwargs: + self.update(**kwargs) + + +class GridSpecFromSubplotSpec(GridSpecBase): + """ + GridSpec whose subplot layout parameters are inherited from the + location specified by a given SubplotSpec. + """ + def __init__(self, nrows, ncols, + subplot_spec, + wspace=None, hspace=None, + height_ratios=None, width_ratios=None): + """ + Parameters + ---------- + nrows, ncols : int + Number of rows and number of columns of the grid. + subplot_spec : SubplotSpec + Spec from which the layout parameters are inherited. + wspace, hspace : float, optional + See `GridSpec` for more details. If not specified default values + (from the figure or rcParams) are used. + height_ratios : array-like of length *nrows*, optional + See `GridSpecBase` for details. + width_ratios : array-like of length *ncols*, optional + See `GridSpecBase` for details. + """ + self._wspace = wspace + self._hspace = hspace + if isinstance(subplot_spec, SubplotSpec): + self._subplot_spec = subplot_spec + else: + raise TypeError( + "subplot_spec must be type SubplotSpec, " + "usually from GridSpec, or axes.get_subplotspec.") + self.figure = self._subplot_spec.get_gridspec().figure + super().__init__(nrows, ncols, + width_ratios=width_ratios, + height_ratios=height_ratios) + + def get_subplot_params(self, figure=None): + """Return a dictionary of subplot layout parameters.""" + hspace = (self._hspace if self._hspace is not None + else figure.subplotpars.hspace if figure is not None + else mpl.rcParams["figure.subplot.hspace"]) + wspace = (self._wspace if self._wspace is not None + else figure.subplotpars.wspace if figure is not None + else mpl.rcParams["figure.subplot.wspace"]) + + figbox = self._subplot_spec.get_position(figure) + left, bottom, right, top = figbox.extents + + return SubplotParams(left=left, right=right, + bottom=bottom, top=top, + wspace=wspace, hspace=hspace) + + def get_topmost_subplotspec(self): + """ + Return the topmost `.SubplotSpec` instance associated with the subplot. + """ + return self._subplot_spec.get_topmost_subplotspec() + + +class SubplotSpec: + """ + The location of a subplot in a `GridSpec`. + + .. note:: + + Likely, you will never instantiate a `SubplotSpec` yourself. Instead, + you will typically obtain one from a `GridSpec` using item-access. + + Parameters + ---------- + gridspec : `~matplotlib.gridspec.GridSpec` + The GridSpec, which the subplot is referencing. + num1, num2 : int + The subplot will occupy the *num1*-th cell of the given + *gridspec*. If *num2* is provided, the subplot will span between + *num1*-th cell and *num2*-th cell **inclusive**. + + The index starts from 0. + """ + def __init__(self, gridspec, num1, num2=None): + self._gridspec = gridspec + self.num1 = num1 + self.num2 = num2 + + def __repr__(self): + return (f"{self.get_gridspec()}[" + f"{self.rowspan.start}:{self.rowspan.stop}, " + f"{self.colspan.start}:{self.colspan.stop}]") + + @staticmethod + def _from_subplot_args(figure, args): + """ + Construct a `.SubplotSpec` from a parent `.Figure` and either + + - a `.SubplotSpec` -- returned as is; + - one or three numbers -- a MATLAB-style subplot specifier. + """ + if len(args) == 1: + arg, = args + if isinstance(arg, SubplotSpec): + return arg + elif not isinstance(arg, Integral): + raise ValueError( + f"Single argument to subplot must be a three-digit " + f"integer, not {arg!r}") + try: + rows, cols, num = map(int, str(arg)) + except ValueError: + raise ValueError( + f"Single argument to subplot must be a three-digit " + f"integer, not {arg!r}") from None + elif len(args) == 3: + rows, cols, num = args + else: + raise _api.nargs_error("subplot", takes="1 or 3", given=len(args)) + + gs = GridSpec._check_gridspec_exists(figure, rows, cols) + if gs is None: + gs = GridSpec(rows, cols, figure=figure) + if isinstance(num, tuple) and len(num) == 2: + if not all(isinstance(n, Integral) for n in num): + raise ValueError( + f"Subplot specifier tuple must contain integers, not {num}" + ) + i, j = num + else: + if not isinstance(num, Integral) or num < 1 or num > rows*cols: + raise ValueError( + f"num must be an integer with 1 <= num <= {rows*cols}, " + f"not {num!r}" + ) + i = j = num + return gs[i-1:j] + + # num2 is a property only to handle the case where it is None and someone + # mutates num1. + + @property + def num2(self): + return self.num1 if self._num2 is None else self._num2 + + @num2.setter + def num2(self, value): + self._num2 = value + + def get_gridspec(self): + return self._gridspec + + def get_geometry(self): + """ + Return the subplot geometry as tuple ``(n_rows, n_cols, start, stop)``. + + The indices *start* and *stop* define the range of the subplot within + the `GridSpec`. *stop* is inclusive (i.e. for a single cell + ``start == stop``). + """ + rows, cols = self.get_gridspec().get_geometry() + return rows, cols, self.num1, self.num2 + + @property + def rowspan(self): + """The rows spanned by this subplot, as a `range` object.""" + ncols = self.get_gridspec().ncols + return range(self.num1 // ncols, self.num2 // ncols + 1) + + @property + def colspan(self): + """The columns spanned by this subplot, as a `range` object.""" + ncols = self.get_gridspec().ncols + # We explicitly support num2 referring to a column on num1's *left*, so + # we must sort the column indices here so that the range makes sense. + c1, c2 = sorted([self.num1 % ncols, self.num2 % ncols]) + return range(c1, c2 + 1) + + def is_first_row(self): + return self.rowspan.start == 0 + + def is_last_row(self): + return self.rowspan.stop == self.get_gridspec().nrows + + def is_first_col(self): + return self.colspan.start == 0 + + def is_last_col(self): + return self.colspan.stop == self.get_gridspec().ncols + + def get_position(self, figure): + """ + Update the subplot position from ``figure.subplotpars``. + """ + gridspec = self.get_gridspec() + nrows, ncols = gridspec.get_geometry() + rows, cols = np.unravel_index([self.num1, self.num2], (nrows, ncols)) + fig_bottoms, fig_tops, fig_lefts, fig_rights = \ + gridspec.get_grid_positions(figure) + + fig_bottom = fig_bottoms[rows].min() + fig_top = fig_tops[rows].max() + fig_left = fig_lefts[cols].min() + fig_right = fig_rights[cols].max() + return Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top) + + def get_topmost_subplotspec(self): + """ + Return the topmost `SubplotSpec` instance associated with the subplot. + """ + gridspec = self.get_gridspec() + if hasattr(gridspec, "get_topmost_subplotspec"): + return gridspec.get_topmost_subplotspec() + else: + return self + + def __eq__(self, other): + """ + Two SubplotSpecs are considered equal if they refer to the same + position(s) in the same `GridSpec`. + """ + # other may not even have the attributes we are checking. + return ((self._gridspec, self.num1, self.num2) + == (getattr(other, "_gridspec", object()), + getattr(other, "num1", object()), + getattr(other, "num2", object()))) + + def __hash__(self): + return hash((self._gridspec, self.num1, self.num2)) + + def subgridspec(self, nrows, ncols, **kwargs): + """ + Create a GridSpec within this subplot. + + The created `.GridSpecFromSubplotSpec` will have this `SubplotSpec` as + a parent. + + Parameters + ---------- + nrows : int + Number of rows in grid. + + ncols : int + Number of columns in grid. + + Returns + ------- + `.GridSpecFromSubplotSpec` + + Other Parameters + ---------------- + **kwargs + All other parameters are passed to `.GridSpecFromSubplotSpec`. + + See Also + -------- + matplotlib.pyplot.subplots + + Examples + -------- + Adding three subplots in the space occupied by a single subplot:: + + fig = plt.figure() + gs0 = fig.add_gridspec(3, 1) + ax1 = fig.add_subplot(gs0[0]) + ax2 = fig.add_subplot(gs0[1]) + gssub = gs0[2].subgridspec(1, 3) + for i in range(3): + fig.add_subplot(gssub[0, i]) + """ + return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs) + + +class SubplotParams: + """ + Parameters defining the positioning of a subplots grid in a figure. + """ + + def __init__(self, left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None): + """ + Defaults are given by :rc:`figure.subplot.[name]`. + + Parameters + ---------- + left : float + The position of the left edge of the subplots, + as a fraction of the figure width. + right : float + The position of the right edge of the subplots, + as a fraction of the figure width. + bottom : float + The position of the bottom edge of the subplots, + as a fraction of the figure height. + top : float + The position of the top edge of the subplots, + as a fraction of the figure height. + wspace : float + The width of the padding between subplots, + as a fraction of the average Axes width. + hspace : float + The height of the padding between subplots, + as a fraction of the average Axes height. + """ + for key in ["left", "bottom", "right", "top", "wspace", "hspace"]: + setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"]) + self.update(left, bottom, right, top, wspace, hspace) + + def update(self, left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None): + """ + Update the dimensions of the passed parameters. *None* means unchanged. + """ + if ((left if left is not None else self.left) + >= (right if right is not None else self.right)): + raise ValueError('left cannot be >= right') + if ((bottom if bottom is not None else self.bottom) + >= (top if top is not None else self.top)): + raise ValueError('bottom cannot be >= top') + if left is not None: + self.left = left + if right is not None: + self.right = right + if bottom is not None: + self.bottom = bottom + if top is not None: + self.top = top + if wspace is not None: + self.wspace = wspace + if hspace is not None: + self.hspace = hspace diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/legend.py b/llava_next/lib/python3.10/site-packages/matplotlib/legend.py new file mode 100644 index 0000000000000000000000000000000000000000..9033fc23c1a1d79fea71724bc7ca4c9d1290e2ba --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/legend.py @@ -0,0 +1,1385 @@ +""" +The legend module defines the Legend class, which is responsible for +drawing legends associated with Axes and/or figures. + +.. important:: + + It is unlikely that you would ever create a Legend instance manually. + Most users would normally create a legend via the `~.Axes.legend` + function. For more details on legends there is also a :ref:`legend guide + `. + +The `Legend` class is a container of legend handles and legend texts. + +The legend handler map specifies how to create legend handles from artists +(lines, patches, etc.) in the Axes or figures. Default legend handlers are +defined in the :mod:`~matplotlib.legend_handler` module. While not all artist +types are covered by the default legend handlers, custom legend handlers can be +defined to support arbitrary objects. + +See the :ref`` for more +information. +""" + +import itertools +import logging +import numbers +import time + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, _docstring, cbook, colors, offsetbox +from matplotlib.artist import Artist, allow_rasterization +from matplotlib.cbook import silent_list +from matplotlib.font_manager import FontProperties +from matplotlib.lines import Line2D +from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch, + StepPatch) +from matplotlib.collections import ( + Collection, CircleCollection, LineCollection, PathCollection, + PolyCollection, RegularPolyCollection) +from matplotlib.text import Text +from matplotlib.transforms import Bbox, BboxBase, TransformedBbox +from matplotlib.transforms import BboxTransformTo, BboxTransformFrom +from matplotlib.offsetbox import ( + AnchoredOffsetbox, DraggableOffsetBox, + HPacker, VPacker, + DrawingArea, TextArea, +) +from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer +from . import legend_handler + + +class DraggableLegend(DraggableOffsetBox): + def __init__(self, legend, use_blit=False, update="loc"): + """ + Wrapper around a `.Legend` to support mouse dragging. + + Parameters + ---------- + legend : `.Legend` + The `.Legend` instance to wrap. + use_blit : bool, optional + Use blitting for faster image composition. For details see + :ref:`func-animation`. + update : {'loc', 'bbox'}, optional + If "loc", update the *loc* parameter of the legend upon finalizing. + If "bbox", update the *bbox_to_anchor* parameter. + """ + self.legend = legend + + _api.check_in_list(["loc", "bbox"], update=update) + self._update = update + + super().__init__(legend, legend._legend_box, use_blit=use_blit) + + def finalize_offset(self): + if self._update == "loc": + self._update_loc(self.get_loc_in_canvas()) + elif self._update == "bbox": + self._update_bbox_to_anchor(self.get_loc_in_canvas()) + + def _update_loc(self, loc_in_canvas): + bbox = self.legend.get_bbox_to_anchor() + # if bbox has zero width or height, the transformation is + # ill-defined. Fall back to the default bbox_to_anchor. + if bbox.width == 0 or bbox.height == 0: + self.legend.set_bbox_to_anchor(None) + bbox = self.legend.get_bbox_to_anchor() + _bbox_transform = BboxTransformFrom(bbox) + self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas)) + + def _update_bbox_to_anchor(self, loc_in_canvas): + loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas) + self.legend.set_bbox_to_anchor(loc_in_bbox) + + +_legend_kw_doc_base = """ +bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats + Box that is used to position the legend in conjunction with *loc*. + Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or + `figure.bbox` (if `.Figure.legend`). This argument allows arbitrary + placement of the legend. + + Bbox coordinates are interpreted in the coordinate system given by + *bbox_transform*, with the default transform + Axes or Figure coordinates, depending on which ``legend`` is called. + + If a 4-tuple or `.BboxBase` is given, then it specifies the bbox + ``(x, y, width, height)`` that the legend is placed in. + To put the legend in the best location in the bottom right + quadrant of the Axes (or figure):: + + loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5) + + A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at + x, y. For example, to put the legend's upper right-hand corner in the + center of the Axes (or figure) the following keywords can be used:: + + loc='upper right', bbox_to_anchor=(0.5, 0.5) + +ncols : int, default: 1 + The number of columns that the legend has. + + For backward compatibility, the spelling *ncol* is also supported + but it is discouraged. If both are given, *ncols* takes precedence. + +prop : None or `~matplotlib.font_manager.FontProperties` or dict + The font properties of the legend. If None (default), the current + :data:`matplotlib.rcParams` will be used. + +fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \ +'x-large', 'xx-large'} + The font size of the legend. If the value is numeric the size will be the + absolute font size in points. String values are relative to the current + default font size. This argument is only used if *prop* is not specified. + +labelcolor : str or list, default: :rc:`legend.labelcolor` + The color of the text in the legend. Either a valid color string + (for example, 'red'), or a list of color strings. The labelcolor can + also be made to match the color of the line or marker using 'linecolor', + 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). + + Labelcolor can be set globally using :rc:`legend.labelcolor`. If None, + use :rc:`text.color`. + +numpoints : int, default: :rc:`legend.numpoints` + The number of marker points in the legend when creating a legend + entry for a `.Line2D` (line). + +scatterpoints : int, default: :rc:`legend.scatterpoints` + The number of marker points in the legend when creating + a legend entry for a `.PathCollection` (scatter plot). + +scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]`` + The vertical offset (relative to the font size) for the markers + created for a scatter plot legend entry. 0.0 is at the base the + legend text, and 1.0 is at the top. To draw all markers at the + same height, set to ``[0.5]``. + +markerscale : float, default: :rc:`legend.markerscale` + The relative size of legend markers compared to the originally drawn ones. + +markerfirst : bool, default: True + If *True*, legend marker is placed to the left of the legend label. + If *False*, legend marker is placed to the right of the legend label. + +reverse : bool, default: False + If *True*, the legend labels are displayed in reverse order from the input. + If *False*, the legend labels are displayed in the same order as the input. + + .. versionadded:: 3.7 + +frameon : bool, default: :rc:`legend.frameon` + Whether the legend should be drawn on a patch (frame). + +fancybox : bool, default: :rc:`legend.fancybox` + Whether round edges should be enabled around the `.FancyBboxPatch` which + makes up the legend's background. + +shadow : None, bool or dict, default: :rc:`legend.shadow` + Whether to draw a shadow behind the legend. + The shadow can be configured using `.Patch` keywords. + Customization via :rc:`legend.shadow` is currently not supported. + +framealpha : float, default: :rc:`legend.framealpha` + The alpha transparency of the legend's background. + If *shadow* is activated and *framealpha* is ``None``, the default value is + ignored. + +facecolor : "inherit" or color, default: :rc:`legend.facecolor` + The legend's background color. + If ``"inherit"``, use :rc:`axes.facecolor`. + +edgecolor : "inherit" or color, default: :rc:`legend.edgecolor` + The legend's background patch edge color. + If ``"inherit"``, use :rc:`axes.edgecolor`. + +mode : {"expand", None} + If *mode* is set to ``"expand"`` the legend will be horizontally + expanded to fill the Axes area (or *bbox_to_anchor* if defines + the legend's size). + +bbox_transform : None or `~matplotlib.transforms.Transform` + The transform for the bounding box (*bbox_to_anchor*). For a value + of ``None`` (default) the Axes' + :data:`~matplotlib.axes.Axes.transAxes` transform will be used. + +title : str or None + The legend's title. Default is no title (``None``). + +title_fontproperties : None or `~matplotlib.font_manager.FontProperties` or dict + The font properties of the legend's title. If None (default), the + *title_fontsize* argument will be used if present; if *title_fontsize* is + also None, the current :rc:`legend.title_fontsize` will be used. + +title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \ +'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize` + The font size of the legend's title. + Note: This cannot be combined with *title_fontproperties*. If you want + to set the fontsize alongside other font properties, use the *size* + parameter in *title_fontproperties*. + +alignment : {'center', 'left', 'right'}, default: 'center' + The alignment of the legend title and the box of entries. The entries + are aligned as a single block, so that markers always lined up. + +borderpad : float, default: :rc:`legend.borderpad` + The fractional whitespace inside the legend border, in font-size units. + +labelspacing : float, default: :rc:`legend.labelspacing` + The vertical space between the legend entries, in font-size units. + +handlelength : float, default: :rc:`legend.handlelength` + The length of the legend handles, in font-size units. + +handleheight : float, default: :rc:`legend.handleheight` + The height of the legend handles, in font-size units. + +handletextpad : float, default: :rc:`legend.handletextpad` + The pad between the legend handle and text, in font-size units. + +borderaxespad : float, default: :rc:`legend.borderaxespad` + The pad between the Axes and legend border, in font-size units. + +columnspacing : float, default: :rc:`legend.columnspacing` + The spacing between columns, in font-size units. + +handler_map : dict or None + The custom dictionary mapping instances or types to a legend + handler. This *handler_map* updates the default handler map + found at `matplotlib.legend.Legend.get_legend_handler_map`. + +draggable : bool, default: False + Whether the legend can be dragged with the mouse. +""" + +_loc_doc_base = """ +loc : str or pair of floats, default: {default} + The location of the legend. + + The strings ``'upper left'``, ``'upper right'``, ``'lower left'``, + ``'lower right'`` place the legend at the corresponding corner of the + {parent}. + + The strings ``'upper center'``, ``'lower center'``, ``'center left'``, + ``'center right'`` place the legend at the center of the corresponding edge + of the {parent}. + + The string ``'center'`` places the legend at the center of the {parent}. +{best} + The location can also be a 2-tuple giving the coordinates of the lower-left + corner of the legend in {parent} coordinates (in which case *bbox_to_anchor* + will be ignored). + + For back-compatibility, ``'center right'`` (but no other location) can also + be spelled ``'right'``, and each "string" location can also be given as a + numeric value: + + ================== ============= + Location String Location Code + ================== ============= + 'best' (Axes only) 0 + 'upper right' 1 + 'upper left' 2 + 'lower left' 3 + 'lower right' 4 + 'right' 5 + 'center left' 6 + 'center right' 7 + 'lower center' 8 + 'upper center' 9 + 'center' 10 + ================== ============= + {outside}""" + +_loc_doc_best = """ + The string ``'best'`` places the legend at the location, among the nine + locations defined so far, with the minimum overlap with other drawn + artists. This option can be quite slow for plots with large amounts of + data; your plotting speed may benefit from providing a specific location. +""" + +_legend_kw_axes_st = ( + _loc_doc_base.format(parent='axes', default=':rc:`legend.loc`', + best=_loc_doc_best, outside='') + + _legend_kw_doc_base) +_docstring.interpd.update(_legend_kw_axes=_legend_kw_axes_st) + +_outside_doc = """ + If a figure is using the constrained layout manager, the string codes + of the *loc* keyword argument can get better layout behaviour using the + prefix 'outside'. There is ambiguity at the corners, so 'outside + upper right' will make space for the legend above the rest of the + axes in the layout, and 'outside right upper' will make space on the + right side of the layout. In addition to the values of *loc* + listed above, we have 'outside right upper', 'outside right lower', + 'outside left upper', and 'outside left lower'. See + :ref:`legend_guide` for more details. +""" + +_legend_kw_figure_st = ( + _loc_doc_base.format(parent='figure', default="'upper right'", + best='', outside=_outside_doc) + + _legend_kw_doc_base) +_docstring.interpd.update(_legend_kw_figure=_legend_kw_figure_st) + +_legend_kw_both_st = ( + _loc_doc_base.format(parent='axes/figure', + default=":rc:`legend.loc` for Axes, 'upper right' for Figure", + best=_loc_doc_best, outside=_outside_doc) + + _legend_kw_doc_base) +_docstring.interpd.update(_legend_kw_doc=_legend_kw_both_st) + +_legend_kw_set_loc_st = ( + _loc_doc_base.format(parent='axes/figure', + default=":rc:`legend.loc` for Axes, 'upper right' for Figure", + best=_loc_doc_best, outside=_outside_doc)) +_docstring.interpd.update(_legend_kw_set_loc_doc=_legend_kw_set_loc_st) + + +class Legend(Artist): + """ + Place a legend on the figure/axes. + """ + + # 'best' is only implemented for Axes legends + codes = {'best': 0, **AnchoredOffsetbox.codes} + zorder = 5 + + def __str__(self): + return "Legend" + + @_docstring.dedent_interpd + def __init__( + self, parent, handles, labels, + *, + loc=None, + numpoints=None, # number of points in the legend line + markerscale=None, # relative size of legend markers vs. original + markerfirst=True, # left/right ordering of legend marker and label + reverse=False, # reverse ordering of legend marker and label + scatterpoints=None, # number of scatter points + scatteryoffsets=None, + prop=None, # properties for the legend texts + fontsize=None, # keyword to set font size directly + labelcolor=None, # keyword to set the text color + + # spacing & pad defined as a fraction of the font-size + borderpad=None, # whitespace inside the legend border + labelspacing=None, # vertical space between the legend entries + handlelength=None, # length of the legend handles + handleheight=None, # height of the legend handles + handletextpad=None, # pad between the legend handle and text + borderaxespad=None, # pad between the Axes and legend border + columnspacing=None, # spacing between columns + + ncols=1, # number of columns + mode=None, # horizontal distribution of columns: None or "expand" + + fancybox=None, # True: fancy box, False: rounded box, None: rcParam + shadow=None, + title=None, # legend title + title_fontsize=None, # legend title font size + framealpha=None, # set frame alpha + edgecolor=None, # frame patch edgecolor + facecolor=None, # frame patch facecolor + + bbox_to_anchor=None, # bbox to which the legend will be anchored + bbox_transform=None, # transform for the bbox + frameon=None, # draw frame + handler_map=None, + title_fontproperties=None, # properties for the legend title + alignment="center", # control the alignment within the legend box + ncol=1, # synonym for ncols (backward compatibility) + draggable=False # whether the legend can be dragged with the mouse + ): + """ + Parameters + ---------- + parent : `~matplotlib.axes.Axes` or `.Figure` + The artist that contains the legend. + + handles : list of (`.Artist` or tuple of `.Artist`) + A list of Artists (lines, patches) to be added to the legend. + + labels : list of str + A list of labels to show next to the artists. The length of handles + and labels should be the same. If they are not, they are truncated + to the length of the shorter list. + + Other Parameters + ---------------- + %(_legend_kw_doc)s + + Attributes + ---------- + legend_handles + List of `.Artist` objects added as legend entries. + + .. versionadded:: 3.7 + """ + # local import only to avoid circularity + from matplotlib.axes import Axes + from matplotlib.figure import FigureBase + + super().__init__() + + if prop is None: + self.prop = FontProperties(size=mpl._val_or_rc(fontsize, "legend.fontsize")) + else: + self.prop = FontProperties._from_any(prop) + if isinstance(prop, dict) and "size" not in prop: + self.prop.set_size(mpl.rcParams["legend.fontsize"]) + + self._fontsize = self.prop.get_size_in_points() + + self.texts = [] + self.legend_handles = [] + self._legend_title_box = None + + #: A dictionary with the extra handler mappings for this Legend + #: instance. + self._custom_handler_map = handler_map + + self.numpoints = mpl._val_or_rc(numpoints, 'legend.numpoints') + self.markerscale = mpl._val_or_rc(markerscale, 'legend.markerscale') + self.scatterpoints = mpl._val_or_rc(scatterpoints, 'legend.scatterpoints') + self.borderpad = mpl._val_or_rc(borderpad, 'legend.borderpad') + self.labelspacing = mpl._val_or_rc(labelspacing, 'legend.labelspacing') + self.handlelength = mpl._val_or_rc(handlelength, 'legend.handlelength') + self.handleheight = mpl._val_or_rc(handleheight, 'legend.handleheight') + self.handletextpad = mpl._val_or_rc(handletextpad, 'legend.handletextpad') + self.borderaxespad = mpl._val_or_rc(borderaxespad, 'legend.borderaxespad') + self.columnspacing = mpl._val_or_rc(columnspacing, 'legend.columnspacing') + self.shadow = mpl._val_or_rc(shadow, 'legend.shadow') + # trim handles and labels if illegal label... + _lab, _hand = [], [] + for label, handle in zip(labels, handles): + if isinstance(label, str) and label.startswith('_'): + _api.warn_deprecated("3.8", message=( + "An artist whose label starts with an underscore was passed to " + "legend(); such artists will no longer be ignored in the future. " + "To suppress this warning, explicitly filter out such artists, " + "e.g. with `[art for art in artists if not " + "art.get_label().startswith('_')]`.")) + else: + _lab.append(label) + _hand.append(handle) + labels, handles = _lab, _hand + + if reverse: + labels.reverse() + handles.reverse() + + if len(handles) < 2: + ncols = 1 + self._ncols = ncols if ncols != 1 else ncol + + if self.numpoints <= 0: + raise ValueError("numpoints must be > 0; it was %d" % numpoints) + + # introduce y-offset for handles of the scatter plot + if scatteryoffsets is None: + self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.]) + else: + self._scatteryoffsets = np.asarray(scatteryoffsets) + reps = self.scatterpoints // len(self._scatteryoffsets) + 1 + self._scatteryoffsets = np.tile(self._scatteryoffsets, + reps)[:self.scatterpoints] + + # _legend_box is a VPacker instance that contains all + # legend items and will be initialized from _init_legend_box() + # method. + self._legend_box = None + + if isinstance(parent, Axes): + self.isaxes = True + self.axes = parent + self.set_figure(parent.figure) + elif isinstance(parent, FigureBase): + self.isaxes = False + self.set_figure(parent) + else: + raise TypeError( + "Legend needs either Axes or FigureBase as parent" + ) + self.parent = parent + + self._mode = mode + self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) + + # Figure out if self.shadow is valid + # If shadow was None, rcParams loads False + # So it shouldn't be None here + + self._shadow_props = {'ox': 2, 'oy': -2} # default location offsets + if isinstance(self.shadow, dict): + self._shadow_props.update(self.shadow) + self.shadow = True + elif self.shadow in (0, 1, True, False): + self.shadow = bool(self.shadow) + else: + raise ValueError( + 'Legend shadow must be a dict or bool, not ' + f'{self.shadow!r} of type {type(self.shadow)}.' + ) + + # We use FancyBboxPatch to draw a legend frame. The location + # and size of the box will be updated during the drawing time. + + facecolor = mpl._val_or_rc(facecolor, "legend.facecolor") + if facecolor == 'inherit': + facecolor = mpl.rcParams["axes.facecolor"] + + edgecolor = mpl._val_or_rc(edgecolor, "legend.edgecolor") + if edgecolor == 'inherit': + edgecolor = mpl.rcParams["axes.edgecolor"] + + fancybox = mpl._val_or_rc(fancybox, "legend.fancybox") + + self.legendPatch = FancyBboxPatch( + xy=(0, 0), width=1, height=1, + facecolor=facecolor, edgecolor=edgecolor, + # If shadow is used, default to alpha=1 (#8943). + alpha=(framealpha if framealpha is not None + else 1 if shadow + else mpl.rcParams["legend.framealpha"]), + # The width and height of the legendPatch will be set (in draw()) + # to the length that includes the padding. Thus we set pad=0 here. + boxstyle=("round,pad=0,rounding_size=0.2" if fancybox + else "square,pad=0"), + mutation_scale=self._fontsize, + snap=True, + visible=mpl._val_or_rc(frameon, "legend.frameon") + ) + self._set_artist_props(self.legendPatch) + + _api.check_in_list(["center", "left", "right"], alignment=alignment) + self._alignment = alignment + + # init with null renderer + self._init_legend_box(handles, labels, markerfirst) + + # Set legend location + self.set_loc(loc) + + # figure out title font properties: + if title_fontsize is not None and title_fontproperties is not None: + raise ValueError( + "title_fontsize and title_fontproperties can't be specified " + "at the same time. Only use one of them. ") + title_prop_fp = FontProperties._from_any(title_fontproperties) + if isinstance(title_fontproperties, dict): + if "size" not in title_fontproperties: + title_fontsize = mpl.rcParams["legend.title_fontsize"] + title_prop_fp.set_size(title_fontsize) + elif title_fontsize is not None: + title_prop_fp.set_size(title_fontsize) + elif not isinstance(title_fontproperties, FontProperties): + title_fontsize = mpl.rcParams["legend.title_fontsize"] + title_prop_fp.set_size(title_fontsize) + + self.set_title(title, prop=title_prop_fp) + + self._draggable = None + self.set_draggable(state=draggable) + + # set the text color + + color_getters = { # getter function depends on line or patch + 'linecolor': ['get_color', 'get_facecolor'], + 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'], + 'mfc': ['get_markerfacecolor', 'get_facecolor'], + 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'], + 'mec': ['get_markeredgecolor', 'get_edgecolor'], + } + labelcolor = mpl._val_or_rc(labelcolor, 'legend.labelcolor') + if labelcolor is None: + labelcolor = mpl.rcParams['text.color'] + if isinstance(labelcolor, str) and labelcolor in color_getters: + getter_names = color_getters[labelcolor] + for handle, text in zip(self.legend_handles, self.texts): + try: + if handle.get_array() is not None: + continue + except AttributeError: + pass + for getter_name in getter_names: + try: + color = getattr(handle, getter_name)() + if isinstance(color, np.ndarray): + if ( + color.shape[0] == 1 + or np.isclose(color, color[0]).all() + ): + text.set_color(color[0]) + else: + pass + else: + text.set_color(color) + break + except AttributeError: + pass + elif cbook._str_equal(labelcolor, 'none'): + for text in self.texts: + text.set_color(labelcolor) + elif np.iterable(labelcolor): + for text, color in zip(self.texts, + itertools.cycle( + colors.to_rgba_array(labelcolor))): + text.set_color(color) + else: + raise ValueError(f"Invalid labelcolor: {labelcolor!r}") + + def _set_artist_props(self, a): + """ + Set the boilerplate props for artists added to Axes. + """ + a.set_figure(self.figure) + if self.isaxes: + a.axes = self.axes + + a.set_transform(self.get_transform()) + + @_docstring.dedent_interpd + def set_loc(self, loc=None): + """ + Set the location of the legend. + + .. versionadded:: 3.8 + + Parameters + ---------- + %(_legend_kw_set_loc_doc)s + """ + loc0 = loc + self._loc_used_default = loc is None + if loc is None: + loc = mpl.rcParams["legend.loc"] + if not self.isaxes and loc in [0, 'best']: + loc = 'upper right' + + type_err_message = ("loc must be string, coordinate tuple, or" + f" an integer 0-10, not {loc!r}") + + # handle outside legends: + self._outside_loc = None + if isinstance(loc, str): + if loc.split()[0] == 'outside': + # strip outside: + loc = loc.split('outside ')[1] + # strip "center" at the beginning + self._outside_loc = loc.replace('center ', '') + # strip first + self._outside_loc = self._outside_loc.split()[0] + locs = loc.split() + if len(locs) > 1 and locs[0] in ('right', 'left'): + # locs doesn't accept "left upper", etc, so swap + if locs[0] != 'center': + locs = locs[::-1] + loc = locs[0] + ' ' + locs[1] + # check that loc is in acceptable strings + loc = _api.check_getitem(self.codes, loc=loc) + elif np.iterable(loc): + # coerce iterable into tuple + loc = tuple(loc) + # validate the tuple represents Real coordinates + if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc): + raise ValueError(type_err_message) + elif isinstance(loc, int): + # validate the integer represents a string numeric value + if loc < 0 or loc > 10: + raise ValueError(type_err_message) + else: + # all other cases are invalid values of loc + raise ValueError(type_err_message) + + if self.isaxes and self._outside_loc: + raise ValueError( + f"'outside' option for loc='{loc0}' keyword argument only " + "works for figure legends") + + if not self.isaxes and loc == 0: + raise ValueError( + "Automatic legend placement (loc='best') not implemented for " + "figure legend") + + tmp = self._loc_used_default + self._set_loc(loc) + self._loc_used_default = tmp # ignore changes done by _set_loc + + def _set_loc(self, loc): + # find_offset function will be provided to _legend_box and + # _legend_box will draw itself at the location of the return + # value of the find_offset. + self._loc_used_default = False + self._loc_real = loc + self.stale = True + self._legend_box.set_offset(self._findoffset) + + def set_ncols(self, ncols): + """Set the number of columns.""" + self._ncols = ncols + + def _get_loc(self): + return self._loc_real + + _loc = property(_get_loc, _set_loc) + + def _findoffset(self, width, height, xdescent, ydescent, renderer): + """Helper function to locate the legend.""" + + if self._loc == 0: # "best". + x, y = self._find_best_position(width, height, renderer) + elif self._loc in Legend.codes.values(): # Fixed location. + bbox = Bbox.from_bounds(0, 0, width, height) + x, y = self._get_anchored_bbox(self._loc, bbox, + self.get_bbox_to_anchor(), + renderer) + else: # Axes or figure coordinates. + fx, fy = self._loc + bbox = self.get_bbox_to_anchor() + x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy + + return x + xdescent, y + ydescent + + @allow_rasterization + def draw(self, renderer): + # docstring inherited + if not self.get_visible(): + return + + renderer.open_group('legend', gid=self.get_gid()) + + fontsize = renderer.points_to_pixels(self._fontsize) + + # if mode == fill, set the width of the legend_box to the + # width of the parent (minus pads) + if self._mode in ["expand"]: + pad = 2 * (self.borderaxespad + self.borderpad) * fontsize + self._legend_box.set_width(self.get_bbox_to_anchor().width - pad) + + # update the location and size of the legend. This needs to + # be done in any case to clip the figure right. + bbox = self._legend_box.get_window_extent(renderer) + self.legendPatch.set_bounds(bbox.bounds) + self.legendPatch.set_mutation_scale(fontsize) + + # self.shadow is validated in __init__ + # So by here it is a bool and self._shadow_props contains any configs + + if self.shadow: + Shadow(self.legendPatch, **self._shadow_props).draw(renderer) + + self.legendPatch.draw(renderer) + self._legend_box.draw(renderer) + + renderer.close_group('legend') + self.stale = False + + # _default_handler_map defines the default mapping between plot + # elements and the legend handlers. + + _default_handler_map = { + StemContainer: legend_handler.HandlerStem(), + ErrorbarContainer: legend_handler.HandlerErrorbar(), + Line2D: legend_handler.HandlerLine2D(), + Patch: legend_handler.HandlerPatch(), + StepPatch: legend_handler.HandlerStepPatch(), + LineCollection: legend_handler.HandlerLineCollection(), + RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(), + CircleCollection: legend_handler.HandlerCircleCollection(), + BarContainer: legend_handler.HandlerPatch( + update_func=legend_handler.update_from_first_child), + tuple: legend_handler.HandlerTuple(), + PathCollection: legend_handler.HandlerPathCollection(), + PolyCollection: legend_handler.HandlerPolyCollection() + } + + # (get|set|update)_default_handler_maps are public interfaces to + # modify the default handler map. + + @classmethod + def get_default_handler_map(cls): + """Return the global default handler map, shared by all legends.""" + return cls._default_handler_map + + @classmethod + def set_default_handler_map(cls, handler_map): + """Set the global default handler map, shared by all legends.""" + cls._default_handler_map = handler_map + + @classmethod + def update_default_handler_map(cls, handler_map): + """Update the global default handler map, shared by all legends.""" + cls._default_handler_map.update(handler_map) + + def get_legend_handler_map(self): + """Return this legend instance's handler map.""" + default_handler_map = self.get_default_handler_map() + return ({**default_handler_map, **self._custom_handler_map} + if self._custom_handler_map else default_handler_map) + + @staticmethod + def get_legend_handler(legend_handler_map, orig_handle): + """ + Return a legend handler from *legend_handler_map* that + corresponds to *orig_handler*. + + *legend_handler_map* should be a dictionary object (that is + returned by the get_legend_handler_map method). + + It first checks if the *orig_handle* itself is a key in the + *legend_handler_map* and return the associated value. + Otherwise, it checks for each of the classes in its + method-resolution-order. If no matching key is found, it + returns ``None``. + """ + try: + return legend_handler_map[orig_handle] + except (TypeError, KeyError): # TypeError if unhashable. + pass + for handle_type in type(orig_handle).mro(): + try: + return legend_handler_map[handle_type] + except KeyError: + pass + return None + + def _init_legend_box(self, handles, labels, markerfirst=True): + """ + Initialize the legend_box. The legend_box is an instance of + the OffsetBox, which is packed with legend handles and + texts. Once packed, their location is calculated during the + drawing time. + """ + + fontsize = self._fontsize + + # legend_box is a HPacker, horizontally packed with columns. + # Each column is a VPacker, vertically packed with legend items. + # Each legend item is a HPacker packed with: + # - handlebox: a DrawingArea which contains the legend handle. + # - labelbox: a TextArea which contains the legend text. + + text_list = [] # the list of text instances + handle_list = [] # the list of handle instances + handles_and_labels = [] + + # The approximate height and descent of text. These values are + # only used for plotting the legend handle. + descent = 0.35 * fontsize * (self.handleheight - 0.7) # heuristic. + height = fontsize * self.handleheight - descent + # each handle needs to be drawn inside a box of (x, y, w, h) = + # (0, -descent, width, height). And their coordinates should + # be given in the display coordinates. + + # The transformation of each handle will be automatically set + # to self.get_transform(). If the artist does not use its + # default transform (e.g., Collections), you need to + # manually set their transform to the self.get_transform(). + legend_handler_map = self.get_legend_handler_map() + + for orig_handle, label in zip(handles, labels): + handler = self.get_legend_handler(legend_handler_map, orig_handle) + if handler is None: + _api.warn_external( + "Legend does not support handles for " + f"{type(orig_handle).__name__} " + "instances.\nA proxy artist may be used " + "instead.\nSee: https://matplotlib.org/" + "stable/users/explain/axes/legend_guide.html" + "#controlling-the-legend-entries") + # No handle for this artist, so we just defer to None. + handle_list.append(None) + else: + textbox = TextArea(label, multilinebaseline=True, + textprops=dict( + verticalalignment='baseline', + horizontalalignment='left', + fontproperties=self.prop)) + handlebox = DrawingArea(width=self.handlelength * fontsize, + height=height, + xdescent=0., ydescent=descent) + + text_list.append(textbox._text) + # Create the artist for the legend which represents the + # original artist/handle. + handle_list.append(handler.legend_artist(self, orig_handle, + fontsize, handlebox)) + handles_and_labels.append((handlebox, textbox)) + + columnbox = [] + # array_split splits n handles_and_labels into ncols columns, with the + # first n%ncols columns having an extra entry. filter(len, ...) + # handles the case where n < ncols: the last ncols-n columns are empty + # and get filtered out. + for handles_and_labels_column in filter( + len, np.array_split(handles_and_labels, self._ncols)): + # pack handlebox and labelbox into itembox + itemboxes = [HPacker(pad=0, + sep=self.handletextpad * fontsize, + children=[h, t] if markerfirst else [t, h], + align="baseline") + for h, t in handles_and_labels_column] + # pack columnbox + alignment = "baseline" if markerfirst else "right" + columnbox.append(VPacker(pad=0, + sep=self.labelspacing * fontsize, + align=alignment, + children=itemboxes)) + + mode = "expand" if self._mode == "expand" else "fixed" + sep = self.columnspacing * fontsize + self._legend_handle_box = HPacker(pad=0, + sep=sep, align="baseline", + mode=mode, + children=columnbox) + self._legend_title_box = TextArea("") + self._legend_box = VPacker(pad=self.borderpad * fontsize, + sep=self.labelspacing * fontsize, + align=self._alignment, + children=[self._legend_title_box, + self._legend_handle_box]) + self._legend_box.set_figure(self.figure) + self._legend_box.axes = self.axes + self.texts = text_list + self.legend_handles = handle_list + + def _auto_legend_data(self): + """ + Return display coordinates for hit testing for "best" positioning. + + Returns + ------- + bboxes + List of bounding boxes of all patches. + lines + List of `.Path` corresponding to each line. + offsets + List of (x, y) offsets of all collection. + """ + assert self.isaxes # always holds, as this is only called internally + bboxes = [] + lines = [] + offsets = [] + for artist in self.parent._children: + if isinstance(artist, Line2D): + lines.append( + artist.get_transform().transform_path(artist.get_path())) + elif isinstance(artist, Rectangle): + bboxes.append( + artist.get_bbox().transformed(artist.get_data_transform())) + elif isinstance(artist, Patch): + lines.append( + artist.get_transform().transform_path(artist.get_path())) + elif isinstance(artist, PolyCollection): + lines.extend(artist.get_transform().transform_path(path) + for path in artist.get_paths()) + elif isinstance(artist, Collection): + transform, transOffset, hoffsets, _ = artist._prepare_points() + if len(hoffsets): + offsets.extend(transOffset.transform(hoffsets)) + elif isinstance(artist, Text): + bboxes.append(artist.get_window_extent()) + + return bboxes, lines, offsets + + def get_children(self): + # docstring inherited + return [self._legend_box, self.get_frame()] + + def get_frame(self): + """Return the `~.patches.Rectangle` used to frame the legend.""" + return self.legendPatch + + def get_lines(self): + r"""Return the list of `~.lines.Line2D`\s in the legend.""" + return [h for h in self.legend_handles if isinstance(h, Line2D)] + + def get_patches(self): + r"""Return the list of `~.patches.Patch`\s in the legend.""" + return silent_list('Patch', + [h for h in self.legend_handles + if isinstance(h, Patch)]) + + def get_texts(self): + r"""Return the list of `~.text.Text`\s in the legend.""" + return silent_list('Text', self.texts) + + def set_alignment(self, alignment): + """ + Set the alignment of the legend title and the box of entries. + + The entries are aligned as a single block, so that markers always + lined up. + + Parameters + ---------- + alignment : {'center', 'left', 'right'}. + + """ + _api.check_in_list(["center", "left", "right"], alignment=alignment) + self._alignment = alignment + self._legend_box.align = alignment + + def get_alignment(self): + """Get the alignment value of the legend box""" + return self._legend_box.align + + def set_title(self, title, prop=None): + """ + Set legend title and title style. + + Parameters + ---------- + title : str + The legend title. + + prop : `.font_manager.FontProperties` or `str` or `pathlib.Path` + The font properties of the legend title. + 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._legend_title_box._text.set_text(title) + if title: + self._legend_title_box._text.set_visible(True) + self._legend_title_box.set_visible(True) + else: + self._legend_title_box._text.set_visible(False) + self._legend_title_box.set_visible(False) + + if prop is not None: + self._legend_title_box._text.set_fontproperties(prop) + + self.stale = True + + def get_title(self): + """Return the `.Text` instance for the legend title.""" + return self._legend_title_box._text + + def get_window_extent(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.figure._get_renderer() + return self._legend_box.get_window_extent(renderer=renderer) + + def get_tightbbox(self, renderer=None): + # docstring inherited + return self._legend_box.get_window_extent(renderer) + + def get_frame_on(self): + """Get whether the legend box patch is drawn.""" + return self.legendPatch.get_visible() + + def set_frame_on(self, b): + """ + Set whether the legend box patch is drawn. + + Parameters + ---------- + b : bool + """ + self.legendPatch.set_visible(b) + self.stale = True + + draw_frame = set_frame_on # Backcompat alias. + + def get_bbox_to_anchor(self): + """Return the bbox that the legend will be anchored to.""" + if self._bbox_to_anchor is None: + return self.parent.bbox + else: + return self._bbox_to_anchor + + def set_bbox_to_anchor(self, bbox, transform=None): + """ + Set the bbox that the legend will be anchored to. + + Parameters + ---------- + bbox : `~matplotlib.transforms.BboxBase` or tuple + The bounding box can be specified in the following ways: + + - A `.BboxBase` instance + - A tuple of ``(left, bottom, width, height)`` in the given + transform (normalized axes coordinate if None) + - A tuple of ``(left, bottom)`` where the width and height will be + assumed to be zero. + - *None*, to remove the bbox anchoring, and use the parent bbox. + + transform : `~matplotlib.transforms.Transform`, optional + A transform to apply to the bounding box. If not specified, this + will use a transform to the bounding box of the parent. + """ + if bbox is None: + self._bbox_to_anchor = None + return + elif isinstance(bbox, BboxBase): + self._bbox_to_anchor = bbox + else: + try: + l = len(bbox) + except TypeError as err: + raise ValueError(f"Invalid bbox: {bbox}") from err + + if l == 2: + bbox = [bbox[0], bbox[1], 0, 0] + + self._bbox_to_anchor = Bbox.from_bounds(*bbox) + + if transform is None: + transform = BboxTransformTo(self.parent.bbox) + + self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor, + transform) + self.stale = True + + def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer): + """ + Place the *bbox* inside the *parentbbox* according to a given + location code. Return the (x, y) coordinate of the bbox. + + Parameters + ---------- + loc : int + A location code in range(1, 11). This corresponds to the possible + values for ``self._loc``, excluding "best". + bbox : `~matplotlib.transforms.Bbox` + bbox to be placed, in display coordinates. + parentbbox : `~matplotlib.transforms.Bbox` + A parent box which will contain the bbox, in display coordinates. + """ + return offsetbox._get_anchored_bbox( + loc, bbox, parentbbox, + self.borderaxespad * renderer.points_to_pixels(self._fontsize)) + + def _find_best_position(self, width, height, renderer): + """Determine the best location to place the legend.""" + assert self.isaxes # always holds, as this is only called internally + + start_time = time.perf_counter() + + bboxes, lines, offsets = self._auto_legend_data() + + bbox = Bbox.from_bounds(0, 0, width, height) + + candidates = [] + for idx in range(1, len(self.codes)): + l, b = self._get_anchored_bbox(idx, bbox, + self.get_bbox_to_anchor(), + renderer) + legendBox = Bbox.from_bounds(l, b, width, height) + # XXX TODO: If markers are present, it would be good to take them + # into account when checking vertex overlaps in the next line. + badness = (sum(legendBox.count_contains(line.vertices) + for line in lines) + + legendBox.count_contains(offsets) + + legendBox.count_overlaps(bboxes) + + sum(line.intersects_bbox(legendBox, filled=False) + for line in lines)) + # Include the index to favor lower codes in case of a tie. + candidates.append((badness, idx, (l, b))) + if badness == 0: + break + + _, _, (l, b) = min(candidates) + + if self._loc_used_default and time.perf_counter() - start_time > 1: + _api.warn_external( + 'Creating legend with loc="best" can be slow with large ' + 'amounts of data.') + + return l, b + + @_api.rename_parameter("3.8", "event", "mouseevent") + def contains(self, mouseevent): + return self.legendPatch.contains(mouseevent) + + def set_draggable(self, state, use_blit=False, update='loc'): + """ + Enable or disable mouse dragging support of the legend. + + Parameters + ---------- + state : bool + Whether mouse dragging is enabled. + use_blit : bool, optional + Use blitting for faster image composition. For details see + :ref:`func-animation`. + update : {'loc', 'bbox'}, optional + The legend parameter to be changed when dragged: + + - 'loc': update the *loc* parameter of the legend + - 'bbox': update the *bbox_to_anchor* parameter of the legend + + Returns + ------- + `.DraggableLegend` or *None* + If *state* is ``True`` this returns the `.DraggableLegend` helper + instance. Otherwise this returns *None*. + """ + if state: + if self._draggable is None: + self._draggable = DraggableLegend(self, + use_blit, + update=update) + else: + if self._draggable is not None: + self._draggable.disconnect() + self._draggable = None + return self._draggable + + def get_draggable(self): + """Return ``True`` if the legend is draggable, ``False`` otherwise.""" + return self._draggable is not None + + +# Helper functions to parse legend arguments for both `figure.legend` and +# `axes.legend`: +def _get_legend_handles(axs, legend_handler_map=None): + """Yield artists that can be used as handles in a legend.""" + handles_original = [] + for ax in axs: + handles_original += [ + *(a for a in ax._children + if isinstance(a, (Line2D, Patch, Collection, Text))), + *ax.containers] + # support parasite Axes: + if hasattr(ax, 'parasites'): + for axx in ax.parasites: + handles_original += [ + *(a for a in axx._children + if isinstance(a, (Line2D, Patch, Collection, Text))), + *axx.containers] + + handler_map = {**Legend.get_default_handler_map(), + **(legend_handler_map or {})} + has_handler = Legend.get_legend_handler + for handle in handles_original: + label = handle.get_label() + if label != '_nolegend_' and has_handler(handler_map, handle): + yield handle + elif (label and not label.startswith('_') and + not has_handler(handler_map, handle)): + _api.warn_external( + "Legend does not support handles for " + f"{type(handle).__name__} " + "instances.\nSee: https://matplotlib.org/stable/" + "tutorials/intermediate/legend_guide.html" + "#implementing-a-custom-legend-handler") + continue + + +def _get_legend_handles_labels(axs, legend_handler_map=None): + """Return handles and labels for legend.""" + handles = [] + labels = [] + for handle in _get_legend_handles(axs, legend_handler_map): + label = handle.get_label() + if label and not label.startswith('_'): + handles.append(handle) + labels.append(label) + return handles, labels + + +def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): + """ + Get the handles and labels from the calls to either ``figure.legend`` + or ``axes.legend``. + + The parser is a bit involved because we support:: + + legend() + legend(labels) + legend(handles, labels) + legend(labels=labels) + legend(handles=handles) + legend(handles=handles, labels=labels) + + The behavior for a mixture of positional and keyword handles and labels + is undefined and issues a warning; it will be an error in the future. + + Parameters + ---------- + axs : list of `.Axes` + If handles are not given explicitly, the artists in these Axes are + used as handles. + *args : tuple + Positional parameters passed to ``legend()``. + handles + The value of the keyword argument ``legend(handles=...)``, or *None* + if that keyword argument was not used. + labels + The value of the keyword argument ``legend(labels=...)``, or *None* + if that keyword argument was not used. + **kwargs + All other keyword arguments passed to ``legend()``. + + Returns + ------- + handles : list of (`.Artist` or tuple of `.Artist`) + The legend handles. + labels : list of str + The legend labels. + kwargs : dict + *kwargs* with keywords handles and labels removed. + + """ + log = logging.getLogger(__name__) + + handlers = kwargs.get('handler_map') + + if (handles is not None or labels is not None) and args: + _api.warn_deprecated("3.9", message=( + "You have mixed positional and keyword arguments, some input may " + "be discarded. This is deprecated since %(since)s and will " + "become an error %(removal)s.")) + + if (hasattr(handles, "__len__") and + hasattr(labels, "__len__") and + len(handles) != len(labels)): + _api.warn_external(f"Mismatched number of handles and labels: " + f"len(handles) = {len(handles)} " + f"len(labels) = {len(labels)}") + # if got both handles and labels as kwargs, make same length + if handles and labels: + handles, labels = zip(*zip(handles, labels)) + + elif handles is not None and labels is None: + labels = [handle.get_label() for handle in handles] + + elif labels is not None and handles is None: + # Get as many handles as there are labels. + handles = [handle for handle, label + in zip(_get_legend_handles(axs, handlers), labels)] + + elif len(args) == 0: # 0 args: automatically detect labels and handles. + handles, labels = _get_legend_handles_labels(axs, handlers) + if not handles: + _api.warn_external( + "No artists with labels found to put in legend. Note that " + "artists whose label start with an underscore are ignored " + "when legend() is called with no argument.") + + elif len(args) == 1: # 1 arg: user defined labels, automatic handle detection. + labels, = args + if any(isinstance(l, Artist) for l in labels): + raise TypeError("A single argument passed to legend() must be a " + "list of labels, but found an Artist in there.") + + # Get as many handles as there are labels. + handles = [handle for handle, label + in zip(_get_legend_handles(axs, handlers), labels)] + + elif len(args) == 2: # 2 args: user defined handles and labels. + handles, labels = args[:2] + + else: + raise _api.nargs_error('legend', '0-2', len(args)) + + return handles, labels, kwargs diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/markers.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/markers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bd2f7dbcaf0ce4a774d743551ce8b3d5e5e1621c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/markers.pyi @@ -0,0 +1,51 @@ +from typing import Literal + +from .path import Path +from .transforms import Affine2D, Transform + +from numpy.typing import ArrayLike +from .typing import CapStyleType, FillStyleType, JoinStyleType + +TICKLEFT: int +TICKRIGHT: int +TICKUP: int +TICKDOWN: int +CARETLEFT: int +CARETRIGHT: int +CARETUP: int +CARETDOWN: int +CARETLEFTBASE: int +CARETRIGHTBASE: int +CARETUPBASE: int +CARETDOWNBASE: int + +class MarkerStyle: + markers: dict[str | int, str] + filled_markers: tuple[str, ...] + fillstyles: tuple[FillStyleType, ...] + + def __init__( + self, + marker: str | ArrayLike | Path | MarkerStyle, + fillstyle: FillStyleType | None = ..., + transform: Transform | None = ..., + capstyle: CapStyleType | None = ..., + joinstyle: JoinStyleType | None = ..., + ) -> None: ... + def __bool__(self) -> bool: ... + def is_filled(self) -> bool: ... + def get_fillstyle(self) -> FillStyleType: ... + def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... + def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ... + def get_marker(self) -> str | ArrayLike | Path | None: ... + def get_path(self) -> Path: ... + def get_transform(self) -> Transform: ... + def get_alt_path(self) -> Path | None: ... + def get_alt_transform(self) -> Transform: ... + def get_snap_threshold(self) -> float | None: ... + def get_user_transform(self) -> Transform | None: ... + def transformed(self, transform: Affine2D) -> MarkerStyle: ... + def rotated( + self, *, deg: float | None = ..., rad: float | None = ... + ) -> MarkerStyle: ... + def scaled(self, sx: float, sy: float | None = ...) -> MarkerStyle: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/offsetbox.py b/llava_next/lib/python3.10/site-packages/matplotlib/offsetbox.py new file mode 100644 index 0000000000000000000000000000000000000000..32c5bafcde1d97c511be89259687b6fc99abc12e --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/offsetbox.py @@ -0,0 +1,1569 @@ +r""" +Container classes for `.Artist`\s. + +`OffsetBox` + The base of all container artists defined in this module. + +`AnchoredOffsetbox`, `AnchoredText` + Anchor and align an arbitrary `.Artist` or a text relative to the parent + axes or a specific anchor point. + +`DrawingArea` + A container with fixed width and height. Children have a fixed position + inside the container and may be clipped. + +`HPacker`, `VPacker` + Containers for layouting their children vertically or horizontally. + +`PaddedBox` + A container to add a padding around an `.Artist`. + +`TextArea` + Contains a single `.Text` instance. +""" + +import functools + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, _docstring +import matplotlib.artist as martist +import matplotlib.path as mpath +import matplotlib.text as mtext +import matplotlib.transforms as mtransforms +from matplotlib.font_manager import FontProperties +from matplotlib.image import BboxImage +from matplotlib.patches import ( + FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist) +from matplotlib.transforms import Bbox, BboxBase, TransformedBbox + + +DEBUG = False + + +def _compat_get_offset(meth): + """ + Decorator for the get_offset method of OffsetBox and subclasses, that + allows supporting both the new signature (self, bbox, renderer) and the old + signature (self, width, height, xdescent, ydescent, renderer). + """ + sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(), + lambda self, bbox, renderer: locals()] + + @functools.wraps(meth) + def get_offset(self, *args, **kwargs): + params = _api.select_matching_signature(sigs, self, *args, **kwargs) + bbox = (params["bbox"] if "bbox" in params else + Bbox.from_bounds(-params["xdescent"], -params["ydescent"], + params["width"], params["height"])) + return meth(params["self"], bbox, params["renderer"]) + return get_offset + + +# for debugging use +def _bbox_artist(*args, **kwargs): + if DEBUG: + mbbox_artist(*args, **kwargs) + + +def _get_packed_offsets(widths, total, sep, mode="fixed"): + r""" + Pack boxes specified by their *widths*. + + For simplicity of the description, the terminology used here assumes a + horizontal layout, but the function works equally for a vertical layout. + + There are three packing *mode*\s: + + - 'fixed': The elements are packed tight to the left with a spacing of + *sep* in between. If *total* is *None* the returned total will be the + right edge of the last box. A non-*None* total will be passed unchecked + to the output. In particular this means that right edge of the last + box may be further to the right than the returned total. + + - 'expand': Distribute the boxes with equal spacing so that the left edge + of the first box is at 0, and the right edge of the last box is at + *total*. The parameter *sep* is ignored in this mode. A total of *None* + is accepted and considered equal to 1. The total is returned unchanged + (except for the conversion *None* to 1). If the total is smaller than + the sum of the widths, the laid out boxes will overlap. + + - 'equal': If *total* is given, the total space is divided in N equal + ranges and each box is left-aligned within its subspace. + Otherwise (*total* is *None*), *sep* must be provided and each box is + left-aligned in its subspace of width ``(max(widths) + sep)``. The + total width is then calculated to be ``N * (max(widths) + sep)``. + + Parameters + ---------- + widths : list of float + Widths of boxes to be packed. + total : float or None + Intended total length. *None* if not used. + sep : float or None + Spacing between boxes. + mode : {'fixed', 'expand', 'equal'} + The packing mode. + + Returns + ------- + total : float + The total width needed to accommodate the laid out boxes. + offsets : array of float + The left offsets of the boxes. + """ + _api.check_in_list(["fixed", "expand", "equal"], mode=mode) + + if mode == "fixed": + offsets_ = np.cumsum([0] + [w + sep for w in widths]) + offsets = offsets_[:-1] + if total is None: + total = offsets_[-1] - sep + return total, offsets + + elif mode == "expand": + # This is a bit of a hack to avoid a TypeError when *total* + # is None and used in conjugation with tight layout. + if total is None: + total = 1 + if len(widths) > 1: + sep = (total - sum(widths)) / (len(widths) - 1) + else: + sep = 0 + offsets_ = np.cumsum([0] + [w + sep for w in widths]) + offsets = offsets_[:-1] + return total, offsets + + elif mode == "equal": + maxh = max(widths) + if total is None: + if sep is None: + raise ValueError("total and sep cannot both be None when " + "using layout mode 'equal'") + total = (maxh + sep) * len(widths) + else: + sep = total / len(widths) - maxh + offsets = (maxh + sep) * np.arange(len(widths)) + return total, offsets + + +def _get_aligned_offsets(yspans, height, align="baseline"): + """ + Align boxes each specified by their ``(y0, y1)`` spans. + + For simplicity of the description, the terminology used here assumes a + horizontal layout (i.e., vertical alignment), but the function works + equally for a vertical layout. + + Parameters + ---------- + yspans + List of (y0, y1) spans of boxes to be aligned. + height : float or None + Intended total height. If None, the maximum of the heights + (``y1 - y0``) in *yspans* is used. + align : {'baseline', 'left', 'top', 'right', 'bottom', 'center'} + The alignment anchor of the boxes. + + Returns + ------- + (y0, y1) + y range spanned by the packing. If a *height* was originally passed + in, then for all alignments other than "baseline", a span of ``(0, + height)`` is used without checking that it is actually large enough). + descent + The descent of the packing. + offsets + The bottom offsets of the boxes. + """ + + _api.check_in_list( + ["baseline", "left", "top", "right", "bottom", "center"], align=align) + if height is None: + height = max(y1 - y0 for y0, y1 in yspans) + + if align == "baseline": + yspan = (min(y0 for y0, y1 in yspans), max(y1 for y0, y1 in yspans)) + offsets = [0] * len(yspans) + elif align in ["left", "bottom"]: + yspan = (0, height) + offsets = [-y0 for y0, y1 in yspans] + elif align in ["right", "top"]: + yspan = (0, height) + offsets = [height - y1 for y0, y1 in yspans] + elif align == "center": + yspan = (0, height) + offsets = [(height - (y1 - y0)) * .5 - y0 for y0, y1 in yspans] + + return yspan, offsets + + +class OffsetBox(martist.Artist): + """ + The OffsetBox is a simple container artist. + + The child artists are meant to be drawn at a relative position to its + parent. + + Being an artist itself, all parameters are passed on to `.Artist`. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args) + self._internal_update(kwargs) + # Clipping has not been implemented in the OffsetBox family, so + # disable the clip flag for consistency. It can always be turned back + # on to zero effect. + self.set_clip_on(False) + self._children = [] + self._offset = (0, 0) + + def set_figure(self, fig): + """ + Set the `.Figure` for the `.OffsetBox` and all its children. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + """ + super().set_figure(fig) + for c in self.get_children(): + c.set_figure(fig) + + @martist.Artist.axes.setter + def axes(self, ax): + # TODO deal with this better + martist.Artist.axes.fset(self, ax) + for c in self.get_children(): + if c is not None: + c.axes = ax + + def contains(self, mouseevent): + """ + Delegate the mouse event contains-check to the children. + + As a container, the `.OffsetBox` does not respond itself to + mouseevents. + + 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. + + See Also + -------- + .Artist.contains + """ + if self._different_canvas(mouseevent): + return False, {} + for c in self.get_children(): + a, b = c.contains(mouseevent) + if a: + return a, b + return False, {} + + def set_offset(self, xy): + """ + Set the offset. + + Parameters + ---------- + xy : (float, float) or callable + The (x, y) coordinates of the offset in display units. These can + either be given explicitly as a tuple (x, y), or by providing a + function that converts the extent into the offset. This function + must have the signature:: + + def offset(width, height, xdescent, ydescent, renderer) \ +-> (float, float) + """ + self._offset = xy + self.stale = True + + @_compat_get_offset + def get_offset(self, bbox, renderer): + """ + Return the offset as a tuple (x, y). + + The extent parameters have to be provided to handle the case where the + offset is dynamically determined by a callable (see + `~.OffsetBox.set_offset`). + + Parameters + ---------- + bbox : `.Bbox` + renderer : `.RendererBase` subclass + """ + return ( + self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer) + if callable(self._offset) + else self._offset) + + def set_width(self, width): + """ + Set the width of the box. + + Parameters + ---------- + width : float + """ + self.width = width + self.stale = True + + def set_height(self, height): + """ + Set the height of the box. + + Parameters + ---------- + height : float + """ + self.height = height + self.stale = True + + def get_visible_children(self): + r"""Return a list of the visible child `.Artist`\s.""" + return [c for c in self._children if c.get_visible()] + + def get_children(self): + r"""Return a list of the child `.Artist`\s.""" + return self._children + + def _get_bbox_and_child_offsets(self, renderer): + """ + Return the bbox of the offsetbox and the child offsets. + + The bbox should satisfy ``x0 <= x1 and y0 <= y1``. + + Parameters + ---------- + renderer : `.RendererBase` subclass + + Returns + ------- + bbox + list of (xoffset, yoffset) pairs + """ + raise NotImplementedError( + "get_bbox_and_offsets must be overridden in derived classes") + + def get_bbox(self, renderer): + """Return the bbox of the offsetbox, ignoring parent offsets.""" + bbox, offsets = self._get_bbox_and_child_offsets(renderer) + return bbox + + def get_window_extent(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.figure._get_renderer() + bbox = self.get_bbox(renderer) + try: # Some subclasses redefine get_offset to take no args. + px, py = self.get_offset(bbox, renderer) + except TypeError: + px, py = self.get_offset() + return bbox.translated(px, py) + + def draw(self, renderer): + """ + Update the location of children if necessary and draw them + to the given *renderer*. + """ + bbox, offsets = self._get_bbox_and_child_offsets(renderer) + px, py = self.get_offset(bbox, renderer) + for c, (ox, oy) in zip(self.get_visible_children(), offsets): + c.set_offset((px + ox, py + oy)) + c.draw(renderer) + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class PackerBase(OffsetBox): + def __init__(self, pad=0., sep=0., width=None, height=None, + align="baseline", mode="fixed", children=None): + """ + Parameters + ---------- + pad : float, default: 0.0 + The boundary padding in points. + + sep : float, default: 0.0 + The spacing between items in points. + + width, height : float, optional + Width and height of the container box in pixels, calculated if + *None*. + + align : {'top', 'bottom', 'left', 'right', 'center', 'baseline'}, \ +default: 'baseline' + Alignment of boxes. + + mode : {'fixed', 'expand', 'equal'}, default: 'fixed' + The packing mode. + + - 'fixed' packs the given `.Artist`\\s tight with *sep* spacing. + - 'expand' uses the maximal available space to distribute the + artists with equal spacing in between. + - 'equal': Each artist an equal fraction of the available space + and is left-aligned (or top-aligned) therein. + + children : list of `.Artist` + The artists to pack. + + Notes + ----- + *pad* and *sep* are in points and will be scaled with the renderer + dpi, while *width* and *height* are in pixels. + """ + super().__init__() + self.height = height + self.width = width + self.sep = sep + self.pad = pad + self.mode = mode + self.align = align + self._children = children + + +class VPacker(PackerBase): + """ + VPacker packs its children vertically, automatically adjusting their + relative positions at draw time. + """ + + def _get_bbox_and_child_offsets(self, renderer): + # docstring inherited + dpicor = renderer.points_to_pixels(1.) + pad = self.pad * dpicor + sep = self.sep * dpicor + + if self.width is not None: + for c in self.get_visible_children(): + if isinstance(c, PackerBase) and c.mode == "expand": + c.set_width(self.width) + + bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()] + (x0, x1), xoffsets = _get_aligned_offsets( + [bbox.intervalx for bbox in bboxes], self.width, self.align) + height, yoffsets = _get_packed_offsets( + [bbox.height for bbox in bboxes], self.height, sep, self.mode) + + yoffsets = height - (yoffsets + [bbox.y1 for bbox in bboxes]) + ydescent = yoffsets[0] + yoffsets = yoffsets - ydescent + + return ( + Bbox.from_bounds(x0, -ydescent, x1 - x0, height).padded(pad), + [*zip(xoffsets, yoffsets)]) + + +class HPacker(PackerBase): + """ + HPacker packs its children horizontally, automatically adjusting their + relative positions at draw time. + """ + + def _get_bbox_and_child_offsets(self, renderer): + # docstring inherited + dpicor = renderer.points_to_pixels(1.) + pad = self.pad * dpicor + sep = self.sep * dpicor + + bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()] + if not bboxes: + return Bbox.from_bounds(0, 0, 0, 0).padded(pad), [] + + (y0, y1), yoffsets = _get_aligned_offsets( + [bbox.intervaly for bbox in bboxes], self.height, self.align) + width, xoffsets = _get_packed_offsets( + [bbox.width for bbox in bboxes], self.width, sep, self.mode) + + x0 = bboxes[0].x0 + xoffsets -= ([bbox.x0 for bbox in bboxes] - x0) + + return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad), + [*zip(xoffsets, yoffsets)]) + + +class PaddedBox(OffsetBox): + """ + A container to add a padding around an `.Artist`. + + The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize + it when rendering. + """ + + def __init__(self, child, pad=0., *, draw_frame=False, patch_attrs=None): + """ + Parameters + ---------- + child : `~matplotlib.artist.Artist` + The contained `.Artist`. + pad : float, default: 0.0 + The padding in points. This will be scaled with the renderer dpi. + In contrast, *width* and *height* are in *pixels* and thus not + scaled. + draw_frame : bool + Whether to draw the contained `.FancyBboxPatch`. + patch_attrs : dict or None + Additional parameters passed to the contained `.FancyBboxPatch`. + """ + super().__init__() + self.pad = pad + self._children = [child] + self.patch = FancyBboxPatch( + xy=(0.0, 0.0), width=1., height=1., + facecolor='w', edgecolor='k', + mutation_scale=1, # self.prop.get_size_in_points(), + snap=True, + visible=draw_frame, + boxstyle="square,pad=0", + ) + if patch_attrs is not None: + self.patch.update(patch_attrs) + + def _get_bbox_and_child_offsets(self, renderer): + # docstring inherited. + pad = self.pad * renderer.points_to_pixels(1.) + return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)]) + + def draw(self, renderer): + # docstring inherited + bbox, offsets = self._get_bbox_and_child_offsets(renderer) + px, py = self.get_offset(bbox, renderer) + for c, (ox, oy) in zip(self.get_visible_children(), offsets): + c.set_offset((px + ox, py + oy)) + + self.draw_frame(renderer) + + for c in self.get_visible_children(): + c.draw(renderer) + + self.stale = False + + def update_frame(self, bbox, fontsize=None): + self.patch.set_bounds(bbox.bounds) + if fontsize: + self.patch.set_mutation_scale(fontsize) + self.stale = True + + def draw_frame(self, renderer): + # update the location and size of the legend + self.update_frame(self.get_window_extent(renderer)) + self.patch.draw(renderer) + + +class DrawingArea(OffsetBox): + """ + The DrawingArea can contain any Artist as a child. The DrawingArea + has a fixed width and height. The position of children relative to + the parent is fixed. The children can be clipped at the + boundaries of the parent. + """ + + def __init__(self, width, height, xdescent=0., ydescent=0., clip=False): + """ + Parameters + ---------- + width, height : float + Width and height of the container box. + xdescent, ydescent : float + Descent of the box in x- and y-direction. + clip : bool + Whether to clip the children to the box. + """ + super().__init__() + self.width = width + self.height = height + self.xdescent = xdescent + self.ydescent = ydescent + self._clip_children = clip + self.offset_transform = mtransforms.Affine2D() + self.dpi_transform = mtransforms.Affine2D() + + @property + def clip_children(self): + """ + If the children of this DrawingArea should be clipped + by DrawingArea bounding box. + """ + return self._clip_children + + @clip_children.setter + def clip_children(self, val): + self._clip_children = bool(val) + self.stale = True + + def get_transform(self): + """ + Return the `~matplotlib.transforms.Transform` applied to the children. + """ + return self.dpi_transform + self.offset_transform + + def set_transform(self, t): + """ + set_transform is ignored. + """ + + def set_offset(self, xy): + """ + Set the offset of the container. + + Parameters + ---------- + xy : (float, float) + The (x, y) coordinates of the offset in display units. + """ + self._offset = xy + self.offset_transform.clear() + self.offset_transform.translate(xy[0], xy[1]) + self.stale = True + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_bbox(self, renderer): + # docstring inherited + dpi_cor = renderer.points_to_pixels(1.) + return Bbox.from_bounds( + -self.xdescent * dpi_cor, -self.ydescent * dpi_cor, + self.width * dpi_cor, self.height * dpi_cor) + + def add_artist(self, a): + """Add an `.Artist` to the container box.""" + self._children.append(a) + if not a.is_transform_set(): + a.set_transform(self.get_transform()) + if self.axes is not None: + a.axes = self.axes + fig = self.figure + if fig is not None: + a.set_figure(fig) + + def draw(self, renderer): + # docstring inherited + + dpi_cor = renderer.points_to_pixels(1.) + self.dpi_transform.clear() + self.dpi_transform.scale(dpi_cor) + + # At this point the DrawingArea has a transform + # to the display space so the path created is + # good for clipping children + tpath = mtransforms.TransformedPath( + mpath.Path([[0, 0], [0, self.height], + [self.width, self.height], + [self.width, 0]]), + self.get_transform()) + for c in self._children: + if self._clip_children and not (c.clipbox or c._clippath): + c.set_clip_path(tpath) + c.draw(renderer) + + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class TextArea(OffsetBox): + """ + The TextArea is a container artist for a single Text instance. + + The text is placed at (0, 0) with baseline+left alignment, by default. The + width and height of the TextArea instance is the width and height of its + child text. + """ + + def __init__(self, s, + *, + textprops=None, + multilinebaseline=False, + ): + """ + Parameters + ---------- + s : str + The text to be displayed. + textprops : dict, default: {} + Dictionary of keyword parameters to be passed to the `.Text` + instance in the TextArea. + multilinebaseline : bool, default: False + Whether the baseline for multiline text is adjusted so that it + is (approximately) center-aligned with single-line text. + """ + if textprops is None: + textprops = {} + self._text = mtext.Text(0, 0, s, **textprops) + super().__init__() + self._children = [self._text] + self.offset_transform = mtransforms.Affine2D() + self._baseline_transform = mtransforms.Affine2D() + self._text.set_transform(self.offset_transform + + self._baseline_transform) + self._multilinebaseline = multilinebaseline + + def set_text(self, s): + """Set the text of this area as a string.""" + self._text.set_text(s) + self.stale = True + + def get_text(self): + """Return the string representation of this area's text.""" + return self._text.get_text() + + def set_multilinebaseline(self, t): + """ + Set multilinebaseline. + + If True, the baseline for multiline text is adjusted so that it is + (approximately) center-aligned with single-line text. This is used + e.g. by the legend implementation so that single-line labels are + baseline-aligned, but multiline labels are "center"-aligned with them. + """ + self._multilinebaseline = t + self.stale = True + + def get_multilinebaseline(self): + """ + Get multilinebaseline. + """ + return self._multilinebaseline + + def set_transform(self, t): + """ + set_transform is ignored. + """ + + def set_offset(self, xy): + """ + Set the offset of the container. + + Parameters + ---------- + xy : (float, float) + The (x, y) coordinates of the offset in display units. + """ + self._offset = xy + self.offset_transform.clear() + self.offset_transform.translate(xy[0], xy[1]) + self.stale = True + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_bbox(self, renderer): + _, h_, d_ = renderer.get_text_width_height_descent( + "lp", self._text._fontproperties, + ismath="TeX" if self._text.get_usetex() else False) + + bbox, info, yd = self._text._get_layout(renderer) + w, h = bbox.size + + self._baseline_transform.clear() + + if len(info) > 1 and self._multilinebaseline: + yd_new = 0.5 * h - 0.5 * (h_ - d_) + self._baseline_transform.translate(0, yd - yd_new) + yd = yd_new + else: # single line + h_d = max(h_ - d_, h - yd) + h = h_d + yd + + ha = self._text.get_horizontalalignment() + x0 = {"left": 0, "center": -w / 2, "right": -w}[ha] + + return Bbox.from_bounds(x0, -yd, w, h) + + def draw(self, renderer): + # docstring inherited + self._text.draw(renderer) + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class AuxTransformBox(OffsetBox): + """ + Offset Box with the aux_transform. Its children will be + transformed with the aux_transform first then will be + offsetted. The absolute coordinate of the aux_transform is meaning + as it will be automatically adjust so that the left-lower corner + of the bounding box of children will be set to (0, 0) before the + offset transform. + + It is similar to drawing area, except that the extent of the box + is not predetermined but calculated from the window extent of its + children. Furthermore, the extent of the children will be + calculated in the transformed coordinate. + """ + def __init__(self, aux_transform): + self.aux_transform = aux_transform + super().__init__() + self.offset_transform = mtransforms.Affine2D() + # ref_offset_transform makes offset_transform always relative to the + # lower-left corner of the bbox of its children. + self.ref_offset_transform = mtransforms.Affine2D() + + def add_artist(self, a): + """Add an `.Artist` to the container box.""" + self._children.append(a) + a.set_transform(self.get_transform()) + self.stale = True + + def get_transform(self): + """ + Return the :class:`~matplotlib.transforms.Transform` applied + to the children + """ + return (self.aux_transform + + self.ref_offset_transform + + self.offset_transform) + + def set_transform(self, t): + """ + set_transform is ignored. + """ + + def set_offset(self, xy): + """ + Set the offset of the container. + + Parameters + ---------- + xy : (float, float) + The (x, y) coordinates of the offset in display units. + """ + self._offset = xy + self.offset_transform.clear() + self.offset_transform.translate(xy[0], xy[1]) + self.stale = True + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_bbox(self, renderer): + # clear the offset transforms + _off = self.offset_transform.get_matrix() # to be restored later + self.ref_offset_transform.clear() + self.offset_transform.clear() + # calculate the extent + bboxes = [c.get_window_extent(renderer) for c in self._children] + ub = Bbox.union(bboxes) + # adjust ref_offset_transform + self.ref_offset_transform.translate(-ub.x0, -ub.y0) + # restore offset transform + self.offset_transform.set_matrix(_off) + return Bbox.from_bounds(0, 0, ub.width, ub.height) + + def draw(self, renderer): + # docstring inherited + for c in self._children: + c.draw(renderer) + _bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class AnchoredOffsetbox(OffsetBox): + """ + An offset box placed according to location *loc*. + + AnchoredOffsetbox has a single child. When multiple children are needed, + use an extra OffsetBox to enclose them. By default, the offset box is + anchored against its parent Axes. You may explicitly specify the + *bbox_to_anchor*. + """ + zorder = 5 # zorder of the legend + + # Location codes + codes = {'upper right': 1, + 'upper left': 2, + 'lower left': 3, + 'lower right': 4, + 'right': 5, + 'center left': 6, + 'center right': 7, + 'lower center': 8, + 'upper center': 9, + 'center': 10, + } + + def __init__(self, loc, *, + pad=0.4, borderpad=0.5, + child=None, prop=None, frameon=True, + bbox_to_anchor=None, + bbox_transform=None, + **kwargs): + """ + Parameters + ---------- + loc : str + The box location. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + pad : float, default: 0.4 + Padding around the child as fraction of the fontsize. + borderpad : float, default: 0.5 + Padding between the offsetbox frame and the *bbox_to_anchor*. + child : `.OffsetBox` + The box that will be anchored. + prop : `.FontProperties` + This is only used as a reference for paddings. If not given, + :rc:`legend.fontsize` is used. + frameon : bool + Whether to draw a frame around the box. + bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats + Box that is used to position the legend in conjunction with *loc*. + bbox_transform : None or :class:`matplotlib.transforms.Transform` + The transform for the bounding box (*bbox_to_anchor*). + **kwargs + All other parameters are passed on to `.OffsetBox`. + + Notes + ----- + See `.Legend` for a detailed description of the anchoring mechanism. + """ + super().__init__(**kwargs) + + self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) + self.set_child(child) + + if isinstance(loc, str): + loc = _api.check_getitem(self.codes, loc=loc) + + self.loc = loc + self.borderpad = borderpad + self.pad = pad + + if prop is None: + self.prop = FontProperties(size=mpl.rcParams["legend.fontsize"]) + else: + self.prop = FontProperties._from_any(prop) + if isinstance(prop, dict) and "size" not in prop: + self.prop.set_size(mpl.rcParams["legend.fontsize"]) + + self.patch = FancyBboxPatch( + xy=(0.0, 0.0), width=1., height=1., + facecolor='w', edgecolor='k', + mutation_scale=self.prop.get_size_in_points(), + snap=True, + visible=frameon, + boxstyle="square,pad=0", + ) + + def set_child(self, child): + """Set the child to be anchored.""" + self._child = child + if child is not None: + child.axes = self.axes + self.stale = True + + def get_child(self): + """Return the child.""" + return self._child + + def get_children(self): + """Return the list of children.""" + return [self._child] + + def get_bbox(self, renderer): + # docstring inherited + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + pad = self.pad * fontsize + return self.get_child().get_bbox(renderer).padded(pad) + + def get_bbox_to_anchor(self): + """Return the bbox that the box is anchored to.""" + if self._bbox_to_anchor is None: + return self.axes.bbox + else: + transform = self._bbox_to_anchor_transform + if transform is None: + return self._bbox_to_anchor + else: + return TransformedBbox(self._bbox_to_anchor, transform) + + def set_bbox_to_anchor(self, bbox, transform=None): + """ + Set the bbox that the box is anchored to. + + *bbox* can be a Bbox instance, a list of [left, bottom, width, + height], or a list of [left, bottom] where the width and + height will be assumed to be zero. The bbox will be + transformed to display coordinate by the given transform. + """ + if bbox is None or isinstance(bbox, BboxBase): + self._bbox_to_anchor = bbox + else: + try: + l = len(bbox) + except TypeError as err: + raise ValueError(f"Invalid bbox: {bbox}") from err + + if l == 2: + bbox = [bbox[0], bbox[1], 0, 0] + + self._bbox_to_anchor = Bbox.from_bounds(*bbox) + + self._bbox_to_anchor_transform = transform + self.stale = True + + @_compat_get_offset + def get_offset(self, bbox, renderer): + # docstring inherited + pad = (self.borderpad + * renderer.points_to_pixels(self.prop.get_size_in_points())) + bbox_to_anchor = self.get_bbox_to_anchor() + x0, y0 = _get_anchored_bbox( + self.loc, Bbox.from_bounds(0, 0, bbox.width, bbox.height), + bbox_to_anchor, pad) + return x0 - bbox.x0, y0 - bbox.y0 + + def update_frame(self, bbox, fontsize=None): + self.patch.set_bounds(bbox.bounds) + if fontsize: + self.patch.set_mutation_scale(fontsize) + + def draw(self, renderer): + # docstring inherited + if not self.get_visible(): + return + + # update the location and size of the legend + bbox = self.get_window_extent(renderer) + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + self.update_frame(bbox, fontsize) + self.patch.draw(renderer) + + px, py = self.get_offset(self.get_bbox(renderer), renderer) + self.get_child().set_offset((px, py)) + self.get_child().draw(renderer) + self.stale = False + + +def _get_anchored_bbox(loc, bbox, parentbbox, borderpad): + """ + Return the (x, y) position of the *bbox* anchored at the *parentbbox* with + the *loc* code with the *borderpad*. + """ + # This is only called internally and *loc* should already have been + # validated. If 0 (None), we just let ``bbox.anchored`` raise. + c = [None, "NE", "NW", "SW", "SE", "E", "W", "E", "S", "N", "C"][loc] + container = parentbbox.padded(-borderpad) + return bbox.anchored(c, container=container).p0 + + +class AnchoredText(AnchoredOffsetbox): + """ + AnchoredOffsetbox with Text. + """ + + def __init__(self, s, loc, *, pad=0.4, borderpad=0.5, prop=None, **kwargs): + """ + Parameters + ---------- + s : str + Text. + + loc : str + Location code. See `AnchoredOffsetbox`. + + pad : float, default: 0.4 + Padding around the text as fraction of the fontsize. + + borderpad : float, default: 0.5 + Spacing between the offsetbox frame and the *bbox_to_anchor*. + + prop : dict, optional + Dictionary of keyword parameters to be passed to the + `~matplotlib.text.Text` instance contained inside AnchoredText. + + **kwargs + All other parameters are passed to `AnchoredOffsetbox`. + """ + + if prop is None: + prop = {} + badkwargs = {'va', 'verticalalignment'} + if badkwargs & set(prop): + raise ValueError( + 'Mixing verticalalignment with AnchoredText is not supported.') + + self.txt = TextArea(s, textprops=prop) + fp = self.txt._text.get_fontproperties() + super().__init__( + loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp, + **kwargs) + + +class OffsetImage(OffsetBox): + + def __init__(self, arr, *, + zoom=1, + cmap=None, + norm=None, + interpolation=None, + origin=None, + filternorm=True, + filterrad=4.0, + resample=False, + dpi_cor=True, + **kwargs + ): + + super().__init__() + self._dpi_cor = dpi_cor + + self.image = BboxImage(bbox=self.get_window_extent, + cmap=cmap, + norm=norm, + interpolation=interpolation, + origin=origin, + filternorm=filternorm, + filterrad=filterrad, + resample=resample, + **kwargs + ) + + self._children = [self.image] + + self.set_zoom(zoom) + self.set_data(arr) + + def set_data(self, arr): + self._data = np.asarray(arr) + self.image.set_data(self._data) + self.stale = True + + def get_data(self): + return self._data + + def set_zoom(self, zoom): + self._zoom = zoom + self.stale = True + + def get_zoom(self): + return self._zoom + + def get_offset(self): + """Return offset of the container.""" + return self._offset + + def get_children(self): + return [self.image] + + def get_bbox(self, renderer): + dpi_cor = renderer.points_to_pixels(1.) if self._dpi_cor else 1. + zoom = self.get_zoom() + data = self.get_data() + ny, nx = data.shape[:2] + w, h = dpi_cor * nx * zoom, dpi_cor * ny * zoom + return Bbox.from_bounds(0, 0, w, h) + + def draw(self, renderer): + # docstring inherited + self.image.draw(renderer) + # bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) + self.stale = False + + +class AnnotationBbox(martist.Artist, mtext._AnnotationBase): + """ + Container for an `OffsetBox` referring to a specific position *xy*. + + Optionally an arrow pointing from the offsetbox to *xy* can be drawn. + + This is like `.Annotation`, but with `OffsetBox` instead of `.Text`. + """ + + zorder = 3 + + def __str__(self): + return f"AnnotationBbox({self.xy[0]:g},{self.xy[1]:g})" + + @_docstring.dedent_interpd + def __init__(self, offsetbox, xy, xybox=None, xycoords='data', boxcoords=None, *, + frameon=True, pad=0.4, # FancyBboxPatch boxstyle. + annotation_clip=None, + box_alignment=(0.5, 0.5), + bboxprops=None, + arrowprops=None, + fontsize=None, + **kwargs): + """ + Parameters + ---------- + offsetbox : `OffsetBox` + + xy : (float, float) + The point *(x, y)* to annotate. The coordinate system is determined + by *xycoords*. + + xybox : (float, float), default: *xy* + The position *(x, y)* to place the text at. The coordinate system + is determined by *boxcoords*. + + xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \ +callable, default: 'data' + The coordinate system that *xy* is given in. See the parameter + *xycoords* in `.Annotation` for a detailed description. + + boxcoords : single or two-tuple of str or `.Artist` or `.Transform` \ +or callable, default: value of *xycoords* + The coordinate system that *xybox* is given in. See the parameter + *textcoords* in `.Annotation` for a detailed description. + + frameon : bool, default: True + By default, the text is surrounded by a white `.FancyBboxPatch` + (accessible as the ``patch`` attribute of the `.AnnotationBbox`). + If *frameon* is set to False, this patch is made invisible. + + 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'. + + pad : float, default: 0.4 + Padding around the offsetbox. + + box_alignment : (float, float) + A tuple of two floats for a vertical and horizontal alignment of + the offset box w.r.t. the *boxcoords*. + The lower-left corner is (0, 0) and upper-right corner is (1, 1). + + bboxprops : dict, optional + A dictionary of properties to set for the annotation bounding box, + for example *boxstyle* and *alpha*. See `.FancyBboxPatch` for + details. + + arrowprops: dict, optional + Arrow properties, see `.Annotation` for description. + + fontsize: float or str, optional + Translated to points and passed as *mutation_scale* into + `.FancyBboxPatch` to scale attributes of the box style (e.g. pad + or rounding_size). The name is chosen in analogy to `.Text` where + *fontsize* defines the mutation scale as well. If not given, + :rc:`legend.fontsize` is used. See `.Text.set_fontsize` for valid + values. + + **kwargs + Other `AnnotationBbox` properties. See `.AnnotationBbox.set` for + a list. + """ + + martist.Artist.__init__(self) + mtext._AnnotationBase.__init__( + self, xy, xycoords=xycoords, annotation_clip=annotation_clip) + + self.offsetbox = offsetbox + self.arrowprops = arrowprops.copy() if arrowprops is not None else None + self.set_fontsize(fontsize) + self.xybox = xybox if xybox is not None else xy + self.boxcoords = boxcoords if boxcoords is not None else xycoords + self._box_alignment = box_alignment + + if arrowprops is not None: + self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5)) + self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), + **self.arrowprops) + else: + self._arrow_relpos = None + self.arrow_patch = None + + self.patch = FancyBboxPatch( # frame + xy=(0.0, 0.0), width=1., height=1., + facecolor='w', edgecolor='k', + mutation_scale=self.prop.get_size_in_points(), + snap=True, + visible=frameon, + ) + self.patch.set_boxstyle("square", pad=pad) + if bboxprops: + self.patch.set(**bboxprops) + + self._internal_update(kwargs) + + @property + def xyann(self): + return self.xybox + + @xyann.setter + def xyann(self, xyann): + self.xybox = xyann + self.stale = True + + @property + def anncoords(self): + return self.boxcoords + + @anncoords.setter + def anncoords(self, coords): + self.boxcoords = coords + self.stale = True + + def contains(self, mouseevent): + if self._different_canvas(mouseevent): + return False, {} + if not self._check_xy(None): + return False, {} + return self.offsetbox.contains(mouseevent) + # self.arrow_patch is currently not checked as this can be a line - JJ + + def get_children(self): + children = [self.offsetbox, self.patch] + if self.arrow_patch: + children.append(self.arrow_patch) + return children + + def set_figure(self, fig): + if self.arrow_patch is not None: + self.arrow_patch.set_figure(fig) + self.offsetbox.set_figure(fig) + martist.Artist.set_figure(self, fig) + + def set_fontsize(self, s=None): + """ + Set the fontsize in points. + + If *s* is not given, reset to :rc:`legend.fontsize`. + """ + if s is None: + s = mpl.rcParams["legend.fontsize"] + + self.prop = FontProperties(size=s) + self.stale = True + + def get_fontsize(self): + """Return the fontsize in points.""" + return self.prop.get_size_in_points() + + def get_window_extent(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.figure._get_renderer() + self.update_positions(renderer) + return Bbox.union([child.get_window_extent(renderer) + for child in self.get_children()]) + + def get_tightbbox(self, renderer=None): + # docstring inherited + if renderer is None: + renderer = self.figure._get_renderer() + self.update_positions(renderer) + return Bbox.union([child.get_tightbbox(renderer) + for child in self.get_children()]) + + def update_positions(self, renderer): + """Update pixel positions for the annotated point, the text, and the arrow.""" + + ox0, oy0 = self._get_xy(renderer, self.xybox, self.boxcoords) + bbox = self.offsetbox.get_bbox(renderer) + fw, fh = self._box_alignment + self.offsetbox.set_offset( + (ox0 - fw*bbox.width - bbox.x0, oy0 - fh*bbox.height - bbox.y0)) + + bbox = self.offsetbox.get_window_extent(renderer) + self.patch.set_bounds(bbox.bounds) + + mutation_scale = renderer.points_to_pixels(self.get_fontsize()) + self.patch.set_mutation_scale(mutation_scale) + + if self.arrowprops: + # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key. + + # 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 + arrow_end = self._get_position_xy(renderer) + # The arrow (from arrow_begin to arrow_end) will be first clipped + # by patchA and patchB, then shrunk by shrinkA and shrinkB (in + # points). If patch A is not set, self.bbox_patch is used. + self.arrow_patch.set_positions(arrow_begin, arrow_end) + + if "mutation_scale" in self.arrowprops: + mutation_scale = renderer.points_to_pixels( + self.arrowprops["mutation_scale"]) + # Else, use fontsize-based mutation_scale defined above. + self.arrow_patch.set_mutation_scale(mutation_scale) + + patchA = self.arrowprops.get("patchA", self.patch) + self.arrow_patch.set_patchA(patchA) + + def draw(self, renderer): + # docstring inherited + if not self.get_visible() or not self._check_xy(renderer): + return + renderer.open_group(self.__class__.__name__, gid=self.get_gid()) + self.update_positions(renderer) + if self.arrow_patch is not None: + if self.arrow_patch.figure is None and self.figure is not None: + self.arrow_patch.figure = self.figure + self.arrow_patch.draw(renderer) + self.patch.draw(renderer) + self.offsetbox.draw(renderer) + renderer.close_group(self.__class__.__name__) + self.stale = False + + +class DraggableBase: + """ + Helper base class for a draggable artist (legend, offsetbox). + + Derived classes must override the following methods:: + + def save_offset(self): + ''' + Called when the object is picked for dragging; should save the + reference position of the artist. + ''' + + def update_offset(self, dx, dy): + ''' + Called during the dragging; (*dx*, *dy*) is the pixel offset from + the point where the mouse drag started. + ''' + + Optionally, you may override the following method:: + + def finalize_offset(self): + '''Called when the mouse is released.''' + + In the current implementation of `.DraggableLegend` and + `DraggableAnnotation`, `update_offset` places the artists in display + coordinates, and `finalize_offset` recalculates their position in axes + coordinate and set a relevant attribute. + """ + + def __init__(self, ref_artist, use_blit=False): + self.ref_artist = ref_artist + if not ref_artist.pickable(): + ref_artist.set_picker(True) + self.got_artist = False + self._use_blit = use_blit and self.canvas.supports_blit + callbacks = self.canvas.callbacks + self._disconnectors = [ + functools.partial( + callbacks.disconnect, callbacks._connect_picklable(name, func)) + for name, func in [ + ("pick_event", self.on_pick), + ("button_release_event", self.on_release), + ("motion_notify_event", self.on_motion), + ] + ] + + # A property, not an attribute, to maintain picklability. + canvas = property(lambda self: self.ref_artist.figure.canvas) + cids = property(lambda self: [ + disconnect.args[0] for disconnect in self._disconnectors[:2]]) + + def on_motion(self, evt): + if self._check_still_parented() and self.got_artist: + dx = evt.x - self.mouse_x + dy = evt.y - self.mouse_y + self.update_offset(dx, dy) + if self._use_blit: + self.canvas.restore_region(self.background) + self.ref_artist.draw( + self.ref_artist.figure._get_renderer()) + self.canvas.blit() + else: + self.canvas.draw() + + def on_pick(self, evt): + if self._check_still_parented() and evt.artist == self.ref_artist: + self.mouse_x = evt.mouseevent.x + self.mouse_y = evt.mouseevent.y + self.got_artist = True + if self._use_blit: + self.ref_artist.set_animated(True) + self.canvas.draw() + self.background = \ + self.canvas.copy_from_bbox(self.ref_artist.figure.bbox) + self.ref_artist.draw( + self.ref_artist.figure._get_renderer()) + self.canvas.blit() + self.save_offset() + + def on_release(self, event): + if self._check_still_parented() and self.got_artist: + self.finalize_offset() + self.got_artist = False + if self._use_blit: + self.ref_artist.set_animated(False) + + def _check_still_parented(self): + if self.ref_artist.figure is None: + self.disconnect() + return False + else: + return True + + def disconnect(self): + """Disconnect the callbacks.""" + for disconnector in self._disconnectors: + disconnector() + + def save_offset(self): + pass + + def update_offset(self, dx, dy): + pass + + def finalize_offset(self): + pass + + +class DraggableOffsetBox(DraggableBase): + def __init__(self, ref_artist, offsetbox, use_blit=False): + super().__init__(ref_artist, use_blit=use_blit) + self.offsetbox = offsetbox + + def save_offset(self): + offsetbox = self.offsetbox + renderer = offsetbox.figure._get_renderer() + offset = offsetbox.get_offset(offsetbox.get_bbox(renderer), renderer) + self.offsetbox_x, self.offsetbox_y = offset + self.offsetbox.set_offset(offset) + + def update_offset(self, dx, dy): + loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy + self.offsetbox.set_offset(loc_in_canvas) + + def get_loc_in_canvas(self): + offsetbox = self.offsetbox + renderer = offsetbox.figure._get_renderer() + bbox = offsetbox.get_bbox(renderer) + ox, oy = offsetbox._offset + loc_in_canvas = (ox + bbox.x0, oy + bbox.y0) + return loc_in_canvas + + +class DraggableAnnotation(DraggableBase): + def __init__(self, annotation, use_blit=False): + super().__init__(annotation, use_blit=use_blit) + self.annotation = annotation + + def save_offset(self): + ann = self.annotation + self.ox, self.oy = ann.get_transform().transform(ann.xyann) + + def update_offset(self, dx, dy): + ann = self.annotation + ann.xyann = ann.get_transform().inverted().transform( + (self.ox + dx, self.oy + dy)) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/patches.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/patches.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f6c9ddf75839dbbc484fc5c613776418d0f5cada --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/patches.pyi @@ -0,0 +1,755 @@ +from . import artist +from .axes import Axes +from .backend_bases import RendererBase, MouseEvent +from .path import Path +from .transforms import Transform, Bbox + +from typing import Any, Literal, overload + +import numpy as np +from numpy.typing import ArrayLike +from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType + +class Patch(artist.Artist): + zorder: float + def __init__( + self, + *, + edgecolor: ColorType | None = ..., + facecolor: ColorType | None = ..., + color: ColorType | None = ..., + linewidth: float | None = ..., + linestyle: LineStyleType | None = ..., + antialiased: bool | None = ..., + hatch: str | None = ..., + fill: bool = ..., + capstyle: CapStyleType | None = ..., + joinstyle: JoinStyleType | None = ..., + **kwargs, + ) -> None: ... + def get_verts(self) -> ArrayLike: ... + def contains(self, mouseevent: MouseEvent, radius: float | None = None) -> tuple[bool, dict[Any, Any]]: ... + def contains_point( + self, point: tuple[float, float], radius: float | None = ... + ) -> bool: ... + def contains_points( + self, points: ArrayLike, radius: float | None = ... + ) -> np.ndarray: ... + def get_extents(self) -> Bbox: ... + def get_transform(self) -> Transform: ... + def get_data_transform(self) -> Transform: ... + def get_patch_transform(self) -> Transform: ... + def get_antialiased(self) -> bool: ... + def get_edgecolor(self) -> ColorType: ... + def get_facecolor(self) -> ColorType: ... + def get_linewidth(self) -> float: ... + def get_linestyle(self) -> LineStyleType: ... + def set_antialiased(self, aa: bool | None) -> None: ... + def set_edgecolor(self, color: ColorType | None) -> None: ... + def set_facecolor(self, color: ColorType | None) -> None: ... + def set_color(self, c: ColorType | None) -> None: ... + def set_alpha(self, alpha: float | None) -> None: ... + def set_linewidth(self, w: float | None) -> None: ... + def set_linestyle(self, ls: LineStyleType | None) -> None: ... + def set_fill(self, b: bool) -> None: ... + def get_fill(self) -> bool: ... + fill = property(get_fill, set_fill) + def set_capstyle(self, s: CapStyleType) -> None: ... + def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ... + def set_joinstyle(self, s: JoinStyleType) -> None: ... + def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... + def set_hatch(self, hatch: str) -> None: ... + def get_hatch(self) -> str: ... + def get_path(self) -> Path: ... + +class Shadow(Patch): + patch: Patch + def __init__(self, patch: Patch, ox: float, oy: float, *, shade: float = ..., **kwargs) -> None: ... + +class Rectangle(Patch): + angle: float + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + *, + angle: float = ..., + rotation_point: Literal["xy", "center"] | tuple[float, float] = ..., + **kwargs, + ) -> None: ... + @property + def rotation_point(self) -> Literal["xy", "center"] | tuple[float, float]: ... + @rotation_point.setter + def rotation_point( + self, value: Literal["xy", "center"] | tuple[float, float] + ) -> None: ... + def get_x(self) -> float: ... + def get_y(self) -> float: ... + def get_xy(self) -> tuple[float, float]: ... + def get_corners(self) -> np.ndarray: ... + def get_center(self) -> np.ndarray: ... + def get_width(self) -> float: ... + def get_height(self) -> float: ... + def get_angle(self) -> float: ... + def set_x(self, x: float) -> None: ... + def set_y(self, y: float) -> None: ... + def set_angle(self, angle: float) -> None: ... + def set_xy(self, xy: tuple[float, float]) -> None: ... + def set_width(self, w: float) -> None: ... + def set_height(self, h: float) -> None: ... + @overload + def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ... + @overload + def set_bounds( + self, left: float, bottom: float, width: float, height: float, / + ) -> None: ... + def get_bbox(self) -> Bbox: ... + xy = property(get_xy, set_xy) + +class RegularPolygon(Patch): + xy: tuple[float, float] + numvertices: int + orientation: float + radius: float + def __init__( + self, + xy: tuple[float, float], + numVertices: int, + *, + radius: float = ..., + orientation: float = ..., + **kwargs, + ) -> None: ... + +class PathPatch(Patch): + def __init__(self, path: Path, **kwargs) -> None: ... + def set_path(self, path: Path) -> None: ... + +class StepPatch(PathPatch): + orientation: Literal["vertical", "horizontal"] + def __init__( + self, + values: ArrayLike, + edges: ArrayLike, + *, + orientation: Literal["vertical", "horizontal"] = ..., + baseline: float = ..., + **kwargs, + ) -> None: ... + + # NamedTuple StairData, defined in body of method + def get_data(self) -> tuple[np.ndarray, np.ndarray, float]: ... + def set_data( + self, + values: ArrayLike | None = ..., + edges: ArrayLike | None = ..., + baseline: float | None = ..., + ) -> None: ... + +class Polygon(Patch): + def __init__(self, xy: ArrayLike, *, closed: bool = ..., **kwargs) -> None: ... + def get_closed(self) -> bool: ... + def set_closed(self, closed: bool) -> None: ... + def get_xy(self) -> np.ndarray: ... + def set_xy(self, xy: ArrayLike) -> None: ... + xy = property(get_xy, set_xy) + +class Wedge(Patch): + center: tuple[float, float] + r: float + theta1: float + theta2: float + width: float | None + def __init__( + self, + center: tuple[float, float], + r: float, + theta1: float, + theta2: float, + *, + width: float | None = ..., + **kwargs, + ) -> None: ... + def set_center(self, center: tuple[float, float]) -> None: ... + def set_radius(self, radius: float) -> None: ... + def set_theta1(self, theta1: float) -> None: ... + def set_theta2(self, theta2: float) -> None: ... + def set_width(self, width: float | None) -> None: ... + +class Arrow(Patch): + def __init__( + self, x: float, y: float, dx: float, dy: float, *, width: float = ..., **kwargs + ) -> None: ... + def set_data( + self, + x: float | None = ..., + y: float | None = ..., + dx: float | None = ..., + dy: float | None = ..., + width: float | None = ..., + ) -> None: ... +class FancyArrow(Polygon): + def __init__( + self, + x: float, + y: float, + dx: float, + dy: float, + *, + width: float = ..., + length_includes_head: bool = ..., + head_width: float | None = ..., + head_length: float | None = ..., + shape: Literal["full", "left", "right"] = ..., + overhang: float = ..., + head_starts_at_zero: bool = ..., + **kwargs, + ) -> None: ... + def set_data( + self, + *, + x: float | None = ..., + y: float | None = ..., + dx: float | None = ..., + dy: float | None = ..., + width: float | None = ..., + head_width: float | None = ..., + head_length: float | None = ..., + ) -> None: ... + +class CirclePolygon(RegularPolygon): + def __init__( + self, + xy: tuple[float, float], + radius: float = ..., + *, + resolution: int = ..., + **kwargs, + ) -> None: ... + +class Ellipse(Patch): + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + *, + angle: float = ..., + **kwargs, + ) -> None: ... + def set_center(self, xy: tuple[float, float]) -> None: ... + def get_center(self) -> float: ... + center = property(get_center, set_center) + + def set_width(self, width: float) -> None: ... + def get_width(self) -> float: ... + width = property(get_width, set_width) + + def set_height(self, height: float) -> None: ... + def get_height(self) -> float: ... + height = property(get_height, set_height) + + def set_angle(self, angle: float) -> None: ... + def get_angle(self) -> float: ... + angle = property(get_angle, set_angle) + + def get_corners(self) -> np.ndarray: ... + + def get_vertices(self) -> list[tuple[float, float]]: ... + def get_co_vertices(self) -> list[tuple[float, float]]: ... + + +class Annulus(Patch): + a: float + b: float + def __init__( + self, + xy: tuple[float, float], + r: float | tuple[float, float], + width: float, + angle: float = ..., + **kwargs, + ) -> None: ... + def set_center(self, xy: tuple[float, float]) -> None: ... + def get_center(self) -> tuple[float, float]: ... + center = property(get_center, set_center) + + def set_width(self, width: float) -> None: ... + def get_width(self) -> float: ... + width = property(get_width, set_width) + + def set_angle(self, angle: float) -> None: ... + def get_angle(self) -> float: ... + angle = property(get_angle, set_angle) + + def set_semimajor(self, a: float) -> None: ... + def set_semiminor(self, b: float) -> None: ... + def set_radii(self, r: float | tuple[float, float]) -> None: ... + def get_radii(self) -> tuple[float, float]: ... + radii = property(get_radii, set_radii) + +class Circle(Ellipse): + def __init__( + self, xy: tuple[float, float], radius: float = ..., **kwargs + ) -> None: ... + def set_radius(self, radius: float) -> None: ... + def get_radius(self) -> float: ... + radius = property(get_radius, set_radius) + +class Arc(Ellipse): + theta1: float + theta2: float + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + *, + angle: float = ..., + theta1: float = ..., + theta2: float = ..., + **kwargs, + ) -> None: ... + +def bbox_artist( + artist: artist.Artist, + renderer: RendererBase, + props: dict[str, Any] | None = ..., + fill: bool = ..., +) -> None: ... +def draw_bbox( + bbox: Bbox, + renderer: RendererBase, + color: ColorType = ..., + trans: Transform | None = ..., +) -> None: ... + +class _Style: + def __new__(cls, stylename, **kwargs): ... + @classmethod + def get_styles(cls) -> dict[str, type]: ... + @classmethod + def pprint_styles(cls) -> str: ... + @classmethod + def register(cls, name: str, style: type) -> None: ... + +class BoxStyle(_Style): + class Square(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Circle(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Ellipse(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class LArrow(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class RArrow(LArrow): + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class DArrow(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Round(BoxStyle): + pad: float + rounding_size: float | None + def __init__( + self, pad: float = ..., rounding_size: float | None = ... + ) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Round4(BoxStyle): + pad: float + rounding_size: float | None + def __init__( + self, pad: float = ..., rounding_size: float | None = ... + ) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Sawtooth(BoxStyle): + pad: float + tooth_size: float | None + def __init__( + self, pad: float = ..., tooth_size: float | None = ... + ) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Roundtooth(Sawtooth): + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + +class ConnectionStyle(_Style): + class _Base(ConnectionStyle): + def __call__( + self, + posA: tuple[float, float], + posB: tuple[float, float], + shrinkA: float = ..., + shrinkB: float = ..., + patchA: Patch | None = ..., + patchB: Patch | None = ..., + ) -> Path: ... + + class Arc3(_Base): + rad: float + def __init__(self, rad: float = ...) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Angle3(_Base): + angleA: float + angleB: float + def __init__(self, angleA: float = ..., angleB: float = ...) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Angle(_Base): + angleA: float + angleB: float + rad: float + def __init__( + self, angleA: float = ..., angleB: float = ..., rad: float = ... + ) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Arc(_Base): + angleA: float + angleB: float + armA: float | None + armB: float | None + rad: float + def __init__( + self, + angleA: float = ..., + angleB: float = ..., + armA: float | None = ..., + armB: float | None = ..., + rad: float = ..., + ) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Bar(_Base): + armA: float + armB: float + fraction: float + angle: float | None + def __init__( + self, + armA: float = ..., + armB: float = ..., + fraction: float = ..., + angle: float | None = ..., + ) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + +class ArrowStyle(_Style): + class _Base(ArrowStyle): + @staticmethod + def ensure_quadratic_bezier(path: Path) -> list[float]: ... + def transmute( + self, path: Path, mutation_size: float, linewidth: float + ) -> tuple[Path, bool]: ... + def __call__( + self, + path: Path, + mutation_size: float, + linewidth: float, + aspect_ratio: float = ..., + ) -> tuple[Path, bool]: ... + + class _Curve(_Base): + arrow: str + fillbegin: bool + fillend: bool + def __init__( + self, + head_length: float = ..., + head_width: float = ..., + widthA: float = ..., + widthB: float = ..., + lengthA: float = ..., + lengthB: float = ..., + angleA: float | None = ..., + angleB: float | None = ..., + scaleA: float | None = ..., + scaleB: float | None = ..., + ) -> None: ... + + class Curve(_Curve): + def __init__(self) -> None: ... + + class CurveA(_Curve): + arrow: str + + class CurveB(_Curve): + arrow: str + + class CurveAB(_Curve): + arrow: str + + class CurveFilledA(_Curve): + arrow: str + + class CurveFilledB(_Curve): + arrow: str + + class CurveFilledAB(_Curve): + arrow: str + + class BracketA(_Curve): + arrow: str + def __init__( + self, widthA: float = ..., lengthA: float = ..., angleA: float = ... + ) -> None: ... + + class BracketB(_Curve): + arrow: str + def __init__( + self, widthB: float = ..., lengthB: float = ..., angleB: float = ... + ) -> None: ... + + class BracketAB(_Curve): + arrow: str + def __init__( + self, + widthA: float = ..., + lengthA: float = ..., + angleA: float = ..., + widthB: float = ..., + lengthB: float = ..., + angleB: float = ..., + ) -> None: ... + + class BarAB(_Curve): + arrow: str + def __init__( + self, + widthA: float = ..., + angleA: float = ..., + widthB: float = ..., + angleB: float = ..., + ) -> None: ... + + class BracketCurve(_Curve): + arrow: str + def __init__( + self, widthA: float = ..., lengthA: float = ..., angleA: float | None = ... + ) -> None: ... + + class CurveBracket(_Curve): + arrow: str + def __init__( + self, widthB: float = ..., lengthB: float = ..., angleB: float | None = ... + ) -> None: ... + + class Simple(_Base): + def __init__( + self, + head_length: float = ..., + head_width: float = ..., + tail_width: float = ..., + ) -> None: ... + + class Fancy(_Base): + def __init__( + self, + head_length: float = ..., + head_width: float = ..., + tail_width: float = ..., + ) -> None: ... + + class Wedge(_Base): + tail_width: float + shrink_factor: float + def __init__( + self, tail_width: float = ..., shrink_factor: float = ... + ) -> None: ... + +class FancyBboxPatch(Patch): + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + boxstyle: str | BoxStyle = ..., + *, + mutation_scale: float = ..., + mutation_aspect: float = ..., + **kwargs, + ) -> None: ... + def set_boxstyle(self, boxstyle: str | BoxStyle | None = ..., **kwargs) -> None: ... + def get_boxstyle(self) -> BoxStyle: ... + def set_mutation_scale(self, scale: float) -> None: ... + def get_mutation_scale(self) -> float: ... + def set_mutation_aspect(self, aspect: float) -> None: ... + def get_mutation_aspect(self) -> float: ... + def get_x(self) -> float: ... + def get_y(self) -> float: ... + def get_width(self) -> float: ... + def get_height(self) -> float: ... + def set_x(self, x: float) -> None: ... + def set_y(self, y: float) -> None: ... + def set_width(self, w: float) -> None: ... + def set_height(self, h: float) -> None: ... + @overload + def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ... + @overload + def set_bounds( + self, left: float, bottom: float, width: float, height: float, / + ) -> None: ... + def get_bbox(self) -> Bbox: ... + +class FancyArrowPatch(Patch): + patchA: Patch + patchB: Patch + shrinkA: float + shrinkB: float + def __init__( + self, + posA: tuple[float, float] | None = ..., + posB: tuple[float, float] | None = ..., + *, + path: Path | None = ..., + arrowstyle: str | ArrowStyle = ..., + connectionstyle: str | ConnectionStyle = ..., + patchA: Patch | None = ..., + patchB: Patch | None = ..., + shrinkA: float = ..., + shrinkB: float = ..., + mutation_scale: float = ..., + mutation_aspect: float | None = ..., + **kwargs, + ) -> None: ... + def set_positions( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> None: ... + def set_patchA(self, patchA: Patch) -> None: ... + def set_patchB(self, patchB: Patch) -> None: ... + def set_connectionstyle(self, connectionstyle: str | ConnectionStyle | None = ..., **kwargs) -> None: ... + def get_connectionstyle(self) -> ConnectionStyle: ... + def set_arrowstyle(self, arrowstyle: str | ArrowStyle | None = ..., **kwargs) -> None: ... + def get_arrowstyle(self) -> ArrowStyle: ... + def set_mutation_scale(self, scale: float) -> None: ... + def get_mutation_scale(self) -> float: ... + def set_mutation_aspect(self, aspect: float | None) -> None: ... + def get_mutation_aspect(self) -> float: ... + +class ConnectionPatch(FancyArrowPatch): + xy1: tuple[float, float] + xy2: tuple[float, float] + coords1: str | Transform + coords2: str | Transform | None + axesA: Axes | None + axesB: Axes | None + def __init__( + self, + xyA: tuple[float, float], + xyB: tuple[float, float], + coordsA: str | Transform, + coordsB: str | Transform | None = ..., + *, + axesA: Axes | None = ..., + axesB: Axes | None = ..., + arrowstyle: str | ArrowStyle = ..., + connectionstyle: str | ConnectionStyle = ..., + patchA: Patch | None = ..., + patchB: Patch | None = ..., + shrinkA: float = ..., + shrinkB: float = ..., + mutation_scale: float = ..., + mutation_aspect: float | None = ..., + clip_on: bool = ..., + **kwargs, + ) -> None: ... + def set_annotation_clip(self, b: bool | None) -> None: ... + def get_annotation_clip(self) -> bool | None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/path.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/path.pyi new file mode 100644 index 0000000000000000000000000000000000000000..464fc6d9a912e359d1deb0f3bb71a8ac349cfb6a --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/path.pyi @@ -0,0 +1,140 @@ +from .bezier import BezierSegment +from .transforms import Affine2D, Transform, Bbox +from collections.abc import Generator, Iterable, Sequence + +import numpy as np +from numpy.typing import ArrayLike + +from typing import Any, overload + +class Path: + code_type: type[np.uint8] + STOP: np.uint8 + MOVETO: np.uint8 + LINETO: np.uint8 + CURVE3: np.uint8 + CURVE4: np.uint8 + CLOSEPOLY: np.uint8 + NUM_VERTICES_FOR_CODE: dict[np.uint8, int] + + def __init__( + self, + vertices: ArrayLike, + codes: ArrayLike | None = ..., + _interpolation_steps: int = ..., + closed: bool = ..., + readonly: bool = ..., + ) -> None: ... + @property + def vertices(self) -> ArrayLike: ... + @vertices.setter + def vertices(self, vertices: ArrayLike) -> None: ... + @property + def codes(self) -> ArrayLike | None: ... + @codes.setter + def codes(self, codes: ArrayLike) -> None: ... + @property + def simplify_threshold(self) -> float: ... + @simplify_threshold.setter + def simplify_threshold(self, threshold: float) -> None: ... + @property + def should_simplify(self) -> bool: ... + @should_simplify.setter + def should_simplify(self, should_simplify: bool) -> None: ... + @property + def readonly(self) -> bool: ... + def copy(self) -> Path: ... + def __deepcopy__(self, memo: dict[int, Any] | None = ...) -> Path: ... + deepcopy = __deepcopy__ + + @classmethod + def make_compound_path_from_polys(cls, XY: ArrayLike) -> Path: ... + @classmethod + def make_compound_path(cls, *args: Path) -> Path: ... + def __len__(self) -> int: ... + def iter_segments( + self, + transform: Transform | None = ..., + remove_nans: bool = ..., + clip: tuple[float, float, float, float] | None = ..., + snap: bool | None = ..., + stroke_width: float = ..., + simplify: bool | None = ..., + curves: bool = ..., + sketch: tuple[float, float, float] | None = ..., + ) -> Generator[tuple[np.ndarray, np.uint8], None, None]: ... + def iter_bezier(self, **kwargs) -> Generator[BezierSegment, None, None]: ... + def cleaned( + self, + transform: Transform | None = ..., + remove_nans: bool = ..., + clip: tuple[float, float, float, float] | None = ..., + *, + simplify: bool | None = ..., + curves: bool = ..., + stroke_width: float = ..., + snap: bool | None = ..., + sketch: tuple[float, float, float] | None = ... + ) -> Path: ... + def transformed(self, transform: Transform) -> Path: ... + def contains_point( + self, + point: tuple[float, float], + transform: Transform | None = ..., + radius: float = ..., + ) -> bool: ... + def contains_points( + self, points: ArrayLike, transform: Transform | None = ..., radius: float = ... + ) -> np.ndarray: ... + def contains_path(self, path: Path, transform: Transform | None = ...) -> bool: ... + def get_extents(self, transform: Transform | None = ..., **kwargs) -> Bbox: ... + def intersects_path(self, other: Path, filled: bool = ...) -> bool: ... + def intersects_bbox(self, bbox: Bbox, filled: bool = ...) -> bool: ... + def interpolated(self, steps: int) -> Path: ... + def to_polygons( + self, + transform: Transform | None = ..., + width: float = ..., + height: float = ..., + closed_only: bool = ..., + ) -> list[ArrayLike]: ... + @classmethod + def unit_rectangle(cls) -> Path: ... + @classmethod + def unit_regular_polygon(cls, numVertices: int) -> Path: ... + @classmethod + def unit_regular_star(cls, numVertices: int, innerCircle: float = ...) -> Path: ... + @classmethod + def unit_regular_asterisk(cls, numVertices: int) -> Path: ... + @classmethod + def unit_circle(cls) -> Path: ... + @classmethod + def circle( + cls, + center: tuple[float, float] = ..., + radius: float = ..., + readonly: bool = ..., + ) -> Path: ... + @classmethod + def unit_circle_righthalf(cls) -> Path: ... + @classmethod + def arc( + cls, theta1: float, theta2: float, n: int | None = ..., is_wedge: bool = ... + ) -> Path: ... + @classmethod + def wedge(cls, theta1: float, theta2: float, n: int | None = ...) -> Path: ... + @overload + @staticmethod + def hatch(hatchpattern: str, density: float = ...) -> Path: ... + @overload + @staticmethod + def hatch(hatchpattern: None, density: float = ...) -> None: ... + def clip_to_bbox(self, bbox: Bbox, inside: bool = ...) -> Path: ... + +def get_path_collection_extents( + master_transform: Transform, + paths: Sequence[Path], + transforms: Iterable[Affine2D], + offsets: ArrayLike, + offset_transform: Affine2D, +) -> Bbox: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/py.typed b/llava_next/lib/python3.10/site-packages/matplotlib/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/pyplot.py b/llava_next/lib/python3.10/site-packages/matplotlib/pyplot.py new file mode 100644 index 0000000000000000000000000000000000000000..442013f7d21a88b5f549bd17249304bc6da57424 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/pyplot.py @@ -0,0 +1,4597 @@ +# Note: The first part of this file can be modified in place, but the latter +# part is autogenerated by the boilerplate.py script. + +""" +`matplotlib.pyplot` is a state-based interface to matplotlib. It provides +an implicit, MATLAB-like, way of plotting. It also opens figures on your +screen, and acts as the figure GUI manager. + +pyplot is mainly intended for interactive plots and simple cases of +programmatic plot generation:: + + import numpy as np + import matplotlib.pyplot as plt + + x = np.arange(0, 5, 0.1) + y = np.sin(x) + plt.plot(x, y) + +The explicit object-oriented API is recommended for complex plots, though +pyplot is still usually used to create the figure and often the Axes in the +figure. See `.pyplot.figure`, `.pyplot.subplots`, and +`.pyplot.subplot_mosaic` to create figures, and +:doc:`Axes API ` for the plotting methods on an Axes:: + + import numpy as np + import matplotlib.pyplot as plt + + x = np.arange(0, 5, 0.1) + y = np.sin(x) + fig, ax = plt.subplots() + ax.plot(x, y) + + +See :ref:`api_interfaces` for an explanation of the tradeoffs between the +implicit and explicit interfaces. +""" + +# fmt: off + +from __future__ import annotations + +from contextlib import AbstractContextManager, ExitStack +from enum import Enum +import functools +import importlib +import inspect +import logging +import sys +import threading +import time +from typing import TYPE_CHECKING, cast, overload + +from cycler import cycler # noqa: F401 +import matplotlib +import matplotlib.colorbar +import matplotlib.image +from matplotlib import _api +from matplotlib import ( # noqa: F401 Re-exported for typing. + cm as cm, get_backend as get_backend, rcParams as rcParams, style as style) +from matplotlib import _pylab_helpers +from matplotlib import interactive # noqa: F401 +from matplotlib import cbook +from matplotlib import _docstring +from matplotlib.backend_bases import ( + FigureCanvasBase, FigureManagerBase, MouseButton) +from matplotlib.figure import Figure, FigureBase, figaspect +from matplotlib.gridspec import GridSpec, SubplotSpec +from matplotlib import rcsetup, rcParamsDefault, rcParamsOrig +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.axes import Subplot # noqa: F401 +from matplotlib.backends import BackendFilter, backend_registry +from matplotlib.projections import PolarAxes +from matplotlib import mlab # for detrend_none, window_hanning +from matplotlib.scale import get_scale_names # noqa: F401 + +from matplotlib.cm import _colormaps +from matplotlib.colors import _color_sequences, Colormap + +import numpy as np + +if TYPE_CHECKING: + from collections.abc import Callable, Hashable, Iterable, Sequence + import datetime + import pathlib + import os + from typing import Any, BinaryIO, Literal, TypeVar + from typing_extensions import ParamSpec + + import PIL.Image + from numpy.typing import ArrayLike + + import matplotlib.axes + import matplotlib.artist + import matplotlib.backend_bases + from matplotlib.axis import Tick + from matplotlib.axes._base import _AxesBase + from matplotlib.backend_bases import RendererBase, Event + from matplotlib.cm import ScalarMappable + from matplotlib.contour import ContourSet, QuadContourSet + from matplotlib.collections import ( + Collection, + LineCollection, + PolyCollection, + PathCollection, + EventCollection, + QuadMesh, + ) + from matplotlib.colorbar import Colorbar + from matplotlib.container import ( + BarContainer, + ErrorbarContainer, + StemContainer, + ) + from matplotlib.figure import SubFigure + from matplotlib.legend import Legend + from matplotlib.mlab import GaussianKDE + from matplotlib.image import AxesImage, FigureImage + from matplotlib.patches import FancyArrow, StepPatch, Wedge + from matplotlib.quiver import Barbs, Quiver, QuiverKey + from matplotlib.scale import ScaleBase + from matplotlib.transforms import Transform, Bbox + from matplotlib.typing import ColorType, LineStyleType, MarkerType, HashableList + from matplotlib.widgets import SubplotTool + + _P = ParamSpec('_P') + _R = TypeVar('_R') + _T = TypeVar('_T') + + +# We may not need the following imports here: +from matplotlib.colors import Normalize +from matplotlib.lines import Line2D, AxLine +from matplotlib.text import Text, Annotation +from matplotlib.patches import Arrow, Circle, Rectangle # noqa: F401 +from matplotlib.patches import Polygon +from matplotlib.widgets import Button, Slider, Widget # noqa: F401 + +from .ticker import ( # noqa: F401 + TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter, + FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent, + LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator, + LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator) + +_log = logging.getLogger(__name__) + + +# Explicit rename instead of import-as for typing's sake. +colormaps = _colormaps +color_sequences = _color_sequences + + +@overload +def _copy_docstring_and_deprecators( + method: Any, + func: Literal[None] = None +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... + + +@overload +def _copy_docstring_and_deprecators( + method: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def _copy_docstring_and_deprecators( + method: Any, + func: Callable[_P, _R] | None = None +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[_P, _R]: + if func is None: + return cast('Callable[[Callable[_P, _R]], Callable[_P, _R]]', + functools.partial(_copy_docstring_and_deprecators, method)) + decorators: list[Callable[[Callable[_P, _R]], Callable[_P, _R]]] = [ + _docstring.copy(method) + ] + # Check whether the definition of *method* includes @_api.rename_parameter + # or @_api.make_keyword_only decorators; if so, propagate them to the + # pyplot wrapper as well. + while hasattr(method, "__wrapped__"): + potential_decorator = _api.deprecation.DECORATORS.get(method) + if potential_decorator: + decorators.append(potential_decorator) + method = method.__wrapped__ + for decorator in decorators[::-1]: + func = decorator(func) + _add_pyplot_note(func, method) + return func + + +_NO_PYPLOT_NOTE = [ + 'FigureBase._gci', # wrapped_func is private + '_AxesBase._sci', # wrapped_func is private + 'Artist.findobj', # not a standard pyplot wrapper because it does not operate + # on the current Figure / Axes. Explanation of relation would + # be more complex and is not too important. +] + + +def _add_pyplot_note(func, wrapped_func): + """ + Add a note to the docstring of *func* that it is a pyplot wrapper. + + The note is added to the "Notes" section of the docstring. If that does + not exist, a "Notes" section is created. In numpydoc, the "Notes" + section is the third last possible section, only potentially followed by + "References" and "Examples". + """ + if not func.__doc__: + return # nothing to do + + qualname = wrapped_func.__qualname__ + if qualname in _NO_PYPLOT_NOTE: + return + + wrapped_func_is_method = True + if "." not in qualname: + # method qualnames are prefixed by the class and ".", e.g. "Axes.plot" + wrapped_func_is_method = False + link = f"{wrapped_func.__module__}.{qualname}" + elif qualname.startswith("Axes."): # e.g. "Axes.plot" + link = ".axes." + qualname + elif qualname.startswith("_AxesBase."): # e.g. "_AxesBase.set_xlabel" + link = ".axes.Axes" + qualname[9:] + elif qualname.startswith("Figure."): # e.g. "Figure.figimage" + link = "." + qualname + elif qualname.startswith("FigureBase."): # e.g. "FigureBase.gca" + link = ".Figure" + qualname[10:] + elif qualname.startswith("FigureCanvasBase."): # "FigureBaseCanvas.mpl_connect" + link = "." + qualname + else: + raise RuntimeError(f"Wrapped method from unexpected class: {qualname}") + + if wrapped_func_is_method: + message = f"This is the :ref:`pyplot wrapper ` for `{link}`." + else: + message = f"This is equivalent to `{link}`." + + # Find the correct insert position: + # - either we already have a "Notes" section into which we can insert + # - or we create one before the next present section. Note that in numpydoc, the + # "Notes" section is the third last possible section, only potentially followed + # by "References" and "Examples". + # - or we append a new "Notes" section at the end. + doc = inspect.cleandoc(func.__doc__) + if "\nNotes\n-----" in doc: + before, after = doc.split("\nNotes\n-----", 1) + elif (index := doc.find("\nReferences\n----------")) != -1: + before, after = doc[:index], doc[index:] + elif (index := doc.find("\nExamples\n--------")) != -1: + before, after = doc[:index], doc[index:] + else: + # No "Notes", "References", or "Examples" --> append to the end. + before = doc + "\n" + after = "" + + func.__doc__ = f"{before}\nNotes\n-----\n\n.. note::\n\n {message}\n{after}" + + +## Global ## + + +# The state controlled by {,un}install_repl_displayhook(). +_ReplDisplayHook = Enum("_ReplDisplayHook", ["NONE", "PLAIN", "IPYTHON"]) +_REPL_DISPLAYHOOK = _ReplDisplayHook.NONE + + +def _draw_all_if_interactive() -> None: + if matplotlib.is_interactive(): + draw_all() + + +def install_repl_displayhook() -> None: + """ + Connect to the display hook of the current shell. + + The display hook gets called when the read-evaluate-print-loop (REPL) of + the shell has finished the execution of a command. We use this callback + to be able to automatically update a figure in interactive mode. + + This works both with IPython and with vanilla python shells. + """ + global _REPL_DISPLAYHOOK + + if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON: + return + + # See if we have IPython hooks around, if so use them. + # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as + # entries can also have been explicitly set to None. + mod_ipython = sys.modules.get("IPython") + if not mod_ipython: + _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN + return + ip = mod_ipython.get_ipython() + if not ip: + _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN + return + + ip.events.register("post_execute", _draw_all_if_interactive) + _REPL_DISPLAYHOOK = _ReplDisplayHook.IPYTHON + + if mod_ipython.version_info[:2] < (8, 24): + # Use of backend2gui is not needed for IPython >= 8.24 as that functionality + # has been moved to Matplotlib. + # This code can be removed when Python 3.12, the latest version supported by + # IPython < 8.24, reaches end-of-life in late 2028. + from IPython.core.pylabtools import backend2gui + ipython_gui_name = backend2gui.get(get_backend()) + else: + _, ipython_gui_name = backend_registry.resolve_backend(get_backend()) + # trigger IPython's eventloop integration, if available + if ipython_gui_name: + ip.enable_gui(ipython_gui_name) + + +def uninstall_repl_displayhook() -> None: + """Disconnect from the display hook of the current shell.""" + global _REPL_DISPLAYHOOK + if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON: + from IPython import get_ipython + ip = get_ipython() + ip.events.unregister("post_execute", _draw_all_if_interactive) + _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE + + +draw_all = _pylab_helpers.Gcf.draw_all + + +# Ensure this appears in the pyplot docs. +@_copy_docstring_and_deprecators(matplotlib.set_loglevel) +def set_loglevel(*args, **kwargs) -> None: + return matplotlib.set_loglevel(*args, **kwargs) + + +@_copy_docstring_and_deprecators(Artist.findobj) +def findobj( + o: Artist | None = None, + match: Callable[[Artist], bool] | type[Artist] | None = None, + include_self: bool = True +) -> list[Artist]: + if o is None: + o = gcf() + return o.findobj(match, include_self=include_self) + + +_backend_mod: type[matplotlib.backend_bases._Backend] | None = None + + +def _get_backend_mod() -> type[matplotlib.backend_bases._Backend]: + """ + Ensure that a backend is selected and return it. + + This is currently private, but may be made public in the future. + """ + if _backend_mod is None: + # Use rcParams._get("backend") to avoid going through the fallback + # logic (which will (re)import pyplot and then call switch_backend if + # we need to resolve the auto sentinel) + switch_backend(rcParams._get("backend")) + return cast(type[matplotlib.backend_bases._Backend], _backend_mod) + + +def switch_backend(newbackend: str) -> None: + """ + Set the pyplot backend. + + Switching to an interactive backend is possible only if no event loop for + another interactive backend has started. Switching to and from + non-interactive backends is always possible. + + If the new backend is different than the current backend then all open + Figures will be closed via ``plt.close('all')``. + + Parameters + ---------- + newbackend : str + The case-insensitive name of the backend to use. + + """ + global _backend_mod + # make sure the init is pulled up so we can assign to it later + import matplotlib.backends + + if newbackend is rcsetup._auto_backend_sentinel: + current_framework = cbook._get_running_interactive_framework() + + if (current_framework and + (backend := backend_registry.backend_for_gui_framework( + current_framework))): + candidates = [backend] + else: + candidates = [] + candidates += [ + "macosx", "qtagg", "gtk4agg", "gtk3agg", "tkagg", "wxagg"] + + # Don't try to fallback on the cairo-based backends as they each have + # an additional dependency (pycairo) over the agg-based backend, and + # are of worse quality. + for candidate in candidates: + try: + switch_backend(candidate) + except ImportError: + continue + else: + rcParamsOrig['backend'] = candidate + return + else: + # Switching to Agg should always succeed; if it doesn't, let the + # exception propagate out. + switch_backend("agg") + rcParamsOrig["backend"] = "agg" + return + # have to escape the switch on access logic + old_backend = dict.__getitem__(rcParams, 'backend') + + module = backend_registry.load_backend_module(newbackend) + canvas_class = module.FigureCanvas + + required_framework = canvas_class.required_interactive_framework + if required_framework is not None: + current_framework = cbook._get_running_interactive_framework() + if (current_framework and required_framework + and current_framework != required_framework): + raise ImportError( + "Cannot load backend {!r} which requires the {!r} interactive " + "framework, as {!r} is currently running".format( + newbackend, required_framework, current_framework)) + + # Load the new_figure_manager() and show() functions from the backend. + + # Classically, backends can directly export these functions. This should + # keep working for backcompat. + new_figure_manager = getattr(module, "new_figure_manager", None) + show = getattr(module, "show", None) + + # In that classical approach, backends are implemented as modules, but + # "inherit" default method implementations from backend_bases._Backend. + # This is achieved by creating a "class" that inherits from + # backend_bases._Backend and whose body is filled with the module globals. + class backend_mod(matplotlib.backend_bases._Backend): + locals().update(vars(module)) + + # However, the newer approach for defining new_figure_manager and + # show is to derive them from canvas methods. In that case, also + # update backend_mod accordingly; also, per-backend customization of + # draw_if_interactive is disabled. + if new_figure_manager is None: + + def new_figure_manager_given_figure(num, figure): + return canvas_class.new_manager(figure, num) + + def new_figure_manager(num, *args, FigureClass=Figure, **kwargs): + fig = FigureClass(*args, **kwargs) + return new_figure_manager_given_figure(num, fig) + + def draw_if_interactive() -> None: + if matplotlib.is_interactive(): + manager = _pylab_helpers.Gcf.get_active() + if manager: + manager.canvas.draw_idle() + + backend_mod.new_figure_manager_given_figure = ( # type: ignore[method-assign] + new_figure_manager_given_figure) + backend_mod.new_figure_manager = ( # type: ignore[method-assign] + new_figure_manager) + backend_mod.draw_if_interactive = ( # type: ignore[method-assign] + draw_if_interactive) + + # If the manager explicitly overrides pyplot_show, use it even if a global + # show is already present, as the latter may be here for backcompat. + manager_class = getattr(canvas_class, "manager_class", None) + # We can't compare directly manager_class.pyplot_show and FMB.pyplot_show because + # pyplot_show is a classmethod so the above constructs are bound classmethods, and + # thus always different (being bound to different classes). We also have to use + # getattr_static instead of vars as manager_class could have no __dict__. + manager_pyplot_show = inspect.getattr_static(manager_class, "pyplot_show", None) + base_pyplot_show = inspect.getattr_static(FigureManagerBase, "pyplot_show", None) + if (show is None + or (manager_pyplot_show is not None + and manager_pyplot_show != base_pyplot_show)): + if not manager_pyplot_show: + raise ValueError( + f"Backend {newbackend} defines neither FigureCanvas.manager_class nor " + f"a toplevel show function") + _pyplot_show = cast('Any', manager_class).pyplot_show + backend_mod.show = _pyplot_show # type: ignore[method-assign] + + _log.debug("Loaded backend %s version %s.", + newbackend, backend_mod.backend_version) + + if newbackend in ("ipympl", "widget"): + # ipympl < 0.9.4 expects rcParams["backend"] to be the fully-qualified backend + # name "module://ipympl.backend_nbagg" not short names "ipympl" or "widget". + import importlib.metadata as im + from matplotlib import _parse_to_version_info # type: ignore[attr-defined] + try: + module_version = im.version("ipympl") + if _parse_to_version_info(module_version) < (0, 9, 4): + newbackend = "module://ipympl.backend_nbagg" + except im.PackageNotFoundError: + pass + + rcParams['backend'] = rcParamsDefault['backend'] = newbackend + _backend_mod = backend_mod + for func_name in ["new_figure_manager", "draw_if_interactive", "show"]: + globals()[func_name].__signature__ = inspect.signature( + getattr(backend_mod, func_name)) + + # Need to keep a global reference to the backend for compatibility reasons. + # See https://github.com/matplotlib/matplotlib/issues/6092 + matplotlib.backends.backend = newbackend # type: ignore[attr-defined] + + if not cbook._str_equal(old_backend, newbackend): + if get_fignums(): + _api.warn_deprecated("3.8", message=( + "Auto-close()ing of figures upon backend switching is deprecated since " + "%(since)s and will be removed %(removal)s. To suppress this warning, " + "explicitly call plt.close('all') first.")) + close("all") + + # Make sure the repl display hook is installed in case we become interactive. + install_repl_displayhook() + + +def _warn_if_gui_out_of_main_thread() -> None: + warn = False + canvas_class = cast(type[FigureCanvasBase], _get_backend_mod().FigureCanvas) + if canvas_class.required_interactive_framework: + if hasattr(threading, 'get_native_id'): + # This compares native thread ids because even if Python-level + # Thread objects match, the underlying OS thread (which is what + # really matters) may be different on Python implementations with + # green threads. + if threading.get_native_id() != threading.main_thread().native_id: + warn = True + else: + # Fall back to Python-level Thread if native IDs are unavailable, + # mainly for PyPy. + if threading.current_thread() is not threading.main_thread(): + warn = True + if warn: + _api.warn_external( + "Starting a Matplotlib GUI outside of the main thread will likely " + "fail.") + + +# This function's signature is rewritten upon backend-load by switch_backend. +def new_figure_manager(*args, **kwargs): + """Create a new figure manager instance.""" + _warn_if_gui_out_of_main_thread() + return _get_backend_mod().new_figure_manager(*args, **kwargs) + + +# This function's signature is rewritten upon backend-load by switch_backend. +def draw_if_interactive(*args, **kwargs): + """ + Redraw the current figure if in interactive mode. + + .. warning:: + + End users will typically not have to call this function because the + the interactive mode takes care of this. + """ + return _get_backend_mod().draw_if_interactive(*args, **kwargs) + + +# This function's signature is rewritten upon backend-load by switch_backend. +def show(*args, **kwargs) -> None: + """ + Display all open figures. + + Parameters + ---------- + block : bool, optional + Whether to wait for all figures to be closed before returning. + + If `True` block and run the GUI main loop until all figure windows + are closed. + + If `False` ensure that all figure windows are displayed and return + immediately. In this case, you are responsible for ensuring + that the event loop is running to have responsive figures. + + Defaults to True in non-interactive mode and to False in interactive + mode (see `.pyplot.isinteractive`). + + See Also + -------- + ion : Enable interactive mode, which shows / updates the figure after + every plotting command, so that calling ``show()`` is not necessary. + ioff : Disable interactive mode. + savefig : Save the figure to an image file instead of showing it on screen. + + Notes + ----- + **Saving figures to file and showing a window at the same time** + + If you want an image file as well as a user interface window, use + `.pyplot.savefig` before `.pyplot.show`. At the end of (a blocking) + ``show()`` the figure is closed and thus unregistered from pyplot. Calling + `.pyplot.savefig` afterwards would save a new and thus empty figure. This + limitation of command order does not apply if the show is non-blocking or + if you keep a reference to the figure and use `.Figure.savefig`. + + **Auto-show in jupyter notebooks** + + The jupyter backends (activated via ``%matplotlib inline``, + ``%matplotlib notebook``, or ``%matplotlib widget``), call ``show()`` at + the end of every cell by default. Thus, you usually don't have to call it + explicitly there. + """ + _warn_if_gui_out_of_main_thread() + return _get_backend_mod().show(*args, **kwargs) + + +def isinteractive() -> bool: + """ + Return whether plots are updated after every plotting command. + + The interactive mode is mainly useful if you build plots from the command + line and want to see the effect of each command while you are building the + figure. + + In interactive mode: + + - newly created figures will be shown immediately; + - figures will automatically redraw on change; + - `.pyplot.show` will not block by default. + + In non-interactive mode: + + - newly created figures and changes to figures will not be reflected until + explicitly asked to be; + - `.pyplot.show` will block by default. + + See Also + -------- + ion : Enable interactive mode. + ioff : Disable interactive mode. + show : Show all figures (and maybe block). + pause : Show all figures, and block for a time. + """ + return matplotlib.is_interactive() + + +# Note: The return type of ioff being AbstractContextManager +# instead of ExitStack is deliberate. +# See https://github.com/matplotlib/matplotlib/issues/27659 +# and https://github.com/matplotlib/matplotlib/pull/27667 for more info. +def ioff() -> AbstractContextManager: + """ + Disable interactive mode. + + See `.pyplot.isinteractive` for more details. + + See Also + -------- + ion : Enable interactive mode. + isinteractive : Whether interactive mode is enabled. + show : Show all figures (and maybe block). + pause : Show all figures, and block for a time. + + Notes + ----- + For a temporary change, this can be used as a context manager:: + + # if interactive mode is on + # then figures will be shown on creation + plt.ion() + # This figure will be shown immediately + fig = plt.figure() + + with plt.ioff(): + # interactive mode will be off + # figures will not automatically be shown + fig2 = plt.figure() + # ... + + To enable optional usage as a context manager, this function returns a + context manager object, which is not intended to be stored or + accessed by the user. + """ + stack = ExitStack() + stack.callback(ion if isinteractive() else ioff) + matplotlib.interactive(False) + uninstall_repl_displayhook() + return stack + + +# Note: The return type of ion being AbstractContextManager +# instead of ExitStack is deliberate. +# See https://github.com/matplotlib/matplotlib/issues/27659 +# and https://github.com/matplotlib/matplotlib/pull/27667 for more info. +def ion() -> AbstractContextManager: + """ + Enable interactive mode. + + See `.pyplot.isinteractive` for more details. + + See Also + -------- + ioff : Disable interactive mode. + isinteractive : Whether interactive mode is enabled. + show : Show all figures (and maybe block). + pause : Show all figures, and block for a time. + + Notes + ----- + For a temporary change, this can be used as a context manager:: + + # if interactive mode is off + # then figures will not be shown on creation + plt.ioff() + # This figure will not be shown immediately + fig = plt.figure() + + with plt.ion(): + # interactive mode will be on + # figures will automatically be shown + fig2 = plt.figure() + # ... + + To enable optional usage as a context manager, this function returns a + context manager object, which is not intended to be stored or + accessed by the user. + """ + stack = ExitStack() + stack.callback(ion if isinteractive() else ioff) + matplotlib.interactive(True) + install_repl_displayhook() + return stack + + +def pause(interval: float) -> None: + """ + Run the GUI event loop for *interval* seconds. + + If there is an active figure, it will be updated and displayed before the + pause, and the GUI event loop (if any) will run during the pause. + + This can be used for crude animation. For more complex animation use + :mod:`matplotlib.animation`. + + If there is no active figure, sleep for *interval* seconds instead. + + See Also + -------- + matplotlib.animation : Proper animations + show : Show all figures and optional block until all figures are closed. + """ + manager = _pylab_helpers.Gcf.get_active() + if manager is not None: + canvas = manager.canvas + if canvas.figure.stale: + canvas.draw_idle() + show(block=False) + canvas.start_event_loop(interval) + else: + time.sleep(interval) + + +@_copy_docstring_and_deprecators(matplotlib.rc) +def rc(group: str, **kwargs) -> None: + matplotlib.rc(group, **kwargs) + + +@_copy_docstring_and_deprecators(matplotlib.rc_context) +def rc_context( + rc: dict[str, Any] | None = None, + fname: str | pathlib.Path | os.PathLike | None = None, +) -> AbstractContextManager[None]: + return matplotlib.rc_context(rc, fname) + + +@_copy_docstring_and_deprecators(matplotlib.rcdefaults) +def rcdefaults() -> None: + matplotlib.rcdefaults() + if matplotlib.is_interactive(): + draw_all() + + +# getp/get/setp are explicitly reexported so that they show up in pyplot docs. + + +@_copy_docstring_and_deprecators(matplotlib.artist.getp) +def getp(obj, *args, **kwargs): + return matplotlib.artist.getp(obj, *args, **kwargs) + + +@_copy_docstring_and_deprecators(matplotlib.artist.get) +def get(obj, *args, **kwargs): + return matplotlib.artist.get(obj, *args, **kwargs) + + +@_copy_docstring_and_deprecators(matplotlib.artist.setp) +def setp(obj, *args, **kwargs): + return matplotlib.artist.setp(obj, *args, **kwargs) + + +def xkcd( + scale: float = 1, length: float = 100, randomness: float = 2 +) -> ExitStack: + """ + Turn on `xkcd `_ sketch-style drawing mode. + + This will only have an effect on things drawn after this function is called. + + For best results, install the `xkcd script `_ + font; xkcd fonts are not packaged with Matplotlib. + + Parameters + ---------- + scale : float, optional + The amplitude of the wiggle perpendicular to the source line. + length : float, optional + The length of the wiggle along the line. + randomness : float, optional + The scale factor by which the length is shrunken or expanded. + + Notes + ----- + This function works by a number of rcParams, so it will probably + override others you have set before. + + If you want the effects of this function to be temporary, it can + be used as a context manager, for example:: + + with plt.xkcd(): + # This figure will be in XKCD-style + fig1 = plt.figure() + # ... + + # This figure will be in regular style + fig2 = plt.figure() + """ + # This cannot be implemented in terms of contextmanager() or rc_context() + # because this needs to work as a non-contextmanager too. + + if rcParams['text.usetex']: + raise RuntimeError( + "xkcd mode is not compatible with text.usetex = True") + + stack = ExitStack() + stack.callback(dict.update, rcParams, rcParams.copy()) # type: ignore[arg-type] + + from matplotlib import patheffects + rcParams.update({ + 'font.family': ['xkcd', 'xkcd Script', 'Comic Neue', 'Comic Sans MS'], + 'font.size': 14.0, + 'path.sketch': (scale, length, randomness), + 'path.effects': [ + patheffects.withStroke(linewidth=4, foreground="w")], + 'axes.linewidth': 1.5, + 'lines.linewidth': 2.0, + 'figure.facecolor': 'white', + 'grid.linewidth': 0.0, + 'axes.grid': False, + 'axes.unicode_minus': False, + 'axes.edgecolor': 'black', + 'xtick.major.size': 8, + 'xtick.major.width': 3, + 'ytick.major.size': 8, + 'ytick.major.width': 3, + }) + + return stack + + +## Figures ## + +def figure( + # autoincrement if None, else integer from 1-N + num: int | str | Figure | SubFigure | None = None, + # defaults to rc figure.figsize + figsize: tuple[float, float] | None = None, + # defaults to rc figure.dpi + dpi: float | None = None, + *, + # defaults to rc figure.facecolor + facecolor: ColorType | None = None, + # defaults to rc figure.edgecolor + edgecolor: ColorType | None = None, + frameon: bool = True, + FigureClass: type[Figure] = Figure, + clear: bool = False, + **kwargs +) -> Figure: + """ + Create a new figure, or activate an existing figure. + + Parameters + ---------- + num : int or str or `.Figure` or `.SubFigure`, optional + A unique identifier for the figure. + + If a figure with that identifier already exists, this figure is made + active and returned. An integer refers to the ``Figure.number`` + attribute, a string refers to the figure label. + + If there is no figure with the identifier or *num* is not given, a new + figure is created, made active and returned. If *num* is an int, it + will be used for the ``Figure.number`` attribute, otherwise, an + auto-generated integer value is used (starting at 1 and incremented + for each new figure). If *num* is a string, the figure label and the + window title is set to this value. If num is a ``SubFigure``, its + parent ``Figure`` is activated. + + figsize : (float, float), default: :rc:`figure.figsize` + Width, height in inches. + + dpi : float, default: :rc:`figure.dpi` + The resolution of the figure in dots-per-inch. + + facecolor : :mpltype:`color`, default: :rc:`figure.facecolor` + The background color. + + edgecolor : :mpltype:`color`, default: :rc:`figure.edgecolor` + The border color. + + frameon : bool, default: True + If False, suppress drawing the figure frame. + + FigureClass : subclass of `~matplotlib.figure.Figure` + If set, an instance of this subclass will be created, rather than a + plain `.Figure`. + + clear : bool, default: False + If True and the figure already exists, then it is cleared. + + 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 measurably slow down figure display. + + - '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 `.Figure.set_tight_layout` for + further details. + + - '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`. + + **kwargs + Additional keyword arguments are passed to the `.Figure` constructor. + + Returns + ------- + `~matplotlib.figure.Figure` + + Notes + ----- + A newly created figure is passed to the `~.FigureCanvasBase.new_manager` + method or the `new_figure_manager` function provided by the current + backend, which install a canvas and a manager on the figure. + + Once this is done, :rc:`figure.hooks` are called, one at a time, on the + figure; these hooks allow arbitrary customization of the figure (e.g., + attaching callbacks) or of associated elements (e.g., modifying the + toolbar). See :doc:`/gallery/user_interfaces/mplcvd` for an example of + toolbar customization. + + If you are creating many figures, make sure you explicitly call + `.pyplot.close` on the figures you are not using, because this will + enable pyplot to properly clean up the memory. + + `~matplotlib.rcParams` defines the default values, which can be modified + in the matplotlibrc file. + """ + if isinstance(num, FigureBase): + # type narrowed to `Figure | SubFigure` by combination of input and isinstance + if num.canvas.manager is None: + raise ValueError("The passed figure is not managed by pyplot") + _pylab_helpers.Gcf.set_active(num.canvas.manager) + return num.figure + + allnums = get_fignums() + next_num = max(allnums) + 1 if allnums else 1 + fig_label = '' + if num is None: + num = next_num + elif isinstance(num, str): + fig_label = num + all_labels = get_figlabels() + if fig_label not in all_labels: + if fig_label == 'all': + _api.warn_external("close('all') closes all existing figures.") + num = next_num + else: + inum = all_labels.index(fig_label) + num = allnums[inum] + else: + num = int(num) # crude validation of num argument + + # Type of "num" has narrowed to int, but mypy can't quite see it + manager = _pylab_helpers.Gcf.get_fig_manager(num) # type: ignore[arg-type] + if manager is None: + max_open_warning = rcParams['figure.max_open_warning'] + if len(allnums) == max_open_warning >= 1: + _api.warn_external( + f"More than {max_open_warning} figures have been opened. " + f"Figures created through the pyplot interface " + f"(`matplotlib.pyplot.figure`) are retained until explicitly " + f"closed and may consume too much memory. (To control this " + f"warning, see the rcParam `figure.max_open_warning`). " + f"Consider using `matplotlib.pyplot.close()`.", + RuntimeWarning) + + manager = new_figure_manager( + num, figsize=figsize, dpi=dpi, + facecolor=facecolor, edgecolor=edgecolor, frameon=frameon, + FigureClass=FigureClass, **kwargs) + fig = manager.canvas.figure + if fig_label: + fig.set_label(fig_label) + + for hookspecs in rcParams["figure.hooks"]: + module_name, dotted_name = hookspecs.split(":") + obj: Any = importlib.import_module(module_name) + for part in dotted_name.split("."): + obj = getattr(obj, part) + obj(fig) + + _pylab_helpers.Gcf._set_new_active_manager(manager) + + # make sure backends (inline) that we don't ship that expect this + # to be called in plotting commands to make the figure call show + # still work. There is probably a better way to do this in the + # FigureManager base class. + draw_if_interactive() + + if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN: + fig.stale_callback = _auto_draw_if_interactive + + if clear: + manager.canvas.figure.clear() + + return manager.canvas.figure + + +def _auto_draw_if_interactive(fig, val): + """ + An internal helper function for making sure that auto-redrawing + works as intended in the plain python repl. + + Parameters + ---------- + fig : Figure + A figure object which is assumed to be associated with a canvas + """ + if (val and matplotlib.is_interactive() + and not fig.canvas.is_saving() + and not fig.canvas._is_idle_drawing): + # Some artists can mark themselves as stale in the middle of drawing + # (e.g. axes position & tick labels being computed at draw time), but + # this shouldn't trigger a redraw because the current redraw will + # already take them into account. + with fig.canvas._idle_draw_cntx(): + fig.canvas.draw_idle() + + +def gcf() -> Figure: + """ + Get the current figure. + + If there is currently no figure on the pyplot figure stack, a new one is + created using `~.pyplot.figure()`. (To test whether there is currently a + figure on the pyplot figure stack, check whether `~.pyplot.get_fignums()` + is empty.) + """ + manager = _pylab_helpers.Gcf.get_active() + if manager is not None: + return manager.canvas.figure + else: + return figure() + + +def fignum_exists(num: int | str) -> bool: + """ + Return whether the figure with the given id exists. + + Parameters + ---------- + num : int or str + A figure identifier. + + Returns + ------- + bool + Whether or not a figure with id *num* exists. + """ + return ( + _pylab_helpers.Gcf.has_fignum(num) + if isinstance(num, int) + else num in get_figlabels() + ) + + +def get_fignums() -> list[int]: + """Return a list of existing figure numbers.""" + return sorted(_pylab_helpers.Gcf.figs) + + +def get_figlabels() -> list[Any]: + """Return a list of existing figure labels.""" + managers = _pylab_helpers.Gcf.get_all_fig_managers() + managers.sort(key=lambda m: m.num) + return [m.canvas.figure.get_label() for m in managers] + + +def get_current_fig_manager() -> FigureManagerBase | None: + """ + Return the figure manager of the current figure. + + The figure manager is a container for the actual backend-depended window + that displays the figure on screen. + + If no current figure exists, a new one is created, and its figure + manager is returned. + + Returns + ------- + `.FigureManagerBase` or backend-dependent subclass thereof + """ + return gcf().canvas.manager + + +@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect) +def connect(s: str, func: Callable[[Event], Any]) -> int: + return gcf().canvas.mpl_connect(s, func) + + +@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect) +def disconnect(cid: int) -> None: + gcf().canvas.mpl_disconnect(cid) + + +def close(fig: None | int | str | Figure | Literal["all"] = None) -> None: + """ + Close a figure window. + + Parameters + ---------- + fig : None or int or str or `.Figure` + The figure to close. There are a number of ways to specify this: + + - *None*: the current figure + - `.Figure`: the given `.Figure` instance + - ``int``: a figure number + - ``str``: a figure name + - 'all': all figures + + """ + if fig is None: + manager = _pylab_helpers.Gcf.get_active() + if manager is None: + return + else: + _pylab_helpers.Gcf.destroy(manager) + elif fig == 'all': + _pylab_helpers.Gcf.destroy_all() + elif isinstance(fig, int): + _pylab_helpers.Gcf.destroy(fig) + elif hasattr(fig, 'int'): + # if we are dealing with a type UUID, we + # can use its integer representation + _pylab_helpers.Gcf.destroy(fig.int) + elif isinstance(fig, str): + all_labels = get_figlabels() + if fig in all_labels: + num = get_fignums()[all_labels.index(fig)] + _pylab_helpers.Gcf.destroy(num) + elif isinstance(fig, Figure): + _pylab_helpers.Gcf.destroy_fig(fig) + else: + raise TypeError("close() argument must be a Figure, an int, a string, " + "or None, not %s" % type(fig)) + + +def clf() -> None: + """Clear the current figure.""" + gcf().clear() + + +def draw() -> None: + """ + Redraw the current figure. + + This is used to update a figure that has been altered, but not + automatically re-drawn. If interactive mode is on (via `.ion()`), this + should be only rarely needed, but there may be ways to modify the state of + a figure without marking it as "stale". Please report these cases as bugs. + + This is equivalent to calling ``fig.canvas.draw_idle()``, where ``fig`` is + the current figure. + + See Also + -------- + .FigureCanvasBase.draw_idle + .FigureCanvasBase.draw + """ + gcf().canvas.draw_idle() + + +@_copy_docstring_and_deprecators(Figure.savefig) +def savefig(*args, **kwargs) -> None: + fig = gcf() + # savefig default implementation has no return, so mypy is unhappy + # presumably this is here because subclasses can return? + res = fig.savefig(*args, **kwargs) # type: ignore[func-returns-value] + fig.canvas.draw_idle() # Need this if 'transparent=True', to reset colors. + return res + + +## Putting things in figures ## + + +def figlegend(*args, **kwargs) -> Legend: + return gcf().legend(*args, **kwargs) +if Figure.legend.__doc__: + figlegend.__doc__ = Figure.legend.__doc__ \ + .replace(" legend(", " figlegend(") \ + .replace("fig.legend(", "plt.figlegend(") \ + .replace("ax.plot(", "plt.plot(") + + +## Axes ## + +@_docstring.dedent_interpd +def axes( + arg: None | tuple[float, float, float, float] = None, + **kwargs +) -> matplotlib.axes.Axes: + """ + Add an Axes to the current figure and make it the current Axes. + + Call signatures:: + + plt.axes() + plt.axes(rect, projection=None, polar=False, **kwargs) + plt.axes(ax) + + Parameters + ---------- + arg : None or 4-tuple + The exact behavior of this function depends on the type: + + - *None*: A new full window Axes is added using + ``subplot(**kwargs)``. + - 4-tuple of floats *rect* = ``(left, bottom, width, height)``. + A new Axes is added with dimensions *rect* in normalized + (0, 1) units using `~.Figure.add_axes` on the current figure. + + 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'. + + 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 + + See Also + -------- + .Figure.add_axes + .pyplot.subplot + .Figure.add_subplot + .Figure.subplots + .pyplot.subplots + + Examples + -------- + :: + + # Creating a new full window Axes + plt.axes() + + # Creating a new Axes with specified dimensions and a grey background + plt.axes((left, bottom, width, height), facecolor='grey') + """ + fig = gcf() + pos = kwargs.pop('position', None) + if arg is None: + if pos is None: + return fig.add_subplot(**kwargs) + else: + return fig.add_axes(pos, **kwargs) + else: + return fig.add_axes(arg, **kwargs) + + +def delaxes(ax: matplotlib.axes.Axes | None = None) -> None: + """ + Remove an `~.axes.Axes` (defaulting to the current Axes) from its figure. + """ + if ax is None: + ax = gca() + ax.remove() + + +def sca(ax: Axes) -> None: + """ + Set the current Axes to *ax* and the current Figure to the parent of *ax*. + """ + # Mypy sees ax.figure as potentially None, + # but if you are calling this, it won't be None + # Additionally the slight difference between `Figure` and `FigureBase` mypy catches + figure(ax.figure) # type: ignore[arg-type] + ax.figure.sca(ax) # type: ignore[union-attr] + + +def cla() -> None: + """Clear the current Axes.""" + # Not generated via boilerplate.py to allow a different docstring. + return gca().cla() + + +## More ways of creating Axes ## + +@_docstring.dedent_interpd +def subplot(*args, **kwargs) -> Axes: + """ + Add an Axes to the current figure or retrieve an existing Axes. + + This is a wrapper of `.Figure.add_subplot` which provides additional + behavior when working with the implicit API (see the notes section). + + Call signatures:: + + subplot(nrows, ncols, index, **kwargs) + subplot(pos, **kwargs) + subplot(**kwargs) + subplot(ax) + + 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`. + + 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'. + + 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 + + Notes + ----- + Creating a new Axes will delete any preexisting Axes that + overlaps with it beyond sharing a boundary:: + + import matplotlib.pyplot as plt + # plot a line, implicitly creating a subplot(111) + plt.plot([1, 2, 3]) + # now create a subplot which represents the top plot of a grid + # with 2 rows and 1 column. Since this subplot will overlap the + # first, the plot (and its Axes) previously created, will be removed + plt.subplot(211) + + If you do not want this behavior, use the `.Figure.add_subplot` method + or the `.pyplot.axes` function instead. + + If no *kwargs* are passed and there exists an Axes in the location + specified by *args* then that Axes will be returned rather than a new + Axes being created. + + If *kwargs* are passed and there exists an Axes in the location + specified by *args*, the projection type is the same, and the + *kwargs* match with the existing Axes, then the existing Axes is + returned. Otherwise a new Axes is created with the specified + parameters. We save a reference to the *kwargs* which we use + for this comparison. If any of the values in *kwargs* are + mutable we will not detect the case where they are mutated. + In these cases we suggest using `.Figure.add_subplot` and the + explicit Axes API rather than the implicit pyplot API. + + See Also + -------- + .Figure.add_subplot + .pyplot.subplots + .pyplot.axes + .Figure.subplots + + Examples + -------- + :: + + plt.subplot(221) + + # equivalent but more general + ax1 = plt.subplot(2, 2, 1) + + # add a subplot with no frame + ax2 = plt.subplot(222, frameon=False) + + # add a polar subplot + plt.subplot(223, projection='polar') + + # add a red subplot that shares the x-axis with ax1 + plt.subplot(224, sharex=ax1, facecolor='red') + + # delete ax2 from the figure + plt.delaxes(ax2) + + # add ax2 to the figure again + plt.subplot(ax2) + + # make the first Axes "current" again + plt.subplot(221) + + """ + # Here we will only normalize `polar=True` vs `projection='polar'` and let + # downstream code deal with the rest. + unset = object() + projection = kwargs.get('projection', unset) + polar = kwargs.pop('polar', unset) + if polar is not unset and polar: + # if we got mixed messages from the user, raise + if projection is not unset and projection != 'polar': + raise ValueError( + f"polar={polar}, yet projection={projection!r}. " + "Only one of these arguments should be supplied." + ) + kwargs['projection'] = projection = 'polar' + + # if subplot called without arguments, create subplot(1, 1, 1) + if len(args) == 0: + args = (1, 1, 1) + + # This check was added because it is very easy to type subplot(1, 2, False) + # when subplots(1, 2, False) was intended (sharex=False, that is). In most + # cases, no error will ever occur, but mysterious behavior can result + # because what was intended to be the sharex argument is instead treated as + # a subplot index for subplot() + if len(args) >= 3 and isinstance(args[2], bool): + _api.warn_external("The subplot index argument to subplot() appears " + "to be a boolean. Did you intend to use " + "subplots()?") + # Check for nrows and ncols, which are not valid subplot args: + if 'nrows' in kwargs or 'ncols' in kwargs: + raise TypeError("subplot() got an unexpected keyword argument 'ncols' " + "and/or 'nrows'. Did you intend to call subplots()?") + + fig = gcf() + + # First, search for an existing subplot with a matching spec. + key = SubplotSpec._from_subplot_args(fig, args) + + for ax in fig.axes: + # If we found an Axes at the position, we can reuse it if the user passed no + # kwargs or if the Axes class and kwargs are identical. + if (ax.get_subplotspec() == key + and (kwargs == {} + or (ax._projection_init + == fig._process_projection_requirements(**kwargs)))): + break + else: + # we have exhausted the known Axes and none match, make a new one! + ax = fig.add_subplot(*args, **kwargs) + + fig.sca(ax) + + return ax + + +@overload +def subplots( + 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 = ..., + **fig_kw +) -> tuple[Figure, Axes]: + ... + + +@overload +def subplots( + 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 = ..., + **fig_kw +) -> tuple[Figure, np.ndarray]: # TODO numpy/numpy#24738 + ... + + +@overload +def subplots( + 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 = ..., + **fig_kw +) -> tuple[Figure, Any]: + ... + + +def subplots( + nrows: int = 1, ncols: int = 1, *, + sharex: bool | Literal["none", "all", "row", "col"] = False, + sharey: bool | Literal["none", "all", "row", "col"] = False, + squeeze: bool = True, + width_ratios: Sequence[float] | None = None, + height_ratios: Sequence[float] | None = None, + subplot_kw: dict[str, Any] | None = None, + gridspec_kw: dict[str, Any] | None = None, + **fig_kw +) -> tuple[Figure, Any]: + """ + Create a figure and a set of subplots. + + This utility wrapper makes it convenient to create common layouts of + subplots, including the enclosing figure object, 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 properties among x (*sharex*) or y (*sharey*) + axes: + + - 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 `~matplotlib.axes.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. Convenience + for ``gridspec_kw={'height_ratios': [...]}``. + + subplot_kw : dict, optional + Dict with keywords passed to the + `~matplotlib.figure.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. + + **fig_kw + All additional keyword arguments are passed to the + `.pyplot.figure` call. + + Returns + ------- + fig : `.Figure` + + ax : `~matplotlib.axes.Axes` or array of Axes + *ax* can be either a single `~.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. + + Typical idioms for handling the return value are:: + + # using the variable ax for single a Axes + fig, ax = plt.subplots() + + # using the variable axs for multiple Axes + fig, axs = plt.subplots(2, 2) + + # using tuple unpacking for multiple Axes + fig, (ax1, ax2) = plt.subplots(1, 2) + fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) + + The names ``ax`` and pluralized ``axs`` are preferred over ``axes`` + because for the latter it's not clear if it refers to a single + `~.axes.Axes` instance or a collection of these. + + See Also + -------- + .pyplot.figure + .pyplot.subplot + .pyplot.axes + .Figure.subplots + .Figure.add_subplot + + Examples + -------- + :: + + # First create some toy data: + x = np.linspace(0, 2*np.pi, 400) + y = np.sin(x**2) + + # Create just a figure and only one subplot + fig, ax = plt.subplots() + ax.plot(x, y) + ax.set_title('Simple plot') + + # Create two subplots and unpack the output array immediately + f, (ax1, ax2) = plt.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 + fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar")) + axs[0, 0].plot(x, y) + axs[1, 1].scatter(x, y) + + # Share a X axis with each column of subplots + plt.subplots(2, 2, sharex='col') + + # Share a Y axis with each row of subplots + plt.subplots(2, 2, sharey='row') + + # Share both X and Y axes with all subplots + plt.subplots(2, 2, sharex='all', sharey='all') + + # Note that this is the same as + plt.subplots(2, 2, sharex=True, sharey=True) + + # Create figure number 10 with a single subplot + # and clears it if it already exists. + fig, ax = plt.subplots(num=10, clear=True) + + """ + fig = figure(**fig_kw) + axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey, + squeeze=squeeze, subplot_kw=subplot_kw, + gridspec_kw=gridspec_kw, height_ratios=height_ratios, + width_ratios=width_ratios) + return fig, axs + + +@overload +def subplot_mosaic( + mosaic: str, + *, + sharex: bool = ..., + sharey: bool = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + empty_sentinel: str = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | None = ..., + **fig_kw: Any +) -> tuple[Figure, dict[str, matplotlib.axes.Axes]]: ... + + +@overload +def subplot_mosaic( + 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 = ..., + gridspec_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[_T | tuple[_T, ...], dict[str, Any]] | None = ..., + **fig_kw: Any +) -> tuple[Figure, dict[_T, matplotlib.axes.Axes]]: ... + + +@overload +def subplot_mosaic( + 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 = ..., + gridspec_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = ..., + **fig_kw: Any +) -> tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: ... + + +def subplot_mosaic( + mosaic: str | list[HashableList[_T]] | list[HashableList[Hashable]], + *, + sharex: bool = False, + sharey: bool = False, + width_ratios: ArrayLike | None = None, + height_ratios: ArrayLike | None = None, + empty_sentinel: Any = '.', + subplot_kw: dict[str, Any] | None = None, + gridspec_kw: dict[str, Any] | None = None, + per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | + dict[_T | tuple[_T, ...], dict[str, Any]] | + dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = None, + **fig_kw: Any +) -> tuple[Figure, dict[str, matplotlib.axes.Axes]] | \ + tuple[Figure, dict[_T, matplotlib.axes.Axes]] | \ + tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: + """ + 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 must be of the form :: + + ''' + AAE + C.E + ''' + + where each character is a column and each line is a row. + This only allows only single character Axes labels and does + not allow nesting but is very terse. + + 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. Convenience + for ``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. Convenience + for ``gridspec_kw={'height_ratios': [...]}``. + + 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. + + 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. + + **fig_kw + All additional keyword arguments are passed to the + `.pyplot.figure` call. + + Returns + ------- + fig : `.Figure` + The new figure + + 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. + + """ + fig = figure(**fig_kw) + ax_dict = fig.subplot_mosaic( # type: ignore[misc] + mosaic, # type: ignore[arg-type] + sharex=sharex, sharey=sharey, + height_ratios=height_ratios, width_ratios=width_ratios, + subplot_kw=subplot_kw, gridspec_kw=gridspec_kw, + empty_sentinel=empty_sentinel, + per_subplot_kw=per_subplot_kw, # type: ignore[arg-type] + ) + return fig, ax_dict + + +def subplot2grid( + shape: tuple[int, int], loc: tuple[int, int], + rowspan: int = 1, colspan: int = 1, + fig: Figure | None = None, + **kwargs +) -> matplotlib.axes.Axes: + """ + Create a subplot at a specific location inside a regular grid. + + Parameters + ---------- + shape : (int, int) + Number of rows and of columns of the grid in which to place axis. + loc : (int, int) + Row number and column number of the axis location within the grid. + rowspan : int, default: 1 + Number of rows for the axis to span downwards. + colspan : int, default: 1 + Number of columns for the axis to span to the right. + fig : `.Figure`, optional + Figure to place the subplot in. Defaults to the current figure. + **kwargs + Additional keyword arguments are handed to `~.Figure.add_subplot`. + + 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. + + Notes + ----- + The following call :: + + ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan) + + is identical to :: + + fig = gcf() + gs = fig.add_gridspec(nrows, ncols) + ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan]) + """ + if fig is None: + fig = gcf() + rows, cols = shape + gs = GridSpec._check_gridspec_exists(fig, rows, cols) + subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan) + return fig.add_subplot(subplotspec, **kwargs) + + +def twinx(ax: matplotlib.axes.Axes | None = None) -> _AxesBase: + """ + Make and return a second Axes that shares the *x*-axis. The new Axes will + overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be + on the right. + + Examples + -------- + :doc:`/gallery/subplots_axes_and_figures/two_scales` + """ + if ax is None: + ax = gca() + ax1 = ax.twinx() + return ax1 + + +def twiny(ax: matplotlib.axes.Axes | None = None) -> _AxesBase: + """ + Make and return a second Axes that shares the *y*-axis. The new Axes will + overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be + on the top. + + Examples + -------- + :doc:`/gallery/subplots_axes_and_figures/two_scales` + """ + if ax is None: + ax = gca() + ax1 = ax.twiny() + return ax1 + + +def subplot_tool(targetfig: Figure | None = None) -> SubplotTool | None: + """ + Launch a subplot tool window for a figure. + + Returns + ------- + `matplotlib.widgets.SubplotTool` + """ + if targetfig is None: + targetfig = gcf() + tb = targetfig.canvas.manager.toolbar # type: ignore[union-attr] + if hasattr(tb, "configure_subplots"): # toolbar2 + from matplotlib.backend_bases import NavigationToolbar2 + return cast(NavigationToolbar2, tb).configure_subplots() + elif hasattr(tb, "trigger_tool"): # toolmanager + from matplotlib.backend_bases import ToolContainerBase + cast(ToolContainerBase, tb).trigger_tool("subplots") + return None + else: + raise ValueError("subplot_tool can only be launched for figures with " + "an associated toolbar") + + +def box(on: bool | None = None) -> None: + """ + Turn the Axes box on or off on the current Axes. + + Parameters + ---------- + on : bool or None + The new `~matplotlib.axes.Axes` box state. If ``None``, toggle + the state. + + See Also + -------- + :meth:`matplotlib.axes.Axes.set_frame_on` + :meth:`matplotlib.axes.Axes.get_frame_on` + """ + ax = gca() + if on is None: + on = not ax.get_frame_on() + ax.set_frame_on(on) + +## Axis ## + + +def xlim(*args, **kwargs) -> tuple[float, float]: + """ + Get or set the x limits of the current Axes. + + Call signatures:: + + left, right = xlim() # return the current xlim + xlim((left, right)) # set the xlim to left, right + xlim(left, right) # set the xlim to left, right + + If you do not specify args, you can pass *left* or *right* as kwargs, + i.e.:: + + xlim(right=3) # adjust the right leaving left unchanged + xlim(left=1) # adjust the left leaving right unchanged + + Setting limits turns autoscaling off for the x-axis. + + Returns + ------- + left, right + A tuple of the new x-axis limits. + + Notes + ----- + Calling this function with no arguments (e.g. ``xlim()``) is the pyplot + equivalent of calling `~.Axes.get_xlim` on the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_xlim` on the current Axes. All arguments are passed though. + """ + ax = gca() + if not args and not kwargs: + return ax.get_xlim() + ret = ax.set_xlim(*args, **kwargs) + return ret + + +def ylim(*args, **kwargs) -> tuple[float, float]: + """ + Get or set the y-limits of the current Axes. + + Call signatures:: + + bottom, top = ylim() # return the current ylim + ylim((bottom, top)) # set the ylim to bottom, top + ylim(bottom, top) # set the ylim to bottom, top + + If you do not specify args, you can alternatively pass *bottom* or + *top* as kwargs, i.e.:: + + ylim(top=3) # adjust the top leaving bottom unchanged + ylim(bottom=1) # adjust the bottom leaving top unchanged + + Setting limits turns autoscaling off for the y-axis. + + Returns + ------- + bottom, top + A tuple of the new y-axis limits. + + Notes + ----- + Calling this function with no arguments (e.g. ``ylim()``) is the pyplot + equivalent of calling `~.Axes.get_ylim` on the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_ylim` on the current Axes. All arguments are passed though. + """ + ax = gca() + if not args and not kwargs: + return ax.get_ylim() + ret = ax.set_ylim(*args, **kwargs) + return ret + + +def xticks( + ticks: ArrayLike | None = None, + labels: Sequence[str] | None = None, + *, + minor: bool = False, + **kwargs +) -> tuple[list[Tick] | np.ndarray, list[Text]]: + """ + Get or set the current tick locations and labels of the x-axis. + + Pass no arguments to return the current values without modifying them. + + Parameters + ---------- + ticks : array-like, optional + The list of xtick locations. Passing an empty list removes all xticks. + labels : array-like, optional + The labels to place at the given *ticks* locations. This argument can + only be passed if *ticks* is passed as well. + minor : bool, default: False + If ``False``, get/set the major ticks/labels; if ``True``, the minor + ticks/labels. + **kwargs + `.Text` properties can be used to control the appearance of the labels. + + .. warning:: + + This only sets the properties of the current ticks, which is + only sufficient if you either pass *ticks*, resulting in a + fixed list of ticks, or if the plot is static. + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `~.pyplot.tick_params` instead if possible. + + + Returns + ------- + locs + The list of xtick locations. + labels + The list of xlabel `.Text` objects. + + Notes + ----- + Calling this function with no arguments (e.g. ``xticks()``) is the pyplot + equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on + the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current Axes. + + Examples + -------- + >>> locs, labels = xticks() # Get the current locations and labels. + >>> xticks(np.arange(0, 1, step=0.2)) # Set label locations. + >>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels. + >>> xticks([0, 1, 2], ['January', 'February', 'March'], + ... rotation=20) # Set text labels and properties. + >>> xticks([]) # Disable xticks. + """ + ax = gca() + + locs: list[Tick] | np.ndarray + if ticks is None: + locs = ax.get_xticks(minor=minor) + if labels is not None: + raise TypeError("xticks(): Parameter 'labels' can't be set " + "without setting 'ticks'") + else: + locs = ax.set_xticks(ticks, minor=minor) + + labels_out: list[Text] = [] + if labels is None: + labels_out = ax.get_xticklabels(minor=minor) + for l in labels_out: + l._internal_update(kwargs) + else: + labels_out = ax.set_xticklabels(labels, minor=minor, **kwargs) + + return locs, labels_out + + +def yticks( + ticks: ArrayLike | None = None, + labels: Sequence[str] | None = None, + *, + minor: bool = False, + **kwargs +) -> tuple[list[Tick] | np.ndarray, list[Text]]: + """ + Get or set the current tick locations and labels of the y-axis. + + Pass no arguments to return the current values without modifying them. + + Parameters + ---------- + ticks : array-like, optional + The list of ytick locations. Passing an empty list removes all yticks. + labels : array-like, optional + The labels to place at the given *ticks* locations. This argument can + only be passed if *ticks* is passed as well. + minor : bool, default: False + If ``False``, get/set the major ticks/labels; if ``True``, the minor + ticks/labels. + **kwargs + `.Text` properties can be used to control the appearance of the labels. + + .. warning:: + + This only sets the properties of the current ticks, which is + only sufficient if you either pass *ticks*, resulting in a + fixed list of ticks, or if the plot is static. + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `~.pyplot.tick_params` instead if possible. + + Returns + ------- + locs + The list of ytick locations. + labels + The list of ylabel `.Text` objects. + + Notes + ----- + Calling this function with no arguments (e.g. ``yticks()``) is the pyplot + equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on + the current Axes. + Calling this function with arguments is the pyplot equivalent of calling + `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current Axes. + + Examples + -------- + >>> locs, labels = yticks() # Get the current locations and labels. + >>> yticks(np.arange(0, 1, step=0.2)) # Set label locations. + >>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels. + >>> yticks([0, 1, 2], ['January', 'February', 'March'], + ... rotation=45) # Set text labels and properties. + >>> yticks([]) # Disable yticks. + """ + ax = gca() + + locs: list[Tick] | np.ndarray + if ticks is None: + locs = ax.get_yticks(minor=minor) + if labels is not None: + raise TypeError("yticks(): Parameter 'labels' can't be set " + "without setting 'ticks'") + else: + locs = ax.set_yticks(ticks, minor=minor) + + labels_out: list[Text] = [] + if labels is None: + labels_out = ax.get_yticklabels(minor=minor) + for l in labels_out: + l._internal_update(kwargs) + else: + labels_out = ax.set_yticklabels(labels, minor=minor, **kwargs) + + return locs, labels_out + + +def rgrids( + radii: ArrayLike | None = None, + labels: Sequence[str | Text] | None = None, + angle: float | None = None, + fmt: str | None = None, + **kwargs +) -> tuple[list[Line2D], list[Text]]: + """ + Get or set the radial gridlines on the current polar plot. + + Call signatures:: + + lines, labels = rgrids() + lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs) + + When called with no arguments, `.rgrids` simply returns the tuple + (*lines*, *labels*). When called with arguments, the labels will + appear at the specified radial distances and angle. + + Parameters + ---------- + radii : tuple with floats + The radii for the radial gridlines + + labels : tuple with strings or None + The labels to use at each radial gridline. The + `matplotlib.ticker.ScalarFormatter` will be used if None. + + angle : float + The angular position of the radius labels in degrees. + + fmt : str or None + Format string used in `matplotlib.ticker.FormatStrFormatter`. + For example '%f'. + + Returns + ------- + lines : list of `.lines.Line2D` + The radial gridlines. + + labels : list of `.text.Text` + The tick labels. + + Other Parameters + ---------------- + **kwargs + *kwargs* are optional `.Text` properties for the labels. + + See Also + -------- + .pyplot.thetagrids + .projections.polar.PolarAxes.set_rgrids + .Axis.get_gridlines + .Axis.get_ticklabels + + Examples + -------- + :: + + # set the locations of the radial gridlines + lines, labels = rgrids( (0.25, 0.5, 1.0) ) + + # set the locations and labels of the radial gridlines + lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' )) + """ + ax = gca() + if not isinstance(ax, PolarAxes): + raise RuntimeError('rgrids only defined for polar Axes') + if all(p is None for p in [radii, labels, angle, fmt]) and not kwargs: + lines_out: list[Line2D] = ax.yaxis.get_gridlines() + labels_out: list[Text] = ax.yaxis.get_ticklabels() + elif radii is None: + raise TypeError("'radii' cannot be None when other parameters are passed") + else: + lines_out, labels_out = ax.set_rgrids( + radii, labels=labels, angle=angle, fmt=fmt, **kwargs) + return lines_out, labels_out + + +def thetagrids( + angles: ArrayLike | None = None, + labels: Sequence[str | Text] | None = None, + fmt: str | None = None, + **kwargs +) -> tuple[list[Line2D], list[Text]]: + """ + Get or set the theta gridlines on the current polar plot. + + Call signatures:: + + lines, labels = thetagrids() + lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs) + + When called with no arguments, `.thetagrids` simply returns the tuple + (*lines*, *labels*). When called with arguments, the labels will + appear at the specified angles. + + Parameters + ---------- + angles : tuple with floats, degrees + The angles of the theta gridlines. + + labels : tuple with strings or None + The labels to use at each radial gridline. The + `.projections.polar.ThetaFormatter` will be used if None. + + fmt : str or None + Format string used in `matplotlib.ticker.FormatStrFormatter`. + For example '%f'. Note that the angle in radians will be used. + + Returns + ------- + lines : list of `.lines.Line2D` + The theta gridlines. + + labels : list of `.text.Text` + The tick labels. + + Other Parameters + ---------------- + **kwargs + *kwargs* are optional `.Text` properties for the labels. + + See Also + -------- + .pyplot.rgrids + .projections.polar.PolarAxes.set_thetagrids + .Axis.get_gridlines + .Axis.get_ticklabels + + Examples + -------- + :: + + # set the locations of the angular gridlines + lines, labels = thetagrids(range(45, 360, 90)) + + # set the locations and labels of the angular gridlines + lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE')) + """ + ax = gca() + if not isinstance(ax, PolarAxes): + raise RuntimeError('thetagrids only defined for polar Axes') + if all(param is None for param in [angles, labels, fmt]) and not kwargs: + lines_out: list[Line2D] = ax.xaxis.get_ticklines() + labels_out: list[Text] = ax.xaxis.get_ticklabels() + elif angles is None: + raise TypeError("'angles' cannot be None when other parameters are passed") + else: + lines_out, labels_out = ax.set_thetagrids(angles, + labels=labels, fmt=fmt, + **kwargs) + return lines_out, labels_out + + +@_api.deprecated("3.7", pending=True) +def get_plot_commands() -> list[str]: + """ + Get a sorted list of all of the plotting commands. + """ + NON_PLOT_COMMANDS = { + 'connect', 'disconnect', 'get_current_fig_manager', 'ginput', + 'new_figure_manager', 'waitforbuttonpress'} + return [name for name in _get_pyplot_commands() + if name not in NON_PLOT_COMMANDS] + + +def _get_pyplot_commands() -> list[str]: + # This works by searching for all functions in this module and removing + # a few hard-coded exclusions, as well as all of the colormap-setting + # functions, and anything marked as private with a preceding underscore. + exclude = {'colormaps', 'colors', 'get_plot_commands', *colormaps} + this_module = inspect.getmodule(get_plot_commands) + return sorted( + name for name, obj in globals().items() + if not name.startswith('_') and name not in exclude + and inspect.isfunction(obj) + and inspect.getmodule(obj) is this_module) + + +## Plotting part 1: manually generated functions and wrappers ## + + +@_copy_docstring_and_deprecators(Figure.colorbar) +def colorbar( + mappable: ScalarMappable | None = None, + cax: matplotlib.axes.Axes | None = None, + ax: matplotlib.axes.Axes | Iterable[matplotlib.axes.Axes] | None = None, + **kwargs +) -> Colorbar: + if mappable is None: + mappable = gci() + if mappable is None: + raise RuntimeError('No mappable was found to use for colorbar ' + 'creation. First define a mappable such as ' + 'an image (with imshow) or a contour set (' + 'with contourf).') + ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kwargs) + return ret + + +def clim(vmin: float | None = None, vmax: float | None = None) -> None: + """ + Set the color limits of the current image. + + If either *vmin* or *vmax* is None, the image min/max respectively + will be used for color scaling. + + If you want to set the clim of multiple images, use + `~.ScalarMappable.set_clim` on every image, for example:: + + for im in gca().get_images(): + im.set_clim(0, 0.5) + + """ + im = gci() + if im is None: + raise RuntimeError('You must first define an image, e.g., with imshow') + + im.set_clim(vmin, vmax) + + +def get_cmap(name: Colormap | str | None = None, lut: int | None = None) -> Colormap: + """ + Get a colormap instance, defaulting to rc values if *name* is None. + + Parameters + ---------- + name : `~matplotlib.colors.Colormap` or str or None, default: None + If a `.Colormap` instance, it will be returned. Otherwise, the name of + a colormap known to Matplotlib, which will be resampled by *lut*. The + default, None, means :rc:`image.cmap`. + lut : int or None, default: None + If *name* is not already a Colormap instance and *lut* is not None, the + colormap will be resampled to have *lut* entries in the lookup table. + + Returns + ------- + Colormap + """ + if name is None: + name = rcParams['image.cmap'] + if isinstance(name, Colormap): + return name + _api.check_in_list(sorted(_colormaps), name=name) + if lut is None: + return _colormaps[name] + else: + return _colormaps[name].resampled(lut) + + +def set_cmap(cmap: Colormap | str) -> None: + """ + Set the default colormap, and applies it to the current image if any. + + Parameters + ---------- + cmap : `~matplotlib.colors.Colormap` or str + A colormap instance or the name of a registered colormap. + + See Also + -------- + colormaps + get_cmap + """ + cmap = get_cmap(cmap) + + rc('image', cmap=cmap.name) + im = gci() + + if im is not None: + im.set_cmap(cmap) + + +@_copy_docstring_and_deprecators(matplotlib.image.imread) +def imread( + fname: str | pathlib.Path | BinaryIO, format: str | None = None +) -> np.ndarray: + return matplotlib.image.imread(fname, format) + + +@_copy_docstring_and_deprecators(matplotlib.image.imsave) +def imsave( + fname: str | os.PathLike | BinaryIO, arr: ArrayLike, **kwargs +) -> None: + matplotlib.image.imsave(fname, arr, **kwargs) + + +def matshow(A: ArrayLike, fignum: None | int = None, **kwargs) -> AxesImage: + """ + Display a 2D array as a matrix in a new figure window. + + The origin is set at the upper left hand corner. + The indexing is ``(row, column)`` so that the first index runs vertically + and the second index runs horizontally in the figure: + + .. code-block:: none + + A[0, 0] ⋯ A[0, M-1] + ⋮ ⋮ + A[N-1, 0] ⋯ A[N-1, M-1] + + The aspect ratio of the figure window is that of the array, + unless this would make an excessively short or narrow figure. + + Tick labels for the xaxis are placed on top. + + Parameters + ---------- + A : 2D array-like + The matrix to be displayed. + + fignum : None or int + If *None*, create a new, appropriately sized figure window. + + If 0, use the current Axes (creating one if there is none, without ever + adjusting the figure size). + + Otherwise, create a new Axes on the figure with the given number + (creating it at the appropriate size if it does not exist, but not + adjusting the figure size otherwise). Note that this will be drawn on + top of any preexisting Axes on the figure. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.axes.Axes.imshow` arguments + + """ + A = np.asanyarray(A) + if fignum == 0: + ax = gca() + else: + # Extract actual aspect ratio of array and make appropriately sized + # figure. + fig = figure(fignum, figsize=figaspect(A)) + ax = fig.add_axes((0.15, 0.09, 0.775, 0.775)) + im = ax.matshow(A, **kwargs) + sci(im) + return im + + +def polar(*args, **kwargs) -> list[Line2D]: + """ + Make a polar plot. + + call signature:: + + polar(theta, r, **kwargs) + + Multiple *theta*, *r* arguments are supported, with format strings, as in + `plot`. + """ + # If an axis already exists, check if it has a polar projection + if gcf().get_axes(): + ax = gca() + if not isinstance(ax, PolarAxes): + _api.warn_external('Trying to create polar plot on an Axes ' + 'that does not have a polar projection.') + else: + ax = axes(projection="polar") + return ax.plot(*args, **kwargs) + + +# If rcParams['backend_fallback'] is true, and an interactive backend is +# requested, ignore rcParams['backend'] and force selection of a backend that +# is compatible with the current running interactive framework. +if (rcParams["backend_fallback"] + and rcParams._get_backend_or_none() in ( # type: ignore[attr-defined] + set(backend_registry.list_builtin(BackendFilter.INTERACTIVE)) - + {'webagg', 'nbagg'}) + and cbook._get_running_interactive_framework()): + rcParams._set("backend", rcsetup._auto_backend_sentinel) + +# fmt: on + +################# REMAINING CONTENT GENERATED BY boilerplate.py ############## + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.figimage) +def figimage( + X: ArrayLike, + xo: int = 0, + yo: int = 0, + alpha: float | None = None, + norm: str | Normalize | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + origin: Literal["upper", "lower"] | None = None, + resize: bool = False, + **kwargs, +) -> FigureImage: + return gcf().figimage( + X, + xo=xo, + yo=yo, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + origin=origin, + resize=resize, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.text) +def figtext( + x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs +) -> Text: + return gcf().text(x, y, s, fontdict=fontdict, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.gca) +def gca() -> Axes: + return gcf().gca() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure._gci) +def gci() -> ScalarMappable | None: + return gcf()._gci() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.ginput) +def ginput( + n: int = 1, + timeout: float = 30, + show_clicks: bool = True, + mouse_add: MouseButton = MouseButton.LEFT, + mouse_pop: MouseButton = MouseButton.RIGHT, + mouse_stop: MouseButton = MouseButton.MIDDLE, +) -> list[tuple[int, int]]: + return gcf().ginput( + n=n, + timeout=timeout, + show_clicks=show_clicks, + mouse_add=mouse_add, + mouse_pop=mouse_pop, + mouse_stop=mouse_stop, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.subplots_adjust) +def subplots_adjust( + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + wspace: float | None = None, + hspace: float | None = None, +) -> None: + gcf().subplots_adjust( + left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.suptitle) +def suptitle(t: str, **kwargs) -> Text: + return gcf().suptitle(t, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.tight_layout) +def tight_layout( + *, + pad: float = 1.08, + h_pad: float | None = None, + w_pad: float | None = None, + rect: tuple[float, float, float, float] | None = None, +) -> None: + gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Figure.waitforbuttonpress) +def waitforbuttonpress(timeout: float = -1) -> None | bool: + return gcf().waitforbuttonpress(timeout=timeout) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.acorr) +def acorr( + x: ArrayLike, *, data=None, **kwargs +) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: + return gca().acorr(x, **({"data": data} if data is not None else {}), **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.angle_spectrum) +def angle_spectrum( + x: ArrayLike, + Fs: float | None = None, + Fc: int | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, Line2D]: + return gca().angle_spectrum( + x, + Fs=Fs, + Fc=Fc, + window=window, + pad_to=pad_to, + sides=sides, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.annotate) +def annotate( + text: str, + xy: tuple[float, float], + xytext: tuple[float, float] | None = None, + xycoords: str + | Artist + | Transform + | Callable[[RendererBase], Bbox | Transform] + | tuple[float, float] = "data", + textcoords: str + | Artist + | Transform + | Callable[[RendererBase], Bbox | Transform] + | tuple[float, float] + | None = None, + arrowprops: dict[str, Any] | None = None, + annotation_clip: bool | None = None, + **kwargs, +) -> Annotation: + return gca().annotate( + text, + xy, + xytext=xytext, + xycoords=xycoords, + textcoords=textcoords, + arrowprops=arrowprops, + annotation_clip=annotation_clip, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.arrow) +def arrow(x: float, y: float, dx: float, dy: float, **kwargs) -> FancyArrow: + return gca().arrow(x, y, dx, dy, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.autoscale) +def autoscale( + enable: bool = True, + axis: Literal["both", "x", "y"] = "both", + tight: bool | None = None, +) -> None: + gca().autoscale(enable=enable, axis=axis, tight=tight) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axhline) +def axhline(y: float = 0, xmin: float = 0, xmax: float = 1, **kwargs) -> Line2D: + return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axhspan) +def axhspan( + ymin: float, ymax: float, xmin: float = 0, xmax: float = 1, **kwargs +) -> Rectangle: + return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axis) +def axis( + arg: tuple[float, float, float, float] | bool | str | None = None, + /, + *, + emit: bool = True, + **kwargs, +) -> tuple[float, float, float, float]: + return gca().axis(arg, emit=emit, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axline) +def axline( + xy1: tuple[float, float], + xy2: tuple[float, float] | None = None, + *, + slope: float | None = None, + **kwargs, +) -> AxLine: + return gca().axline(xy1, xy2=xy2, slope=slope, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axvline) +def axvline(x: float = 0, ymin: float = 0, ymax: float = 1, **kwargs) -> Line2D: + return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.axvspan) +def axvspan( + xmin: float, xmax: float, ymin: float = 0, ymax: float = 1, **kwargs +) -> Rectangle: + return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.bar) +def bar( + x: float | ArrayLike, + height: float | ArrayLike, + width: float | ArrayLike = 0.8, + bottom: float | ArrayLike | None = None, + *, + align: Literal["center", "edge"] = "center", + data=None, + **kwargs, +) -> BarContainer: + return gca().bar( + x, + height, + width=width, + bottom=bottom, + align=align, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.barbs) +def barbs(*args, data=None, **kwargs) -> Barbs: + return gca().barbs(*args, **({"data": data} if data is not None else {}), **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.barh) +def barh( + y: float | ArrayLike, + width: float | ArrayLike, + height: float | ArrayLike = 0.8, + left: float | ArrayLike | None = None, + *, + align: Literal["center", "edge"] = "center", + data=None, + **kwargs, +) -> BarContainer: + return gca().barh( + y, + width, + height=height, + left=left, + align=align, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.bar_label) +def bar_label( + container: BarContainer, + labels: ArrayLike | None = None, + *, + fmt: str | Callable[[float], str] = "%g", + label_type: Literal["center", "edge"] = "edge", + padding: float = 0, + **kwargs, +) -> list[Annotation]: + return gca().bar_label( + container, + labels=labels, + fmt=fmt, + label_type=label_type, + padding=padding, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.boxplot) +def boxplot( + x: ArrayLike | Sequence[ArrayLike], + notch: bool | None = None, + sym: str | None = None, + vert: bool | None = None, + whis: float | tuple[float, float] | None = None, + positions: ArrayLike | None = None, + widths: float | ArrayLike | None = None, + patch_artist: bool | None = None, + bootstrap: int | None = None, + usermedians: ArrayLike | None = None, + conf_intervals: ArrayLike | None = None, + meanline: bool | None = None, + showmeans: bool | None = None, + showcaps: bool | None = None, + showbox: bool | None = None, + showfliers: bool | None = None, + boxprops: dict[str, Any] | None = None, + tick_labels: Sequence[str] | None = None, + flierprops: dict[str, Any] | None = None, + medianprops: dict[str, Any] | None = None, + meanprops: dict[str, Any] | None = None, + capprops: dict[str, Any] | None = None, + whiskerprops: dict[str, Any] | None = None, + manage_ticks: bool = True, + autorange: bool = False, + zorder: float | None = None, + capwidths: float | ArrayLike | None = None, + label: Sequence[str] | None = None, + *, + data=None, +) -> dict[str, Any]: + return gca().boxplot( + x, + notch=notch, + sym=sym, + vert=vert, + whis=whis, + positions=positions, + widths=widths, + patch_artist=patch_artist, + bootstrap=bootstrap, + usermedians=usermedians, + conf_intervals=conf_intervals, + meanline=meanline, + showmeans=showmeans, + showcaps=showcaps, + showbox=showbox, + showfliers=showfliers, + boxprops=boxprops, + tick_labels=tick_labels, + flierprops=flierprops, + medianprops=medianprops, + meanprops=meanprops, + capprops=capprops, + whiskerprops=whiskerprops, + manage_ticks=manage_ticks, + autorange=autorange, + zorder=zorder, + capwidths=capwidths, + label=label, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.broken_barh) +def broken_barh( + xranges: Sequence[tuple[float, float]], + yrange: tuple[float, float], + *, + data=None, + **kwargs, +) -> PolyCollection: + return gca().broken_barh( + xranges, yrange, **({"data": data} if data is not None else {}), **kwargs + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.clabel) +def clabel(CS: ContourSet, levels: ArrayLike | None = None, **kwargs) -> list[Text]: + return gca().clabel(CS, levels=levels, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.cohere) +def cohere( + x: ArrayLike, + y: ArrayLike, + NFFT: int = 256, + Fs: float = 2, + Fc: int = 0, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] = mlab.detrend_none, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike = mlab.window_hanning, + noverlap: int = 0, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] = "default", + scale_by_freq: bool | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray]: + return gca().cohere( + x, + y, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.contour) +def contour(*args, data=None, **kwargs) -> QuadContourSet: + __ret = gca().contour( + *args, **({"data": data} if data is not None else {}), **kwargs + ) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.contourf) +def contourf(*args, data=None, **kwargs) -> QuadContourSet: + __ret = gca().contourf( + *args, **({"data": data} if data is not None else {}), **kwargs + ) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.csd) +def csd( + x: ArrayLike, + y: ArrayLike, + NFFT: int | None = None, + Fs: float | None = None, + Fc: int | None = None, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + noverlap: int | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale_by_freq: bool | None = None, + return_line: bool | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: + return gca().csd( + x, + y, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + return_line=return_line, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.ecdf) +def ecdf( + x: ArrayLike, + weights: ArrayLike | None = None, + *, + complementary: bool = False, + orientation: Literal["vertical", "horizonatal"] = "vertical", + compress: bool = False, + data=None, + **kwargs, +) -> Line2D: + return gca().ecdf( + x, + weights=weights, + complementary=complementary, + orientation=orientation, + compress=compress, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.errorbar) +def errorbar( + x: float | ArrayLike, + y: float | ArrayLike, + yerr: float | ArrayLike | None = None, + xerr: float | ArrayLike | None = None, + fmt: str = "", + ecolor: ColorType | None = None, + elinewidth: float | None = None, + capsize: float | None = None, + barsabove: bool = False, + lolims: bool | ArrayLike = False, + uplims: bool | ArrayLike = False, + xlolims: bool | ArrayLike = False, + xuplims: bool | ArrayLike = False, + errorevery: int | tuple[int, int] = 1, + capthick: float | None = None, + *, + data=None, + **kwargs, +) -> ErrorbarContainer: + return gca().errorbar( + x, + y, + yerr=yerr, + xerr=xerr, + fmt=fmt, + ecolor=ecolor, + elinewidth=elinewidth, + capsize=capsize, + barsabove=barsabove, + lolims=lolims, + uplims=uplims, + xlolims=xlolims, + xuplims=xuplims, + errorevery=errorevery, + capthick=capthick, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.eventplot) +def eventplot( + positions: ArrayLike | Sequence[ArrayLike], + orientation: Literal["horizontal", "vertical"] = "horizontal", + lineoffsets: float | Sequence[float] = 1, + linelengths: float | Sequence[float] = 1, + linewidths: float | Sequence[float] | None = None, + colors: ColorType | Sequence[ColorType] | None = None, + alpha: float | Sequence[float] | None = None, + linestyles: LineStyleType | Sequence[LineStyleType] = "solid", + *, + data=None, + **kwargs, +) -> EventCollection: + return gca().eventplot( + positions, + orientation=orientation, + lineoffsets=lineoffsets, + linelengths=linelengths, + linewidths=linewidths, + colors=colors, + alpha=alpha, + linestyles=linestyles, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.fill) +def fill(*args, data=None, **kwargs) -> list[Polygon]: + return gca().fill(*args, **({"data": data} if data is not None else {}), **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.fill_between) +def fill_between( + x: ArrayLike, + y1: ArrayLike | float, + y2: ArrayLike | float = 0, + where: Sequence[bool] | None = None, + interpolate: bool = False, + step: Literal["pre", "post", "mid"] | None = None, + *, + data=None, + **kwargs, +) -> PolyCollection: + return gca().fill_between( + x, + y1, + y2=y2, + where=where, + interpolate=interpolate, + step=step, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.fill_betweenx) +def fill_betweenx( + y: ArrayLike, + x1: ArrayLike | float, + x2: ArrayLike | float = 0, + where: Sequence[bool] | None = None, + step: Literal["pre", "post", "mid"] | None = None, + interpolate: bool = False, + *, + data=None, + **kwargs, +) -> PolyCollection: + return gca().fill_betweenx( + y, + x1, + x2=x2, + where=where, + step=step, + interpolate=interpolate, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.grid) +def grid( + visible: bool | None = None, + which: Literal["major", "minor", "both"] = "major", + axis: Literal["both", "x", "y"] = "both", + **kwargs, +) -> None: + gca().grid(visible=visible, which=which, axis=axis, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hexbin) +def hexbin( + x: ArrayLike, + y: ArrayLike, + C: ArrayLike | None = None, + gridsize: int | tuple[int, int] = 100, + bins: Literal["log"] | int | Sequence[float] | None = None, + xscale: Literal["linear", "log"] = "linear", + yscale: Literal["linear", "log"] = "linear", + extent: tuple[float, float, float, float] | None = None, + cmap: str | Colormap | None = None, + norm: str | Normalize | None = None, + vmin: float | None = None, + vmax: float | None = None, + alpha: float | None = None, + linewidths: float | None = None, + edgecolors: Literal["face", "none"] | ColorType = "face", + reduce_C_function: Callable[[np.ndarray | list[float]], float] = np.mean, + mincnt: int | None = None, + marginals: bool = False, + *, + data=None, + **kwargs, +) -> PolyCollection: + __ret = gca().hexbin( + x, + y, + C=C, + gridsize=gridsize, + bins=bins, + xscale=xscale, + yscale=yscale, + extent=extent, + cmap=cmap, + norm=norm, + vmin=vmin, + vmax=vmax, + alpha=alpha, + linewidths=linewidths, + edgecolors=edgecolors, + reduce_C_function=reduce_C_function, + mincnt=mincnt, + marginals=marginals, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hist) +def hist( + x: ArrayLike | Sequence[ArrayLike], + bins: int | Sequence[float] | str | None = None, + range: tuple[float, float] | None = None, + density: bool = False, + weights: ArrayLike | None = None, + cumulative: bool | float = False, + bottom: ArrayLike | float | None = None, + histtype: Literal["bar", "barstacked", "step", "stepfilled"] = "bar", + align: Literal["left", "mid", "right"] = "mid", + orientation: Literal["vertical", "horizontal"] = "vertical", + rwidth: float | None = None, + log: bool = False, + color: ColorType | Sequence[ColorType] | None = None, + label: str | Sequence[str] | None = None, + stacked: bool = False, + *, + data=None, + **kwargs, +) -> tuple[ + np.ndarray | list[np.ndarray], + np.ndarray, + BarContainer | Polygon | list[BarContainer | Polygon], +]: + return gca().hist( + x, + bins=bins, + range=range, + density=density, + weights=weights, + cumulative=cumulative, + bottom=bottom, + histtype=histtype, + align=align, + orientation=orientation, + rwidth=rwidth, + log=log, + color=color, + label=label, + stacked=stacked, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.stairs) +def stairs( + values: ArrayLike, + edges: ArrayLike | None = None, + *, + orientation: Literal["vertical", "horizontal"] = "vertical", + baseline: float | ArrayLike | None = 0, + fill: bool = False, + data=None, + **kwargs, +) -> StepPatch: + return gca().stairs( + values, + edges=edges, + orientation=orientation, + baseline=baseline, + fill=fill, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hist2d) +def hist2d( + x: ArrayLike, + y: ArrayLike, + bins: None | int | tuple[int, int] | ArrayLike | tuple[ArrayLike, ArrayLike] = 10, + range: ArrayLike | None = None, + density: bool = False, + weights: ArrayLike | None = None, + cmin: float | None = None, + cmax: float | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: + __ret = gca().hist2d( + x, + y, + bins=bins, + range=range, + density=density, + weights=weights, + cmin=cmin, + cmax=cmax, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret[-1]) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.hlines) +def hlines( + y: float | ArrayLike, + xmin: float | ArrayLike, + xmax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = None, + linestyles: LineStyleType = "solid", + label: str = "", + *, + data=None, + **kwargs, +) -> LineCollection: + return gca().hlines( + y, + xmin, + xmax, + colors=colors, + linestyles=linestyles, + label=label, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.imshow) +def imshow( + X: ArrayLike | PIL.Image.Image, + cmap: str | Colormap | None = None, + norm: str | Normalize | None = None, + *, + aspect: Literal["equal", "auto"] | float | None = None, + interpolation: str | None = None, + alpha: float | ArrayLike | None = None, + vmin: float | None = None, + vmax: float | None = None, + origin: Literal["upper", "lower"] | None = None, + extent: tuple[float, float, float, float] | None = None, + interpolation_stage: Literal["data", "rgba"] | None = None, + filternorm: bool = True, + filterrad: float = 4.0, + resample: bool | None = None, + url: str | None = None, + data=None, + **kwargs, +) -> AxesImage: + __ret = gca().imshow( + X, + cmap=cmap, + norm=norm, + aspect=aspect, + interpolation=interpolation, + alpha=alpha, + vmin=vmin, + vmax=vmax, + origin=origin, + extent=extent, + interpolation_stage=interpolation_stage, + filternorm=filternorm, + filterrad=filterrad, + resample=resample, + url=url, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.legend) +def legend(*args, **kwargs) -> Legend: + return gca().legend(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.locator_params) +def locator_params( + axis: Literal["both", "x", "y"] = "both", tight: bool | None = None, **kwargs +) -> None: + gca().locator_params(axis=axis, tight=tight, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.loglog) +def loglog(*args, **kwargs) -> list[Line2D]: + return gca().loglog(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.magnitude_spectrum) +def magnitude_spectrum( + x: ArrayLike, + Fs: float | None = None, + Fc: int | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale: Literal["default", "linear", "dB"] | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, Line2D]: + return gca().magnitude_spectrum( + x, + Fs=Fs, + Fc=Fc, + window=window, + pad_to=pad_to, + sides=sides, + scale=scale, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.margins) +def margins( + *margins: float, + x: float | None = None, + y: float | None = None, + tight: bool | None = True, +) -> tuple[float, float] | None: + return gca().margins(*margins, x=x, y=y, tight=tight) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.minorticks_off) +def minorticks_off() -> None: + gca().minorticks_off() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.minorticks_on) +def minorticks_on() -> None: + gca().minorticks_on() + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.pcolor) +def pcolor( + *args: ArrayLike, + shading: Literal["flat", "nearest", "auto"] | None = None, + alpha: float | None = None, + norm: str | Normalize | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + data=None, + **kwargs, +) -> Collection: + __ret = gca().pcolor( + *args, + shading=shading, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.pcolormesh) +def pcolormesh( + *args: ArrayLike, + alpha: float | None = None, + norm: str | Normalize | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + shading: Literal["flat", "nearest", "gouraud", "auto"] | None = None, + antialiased: bool = False, + data=None, + **kwargs, +) -> QuadMesh: + __ret = gca().pcolormesh( + *args, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + shading=shading, + antialiased=antialiased, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.phase_spectrum) +def phase_spectrum( + x: ArrayLike, + Fs: float | None = None, + Fc: int | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, Line2D]: + return gca().phase_spectrum( + x, + Fs=Fs, + Fc=Fc, + window=window, + pad_to=pad_to, + sides=sides, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.pie) +def pie( + x: ArrayLike, + explode: ArrayLike | None = None, + labels: Sequence[str] | None = None, + colors: ColorType | Sequence[ColorType] | None = None, + autopct: str | Callable[[float], str] | None = None, + pctdistance: float = 0.6, + shadow: bool = False, + labeldistance: float | None = 1.1, + startangle: float = 0, + radius: float = 1, + counterclock: bool = True, + wedgeprops: dict[str, Any] | None = None, + textprops: dict[str, Any] | None = None, + center: tuple[float, float] = (0, 0), + frame: bool = False, + rotatelabels: bool = False, + *, + normalize: bool = True, + hatch: str | Sequence[str] | None = None, + data=None, +) -> tuple[list[Wedge], list[Text]] | tuple[list[Wedge], list[Text], list[Text]]: + return gca().pie( + x, + explode=explode, + labels=labels, + colors=colors, + autopct=autopct, + pctdistance=pctdistance, + shadow=shadow, + labeldistance=labeldistance, + startangle=startangle, + radius=radius, + counterclock=counterclock, + wedgeprops=wedgeprops, + textprops=textprops, + center=center, + frame=frame, + rotatelabels=rotatelabels, + normalize=normalize, + hatch=hatch, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.plot) +def plot( + *args: float | ArrayLike | str, + scalex: bool = True, + scaley: bool = True, + data=None, + **kwargs, +) -> list[Line2D]: + return gca().plot( + *args, + scalex=scalex, + scaley=scaley, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.plot_date) +def plot_date( + x: ArrayLike, + y: ArrayLike, + fmt: str = "o", + tz: str | datetime.tzinfo | None = None, + xdate: bool = True, + ydate: bool = False, + *, + data=None, + **kwargs, +) -> list[Line2D]: + return gca().plot_date( + x, + y, + fmt=fmt, + tz=tz, + xdate=xdate, + ydate=ydate, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.psd) +def psd( + x: ArrayLike, + NFFT: int | None = None, + Fs: float | None = None, + Fc: int | None = None, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + noverlap: int | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale_by_freq: bool | None = None, + return_line: bool | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: + return gca().psd( + x, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + return_line=return_line, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.quiver) +def quiver(*args, data=None, **kwargs) -> Quiver: + __ret = gca().quiver( + *args, **({"data": data} if data is not None else {}), **kwargs + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.quiverkey) +def quiverkey( + Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs +) -> QuiverKey: + return gca().quiverkey(Q, X, Y, U, label, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.scatter) +def scatter( + x: float | ArrayLike, + y: float | ArrayLike, + s: float | ArrayLike | None = None, + c: ArrayLike | Sequence[ColorType] | ColorType | None = None, + marker: MarkerType | None = None, + cmap: str | Colormap | None = None, + norm: str | Normalize | None = None, + vmin: float | None = None, + vmax: float | None = None, + alpha: float | None = None, + linewidths: float | Sequence[float] | None = None, + *, + edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = None, + plotnonfinite: bool = False, + data=None, + **kwargs, +) -> PathCollection: + __ret = gca().scatter( + x, + y, + s=s, + c=c, + marker=marker, + cmap=cmap, + norm=norm, + vmin=vmin, + vmax=vmax, + alpha=alpha, + linewidths=linewidths, + edgecolors=edgecolors, + plotnonfinite=plotnonfinite, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.semilogx) +def semilogx(*args, **kwargs) -> list[Line2D]: + return gca().semilogx(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.semilogy) +def semilogy(*args, **kwargs) -> list[Line2D]: + return gca().semilogy(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.specgram) +def specgram( + x: ArrayLike, + NFFT: int | None = None, + Fs: float | None = None, + Fc: int | None = None, + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = None, + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None, + noverlap: int | None = None, + cmap: str | Colormap | None = None, + xextent: tuple[float, float] | None = None, + pad_to: int | None = None, + sides: Literal["default", "onesided", "twosided"] | None = None, + scale_by_freq: bool | None = None, + mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = None, + scale: Literal["default", "linear", "dB"] | None = None, + vmin: float | None = None, + vmax: float | None = None, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: + __ret = gca().specgram( + x, + NFFT=NFFT, + Fs=Fs, + Fc=Fc, + detrend=detrend, + window=window, + noverlap=noverlap, + cmap=cmap, + xextent=xextent, + pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + mode=mode, + scale=scale, + vmin=vmin, + vmax=vmax, + **({"data": data} if data is not None else {}), + **kwargs, + ) + sci(__ret[-1]) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.spy) +def spy( + Z: ArrayLike, + precision: float | Literal["present"] = 0, + marker: str | None = None, + markersize: float | None = None, + aspect: Literal["equal", "auto"] | float | None = "equal", + origin: Literal["upper", "lower"] = "upper", + **kwargs, +) -> AxesImage: + __ret = gca().spy( + Z, + precision=precision, + marker=marker, + markersize=markersize, + aspect=aspect, + origin=origin, + **kwargs, + ) + if isinstance(__ret, cm.ScalarMappable): + sci(__ret) # noqa + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.stackplot) +def stackplot( + x, *args, labels=(), colors=None, hatch=None, baseline="zero", data=None, **kwargs +): + return gca().stackplot( + x, + *args, + labels=labels, + colors=colors, + hatch=hatch, + baseline=baseline, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.stem) +def stem( + *args: ArrayLike | str, + linefmt: str | None = None, + markerfmt: str | None = None, + basefmt: str | None = None, + bottom: float = 0, + label: str | None = None, + orientation: Literal["vertical", "horizontal"] = "vertical", + data=None, +) -> StemContainer: + return gca().stem( + *args, + linefmt=linefmt, + markerfmt=markerfmt, + basefmt=basefmt, + bottom=bottom, + label=label, + orientation=orientation, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.step) +def step( + x: ArrayLike, + y: ArrayLike, + *args, + where: Literal["pre", "post", "mid"] = "pre", + data=None, + **kwargs, +) -> list[Line2D]: + return gca().step( + x, + y, + *args, + where=where, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.streamplot) +def streamplot( + 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, + *, + data=None, +): + __ret = gca().streamplot( + x, + y, + u, + v, + density=density, + linewidth=linewidth, + color=color, + cmap=cmap, + norm=norm, + arrowsize=arrowsize, + arrowstyle=arrowstyle, + minlength=minlength, + transform=transform, + zorder=zorder, + start_points=start_points, + maxlength=maxlength, + integration_direction=integration_direction, + broken_streamlines=broken_streamlines, + **({"data": data} if data is not None else {}), + ) + sci(__ret.lines) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.table) +def table( + 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, +): + return gca().table( + cellText=cellText, + cellColours=cellColours, + cellLoc=cellLoc, + colWidths=colWidths, + rowLabels=rowLabels, + rowColours=rowColours, + rowLoc=rowLoc, + colLabels=colLabels, + colColours=colColours, + colLoc=colLoc, + loc=loc, + bbox=bbox, + edges=edges, + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.text) +def text( + x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs +) -> Text: + return gca().text(x, y, s, fontdict=fontdict, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tick_params) +def tick_params(axis: Literal["both", "x", "y"] = "both", **kwargs) -> None: + gca().tick_params(axis=axis, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.ticklabel_format) +def ticklabel_format( + *, + axis: Literal["both", "x", "y"] = "both", + style: Literal["", "sci", "scientific", "plain"] | None = None, + scilimits: tuple[int, int] | None = None, + useOffset: bool | float | None = None, + useLocale: bool | None = None, + useMathText: bool | None = None, +) -> None: + gca().ticklabel_format( + axis=axis, + style=style, + scilimits=scilimits, + useOffset=useOffset, + useLocale=useLocale, + useMathText=useMathText, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tricontour) +def tricontour(*args, **kwargs): + __ret = gca().tricontour(*args, **kwargs) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tricontourf) +def tricontourf(*args, **kwargs): + __ret = gca().tricontourf(*args, **kwargs) + if __ret._A is not None: # type: ignore[attr-defined] + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.tripcolor) +def tripcolor( + *args, + alpha=1.0, + norm=None, + cmap=None, + vmin=None, + vmax=None, + shading="flat", + facecolors=None, + **kwargs, +): + __ret = gca().tripcolor( + *args, + alpha=alpha, + norm=norm, + cmap=cmap, + vmin=vmin, + vmax=vmax, + shading=shading, + facecolors=facecolors, + **kwargs, + ) + sci(__ret) + return __ret + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.triplot) +def triplot(*args, **kwargs): + return gca().triplot(*args, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.violinplot) +def violinplot( + dataset: ArrayLike | Sequence[ArrayLike], + positions: ArrayLike | None = None, + vert: bool = True, + widths: float | ArrayLike = 0.5, + showmeans: bool = False, + showextrema: bool = True, + showmedians: bool = False, + quantiles: Sequence[float | Sequence[float]] | None = None, + points: int = 100, + bw_method: Literal["scott", "silverman"] + | float + | Callable[[GaussianKDE], float] + | None = None, + side: Literal["both", "low", "high"] = "both", + *, + data=None, +) -> dict[str, Collection]: + return gca().violinplot( + dataset, + positions=positions, + vert=vert, + widths=widths, + showmeans=showmeans, + showextrema=showextrema, + showmedians=showmedians, + quantiles=quantiles, + points=points, + bw_method=bw_method, + side=side, + **({"data": data} if data is not None else {}), + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.vlines) +def vlines( + x: float | ArrayLike, + ymin: float | ArrayLike, + ymax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = None, + linestyles: LineStyleType = "solid", + label: str = "", + *, + data=None, + **kwargs, +) -> LineCollection: + return gca().vlines( + x, + ymin, + ymax, + colors=colors, + linestyles=linestyles, + label=label, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.xcorr) +def xcorr( + x: ArrayLike, + y: ArrayLike, + normed: bool = True, + detrend: Callable[[ArrayLike], ArrayLike] = mlab.detrend_none, + usevlines: bool = True, + maxlags: int = 10, + *, + data=None, + **kwargs, +) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: + return gca().xcorr( + x, + y, + normed=normed, + detrend=detrend, + usevlines=usevlines, + maxlags=maxlags, + **({"data": data} if data is not None else {}), + **kwargs, + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes._sci) +def sci(im: ScalarMappable) -> None: + gca()._sci(im) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_title) +def title( + label: str, + fontdict: dict[str, Any] | None = None, + loc: Literal["left", "center", "right"] | None = None, + pad: float | None = None, + *, + y: float | None = None, + **kwargs, +) -> Text: + return gca().set_title(label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_xlabel) +def xlabel( + xlabel: str, + fontdict: dict[str, Any] | None = None, + labelpad: float | None = None, + *, + loc: Literal["left", "center", "right"] | None = None, + **kwargs, +) -> Text: + return gca().set_xlabel( + xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_ylabel) +def ylabel( + ylabel: str, + fontdict: dict[str, Any] | None = None, + labelpad: float | None = None, + *, + loc: Literal["bottom", "center", "top"] | None = None, + **kwargs, +) -> Text: + return gca().set_ylabel( + ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs + ) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_xscale) +def xscale(value: str | ScaleBase, **kwargs) -> None: + gca().set_xscale(value, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +@_copy_docstring_and_deprecators(Axes.set_yscale) +def yscale(value: str | ScaleBase, **kwargs) -> None: + gca().set_yscale(value, **kwargs) + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def autumn() -> None: + """ + Set the colormap to 'autumn'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("autumn") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def bone() -> None: + """ + Set the colormap to 'bone'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("bone") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def cool() -> None: + """ + Set the colormap to 'cool'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("cool") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def copper() -> None: + """ + Set the colormap to 'copper'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("copper") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def flag() -> None: + """ + Set the colormap to 'flag'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("flag") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def gray() -> None: + """ + Set the colormap to 'gray'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("gray") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def hot() -> None: + """ + Set the colormap to 'hot'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("hot") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def hsv() -> None: + """ + Set the colormap to 'hsv'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("hsv") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def jet() -> None: + """ + Set the colormap to 'jet'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("jet") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def pink() -> None: + """ + Set the colormap to 'pink'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("pink") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def prism() -> None: + """ + Set the colormap to 'prism'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("prism") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def spring() -> None: + """ + Set the colormap to 'spring'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("spring") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def summer() -> None: + """ + Set the colormap to 'summer'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("summer") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def winter() -> None: + """ + Set the colormap to 'winter'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("winter") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def magma() -> None: + """ + Set the colormap to 'magma'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("magma") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def inferno() -> None: + """ + Set the colormap to 'inferno'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("inferno") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def plasma() -> None: + """ + Set the colormap to 'plasma'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("plasma") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def viridis() -> None: + """ + Set the colormap to 'viridis'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("viridis") + + +# Autogenerated by boilerplate.py. Do not edit as changes will be lost. +def nipy_spectral() -> None: + """ + Set the colormap to 'nipy_spectral'. + + This changes the default colormap as well as the colormap of the current + image if there is one. See ``help(colormaps)`` for more information. + """ + set_cmap("nipy_spectral") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/rcsetup.py b/llava_next/lib/python3.10/site-packages/matplotlib/rcsetup.py new file mode 100644 index 0000000000000000000000000000000000000000..b0cd22098489b158785abf2f57f88119ade9757c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/rcsetup.py @@ -0,0 +1,1377 @@ +""" +The rcsetup module contains the validation code for customization using +Matplotlib's rc settings. + +Each rc setting is assigned a function used to validate any attempted changes +to that setting. The validation functions are defined in the rcsetup module, +and are used to construct the rcParams global object which stores the settings +and is referenced throughout Matplotlib. + +The default values of the rc settings are set in the default matplotlibrc file. +Any additions or deletions to the parameter set listed here should also be +propagated to the :file:`lib/matplotlib/mpl-data/matplotlibrc` in Matplotlib's +root source directory. +""" + +import ast +from functools import lru_cache, reduce +from numbers import Real +import operator +import os +import re + +import numpy as np + +from matplotlib import _api, cbook +from matplotlib.backends import BackendFilter, backend_registry +from matplotlib.cbook import ls_mapper +from matplotlib.colors import Colormap, is_color_like +from matplotlib._fontconfig_pattern import parse_fontconfig_pattern +from matplotlib._enums import JoinStyle, CapStyle + +# Don't let the original cycler collide with our validating cycler +from cycler import Cycler, cycler as ccycler + + +@_api.caching_module_getattr +class __getattr__: + @_api.deprecated( + "3.9", + alternative="``matplotlib.backends.backend_registry.list_builtin" + "(matplotlib.backends.BackendFilter.INTERACTIVE)``") + @property + def interactive_bk(self): + return backend_registry.list_builtin(BackendFilter.INTERACTIVE) + + @_api.deprecated( + "3.9", + alternative="``matplotlib.backends.backend_registry.list_builtin" + "(matplotlib.backends.BackendFilter.NON_INTERACTIVE)``") + @property + def non_interactive_bk(self): + return backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE) + + @_api.deprecated( + "3.9", + alternative="``matplotlib.backends.backend_registry.list_builtin()``") + @property + def all_backends(self): + return backend_registry.list_builtin() + + +class ValidateInStrings: + def __init__(self, key, valid, ignorecase=False, *, + _deprecated_since=None): + """*valid* is a list of legal strings.""" + self.key = key + self.ignorecase = ignorecase + self._deprecated_since = _deprecated_since + + def func(s): + if ignorecase: + return s.lower() + else: + return s + self.valid = {func(k): k for k in valid} + + def __call__(self, s): + if self._deprecated_since: + name, = (k for k, v in globals().items() if v is self) + _api.warn_deprecated( + self._deprecated_since, name=name, obj_type="function") + if self.ignorecase and isinstance(s, str): + s = s.lower() + if s in self.valid: + return self.valid[s] + msg = (f"{s!r} is not a valid value for {self.key}; supported values " + f"are {[*self.valid.values()]}") + if (isinstance(s, str) + and (s.startswith('"') and s.endswith('"') + or s.startswith("'") and s.endswith("'")) + and s[1:-1] in self.valid): + msg += "; remove quotes surrounding your string" + raise ValueError(msg) + + +@lru_cache +def _listify_validator(scalar_validator, allow_stringlist=False, *, + n=None, doc=None): + def f(s): + if isinstance(s, str): + try: + val = [scalar_validator(v.strip()) for v in s.split(',') + if v.strip()] + except Exception: + if allow_stringlist: + # Sometimes, a list of colors might be a single string + # of single-letter colornames. So give that a shot. + val = [scalar_validator(v.strip()) for v in s if v.strip()] + else: + raise + # Allow any ordered sequence type -- generators, np.ndarray, pd.Series + # -- but not sets, whose iteration order is non-deterministic. + elif np.iterable(s) and not isinstance(s, (set, frozenset)): + # The condition on this list comprehension will preserve the + # behavior of filtering out any empty strings (behavior was + # from the original validate_stringlist()), while allowing + # any non-string/text scalar values such as numbers and arrays. + val = [scalar_validator(v) for v in s + if not isinstance(v, str) or v] + else: + raise ValueError( + f"Expected str or other non-set iterable, but got {s}") + if n is not None and len(val) != n: + raise ValueError( + f"Expected {n} values, but there are {len(val)} values in {s}") + return val + + try: + f.__name__ = f"{scalar_validator.__name__}list" + except AttributeError: # class instance. + f.__name__ = f"{type(scalar_validator).__name__}List" + f.__qualname__ = f.__qualname__.rsplit(".", 1)[0] + "." + f.__name__ + f.__doc__ = doc if doc is not None else scalar_validator.__doc__ + return f + + +def validate_any(s): + return s +validate_anylist = _listify_validator(validate_any) + + +def _validate_date(s): + try: + np.datetime64(s) + return s + except ValueError: + raise ValueError( + f'{s!r} should be a string that can be parsed by numpy.datetime64') + + +def validate_bool(b): + """Convert b to ``bool`` or raise.""" + if isinstance(b, str): + b = b.lower() + if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): + return True + elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): + return False + else: + raise ValueError(f'Cannot convert {b!r} to bool') + + +def validate_axisbelow(s): + try: + return validate_bool(s) + except ValueError: + if isinstance(s, str): + if s == 'line': + return 'line' + raise ValueError(f'{s!r} cannot be interpreted as' + ' True, False, or "line"') + + +def validate_dpi(s): + """Confirm s is string 'figure' or convert s to float or raise.""" + if s == 'figure': + return s + try: + return float(s) + except ValueError as e: + raise ValueError(f'{s!r} is not string "figure" and ' + f'could not convert {s!r} to float') from e + + +def _make_type_validator(cls, *, allow_none=False): + """ + Return a validator that converts inputs to *cls* or raises (and possibly + allows ``None`` as well). + """ + + def validator(s): + if (allow_none and + (s is None or cbook._str_lower_equal(s, "none"))): + return None + if cls is str and not isinstance(s, str): + raise ValueError(f'Could not convert {s!r} to str') + try: + return cls(s) + except (TypeError, ValueError) as e: + raise ValueError( + f'Could not convert {s!r} to {cls.__name__}') from e + + validator.__name__ = f"validate_{cls.__name__}" + if allow_none: + validator.__name__ += "_or_None" + validator.__qualname__ = ( + validator.__qualname__.rsplit(".", 1)[0] + "." + validator.__name__) + return validator + + +validate_string = _make_type_validator(str) +validate_string_or_None = _make_type_validator(str, allow_none=True) +validate_stringlist = _listify_validator( + validate_string, doc='return a list of strings') +validate_int = _make_type_validator(int) +validate_int_or_None = _make_type_validator(int, allow_none=True) +validate_float = _make_type_validator(float) +validate_float_or_None = _make_type_validator(float, allow_none=True) +validate_floatlist = _listify_validator( + validate_float, doc='return a list of floats') + + +def _validate_marker(s): + try: + return validate_int(s) + except ValueError as e: + try: + return validate_string(s) + except ValueError as e: + raise ValueError('Supported markers are [string, int]') from e + + +_validate_markerlist = _listify_validator( + _validate_marker, doc='return a list of markers') + + +def _validate_pathlike(s): + if isinstance(s, (str, os.PathLike)): + # Store value as str because savefig.directory needs to distinguish + # between "" (cwd) and "." (cwd, but gets updated by user selections). + return os.fsdecode(s) + else: + return validate_string(s) + + +def validate_fonttype(s): + """ + Confirm that this is a Postscript or PDF font type that we know how to + convert to. + """ + fonttypes = {'type3': 3, + 'truetype': 42} + try: + fonttype = validate_int(s) + except ValueError: + try: + return fonttypes[s.lower()] + except KeyError as e: + raise ValueError('Supported Postscript/PDF font types are %s' + % list(fonttypes)) from e + else: + if fonttype not in fonttypes.values(): + raise ValueError( + 'Supported Postscript/PDF font types are %s' % + list(fonttypes.values())) + return fonttype + + +_auto_backend_sentinel = object() + + +def validate_backend(s): + if s is _auto_backend_sentinel or backend_registry.is_valid_backend(s): + return s + else: + msg = (f"'{s}' is not a valid value for backend; supported values are " + f"{backend_registry.list_all()}") + raise ValueError(msg) + + +def _validate_toolbar(s): + s = ValidateInStrings( + 'toolbar', ['None', 'toolbar2', 'toolmanager'], ignorecase=True)(s) + if s == 'toolmanager': + _api.warn_external( + "Treat the new Tool classes introduced in v1.5 as experimental " + "for now; the API and rcParam may change in future versions.") + return s + + +def validate_color_or_inherit(s): + """Return a valid color arg.""" + if cbook._str_equal(s, 'inherit'): + return s + return validate_color(s) + + +def validate_color_or_auto(s): + if cbook._str_equal(s, 'auto'): + return s + return validate_color(s) + + +def validate_color_for_prop_cycle(s): + # N-th color cycle syntax can't go into the color cycle. + if isinstance(s, str) and re.match("^C[0-9]$", s): + raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler") + return validate_color(s) + + +def _validate_color_or_linecolor(s): + if cbook._str_equal(s, 'linecolor'): + return s + elif cbook._str_equal(s, 'mfc') or cbook._str_equal(s, 'markerfacecolor'): + return 'markerfacecolor' + elif cbook._str_equal(s, 'mec') or cbook._str_equal(s, 'markeredgecolor'): + return 'markeredgecolor' + elif s is None: + return None + elif isinstance(s, str) and len(s) == 6 or len(s) == 8: + stmp = '#' + s + if is_color_like(stmp): + return stmp + if s.lower() == 'none': + return None + elif is_color_like(s): + return s + + raise ValueError(f'{s!r} does not look like a color arg') + + +def validate_color(s): + """Return a valid color arg.""" + if isinstance(s, str): + if s.lower() == 'none': + return 'none' + if len(s) == 6 or len(s) == 8: + stmp = '#' + s + if is_color_like(stmp): + return stmp + + if is_color_like(s): + return s + + # If it is still valid, it must be a tuple (as a string from matplotlibrc). + try: + color = ast.literal_eval(s) + except (SyntaxError, ValueError): + pass + else: + if is_color_like(color): + return color + + raise ValueError(f'{s!r} does not look like a color arg') + + +validate_colorlist = _listify_validator( + validate_color, allow_stringlist=True, doc='return a list of colorspecs') + + +def _validate_cmap(s): + _api.check_isinstance((str, Colormap), cmap=s) + return s + + +def validate_aspect(s): + if s in ('auto', 'equal'): + return s + try: + return float(s) + except ValueError as e: + raise ValueError('not a valid aspect specification') from e + + +def validate_fontsize_None(s): + if s is None or s == 'None': + return None + else: + return validate_fontsize(s) + + +def validate_fontsize(s): + fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large', + 'x-large', 'xx-large', 'smaller', 'larger'] + if isinstance(s, str): + s = s.lower() + if s in fontsizes: + return s + try: + return float(s) + except ValueError as e: + raise ValueError("%s is not a valid font size. Valid font sizes " + "are %s." % (s, ", ".join(fontsizes))) from e + + +validate_fontsizelist = _listify_validator(validate_fontsize) + + +def validate_fontweight(s): + weights = [ + 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', + 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'] + # Note: Historically, weights have been case-sensitive in Matplotlib + if s in weights: + return s + try: + return int(s) + except (ValueError, TypeError) as e: + raise ValueError(f'{s} is not a valid font weight.') from e + + +def validate_fontstretch(s): + stretchvalues = [ + 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', + 'normal', 'semi-expanded', 'expanded', 'extra-expanded', + 'ultra-expanded'] + # Note: Historically, stretchvalues have been case-sensitive in Matplotlib + if s in stretchvalues: + return s + try: + return int(s) + except (ValueError, TypeError) as e: + raise ValueError(f'{s} is not a valid font stretch.') from e + + +def validate_font_properties(s): + parse_fontconfig_pattern(s) + return s + + +def _validate_mathtext_fallback(s): + _fallback_fonts = ['cm', 'stix', 'stixsans'] + if isinstance(s, str): + s = s.lower() + if s is None or s == 'none': + return None + elif s.lower() in _fallback_fonts: + return s + else: + raise ValueError( + f"{s} is not a valid fallback font name. Valid fallback font " + f"names are {','.join(_fallback_fonts)}. Passing 'None' will turn " + "fallback off.") + + +def validate_whiskers(s): + try: + return _listify_validator(validate_float, n=2)(s) + except (TypeError, ValueError): + try: + return float(s) + except ValueError as e: + raise ValueError("Not a valid whisker value [float, " + "(float, float)]") from e + + +def validate_ps_distiller(s): + if isinstance(s, str): + s = s.lower() + if s in ('none', None, 'false', False): + return None + else: + return ValidateInStrings('ps.usedistiller', ['ghostscript', 'xpdf'])(s) + + +def _validate_papersize(s): + # Re-inline this validator when the 'auto' deprecation expires. + s = ValidateInStrings("ps.papersize", + ["figure", "auto", "letter", "legal", "ledger", + *[f"{ab}{i}" for ab in "ab" for i in range(11)]], + ignorecase=True)(s) + if s == "auto": + _api.warn_deprecated("3.8", name="ps.papersize='auto'", + addendum="Pass an explicit paper type, figure, or omit " + "the *ps.papersize* rcParam entirely.") + return s + + +# A validator dedicated to the named line styles, based on the items in +# ls_mapper, and a list of possible strings read from Line2D.set_linestyle +_validate_named_linestyle = ValidateInStrings( + 'linestyle', + [*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''], + ignorecase=True) + + +def _validate_linestyle(ls): + """ + A validator for all possible line styles, the named ones *and* + the on-off ink sequences. + """ + if isinstance(ls, str): + try: # Look first for a valid named line style, like '--' or 'solid'. + return _validate_named_linestyle(ls) + except ValueError: + pass + try: + ls = ast.literal_eval(ls) # Parsing matplotlibrc. + except (SyntaxError, ValueError): + pass # Will error with the ValueError at the end. + + def _is_iterable_not_string_like(x): + # Explicitly exclude bytes/bytearrays so that they are not + # nonsensically interpreted as sequences of numbers (codepoints). + return np.iterable(x) and not isinstance(x, (str, bytes, bytearray)) + + if _is_iterable_not_string_like(ls): + if len(ls) == 2 and _is_iterable_not_string_like(ls[1]): + # (offset, (on, off, on, off, ...)) + offset, onoff = ls + else: + # For backcompat: (on, off, on, off, ...); the offset is implicit. + offset = 0 + onoff = ls + + if (isinstance(offset, Real) + and len(onoff) % 2 == 0 + and all(isinstance(elem, Real) for elem in onoff)): + return (offset, onoff) + + raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.") + + +validate_fillstyle = ValidateInStrings( + 'markers.fillstyle', ['full', 'left', 'right', 'bottom', 'top', 'none']) + + +validate_fillstylelist = _listify_validator(validate_fillstyle) + + +def validate_markevery(s): + """ + Validate the markevery property of a Line2D object. + + Parameters + ---------- + s : None, int, (int, int), slice, float, (float, float), or list[int] + + Returns + ------- + None, int, (int, int), slice, float, (float, float), or list[int] + """ + # Validate s against type slice float int and None + if isinstance(s, (slice, float, int, type(None))): + return s + # Validate s against type tuple + if isinstance(s, tuple): + if (len(s) == 2 + and (all(isinstance(e, int) for e in s) + or all(isinstance(e, float) for e in s))): + return s + else: + raise TypeError( + "'markevery' tuple must be pair of ints or of floats") + # Validate s against type list + if isinstance(s, list): + if all(isinstance(e, int) for e in s): + return s + else: + raise TypeError( + "'markevery' list must have all elements of type int") + raise TypeError("'markevery' is of an invalid type") + + +validate_markeverylist = _listify_validator(validate_markevery) + + +def validate_bbox(s): + if isinstance(s, str): + s = s.lower() + if s == 'tight': + return s + if s == 'standard': + return None + raise ValueError("bbox should be 'tight' or 'standard'") + elif s is not None: + # Backwards compatibility. None is equivalent to 'standard'. + raise ValueError("bbox should be 'tight' or 'standard'") + return s + + +def validate_sketch(s): + + if isinstance(s, str): + s = s.lower().strip() + if s.startswith("(") and s.endswith(")"): + s = s[1:-1] + if s == 'none' or s is None: + return None + try: + return tuple(_listify_validator(validate_float, n=3)(s)) + except ValueError as exc: + raise ValueError("Expected a (scale, length, randomness) tuple") from exc + + +def _validate_greaterthan_minushalf(s): + s = validate_float(s) + if s > -0.5: + return s + else: + raise RuntimeError(f'Value must be >-0.5; got {s}') + + +def _validate_greaterequal0_lessequal1(s): + s = validate_float(s) + if 0 <= s <= 1: + return s + else: + raise RuntimeError(f'Value must be >=0 and <=1; got {s}') + + +def _validate_int_greaterequal0(s): + s = validate_int(s) + if s >= 0: + return s + else: + raise RuntimeError(f'Value must be >=0; got {s}') + + +def validate_hatch(s): + r""" + Validate a hatch pattern. + A hatch pattern string can have any sequence of the following + characters: ``\ / | - + * . x o O``. + """ + if not isinstance(s, str): + raise ValueError("Hatch pattern must be a string") + _api.check_isinstance(str, hatch_pattern=s) + unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'} + if unknown: + raise ValueError("Unknown hatch symbol(s): %s" % list(unknown)) + return s + + +validate_hatchlist = _listify_validator(validate_hatch) +validate_dashlist = _listify_validator(validate_floatlist) + + +def _validate_minor_tick_ndivs(n): + """ + Validate ndiv parameter related to the minor ticks. + It controls the number of minor ticks to be placed between + two major ticks. + """ + + if cbook._str_lower_equal(n, 'auto'): + return n + try: + n = _validate_int_greaterequal0(n) + return n + except (RuntimeError, ValueError): + pass + + raise ValueError("'tick.minor.ndivs' must be 'auto' or non-negative int") + + +_prop_validators = { + 'color': _listify_validator(validate_color_for_prop_cycle, + allow_stringlist=True), + 'linewidth': validate_floatlist, + 'linestyle': _listify_validator(_validate_linestyle), + 'facecolor': validate_colorlist, + 'edgecolor': validate_colorlist, + 'joinstyle': _listify_validator(JoinStyle), + 'capstyle': _listify_validator(CapStyle), + 'fillstyle': validate_fillstylelist, + 'markerfacecolor': validate_colorlist, + 'markersize': validate_floatlist, + 'markeredgewidth': validate_floatlist, + 'markeredgecolor': validate_colorlist, + 'markevery': validate_markeverylist, + 'alpha': validate_floatlist, + 'marker': _validate_markerlist, + 'hatch': validate_hatchlist, + 'dashes': validate_dashlist, + } +_prop_aliases = { + 'c': 'color', + 'lw': 'linewidth', + 'ls': 'linestyle', + 'fc': 'facecolor', + 'ec': 'edgecolor', + 'mfc': 'markerfacecolor', + 'mec': 'markeredgecolor', + 'mew': 'markeredgewidth', + 'ms': 'markersize', + } + + +def cycler(*args, **kwargs): + """ + Create a `~cycler.Cycler` object much like :func:`cycler.cycler`, + but includes input validation. + + Call signatures:: + + cycler(cycler) + cycler(label=values[, label2=values2[, ...]]) + cycler(label, values) + + Form 1 copies a given `~cycler.Cycler` object. + + Form 2 creates a `~cycler.Cycler` which cycles over one or more + properties simultaneously. If multiple properties are given, their + value lists must have the same length. + + Form 3 creates a `~cycler.Cycler` for a single property. This form + exists for compatibility with the original cycler. Its use is + discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``. + + Parameters + ---------- + cycler : Cycler + Copy constructor for Cycler. + + label : str + The property key. Must be a valid `.Artist` property. + For example, 'color' or 'linestyle'. Aliases are allowed, + such as 'c' for 'color' and 'lw' for 'linewidth'. + + values : iterable + Finite-length iterable of the property values. These values + are validated and will raise a ValueError if invalid. + + Returns + ------- + Cycler + A new :class:`~cycler.Cycler` for the given properties. + + Examples + -------- + Creating a cycler for a single property: + + >>> c = cycler(color=['red', 'green', 'blue']) + + Creating a cycler for simultaneously cycling over multiple properties + (e.g. red circle, green plus, blue cross): + + >>> c = cycler(color=['red', 'green', 'blue'], + ... marker=['o', '+', 'x']) + + """ + if args and kwargs: + raise TypeError("cycler() can only accept positional OR keyword " + "arguments -- not both.") + elif not args and not kwargs: + raise TypeError("cycler() must have positional OR keyword arguments") + + if len(args) == 1: + if not isinstance(args[0], Cycler): + raise TypeError("If only one positional argument given, it must " + "be a Cycler instance.") + return validate_cycler(args[0]) + elif len(args) == 2: + pairs = [(args[0], args[1])] + elif len(args) > 2: + raise _api.nargs_error('cycler', '0-2', len(args)) + else: + pairs = kwargs.items() + + validated = [] + for prop, vals in pairs: + norm_prop = _prop_aliases.get(prop, prop) + validator = _prop_validators.get(norm_prop, None) + if validator is None: + raise TypeError("Unknown artist property: %s" % prop) + vals = validator(vals) + # We will normalize the property names as well to reduce + # the amount of alias handling code elsewhere. + validated.append((norm_prop, vals)) + + return reduce(operator.add, (ccycler(k, v) for k, v in validated)) + + +class _DunderChecker(ast.NodeVisitor): + def visit_Attribute(self, node): + if node.attr.startswith("__") and node.attr.endswith("__"): + raise ValueError("cycler strings with dunders are forbidden") + self.generic_visit(node) + + +# A validator dedicated to the named legend loc +_validate_named_legend_loc = ValidateInStrings( + 'legend.loc', + [ + "best", + "upper right", "upper left", "lower left", "lower right", "right", + "center left", "center right", "lower center", "upper center", + "center"], + ignorecase=True) + + +def _validate_legend_loc(loc): + """ + Confirm that loc is a type which rc.Params["legend.loc"] supports. + + .. versionadded:: 3.8 + + Parameters + ---------- + loc : str | int | (float, float) | str((float, float)) + The location of the legend. + + Returns + ------- + loc : str | int | (float, float) or raise ValueError exception + The location of the legend. + """ + if isinstance(loc, str): + try: + return _validate_named_legend_loc(loc) + except ValueError: + pass + try: + loc = ast.literal_eval(loc) + except (SyntaxError, ValueError): + pass + if isinstance(loc, int): + if 0 <= loc <= 10: + return loc + if isinstance(loc, tuple): + if len(loc) == 2 and all(isinstance(e, Real) for e in loc): + return loc + raise ValueError(f"{loc} is not a valid legend location.") + + +def validate_cycler(s): + """Return a Cycler object from a string repr or the object itself.""" + if isinstance(s, str): + # TODO: We might want to rethink this... + # While I think I have it quite locked down, it is execution of + # arbitrary code without sanitation. + # Combine this with the possibility that rcparams might come from the + # internet (future plans), this could be downright dangerous. + # I locked it down by only having the 'cycler()' function available. + # UPDATE: Partly plugging a security hole. + # I really should have read this: + # https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html + # We should replace this eval with a combo of PyParsing and + # ast.literal_eval() + try: + _DunderChecker().visit(ast.parse(s)) + s = eval(s, {'cycler': cycler, '__builtins__': {}}) + except BaseException as e: + raise ValueError(f"{s!r} is not a valid cycler construction: {e}" + ) from e + # Should make sure what comes from the above eval() + # is a Cycler object. + if isinstance(s, Cycler): + cycler_inst = s + else: + raise ValueError(f"Object is not a string or Cycler instance: {s!r}") + + unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases)) + if unknowns: + raise ValueError("Unknown artist properties: %s" % unknowns) + + # Not a full validation, but it'll at least normalize property names + # A fuller validation would require v0.10 of cycler. + checker = set() + for prop in cycler_inst.keys: + norm_prop = _prop_aliases.get(prop, prop) + if norm_prop != prop and norm_prop in cycler_inst.keys: + raise ValueError(f"Cannot specify both {norm_prop!r} and alias " + f"{prop!r} in the same prop_cycle") + if norm_prop in checker: + raise ValueError(f"Another property was already aliased to " + f"{norm_prop!r}. Collision normalizing {prop!r}.") + checker.update([norm_prop]) + + # This is just an extra-careful check, just in case there is some + # edge-case I haven't thought of. + assert len(checker) == len(cycler_inst.keys) + + # Now, it should be safe to mutate this cycler + for prop in cycler_inst.keys: + norm_prop = _prop_aliases.get(prop, prop) + cycler_inst.change_key(prop, norm_prop) + + for key, vals in cycler_inst.by_key().items(): + _prop_validators[key](vals) + + return cycler_inst + + +def validate_hist_bins(s): + valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"] + if isinstance(s, str) and s in valid_strs: + return s + try: + return int(s) + except (TypeError, ValueError): + pass + try: + return validate_floatlist(s) + except ValueError: + pass + raise ValueError(f"'hist.bins' must be one of {valid_strs}, an int or" + " a sequence of floats") + + +class _ignorecase(list): + """A marker class indicating that a list-of-str is case-insensitive.""" + + +def _convert_validator_spec(key, conv): + if isinstance(conv, list): + ignorecase = isinstance(conv, _ignorecase) + return ValidateInStrings(key, conv, ignorecase=ignorecase) + else: + return conv + + +# Mapping of rcParams to validators. +# Converters given as lists or _ignorecase are converted to ValidateInStrings +# immediately below. +# The rcParams defaults are defined in lib/matplotlib/mpl-data/matplotlibrc, which +# gets copied to matplotlib/mpl-data/matplotlibrc by the setup script. +_validators = { + "backend": validate_backend, + "backend_fallback": validate_bool, + "figure.hooks": validate_stringlist, + "toolbar": _validate_toolbar, + "interactive": validate_bool, + "timezone": validate_string, + + "webagg.port": validate_int, + "webagg.address": validate_string, + "webagg.open_in_browser": validate_bool, + "webagg.port_retries": validate_int, + + # line props + "lines.linewidth": validate_float, # line width in points + "lines.linestyle": _validate_linestyle, # solid line + "lines.color": validate_color, # first color in color cycle + "lines.marker": _validate_marker, # marker name + "lines.markerfacecolor": validate_color_or_auto, # default color + "lines.markeredgecolor": validate_color_or_auto, # default color + "lines.markeredgewidth": validate_float, + "lines.markersize": validate_float, # markersize, in points + "lines.antialiased": validate_bool, # antialiased (no jaggies) + "lines.dash_joinstyle": JoinStyle, + "lines.solid_joinstyle": JoinStyle, + "lines.dash_capstyle": CapStyle, + "lines.solid_capstyle": CapStyle, + "lines.dashed_pattern": validate_floatlist, + "lines.dashdot_pattern": validate_floatlist, + "lines.dotted_pattern": validate_floatlist, + "lines.scale_dashes": validate_bool, + + # marker props + "markers.fillstyle": validate_fillstyle, + + ## pcolor(mesh) props: + "pcolor.shading": ["auto", "flat", "nearest", "gouraud"], + "pcolormesh.snap": validate_bool, + + ## patch props + "patch.linewidth": validate_float, # line width in points + "patch.edgecolor": validate_color, + "patch.force_edgecolor": validate_bool, + "patch.facecolor": validate_color, # first color in cycle + "patch.antialiased": validate_bool, # antialiased (no jaggies) + + ## hatch props + "hatch.color": validate_color, + "hatch.linewidth": validate_float, + + ## Histogram properties + "hist.bins": validate_hist_bins, + + ## Boxplot properties + "boxplot.notch": validate_bool, + "boxplot.vertical": validate_bool, + "boxplot.whiskers": validate_whiskers, + "boxplot.bootstrap": validate_int_or_None, + "boxplot.patchartist": validate_bool, + "boxplot.showmeans": validate_bool, + "boxplot.showcaps": validate_bool, + "boxplot.showbox": validate_bool, + "boxplot.showfliers": validate_bool, + "boxplot.meanline": validate_bool, + + "boxplot.flierprops.color": validate_color, + "boxplot.flierprops.marker": _validate_marker, + "boxplot.flierprops.markerfacecolor": validate_color_or_auto, + "boxplot.flierprops.markeredgecolor": validate_color, + "boxplot.flierprops.markeredgewidth": validate_float, + "boxplot.flierprops.markersize": validate_float, + "boxplot.flierprops.linestyle": _validate_linestyle, + "boxplot.flierprops.linewidth": validate_float, + + "boxplot.boxprops.color": validate_color, + "boxplot.boxprops.linewidth": validate_float, + "boxplot.boxprops.linestyle": _validate_linestyle, + + "boxplot.whiskerprops.color": validate_color, + "boxplot.whiskerprops.linewidth": validate_float, + "boxplot.whiskerprops.linestyle": _validate_linestyle, + + "boxplot.capprops.color": validate_color, + "boxplot.capprops.linewidth": validate_float, + "boxplot.capprops.linestyle": _validate_linestyle, + + "boxplot.medianprops.color": validate_color, + "boxplot.medianprops.linewidth": validate_float, + "boxplot.medianprops.linestyle": _validate_linestyle, + + "boxplot.meanprops.color": validate_color, + "boxplot.meanprops.marker": _validate_marker, + "boxplot.meanprops.markerfacecolor": validate_color, + "boxplot.meanprops.markeredgecolor": validate_color, + "boxplot.meanprops.markersize": validate_float, + "boxplot.meanprops.linestyle": _validate_linestyle, + "boxplot.meanprops.linewidth": validate_float, + + ## font props + "font.family": validate_stringlist, # used by text object + "font.style": validate_string, + "font.variant": validate_string, + "font.stretch": validate_fontstretch, + "font.weight": validate_fontweight, + "font.size": validate_float, # Base font size in points + "font.serif": validate_stringlist, + "font.sans-serif": validate_stringlist, + "font.cursive": validate_stringlist, + "font.fantasy": validate_stringlist, + "font.monospace": validate_stringlist, + + # text props + "text.color": validate_color, + "text.usetex": validate_bool, + "text.latex.preamble": validate_string, + "text.hinting": ["default", "no_autohint", "force_autohint", + "no_hinting", "auto", "native", "either", "none"], + "text.hinting_factor": validate_int, + "text.kerning_factor": validate_int, + "text.antialiased": validate_bool, + "text.parse_math": validate_bool, + + "mathtext.cal": validate_font_properties, + "mathtext.rm": validate_font_properties, + "mathtext.tt": validate_font_properties, + "mathtext.it": validate_font_properties, + "mathtext.bf": validate_font_properties, + "mathtext.bfit": validate_font_properties, + "mathtext.sf": validate_font_properties, + "mathtext.fontset": ["dejavusans", "dejavuserif", "cm", "stix", + "stixsans", "custom"], + "mathtext.default": ["rm", "cal", "bfit", "it", "tt", "sf", "bf", "default", + "bb", "frak", "scr", "regular"], + "mathtext.fallback": _validate_mathtext_fallback, + + "image.aspect": validate_aspect, # equal, auto, a number + "image.interpolation": validate_string, + "image.interpolation_stage": ["data", "rgba"], + "image.cmap": _validate_cmap, # gray, jet, etc. + "image.lut": validate_int, # lookup table + "image.origin": ["upper", "lower"], + "image.resample": validate_bool, + # Specify whether vector graphics backends will combine all images on a + # set of Axes into a single composite image + "image.composite_image": validate_bool, + + # contour props + "contour.negative_linestyle": _validate_linestyle, + "contour.corner_mask": validate_bool, + "contour.linewidth": validate_float_or_None, + "contour.algorithm": ["mpl2005", "mpl2014", "serial", "threaded"], + + # errorbar props + "errorbar.capsize": validate_float, + + # axis props + # alignment of x/y axis title + "xaxis.labellocation": ["left", "center", "right"], + "yaxis.labellocation": ["bottom", "center", "top"], + + # Axes props + "axes.axisbelow": validate_axisbelow, + "axes.facecolor": validate_color, # background color + "axes.edgecolor": validate_color, # edge color + "axes.linewidth": validate_float, # edge linewidth + + "axes.spines.left": validate_bool, # Set visibility of axes spines, + "axes.spines.right": validate_bool, # i.e., the lines around the chart + "axes.spines.bottom": validate_bool, # denoting data boundary. + "axes.spines.top": validate_bool, + + "axes.titlesize": validate_fontsize, # Axes title fontsize + "axes.titlelocation": ["left", "center", "right"], # Axes title alignment + "axes.titleweight": validate_fontweight, # Axes title font weight + "axes.titlecolor": validate_color_or_auto, # Axes title font color + # title location, axes units, None means auto + "axes.titley": validate_float_or_None, + # pad from Axes top decoration to title in points + "axes.titlepad": validate_float, + "axes.grid": validate_bool, # display grid or not + "axes.grid.which": ["minor", "both", "major"], # which grids are drawn + "axes.grid.axis": ["x", "y", "both"], # grid type + "axes.labelsize": validate_fontsize, # fontsize of x & y labels + "axes.labelpad": validate_float, # space between label and axis + "axes.labelweight": validate_fontweight, # fontsize of x & y labels + "axes.labelcolor": validate_color, # color of axis label + # use scientific notation if log10 of the axis range is smaller than the + # first or larger than the second + "axes.formatter.limits": _listify_validator(validate_int, n=2), + # use current locale to format ticks + "axes.formatter.use_locale": validate_bool, + "axes.formatter.use_mathtext": validate_bool, + # minimum exponent to format in scientific notation + "axes.formatter.min_exponent": validate_int, + "axes.formatter.useoffset": validate_bool, + "axes.formatter.offset_threshold": validate_int, + "axes.unicode_minus": validate_bool, + # This entry can be either a cycler object or a string repr of a + # cycler-object, which gets eval()'ed to create the object. + "axes.prop_cycle": validate_cycler, + # If "data", axes limits are set close to the data. + # If "round_numbers" axes limits are set to the nearest round numbers. + "axes.autolimit_mode": ["data", "round_numbers"], + "axes.xmargin": _validate_greaterthan_minushalf, # margin added to xaxis + "axes.ymargin": _validate_greaterthan_minushalf, # margin added to yaxis + "axes.zmargin": _validate_greaterthan_minushalf, # margin added to zaxis + + "polaraxes.grid": validate_bool, # display polar grid or not + "axes3d.grid": validate_bool, # display 3d grid + "axes3d.automargin": validate_bool, # automatically add margin when + # manually setting 3D axis limits + + "axes3d.xaxis.panecolor": validate_color, # 3d background pane + "axes3d.yaxis.panecolor": validate_color, # 3d background pane + "axes3d.zaxis.panecolor": validate_color, # 3d background pane + + # scatter props + "scatter.marker": _validate_marker, + "scatter.edgecolors": validate_string, + + "date.epoch": _validate_date, + "date.autoformatter.year": validate_string, + "date.autoformatter.month": validate_string, + "date.autoformatter.day": validate_string, + "date.autoformatter.hour": validate_string, + "date.autoformatter.minute": validate_string, + "date.autoformatter.second": validate_string, + "date.autoformatter.microsecond": validate_string, + + 'date.converter': ['auto', 'concise'], + # for auto date locator, choose interval_multiples + 'date.interval_multiples': validate_bool, + + # legend properties + "legend.fancybox": validate_bool, + "legend.loc": _validate_legend_loc, + + # the number of points in the legend line + "legend.numpoints": validate_int, + # the number of points in the legend line for scatter + "legend.scatterpoints": validate_int, + "legend.fontsize": validate_fontsize, + "legend.title_fontsize": validate_fontsize_None, + # color of the legend + "legend.labelcolor": _validate_color_or_linecolor, + # the relative size of legend markers vs. original + "legend.markerscale": validate_float, + # using dict in rcParams not yet supported, so make sure it is bool + "legend.shadow": validate_bool, + # whether or not to draw a frame around legend + "legend.frameon": validate_bool, + # alpha value of the legend frame + "legend.framealpha": validate_float_or_None, + + ## the following dimensions are in fraction of the font size + "legend.borderpad": validate_float, # units are fontsize + # the vertical space between the legend entries + "legend.labelspacing": validate_float, + # the length of the legend lines + "legend.handlelength": validate_float, + # the length of the legend lines + "legend.handleheight": validate_float, + # the space between the legend line and legend text + "legend.handletextpad": validate_float, + # the border between the Axes and legend edge + "legend.borderaxespad": validate_float, + # the border between the Axes and legend edge + "legend.columnspacing": validate_float, + "legend.facecolor": validate_color_or_inherit, + "legend.edgecolor": validate_color_or_inherit, + + # tick properties + "xtick.top": validate_bool, # draw ticks on top side + "xtick.bottom": validate_bool, # draw ticks on bottom side + "xtick.labeltop": validate_bool, # draw label on top + "xtick.labelbottom": validate_bool, # draw label on bottom + "xtick.major.size": validate_float, # major xtick size in points + "xtick.minor.size": validate_float, # minor xtick size in points + "xtick.major.width": validate_float, # major xtick width in points + "xtick.minor.width": validate_float, # minor xtick width in points + "xtick.major.pad": validate_float, # distance to label in points + "xtick.minor.pad": validate_float, # distance to label in points + "xtick.color": validate_color, # color of xticks + "xtick.labelcolor": validate_color_or_inherit, # color of xtick labels + "xtick.minor.visible": validate_bool, # visibility of minor xticks + "xtick.minor.top": validate_bool, # draw top minor xticks + "xtick.minor.bottom": validate_bool, # draw bottom minor xticks + "xtick.major.top": validate_bool, # draw top major xticks + "xtick.major.bottom": validate_bool, # draw bottom major xticks + # number of minor xticks + "xtick.minor.ndivs": _validate_minor_tick_ndivs, + "xtick.labelsize": validate_fontsize, # fontsize of xtick labels + "xtick.direction": ["out", "in", "inout"], # direction of xticks + "xtick.alignment": ["center", "right", "left"], + + "ytick.left": validate_bool, # draw ticks on left side + "ytick.right": validate_bool, # draw ticks on right side + "ytick.labelleft": validate_bool, # draw tick labels on left side + "ytick.labelright": validate_bool, # draw tick labels on right side + "ytick.major.size": validate_float, # major ytick size in points + "ytick.minor.size": validate_float, # minor ytick size in points + "ytick.major.width": validate_float, # major ytick width in points + "ytick.minor.width": validate_float, # minor ytick width in points + "ytick.major.pad": validate_float, # distance to label in points + "ytick.minor.pad": validate_float, # distance to label in points + "ytick.color": validate_color, # color of yticks + "ytick.labelcolor": validate_color_or_inherit, # color of ytick labels + "ytick.minor.visible": validate_bool, # visibility of minor yticks + "ytick.minor.left": validate_bool, # draw left minor yticks + "ytick.minor.right": validate_bool, # draw right minor yticks + "ytick.major.left": validate_bool, # draw left major yticks + "ytick.major.right": validate_bool, # draw right major yticks + # number of minor yticks + "ytick.minor.ndivs": _validate_minor_tick_ndivs, + "ytick.labelsize": validate_fontsize, # fontsize of ytick labels + "ytick.direction": ["out", "in", "inout"], # direction of yticks + "ytick.alignment": [ + "center", "top", "bottom", "baseline", "center_baseline"], + + "grid.color": validate_color, # grid color + "grid.linestyle": _validate_linestyle, # solid + "grid.linewidth": validate_float, # in points + "grid.alpha": validate_float, + + ## figure props + # figure title + "figure.titlesize": validate_fontsize, + "figure.titleweight": validate_fontweight, + + # figure labels + "figure.labelsize": validate_fontsize, + "figure.labelweight": validate_fontweight, + + # figure size in inches: width by height + "figure.figsize": _listify_validator(validate_float, n=2), + "figure.dpi": validate_float, + "figure.facecolor": validate_color, + "figure.edgecolor": validate_color, + "figure.frameon": validate_bool, + "figure.autolayout": validate_bool, + "figure.max_open_warning": validate_int, + "figure.raise_window": validate_bool, + "macosx.window_mode": ["system", "tab", "window"], + + "figure.subplot.left": validate_float, + "figure.subplot.right": validate_float, + "figure.subplot.bottom": validate_float, + "figure.subplot.top": validate_float, + "figure.subplot.wspace": validate_float, + "figure.subplot.hspace": validate_float, + + "figure.constrained_layout.use": validate_bool, # run constrained_layout? + # wspace and hspace are fraction of adjacent subplots to use for space. + # Much smaller than above because we don't need room for the text. + "figure.constrained_layout.hspace": validate_float, + "figure.constrained_layout.wspace": validate_float, + # buffer around the Axes, in inches. + "figure.constrained_layout.h_pad": validate_float, + "figure.constrained_layout.w_pad": validate_float, + + ## Saving figure's properties + 'savefig.dpi': validate_dpi, + 'savefig.facecolor': validate_color_or_auto, + 'savefig.edgecolor': validate_color_or_auto, + 'savefig.orientation': ['landscape', 'portrait'], + "savefig.format": validate_string, + "savefig.bbox": validate_bbox, # "tight", or "standard" (= None) + "savefig.pad_inches": validate_float, + # default directory in savefig dialog box + "savefig.directory": _validate_pathlike, + "savefig.transparent": validate_bool, + + "tk.window_focus": validate_bool, # Maintain shell focus for TkAgg + + # Set the papersize/type + "ps.papersize": _validate_papersize, + "ps.useafm": validate_bool, + # use ghostscript or xpdf to distill ps output + "ps.usedistiller": validate_ps_distiller, + "ps.distiller.res": validate_int, # dpi + "ps.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype) + "pdf.compression": validate_int, # 0-9 compression level; 0 to disable + "pdf.inheritcolor": validate_bool, # skip color setting commands + # use only the 14 PDF core fonts embedded in every PDF viewing application + "pdf.use14corefonts": validate_bool, + "pdf.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype) + + "pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used + "pgf.rcfonts": validate_bool, # use mpl's rc settings for font config + "pgf.preamble": validate_string, # custom LaTeX preamble + + # write raster image data into the svg file + "svg.image_inline": validate_bool, + "svg.fonttype": ["none", "path"], # save text as text ("none") or "paths" + "svg.hashsalt": validate_string_or_None, + + # set this when you want to generate hardcopy docstring + "docstring.hardcopy": validate_bool, + + "path.simplify": validate_bool, + "path.simplify_threshold": _validate_greaterequal0_lessequal1, + "path.snap": validate_bool, + "path.sketch": validate_sketch, + "path.effects": validate_anylist, + "agg.path.chunksize": validate_int, # 0 to disable chunking + + # key-mappings (multi-character mappings should be a list/tuple) + "keymap.fullscreen": validate_stringlist, + "keymap.home": validate_stringlist, + "keymap.back": validate_stringlist, + "keymap.forward": validate_stringlist, + "keymap.pan": validate_stringlist, + "keymap.zoom": validate_stringlist, + "keymap.save": validate_stringlist, + "keymap.quit": validate_stringlist, + "keymap.quit_all": validate_stringlist, # e.g.: "W", "cmd+W", "Q" + "keymap.grid": validate_stringlist, + "keymap.grid_minor": validate_stringlist, + "keymap.yscale": validate_stringlist, + "keymap.xscale": validate_stringlist, + "keymap.help": validate_stringlist, + "keymap.copy": validate_stringlist, + + # Animation settings + "animation.html": ["html5", "jshtml", "none"], + # Limit, in MB, of size of base64 encoded animation in HTML + # (i.e. IPython notebook) + "animation.embed_limit": validate_float, + "animation.writer": validate_string, + "animation.codec": validate_string, + "animation.bitrate": validate_int, + # Controls image format when frames are written to disk + "animation.frame_format": ["png", "jpeg", "tiff", "raw", "rgba", "ppm", + "sgi", "bmp", "pbm", "svg"], + # Path to ffmpeg binary. If just binary name, subprocess uses $PATH. + "animation.ffmpeg_path": _validate_pathlike, + # Additional arguments for ffmpeg movie writer (using pipes) + "animation.ffmpeg_args": validate_stringlist, + # Path to convert binary. If just binary name, subprocess uses $PATH. + "animation.convert_path": _validate_pathlike, + # Additional arguments for convert movie writer (using pipes) + "animation.convert_args": validate_stringlist, + + # Classic (pre 2.0) compatibility mode + # This is used for things that are hard to make backward compatible + # with a sane rcParam alone. This does *not* turn on classic mode + # altogether. For that use `matplotlib.style.use("classic")`. + "_internal.classic_mode": validate_bool +} +_hardcoded_defaults = { # Defaults not inferred from + # lib/matplotlib/mpl-data/matplotlibrc... + # ... because they are private: + "_internal.classic_mode": False, + # ... because they are deprecated: + # No current deprecations. + # backend is handled separately when constructing rcParamsDefault. +} +_validators = {k: _convert_validator_spec(k, conv) + for k, conv in _validators.items()} diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/sankey.py b/llava_next/lib/python3.10/site-packages/matplotlib/sankey.py new file mode 100644 index 0000000000000000000000000000000000000000..665b9d6deba2450c284e8a6dada932aae07a68fa --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/sankey.py @@ -0,0 +1,814 @@ +""" +Module for creating Sankey diagrams using Matplotlib. +""" + +import logging +from types import SimpleNamespace + +import numpy as np + +import matplotlib as mpl +from matplotlib.path import Path +from matplotlib.patches import PathPatch +from matplotlib.transforms import Affine2D +from matplotlib import _docstring + +_log = logging.getLogger(__name__) + +__author__ = "Kevin L. Davies" +__credits__ = ["Yannick Copin"] +__license__ = "BSD" +__version__ = "2011/09/16" + +# Angles [deg/90] +RIGHT = 0 +UP = 1 +# LEFT = 2 +DOWN = 3 + + +class Sankey: + """ + Sankey diagram. + + Sankey diagrams are a specific type of flow diagram, in which + the width of the arrows is shown proportionally to the flow + quantity. They are typically used to visualize energy or + material or cost transfers between processes. + `Wikipedia (6/1/2011) `_ + + """ + + def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25, + radius=0.1, shoulder=0.03, offset=0.15, head_angle=100, + margin=0.4, tolerance=1e-6, **kwargs): + """ + Create a new Sankey instance. + + The optional arguments listed below are applied to all subdiagrams so + that there is consistent alignment and formatting. + + In order to draw a complex Sankey diagram, create an instance of + `Sankey` by calling it without any kwargs:: + + sankey = Sankey() + + Then add simple Sankey sub-diagrams:: + + sankey.add() # 1 + sankey.add() # 2 + #... + sankey.add() # n + + Finally, create the full diagram:: + + sankey.finish() + + Or, instead, simply daisy-chain those calls:: + + Sankey().add().add... .add().finish() + + Other Parameters + ---------------- + ax : `~matplotlib.axes.Axes` + Axes onto which the data should be plotted. If *ax* isn't + provided, new Axes will be created. + scale : float + Scaling factor for the flows. *scale* sizes the width of the paths + in order to maintain proper layout. The same scale is applied to + all subdiagrams. The value should be chosen such that the product + of the scale and the sum of the inputs is approximately 1.0 (and + the product of the scale and the sum of the outputs is + approximately -1.0). + unit : str + The physical unit associated with the flow quantities. If *unit* + is None, then none of the quantities are labeled. + format : str or callable + A Python number formatting string or callable used to label the + flows with their quantities (i.e., a number times a unit, where the + unit is given). If a format string is given, the label will be + ``format % quantity``. If a callable is given, it will be called + with ``quantity`` as an argument. + gap : float + Space between paths that break in/break away to/from the top or + bottom. + radius : float + Inner radius of the vertical paths. + shoulder : float + Size of the shoulders of output arrows. + offset : float + Text offset (from the dip or tip of the arrow). + head_angle : float + Angle, in degrees, of the arrow heads (and negative of the angle of + the tails). + margin : float + Minimum space between Sankey outlines and the edge of the plot + area. + tolerance : float + Acceptable maximum of the magnitude of the sum of flows. The + magnitude of the sum of connected flows cannot be greater than + *tolerance*. + **kwargs + Any additional keyword arguments will be passed to `add`, which + will create the first subdiagram. + + See Also + -------- + Sankey.add + Sankey.finish + + Examples + -------- + .. plot:: gallery/specialty_plots/sankey_basics.py + """ + # Check the arguments. + if gap < 0: + raise ValueError( + "'gap' is negative, which is not allowed because it would " + "cause the paths to overlap") + if radius > gap: + raise ValueError( + "'radius' is greater than 'gap', which is not allowed because " + "it would cause the paths to overlap") + if head_angle < 0: + raise ValueError( + "'head_angle' is negative, which is not allowed because it " + "would cause inputs to look like outputs and vice versa") + if tolerance < 0: + raise ValueError( + "'tolerance' is negative, but it must be a magnitude") + + # Create Axes if necessary. + if ax is None: + import matplotlib.pyplot as plt + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[]) + + self.diagrams = [] + + # Store the inputs. + self.ax = ax + self.unit = unit + self.format = format + self.scale = scale + self.gap = gap + self.radius = radius + self.shoulder = shoulder + self.offset = offset + self.margin = margin + self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0) + self.tolerance = tolerance + + # Initialize the vertices of tight box around the diagram(s). + self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf)) + + # If there are any kwargs, create the first subdiagram. + if len(kwargs): + self.add(**kwargs) + + def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)): + """ + Return the codes and vertices for a rotated, scaled, and translated + 90 degree arc. + + Other Parameters + ---------------- + quadrant : {0, 1, 2, 3}, default: 0 + Uses 0-based indexing (0, 1, 2, or 3). + cw : bool, default: True + If True, the arc vertices are produced clockwise; counter-clockwise + otherwise. + radius : float, default: 1 + The radius of the arc. + center : (float, float), default: (0, 0) + (x, y) tuple of the arc's center. + """ + # Note: It would be possible to use matplotlib's transforms to rotate, + # scale, and translate the arc, but since the angles are discrete, + # it's just as easy and maybe more efficient to do it here. + ARC_CODES = [Path.LINETO, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4] + # Vertices of a cubic Bezier curve approximating a 90 deg arc + # These can be determined by Path.arc(0, 90). + ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00], + [1.00000000e+00, 2.65114773e-01], + [8.94571235e-01, 5.19642327e-01], + [7.07106781e-01, 7.07106781e-01], + [5.19642327e-01, 8.94571235e-01], + [2.65114773e-01, 1.00000000e+00], + # Insignificant + # [6.12303177e-17, 1.00000000e+00]]) + [0.00000000e+00, 1.00000000e+00]]) + if quadrant in (0, 2): + if cw: + vertices = ARC_VERTICES + else: + vertices = ARC_VERTICES[:, ::-1] # Swap x and y. + else: # 1, 3 + # Negate x. + if cw: + # Swap x and y. + vertices = np.column_stack((-ARC_VERTICES[:, 1], + ARC_VERTICES[:, 0])) + else: + vertices = np.column_stack((-ARC_VERTICES[:, 0], + ARC_VERTICES[:, 1])) + if quadrant > 1: + radius = -radius # Rotate 180 deg. + return list(zip(ARC_CODES, radius * vertices + + np.tile(center, (ARC_VERTICES.shape[0], 1)))) + + def _add_input(self, path, angle, flow, length): + """ + Add an input to a path and return its tip and label locations. + """ + if angle is None: + return [0, 0], [0, 0] + else: + x, y = path[-1][1] # Use the last point as a reference. + dipdepth = (flow / 2) * self.pitch + if angle == RIGHT: + x -= length + dip = [x + dipdepth, y + flow / 2.0] + path.extend([(Path.LINETO, [x, y]), + (Path.LINETO, dip), + (Path.LINETO, [x, y + flow]), + (Path.LINETO, [x + self.gap, y + flow])]) + label_location = [dip[0] - self.offset, dip[1]] + else: # Vertical + x -= self.gap + if angle == UP: + sign = 1 + else: + sign = -1 + + dip = [x - flow / 2, y - sign * (length - dipdepth)] + if angle == DOWN: + quadrant = 2 + else: + quadrant = 1 + + # Inner arc isn't needed if inner radius is zero + if self.radius: + path.extend(self._arc(quadrant=quadrant, + cw=angle == UP, + radius=self.radius, + center=(x + self.radius, + y - sign * self.radius))) + else: + path.append((Path.LINETO, [x, y])) + path.extend([(Path.LINETO, [x, y - sign * length]), + (Path.LINETO, dip), + (Path.LINETO, [x - flow, y - sign * length])]) + path.extend(self._arc(quadrant=quadrant, + cw=angle == DOWN, + radius=flow + self.radius, + center=(x + self.radius, + y - sign * self.radius))) + path.append((Path.LINETO, [x - flow, y + sign * flow])) + label_location = [dip[0], dip[1] - sign * self.offset] + + return dip, label_location + + def _add_output(self, path, angle, flow, length): + """ + Append an output to a path and return its tip and label locations. + + .. note:: *flow* is negative for an output. + """ + if angle is None: + return [0, 0], [0, 0] + else: + x, y = path[-1][1] # Use the last point as a reference. + tipheight = (self.shoulder - flow / 2) * self.pitch + if angle == RIGHT: + x += length + tip = [x + tipheight, y + flow / 2.0] + path.extend([(Path.LINETO, [x, y]), + (Path.LINETO, [x, y + self.shoulder]), + (Path.LINETO, tip), + (Path.LINETO, [x, y - self.shoulder + flow]), + (Path.LINETO, [x, y + flow]), + (Path.LINETO, [x - self.gap, y + flow])]) + label_location = [tip[0] + self.offset, tip[1]] + else: # Vertical + x += self.gap + if angle == UP: + sign, quadrant = 1, 3 + else: + sign, quadrant = -1, 0 + + tip = [x - flow / 2.0, y + sign * (length + tipheight)] + # Inner arc isn't needed if inner radius is zero + if self.radius: + path.extend(self._arc(quadrant=quadrant, + cw=angle == UP, + radius=self.radius, + center=(x - self.radius, + y + sign * self.radius))) + else: + path.append((Path.LINETO, [x, y])) + path.extend([(Path.LINETO, [x, y + sign * length]), + (Path.LINETO, [x - self.shoulder, + y + sign * length]), + (Path.LINETO, tip), + (Path.LINETO, [x + self.shoulder - flow, + y + sign * length]), + (Path.LINETO, [x - flow, y + sign * length])]) + path.extend(self._arc(quadrant=quadrant, + cw=angle == DOWN, + radius=self.radius - flow, + center=(x - self.radius, + y + sign * self.radius))) + path.append((Path.LINETO, [x - flow, y + sign * flow])) + label_location = [tip[0], tip[1] + sign * self.offset] + return tip, label_location + + def _revert(self, path, first_action=Path.LINETO): + """ + A path is not simply reversible by path[::-1] since the code + specifies an action to take from the **previous** point. + """ + reverse_path = [] + next_code = first_action + for code, position in path[::-1]: + reverse_path.append((next_code, position)) + next_code = code + return reverse_path + # This might be more efficient, but it fails because 'tuple' object + # doesn't support item assignment: + # path[1] = path[1][-1:0:-1] + # path[1][0] = first_action + # path[2] = path[2][::-1] + # return path + + @_docstring.dedent_interpd + def add(self, patchlabel='', flows=None, orientations=None, labels='', + trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0), + rotation=0, **kwargs): + """ + Add a simple Sankey diagram with flows at the same hierarchical level. + + Parameters + ---------- + patchlabel : str + Label to be placed at the center of the diagram. + Note that *label* (not *patchlabel*) can be passed as keyword + argument to create an entry in the legend. + + flows : list of float + Array of flow values. By convention, inputs are positive and + outputs are negative. + + Flows are placed along the top of the diagram from the inside out + in order of their index within *flows*. They are placed along the + sides of the diagram from the top down and along the bottom from + the outside in. + + If the sum of the inputs and outputs is + nonzero, the discrepancy will appear as a cubic Bézier curve along + the top and bottom edges of the trunk. + + orientations : list of {-1, 0, 1} + List of orientations of the flows (or a single orientation to be + used for all flows). Valid values are 0 (inputs from + the left, outputs to the right), 1 (from and to the top) or -1 + (from and to the bottom). + + labels : list of (str or None) + List of labels for the flows (or a single label to be used for all + flows). Each label may be *None* (no label), or a labeling string. + If an entry is a (possibly empty) string, then the quantity for the + corresponding flow will be shown below the string. However, if + the *unit* of the main diagram is None, then quantities are never + shown, regardless of the value of this argument. + + trunklength : float + Length between the bases of the input and output groups (in + data-space units). + + pathlengths : list of float + List of lengths of the vertical arrows before break-in or after + break-away. If a single value is given, then it will be applied to + the first (inside) paths on the top and bottom, and the length of + all other arrows will be justified accordingly. The *pathlengths* + are not applied to the horizontal inputs and outputs. + + prior : int + Index of the prior diagram to which this diagram should be + connected. + + connect : (int, int) + A (prior, this) tuple indexing the flow of the prior diagram and + the flow of this diagram which should be connected. If this is the + first diagram or *prior* is *None*, *connect* will be ignored. + + rotation : float + Angle of rotation of the diagram in degrees. The interpretation of + the *orientations* argument will be rotated accordingly (e.g., if + *rotation* == 90, an *orientations* entry of 1 means to/from the + left). *rotation* is ignored if this diagram is connected to an + existing one (using *prior* and *connect*). + + Returns + ------- + Sankey + The current `.Sankey` instance. + + Other Parameters + ---------------- + **kwargs + Additional keyword arguments set `matplotlib.patches.PathPatch` + properties, listed below. For example, one may want to use + ``fill=False`` or ``label="A legend entry"``. + + %(Patch:kwdoc)s + + See Also + -------- + Sankey.finish + """ + # Check and preprocess the arguments. + flows = np.array([1.0, -1.0]) if flows is None else np.array(flows) + n = flows.shape[0] # Number of flows + if rotation is None: + rotation = 0 + else: + # In the code below, angles are expressed in deg/90. + rotation /= 90.0 + if orientations is None: + orientations = 0 + try: + orientations = np.broadcast_to(orientations, n) + except ValueError: + raise ValueError( + f"The shapes of 'flows' {np.shape(flows)} and 'orientations' " + f"{np.shape(orientations)} are incompatible" + ) from None + try: + labels = np.broadcast_to(labels, n) + except ValueError: + raise ValueError( + f"The shapes of 'flows' {np.shape(flows)} and 'labels' " + f"{np.shape(labels)} are incompatible" + ) from None + if trunklength < 0: + raise ValueError( + "'trunklength' is negative, which is not allowed because it " + "would cause poor layout") + if abs(np.sum(flows)) > self.tolerance: + _log.info("The sum of the flows is nonzero (%f; patchlabel=%r); " + "is the system not at steady state?", + np.sum(flows), patchlabel) + scaled_flows = self.scale * flows + gain = sum(max(flow, 0) for flow in scaled_flows) + loss = sum(min(flow, 0) for flow in scaled_flows) + if prior is not None: + if prior < 0: + raise ValueError("The index of the prior diagram is negative") + if min(connect) < 0: + raise ValueError( + "At least one of the connection indices is negative") + if prior >= len(self.diagrams): + raise ValueError( + f"The index of the prior diagram is {prior}, but there " + f"are only {len(self.diagrams)} other diagrams") + if connect[0] >= len(self.diagrams[prior].flows): + raise ValueError( + "The connection index to the source diagram is {}, but " + "that diagram has only {} flows".format( + connect[0], len(self.diagrams[prior].flows))) + if connect[1] >= n: + raise ValueError( + f"The connection index to this diagram is {connect[1]}, " + f"but this diagram has only {n} flows") + if self.diagrams[prior].angles[connect[0]] is None: + raise ValueError( + f"The connection cannot be made, which may occur if the " + f"magnitude of flow {connect[0]} of diagram {prior} is " + f"less than the specified tolerance") + flow_error = (self.diagrams[prior].flows[connect[0]] + + flows[connect[1]]) + if abs(flow_error) >= self.tolerance: + raise ValueError( + f"The scaled sum of the connected flows is {flow_error}, " + f"which is not within the tolerance ({self.tolerance})") + + # Determine if the flows are inputs. + are_inputs = [None] * n + for i, flow in enumerate(flows): + if flow >= self.tolerance: + are_inputs[i] = True + elif flow <= -self.tolerance: + are_inputs[i] = False + else: + _log.info( + "The magnitude of flow %d (%f) is below the tolerance " + "(%f).\nIt will not be shown, and it cannot be used in a " + "connection.", i, flow, self.tolerance) + + # Determine the angles of the arrows (before rotation). + angles = [None] * n + for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)): + if orient == 1: + if is_input: + angles[i] = DOWN + elif is_input is False: + # Be specific since is_input can be None. + angles[i] = UP + elif orient == 0: + if is_input is not None: + angles[i] = RIGHT + else: + if orient != -1: + raise ValueError( + f"The value of orientations[{i}] is {orient}, " + f"but it must be -1, 0, or 1") + if is_input: + angles[i] = UP + elif is_input is False: + angles[i] = DOWN + + # Justify the lengths of the paths. + if np.iterable(pathlengths): + if len(pathlengths) != n: + raise ValueError( + f"The lengths of 'flows' ({n}) and 'pathlengths' " + f"({len(pathlengths)}) are incompatible") + else: # Make pathlengths into a list. + urlength = pathlengths + ullength = pathlengths + lrlength = pathlengths + lllength = pathlengths + d = dict(RIGHT=pathlengths) + pathlengths = [d.get(angle, 0) for angle in angles] + # Determine the lengths of the top-side arrows + # from the middle outwards. + for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs, + scaled_flows)): + if angle == DOWN and is_input: + pathlengths[i] = ullength + ullength += flow + elif angle == UP and is_input is False: + pathlengths[i] = urlength + urlength -= flow # Flow is negative for outputs. + # Determine the lengths of the bottom-side arrows + # from the middle outwards. + for i, (angle, is_input, flow) in enumerate(reversed(list(zip( + angles, are_inputs, scaled_flows)))): + if angle == UP and is_input: + pathlengths[n - i - 1] = lllength + lllength += flow + elif angle == DOWN and is_input is False: + pathlengths[n - i - 1] = lrlength + lrlength -= flow + # Determine the lengths of the left-side arrows + # from the bottom upwards. + has_left_input = False + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, zip(scaled_flows, pathlengths))))): + if angle == RIGHT: + if is_input: + if has_left_input: + pathlengths[n - i - 1] = 0 + else: + has_left_input = True + # Determine the lengths of the right-side arrows + # from the top downwards. + has_right_output = False + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == RIGHT: + if is_input is False: + if has_right_output: + pathlengths[i] = 0 + else: + has_right_output = True + + # Begin the subpaths, and smooth the transition if the sum of the flows + # is nonzero. + urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right + gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, + gain / 2.0]), + (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, + gain / 2.0]), + (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, + -loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, + -loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap), + -loss / 2.0])] + llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left + loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, + loss / 2.0]), + (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, + loss / 2.0]), + (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, + -gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, + -gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0), + -gain / 2.0])] + lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right + loss / 2.0])] + ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left + gain / 2.0])] + + # Add the subpaths and assign the locations of the tips and labels. + tips = np.zeros((n, 2)) + label_locations = np.zeros((n, 2)) + # Add the top-side inputs and outputs from the middle outwards. + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == DOWN and is_input: + tips[i, :], label_locations[i, :] = self._add_input( + ulpath, angle, *spec) + elif angle == UP and is_input is False: + tips[i, :], label_locations[i, :] = self._add_output( + urpath, angle, *spec) + # Add the bottom-side inputs and outputs from the middle outwards. + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + if angle == UP and is_input: + tip, label_location = self._add_input(llpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + elif angle == DOWN and is_input is False: + tip, label_location = self._add_output(lrpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + # Add the left-side inputs from the bottom upwards. + has_left_input = False + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + if angle == RIGHT and is_input: + if not has_left_input: + # Make sure the lower path extends + # at least as far as the upper one. + if llpath[-1][1][0] > ulpath[-1][1][0]: + llpath.append((Path.LINETO, [ulpath[-1][1][0], + llpath[-1][1][1]])) + has_left_input = True + tip, label_location = self._add_input(llpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + # Add the right-side outputs from the top downwards. + has_right_output = False + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == RIGHT and is_input is False: + if not has_right_output: + # Make sure the upper path extends + # at least as far as the lower one. + if urpath[-1][1][0] < lrpath[-1][1][0]: + urpath.append((Path.LINETO, [lrpath[-1][1][0], + urpath[-1][1][1]])) + has_right_output = True + tips[i, :], label_locations[i, :] = self._add_output( + urpath, angle, *spec) + # Trim any hanging vertices. + if not has_left_input: + ulpath.pop() + llpath.pop() + if not has_right_output: + lrpath.pop() + urpath.pop() + + # Concatenate the subpaths in the correct order (clockwise from top). + path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) + + [(Path.CLOSEPOLY, urpath[0][1])]) + + # Create a patch with the Sankey outline. + codes, vertices = zip(*path) + vertices = np.array(vertices) + + def _get_angle(a, r): + if a is None: + return None + else: + return a + r + + if prior is None: + if rotation != 0: # By default, none of this is needed. + angles = [_get_angle(angle, rotation) for angle in angles] + rotate = Affine2D().rotate_deg(rotation * 90).transform_affine + tips = rotate(tips) + label_locations = rotate(label_locations) + vertices = rotate(vertices) + text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center') + else: + rotation = (self.diagrams[prior].angles[connect[0]] - + angles[connect[1]]) + angles = [_get_angle(angle, rotation) for angle in angles] + rotate = Affine2D().rotate_deg(rotation * 90).transform_affine + tips = rotate(tips) + offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]] + translate = Affine2D().translate(*offset).transform_affine + tips = translate(tips) + label_locations = translate(rotate(label_locations)) + vertices = translate(rotate(vertices)) + kwds = dict(s=patchlabel, ha='center', va='center') + text = self.ax.text(*offset, **kwds) + if mpl.rcParams['_internal.classic_mode']: + fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4')) + lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5)) + else: + fc = kwargs.pop('fc', kwargs.pop('facecolor', None)) + lw = kwargs.pop('lw', kwargs.pop('linewidth', None)) + if fc is None: + fc = self.ax._get_patches_for_fill.get_next_color() + patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs) + self.ax.add_patch(patch) + + # Add the path labels. + texts = [] + for number, angle, label, location in zip(flows, angles, labels, + label_locations): + if label is None or angle is None: + label = '' + elif self.unit is not None: + if isinstance(self.format, str): + quantity = self.format % abs(number) + self.unit + elif callable(self.format): + quantity = self.format(number) + else: + raise TypeError( + 'format must be callable or a format string') + if label != '': + label += "\n" + label += quantity + texts.append(self.ax.text(x=location[0], y=location[1], + s=label, + ha='center', va='center')) + # Text objects are placed even they are empty (as long as the magnitude + # of the corresponding flow is larger than the tolerance) in case the + # user wants to provide labels later. + + # Expand the size of the diagram if necessary. + self.extent = (min(np.min(vertices[:, 0]), + np.min(label_locations[:, 0]), + self.extent[0]), + max(np.max(vertices[:, 0]), + np.max(label_locations[:, 0]), + self.extent[1]), + min(np.min(vertices[:, 1]), + np.min(label_locations[:, 1]), + self.extent[2]), + max(np.max(vertices[:, 1]), + np.max(label_locations[:, 1]), + self.extent[3])) + # Include both vertices _and_ label locations in the extents; there are + # where either could determine the margins (e.g., arrow shoulders). + + # Add this diagram as a subdiagram. + self.diagrams.append( + SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips, + text=text, texts=texts)) + + # Allow a daisy-chained call structure (see docstring for the class). + return self + + def finish(self): + """ + Adjust the Axes and return a list of information about the Sankey + subdiagram(s). + + Returns a list of subdiagrams with the following fields: + + ======== ============================================================= + Field Description + ======== ============================================================= + *patch* Sankey outline (a `~matplotlib.patches.PathPatch`). + *flows* Flow values (positive for input, negative for output). + *angles* List of angles of the arrows [deg/90]. + For example, if the diagram has not been rotated, + an input to the top side has an angle of 3 (DOWN), + and an output from the top side has an angle of 1 (UP). + If a flow has been skipped (because its magnitude is less + than *tolerance*), then its angle will be *None*. + *tips* (N, 2)-array of the (x, y) positions of the tips (or "dips") + of the flow paths. + If the magnitude of a flow is less the *tolerance* of this + `Sankey` instance, the flow is skipped and its tip will be at + the center of the diagram. + *text* `.Text` instance for the diagram label. + *texts* List of `.Text` instances for the flow labels. + ======== ============================================================= + + See Also + -------- + Sankey.add + """ + self.ax.axis([self.extent[0] - self.margin, + self.extent[1] + self.margin, + self.extent[2] - self.margin, + self.extent[3] + self.margin]) + self.ax.set_aspect('equal', adjustable='datalim') + return self.diagrams diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/sankey.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/sankey.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4a40c31e3c6ae726de79c5b9f804c175c65eb76c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/sankey.pyi @@ -0,0 +1,61 @@ +from matplotlib.axes import Axes + +from collections.abc import Callable, Iterable +from typing import Any + +import numpy as np + +__license__: str +__credits__: list[str] +__author__: str +__version__: str + +RIGHT: int +UP: int +DOWN: int + +# TODO typing units +class Sankey: + diagrams: list[Any] + ax: Axes + unit: Any + format: str | Callable[[float], str] + scale: float + gap: float + radius: float + shoulder: float + offset: float + margin: float + pitch: float + tolerance: float + extent: np.ndarray + def __init__( + self, + ax: Axes | None = ..., + scale: float = ..., + unit: Any = ..., + format: str | Callable[[float], str] = ..., + gap: float = ..., + radius: float = ..., + shoulder: float = ..., + offset: float = ..., + head_angle: float = ..., + margin: float = ..., + tolerance: float = ..., + **kwargs + ) -> None: ... + def add( + self, + patchlabel: str = ..., + flows: Iterable[float] | None = ..., + orientations: Iterable[int] | None = ..., + labels: str | Iterable[str | None] = ..., + trunklength: float = ..., + pathlengths: float | Iterable[float] = ..., + prior: int | None = ..., + connect: tuple[int, int] = ..., + rotation: float = ..., + **kwargs + # Replace return with Self when py3.9 is dropped + ) -> Sankey: ... + def finish(self) -> list[Any]: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/streamplot.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/streamplot.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9da83096e5a84dc65e5eb0035dc12eb866cfe35f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/streamplot.pyi @@ -0,0 +1,82 @@ +from matplotlib.axes import Axes +from matplotlib.colors import Normalize, Colormap +from matplotlib.collections import LineCollection, PatchCollection +from matplotlib.patches import ArrowStyle +from matplotlib.transforms import Transform + +from typing import Literal +from numpy.typing import ArrayLike +from .typing import ColorType + +def streamplot( + axes: Axes, + x: ArrayLike, + y: ArrayLike, + u: ArrayLike, + v: ArrayLike, + density: float | tuple[float, float] = ..., + linewidth: float | ArrayLike | None = ..., + color: ColorType | ArrayLike | None = ..., + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + arrowsize: float = ..., + arrowstyle: str | ArrowStyle = ..., + minlength: float = ..., + transform: Transform | None = ..., + zorder: float | None = ..., + start_points: ArrayLike | None = ..., + maxlength: float = ..., + integration_direction: Literal["forward", "backward", "both"] = ..., + broken_streamlines: bool = ..., +) -> StreamplotSet: ... + +class StreamplotSet: + lines: LineCollection + arrows: PatchCollection + def __init__(self, lines: LineCollection, arrows: PatchCollection) -> None: ... + +class DomainMap: + grid: Grid + mask: StreamMask + x_grid2mask: float + y_grid2mask: float + x_mask2grid: float + y_mask2grid: float + x_data2grid: float + y_data2grid: float + def __init__(self, grid: Grid, mask: StreamMask) -> None: ... + def grid2mask(self, xi: float, yi: float) -> tuple[int, int]: ... + def mask2grid(self, xm: float, ym: float) -> tuple[float, float]: ... + def data2grid(self, xd: float, yd: float) -> tuple[float, float]: ... + def grid2data(self, xg: float, yg: float) -> tuple[float, float]: ... + def start_trajectory( + self, xg: float, yg: float, broken_streamlines: bool = ... + ) -> None: ... + def reset_start_point(self, xg: float, yg: float) -> None: ... + def update_trajectory(self, xg, yg, broken_streamlines: bool = ...) -> None: ... + def undo_trajectory(self) -> None: ... + +class Grid: + nx: int + ny: int + dx: float + dy: float + x_origin: float + y_origin: float + width: float + height: float + def __init__(self, x: ArrayLike, y: ArrayLike) -> None: ... + @property + def shape(self) -> tuple[int, int]: ... + def within_grid(self, xi: float, yi: float) -> bool: ... + +class StreamMask: + nx: int + ny: int + shape: tuple[int, int] + def __init__(self, density: float | tuple[float, float]) -> None: ... + def __getitem__(self, args): ... + +class InvalidIndexError(Exception): ... +class TerminateTrajectory(Exception): ... +class OutOfBounds(IndexError): ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/style/__init__.py b/llava_next/lib/python3.10/site-packages/matplotlib/style/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..488c6d6ae1ec310cdd84bb209b4103da26fed284 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/style/__init__.py @@ -0,0 +1,4 @@ +from .core import available, context, library, reload_library, use + + +__all__ = ["available", "context", "library", "reload_library", "use"] diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f1f0a1cb5374c7388b145d56eebca0adae8a23b Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/core.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20d9937dfc27dce8540a62b0c8d1ab3c58184c0e Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/core.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/style/core.py b/llava_next/lib/python3.10/site-packages/matplotlib/style/core.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9008c561655a8de68768af20272126b66b896d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/style/core.py @@ -0,0 +1,245 @@ +""" +Core functions and attributes for the matplotlib style library: + +``use`` + Select style sheet to override the current matplotlib settings. +``context`` + Context manager to use a style sheet temporarily. +``available`` + List available style sheets. +``library`` + A dictionary of style names and matplotlib settings. +""" + +import contextlib +import logging +import os +from pathlib import Path +import sys +import warnings + +if sys.version_info >= (3, 10): + import importlib.resources as importlib_resources +else: + # Even though Py3.9 has importlib.resources, it doesn't properly handle + # modules added in sys.path. + import importlib_resources + +import matplotlib as mpl +from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault + +_log = logging.getLogger(__name__) + +__all__ = ['use', 'context', 'available', 'library', 'reload_library'] + + +BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') +# Users may want multiple library paths, so store a list of paths. +USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')] +STYLE_EXTENSION = 'mplstyle' +# A list of rcParams that should not be applied from styles +STYLE_BLACKLIST = { + 'interactive', 'backend', 'webagg.port', 'webagg.address', + 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', + 'toolbar', 'timezone', 'figure.max_open_warning', + 'figure.raise_window', 'savefig.directory', 'tk.window_focus', + 'docstring.hardcopy', 'date.epoch'} + + +@_docstring.Substitution( + "\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower))) +) +def use(style): + """ + Use Matplotlib style settings from a style specification. + + The style name of 'default' is reserved for reverting back to + the default style settings. + + .. note:: + + This updates the `.rcParams` with the settings from the style. + `.rcParams` not defined in the style are kept. + + Parameters + ---------- + style : str, dict, Path or list + + A style specification. Valid options are: + + str + - One of the style names in `.style.available` (a builtin style or + a style installed in the user library path). + + - A dotted name of the form "package.style_name"; in that case, + "package" should be an importable Python package name, e.g. at + ``/path/to/package/__init__.py``; the loaded style file is + ``/path/to/package/style_name.mplstyle``. (Style files in + subpackages are likewise supported.) + + - The path or URL to a style file, which gets loaded by + `.rc_params_from_file`. + + dict + A mapping of key/value pairs for `matplotlib.rcParams`. + + Path + The path to a style file, which gets loaded by + `.rc_params_from_file`. + + list + A list of style specifiers (str, Path or dict), which are applied + from first to last in the list. + + Notes + ----- + The following `.rcParams` are not related to style and will be ignored if + found in a style specification: + + %s + """ + if isinstance(style, (str, Path)) or hasattr(style, 'keys'): + # If name is a single str, Path or dict, make it a single element list. + styles = [style] + else: + styles = style + + style_alias = {'mpl20': 'default', 'mpl15': 'classic'} + + for style in styles: + if isinstance(style, str): + style = style_alias.get(style, style) + if style == "default": + # Deprecation warnings were already handled when creating + # rcParamsDefault, no need to reemit them here. + with _api.suppress_matplotlib_deprecation_warning(): + # don't trigger RcParams.__getitem__('backend') + style = {k: rcParamsDefault[k] for k in rcParamsDefault + if k not in STYLE_BLACKLIST} + elif style in library: + style = library[style] + elif "." in style: + pkg, _, name = style.rpartition(".") + try: + path = (importlib_resources.files(pkg) + / f"{name}.{STYLE_EXTENSION}") + style = _rc_params_in_file(path) + except (ModuleNotFoundError, OSError, TypeError) as exc: + # There is an ambiguity whether a dotted name refers to a + # package.style_name or to a dotted file path. Currently, + # we silently try the first form and then the second one; + # in the future, we may consider forcing file paths to + # either use Path objects or be prepended with "./" and use + # the slash as marker for file paths. + pass + if isinstance(style, (str, Path)): + try: + style = _rc_params_in_file(style) + except OSError as err: + raise OSError( + f"{style!r} is not a valid package style, path of style " + f"file, URL of style file, or library style name (library " + f"styles are listed in `style.available`)") from err + filtered = {} + for k in style: # don't trigger RcParams.__getitem__('backend') + if k in STYLE_BLACKLIST: + _api.warn_external( + f"Style includes a parameter, {k!r}, that is not " + f"related to style. Ignoring this parameter.") + else: + filtered[k] = style[k] + mpl.rcParams.update(filtered) + + +@contextlib.contextmanager +def context(style, after_reset=False): + """ + Context manager for using style settings temporarily. + + Parameters + ---------- + style : str, dict, Path or list + A style specification. Valid options are: + + str + - One of the style names in `.style.available` (a builtin style or + a style installed in the user library path). + + - A dotted name of the form "package.style_name"; in that case, + "package" should be an importable Python package name, e.g. at + ``/path/to/package/__init__.py``; the loaded style file is + ``/path/to/package/style_name.mplstyle``. (Style files in + subpackages are likewise supported.) + + - The path or URL to a style file, which gets loaded by + `.rc_params_from_file`. + dict + A mapping of key/value pairs for `matplotlib.rcParams`. + + Path + The path to a style file, which gets loaded by + `.rc_params_from_file`. + + list + A list of style specifiers (str, Path or dict), which are applied + from first to last in the list. + + after_reset : bool + If True, apply style after resetting settings to their defaults; + otherwise, apply style on top of the current settings. + """ + with mpl.rc_context(): + if after_reset: + mpl.rcdefaults() + use(style) + yield + + +def update_user_library(library): + """Update style library with user-defined rc files.""" + for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS): + styles = read_style_directory(stylelib_path) + update_nested_dict(library, styles) + return library + + +def read_style_directory(style_dir): + """Return dictionary of styles defined in *style_dir*.""" + styles = dict() + for path in Path(style_dir).glob(f"*.{STYLE_EXTENSION}"): + with warnings.catch_warnings(record=True) as warns: + styles[path.stem] = _rc_params_in_file(path) + for w in warns: + _log.warning('In %s: %s', path, w.message) + return styles + + +def update_nested_dict(main_dict, new_dict): + """ + Update nested dict (only level of nesting) with new values. + + Unlike `dict.update`, this assumes that the values of the parent dict are + dicts (or dict-like), so you shouldn't replace the nested dict if it + already exists. Instead you should update the sub-dict. + """ + # update named styles specified by user + for name, rc_dict in new_dict.items(): + main_dict.setdefault(name, {}).update(rc_dict) + return main_dict + + +# Load style library +# ================== +_base_library = read_style_directory(BASE_LIBRARY_PATH) +library = {} +available = [] + + +def reload_library(): + """Reload the style library.""" + library.clear() + library.update(update_user_library(_base_library)) + available[:] = sorted(library.keys()) + + +reload_library() diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/style/core.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/style/core.pyi new file mode 100644 index 0000000000000000000000000000000000000000..73400492143ccc346d9e284b52e8702cb59cc263 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/style/core.pyi @@ -0,0 +1,19 @@ +from collections.abc import Generator +import contextlib + +from matplotlib import RcParams +from matplotlib.typing import RcStyleType + +USER_LIBRARY_PATHS: list[str] = ... +STYLE_EXTENSION: str = ... + +def use(style: RcStyleType) -> None: ... +@contextlib.contextmanager +def context( + style: RcStyleType, after_reset: bool = ... +) -> Generator[None, None, None]: ... + +library: dict[str, RcParams] +available: list[str] + +def reload_library() -> None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19113d3996268ca6d3cec637785f7a30da0aae2f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.py @@ -0,0 +1,234 @@ +""" +Helper functions for testing. +""" +from pathlib import Path +from tempfile import TemporaryDirectory +import locale +import logging +import os +import subprocess +import sys + +import matplotlib as mpl +from matplotlib import _api + +_log = logging.getLogger(__name__) + + +def set_font_settings_for_testing(): + mpl.rcParams['font.family'] = 'DejaVu Sans' + mpl.rcParams['text.hinting'] = 'none' + mpl.rcParams['text.hinting_factor'] = 8 + + +def set_reproducibility_for_testing(): + mpl.rcParams['svg.hashsalt'] = 'matplotlib' + + +def setup(): + # The baseline images are created in this locale, so we should use + # it during all of the tests. + + try: + locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') + except locale.Error: + try: + locale.setlocale(locale.LC_ALL, 'English_United States.1252') + except locale.Error: + _log.warning( + "Could not set locale to English/United States. " + "Some date-related tests may fail.") + + mpl.use('Agg') + + with _api.suppress_matplotlib_deprecation_warning(): + mpl.rcdefaults() # Start with all defaults + + # These settings *must* be hardcoded for running the comparison tests and + # are not necessarily the default values as specified in rcsetup.py. + set_font_settings_for_testing() + set_reproducibility_for_testing() + + +def subprocess_run_for_testing(command, env=None, timeout=60, stdout=None, + stderr=None, check=False, text=True, + capture_output=False): + """ + Create and run a subprocess. + + Thin wrapper around `subprocess.run`, intended for testing. Will + mark fork() failures on Cygwin as expected failures: not a + success, but not indicating a problem with the code either. + + Parameters + ---------- + args : list of str + env : dict[str, str] + timeout : float + stdout, stderr + check : bool + text : bool + Also called ``universal_newlines`` in subprocess. I chose this + name since the main effect is returning bytes (`False`) vs. str + (`True`), though it also tries to normalize newlines across + platforms. + capture_output : bool + Set stdout and stderr to subprocess.PIPE + + Returns + ------- + proc : subprocess.Popen + + See Also + -------- + subprocess.run + + Raises + ------ + pytest.xfail + If platform is Cygwin and subprocess reports a fork() failure. + """ + if capture_output: + stdout = stderr = subprocess.PIPE + try: + proc = subprocess.run( + command, env=env, + timeout=timeout, check=check, + stdout=stdout, stderr=stderr, + text=text + ) + except BlockingIOError: + if sys.platform == "cygwin": + # Might want to make this more specific + import pytest + pytest.xfail("Fork failure") + raise + return proc + + +def subprocess_run_helper(func, *args, timeout, extra_env=None): + """ + Run a function in a sub-process. + + Parameters + ---------- + func : function + The function to be run. It must be in a module that is importable. + *args : str + Any additional command line arguments to be passed in + the first argument to ``subprocess.run``. + extra_env : dict[str, str] + Any additional environment variables to be set for the subprocess. + """ + target = func.__name__ + module = func.__module__ + file = func.__code__.co_filename + proc = subprocess_run_for_testing( + [ + sys.executable, + "-c", + f"import importlib.util;" + f"_spec = importlib.util.spec_from_file_location({module!r}, {file!r});" + f"_module = importlib.util.module_from_spec(_spec);" + f"_spec.loader.exec_module(_module);" + f"_module.{target}()", + *args + ], + env={**os.environ, "SOURCE_DATE_EPOCH": "0", **(extra_env or {})}, + timeout=timeout, check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True + ) + return proc + + +def _check_for_pgf(texsystem): + """ + Check if a given TeX system + pgf is available + + Parameters + ---------- + texsystem : str + The executable name to check + """ + with TemporaryDirectory() as tmpdir: + tex_path = Path(tmpdir, "test.tex") + tex_path.write_text(r""" + \documentclass{article} + \usepackage{pgf} + \begin{document} + \typeout{pgfversion=\pgfversion} + \makeatletter + \@@end + """, encoding="utf-8") + try: + subprocess.check_call( + [texsystem, "-halt-on-error", str(tex_path)], cwd=tmpdir, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except (OSError, subprocess.CalledProcessError): + return False + return True + + +def _has_tex_package(package): + try: + mpl.dviread.find_tex_file(f"{package}.sty") + return True + except FileNotFoundError: + return False + + +def ipython_in_subprocess(requested_backend_or_gui_framework, all_expected_backends): + import pytest + IPython = pytest.importorskip("IPython") + + if sys.platform == "win32": + pytest.skip("Cannot change backend running IPython in subprocess on Windows") + + if (IPython.version_info[:3] == (8, 24, 0) and + requested_backend_or_gui_framework == "osx"): + pytest.skip("Bug using macosx backend in IPython 8.24.0 fixed in 8.24.1") + + # This code can be removed when Python 3.12, the latest version supported + # by IPython < 8.24, reaches end-of-life in late 2028. + for min_version, backend in all_expected_backends.items(): + if IPython.version_info[:2] >= min_version: + expected_backend = backend + break + + code = ("import matplotlib as mpl, matplotlib.pyplot as plt;" + "fig, ax=plt.subplots(); ax.plot([1, 3, 2]); mpl.get_backend()") + proc = subprocess_run_for_testing( + [ + "ipython", + "--no-simple-prompt", + f"--matplotlib={requested_backend_or_gui_framework}", + "-c", code, + ], + check=True, + capture_output=True, + ) + + assert proc.stdout.strip().endswith(f"'{expected_backend}'") + + +def is_ci_environment(): + # Common CI variables + ci_environment_variables = [ + 'CI', # Generic CI environment variable + 'CONTINUOUS_INTEGRATION', # Generic CI environment variable + 'TRAVIS', # Travis CI + 'CIRCLECI', # CircleCI + 'JENKINS', # Jenkins + 'GITLAB_CI', # GitLab CI + 'GITHUB_ACTIONS', # GitHub Actions + 'TEAMCITY_VERSION' # TeamCity + # Add other CI environment variables as needed + ] + + for env_var in ci_environment_variables: + if os.getenv(env_var): + return True + + return False diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6917b6a5a38080b389f5d970beb8973c1c041206 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.pyi @@ -0,0 +1,54 @@ +from collections.abc import Callable +import subprocess +from typing import Any, IO, Literal, overload + +def set_font_settings_for_testing() -> None: ... +def set_reproducibility_for_testing() -> None: ... +def setup() -> None: ... +@overload +def subprocess_run_for_testing( + command: list[str], + env: dict[str, str] | None = ..., + timeout: float | None = ..., + stdout: int | IO[Any] | None = ..., + stderr: int | IO[Any] | None = ..., + check: bool = ..., + *, + text: Literal[True], + capture_output: bool = ..., +) -> subprocess.CompletedProcess[str]: ... +@overload +def subprocess_run_for_testing( + command: list[str], + env: dict[str, str] | None = ..., + timeout: float | None = ..., + stdout: int | IO[Any] | None = ..., + stderr: int | IO[Any] | None = ..., + check: bool = ..., + text: Literal[False] = ..., + capture_output: bool = ..., +) -> subprocess.CompletedProcess[bytes]: ... +@overload +def subprocess_run_for_testing( + command: list[str], + env: dict[str, str] | None = ..., + timeout: float | None = ..., + stdout: int | IO[Any] | None = ..., + stderr: int | IO[Any] | None = ..., + check: bool = ..., + text: bool = ..., + capture_output: bool = ..., +) -> subprocess.CompletedProcess[bytes] | subprocess.CompletedProcess[str]: ... +def subprocess_run_helper( + func: Callable[[], None], + *args: Any, + timeout: float, + extra_env: dict[str, str] | None = ..., +) -> subprocess.CompletedProcess[str]: ... +def _check_for_pgf(texsystem: str) -> bool: ... +def _has_tex_package(package: str) -> bool: ... +def ipython_in_subprocess( + requested_backend_or_gui_framework: str, + all_expected_backends: dict[tuple[int, int], str], +) -> None: ... +def is_ci_environment() -> bool: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/_markers.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/_markers.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ef8687a8b39766ba0385b5145b841043251de5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/_markers.py @@ -0,0 +1,49 @@ +""" +pytest markers for the internal Matplotlib test suite. +""" + +import logging +import shutil + +import pytest + +import matplotlib.testing +import matplotlib.testing.compare +from matplotlib import _get_executable_info, ExecutableNotFoundError + + +_log = logging.getLogger(__name__) + + +def _checkdep_usetex() -> bool: + if not shutil.which("tex"): + _log.warning("usetex mode requires TeX.") + return False + try: + _get_executable_info("dvipng") + except ExecutableNotFoundError: + _log.warning("usetex mode requires dvipng.") + return False + try: + _get_executable_info("gs") + except ExecutableNotFoundError: + _log.warning("usetex mode requires ghostscript.") + return False + return True + + +needs_ghostscript = pytest.mark.skipif( + "eps" not in matplotlib.testing.compare.converter, + reason="This test needs a ghostscript installation") +needs_pgf_lualatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('lualatex'), + reason='lualatex + pgf is required') +needs_pgf_pdflatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('pdflatex'), + reason='pdflatex + pgf is required') +needs_pgf_xelatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('xelatex'), + reason='xelatex + pgf is required') +needs_usetex = pytest.mark.skipif( + not _checkdep_usetex(), + reason="This test needs a TeX installation") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/compare.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..ee93061480e7172fed13a2cc34f41dcbadbd681a --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/compare.py @@ -0,0 +1,520 @@ +""" +Utilities for comparing image results. +""" + +import atexit +import functools +import hashlib +import logging +import os +from pathlib import Path +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory, TemporaryFile +import weakref + +import numpy as np +from PIL import Image + +import matplotlib as mpl +from matplotlib import cbook +from matplotlib.testing.exceptions import ImageComparisonFailure + +_log = logging.getLogger(__name__) + +__all__ = ['calculate_rms', 'comparable_formats', 'compare_images'] + + +def make_test_filename(fname, purpose): + """ + Make a new filename by inserting *purpose* before the file's extension. + """ + base, ext = os.path.splitext(fname) + return f'{base}-{purpose}{ext}' + + +def _get_cache_path(): + cache_dir = Path(mpl.get_cachedir(), 'test_cache') + cache_dir.mkdir(parents=True, exist_ok=True) + return cache_dir + + +def get_cache_dir(): + return str(_get_cache_path()) + + +def get_file_hash(path, block_size=2 ** 20): + md5 = hashlib.md5() + with open(path, 'rb') as fd: + while True: + data = fd.read(block_size) + if not data: + break + md5.update(data) + + if Path(path).suffix == '.pdf': + md5.update(str(mpl._get_executable_info("gs").version) + .encode('utf-8')) + elif Path(path).suffix == '.svg': + md5.update(str(mpl._get_executable_info("inkscape").version) + .encode('utf-8')) + + return md5.hexdigest() + + +class _ConverterError(Exception): + pass + + +class _Converter: + def __init__(self): + self._proc = None + # Explicitly register deletion from an atexit handler because if we + # wait until the object is GC'd (which occurs later), then some module + # globals (e.g. signal.SIGKILL) has already been set to None, and + # kill() doesn't work anymore... + atexit.register(self.__del__) + + def __del__(self): + if self._proc: + self._proc.kill() + self._proc.wait() + for stream in filter(None, [self._proc.stdin, + self._proc.stdout, + self._proc.stderr]): + stream.close() + self._proc = None + + def _read_until(self, terminator): + """Read until the prompt is reached.""" + buf = bytearray() + while True: + c = self._proc.stdout.read(1) + if not c: + raise _ConverterError(os.fsdecode(bytes(buf))) + buf.extend(c) + if buf.endswith(terminator): + return bytes(buf) + + +class _GSConverter(_Converter): + def __call__(self, orig, dest): + if not self._proc: + self._proc = subprocess.Popen( + [mpl._get_executable_info("gs").executable, + "-dNOSAFER", "-dNOPAUSE", "-dEPSCrop", "-sDEVICE=png16m"], + # As far as I can see, ghostscript never outputs to stderr. + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + try: + self._read_until(b"\nGS") + except _ConverterError as e: + raise OSError(f"Failed to start Ghostscript:\n\n{e.args[0]}") from None + + def encode_and_escape(name): + return (os.fsencode(name) + .replace(b"\\", b"\\\\") + .replace(b"(", br"\(") + .replace(b")", br"\)")) + + self._proc.stdin.write( + b"<< /OutputFile (" + + encode_and_escape(dest) + + b") >> setpagedevice (" + + encode_and_escape(orig) + + b") run flush\n") + self._proc.stdin.flush() + # GS> if nothing left on the stack; GS if n items left on the stack. + err = self._read_until((b"GS<", b"GS>")) + stack = self._read_until(b">") if err.endswith(b"GS<") else b"" + if stack or not os.path.exists(dest): + stack_size = int(stack[:-1]) if stack else 0 + self._proc.stdin.write(b"pop\n" * stack_size) + # Using the systemencoding should at least get the filenames right. + raise ImageComparisonFailure( + (err + stack).decode(sys.getfilesystemencoding(), "replace")) + + +class _SVGConverter(_Converter): + def __call__(self, orig, dest): + old_inkscape = mpl._get_executable_info("inkscape").version.major < 1 + terminator = b"\n>" if old_inkscape else b"> " + if not hasattr(self, "_tmpdir"): + self._tmpdir = TemporaryDirectory() + # On Windows, we must make sure that self._proc has terminated + # (which __del__ does) before clearing _tmpdir. + weakref.finalize(self._tmpdir, self.__del__) + if (not self._proc # First run. + or self._proc.poll() is not None): # Inkscape terminated. + if self._proc is not None and self._proc.poll() is not None: + for stream in filter(None, [self._proc.stdin, + self._proc.stdout, + self._proc.stderr]): + stream.close() + env = { + **os.environ, + # If one passes e.g. a png file to Inkscape, it will try to + # query the user for conversion options via a GUI (even with + # `--without-gui`). Unsetting `DISPLAY` prevents this (and + # causes GTK to crash and Inkscape to terminate, but that'll + # just be reported as a regular exception below). + "DISPLAY": "", + # Do not load any user options. + "INKSCAPE_PROFILE_DIR": self._tmpdir.name, + } + # Old versions of Inkscape (e.g. 0.48.3.1) seem to sometimes + # deadlock when stderr is redirected to a pipe, so we redirect it + # to a temporary file instead. This is not necessary anymore as of + # Inkscape 0.92.1. + stderr = TemporaryFile() + self._proc = subprocess.Popen( + ["inkscape", "--without-gui", "--shell"] if old_inkscape else + ["inkscape", "--shell"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, + env=env, cwd=self._tmpdir.name) + # Slight abuse, but makes shutdown handling easier. + self._proc.stderr = stderr + try: + self._read_until(terminator) + except _ConverterError as err: + raise OSError( + "Failed to start Inkscape in interactive mode:\n\n" + + err.args[0]) from err + + # Inkscape's shell mode does not support escaping metacharacters in the + # filename ("\n", and ":;" for inkscape>=1). Avoid any problems by + # running from a temporary directory and using fixed filenames. + inkscape_orig = Path(self._tmpdir.name, os.fsdecode(b"f.svg")) + inkscape_dest = Path(self._tmpdir.name, os.fsdecode(b"f.png")) + try: + inkscape_orig.symlink_to(Path(orig).resolve()) + except OSError: + shutil.copyfile(orig, inkscape_orig) + self._proc.stdin.write( + b"f.svg --export-png=f.png\n" if old_inkscape else + b"file-open:f.svg;export-filename:f.png;export-do;file-close\n") + self._proc.stdin.flush() + try: + self._read_until(terminator) + except _ConverterError as err: + # Inkscape's output is not localized but gtk's is, so the output + # stream probably has a mixed encoding. Using the filesystem + # encoding should at least get the filenames right... + self._proc.stderr.seek(0) + raise ImageComparisonFailure( + self._proc.stderr.read().decode( + sys.getfilesystemencoding(), "replace")) from err + os.remove(inkscape_orig) + shutil.move(inkscape_dest, dest) + + def __del__(self): + super().__del__() + if hasattr(self, "_tmpdir"): + self._tmpdir.cleanup() + + +class _SVGWithMatplotlibFontsConverter(_SVGConverter): + """ + A SVG converter which explicitly adds the fonts shipped by Matplotlib to + Inkspace's font search path, to better support `svg.fonttype = "none"` + (which is in particular used by certain mathtext tests). + """ + + def __call__(self, orig, dest): + if not hasattr(self, "_tmpdir"): + self._tmpdir = TemporaryDirectory() + shutil.copytree(cbook._get_data_path("fonts/ttf"), + Path(self._tmpdir.name, "fonts")) + return super().__call__(orig, dest) + + +def _update_converter(): + try: + mpl._get_executable_info("gs") + except mpl.ExecutableNotFoundError: + pass + else: + converter['pdf'] = converter['eps'] = _GSConverter() + try: + mpl._get_executable_info("inkscape") + except mpl.ExecutableNotFoundError: + pass + else: + converter['svg'] = _SVGConverter() + + +#: A dictionary that maps filename extensions to functions which themselves +#: convert between arguments `old` and `new` (filenames). +converter = {} +_update_converter() +_svg_with_matplotlib_fonts_converter = _SVGWithMatplotlibFontsConverter() + + +def comparable_formats(): + """ + Return the list of file formats that `.compare_images` can compare + on this system. + + Returns + ------- + list of str + E.g. ``['png', 'pdf', 'svg', 'eps']``. + + """ + return ['png', *converter] + + +def convert(filename, cache): + """ + Convert the named file to png; return the name of the created file. + + If *cache* is True, the result of the conversion is cached in + `matplotlib.get_cachedir() + '/test_cache/'`. The caching is based on a + hash of the exact contents of the input file. Old cache entries are + automatically deleted as needed to keep the size of the cache capped to + twice the size of all baseline images. + """ + path = Path(filename) + if not path.exists(): + raise OSError(f"{path} does not exist") + if path.suffix[1:] not in converter: + import pytest + pytest.skip(f"Don't know how to convert {path.suffix} files to png") + newpath = path.parent / f"{path.stem}_{path.suffix[1:]}.png" + + # Only convert the file if the destination doesn't already exist or + # is out of date. + if not newpath.exists() or newpath.stat().st_mtime < path.stat().st_mtime: + cache_dir = _get_cache_path() if cache else None + + if cache_dir is not None: + _register_conversion_cache_cleaner_once() + hash_value = get_file_hash(path) + cached_path = cache_dir / (hash_value + newpath.suffix) + if cached_path.exists(): + _log.debug("For %s: reusing cached conversion.", filename) + shutil.copyfile(cached_path, newpath) + return str(newpath) + + _log.debug("For %s: converting to png.", filename) + convert = converter[path.suffix[1:]] + if path.suffix == ".svg": + contents = path.read_text() + # NOTE: This check should be kept in sync with font styling in + # `lib/matplotlib/backends/backend_svg.py`. If it changes, then be sure to + # re-generate any SVG test files using this mode, or else such tests will + # fail to use the converter for the expected images (but will for the + # results), and the tests will fail strangely. + if 'style="font:' in contents: + # for svg.fonttype = none, we explicitly patch the font search + # path so that fonts shipped by Matplotlib are found. + convert = _svg_with_matplotlib_fonts_converter + convert(path, newpath) + + if cache_dir is not None: + _log.debug("For %s: caching conversion result.", filename) + shutil.copyfile(newpath, cached_path) + + return str(newpath) + + +def _clean_conversion_cache(): + # This will actually ignore mpl_toolkits baseline images, but they're + # relatively small. + baseline_images_size = sum( + path.stat().st_size + for path in Path(mpl.__file__).parent.glob("**/baseline_images/**/*")) + # 2x: one full copy of baselines, and one full copy of test results + # (actually an overestimate: we don't convert png baselines and results). + max_cache_size = 2 * baseline_images_size + # Reduce cache until it fits. + with cbook._lock_path(_get_cache_path()): + cache_stat = { + path: path.stat() for path in _get_cache_path().glob("*")} + cache_size = sum(stat.st_size for stat in cache_stat.values()) + paths_by_atime = sorted( # Oldest at the end. + cache_stat, key=lambda path: cache_stat[path].st_atime, + reverse=True) + while cache_size > max_cache_size: + path = paths_by_atime.pop() + cache_size -= cache_stat[path].st_size + path.unlink() + + +@functools.cache # Ensure this is only registered once. +def _register_conversion_cache_cleaner_once(): + atexit.register(_clean_conversion_cache) + + +def crop_to_same(actual_path, actual_image, expected_path, expected_image): + # clip the images to the same size -- this is useful only when + # comparing eps to pdf + if actual_path[-7:-4] == 'eps' and expected_path[-7:-4] == 'pdf': + aw, ah, ad = actual_image.shape + ew, eh, ed = expected_image.shape + actual_image = actual_image[int(aw / 2 - ew / 2):int( + aw / 2 + ew / 2), int(ah / 2 - eh / 2):int(ah / 2 + eh / 2)] + return actual_image, expected_image + + +def calculate_rms(expected_image, actual_image): + """ + Calculate the per-pixel errors, then compute the root mean square error. + """ + if expected_image.shape != actual_image.shape: + raise ImageComparisonFailure( + f"Image sizes do not match expected size: {expected_image.shape} " + f"actual size {actual_image.shape}") + # Convert to float to avoid overflowing finite integer types. + return np.sqrt(((expected_image - actual_image).astype(float) ** 2).mean()) + + +# NOTE: compare_image and save_diff_image assume that the image does not have +# 16-bit depth, as Pillow converts these to RGB incorrectly. + + +def _load_image(path): + img = Image.open(path) + # In an RGBA image, if the smallest value in the alpha channel is 255, all + # values in it must be 255, meaning that the image is opaque. If so, + # discard the alpha channel so that it may compare equal to an RGB image. + if img.mode != "RGBA" or img.getextrema()[3][0] == 255: + img = img.convert("RGB") + return np.asarray(img) + + +def compare_images(expected, actual, tol, in_decorator=False): + """ + Compare two "image" files checking differences within a tolerance. + + The two given filenames may point to files which are convertible to + PNG via the `.converter` dictionary. The underlying RMS is calculated + with the `.calculate_rms` function. + + Parameters + ---------- + expected : str + The filename of the expected image. + actual : str + The filename of the actual image. + tol : float + The tolerance (a color value difference, where 255 is the + maximal difference). The test fails if the average pixel + difference is greater than this value. + in_decorator : bool + Determines the output format. If called from image_comparison + decorator, this should be True. (default=False) + + Returns + ------- + None or dict or str + Return *None* if the images are equal within the given tolerance. + + If the images differ, the return value depends on *in_decorator*. + If *in_decorator* is true, a dict with the following entries is + returned: + + - *rms*: The RMS of the image difference. + - *expected*: The filename of the expected image. + - *actual*: The filename of the actual image. + - *diff_image*: The filename of the difference image. + - *tol*: The comparison tolerance. + + Otherwise, a human-readable multi-line string representation of this + information is returned. + + Examples + -------- + :: + + img1 = "./baseline/plot.png" + img2 = "./output/plot.png" + compare_images(img1, img2, 0.001) + + """ + actual = os.fspath(actual) + if not os.path.exists(actual): + raise Exception(f"Output image {actual} does not exist.") + if os.stat(actual).st_size == 0: + raise Exception(f"Output image file {actual} is empty.") + + # Convert the image to png + expected = os.fspath(expected) + if not os.path.exists(expected): + raise OSError(f'Baseline image {expected!r} does not exist.') + extension = expected.split('.')[-1] + if extension != 'png': + actual = convert(actual, cache=True) + expected = convert(expected, cache=True) + + # open the image files + expected_image = _load_image(expected) + actual_image = _load_image(actual) + + actual_image, expected_image = crop_to_same( + actual, actual_image, expected, expected_image) + + diff_image = make_test_filename(actual, 'failed-diff') + + if tol <= 0: + if np.array_equal(expected_image, actual_image): + return None + + # convert to signed integers, so that the images can be subtracted without + # overflow + expected_image = expected_image.astype(np.int16) + actual_image = actual_image.astype(np.int16) + + rms = calculate_rms(expected_image, actual_image) + + if rms <= tol: + return None + + save_diff_image(expected, actual, diff_image) + + results = dict(rms=rms, expected=str(expected), + actual=str(actual), diff=str(diff_image), tol=tol) + + if not in_decorator: + # Then the results should be a string suitable for stdout. + template = ['Error: Image files did not match.', + 'RMS Value: {rms}', + 'Expected: \n {expected}', + 'Actual: \n {actual}', + 'Difference:\n {diff}', + 'Tolerance: \n {tol}', ] + results = '\n '.join([line.format(**results) for line in template]) + return results + + +def save_diff_image(expected, actual, output): + """ + Parameters + ---------- + expected : str + File path of expected image. + actual : str + File path of actual image. + output : str + File path to save difference image to. + """ + expected_image = _load_image(expected) + actual_image = _load_image(actual) + actual_image, expected_image = crop_to_same( + actual, actual_image, expected, expected_image) + expected_image = np.array(expected_image, float) + actual_image = np.array(actual_image, float) + if expected_image.shape != actual_image.shape: + raise ImageComparisonFailure( + f"Image sizes do not match expected size: {expected_image.shape} " + f"actual size {actual_image.shape}") + abs_diff = np.abs(expected_image - actual_image) + + # expand differences in luminance domain + abs_diff *= 10 + abs_diff = np.clip(abs_diff, 0, 255).astype(np.uint8) + + if abs_diff.shape[2] == 4: # Hard-code the alpha channel to fully solid + abs_diff[:, :, 3] = 255 + + Image.fromarray(abs_diff).save(output, format="png") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/compare.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/testing/compare.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8f11b3bebc1a0f4186448b1e8d6a8f11f06e3b4f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/compare.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable +from typing import Literal, overload + +from numpy.typing import NDArray + +__all__ = ["calculate_rms", "comparable_formats", "compare_images"] + +def make_test_filename(fname: str, purpose: str) -> str: ... +def get_cache_dir() -> str: ... +def get_file_hash(path: str, block_size: int = ...) -> str: ... + +converter: dict[str, Callable[[str, str], None]] = {} + +def comparable_formats() -> list[str]: ... +def convert(filename: str, cache: bool) -> str: ... +def crop_to_same( + actual_path: str, actual_image: NDArray, expected_path: str, expected_image: NDArray +) -> tuple[NDArray, NDArray]: ... +def calculate_rms(expected_image: NDArray, actual_image: NDArray) -> float: ... +@overload +def compare_images( + expected: str, actual: str, tol: float, in_decorator: Literal[True] +) -> None | dict[str, float | str]: ... +@overload +def compare_images( + expected: str, actual: str, tol: float, in_decorator: Literal[False] +) -> None | str: ... +@overload +def compare_images( + expected: str, actual: str, tol: float, in_decorator: bool = ... +) -> None | str | dict[str, float | str]: ... +def save_diff_image(expected: str, actual: str, output: str) -> None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/conftest.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..c285c247e7b47796a2e58d6c8c7d342e3781feee --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/conftest.py @@ -0,0 +1,100 @@ +import pytest +import sys +import matplotlib +from matplotlib import _api + + +def pytest_configure(config): + # config is initialized here rather than in pytest.ini so that `pytest + # --pyargs matplotlib` (which would not find pytest.ini) works. The only + # entries in pytest.ini set minversion (which is checked earlier), + # testpaths/python_files, as they are required to properly find the tests + for key, value in [ + ("markers", "flaky: (Provided by pytest-rerunfailures.)"), + ("markers", "timeout: (Provided by pytest-timeout.)"), + ("markers", "backend: Set alternate Matplotlib backend temporarily."), + ("markers", "baseline_images: Compare output against references."), + ("markers", "pytz: Tests that require pytz to be installed."), + ("filterwarnings", "error"), + ("filterwarnings", + "ignore:.*The py23 module has been deprecated:DeprecationWarning"), + ("filterwarnings", + r"ignore:DynamicImporter.find_spec\(\) not found; " + r"falling back to find_module\(\):ImportWarning"), + ]: + config.addinivalue_line(key, value) + + matplotlib.use('agg', force=True) + matplotlib._called_from_pytest = True + matplotlib._init_tests() + + +def pytest_unconfigure(config): + matplotlib._called_from_pytest = False + + +@pytest.fixture(autouse=True) +def mpl_test_settings(request): + from matplotlib.testing.decorators import _cleanup_cm + + with _cleanup_cm(): + + backend = None + backend_marker = request.node.get_closest_marker('backend') + prev_backend = matplotlib.get_backend() + if backend_marker is not None: + assert len(backend_marker.args) == 1, \ + "Marker 'backend' must specify 1 backend." + backend, = backend_marker.args + skip_on_importerror = backend_marker.kwargs.get( + 'skip_on_importerror', False) + + # special case Qt backend importing to avoid conflicts + if backend.lower().startswith('qt5'): + if any(sys.modules.get(k) for k in ('PyQt4', 'PySide')): + pytest.skip('Qt4 binding already imported') + + matplotlib.testing.setup() + with _api.suppress_matplotlib_deprecation_warning(): + if backend is not None: + # This import must come after setup() so it doesn't load the + # default backend prematurely. + import matplotlib.pyplot as plt + try: + plt.switch_backend(backend) + except ImportError as exc: + # Should only occur for the cairo backend tests, if neither + # pycairo nor cairocffi are installed. + if 'cairo' in backend.lower() or skip_on_importerror: + pytest.skip("Failed to switch to backend " + f"{backend} ({exc}).") + else: + raise + # Default of cleanup and image_comparison too. + matplotlib.style.use(["classic", "_classic_test_patch"]) + try: + yield + finally: + if backend is not None: + plt.close("all") + matplotlib.use(prev_backend) + + +@pytest.fixture +def pd(): + """Fixture to import and configure pandas.""" + pd = pytest.importorskip('pandas') + try: + from pandas.plotting import ( + deregister_matplotlib_converters as deregister) + deregister() + except ImportError: + pass + return pd + + +@pytest.fixture +def xr(): + """Fixture to import xarray.""" + xr = pytest.importorskip('xarray') + return xr diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/conftest.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/testing/conftest.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2af0eb93cc8ab537a9e5cfc4a02508a4f5b7a919 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/conftest.pyi @@ -0,0 +1,12 @@ +from types import ModuleType + +import pytest + +def pytest_configure(config: pytest.Config) -> None: ... +def pytest_unconfigure(config: pytest.Config) -> None: ... +@pytest.fixture +def mpl_test_settings(request: pytest.FixtureRequest) -> None: ... +@pytest.fixture +def pd() -> ModuleType: ... +@pytest.fixture +def xr() -> ModuleType: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/decorators.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..49ac4a1506f8410d134eb31587817098f65ca7af --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/decorators.py @@ -0,0 +1,464 @@ +import contextlib +import functools +import inspect +import os +from platform import uname +from pathlib import Path +import shutil +import string +import sys +import warnings + +from packaging.version import parse as parse_version + +import matplotlib.style +import matplotlib.units +import matplotlib.testing +from matplotlib import _pylab_helpers, cbook, ft2font, pyplot as plt, ticker +from .compare import comparable_formats, compare_images, make_test_filename +from .exceptions import ImageComparisonFailure + + +@contextlib.contextmanager +def _cleanup_cm(): + orig_units_registry = matplotlib.units.registry.copy() + try: + with warnings.catch_warnings(), matplotlib.rc_context(): + yield + finally: + matplotlib.units.registry.clear() + matplotlib.units.registry.update(orig_units_registry) + plt.close("all") + + +def _check_freetype_version(ver): + if ver is None: + return True + + if isinstance(ver, str): + ver = (ver, ver) + ver = [parse_version(x) for x in ver] + found = parse_version(ft2font.__freetype_version__) + + return ver[0] <= found <= ver[1] + + +def _checked_on_freetype_version(required_freetype_version): + import pytest + return pytest.mark.xfail( + not _check_freetype_version(required_freetype_version), + reason=f"Mismatched version of freetype. " + f"Test requires '{required_freetype_version}', " + f"you have '{ft2font.__freetype_version__}'", + raises=ImageComparisonFailure, strict=False) + + +def remove_ticks_and_titles(figure): + figure.suptitle("") + null_formatter = ticker.NullFormatter() + def remove_ticks(ax): + """Remove ticks in *ax* and all its child Axes.""" + ax.set_title("") + ax.xaxis.set_major_formatter(null_formatter) + ax.xaxis.set_minor_formatter(null_formatter) + ax.yaxis.set_major_formatter(null_formatter) + ax.yaxis.set_minor_formatter(null_formatter) + try: + ax.zaxis.set_major_formatter(null_formatter) + ax.zaxis.set_minor_formatter(null_formatter) + except AttributeError: + pass + for child in ax.child_axes: + remove_ticks(child) + for ax in figure.get_axes(): + remove_ticks(ax) + + +@contextlib.contextmanager +def _collect_new_figures(): + """ + After:: + + with _collect_new_figures() as figs: + some_code() + + the list *figs* contains the figures that have been created during the + execution of ``some_code``, sorted by figure number. + """ + managers = _pylab_helpers.Gcf.figs + preexisting = [manager for manager in managers.values()] + new_figs = [] + try: + yield new_figs + finally: + new_managers = sorted([manager for manager in managers.values() + if manager not in preexisting], + key=lambda manager: manager.num) + new_figs[:] = [manager.canvas.figure for manager in new_managers] + + +def _raise_on_image_difference(expected, actual, tol): + __tracebackhide__ = True + + err = compare_images(expected, actual, tol, in_decorator=True) + if err: + for key in ["actual", "expected", "diff"]: + err[key] = os.path.relpath(err[key]) + raise ImageComparisonFailure( + ('images not close (RMS %(rms).3f):' + '\n\t%(actual)s\n\t%(expected)s\n\t%(diff)s') % err) + + +class _ImageComparisonBase: + """ + Image comparison base class + + This class provides *just* the comparison-related functionality and avoids + any code that would be specific to any testing framework. + """ + + def __init__(self, func, tol, remove_text, savefig_kwargs): + self.func = func + self.baseline_dir, self.result_dir = _image_directories(func) + self.tol = tol + self.remove_text = remove_text + self.savefig_kwargs = savefig_kwargs + + def copy_baseline(self, baseline, extension): + baseline_path = self.baseline_dir / baseline + orig_expected_path = baseline_path.with_suffix(f'.{extension}') + if extension == 'eps' and not orig_expected_path.exists(): + orig_expected_path = orig_expected_path.with_suffix('.pdf') + expected_fname = make_test_filename( + self.result_dir / orig_expected_path.name, 'expected') + try: + # os.symlink errors if the target already exists. + with contextlib.suppress(OSError): + os.remove(expected_fname) + try: + if 'microsoft' in uname().release.lower(): + raise OSError # On WSL, symlink breaks silently + os.symlink(orig_expected_path, expected_fname) + except OSError: # On Windows, symlink *may* be unavailable. + shutil.copyfile(orig_expected_path, expected_fname) + except OSError as err: + raise ImageComparisonFailure( + f"Missing baseline image {expected_fname} because the " + f"following file cannot be accessed: " + f"{orig_expected_path}") from err + return expected_fname + + def compare(self, fig, baseline, extension, *, _lock=False): + __tracebackhide__ = True + + if self.remove_text: + remove_ticks_and_titles(fig) + + actual_path = (self.result_dir / baseline).with_suffix(f'.{extension}') + kwargs = self.savefig_kwargs.copy() + if extension == 'pdf': + kwargs.setdefault('metadata', + {'Creator': None, 'Producer': None, + 'CreationDate': None}) + + lock = (cbook._lock_path(actual_path) + if _lock else contextlib.nullcontext()) + with lock: + try: + fig.savefig(actual_path, **kwargs) + finally: + # Matplotlib has an autouse fixture to close figures, but this + # makes things more convenient for third-party users. + plt.close(fig) + expected_path = self.copy_baseline(baseline, extension) + _raise_on_image_difference(expected_path, actual_path, self.tol) + + +def _pytest_image_comparison(baseline_images, extensions, tol, + freetype_version, remove_text, savefig_kwargs, + style): + """ + Decorate function with image comparison for pytest. + + This function creates a decorator that wraps a figure-generating function + with image comparison code. + """ + import pytest + + KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY + + def decorator(func): + old_sig = inspect.signature(func) + + @functools.wraps(func) + @pytest.mark.parametrize('extension', extensions) + @matplotlib.style.context(style) + @_checked_on_freetype_version(freetype_version) + @functools.wraps(func) + def wrapper(*args, extension, request, **kwargs): + __tracebackhide__ = True + if 'extension' in old_sig.parameters: + kwargs['extension'] = extension + if 'request' in old_sig.parameters: + kwargs['request'] = request + + if extension not in comparable_formats(): + reason = { + 'pdf': 'because Ghostscript is not installed', + 'eps': 'because Ghostscript is not installed', + 'svg': 'because Inkscape is not installed', + }.get(extension, 'on this system') + pytest.skip(f"Cannot compare {extension} files {reason}") + + img = _ImageComparisonBase(func, tol=tol, remove_text=remove_text, + savefig_kwargs=savefig_kwargs) + matplotlib.testing.set_font_settings_for_testing() + + with _collect_new_figures() as figs: + func(*args, **kwargs) + + # If the test is parametrized in any way other than applied via + # this decorator, then we need to use a lock to prevent two + # processes from touching the same output file. + needs_lock = any( + marker.args[0] != 'extension' + for marker in request.node.iter_markers('parametrize')) + + if baseline_images is not None: + our_baseline_images = baseline_images + else: + # Allow baseline image list to be produced on the fly based on + # current parametrization. + our_baseline_images = request.getfixturevalue( + 'baseline_images') + + assert len(figs) == len(our_baseline_images), ( + f"Test generated {len(figs)} images but there are " + f"{len(our_baseline_images)} baseline images") + for fig, baseline in zip(figs, our_baseline_images): + img.compare(fig, baseline, extension, _lock=needs_lock) + + parameters = list(old_sig.parameters.values()) + if 'extension' not in old_sig.parameters: + parameters += [inspect.Parameter('extension', KEYWORD_ONLY)] + if 'request' not in old_sig.parameters: + parameters += [inspect.Parameter("request", KEYWORD_ONLY)] + new_sig = old_sig.replace(parameters=parameters) + wrapper.__signature__ = new_sig + + # Reach a bit into pytest internals to hoist the marks from our wrapped + # function. + new_marks = getattr(func, 'pytestmark', []) + wrapper.pytestmark + wrapper.pytestmark = new_marks + + return wrapper + + return decorator + + +def image_comparison(baseline_images, extensions=None, tol=0, + freetype_version=None, remove_text=False, + savefig_kwarg=None, + # Default of mpl_test_settings fixture and cleanup too. + style=("classic", "_classic_test_patch")): + """ + Compare images generated by the test with those specified in + *baseline_images*, which must correspond, else an `ImageComparisonFailure` + exception will be raised. + + Parameters + ---------- + baseline_images : list or None + A list of strings specifying the names of the images generated by + calls to `.Figure.savefig`. + + If *None*, the test function must use the ``baseline_images`` fixture, + either as a parameter or with `pytest.mark.usefixtures`. This value is + only allowed when using pytest. + + extensions : None or list of str + The list of extensions to test, e.g. ``['png', 'pdf']``. + + If *None*, defaults to all supported extensions: png, pdf, and svg. + + When testing a single extension, it can be directly included in the + names passed to *baseline_images*. In that case, *extensions* must not + be set. + + In order to keep the size of the test suite from ballooning, we only + include the ``svg`` or ``pdf`` outputs if the test is explicitly + exercising a feature dependent on that backend (see also the + `check_figures_equal` decorator for that purpose). + + tol : float, default: 0 + The RMS threshold above which the test is considered failed. + + Due to expected small differences in floating-point calculations, on + 32-bit systems an additional 0.06 is added to this threshold. + + freetype_version : str or tuple + The expected freetype version or range of versions for this test to + pass. + + remove_text : bool + Remove the title and tick text from the figure before comparison. This + is useful to make the baseline images independent of variations in text + rendering between different versions of FreeType. + + This does not remove other, more deliberate, text, such as legends and + annotations. + + savefig_kwarg : dict + Optional arguments that are passed to the savefig method. + + style : str, dict, or list + The optional style(s) to apply to the image test. The test itself + can also apply additional styles if desired. Defaults to ``["classic", + "_classic_test_patch"]``. + """ + + if baseline_images is not None: + # List of non-empty filename extensions. + baseline_exts = [*filter(None, {Path(baseline).suffix[1:] + for baseline in baseline_images})] + if baseline_exts: + if extensions is not None: + raise ValueError( + "When including extensions directly in 'baseline_images', " + "'extensions' cannot be set as well") + if len(baseline_exts) > 1: + raise ValueError( + "When including extensions directly in 'baseline_images', " + "all baselines must share the same suffix") + extensions = baseline_exts + baseline_images = [ # Chop suffix out from baseline_images. + Path(baseline).stem for baseline in baseline_images] + if extensions is None: + # Default extensions to test, if not set via baseline_images. + extensions = ['png', 'pdf', 'svg'] + if savefig_kwarg is None: + savefig_kwarg = dict() # default no kwargs to savefig + if sys.maxsize <= 2**32: + tol += 0.06 + return _pytest_image_comparison( + baseline_images=baseline_images, extensions=extensions, tol=tol, + freetype_version=freetype_version, remove_text=remove_text, + savefig_kwargs=savefig_kwarg, style=style) + + +def check_figures_equal(*, extensions=("png", "pdf", "svg"), tol=0): + """ + Decorator for test cases that generate and compare two figures. + + The decorated function must take two keyword arguments, *fig_test* + and *fig_ref*, and draw the test and reference images on them. + After the function returns, the figures are saved and compared. + + This decorator should be preferred over `image_comparison` when possible in + order to keep the size of the test suite from ballooning. + + Parameters + ---------- + extensions : list, default: ["png", "pdf", "svg"] + The extensions to test. + tol : float + The RMS threshold above which the test is considered failed. + + Raises + ------ + RuntimeError + If any new figures are created (and not subsequently closed) inside + the test function. + + Examples + -------- + Check that calling `.Axes.plot` with a single argument plots it against + ``[0, 1, 2, ...]``:: + + @check_figures_equal() + def test_plot(fig_test, fig_ref): + fig_test.subplots().plot([1, 3, 5]) + fig_ref.subplots().plot([0, 1, 2], [1, 3, 5]) + + """ + ALLOWED_CHARS = set(string.digits + string.ascii_letters + '_-[]()') + KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY + + def decorator(func): + import pytest + + _, result_dir = _image_directories(func) + old_sig = inspect.signature(func) + + if not {"fig_test", "fig_ref"}.issubset(old_sig.parameters): + raise ValueError("The decorated function must have at least the " + "parameters 'fig_test' and 'fig_ref', but your " + f"function has the signature {old_sig}") + + @pytest.mark.parametrize("ext", extensions) + def wrapper(*args, ext, request, **kwargs): + if 'ext' in old_sig.parameters: + kwargs['ext'] = ext + if 'request' in old_sig.parameters: + kwargs['request'] = request + + file_name = "".join(c for c in request.node.name + if c in ALLOWED_CHARS) + try: + fig_test = plt.figure("test") + fig_ref = plt.figure("reference") + with _collect_new_figures() as figs: + func(*args, fig_test=fig_test, fig_ref=fig_ref, **kwargs) + if figs: + raise RuntimeError('Number of open figures changed during ' + 'test. Make sure you are plotting to ' + 'fig_test or fig_ref, or if this is ' + 'deliberate explicitly close the ' + 'new figure(s) inside the test.') + test_image_path = result_dir / (file_name + "." + ext) + ref_image_path = result_dir / (file_name + "-expected." + ext) + fig_test.savefig(test_image_path) + fig_ref.savefig(ref_image_path) + _raise_on_image_difference( + ref_image_path, test_image_path, tol=tol + ) + finally: + plt.close(fig_test) + plt.close(fig_ref) + + parameters = [ + param + for param in old_sig.parameters.values() + if param.name not in {"fig_test", "fig_ref"} + ] + if 'ext' not in old_sig.parameters: + parameters += [inspect.Parameter("ext", KEYWORD_ONLY)] + if 'request' not in old_sig.parameters: + parameters += [inspect.Parameter("request", KEYWORD_ONLY)] + new_sig = old_sig.replace(parameters=parameters) + wrapper.__signature__ = new_sig + + # reach a bit into pytest internals to hoist the marks from + # our wrapped function + new_marks = getattr(func, "pytestmark", []) + wrapper.pytestmark + wrapper.pytestmark = new_marks + + return wrapper + + return decorator + + +def _image_directories(func): + """ + Compute the baseline and result image directories for testing *func*. + + For test module ``foo.bar.test_baz``, the baseline directory is at + ``foo/bar/baseline_images/test_baz`` and the result directory at + ``$(pwd)/result_images/test_baz``. The result directory is created if it + doesn't exist. + """ + module_path = Path(inspect.getfile(func)) + baseline_dir = module_path.parent / "baseline_images" / module_path.stem + result_dir = Path().resolve() / "result_images" / module_path.stem + result_dir.mkdir(parents=True, exist_ok=True) + return baseline_dir, result_dir diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/decorators.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/testing/decorators.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f1b6c5e595cbca4899cf169a6a85b917ad98bfb4 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/decorators.pyi @@ -0,0 +1,25 @@ +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +from matplotlib.figure import Figure +from matplotlib.typing import RcStyleType + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +def remove_ticks_and_titles(figure: Figure) -> None: ... +def image_comparison( + baseline_images: list[str] | None, + extensions: list[str] | None = ..., + tol: float = ..., + freetype_version: tuple[str, str] | str | None = ..., + remove_text: bool = ..., + savefig_kwarg: dict[str, Any] | None = ..., + style: RcStyleType = ..., +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def check_figures_equal( + *, extensions: Sequence[str] = ..., tol: float = ... +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def _image_directories(func: Callable) -> tuple[Path, Path]: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/exceptions.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..c39a39207747c75d768ea2dd498dfed364eb88c5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/exceptions.py @@ -0,0 +1,4 @@ +class ImageComparisonFailure(AssertionError): + """ + Raise this exception to mark a test as a comparison between two images. + """ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Duration.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Duration.py new file mode 100644 index 0000000000000000000000000000000000000000..052c5a47c0fd8313795acfcfc2e1aaf851d05c60 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Duration.py @@ -0,0 +1,138 @@ +"""Duration module.""" + +import functools +import operator + +from matplotlib import _api + + +class Duration: + """Class Duration in development.""" + + allowed = ["ET", "UTC"] + + def __init__(self, frame, seconds): + """ + Create a new Duration object. + + = ERROR CONDITIONS + - If the input frame is not in the allowed list, an error is thrown. + + = INPUT VARIABLES + - frame The frame of the duration. Must be 'ET' or 'UTC' + - seconds The number of seconds in the Duration. + """ + _api.check_in_list(self.allowed, frame=frame) + self._frame = frame + self._seconds = seconds + + def frame(self): + """Return the frame the duration is in.""" + return self._frame + + def __abs__(self): + """Return the absolute value of the duration.""" + return Duration(self._frame, abs(self._seconds)) + + def __neg__(self): + """Return the negative value of this Duration.""" + return Duration(self._frame, -self._seconds) + + def seconds(self): + """Return the number of seconds in the Duration.""" + return self._seconds + + def __bool__(self): + return self._seconds != 0 + + def _cmp(self, op, rhs): + """ + Check that *self* and *rhs* share frames; compare them using *op*. + """ + self.checkSameFrame(rhs, "compare") + return op(self._seconds, rhs._seconds) + + __eq__ = functools.partialmethod(_cmp, operator.eq) + __ne__ = functools.partialmethod(_cmp, operator.ne) + __lt__ = functools.partialmethod(_cmp, operator.lt) + __le__ = functools.partialmethod(_cmp, operator.le) + __gt__ = functools.partialmethod(_cmp, operator.gt) + __ge__ = functools.partialmethod(_cmp, operator.ge) + + def __add__(self, rhs): + """ + Add two Durations. + + = ERROR CONDITIONS + - If the input rhs is not in the same frame, an error is thrown. + + = INPUT VARIABLES + - rhs The Duration to add. + + = RETURN VALUE + - Returns the sum of ourselves and the input Duration. + """ + # Delay-load due to circular dependencies. + import matplotlib.testing.jpl_units as U + + if isinstance(rhs, U.Epoch): + return rhs + self + + self.checkSameFrame(rhs, "add") + return Duration(self._frame, self._seconds + rhs._seconds) + + def __sub__(self, rhs): + """ + Subtract two Durations. + + = ERROR CONDITIONS + - If the input rhs is not in the same frame, an error is thrown. + + = INPUT VARIABLES + - rhs The Duration to subtract. + + = RETURN VALUE + - Returns the difference of ourselves and the input Duration. + """ + self.checkSameFrame(rhs, "sub") + return Duration(self._frame, self._seconds - rhs._seconds) + + def __mul__(self, rhs): + """ + Scale a UnitDbl by a value. + + = INPUT VARIABLES + - rhs The scalar to multiply by. + + = RETURN VALUE + - Returns the scaled Duration. + """ + return Duration(self._frame, self._seconds * float(rhs)) + + __rmul__ = __mul__ + + def __str__(self): + """Print the Duration.""" + return f"{self._seconds:g} {self._frame}" + + def __repr__(self): + """Print the Duration.""" + return f"Duration('{self._frame}', {self._seconds:g})" + + def checkSameFrame(self, rhs, func): + """ + Check to see if frames are the same. + + = ERROR CONDITIONS + - If the frame of the rhs Duration is not the same as our frame, + an error is thrown. + + = INPUT VARIABLES + - rhs The Duration to check for the same frame + - func The name of the function doing the check. + """ + if self._frame != rhs._frame: + raise ValueError( + f"Cannot {func} Durations with different frames.\n" + f"LHS: {self._frame}\n" + f"RHS: {rhs._frame}") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py new file mode 100644 index 0000000000000000000000000000000000000000..501b7fa38c792d5bc3c7c683e62e1393a63a4ff7 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py @@ -0,0 +1,211 @@ +"""Epoch module.""" + +import functools +import operator +import math +import datetime as DT + +from matplotlib import _api +from matplotlib.dates import date2num + + +class Epoch: + # Frame conversion offsets in seconds + # t(TO) = t(FROM) + allowed[ FROM ][ TO ] + allowed = { + "ET": { + "UTC": +64.1839, + }, + "UTC": { + "ET": -64.1839, + }, + } + + def __init__(self, frame, sec=None, jd=None, daynum=None, dt=None): + """ + Create a new Epoch object. + + Build an epoch 1 of 2 ways: + + Using seconds past a Julian date: + # Epoch('ET', sec=1e8, jd=2451545) + + or using a matplotlib day number + # Epoch('ET', daynum=730119.5) + + = ERROR CONDITIONS + - If the input units are not in the allowed list, an error is thrown. + + = INPUT VARIABLES + - frame The frame of the epoch. Must be 'ET' or 'UTC' + - sec The number of seconds past the input JD. + - jd The Julian date of the epoch. + - daynum The matplotlib day number of the epoch. + - dt A python datetime instance. + """ + if ((sec is None and jd is not None) or + (sec is not None and jd is None) or + (daynum is not None and + (sec is not None or jd is not None)) or + (daynum is None and dt is None and + (sec is None or jd is None)) or + (daynum is not None and dt is not None) or + (dt is not None and (sec is not None or jd is not None)) or + ((dt is not None) and not isinstance(dt, DT.datetime))): + raise ValueError( + "Invalid inputs. Must enter sec and jd together, " + "daynum by itself, or dt (must be a python datetime).\n" + "Sec = %s\n" + "JD = %s\n" + "dnum= %s\n" + "dt = %s" % (sec, jd, daynum, dt)) + + _api.check_in_list(self.allowed, frame=frame) + self._frame = frame + + if dt is not None: + daynum = date2num(dt) + + if daynum is not None: + # 1-JAN-0001 in JD = 1721425.5 + jd = float(daynum) + 1721425.5 + self._jd = math.floor(jd) + self._seconds = (jd - self._jd) * 86400.0 + + else: + self._seconds = float(sec) + self._jd = float(jd) + + # Resolve seconds down to [ 0, 86400) + deltaDays = math.floor(self._seconds / 86400) + self._jd += deltaDays + self._seconds -= deltaDays * 86400.0 + + def convert(self, frame): + if self._frame == frame: + return self + + offset = self.allowed[self._frame][frame] + + return Epoch(frame, self._seconds + offset, self._jd) + + def frame(self): + return self._frame + + def julianDate(self, frame): + t = self + if frame != self._frame: + t = self.convert(frame) + + return t._jd + t._seconds / 86400.0 + + def secondsPast(self, frame, jd): + t = self + if frame != self._frame: + t = self.convert(frame) + + delta = t._jd - jd + return t._seconds + delta * 86400 + + def _cmp(self, op, rhs): + """Compare Epochs *self* and *rhs* using operator *op*.""" + t = self + if self._frame != rhs._frame: + t = self.convert(rhs._frame) + if t._jd != rhs._jd: + return op(t._jd, rhs._jd) + return op(t._seconds, rhs._seconds) + + __eq__ = functools.partialmethod(_cmp, operator.eq) + __ne__ = functools.partialmethod(_cmp, operator.ne) + __lt__ = functools.partialmethod(_cmp, operator.lt) + __le__ = functools.partialmethod(_cmp, operator.le) + __gt__ = functools.partialmethod(_cmp, operator.gt) + __ge__ = functools.partialmethod(_cmp, operator.ge) + + def __add__(self, rhs): + """ + Add a duration to an Epoch. + + = INPUT VARIABLES + - rhs The Epoch to subtract. + + = RETURN VALUE + - Returns the difference of ourselves and the input Epoch. + """ + t = self + if self._frame != rhs.frame(): + t = self.convert(rhs._frame) + + sec = t._seconds + rhs.seconds() + + return Epoch(t._frame, sec, t._jd) + + def __sub__(self, rhs): + """ + Subtract two Epoch's or a Duration from an Epoch. + + Valid: + Duration = Epoch - Epoch + Epoch = Epoch - Duration + + = INPUT VARIABLES + - rhs The Epoch to subtract. + + = RETURN VALUE + - Returns either the duration between to Epoch's or the a new + Epoch that is the result of subtracting a duration from an epoch. + """ + # Delay-load due to circular dependencies. + import matplotlib.testing.jpl_units as U + + # Handle Epoch - Duration + if isinstance(rhs, U.Duration): + return self + -rhs + + t = self + if self._frame != rhs._frame: + t = self.convert(rhs._frame) + + days = t._jd - rhs._jd + sec = t._seconds - rhs._seconds + + return U.Duration(rhs._frame, days*86400 + sec) + + def __str__(self): + """Print the Epoch.""" + return f"{self.julianDate(self._frame):22.15e} {self._frame}" + + def __repr__(self): + """Print the Epoch.""" + return str(self) + + @staticmethod + def range(start, stop, step): + """ + Generate a range of Epoch objects. + + Similar to the Python range() method. Returns the range [ + start, stop) at the requested step. Each element will be a + Epoch object. + + = INPUT VARIABLES + - start The starting value of the range. + - stop The stop value of the range. + - step Step to use. + + = RETURN VALUE + - Returns a list containing the requested Epoch values. + """ + elems = [] + + i = 0 + while True: + d = start + i * step + if d >= stop: + break + + elems.append(d) + i += 1 + + return elems diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/EpochConverter.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/EpochConverter.py new file mode 100644 index 0000000000000000000000000000000000000000..1edc2acf2b24fe4aab242455dd32679456f69b57 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/EpochConverter.py @@ -0,0 +1,94 @@ +"""EpochConverter module containing class EpochConverter.""" + +from matplotlib import cbook, units +import matplotlib.dates as date_ticker + +__all__ = ['EpochConverter'] + + +class EpochConverter(units.ConversionInterface): + """ + Provides Matplotlib conversion functionality for Monte Epoch and Duration + classes. + """ + + jdRef = 1721425.5 + + @staticmethod + def axisinfo(unit, axis): + # docstring inherited + majloc = date_ticker.AutoDateLocator() + majfmt = date_ticker.AutoDateFormatter(majloc) + return units.AxisInfo(majloc=majloc, majfmt=majfmt, label=unit) + + @staticmethod + def float2epoch(value, unit): + """ + Convert a Matplotlib floating-point date into an Epoch of the specified + units. + + = INPUT VARIABLES + - value The Matplotlib floating-point date. + - unit The unit system to use for the Epoch. + + = RETURN VALUE + - Returns the value converted to an Epoch in the specified time system. + """ + # Delay-load due to circular dependencies. + import matplotlib.testing.jpl_units as U + + secPastRef = value * 86400.0 * U.UnitDbl(1.0, 'sec') + return U.Epoch(unit, secPastRef, EpochConverter.jdRef) + + @staticmethod + def epoch2float(value, unit): + """ + Convert an Epoch value to a float suitable for plotting as a python + datetime object. + + = INPUT VARIABLES + - value An Epoch or list of Epochs that need to be converted. + - unit The units to use for an axis with Epoch data. + + = RETURN VALUE + - Returns the value parameter converted to floats. + """ + return value.julianDate(unit) - EpochConverter.jdRef + + @staticmethod + def duration2float(value): + """ + Convert a Duration value to a float suitable for plotting as a python + datetime object. + + = INPUT VARIABLES + - value A Duration or list of Durations that need to be converted. + + = RETURN VALUE + - Returns the value parameter converted to floats. + """ + return value.seconds() / 86400.0 + + @staticmethod + def convert(value, unit, axis): + # docstring inherited + + # Delay-load due to circular dependencies. + import matplotlib.testing.jpl_units as U + + if not cbook.is_scalar_or_string(value): + return [EpochConverter.convert(x, unit, axis) for x in value] + if unit is None: + unit = EpochConverter.default_units(value, axis) + if isinstance(value, U.Duration): + return EpochConverter.duration2float(value) + else: + return EpochConverter.epoch2float(value, unit) + + @staticmethod + def default_units(value, axis): + # docstring inherited + if cbook.is_scalar_or_string(value): + return value.frame() + else: + return EpochConverter.default_units(value[0], axis) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/StrConverter.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/StrConverter.py new file mode 100644 index 0000000000000000000000000000000000000000..a62d4981dc79201214dc926eaa6a4c74ffcba078 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/StrConverter.py @@ -0,0 +1,97 @@ +"""StrConverter module containing class StrConverter.""" + +import numpy as np + +import matplotlib.units as units + +__all__ = ['StrConverter'] + + +class StrConverter(units.ConversionInterface): + """ + A Matplotlib converter class for string data values. + + Valid units for string are: + - 'indexed' : Values are indexed as they are specified for plotting. + - 'sorted' : Values are sorted alphanumerically. + - 'inverted' : Values are inverted so that the first value is on top. + - 'sorted-inverted' : A combination of 'sorted' and 'inverted' + """ + + @staticmethod + def axisinfo(unit, axis): + # docstring inherited + return None + + @staticmethod + def convert(value, unit, axis): + # docstring inherited + + if value == []: + return [] + + # we delay loading to make matplotlib happy + ax = axis.axes + if axis is ax.xaxis: + isXAxis = True + else: + isXAxis = False + + axis.get_major_ticks() + ticks = axis.get_ticklocs() + labels = axis.get_ticklabels() + + labels = [l.get_text() for l in labels if l.get_text()] + + if not labels: + ticks = [] + labels = [] + + if not np.iterable(value): + value = [value] + + newValues = [] + for v in value: + if v not in labels and v not in newValues: + newValues.append(v) + + labels.extend(newValues) + + # DISABLED: This is disabled because matplotlib bar plots do not + # DISABLED: recalculate the unit conversion of the data values + # DISABLED: this is due to design and is not really a bug. + # DISABLED: If this gets changed, then we can activate the following + # DISABLED: block of code. Note that this works for line plots. + # DISABLED if unit: + # DISABLED if unit.find("sorted") > -1: + # DISABLED labels.sort() + # DISABLED if unit.find("inverted") > -1: + # DISABLED labels = labels[::-1] + + # add padding (so they do not appear on the axes themselves) + labels = [''] + labels + [''] + ticks = list(range(len(labels))) + ticks[0] = 0.5 + ticks[-1] = ticks[-1] - 0.5 + + axis.set_ticks(ticks) + axis.set_ticklabels(labels) + # we have to do the following lines to make ax.autoscale_view work + loc = axis.get_major_locator() + loc.set_bounds(ticks[0], ticks[-1]) + + if isXAxis: + ax.set_xlim(ticks[0], ticks[-1]) + else: + ax.set_ylim(ticks[0], ticks[-1]) + + result = [ticks[labels.index(v)] for v in value] + + ax.viewLim.ignore(-1) + return result + + @staticmethod + def default_units(value, axis): + # docstring inherited + # The default behavior for string indexing. + return "indexed" diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDbl.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDbl.py new file mode 100644 index 0000000000000000000000000000000000000000..5226c06ad54b9f7718a59e7ed19198d442c04f31 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDbl.py @@ -0,0 +1,180 @@ +"""UnitDbl module.""" + +import functools +import operator + +from matplotlib import _api + + +class UnitDbl: + """Class UnitDbl in development.""" + + # Unit conversion table. Small subset of the full one but enough + # to test the required functions. First field is a scale factor to + # convert the input units to the units of the second field. Only + # units in this table are allowed. + allowed = { + "m": (0.001, "km"), + "km": (1, "km"), + "mile": (1.609344, "km"), + + "rad": (1, "rad"), + "deg": (1.745329251994330e-02, "rad"), + + "sec": (1, "sec"), + "min": (60.0, "sec"), + "hour": (3600, "sec"), + } + + _types = { + "km": "distance", + "rad": "angle", + "sec": "time", + } + + def __init__(self, value, units): + """ + Create a new UnitDbl object. + + Units are internally converted to km, rad, and sec. The only + valid inputs for units are [m, km, mile, rad, deg, sec, min, hour]. + + The field UnitDbl.value will contain the converted value. Use + the convert() method to get a specific type of units back. + + = ERROR CONDITIONS + - If the input units are not in the allowed list, an error is thrown. + + = INPUT VARIABLES + - value The numeric value of the UnitDbl. + - units The string name of the units the value is in. + """ + data = _api.check_getitem(self.allowed, units=units) + self._value = float(value * data[0]) + self._units = data[1] + + def convert(self, units): + """ + Convert the UnitDbl to a specific set of units. + + = ERROR CONDITIONS + - If the input units are not in the allowed list, an error is thrown. + + = INPUT VARIABLES + - units The string name of the units to convert to. + + = RETURN VALUE + - Returns the value of the UnitDbl in the requested units as a floating + point number. + """ + if self._units == units: + return self._value + data = _api.check_getitem(self.allowed, units=units) + if self._units != data[1]: + raise ValueError(f"Error trying to convert to different units.\n" + f" Invalid conversion requested.\n" + f" UnitDbl: {self}\n" + f" Units: {units}\n") + return self._value / data[0] + + def __abs__(self): + """Return the absolute value of this UnitDbl.""" + return UnitDbl(abs(self._value), self._units) + + def __neg__(self): + """Return the negative value of this UnitDbl.""" + return UnitDbl(-self._value, self._units) + + def __bool__(self): + """Return the truth value of a UnitDbl.""" + return bool(self._value) + + def _cmp(self, op, rhs): + """Check that *self* and *rhs* share units; compare them using *op*.""" + self.checkSameUnits(rhs, "compare") + return op(self._value, rhs._value) + + __eq__ = functools.partialmethod(_cmp, operator.eq) + __ne__ = functools.partialmethod(_cmp, operator.ne) + __lt__ = functools.partialmethod(_cmp, operator.lt) + __le__ = functools.partialmethod(_cmp, operator.le) + __gt__ = functools.partialmethod(_cmp, operator.gt) + __ge__ = functools.partialmethod(_cmp, operator.ge) + + def _binop_unit_unit(self, op, rhs): + """Check that *self* and *rhs* share units; combine them using *op*.""" + self.checkSameUnits(rhs, op.__name__) + return UnitDbl(op(self._value, rhs._value), self._units) + + __add__ = functools.partialmethod(_binop_unit_unit, operator.add) + __sub__ = functools.partialmethod(_binop_unit_unit, operator.sub) + + def _binop_unit_scalar(self, op, scalar): + """Combine *self* and *scalar* using *op*.""" + return UnitDbl(op(self._value, scalar), self._units) + + __mul__ = functools.partialmethod(_binop_unit_scalar, operator.mul) + __rmul__ = functools.partialmethod(_binop_unit_scalar, operator.mul) + + def __str__(self): + """Print the UnitDbl.""" + return f"{self._value:g} *{self._units}" + + def __repr__(self): + """Print the UnitDbl.""" + return f"UnitDbl({self._value:g}, '{self._units}')" + + def type(self): + """Return the type of UnitDbl data.""" + return self._types[self._units] + + @staticmethod + def range(start, stop, step=None): + """ + Generate a range of UnitDbl objects. + + Similar to the Python range() method. Returns the range [ + start, stop) at the requested step. Each element will be a + UnitDbl object. + + = INPUT VARIABLES + - start The starting value of the range. + - stop The stop value of the range. + - step Optional step to use. If set to None, then a UnitDbl of + value 1 w/ the units of the start is used. + + = RETURN VALUE + - Returns a list containing the requested UnitDbl values. + """ + if step is None: + step = UnitDbl(1, start._units) + + elems = [] + + i = 0 + while True: + d = start + i * step + if d >= stop: + break + + elems.append(d) + i += 1 + + return elems + + def checkSameUnits(self, rhs, func): + """ + Check to see if units are the same. + + = ERROR CONDITIONS + - If the units of the rhs UnitDbl are not the same as our units, + an error is thrown. + + = INPUT VARIABLES + - rhs The UnitDbl to check for the same units + - func The name of the function doing the check. + """ + if self._units != rhs._units: + raise ValueError(f"Cannot {func} units of different types.\n" + f"LHS: {self._units}\n" + f"RHS: {rhs._units}") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDblConverter.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDblConverter.py new file mode 100644 index 0000000000000000000000000000000000000000..23065379f58193ae2f240d7bff44aaf70f8a8dca --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDblConverter.py @@ -0,0 +1,85 @@ +"""UnitDblConverter module containing class UnitDblConverter.""" + +import numpy as np + +from matplotlib import cbook, units +import matplotlib.projections.polar as polar + +__all__ = ['UnitDblConverter'] + + +# A special function for use with the matplotlib FuncFormatter class +# for formatting axes with radian units. +# This was copied from matplotlib example code. +def rad_fn(x, pos=None): + """Radian function formatter.""" + n = int((x / np.pi) * 2.0 + 0.25) + if n == 0: + return str(x) + elif n == 1: + return r'$\pi/2$' + elif n == 2: + return r'$\pi$' + elif n % 2 == 0: + return fr'${n//2}\pi$' + else: + return fr'${n}\pi/2$' + + +class UnitDblConverter(units.ConversionInterface): + """ + Provides Matplotlib conversion functionality for the Monte UnitDbl class. + """ + # default for plotting + defaults = { + "distance": 'km', + "angle": 'deg', + "time": 'sec', + } + + @staticmethod + def axisinfo(unit, axis): + # docstring inherited + + # Delay-load due to circular dependencies. + import matplotlib.testing.jpl_units as U + + # Check to see if the value used for units is a string unit value + # or an actual instance of a UnitDbl so that we can use the unit + # value for the default axis label value. + if unit: + label = unit if isinstance(unit, str) else unit.label() + else: + label = None + + if label == "deg" and isinstance(axis.axes, polar.PolarAxes): + # If we want degrees for a polar plot, use the PolarPlotFormatter + majfmt = polar.PolarAxes.ThetaFormatter() + else: + majfmt = U.UnitDblFormatter(useOffset=False) + + return units.AxisInfo(majfmt=majfmt, label=label) + + @staticmethod + def convert(value, unit, axis): + # docstring inherited + if not cbook.is_scalar_or_string(value): + return [UnitDblConverter.convert(x, unit, axis) for x in value] + # If no units were specified, then get the default units to use. + if unit is None: + unit = UnitDblConverter.default_units(value, axis) + # Convert the incoming UnitDbl value/values to float/floats + if isinstance(axis.axes, polar.PolarAxes) and value.type() == "angle": + # Guarantee that units are radians for polar plots. + return value.convert("rad") + return value.convert(unit) + + @staticmethod + def default_units(value, axis): + # docstring inherited + # Determine the default units based on the user preferences set for + # default units when printing a UnitDbl. + if cbook.is_scalar_or_string(value): + return UnitDblConverter.defaults[value.type()] + else: + return UnitDblConverter.default_units(value[0], axis) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDblFormatter.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDblFormatter.py new file mode 100644 index 0000000000000000000000000000000000000000..30a9914015bc7eb955c88e562a771591b82ad2e8 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/UnitDblFormatter.py @@ -0,0 +1,28 @@ +"""UnitDblFormatter module containing class UnitDblFormatter.""" + +import matplotlib.ticker as ticker + +__all__ = ['UnitDblFormatter'] + + +class UnitDblFormatter(ticker.ScalarFormatter): + """ + The formatter for UnitDbl data types. + + This allows for formatting with the unit string. + """ + + def __call__(self, x, pos=None): + # docstring inherited + if len(self.locs) == 0: + return '' + else: + return f'{x:.12}' + + def format_data_short(self, value): + # docstring inherited + return f'{value:.12}' + + def format_data(self, value): + # docstring inherited + return f'{value:.12}' diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__init__.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8caa9a8957a250b78712c25175bec415507e416 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__init__.py @@ -0,0 +1,76 @@ +""" +A sample set of units for use with testing unit conversion +of Matplotlib routines. These are used because they use very strict +enforcement of unitized data which will test the entire spectrum of how +unitized data might be used (it is not always meaningful to convert to +a float without specific units given). + +UnitDbl is essentially a unitized floating point number. It has a +minimal set of supported units (enough for testing purposes). All +of the mathematical operation are provided to fully test any behaviour +that might occur with unitized data. Remember that unitized data has +rules as to how it can be applied to one another (a value of distance +cannot be added to a value of time). Thus we need to guard against any +accidental "default" conversion that will strip away the meaning of the +data and render it neutered. + +Epoch is different than a UnitDbl of time. Time is something that can be +measured where an Epoch is a specific moment in time. Epochs are typically +referenced as an offset from some predetermined epoch. + +A difference of two epochs is a Duration. The distinction between a Duration +and a UnitDbl of time is made because an Epoch can have different frames (or +units). In the case of our test Epoch class the two allowed frames are 'UTC' +and 'ET' (Note that these are rough estimates provided for testing purposes +and should not be used in production code where accuracy of time frames is +desired). As such a Duration also has a frame of reference and therefore needs +to be called out as different that a simple measurement of time since a delta-t +in one frame may not be the same in another. +""" + +from .Duration import Duration +from .Epoch import Epoch +from .UnitDbl import UnitDbl + +from .StrConverter import StrConverter +from .EpochConverter import EpochConverter +from .UnitDblConverter import UnitDblConverter + +from .UnitDblFormatter import UnitDblFormatter + + +__version__ = "1.0" + +__all__ = [ + 'register', + 'Duration', + 'Epoch', + 'UnitDbl', + 'UnitDblFormatter', + ] + + +def register(): + """Register the unit conversion classes with matplotlib.""" + import matplotlib.units as mplU + + mplU.registry[str] = StrConverter() + mplU.registry[Epoch] = EpochConverter() + mplU.registry[Duration] = EpochConverter() + mplU.registry[UnitDbl] = UnitDblConverter() + + +# Some default unit instances +# Distances +m = UnitDbl(1.0, "m") +km = UnitDbl(1.0, "km") +mile = UnitDbl(1.0, "mile") +# Angles +deg = UnitDbl(1.0, "deg") +rad = UnitDbl(1.0, "rad") +# Time +sec = UnitDbl(1.0, "sec") +min = UnitDbl(1.0, "min") +hr = UnitDbl(1.0, "hour") +day = UnitDbl(24.0, "hour") +sec = UnitDbl(1.0, "sec") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/Epoch.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/Epoch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..844d01ce6ed5fdba30389c410ab2cecfe25da642 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/Epoch.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/EpochConverter.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/EpochConverter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c46fa957e495c8f1014344a3250cd52d801c763 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/EpochConverter.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/StrConverter.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/StrConverter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a18d3026618088d49d662081b149e034b9ec4d5 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/StrConverter.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/UnitDblConverter.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/UnitDblConverter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b59bb5a587b71b2606947ccc84295be05df76fe Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/UnitDblConverter.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/UnitDblFormatter.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/UnitDblFormatter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b94e566d481332826c85b63cb38765dd9de3f726 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/UnitDblFormatter.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/widgets.py b/llava_next/lib/python3.10/site-packages/matplotlib/testing/widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..748cdaccc7e9fdd5296a37ad85fdb9fa83466fc4 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/widgets.py @@ -0,0 +1,119 @@ +""" +======================== +Widget testing utilities +======================== + +See also :mod:`matplotlib.tests.test_widgets`. +""" + +from unittest import mock + +import matplotlib.pyplot as plt + + +def get_ax(): + """Create a plot and return its Axes.""" + fig, ax = plt.subplots(1, 1) + ax.plot([0, 200], [0, 200]) + ax.set_aspect(1.0) + ax.figure.canvas.draw() + return ax + + +def noop(*args, **kwargs): + pass + + +def mock_event(ax, button=1, xdata=0, ydata=0, key=None, step=1): + r""" + Create a mock event that can stand in for `.Event` and its subclasses. + + This event is intended to be used in tests where it can be passed into + event handling functions. + + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The Axes the event will be in. + xdata : float + x coord of mouse in data coords. + ydata : float + y coord of mouse in data coords. + button : None or `MouseButton` or {'up', 'down'} + The mouse button pressed in this event (see also `.MouseEvent`). + key : None or str + The key pressed when the mouse event triggered (see also `.KeyEvent`). + step : int + Number of scroll steps (positive for 'up', negative for 'down'). + + Returns + ------- + event + A `.Event`\-like Mock instance. + """ + event = mock.Mock() + event.button = button + event.x, event.y = ax.transData.transform([(xdata, ydata), + (xdata, ydata)])[0] + event.xdata, event.ydata = xdata, ydata + event.inaxes = ax + event.canvas = ax.figure.canvas + event.key = key + event.step = step + event.guiEvent = None + event.name = 'Custom' + return event + + +def do_event(tool, etype, button=1, xdata=0, ydata=0, key=None, step=1): + """ + Trigger an event on the given tool. + + Parameters + ---------- + tool : matplotlib.widgets.AxesWidget + etype : str + The event to trigger. + xdata : float + x coord of mouse in data coords. + ydata : float + y coord of mouse in data coords. + button : None or `MouseButton` or {'up', 'down'} + The mouse button pressed in this event (see also `.MouseEvent`). + key : None or str + The key pressed when the mouse event triggered (see also `.KeyEvent`). + step : int + Number of scroll steps (positive for 'up', negative for 'down'). + """ + event = mock_event(tool.ax, button, xdata, ydata, key, step) + func = getattr(tool, etype) + func(event) + + +def click_and_drag(tool, start, end, key=None): + """ + Helper to simulate a mouse drag operation. + + Parameters + ---------- + tool : `~matplotlib.widgets.Widget` + start : [float, float] + Starting point in data coordinates. + end : [float, float] + End point in data coordinates. + key : None or str + An optional key that is pressed during the whole operation + (see also `.KeyEvent`). + """ + if key is not None: + # Press key + do_event(tool, 'on_key_press', xdata=start[0], ydata=start[1], + button=1, key=key) + # Click, move, and release mouse + do_event(tool, 'press', xdata=start[0], ydata=start[1], button=1) + do_event(tool, 'onmove', xdata=end[0], ydata=end[1], button=1) + do_event(tool, 'release', xdata=end[0], ydata=end[1], button=1) + if key is not None: + # Release key + do_event(tool, 'on_key_release', xdata=end[0], ydata=end[1], + button=1, key=key) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/testing/widgets.pyi b/llava_next/lib/python3.10/site-packages/matplotlib/testing/widgets.pyi new file mode 100644 index 0000000000000000000000000000000000000000..858ff457158283bae9db974e05098890ef5ac260 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/testing/widgets.pyi @@ -0,0 +1,31 @@ +from typing import Any, Literal + +from matplotlib.axes import Axes +from matplotlib.backend_bases import Event, MouseButton +from matplotlib.widgets import AxesWidget, Widget + +def get_ax() -> Axes: ... +def noop(*args: Any, **kwargs: Any) -> None: ... +def mock_event( + ax: Axes, + button: MouseButton | int | Literal["up", "down"] | None = ..., + xdata: float = ..., + ydata: float = ..., + key: str | None = ..., + step: int = ..., +) -> Event: ... +def do_event( + tool: AxesWidget, + etype: str, + button: MouseButton | int | Literal["up", "down"] | None = ..., + xdata: float = ..., + ydata: float = ..., + key: str | None = ..., + step: int = ..., +) -> None: ... +def click_and_drag( + tool: Widget, + start: tuple[float, float], + end: tuple[float, float], + key: str | None = ..., +) -> None: ... diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/textpath.py b/llava_next/lib/python3.10/site-packages/matplotlib/textpath.py new file mode 100644 index 0000000000000000000000000000000000000000..c00966d6e6c36d6bbea0770c44535a1b94df6234 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/textpath.py @@ -0,0 +1,397 @@ +from collections import OrderedDict +import logging +import urllib.parse + +import numpy as np + +from matplotlib import _text_helpers, dviread +from matplotlib.font_manager import ( + FontProperties, get_font, fontManager as _fontManager +) +from matplotlib.ft2font import LOAD_NO_HINTING, LOAD_TARGET_LIGHT +from matplotlib.mathtext import MathTextParser +from matplotlib.path import Path +from matplotlib.texmanager import TexManager +from matplotlib.transforms import Affine2D + +_log = logging.getLogger(__name__) + + +class TextToPath: + """A class that converts strings to paths.""" + + FONT_SCALE = 100. + DPI = 72 + + def __init__(self): + self.mathtext_parser = MathTextParser('path') + self._texmanager = None + + def _get_font(self, prop): + """ + Find the `FT2Font` matching font properties *prop*, with its size set. + """ + filenames = _fontManager._find_fonts_by_props(prop) + font = get_font(filenames) + font.set_size(self.FONT_SCALE, self.DPI) + return font + + def _get_hinting_flag(self): + return LOAD_NO_HINTING + + def _get_char_id(self, font, ccode): + """ + Return a unique id for the given font and character-code set. + """ + return urllib.parse.quote(f"{font.postscript_name}-{ccode:x}") + + def get_text_width_height_descent(self, s, prop, ismath): + fontsize = prop.get_size_in_points() + + if ismath == "TeX": + return TexManager().get_text_width_height_descent(s, fontsize) + + scale = fontsize / self.FONT_SCALE + + if ismath: + prop = prop.copy() + prop.set_size(self.FONT_SCALE) + width, height, descent, *_ = \ + self.mathtext_parser.parse(s, 72, prop) + return width * scale, height * scale, descent * scale + + font = self._get_font(prop) + font.set_text(s, 0.0, flags=LOAD_NO_HINTING) + w, h = font.get_width_height() + w /= 64.0 # convert from subpixels + h /= 64.0 + d = font.get_descent() + d /= 64.0 + return w * scale, h * scale, d * scale + + def get_text_path(self, prop, s, ismath=False): + """ + Convert text *s* to path (a tuple of vertices and codes for + matplotlib.path.Path). + + Parameters + ---------- + prop : `~matplotlib.font_manager.FontProperties` + The font properties for the text. + s : str + The text to be converted. + ismath : {False, True, "TeX"} + If True, use mathtext parser. If "TeX", use tex for rendering. + + Returns + ------- + verts : list + A list of arrays containing the (x, y) coordinates of the vertices. + codes : list + A list of path codes. + + Examples + -------- + Create a list of vertices and codes from a text, and create a `.Path` + from those:: + + from matplotlib.path import Path + from matplotlib.text import TextToPath + from matplotlib.font_manager import FontProperties + + fp = FontProperties(family="Comic Neue", style="italic") + verts, codes = TextToPath().get_text_path(fp, "ABC") + path = Path(verts, codes, closed=False) + + Also see `TextPath` for a more direct way to create a path from a text. + """ + if ismath == "TeX": + glyph_info, glyph_map, rects = self.get_glyphs_tex(prop, s) + elif not ismath: + font = self._get_font(prop) + glyph_info, glyph_map, rects = self.get_glyphs_with_font(font, s) + else: + glyph_info, glyph_map, rects = self.get_glyphs_mathtext(prop, s) + + verts, codes = [], [] + for glyph_id, xposition, yposition, scale in glyph_info: + verts1, codes1 = glyph_map[glyph_id] + verts.extend(verts1 * scale + [xposition, yposition]) + codes.extend(codes1) + for verts1, codes1 in rects: + verts.extend(verts1) + codes.extend(codes1) + + # Make sure an empty string or one with nothing to print + # (e.g. only spaces & newlines) will be valid/empty path + if not verts: + verts = np.empty((0, 2)) + + return verts, codes + + def get_glyphs_with_font(self, font, s, glyph_map=None, + return_new_glyphs_only=False): + """ + Convert string *s* to vertices and codes using the provided ttf font. + """ + + if glyph_map is None: + glyph_map = OrderedDict() + + if return_new_glyphs_only: + glyph_map_new = OrderedDict() + else: + glyph_map_new = glyph_map + + xpositions = [] + glyph_ids = [] + for item in _text_helpers.layout(s, font): + char_id = self._get_char_id(item.ft_object, ord(item.char)) + glyph_ids.append(char_id) + xpositions.append(item.x) + if char_id not in glyph_map: + glyph_map_new[char_id] = item.ft_object.get_path() + + ypositions = [0] * len(xpositions) + sizes = [1.] * len(xpositions) + + rects = [] + + return (list(zip(glyph_ids, xpositions, ypositions, sizes)), + glyph_map_new, rects) + + def get_glyphs_mathtext(self, prop, s, glyph_map=None, + return_new_glyphs_only=False): + """ + Parse mathtext string *s* and convert it to a (vertices, codes) pair. + """ + + prop = prop.copy() + prop.set_size(self.FONT_SCALE) + + width, height, descent, glyphs, rects = self.mathtext_parser.parse( + s, self.DPI, prop) + + if not glyph_map: + glyph_map = OrderedDict() + + if return_new_glyphs_only: + glyph_map_new = OrderedDict() + else: + glyph_map_new = glyph_map + + xpositions = [] + ypositions = [] + glyph_ids = [] + sizes = [] + + for font, fontsize, ccode, ox, oy in glyphs: + char_id = self._get_char_id(font, ccode) + if char_id not in glyph_map: + font.clear() + font.set_size(self.FONT_SCALE, self.DPI) + font.load_char(ccode, flags=LOAD_NO_HINTING) + glyph_map_new[char_id] = font.get_path() + + xpositions.append(ox) + ypositions.append(oy) + glyph_ids.append(char_id) + size = fontsize / self.FONT_SCALE + sizes.append(size) + + myrects = [] + for ox, oy, w, h in rects: + vert1 = [(ox, oy), (ox, oy + h), (ox + w, oy + h), + (ox + w, oy), (ox, oy), (0, 0)] + code1 = [Path.MOVETO, + Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + myrects.append((vert1, code1)) + + return (list(zip(glyph_ids, xpositions, ypositions, sizes)), + glyph_map_new, myrects) + + def get_glyphs_tex(self, prop, s, glyph_map=None, + return_new_glyphs_only=False): + """Convert the string *s* to vertices and codes using usetex mode.""" + # Mostly borrowed from pdf backend. + + dvifile = TexManager().make_dvi(s, self.FONT_SCALE) + with dviread.Dvi(dvifile, self.DPI) as dvi: + page, = dvi + + if glyph_map is None: + glyph_map = OrderedDict() + + if return_new_glyphs_only: + glyph_map_new = OrderedDict() + else: + glyph_map_new = glyph_map + + glyph_ids, xpositions, ypositions, sizes = [], [], [], [] + + # Gather font information and do some setup for combining + # characters into strings. + for text in page.text: + font = get_font(text.font_path) + char_id = self._get_char_id(font, text.glyph) + if char_id not in glyph_map: + font.clear() + font.set_size(self.FONT_SCALE, self.DPI) + glyph_name_or_index = text.glyph_name_or_index + if isinstance(glyph_name_or_index, str): + index = font.get_name_index(glyph_name_or_index) + font.load_glyph(index, flags=LOAD_TARGET_LIGHT) + elif isinstance(glyph_name_or_index, int): + self._select_native_charmap(font) + font.load_char( + glyph_name_or_index, flags=LOAD_TARGET_LIGHT) + else: # Should not occur. + raise TypeError(f"Glyph spec of unexpected type: " + f"{glyph_name_or_index!r}") + glyph_map_new[char_id] = font.get_path() + + glyph_ids.append(char_id) + xpositions.append(text.x) + ypositions.append(text.y) + sizes.append(text.font_size / self.FONT_SCALE) + + myrects = [] + + for ox, oy, h, w in page.boxes: + vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h), + (ox, oy + h), (ox, oy), (0, 0)] + code1 = [Path.MOVETO, + Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + myrects.append((vert1, code1)) + + return (list(zip(glyph_ids, xpositions, ypositions, sizes)), + glyph_map_new, myrects) + + @staticmethod + def _select_native_charmap(font): + # Select the native charmap. (we can't directly identify it but it's + # typically an Adobe charmap). + for charmap_code in [ + 1094992451, # ADOBE_CUSTOM. + 1094995778, # ADOBE_STANDARD. + ]: + try: + font.select_charmap(charmap_code) + except (ValueError, RuntimeError): + pass + else: + break + else: + _log.warning("No supported encoding in font (%s).", font.fname) + + +text_to_path = TextToPath() + + +class TextPath(Path): + """ + Create a path from the text. + """ + + def __init__(self, xy, s, size=None, prop=None, + _interpolation_steps=1, usetex=False): + r""" + Create a path from the text. Note that it simply is a path, + not an artist. You need to use the `.PathPatch` (or other artists) + to draw this path onto the canvas. + + Parameters + ---------- + xy : tuple or array of two float values + Position of the text. For no offset, use ``xy=(0, 0)``. + + s : str + The text to convert to a path. + + size : float, optional + Font size in points. Defaults to the size specified via the font + properties *prop*. + + prop : `~matplotlib.font_manager.FontProperties`, optional + Font property. If not provided, will use a default + `.FontProperties` with parameters from the + :ref:`rcParams`. + + _interpolation_steps : int, optional + (Currently ignored) + + usetex : bool, default: False + Whether to use tex rendering. + + Examples + -------- + The following creates a path from the string "ABC" with Helvetica + font face; and another path from the latex fraction 1/2:: + + from matplotlib.text import TextPath + from matplotlib.font_manager import FontProperties + + fp = FontProperties(family="Helvetica", style="italic") + path1 = TextPath((12, 12), "ABC", size=12, prop=fp) + path2 = TextPath((0, 0), r"$\frac{1}{2}$", size=12, usetex=True) + + Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`. + """ + # Circular import. + from matplotlib.text import Text + + prop = FontProperties._from_any(prop) + if size is None: + size = prop.get_size_in_points() + + self._xy = xy + self.set_size(size) + + self._cached_vertices = None + s, ismath = Text(usetex=usetex)._preprocess_math(s) + super().__init__( + *text_to_path.get_text_path(prop, s, ismath=ismath), + _interpolation_steps=_interpolation_steps, + readonly=True) + self._should_simplify = False + + def set_size(self, size): + """Set the text size.""" + self._size = size + self._invalid = True + + def get_size(self): + """Get the text size.""" + return self._size + + @property + def vertices(self): + """ + Return the cached path after updating it if necessary. + """ + self._revalidate_path() + return self._cached_vertices + + @property + def codes(self): + """ + Return the codes + """ + return self._codes + + def _revalidate_path(self): + """ + Update the path if necessary. + + The path for the text is initially create with the font size of + `.FONT_SCALE`, and this path is rescaled to other size when necessary. + """ + if self._invalid or self._cached_vertices is None: + tr = (Affine2D() + .scale(self._size / text_to_path.FONT_SCALE) + .translate(*self._xy)) + self._cached_vertices = tr.transform(self._vertices) + self._cached_vertices.flags.writeable = False + self._invalid = False diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/ticker.py b/llava_next/lib/python3.10/site-packages/matplotlib/ticker.py new file mode 100644 index 0000000000000000000000000000000000000000..2b00937f9e2957ac04e7cae3b6ad274d7d0518bb --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/ticker.py @@ -0,0 +1,2938 @@ +""" +Tick locating and formatting +============================ + +This module contains classes for configuring tick locating and formatting. +Generic tick locators and formatters are provided, as well as domain specific +custom ones. + +Although the locators know nothing about major or minor ticks, they are used +by the Axis class to support major and minor tick locating and formatting. + +.. _tick_locating: +.. _locators: + +Tick locating +------------- + +The Locator class is the base class for all tick locators. The locators +handle autoscaling of the view limits based on the data limits, and the +choosing of tick locations. A useful semi-automatic tick locator is +`MultipleLocator`. It is initialized with a base, e.g., 10, and it picks +axis limits and ticks that are multiples of that base. + +The Locator subclasses defined here are: + +======================= ======================================================= +`AutoLocator` `MaxNLocator` with simple defaults. This is the default + tick locator for most plotting. +`MaxNLocator` Finds up to a max number of intervals with ticks at + nice locations. +`LinearLocator` Space ticks evenly from min to max. +`LogLocator` Space ticks logarithmically from min to max. +`MultipleLocator` Ticks and range are a multiple of base; either integer + or float. +`FixedLocator` Tick locations are fixed. +`IndexLocator` Locator for index plots (e.g., where + ``x = range(len(y))``). +`NullLocator` No ticks. +`SymmetricalLogLocator` Locator for use with the symlog norm; works like + `LogLocator` for the part outside of the threshold and + adds 0 if inside the limits. +`AsinhLocator` Locator for use with the asinh norm, attempting to + space ticks approximately uniformly. +`LogitLocator` Locator for logit scaling. +`AutoMinorLocator` Locator for minor ticks when the axis is linear and the + major ticks are uniformly spaced. Subdivides the major + tick interval into a specified number of minor + intervals, defaulting to 4 or 5 depending on the major + interval. +======================= ======================================================= + +There are a number of locators specialized for date locations - see +the :mod:`.dates` module. + +You can define your own locator by deriving from Locator. You must +override the ``__call__`` method, which returns a sequence of locations, +and you will probably want to override the autoscale method to set the +view limits from the data limits. + +If you want to override the default locator, use one of the above or a custom +locator and pass it to the x- or y-axis instance. The relevant methods are:: + + ax.xaxis.set_major_locator(xmajor_locator) + ax.xaxis.set_minor_locator(xminor_locator) + ax.yaxis.set_major_locator(ymajor_locator) + ax.yaxis.set_minor_locator(yminor_locator) + +The default minor locator is `NullLocator`, i.e., no minor ticks on by default. + +.. note:: + `Locator` instances should not be used with more than one + `~matplotlib.axis.Axis` or `~matplotlib.axes.Axes`. So instead of:: + + locator = MultipleLocator(5) + ax.xaxis.set_major_locator(locator) + ax2.xaxis.set_major_locator(locator) + + do the following instead:: + + ax.xaxis.set_major_locator(MultipleLocator(5)) + ax2.xaxis.set_major_locator(MultipleLocator(5)) + +.. _formatters: + +Tick formatting +--------------- + +Tick formatting is controlled by classes derived from Formatter. The formatter +operates on a single tick value and returns a string to the axis. + +========================= ===================================================== +`NullFormatter` No labels on the ticks. +`FixedFormatter` Set the strings manually for the labels. +`FuncFormatter` User defined function sets the labels. +`StrMethodFormatter` Use string `format` method. +`FormatStrFormatter` Use an old-style sprintf format string. +`ScalarFormatter` Default formatter for scalars: autopick the format + string. +`LogFormatter` Formatter for log axes. +`LogFormatterExponent` Format values for log axis using + ``exponent = log_base(value)``. +`LogFormatterMathtext` Format values for log axis using + ``exponent = log_base(value)`` using Math text. +`LogFormatterSciNotation` Format values for log axis using scientific notation. +`LogitFormatter` Probability formatter. +`EngFormatter` Format labels in engineering notation. +`PercentFormatter` Format labels as a percentage. +========================= ===================================================== + +You can derive your own formatter from the Formatter base class by +simply overriding the ``__call__`` method. The formatter class has +access to the axis view and data limits. + +To control the major and minor tick label formats, use one of the +following methods:: + + ax.xaxis.set_major_formatter(xmajor_formatter) + ax.xaxis.set_minor_formatter(xminor_formatter) + ax.yaxis.set_major_formatter(ymajor_formatter) + ax.yaxis.set_minor_formatter(yminor_formatter) + +In addition to a `.Formatter` instance, `~.Axis.set_major_formatter` and +`~.Axis.set_minor_formatter` also accept a ``str`` or function. ``str`` input +will be internally replaced with an autogenerated `.StrMethodFormatter` with +the input ``str``. For function input, a `.FuncFormatter` with the input +function will be generated and used. + +See :doc:`/gallery/ticks/major_minor_demo` for an example of setting major +and minor ticks. See the :mod:`matplotlib.dates` module for more information +and examples of using date locators and formatters. +""" + +import itertools +import logging +import locale +import math +from numbers import Integral +import string + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +from matplotlib import transforms as mtransforms + +_log = logging.getLogger(__name__) + +__all__ = ('TickHelper', 'Formatter', 'FixedFormatter', + 'NullFormatter', 'FuncFormatter', 'FormatStrFormatter', + 'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter', + 'LogFormatterExponent', 'LogFormatterMathtext', + 'LogFormatterSciNotation', + 'LogitFormatter', 'EngFormatter', 'PercentFormatter', + 'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator', + 'LinearLocator', 'LogLocator', 'AutoLocator', + 'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator', + 'SymmetricalLogLocator', 'AsinhLocator', 'LogitLocator') + + +class _DummyAxis: + __name__ = "dummy" + + def __init__(self, minpos=0): + self._data_interval = (0, 1) + self._view_interval = (0, 1) + self._minpos = minpos + + def get_view_interval(self): + return self._view_interval + + def set_view_interval(self, vmin, vmax): + self._view_interval = (vmin, vmax) + + def get_minpos(self): + return self._minpos + + def get_data_interval(self): + return self._data_interval + + def set_data_interval(self, vmin, vmax): + self._data_interval = (vmin, vmax) + + def get_tick_space(self): + # Just use the long-standing default of nbins==9 + return 9 + + +class TickHelper: + axis = None + + def set_axis(self, axis): + self.axis = axis + + def create_dummy_axis(self, **kwargs): + if self.axis is None: + self.axis = _DummyAxis(**kwargs) + + +class Formatter(TickHelper): + """ + Create a string based on a tick value and location. + """ + # some classes want to see all the locs to help format + # individual ones + locs = [] + + def __call__(self, x, pos=None): + """ + Return the format for tick value *x* at position pos. + ``pos=None`` indicates an unspecified location. + """ + raise NotImplementedError('Derived must override') + + def format_ticks(self, values): + """Return the tick labels for all the ticks at once.""" + self.set_locs(values) + return [self(value, i) for i, value in enumerate(values)] + + def format_data(self, value): + """ + Return the full string representation of the value with the + position unspecified. + """ + return self.__call__(value) + + def format_data_short(self, value): + """ + Return a short string version of the tick value. + + Defaults to the position-independent long value. + """ + return self.format_data(value) + + def get_offset(self): + return '' + + def set_locs(self, locs): + """ + Set the locations of the ticks. + + This method is called before computing the tick labels because some + formatters need to know all tick locations to do so. + """ + self.locs = locs + + @staticmethod + def fix_minus(s): + """ + Some classes may want to replace a hyphen for minus with the proper + Unicode symbol (U+2212) for typographical correctness. This is a + helper method to perform such a replacement when it is enabled via + :rc:`axes.unicode_minus`. + """ + return (s.replace('-', '\N{MINUS SIGN}') + if mpl.rcParams['axes.unicode_minus'] + else s) + + def _set_locator(self, locator): + """Subclasses may want to override this to set a locator.""" + pass + + +class NullFormatter(Formatter): + """Always return the empty string.""" + + def __call__(self, x, pos=None): + # docstring inherited + return '' + + +class FixedFormatter(Formatter): + """ + Return fixed strings for tick labels based only on position, not value. + + .. note:: + `.FixedFormatter` should only be used together with `.FixedLocator`. + Otherwise, the labels may end up in unexpected positions. + """ + + def __init__(self, seq): + """Set the sequence *seq* of strings that will be used for labels.""" + self.seq = seq + self.offset_string = '' + + def __call__(self, x, pos=None): + """ + Return the label that matches the position, regardless of the value. + + For positions ``pos < len(seq)``, return ``seq[i]`` regardless of + *x*. Otherwise return empty string. ``seq`` is the sequence of + strings that this object was initialized with. + """ + if pos is None or pos >= len(self.seq): + return '' + else: + return self.seq[pos] + + def get_offset(self): + return self.offset_string + + def set_offset_string(self, ofs): + self.offset_string = ofs + + +class FuncFormatter(Formatter): + """ + Use a user-defined function for formatting. + + The function should take in two inputs (a tick value ``x`` and a + position ``pos``), and return a string containing the corresponding + tick label. + """ + + def __init__(self, func): + self.func = func + self.offset_string = "" + + def __call__(self, x, pos=None): + """ + Return the value of the user defined function. + + *x* and *pos* are passed through as-is. + """ + return self.func(x, pos) + + def get_offset(self): + return self.offset_string + + def set_offset_string(self, ofs): + self.offset_string = ofs + + +class FormatStrFormatter(Formatter): + """ + Use an old-style ('%' operator) format string to format the tick. + + The format string should have a single variable format (%) in it. + It will be applied to the value (not the position) of the tick. + + Negative numeric values (e.g., -1) will use a dash, not a Unicode minus; + use mathtext to get a Unicode minus by wrapping the format specifier with $ + (e.g. "$%g$"). + """ + + def __init__(self, fmt): + self.fmt = fmt + + def __call__(self, x, pos=None): + """ + Return the formatted label string. + + Only the value *x* is formatted. The position is ignored. + """ + return self.fmt % x + + +class _UnicodeMinusFormat(string.Formatter): + """ + A specialized string formatter so that `.StrMethodFormatter` respects + :rc:`axes.unicode_minus`. This implementation relies on the fact that the + format string is only ever called with kwargs *x* and *pos*, so it blindly + replaces dashes by unicode minuses without further checking. + """ + + def format_field(self, value, format_spec): + return Formatter.fix_minus(super().format_field(value, format_spec)) + + +class StrMethodFormatter(Formatter): + """ + Use a new-style format string (as used by `str.format`) to format the tick. + + The field used for the tick value must be labeled *x* and the field used + for the tick position must be labeled *pos*. + + The formatter will respect :rc:`axes.unicode_minus` when formatting + negative numeric values. + + It is typically unnecessary to explicitly construct `.StrMethodFormatter` + objects, as `~.Axis.set_major_formatter` directly accepts the format string + itself. + """ + + def __init__(self, fmt): + self.fmt = fmt + + def __call__(self, x, pos=None): + """ + Return the formatted label string. + + *x* and *pos* are passed to `str.format` as keyword arguments + with those exact names. + """ + return _UnicodeMinusFormat().format(self.fmt, x=x, pos=pos) + + +class ScalarFormatter(Formatter): + """ + Format tick values as a number. + + Parameters + ---------- + useOffset : bool or float, default: :rc:`axes.formatter.useoffset` + Whether to use offset notation. See `.set_useOffset`. + useMathText : bool, default: :rc:`axes.formatter.use_mathtext` + Whether to use fancy math formatting. See `.set_useMathText`. + useLocale : bool, default: :rc:`axes.formatter.use_locale`. + Whether to use locale settings for decimal sign and positive sign. + See `.set_useLocale`. + + Notes + ----- + In addition to the parameters above, the formatting of scientific vs. + floating point representation can be configured via `.set_scientific` + and `.set_powerlimits`). + + **Offset notation and scientific notation** + + Offset notation and scientific notation look quite similar at first sight. + Both split some information from the formatted tick values and display it + at the end of the axis. + + - The scientific notation splits up the order of magnitude, i.e. a + multiplicative scaling factor, e.g. ``1e6``. + + - The offset notation separates an additive constant, e.g. ``+1e6``. The + offset notation label is always prefixed with a ``+`` or ``-`` sign + and is thus distinguishable from the order of magnitude label. + + The following plot with x limits ``1_000_000`` to ``1_000_010`` illustrates + the different formatting. Note the labels at the right edge of the x axis. + + .. plot:: + + lim = (1_000_000, 1_000_010) + + fig, (ax1, ax2, ax3) = plt.subplots(3, 1, gridspec_kw={'hspace': 2}) + ax1.set(title='offset_notation', xlim=lim) + ax2.set(title='scientific notation', xlim=lim) + ax2.xaxis.get_major_formatter().set_useOffset(False) + ax3.set(title='floating point notation', xlim=lim) + ax3.xaxis.get_major_formatter().set_useOffset(False) + ax3.xaxis.get_major_formatter().set_scientific(False) + + """ + + def __init__(self, useOffset=None, useMathText=None, useLocale=None): + if useOffset is None: + useOffset = mpl.rcParams['axes.formatter.useoffset'] + self._offset_threshold = \ + mpl.rcParams['axes.formatter.offset_threshold'] + self.set_useOffset(useOffset) + self._usetex = mpl.rcParams['text.usetex'] + self.set_useMathText(useMathText) + self.orderOfMagnitude = 0 + self.format = '' + self._scientific = True + self._powerlimits = mpl.rcParams['axes.formatter.limits'] + self.set_useLocale(useLocale) + + def get_useOffset(self): + """ + Return whether automatic mode for offset notation is active. + + This returns True if ``set_useOffset(True)``; it returns False if an + explicit offset was set, e.g. ``set_useOffset(1000)``. + + See Also + -------- + ScalarFormatter.set_useOffset + """ + return self._useOffset + + def set_useOffset(self, val): + """ + Set whether to use offset notation. + + When formatting a set numbers whose value is large compared to their + range, the formatter can separate an additive constant. This can + shorten the formatted numbers so that they are less likely to overlap + when drawn on an axis. + + Parameters + ---------- + val : bool or float + - If False, do not use offset notation. + - If True (=automatic mode), use offset notation if it can make + the residual numbers significantly shorter. The exact behavior + is controlled by :rc:`axes.formatter.offset_threshold`. + - If a number, force an offset of the given value. + + Examples + -------- + With active offset notation, the values + + ``100_000, 100_002, 100_004, 100_006, 100_008`` + + will be formatted as ``0, 2, 4, 6, 8`` plus an offset ``+1e5``, which + is written to the edge of the axis. + """ + if val in [True, False]: + self.offset = 0 + self._useOffset = val + else: + self._useOffset = False + self.offset = val + + useOffset = property(fget=get_useOffset, fset=set_useOffset) + + def get_useLocale(self): + """ + Return whether locale settings are used for formatting. + + See Also + -------- + ScalarFormatter.set_useLocale + """ + return self._useLocale + + def set_useLocale(self, val): + """ + Set whether to use locale settings for decimal sign and positive sign. + + Parameters + ---------- + val : bool or None + *None* resets to :rc:`axes.formatter.use_locale`. + """ + if val is None: + self._useLocale = mpl.rcParams['axes.formatter.use_locale'] + else: + self._useLocale = val + + useLocale = property(fget=get_useLocale, fset=set_useLocale) + + def _format_maybe_minus_and_locale(self, fmt, arg): + """ + Format *arg* with *fmt*, applying Unicode minus and locale if desired. + """ + return self.fix_minus( + # Escape commas introduced by locale.format_string if using math text, + # but not those present from the beginning in fmt. + (",".join(locale.format_string(part, (arg,), True).replace(",", "{,}") + for part in fmt.split(",")) if self._useMathText + else locale.format_string(fmt, (arg,), True)) + if self._useLocale + else fmt % arg) + + def get_useMathText(self): + """ + Return whether to use fancy math formatting. + + See Also + -------- + ScalarFormatter.set_useMathText + """ + return self._useMathText + + def set_useMathText(self, val): + r""" + Set whether to use fancy math formatting. + + If active, scientific notation is formatted as :math:`1.2 \times 10^3`. + + Parameters + ---------- + val : bool or None + *None* resets to :rc:`axes.formatter.use_mathtext`. + """ + if val is None: + self._useMathText = mpl.rcParams['axes.formatter.use_mathtext'] + if self._useMathText is False: + try: + from matplotlib import font_manager + ufont = font_manager.findfont( + font_manager.FontProperties( + mpl.rcParams["font.family"] + ), + fallback_to_default=False, + ) + except ValueError: + ufont = None + + if ufont == str(cbook._get_data_path("fonts/ttf/cmr10.ttf")): + _api.warn_external( + "cmr10 font should ideally be used with " + "mathtext, set axes.formatter.use_mathtext to True" + ) + else: + self._useMathText = val + + useMathText = property(fget=get_useMathText, fset=set_useMathText) + + def __call__(self, x, pos=None): + """ + Return the format for tick value *x* at position *pos*. + """ + if len(self.locs) == 0: + return '' + else: + xp = (x - self.offset) / (10. ** self.orderOfMagnitude) + if abs(xp) < 1e-8: + xp = 0 + return self._format_maybe_minus_and_locale(self.format, xp) + + def set_scientific(self, b): + """ + Turn scientific notation on or off. + + See Also + -------- + ScalarFormatter.set_powerlimits + """ + self._scientific = bool(b) + + def set_powerlimits(self, lims): + r""" + Set size thresholds for scientific notation. + + Parameters + ---------- + lims : (int, int) + A tuple *(min_exp, max_exp)* containing the powers of 10 that + determine the switchover threshold. For a number representable as + :math:`a \times 10^\mathrm{exp}` with :math:`1 <= |a| < 10`, + scientific notation will be used if ``exp <= min_exp`` or + ``exp >= max_exp``. + + The default limits are controlled by :rc:`axes.formatter.limits`. + + In particular numbers with *exp* equal to the thresholds are + written in scientific notation. + + Typically, *min_exp* will be negative and *max_exp* will be + positive. + + For example, ``formatter.set_powerlimits((-3, 4))`` will provide + the following formatting: + :math:`1 \times 10^{-3}, 9.9 \times 10^{-3}, 0.01,` + :math:`9999, 1 \times 10^4`. + + See Also + -------- + ScalarFormatter.set_scientific + """ + if len(lims) != 2: + raise ValueError("'lims' must be a sequence of length 2") + self._powerlimits = lims + + def format_data_short(self, value): + # docstring inherited + if value is np.ma.masked: + return "" + if isinstance(value, Integral): + fmt = "%d" + else: + if getattr(self.axis, "__name__", "") in ["xaxis", "yaxis"]: + if self.axis.__name__ == "xaxis": + axis_trf = self.axis.axes.get_xaxis_transform() + axis_inv_trf = axis_trf.inverted() + screen_xy = axis_trf.transform((value, 0)) + neighbor_values = axis_inv_trf.transform( + screen_xy + [[-1, 0], [+1, 0]])[:, 0] + else: # yaxis: + axis_trf = self.axis.axes.get_yaxis_transform() + axis_inv_trf = axis_trf.inverted() + screen_xy = axis_trf.transform((0, value)) + neighbor_values = axis_inv_trf.transform( + screen_xy + [[0, -1], [0, +1]])[:, 1] + delta = abs(neighbor_values - value).max() + else: + # Rough approximation: no more than 1e4 divisions. + a, b = self.axis.get_view_interval() + delta = (b - a) / 1e4 + fmt = f"%-#.{cbook._g_sig_digits(value, delta)}g" + return self._format_maybe_minus_and_locale(fmt, value) + + def format_data(self, value): + # docstring inherited + e = math.floor(math.log10(abs(value))) + s = round(value / 10**e, 10) + significand = self._format_maybe_minus_and_locale( + "%d" if s % 1 == 0 else "%1.10g", s) + if e == 0: + return significand + exponent = self._format_maybe_minus_and_locale("%d", e) + if self._useMathText or self._usetex: + exponent = "10^{%s}" % exponent + return (exponent if s == 1 # reformat 1x10^y as 10^y + else rf"{significand} \times {exponent}") + else: + return f"{significand}e{exponent}" + + def get_offset(self): + """ + Return scientific notation, plus offset. + """ + if len(self.locs) == 0: + return '' + if self.orderOfMagnitude or self.offset: + offsetStr = '' + sciNotStr = '' + if self.offset: + offsetStr = self.format_data(self.offset) + if self.offset > 0: + offsetStr = '+' + offsetStr + if self.orderOfMagnitude: + if self._usetex or self._useMathText: + sciNotStr = self.format_data(10 ** self.orderOfMagnitude) + else: + sciNotStr = '1e%d' % self.orderOfMagnitude + if self._useMathText or self._usetex: + if sciNotStr != '': + sciNotStr = r'\times\mathdefault{%s}' % sciNotStr + s = fr'${sciNotStr}\mathdefault{{{offsetStr}}}$' + else: + s = ''.join((sciNotStr, offsetStr)) + return self.fix_minus(s) + return '' + + def set_locs(self, locs): + # docstring inherited + self.locs = locs + if len(self.locs) > 0: + if self._useOffset: + self._compute_offset() + self._set_order_of_magnitude() + self._set_format() + + def _compute_offset(self): + locs = self.locs + # Restrict to visible ticks. + vmin, vmax = sorted(self.axis.get_view_interval()) + locs = np.asarray(locs) + locs = locs[(vmin <= locs) & (locs <= vmax)] + if not len(locs): + self.offset = 0 + return + lmin, lmax = locs.min(), locs.max() + # Only use offset if there are at least two ticks and every tick has + # the same sign. + if lmin == lmax or lmin <= 0 <= lmax: + self.offset = 0 + return + # min, max comparing absolute values (we want division to round towards + # zero so we work on absolute values). + abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))]) + sign = math.copysign(1, lmin) + # What is the smallest power of ten such that abs_min and abs_max are + # equal up to that precision? + # Note: Internally using oom instead of 10 ** oom avoids some numerical + # accuracy issues. + oom_max = np.ceil(math.log10(abs_max)) + oom = 1 + next(oom for oom in itertools.count(oom_max, -1) + if abs_min // 10 ** oom != abs_max // 10 ** oom) + if (abs_max - abs_min) / 10 ** oom <= 1e-2: + # Handle the case of straddling a multiple of a large power of ten + # (relative to the span). + # What is the smallest power of ten such that abs_min and abs_max + # are no more than 1 apart at that precision? + oom = 1 + next(oom for oom in itertools.count(oom_max, -1) + if abs_max // 10 ** oom - abs_min // 10 ** oom > 1) + # Only use offset if it saves at least _offset_threshold digits. + n = self._offset_threshold - 1 + self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom + if abs_max // 10 ** oom >= 10**n + else 0) + + def _set_order_of_magnitude(self): + # if scientific notation is to be used, find the appropriate exponent + # if using a numerical offset, find the exponent after applying the + # offset. When lower power limit = upper <> 0, use provided exponent. + if not self._scientific: + self.orderOfMagnitude = 0 + return + if self._powerlimits[0] == self._powerlimits[1] != 0: + # fixed scaling when lower power limit = upper <> 0. + self.orderOfMagnitude = self._powerlimits[0] + return + # restrict to visible ticks + vmin, vmax = sorted(self.axis.get_view_interval()) + locs = np.asarray(self.locs) + locs = locs[(vmin <= locs) & (locs <= vmax)] + locs = np.abs(locs) + if not len(locs): + self.orderOfMagnitude = 0 + return + if self.offset: + oom = math.floor(math.log10(vmax - vmin)) + else: + val = locs.max() + if val == 0: + oom = 0 + else: + oom = math.floor(math.log10(val)) + if oom <= self._powerlimits[0]: + self.orderOfMagnitude = oom + elif oom >= self._powerlimits[1]: + self.orderOfMagnitude = oom + else: + self.orderOfMagnitude = 0 + + def _set_format(self): + # set the format string to format all the ticklabels + if len(self.locs) < 2: + # Temporarily augment the locations with the axis end points. + _locs = [*self.locs, *self.axis.get_view_interval()] + else: + _locs = self.locs + locs = (np.asarray(_locs) - self.offset) / 10. ** self.orderOfMagnitude + loc_range = np.ptp(locs) + # Curvilinear coordinates can yield two identical points. + if loc_range == 0: + loc_range = np.max(np.abs(locs)) + # Both points might be zero. + if loc_range == 0: + loc_range = 1 + if len(self.locs) < 2: + # We needed the end points only for the loc_range calculation. + locs = locs[:-2] + loc_range_oom = int(math.floor(math.log10(loc_range))) + # first estimate: + sigfigs = max(0, 3 - loc_range_oom) + # refined estimate: + thresh = 1e-3 * 10 ** loc_range_oom + while sigfigs >= 0: + if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh: + sigfigs -= 1 + else: + break + sigfigs += 1 + self.format = f'%1.{sigfigs}f' + if self._usetex or self._useMathText: + self.format = r'$\mathdefault{%s}$' % self.format + + +class LogFormatter(Formatter): + """ + Base class for formatting ticks on a log or symlog scale. + + It may be instantiated directly, or subclassed. + + Parameters + ---------- + base : float, default: 10. + Base of the logarithm used in all calculations. + + labelOnlyBase : bool, default: False + If True, label ticks only at integer powers of base. + This is normally True for major ticks and False for + minor ticks. + + minor_thresholds : (subset, all), default: (1, 0.4) + If labelOnlyBase is False, these two numbers control + the labeling of ticks that are not at integer powers of + base; normally these are the minor ticks. The controlling + parameter is the log of the axis data range. In the typical + case where base is 10 it is the number of decades spanned + by the axis, so we can call it 'numdec'. If ``numdec <= all``, + all minor ticks will be labeled. If ``all < numdec <= subset``, + then only a subset of minor ticks will be labeled, so as to + avoid crowding. If ``numdec > subset`` then no minor ticks will + be labeled. + + linthresh : None or float, default: None + If a symmetric log scale is in use, its ``linthresh`` + parameter must be supplied here. + + Notes + ----- + The `set_locs` method must be called to enable the subsetting + logic controlled by the ``minor_thresholds`` parameter. + + In some cases such as the colorbar, there is no distinction between + major and minor ticks; the tick locations might be set manually, + or by a locator that puts ticks at integer powers of base and + at intermediate locations. For this situation, disable the + minor_thresholds logic by using ``minor_thresholds=(np.inf, np.inf)``, + so that all ticks will be labeled. + + To disable labeling of minor ticks when 'labelOnlyBase' is False, + use ``minor_thresholds=(0, 0)``. This is the default for the + "classic" style. + + Examples + -------- + To label a subset of minor ticks when the view limits span up + to 2 decades, and all of the ticks when zoomed in to 0.5 decades + or less, use ``minor_thresholds=(2, 0.5)``. + + To label all minor ticks when the view limits span up to 1.5 + decades, use ``minor_thresholds=(1.5, 1.5)``. + """ + + def __init__(self, base=10.0, labelOnlyBase=False, + minor_thresholds=None, + linthresh=None): + + self.set_base(base) + self.set_label_minor(labelOnlyBase) + if minor_thresholds is None: + if mpl.rcParams['_internal.classic_mode']: + minor_thresholds = (0, 0) + else: + minor_thresholds = (1, 0.4) + self.minor_thresholds = minor_thresholds + self._sublabels = None + self._linthresh = linthresh + + def set_base(self, base): + """ + Change the *base* for labeling. + + .. warning:: + Should always match the base used for :class:`LogLocator` + """ + self._base = float(base) + + def set_label_minor(self, labelOnlyBase): + """ + Switch minor tick labeling on or off. + + Parameters + ---------- + labelOnlyBase : bool + If True, label ticks only at integer powers of base. + """ + self.labelOnlyBase = labelOnlyBase + + def set_locs(self, locs=None): + """ + Use axis view limits to control which ticks are labeled. + + The *locs* parameter is ignored in the present algorithm. + """ + if np.isinf(self.minor_thresholds[0]): + self._sublabels = None + return + + # Handle symlog case: + linthresh = self._linthresh + if linthresh is None: + try: + linthresh = self.axis.get_transform().linthresh + except AttributeError: + pass + + vmin, vmax = self.axis.get_view_interval() + if vmin > vmax: + vmin, vmax = vmax, vmin + + if linthresh is None and vmin <= 0: + # It's probably a colorbar with + # a format kwarg setting a LogFormatter in the manner + # that worked with 1.5.x, but that doesn't work now. + self._sublabels = {1} # label powers of base + return + + b = self._base + if linthresh is not None: # symlog + # Only compute the number of decades in the logarithmic part of the + # axis + numdec = 0 + if vmin < -linthresh: + rhs = min(vmax, -linthresh) + numdec += math.log(vmin / rhs) / math.log(b) + if vmax > linthresh: + lhs = max(vmin, linthresh) + numdec += math.log(vmax / lhs) / math.log(b) + else: + vmin = math.log(vmin) / math.log(b) + vmax = math.log(vmax) / math.log(b) + numdec = abs(vmax - vmin) + + if numdec > self.minor_thresholds[0]: + # Label only bases + self._sublabels = {1} + elif numdec > self.minor_thresholds[1]: + # Add labels between bases at log-spaced coefficients; + # include base powers in case the locations include + # "major" and "minor" points, as in colorbar. + c = np.geomspace(1, b, int(b)//2 + 1) + self._sublabels = set(np.round(c)) + # For base 10, this yields (1, 2, 3, 4, 6, 10). + else: + # Label all integer multiples of base**n. + self._sublabels = set(np.arange(1, b + 1)) + + def _num_to_string(self, x, vmin, vmax): + if x > 10000: + s = '%1.0e' % x + elif x < 1: + s = '%1.0e' % x + else: + s = self._pprint_val(x, vmax - vmin) + return s + + def __call__(self, x, pos=None): + # docstring inherited + if x == 0.0: # Symlog + return '0' + + x = abs(x) + b = self._base + # only label the decades + fx = math.log(x) / math.log(b) + is_x_decade = _is_close_to_int(fx) + exponent = round(fx) if is_x_decade else np.floor(fx) + coeff = round(b ** (fx - exponent)) + + if self.labelOnlyBase and not is_x_decade: + return '' + if self._sublabels is not None and coeff not in self._sublabels: + return '' + + vmin, vmax = self.axis.get_view_interval() + vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) + s = self._num_to_string(x, vmin, vmax) + return self.fix_minus(s) + + def format_data(self, value): + with cbook._setattr_cm(self, labelOnlyBase=False): + return cbook.strip_math(self.__call__(value)) + + def format_data_short(self, value): + # docstring inherited + return ('%-12g' % value).rstrip() + + def _pprint_val(self, x, d): + # If the number is not too big and it's an int, format it as an int. + if abs(x) < 1e4 and x == int(x): + return '%d' % x + fmt = ('%1.3e' if d < 1e-2 else + '%1.3f' if d <= 1 else + '%1.2f' if d <= 10 else + '%1.1f' if d <= 1e5 else + '%1.1e') + s = fmt % x + tup = s.split('e') + if len(tup) == 2: + mantissa = tup[0].rstrip('0').rstrip('.') + exponent = int(tup[1]) + if exponent: + s = '%se%d' % (mantissa, exponent) + else: + s = mantissa + else: + s = s.rstrip('0').rstrip('.') + return s + + +class LogFormatterExponent(LogFormatter): + """ + Format values for log axis using ``exponent = log_base(value)``. + """ + def _num_to_string(self, x, vmin, vmax): + fx = math.log(x) / math.log(self._base) + if abs(fx) > 10000: + s = '%1.0g' % fx + elif abs(fx) < 1: + s = '%1.0g' % fx + else: + fd = math.log(vmax - vmin) / math.log(self._base) + s = self._pprint_val(fx, fd) + return s + + +class LogFormatterMathtext(LogFormatter): + """ + Format values for log axis using ``exponent = log_base(value)``. + """ + + def _non_decade_format(self, sign_string, base, fx, usetex): + """Return string for non-decade locations.""" + return r'$\mathdefault{%s%s^{%.2f}}$' % (sign_string, base, fx) + + def __call__(self, x, pos=None): + # docstring inherited + if x == 0: # Symlog + return r'$\mathdefault{0}$' + + sign_string = '-' if x < 0 else '' + x = abs(x) + b = self._base + + # only label the decades + fx = math.log(x) / math.log(b) + is_x_decade = _is_close_to_int(fx) + exponent = round(fx) if is_x_decade else np.floor(fx) + coeff = round(b ** (fx - exponent)) + + if self.labelOnlyBase and not is_x_decade: + return '' + if self._sublabels is not None and coeff not in self._sublabels: + return '' + + if is_x_decade: + fx = round(fx) + + # use string formatting of the base if it is not an integer + if b % 1 == 0.0: + base = '%d' % b + else: + base = '%s' % b + + if abs(fx) < mpl.rcParams['axes.formatter.min_exponent']: + return r'$\mathdefault{%s%g}$' % (sign_string, x) + elif not is_x_decade: + usetex = mpl.rcParams['text.usetex'] + return self._non_decade_format(sign_string, base, fx, usetex) + else: + return r'$\mathdefault{%s%s^{%d}}$' % (sign_string, base, fx) + + +class LogFormatterSciNotation(LogFormatterMathtext): + """ + Format values following scientific notation in a logarithmic axis. + """ + + def _non_decade_format(self, sign_string, base, fx, usetex): + """Return string for non-decade locations.""" + b = float(base) + exponent = math.floor(fx) + coeff = b ** (fx - exponent) + if _is_close_to_int(coeff): + coeff = round(coeff) + return r'$\mathdefault{%s%g\times%s^{%d}}$' \ + % (sign_string, coeff, base, exponent) + + +class LogitFormatter(Formatter): + """ + Probability formatter (using Math text). + """ + + def __init__( + self, + *, + use_overline=False, + one_half=r"\frac{1}{2}", + minor=False, + minor_threshold=25, + minor_number=6, + ): + r""" + Parameters + ---------- + use_overline : bool, default: False + If x > 1/2, with x = 1-v, indicate if x should be displayed as + $\overline{v}$. The default is to display $1-v$. + + one_half : str, default: r"\frac{1}{2}" + The string used to represent 1/2. + + minor : bool, default: False + Indicate if the formatter is formatting minor ticks or not. + Basically minor ticks are not labelled, except when only few ticks + are provided, ticks with most space with neighbor ticks are + labelled. See other parameters to change the default behavior. + + minor_threshold : int, default: 25 + Maximum number of locs for labelling some minor ticks. This + parameter have no effect if minor is False. + + minor_number : int, default: 6 + Number of ticks which are labelled when the number of ticks is + below the threshold. + """ + self._use_overline = use_overline + self._one_half = one_half + self._minor = minor + self._labelled = set() + self._minor_threshold = minor_threshold + self._minor_number = minor_number + + def use_overline(self, use_overline): + r""" + Switch display mode with overline for labelling p>1/2. + + Parameters + ---------- + use_overline : bool, default: False + If x > 1/2, with x = 1-v, indicate if x should be displayed as + $\overline{v}$. The default is to display $1-v$. + """ + self._use_overline = use_overline + + def set_one_half(self, one_half): + r""" + Set the way one half is displayed. + + one_half : str, default: r"\frac{1}{2}" + The string used to represent 1/2. + """ + self._one_half = one_half + + def set_minor_threshold(self, minor_threshold): + """ + Set the threshold for labelling minors ticks. + + Parameters + ---------- + minor_threshold : int + Maximum number of locations for labelling some minor ticks. This + parameter have no effect if minor is False. + """ + self._minor_threshold = minor_threshold + + def set_minor_number(self, minor_number): + """ + Set the number of minor ticks to label when some minor ticks are + labelled. + + Parameters + ---------- + minor_number : int + Number of ticks which are labelled when the number of ticks is + below the threshold. + """ + self._minor_number = minor_number + + def set_locs(self, locs): + self.locs = np.array(locs) + self._labelled.clear() + + if not self._minor: + return None + if all( + _is_decade(x, rtol=1e-7) + or _is_decade(1 - x, rtol=1e-7) + or (_is_close_to_int(2 * x) and + int(np.round(2 * x)) == 1) + for x in locs + ): + # minor ticks are subsample from ideal, so no label + return None + if len(locs) < self._minor_threshold: + if len(locs) < self._minor_number: + self._labelled.update(locs) + else: + # we do not have a lot of minor ticks, so only few decades are + # displayed, then we choose some (spaced) minor ticks to label. + # Only minor ticks are known, we assume it is sufficient to + # choice which ticks are displayed. + # For each ticks we compute the distance between the ticks and + # the previous, and between the ticks and the next one. Ticks + # with smallest minimum are chosen. As tiebreak, the ticks + # with smallest sum is chosen. + diff = np.diff(-np.log(1 / self.locs - 1)) + space_pessimistic = np.minimum( + np.concatenate(((np.inf,), diff)), + np.concatenate((diff, (np.inf,))), + ) + space_sum = ( + np.concatenate(((0,), diff)) + + np.concatenate((diff, (0,))) + ) + good_minor = sorted( + range(len(self.locs)), + key=lambda i: (space_pessimistic[i], space_sum[i]), + )[-self._minor_number:] + self._labelled.update(locs[i] for i in good_minor) + + def _format_value(self, x, locs, sci_notation=True): + if sci_notation: + exponent = math.floor(np.log10(x)) + min_precision = 0 + else: + exponent = 0 + min_precision = 1 + value = x * 10 ** (-exponent) + if len(locs) < 2: + precision = min_precision + else: + diff = np.sort(np.abs(locs - x))[1] + precision = -np.log10(diff) + exponent + precision = ( + int(np.round(precision)) + if _is_close_to_int(precision) + else math.ceil(precision) + ) + if precision < min_precision: + precision = min_precision + mantissa = r"%.*f" % (precision, value) + if not sci_notation: + return mantissa + s = r"%s\cdot10^{%d}" % (mantissa, exponent) + return s + + def _one_minus(self, s): + if self._use_overline: + return r"\overline{%s}" % s + else: + return f"1-{s}" + + def __call__(self, x, pos=None): + if self._minor and x not in self._labelled: + return "" + if x <= 0 or x >= 1: + return "" + if _is_close_to_int(2 * x) and round(2 * x) == 1: + s = self._one_half + elif x < 0.5 and _is_decade(x, rtol=1e-7): + exponent = round(math.log10(x)) + s = "10^{%d}" % exponent + elif x > 0.5 and _is_decade(1 - x, rtol=1e-7): + exponent = round(math.log10(1 - x)) + s = self._one_minus("10^{%d}" % exponent) + elif x < 0.1: + s = self._format_value(x, self.locs) + elif x > 0.9: + s = self._one_minus(self._format_value(1-x, 1-self.locs)) + else: + s = self._format_value(x, self.locs, sci_notation=False) + return r"$\mathdefault{%s}$" % s + + def format_data_short(self, value): + # docstring inherited + # Thresholds chosen to use scientific notation iff exponent <= -2. + if value < 0.1: + return f"{value:e}" + if value < 0.9: + return f"{value:f}" + return f"1-{1 - value:e}" + + +class EngFormatter(Formatter): + """ + Format axis values using engineering prefixes to represent powers + of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7. + """ + + # The SI engineering prefixes + ENG_PREFIXES = { + -30: "q", + -27: "r", + -24: "y", + -21: "z", + -18: "a", + -15: "f", + -12: "p", + -9: "n", + -6: "\N{MICRO SIGN}", + -3: "m", + 0: "", + 3: "k", + 6: "M", + 9: "G", + 12: "T", + 15: "P", + 18: "E", + 21: "Z", + 24: "Y", + 27: "R", + 30: "Q" + } + + def __init__(self, unit="", places=None, sep=" ", *, usetex=None, + useMathText=None): + r""" + Parameters + ---------- + unit : str, default: "" + Unit symbol to use, suitable for use with single-letter + representations of powers of 1000. For example, 'Hz' or 'm'. + + places : int, default: None + Precision with which to display the number, specified in + digits after the decimal point (there will be between one + and three digits before the decimal point). If it is None, + the formatting falls back to the floating point format '%g', + which displays up to 6 *significant* digits, i.e. the equivalent + value for *places* varies between 0 and 5 (inclusive). + + sep : str, default: " " + Separator used between the value and the prefix/unit. For + example, one get '3.14 mV' if ``sep`` is " " (default) and + '3.14mV' if ``sep`` is "". Besides the default behavior, some + other useful options may be: + + * ``sep=""`` to append directly the prefix/unit to the value; + * ``sep="\N{THIN SPACE}"`` (``U+2009``); + * ``sep="\N{NARROW NO-BREAK SPACE}"`` (``U+202F``); + * ``sep="\N{NO-BREAK SPACE}"`` (``U+00A0``). + + usetex : bool, default: :rc:`text.usetex` + To enable/disable the use of TeX's math mode for rendering the + numbers in the formatter. + + useMathText : bool, default: :rc:`axes.formatter.use_mathtext` + To enable/disable the use mathtext for rendering the numbers in + the formatter. + """ + self.unit = unit + self.places = places + self.sep = sep + self.set_usetex(usetex) + self.set_useMathText(useMathText) + + def get_usetex(self): + return self._usetex + + def set_usetex(self, val): + if val is None: + self._usetex = mpl.rcParams['text.usetex'] + else: + self._usetex = val + + usetex = property(fget=get_usetex, fset=set_usetex) + + def get_useMathText(self): + return self._useMathText + + def set_useMathText(self, val): + if val is None: + self._useMathText = mpl.rcParams['axes.formatter.use_mathtext'] + else: + self._useMathText = val + + useMathText = property(fget=get_useMathText, fset=set_useMathText) + + def __call__(self, x, pos=None): + s = f"{self.format_eng(x)}{self.unit}" + # Remove the trailing separator when there is neither prefix nor unit + if self.sep and s.endswith(self.sep): + s = s[:-len(self.sep)] + return self.fix_minus(s) + + def format_eng(self, num): + """ + Format a number in engineering notation, appending a letter + representing the power of 1000 of the original number. + Some examples: + + >>> format_eng(0) # for self.places = 0 + '0' + + >>> format_eng(1000000) # for self.places = 1 + '1.0 M' + + >>> format_eng(-1e-6) # for self.places = 2 + '-1.00 \N{MICRO SIGN}' + """ + sign = 1 + fmt = "g" if self.places is None else f".{self.places:d}f" + + if num < 0: + sign = -1 + num = -num + + if num != 0: + pow10 = int(math.floor(math.log10(num) / 3) * 3) + else: + pow10 = 0 + # Force num to zero, to avoid inconsistencies like + # format_eng(-0) = "0" and format_eng(0.0) = "0" + # but format_eng(-0.0) = "-0.0" + num = 0.0 + + pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES)) + + mant = sign * num / (10.0 ** pow10) + # Taking care of the cases like 999.9..., which may be rounded to 1000 + # instead of 1 k. Beware of the corner case of values that are beyond + # the range of SI prefixes (i.e. > 'Y'). + if (abs(float(format(mant, fmt))) >= 1000 + and pow10 < max(self.ENG_PREFIXES)): + mant /= 1000 + pow10 += 3 + + prefix = self.ENG_PREFIXES[int(pow10)] + if self._usetex or self._useMathText: + formatted = f"${mant:{fmt}}${self.sep}{prefix}" + else: + formatted = f"{mant:{fmt}}{self.sep}{prefix}" + + return formatted + + +class PercentFormatter(Formatter): + """ + Format numbers as a percentage. + + Parameters + ---------- + xmax : float + Determines how the number is converted into a percentage. + *xmax* is the data value that corresponds to 100%. + Percentages are computed as ``x / xmax * 100``. So if the data is + already scaled to be percentages, *xmax* will be 100. Another common + situation is where *xmax* is 1.0. + + decimals : None or int + The number of decimal places to place after the point. + If *None* (the default), the number will be computed automatically. + + symbol : str or None + A string that will be appended to the label. It may be + *None* or empty to indicate that no symbol should be used. LaTeX + special characters are escaped in *symbol* whenever latex mode is + enabled, unless *is_latex* is *True*. + + is_latex : bool + If *False*, reserved LaTeX characters in *symbol* will be escaped. + """ + def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False): + self.xmax = xmax + 0.0 + self.decimals = decimals + self._symbol = symbol + self._is_latex = is_latex + + def __call__(self, x, pos=None): + """Format the tick as a percentage with the appropriate scaling.""" + ax_min, ax_max = self.axis.get_view_interval() + display_range = abs(ax_max - ax_min) + return self.fix_minus(self.format_pct(x, display_range)) + + def format_pct(self, x, display_range): + """ + Format the number as a percentage number with the correct + number of decimals and adds the percent symbol, if any. + + If ``self.decimals`` is `None`, the number of digits after the + decimal point is set based on the *display_range* of the axis + as follows: + + ============= ======== ======================= + display_range decimals sample + ============= ======== ======================= + >50 0 ``x = 34.5`` => 35% + >5 1 ``x = 34.5`` => 34.5% + >0.5 2 ``x = 34.5`` => 34.50% + ... ... ... + ============= ======== ======================= + + This method will not be very good for tiny axis ranges or + extremely large ones. It assumes that the values on the chart + are percentages displayed on a reasonable scale. + """ + x = self.convert_to_pct(x) + if self.decimals is None: + # conversion works because display_range is a difference + scaled_range = self.convert_to_pct(display_range) + if scaled_range <= 0: + decimals = 0 + else: + # Luckily Python's built-in ceil rounds to +inf, not away from + # zero. This is very important since the equation for decimals + # starts out as `scaled_range > 0.5 * 10**(2 - decimals)` + # and ends up with `decimals > 2 - log10(2 * scaled_range)`. + decimals = math.ceil(2.0 - math.log10(2.0 * scaled_range)) + if decimals > 5: + decimals = 5 + elif decimals < 0: + decimals = 0 + else: + decimals = self.decimals + s = f'{x:0.{int(decimals)}f}' + + return s + self.symbol + + def convert_to_pct(self, x): + return 100.0 * (x / self.xmax) + + @property + def symbol(self): + r""" + The configured percent symbol as a string. + + If LaTeX is enabled via :rc:`text.usetex`, the special characters + ``{'#', '$', '%', '&', '~', '_', '^', '\', '{', '}'}`` are + automatically escaped in the string. + """ + symbol = self._symbol + if not symbol: + symbol = '' + elif not self._is_latex and mpl.rcParams['text.usetex']: + # Source: http://www.personal.ceu.hu/tex/specchar.htm + # Backslash must be first for this to work correctly since + # it keeps getting added in + for spec in r'\#$%&~_^{}': + symbol = symbol.replace(spec, '\\' + spec) + return symbol + + @symbol.setter + def symbol(self, symbol): + self._symbol = symbol + + +class Locator(TickHelper): + """ + Determine tick locations. + + Note that the same locator should not be used across multiple + `~matplotlib.axis.Axis` because the locator stores references to the Axis + data and view limits. + """ + + # Some automatic tick locators can generate so many ticks they + # kill the machine when you try and render them. + # This parameter is set to cause locators to raise an error if too + # many ticks are generated. + MAXTICKS = 1000 + + def tick_values(self, vmin, vmax): + """ + Return the values of the located ticks given **vmin** and **vmax**. + + .. note:: + To get tick locations with the vmin and vmax values defined + automatically for the associated ``axis`` simply call + the Locator instance:: + + >>> print(type(loc)) + + >>> print(loc()) + [1, 2, 3, 4] + + """ + raise NotImplementedError('Derived must override') + + def set_params(self, **kwargs): + """ + Do nothing, and raise a warning. Any locator class not supporting the + set_params() function will call this. + """ + _api.warn_external( + "'set_params()' not defined for locator of type " + + str(type(self))) + + def __call__(self): + """Return the locations of the ticks.""" + # note: some locators return data limits, other return view limits, + # hence there is no *one* interface to call self.tick_values. + raise NotImplementedError('Derived must override') + + def raise_if_exceeds(self, locs): + """ + Log at WARNING level if *locs* is longer than `Locator.MAXTICKS`. + + This is intended to be called immediately before returning *locs* from + ``__call__`` to inform users in case their Locator returns a huge + number of ticks, causing Matplotlib to run out of memory. + + The "strange" name of this method dates back to when it would raise an + exception instead of emitting a log. + """ + if len(locs) >= self.MAXTICKS: + _log.warning( + "Locator attempting to generate %s ticks ([%s, ..., %s]), " + "which exceeds Locator.MAXTICKS (%s).", + len(locs), locs[0], locs[-1], self.MAXTICKS) + return locs + + def nonsingular(self, v0, v1): + """ + Adjust a range as needed to avoid singularities. + + This method gets called during autoscaling, with ``(v0, v1)`` set to + the data limits on the Axes if the Axes contains any data, or + ``(-inf, +inf)`` if not. + + - If ``v0 == v1`` (possibly up to some floating point slop), this + method returns an expanded interval around this value. + - If ``(v0, v1) == (-inf, +inf)``, this method returns appropriate + default view limits. + - Otherwise, ``(v0, v1)`` is returned without modification. + """ + return mtransforms.nonsingular(v0, v1, expander=.05) + + def view_limits(self, vmin, vmax): + """ + Select a scale for the range from vmin to vmax. + + Subclasses should override this method to change locator behaviour. + """ + return mtransforms.nonsingular(vmin, vmax) + + +class IndexLocator(Locator): + """ + Place ticks at every nth point plotted. + + IndexLocator assumes index plotting; i.e., that the ticks are placed at integer + values in the range between 0 and len(data) inclusive. + """ + def __init__(self, base, offset): + """Place ticks every *base* data point, starting at *offset*.""" + self._base = base + self.offset = offset + + def set_params(self, base=None, offset=None): + """Set parameters within this locator""" + if base is not None: + self._base = base + if offset is not None: + self.offset = offset + + def __call__(self): + """Return the locations of the ticks""" + dmin, dmax = self.axis.get_data_interval() + return self.tick_values(dmin, dmax) + + def tick_values(self, vmin, vmax): + return self.raise_if_exceeds( + np.arange(vmin + self.offset, vmax + 1, self._base)) + + +class FixedLocator(Locator): + """ + Place ticks at a set of fixed values. + + If *nbins* is None ticks are placed at all values. Otherwise, the *locs* array of + possible positions will be subsampled to keep the number of ticks <= + :math:`nbins* +1`. The subsampling will be done to include the smallest absolute + value; for example, if zero is included in the array of possibilities, then it of + the chosen ticks. + """ + + def __init__(self, locs, nbins=None): + self.locs = np.asarray(locs) + _api.check_shape((None,), locs=self.locs) + self.nbins = max(nbins, 2) if nbins is not None else None + + def set_params(self, nbins=None): + """Set parameters within this locator.""" + if nbins is not None: + self.nbins = nbins + + def __call__(self): + return self.tick_values(None, None) + + def tick_values(self, vmin, vmax): + """ + Return the locations of the ticks. + + .. note:: + + Because the values are fixed, vmin and vmax are not used in this + method. + + """ + if self.nbins is None: + return self.locs + step = max(int(np.ceil(len(self.locs) / self.nbins)), 1) + ticks = self.locs[::step] + for i in range(1, step): + ticks1 = self.locs[i::step] + if np.abs(ticks1).min() < np.abs(ticks).min(): + ticks = ticks1 + return self.raise_if_exceeds(ticks) + + +class NullLocator(Locator): + """ + No ticks + """ + + def __call__(self): + return self.tick_values(None, None) + + def tick_values(self, vmin, vmax): + """ + Return the locations of the ticks. + + .. note:: + + Because the values are Null, vmin and vmax are not used in this + method. + """ + return [] + + +class LinearLocator(Locator): + """ + Place ticks at evenly spaced values. + + The first time this function is called it will try to set the + number of ticks to make a nice tick partitioning. Thereafter, the + number of ticks will be fixed so that interactive navigation will + be nice + + """ + def __init__(self, numticks=None, presets=None): + """ + Parameters + ---------- + numticks : int or None, default None + Number of ticks. If None, *numticks* = 11. + presets : dict or None, default: None + Dictionary mapping ``(vmin, vmax)`` to an array of locations. + Overrides *numticks* if there is an entry for the current + ``(vmin, vmax)``. + """ + self.numticks = numticks + if presets is None: + self.presets = {} + else: + self.presets = presets + + @property + def numticks(self): + # Old hard-coded default. + return self._numticks if self._numticks is not None else 11 + + @numticks.setter + def numticks(self, numticks): + self._numticks = numticks + + def set_params(self, numticks=None, presets=None): + """Set parameters within this locator.""" + if presets is not None: + self.presets = presets + if numticks is not None: + self.numticks = numticks + + def __call__(self): + """Return the locations of the ticks.""" + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) + + if (vmin, vmax) in self.presets: + return self.presets[(vmin, vmax)] + + if self.numticks == 0: + return [] + ticklocs = np.linspace(vmin, vmax, self.numticks) + + return self.raise_if_exceeds(ticklocs) + + def view_limits(self, vmin, vmax): + """Try to choose the view limits intelligently.""" + + if vmax < vmin: + vmin, vmax = vmax, vmin + + if vmin == vmax: + vmin -= 1 + vmax += 1 + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + exponent, remainder = divmod( + math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1))) + exponent -= (remainder < .5) + scale = max(self.numticks - 1, 1) ** (-exponent) + vmin = math.floor(scale * vmin) / scale + vmax = math.ceil(scale * vmax) / scale + + return mtransforms.nonsingular(vmin, vmax) + + +class MultipleLocator(Locator): + """ + Place ticks at every integer multiple of a base plus an offset. + """ + + def __init__(self, base=1.0, offset=0.0): + """ + Parameters + ---------- + base : float > 0 + Interval between ticks. + offset : float + Value added to each multiple of *base*. + + .. versionadded:: 3.8 + """ + self._edge = _Edge_integer(base, 0) + self._offset = offset + + def set_params(self, base=None, offset=None): + """ + Set parameters within this locator. + + Parameters + ---------- + base : float > 0 + Interval between ticks. + offset : float + Value added to each multiple of *base*. + + .. versionadded:: 3.8 + """ + if base is not None: + self._edge = _Edge_integer(base, 0) + if offset is not None: + self._offset = offset + + def __call__(self): + """Return the locations of the ticks.""" + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + if vmax < vmin: + vmin, vmax = vmax, vmin + step = self._edge.step + vmin -= self._offset + vmax -= self._offset + vmin = self._edge.ge(vmin) * step + n = (vmax - vmin + 0.001 * step) // step + locs = vmin - step + np.arange(n + 3) * step + self._offset + return self.raise_if_exceeds(locs) + + def view_limits(self, dmin, dmax): + """ + Set the view limits to the nearest tick values that contain the data. + """ + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + vmin = self._edge.le(dmin - self._offset) * self._edge.step + self._offset + vmax = self._edge.ge(dmax - self._offset) * self._edge.step + self._offset + if vmin == vmax: + vmin -= 1 + vmax += 1 + else: + vmin = dmin + vmax = dmax + + return mtransforms.nonsingular(vmin, vmax) + + +def scale_range(vmin, vmax, n=1, threshold=100): + dv = abs(vmax - vmin) # > 0 as nonsingular is called before. + meanv = (vmax + vmin) / 2 + if abs(meanv) / dv < threshold: + offset = 0 + else: + offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv) + scale = 10 ** (math.log10(dv / n) // 1) + return scale, offset + + +class _Edge_integer: + """ + Helper for `.MaxNLocator`, `.MultipleLocator`, etc. + + Take floating-point precision limitations into account when calculating + tick locations as integer multiples of a step. + """ + def __init__(self, step, offset): + """ + Parameters + ---------- + step : float > 0 + Interval between ticks. + offset : float + Offset subtracted from the data limits prior to calculating tick + locations. + """ + if step <= 0: + raise ValueError("'step' must be positive") + self.step = step + self._offset = abs(offset) + + def closeto(self, ms, edge): + # Allow more slop when the offset is large compared to the step. + if self._offset > 0: + digits = np.log10(self._offset / self.step) + tol = max(1e-10, 10 ** (digits - 12)) + tol = min(0.4999, tol) + else: + tol = 1e-10 + return abs(ms - edge) < tol + + def le(self, x): + """Return the largest n: n*step <= x.""" + d, m = divmod(x, self.step) + if self.closeto(m / self.step, 1): + return d + 1 + return d + + def ge(self, x): + """Return the smallest n: n*step >= x.""" + d, m = divmod(x, self.step) + if self.closeto(m / self.step, 0): + return d + return d + 1 + + +class MaxNLocator(Locator): + """ + Place evenly spaced ticks, with a cap on the total number of ticks. + + Finds nice tick locations with no more than :math:`nbins + 1` ticks being within the + view limits. Locations beyond the limits are added to support autoscaling. + """ + default_params = dict(nbins=10, + steps=None, + integer=False, + symmetric=False, + prune=None, + min_n_ticks=2) + + def __init__(self, nbins=None, **kwargs): + """ + Parameters + ---------- + nbins : int or 'auto', default: 10 + Maximum number of intervals; one less than max number of + ticks. If the string 'auto', the number of bins will be + automatically determined based on the length of the axis. + + steps : array-like, optional + Sequence of acceptable tick multiples, starting with 1 and + ending with 10. For example, if ``steps=[1, 2, 4, 5, 10]``, + ``20, 40, 60`` or ``0.4, 0.6, 0.8`` would be possible + sets of ticks because they are multiples of 2. + ``30, 60, 90`` would not be generated because 3 does not + appear in this example list of steps. + + integer : bool, default: False + If True, ticks will take only integer values, provided at least + *min_n_ticks* integers are found within the view limits. + + symmetric : bool, default: False + If True, autoscaling will result in a range symmetric about zero. + + prune : {'lower', 'upper', 'both', None}, default: None + Remove the 'lower' tick, the 'upper' tick, or ticks on 'both' sides + *if they fall exactly on an axis' edge* (this typically occurs when + :rc:`axes.autolimit_mode` is 'round_numbers'). Removing such ticks + is mostly useful for stacked or ganged plots, where the upper tick + of an Axes overlaps with the lower tick of the axes above it. + + min_n_ticks : int, default: 2 + Relax *nbins* and *integer* constraints if necessary to obtain + this minimum number of ticks. + """ + if nbins is not None: + kwargs['nbins'] = nbins + self.set_params(**{**self.default_params, **kwargs}) + + @staticmethod + def _validate_steps(steps): + if not np.iterable(steps): + raise ValueError('steps argument must be an increasing sequence ' + 'of numbers between 1 and 10 inclusive') + steps = np.asarray(steps) + if np.any(np.diff(steps) <= 0) or steps[-1] > 10 or steps[0] < 1: + raise ValueError('steps argument must be an increasing sequence ' + 'of numbers between 1 and 10 inclusive') + if steps[0] != 1: + steps = np.concatenate([[1], steps]) + if steps[-1] != 10: + steps = np.concatenate([steps, [10]]) + return steps + + @staticmethod + def _staircase(steps): + # Make an extended staircase within which the needed step will be + # found. This is probably much larger than necessary. + return np.concatenate([0.1 * steps[:-1], steps, [10 * steps[1]]]) + + def set_params(self, **kwargs): + """ + Set parameters for this locator. + + Parameters + ---------- + nbins : int or 'auto', optional + see `.MaxNLocator` + steps : array-like, optional + see `.MaxNLocator` + integer : bool, optional + see `.MaxNLocator` + symmetric : bool, optional + see `.MaxNLocator` + prune : {'lower', 'upper', 'both', None}, optional + see `.MaxNLocator` + min_n_ticks : int, optional + see `.MaxNLocator` + """ + if 'nbins' in kwargs: + self._nbins = kwargs.pop('nbins') + if self._nbins != 'auto': + self._nbins = int(self._nbins) + if 'symmetric' in kwargs: + self._symmetric = kwargs.pop('symmetric') + if 'prune' in kwargs: + prune = kwargs.pop('prune') + _api.check_in_list(['upper', 'lower', 'both', None], prune=prune) + self._prune = prune + if 'min_n_ticks' in kwargs: + self._min_n_ticks = max(1, kwargs.pop('min_n_ticks')) + if 'steps' in kwargs: + steps = kwargs.pop('steps') + if steps is None: + self._steps = np.array([1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) + else: + self._steps = self._validate_steps(steps) + self._extended_steps = self._staircase(self._steps) + if 'integer' in kwargs: + self._integer = kwargs.pop('integer') + if kwargs: + raise _api.kwarg_error("set_params", kwargs) + + def _raw_ticks(self, vmin, vmax): + """ + Generate a list of tick locations including the range *vmin* to + *vmax*. In some applications, one or both of the end locations + will not be needed, in which case they are trimmed off + elsewhere. + """ + if self._nbins == 'auto': + if self.axis is not None: + nbins = np.clip(self.axis.get_tick_space(), + max(1, self._min_n_ticks - 1), 9) + else: + nbins = 9 + else: + nbins = self._nbins + + scale, offset = scale_range(vmin, vmax, nbins) + _vmin = vmin - offset + _vmax = vmax - offset + steps = self._extended_steps * scale + if self._integer: + # For steps > 1, keep only integer values. + igood = (steps < 1) | (np.abs(steps - np.round(steps)) < 0.001) + steps = steps[igood] + + raw_step = ((_vmax - _vmin) / nbins) + if hasattr(self.axis, "axes") and self.axis.axes.name == '3d': + # Due to the change in automargin behavior in mpl3.9, we need to + # adjust the raw step to match the mpl3.8 appearance. The zoom + # factor of 2/48, gives us the 23/24 modifier. + raw_step = raw_step * 23/24 + large_steps = steps >= raw_step + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + # Classic round_numbers mode may require a larger step. + # Get first multiple of steps that are <= _vmin + floored_vmins = (_vmin // steps) * steps + floored_vmaxs = floored_vmins + steps * nbins + large_steps = large_steps & (floored_vmaxs >= _vmax) + + # Find index of smallest large step + if any(large_steps): + istep = np.nonzero(large_steps)[0][0] + else: + istep = len(steps) - 1 + + # Start at smallest of the steps greater than the raw step, and check + # if it provides enough ticks. If not, work backwards through + # smaller steps until one is found that provides enough ticks. + for step in steps[:istep+1][::-1]: + + if (self._integer and + np.floor(_vmax) - np.ceil(_vmin) >= self._min_n_ticks - 1): + step = max(1, step) + best_vmin = (_vmin // step) * step + + # Find tick locations spanning the vmin-vmax range, taking into + # account degradation of precision when there is a large offset. + # The edge ticks beyond vmin and/or vmax are needed for the + # "round_numbers" autolimit mode. + edge = _Edge_integer(step, offset) + low = edge.le(_vmin - best_vmin) + high = edge.ge(_vmax - best_vmin) + ticks = np.arange(low, high + 1) * step + best_vmin + # Count only the ticks that will be displayed. + nticks = ((ticks <= _vmax) & (ticks >= _vmin)).sum() + if nticks >= self._min_n_ticks: + break + return ticks + offset + + def __call__(self): + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + if self._symmetric: + vmax = max(abs(vmin), abs(vmax)) + vmin = -vmax + vmin, vmax = mtransforms.nonsingular( + vmin, vmax, expander=1e-13, tiny=1e-14) + locs = self._raw_ticks(vmin, vmax) + + prune = self._prune + if prune == 'lower': + locs = locs[1:] + elif prune == 'upper': + locs = locs[:-1] + elif prune == 'both': + locs = locs[1:-1] + return self.raise_if_exceeds(locs) + + def view_limits(self, dmin, dmax): + if self._symmetric: + dmax = max(abs(dmin), abs(dmax)) + dmin = -dmax + + dmin, dmax = mtransforms.nonsingular( + dmin, dmax, expander=1e-12, tiny=1e-13) + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + return self._raw_ticks(dmin, dmax)[[0, -1]] + else: + return dmin, dmax + + +def _is_decade(x, *, base=10, rtol=None): + """Return True if *x* is an integer power of *base*.""" + if not np.isfinite(x): + return False + if x == 0.0: + return True + lx = np.log(abs(x)) / np.log(base) + if rtol is None: + return np.isclose(lx, np.round(lx)) + else: + return np.isclose(lx, np.round(lx), rtol=rtol) + + +def _decade_less_equal(x, base): + """ + Return the largest integer power of *base* that's less or equal to *x*. + + If *x* is negative, the exponent will be *greater*. + """ + return (x if x == 0 else + -_decade_greater_equal(-x, base) if x < 0 else + base ** np.floor(np.log(x) / np.log(base))) + + +def _decade_greater_equal(x, base): + """ + Return the smallest integer power of *base* that's greater or equal to *x*. + + If *x* is negative, the exponent will be *smaller*. + """ + return (x if x == 0 else + -_decade_less_equal(-x, base) if x < 0 else + base ** np.ceil(np.log(x) / np.log(base))) + + +def _decade_less(x, base): + """ + Return the largest integer power of *base* that's less than *x*. + + If *x* is negative, the exponent will be *greater*. + """ + if x < 0: + return -_decade_greater(-x, base) + less = _decade_less_equal(x, base) + if less == x: + less /= base + return less + + +def _decade_greater(x, base): + """ + Return the smallest integer power of *base* that's greater than *x*. + + If *x* is negative, the exponent will be *smaller*. + """ + if x < 0: + return -_decade_less(-x, base) + greater = _decade_greater_equal(x, base) + if greater == x: + greater *= base + return greater + + +def _is_close_to_int(x): + return math.isclose(x, round(x)) + + +class LogLocator(Locator): + """ + Place logarithmically spaced ticks. + + Places ticks at the values ``subs[j] * base**i``. + """ + + @_api.delete_parameter("3.8", "numdecs") + def __init__(self, base=10.0, subs=(1.0,), numdecs=4, numticks=None): + """ + Parameters + ---------- + base : float, default: 10.0 + The base of the log used, so major ticks are placed at ``base**n``, where + ``n`` is an integer. + subs : None or {'auto', 'all'} or sequence of float, default: (1.0,) + Gives the multiples of integer powers of the base at which to place ticks. + The default of ``(1.0, )`` places ticks only at integer powers of the base. + Permitted string values are ``'auto'`` and ``'all'``. Both of these use an + algorithm based on the axis view limits to determine whether and how to put + ticks between integer powers of the base: + - ``'auto'``: Ticks are placed only between integer powers. + - ``'all'``: Ticks are placed between *and* at integer powers. + - ``None``: Equivalent to ``'auto'``. + numticks : None or int, default: None + The maximum number of ticks to allow on a given axis. The default of + ``None`` will try to choose intelligently as long as this Locator has + already been assigned to an axis using `~.axis.Axis.get_tick_space`, but + otherwise falls back to 9. + """ + if numticks is None: + if mpl.rcParams['_internal.classic_mode']: + numticks = 15 + else: + numticks = 'auto' + self._base = float(base) + self._set_subs(subs) + self._numdecs = numdecs + self.numticks = numticks + + @_api.delete_parameter("3.8", "numdecs") + def set_params(self, base=None, subs=None, numdecs=None, numticks=None): + """Set parameters within this locator.""" + if base is not None: + self._base = float(base) + if subs is not None: + self._set_subs(subs) + if numdecs is not None: + self._numdecs = numdecs + if numticks is not None: + self.numticks = numticks + + numdecs = _api.deprecate_privatize_attribute( + "3.8", addendum="This attribute has no effect.") + + def _set_subs(self, subs): + """ + Set the minor ticks for the log scaling every ``base**i*subs[j]``. + """ + if subs is None: # consistency with previous bad API + self._subs = 'auto' + elif isinstance(subs, str): + _api.check_in_list(('all', 'auto'), subs=subs) + self._subs = subs + else: + try: + self._subs = np.asarray(subs, dtype=float) + except ValueError as e: + raise ValueError("subs must be None, 'all', 'auto' or " + "a sequence of floats, not " + f"{subs}.") from e + if self._subs.ndim != 1: + raise ValueError("A sequence passed to subs must be " + "1-dimensional, not " + f"{self._subs.ndim}-dimensional.") + + def __call__(self): + """Return the locations of the ticks.""" + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + if self.numticks == 'auto': + if self.axis is not None: + numticks = np.clip(self.axis.get_tick_space(), 2, 9) + else: + numticks = 9 + else: + numticks = self.numticks + + b = self._base + if vmin <= 0.0: + if self.axis is not None: + vmin = self.axis.get_minpos() + + if vmin <= 0.0 or not np.isfinite(vmin): + raise ValueError( + "Data has no positive values, and therefore cannot be log-scaled.") + + _log.debug('vmin %s vmax %s', vmin, vmax) + + if vmax < vmin: + vmin, vmax = vmax, vmin + log_vmin = math.log(vmin) / math.log(b) + log_vmax = math.log(vmax) / math.log(b) + + numdec = math.floor(log_vmax) - math.ceil(log_vmin) + + if isinstance(self._subs, str): + if numdec > 10 or b < 3: + if self._subs == 'auto': + return np.array([]) # no minor or major ticks + else: + subs = np.array([1.0]) # major ticks + else: + _first = 2.0 if self._subs == 'auto' else 1.0 + subs = np.arange(_first, b) + else: + subs = self._subs + + # Get decades between major ticks. + stride = (max(math.ceil(numdec / (numticks - 1)), 1) + if mpl.rcParams['_internal.classic_mode'] else + numdec // numticks + 1) + + # if we have decided that the stride is as big or bigger than + # the range, clip the stride back to the available range - 1 + # with a floor of 1. This prevents getting axis with only 1 tick + # visible. + if stride >= numdec: + stride = max(1, numdec - 1) + + # Does subs include anything other than 1? Essentially a hack to know + # whether we're a major or a minor locator. + have_subs = len(subs) > 1 or (len(subs) == 1 and subs[0] != 1.0) + + decades = np.arange(math.floor(log_vmin) - stride, + math.ceil(log_vmax) + 2 * stride, stride) + + if have_subs: + if stride == 1: + ticklocs = np.concatenate( + [subs * decade_start for decade_start in b ** decades]) + else: + ticklocs = np.array([]) + else: + ticklocs = b ** decades + + _log.debug('ticklocs %r', ticklocs) + if (len(subs) > 1 + and stride == 1 + and ((vmin <= ticklocs) & (ticklocs <= vmax)).sum() <= 1): + # If we're a minor locator *that expects at least two ticks per + # decade* and the major locator stride is 1 and there's no more + # than one minor tick, switch to AutoLocator. + return AutoLocator().tick_values(vmin, vmax) + else: + return self.raise_if_exceeds(ticklocs) + + def view_limits(self, vmin, vmax): + """Try to choose the view limits intelligently.""" + b = self._base + + vmin, vmax = self.nonsingular(vmin, vmax) + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + vmin = _decade_less_equal(vmin, b) + vmax = _decade_greater_equal(vmax, b) + + return vmin, vmax + + def nonsingular(self, vmin, vmax): + if vmin > vmax: + vmin, vmax = vmax, vmin + if not np.isfinite(vmin) or not np.isfinite(vmax): + vmin, vmax = 1, 10 # Initial range, no data plotted yet. + elif vmax <= 0: + _api.warn_external( + "Data has no positive values, and therefore cannot be " + "log-scaled.") + vmin, vmax = 1, 10 + else: + # Consider shared axises + minpos = min(axis.get_minpos() for axis in self.axis._get_shared_axis()) + if not np.isfinite(minpos): + minpos = 1e-300 # This should never take effect. + if vmin <= 0: + vmin = minpos + if vmin == vmax: + vmin = _decade_less(vmin, self._base) + vmax = _decade_greater(vmax, self._base) + return vmin, vmax + + +class SymmetricalLogLocator(Locator): + """ + Place ticks spaced linearly near zero and spaced logarithmically beyond a threshold. + """ + + def __init__(self, transform=None, subs=None, linthresh=None, base=None): + """ + Parameters + ---------- + transform : `~.scale.SymmetricalLogTransform`, optional + If set, defines the *base* and *linthresh* of the symlog transform. + base, linthresh : float, optional + The *base* and *linthresh* of the symlog transform, as documented + for `.SymmetricalLogScale`. These parameters are only used if + *transform* is not set. + subs : sequence of float, default: [1] + The multiples of integer powers of the base where ticks are placed, + i.e., ticks are placed at + ``[sub * base**i for i in ... for sub in subs]``. + + Notes + ----- + Either *transform*, or both *base* and *linthresh*, must be given. + """ + if transform is not None: + self._base = transform.base + self._linthresh = transform.linthresh + elif linthresh is not None and base is not None: + self._base = base + self._linthresh = linthresh + else: + raise ValueError("Either transform, or both linthresh " + "and base, must be provided.") + if subs is None: + self._subs = [1.0] + else: + self._subs = subs + self.numticks = 15 + + def set_params(self, subs=None, numticks=None): + """Set parameters within this locator.""" + if numticks is not None: + self.numticks = numticks + if subs is not None: + self._subs = subs + + def __call__(self): + """Return the locations of the ticks.""" + # Note, these are untransformed coordinates + vmin, vmax = self.axis.get_view_interval() + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + linthresh = self._linthresh + + if vmax < vmin: + vmin, vmax = vmax, vmin + + # The domain is divided into three sections, only some of + # which may actually be present. + # + # <======== -t ==0== t ========> + # aaaaaaaaa bbbbb ccccccccc + # + # a) and c) will have ticks at integral log positions. The + # number of ticks needs to be reduced if there are more + # than self.numticks of them. + # + # b) has a tick at 0 and only 0 (we assume t is a small + # number, and the linear segment is just an implementation + # detail and not interesting.) + # + # We could also add ticks at t, but that seems to usually be + # uninteresting. + # + # "simple" mode is when the range falls entirely within [-t, t] + # -- it should just display (vmin, 0, vmax) + if -linthresh <= vmin < vmax <= linthresh: + # only the linear range is present + return sorted({vmin, 0, vmax}) + + # Lower log range is present + has_a = (vmin < -linthresh) + # Upper log range is present + has_c = (vmax > linthresh) + + # Check if linear range is present + has_b = (has_a and vmax > -linthresh) or (has_c and vmin < linthresh) + + base = self._base + + def get_log_range(lo, hi): + lo = np.floor(np.log(lo) / np.log(base)) + hi = np.ceil(np.log(hi) / np.log(base)) + return lo, hi + + # Calculate all the ranges, so we can determine striding + a_lo, a_hi = (0, 0) + if has_a: + a_upper_lim = min(-linthresh, vmax) + a_lo, a_hi = get_log_range(abs(a_upper_lim), abs(vmin) + 1) + + c_lo, c_hi = (0, 0) + if has_c: + c_lower_lim = max(linthresh, vmin) + c_lo, c_hi = get_log_range(c_lower_lim, vmax + 1) + + # Calculate the total number of integer exponents in a and c ranges + total_ticks = (a_hi - a_lo) + (c_hi - c_lo) + if has_b: + total_ticks += 1 + stride = max(total_ticks // (self.numticks - 1), 1) + + decades = [] + if has_a: + decades.extend(-1 * (base ** (np.arange(a_lo, a_hi, + stride)[::-1]))) + + if has_b: + decades.append(0.0) + + if has_c: + decades.extend(base ** (np.arange(c_lo, c_hi, stride))) + + subs = np.asarray(self._subs) + + if len(subs) > 1 or subs[0] != 1.0: + ticklocs = [] + for decade in decades: + if decade == 0: + ticklocs.append(decade) + else: + ticklocs.extend(subs * decade) + else: + ticklocs = decades + + return self.raise_if_exceeds(np.array(ticklocs)) + + def view_limits(self, vmin, vmax): + """Try to choose the view limits intelligently.""" + b = self._base + if vmax < vmin: + vmin, vmax = vmax, vmin + + if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': + vmin = _decade_less_equal(vmin, b) + vmax = _decade_greater_equal(vmax, b) + if vmin == vmax: + vmin = _decade_less(vmin, b) + vmax = _decade_greater(vmax, b) + + return mtransforms.nonsingular(vmin, vmax) + + +class AsinhLocator(Locator): + """ + Place ticks spaced evenly on an inverse-sinh scale. + + Generally used with the `~.scale.AsinhScale` class. + + .. note:: + + This API is provisional and may be revised in the future + based on early user feedback. + """ + def __init__(self, linear_width, numticks=11, symthresh=0.2, + base=10, subs=None): + """ + Parameters + ---------- + linear_width : float + The scale parameter defining the extent + of the quasi-linear region. + numticks : int, default: 11 + The approximate number of major ticks that will fit + along the entire axis + symthresh : float, default: 0.2 + The fractional threshold beneath which data which covers + a range that is approximately symmetric about zero + will have ticks that are exactly symmetric. + 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 : tuple, default: None + Multiples of the number base, typically used + for the minor ticks, e.g. (2, 5) when base=10. + """ + super().__init__() + self.linear_width = linear_width + self.numticks = numticks + self.symthresh = symthresh + self.base = base + self.subs = subs + + def set_params(self, numticks=None, symthresh=None, + base=None, subs=None): + """Set parameters within this locator.""" + if numticks is not None: + self.numticks = numticks + if symthresh is not None: + self.symthresh = symthresh + if base is not None: + self.base = base + if subs is not None: + self.subs = subs if len(subs) > 0 else None + + def __call__(self): + vmin, vmax = self.axis.get_view_interval() + if (vmin * vmax) < 0 and abs(1 + vmax / vmin) < self.symthresh: + # Data-range appears to be almost symmetric, so round up: + bound = max(abs(vmin), abs(vmax)) + return self.tick_values(-bound, bound) + else: + return self.tick_values(vmin, vmax) + + def tick_values(self, vmin, vmax): + # Construct a set of uniformly-spaced "on-screen" locations. + ymin, ymax = self.linear_width * np.arcsinh(np.array([vmin, vmax]) + / self.linear_width) + ys = np.linspace(ymin, ymax, self.numticks) + zero_dev = abs(ys / (ymax - ymin)) + if ymin * ymax < 0: + # Ensure that the zero tick-mark is included, if the axis straddles zero. + ys = np.hstack([ys[(zero_dev > 0.5 / self.numticks)], 0.0]) + + # Transform the "on-screen" grid to the data space: + xs = self.linear_width * np.sinh(ys / self.linear_width) + zero_xs = (ys == 0) + + # Round the data-space values to be intuitive base-n numbers, keeping track of + # positive and negative values separately and carefully treating the zero value. + with np.errstate(divide="ignore"): # base ** log(0) = base ** -inf = 0. + if self.base > 1: + pows = (np.sign(xs) + * self.base ** np.floor(np.log(abs(xs)) / math.log(self.base))) + qs = np.outer(pows, self.subs).flatten() if self.subs else pows + else: # No need to adjust sign(pows), as it cancels out when computing qs. + pows = np.where(zero_xs, 1, 10**np.floor(np.log10(abs(xs)))) + qs = pows * np.round(xs / pows) + ticks = np.array(sorted(set(qs))) + + return ticks if len(ticks) >= 2 else np.linspace(vmin, vmax, self.numticks) + + +class LogitLocator(MaxNLocator): + """ + Place ticks spaced evenly on a logit scale. + """ + + def __init__(self, minor=False, *, nbins="auto"): + """ + Parameters + ---------- + nbins : int or 'auto', optional + Number of ticks. Only used if minor is False. + minor : bool, default: False + Indicate if this locator is for minor ticks or not. + """ + + self._minor = minor + super().__init__(nbins=nbins, steps=[1, 2, 5, 10]) + + def set_params(self, minor=None, **kwargs): + """Set parameters within this locator.""" + if minor is not None: + self._minor = minor + super().set_params(**kwargs) + + @property + def minor(self): + return self._minor + + @minor.setter + def minor(self, value): + self.set_params(minor=value) + + def tick_values(self, vmin, vmax): + # dummy axis has no axes attribute + if hasattr(self.axis, "axes") and self.axis.axes.name == "polar": + raise NotImplementedError("Polar axis cannot be logit scaled yet") + + if self._nbins == "auto": + if self.axis is not None: + nbins = self.axis.get_tick_space() + if nbins < 2: + nbins = 2 + else: + nbins = 9 + else: + nbins = self._nbins + + # We define ideal ticks with their index: + # linscale: ... 1e-3 1e-2 1e-1 1/2 1-1e-1 1-1e-2 1-1e-3 ... + # b-scale : ... -3 -2 -1 0 1 2 3 ... + def ideal_ticks(x): + return 10 ** x if x < 0 else 1 - (10 ** (-x)) if x > 0 else 0.5 + + vmin, vmax = self.nonsingular(vmin, vmax) + binf = int( + np.floor(np.log10(vmin)) + if vmin < 0.5 + else 0 + if vmin < 0.9 + else -np.ceil(np.log10(1 - vmin)) + ) + bsup = int( + np.ceil(np.log10(vmax)) + if vmax <= 0.5 + else 1 + if vmax <= 0.9 + else -np.floor(np.log10(1 - vmax)) + ) + numideal = bsup - binf - 1 + if numideal >= 2: + # have 2 or more wanted ideal ticks, so use them as major ticks + if numideal > nbins: + # to many ideal ticks, subsampling ideals for major ticks, and + # take others for minor ticks + subsampling_factor = math.ceil(numideal / nbins) + if self._minor: + ticklocs = [ + ideal_ticks(b) + for b in range(binf, bsup + 1) + if (b % subsampling_factor) != 0 + ] + else: + ticklocs = [ + ideal_ticks(b) + for b in range(binf, bsup + 1) + if (b % subsampling_factor) == 0 + ] + return self.raise_if_exceeds(np.array(ticklocs)) + if self._minor: + ticklocs = [] + for b in range(binf, bsup): + if b < -1: + ticklocs.extend(np.arange(2, 10) * 10 ** b) + elif b == -1: + ticklocs.extend(np.arange(2, 5) / 10) + elif b == 0: + ticklocs.extend(np.arange(6, 9) / 10) + else: + ticklocs.extend( + 1 - np.arange(2, 10)[::-1] * 10 ** (-b - 1) + ) + return self.raise_if_exceeds(np.array(ticklocs)) + ticklocs = [ideal_ticks(b) for b in range(binf, bsup + 1)] + return self.raise_if_exceeds(np.array(ticklocs)) + # the scale is zoomed so same ticks as linear scale can be used + if self._minor: + return [] + return super().tick_values(vmin, vmax) + + def nonsingular(self, vmin, vmax): + standard_minpos = 1e-7 + initial_range = (standard_minpos, 1 - standard_minpos) + if vmin > vmax: + vmin, vmax = vmax, vmin + if not np.isfinite(vmin) or not np.isfinite(vmax): + vmin, vmax = initial_range # Initial range, no data plotted yet. + elif vmax <= 0 or vmin >= 1: + # vmax <= 0 occurs when all values are negative + # vmin >= 1 occurs when all values are greater than one + _api.warn_external( + "Data has no values between 0 and 1, and therefore cannot be " + "logit-scaled." + ) + vmin, vmax = initial_range + else: + minpos = ( + self.axis.get_minpos() + if self.axis is not None + else standard_minpos + ) + if not np.isfinite(minpos): + minpos = standard_minpos # This should never take effect. + if vmin <= 0: + vmin = minpos + # NOTE: for vmax, we should query a property similar to get_minpos, + # but related to the maximal, less-than-one data point. + # Unfortunately, Bbox._minpos is defined very deep in the BBox and + # updated with data, so for now we use 1 - minpos as a substitute. + if vmax >= 1: + vmax = 1 - minpos + if vmin == vmax: + vmin, vmax = 0.1 * vmin, 1 - 0.1 * vmin + + return vmin, vmax + + +class AutoLocator(MaxNLocator): + """ + Place evenly spaced ticks, with the step size and maximum number of ticks chosen + automatically. + + This is a subclass of `~matplotlib.ticker.MaxNLocator`, with parameters + *nbins = 'auto'* and *steps = [1, 2, 2.5, 5, 10]*. + """ + def __init__(self): + """ + To know the values of the non-public parameters, please have a + look to the defaults of `~matplotlib.ticker.MaxNLocator`. + """ + if mpl.rcParams['_internal.classic_mode']: + nbins = 9 + steps = [1, 2, 5, 10] + else: + nbins = 'auto' + steps = [1, 2, 2.5, 5, 10] + super().__init__(nbins=nbins, steps=steps) + + +class AutoMinorLocator(Locator): + """ + Place evenly spaced minor ticks, with the step size and maximum number of ticks + chosen automatically. + + The Axis scale must be linear with evenly spaced major ticks . + """ + + def __init__(self, n=None): + """ + *n* is the number of subdivisions of the interval between + major ticks; e.g., n=2 will place a single minor tick midway + between major ticks. + + If *n* is omitted or None, the value stored in rcParams will be used. + In case *n* is set to 'auto', it will be set to 4 or 5. If the distance + between the major ticks equals 1, 2.5, 5 or 10 it can be perfectly + divided in 5 equidistant sub-intervals with a length multiple of + 0.05. Otherwise it is divided in 4 sub-intervals. + """ + self.ndivs = n + + def __call__(self): + # docstring inherited + if self.axis.get_scale() == 'log': + _api.warn_external('AutoMinorLocator does not work on logarithmic scales') + return [] + + majorlocs = np.unique(self.axis.get_majorticklocs()) + if len(majorlocs) < 2: + # Need at least two major ticks to find minor tick locations. + # TODO: Figure out a way to still be able to display minor ticks with less + # than two major ticks visible. For now, just display no ticks at all. + return [] + majorstep = majorlocs[1] - majorlocs[0] + + if self.ndivs is None: + self.ndivs = mpl.rcParams[ + 'ytick.minor.ndivs' if self.axis.axis_name == 'y' + else 'xtick.minor.ndivs'] # for x and z axis + + if self.ndivs == 'auto': + majorstep_mantissa = 10 ** (np.log10(majorstep) % 1) + ndivs = 5 if np.isclose(majorstep_mantissa, [1, 2.5, 5, 10]).any() else 4 + else: + ndivs = self.ndivs + + minorstep = majorstep / ndivs + + vmin, vmax = sorted(self.axis.get_view_interval()) + t0 = majorlocs[0] + tmin = round((vmin - t0) / minorstep) + tmax = round((vmax - t0) / minorstep) + 1 + locs = (np.arange(tmin, tmax) * minorstep) + t0 + + return self.raise_if_exceeds(locs) + + def tick_values(self, vmin, vmax): + raise NotImplementedError( + f"Cannot get tick locations for a {type(self).__name__}") diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/transforms.py b/llava_next/lib/python3.10/site-packages/matplotlib/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..3575bd1fc14d7d64cbb2e38fccc682b59eeeac82 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/transforms.py @@ -0,0 +1,2992 @@ +""" +Matplotlib includes a framework for arbitrary geometric +transformations that is used determine the final position of all +elements drawn on the canvas. + +Transforms are composed into trees of `TransformNode` objects +whose actual value depends on their children. When the contents of +children change, their parents are automatically invalidated. The +next time an invalidated transform is accessed, it is recomputed to +reflect those changes. This invalidation/caching approach prevents +unnecessary recomputations of transforms, and contributes to better +interactive performance. + +For example, here is a graph of the transform tree used to plot data +to the graph: + +.. image:: ../_static/transforms.png + +The framework can be used for both affine and non-affine +transformations. However, for speed, we want to use the backend +renderers to perform affine transformations whenever possible. +Therefore, it is possible to perform just the affine or non-affine +part of a transformation on a set of data. The affine is always +assumed to occur after the non-affine. For any transform:: + + full transform == non-affine part + affine part + +The backends are not expected to handle non-affine transformations +themselves. + +See the tutorial :ref:`transforms_tutorial` for examples +of how to use transforms. +""" + +# Note: There are a number of places in the code where we use `np.min` or +# `np.minimum` instead of the builtin `min`, and likewise for `max`. This is +# done so that `nan`s are propagated, instead of being silently dropped. + +import copy +import functools +import textwrap +import weakref +import math + +import numpy as np +from numpy.linalg import inv + +from matplotlib import _api +from matplotlib._path import ( + affine_transform, count_bboxes_overlapping_bbox, update_path_extents) +from .path import Path + +DEBUG = False + + +def _make_str_method(*args, **kwargs): + """ + Generate a ``__str__`` method for a `.Transform` subclass. + + After :: + + class T: + __str__ = _make_str_method("attr", key="other") + + ``str(T(...))`` will be + + .. code-block:: text + + {type(T).__name__}( + {self.attr}, + key={self.other}) + """ + indent = functools.partial(textwrap.indent, prefix=" " * 4) + def strrepr(x): return repr(x) if isinstance(x, str) else str(x) + return lambda self: ( + type(self).__name__ + "(" + + ",".join([*(indent("\n" + strrepr(getattr(self, arg))) + for arg in args), + *(indent("\n" + k + "=" + strrepr(getattr(self, arg))) + for k, arg in kwargs.items())]) + + ")") + + +class TransformNode: + """ + The base class for anything that participates in the transform tree + and needs to invalidate its parents or be invalidated. This includes + classes that are not really transforms, such as bounding boxes, since some + transforms depend on bounding boxes to compute their values. + """ + + # Invalidation may affect only the affine part. If the + # invalidation was "affine-only", the _invalid member is set to + # INVALID_AFFINE_ONLY + INVALID_NON_AFFINE = _api.deprecated("3.8")(_api.classproperty(lambda cls: 1)) + INVALID_AFFINE = _api.deprecated("3.8")(_api.classproperty(lambda cls: 2)) + INVALID = _api.deprecated("3.8")(_api.classproperty(lambda cls: 3)) + + # Possible values for the _invalid attribute. + _VALID, _INVALID_AFFINE_ONLY, _INVALID_FULL = range(3) + + # Some metadata about the transform, used to determine whether an + # invalidation is affine-only + is_affine = False + is_bbox = _api.deprecated("3.9")(_api.classproperty(lambda cls: False)) + + pass_through = False + """ + If pass_through is True, all ancestors will always be + invalidated, even if 'self' is already invalid. + """ + + def __init__(self, shorthand_name=None): + """ + Parameters + ---------- + shorthand_name : str + A string representing the "name" of the transform. The name carries + no significance other than to improve the readability of + ``str(transform)`` when DEBUG=True. + """ + self._parents = {} + # Initially invalid, until first computation. + self._invalid = self._INVALID_FULL + self._shorthand_name = shorthand_name or '' + + if DEBUG: + def __str__(self): + # either just return the name of this TransformNode, or its repr + return self._shorthand_name or repr(self) + + def __getstate__(self): + # turn the dictionary with weak values into a normal dictionary + return {**self.__dict__, + '_parents': {k: v() for k, v in self._parents.items()}} + + def __setstate__(self, data_dict): + self.__dict__ = data_dict + # turn the normal dictionary back into a dictionary with weak values + # The extra lambda is to provide a callback to remove dead + # weakrefs from the dictionary when garbage collection is done. + self._parents = { + k: weakref.ref(v, lambda _, pop=self._parents.pop, k=k: pop(k)) + for k, v in self._parents.items() if v is not None} + + def __copy__(self): + other = copy.copy(super()) + # If `c = a + b; a1 = copy(a)`, then modifications to `a1` do not + # propagate back to `c`, i.e. we need to clear the parents of `a1`. + other._parents = {} + # If `c = a + b; c1 = copy(c)`, then modifications to `a` also need to + # be propagated to `c1`. + for key, val in vars(self).items(): + if isinstance(val, TransformNode) and id(self) in val._parents: + other.set_children(val) # val == getattr(other, key) + return other + + def invalidate(self): + """ + Invalidate this `TransformNode` and triggers an invalidation of its + ancestors. Should be called any time the transform changes. + """ + return self._invalidate_internal( + level=self._INVALID_AFFINE_ONLY if self.is_affine else self._INVALID_FULL, + invalidating_node=self) + + def _invalidate_internal(self, level, invalidating_node): + """ + Called by :meth:`invalidate` and subsequently ascends the transform + stack calling each TransformNode's _invalidate_internal method. + """ + # If we are already more invalid than the currently propagated invalidation, + # then we don't need to do anything. + if level <= self._invalid and not self.pass_through: + return + self._invalid = level + for parent in list(self._parents.values()): + parent = parent() # Dereference the weak reference. + if parent is not None: + parent._invalidate_internal(level=level, invalidating_node=self) + + def set_children(self, *children): + """ + Set the children of the transform, to let the invalidation + system know which transforms can invalidate this transform. + Should be called from the constructor of any transforms that + depend on other transforms. + """ + # Parents are stored as weak references, so that if the + # parents are destroyed, references from the children won't + # keep them alive. + id_self = id(self) + for child in children: + # Use weak references so this dictionary won't keep obsolete nodes + # alive; the callback deletes the dictionary entry. This is a + # performance improvement over using WeakValueDictionary. + ref = weakref.ref( + self, lambda _, pop=child._parents.pop, k=id_self: pop(k)) + child._parents[id_self] = ref + + def frozen(self): + """ + Return a frozen copy of this transform node. The frozen copy will not + be updated when its children change. Useful for storing a previously + known state of a transform where ``copy.deepcopy()`` might normally be + used. + """ + return self + + +class BboxBase(TransformNode): + """ + The base class of all bounding boxes. + + This class is immutable; `Bbox` is a mutable subclass. + + The canonical representation is as two points, with no + restrictions on their ordering. Convenience properties are + provided to get the left, bottom, right and top edges and width + and height, but these are not stored explicitly. + """ + + is_bbox = _api.deprecated("3.9")(_api.classproperty(lambda cls: True)) + is_affine = True + + if DEBUG: + @staticmethod + def _check(points): + if isinstance(points, np.ma.MaskedArray): + _api.warn_external("Bbox bounds are a masked array.") + points = np.asarray(points) + if any((points[1, :] - points[0, :]) == 0): + _api.warn_external("Singular Bbox.") + + def frozen(self): + return Bbox(self.get_points().copy()) + frozen.__doc__ = TransformNode.__doc__ + + def __array__(self, *args, **kwargs): + return self.get_points() + + @property + def x0(self): + """ + The first of the pair of *x* coordinates that define the bounding box. + + This is not guaranteed to be less than :attr:`x1` (for that, use + :attr:`xmin`). + """ + return self.get_points()[0, 0] + + @property + def y0(self): + """ + The first of the pair of *y* coordinates that define the bounding box. + + This is not guaranteed to be less than :attr:`y1` (for that, use + :attr:`ymin`). + """ + return self.get_points()[0, 1] + + @property + def x1(self): + """ + The second of the pair of *x* coordinates that define the bounding box. + + This is not guaranteed to be greater than :attr:`x0` (for that, use + :attr:`xmax`). + """ + return self.get_points()[1, 0] + + @property + def y1(self): + """ + The second of the pair of *y* coordinates that define the bounding box. + + This is not guaranteed to be greater than :attr:`y0` (for that, use + :attr:`ymax`). + """ + return self.get_points()[1, 1] + + @property + def p0(self): + """ + The first pair of (*x*, *y*) coordinates that define the bounding box. + + This is not guaranteed to be the bottom-left corner (for that, use + :attr:`min`). + """ + return self.get_points()[0] + + @property + def p1(self): + """ + The second pair of (*x*, *y*) coordinates that define the bounding box. + + This is not guaranteed to be the top-right corner (for that, use + :attr:`max`). + """ + return self.get_points()[1] + + @property + def xmin(self): + """The left edge of the bounding box.""" + return np.min(self.get_points()[:, 0]) + + @property + def ymin(self): + """The bottom edge of the bounding box.""" + return np.min(self.get_points()[:, 1]) + + @property + def xmax(self): + """The right edge of the bounding box.""" + return np.max(self.get_points()[:, 0]) + + @property + def ymax(self): + """The top edge of the bounding box.""" + return np.max(self.get_points()[:, 1]) + + @property + def min(self): + """The bottom-left corner of the bounding box.""" + return np.min(self.get_points(), axis=0) + + @property + def max(self): + """The top-right corner of the bounding box.""" + return np.max(self.get_points(), axis=0) + + @property + def intervalx(self): + """ + The pair of *x* coordinates that define the bounding box. + + This is not guaranteed to be sorted from left to right. + """ + return self.get_points()[:, 0] + + @property + def intervaly(self): + """ + The pair of *y* coordinates that define the bounding box. + + This is not guaranteed to be sorted from bottom to top. + """ + return self.get_points()[:, 1] + + @property + def width(self): + """The (signed) width of the bounding box.""" + points = self.get_points() + return points[1, 0] - points[0, 0] + + @property + def height(self): + """The (signed) height of the bounding box.""" + points = self.get_points() + return points[1, 1] - points[0, 1] + + @property + def size(self): + """The (signed) width and height of the bounding box.""" + points = self.get_points() + return points[1] - points[0] + + @property + def bounds(self): + """Return (:attr:`x0`, :attr:`y0`, :attr:`width`, :attr:`height`).""" + (x0, y0), (x1, y1) = self.get_points() + return (x0, y0, x1 - x0, y1 - y0) + + @property + def extents(self): + """Return (:attr:`x0`, :attr:`y0`, :attr:`x1`, :attr:`y1`).""" + return self.get_points().flatten() # flatten returns a copy. + + def get_points(self): + raise NotImplementedError + + def containsx(self, x): + """ + Return whether *x* is in the closed (:attr:`x0`, :attr:`x1`) interval. + """ + x0, x1 = self.intervalx + return x0 <= x <= x1 or x0 >= x >= x1 + + def containsy(self, y): + """ + Return whether *y* is in the closed (:attr:`y0`, :attr:`y1`) interval. + """ + y0, y1 = self.intervaly + return y0 <= y <= y1 or y0 >= y >= y1 + + def contains(self, x, y): + """ + Return whether ``(x, y)`` is in the bounding box or on its edge. + """ + return self.containsx(x) and self.containsy(y) + + def overlaps(self, other): + """ + Return whether this bounding box overlaps with the other bounding box. + + Parameters + ---------- + other : `.BboxBase` + """ + ax1, ay1, ax2, ay2 = self.extents + bx1, by1, bx2, by2 = other.extents + if ax2 < ax1: + ax2, ax1 = ax1, ax2 + if ay2 < ay1: + ay2, ay1 = ay1, ay2 + if bx2 < bx1: + bx2, bx1 = bx1, bx2 + if by2 < by1: + by2, by1 = by1, by2 + return ax1 <= bx2 and bx1 <= ax2 and ay1 <= by2 and by1 <= ay2 + + def fully_containsx(self, x): + """ + Return whether *x* is in the open (:attr:`x0`, :attr:`x1`) interval. + """ + x0, x1 = self.intervalx + return x0 < x < x1 or x0 > x > x1 + + def fully_containsy(self, y): + """ + Return whether *y* is in the open (:attr:`y0`, :attr:`y1`) interval. + """ + y0, y1 = self.intervaly + return y0 < y < y1 or y0 > y > y1 + + def fully_contains(self, x, y): + """ + Return whether ``x, y`` is in the bounding box, but not on its edge. + """ + return self.fully_containsx(x) and self.fully_containsy(y) + + def fully_overlaps(self, other): + """ + Return whether this bounding box overlaps with the other bounding box, + not including the edges. + + Parameters + ---------- + other : `.BboxBase` + """ + ax1, ay1, ax2, ay2 = self.extents + bx1, by1, bx2, by2 = other.extents + if ax2 < ax1: + ax2, ax1 = ax1, ax2 + if ay2 < ay1: + ay2, ay1 = ay1, ay2 + if bx2 < bx1: + bx2, bx1 = bx1, bx2 + if by2 < by1: + by2, by1 = by1, by2 + return ax1 < bx2 and bx1 < ax2 and ay1 < by2 and by1 < ay2 + + def transformed(self, transform): + """ + Construct a `Bbox` by statically transforming this one by *transform*. + """ + pts = self.get_points() + ll, ul, lr = transform.transform(np.array( + [pts[0], [pts[0, 0], pts[1, 1]], [pts[1, 0], pts[0, 1]]])) + return Bbox([ll, [lr[0], ul[1]]]) + + coefs = {'C': (0.5, 0.5), + 'SW': (0, 0), + 'S': (0.5, 0), + 'SE': (1.0, 0), + 'E': (1.0, 0.5), + 'NE': (1.0, 1.0), + 'N': (0.5, 1.0), + 'NW': (0, 1.0), + 'W': (0, 0.5)} + + def anchored(self, c, container=None): + """ + Return a copy of the `Bbox` anchored to *c* within *container*. + + Parameters + ---------- + c : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} + Either an (*x*, *y*) pair of relative coordinates (0 is left or + bottom, 1 is right or top), 'C' (center), or a cardinal direction + ('SW', southwest, is bottom left, etc.). + container : `Bbox`, optional + The box within which the `Bbox` is positioned. + + See Also + -------- + .Axes.set_anchor + """ + if container is None: + _api.warn_deprecated( + "3.8", message="Calling anchored() with no container bbox " + "returns a frozen copy of the original bbox and is deprecated " + "since %(since)s.") + container = self + l, b, w, h = container.bounds + L, B, W, H = self.bounds + cx, cy = self.coefs[c] if isinstance(c, str) else c + return Bbox(self._points + + [(l + cx * (w - W)) - L, + (b + cy * (h - H)) - B]) + + def shrunk(self, mx, my): + """ + Return a copy of the `Bbox`, shrunk by the factor *mx* + in the *x* direction and the factor *my* in the *y* direction. + The lower left corner of the box remains unchanged. Normally + *mx* and *my* will be less than 1, but this is not enforced. + """ + w, h = self.size + return Bbox([self._points[0], + self._points[0] + [mx * w, my * h]]) + + def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0): + """ + Return a copy of the `Bbox`, shrunk so that it is as + large as it can be while having the desired aspect ratio, + *box_aspect*. If the box coordinates are relative (i.e. + fractions of a larger box such as a figure) then the + physical aspect ratio of that figure is specified with + *fig_aspect*, so that *box_aspect* can also be given as a + ratio of the absolute dimensions, not the relative dimensions. + """ + if box_aspect <= 0 or fig_aspect <= 0: + raise ValueError("'box_aspect' and 'fig_aspect' must be positive") + if container is None: + container = self + w, h = container.size + H = w * box_aspect / fig_aspect + if H <= h: + W = w + else: + W = h * fig_aspect / box_aspect + H = h + return Bbox([self._points[0], + self._points[0] + (W, H)]) + + def splitx(self, *args): + """ + Return a list of new `Bbox` objects formed by splitting the original + one with vertical lines at fractional positions given by *args*. + """ + xf = [0, *args, 1] + x0, y0, x1, y1 = self.extents + w = x1 - x0 + return [Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]]) + for xf0, xf1 in zip(xf[:-1], xf[1:])] + + def splity(self, *args): + """ + Return a list of new `Bbox` objects formed by splitting the original + one with horizontal lines at fractional positions given by *args*. + """ + yf = [0, *args, 1] + x0, y0, x1, y1 = self.extents + h = y1 - y0 + return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]]) + for yf0, yf1 in zip(yf[:-1], yf[1:])] + + def count_contains(self, vertices): + """ + Count the number of vertices contained in the `Bbox`. + Any vertices with a non-finite x or y value are ignored. + + Parameters + ---------- + vertices : (N, 2) array + """ + if len(vertices) == 0: + return 0 + vertices = np.asarray(vertices) + with np.errstate(invalid='ignore'): + return (((self.min < vertices) & + (vertices < self.max)).all(axis=1).sum()) + + def count_overlaps(self, bboxes): + """ + Count the number of bounding boxes that overlap this one. + + Parameters + ---------- + bboxes : sequence of `.BboxBase` + """ + return count_bboxes_overlapping_bbox( + self, np.atleast_3d([np.array(x) for x in bboxes])) + + def expanded(self, sw, sh): + """ + Construct a `Bbox` by expanding this one around its center by the + factors *sw* and *sh*. + """ + width = self.width + height = self.height + deltaw = (sw * width - width) / 2.0 + deltah = (sh * height - height) / 2.0 + a = np.array([[-deltaw, -deltah], [deltaw, deltah]]) + return Bbox(self._points + a) + + @_api.rename_parameter("3.8", "p", "w_pad") + def padded(self, w_pad, h_pad=None): + """ + Construct a `Bbox` by padding this one on all four sides. + + Parameters + ---------- + w_pad : float + Width pad + h_pad : float, optional + Height pad. Defaults to *w_pad*. + + """ + points = self.get_points() + if h_pad is None: + h_pad = w_pad + return Bbox(points + [[-w_pad, -h_pad], [w_pad, h_pad]]) + + def translated(self, tx, ty): + """Construct a `Bbox` by translating this one by *tx* and *ty*.""" + return Bbox(self._points + (tx, ty)) + + def corners(self): + """ + Return the corners of this rectangle as an array of points. + + Specifically, this returns the array + ``[[x0, y0], [x0, y1], [x1, y0], [x1, y1]]``. + """ + (x0, y0), (x1, y1) = self.get_points() + return np.array([[x0, y0], [x0, y1], [x1, y0], [x1, y1]]) + + def rotated(self, radians): + """ + Return the axes-aligned bounding box that bounds the result of rotating + this `Bbox` by an angle of *radians*. + """ + corners = self.corners() + corners_rotated = Affine2D().rotate(radians).transform(corners) + bbox = Bbox.unit() + bbox.update_from_data_xy(corners_rotated, ignore=True) + return bbox + + @staticmethod + def union(bboxes): + """Return a `Bbox` that contains all of the given *bboxes*.""" + if not len(bboxes): + raise ValueError("'bboxes' cannot be empty") + x0 = np.min([bbox.xmin for bbox in bboxes]) + x1 = np.max([bbox.xmax for bbox in bboxes]) + y0 = np.min([bbox.ymin for bbox in bboxes]) + y1 = np.max([bbox.ymax for bbox in bboxes]) + return Bbox([[x0, y0], [x1, y1]]) + + @staticmethod + def intersection(bbox1, bbox2): + """ + Return the intersection of *bbox1* and *bbox2* if they intersect, or + None if they don't. + """ + x0 = np.maximum(bbox1.xmin, bbox2.xmin) + x1 = np.minimum(bbox1.xmax, bbox2.xmax) + y0 = np.maximum(bbox1.ymin, bbox2.ymin) + y1 = np.minimum(bbox1.ymax, bbox2.ymax) + return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None + + +_default_minpos = np.array([np.inf, np.inf]) + + +class Bbox(BboxBase): + """ + A mutable bounding box. + + Examples + -------- + **Create from known bounds** + + The default constructor takes the boundary "points" ``[[xmin, ymin], + [xmax, ymax]]``. + + >>> Bbox([[1, 1], [3, 7]]) + Bbox([[1.0, 1.0], [3.0, 7.0]]) + + Alternatively, a Bbox can be created from the flattened points array, the + so-called "extents" ``(xmin, ymin, xmax, ymax)`` + + >>> Bbox.from_extents(1, 1, 3, 7) + Bbox([[1.0, 1.0], [3.0, 7.0]]) + + or from the "bounds" ``(xmin, ymin, width, height)``. + + >>> Bbox.from_bounds(1, 1, 2, 6) + Bbox([[1.0, 1.0], [3.0, 7.0]]) + + **Create from collections of points** + + The "empty" object for accumulating Bboxs is the null bbox, which is a + stand-in for the empty set. + + >>> Bbox.null() + Bbox([[inf, inf], [-inf, -inf]]) + + Adding points to the null bbox will give you the bbox of those points. + + >>> box = Bbox.null() + >>> box.update_from_data_xy([[1, 1]]) + >>> box + Bbox([[1.0, 1.0], [1.0, 1.0]]) + >>> box.update_from_data_xy([[2, 3], [3, 2]], ignore=False) + >>> box + Bbox([[1.0, 1.0], [3.0, 3.0]]) + + Setting ``ignore=True`` is equivalent to starting over from a null bbox. + + >>> box.update_from_data_xy([[1, 1]], ignore=True) + >>> box + Bbox([[1.0, 1.0], [1.0, 1.0]]) + + .. warning:: + + It is recommended to always specify ``ignore`` explicitly. If not, the + default value of ``ignore`` can be changed at any time by code with + access to your Bbox, for example using the method `~.Bbox.ignore`. + + **Properties of the ``null`` bbox** + + .. note:: + + The current behavior of `Bbox.null()` may be surprising as it does + not have all of the properties of the "empty set", and as such does + not behave like a "zero" object in the mathematical sense. We may + change that in the future (with a deprecation period). + + The null bbox is the identity for intersections + + >>> Bbox.intersection(Bbox([[1, 1], [3, 7]]), Bbox.null()) + Bbox([[1.0, 1.0], [3.0, 7.0]]) + + except with itself, where it returns the full space. + + >>> Bbox.intersection(Bbox.null(), Bbox.null()) + Bbox([[-inf, -inf], [inf, inf]]) + + A union containing null will always return the full space (not the other + set!) + + >>> Bbox.union([Bbox([[0, 0], [0, 0]]), Bbox.null()]) + Bbox([[-inf, -inf], [inf, inf]]) + """ + + def __init__(self, points, **kwargs): + """ + Parameters + ---------- + points : `~numpy.ndarray` + A (2, 2) array of the form ``[[x0, y0], [x1, y1]]``. + """ + super().__init__(**kwargs) + points = np.asarray(points, float) + if points.shape != (2, 2): + raise ValueError('Bbox points must be of the form ' + '"[[x0, y0], [x1, y1]]".') + self._points = points + self._minpos = _default_minpos.copy() + self._ignore = True + # it is helpful in some contexts to know if the bbox is a + # default or has been mutated; we store the orig points to + # support the mutated methods + self._points_orig = self._points.copy() + if DEBUG: + ___init__ = __init__ + + def __init__(self, points, **kwargs): + self._check(points) + self.___init__(points, **kwargs) + + def invalidate(self): + self._check(self._points) + super().invalidate() + + def frozen(self): + # docstring inherited + frozen_bbox = super().frozen() + frozen_bbox._minpos = self.minpos.copy() + return frozen_bbox + + @staticmethod + def unit(): + """Create a new unit `Bbox` from (0, 0) to (1, 1).""" + return Bbox([[0, 0], [1, 1]]) + + @staticmethod + def null(): + """Create a new null `Bbox` from (inf, inf) to (-inf, -inf).""" + return Bbox([[np.inf, np.inf], [-np.inf, -np.inf]]) + + @staticmethod + def from_bounds(x0, y0, width, height): + """ + Create a new `Bbox` from *x0*, *y0*, *width* and *height*. + + *width* and *height* may be negative. + """ + return Bbox.from_extents(x0, y0, x0 + width, y0 + height) + + @staticmethod + def from_extents(*args, minpos=None): + """ + Create a new Bbox from *left*, *bottom*, *right* and *top*. + + The *y*-axis increases upwards. + + Parameters + ---------- + left, bottom, right, top : float + The four extents of the bounding box. + minpos : float or None + If this is supplied, the Bbox will have a minimum positive value + set. This is useful when dealing with logarithmic scales and other + scales where negative bounds result in floating point errors. + """ + bbox = Bbox(np.reshape(args, (2, 2))) + if minpos is not None: + bbox._minpos[:] = minpos + return bbox + + def __format__(self, fmt): + return ( + 'Bbox(x0={0.x0:{1}}, y0={0.y0:{1}}, x1={0.x1:{1}}, y1={0.y1:{1}})'. + format(self, fmt)) + + def __str__(self): + return format(self, '') + + def __repr__(self): + return 'Bbox([[{0.x0}, {0.y0}], [{0.x1}, {0.y1}]])'.format(self) + + def ignore(self, value): + """ + Set whether the existing bounds of the box should be ignored + by subsequent calls to :meth:`update_from_data_xy`. + + value : bool + - When ``True``, subsequent calls to `update_from_data_xy` will + ignore the existing bounds of the `Bbox`. + - When ``False``, subsequent calls to `update_from_data_xy` will + include the existing bounds of the `Bbox`. + """ + self._ignore = value + + def update_from_path(self, path, ignore=None, updatex=True, updatey=True): + """ + Update the bounds of the `Bbox` to contain the vertices of the + provided path. After updating, the bounds will have positive *width* + and *height*; *x0* and *y0* will be the minimal values. + + Parameters + ---------- + path : `~matplotlib.path.Path` + ignore : bool, optional + - When ``True``, ignore the existing bounds of the `Bbox`. + - When ``False``, include the existing bounds of the `Bbox`. + - When ``None``, use the last value passed to :meth:`ignore`. + updatex, updatey : bool, default: True + When ``True``, update the x/y values. + """ + if ignore is None: + ignore = self._ignore + + if path.vertices.size == 0: + return + + points, minpos, changed = update_path_extents( + path, None, self._points, self._minpos, ignore) + + if changed: + self.invalidate() + if updatex: + self._points[:, 0] = points[:, 0] + self._minpos[0] = minpos[0] + if updatey: + self._points[:, 1] = points[:, 1] + self._minpos[1] = minpos[1] + + def update_from_data_x(self, x, ignore=None): + """ + Update the x-bounds of the `Bbox` based on the passed in data. After + updating, the bounds will have positive *width*, and *x0* will be the + minimal value. + + Parameters + ---------- + x : `~numpy.ndarray` + Array of x-values. + ignore : bool, optional + - When ``True``, ignore the existing bounds of the `Bbox`. + - When ``False``, include the existing bounds of the `Bbox`. + - When ``None``, use the last value passed to :meth:`ignore`. + """ + x = np.ravel(x) + self.update_from_data_xy(np.column_stack([x, np.ones(x.size)]), + ignore=ignore, updatey=False) + + def update_from_data_y(self, y, ignore=None): + """ + Update the y-bounds of the `Bbox` based on the passed in data. After + updating, the bounds will have positive *height*, and *y0* will be the + minimal value. + + Parameters + ---------- + y : `~numpy.ndarray` + Array of y-values. + ignore : bool, optional + - When ``True``, ignore the existing bounds of the `Bbox`. + - When ``False``, include the existing bounds of the `Bbox`. + - When ``None``, use the last value passed to :meth:`ignore`. + """ + y = np.ravel(y) + self.update_from_data_xy(np.column_stack([np.ones(y.size), y]), + ignore=ignore, updatex=False) + + def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True): + """ + Update the `Bbox` bounds based on the passed in *xy* coordinates. + + After updating, the bounds will have positive *width* and *height*; + *x0* and *y0* will be the minimal values. + + Parameters + ---------- + xy : (N, 2) array-like + The (x, y) coordinates. + ignore : bool, optional + - When ``True``, ignore the existing bounds of the `Bbox`. + - When ``False``, include the existing bounds of the `Bbox`. + - When ``None``, use the last value passed to :meth:`ignore`. + updatex, updatey : bool, default: True + When ``True``, update the x/y values. + """ + if len(xy) == 0: + return + + path = Path(xy) + self.update_from_path(path, ignore=ignore, + updatex=updatex, updatey=updatey) + + @BboxBase.x0.setter + def x0(self, val): + self._points[0, 0] = val + self.invalidate() + + @BboxBase.y0.setter + def y0(self, val): + self._points[0, 1] = val + self.invalidate() + + @BboxBase.x1.setter + def x1(self, val): + self._points[1, 0] = val + self.invalidate() + + @BboxBase.y1.setter + def y1(self, val): + self._points[1, 1] = val + self.invalidate() + + @BboxBase.p0.setter + def p0(self, val): + self._points[0] = val + self.invalidate() + + @BboxBase.p1.setter + def p1(self, val): + self._points[1] = val + self.invalidate() + + @BboxBase.intervalx.setter + def intervalx(self, interval): + self._points[:, 0] = interval + self.invalidate() + + @BboxBase.intervaly.setter + def intervaly(self, interval): + self._points[:, 1] = interval + self.invalidate() + + @BboxBase.bounds.setter + def bounds(self, bounds): + l, b, w, h = bounds + points = np.array([[l, b], [l + w, b + h]], float) + if np.any(self._points != points): + self._points = points + self.invalidate() + + @property + def minpos(self): + """ + The minimum positive value in both directions within the Bbox. + + This is useful when dealing with logarithmic scales and other scales + where negative bounds result in floating point errors, and will be used + as the minimum extent instead of *p0*. + """ + return self._minpos + + @minpos.setter + def minpos(self, val): + self._minpos[:] = val + + @property + def minposx(self): + """ + The minimum positive value in the *x*-direction within the Bbox. + + This is useful when dealing with logarithmic scales and other scales + where negative bounds result in floating point errors, and will be used + as the minimum *x*-extent instead of *x0*. + """ + return self._minpos[0] + + @minposx.setter + def minposx(self, val): + self._minpos[0] = val + + @property + def minposy(self): + """ + The minimum positive value in the *y*-direction within the Bbox. + + This is useful when dealing with logarithmic scales and other scales + where negative bounds result in floating point errors, and will be used + as the minimum *y*-extent instead of *y0*. + """ + return self._minpos[1] + + @minposy.setter + def minposy(self, val): + self._minpos[1] = val + + def get_points(self): + """ + Get the points of the bounding box as an array of the form + ``[[x0, y0], [x1, y1]]``. + """ + self._invalid = 0 + return self._points + + def set_points(self, points): + """ + Set the points of the bounding box directly from an array of the form + ``[[x0, y0], [x1, y1]]``. No error checking is performed, as this + method is mainly for internal use. + """ + if np.any(self._points != points): + self._points = points + self.invalidate() + + def set(self, other): + """ + Set this bounding box from the "frozen" bounds of another `Bbox`. + """ + if np.any(self._points != other.get_points()): + self._points = other.get_points() + self.invalidate() + + def mutated(self): + """Return whether the bbox has changed since init.""" + return self.mutatedx() or self.mutatedy() + + def mutatedx(self): + """Return whether the x-limits have changed since init.""" + return (self._points[0, 0] != self._points_orig[0, 0] or + self._points[1, 0] != self._points_orig[1, 0]) + + def mutatedy(self): + """Return whether the y-limits have changed since init.""" + return (self._points[0, 1] != self._points_orig[0, 1] or + self._points[1, 1] != self._points_orig[1, 1]) + + +class TransformedBbox(BboxBase): + """ + A `Bbox` that is automatically transformed by a given + transform. When either the child bounding box or transform + changes, the bounds of this bbox will update accordingly. + """ + + def __init__(self, bbox, transform, **kwargs): + """ + Parameters + ---------- + bbox : `Bbox` + transform : `Transform` + """ + _api.check_isinstance(BboxBase, bbox=bbox) + _api.check_isinstance(Transform, transform=transform) + if transform.input_dims != 2 or transform.output_dims != 2: + raise ValueError( + "The input and output dimensions of 'transform' must be 2") + + super().__init__(**kwargs) + self._bbox = bbox + self._transform = transform + self.set_children(bbox, transform) + self._points = None + + __str__ = _make_str_method("_bbox", "_transform") + + def get_points(self): + # docstring inherited + if self._invalid: + p = self._bbox.get_points() + # Transform all four points, then make a new bounding box + # from the result, taking care to make the orientation the + # same. + points = self._transform.transform( + [[p[0, 0], p[0, 1]], + [p[1, 0], p[0, 1]], + [p[0, 0], p[1, 1]], + [p[1, 0], p[1, 1]]]) + points = np.ma.filled(points, 0.0) + + xs = min(points[:, 0]), max(points[:, 0]) + if p[0, 0] > p[1, 0]: + xs = xs[::-1] + + ys = min(points[:, 1]), max(points[:, 1]) + if p[0, 1] > p[1, 1]: + ys = ys[::-1] + + self._points = np.array([ + [xs[0], ys[0]], + [xs[1], ys[1]] + ]) + + self._invalid = 0 + return self._points + + if DEBUG: + _get_points = get_points + + def get_points(self): + points = self._get_points() + self._check(points) + return points + + def contains(self, x, y): + # Docstring inherited. + return self._bbox.contains(*self._transform.inverted().transform((x, y))) + + def fully_contains(self, x, y): + # Docstring inherited. + return self._bbox.fully_contains(*self._transform.inverted().transform((x, y))) + + +class LockableBbox(BboxBase): + """ + A `Bbox` where some elements may be locked at certain values. + + When the child bounding box changes, the bounds of this bbox will update + accordingly with the exception of the locked elements. + """ + def __init__(self, bbox, x0=None, y0=None, x1=None, y1=None, **kwargs): + """ + Parameters + ---------- + bbox : `Bbox` + The child bounding box to wrap. + + x0 : float or None + The locked value for x0, or None to leave unlocked. + + y0 : float or None + The locked value for y0, or None to leave unlocked. + + x1 : float or None + The locked value for x1, or None to leave unlocked. + + y1 : float or None + The locked value for y1, or None to leave unlocked. + + """ + _api.check_isinstance(BboxBase, bbox=bbox) + super().__init__(**kwargs) + self._bbox = bbox + self.set_children(bbox) + self._points = None + fp = [x0, y0, x1, y1] + mask = [val is None for val in fp] + self._locked_points = np.ma.array(fp, float, mask=mask).reshape((2, 2)) + + __str__ = _make_str_method("_bbox", "_locked_points") + + def get_points(self): + # docstring inherited + if self._invalid: + points = self._bbox.get_points() + self._points = np.where(self._locked_points.mask, + points, + self._locked_points) + self._invalid = 0 + return self._points + + if DEBUG: + _get_points = get_points + + def get_points(self): + points = self._get_points() + self._check(points) + return points + + @property + def locked_x0(self): + """ + float or None: The value used for the locked x0. + """ + if self._locked_points.mask[0, 0]: + return None + else: + return self._locked_points[0, 0] + + @locked_x0.setter + def locked_x0(self, x0): + self._locked_points.mask[0, 0] = x0 is None + self._locked_points.data[0, 0] = x0 + self.invalidate() + + @property + def locked_y0(self): + """ + float or None: The value used for the locked y0. + """ + if self._locked_points.mask[0, 1]: + return None + else: + return self._locked_points[0, 1] + + @locked_y0.setter + def locked_y0(self, y0): + self._locked_points.mask[0, 1] = y0 is None + self._locked_points.data[0, 1] = y0 + self.invalidate() + + @property + def locked_x1(self): + """ + float or None: The value used for the locked x1. + """ + if self._locked_points.mask[1, 0]: + return None + else: + return self._locked_points[1, 0] + + @locked_x1.setter + def locked_x1(self, x1): + self._locked_points.mask[1, 0] = x1 is None + self._locked_points.data[1, 0] = x1 + self.invalidate() + + @property + def locked_y1(self): + """ + float or None: The value used for the locked y1. + """ + if self._locked_points.mask[1, 1]: + return None + else: + return self._locked_points[1, 1] + + @locked_y1.setter + def locked_y1(self, y1): + self._locked_points.mask[1, 1] = y1 is None + self._locked_points.data[1, 1] = y1 + self.invalidate() + + +class Transform(TransformNode): + """ + The base class of all `TransformNode` instances that + actually perform a transformation. + + All non-affine transformations should be subclasses of this class. + New affine transformations should be subclasses of `Affine2D`. + + Subclasses of this class should override the following members (at + minimum): + + - :attr:`input_dims` + - :attr:`output_dims` + - :meth:`transform` + - :meth:`inverted` (if an inverse exists) + + The following attributes may be overridden if the default is unsuitable: + + - :attr:`is_separable` (defaults to True for 1D -> 1D transforms, False + otherwise) + - :attr:`has_inverse` (defaults to True if :meth:`inverted` is overridden, + False otherwise) + + If the transform needs to do something non-standard with + `matplotlib.path.Path` objects, such as adding curves + where there were once line segments, it should override: + + - :meth:`transform_path` + """ + + input_dims = None + """ + The number of input dimensions of this transform. + Must be overridden (with integers) in the subclass. + """ + + output_dims = None + """ + The number of output dimensions of this transform. + Must be overridden (with integers) in the subclass. + """ + + is_separable = False + """True if this transform is separable in the x- and y- dimensions.""" + + has_inverse = False + """True if this transform has a corresponding inverse transform.""" + + def __init_subclass__(cls): + # 1d transforms are always separable; we assume higher-dimensional ones + # are not but subclasses can also directly set is_separable -- this is + # verified by checking whether "is_separable" appears more than once in + # the class's MRO (it appears once in Transform). + if (sum("is_separable" in vars(parent) for parent in cls.__mro__) == 1 + and cls.input_dims == cls.output_dims == 1): + cls.is_separable = True + # Transform.inverted raises NotImplementedError; we assume that if this + # is overridden then the transform is invertible but subclass can also + # directly set has_inverse. + if (sum("has_inverse" in vars(parent) for parent in cls.__mro__) == 1 + and hasattr(cls, "inverted") + and cls.inverted is not Transform.inverted): + cls.has_inverse = True + + def __add__(self, other): + """ + Compose two transforms together so that *self* is followed by *other*. + + ``A + B`` returns a transform ``C`` so that + ``C.transform(x) == B.transform(A.transform(x))``. + """ + return (composite_transform_factory(self, other) + if isinstance(other, Transform) else + NotImplemented) + + # Equality is based on object identity for `Transform`s (so we don't + # override `__eq__`), but some subclasses, such as TransformWrapper & + # AffineBase, override this behavior. + + def _iter_break_from_left_to_right(self): + """ + Return an iterator breaking down this transform stack from left to + right recursively. If self == ((A, N), A) then the result will be an + iterator which yields I : ((A, N), A), followed by A : (N, A), + followed by (A, N) : (A), but not ((A, N), A) : I. + + This is equivalent to flattening the stack then yielding + ``flat_stack[:i], flat_stack[i:]`` where i=0..(n-1). + """ + yield IdentityTransform(), self + + @property + def depth(self): + """ + Return the number of transforms which have been chained + together to form this Transform instance. + + .. note:: + + For the special case of a Composite transform, the maximum depth + of the two is returned. + + """ + return 1 + + def contains_branch(self, other): + """ + Return whether the given transform is a sub-tree of this transform. + + This routine uses transform equality to identify sub-trees, therefore + in many situations it is object id which will be used. + + For the case where the given transform represents the whole + of this transform, returns True. + """ + if self.depth < other.depth: + return False + + # check that a subtree is equal to other (starting from self) + for _, sub_tree in self._iter_break_from_left_to_right(): + if sub_tree == other: + return True + return False + + def contains_branch_seperately(self, other_transform): + """ + Return whether the given branch is a sub-tree of this transform on + each separate dimension. + + A common use for this method is to identify if a transform is a blended + transform containing an Axes' data transform. e.g.:: + + x_isdata, y_isdata = trans.contains_branch_seperately(ax.transData) + + """ + if self.output_dims != 2: + raise ValueError('contains_branch_seperately only supports ' + 'transforms with 2 output dimensions') + # for a non-blended transform each separate dimension is the same, so + # just return the appropriate shape. + return (self.contains_branch(other_transform), ) * 2 + + def __sub__(self, other): + """ + Compose *self* with the inverse of *other*, cancelling identical terms + if any:: + + # In general: + A - B == A + B.inverted() + # (but see note regarding frozen transforms below). + + # If A "ends with" B (i.e. A == A' + B for some A') we can cancel + # out B: + (A' + B) - B == A' + + # Likewise, if B "starts with" A (B = A + B'), we can cancel out A: + A - (A + B') == B'.inverted() == B'^-1 + + Cancellation (rather than naively returning ``A + B.inverted()``) is + important for multiple reasons: + + - It avoids floating-point inaccuracies when computing the inverse of + B: ``B - B`` is guaranteed to cancel out exactly (resulting in the + identity transform), whereas ``B + B.inverted()`` may differ by a + small epsilon. + - ``B.inverted()`` always returns a frozen transform: if one computes + ``A + B + B.inverted()`` and later mutates ``B``, then + ``B.inverted()`` won't be updated and the last two terms won't cancel + out anymore; on the other hand, ``A + B - B`` will always be equal to + ``A`` even if ``B`` is mutated. + """ + # we only know how to do this operation if other is a Transform. + if not isinstance(other, Transform): + return NotImplemented + for remainder, sub_tree in self._iter_break_from_left_to_right(): + if sub_tree == other: + return remainder + for remainder, sub_tree in other._iter_break_from_left_to_right(): + if sub_tree == self: + if not remainder.has_inverse: + raise ValueError( + "The shortcut cannot be computed since 'other' " + "includes a non-invertible component") + return remainder.inverted() + # if we have got this far, then there was no shortcut possible + if other.has_inverse: + return self + other.inverted() + else: + raise ValueError('It is not possible to compute transA - transB ' + 'since transB cannot be inverted and there is no ' + 'shortcut possible.') + + def __array__(self, *args, **kwargs): + """Array interface to get at this Transform's affine matrix.""" + return self.get_affine().get_matrix() + + def transform(self, values): + """ + Apply this transformation on the given array of *values*. + + Parameters + ---------- + values : array-like + The input values as an array of length :attr:`input_dims` or + shape (N, :attr:`input_dims`). + + Returns + ------- + array + The output values as an array of length :attr:`output_dims` or + shape (N, :attr:`output_dims`), depending on the input. + """ + # Ensure that values is a 2d array (but remember whether + # we started with a 1d or 2d array). + values = np.asanyarray(values) + ndim = values.ndim + values = values.reshape((-1, self.input_dims)) + + # Transform the values + res = self.transform_affine(self.transform_non_affine(values)) + + # Convert the result back to the shape of the input values. + if ndim == 0: + assert not np.ma.is_masked(res) # just to be on the safe side + return res[0, 0] + if ndim == 1: + return res.reshape(-1) + elif ndim == 2: + return res + raise ValueError( + "Input values must have shape (N, {dims}) or ({dims},)" + .format(dims=self.input_dims)) + + def transform_affine(self, values): + """ + Apply only the affine part of this transformation on the + given array of values. + + ``transform(values)`` is always equivalent to + ``transform_affine(transform_non_affine(values))``. + + In non-affine transformations, this is generally a no-op. In + affine transformations, this is equivalent to + ``transform(values)``. + + Parameters + ---------- + values : array + The input values as an array of length :attr:`input_dims` or + shape (N, :attr:`input_dims`). + + Returns + ------- + array + The output values as an array of length :attr:`output_dims` or + shape (N, :attr:`output_dims`), depending on the input. + """ + return self.get_affine().transform(values) + + def transform_non_affine(self, values): + """ + Apply only the non-affine part of this transformation. + + ``transform(values)`` is always equivalent to + ``transform_affine(transform_non_affine(values))``. + + In non-affine transformations, this is generally equivalent to + ``transform(values)``. In affine transformations, this is + always a no-op. + + Parameters + ---------- + values : array + The input values as an array of length :attr:`input_dims` or + shape (N, :attr:`input_dims`). + + Returns + ------- + array + The output values as an array of length :attr:`output_dims` or + shape (N, :attr:`output_dims`), depending on the input. + """ + return values + + def transform_bbox(self, bbox): + """ + Transform the given bounding box. + + For smarter transforms including caching (a common requirement in + Matplotlib), see `TransformedBbox`. + """ + return Bbox(self.transform(bbox.get_points())) + + def get_affine(self): + """Get the affine part of this transform.""" + return IdentityTransform() + + def get_matrix(self): + """Get the matrix for the affine part of this transform.""" + return self.get_affine().get_matrix() + + def transform_point(self, point): + """ + Return a transformed point. + + This function is only kept for backcompatibility; the more general + `.transform` method is capable of transforming both a list of points + and a single point. + + The point is given as a sequence of length :attr:`input_dims`. + The transformed point is returned as a sequence of length + :attr:`output_dims`. + """ + if len(point) != self.input_dims: + raise ValueError("The length of 'point' must be 'self.input_dims'") + return self.transform(point) + + def transform_path(self, path): + """ + Apply the transform to `.Path` *path*, returning a new `.Path`. + + In some cases, this transform may insert curves into the path + that began as line segments. + """ + return self.transform_path_affine(self.transform_path_non_affine(path)) + + def transform_path_affine(self, path): + """ + Apply the affine part of this transform to `.Path` *path*, returning a + new `.Path`. + + ``transform_path(path)`` is equivalent to + ``transform_path_affine(transform_path_non_affine(values))``. + """ + return self.get_affine().transform_path_affine(path) + + def transform_path_non_affine(self, path): + """ + Apply the non-affine part of this transform to `.Path` *path*, + returning a new `.Path`. + + ``transform_path(path)`` is equivalent to + ``transform_path_affine(transform_path_non_affine(values))``. + """ + x = self.transform_non_affine(path.vertices) + return Path._fast_from_codes_and_verts(x, path.codes, path) + + def transform_angles(self, angles, pts, radians=False, pushoff=1e-5): + """ + Transform a set of angles anchored at specific locations. + + Parameters + ---------- + angles : (N,) array-like + The angles to transform. + pts : (N, 2) array-like + The points where the angles are anchored. + radians : bool, default: False + Whether *angles* are radians or degrees. + pushoff : float + For each point in *pts* and angle in *angles*, the transformed + angle is computed by transforming a segment of length *pushoff* + starting at that point and making that angle relative to the + horizontal axis, and measuring the angle between the horizontal + axis and the transformed segment. + + Returns + ------- + (N,) array + """ + # Must be 2D + if self.input_dims != 2 or self.output_dims != 2: + raise NotImplementedError('Only defined in 2D') + angles = np.asarray(angles) + pts = np.asarray(pts) + _api.check_shape((None, 2), pts=pts) + _api.check_shape((None,), angles=angles) + if len(angles) != len(pts): + raise ValueError("There must be as many 'angles' as 'pts'") + # Convert to radians if desired + if not radians: + angles = np.deg2rad(angles) + # Move a short distance away + pts2 = pts + pushoff * np.column_stack([np.cos(angles), + np.sin(angles)]) + # Transform both sets of points + tpts = self.transform(pts) + tpts2 = self.transform(pts2) + # Calculate transformed angles + d = tpts2 - tpts + a = np.arctan2(d[:, 1], d[:, 0]) + # Convert back to degrees if desired + if not radians: + a = np.rad2deg(a) + return a + + def inverted(self): + """ + Return the corresponding inverse transformation. + + It holds ``x == self.inverted().transform(self.transform(x))``. + + The return value of this method should be treated as + temporary. An update to *self* does not cause a corresponding + update to its inverted copy. + """ + raise NotImplementedError() + + +class TransformWrapper(Transform): + """ + A helper class that holds a single child transform and acts + equivalently to it. + + This is useful if a node of the transform tree must be replaced at + run time with a transform of a different type. This class allows + that replacement to correctly trigger invalidation. + + `TransformWrapper` instances must have the same input and output dimensions + during their entire lifetime, so the child transform may only be replaced + with another child transform of the same dimensions. + """ + + pass_through = True + + def __init__(self, child): + """ + *child*: A `Transform` instance. This child may later + be replaced with :meth:`set`. + """ + _api.check_isinstance(Transform, child=child) + super().__init__() + self.set(child) + + def __eq__(self, other): + return self._child.__eq__(other) + + __str__ = _make_str_method("_child") + + def frozen(self): + # docstring inherited + return self._child.frozen() + + def set(self, child): + """ + Replace the current child of this transform with another one. + + The new child must have the same number of input and output + dimensions as the current child. + """ + if hasattr(self, "_child"): # Absent during init. + self.invalidate() + new_dims = (child.input_dims, child.output_dims) + old_dims = (self._child.input_dims, self._child.output_dims) + if new_dims != old_dims: + raise ValueError( + f"The input and output dims of the new child {new_dims} " + f"do not match those of current child {old_dims}") + self._child._parents.pop(id(self), None) + + self._child = child + self.set_children(child) + + self.transform = child.transform + self.transform_affine = child.transform_affine + self.transform_non_affine = child.transform_non_affine + self.transform_path = child.transform_path + self.transform_path_affine = child.transform_path_affine + self.transform_path_non_affine = child.transform_path_non_affine + self.get_affine = child.get_affine + self.inverted = child.inverted + self.get_matrix = child.get_matrix + # note we do not wrap other properties here since the transform's + # child can be changed with WrappedTransform.set and so checking + # is_affine and other such properties may be dangerous. + + self._invalid = 0 + self.invalidate() + self._invalid = 0 + + input_dims = property(lambda self: self._child.input_dims) + output_dims = property(lambda self: self._child.output_dims) + is_affine = property(lambda self: self._child.is_affine) + is_separable = property(lambda self: self._child.is_separable) + has_inverse = property(lambda self: self._child.has_inverse) + + +class AffineBase(Transform): + """ + The base class of all affine transformations of any number of dimensions. + """ + is_affine = True + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._inverted = None + + def __array__(self, *args, **kwargs): + # optimises the access of the transform matrix vs. the superclass + return self.get_matrix() + + def __eq__(self, other): + if getattr(other, "is_affine", False) and hasattr(other, "get_matrix"): + return (self.get_matrix() == other.get_matrix()).all() + return NotImplemented + + def transform(self, values): + # docstring inherited + return self.transform_affine(values) + + def transform_affine(self, values): + # docstring inherited + raise NotImplementedError('Affine subclasses should override this ' + 'method.') + + @_api.rename_parameter("3.8", "points", "values") + def transform_non_affine(self, values): + # docstring inherited + return values + + def transform_path(self, path): + # docstring inherited + return self.transform_path_affine(path) + + def transform_path_affine(self, path): + # docstring inherited + return Path(self.transform_affine(path.vertices), + path.codes, path._interpolation_steps) + + def transform_path_non_affine(self, path): + # docstring inherited + return path + + def get_affine(self): + # docstring inherited + return self + + +class Affine2DBase(AffineBase): + """ + The base class of all 2D affine transformations. + + 2D affine transformations are performed using a 3x3 numpy array:: + + a c e + b d f + 0 0 1 + + This class provides the read-only interface. For a mutable 2D + affine transformation, use `Affine2D`. + + Subclasses of this class will generally only need to override a + constructor and `~.Transform.get_matrix` that generates a custom 3x3 matrix. + """ + input_dims = 2 + output_dims = 2 + + def frozen(self): + # docstring inherited + return Affine2D(self.get_matrix().copy()) + + @property + def is_separable(self): + mtx = self.get_matrix() + return mtx[0, 1] == mtx[1, 0] == 0.0 + + def to_values(self): + """ + Return the values of the matrix as an ``(a, b, c, d, e, f)`` tuple. + """ + mtx = self.get_matrix() + return tuple(mtx[:2].swapaxes(0, 1).flat) + + @_api.rename_parameter("3.8", "points", "values") + def transform_affine(self, values): + mtx = self.get_matrix() + if isinstance(values, np.ma.MaskedArray): + tpoints = affine_transform(values.data, mtx) + return np.ma.MaskedArray(tpoints, mask=np.ma.getmask(values)) + return affine_transform(values, mtx) + + if DEBUG: + _transform_affine = transform_affine + + @_api.rename_parameter("3.8", "points", "values") + def transform_affine(self, values): + # docstring inherited + # The major speed trap here is just converting to the + # points to an array in the first place. If we can use + # more arrays upstream, that should help here. + if not isinstance(values, np.ndarray): + _api.warn_external( + f'A non-numpy array of type {type(values)} was passed in ' + f'for transformation, which results in poor performance.') + return self._transform_affine(values) + + def inverted(self): + # docstring inherited + if self._inverted is None or self._invalid: + mtx = self.get_matrix() + shorthand_name = None + if self._shorthand_name: + shorthand_name = '(%s)-1' % self._shorthand_name + self._inverted = Affine2D(inv(mtx), shorthand_name=shorthand_name) + self._invalid = 0 + return self._inverted + + +class Affine2D(Affine2DBase): + """ + A mutable 2D affine transformation. + """ + + def __init__(self, matrix=None, **kwargs): + """ + Initialize an Affine transform from a 3x3 numpy float array:: + + a c e + b d f + 0 0 1 + + If *matrix* is None, initialize with the identity transform. + """ + super().__init__(**kwargs) + if matrix is None: + # A bit faster than np.identity(3). + matrix = IdentityTransform._mtx + self._mtx = matrix.copy() + self._invalid = 0 + + _base_str = _make_str_method("_mtx") + + def __str__(self): + return (self._base_str() + if (self._mtx != np.diag(np.diag(self._mtx))).any() + else f"Affine2D().scale({self._mtx[0, 0]}, {self._mtx[1, 1]})" + if self._mtx[0, 0] != self._mtx[1, 1] + else f"Affine2D().scale({self._mtx[0, 0]})") + + @staticmethod + def from_values(a, b, c, d, e, f): + """ + Create a new Affine2D instance from the given values:: + + a c e + b d f + 0 0 1 + + . + """ + return Affine2D( + np.array([a, c, e, b, d, f, 0.0, 0.0, 1.0], float).reshape((3, 3))) + + def get_matrix(self): + """ + Get the underlying transformation matrix as a 3x3 array:: + + a c e + b d f + 0 0 1 + + . + """ + if self._invalid: + self._inverted = None + self._invalid = 0 + return self._mtx + + def set_matrix(self, mtx): + """ + Set the underlying transformation matrix from a 3x3 array:: + + a c e + b d f + 0 0 1 + + . + """ + self._mtx = mtx + self.invalidate() + + def set(self, other): + """ + Set this transformation from the frozen copy of another + `Affine2DBase` object. + """ + _api.check_isinstance(Affine2DBase, other=other) + self._mtx = other.get_matrix() + self.invalidate() + + def clear(self): + """ + Reset the underlying matrix to the identity transform. + """ + # A bit faster than np.identity(3). + self._mtx = IdentityTransform._mtx.copy() + self.invalidate() + return self + + def rotate(self, theta): + """ + Add a rotation (in radians) to this transform in place. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + a = math.cos(theta) + b = math.sin(theta) + mtx = self._mtx + # Operating and assigning one scalar at a time is much faster. + (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist() + # mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx + mtx[0, 0] = a * xx - b * yx + mtx[0, 1] = a * xy - b * yy + mtx[0, 2] = a * x0 - b * y0 + mtx[1, 0] = b * xx + a * yx + mtx[1, 1] = b * xy + a * yy + mtx[1, 2] = b * x0 + a * y0 + self.invalidate() + return self + + def rotate_deg(self, degrees): + """ + Add a rotation (in degrees) to this transform in place. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + return self.rotate(math.radians(degrees)) + + def rotate_around(self, x, y, theta): + """ + Add a rotation (in radians) around the point (x, y) in place. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + return self.translate(-x, -y).rotate(theta).translate(x, y) + + def rotate_deg_around(self, x, y, degrees): + """ + Add a rotation (in degrees) around the point (x, y) in place. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + # Cast to float to avoid wraparound issues with uint8's + x, y = float(x), float(y) + return self.translate(-x, -y).rotate_deg(degrees).translate(x, y) + + def translate(self, tx, ty): + """ + Add a translation in place. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + self._mtx[0, 2] += tx + self._mtx[1, 2] += ty + self.invalidate() + return self + + def scale(self, sx, sy=None): + """ + Add a scale in place. + + If *sy* is None, the same scale is applied in both the *x*- and + *y*-directions. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + if sy is None: + sy = sx + # explicit element-wise scaling is fastest + self._mtx[0, 0] *= sx + self._mtx[0, 1] *= sx + self._mtx[0, 2] *= sx + self._mtx[1, 0] *= sy + self._mtx[1, 1] *= sy + self._mtx[1, 2] *= sy + self.invalidate() + return self + + def skew(self, xShear, yShear): + """ + Add a skew in place. + + *xShear* and *yShear* are the shear angles along the *x*- and + *y*-axes, respectively, in radians. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + rx = math.tan(xShear) + ry = math.tan(yShear) + mtx = self._mtx + # Operating and assigning one scalar at a time is much faster. + (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist() + # mtx = [[1 rx 0], [ry 1 0], [0 0 1]] * mtx + mtx[0, 0] += rx * yx + mtx[0, 1] += rx * yy + mtx[0, 2] += rx * y0 + mtx[1, 0] += ry * xx + mtx[1, 1] += ry * xy + mtx[1, 2] += ry * x0 + self.invalidate() + return self + + def skew_deg(self, xShear, yShear): + """ + Add a skew in place. + + *xShear* and *yShear* are the shear angles along the *x*- and + *y*-axes, respectively, in degrees. + + Returns *self*, so this method can easily be chained with more + calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate` + and :meth:`scale`. + """ + return self.skew(math.radians(xShear), math.radians(yShear)) + + +class IdentityTransform(Affine2DBase): + """ + A special class that does one thing, the identity transform, in a + fast way. + """ + _mtx = np.identity(3) + + def frozen(self): + # docstring inherited + return self + + __str__ = _make_str_method() + + def get_matrix(self): + # docstring inherited + return self._mtx + + @_api.rename_parameter("3.8", "points", "values") + def transform(self, values): + # docstring inherited + return np.asanyarray(values) + + @_api.rename_parameter("3.8", "points", "values") + def transform_affine(self, values): + # docstring inherited + return np.asanyarray(values) + + @_api.rename_parameter("3.8", "points", "values") + def transform_non_affine(self, values): + # docstring inherited + return np.asanyarray(values) + + def transform_path(self, path): + # docstring inherited + return path + + def transform_path_affine(self, path): + # docstring inherited + return path + + def transform_path_non_affine(self, path): + # docstring inherited + return path + + def get_affine(self): + # docstring inherited + return self + + def inverted(self): + # docstring inherited + return self + + +class _BlendedMixin: + """Common methods for `BlendedGenericTransform` and `BlendedAffine2D`.""" + + def __eq__(self, other): + if isinstance(other, (BlendedAffine2D, BlendedGenericTransform)): + return (self._x == other._x) and (self._y == other._y) + elif self._x == self._y: + return self._x == other + else: + return NotImplemented + + def contains_branch_seperately(self, transform): + return (self._x.contains_branch(transform), + self._y.contains_branch(transform)) + + __str__ = _make_str_method("_x", "_y") + + +class BlendedGenericTransform(_BlendedMixin, Transform): + """ + A "blended" transform uses one transform for the *x*-direction, and + another transform for the *y*-direction. + + This "generic" version can handle any given child transform in the + *x*- and *y*-directions. + """ + input_dims = 2 + output_dims = 2 + is_separable = True + pass_through = True + + def __init__(self, x_transform, y_transform, **kwargs): + """ + Create a new "blended" transform using *x_transform* to transform the + *x*-axis and *y_transform* to transform the *y*-axis. + + You will generally not call this constructor directly but use the + `blended_transform_factory` function instead, which can determine + automatically which kind of blended transform to create. + """ + Transform.__init__(self, **kwargs) + self._x = x_transform + self._y = y_transform + self.set_children(x_transform, y_transform) + self._affine = None + + @property + def depth(self): + return max(self._x.depth, self._y.depth) + + def contains_branch(self, other): + # A blended transform cannot possibly contain a branch from two + # different transforms. + return False + + is_affine = property(lambda self: self._x.is_affine and self._y.is_affine) + has_inverse = property( + lambda self: self._x.has_inverse and self._y.has_inverse) + + def frozen(self): + # docstring inherited + return blended_transform_factory(self._x.frozen(), self._y.frozen()) + + @_api.rename_parameter("3.8", "points", "values") + def transform_non_affine(self, values): + # docstring inherited + if self._x.is_affine and self._y.is_affine: + return values + x = self._x + y = self._y + + if x == y and x.input_dims == 2: + return x.transform_non_affine(values) + + if x.input_dims == 2: + x_points = x.transform_non_affine(values)[:, 0:1] + else: + x_points = x.transform_non_affine(values[:, 0]) + x_points = x_points.reshape((len(x_points), 1)) + + if y.input_dims == 2: + y_points = y.transform_non_affine(values)[:, 1:] + else: + y_points = y.transform_non_affine(values[:, 1]) + y_points = y_points.reshape((len(y_points), 1)) + + if (isinstance(x_points, np.ma.MaskedArray) or + isinstance(y_points, np.ma.MaskedArray)): + return np.ma.concatenate((x_points, y_points), 1) + else: + return np.concatenate((x_points, y_points), 1) + + def inverted(self): + # docstring inherited + return BlendedGenericTransform(self._x.inverted(), self._y.inverted()) + + def get_affine(self): + # docstring inherited + if self._invalid or self._affine is None: + if self._x == self._y: + self._affine = self._x.get_affine() + else: + x_mtx = self._x.get_affine().get_matrix() + y_mtx = self._y.get_affine().get_matrix() + # We already know the transforms are separable, so we can skip + # setting b and c to zero. + mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]]) + self._affine = Affine2D(mtx) + self._invalid = 0 + return self._affine + + +class BlendedAffine2D(_BlendedMixin, Affine2DBase): + """ + A "blended" transform uses one transform for the *x*-direction, and + another transform for the *y*-direction. + + This version is an optimization for the case where both child + transforms are of type `Affine2DBase`. + """ + + is_separable = True + + def __init__(self, x_transform, y_transform, **kwargs): + """ + Create a new "blended" transform using *x_transform* to transform the + *x*-axis and *y_transform* to transform the *y*-axis. + + Both *x_transform* and *y_transform* must be 2D affine transforms. + + You will generally not call this constructor directly but use the + `blended_transform_factory` function instead, which can determine + automatically which kind of blended transform to create. + """ + is_affine = x_transform.is_affine and y_transform.is_affine + is_separable = x_transform.is_separable and y_transform.is_separable + is_correct = is_affine and is_separable + if not is_correct: + raise ValueError("Both *x_transform* and *y_transform* must be 2D " + "affine transforms") + + Transform.__init__(self, **kwargs) + self._x = x_transform + self._y = y_transform + self.set_children(x_transform, y_transform) + + Affine2DBase.__init__(self) + self._mtx = None + + def get_matrix(self): + # docstring inherited + if self._invalid: + if self._x == self._y: + self._mtx = self._x.get_matrix() + else: + x_mtx = self._x.get_matrix() + y_mtx = self._y.get_matrix() + # We already know the transforms are separable, so we can skip + # setting b and c to zero. + self._mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]]) + self._inverted = None + self._invalid = 0 + return self._mtx + + +def blended_transform_factory(x_transform, y_transform): + """ + Create a new "blended" transform using *x_transform* to transform + the *x*-axis and *y_transform* to transform the *y*-axis. + + A faster version of the blended transform is returned for the case + where both child transforms are affine. + """ + if (isinstance(x_transform, Affine2DBase) and + isinstance(y_transform, Affine2DBase)): + return BlendedAffine2D(x_transform, y_transform) + return BlendedGenericTransform(x_transform, y_transform) + + +class CompositeGenericTransform(Transform): + """ + A composite transform formed by applying transform *a* then + transform *b*. + + This "generic" version can handle any two arbitrary + transformations. + """ + pass_through = True + + def __init__(self, a, b, **kwargs): + """ + Create a new composite transform that is the result of + applying transform *a* then transform *b*. + + You will generally not call this constructor directly but write ``a + + b`` instead, which will automatically choose the best kind of composite + transform instance to create. + """ + if a.output_dims != b.input_dims: + raise ValueError("The output dimension of 'a' must be equal to " + "the input dimensions of 'b'") + self.input_dims = a.input_dims + self.output_dims = b.output_dims + + super().__init__(**kwargs) + self._a = a + self._b = b + self.set_children(a, b) + + def frozen(self): + # docstring inherited + self._invalid = 0 + frozen = composite_transform_factory( + self._a.frozen(), self._b.frozen()) + if not isinstance(frozen, CompositeGenericTransform): + return frozen.frozen() + return frozen + + def _invalidate_internal(self, level, invalidating_node): + # When the left child is invalidated at AFFINE_ONLY level and the right child is + # non-affine, the composite transform is FULLY invalidated. + if invalidating_node is self._a and not self._b.is_affine: + level = Transform._INVALID_FULL + super()._invalidate_internal(level, invalidating_node) + + def __eq__(self, other): + if isinstance(other, (CompositeGenericTransform, CompositeAffine2D)): + return self is other or (self._a == other._a + and self._b == other._b) + else: + return False + + def _iter_break_from_left_to_right(self): + for left, right in self._a._iter_break_from_left_to_right(): + yield left, right + self._b + for left, right in self._b._iter_break_from_left_to_right(): + yield self._a + left, right + + def contains_branch_seperately(self, other_transform): + # docstring inherited + if self.output_dims != 2: + raise ValueError('contains_branch_seperately only supports ' + 'transforms with 2 output dimensions') + if self == other_transform: + return (True, True) + return self._b.contains_branch_seperately(other_transform) + + depth = property(lambda self: self._a.depth + self._b.depth) + is_affine = property(lambda self: self._a.is_affine and self._b.is_affine) + is_separable = property( + lambda self: self._a.is_separable and self._b.is_separable) + has_inverse = property( + lambda self: self._a.has_inverse and self._b.has_inverse) + + __str__ = _make_str_method("_a", "_b") + + @_api.rename_parameter("3.8", "points", "values") + def transform_affine(self, values): + # docstring inherited + return self.get_affine().transform(values) + + @_api.rename_parameter("3.8", "points", "values") + def transform_non_affine(self, values): + # docstring inherited + if self._a.is_affine and self._b.is_affine: + return values + elif not self._a.is_affine and self._b.is_affine: + return self._a.transform_non_affine(values) + else: + return self._b.transform_non_affine(self._a.transform(values)) + + def transform_path_non_affine(self, path): + # docstring inherited + if self._a.is_affine and self._b.is_affine: + return path + elif not self._a.is_affine and self._b.is_affine: + return self._a.transform_path_non_affine(path) + else: + return self._b.transform_path_non_affine( + self._a.transform_path(path)) + + def get_affine(self): + # docstring inherited + if not self._b.is_affine: + return self._b.get_affine() + else: + return Affine2D(np.dot(self._b.get_affine().get_matrix(), + self._a.get_affine().get_matrix())) + + def inverted(self): + # docstring inherited + return CompositeGenericTransform( + self._b.inverted(), self._a.inverted()) + + +class CompositeAffine2D(Affine2DBase): + """ + A composite transform formed by applying transform *a* then transform *b*. + + This version is an optimization that handles the case where both *a* + and *b* are 2D affines. + """ + def __init__(self, a, b, **kwargs): + """ + Create a new composite transform that is the result of + applying `Affine2DBase` *a* then `Affine2DBase` *b*. + + You will generally not call this constructor directly but write ``a + + b`` instead, which will automatically choose the best kind of composite + transform instance to create. + """ + if not a.is_affine or not b.is_affine: + raise ValueError("'a' and 'b' must be affine transforms") + if a.output_dims != b.input_dims: + raise ValueError("The output dimension of 'a' must be equal to " + "the input dimensions of 'b'") + self.input_dims = a.input_dims + self.output_dims = b.output_dims + + super().__init__(**kwargs) + self._a = a + self._b = b + self.set_children(a, b) + self._mtx = None + + @property + def depth(self): + return self._a.depth + self._b.depth + + def _iter_break_from_left_to_right(self): + for left, right in self._a._iter_break_from_left_to_right(): + yield left, right + self._b + for left, right in self._b._iter_break_from_left_to_right(): + yield self._a + left, right + + __str__ = _make_str_method("_a", "_b") + + def get_matrix(self): + # docstring inherited + if self._invalid: + self._mtx = np.dot( + self._b.get_matrix(), + self._a.get_matrix()) + self._inverted = None + self._invalid = 0 + return self._mtx + + +def composite_transform_factory(a, b): + """ + Create a new composite transform that is the result of applying + transform a then transform b. + + Shortcut versions of the blended transform are provided for the + case where both child transforms are affine, or one or the other + is the identity transform. + + Composite transforms may also be created using the '+' operator, + e.g.:: + + c = a + b + """ + # check to see if any of a or b are IdentityTransforms. We use + # isinstance here to guarantee that the transforms will *always* + # be IdentityTransforms. Since TransformWrappers are mutable, + # use of equality here would be wrong. + if isinstance(a, IdentityTransform): + return b + elif isinstance(b, IdentityTransform): + return a + elif isinstance(a, Affine2D) and isinstance(b, Affine2D): + return CompositeAffine2D(a, b) + return CompositeGenericTransform(a, b) + + +class BboxTransform(Affine2DBase): + """ + `BboxTransform` linearly transforms points from one `Bbox` to another. + """ + + is_separable = True + + def __init__(self, boxin, boxout, **kwargs): + """ + Create a new `BboxTransform` that linearly transforms + points from *boxin* to *boxout*. + """ + _api.check_isinstance(BboxBase, boxin=boxin, boxout=boxout) + + super().__init__(**kwargs) + self._boxin = boxin + self._boxout = boxout + self.set_children(boxin, boxout) + self._mtx = None + self._inverted = None + + __str__ = _make_str_method("_boxin", "_boxout") + + def get_matrix(self): + # docstring inherited + if self._invalid: + inl, inb, inw, inh = self._boxin.bounds + outl, outb, outw, outh = self._boxout.bounds + x_scale = outw / inw + y_scale = outh / inh + if DEBUG and (x_scale == 0 or y_scale == 0): + raise ValueError( + "Transforming from or to a singular bounding box") + self._mtx = np.array([[x_scale, 0.0 , (-inl*x_scale+outl)], + [0.0 , y_scale, (-inb*y_scale+outb)], + [0.0 , 0.0 , 1.0 ]], + float) + self._inverted = None + self._invalid = 0 + return self._mtx + + +class BboxTransformTo(Affine2DBase): + """ + `BboxTransformTo` is a transformation that linearly transforms points from + the unit bounding box to a given `Bbox`. + """ + + is_separable = True + + def __init__(self, boxout, **kwargs): + """ + Create a new `BboxTransformTo` that linearly transforms + points from the unit bounding box to *boxout*. + """ + _api.check_isinstance(BboxBase, boxout=boxout) + + super().__init__(**kwargs) + self._boxout = boxout + self.set_children(boxout) + self._mtx = None + self._inverted = None + + __str__ = _make_str_method("_boxout") + + def get_matrix(self): + # docstring inherited + if self._invalid: + outl, outb, outw, outh = self._boxout.bounds + if DEBUG and (outw == 0 or outh == 0): + raise ValueError("Transforming to a singular bounding box.") + self._mtx = np.array([[outw, 0.0, outl], + [ 0.0, outh, outb], + [ 0.0, 0.0, 1.0]], + float) + self._inverted = None + self._invalid = 0 + return self._mtx + + +@_api.deprecated("3.9") +class BboxTransformToMaxOnly(BboxTransformTo): + """ + `BboxTransformToMaxOnly` is a transformation that linearly transforms points from + the unit bounding box to a given `Bbox` with a fixed upper left of (0, 0). + """ + def get_matrix(self): + # docstring inherited + if self._invalid: + xmax, ymax = self._boxout.max + if DEBUG and (xmax == 0 or ymax == 0): + raise ValueError("Transforming to a singular bounding box.") + self._mtx = np.array([[xmax, 0.0, 0.0], + [ 0.0, ymax, 0.0], + [ 0.0, 0.0, 1.0]], + float) + self._inverted = None + self._invalid = 0 + return self._mtx + + +class BboxTransformFrom(Affine2DBase): + """ + `BboxTransformFrom` linearly transforms points from a given `Bbox` to the + unit bounding box. + """ + is_separable = True + + def __init__(self, boxin, **kwargs): + _api.check_isinstance(BboxBase, boxin=boxin) + + super().__init__(**kwargs) + self._boxin = boxin + self.set_children(boxin) + self._mtx = None + self._inverted = None + + __str__ = _make_str_method("_boxin") + + def get_matrix(self): + # docstring inherited + if self._invalid: + inl, inb, inw, inh = self._boxin.bounds + if DEBUG and (inw == 0 or inh == 0): + raise ValueError("Transforming from a singular bounding box.") + x_scale = 1.0 / inw + y_scale = 1.0 / inh + self._mtx = np.array([[x_scale, 0.0 , (-inl*x_scale)], + [0.0 , y_scale, (-inb*y_scale)], + [0.0 , 0.0 , 1.0 ]], + float) + self._inverted = None + self._invalid = 0 + return self._mtx + + +class ScaledTranslation(Affine2DBase): + """ + A transformation that translates by *xt* and *yt*, after *xt* and *yt* + have been transformed by *scale_trans*. + """ + def __init__(self, xt, yt, scale_trans, **kwargs): + super().__init__(**kwargs) + self._t = (xt, yt) + self._scale_trans = scale_trans + self.set_children(scale_trans) + self._mtx = None + self._inverted = None + + __str__ = _make_str_method("_t") + + def get_matrix(self): + # docstring inherited + if self._invalid: + # A bit faster than np.identity(3). + self._mtx = IdentityTransform._mtx.copy() + self._mtx[:2, 2] = self._scale_trans.transform(self._t) + self._invalid = 0 + self._inverted = None + return self._mtx + + +class AffineDeltaTransform(Affine2DBase): + r""" + A transform wrapper for transforming displacements between pairs of points. + + This class is intended to be used to transform displacements ("position + deltas") between pairs of points (e.g., as the ``offset_transform`` + of `.Collection`\s): given a transform ``t`` such that ``t = + AffineDeltaTransform(t) + offset``, ``AffineDeltaTransform`` + satisfies ``AffineDeltaTransform(a - b) == AffineDeltaTransform(a) - + AffineDeltaTransform(b)``. + + This is implemented by forcing the offset components of the transform + matrix to zero. + + This class is experimental as of 3.3, and the API may change. + """ + + def __init__(self, transform, **kwargs): + super().__init__(**kwargs) + self._base_transform = transform + + __str__ = _make_str_method("_base_transform") + + def get_matrix(self): + if self._invalid: + self._mtx = self._base_transform.get_matrix().copy() + self._mtx[:2, -1] = 0 + return self._mtx + + +class TransformedPath(TransformNode): + """ + A `TransformedPath` caches a non-affine transformed copy of the + `~.path.Path`. This cached copy is automatically updated when the + non-affine part of the transform changes. + + .. note:: + + Paths are considered immutable by this class. Any update to the + path's vertices/codes will not trigger a transform recomputation. + + """ + def __init__(self, path, transform): + """ + Parameters + ---------- + path : `~.path.Path` + transform : `Transform` + """ + _api.check_isinstance(Transform, transform=transform) + super().__init__() + self._path = path + self._transform = transform + self.set_children(transform) + self._transformed_path = None + self._transformed_points = None + + def _revalidate(self): + # only recompute if the invalidation includes the non_affine part of + # the transform + if (self._invalid == self._INVALID_FULL + or self._transformed_path is None): + self._transformed_path = \ + self._transform.transform_path_non_affine(self._path) + self._transformed_points = \ + Path._fast_from_codes_and_verts( + self._transform.transform_non_affine(self._path.vertices), + None, self._path) + self._invalid = 0 + + def get_transformed_points_and_affine(self): + """ + Return a copy of the child path, with the non-affine part of + the transform already applied, along with the affine part of + the path necessary to complete the transformation. Unlike + :meth:`get_transformed_path_and_affine`, no interpolation will + be performed. + """ + self._revalidate() + return self._transformed_points, self.get_affine() + + def get_transformed_path_and_affine(self): + """ + Return a copy of the child path, with the non-affine part of + the transform already applied, along with the affine part of + the path necessary to complete the transformation. + """ + self._revalidate() + return self._transformed_path, self.get_affine() + + def get_fully_transformed_path(self): + """ + Return a fully-transformed copy of the child path. + """ + self._revalidate() + return self._transform.transform_path_affine(self._transformed_path) + + def get_affine(self): + return self._transform.get_affine() + + +class TransformedPatchPath(TransformedPath): + """ + A `TransformedPatchPath` caches a non-affine transformed copy of the + `~.patches.Patch`. This cached copy is automatically updated when the + non-affine part of the transform or the patch changes. + """ + + def __init__(self, patch): + """ + Parameters + ---------- + patch : `~.patches.Patch` + """ + # Defer to TransformedPath.__init__. + super().__init__(patch.get_path(), patch.get_transform()) + self._patch = patch + + def _revalidate(self): + patch_path = self._patch.get_path() + # Force invalidation if the patch path changed; otherwise, let base + # class check invalidation. + if patch_path != self._path: + self._path = patch_path + self._transformed_path = None + super()._revalidate() + + +def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): + """ + Modify the endpoints of a range as needed to avoid singularities. + + Parameters + ---------- + vmin, vmax : float + The initial endpoints. + expander : float, default: 0.001 + Fractional amount by which *vmin* and *vmax* are expanded if + the original interval is too small, based on *tiny*. + tiny : float, default: 1e-15 + Threshold for the ratio of the interval to the maximum absolute + value of its endpoints. If the interval is smaller than + this, it will be expanded. This value should be around + 1e-15 or larger; otherwise the interval will be approaching + the double precision resolution limit. + increasing : bool, default: True + If True, swap *vmin*, *vmax* if *vmin* > *vmax*. + + Returns + ------- + vmin, vmax : float + Endpoints, expanded and/or swapped if necessary. + If either input is inf or NaN, or if both inputs are 0 or very + close to zero, it returns -*expander*, *expander*. + """ + + if (not np.isfinite(vmin)) or (not np.isfinite(vmax)): + return -expander, expander + + swapped = False + if vmax < vmin: + vmin, vmax = vmax, vmin + swapped = True + + # Expand vmin, vmax to float: if they were integer types, they can wrap + # around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow. + vmin, vmax = map(float, [vmin, vmax]) + + maxabsvalue = max(abs(vmin), abs(vmax)) + if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny: + vmin = -expander + vmax = expander + + elif vmax - vmin <= maxabsvalue * tiny: + if vmax == 0 and vmin == 0: + vmin = -expander + vmax = expander + else: + vmin -= expander*abs(vmin) + vmax += expander*abs(vmax) + + if swapped and not increasing: + vmin, vmax = vmax, vmin + return vmin, vmax + + +def interval_contains(interval, val): + """ + Check, inclusively, whether an interval includes a given value. + + Parameters + ---------- + interval : (float, float) + The endpoints of the interval. + val : float + Value to check is within interval. + + Returns + ------- + bool + Whether *val* is within the *interval*. + """ + a, b = interval + if a > b: + a, b = b, a + return a <= val <= b + + +def _interval_contains_close(interval, val, rtol=1e-10): + """ + Check, inclusively, whether an interval includes a given value, with the + interval expanded by a small tolerance to admit floating point errors. + + Parameters + ---------- + interval : (float, float) + The endpoints of the interval. + val : float + Value to check is within interval. + rtol : float, default: 1e-10 + Relative tolerance slippage allowed outside of the interval. + For an interval ``[a, b]``, values + ``a - rtol * (b - a) <= val <= b + rtol * (b - a)`` are considered + inside the interval. + + Returns + ------- + bool + Whether *val* is within the *interval* (with tolerance). + """ + a, b = interval + if a > b: + a, b = b, a + rtol = (b - a) * rtol + return a - rtol <= val <= b + rtol + + +def interval_contains_open(interval, val): + """ + Check, excluding endpoints, whether an interval includes a given value. + + Parameters + ---------- + interval : (float, float) + The endpoints of the interval. + val : float + Value to check is within interval. + + Returns + ------- + bool + Whether *val* is within the *interval*. + """ + a, b = interval + return a < val < b or a > val > b + + +def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'): + """ + Return a new transform with an added offset. + + Parameters + ---------- + trans : `Transform` subclass + Any transform, to which offset will be applied. + fig : `~matplotlib.figure.Figure`, default: None + Current figure. It can be None if *units* are 'dots'. + x, y : float, default: 0.0 + The offset to apply. + units : {'inches', 'points', 'dots'}, default: 'inches' + Units of the offset. + + Returns + ------- + `Transform` subclass + Transform with applied offset. + """ + _api.check_in_list(['dots', 'points', 'inches'], units=units) + if units == 'dots': + return trans + Affine2D().translate(x, y) + if fig is None: + raise ValueError('For units of inches or points a fig kwarg is needed') + if units == 'points': + x /= 72.0 + y /= 72.0 + # Default units are 'inches' + return trans + ScaledTranslation(x, y, fig.dpi_scale_trans) diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/typing.py b/llava_next/lib/python3.10/site-packages/matplotlib/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..02059be94ba2f378ef5e3cccaa22a503d676afa9 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/typing.py @@ -0,0 +1,60 @@ +""" +Typing support for Matplotlib + +This module contains Type aliases which are useful for Matplotlib and potentially +downstream libraries. + +.. admonition:: Provisional status of typing + + The ``typing`` module and type stub files are considered provisional and may change + at any time without a deprecation period. +""" +from collections.abc import Hashable, Sequence +import pathlib +from typing import Any, Literal, TypeVar, Union + +from . import path +from ._enums import JoinStyle, CapStyle +from .markers import MarkerStyle + +# The following are type aliases. Once python 3.9 is dropped, they should be annotated +# using ``typing.TypeAlias`` and Unions should be converted to using ``|`` syntax. + +RGBColorType = Union[tuple[float, float, float], str] +RGBAColorType = Union[ + str, # "none" or "#RRGGBBAA"/"#RGBA" hex strings + tuple[float, float, float, float], + # 2 tuple (color, alpha) representations, not infinitely recursive + # RGBColorType includes the (str, float) tuple, even for RGBA strings + tuple[RGBColorType, float], + # (4-tuple, float) is odd, but accepted as the outer float overriding A of 4-tuple + tuple[tuple[float, float, float, float], float], +] + +ColorType = Union[RGBColorType, RGBAColorType] + +RGBColourType = RGBColorType +RGBAColourType = RGBAColorType +ColourType = ColorType + +LineStyleType = Union[str, tuple[float, Sequence[float]]] +DrawStyleType = Literal["default", "steps", "steps-pre", "steps-mid", "steps-post"] +MarkEveryType = Union[ + None, int, tuple[int, int], slice, list[int], float, tuple[float, float], list[bool] +] + +MarkerType = Union[str, path.Path, MarkerStyle] +FillStyleType = Literal["full", "left", "right", "bottom", "top", "none"] +JoinStyleType = Union[JoinStyle, Literal["miter", "round", "bevel"]] +CapStyleType = Union[CapStyle, Literal["butt", "projecting", "round"]] + +RcStyleType = Union[ + str, + dict[str, Any], + pathlib.Path, + Sequence[Union[str, pathlib.Path, dict[str, Any]]], +] + +_HT = TypeVar("_HT", bound=Hashable) +HashableList = list[Union[_HT, "HashableList[_HT]"]] +"""A nested list of Hashable values.""" diff --git a/llava_next/lib/python3.10/site-packages/matplotlib/units.py b/llava_next/lib/python3.10/site-packages/matplotlib/units.py new file mode 100644 index 0000000000000000000000000000000000000000..e3480f228bb45cff45ed0566ceabdb1f3dcd53e1 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/matplotlib/units.py @@ -0,0 +1,195 @@ +""" +The classes here provide support for using custom classes with +Matplotlib, e.g., those that do not expose the array interface but know +how to convert themselves to arrays. It also supports classes with +units and units conversion. Use cases include converters for custom +objects, e.g., a list of datetime objects, as well as for objects that +are unit aware. We don't assume any particular units implementation; +rather a units implementation must register with the Registry converter +dictionary and provide a `ConversionInterface`. For example, +here is a complete implementation which supports plotting with native +datetime objects:: + + import matplotlib.units as units + import matplotlib.dates as dates + import matplotlib.ticker as ticker + import datetime + + class DateConverter(units.ConversionInterface): + + @staticmethod + def convert(value, unit, axis): + "Convert a datetime value to a scalar or array." + return dates.date2num(value) + + @staticmethod + def axisinfo(unit, axis): + "Return major and minor tick locators and formatters." + if unit != 'date': + return None + majloc = dates.AutoDateLocator() + majfmt = dates.AutoDateFormatter(majloc) + return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='date') + + @staticmethod + def default_units(x, axis): + "Return the default unit for x or None." + return 'date' + + # Finally we register our object type with the Matplotlib units registry. + units.registry[datetime.date] = DateConverter() +""" + +from decimal import Decimal +from numbers import Number + +import numpy as np +from numpy import ma + +from matplotlib import cbook + + +class ConversionError(TypeError): + pass + + +def _is_natively_supported(x): + """ + Return whether *x* is of a type that Matplotlib natively supports or an + array of objects of such types. + """ + # Matplotlib natively supports all number types except Decimal. + if np.iterable(x): + # Assume lists are homogeneous as other functions in unit system. + for thisx in x: + if thisx is ma.masked: + continue + return isinstance(thisx, Number) and not isinstance(thisx, Decimal) + else: + return isinstance(x, Number) and not isinstance(x, Decimal) + + +class AxisInfo: + """ + Information to support default axis labeling, tick labeling, and limits. + + An instance of this class must be returned by + `ConversionInterface.axisinfo`. + """ + def __init__(self, majloc=None, minloc=None, + majfmt=None, minfmt=None, label=None, + default_limits=None): + """ + Parameters + ---------- + majloc, minloc : Locator, optional + Tick locators for the major and minor ticks. + majfmt, minfmt : Formatter, optional + Tick formatters for the major and minor ticks. + label : str, optional + The default axis label. + default_limits : optional + The default min and max limits of the axis if no data has + been plotted. + + Notes + ----- + If any of the above are ``None``, the axis will simply use the + default value. + """ + self.majloc = majloc + self.minloc = minloc + self.majfmt = majfmt + self.minfmt = minfmt + self.label = label + self.default_limits = default_limits + + +class ConversionInterface: + """ + The minimal interface for a converter to take custom data types (or + sequences) and convert them to values Matplotlib can use. + """ + + @staticmethod + def axisinfo(unit, axis): + """Return an `.AxisInfo` for the axis with the specified units.""" + return None + + @staticmethod + def default_units(x, axis): + """Return the default unit for *x* or ``None`` for the given axis.""" + return None + + @staticmethod + def convert(obj, unit, axis): + """ + Convert *obj* using *unit* for the specified *axis*. + + If *obj* is a sequence, return the converted sequence. The output must + be a sequence of scalars that can be used by the numpy array layer. + """ + return obj + + +class DecimalConverter(ConversionInterface): + """Converter for decimal.Decimal data to float.""" + + @staticmethod + def convert(value, unit, axis): + """ + Convert Decimals to floats. + + The *unit* and *axis* arguments are not used. + + Parameters + ---------- + value : decimal.Decimal or iterable + Decimal or list of Decimal need to be converted + """ + if isinstance(value, Decimal): + return float(value) + # value is Iterable[Decimal] + elif isinstance(value, ma.MaskedArray): + return ma.asarray(value, dtype=float) + else: + return np.asarray(value, dtype=float) + + # axisinfo and default_units can be inherited as Decimals are Numbers. + + +class Registry(dict): + """Register types with conversion interface.""" + + def get_converter(self, x): + """Get the converter interface instance for *x*, or None.""" + # Unpack in case of e.g. Pandas or xarray object + x = cbook._unpack_to_numpy(x) + + if isinstance(x, np.ndarray): + # In case x in a masked array, access the underlying data (only its + # type matters). If x is a regular ndarray, getdata() just returns + # the array itself. + x = np.ma.getdata(x).ravel() + # If there are no elements in x, infer the units from its dtype + if not x.size: + return self.get_converter(np.array([0], dtype=x.dtype)) + for cls in type(x).__mro__: # Look up in the cache. + try: + return self[cls] + except KeyError: + pass + try: # If cache lookup fails, look up based on first element... + first = cbook._safe_first_finite(x) + except (TypeError, StopIteration): + pass + else: + # ... and avoid infinite recursion for pathological iterables for + # which indexing returns instances of the same iterable class. + if type(first) is not type(x): + return self.get_converter(first) + return None + + +registry = Registry() +registry[Decimal] = DecimalConverter()